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 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
25 * Copyright (c) 2012 by Delphix. All rights reserved.
26 */
27
28 /*
29 * DTrace - Dynamic Tracing for Solaris
30 *
31 * This is the implementation of the Solaris Dynamic Tracing framework
32 * (DTrace). The user-visible interface to DTrace is described at length in
33 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
34 * library, the in-kernel DTrace framework, and the DTrace providers are
35 * described in the block comments in the <sys/dtrace.h> header file. The
36 * internal architecture of DTrace is described in the block comments in the
37 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
38 * implementation very much assume mastery of all of these sources; if one has
39 * an unanswered question about the implementation, one should consult them
40 * first.
41 *
42 * The functions here are ordered roughly as follows:
43 *
44 * - Probe context functions
45 * - Probe hashing functions
46 * - Non-probe context utility functions
47 * - Matching functions
48 * - Provider-to-Framework API functions
49 * - Probe management functions
50 * - DIF object functions
51 * - Format functions
52 * - Predicate functions
53 * - ECB functions
54 * - Buffer functions
55 * - Enabling functions
56 * - DOF functions
57 * - Anonymous enabling functions
58 * - Consumer state functions
59 * - Helper functions
60 * - Hook functions
61 * - Driver cookbook functions
62 *
63 * Each group of functions begins with a block comment labelled the "DTrace
64 * [Group] Functions", allowing one to find each block by searching forward
65 * on capital-f functions.
66 */
67 #include <sys/errno.h>
68 #include <sys/stat.h>
69 #include <sys/modctl.h>
70 #include <sys/conf.h>
71 #include <sys/systm.h>
72 #include <sys/ddi.h>
73 #include <sys/sunddi.h>
74 #include <sys/cpuvar.h>
75 #include <sys/kmem.h>
76 #include <sys/strsubr.h>
77 #include <sys/sysmacros.h>
78 #include <sys/dtrace_impl.h>
79 #include <sys/atomic.h>
80 #include <sys/cmn_err.h>
81 #include <sys/mutex_impl.h>
82 #include <sys/rwlock_impl.h>
83 #include <sys/ctf_api.h>
84 #include <sys/panic.h>
85 #include <sys/priv_impl.h>
86 #include <sys/policy.h>
87 #include <sys/cred_impl.h>
88 #include <sys/procfs_isa.h>
89 #include <sys/taskq.h>
90 #include <sys/mkdev.h>
91 #include <sys/kdi.h>
92 #include <sys/zone.h>
93 #include <sys/socket.h>
94 #include <netinet/in.h>
95
96 /*
97 * DTrace Tunable Variables
98 *
99 * The following variables may be tuned by adding a line to /etc/system that
100 * includes both the name of the DTrace module ("dtrace") and the name of the
101 * variable. For example:
102 *
103 * set dtrace:dtrace_destructive_disallow = 1
104 *
105 * In general, the only variables that one should be tuning this way are those
106 * that affect system-wide DTrace behavior, and for which the default behavior
107 * is undesirable. Most of these variables are tunable on a per-consumer
108 * basis using DTrace options, and need not be tuned on a system-wide basis.
109 * When tuning these variables, avoid pathological values; while some attempt
110 * is made to verify the integrity of these variables, they are not considered
111 * part of the supported interface to DTrace, and they are therefore not
112 * checked comprehensively. Further, these variables should not be tuned
113 * dynamically via "mdb -kw" or other means; they should only be tuned via
114 * /etc/system.
115 */
116 int dtrace_destructive_disallow = 0;
117 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
118 size_t dtrace_difo_maxsize = (256 * 1024);
119 dtrace_optval_t dtrace_dof_maxsize = (256 * 1024);
120 size_t dtrace_global_maxsize = (16 * 1024);
121 size_t dtrace_actions_max = (16 * 1024);
122 size_t dtrace_retain_max = 1024;
123 dtrace_optval_t dtrace_helper_actions_max = 1024;
124 dtrace_optval_t dtrace_helper_providers_max = 32;
125 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
126 size_t dtrace_strsize_default = 256;
127 dtrace_optval_t dtrace_cleanrate_default = 9900990; /* 101 hz */
128 dtrace_optval_t dtrace_cleanrate_min = 200000; /* 5000 hz */
129 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
130 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
131 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
132 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
133 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
134 dtrace_optval_t dtrace_nspec_default = 1;
135 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
136 dtrace_optval_t dtrace_stackframes_default = 20;
137 dtrace_optval_t dtrace_ustackframes_default = 20;
138 dtrace_optval_t dtrace_jstackframes_default = 50;
139 dtrace_optval_t dtrace_jstackstrsize_default = 512;
140 int dtrace_msgdsize_max = 128;
141 hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
142 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
143 int dtrace_devdepth_max = 32;
144 int dtrace_err_verbose;
145 hrtime_t dtrace_deadman_interval = NANOSEC;
146 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
147 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
148 hrtime_t dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
149
150 /*
151 * DTrace External Variables
152 *
153 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
154 * available to DTrace consumers via the backtick (`) syntax. One of these,
155 * dtrace_zero, is made deliberately so: it is provided as a source of
156 * well-known, zero-filled memory. While this variable is not documented,
157 * it is used by some translators as an implementation detail.
158 */
159 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
160
161 /*
162 * DTrace Internal Variables
163 */
164 static dev_info_t *dtrace_devi; /* device info */
165 static vmem_t *dtrace_arena; /* probe ID arena */
166 static vmem_t *dtrace_minor; /* minor number arena */
167 static taskq_t *dtrace_taskq; /* task queue */
168 static dtrace_probe_t **dtrace_probes; /* array of all probes */
169 static int dtrace_nprobes; /* number of probes */
170 static dtrace_provider_t *dtrace_provider; /* provider list */
171 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
172 static int dtrace_opens; /* number of opens */
173 static int dtrace_helpers; /* number of helpers */
174 static int dtrace_getf; /* number of unpriv getf()s */
175 static void *dtrace_softstate; /* softstate pointer */
176 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
177 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
178 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
179 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
180 static int dtrace_toxranges; /* number of toxic ranges */
181 static int dtrace_toxranges_max; /* size of toxic range array */
182 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
183 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
184 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
185 static kthread_t *dtrace_panicked; /* panicking thread */
186 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
187 static dtrace_genid_t dtrace_probegen; /* current probe generation */
188 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
189 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
190 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
191 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
192 static int dtrace_dynvar_failclean; /* dynvars failed to clean */
193
194 /*
195 * DTrace Locking
196 * DTrace is protected by three (relatively coarse-grained) locks:
197 *
198 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
199 * including enabling state, probes, ECBs, consumer state, helper state,
200 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
201 * probe context is lock-free -- synchronization is handled via the
202 * dtrace_sync() cross call mechanism.
203 *
204 * (2) dtrace_provider_lock is required when manipulating provider state, or
205 * when provider state must be held constant.
206 *
207 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
208 * when meta provider state must be held constant.
209 *
210 * The lock ordering between these three locks is dtrace_meta_lock before
211 * dtrace_provider_lock before dtrace_lock. (In particular, there are
212 * several places where dtrace_provider_lock is held by the framework as it
213 * calls into the providers -- which then call back into the framework,
214 * grabbing dtrace_lock.)
215 *
216 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
217 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
218 * role as a coarse-grained lock; it is acquired before both of these locks.
219 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
220 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
221 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
222 * acquired _between_ dtrace_provider_lock and dtrace_lock.
223 */
224 static kmutex_t dtrace_lock; /* probe state lock */
225 static kmutex_t dtrace_provider_lock; /* provider state lock */
226 static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
227
228 /*
229 * DTrace Provider Variables
230 *
231 * These are the variables relating to DTrace as a provider (that is, the
232 * provider of the BEGIN, END, and ERROR probes).
233 */
234 static dtrace_pattr_t dtrace_provider_attr = {
235 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
236 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
237 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
238 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
239 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
240 };
241
242 static void
243 dtrace_nullop(void)
244 {}
245
246 static int
247 dtrace_enable_nullop(void)
248 {
249 return (0);
250 }
251
252 static dtrace_pops_t dtrace_provider_ops = {
253 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
254 (void (*)(void *, struct modctl *))dtrace_nullop,
255 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
256 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
257 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
258 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
259 NULL,
260 NULL,
261 NULL,
262 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
263 };
264
265 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
266 static dtrace_id_t dtrace_probeid_end; /* special END probe */
267 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
268
269 /*
270 * DTrace Helper Tracing Variables
271 */
272 uint32_t dtrace_helptrace_next = 0;
273 uint32_t dtrace_helptrace_nlocals;
274 char *dtrace_helptrace_buffer;
275 int dtrace_helptrace_bufsize = 512 * 1024;
276
277 #ifdef DEBUG
278 int dtrace_helptrace_enabled = 1;
279 #else
280 int dtrace_helptrace_enabled = 0;
281 #endif
282
283 /*
284 * DTrace Error Hashing
285 *
286 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
287 * table. This is very useful for checking coverage of tests that are
288 * expected to induce DIF or DOF processing errors, and may be useful for
289 * debugging problems in the DIF code generator or in DOF generation . The
290 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
291 */
292 #ifdef DEBUG
293 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
294 static const char *dtrace_errlast;
295 static kthread_t *dtrace_errthread;
296 static kmutex_t dtrace_errlock;
297 #endif
298
299 /*
300 * DTrace Macros and Constants
301 *
302 * These are various macros that are useful in various spots in the
303 * implementation, along with a few random constants that have no meaning
304 * outside of the implementation. There is no real structure to this cpp
305 * mishmash -- but is there ever?
306 */
307 #define DTRACE_HASHSTR(hash, probe) \
308 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
309
310 #define DTRACE_HASHNEXT(hash, probe) \
311 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
312
313 #define DTRACE_HASHPREV(hash, probe) \
314 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
315
316 #define DTRACE_HASHEQ(hash, lhs, rhs) \
317 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
318 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
319
320 #define DTRACE_AGGHASHSIZE_SLEW 17
321
322 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
323
324 /*
325 * The key for a thread-local variable consists of the lower 61 bits of the
326 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
327 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
328 * equal to a variable identifier. This is necessary (but not sufficient) to
329 * assure that global associative arrays never collide with thread-local
330 * variables. To guarantee that they cannot collide, we must also define the
331 * order for keying dynamic variables. That order is:
332 *
333 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
334 *
335 * Because the variable-key and the tls-key are in orthogonal spaces, there is
336 * no way for a global variable key signature to match a thread-local key
337 * signature.
338 */
339 #define DTRACE_TLS_THRKEY(where) { \
340 uint_t intr = 0; \
341 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
342 for (; actv; actv >>= 1) \
343 intr++; \
344 ASSERT(intr < (1 << 3)); \
345 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
346 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
347 }
348
349 #define DT_BSWAP_8(x) ((x) & 0xff)
350 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
351 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
352 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
353
354 #define DT_MASK_LO 0x00000000FFFFFFFFULL
355
356 #define DTRACE_STORE(type, tomax, offset, what) \
357 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
358
359 #ifndef __x86
360 #define DTRACE_ALIGNCHECK(addr, size, flags) \
361 if (addr & (size - 1)) { \
362 *flags |= CPU_DTRACE_BADALIGN; \
363 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
364 return (0); \
365 }
366 #else
367 #define DTRACE_ALIGNCHECK(addr, size, flags)
368 #endif
369
370 /*
371 * Test whether a range of memory starting at testaddr of size testsz falls
372 * within the range of memory described by addr, sz. We take care to avoid
373 * problems with overflow and underflow of the unsigned quantities, and
374 * disallow all negative sizes. Ranges of size 0 are allowed.
375 */
376 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
377 ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
378 (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
379 (testaddr) + (testsz) >= (testaddr))
380
381 /*
382 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
383 * alloc_sz on the righthand side of the comparison in order to avoid overflow
384 * or underflow in the comparison with it. This is simpler than the INRANGE
385 * check above, because we know that the dtms_scratch_ptr is valid in the
386 * range. Allocations of size zero are allowed.
387 */
388 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
389 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
390 (mstate)->dtms_scratch_ptr >= (alloc_sz))
391
392 #define DTRACE_LOADFUNC(bits) \
393 /*CSTYLED*/ \
394 uint##bits##_t \
395 dtrace_load##bits(uintptr_t addr) \
396 { \
397 size_t size = bits / NBBY; \
398 /*CSTYLED*/ \
399 uint##bits##_t rval; \
400 int i; \
401 volatile uint16_t *flags = (volatile uint16_t *) \
402 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
403 \
404 DTRACE_ALIGNCHECK(addr, size, flags); \
405 \
406 for (i = 0; i < dtrace_toxranges; i++) { \
407 if (addr >= dtrace_toxrange[i].dtt_limit) \
408 continue; \
409 \
410 if (addr + size <= dtrace_toxrange[i].dtt_base) \
411 continue; \
412 \
413 /* \
414 * This address falls within a toxic region; return 0. \
415 */ \
416 *flags |= CPU_DTRACE_BADADDR; \
417 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
418 return (0); \
419 } \
420 \
421 *flags |= CPU_DTRACE_NOFAULT; \
422 /*CSTYLED*/ \
423 rval = *((volatile uint##bits##_t *)addr); \
424 *flags &= ~CPU_DTRACE_NOFAULT; \
425 \
426 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
427 }
428
429 #ifdef _LP64
430 #define dtrace_loadptr dtrace_load64
431 #else
432 #define dtrace_loadptr dtrace_load32
433 #endif
434
435 #define DTRACE_DYNHASH_FREE 0
436 #define DTRACE_DYNHASH_SINK 1
437 #define DTRACE_DYNHASH_VALID 2
438
439 #define DTRACE_MATCH_FAIL -1
440 #define DTRACE_MATCH_NEXT 0
441 #define DTRACE_MATCH_DONE 1
442 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
443 #define DTRACE_STATE_ALIGN 64
444
445 #define DTRACE_FLAGS2FLT(flags) \
446 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
447 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
448 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
449 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
450 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
451 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
452 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
453 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
454 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
455 DTRACEFLT_UNKNOWN)
456
457 #define DTRACEACT_ISSTRING(act) \
458 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
459 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
460
461 static size_t dtrace_strlen(const char *, size_t);
462 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
463 static void dtrace_enabling_provide(dtrace_provider_t *);
464 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
465 static void dtrace_enabling_matchall(void);
466 static void dtrace_enabling_reap(void);
467 static dtrace_state_t *dtrace_anon_grab(void);
468 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
469 dtrace_state_t *, uint64_t, uint64_t);
470 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
471 static void dtrace_buffer_drop(dtrace_buffer_t *);
472 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
473 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
474 dtrace_state_t *, dtrace_mstate_t *);
475 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
476 dtrace_optval_t);
477 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
478 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
479 static int dtrace_priv_proc(dtrace_state_t *, dtrace_mstate_t *);
480 static void dtrace_getf_barrier(void);
481
482 /*
483 * DTrace Probe Context Functions
484 *
485 * These functions are called from probe context. Because probe context is
486 * any context in which C may be called, arbitrarily locks may be held,
487 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
488 * As a result, functions called from probe context may only call other DTrace
489 * support functions -- they may not interact at all with the system at large.
490 * (Note that the ASSERT macro is made probe-context safe by redefining it in
491 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
492 * loads are to be performed from probe context, they _must_ be in terms of
493 * the safe dtrace_load*() variants.
494 *
495 * Some functions in this block are not actually called from probe context;
496 * for these functions, there will be a comment above the function reading
497 * "Note: not called from probe context."
498 */
499 void
500 dtrace_panic(const char *format, ...)
501 {
502 va_list alist;
503
504 va_start(alist, format);
505 dtrace_vpanic(format, alist);
506 va_end(alist);
507 }
508
509 int
510 dtrace_assfail(const char *a, const char *f, int l)
511 {
512 dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
513
514 /*
515 * We just need something here that even the most clever compiler
516 * cannot optimize away.
517 */
518 return (a[(uintptr_t)f]);
519 }
520
521 /*
522 * Atomically increment a specified error counter from probe context.
523 */
524 static void
525 dtrace_error(uint32_t *counter)
526 {
527 /*
528 * Most counters stored to in probe context are per-CPU counters.
529 * However, there are some error conditions that are sufficiently
530 * arcane that they don't merit per-CPU storage. If these counters
531 * are incremented concurrently on different CPUs, scalability will be
532 * adversely affected -- but we don't expect them to be white-hot in a
533 * correctly constructed enabling...
534 */
535 uint32_t oval, nval;
536
537 do {
538 oval = *counter;
539
540 if ((nval = oval + 1) == 0) {
541 /*
542 * If the counter would wrap, set it to 1 -- assuring
543 * that the counter is never zero when we have seen
544 * errors. (The counter must be 32-bits because we
545 * aren't guaranteed a 64-bit compare&swap operation.)
546 * To save this code both the infamy of being fingered
547 * by a priggish news story and the indignity of being
548 * the target of a neo-puritan witch trial, we're
549 * carefully avoiding any colorful description of the
550 * likelihood of this condition -- but suffice it to
551 * say that it is only slightly more likely than the
552 * overflow of predicate cache IDs, as discussed in
553 * dtrace_predicate_create().
554 */
555 nval = 1;
556 }
557 } while (dtrace_cas32(counter, oval, nval) != oval);
558 }
559
560 /*
561 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
562 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
563 */
564 DTRACE_LOADFUNC(8)
565 DTRACE_LOADFUNC(16)
566 DTRACE_LOADFUNC(32)
567 DTRACE_LOADFUNC(64)
568
569 static int
570 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
571 {
572 if (dest < mstate->dtms_scratch_base)
573 return (0);
574
575 if (dest + size < dest)
576 return (0);
577
578 if (dest + size > mstate->dtms_scratch_ptr)
579 return (0);
580
581 return (1);
582 }
583
584 static int
585 dtrace_canstore_statvar(uint64_t addr, size_t sz,
586 dtrace_statvar_t **svars, int nsvars)
587 {
588 int i;
589
590 for (i = 0; i < nsvars; i++) {
591 dtrace_statvar_t *svar = svars[i];
592
593 if (svar == NULL || svar->dtsv_size == 0)
594 continue;
595
596 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
597 return (1);
598 }
599
600 return (0);
601 }
602
603 /*
604 * Check to see if the address is within a memory region to which a store may
605 * be issued. This includes the DTrace scratch areas, and any DTrace variable
606 * region. The caller of dtrace_canstore() is responsible for performing any
607 * alignment checks that are needed before stores are actually executed.
608 */
609 static int
610 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
611 dtrace_vstate_t *vstate)
612 {
613 /*
614 * First, check to see if the address is in scratch space...
615 */
616 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
617 mstate->dtms_scratch_size))
618 return (1);
619
620 /*
621 * Now check to see if it's a dynamic variable. This check will pick
622 * up both thread-local variables and any global dynamically-allocated
623 * variables.
624 */
625 if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
626 vstate->dtvs_dynvars.dtds_size)) {
627 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
628 uintptr_t base = (uintptr_t)dstate->dtds_base +
629 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
630 uintptr_t chunkoffs;
631
632 /*
633 * Before we assume that we can store here, we need to make
634 * sure that it isn't in our metadata -- storing to our
635 * dynamic variable metadata would corrupt our state. For
636 * the range to not include any dynamic variable metadata,
637 * it must:
638 *
639 * (1) Start above the hash table that is at the base of
640 * the dynamic variable space
641 *
642 * (2) Have a starting chunk offset that is beyond the
643 * dtrace_dynvar_t that is at the base of every chunk
644 *
645 * (3) Not span a chunk boundary
646 *
647 */
648 if (addr < base)
649 return (0);
650
651 chunkoffs = (addr - base) % dstate->dtds_chunksize;
652
653 if (chunkoffs < sizeof (dtrace_dynvar_t))
654 return (0);
655
656 if (chunkoffs + sz > dstate->dtds_chunksize)
657 return (0);
658
659 return (1);
660 }
661
662 /*
663 * Finally, check the static local and global variables. These checks
664 * take the longest, so we perform them last.
665 */
666 if (dtrace_canstore_statvar(addr, sz,
667 vstate->dtvs_locals, vstate->dtvs_nlocals))
668 return (1);
669
670 if (dtrace_canstore_statvar(addr, sz,
671 vstate->dtvs_globals, vstate->dtvs_nglobals))
672 return (1);
673
674 return (0);
675 }
676
677
678 /*
679 * Convenience routine to check to see if the address is within a memory
680 * region in which a load may be issued given the user's privilege level;
681 * if not, it sets the appropriate error flags and loads 'addr' into the
682 * illegal value slot.
683 *
684 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
685 * appropriate memory access protection.
686 */
687 static int
688 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
689 dtrace_vstate_t *vstate)
690 {
691 volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
692 file_t *fp;
693
694 /*
695 * If we hold the privilege to read from kernel memory, then
696 * everything is readable.
697 */
698 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
699 return (1);
700
701 /*
702 * You can obviously read that which you can store.
703 */
704 if (dtrace_canstore(addr, sz, mstate, vstate))
705 return (1);
706
707 /*
708 * We're allowed to read from our own string table.
709 */
710 if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
711 mstate->dtms_difo->dtdo_strlen))
712 return (1);
713
714 if (vstate->dtvs_state != NULL &&
715 dtrace_priv_proc(vstate->dtvs_state, mstate)) {
716 proc_t *p;
717
718 /*
719 * When we have privileges to the current process, there are
720 * several context-related kernel structures that are safe to
721 * read, even absent the privilege to read from kernel memory.
722 * These reads are safe because these structures contain only
723 * state that (1) we're permitted to read, (2) is harmless or
724 * (3) contains pointers to additional kernel state that we're
725 * not permitted to read (and as such, do not present an
726 * opportunity for privilege escalation). Finally (and
727 * critically), because of the nature of their relation with
728 * the current thread context, the memory associated with these
729 * structures cannot change over the duration of probe context,
730 * and it is therefore impossible for this memory to be
731 * deallocated and reallocated as something else while it's
732 * being operated upon.
733 */
734 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
735 return (1);
736
737 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
738 sz, curthread->t_procp, sizeof (proc_t))) {
739 return (1);
740 }
741
742 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
743 curthread->t_cred, sizeof (cred_t))) {
744 return (1);
745 }
746
747 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
748 &(p->p_pidp->pid_id), sizeof (pid_t))) {
749 return (1);
750 }
751
752 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
753 curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
754 return (1);
755 }
756 }
757
758 if ((fp = mstate->dtms_getf) != NULL) {
759 uintptr_t psz = sizeof (void *);
760 vnode_t *vp;
761 vnodeops_t *op;
762
763 /*
764 * When getf() returns a file_t, the enabling is implicitly
765 * granted the (transient) right to read the returned file_t
766 * as well as the v_path and v_op->vnop_name of the underlying
767 * vnode. These accesses are allowed after a successful
768 * getf() because the members that they refer to cannot change
769 * once set -- and the barrier logic in the kernel's closef()
770 * path assures that the file_t and its referenced vode_t
771 * cannot themselves be stale (that is, it impossible for
772 * either dtms_getf itself or its f_vnode member to reference
773 * freed memory).
774 */
775 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
776 return (1);
777
778 if ((vp = fp->f_vnode) != NULL) {
779 if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
780 return (1);
781
782 if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
783 vp->v_path, strlen(vp->v_path) + 1)) {
784 return (1);
785 }
786
787 if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
788 return (1);
789
790 if ((op = vp->v_op) != NULL &&
791 DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
792 return (1);
793 }
794
795 if (op != NULL && op->vnop_name != NULL &&
796 DTRACE_INRANGE(addr, sz, op->vnop_name,
797 strlen(op->vnop_name) + 1)) {
798 return (1);
799 }
800 }
801 }
802
803 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
804 *illval = addr;
805 return (0);
806 }
807
808 /*
809 * Convenience routine to check to see if a given string is within a memory
810 * region in which a load may be issued given the user's privilege level;
811 * this exists so that we don't need to issue unnecessary dtrace_strlen()
812 * calls in the event that the user has all privileges.
813 */
814 static int
815 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
816 dtrace_vstate_t *vstate)
817 {
818 size_t strsz;
819
820 /*
821 * If we hold the privilege to read from kernel memory, then
822 * everything is readable.
823 */
824 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
825 return (1);
826
827 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
828 if (dtrace_canload(addr, strsz, mstate, vstate))
829 return (1);
830
831 return (0);
832 }
833
834 /*
835 * Convenience routine to check to see if a given variable is within a memory
836 * region in which a load may be issued given the user's privilege level.
837 */
838 static int
839 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
840 dtrace_vstate_t *vstate)
841 {
842 size_t sz;
843 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
844
845 /*
846 * If we hold the privilege to read from kernel memory, then
847 * everything is readable.
848 */
849 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
850 return (1);
851
852 if (type->dtdt_kind == DIF_TYPE_STRING)
853 sz = dtrace_strlen(src,
854 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
855 else
856 sz = type->dtdt_size;
857
858 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
859 }
860
861 /*
862 * Compare two strings using safe loads.
863 */
864 static int
865 dtrace_strncmp(char *s1, char *s2, size_t limit)
866 {
867 uint8_t c1, c2;
868 volatile uint16_t *flags;
869
870 if (s1 == s2 || limit == 0)
871 return (0);
872
873 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
874
875 do {
876 if (s1 == NULL) {
877 c1 = '\0';
878 } else {
879 c1 = dtrace_load8((uintptr_t)s1++);
880 }
881
882 if (s2 == NULL) {
883 c2 = '\0';
884 } else {
885 c2 = dtrace_load8((uintptr_t)s2++);
886 }
887
888 if (c1 != c2)
889 return (c1 - c2);
890 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
891
892 return (0);
893 }
894
895 /*
896 * Compute strlen(s) for a string using safe memory accesses. The additional
897 * len parameter is used to specify a maximum length to ensure completion.
898 */
899 static size_t
900 dtrace_strlen(const char *s, size_t lim)
901 {
902 uint_t len;
903
904 for (len = 0; len != lim; len++) {
905 if (dtrace_load8((uintptr_t)s++) == '\0')
906 break;
907 }
908
909 return (len);
910 }
911
912 /*
913 * Check if an address falls within a toxic region.
914 */
915 static int
916 dtrace_istoxic(uintptr_t kaddr, size_t size)
917 {
918 uintptr_t taddr, tsize;
919 int i;
920
921 for (i = 0; i < dtrace_toxranges; i++) {
922 taddr = dtrace_toxrange[i].dtt_base;
923 tsize = dtrace_toxrange[i].dtt_limit - taddr;
924
925 if (kaddr - taddr < tsize) {
926 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
927 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
928 return (1);
929 }
930
931 if (taddr - kaddr < size) {
932 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
933 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
934 return (1);
935 }
936 }
937
938 return (0);
939 }
940
941 /*
942 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
943 * memory specified by the DIF program. The dst is assumed to be safe memory
944 * that we can store to directly because it is managed by DTrace. As with
945 * standard bcopy, overlapping copies are handled properly.
946 */
947 static void
948 dtrace_bcopy(const void *src, void *dst, size_t len)
949 {
950 if (len != 0) {
951 uint8_t *s1 = dst;
952 const uint8_t *s2 = src;
953
954 if (s1 <= s2) {
955 do {
956 *s1++ = dtrace_load8((uintptr_t)s2++);
957 } while (--len != 0);
958 } else {
959 s2 += len;
960 s1 += len;
961
962 do {
963 *--s1 = dtrace_load8((uintptr_t)--s2);
964 } while (--len != 0);
965 }
966 }
967 }
968
969 /*
970 * Copy src to dst using safe memory accesses, up to either the specified
971 * length, or the point that a nul byte is encountered. The src is assumed to
972 * be unsafe memory specified by the DIF program. The dst is assumed to be
973 * safe memory that we can store to directly because it is managed by DTrace.
974 * Unlike dtrace_bcopy(), overlapping regions are not handled.
975 */
976 static void
977 dtrace_strcpy(const void *src, void *dst, size_t len)
978 {
979 if (len != 0) {
980 uint8_t *s1 = dst, c;
981 const uint8_t *s2 = src;
982
983 do {
984 *s1++ = c = dtrace_load8((uintptr_t)s2++);
985 } while (--len != 0 && c != '\0');
986 }
987 }
988
989 /*
990 * Copy src to dst, deriving the size and type from the specified (BYREF)
991 * variable type. The src is assumed to be unsafe memory specified by the DIF
992 * program. The dst is assumed to be DTrace variable memory that is of the
993 * specified type; we assume that we can store to directly.
994 */
995 static void
996 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
997 {
998 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
999
1000 if (type->dtdt_kind == DIF_TYPE_STRING) {
1001 dtrace_strcpy(src, dst, type->dtdt_size);
1002 } else {
1003 dtrace_bcopy(src, dst, type->dtdt_size);
1004 }
1005 }
1006
1007 /*
1008 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1009 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1010 * safe memory that we can access directly because it is managed by DTrace.
1011 */
1012 static int
1013 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1014 {
1015 volatile uint16_t *flags;
1016
1017 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1018
1019 if (s1 == s2)
1020 return (0);
1021
1022 if (s1 == NULL || s2 == NULL)
1023 return (1);
1024
1025 if (s1 != s2 && len != 0) {
1026 const uint8_t *ps1 = s1;
1027 const uint8_t *ps2 = s2;
1028
1029 do {
1030 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1031 return (1);
1032 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1033 }
1034 return (0);
1035 }
1036
1037 /*
1038 * Zero the specified region using a simple byte-by-byte loop. Note that this
1039 * is for safe DTrace-managed memory only.
1040 */
1041 static void
1042 dtrace_bzero(void *dst, size_t len)
1043 {
1044 uchar_t *cp;
1045
1046 for (cp = dst; len != 0; len--)
1047 *cp++ = 0;
1048 }
1049
1050 static void
1051 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1052 {
1053 uint64_t result[2];
1054
1055 result[0] = addend1[0] + addend2[0];
1056 result[1] = addend1[1] + addend2[1] +
1057 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1058
1059 sum[0] = result[0];
1060 sum[1] = result[1];
1061 }
1062
1063 /*
1064 * Shift the 128-bit value in a by b. If b is positive, shift left.
1065 * If b is negative, shift right.
1066 */
1067 static void
1068 dtrace_shift_128(uint64_t *a, int b)
1069 {
1070 uint64_t mask;
1071
1072 if (b == 0)
1073 return;
1074
1075 if (b < 0) {
1076 b = -b;
1077 if (b >= 64) {
1078 a[0] = a[1] >> (b - 64);
1079 a[1] = 0;
1080 } else {
1081 a[0] >>= b;
1082 mask = 1LL << (64 - b);
1083 mask -= 1;
1084 a[0] |= ((a[1] & mask) << (64 - b));
1085 a[1] >>= b;
1086 }
1087 } else {
1088 if (b >= 64) {
1089 a[1] = a[0] << (b - 64);
1090 a[0] = 0;
1091 } else {
1092 a[1] <<= b;
1093 mask = a[0] >> (64 - b);
1094 a[1] |= mask;
1095 a[0] <<= b;
1096 }
1097 }
1098 }
1099
1100 /*
1101 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1102 * use native multiplication on those, and then re-combine into the
1103 * resulting 128-bit value.
1104 *
1105 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1106 * hi1 * hi2 << 64 +
1107 * hi1 * lo2 << 32 +
1108 * hi2 * lo1 << 32 +
1109 * lo1 * lo2
1110 */
1111 static void
1112 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1113 {
1114 uint64_t hi1, hi2, lo1, lo2;
1115 uint64_t tmp[2];
1116
1117 hi1 = factor1 >> 32;
1118 hi2 = factor2 >> 32;
1119
1120 lo1 = factor1 & DT_MASK_LO;
1121 lo2 = factor2 & DT_MASK_LO;
1122
1123 product[0] = lo1 * lo2;
1124 product[1] = hi1 * hi2;
1125
1126 tmp[0] = hi1 * lo2;
1127 tmp[1] = 0;
1128 dtrace_shift_128(tmp, 32);
1129 dtrace_add_128(product, tmp, product);
1130
1131 tmp[0] = hi2 * lo1;
1132 tmp[1] = 0;
1133 dtrace_shift_128(tmp, 32);
1134 dtrace_add_128(product, tmp, product);
1135 }
1136
1137 /*
1138 * This privilege check should be used by actions and subroutines to
1139 * verify that the user credentials of the process that enabled the
1140 * invoking ECB match the target credentials
1141 */
1142 static int
1143 dtrace_priv_proc_common_user(dtrace_state_t *state)
1144 {
1145 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1146
1147 /*
1148 * We should always have a non-NULL state cred here, since if cred
1149 * is null (anonymous tracing), we fast-path bypass this routine.
1150 */
1151 ASSERT(s_cr != NULL);
1152
1153 if ((cr = CRED()) != NULL &&
1154 s_cr->cr_uid == cr->cr_uid &&
1155 s_cr->cr_uid == cr->cr_ruid &&
1156 s_cr->cr_uid == cr->cr_suid &&
1157 s_cr->cr_gid == cr->cr_gid &&
1158 s_cr->cr_gid == cr->cr_rgid &&
1159 s_cr->cr_gid == cr->cr_sgid)
1160 return (1);
1161
1162 return (0);
1163 }
1164
1165 /*
1166 * This privilege check should be used by actions and subroutines to
1167 * verify that the zone of the process that enabled the invoking ECB
1168 * matches the target credentials
1169 */
1170 static int
1171 dtrace_priv_proc_common_zone(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 && s_cr->cr_zone == cr->cr_zone)
1182 return (1);
1183
1184 return (0);
1185 }
1186
1187 /*
1188 * This privilege check should be used by actions and subroutines to
1189 * verify that the process has not setuid or changed credentials.
1190 */
1191 static int
1192 dtrace_priv_proc_common_nocd()
1193 {
1194 proc_t *proc;
1195
1196 if ((proc = ttoproc(curthread)) != NULL &&
1197 !(proc->p_flag & SNOCD))
1198 return (1);
1199
1200 return (0);
1201 }
1202
1203 static int
1204 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1205 {
1206 int action = state->dts_cred.dcr_action;
1207
1208 if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1209 goto bad;
1210
1211 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1212 dtrace_priv_proc_common_zone(state) == 0)
1213 goto bad;
1214
1215 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1216 dtrace_priv_proc_common_user(state) == 0)
1217 goto bad;
1218
1219 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1220 dtrace_priv_proc_common_nocd() == 0)
1221 goto bad;
1222
1223 return (1);
1224
1225 bad:
1226 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1227
1228 return (0);
1229 }
1230
1231 static int
1232 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1233 {
1234 if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1235 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1236 return (1);
1237
1238 if (dtrace_priv_proc_common_zone(state) &&
1239 dtrace_priv_proc_common_user(state) &&
1240 dtrace_priv_proc_common_nocd())
1241 return (1);
1242 }
1243
1244 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1245
1246 return (0);
1247 }
1248
1249 static int
1250 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1251 {
1252 if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1253 (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1254 return (1);
1255
1256 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1257
1258 return (0);
1259 }
1260
1261 static int
1262 dtrace_priv_kernel(dtrace_state_t *state)
1263 {
1264 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1265 return (1);
1266
1267 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1268
1269 return (0);
1270 }
1271
1272 static int
1273 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1274 {
1275 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1276 return (1);
1277
1278 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1279
1280 return (0);
1281 }
1282
1283 /*
1284 * Determine if the dte_cond of the specified ECB allows for processing of
1285 * the current probe to continue. Note that this routine may allow continued
1286 * processing, but with access(es) stripped from the mstate's dtms_access
1287 * field.
1288 */
1289 static int
1290 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1291 dtrace_ecb_t *ecb)
1292 {
1293 dtrace_probe_t *probe = ecb->dte_probe;
1294 dtrace_provider_t *prov = probe->dtpr_provider;
1295 dtrace_pops_t *pops = &prov->dtpv_pops;
1296 int mode = DTRACE_MODE_NOPRIV_DROP;
1297
1298 ASSERT(ecb->dte_cond);
1299
1300 if (pops->dtps_mode != NULL) {
1301 mode = pops->dtps_mode(prov->dtpv_arg,
1302 probe->dtpr_id, probe->dtpr_arg);
1303
1304 ASSERT(mode & (DTRACE_MODE_USER | DTRACE_MODE_KERNEL));
1305 ASSERT(mode & (DTRACE_MODE_NOPRIV_RESTRICT |
1306 DTRACE_MODE_NOPRIV_DROP));
1307 }
1308
1309 /*
1310 * If the dte_cond bits indicate that this consumer is only allowed to
1311 * see user-mode firings of this probe, check that the probe was fired
1312 * while in a user context. If that's not the case, use the policy
1313 * specified by the provider to determine if we drop the probe or
1314 * merely restrict operation.
1315 */
1316 if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1317 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1318
1319 if (!(mode & DTRACE_MODE_USER)) {
1320 if (mode & DTRACE_MODE_NOPRIV_DROP)
1321 return (0);
1322
1323 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1324 }
1325 }
1326
1327 /*
1328 * This is more subtle than it looks. We have to be absolutely certain
1329 * that CRED() isn't going to change out from under us so it's only
1330 * legit to examine that structure if we're in constrained situations.
1331 * Currently, the only times we'll this check is if a non-super-user
1332 * has enabled the profile or syscall providers -- providers that
1333 * allow visibility of all processes. For the profile case, the check
1334 * above will ensure that we're examining a user context.
1335 */
1336 if (ecb->dte_cond & DTRACE_COND_OWNER) {
1337 cred_t *cr;
1338 cred_t *s_cr = state->dts_cred.dcr_cred;
1339 proc_t *proc;
1340
1341 ASSERT(s_cr != NULL);
1342
1343 if ((cr = CRED()) == NULL ||
1344 s_cr->cr_uid != cr->cr_uid ||
1345 s_cr->cr_uid != cr->cr_ruid ||
1346 s_cr->cr_uid != cr->cr_suid ||
1347 s_cr->cr_gid != cr->cr_gid ||
1348 s_cr->cr_gid != cr->cr_rgid ||
1349 s_cr->cr_gid != cr->cr_sgid ||
1350 (proc = ttoproc(curthread)) == NULL ||
1351 (proc->p_flag & SNOCD)) {
1352 if (mode & DTRACE_MODE_NOPRIV_DROP)
1353 return (0);
1354
1355 mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1356 }
1357 }
1358
1359 /*
1360 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1361 * in our zone, check to see if our mode policy is to restrict rather
1362 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1363 * and DTRACE_ACCESS_ARGS
1364 */
1365 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1366 cred_t *cr;
1367 cred_t *s_cr = state->dts_cred.dcr_cred;
1368
1369 ASSERT(s_cr != NULL);
1370
1371 if ((cr = CRED()) == NULL ||
1372 s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1373 if (mode & DTRACE_MODE_NOPRIV_DROP)
1374 return (0);
1375
1376 mstate->dtms_access &=
1377 ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1378 }
1379 }
1380
1381 /*
1382 * By merits of being in this code path at all, we have limited
1383 * privileges. If the provider has indicated that limited privileges
1384 * are to denote restricted operation, strip off the ability to access
1385 * arguments.
1386 */
1387 if (mode & DTRACE_MODE_LIMITEDPRIV_RESTRICT)
1388 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1389
1390 return (1);
1391 }
1392
1393 /*
1394 * Note: not called from probe context. This function is called
1395 * asynchronously (and at a regular interval) from outside of probe context to
1396 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1397 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1398 */
1399 void
1400 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1401 {
1402 dtrace_dynvar_t *dirty;
1403 dtrace_dstate_percpu_t *dcpu;
1404 dtrace_dynvar_t **rinsep;
1405 int i, j, work = 0;
1406
1407 for (i = 0; i < NCPU; i++) {
1408 dcpu = &dstate->dtds_percpu[i];
1409 rinsep = &dcpu->dtdsc_rinsing;
1410
1411 /*
1412 * If the dirty list is NULL, there is no dirty work to do.
1413 */
1414 if (dcpu->dtdsc_dirty == NULL)
1415 continue;
1416
1417 if (dcpu->dtdsc_rinsing != NULL) {
1418 /*
1419 * If the rinsing list is non-NULL, then it is because
1420 * this CPU was selected to accept another CPU's
1421 * dirty list -- and since that time, dirty buffers
1422 * have accumulated. This is a highly unlikely
1423 * condition, but we choose to ignore the dirty
1424 * buffers -- they'll be picked up a future cleanse.
1425 */
1426 continue;
1427 }
1428
1429 if (dcpu->dtdsc_clean != NULL) {
1430 /*
1431 * If the clean list is non-NULL, then we're in a
1432 * situation where a CPU has done deallocations (we
1433 * have a non-NULL dirty list) but no allocations (we
1434 * also have a non-NULL clean list). We can't simply
1435 * move the dirty list into the clean list on this
1436 * CPU, yet we also don't want to allow this condition
1437 * to persist, lest a short clean list prevent a
1438 * massive dirty list from being cleaned (which in
1439 * turn could lead to otherwise avoidable dynamic
1440 * drops). To deal with this, we look for some CPU
1441 * with a NULL clean list, NULL dirty list, and NULL
1442 * rinsing list -- and then we borrow this CPU to
1443 * rinse our dirty list.
1444 */
1445 for (j = 0; j < NCPU; j++) {
1446 dtrace_dstate_percpu_t *rinser;
1447
1448 rinser = &dstate->dtds_percpu[j];
1449
1450 if (rinser->dtdsc_rinsing != NULL)
1451 continue;
1452
1453 if (rinser->dtdsc_dirty != NULL)
1454 continue;
1455
1456 if (rinser->dtdsc_clean != NULL)
1457 continue;
1458
1459 rinsep = &rinser->dtdsc_rinsing;
1460 break;
1461 }
1462
1463 if (j == NCPU) {
1464 /*
1465 * We were unable to find another CPU that
1466 * could accept this dirty list -- we are
1467 * therefore unable to clean it now.
1468 */
1469 dtrace_dynvar_failclean++;
1470 continue;
1471 }
1472 }
1473
1474 work = 1;
1475
1476 /*
1477 * Atomically move the dirty list aside.
1478 */
1479 do {
1480 dirty = dcpu->dtdsc_dirty;
1481
1482 /*
1483 * Before we zap the dirty list, set the rinsing list.
1484 * (This allows for a potential assertion in
1485 * dtrace_dynvar(): if a free dynamic variable appears
1486 * on a hash chain, either the dirty list or the
1487 * rinsing list for some CPU must be non-NULL.)
1488 */
1489 *rinsep = dirty;
1490 dtrace_membar_producer();
1491 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1492 dirty, NULL) != dirty);
1493 }
1494
1495 if (!work) {
1496 /*
1497 * We have no work to do; we can simply return.
1498 */
1499 return;
1500 }
1501
1502 dtrace_sync();
1503
1504 for (i = 0; i < NCPU; i++) {
1505 dcpu = &dstate->dtds_percpu[i];
1506
1507 if (dcpu->dtdsc_rinsing == NULL)
1508 continue;
1509
1510 /*
1511 * We are now guaranteed that no hash chain contains a pointer
1512 * into this dirty list; we can make it clean.
1513 */
1514 ASSERT(dcpu->dtdsc_clean == NULL);
1515 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1516 dcpu->dtdsc_rinsing = NULL;
1517 }
1518
1519 /*
1520 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1521 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1522 * This prevents a race whereby a CPU incorrectly decides that
1523 * the state should be something other than DTRACE_DSTATE_CLEAN
1524 * after dtrace_dynvar_clean() has completed.
1525 */
1526 dtrace_sync();
1527
1528 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1529 }
1530
1531 /*
1532 * Depending on the value of the op parameter, this function looks-up,
1533 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1534 * allocation is requested, this function will return a pointer to a
1535 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1536 * variable can be allocated. If NULL is returned, the appropriate counter
1537 * will be incremented.
1538 */
1539 dtrace_dynvar_t *
1540 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1541 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1542 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1543 {
1544 uint64_t hashval = DTRACE_DYNHASH_VALID;
1545 dtrace_dynhash_t *hash = dstate->dtds_hash;
1546 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1547 processorid_t me = CPU->cpu_id, cpu = me;
1548 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1549 size_t bucket, ksize;
1550 size_t chunksize = dstate->dtds_chunksize;
1551 uintptr_t kdata, lock, nstate;
1552 uint_t i;
1553
1554 ASSERT(nkeys != 0);
1555
1556 /*
1557 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1558 * algorithm. For the by-value portions, we perform the algorithm in
1559 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1560 * bit, and seems to have only a minute effect on distribution. For
1561 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1562 * over each referenced byte. It's painful to do this, but it's much
1563 * better than pathological hash distribution. The efficacy of the
1564 * hashing algorithm (and a comparison with other algorithms) may be
1565 * found by running the ::dtrace_dynstat MDB dcmd.
1566 */
1567 for (i = 0; i < nkeys; i++) {
1568 if (key[i].dttk_size == 0) {
1569 uint64_t val = key[i].dttk_value;
1570
1571 hashval += (val >> 48) & 0xffff;
1572 hashval += (hashval << 10);
1573 hashval ^= (hashval >> 6);
1574
1575 hashval += (val >> 32) & 0xffff;
1576 hashval += (hashval << 10);
1577 hashval ^= (hashval >> 6);
1578
1579 hashval += (val >> 16) & 0xffff;
1580 hashval += (hashval << 10);
1581 hashval ^= (hashval >> 6);
1582
1583 hashval += val & 0xffff;
1584 hashval += (hashval << 10);
1585 hashval ^= (hashval >> 6);
1586 } else {
1587 /*
1588 * This is incredibly painful, but it beats the hell
1589 * out of the alternative.
1590 */
1591 uint64_t j, size = key[i].dttk_size;
1592 uintptr_t base = (uintptr_t)key[i].dttk_value;
1593
1594 if (!dtrace_canload(base, size, mstate, vstate))
1595 break;
1596
1597 for (j = 0; j < size; j++) {
1598 hashval += dtrace_load8(base + j);
1599 hashval += (hashval << 10);
1600 hashval ^= (hashval >> 6);
1601 }
1602 }
1603 }
1604
1605 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1606 return (NULL);
1607
1608 hashval += (hashval << 3);
1609 hashval ^= (hashval >> 11);
1610 hashval += (hashval << 15);
1611
1612 /*
1613 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1614 * comes out to be one of our two sentinel hash values. If this
1615 * actually happens, we set the hashval to be a value known to be a
1616 * non-sentinel value.
1617 */
1618 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1619 hashval = DTRACE_DYNHASH_VALID;
1620
1621 /*
1622 * Yes, it's painful to do a divide here. If the cycle count becomes
1623 * important here, tricks can be pulled to reduce it. (However, it's
1624 * critical that hash collisions be kept to an absolute minimum;
1625 * they're much more painful than a divide.) It's better to have a
1626 * solution that generates few collisions and still keeps things
1627 * relatively simple.
1628 */
1629 bucket = hashval % dstate->dtds_hashsize;
1630
1631 if (op == DTRACE_DYNVAR_DEALLOC) {
1632 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1633
1634 for (;;) {
1635 while ((lock = *lockp) & 1)
1636 continue;
1637
1638 if (dtrace_casptr((void *)lockp,
1639 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1640 break;
1641 }
1642
1643 dtrace_membar_producer();
1644 }
1645
1646 top:
1647 prev = NULL;
1648 lock = hash[bucket].dtdh_lock;
1649
1650 dtrace_membar_consumer();
1651
1652 start = hash[bucket].dtdh_chain;
1653 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1654 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1655 op != DTRACE_DYNVAR_DEALLOC));
1656
1657 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1658 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1659 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1660
1661 if (dvar->dtdv_hashval != hashval) {
1662 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1663 /*
1664 * We've reached the sink, and therefore the
1665 * end of the hash chain; we can kick out of
1666 * the loop knowing that we have seen a valid
1667 * snapshot of state.
1668 */
1669 ASSERT(dvar->dtdv_next == NULL);
1670 ASSERT(dvar == &dtrace_dynhash_sink);
1671 break;
1672 }
1673
1674 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1675 /*
1676 * We've gone off the rails: somewhere along
1677 * the line, one of the members of this hash
1678 * chain was deleted. Note that we could also
1679 * detect this by simply letting this loop run
1680 * to completion, as we would eventually hit
1681 * the end of the dirty list. However, we
1682 * want to avoid running the length of the
1683 * dirty list unnecessarily (it might be quite
1684 * long), so we catch this as early as
1685 * possible by detecting the hash marker. In
1686 * this case, we simply set dvar to NULL and
1687 * break; the conditional after the loop will
1688 * send us back to top.
1689 */
1690 dvar = NULL;
1691 break;
1692 }
1693
1694 goto next;
1695 }
1696
1697 if (dtuple->dtt_nkeys != nkeys)
1698 goto next;
1699
1700 for (i = 0; i < nkeys; i++, dkey++) {
1701 if (dkey->dttk_size != key[i].dttk_size)
1702 goto next; /* size or type mismatch */
1703
1704 if (dkey->dttk_size != 0) {
1705 if (dtrace_bcmp(
1706 (void *)(uintptr_t)key[i].dttk_value,
1707 (void *)(uintptr_t)dkey->dttk_value,
1708 dkey->dttk_size))
1709 goto next;
1710 } else {
1711 if (dkey->dttk_value != key[i].dttk_value)
1712 goto next;
1713 }
1714 }
1715
1716 if (op != DTRACE_DYNVAR_DEALLOC)
1717 return (dvar);
1718
1719 ASSERT(dvar->dtdv_next == NULL ||
1720 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1721
1722 if (prev != NULL) {
1723 ASSERT(hash[bucket].dtdh_chain != dvar);
1724 ASSERT(start != dvar);
1725 ASSERT(prev->dtdv_next == dvar);
1726 prev->dtdv_next = dvar->dtdv_next;
1727 } else {
1728 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1729 start, dvar->dtdv_next) != start) {
1730 /*
1731 * We have failed to atomically swing the
1732 * hash table head pointer, presumably because
1733 * of a conflicting allocation on another CPU.
1734 * We need to reread the hash chain and try
1735 * again.
1736 */
1737 goto top;
1738 }
1739 }
1740
1741 dtrace_membar_producer();
1742
1743 /*
1744 * Now set the hash value to indicate that it's free.
1745 */
1746 ASSERT(hash[bucket].dtdh_chain != dvar);
1747 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1748
1749 dtrace_membar_producer();
1750
1751 /*
1752 * Set the next pointer to point at the dirty list, and
1753 * atomically swing the dirty pointer to the newly freed dvar.
1754 */
1755 do {
1756 next = dcpu->dtdsc_dirty;
1757 dvar->dtdv_next = next;
1758 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1759
1760 /*
1761 * Finally, unlock this hash bucket.
1762 */
1763 ASSERT(hash[bucket].dtdh_lock == lock);
1764 ASSERT(lock & 1);
1765 hash[bucket].dtdh_lock++;
1766
1767 return (NULL);
1768 next:
1769 prev = dvar;
1770 continue;
1771 }
1772
1773 if (dvar == NULL) {
1774 /*
1775 * If dvar is NULL, it is because we went off the rails:
1776 * one of the elements that we traversed in the hash chain
1777 * was deleted while we were traversing it. In this case,
1778 * we assert that we aren't doing a dealloc (deallocs lock
1779 * the hash bucket to prevent themselves from racing with
1780 * one another), and retry the hash chain traversal.
1781 */
1782 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1783 goto top;
1784 }
1785
1786 if (op != DTRACE_DYNVAR_ALLOC) {
1787 /*
1788 * If we are not to allocate a new variable, we want to
1789 * return NULL now. Before we return, check that the value
1790 * of the lock word hasn't changed. If it has, we may have
1791 * seen an inconsistent snapshot.
1792 */
1793 if (op == DTRACE_DYNVAR_NOALLOC) {
1794 if (hash[bucket].dtdh_lock != lock)
1795 goto top;
1796 } else {
1797 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1798 ASSERT(hash[bucket].dtdh_lock == lock);
1799 ASSERT(lock & 1);
1800 hash[bucket].dtdh_lock++;
1801 }
1802
1803 return (NULL);
1804 }
1805
1806 /*
1807 * We need to allocate a new dynamic variable. The size we need is the
1808 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1809 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1810 * the size of any referred-to data (dsize). We then round the final
1811 * size up to the chunksize for allocation.
1812 */
1813 for (ksize = 0, i = 0; i < nkeys; i++)
1814 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1815
1816 /*
1817 * This should be pretty much impossible, but could happen if, say,
1818 * strange DIF specified the tuple. Ideally, this should be an
1819 * assertion and not an error condition -- but that requires that the
1820 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1821 * bullet-proof. (That is, it must not be able to be fooled by
1822 * malicious DIF.) Given the lack of backwards branches in DIF,
1823 * solving this would presumably not amount to solving the Halting
1824 * Problem -- but it still seems awfully hard.
1825 */
1826 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1827 ksize + dsize > chunksize) {
1828 dcpu->dtdsc_drops++;
1829 return (NULL);
1830 }
1831
1832 nstate = DTRACE_DSTATE_EMPTY;
1833
1834 do {
1835 retry:
1836 free = dcpu->dtdsc_free;
1837
1838 if (free == NULL) {
1839 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1840 void *rval;
1841
1842 if (clean == NULL) {
1843 /*
1844 * We're out of dynamic variable space on
1845 * this CPU. Unless we have tried all CPUs,
1846 * we'll try to allocate from a different
1847 * CPU.
1848 */
1849 switch (dstate->dtds_state) {
1850 case DTRACE_DSTATE_CLEAN: {
1851 void *sp = &dstate->dtds_state;
1852
1853 if (++cpu >= NCPU)
1854 cpu = 0;
1855
1856 if (dcpu->dtdsc_dirty != NULL &&
1857 nstate == DTRACE_DSTATE_EMPTY)
1858 nstate = DTRACE_DSTATE_DIRTY;
1859
1860 if (dcpu->dtdsc_rinsing != NULL)
1861 nstate = DTRACE_DSTATE_RINSING;
1862
1863 dcpu = &dstate->dtds_percpu[cpu];
1864
1865 if (cpu != me)
1866 goto retry;
1867
1868 (void) dtrace_cas32(sp,
1869 DTRACE_DSTATE_CLEAN, nstate);
1870
1871 /*
1872 * To increment the correct bean
1873 * counter, take another lap.
1874 */
1875 goto retry;
1876 }
1877
1878 case DTRACE_DSTATE_DIRTY:
1879 dcpu->dtdsc_dirty_drops++;
1880 break;
1881
1882 case DTRACE_DSTATE_RINSING:
1883 dcpu->dtdsc_rinsing_drops++;
1884 break;
1885
1886 case DTRACE_DSTATE_EMPTY:
1887 dcpu->dtdsc_drops++;
1888 break;
1889 }
1890
1891 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1892 return (NULL);
1893 }
1894
1895 /*
1896 * The clean list appears to be non-empty. We want to
1897 * move the clean list to the free list; we start by
1898 * moving the clean pointer aside.
1899 */
1900 if (dtrace_casptr(&dcpu->dtdsc_clean,
1901 clean, NULL) != clean) {
1902 /*
1903 * We are in one of two situations:
1904 *
1905 * (a) The clean list was switched to the
1906 * free list by another CPU.
1907 *
1908 * (b) The clean list was added to by the
1909 * cleansing cyclic.
1910 *
1911 * In either of these situations, we can
1912 * just reattempt the free list allocation.
1913 */
1914 goto retry;
1915 }
1916
1917 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1918
1919 /*
1920 * Now we'll move the clean list to our free list.
1921 * It's impossible for this to fail: the only way
1922 * the free list can be updated is through this
1923 * code path, and only one CPU can own the clean list.
1924 * Thus, it would only be possible for this to fail if
1925 * this code were racing with dtrace_dynvar_clean().
1926 * (That is, if dtrace_dynvar_clean() updated the clean
1927 * list, and we ended up racing to update the free
1928 * list.) This race is prevented by the dtrace_sync()
1929 * in dtrace_dynvar_clean() -- which flushes the
1930 * owners of the clean lists out before resetting
1931 * the clean lists.
1932 */
1933 dcpu = &dstate->dtds_percpu[me];
1934 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1935 ASSERT(rval == NULL);
1936 goto retry;
1937 }
1938
1939 dvar = free;
1940 new_free = dvar->dtdv_next;
1941 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1942
1943 /*
1944 * We have now allocated a new chunk. We copy the tuple keys into the
1945 * tuple array and copy any referenced key data into the data space
1946 * following the tuple array. As we do this, we relocate dttk_value
1947 * in the final tuple to point to the key data address in the chunk.
1948 */
1949 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1950 dvar->dtdv_data = (void *)(kdata + ksize);
1951 dvar->dtdv_tuple.dtt_nkeys = nkeys;
1952
1953 for (i = 0; i < nkeys; i++) {
1954 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1955 size_t kesize = key[i].dttk_size;
1956
1957 if (kesize != 0) {
1958 dtrace_bcopy(
1959 (const void *)(uintptr_t)key[i].dttk_value,
1960 (void *)kdata, kesize);
1961 dkey->dttk_value = kdata;
1962 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1963 } else {
1964 dkey->dttk_value = key[i].dttk_value;
1965 }
1966
1967 dkey->dttk_size = kesize;
1968 }
1969
1970 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1971 dvar->dtdv_hashval = hashval;
1972 dvar->dtdv_next = start;
1973
1974 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1975 return (dvar);
1976
1977 /*
1978 * The cas has failed. Either another CPU is adding an element to
1979 * this hash chain, or another CPU is deleting an element from this
1980 * hash chain. The simplest way to deal with both of these cases
1981 * (though not necessarily the most efficient) is to free our
1982 * allocated block and tail-call ourselves. Note that the free is
1983 * to the dirty list and _not_ to the free list. This is to prevent
1984 * races with allocators, above.
1985 */
1986 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1987
1988 dtrace_membar_producer();
1989
1990 do {
1991 free = dcpu->dtdsc_dirty;
1992 dvar->dtdv_next = free;
1993 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1994
1995 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1996 }
1997
1998 /*ARGSUSED*/
1999 static void
2000 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2001 {
2002 if ((int64_t)nval < (int64_t)*oval)
2003 *oval = nval;
2004 }
2005
2006 /*ARGSUSED*/
2007 static void
2008 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2009 {
2010 if ((int64_t)nval > (int64_t)*oval)
2011 *oval = nval;
2012 }
2013
2014 static void
2015 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2016 {
2017 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2018 int64_t val = (int64_t)nval;
2019
2020 if (val < 0) {
2021 for (i = 0; i < zero; i++) {
2022 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2023 quanta[i] += incr;
2024 return;
2025 }
2026 }
2027 } else {
2028 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2029 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2030 quanta[i - 1] += incr;
2031 return;
2032 }
2033 }
2034
2035 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2036 return;
2037 }
2038
2039 ASSERT(0);
2040 }
2041
2042 static void
2043 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2044 {
2045 uint64_t arg = *lquanta++;
2046 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2047 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2048 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2049 int32_t val = (int32_t)nval, level;
2050
2051 ASSERT(step != 0);
2052 ASSERT(levels != 0);
2053
2054 if (val < base) {
2055 /*
2056 * This is an underflow.
2057 */
2058 lquanta[0] += incr;
2059 return;
2060 }
2061
2062 level = (val - base) / step;
2063
2064 if (level < levels) {
2065 lquanta[level + 1] += incr;
2066 return;
2067 }
2068
2069 /*
2070 * This is an overflow.
2071 */
2072 lquanta[levels + 1] += incr;
2073 }
2074
2075 static int
2076 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2077 uint16_t high, uint16_t nsteps, int64_t value)
2078 {
2079 int64_t this = 1, last, next;
2080 int base = 1, order;
2081
2082 ASSERT(factor <= nsteps);
2083 ASSERT(nsteps % factor == 0);
2084
2085 for (order = 0; order < low; order++)
2086 this *= factor;
2087
2088 /*
2089 * If our value is less than our factor taken to the power of the
2090 * low order of magnitude, it goes into the zeroth bucket.
2091 */
2092 if (value < (last = this))
2093 return (0);
2094
2095 for (this *= factor; order <= high; order++) {
2096 int nbuckets = this > nsteps ? nsteps : this;
2097
2098 if ((next = this * factor) < this) {
2099 /*
2100 * We should not generally get log/linear quantizations
2101 * with a high magnitude that allows 64-bits to
2102 * overflow, but we nonetheless protect against this
2103 * by explicitly checking for overflow, and clamping
2104 * our value accordingly.
2105 */
2106 value = this - 1;
2107 }
2108
2109 if (value < this) {
2110 /*
2111 * If our value lies within this order of magnitude,
2112 * determine its position by taking the offset within
2113 * the order of magnitude, dividing by the bucket
2114 * width, and adding to our (accumulated) base.
2115 */
2116 return (base + (value - last) / (this / nbuckets));
2117 }
2118
2119 base += nbuckets - (nbuckets / factor);
2120 last = this;
2121 this = next;
2122 }
2123
2124 /*
2125 * Our value is greater than or equal to our factor taken to the
2126 * power of one plus the high magnitude -- return the top bucket.
2127 */
2128 return (base);
2129 }
2130
2131 static void
2132 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2133 {
2134 uint64_t arg = *llquanta++;
2135 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2136 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2137 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2138 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2139
2140 llquanta[dtrace_aggregate_llquantize_bucket(factor,
2141 low, high, nsteps, nval)] += incr;
2142 }
2143
2144 /*ARGSUSED*/
2145 static void
2146 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2147 {
2148 data[0]++;
2149 data[1] += nval;
2150 }
2151
2152 /*ARGSUSED*/
2153 static void
2154 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2155 {
2156 int64_t snval = (int64_t)nval;
2157 uint64_t tmp[2];
2158
2159 data[0]++;
2160 data[1] += nval;
2161
2162 /*
2163 * What we want to say here is:
2164 *
2165 * data[2] += nval * nval;
2166 *
2167 * But given that nval is 64-bit, we could easily overflow, so
2168 * we do this as 128-bit arithmetic.
2169 */
2170 if (snval < 0)
2171 snval = -snval;
2172
2173 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2174 dtrace_add_128(data + 2, tmp, data + 2);
2175 }
2176
2177 /*ARGSUSED*/
2178 static void
2179 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2180 {
2181 *oval = *oval + 1;
2182 }
2183
2184 /*ARGSUSED*/
2185 static void
2186 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2187 {
2188 *oval += nval;
2189 }
2190
2191 /*
2192 * Aggregate given the tuple in the principal data buffer, and the aggregating
2193 * action denoted by the specified dtrace_aggregation_t. The aggregation
2194 * buffer is specified as the buf parameter. This routine does not return
2195 * failure; if there is no space in the aggregation buffer, the data will be
2196 * dropped, and a corresponding counter incremented.
2197 */
2198 static void
2199 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2200 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2201 {
2202 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2203 uint32_t i, ndx, size, fsize;
2204 uint32_t align = sizeof (uint64_t) - 1;
2205 dtrace_aggbuffer_t *agb;
2206 dtrace_aggkey_t *key;
2207 uint32_t hashval = 0, limit, isstr;
2208 caddr_t tomax, data, kdata;
2209 dtrace_actkind_t action;
2210 dtrace_action_t *act;
2211 uintptr_t offs;
2212
2213 if (buf == NULL)
2214 return;
2215
2216 if (!agg->dtag_hasarg) {
2217 /*
2218 * Currently, only quantize() and lquantize() take additional
2219 * arguments, and they have the same semantics: an increment
2220 * value that defaults to 1 when not present. If additional
2221 * aggregating actions take arguments, the setting of the
2222 * default argument value will presumably have to become more
2223 * sophisticated...
2224 */
2225 arg = 1;
2226 }
2227
2228 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2229 size = rec->dtrd_offset - agg->dtag_base;
2230 fsize = size + rec->dtrd_size;
2231
2232 ASSERT(dbuf->dtb_tomax != NULL);
2233 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2234
2235 if ((tomax = buf->dtb_tomax) == NULL) {
2236 dtrace_buffer_drop(buf);
2237 return;
2238 }
2239
2240 /*
2241 * The metastructure is always at the bottom of the buffer.
2242 */
2243 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2244 sizeof (dtrace_aggbuffer_t));
2245
2246 if (buf->dtb_offset == 0) {
2247 /*
2248 * We just kludge up approximately 1/8th of the size to be
2249 * buckets. If this guess ends up being routinely
2250 * off-the-mark, we may need to dynamically readjust this
2251 * based on past performance.
2252 */
2253 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2254
2255 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2256 (uintptr_t)tomax || hashsize == 0) {
2257 /*
2258 * We've been given a ludicrously small buffer;
2259 * increment our drop count and leave.
2260 */
2261 dtrace_buffer_drop(buf);
2262 return;
2263 }
2264
2265 /*
2266 * And now, a pathetic attempt to try to get a an odd (or
2267 * perchance, a prime) hash size for better hash distribution.
2268 */
2269 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2270 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2271
2272 agb->dtagb_hashsize = hashsize;
2273 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2274 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2275 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2276
2277 for (i = 0; i < agb->dtagb_hashsize; i++)
2278 agb->dtagb_hash[i] = NULL;
2279 }
2280
2281 ASSERT(agg->dtag_first != NULL);
2282 ASSERT(agg->dtag_first->dta_intuple);
2283
2284 /*
2285 * Calculate the hash value based on the key. Note that we _don't_
2286 * include the aggid in the hashing (but we will store it as part of
2287 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2288 * algorithm: a simple, quick algorithm that has no known funnels, and
2289 * gets good distribution in practice. The efficacy of the hashing
2290 * algorithm (and a comparison with other algorithms) may be found by
2291 * running the ::dtrace_aggstat MDB dcmd.
2292 */
2293 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2294 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2295 limit = i + act->dta_rec.dtrd_size;
2296 ASSERT(limit <= size);
2297 isstr = DTRACEACT_ISSTRING(act);
2298
2299 for (; i < limit; i++) {
2300 hashval += data[i];
2301 hashval += (hashval << 10);
2302 hashval ^= (hashval >> 6);
2303
2304 if (isstr && data[i] == '\0')
2305 break;
2306 }
2307 }
2308
2309 hashval += (hashval << 3);
2310 hashval ^= (hashval >> 11);
2311 hashval += (hashval << 15);
2312
2313 /*
2314 * Yes, the divide here is expensive -- but it's generally the least
2315 * of the performance issues given the amount of data that we iterate
2316 * over to compute hash values, compare data, etc.
2317 */
2318 ndx = hashval % agb->dtagb_hashsize;
2319
2320 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2321 ASSERT((caddr_t)key >= tomax);
2322 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2323
2324 if (hashval != key->dtak_hashval || key->dtak_size != size)
2325 continue;
2326
2327 kdata = key->dtak_data;
2328 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2329
2330 for (act = agg->dtag_first; act->dta_intuple;
2331 act = act->dta_next) {
2332 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2333 limit = i + act->dta_rec.dtrd_size;
2334 ASSERT(limit <= size);
2335 isstr = DTRACEACT_ISSTRING(act);
2336
2337 for (; i < limit; i++) {
2338 if (kdata[i] != data[i])
2339 goto next;
2340
2341 if (isstr && data[i] == '\0')
2342 break;
2343 }
2344 }
2345
2346 if (action != key->dtak_action) {
2347 /*
2348 * We are aggregating on the same value in the same
2349 * aggregation with two different aggregating actions.
2350 * (This should have been picked up in the compiler,
2351 * so we may be dealing with errant or devious DIF.)
2352 * This is an error condition; we indicate as much,
2353 * and return.
2354 */
2355 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2356 return;
2357 }
2358
2359 /*
2360 * This is a hit: we need to apply the aggregator to
2361 * the value at this key.
2362 */
2363 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2364 return;
2365 next:
2366 continue;
2367 }
2368
2369 /*
2370 * We didn't find it. We need to allocate some zero-filled space,
2371 * link it into the hash table appropriately, and apply the aggregator
2372 * to the (zero-filled) value.
2373 */
2374 offs = buf->dtb_offset;
2375 while (offs & (align - 1))
2376 offs += sizeof (uint32_t);
2377
2378 /*
2379 * If we don't have enough room to both allocate a new key _and_
2380 * its associated data, increment the drop count and return.
2381 */
2382 if ((uintptr_t)tomax + offs + fsize >
2383 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2384 dtrace_buffer_drop(buf);
2385 return;
2386 }
2387
2388 /*CONSTCOND*/
2389 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2390 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2391 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2392
2393 key->dtak_data = kdata = tomax + offs;
2394 buf->dtb_offset = offs + fsize;
2395
2396 /*
2397 * Now copy the data across.
2398 */
2399 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2400
2401 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2402 kdata[i] = data[i];
2403
2404 /*
2405 * Because strings are not zeroed out by default, we need to iterate
2406 * looking for actions that store strings, and we need to explicitly
2407 * pad these strings out with zeroes.
2408 */
2409 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2410 int nul;
2411
2412 if (!DTRACEACT_ISSTRING(act))
2413 continue;
2414
2415 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2416 limit = i + act->dta_rec.dtrd_size;
2417 ASSERT(limit <= size);
2418
2419 for (nul = 0; i < limit; i++) {
2420 if (nul) {
2421 kdata[i] = '\0';
2422 continue;
2423 }
2424
2425 if (data[i] != '\0')
2426 continue;
2427
2428 nul = 1;
2429 }
2430 }
2431
2432 for (i = size; i < fsize; i++)
2433 kdata[i] = 0;
2434
2435 key->dtak_hashval = hashval;
2436 key->dtak_size = size;
2437 key->dtak_action = action;
2438 key->dtak_next = agb->dtagb_hash[ndx];
2439 agb->dtagb_hash[ndx] = key;
2440
2441 /*
2442 * Finally, apply the aggregator.
2443 */
2444 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2445 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2446 }
2447
2448 /*
2449 * Given consumer state, this routine finds a speculation in the INACTIVE
2450 * state and transitions it into the ACTIVE state. If there is no speculation
2451 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2452 * incremented -- it is up to the caller to take appropriate action.
2453 */
2454 static int
2455 dtrace_speculation(dtrace_state_t *state)
2456 {
2457 int i = 0;
2458 dtrace_speculation_state_t current;
2459 uint32_t *stat = &state->dts_speculations_unavail, count;
2460
2461 while (i < state->dts_nspeculations) {
2462 dtrace_speculation_t *spec = &state->dts_speculations[i];
2463
2464 current = spec->dtsp_state;
2465
2466 if (current != DTRACESPEC_INACTIVE) {
2467 if (current == DTRACESPEC_COMMITTINGMANY ||
2468 current == DTRACESPEC_COMMITTING ||
2469 current == DTRACESPEC_DISCARDING)
2470 stat = &state->dts_speculations_busy;
2471 i++;
2472 continue;
2473 }
2474
2475 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2476 current, DTRACESPEC_ACTIVE) == current)
2477 return (i + 1);
2478 }
2479
2480 /*
2481 * We couldn't find a speculation. If we found as much as a single
2482 * busy speculation buffer, we'll attribute this failure as "busy"
2483 * instead of "unavail".
2484 */
2485 do {
2486 count = *stat;
2487 } while (dtrace_cas32(stat, count, count + 1) != count);
2488
2489 return (0);
2490 }
2491
2492 /*
2493 * This routine commits an active speculation. If the specified speculation
2494 * is not in a valid state to perform a commit(), this routine will silently do
2495 * nothing. The state of the specified speculation is transitioned according
2496 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2497 */
2498 static void
2499 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2500 dtrace_specid_t which)
2501 {
2502 dtrace_speculation_t *spec;
2503 dtrace_buffer_t *src, *dest;
2504 uintptr_t daddr, saddr, dlimit, slimit;
2505 dtrace_speculation_state_t current, new;
2506 intptr_t offs;
2507 uint64_t timestamp;
2508
2509 if (which == 0)
2510 return;
2511
2512 if (which > state->dts_nspeculations) {
2513 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2514 return;
2515 }
2516
2517 spec = &state->dts_speculations[which - 1];
2518 src = &spec->dtsp_buffer[cpu];
2519 dest = &state->dts_buffer[cpu];
2520
2521 do {
2522 current = spec->dtsp_state;
2523
2524 if (current == DTRACESPEC_COMMITTINGMANY)
2525 break;
2526
2527 switch (current) {
2528 case DTRACESPEC_INACTIVE:
2529 case DTRACESPEC_DISCARDING:
2530 return;
2531
2532 case DTRACESPEC_COMMITTING:
2533 /*
2534 * This is only possible if we are (a) commit()'ing
2535 * without having done a prior speculate() on this CPU
2536 * and (b) racing with another commit() on a different
2537 * CPU. There's nothing to do -- we just assert that
2538 * our offset is 0.
2539 */
2540 ASSERT(src->dtb_offset == 0);
2541 return;
2542
2543 case DTRACESPEC_ACTIVE:
2544 new = DTRACESPEC_COMMITTING;
2545 break;
2546
2547 case DTRACESPEC_ACTIVEONE:
2548 /*
2549 * This speculation is active on one CPU. If our
2550 * buffer offset is non-zero, we know that the one CPU
2551 * must be us. Otherwise, we are committing on a
2552 * different CPU from the speculate(), and we must
2553 * rely on being asynchronously cleaned.
2554 */
2555 if (src->dtb_offset != 0) {
2556 new = DTRACESPEC_COMMITTING;
2557 break;
2558 }
2559 /*FALLTHROUGH*/
2560
2561 case DTRACESPEC_ACTIVEMANY:
2562 new = DTRACESPEC_COMMITTINGMANY;
2563 break;
2564
2565 default:
2566 ASSERT(0);
2567 }
2568 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2569 current, new) != current);
2570
2571 /*
2572 * We have set the state to indicate that we are committing this
2573 * speculation. Now reserve the necessary space in the destination
2574 * buffer.
2575 */
2576 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2577 sizeof (uint64_t), state, NULL)) < 0) {
2578 dtrace_buffer_drop(dest);
2579 goto out;
2580 }
2581
2582 /*
2583 * We have sufficient space to copy the speculative buffer into the
2584 * primary buffer. First, modify the speculative buffer, filling
2585 * in the timestamp of all entries with the current time. The data
2586 * must have the commit() time rather than the time it was traced,
2587 * so that all entries in the primary buffer are in timestamp order.
2588 */
2589 timestamp = dtrace_gethrtime();
2590 saddr = (uintptr_t)src->dtb_tomax;
2591 slimit = saddr + src->dtb_offset;
2592 while (saddr < slimit) {
2593 size_t size;
2594 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2595
2596 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2597 saddr += sizeof (dtrace_epid_t);
2598 continue;
2599 }
2600 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2601 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2602
2603 ASSERT3U(saddr + size, <=, slimit);
2604 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2605 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2606
2607 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2608
2609 saddr += size;
2610 }
2611
2612 /*
2613 * Copy the buffer across. (Note that this is a
2614 * highly subobtimal bcopy(); in the unlikely event that this becomes
2615 * a serious performance issue, a high-performance DTrace-specific
2616 * bcopy() should obviously be invented.)
2617 */
2618 daddr = (uintptr_t)dest->dtb_tomax + offs;
2619 dlimit = daddr + src->dtb_offset;
2620 saddr = (uintptr_t)src->dtb_tomax;
2621
2622 /*
2623 * First, the aligned portion.
2624 */
2625 while (dlimit - daddr >= sizeof (uint64_t)) {
2626 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2627
2628 daddr += sizeof (uint64_t);
2629 saddr += sizeof (uint64_t);
2630 }
2631
2632 /*
2633 * Now any left-over bit...
2634 */
2635 while (dlimit - daddr)
2636 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2637
2638 /*
2639 * Finally, commit the reserved space in the destination buffer.
2640 */
2641 dest->dtb_offset = offs + src->dtb_offset;
2642
2643 out:
2644 /*
2645 * If we're lucky enough to be the only active CPU on this speculation
2646 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2647 */
2648 if (current == DTRACESPEC_ACTIVE ||
2649 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2650 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2651 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2652
2653 ASSERT(rval == DTRACESPEC_COMMITTING);
2654 }
2655
2656 src->dtb_offset = 0;
2657 src->dtb_xamot_drops += src->dtb_drops;
2658 src->dtb_drops = 0;
2659 }
2660
2661 /*
2662 * This routine discards an active speculation. If the specified speculation
2663 * is not in a valid state to perform a discard(), this routine will silently
2664 * do nothing. The state of the specified speculation is transitioned
2665 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2666 */
2667 static void
2668 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2669 dtrace_specid_t which)
2670 {
2671 dtrace_speculation_t *spec;
2672 dtrace_speculation_state_t current, new;
2673 dtrace_buffer_t *buf;
2674
2675 if (which == 0)
2676 return;
2677
2678 if (which > state->dts_nspeculations) {
2679 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2680 return;
2681 }
2682
2683 spec = &state->dts_speculations[which - 1];
2684 buf = &spec->dtsp_buffer[cpu];
2685
2686 do {
2687 current = spec->dtsp_state;
2688
2689 switch (current) {
2690 case DTRACESPEC_INACTIVE:
2691 case DTRACESPEC_COMMITTINGMANY:
2692 case DTRACESPEC_COMMITTING:
2693 case DTRACESPEC_DISCARDING:
2694 return;
2695
2696 case DTRACESPEC_ACTIVE:
2697 case DTRACESPEC_ACTIVEMANY:
2698 new = DTRACESPEC_DISCARDING;
2699 break;
2700
2701 case DTRACESPEC_ACTIVEONE:
2702 if (buf->dtb_offset != 0) {
2703 new = DTRACESPEC_INACTIVE;
2704 } else {
2705 new = DTRACESPEC_DISCARDING;
2706 }
2707 break;
2708
2709 default:
2710 ASSERT(0);
2711 }
2712 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2713 current, new) != current);
2714
2715 buf->dtb_offset = 0;
2716 buf->dtb_drops = 0;
2717 }
2718
2719 /*
2720 * Note: not called from probe context. This function is called
2721 * asynchronously from cross call context to clean any speculations that are
2722 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2723 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2724 * speculation.
2725 */
2726 static void
2727 dtrace_speculation_clean_here(dtrace_state_t *state)
2728 {
2729 dtrace_icookie_t cookie;
2730 processorid_t cpu = CPU->cpu_id;
2731 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2732 dtrace_specid_t i;
2733
2734 cookie = dtrace_interrupt_disable();
2735
2736 if (dest->dtb_tomax == NULL) {
2737 dtrace_interrupt_enable(cookie);
2738 return;
2739 }
2740
2741 for (i = 0; i < state->dts_nspeculations; i++) {
2742 dtrace_speculation_t *spec = &state->dts_speculations[i];
2743 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2744
2745 if (src->dtb_tomax == NULL)
2746 continue;
2747
2748 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2749 src->dtb_offset = 0;
2750 continue;
2751 }
2752
2753 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2754 continue;
2755
2756 if (src->dtb_offset == 0)
2757 continue;
2758
2759 dtrace_speculation_commit(state, cpu, i + 1);
2760 }
2761
2762 dtrace_interrupt_enable(cookie);
2763 }
2764
2765 /*
2766 * Note: not called from probe context. This function is called
2767 * asynchronously (and at a regular interval) to clean any speculations that
2768 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2769 * is work to be done, it cross calls all CPUs to perform that work;
2770 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2771 * INACTIVE state until they have been cleaned by all CPUs.
2772 */
2773 static void
2774 dtrace_speculation_clean(dtrace_state_t *state)
2775 {
2776 int work = 0, rv;
2777 dtrace_specid_t i;
2778
2779 for (i = 0; i < state->dts_nspeculations; i++) {
2780 dtrace_speculation_t *spec = &state->dts_speculations[i];
2781
2782 ASSERT(!spec->dtsp_cleaning);
2783
2784 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2785 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2786 continue;
2787
2788 work++;
2789 spec->dtsp_cleaning = 1;
2790 }
2791
2792 if (!work)
2793 return;
2794
2795 dtrace_xcall(DTRACE_CPUALL,
2796 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2797
2798 /*
2799 * We now know that all CPUs have committed or discarded their
2800 * speculation buffers, as appropriate. We can now set the state
2801 * to inactive.
2802 */
2803 for (i = 0; i < state->dts_nspeculations; i++) {
2804 dtrace_speculation_t *spec = &state->dts_speculations[i];
2805 dtrace_speculation_state_t current, new;
2806
2807 if (!spec->dtsp_cleaning)
2808 continue;
2809
2810 current = spec->dtsp_state;
2811 ASSERT(current == DTRACESPEC_DISCARDING ||
2812 current == DTRACESPEC_COMMITTINGMANY);
2813
2814 new = DTRACESPEC_INACTIVE;
2815
2816 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2817 ASSERT(rv == current);
2818 spec->dtsp_cleaning = 0;
2819 }
2820 }
2821
2822 /*
2823 * Called as part of a speculate() to get the speculative buffer associated
2824 * with a given speculation. Returns NULL if the specified speculation is not
2825 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2826 * the active CPU is not the specified CPU -- the speculation will be
2827 * atomically transitioned into the ACTIVEMANY state.
2828 */
2829 static dtrace_buffer_t *
2830 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2831 dtrace_specid_t which)
2832 {
2833 dtrace_speculation_t *spec;
2834 dtrace_speculation_state_t current, new;
2835 dtrace_buffer_t *buf;
2836
2837 if (which == 0)
2838 return (NULL);
2839
2840 if (which > state->dts_nspeculations) {
2841 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2842 return (NULL);
2843 }
2844
2845 spec = &state->dts_speculations[which - 1];
2846 buf = &spec->dtsp_buffer[cpuid];
2847
2848 do {
2849 current = spec->dtsp_state;
2850
2851 switch (current) {
2852 case DTRACESPEC_INACTIVE:
2853 case DTRACESPEC_COMMITTINGMANY:
2854 case DTRACESPEC_DISCARDING:
2855 return (NULL);
2856
2857 case DTRACESPEC_COMMITTING:
2858 ASSERT(buf->dtb_offset == 0);
2859 return (NULL);
2860
2861 case DTRACESPEC_ACTIVEONE:
2862 /*
2863 * This speculation is currently active on one CPU.
2864 * Check the offset in the buffer; if it's non-zero,
2865 * that CPU must be us (and we leave the state alone).
2866 * If it's zero, assume that we're starting on a new
2867 * CPU -- and change the state to indicate that the
2868 * speculation is active on more than one CPU.
2869 */
2870 if (buf->dtb_offset != 0)
2871 return (buf);
2872
2873 new = DTRACESPEC_ACTIVEMANY;
2874 break;
2875
2876 case DTRACESPEC_ACTIVEMANY:
2877 return (buf);
2878
2879 case DTRACESPEC_ACTIVE:
2880 new = DTRACESPEC_ACTIVEONE;
2881 break;
2882
2883 default:
2884 ASSERT(0);
2885 }
2886 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2887 current, new) != current);
2888
2889 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2890 return (buf);
2891 }
2892
2893 /*
2894 * Return a string. In the event that the user lacks the privilege to access
2895 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2896 * don't fail access checking.
2897 *
2898 * dtrace_dif_variable() uses this routine as a helper for various
2899 * builtin values such as 'execname' and 'probefunc.'
2900 */
2901 uintptr_t
2902 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2903 dtrace_mstate_t *mstate)
2904 {
2905 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2906 uintptr_t ret;
2907 size_t strsz;
2908
2909 /*
2910 * The easy case: this probe is allowed to read all of memory, so
2911 * we can just return this as a vanilla pointer.
2912 */
2913 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2914 return (addr);
2915
2916 /*
2917 * This is the tougher case: we copy the string in question from
2918 * kernel memory into scratch memory and return it that way: this
2919 * ensures that we won't trip up when access checking tests the
2920 * BYREF return value.
2921 */
2922 strsz = dtrace_strlen((char *)addr, size) + 1;
2923
2924 if (mstate->dtms_scratch_ptr + strsz >
2925 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2926 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2927 return (NULL);
2928 }
2929
2930 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2931 strsz);
2932 ret = mstate->dtms_scratch_ptr;
2933 mstate->dtms_scratch_ptr += strsz;
2934 return (ret);
2935 }
2936
2937 /*
2938 * This function implements the DIF emulator's variable lookups. The emulator
2939 * passes a reserved variable identifier and optional built-in array index.
2940 */
2941 static uint64_t
2942 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2943 uint64_t ndx)
2944 {
2945 /*
2946 * If we're accessing one of the uncached arguments, we'll turn this
2947 * into a reference in the args array.
2948 */
2949 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2950 ndx = v - DIF_VAR_ARG0;
2951 v = DIF_VAR_ARGS;
2952 }
2953
2954 switch (v) {
2955 case DIF_VAR_ARGS:
2956 if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
2957 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
2958 CPU_DTRACE_KPRIV;
2959 return (0);
2960 }
2961
2962 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2963 if (ndx >= sizeof (mstate->dtms_arg) /
2964 sizeof (mstate->dtms_arg[0])) {
2965 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2966 dtrace_provider_t *pv;
2967 uint64_t val;
2968
2969 pv = mstate->dtms_probe->dtpr_provider;
2970 if (pv->dtpv_pops.dtps_getargval != NULL)
2971 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2972 mstate->dtms_probe->dtpr_id,
2973 mstate->dtms_probe->dtpr_arg, ndx, aframes);
2974 else
2975 val = dtrace_getarg(ndx, aframes);
2976
2977 /*
2978 * This is regrettably required to keep the compiler
2979 * from tail-optimizing the call to dtrace_getarg().
2980 * The condition always evaluates to true, but the
2981 * compiler has no way of figuring that out a priori.
2982 * (None of this would be necessary if the compiler
2983 * could be relied upon to _always_ tail-optimize
2984 * the call to dtrace_getarg() -- but it can't.)
2985 */
2986 if (mstate->dtms_probe != NULL)
2987 return (val);
2988
2989 ASSERT(0);
2990 }
2991
2992 return (mstate->dtms_arg[ndx]);
2993
2994 case DIF_VAR_UREGS: {
2995 klwp_t *lwp;
2996
2997 if (!dtrace_priv_proc(state, mstate))
2998 return (0);
2999
3000 if ((lwp = curthread->t_lwp) == NULL) {
3001 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3002 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
3003 return (0);
3004 }
3005
3006 return (dtrace_getreg(lwp->lwp_regs, ndx));
3007 }
3008
3009 case DIF_VAR_VMREGS: {
3010 uint64_t rval;
3011
3012 if (!dtrace_priv_kernel(state))
3013 return (0);
3014
3015 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3016
3017 rval = dtrace_getvmreg(ndx,
3018 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
3019
3020 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3021
3022 return (rval);
3023 }
3024
3025 case DIF_VAR_CURTHREAD:
3026 if (!dtrace_priv_proc(state, mstate))
3027 return (0);
3028 return ((uint64_t)(uintptr_t)curthread);
3029
3030 case DIF_VAR_TIMESTAMP:
3031 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3032 mstate->dtms_timestamp = dtrace_gethrtime();
3033 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3034 }
3035 return (mstate->dtms_timestamp);
3036
3037 case DIF_VAR_VTIMESTAMP:
3038 ASSERT(dtrace_vtime_references != 0);
3039 return (curthread->t_dtrace_vtime);
3040
3041 case DIF_VAR_WALLTIMESTAMP:
3042 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3043 mstate->dtms_walltimestamp = dtrace_gethrestime();
3044 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3045 }
3046 return (mstate->dtms_walltimestamp);
3047
3048 case DIF_VAR_IPL:
3049 if (!dtrace_priv_kernel(state))
3050 return (0);
3051 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3052 mstate->dtms_ipl = dtrace_getipl();
3053 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3054 }
3055 return (mstate->dtms_ipl);
3056
3057 case DIF_VAR_EPID:
3058 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3059 return (mstate->dtms_epid);
3060
3061 case DIF_VAR_ID:
3062 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3063 return (mstate->dtms_probe->dtpr_id);
3064
3065 case DIF_VAR_STACKDEPTH:
3066 if (!dtrace_priv_kernel(state))
3067 return (0);
3068 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3069 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3070
3071 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3072 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3073 }
3074 return (mstate->dtms_stackdepth);
3075
3076 case DIF_VAR_USTACKDEPTH:
3077 if (!dtrace_priv_proc(state, mstate))
3078 return (0);
3079 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3080 /*
3081 * See comment in DIF_VAR_PID.
3082 */
3083 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3084 CPU_ON_INTR(CPU)) {
3085 mstate->dtms_ustackdepth = 0;
3086 } else {
3087 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3088 mstate->dtms_ustackdepth =
3089 dtrace_getustackdepth();
3090 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3091 }
3092 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3093 }
3094 return (mstate->dtms_ustackdepth);
3095
3096 case DIF_VAR_CALLER:
3097 if (!dtrace_priv_kernel(state))
3098 return (0);
3099 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3100 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3101
3102 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3103 /*
3104 * If this is an unanchored probe, we are
3105 * required to go through the slow path:
3106 * dtrace_caller() only guarantees correct
3107 * results for anchored probes.
3108 */
3109 pc_t caller[2];
3110
3111 dtrace_getpcstack(caller, 2, aframes,
3112 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3113 mstate->dtms_caller = caller[1];
3114 } else if ((mstate->dtms_caller =
3115 dtrace_caller(aframes)) == -1) {
3116 /*
3117 * We have failed to do this the quick way;
3118 * we must resort to the slower approach of
3119 * calling dtrace_getpcstack().
3120 */
3121 pc_t caller;
3122
3123 dtrace_getpcstack(&caller, 1, aframes, NULL);
3124 mstate->dtms_caller = caller;
3125 }
3126
3127 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3128 }
3129 return (mstate->dtms_caller);
3130
3131 case DIF_VAR_UCALLER:
3132 if (!dtrace_priv_proc(state, mstate))
3133 return (0);
3134
3135 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3136 uint64_t ustack[3];
3137
3138 /*
3139 * dtrace_getupcstack() fills in the first uint64_t
3140 * with the current PID. The second uint64_t will
3141 * be the program counter at user-level. The third
3142 * uint64_t will contain the caller, which is what
3143 * we're after.
3144 */
3145 ustack[2] = NULL;
3146 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3147 dtrace_getupcstack(ustack, 3);
3148 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3149 mstate->dtms_ucaller = ustack[2];
3150 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3151 }
3152
3153 return (mstate->dtms_ucaller);
3154
3155 case DIF_VAR_PROBEPROV:
3156 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3157 return (dtrace_dif_varstr(
3158 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3159 state, mstate));
3160
3161 case DIF_VAR_PROBEMOD:
3162 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3163 return (dtrace_dif_varstr(
3164 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3165 state, mstate));
3166
3167 case DIF_VAR_PROBEFUNC:
3168 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3169 return (dtrace_dif_varstr(
3170 (uintptr_t)mstate->dtms_probe->dtpr_func,
3171 state, mstate));
3172
3173 case DIF_VAR_PROBENAME:
3174 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3175 return (dtrace_dif_varstr(
3176 (uintptr_t)mstate->dtms_probe->dtpr_name,
3177 state, mstate));
3178
3179 case DIF_VAR_PID:
3180 if (!dtrace_priv_proc(state, mstate))
3181 return (0);
3182
3183 /*
3184 * Note that we are assuming that an unanchored probe is
3185 * always due to a high-level interrupt. (And we're assuming
3186 * that there is only a single high level interrupt.)
3187 */
3188 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3189 return (pid0.pid_id);
3190
3191 /*
3192 * It is always safe to dereference one's own t_procp pointer:
3193 * it always points to a valid, allocated proc structure.
3194 * Further, it is always safe to dereference the p_pidp member
3195 * of one's own proc structure. (These are truisms becuase
3196 * threads and processes don't clean up their own state --
3197 * they leave that task to whomever reaps them.)
3198 */
3199 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3200
3201 case DIF_VAR_PPID:
3202 if (!dtrace_priv_proc(state, mstate))
3203 return (0);
3204
3205 /*
3206 * See comment in DIF_VAR_PID.
3207 */
3208 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3209 return (pid0.pid_id);
3210
3211 /*
3212 * It is always safe to dereference one's own t_procp pointer:
3213 * it always points to a valid, allocated proc structure.
3214 * (This is true because threads don't clean up their own
3215 * state -- they leave that task to whomever reaps them.)
3216 */
3217 return ((uint64_t)curthread->t_procp->p_ppid);
3218
3219 case DIF_VAR_TID:
3220 /*
3221 * See comment in DIF_VAR_PID.
3222 */
3223 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3224 return (0);
3225
3226 return ((uint64_t)curthread->t_tid);
3227
3228 case DIF_VAR_EXECNAME:
3229 if (!dtrace_priv_proc(state, mstate))
3230 return (0);
3231
3232 /*
3233 * See comment in DIF_VAR_PID.
3234 */
3235 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3236 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3237
3238 /*
3239 * It is always safe to dereference one's own t_procp pointer:
3240 * it always points to a valid, allocated proc structure.
3241 * (This is true because threads don't clean up their own
3242 * state -- they leave that task to whomever reaps them.)
3243 */
3244 return (dtrace_dif_varstr(
3245 (uintptr_t)curthread->t_procp->p_user.u_comm,
3246 state, mstate));
3247
3248 case DIF_VAR_ZONENAME:
3249 if (!dtrace_priv_proc(state, mstate))
3250 return (0);
3251
3252 /*
3253 * See comment in DIF_VAR_PID.
3254 */
3255 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3256 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3257
3258 /*
3259 * It is always safe to dereference one's own t_procp pointer:
3260 * it always points to a valid, allocated proc structure.
3261 * (This is true because threads don't clean up their own
3262 * state -- they leave that task to whomever reaps them.)
3263 */
3264 return (dtrace_dif_varstr(
3265 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3266 state, mstate));
3267
3268 case DIF_VAR_UID:
3269 if (!dtrace_priv_proc(state, mstate))
3270 return (0);
3271
3272 /*
3273 * See comment in DIF_VAR_PID.
3274 */
3275 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3276 return ((uint64_t)p0.p_cred->cr_uid);
3277
3278 /*
3279 * It is always safe to dereference one's own t_procp pointer:
3280 * it always points to a valid, allocated proc structure.
3281 * (This is true because threads don't clean up their own
3282 * state -- they leave that task to whomever reaps them.)
3283 *
3284 * Additionally, it is safe to dereference one's own process
3285 * credential, since this is never NULL after process birth.
3286 */
3287 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3288
3289 case DIF_VAR_GID:
3290 if (!dtrace_priv_proc(state, mstate))
3291 return (0);
3292
3293 /*
3294 * See comment in DIF_VAR_PID.
3295 */
3296 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3297 return ((uint64_t)p0.p_cred->cr_gid);
3298
3299 /*
3300 * It is always safe to dereference one's own t_procp pointer:
3301 * it always points to a valid, allocated proc structure.
3302 * (This is true because threads don't clean up their own
3303 * state -- they leave that task to whomever reaps them.)
3304 *
3305 * Additionally, it is safe to dereference one's own process
3306 * credential, since this is never NULL after process birth.
3307 */
3308 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3309
3310 case DIF_VAR_ERRNO: {
3311 klwp_t *lwp;
3312 if (!dtrace_priv_proc(state, mstate))
3313 return (0);
3314
3315 /*
3316 * See comment in DIF_VAR_PID.
3317 */
3318 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3319 return (0);
3320
3321 /*
3322 * It is always safe to dereference one's own t_lwp pointer in
3323 * the event that this pointer is non-NULL. (This is true
3324 * because threads and lwps don't clean up their own state --
3325 * they leave that task to whomever reaps them.)
3326 */
3327 if ((lwp = curthread->t_lwp) == NULL)
3328 return (0);
3329
3330 return ((uint64_t)lwp->lwp_errno);
3331 }
3332 default:
3333 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3334 return (0);
3335 }
3336 }
3337
3338 /*
3339 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3340 * Notice that we don't bother validating the proper number of arguments or
3341 * their types in the tuple stack. This isn't needed because all argument
3342 * interpretation is safe because of our load safety -- the worst that can
3343 * happen is that a bogus program can obtain bogus results.
3344 */
3345 static void
3346 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3347 dtrace_key_t *tupregs, int nargs,
3348 dtrace_mstate_t *mstate, dtrace_state_t *state)
3349 {
3350 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3351 volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3352 dtrace_vstate_t *vstate = &state->dts_vstate;
3353
3354 union {
3355 mutex_impl_t mi;
3356 uint64_t mx;
3357 } m;
3358
3359 union {
3360 krwlock_t ri;
3361 uintptr_t rw;
3362 } r;
3363
3364 switch (subr) {
3365 case DIF_SUBR_RAND:
3366 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3367 break;
3368
3369 case DIF_SUBR_MUTEX_OWNED:
3370 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3371 mstate, vstate)) {
3372 regs[rd] = NULL;
3373 break;
3374 }
3375
3376 m.mx = dtrace_load64(tupregs[0].dttk_value);
3377 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3378 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3379 else
3380 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3381 break;
3382
3383 case DIF_SUBR_MUTEX_OWNER:
3384 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3385 mstate, vstate)) {
3386 regs[rd] = NULL;
3387 break;
3388 }
3389
3390 m.mx = dtrace_load64(tupregs[0].dttk_value);
3391 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3392 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3393 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3394 else
3395 regs[rd] = 0;
3396 break;
3397
3398 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3399 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3400 mstate, vstate)) {
3401 regs[rd] = NULL;
3402 break;
3403 }
3404
3405 m.mx = dtrace_load64(tupregs[0].dttk_value);
3406 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3407 break;
3408
3409 case DIF_SUBR_MUTEX_TYPE_SPIN:
3410 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3411 mstate, vstate)) {
3412 regs[rd] = NULL;
3413 break;
3414 }
3415
3416 m.mx = dtrace_load64(tupregs[0].dttk_value);
3417 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3418 break;
3419
3420 case DIF_SUBR_RW_READ_HELD: {
3421 uintptr_t tmp;
3422
3423 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3424 mstate, vstate)) {
3425 regs[rd] = NULL;
3426 break;
3427 }
3428
3429 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3430 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3431 break;
3432 }
3433
3434 case DIF_SUBR_RW_WRITE_HELD:
3435 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3436 mstate, vstate)) {
3437 regs[rd] = NULL;
3438 break;
3439 }
3440
3441 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3442 regs[rd] = _RW_WRITE_HELD(&r.ri);
3443 break;
3444
3445 case DIF_SUBR_RW_ISWRITER:
3446 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3447 mstate, vstate)) {
3448 regs[rd] = NULL;
3449 break;
3450 }
3451
3452 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3453 regs[rd] = _RW_ISWRITER(&r.ri);
3454 break;
3455
3456 case DIF_SUBR_BCOPY: {
3457 /*
3458 * We need to be sure that the destination is in the scratch
3459 * region -- no other region is allowed.
3460 */
3461 uintptr_t src = tupregs[0].dttk_value;
3462 uintptr_t dest = tupregs[1].dttk_value;
3463 size_t size = tupregs[2].dttk_value;
3464
3465 if (!dtrace_inscratch(dest, size, mstate)) {
3466 *flags |= CPU_DTRACE_BADADDR;
3467 *illval = regs[rd];
3468 break;
3469 }
3470
3471 if (!dtrace_canload(src, size, mstate, vstate)) {
3472 regs[rd] = NULL;
3473 break;
3474 }
3475
3476 dtrace_bcopy((void *)src, (void *)dest, size);
3477 break;
3478 }
3479
3480 case DIF_SUBR_ALLOCA:
3481 case DIF_SUBR_COPYIN: {
3482 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3483 uint64_t size =
3484 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3485 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3486
3487 /*
3488 * This action doesn't require any credential checks since
3489 * probes will not activate in user contexts to which the
3490 * enabling user does not have permissions.
3491 */
3492
3493 /*
3494 * Rounding up the user allocation size could have overflowed
3495 * a large, bogus allocation (like -1ULL) to 0.
3496 */
3497 if (scratch_size < size ||
3498 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3499 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3500 regs[rd] = NULL;
3501 break;
3502 }
3503
3504 if (subr == DIF_SUBR_COPYIN) {
3505 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3506 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3507 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3508 }
3509
3510 mstate->dtms_scratch_ptr += scratch_size;
3511 regs[rd] = dest;
3512 break;
3513 }
3514
3515 case DIF_SUBR_COPYINTO: {
3516 uint64_t size = tupregs[1].dttk_value;
3517 uintptr_t dest = tupregs[2].dttk_value;
3518
3519 /*
3520 * This action doesn't require any credential checks since
3521 * probes will not activate in user contexts to which the
3522 * enabling user does not have permissions.
3523 */
3524 if (!dtrace_inscratch(dest, size, mstate)) {
3525 *flags |= CPU_DTRACE_BADADDR;
3526 *illval = regs[rd];
3527 break;
3528 }
3529
3530 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3531 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3532 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3533 break;
3534 }
3535
3536 case DIF_SUBR_COPYINSTR: {
3537 uintptr_t dest = mstate->dtms_scratch_ptr;
3538 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3539
3540 if (nargs > 1 && tupregs[1].dttk_value < size)
3541 size = tupregs[1].dttk_value + 1;
3542
3543 /*
3544 * This action doesn't require any credential checks since
3545 * probes will not activate in user contexts to which the
3546 * enabling user does not have permissions.
3547 */
3548 if (!DTRACE_INSCRATCH(mstate, size)) {
3549 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3550 regs[rd] = NULL;
3551 break;
3552 }
3553
3554 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3555 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3556 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3557
3558 ((char *)dest)[size - 1] = '\0';
3559 mstate->dtms_scratch_ptr += size;
3560 regs[rd] = dest;
3561 break;
3562 }
3563
3564 case DIF_SUBR_MSGSIZE:
3565 case DIF_SUBR_MSGDSIZE: {
3566 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3567 uintptr_t wptr, rptr;
3568 size_t count = 0;
3569 int cont = 0;
3570
3571 while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3572
3573 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3574 vstate)) {
3575 regs[rd] = NULL;
3576 break;
3577 }
3578
3579 wptr = dtrace_loadptr(baddr +
3580 offsetof(mblk_t, b_wptr));
3581
3582 rptr = dtrace_loadptr(baddr +
3583 offsetof(mblk_t, b_rptr));
3584
3585 if (wptr < rptr) {
3586 *flags |= CPU_DTRACE_BADADDR;
3587 *illval = tupregs[0].dttk_value;
3588 break;
3589 }
3590
3591 daddr = dtrace_loadptr(baddr +
3592 offsetof(mblk_t, b_datap));
3593
3594 baddr = dtrace_loadptr(baddr +
3595 offsetof(mblk_t, b_cont));
3596
3597 /*
3598 * We want to prevent against denial-of-service here,
3599 * so we're only going to search the list for
3600 * dtrace_msgdsize_max mblks.
3601 */
3602 if (cont++ > dtrace_msgdsize_max) {
3603 *flags |= CPU_DTRACE_ILLOP;
3604 break;
3605 }
3606
3607 if (subr == DIF_SUBR_MSGDSIZE) {
3608 if (dtrace_load8(daddr +
3609 offsetof(dblk_t, db_type)) != M_DATA)
3610 continue;
3611 }
3612
3613 count += wptr - rptr;
3614 }
3615
3616 if (!(*flags & CPU_DTRACE_FAULT))
3617 regs[rd] = count;
3618
3619 break;
3620 }
3621
3622 case DIF_SUBR_PROGENYOF: {
3623 pid_t pid = tupregs[0].dttk_value;
3624 proc_t *p;
3625 int rval = 0;
3626
3627 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3628
3629 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3630 if (p->p_pidp->pid_id == pid) {
3631 rval = 1;
3632 break;
3633 }
3634 }
3635
3636 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3637
3638 regs[rd] = rval;
3639 break;
3640 }
3641
3642 case DIF_SUBR_SPECULATION:
3643 regs[rd] = dtrace_speculation(state);
3644 break;
3645
3646 case DIF_SUBR_COPYOUT: {
3647 uintptr_t kaddr = tupregs[0].dttk_value;
3648 uintptr_t uaddr = tupregs[1].dttk_value;
3649 uint64_t size = tupregs[2].dttk_value;
3650
3651 if (!dtrace_destructive_disallow &&
3652 dtrace_priv_proc_control(state, mstate) &&
3653 !dtrace_istoxic(kaddr, size)) {
3654 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3655 dtrace_copyout(kaddr, uaddr, size, flags);
3656 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3657 }
3658 break;
3659 }
3660
3661 case DIF_SUBR_COPYOUTSTR: {
3662 uintptr_t kaddr = tupregs[0].dttk_value;
3663 uintptr_t uaddr = tupregs[1].dttk_value;
3664 uint64_t size = tupregs[2].dttk_value;
3665
3666 if (!dtrace_destructive_disallow &&
3667 dtrace_priv_proc_control(state, mstate) &&
3668 !dtrace_istoxic(kaddr, size)) {
3669 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3670 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3671 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3672 }
3673 break;
3674 }
3675
3676 case DIF_SUBR_STRLEN: {
3677 size_t sz;
3678 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3679 sz = dtrace_strlen((char *)addr,
3680 state->dts_options[DTRACEOPT_STRSIZE]);
3681
3682 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3683 regs[rd] = NULL;
3684 break;
3685 }
3686
3687 regs[rd] = sz;
3688
3689 break;
3690 }
3691
3692 case DIF_SUBR_STRCHR:
3693 case DIF_SUBR_STRRCHR: {
3694 /*
3695 * We're going to iterate over the string looking for the
3696 * specified character. We will iterate until we have reached
3697 * the string length or we have found the character. If this
3698 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3699 * of the specified character instead of the first.
3700 */
3701 uintptr_t saddr = tupregs[0].dttk_value;
3702 uintptr_t addr = tupregs[0].dttk_value;
3703 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3704 char c, target = (char)tupregs[1].dttk_value;
3705
3706 for (regs[rd] = NULL; addr < limit; addr++) {
3707 if ((c = dtrace_load8(addr)) == target) {
3708 regs[rd] = addr;
3709
3710 if (subr == DIF_SUBR_STRCHR)
3711 break;
3712 }
3713
3714 if (c == '\0')
3715 break;
3716 }
3717
3718 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3719 regs[rd] = NULL;
3720 break;
3721 }
3722
3723 break;
3724 }
3725
3726 case DIF_SUBR_STRSTR:
3727 case DIF_SUBR_INDEX:
3728 case DIF_SUBR_RINDEX: {
3729 /*
3730 * We're going to iterate over the string looking for the
3731 * specified string. We will iterate until we have reached
3732 * the string length or we have found the string. (Yes, this
3733 * is done in the most naive way possible -- but considering
3734 * that the string we're searching for is likely to be
3735 * relatively short, the complexity of Rabin-Karp or similar
3736 * hardly seems merited.)
3737 */
3738 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3739 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3740 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3741 size_t len = dtrace_strlen(addr, size);
3742 size_t sublen = dtrace_strlen(substr, size);
3743 char *limit = addr + len, *orig = addr;
3744 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3745 int inc = 1;
3746
3747 regs[rd] = notfound;
3748
3749 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3750 regs[rd] = NULL;
3751 break;
3752 }
3753
3754 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3755 vstate)) {
3756 regs[rd] = NULL;
3757 break;
3758 }
3759
3760 /*
3761 * strstr() and index()/rindex() have similar semantics if
3762 * both strings are the empty string: strstr() returns a
3763 * pointer to the (empty) string, and index() and rindex()
3764 * both return index 0 (regardless of any position argument).
3765 */
3766 if (sublen == 0 && len == 0) {
3767 if (subr == DIF_SUBR_STRSTR)
3768 regs[rd] = (uintptr_t)addr;
3769 else
3770 regs[rd] = 0;
3771 break;
3772 }
3773
3774 if (subr != DIF_SUBR_STRSTR) {
3775 if (subr == DIF_SUBR_RINDEX) {
3776 limit = orig - 1;
3777 addr += len;
3778 inc = -1;
3779 }
3780
3781 /*
3782 * Both index() and rindex() take an optional position
3783 * argument that denotes the starting position.
3784 */
3785 if (nargs == 3) {
3786 int64_t pos = (int64_t)tupregs[2].dttk_value;
3787
3788 /*
3789 * If the position argument to index() is
3790 * negative, Perl implicitly clamps it at
3791 * zero. This semantic is a little surprising
3792 * given the special meaning of negative
3793 * positions to similar Perl functions like
3794 * substr(), but it appears to reflect a
3795 * notion that index() can start from a
3796 * negative index and increment its way up to
3797 * the string. Given this notion, Perl's
3798 * rindex() is at least self-consistent in
3799 * that it implicitly clamps positions greater
3800 * than the string length to be the string
3801 * length. Where Perl completely loses
3802 * coherence, however, is when the specified
3803 * substring is the empty string (""). In
3804 * this case, even if the position is
3805 * negative, rindex() returns 0 -- and even if
3806 * the position is greater than the length,
3807 * index() returns the string length. These
3808 * semantics violate the notion that index()
3809 * should never return a value less than the
3810 * specified position and that rindex() should
3811 * never return a value greater than the
3812 * specified position. (One assumes that
3813 * these semantics are artifacts of Perl's
3814 * implementation and not the results of
3815 * deliberate design -- it beggars belief that
3816 * even Larry Wall could desire such oddness.)
3817 * While in the abstract one would wish for
3818 * consistent position semantics across
3819 * substr(), index() and rindex() -- or at the
3820 * very least self-consistent position
3821 * semantics for index() and rindex() -- we
3822 * instead opt to keep with the extant Perl
3823 * semantics, in all their broken glory. (Do
3824 * we have more desire to maintain Perl's
3825 * semantics than Perl does? Probably.)
3826 */
3827 if (subr == DIF_SUBR_RINDEX) {
3828 if (pos < 0) {
3829 if (sublen == 0)
3830 regs[rd] = 0;
3831 break;
3832 }
3833
3834 if (pos > len)
3835 pos = len;
3836 } else {
3837 if (pos < 0)
3838 pos = 0;
3839
3840 if (pos >= len) {
3841 if (sublen == 0)
3842 regs[rd] = len;
3843 break;
3844 }
3845 }
3846
3847 addr = orig + pos;
3848 }
3849 }
3850
3851 for (regs[rd] = notfound; addr != limit; addr += inc) {
3852 if (dtrace_strncmp(addr, substr, sublen) == 0) {
3853 if (subr != DIF_SUBR_STRSTR) {
3854 /*
3855 * As D index() and rindex() are
3856 * modeled on Perl (and not on awk),
3857 * we return a zero-based (and not a
3858 * one-based) index. (For you Perl
3859 * weenies: no, we're not going to add
3860 * $[ -- and shouldn't you be at a con
3861 * or something?)
3862 */
3863 regs[rd] = (uintptr_t)(addr - orig);
3864 break;
3865 }
3866
3867 ASSERT(subr == DIF_SUBR_STRSTR);
3868 regs[rd] = (uintptr_t)addr;
3869 break;
3870 }
3871 }
3872
3873 break;
3874 }
3875
3876 case DIF_SUBR_STRTOK: {
3877 uintptr_t addr = tupregs[0].dttk_value;
3878 uintptr_t tokaddr = tupregs[1].dttk_value;
3879 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3880 uintptr_t limit, toklimit = tokaddr + size;
3881 uint8_t c, tokmap[32]; /* 256 / 8 */
3882 char *dest = (char *)mstate->dtms_scratch_ptr;
3883 int i;
3884
3885 /*
3886 * Check both the token buffer and (later) the input buffer,
3887 * since both could be non-scratch addresses.
3888 */
3889 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3890 regs[rd] = NULL;
3891 break;
3892 }
3893
3894 if (!DTRACE_INSCRATCH(mstate, size)) {
3895 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3896 regs[rd] = NULL;
3897 break;
3898 }
3899
3900 if (addr == NULL) {
3901 /*
3902 * If the address specified is NULL, we use our saved
3903 * strtok pointer from the mstate. Note that this
3904 * means that the saved strtok pointer is _only_
3905 * valid within multiple enablings of the same probe --
3906 * it behaves like an implicit clause-local variable.
3907 */
3908 addr = mstate->dtms_strtok;
3909 } else {
3910 /*
3911 * If the user-specified address is non-NULL we must
3912 * access check it. This is the only time we have
3913 * a chance to do so, since this address may reside
3914 * in the string table of this clause-- future calls
3915 * (when we fetch addr from mstate->dtms_strtok)
3916 * would fail this access check.
3917 */
3918 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3919 regs[rd] = NULL;
3920 break;
3921 }
3922 }
3923
3924 /*
3925 * First, zero the token map, and then process the token
3926 * string -- setting a bit in the map for every character
3927 * found in the token string.
3928 */
3929 for (i = 0; i < sizeof (tokmap); i++)
3930 tokmap[i] = 0;
3931
3932 for (; tokaddr < toklimit; tokaddr++) {
3933 if ((c = dtrace_load8(tokaddr)) == '\0')
3934 break;
3935
3936 ASSERT((c >> 3) < sizeof (tokmap));
3937 tokmap[c >> 3] |= (1 << (c & 0x7));
3938 }
3939
3940 for (limit = addr + size; addr < limit; addr++) {
3941 /*
3942 * We're looking for a character that is _not_ contained
3943 * in the token string.
3944 */
3945 if ((c = dtrace_load8(addr)) == '\0')
3946 break;
3947
3948 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3949 break;
3950 }
3951
3952 if (c == '\0') {
3953 /*
3954 * We reached the end of the string without finding
3955 * any character that was not in the token string.
3956 * We return NULL in this case, and we set the saved
3957 * address to NULL as well.
3958 */
3959 regs[rd] = NULL;
3960 mstate->dtms_strtok = NULL;
3961 break;
3962 }
3963
3964 /*
3965 * From here on, we're copying into the destination string.
3966 */
3967 for (i = 0; addr < limit && i < size - 1; addr++) {
3968 if ((c = dtrace_load8(addr)) == '\0')
3969 break;
3970
3971 if (tokmap[c >> 3] & (1 << (c & 0x7)))
3972 break;
3973
3974 ASSERT(i < size);
3975 dest[i++] = c;
3976 }
3977
3978 ASSERT(i < size);
3979 dest[i] = '\0';
3980 regs[rd] = (uintptr_t)dest;
3981 mstate->dtms_scratch_ptr += size;
3982 mstate->dtms_strtok = addr;
3983 break;
3984 }
3985
3986 case DIF_SUBR_SUBSTR: {
3987 uintptr_t s = tupregs[0].dttk_value;
3988 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3989 char *d = (char *)mstate->dtms_scratch_ptr;
3990 int64_t index = (int64_t)tupregs[1].dttk_value;
3991 int64_t remaining = (int64_t)tupregs[2].dttk_value;
3992 size_t len = dtrace_strlen((char *)s, size);
3993 int64_t i;
3994
3995 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3996 regs[rd] = NULL;
3997 break;
3998 }
3999
4000 if (!DTRACE_INSCRATCH(mstate, size)) {
4001 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4002 regs[rd] = NULL;
4003 break;
4004 }
4005
4006 if (nargs <= 2)
4007 remaining = (int64_t)size;
4008
4009 if (index < 0) {
4010 index += len;
4011
4012 if (index < 0 && index + remaining > 0) {
4013 remaining += index;
4014 index = 0;
4015 }
4016 }
4017
4018 if (index >= len || index < 0) {
4019 remaining = 0;
4020 } else if (remaining < 0) {
4021 remaining += len - index;
4022 } else if (index + remaining > size) {
4023 remaining = size - index;
4024 }
4025
4026 for (i = 0; i < remaining; i++) {
4027 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4028 break;
4029 }
4030
4031 d[i] = '\0';
4032
4033 mstate->dtms_scratch_ptr += size;
4034 regs[rd] = (uintptr_t)d;
4035 break;
4036 }
4037
4038 case DIF_SUBR_TOUPPER:
4039 case DIF_SUBR_TOLOWER: {
4040 uintptr_t s = tupregs[0].dttk_value;
4041 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4042 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4043 size_t len = dtrace_strlen((char *)s, size);
4044 char lower, upper, convert;
4045 int64_t i;
4046
4047 if (subr == DIF_SUBR_TOUPPER) {
4048 lower = 'a';
4049 upper = 'z';
4050 convert = 'A';
4051 } else {
4052 lower = 'A';
4053 upper = 'Z';
4054 convert = 'a';
4055 }
4056
4057 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4058 regs[rd] = NULL;
4059 break;
4060 }
4061
4062 if (!DTRACE_INSCRATCH(mstate, size)) {
4063 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4064 regs[rd] = NULL;
4065 break;
4066 }
4067
4068 for (i = 0; i < size - 1; i++) {
4069 if ((c = dtrace_load8(s + i)) == '\0')
4070 break;
4071
4072 if (c >= lower && c <= upper)
4073 c = convert + (c - lower);
4074
4075 dest[i] = c;
4076 }
4077
4078 ASSERT(i < size);
4079 dest[i] = '\0';
4080 regs[rd] = (uintptr_t)dest;
4081 mstate->dtms_scratch_ptr += size;
4082 break;
4083 }
4084
4085 case DIF_SUBR_GETMAJOR:
4086 #ifdef _LP64
4087 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4088 #else
4089 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4090 #endif
4091 break;
4092
4093 case DIF_SUBR_GETMINOR:
4094 #ifdef _LP64
4095 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4096 #else
4097 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4098 #endif
4099 break;
4100
4101 case DIF_SUBR_DDI_PATHNAME: {
4102 /*
4103 * This one is a galactic mess. We are going to roughly
4104 * emulate ddi_pathname(), but it's made more complicated
4105 * by the fact that we (a) want to include the minor name and
4106 * (b) must proceed iteratively instead of recursively.
4107 */
4108 uintptr_t dest = mstate->dtms_scratch_ptr;
4109 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4110 char *start = (char *)dest, *end = start + size - 1;
4111 uintptr_t daddr = tupregs[0].dttk_value;
4112 int64_t minor = (int64_t)tupregs[1].dttk_value;
4113 char *s;
4114 int i, len, depth = 0;
4115
4116 /*
4117 * Due to all the pointer jumping we do and context we must
4118 * rely upon, we just mandate that the user must have kernel
4119 * read privileges to use this routine.
4120 */
4121 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4122 *flags |= CPU_DTRACE_KPRIV;
4123 *illval = daddr;
4124 regs[rd] = NULL;
4125 }
4126
4127 if (!DTRACE_INSCRATCH(mstate, size)) {
4128 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4129 regs[rd] = NULL;
4130 break;
4131 }
4132
4133 *end = '\0';
4134
4135 /*
4136 * We want to have a name for the minor. In order to do this,
4137 * we need to walk the minor list from the devinfo. We want
4138 * to be sure that we don't infinitely walk a circular list,
4139 * so we check for circularity by sending a scout pointer
4140 * ahead two elements for every element that we iterate over;
4141 * if the list is circular, these will ultimately point to the
4142 * same element. You may recognize this little trick as the
4143 * answer to a stupid interview question -- one that always
4144 * seems to be asked by those who had to have it laboriously
4145 * explained to them, and who can't even concisely describe
4146 * the conditions under which one would be forced to resort to
4147 * this technique. Needless to say, those conditions are
4148 * found here -- and probably only here. Is this the only use
4149 * of this infamous trick in shipping, production code? If it
4150 * isn't, it probably should be...
4151 */
4152 if (minor != -1) {
4153 uintptr_t maddr = dtrace_loadptr(daddr +
4154 offsetof(struct dev_info, devi_minor));
4155
4156 uintptr_t next = offsetof(struct ddi_minor_data, next);
4157 uintptr_t name = offsetof(struct ddi_minor_data,
4158 d_minor) + offsetof(struct ddi_minor, name);
4159 uintptr_t dev = offsetof(struct ddi_minor_data,
4160 d_minor) + offsetof(struct ddi_minor, dev);
4161 uintptr_t scout;
4162
4163 if (maddr != NULL)
4164 scout = dtrace_loadptr(maddr + next);
4165
4166 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4167 uint64_t m;
4168 #ifdef _LP64
4169 m = dtrace_load64(maddr + dev) & MAXMIN64;
4170 #else
4171 m = dtrace_load32(maddr + dev) & MAXMIN;
4172 #endif
4173 if (m != minor) {
4174 maddr = dtrace_loadptr(maddr + next);
4175
4176 if (scout == NULL)
4177 continue;
4178
4179 scout = dtrace_loadptr(scout + next);
4180
4181 if (scout == NULL)
4182 continue;
4183
4184 scout = dtrace_loadptr(scout + next);
4185
4186 if (scout == NULL)
4187 continue;
4188
4189 if (scout == maddr) {
4190 *flags |= CPU_DTRACE_ILLOP;
4191 break;
4192 }
4193
4194 continue;
4195 }
4196
4197 /*
4198 * We have the minor data. Now we need to
4199 * copy the minor's name into the end of the
4200 * pathname.
4201 */
4202 s = (char *)dtrace_loadptr(maddr + name);
4203 len = dtrace_strlen(s, size);
4204
4205 if (*flags & CPU_DTRACE_FAULT)
4206 break;
4207
4208 if (len != 0) {
4209 if ((end -= (len + 1)) < start)
4210 break;
4211
4212 *end = ':';
4213 }
4214
4215 for (i = 1; i <= len; i++)
4216 end[i] = dtrace_load8((uintptr_t)s++);
4217 break;
4218 }
4219 }
4220
4221 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4222 ddi_node_state_t devi_state;
4223
4224 devi_state = dtrace_load32(daddr +
4225 offsetof(struct dev_info, devi_node_state));
4226
4227 if (*flags & CPU_DTRACE_FAULT)
4228 break;
4229
4230 if (devi_state >= DS_INITIALIZED) {
4231 s = (char *)dtrace_loadptr(daddr +
4232 offsetof(struct dev_info, devi_addr));
4233 len = dtrace_strlen(s, size);
4234
4235 if (*flags & CPU_DTRACE_FAULT)
4236 break;
4237
4238 if (len != 0) {
4239 if ((end -= (len + 1)) < start)
4240 break;
4241
4242 *end = '@';
4243 }
4244
4245 for (i = 1; i <= len; i++)
4246 end[i] = dtrace_load8((uintptr_t)s++);
4247 }
4248
4249 /*
4250 * Now for the node name...
4251 */
4252 s = (char *)dtrace_loadptr(daddr +
4253 offsetof(struct dev_info, devi_node_name));
4254
4255 daddr = dtrace_loadptr(daddr +
4256 offsetof(struct dev_info, devi_parent));
4257
4258 /*
4259 * If our parent is NULL (that is, if we're the root
4260 * node), we're going to use the special path
4261 * "devices".
4262 */
4263 if (daddr == NULL)
4264 s = "devices";
4265
4266 len = dtrace_strlen(s, size);
4267 if (*flags & CPU_DTRACE_FAULT)
4268 break;
4269
4270 if ((end -= (len + 1)) < start)
4271 break;
4272
4273 for (i = 1; i <= len; i++)
4274 end[i] = dtrace_load8((uintptr_t)s++);
4275 *end = '/';
4276
4277 if (depth++ > dtrace_devdepth_max) {
4278 *flags |= CPU_DTRACE_ILLOP;
4279 break;
4280 }
4281 }
4282
4283 if (end < start)
4284 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4285
4286 if (daddr == NULL) {
4287 regs[rd] = (uintptr_t)end;
4288 mstate->dtms_scratch_ptr += size;
4289 }
4290
4291 break;
4292 }
4293
4294 case DIF_SUBR_STRJOIN: {
4295 char *d = (char *)mstate->dtms_scratch_ptr;
4296 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4297 uintptr_t s1 = tupregs[0].dttk_value;
4298 uintptr_t s2 = tupregs[1].dttk_value;
4299 int i = 0;
4300
4301 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4302 !dtrace_strcanload(s2, size, mstate, vstate)) {
4303 regs[rd] = NULL;
4304 break;
4305 }
4306
4307 if (!DTRACE_INSCRATCH(mstate, size)) {
4308 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4309 regs[rd] = NULL;
4310 break;
4311 }
4312
4313 for (;;) {
4314 if (i >= size) {
4315 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4316 regs[rd] = NULL;
4317 break;
4318 }
4319
4320 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4321 i--;
4322 break;
4323 }
4324 }
4325
4326 for (;;) {
4327 if (i >= size) {
4328 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4329 regs[rd] = NULL;
4330 break;
4331 }
4332
4333 if ((d[i++] = dtrace_load8(s2++)) == '\0')
4334 break;
4335 }
4336
4337 if (i < size) {
4338 mstate->dtms_scratch_ptr += i;
4339 regs[rd] = (uintptr_t)d;
4340 }
4341
4342 break;
4343 }
4344
4345 case DIF_SUBR_LLTOSTR: {
4346 int64_t i = (int64_t)tupregs[0].dttk_value;
4347 uint64_t val, digit;
4348 uint64_t size = 65; /* enough room for 2^64 in binary */
4349 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4350 int base = 10;
4351
4352 if (nargs > 1) {
4353 if ((base = tupregs[1].dttk_value) <= 1 ||
4354 base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4355 *flags |= CPU_DTRACE_ILLOP;
4356 break;
4357 }
4358 }
4359
4360 val = (base == 10 && i < 0) ? i * -1 : i;
4361
4362 if (!DTRACE_INSCRATCH(mstate, size)) {
4363 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4364 regs[rd] = NULL;
4365 break;
4366 }
4367
4368 for (*end-- = '\0'; val; val /= base) {
4369 if ((digit = val % base) <= '9' - '0') {
4370 *end-- = '0' + digit;
4371 } else {
4372 *end-- = 'a' + (digit - ('9' - '0') - 1);
4373 }
4374 }
4375
4376 if (i == 0 && base == 16)
4377 *end-- = '0';
4378
4379 if (base == 16)
4380 *end-- = 'x';
4381
4382 if (i == 0 || base == 8 || base == 16)
4383 *end-- = '0';
4384
4385 if (i < 0 && base == 10)
4386 *end-- = '-';
4387
4388 regs[rd] = (uintptr_t)end + 1;
4389 mstate->dtms_scratch_ptr += size;
4390 break;
4391 }
4392
4393 case DIF_SUBR_HTONS:
4394 case DIF_SUBR_NTOHS:
4395 #ifdef _BIG_ENDIAN
4396 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4397 #else
4398 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4399 #endif
4400 break;
4401
4402
4403 case DIF_SUBR_HTONL:
4404 case DIF_SUBR_NTOHL:
4405 #ifdef _BIG_ENDIAN
4406 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4407 #else
4408 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4409 #endif
4410 break;
4411
4412
4413 case DIF_SUBR_HTONLL:
4414 case DIF_SUBR_NTOHLL:
4415 #ifdef _BIG_ENDIAN
4416 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4417 #else
4418 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4419 #endif
4420 break;
4421
4422
4423 case DIF_SUBR_DIRNAME:
4424 case DIF_SUBR_BASENAME: {
4425 char *dest = (char *)mstate->dtms_scratch_ptr;
4426 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4427 uintptr_t src = tupregs[0].dttk_value;
4428 int i, j, len = dtrace_strlen((char *)src, size);
4429 int lastbase = -1, firstbase = -1, lastdir = -1;
4430 int start, end;
4431
4432 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4433 regs[rd] = NULL;
4434 break;
4435 }
4436
4437 if (!DTRACE_INSCRATCH(mstate, size)) {
4438 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4439 regs[rd] = NULL;
4440 break;
4441 }
4442
4443 /*
4444 * The basename and dirname for a zero-length string is
4445 * defined to be "."
4446 */
4447 if (len == 0) {
4448 len = 1;
4449 src = (uintptr_t)".";
4450 }
4451
4452 /*
4453 * Start from the back of the string, moving back toward the
4454 * front until we see a character that isn't a slash. That
4455 * character is the last character in the basename.
4456 */
4457 for (i = len - 1; i >= 0; i--) {
4458 if (dtrace_load8(src + i) != '/')
4459 break;
4460 }
4461
4462 if (i >= 0)
4463 lastbase = i;
4464
4465 /*
4466 * Starting from the last character in the basename, move
4467 * towards the front until we find a slash. The character
4468 * that we processed immediately before that is the first
4469 * character in the basename.
4470 */
4471 for (; i >= 0; i--) {
4472 if (dtrace_load8(src + i) == '/')
4473 break;
4474 }
4475
4476 if (i >= 0)
4477 firstbase = i + 1;
4478
4479 /*
4480 * Now keep going until we find a non-slash character. That
4481 * character is the last character in the dirname.
4482 */
4483 for (; i >= 0; i--) {
4484 if (dtrace_load8(src + i) != '/')
4485 break;
4486 }
4487
4488 if (i >= 0)
4489 lastdir = i;
4490
4491 ASSERT(!(lastbase == -1 && firstbase != -1));
4492 ASSERT(!(firstbase == -1 && lastdir != -1));
4493
4494 if (lastbase == -1) {
4495 /*
4496 * We didn't find a non-slash character. We know that
4497 * the length is non-zero, so the whole string must be
4498 * slashes. In either the dirname or the basename
4499 * case, we return '/'.
4500 */
4501 ASSERT(firstbase == -1);
4502 firstbase = lastbase = lastdir = 0;
4503 }
4504
4505 if (firstbase == -1) {
4506 /*
4507 * The entire string consists only of a basename
4508 * component. If we're looking for dirname, we need
4509 * to change our string to be just "."; if we're
4510 * looking for a basename, we'll just set the first
4511 * character of the basename to be 0.
4512 */
4513 if (subr == DIF_SUBR_DIRNAME) {
4514 ASSERT(lastdir == -1);
4515 src = (uintptr_t)".";
4516 lastdir = 0;
4517 } else {
4518 firstbase = 0;
4519 }
4520 }
4521
4522 if (subr == DIF_SUBR_DIRNAME) {
4523 if (lastdir == -1) {
4524 /*
4525 * We know that we have a slash in the name --
4526 * or lastdir would be set to 0, above. And
4527 * because lastdir is -1, we know that this
4528 * slash must be the first character. (That
4529 * is, the full string must be of the form
4530 * "/basename".) In this case, the last
4531 * character of the directory name is 0.
4532 */
4533 lastdir = 0;
4534 }
4535
4536 start = 0;
4537 end = lastdir;
4538 } else {
4539 ASSERT(subr == DIF_SUBR_BASENAME);
4540 ASSERT(firstbase != -1 && lastbase != -1);
4541 start = firstbase;
4542 end = lastbase;
4543 }
4544
4545 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4546 dest[j] = dtrace_load8(src + i);
4547
4548 dest[j] = '\0';
4549 regs[rd] = (uintptr_t)dest;
4550 mstate->dtms_scratch_ptr += size;
4551 break;
4552 }
4553
4554 case DIF_SUBR_GETF: {
4555 uintptr_t fd = tupregs[0].dttk_value;
4556 uf_info_t *finfo = &curthread->t_procp->p_user.u_finfo;
4557 file_t *fp;
4558
4559 if (!dtrace_priv_proc(state, mstate)) {
4560 regs[rd] = NULL;
4561 break;
4562 }
4563
4564 /*
4565 * This is safe because fi_nfiles only increases, and the
4566 * fi_list array is not freed when the array size doubles.
4567 * (See the comment in flist_grow() for details on the
4568 * management of the u_finfo structure.)
4569 */
4570 fp = fd < finfo->fi_nfiles ? finfo->fi_list[fd].uf_file : NULL;
4571
4572 mstate->dtms_getf = fp;
4573 regs[rd] = (uintptr_t)fp;
4574 break;
4575 }
4576
4577 case DIF_SUBR_CLEANPATH: {
4578 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4579 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4580 uintptr_t src = tupregs[0].dttk_value;
4581 int i = 0, j = 0;
4582 zone_t *z;
4583
4584 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4585 regs[rd] = NULL;
4586 break;
4587 }
4588
4589 if (!DTRACE_INSCRATCH(mstate, size)) {
4590 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4591 regs[rd] = NULL;
4592 break;
4593 }
4594
4595 /*
4596 * Move forward, loading each character.
4597 */
4598 do {
4599 c = dtrace_load8(src + i++);
4600 next:
4601 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
4602 break;
4603
4604 if (c != '/') {
4605 dest[j++] = c;
4606 continue;
4607 }
4608
4609 c = dtrace_load8(src + i++);
4610
4611 if (c == '/') {
4612 /*
4613 * We have two slashes -- we can just advance
4614 * to the next character.
4615 */
4616 goto next;
4617 }
4618
4619 if (c != '.') {
4620 /*
4621 * This is not "." and it's not ".." -- we can
4622 * just store the "/" and this character and
4623 * drive on.
4624 */
4625 dest[j++] = '/';
4626 dest[j++] = c;
4627 continue;
4628 }
4629
4630 c = dtrace_load8(src + i++);
4631
4632 if (c == '/') {
4633 /*
4634 * This is a "/./" component. We're not going
4635 * to store anything in the destination buffer;
4636 * we're just going to go to the next component.
4637 */
4638 goto next;
4639 }
4640
4641 if (c != '.') {
4642 /*
4643 * This is not ".." -- we can just store the
4644 * "/." and this character and continue
4645 * processing.
4646 */
4647 dest[j++] = '/';
4648 dest[j++] = '.';
4649 dest[j++] = c;
4650 continue;
4651 }
4652
4653 c = dtrace_load8(src + i++);
4654
4655 if (c != '/' && c != '\0') {
4656 /*
4657 * This is not ".." -- it's "..[mumble]".
4658 * We'll store the "/.." and this character
4659 * and continue processing.
4660 */
4661 dest[j++] = '/';
4662 dest[j++] = '.';
4663 dest[j++] = '.';
4664 dest[j++] = c;
4665 continue;
4666 }
4667
4668 /*
4669 * This is "/../" or "/..\0". We need to back up
4670 * our destination pointer until we find a "/".
4671 */
4672 i--;
4673 while (j != 0 && dest[--j] != '/')
4674 continue;
4675
4676 if (c == '\0')
4677 dest[++j] = '/';
4678 } while (c != '\0');
4679
4680 dest[j] = '\0';
4681
4682 if (mstate->dtms_getf != NULL &&
4683 !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
4684 (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
4685 /*
4686 * If we've done a getf() as a part of this ECB and we
4687 * don't have kernel access (and we're not in the global
4688 * zone), check if the path we cleaned up begins with
4689 * the zone's root path, and trim it off if so. Note
4690 * that this is an output cleanliness issue, not a
4691 * security issue: knowing one's zone root path does
4692 * not enable privilege escalation.
4693 */
4694 if (strstr(dest, z->zone_rootpath) == dest)
4695 dest += strlen(z->zone_rootpath) - 1;
4696 }
4697
4698 regs[rd] = (uintptr_t)dest;
4699 mstate->dtms_scratch_ptr += size;
4700 break;
4701 }
4702
4703 case DIF_SUBR_INET_NTOA:
4704 case DIF_SUBR_INET_NTOA6:
4705 case DIF_SUBR_INET_NTOP: {
4706 size_t size;
4707 int af, argi, i;
4708 char *base, *end;
4709
4710 if (subr == DIF_SUBR_INET_NTOP) {
4711 af = (int)tupregs[0].dttk_value;
4712 argi = 1;
4713 } else {
4714 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4715 argi = 0;
4716 }
4717
4718 if (af == AF_INET) {
4719 ipaddr_t ip4;
4720 uint8_t *ptr8, val;
4721
4722 /*
4723 * Safely load the IPv4 address.
4724 */
4725 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4726
4727 /*
4728 * Check an IPv4 string will fit in scratch.
4729 */
4730 size = INET_ADDRSTRLEN;
4731 if (!DTRACE_INSCRATCH(mstate, size)) {
4732 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4733 regs[rd] = NULL;
4734 break;
4735 }
4736 base = (char *)mstate->dtms_scratch_ptr;
4737 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4738
4739 /*
4740 * Stringify as a dotted decimal quad.
4741 */
4742 *end-- = '\0';
4743 ptr8 = (uint8_t *)&ip4;
4744 for (i = 3; i >= 0; i--) {
4745 val = ptr8[i];
4746
4747 if (val == 0) {
4748 *end-- = '0';
4749 } else {
4750 for (; val; val /= 10) {
4751 *end-- = '0' + (val % 10);
4752 }
4753 }
4754
4755 if (i > 0)
4756 *end-- = '.';
4757 }
4758 ASSERT(end + 1 >= base);
4759
4760 } else if (af == AF_INET6) {
4761 struct in6_addr ip6;
4762 int firstzero, tryzero, numzero, v6end;
4763 uint16_t val;
4764 const char digits[] = "0123456789abcdef";
4765
4766 /*
4767 * Stringify using RFC 1884 convention 2 - 16 bit
4768 * hexadecimal values with a zero-run compression.
4769 * Lower case hexadecimal digits are used.
4770 * eg, fe80::214:4fff:fe0b:76c8.
4771 * The IPv4 embedded form is returned for inet_ntop,
4772 * just the IPv4 string is returned for inet_ntoa6.
4773 */
4774
4775 /*
4776 * Safely load the IPv6 address.
4777 */
4778 dtrace_bcopy(
4779 (void *)(uintptr_t)tupregs[argi].dttk_value,
4780 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4781
4782 /*
4783 * Check an IPv6 string will fit in scratch.
4784 */
4785 size = INET6_ADDRSTRLEN;
4786 if (!DTRACE_INSCRATCH(mstate, size)) {
4787 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4788 regs[rd] = NULL;
4789 break;
4790 }
4791 base = (char *)mstate->dtms_scratch_ptr;
4792 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4793 *end-- = '\0';
4794
4795 /*
4796 * Find the longest run of 16 bit zero values
4797 * for the single allowed zero compression - "::".
4798 */
4799 firstzero = -1;
4800 tryzero = -1;
4801 numzero = 1;
4802 for (i = 0; i < sizeof (struct in6_addr); i++) {
4803 if (ip6._S6_un._S6_u8[i] == 0 &&
4804 tryzero == -1 && i % 2 == 0) {
4805 tryzero = i;
4806 continue;
4807 }
4808
4809 if (tryzero != -1 &&
4810 (ip6._S6_un._S6_u8[i] != 0 ||
4811 i == sizeof (struct in6_addr) - 1)) {
4812
4813 if (i - tryzero <= numzero) {
4814 tryzero = -1;
4815 continue;
4816 }
4817
4818 firstzero = tryzero;
4819 numzero = i - i % 2 - tryzero;
4820 tryzero = -1;
4821
4822 if (ip6._S6_un._S6_u8[i] == 0 &&
4823 i == sizeof (struct in6_addr) - 1)
4824 numzero += 2;
4825 }
4826 }
4827 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4828
4829 /*
4830 * Check for an IPv4 embedded address.
4831 */
4832 v6end = sizeof (struct in6_addr) - 2;
4833 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4834 IN6_IS_ADDR_V4COMPAT(&ip6)) {
4835 for (i = sizeof (struct in6_addr) - 1;
4836 i >= DTRACE_V4MAPPED_OFFSET; i--) {
4837 ASSERT(end >= base);
4838
4839 val = ip6._S6_un._S6_u8[i];
4840
4841 if (val == 0) {
4842 *end-- = '0';
4843 } else {
4844 for (; val; val /= 10) {
4845 *end-- = '0' + val % 10;
4846 }
4847 }
4848
4849 if (i > DTRACE_V4MAPPED_OFFSET)
4850 *end-- = '.';
4851 }
4852
4853 if (subr == DIF_SUBR_INET_NTOA6)
4854 goto inetout;
4855
4856 /*
4857 * Set v6end to skip the IPv4 address that
4858 * we have already stringified.
4859 */
4860 v6end = 10;
4861 }
4862
4863 /*
4864 * Build the IPv6 string by working through the
4865 * address in reverse.
4866 */
4867 for (i = v6end; i >= 0; i -= 2) {
4868 ASSERT(end >= base);
4869
4870 if (i == firstzero + numzero - 2) {
4871 *end-- = ':';
4872 *end-- = ':';
4873 i -= numzero - 2;
4874 continue;
4875 }
4876
4877 if (i < 14 && i != firstzero - 2)
4878 *end-- = ':';
4879
4880 val = (ip6._S6_un._S6_u8[i] << 8) +
4881 ip6._S6_un._S6_u8[i + 1];
4882
4883 if (val == 0) {
4884 *end-- = '0';
4885 } else {
4886 for (; val; val /= 16) {
4887 *end-- = digits[val % 16];
4888 }
4889 }
4890 }
4891 ASSERT(end + 1 >= base);
4892
4893 } else {
4894 /*
4895 * The user didn't use AH_INET or AH_INET6.
4896 */
4897 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4898 regs[rd] = NULL;
4899 break;
4900 }
4901
4902 inetout: regs[rd] = (uintptr_t)end + 1;
4903 mstate->dtms_scratch_ptr += size;
4904 break;
4905 }
4906
4907 }
4908 }
4909
4910 /*
4911 * Emulate the execution of DTrace IR instructions specified by the given
4912 * DIF object. This function is deliberately void of assertions as all of
4913 * the necessary checks are handled by a call to dtrace_difo_validate().
4914 */
4915 static uint64_t
4916 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4917 dtrace_vstate_t *vstate, dtrace_state_t *state)
4918 {
4919 const dif_instr_t *text = difo->dtdo_buf;
4920 const uint_t textlen = difo->dtdo_len;
4921 const char *strtab = difo->dtdo_strtab;
4922 const uint64_t *inttab = difo->dtdo_inttab;
4923
4924 uint64_t rval = 0;
4925 dtrace_statvar_t *svar;
4926 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4927 dtrace_difv_t *v;
4928 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4929 volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4930
4931 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4932 uint64_t regs[DIF_DIR_NREGS];
4933 uint64_t *tmp;
4934
4935 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4936 int64_t cc_r;
4937 uint_t pc = 0, id, opc;
4938 uint8_t ttop = 0;
4939 dif_instr_t instr;
4940 uint_t r1, r2, rd;
4941
4942 /*
4943 * We stash the current DIF object into the machine state: we need it
4944 * for subsequent access checking.
4945 */
4946 mstate->dtms_difo = difo;
4947
4948 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
4949
4950 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4951 opc = pc;
4952
4953 instr = text[pc++];
4954 r1 = DIF_INSTR_R1(instr);
4955 r2 = DIF_INSTR_R2(instr);
4956 rd = DIF_INSTR_RD(instr);
4957
4958 switch (DIF_INSTR_OP(instr)) {
4959 case DIF_OP_OR:
4960 regs[rd] = regs[r1] | regs[r2];
4961 break;
4962 case DIF_OP_XOR:
4963 regs[rd] = regs[r1] ^ regs[r2];
4964 break;
4965 case DIF_OP_AND:
4966 regs[rd] = regs[r1] & regs[r2];
4967 break;
4968 case DIF_OP_SLL:
4969 regs[rd] = regs[r1] << regs[r2];
4970 break;
4971 case DIF_OP_SRL:
4972 regs[rd] = regs[r1] >> regs[r2];
4973 break;
4974 case DIF_OP_SUB:
4975 regs[rd] = regs[r1] - regs[r2];
4976 break;
4977 case DIF_OP_ADD:
4978 regs[rd] = regs[r1] + regs[r2];
4979 break;
4980 case DIF_OP_MUL:
4981 regs[rd] = regs[r1] * regs[r2];
4982 break;
4983 case DIF_OP_SDIV:
4984 if (regs[r2] == 0) {
4985 regs[rd] = 0;
4986 *flags |= CPU_DTRACE_DIVZERO;
4987 } else {
4988 regs[rd] = (int64_t)regs[r1] /
4989 (int64_t)regs[r2];
4990 }
4991 break;
4992
4993 case DIF_OP_UDIV:
4994 if (regs[r2] == 0) {
4995 regs[rd] = 0;
4996 *flags |= CPU_DTRACE_DIVZERO;
4997 } else {
4998 regs[rd] = regs[r1] / regs[r2];
4999 }
5000 break;
5001
5002 case DIF_OP_SREM:
5003 if (regs[r2] == 0) {
5004 regs[rd] = 0;
5005 *flags |= CPU_DTRACE_DIVZERO;
5006 } else {
5007 regs[rd] = (int64_t)regs[r1] %
5008 (int64_t)regs[r2];
5009 }
5010 break;
5011
5012 case DIF_OP_UREM:
5013 if (regs[r2] == 0) {
5014 regs[rd] = 0;
5015 *flags |= CPU_DTRACE_DIVZERO;
5016 } else {
5017 regs[rd] = regs[r1] % regs[r2];
5018 }
5019 break;
5020
5021 case DIF_OP_NOT:
5022 regs[rd] = ~regs[r1];
5023 break;
5024 case DIF_OP_MOV:
5025 regs[rd] = regs[r1];
5026 break;
5027 case DIF_OP_CMP:
5028 cc_r = regs[r1] - regs[r2];
5029 cc_n = cc_r < 0;
5030 cc_z = cc_r == 0;
5031 cc_v = 0;
5032 cc_c = regs[r1] < regs[r2];
5033 break;
5034 case DIF_OP_TST:
5035 cc_n = cc_v = cc_c = 0;
5036 cc_z = regs[r1] == 0;
5037 break;
5038 case DIF_OP_BA:
5039 pc = DIF_INSTR_LABEL(instr);
5040 break;
5041 case DIF_OP_BE:
5042 if (cc_z)
5043 pc = DIF_INSTR_LABEL(instr);
5044 break;
5045 case DIF_OP_BNE:
5046 if (cc_z == 0)
5047 pc = DIF_INSTR_LABEL(instr);
5048 break;
5049 case DIF_OP_BG:
5050 if ((cc_z | (cc_n ^ cc_v)) == 0)
5051 pc = DIF_INSTR_LABEL(instr);
5052 break;
5053 case DIF_OP_BGU:
5054 if ((cc_c | cc_z) == 0)
5055 pc = DIF_INSTR_LABEL(instr);
5056 break;
5057 case DIF_OP_BGE:
5058 if ((cc_n ^ cc_v) == 0)
5059 pc = DIF_INSTR_LABEL(instr);
5060 break;
5061 case DIF_OP_BGEU:
5062 if (cc_c == 0)
5063 pc = DIF_INSTR_LABEL(instr);
5064 break;
5065 case DIF_OP_BL:
5066 if (cc_n ^ cc_v)
5067 pc = DIF_INSTR_LABEL(instr);
5068 break;
5069 case DIF_OP_BLU:
5070 if (cc_c)
5071 pc = DIF_INSTR_LABEL(instr);
5072 break;
5073 case DIF_OP_BLE:
5074 if (cc_z | (cc_n ^ cc_v))
5075 pc = DIF_INSTR_LABEL(instr);
5076 break;
5077 case DIF_OP_BLEU:
5078 if (cc_c | cc_z)
5079 pc = DIF_INSTR_LABEL(instr);
5080 break;
5081 case DIF_OP_RLDSB:
5082 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5083 break;
5084 /*FALLTHROUGH*/
5085 case DIF_OP_LDSB:
5086 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5087 break;
5088 case DIF_OP_RLDSH:
5089 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5090 break;
5091 /*FALLTHROUGH*/
5092 case DIF_OP_LDSH:
5093 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5094 break;
5095 case DIF_OP_RLDSW:
5096 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5097 break;
5098 /*FALLTHROUGH*/
5099 case DIF_OP_LDSW:
5100 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5101 break;
5102 case DIF_OP_RLDUB:
5103 if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5104 break;
5105 /*FALLTHROUGH*/
5106 case DIF_OP_LDUB:
5107 regs[rd] = dtrace_load8(regs[r1]);
5108 break;
5109 case DIF_OP_RLDUH:
5110 if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5111 break;
5112 /*FALLTHROUGH*/
5113 case DIF_OP_LDUH:
5114 regs[rd] = dtrace_load16(regs[r1]);
5115 break;
5116 case DIF_OP_RLDUW:
5117 if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5118 break;
5119 /*FALLTHROUGH*/
5120 case DIF_OP_LDUW:
5121 regs[rd] = dtrace_load32(regs[r1]);
5122 break;
5123 case DIF_OP_RLDX:
5124 if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5125 break;
5126 /*FALLTHROUGH*/
5127 case DIF_OP_LDX:
5128 regs[rd] = dtrace_load64(regs[r1]);
5129 break;
5130 case DIF_OP_ULDSB:
5131 regs[rd] = (int8_t)
5132 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5133 break;
5134 case DIF_OP_ULDSH:
5135 regs[rd] = (int16_t)
5136 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5137 break;
5138 case DIF_OP_ULDSW:
5139 regs[rd] = (int32_t)
5140 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5141 break;
5142 case DIF_OP_ULDUB:
5143 regs[rd] =
5144 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5145 break;
5146 case DIF_OP_ULDUH:
5147 regs[rd] =
5148 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5149 break;
5150 case DIF_OP_ULDUW:
5151 regs[rd] =
5152 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5153 break;
5154 case DIF_OP_ULDX:
5155 regs[rd] =
5156 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5157 break;
5158 case DIF_OP_RET:
5159 rval = regs[rd];
5160 pc = textlen;
5161 break;
5162 case DIF_OP_NOP:
5163 break;
5164 case DIF_OP_SETX:
5165 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5166 break;
5167 case DIF_OP_SETS:
5168 regs[rd] = (uint64_t)(uintptr_t)
5169 (strtab + DIF_INSTR_STRING(instr));
5170 break;
5171 case DIF_OP_SCMP: {
5172 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5173 uintptr_t s1 = regs[r1];
5174 uintptr_t s2 = regs[r2];
5175
5176 if (s1 != NULL &&
5177 !dtrace_strcanload(s1, sz, mstate, vstate))
5178 break;
5179 if (s2 != NULL &&
5180 !dtrace_strcanload(s2, sz, mstate, vstate))
5181 break;
5182
5183 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5184
5185 cc_n = cc_r < 0;
5186 cc_z = cc_r == 0;
5187 cc_v = cc_c = 0;
5188 break;
5189 }
5190 case DIF_OP_LDGA:
5191 regs[rd] = dtrace_dif_variable(mstate, state,
5192 r1, regs[r2]);
5193 break;
5194 case DIF_OP_LDGS:
5195 id = DIF_INSTR_VAR(instr);
5196
5197 if (id >= DIF_VAR_OTHER_UBASE) {
5198 uintptr_t a;
5199
5200 id -= DIF_VAR_OTHER_UBASE;
5201 svar = vstate->dtvs_globals[id];
5202 ASSERT(svar != NULL);
5203 v = &svar->dtsv_var;
5204
5205 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5206 regs[rd] = svar->dtsv_data;
5207 break;
5208 }
5209
5210 a = (uintptr_t)svar->dtsv_data;
5211
5212 if (*(uint8_t *)a == UINT8_MAX) {
5213 /*
5214 * If the 0th byte is set to UINT8_MAX
5215 * then this is to be treated as a
5216 * reference to a NULL variable.
5217 */
5218 regs[rd] = NULL;
5219 } else {
5220 regs[rd] = a + sizeof (uint64_t);
5221 }
5222
5223 break;
5224 }
5225
5226 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5227 break;
5228
5229 case DIF_OP_STGS:
5230 id = DIF_INSTR_VAR(instr);
5231
5232 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5233 id -= DIF_VAR_OTHER_UBASE;
5234
5235 svar = vstate->dtvs_globals[id];
5236 ASSERT(svar != NULL);
5237 v = &svar->dtsv_var;
5238
5239 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5240 uintptr_t a = (uintptr_t)svar->dtsv_data;
5241
5242 ASSERT(a != NULL);
5243 ASSERT(svar->dtsv_size != 0);
5244
5245 if (regs[rd] == NULL) {
5246 *(uint8_t *)a = UINT8_MAX;
5247 break;
5248 } else {
5249 *(uint8_t *)a = 0;
5250 a += sizeof (uint64_t);
5251 }
5252 if (!dtrace_vcanload(
5253 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5254 mstate, vstate))
5255 break;
5256
5257 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5258 (void *)a, &v->dtdv_type);
5259 break;
5260 }
5261
5262 svar->dtsv_data = regs[rd];
5263 break;
5264
5265 case DIF_OP_LDTA:
5266 /*
5267 * There are no DTrace built-in thread-local arrays at
5268 * present. This opcode is saved for future work.
5269 */
5270 *flags |= CPU_DTRACE_ILLOP;
5271 regs[rd] = 0;
5272 break;
5273
5274 case DIF_OP_LDLS:
5275 id = DIF_INSTR_VAR(instr);
5276
5277 if (id < DIF_VAR_OTHER_UBASE) {
5278 /*
5279 * For now, this has no meaning.
5280 */
5281 regs[rd] = 0;
5282 break;
5283 }
5284
5285 id -= DIF_VAR_OTHER_UBASE;
5286
5287 ASSERT(id < vstate->dtvs_nlocals);
5288 ASSERT(vstate->dtvs_locals != NULL);
5289
5290 svar = vstate->dtvs_locals[id];
5291 ASSERT(svar != NULL);
5292 v = &svar->dtsv_var;
5293
5294 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5295 uintptr_t a = (uintptr_t)svar->dtsv_data;
5296 size_t sz = v->dtdv_type.dtdt_size;
5297
5298 sz += sizeof (uint64_t);
5299 ASSERT(svar->dtsv_size == NCPU * sz);
5300 a += CPU->cpu_id * sz;
5301
5302 if (*(uint8_t *)a == UINT8_MAX) {
5303 /*
5304 * If the 0th byte is set to UINT8_MAX
5305 * then this is to be treated as a
5306 * reference to a NULL variable.
5307 */
5308 regs[rd] = NULL;
5309 } else {
5310 regs[rd] = a + sizeof (uint64_t);
5311 }
5312
5313 break;
5314 }
5315
5316 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5317 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5318 regs[rd] = tmp[CPU->cpu_id];
5319 break;
5320
5321 case DIF_OP_STLS:
5322 id = DIF_INSTR_VAR(instr);
5323
5324 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5325 id -= DIF_VAR_OTHER_UBASE;
5326 ASSERT(id < vstate->dtvs_nlocals);
5327
5328 ASSERT(vstate->dtvs_locals != NULL);
5329 svar = vstate->dtvs_locals[id];
5330 ASSERT(svar != NULL);
5331 v = &svar->dtsv_var;
5332
5333 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5334 uintptr_t a = (uintptr_t)svar->dtsv_data;
5335 size_t sz = v->dtdv_type.dtdt_size;
5336
5337 sz += sizeof (uint64_t);
5338 ASSERT(svar->dtsv_size == NCPU * sz);
5339 a += CPU->cpu_id * sz;
5340
5341 if (regs[rd] == NULL) {
5342 *(uint8_t *)a = UINT8_MAX;
5343 break;
5344 } else {
5345 *(uint8_t *)a = 0;
5346 a += sizeof (uint64_t);
5347 }
5348
5349 if (!dtrace_vcanload(
5350 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5351 mstate, vstate))
5352 break;
5353
5354 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5355 (void *)a, &v->dtdv_type);
5356 break;
5357 }
5358
5359 ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5360 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5361 tmp[CPU->cpu_id] = regs[rd];
5362 break;
5363
5364 case DIF_OP_LDTS: {
5365 dtrace_dynvar_t *dvar;
5366 dtrace_key_t *key;
5367
5368 id = DIF_INSTR_VAR(instr);
5369 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5370 id -= DIF_VAR_OTHER_UBASE;
5371 v = &vstate->dtvs_tlocals[id];
5372
5373 key = &tupregs[DIF_DTR_NREGS];
5374 key[0].dttk_value = (uint64_t)id;
5375 key[0].dttk_size = 0;
5376 DTRACE_TLS_THRKEY(key[1].dttk_value);
5377 key[1].dttk_size = 0;
5378
5379 dvar = dtrace_dynvar(dstate, 2, key,
5380 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5381 mstate, vstate);
5382
5383 if (dvar == NULL) {
5384 regs[rd] = 0;
5385 break;
5386 }
5387
5388 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5389 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5390 } else {
5391 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5392 }
5393
5394 break;
5395 }
5396
5397 case DIF_OP_STTS: {
5398 dtrace_dynvar_t *dvar;
5399 dtrace_key_t *key;
5400
5401 id = DIF_INSTR_VAR(instr);
5402 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5403 id -= DIF_VAR_OTHER_UBASE;
5404
5405 key = &tupregs[DIF_DTR_NREGS];
5406 key[0].dttk_value = (uint64_t)id;
5407 key[0].dttk_size = 0;
5408 DTRACE_TLS_THRKEY(key[1].dttk_value);
5409 key[1].dttk_size = 0;
5410 v = &vstate->dtvs_tlocals[id];
5411
5412 dvar = dtrace_dynvar(dstate, 2, key,
5413 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5414 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5415 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5416 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5417
5418 /*
5419 * Given that we're storing to thread-local data,
5420 * we need to flush our predicate cache.
5421 */
5422 curthread->t_predcache = NULL;
5423
5424 if (dvar == NULL)
5425 break;
5426
5427 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5428 if (!dtrace_vcanload(
5429 (void *)(uintptr_t)regs[rd],
5430 &v->dtdv_type, mstate, vstate))
5431 break;
5432
5433 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5434 dvar->dtdv_data, &v->dtdv_type);
5435 } else {
5436 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5437 }
5438
5439 break;
5440 }
5441
5442 case DIF_OP_SRA:
5443 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5444 break;
5445
5446 case DIF_OP_CALL:
5447 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5448 regs, tupregs, ttop, mstate, state);
5449 break;
5450
5451 case DIF_OP_PUSHTR:
5452 if (ttop == DIF_DTR_NREGS) {
5453 *flags |= CPU_DTRACE_TUPOFLOW;
5454 break;
5455 }
5456
5457 if (r1 == DIF_TYPE_STRING) {
5458 /*
5459 * If this is a string type and the size is 0,
5460 * we'll use the system-wide default string
5461 * size. Note that we are _not_ looking at
5462 * the value of the DTRACEOPT_STRSIZE option;
5463 * had this been set, we would expect to have
5464 * a non-zero size value in the "pushtr".
5465 */
5466 tupregs[ttop].dttk_size =
5467 dtrace_strlen((char *)(uintptr_t)regs[rd],
5468 regs[r2] ? regs[r2] :
5469 dtrace_strsize_default) + 1;
5470 } else {
5471 tupregs[ttop].dttk_size = regs[r2];
5472 }
5473
5474 tupregs[ttop++].dttk_value = regs[rd];
5475 break;
5476
5477 case DIF_OP_PUSHTV:
5478 if (ttop == DIF_DTR_NREGS) {
5479 *flags |= CPU_DTRACE_TUPOFLOW;
5480 break;
5481 }
5482
5483 tupregs[ttop].dttk_value = regs[rd];
5484 tupregs[ttop++].dttk_size = 0;
5485 break;
5486
5487 case DIF_OP_POPTS:
5488 if (ttop != 0)
5489 ttop--;
5490 break;
5491
5492 case DIF_OP_FLUSHTS:
5493 ttop = 0;
5494 break;
5495
5496 case DIF_OP_LDGAA:
5497 case DIF_OP_LDTAA: {
5498 dtrace_dynvar_t *dvar;
5499 dtrace_key_t *key = tupregs;
5500 uint_t nkeys = ttop;
5501
5502 id = DIF_INSTR_VAR(instr);
5503 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5504 id -= DIF_VAR_OTHER_UBASE;
5505
5506 key[nkeys].dttk_value = (uint64_t)id;
5507 key[nkeys++].dttk_size = 0;
5508
5509 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5510 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5511 key[nkeys++].dttk_size = 0;
5512 v = &vstate->dtvs_tlocals[id];
5513 } else {
5514 v = &vstate->dtvs_globals[id]->dtsv_var;
5515 }
5516
5517 dvar = dtrace_dynvar(dstate, nkeys, key,
5518 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5519 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5520 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5521
5522 if (dvar == NULL) {
5523 regs[rd] = 0;
5524 break;
5525 }
5526
5527 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5528 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5529 } else {
5530 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5531 }
5532
5533 break;
5534 }
5535
5536 case DIF_OP_STGAA:
5537 case DIF_OP_STTAA: {
5538 dtrace_dynvar_t *dvar;
5539 dtrace_key_t *key = tupregs;
5540 uint_t nkeys = ttop;
5541
5542 id = DIF_INSTR_VAR(instr);
5543 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5544 id -= DIF_VAR_OTHER_UBASE;
5545
5546 key[nkeys].dttk_value = (uint64_t)id;
5547 key[nkeys++].dttk_size = 0;
5548
5549 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5550 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5551 key[nkeys++].dttk_size = 0;
5552 v = &vstate->dtvs_tlocals[id];
5553 } else {
5554 v = &vstate->dtvs_globals[id]->dtsv_var;
5555 }
5556
5557 dvar = dtrace_dynvar(dstate, nkeys, key,
5558 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5559 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5560 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5561 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5562
5563 if (dvar == NULL)
5564 break;
5565
5566 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5567 if (!dtrace_vcanload(
5568 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5569 mstate, vstate))
5570 break;
5571
5572 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5573 dvar->dtdv_data, &v->dtdv_type);
5574 } else {
5575 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5576 }
5577
5578 break;
5579 }
5580
5581 case DIF_OP_ALLOCS: {
5582 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5583 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5584
5585 /*
5586 * Rounding up the user allocation size could have
5587 * overflowed large, bogus allocations (like -1ULL) to
5588 * 0.
5589 */
5590 if (size < regs[r1] ||
5591 !DTRACE_INSCRATCH(mstate, size)) {
5592 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5593 regs[rd] = NULL;
5594 break;
5595 }
5596
5597 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5598 mstate->dtms_scratch_ptr += size;
5599 regs[rd] = ptr;
5600 break;
5601 }
5602
5603 case DIF_OP_COPYS:
5604 if (!dtrace_canstore(regs[rd], regs[r2],
5605 mstate, vstate)) {
5606 *flags |= CPU_DTRACE_BADADDR;
5607 *illval = regs[rd];
5608 break;
5609 }
5610
5611 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5612 break;
5613
5614 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5615 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5616 break;
5617
5618 case DIF_OP_STB:
5619 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5620 *flags |= CPU_DTRACE_BADADDR;
5621 *illval = regs[rd];
5622 break;
5623 }
5624 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5625 break;
5626
5627 case DIF_OP_STH:
5628 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5629 *flags |= CPU_DTRACE_BADADDR;
5630 *illval = regs[rd];
5631 break;
5632 }
5633 if (regs[rd] & 1) {
5634 *flags |= CPU_DTRACE_BADALIGN;
5635 *illval = regs[rd];
5636 break;
5637 }
5638 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5639 break;
5640
5641 case DIF_OP_STW:
5642 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5643 *flags |= CPU_DTRACE_BADADDR;
5644 *illval = regs[rd];
5645 break;
5646 }
5647 if (regs[rd] & 3) {
5648 *flags |= CPU_DTRACE_BADALIGN;
5649 *illval = regs[rd];
5650 break;
5651 }
5652 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5653 break;
5654
5655 case DIF_OP_STX:
5656 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5657 *flags |= CPU_DTRACE_BADADDR;
5658 *illval = regs[rd];
5659 break;
5660 }
5661 if (regs[rd] & 7) {
5662 *flags |= CPU_DTRACE_BADALIGN;
5663 *illval = regs[rd];
5664 break;
5665 }
5666 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5667 break;
5668 }
5669 }
5670
5671 if (!(*flags & CPU_DTRACE_FAULT))
5672 return (rval);
5673
5674 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5675 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5676
5677 return (0);
5678 }
5679
5680 static void
5681 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5682 {
5683 dtrace_probe_t *probe = ecb->dte_probe;
5684 dtrace_provider_t *prov = probe->dtpr_provider;
5685 char c[DTRACE_FULLNAMELEN + 80], *str;
5686 char *msg = "dtrace: breakpoint action at probe ";
5687 char *ecbmsg = " (ecb ";
5688 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5689 uintptr_t val = (uintptr_t)ecb;
5690 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5691
5692 if (dtrace_destructive_disallow)
5693 return;
5694
5695 /*
5696 * It's impossible to be taking action on the NULL probe.
5697 */
5698 ASSERT(probe != NULL);
5699
5700 /*
5701 * This is a poor man's (destitute man's?) sprintf(): we want to
5702 * print the provider name, module name, function name and name of
5703 * the probe, along with the hex address of the ECB with the breakpoint
5704 * action -- all of which we must place in the character buffer by
5705 * hand.
5706 */
5707 while (*msg != '\0')
5708 c[i++] = *msg++;
5709
5710 for (str = prov->dtpv_name; *str != '\0'; str++)
5711 c[i++] = *str;
5712 c[i++] = ':';
5713
5714 for (str = probe->dtpr_mod; *str != '\0'; str++)
5715 c[i++] = *str;
5716 c[i++] = ':';
5717
5718 for (str = probe->dtpr_func; *str != '\0'; str++)
5719 c[i++] = *str;
5720 c[i++] = ':';
5721
5722 for (str = probe->dtpr_name; *str != '\0'; str++)
5723 c[i++] = *str;
5724
5725 while (*ecbmsg != '\0')
5726 c[i++] = *ecbmsg++;
5727
5728 while (shift >= 0) {
5729 mask = (uintptr_t)0xf << shift;
5730
5731 if (val >= ((uintptr_t)1 << shift))
5732 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5733 shift -= 4;
5734 }
5735
5736 c[i++] = ')';
5737 c[i] = '\0';
5738
5739 debug_enter(c);
5740 }
5741
5742 static void
5743 dtrace_action_panic(dtrace_ecb_t *ecb)
5744 {
5745 dtrace_probe_t *probe = ecb->dte_probe;
5746
5747 /*
5748 * It's impossible to be taking action on the NULL probe.
5749 */
5750 ASSERT(probe != NULL);
5751
5752 if (dtrace_destructive_disallow)
5753 return;
5754
5755 if (dtrace_panicked != NULL)
5756 return;
5757
5758 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5759 return;
5760
5761 /*
5762 * We won the right to panic. (We want to be sure that only one
5763 * thread calls panic() from dtrace_probe(), and that panic() is
5764 * called exactly once.)
5765 */
5766 dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5767 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5768 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5769 }
5770
5771 static void
5772 dtrace_action_raise(uint64_t sig)
5773 {
5774 if (dtrace_destructive_disallow)
5775 return;
5776
5777 if (sig >= NSIG) {
5778 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5779 return;
5780 }
5781
5782 /*
5783 * raise() has a queue depth of 1 -- we ignore all subsequent
5784 * invocations of the raise() action.
5785 */
5786 if (curthread->t_dtrace_sig == 0)
5787 curthread->t_dtrace_sig = (uint8_t)sig;
5788
5789 curthread->t_sig_check = 1;
5790 aston(curthread);
5791 }
5792
5793 static void
5794 dtrace_action_stop(void)
5795 {
5796 if (dtrace_destructive_disallow)
5797 return;
5798
5799 if (!curthread->t_dtrace_stop) {
5800 curthread->t_dtrace_stop = 1;
5801 curthread->t_sig_check = 1;
5802 aston(curthread);
5803 }
5804 }
5805
5806 static void
5807 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5808 {
5809 hrtime_t now;
5810 volatile uint16_t *flags;
5811 cpu_t *cpu = CPU;
5812
5813 if (dtrace_destructive_disallow)
5814 return;
5815
5816 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5817
5818 now = dtrace_gethrtime();
5819
5820 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5821 /*
5822 * We need to advance the mark to the current time.
5823 */
5824 cpu->cpu_dtrace_chillmark = now;
5825 cpu->cpu_dtrace_chilled = 0;
5826 }
5827
5828 /*
5829 * Now check to see if the requested chill time would take us over
5830 * the maximum amount of time allowed in the chill interval. (Or
5831 * worse, if the calculation itself induces overflow.)
5832 */
5833 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5834 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5835 *flags |= CPU_DTRACE_ILLOP;
5836 return;
5837 }
5838
5839 while (dtrace_gethrtime() - now < val)
5840 continue;
5841
5842 /*
5843 * Normally, we assure that the value of the variable "timestamp" does
5844 * not change within an ECB. The presence of chill() represents an
5845 * exception to this rule, however.
5846 */
5847 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5848 cpu->cpu_dtrace_chilled += val;
5849 }
5850
5851 static void
5852 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5853 uint64_t *buf, uint64_t arg)
5854 {
5855 int nframes = DTRACE_USTACK_NFRAMES(arg);
5856 int strsize = DTRACE_USTACK_STRSIZE(arg);
5857 uint64_t *pcs = &buf[1], *fps;
5858 char *str = (char *)&pcs[nframes];
5859 int size, offs = 0, i, j;
5860 uintptr_t old = mstate->dtms_scratch_ptr, saved;
5861 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5862 char *sym;
5863
5864 /*
5865 * Should be taking a faster path if string space has not been
5866 * allocated.
5867 */
5868 ASSERT(strsize != 0);
5869
5870 /*
5871 * We will first allocate some temporary space for the frame pointers.
5872 */
5873 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5874 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5875 (nframes * sizeof (uint64_t));
5876
5877 if (!DTRACE_INSCRATCH(mstate, size)) {
5878 /*
5879 * Not enough room for our frame pointers -- need to indicate
5880 * that we ran out of scratch space.
5881 */
5882 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5883 return;
5884 }
5885
5886 mstate->dtms_scratch_ptr += size;
5887 saved = mstate->dtms_scratch_ptr;
5888
5889 /*
5890 * Now get a stack with both program counters and frame pointers.
5891 */
5892 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5893 dtrace_getufpstack(buf, fps, nframes + 1);
5894 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5895
5896 /*
5897 * If that faulted, we're cooked.
5898 */
5899 if (*flags & CPU_DTRACE_FAULT)
5900 goto out;
5901
5902 /*
5903 * Now we want to walk up the stack, calling the USTACK helper. For
5904 * each iteration, we restore the scratch pointer.
5905 */
5906 for (i = 0; i < nframes; i++) {
5907 mstate->dtms_scratch_ptr = saved;
5908
5909 if (offs >= strsize)
5910 break;
5911
5912 sym = (char *)(uintptr_t)dtrace_helper(
5913 DTRACE_HELPER_ACTION_USTACK,
5914 mstate, state, pcs[i], fps[i]);
5915
5916 /*
5917 * If we faulted while running the helper, we're going to
5918 * clear the fault and null out the corresponding string.
5919 */
5920 if (*flags & CPU_DTRACE_FAULT) {
5921 *flags &= ~CPU_DTRACE_FAULT;
5922 str[offs++] = '\0';
5923 continue;
5924 }
5925
5926 if (sym == NULL) {
5927 str[offs++] = '\0';
5928 continue;
5929 }
5930
5931 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5932
5933 /*
5934 * Now copy in the string that the helper returned to us.
5935 */
5936 for (j = 0; offs + j < strsize; j++) {
5937 if ((str[offs + j] = sym[j]) == '\0')
5938 break;
5939 }
5940
5941 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5942
5943 offs += j + 1;
5944 }
5945
5946 if (offs >= strsize) {
5947 /*
5948 * If we didn't have room for all of the strings, we don't
5949 * abort processing -- this needn't be a fatal error -- but we
5950 * still want to increment a counter (dts_stkstroverflows) to
5951 * allow this condition to be warned about. (If this is from
5952 * a jstack() action, it is easily tuned via jstackstrsize.)
5953 */
5954 dtrace_error(&state->dts_stkstroverflows);
5955 }
5956
5957 while (offs < strsize)
5958 str[offs++] = '\0';
5959
5960 out:
5961 mstate->dtms_scratch_ptr = old;
5962 }
5963
5964 /*
5965 * If you're looking for the epicenter of DTrace, you just found it. This
5966 * is the function called by the provider to fire a probe -- from which all
5967 * subsequent probe-context DTrace activity emanates.
5968 */
5969 void
5970 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5971 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5972 {
5973 processorid_t cpuid;
5974 dtrace_icookie_t cookie;
5975 dtrace_probe_t *probe;
5976 dtrace_mstate_t mstate;
5977 dtrace_ecb_t *ecb;
5978 dtrace_action_t *act;
5979 intptr_t offs;
5980 size_t size;
5981 int vtime, onintr;
5982 volatile uint16_t *flags;
5983 hrtime_t now, end;
5984
5985 /*
5986 * Kick out immediately if this CPU is still being born (in which case
5987 * curthread will be set to -1) or the current thread can't allow
5988 * probes in its current context.
5989 */
5990 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
5991 return;
5992
5993 cookie = dtrace_interrupt_disable();
5994 probe = dtrace_probes[id - 1];
5995 cpuid = CPU->cpu_id;
5996 onintr = CPU_ON_INTR(CPU);
5997
5998 CPU->cpu_dtrace_probes++;
5999
6000 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6001 probe->dtpr_predcache == curthread->t_predcache) {
6002 /*
6003 * We have hit in the predicate cache; we know that
6004 * this predicate would evaluate to be false.
6005 */
6006 dtrace_interrupt_enable(cookie);
6007 return;
6008 }
6009
6010 if (panic_quiesce) {
6011 /*
6012 * We don't trace anything if we're panicking.
6013 */
6014 dtrace_interrupt_enable(cookie);
6015 return;
6016 }
6017
6018 now = dtrace_gethrtime();
6019 vtime = dtrace_vtime_references != 0;
6020
6021 if (vtime && curthread->t_dtrace_start)
6022 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6023
6024 mstate.dtms_difo = NULL;
6025 mstate.dtms_probe = probe;
6026 mstate.dtms_strtok = NULL;
6027 mstate.dtms_arg[0] = arg0;
6028 mstate.dtms_arg[1] = arg1;
6029 mstate.dtms_arg[2] = arg2;
6030 mstate.dtms_arg[3] = arg3;
6031 mstate.dtms_arg[4] = arg4;
6032
6033 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6034
6035 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6036 dtrace_predicate_t *pred = ecb->dte_predicate;
6037 dtrace_state_t *state = ecb->dte_state;
6038 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6039 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6040 dtrace_vstate_t *vstate = &state->dts_vstate;
6041 dtrace_provider_t *prov = probe->dtpr_provider;
6042 uint64_t tracememsize = 0;
6043 int committed = 0;
6044 caddr_t tomax;
6045
6046 /*
6047 * A little subtlety with the following (seemingly innocuous)
6048 * declaration of the automatic 'val': by looking at the
6049 * code, you might think that it could be declared in the
6050 * action processing loop, below. (That is, it's only used in
6051 * the action processing loop.) However, it must be declared
6052 * out of that scope because in the case of DIF expression
6053 * arguments to aggregating actions, one iteration of the
6054 * action loop will use the last iteration's value.
6055 */
6056 #ifdef lint
6057 uint64_t val = 0;
6058 #else
6059 uint64_t val;
6060 #endif
6061
6062 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6063 mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
6064 mstate.dtms_getf = NULL;
6065
6066 *flags &= ~CPU_DTRACE_ERROR;
6067
6068 if (prov == dtrace_provider) {
6069 /*
6070 * If dtrace itself is the provider of this probe,
6071 * we're only going to continue processing the ECB if
6072 * arg0 (the dtrace_state_t) is equal to the ECB's
6073 * creating state. (This prevents disjoint consumers
6074 * from seeing one another's metaprobes.)
6075 */
6076 if (arg0 != (uint64_t)(uintptr_t)state)
6077 continue;
6078 }
6079
6080 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6081 /*
6082 * We're not currently active. If our provider isn't
6083 * the dtrace pseudo provider, we're not interested.
6084 */
6085 if (prov != dtrace_provider)
6086 continue;
6087
6088 /*
6089 * Now we must further check if we are in the BEGIN
6090 * probe. If we are, we will only continue processing
6091 * if we're still in WARMUP -- if one BEGIN enabling
6092 * has invoked the exit() action, we don't want to
6093 * evaluate subsequent BEGIN enablings.
6094 */
6095 if (probe->dtpr_id == dtrace_probeid_begin &&
6096 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6097 ASSERT(state->dts_activity ==
6098 DTRACE_ACTIVITY_DRAINING);
6099 continue;
6100 }
6101 }
6102
6103 if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
6104 continue;
6105
6106 if (now - state->dts_alive > dtrace_deadman_timeout) {
6107 /*
6108 * We seem to be dead. Unless we (a) have kernel
6109 * destructive permissions (b) have explicitly enabled
6110 * destructive actions and (c) destructive actions have
6111 * not been disabled, we're going to transition into
6112 * the KILLED state, from which no further processing
6113 * on this state will be performed.
6114 */
6115 if (!dtrace_priv_kernel_destructive(state) ||
6116 !state->dts_cred.dcr_destructive ||
6117 dtrace_destructive_disallow) {
6118 void *activity = &state->dts_activity;
6119 dtrace_activity_t current;
6120
6121 do {
6122 current = state->dts_activity;
6123 } while (dtrace_cas32(activity, current,
6124 DTRACE_ACTIVITY_KILLED) != current);
6125
6126 continue;
6127 }
6128 }
6129
6130 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6131 ecb->dte_alignment, state, &mstate)) < 0)
6132 continue;
6133
6134 tomax = buf->dtb_tomax;
6135 ASSERT(tomax != NULL);
6136
6137 if (ecb->dte_size != 0) {
6138 dtrace_rechdr_t dtrh;
6139 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6140 mstate.dtms_timestamp = dtrace_gethrtime();
6141 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6142 }
6143 ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6144 dtrh.dtrh_epid = ecb->dte_epid;
6145 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6146 mstate.dtms_timestamp);
6147 *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6148 }
6149
6150 mstate.dtms_epid = ecb->dte_epid;
6151 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6152
6153 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6154 mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
6155
6156 if (pred != NULL) {
6157 dtrace_difo_t *dp = pred->dtp_difo;
6158 int rval;
6159
6160 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6161
6162 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6163 dtrace_cacheid_t cid = probe->dtpr_predcache;
6164
6165 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6166 /*
6167 * Update the predicate cache...
6168 */
6169 ASSERT(cid == pred->dtp_cacheid);
6170 curthread->t_predcache = cid;
6171 }
6172
6173 continue;
6174 }
6175 }
6176
6177 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6178 act != NULL; act = act->dta_next) {
6179 size_t valoffs;
6180 dtrace_difo_t *dp;
6181 dtrace_recdesc_t *rec = &act->dta_rec;
6182
6183 size = rec->dtrd_size;
6184 valoffs = offs + rec->dtrd_offset;
6185
6186 if (DTRACEACT_ISAGG(act->dta_kind)) {
6187 uint64_t v = 0xbad;
6188 dtrace_aggregation_t *agg;
6189
6190 agg = (dtrace_aggregation_t *)act;
6191
6192 if ((dp = act->dta_difo) != NULL)
6193 v = dtrace_dif_emulate(dp,
6194 &mstate, vstate, state);
6195
6196 if (*flags & CPU_DTRACE_ERROR)
6197 continue;
6198
6199 /*
6200 * Note that we always pass the expression
6201 * value from the previous iteration of the
6202 * action loop. This value will only be used
6203 * if there is an expression argument to the
6204 * aggregating action, denoted by the
6205 * dtag_hasarg field.
6206 */
6207 dtrace_aggregate(agg, buf,
6208 offs, aggbuf, v, val);
6209 continue;
6210 }
6211
6212 switch (act->dta_kind) {
6213 case DTRACEACT_STOP:
6214 if (dtrace_priv_proc_destructive(state,
6215 &mstate))
6216 dtrace_action_stop();
6217 continue;
6218
6219 case DTRACEACT_BREAKPOINT:
6220 if (dtrace_priv_kernel_destructive(state))
6221 dtrace_action_breakpoint(ecb);
6222 continue;
6223
6224 case DTRACEACT_PANIC:
6225 if (dtrace_priv_kernel_destructive(state))
6226 dtrace_action_panic(ecb);
6227 continue;
6228
6229 case DTRACEACT_STACK:
6230 if (!dtrace_priv_kernel(state))
6231 continue;
6232
6233 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6234 size / sizeof (pc_t), probe->dtpr_aframes,
6235 DTRACE_ANCHORED(probe) ? NULL :
6236 (uint32_t *)arg0);
6237
6238 continue;
6239
6240 case DTRACEACT_JSTACK:
6241 case DTRACEACT_USTACK:
6242 if (!dtrace_priv_proc(state, &mstate))
6243 continue;
6244
6245 /*
6246 * See comment in DIF_VAR_PID.
6247 */
6248 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6249 CPU_ON_INTR(CPU)) {
6250 int depth = DTRACE_USTACK_NFRAMES(
6251 rec->dtrd_arg) + 1;
6252
6253 dtrace_bzero((void *)(tomax + valoffs),
6254 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6255 + depth * sizeof (uint64_t));
6256
6257 continue;
6258 }
6259
6260 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6261 curproc->p_dtrace_helpers != NULL) {
6262 /*
6263 * This is the slow path -- we have
6264 * allocated string space, and we're
6265 * getting the stack of a process that
6266 * has helpers. Call into a separate
6267 * routine to perform this processing.
6268 */
6269 dtrace_action_ustack(&mstate, state,
6270 (uint64_t *)(tomax + valoffs),
6271 rec->dtrd_arg);
6272 continue;
6273 }
6274
6275 /*
6276 * Clear the string space, since there's no
6277 * helper to do it for us.
6278 */
6279 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
6280 int depth = DTRACE_USTACK_NFRAMES(
6281 rec->dtrd_arg);
6282 size_t strsize = DTRACE_USTACK_STRSIZE(
6283 rec->dtrd_arg);
6284 uint64_t *buf = (uint64_t *)(tomax +
6285 valoffs);
6286 void *strspace = &buf[depth + 1];
6287
6288 dtrace_bzero(strspace,
6289 MIN(depth, strsize));
6290 }
6291
6292 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6293 dtrace_getupcstack((uint64_t *)
6294 (tomax + valoffs),
6295 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6296 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6297 continue;
6298
6299 default:
6300 break;
6301 }
6302
6303 dp = act->dta_difo;
6304 ASSERT(dp != NULL);
6305
6306 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6307
6308 if (*flags & CPU_DTRACE_ERROR)
6309 continue;
6310
6311 switch (act->dta_kind) {
6312 case DTRACEACT_SPECULATE: {
6313 dtrace_rechdr_t *dtrh;
6314
6315 ASSERT(buf == &state->dts_buffer[cpuid]);
6316 buf = dtrace_speculation_buffer(state,
6317 cpuid, val);
6318
6319 if (buf == NULL) {
6320 *flags |= CPU_DTRACE_DROP;
6321 continue;
6322 }
6323
6324 offs = dtrace_buffer_reserve(buf,
6325 ecb->dte_needed, ecb->dte_alignment,
6326 state, NULL);
6327
6328 if (offs < 0) {
6329 *flags |= CPU_DTRACE_DROP;
6330 continue;
6331 }
6332
6333 tomax = buf->dtb_tomax;
6334 ASSERT(tomax != NULL);
6335
6336 if (ecb->dte_size == 0)
6337 continue;
6338
6339 ASSERT3U(ecb->dte_size, >=,
6340 sizeof (dtrace_rechdr_t));
6341 dtrh = ((void *)(tomax + offs));
6342 dtrh->dtrh_epid = ecb->dte_epid;
6343 /*
6344 * When the speculation is committed, all of
6345 * the records in the speculative buffer will
6346 * have their timestamps set to the commit
6347 * time. Until then, it is set to a sentinel
6348 * value, for debugability.
6349 */
6350 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6351 continue;
6352 }
6353
6354 case DTRACEACT_CHILL:
6355 if (dtrace_priv_kernel_destructive(state))
6356 dtrace_action_chill(&mstate, val);
6357 continue;
6358
6359 case DTRACEACT_RAISE:
6360 if (dtrace_priv_proc_destructive(state,
6361 &mstate))
6362 dtrace_action_raise(val);
6363 continue;
6364
6365 case DTRACEACT_COMMIT:
6366 ASSERT(!committed);
6367
6368 /*
6369 * We need to commit our buffer state.
6370 */
6371 if (ecb->dte_size)
6372 buf->dtb_offset = offs + ecb->dte_size;
6373 buf = &state->dts_buffer[cpuid];
6374 dtrace_speculation_commit(state, cpuid, val);
6375 committed = 1;
6376 continue;
6377
6378 case DTRACEACT_DISCARD:
6379 dtrace_speculation_discard(state, cpuid, val);
6380 continue;
6381
6382 case DTRACEACT_DIFEXPR:
6383 case DTRACEACT_LIBACT:
6384 case DTRACEACT_PRINTF:
6385 case DTRACEACT_PRINTA:
6386 case DTRACEACT_SYSTEM:
6387 case DTRACEACT_FREOPEN:
6388 case DTRACEACT_TRACEMEM:
6389 break;
6390
6391 case DTRACEACT_TRACEMEM_DYNSIZE:
6392 tracememsize = val;
6393 break;
6394
6395 case DTRACEACT_SYM:
6396 case DTRACEACT_MOD:
6397 if (!dtrace_priv_kernel(state))
6398 continue;
6399 break;
6400
6401 case DTRACEACT_USYM:
6402 case DTRACEACT_UMOD:
6403 case DTRACEACT_UADDR: {
6404 struct pid *pid = curthread->t_procp->p_pidp;
6405
6406 if (!dtrace_priv_proc(state, &mstate))
6407 continue;
6408
6409 DTRACE_STORE(uint64_t, tomax,
6410 valoffs, (uint64_t)pid->pid_id);
6411 DTRACE_STORE(uint64_t, tomax,
6412 valoffs + sizeof (uint64_t), val);
6413
6414 continue;
6415 }
6416
6417 case DTRACEACT_EXIT: {
6418 /*
6419 * For the exit action, we are going to attempt
6420 * to atomically set our activity to be
6421 * draining. If this fails (either because
6422 * another CPU has beat us to the exit action,
6423 * or because our current activity is something
6424 * other than ACTIVE or WARMUP), we will
6425 * continue. This assures that the exit action
6426 * can be successfully recorded at most once
6427 * when we're in the ACTIVE state. If we're
6428 * encountering the exit() action while in
6429 * COOLDOWN, however, we want to honor the new
6430 * status code. (We know that we're the only
6431 * thread in COOLDOWN, so there is no race.)
6432 */
6433 void *activity = &state->dts_activity;
6434 dtrace_activity_t current = state->dts_activity;
6435
6436 if (current == DTRACE_ACTIVITY_COOLDOWN)
6437 break;
6438
6439 if (current != DTRACE_ACTIVITY_WARMUP)
6440 current = DTRACE_ACTIVITY_ACTIVE;
6441
6442 if (dtrace_cas32(activity, current,
6443 DTRACE_ACTIVITY_DRAINING) != current) {
6444 *flags |= CPU_DTRACE_DROP;
6445 continue;
6446 }
6447
6448 break;
6449 }
6450
6451 default:
6452 ASSERT(0);
6453 }
6454
6455 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6456 uintptr_t end = valoffs + size;
6457
6458 if (tracememsize != 0 &&
6459 valoffs + tracememsize < end) {
6460 end = valoffs + tracememsize;
6461 tracememsize = 0;
6462 }
6463
6464 if (!dtrace_vcanload((void *)(uintptr_t)val,
6465 &dp->dtdo_rtype, &mstate, vstate))
6466 continue;
6467
6468 /*
6469 * If this is a string, we're going to only
6470 * load until we find the zero byte -- after
6471 * which we'll store zero bytes.
6472 */
6473 if (dp->dtdo_rtype.dtdt_kind ==
6474 DIF_TYPE_STRING) {
6475 char c = '\0' + 1;
6476 int intuple = act->dta_intuple;
6477 size_t s;
6478
6479 for (s = 0; s < size; s++) {
6480 if (c != '\0')
6481 c = dtrace_load8(val++);
6482
6483 DTRACE_STORE(uint8_t, tomax,
6484 valoffs++, c);
6485
6486 if (c == '\0' && intuple)
6487 break;
6488 }
6489
6490 continue;
6491 }
6492
6493 while (valoffs < end) {
6494 DTRACE_STORE(uint8_t, tomax, valoffs++,
6495 dtrace_load8(val++));
6496 }
6497
6498 continue;
6499 }
6500
6501 switch (size) {
6502 case 0:
6503 break;
6504
6505 case sizeof (uint8_t):
6506 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6507 break;
6508 case sizeof (uint16_t):
6509 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6510 break;
6511 case sizeof (uint32_t):
6512 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6513 break;
6514 case sizeof (uint64_t):
6515 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6516 break;
6517 default:
6518 /*
6519 * Any other size should have been returned by
6520 * reference, not by value.
6521 */
6522 ASSERT(0);
6523 break;
6524 }
6525 }
6526
6527 if (*flags & CPU_DTRACE_DROP)
6528 continue;
6529
6530 if (*flags & CPU_DTRACE_FAULT) {
6531 int ndx;
6532 dtrace_action_t *err;
6533
6534 buf->dtb_errors++;
6535
6536 if (probe->dtpr_id == dtrace_probeid_error) {
6537 /*
6538 * There's nothing we can do -- we had an
6539 * error on the error probe. We bump an
6540 * error counter to at least indicate that
6541 * this condition happened.
6542 */
6543 dtrace_error(&state->dts_dblerrors);
6544 continue;
6545 }
6546
6547 if (vtime) {
6548 /*
6549 * Before recursing on dtrace_probe(), we
6550 * need to explicitly clear out our start
6551 * time to prevent it from being accumulated
6552 * into t_dtrace_vtime.
6553 */
6554 curthread->t_dtrace_start = 0;
6555 }
6556
6557 /*
6558 * Iterate over the actions to figure out which action
6559 * we were processing when we experienced the error.
6560 * Note that act points _past_ the faulting action; if
6561 * act is ecb->dte_action, the fault was in the
6562 * predicate, if it's ecb->dte_action->dta_next it's
6563 * in action #1, and so on.
6564 */
6565 for (err = ecb->dte_action, ndx = 0;
6566 err != act; err = err->dta_next, ndx++)
6567 continue;
6568
6569 dtrace_probe_error(state, ecb->dte_epid, ndx,
6570 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6571 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6572 cpu_core[cpuid].cpuc_dtrace_illval);
6573
6574 continue;
6575 }
6576
6577 if (!committed)
6578 buf->dtb_offset = offs + ecb->dte_size;
6579 }
6580
6581 end = dtrace_gethrtime();
6582 if (vtime)
6583 curthread->t_dtrace_start = end;
6584
6585 CPU->cpu_dtrace_nsec += end - now;
6586
6587 dtrace_interrupt_enable(cookie);
6588 }
6589
6590 /*
6591 * DTrace Probe Hashing Functions
6592 *
6593 * The functions in this section (and indeed, the functions in remaining
6594 * sections) are not _called_ from probe context. (Any exceptions to this are
6595 * marked with a "Note:".) Rather, they are called from elsewhere in the
6596 * DTrace framework to look-up probes in, add probes to and remove probes from
6597 * the DTrace probe hashes. (Each probe is hashed by each element of the
6598 * probe tuple -- allowing for fast lookups, regardless of what was
6599 * specified.)
6600 */
6601 static uint_t
6602 dtrace_hash_str(char *p)
6603 {
6604 unsigned int g;
6605 uint_t hval = 0;
6606
6607 while (*p) {
6608 hval = (hval << 4) + *p++;
6609 if ((g = (hval & 0xf0000000)) != 0)
6610 hval ^= g >> 24;
6611 hval &= ~g;
6612 }
6613 return (hval);
6614 }
6615
6616 static dtrace_hash_t *
6617 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6618 {
6619 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6620
6621 hash->dth_stroffs = stroffs;
6622 hash->dth_nextoffs = nextoffs;
6623 hash->dth_prevoffs = prevoffs;
6624
6625 hash->dth_size = 1;
6626 hash->dth_mask = hash->dth_size - 1;
6627
6628 hash->dth_tab = kmem_zalloc(hash->dth_size *
6629 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6630
6631 return (hash);
6632 }
6633
6634 static void
6635 dtrace_hash_destroy(dtrace_hash_t *hash)
6636 {
6637 #ifdef DEBUG
6638 int i;
6639
6640 for (i = 0; i < hash->dth_size; i++)
6641 ASSERT(hash->dth_tab[i] == NULL);
6642 #endif
6643
6644 kmem_free(hash->dth_tab,
6645 hash->dth_size * sizeof (dtrace_hashbucket_t *));
6646 kmem_free(hash, sizeof (dtrace_hash_t));
6647 }
6648
6649 static void
6650 dtrace_hash_resize(dtrace_hash_t *hash)
6651 {
6652 int size = hash->dth_size, i, ndx;
6653 int new_size = hash->dth_size << 1;
6654 int new_mask = new_size - 1;
6655 dtrace_hashbucket_t **new_tab, *bucket, *next;
6656
6657 ASSERT((new_size & new_mask) == 0);
6658
6659 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6660
6661 for (i = 0; i < size; i++) {
6662 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6663 dtrace_probe_t *probe = bucket->dthb_chain;
6664
6665 ASSERT(probe != NULL);
6666 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6667
6668 next = bucket->dthb_next;
6669 bucket->dthb_next = new_tab[ndx];
6670 new_tab[ndx] = bucket;
6671 }
6672 }
6673
6674 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6675 hash->dth_tab = new_tab;
6676 hash->dth_size = new_size;
6677 hash->dth_mask = new_mask;
6678 }
6679
6680 static void
6681 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6682 {
6683 int hashval = DTRACE_HASHSTR(hash, new);
6684 int ndx = hashval & hash->dth_mask;
6685 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6686 dtrace_probe_t **nextp, **prevp;
6687
6688 for (; bucket != NULL; bucket = bucket->dthb_next) {
6689 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6690 goto add;
6691 }
6692
6693 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6694 dtrace_hash_resize(hash);
6695 dtrace_hash_add(hash, new);
6696 return;
6697 }
6698
6699 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6700 bucket->dthb_next = hash->dth_tab[ndx];
6701 hash->dth_tab[ndx] = bucket;
6702 hash->dth_nbuckets++;
6703
6704 add:
6705 nextp = DTRACE_HASHNEXT(hash, new);
6706 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6707 *nextp = bucket->dthb_chain;
6708
6709 if (bucket->dthb_chain != NULL) {
6710 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6711 ASSERT(*prevp == NULL);
6712 *prevp = new;
6713 }
6714
6715 bucket->dthb_chain = new;
6716 bucket->dthb_len++;
6717 }
6718
6719 static dtrace_probe_t *
6720 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6721 {
6722 int hashval = DTRACE_HASHSTR(hash, template);
6723 int ndx = hashval & hash->dth_mask;
6724 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6725
6726 for (; bucket != NULL; bucket = bucket->dthb_next) {
6727 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6728 return (bucket->dthb_chain);
6729 }
6730
6731 return (NULL);
6732 }
6733
6734 static int
6735 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6736 {
6737 int hashval = DTRACE_HASHSTR(hash, template);
6738 int ndx = hashval & hash->dth_mask;
6739 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6740
6741 for (; bucket != NULL; bucket = bucket->dthb_next) {
6742 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6743 return (bucket->dthb_len);
6744 }
6745
6746 return (NULL);
6747 }
6748
6749 static void
6750 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6751 {
6752 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6753 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6754
6755 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6756 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6757
6758 /*
6759 * Find the bucket that we're removing this probe from.
6760 */
6761 for (; bucket != NULL; bucket = bucket->dthb_next) {
6762 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6763 break;
6764 }
6765
6766 ASSERT(bucket != NULL);
6767
6768 if (*prevp == NULL) {
6769 if (*nextp == NULL) {
6770 /*
6771 * The removed probe was the only probe on this
6772 * bucket; we need to remove the bucket.
6773 */
6774 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6775
6776 ASSERT(bucket->dthb_chain == probe);
6777 ASSERT(b != NULL);
6778
6779 if (b == bucket) {
6780 hash->dth_tab[ndx] = bucket->dthb_next;
6781 } else {
6782 while (b->dthb_next != bucket)
6783 b = b->dthb_next;
6784 b->dthb_next = bucket->dthb_next;
6785 }
6786
6787 ASSERT(hash->dth_nbuckets > 0);
6788 hash->dth_nbuckets--;
6789 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6790 return;
6791 }
6792
6793 bucket->dthb_chain = *nextp;
6794 } else {
6795 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6796 }
6797
6798 if (*nextp != NULL)
6799 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6800 }
6801
6802 /*
6803 * DTrace Utility Functions
6804 *
6805 * These are random utility functions that are _not_ called from probe context.
6806 */
6807 static int
6808 dtrace_badattr(const dtrace_attribute_t *a)
6809 {
6810 return (a->dtat_name > DTRACE_STABILITY_MAX ||
6811 a->dtat_data > DTRACE_STABILITY_MAX ||
6812 a->dtat_class > DTRACE_CLASS_MAX);
6813 }
6814
6815 /*
6816 * Return a duplicate copy of a string. If the specified string is NULL,
6817 * this function returns a zero-length string.
6818 */
6819 static char *
6820 dtrace_strdup(const char *str)
6821 {
6822 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6823
6824 if (str != NULL)
6825 (void) strcpy(new, str);
6826
6827 return (new);
6828 }
6829
6830 #define DTRACE_ISALPHA(c) \
6831 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6832
6833 static int
6834 dtrace_badname(const char *s)
6835 {
6836 char c;
6837
6838 if (s == NULL || (c = *s++) == '\0')
6839 return (0);
6840
6841 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6842 return (1);
6843
6844 while ((c = *s++) != '\0') {
6845 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6846 c != '-' && c != '_' && c != '.' && c != '`')
6847 return (1);
6848 }
6849
6850 return (0);
6851 }
6852
6853 static void
6854 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6855 {
6856 uint32_t priv;
6857
6858 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6859 /*
6860 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6861 */
6862 priv = DTRACE_PRIV_ALL;
6863 } else {
6864 *uidp = crgetuid(cr);
6865 *zoneidp = crgetzoneid(cr);
6866
6867 priv = 0;
6868 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6869 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6870 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6871 priv |= DTRACE_PRIV_USER;
6872 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6873 priv |= DTRACE_PRIV_PROC;
6874 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6875 priv |= DTRACE_PRIV_OWNER;
6876 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6877 priv |= DTRACE_PRIV_ZONEOWNER;
6878 }
6879
6880 *privp = priv;
6881 }
6882
6883 #ifdef DTRACE_ERRDEBUG
6884 static void
6885 dtrace_errdebug(const char *str)
6886 {
6887 int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6888 int occupied = 0;
6889
6890 mutex_enter(&dtrace_errlock);
6891 dtrace_errlast = str;
6892 dtrace_errthread = curthread;
6893
6894 while (occupied++ < DTRACE_ERRHASHSZ) {
6895 if (dtrace_errhash[hval].dter_msg == str) {
6896 dtrace_errhash[hval].dter_count++;
6897 goto out;
6898 }
6899
6900 if (dtrace_errhash[hval].dter_msg != NULL) {
6901 hval = (hval + 1) % DTRACE_ERRHASHSZ;
6902 continue;
6903 }
6904
6905 dtrace_errhash[hval].dter_msg = str;
6906 dtrace_errhash[hval].dter_count = 1;
6907 goto out;
6908 }
6909
6910 panic("dtrace: undersized error hash");
6911 out:
6912 mutex_exit(&dtrace_errlock);
6913 }
6914 #endif
6915
6916 /*
6917 * DTrace Matching Functions
6918 *
6919 * These functions are used to match groups of probes, given some elements of
6920 * a probe tuple, or some globbed expressions for elements of a probe tuple.
6921 */
6922 static int
6923 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6924 zoneid_t zoneid)
6925 {
6926 if (priv != DTRACE_PRIV_ALL) {
6927 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6928 uint32_t match = priv & ppriv;
6929
6930 /*
6931 * No PRIV_DTRACE_* privileges...
6932 */
6933 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6934 DTRACE_PRIV_KERNEL)) == 0)
6935 return (0);
6936
6937 /*
6938 * No matching bits, but there were bits to match...
6939 */
6940 if (match == 0 && ppriv != 0)
6941 return (0);
6942
6943 /*
6944 * Need to have permissions to the process, but don't...
6945 */
6946 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6947 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6948 return (0);
6949 }
6950
6951 /*
6952 * Need to be in the same zone unless we possess the
6953 * privilege to examine all zones.
6954 */
6955 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6956 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6957 return (0);
6958 }
6959 }
6960
6961 return (1);
6962 }
6963
6964 /*
6965 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6966 * consists of input pattern strings and an ops-vector to evaluate them.
6967 * This function returns >0 for match, 0 for no match, and <0 for error.
6968 */
6969 static int
6970 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6971 uint32_t priv, uid_t uid, zoneid_t zoneid)
6972 {
6973 dtrace_provider_t *pvp = prp->dtpr_provider;
6974 int rv;
6975
6976 if (pvp->dtpv_defunct)
6977 return (0);
6978
6979 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6980 return (rv);
6981
6982 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6983 return (rv);
6984
6985 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6986 return (rv);
6987
6988 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6989 return (rv);
6990
6991 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6992 return (0);
6993
6994 return (rv);
6995 }
6996
6997 /*
6998 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6999 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7000 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7001 * In addition, all of the recursion cases except for '*' matching have been
7002 * unwound. For '*', we still implement recursive evaluation, but a depth
7003 * counter is maintained and matching is aborted if we recurse too deep.
7004 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7005 */
7006 static int
7007 dtrace_match_glob(const char *s, const char *p, int depth)
7008 {
7009 const char *olds;
7010 char s1, c;
7011 int gs;
7012
7013 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7014 return (-1);
7015
7016 if (s == NULL)
7017 s = ""; /* treat NULL as empty string */
7018
7019 top:
7020 olds = s;
7021 s1 = *s++;
7022
7023 if (p == NULL)
7024 return (0);
7025
7026 if ((c = *p++) == '\0')
7027 return (s1 == '\0');
7028
7029 switch (c) {
7030 case '[': {
7031 int ok = 0, notflag = 0;
7032 char lc = '\0';
7033
7034 if (s1 == '\0')
7035 return (0);
7036
7037 if (*p == '!') {
7038 notflag = 1;
7039 p++;
7040 }
7041
7042 if ((c = *p++) == '\0')
7043 return (0);
7044
7045 do {
7046 if (c == '-' && lc != '\0' && *p != ']') {
7047 if ((c = *p++) == '\0')
7048 return (0);
7049 if (c == '\\' && (c = *p++) == '\0')
7050 return (0);
7051
7052 if (notflag) {
7053 if (s1 < lc || s1 > c)
7054 ok++;
7055 else
7056 return (0);
7057 } else if (lc <= s1 && s1 <= c)
7058 ok++;
7059
7060 } else if (c == '\\' && (c = *p++) == '\0')
7061 return (0);
7062
7063 lc = c; /* save left-hand 'c' for next iteration */
7064
7065 if (notflag) {
7066 if (s1 != c)
7067 ok++;
7068 else
7069 return (0);
7070 } else if (s1 == c)
7071 ok++;
7072
7073 if ((c = *p++) == '\0')
7074 return (0);
7075
7076 } while (c != ']');
7077
7078 if (ok)
7079 goto top;
7080
7081 return (0);
7082 }
7083
7084 case '\\':
7085 if ((c = *p++) == '\0')
7086 return (0);
7087 /*FALLTHRU*/
7088
7089 default:
7090 if (c != s1)
7091 return (0);
7092 /*FALLTHRU*/
7093
7094 case '?':
7095 if (s1 != '\0')
7096 goto top;
7097 return (0);
7098
7099 case '*':
7100 while (*p == '*')
7101 p++; /* consecutive *'s are identical to a single one */
7102
7103 if (*p == '\0')
7104 return (1);
7105
7106 for (s = olds; *s != '\0'; s++) {
7107 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7108 return (gs);
7109 }
7110
7111 return (0);
7112 }
7113 }
7114
7115 /*ARGSUSED*/
7116 static int
7117 dtrace_match_string(const char *s, const char *p, int depth)
7118 {
7119 return (s != NULL && strcmp(s, p) == 0);
7120 }
7121
7122 /*ARGSUSED*/
7123 static int
7124 dtrace_match_nul(const char *s, const char *p, int depth)
7125 {
7126 return (1); /* always match the empty pattern */
7127 }
7128
7129 /*ARGSUSED*/
7130 static int
7131 dtrace_match_nonzero(const char *s, const char *p, int depth)
7132 {
7133 return (s != NULL && s[0] != '\0');
7134 }
7135
7136 static int
7137 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7138 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7139 {
7140 dtrace_probe_t template, *probe;
7141 dtrace_hash_t *hash = NULL;
7142 int len, rc, best = INT_MAX, nmatched = 0;
7143 dtrace_id_t i;
7144
7145 ASSERT(MUTEX_HELD(&dtrace_lock));
7146
7147 /*
7148 * If the probe ID is specified in the key, just lookup by ID and
7149 * invoke the match callback once if a matching probe is found.
7150 */
7151 if (pkp->dtpk_id != DTRACE_IDNONE) {
7152 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7153 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7154 if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7155 return (DTRACE_MATCH_FAIL);
7156 nmatched++;
7157 }
7158 return (nmatched);
7159 }
7160
7161 template.dtpr_mod = (char *)pkp->dtpk_mod;
7162 template.dtpr_func = (char *)pkp->dtpk_func;
7163 template.dtpr_name = (char *)pkp->dtpk_name;
7164
7165 /*
7166 * We want to find the most distinct of the module name, function
7167 * name, and name. So for each one that is not a glob pattern or
7168 * empty string, we perform a lookup in the corresponding hash and
7169 * use the hash table with the fewest collisions to do our search.
7170 */
7171 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7172 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7173 best = len;
7174 hash = dtrace_bymod;
7175 }
7176
7177 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7178 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7179 best = len;
7180 hash = dtrace_byfunc;
7181 }
7182
7183 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7184 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7185 best = len;
7186 hash = dtrace_byname;
7187 }
7188
7189 /*
7190 * If we did not select a hash table, iterate over every probe and
7191 * invoke our callback for each one that matches our input probe key.
7192 */
7193 if (hash == NULL) {
7194 for (i = 0; i < dtrace_nprobes; i++) {
7195 if ((probe = dtrace_probes[i]) == NULL ||
7196 dtrace_match_probe(probe, pkp, priv, uid,
7197 zoneid) <= 0)
7198 continue;
7199
7200 nmatched++;
7201
7202 if ((rc = (*matched)(probe, arg)) !=
7203 DTRACE_MATCH_NEXT) {
7204 if (rc == DTRACE_MATCH_FAIL)
7205 return (DTRACE_MATCH_FAIL);
7206 break;
7207 }
7208 }
7209
7210 return (nmatched);
7211 }
7212
7213 /*
7214 * If we selected a hash table, iterate over each probe of the same key
7215 * name and invoke the callback for every probe that matches the other
7216 * attributes of our input probe key.
7217 */
7218 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7219 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7220
7221 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7222 continue;
7223
7224 nmatched++;
7225
7226 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7227 if (rc == DTRACE_MATCH_FAIL)
7228 return (DTRACE_MATCH_FAIL);
7229 break;
7230 }
7231 }
7232
7233 return (nmatched);
7234 }
7235
7236 /*
7237 * Return the function pointer dtrace_probecmp() should use to compare the
7238 * specified pattern with a string. For NULL or empty patterns, we select
7239 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7240 * For non-empty non-glob strings, we use dtrace_match_string().
7241 */
7242 static dtrace_probekey_f *
7243 dtrace_probekey_func(const char *p)
7244 {
7245 char c;
7246
7247 if (p == NULL || *p == '\0')
7248 return (&dtrace_match_nul);
7249
7250 while ((c = *p++) != '\0') {
7251 if (c == '[' || c == '?' || c == '*' || c == '\\')
7252 return (&dtrace_match_glob);
7253 }
7254
7255 return (&dtrace_match_string);
7256 }
7257
7258 /*
7259 * Build a probe comparison key for use with dtrace_match_probe() from the
7260 * given probe description. By convention, a null key only matches anchored
7261 * probes: if each field is the empty string, reset dtpk_fmatch to
7262 * dtrace_match_nonzero().
7263 */
7264 static void
7265 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7266 {
7267 pkp->dtpk_prov = pdp->dtpd_provider;
7268 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7269
7270 pkp->dtpk_mod = pdp->dtpd_mod;
7271 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7272
7273 pkp->dtpk_func = pdp->dtpd_func;
7274 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7275
7276 pkp->dtpk_name = pdp->dtpd_name;
7277 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7278
7279 pkp->dtpk_id = pdp->dtpd_id;
7280
7281 if (pkp->dtpk_id == DTRACE_IDNONE &&
7282 pkp->dtpk_pmatch == &dtrace_match_nul &&
7283 pkp->dtpk_mmatch == &dtrace_match_nul &&
7284 pkp->dtpk_fmatch == &dtrace_match_nul &&
7285 pkp->dtpk_nmatch == &dtrace_match_nul)
7286 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7287 }
7288
7289 /*
7290 * DTrace Provider-to-Framework API Functions
7291 *
7292 * These functions implement much of the Provider-to-Framework API, as
7293 * described in <sys/dtrace.h>. The parts of the API not in this section are
7294 * the functions in the API for probe management (found below), and
7295 * dtrace_probe() itself (found above).
7296 */
7297
7298 /*
7299 * Register the calling provider with the DTrace framework. This should
7300 * generally be called by DTrace providers in their attach(9E) entry point.
7301 */
7302 int
7303 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7304 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7305 {
7306 dtrace_provider_t *provider;
7307
7308 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7309 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7310 "arguments", name ? name : "<NULL>");
7311 return (EINVAL);
7312 }
7313
7314 if (name[0] == '\0' || dtrace_badname(name)) {
7315 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7316 "provider name", name);
7317 return (EINVAL);
7318 }
7319
7320 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7321 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7322 pops->dtps_destroy == NULL ||
7323 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7324 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7325 "provider ops", name);
7326 return (EINVAL);
7327 }
7328
7329 if (dtrace_badattr(&pap->dtpa_provider) ||
7330 dtrace_badattr(&pap->dtpa_mod) ||
7331 dtrace_badattr(&pap->dtpa_func) ||
7332 dtrace_badattr(&pap->dtpa_name) ||
7333 dtrace_badattr(&pap->dtpa_args)) {
7334 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7335 "provider attributes", name);
7336 return (EINVAL);
7337 }
7338
7339 if (priv & ~DTRACE_PRIV_ALL) {
7340 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7341 "privilege attributes", name);
7342 return (EINVAL);
7343 }
7344
7345 if ((priv & DTRACE_PRIV_KERNEL) &&
7346 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7347 pops->dtps_mode == NULL) {
7348 cmn_err(CE_WARN, "failed to register provider '%s': need "
7349 "dtps_mode() op for given privilege attributes", name);
7350 return (EINVAL);
7351 }
7352
7353 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7354 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7355 (void) strcpy(provider->dtpv_name, name);
7356
7357 provider->dtpv_attr = *pap;
7358 provider->dtpv_priv.dtpp_flags = priv;
7359 if (cr != NULL) {
7360 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7361 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7362 }
7363 provider->dtpv_pops = *pops;
7364
7365 if (pops->dtps_provide == NULL) {
7366 ASSERT(pops->dtps_provide_module != NULL);
7367 provider->dtpv_pops.dtps_provide =
7368 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7369 }
7370
7371 if (pops->dtps_provide_module == NULL) {
7372 ASSERT(pops->dtps_provide != NULL);
7373 provider->dtpv_pops.dtps_provide_module =
7374 (void (*)(void *, struct modctl *))dtrace_nullop;
7375 }
7376
7377 if (pops->dtps_suspend == NULL) {
7378 ASSERT(pops->dtps_resume == NULL);
7379 provider->dtpv_pops.dtps_suspend =
7380 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7381 provider->dtpv_pops.dtps_resume =
7382 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7383 }
7384
7385 provider->dtpv_arg = arg;
7386 *idp = (dtrace_provider_id_t)provider;
7387
7388 if (pops == &dtrace_provider_ops) {
7389 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7390 ASSERT(MUTEX_HELD(&dtrace_lock));
7391 ASSERT(dtrace_anon.dta_enabling == NULL);
7392
7393 /*
7394 * We make sure that the DTrace provider is at the head of
7395 * the provider chain.
7396 */
7397 provider->dtpv_next = dtrace_provider;
7398 dtrace_provider = provider;
7399 return (0);
7400 }
7401
7402 mutex_enter(&dtrace_provider_lock);
7403 mutex_enter(&dtrace_lock);
7404
7405 /*
7406 * If there is at least one provider registered, we'll add this
7407 * provider after the first provider.
7408 */
7409 if (dtrace_provider != NULL) {
7410 provider->dtpv_next = dtrace_provider->dtpv_next;
7411 dtrace_provider->dtpv_next = provider;
7412 } else {
7413 dtrace_provider = provider;
7414 }
7415
7416 if (dtrace_retained != NULL) {
7417 dtrace_enabling_provide(provider);
7418
7419 /*
7420 * Now we need to call dtrace_enabling_matchall() -- which
7421 * will acquire cpu_lock and dtrace_lock. We therefore need
7422 * to drop all of our locks before calling into it...
7423 */
7424 mutex_exit(&dtrace_lock);
7425 mutex_exit(&dtrace_provider_lock);
7426 dtrace_enabling_matchall();
7427
7428 return (0);
7429 }
7430
7431 mutex_exit(&dtrace_lock);
7432 mutex_exit(&dtrace_provider_lock);
7433
7434 return (0);
7435 }
7436
7437 /*
7438 * Unregister the specified provider from the DTrace framework. This should
7439 * generally be called by DTrace providers in their detach(9E) entry point.
7440 */
7441 int
7442 dtrace_unregister(dtrace_provider_id_t id)
7443 {
7444 dtrace_provider_t *old = (dtrace_provider_t *)id;
7445 dtrace_provider_t *prev = NULL;
7446 int i, self = 0, noreap = 0;
7447 dtrace_probe_t *probe, *first = NULL;
7448
7449 if (old->dtpv_pops.dtps_enable ==
7450 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7451 /*
7452 * If DTrace itself is the provider, we're called with locks
7453 * already held.
7454 */
7455 ASSERT(old == dtrace_provider);
7456 ASSERT(dtrace_devi != NULL);
7457 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7458 ASSERT(MUTEX_HELD(&dtrace_lock));
7459 self = 1;
7460
7461 if (dtrace_provider->dtpv_next != NULL) {
7462 /*
7463 * There's another provider here; return failure.
7464 */
7465 return (EBUSY);
7466 }
7467 } else {
7468 mutex_enter(&dtrace_provider_lock);
7469 mutex_enter(&mod_lock);
7470 mutex_enter(&dtrace_lock);
7471 }
7472
7473 /*
7474 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7475 * probes, we refuse to let providers slither away, unless this
7476 * provider has already been explicitly invalidated.
7477 */
7478 if (!old->dtpv_defunct &&
7479 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7480 dtrace_anon.dta_state->dts_necbs > 0))) {
7481 if (!self) {
7482 mutex_exit(&dtrace_lock);
7483 mutex_exit(&mod_lock);
7484 mutex_exit(&dtrace_provider_lock);
7485 }
7486 return (EBUSY);
7487 }
7488
7489 /*
7490 * Attempt to destroy the probes associated with this provider.
7491 */
7492 for (i = 0; i < dtrace_nprobes; i++) {
7493 if ((probe = dtrace_probes[i]) == NULL)
7494 continue;
7495
7496 if (probe->dtpr_provider != old)
7497 continue;
7498
7499 if (probe->dtpr_ecb == NULL)
7500 continue;
7501
7502 /*
7503 * If we are trying to unregister a defunct provider, and the
7504 * provider was made defunct within the interval dictated by
7505 * dtrace_unregister_defunct_reap, we'll (asynchronously)
7506 * attempt to reap our enablings. To denote that the provider
7507 * should reattempt to unregister itself at some point in the
7508 * future, we will return a differentiable error code (EAGAIN
7509 * instead of EBUSY) in this case.
7510 */
7511 if (dtrace_gethrtime() - old->dtpv_defunct >
7512 dtrace_unregister_defunct_reap)
7513 noreap = 1;
7514
7515 if (!self) {
7516 mutex_exit(&dtrace_lock);
7517 mutex_exit(&mod_lock);
7518 mutex_exit(&dtrace_provider_lock);
7519 }
7520
7521 if (noreap)
7522 return (EBUSY);
7523
7524 (void) taskq_dispatch(dtrace_taskq,
7525 (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
7526
7527 return (EAGAIN);
7528 }
7529
7530 /*
7531 * All of the probes for this provider are disabled; we can safely
7532 * remove all of them from their hash chains and from the probe array.
7533 */
7534 for (i = 0; i < dtrace_nprobes; i++) {
7535 if ((probe = dtrace_probes[i]) == NULL)
7536 continue;
7537
7538 if (probe->dtpr_provider != old)
7539 continue;
7540
7541 dtrace_probes[i] = NULL;
7542
7543 dtrace_hash_remove(dtrace_bymod, probe);
7544 dtrace_hash_remove(dtrace_byfunc, probe);
7545 dtrace_hash_remove(dtrace_byname, probe);
7546
7547 if (first == NULL) {
7548 first = probe;
7549 probe->dtpr_nextmod = NULL;
7550 } else {
7551 probe->dtpr_nextmod = first;
7552 first = probe;
7553 }
7554 }
7555
7556 /*
7557 * The provider's probes have been removed from the hash chains and
7558 * from the probe array. Now issue a dtrace_sync() to be sure that
7559 * everyone has cleared out from any probe array processing.
7560 */
7561 dtrace_sync();
7562
7563 for (probe = first; probe != NULL; probe = first) {
7564 first = probe->dtpr_nextmod;
7565
7566 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7567 probe->dtpr_arg);
7568 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7569 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7570 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7571 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7572 kmem_free(probe, sizeof (dtrace_probe_t));
7573 }
7574
7575 if ((prev = dtrace_provider) == old) {
7576 ASSERT(self || dtrace_devi == NULL);
7577 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7578 dtrace_provider = old->dtpv_next;
7579 } else {
7580 while (prev != NULL && prev->dtpv_next != old)
7581 prev = prev->dtpv_next;
7582
7583 if (prev == NULL) {
7584 panic("attempt to unregister non-existent "
7585 "dtrace provider %p\n", (void *)id);
7586 }
7587
7588 prev->dtpv_next = old->dtpv_next;
7589 }
7590
7591 if (!self) {
7592 mutex_exit(&dtrace_lock);
7593 mutex_exit(&mod_lock);
7594 mutex_exit(&dtrace_provider_lock);
7595 }
7596
7597 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7598 kmem_free(old, sizeof (dtrace_provider_t));
7599
7600 return (0);
7601 }
7602
7603 /*
7604 * Invalidate the specified provider. All subsequent probe lookups for the
7605 * specified provider will fail, but its probes will not be removed.
7606 */
7607 void
7608 dtrace_invalidate(dtrace_provider_id_t id)
7609 {
7610 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7611
7612 ASSERT(pvp->dtpv_pops.dtps_enable !=
7613 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7614
7615 mutex_enter(&dtrace_provider_lock);
7616 mutex_enter(&dtrace_lock);
7617
7618 pvp->dtpv_defunct = dtrace_gethrtime();
7619
7620 mutex_exit(&dtrace_lock);
7621 mutex_exit(&dtrace_provider_lock);
7622 }
7623
7624 /*
7625 * Indicate whether or not DTrace has attached.
7626 */
7627 int
7628 dtrace_attached(void)
7629 {
7630 /*
7631 * dtrace_provider will be non-NULL iff the DTrace driver has
7632 * attached. (It's non-NULL because DTrace is always itself a
7633 * provider.)
7634 */
7635 return (dtrace_provider != NULL);
7636 }
7637
7638 /*
7639 * Remove all the unenabled probes for the given provider. This function is
7640 * not unlike dtrace_unregister(), except that it doesn't remove the provider
7641 * -- just as many of its associated probes as it can.
7642 */
7643 int
7644 dtrace_condense(dtrace_provider_id_t id)
7645 {
7646 dtrace_provider_t *prov = (dtrace_provider_t *)id;
7647 int i;
7648 dtrace_probe_t *probe;
7649
7650 /*
7651 * Make sure this isn't the dtrace provider itself.
7652 */
7653 ASSERT(prov->dtpv_pops.dtps_enable !=
7654 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7655
7656 mutex_enter(&dtrace_provider_lock);
7657 mutex_enter(&dtrace_lock);
7658
7659 /*
7660 * Attempt to destroy the probes associated with this provider.
7661 */
7662 for (i = 0; i < dtrace_nprobes; i++) {
7663 if ((probe = dtrace_probes[i]) == NULL)
7664 continue;
7665
7666 if (probe->dtpr_provider != prov)
7667 continue;
7668
7669 if (probe->dtpr_ecb != NULL)
7670 continue;
7671
7672 dtrace_probes[i] = NULL;
7673
7674 dtrace_hash_remove(dtrace_bymod, probe);
7675 dtrace_hash_remove(dtrace_byfunc, probe);
7676 dtrace_hash_remove(dtrace_byname, probe);
7677
7678 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7679 probe->dtpr_arg);
7680 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7681 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7682 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7683 kmem_free(probe, sizeof (dtrace_probe_t));
7684 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7685 }
7686
7687 mutex_exit(&dtrace_lock);
7688 mutex_exit(&dtrace_provider_lock);
7689
7690 return (0);
7691 }
7692
7693 /*
7694 * DTrace Probe Management Functions
7695 *
7696 * The functions in this section perform the DTrace probe management,
7697 * including functions to create probes, look-up probes, and call into the
7698 * providers to request that probes be provided. Some of these functions are
7699 * in the Provider-to-Framework API; these functions can be identified by the
7700 * fact that they are not declared "static".
7701 */
7702
7703 /*
7704 * Create a probe with the specified module name, function name, and name.
7705 */
7706 dtrace_id_t
7707 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7708 const char *func, const char *name, int aframes, void *arg)
7709 {
7710 dtrace_probe_t *probe, **probes;
7711 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7712 dtrace_id_t id;
7713
7714 if (provider == dtrace_provider) {
7715 ASSERT(MUTEX_HELD(&dtrace_lock));
7716 } else {
7717 mutex_enter(&dtrace_lock);
7718 }
7719
7720 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7721 VM_BESTFIT | VM_SLEEP);
7722 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7723
7724 probe->dtpr_id = id;
7725 probe->dtpr_gen = dtrace_probegen++;
7726 probe->dtpr_mod = dtrace_strdup(mod);
7727 probe->dtpr_func = dtrace_strdup(func);
7728 probe->dtpr_name = dtrace_strdup(name);
7729 probe->dtpr_arg = arg;
7730 probe->dtpr_aframes = aframes;
7731 probe->dtpr_provider = provider;
7732
7733 dtrace_hash_add(dtrace_bymod, probe);
7734 dtrace_hash_add(dtrace_byfunc, probe);
7735 dtrace_hash_add(dtrace_byname, probe);
7736
7737 if (id - 1 >= dtrace_nprobes) {
7738 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7739 size_t nsize = osize << 1;
7740
7741 if (nsize == 0) {
7742 ASSERT(osize == 0);
7743 ASSERT(dtrace_probes == NULL);
7744 nsize = sizeof (dtrace_probe_t *);
7745 }
7746
7747 probes = kmem_zalloc(nsize, KM_SLEEP);
7748
7749 if (dtrace_probes == NULL) {
7750 ASSERT(osize == 0);
7751 dtrace_probes = probes;
7752 dtrace_nprobes = 1;
7753 } else {
7754 dtrace_probe_t **oprobes = dtrace_probes;
7755
7756 bcopy(oprobes, probes, osize);
7757 dtrace_membar_producer();
7758 dtrace_probes = probes;
7759
7760 dtrace_sync();
7761
7762 /*
7763 * All CPUs are now seeing the new probes array; we can
7764 * safely free the old array.
7765 */
7766 kmem_free(oprobes, osize);
7767 dtrace_nprobes <<= 1;
7768 }
7769
7770 ASSERT(id - 1 < dtrace_nprobes);
7771 }
7772
7773 ASSERT(dtrace_probes[id - 1] == NULL);
7774 dtrace_probes[id - 1] = probe;
7775
7776 if (provider != dtrace_provider)
7777 mutex_exit(&dtrace_lock);
7778
7779 return (id);
7780 }
7781
7782 static dtrace_probe_t *
7783 dtrace_probe_lookup_id(dtrace_id_t id)
7784 {
7785 ASSERT(MUTEX_HELD(&dtrace_lock));
7786
7787 if (id == 0 || id > dtrace_nprobes)
7788 return (NULL);
7789
7790 return (dtrace_probes[id - 1]);
7791 }
7792
7793 static int
7794 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7795 {
7796 *((dtrace_id_t *)arg) = probe->dtpr_id;
7797
7798 return (DTRACE_MATCH_DONE);
7799 }
7800
7801 /*
7802 * Look up a probe based on provider and one or more of module name, function
7803 * name and probe name.
7804 */
7805 dtrace_id_t
7806 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7807 const char *func, const char *name)
7808 {
7809 dtrace_probekey_t pkey;
7810 dtrace_id_t id;
7811 int match;
7812
7813 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7814 pkey.dtpk_pmatch = &dtrace_match_string;
7815 pkey.dtpk_mod = mod;
7816 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7817 pkey.dtpk_func = func;
7818 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7819 pkey.dtpk_name = name;
7820 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7821 pkey.dtpk_id = DTRACE_IDNONE;
7822
7823 mutex_enter(&dtrace_lock);
7824 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7825 dtrace_probe_lookup_match, &id);
7826 mutex_exit(&dtrace_lock);
7827
7828 ASSERT(match == 1 || match == 0);
7829 return (match ? id : 0);
7830 }
7831
7832 /*
7833 * Returns the probe argument associated with the specified probe.
7834 */
7835 void *
7836 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7837 {
7838 dtrace_probe_t *probe;
7839 void *rval = NULL;
7840
7841 mutex_enter(&dtrace_lock);
7842
7843 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7844 probe->dtpr_provider == (dtrace_provider_t *)id)
7845 rval = probe->dtpr_arg;
7846
7847 mutex_exit(&dtrace_lock);
7848
7849 return (rval);
7850 }
7851
7852 /*
7853 * Copy a probe into a probe description.
7854 */
7855 static void
7856 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7857 {
7858 bzero(pdp, sizeof (dtrace_probedesc_t));
7859 pdp->dtpd_id = prp->dtpr_id;
7860
7861 (void) strncpy(pdp->dtpd_provider,
7862 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7863
7864 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7865 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7866 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7867 }
7868
7869 /*
7870 * Called to indicate that a probe -- or probes -- should be provided by a
7871 * specfied provider. If the specified description is NULL, the provider will
7872 * be told to provide all of its probes. (This is done whenever a new
7873 * consumer comes along, or whenever a retained enabling is to be matched.) If
7874 * the specified description is non-NULL, the provider is given the
7875 * opportunity to dynamically provide the specified probe, allowing providers
7876 * to support the creation of probes on-the-fly. (So-called _autocreated_
7877 * probes.) If the provider is NULL, the operations will be applied to all
7878 * providers; if the provider is non-NULL the operations will only be applied
7879 * to the specified provider. The dtrace_provider_lock must be held, and the
7880 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7881 * will need to grab the dtrace_lock when it reenters the framework through
7882 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7883 */
7884 static void
7885 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7886 {
7887 struct modctl *ctl;
7888 int all = 0;
7889
7890 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7891
7892 if (prv == NULL) {
7893 all = 1;
7894 prv = dtrace_provider;
7895 }
7896
7897 do {
7898 /*
7899 * First, call the blanket provide operation.
7900 */
7901 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7902
7903 /*
7904 * Now call the per-module provide operation. We will grab
7905 * mod_lock to prevent the list from being modified. Note
7906 * that this also prevents the mod_busy bits from changing.
7907 * (mod_busy can only be changed with mod_lock held.)
7908 */
7909 mutex_enter(&mod_lock);
7910
7911 ctl = &modules;
7912 do {
7913 if (ctl->mod_busy || ctl->mod_mp == NULL)
7914 continue;
7915
7916 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7917
7918 } while ((ctl = ctl->mod_next) != &modules);
7919
7920 mutex_exit(&mod_lock);
7921 } while (all && (prv = prv->dtpv_next) != NULL);
7922 }
7923
7924 /*
7925 * Iterate over each probe, and call the Framework-to-Provider API function
7926 * denoted by offs.
7927 */
7928 static void
7929 dtrace_probe_foreach(uintptr_t offs)
7930 {
7931 dtrace_provider_t *prov;
7932 void (*func)(void *, dtrace_id_t, void *);
7933 dtrace_probe_t *probe;
7934 dtrace_icookie_t cookie;
7935 int i;
7936
7937 /*
7938 * We disable interrupts to walk through the probe array. This is
7939 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7940 * won't see stale data.
7941 */
7942 cookie = dtrace_interrupt_disable();
7943
7944 for (i = 0; i < dtrace_nprobes; i++) {
7945 if ((probe = dtrace_probes[i]) == NULL)
7946 continue;
7947
7948 if (probe->dtpr_ecb == NULL) {
7949 /*
7950 * This probe isn't enabled -- don't call the function.
7951 */
7952 continue;
7953 }
7954
7955 prov = probe->dtpr_provider;
7956 func = *((void(**)(void *, dtrace_id_t, void *))
7957 ((uintptr_t)&prov->dtpv_pops + offs));
7958
7959 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7960 }
7961
7962 dtrace_interrupt_enable(cookie);
7963 }
7964
7965 static int
7966 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7967 {
7968 dtrace_probekey_t pkey;
7969 uint32_t priv;
7970 uid_t uid;
7971 zoneid_t zoneid;
7972
7973 ASSERT(MUTEX_HELD(&dtrace_lock));
7974 dtrace_ecb_create_cache = NULL;
7975
7976 if (desc == NULL) {
7977 /*
7978 * If we're passed a NULL description, we're being asked to
7979 * create an ECB with a NULL probe.
7980 */
7981 (void) dtrace_ecb_create_enable(NULL, enab);
7982 return (0);
7983 }
7984
7985 dtrace_probekey(desc, &pkey);
7986 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7987 &priv, &uid, &zoneid);
7988
7989 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7990 enab));
7991 }
7992
7993 /*
7994 * DTrace Helper Provider Functions
7995 */
7996 static void
7997 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7998 {
7999 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8000 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8001 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8002 }
8003
8004 static void
8005 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8006 const dof_provider_t *dofprov, char *strtab)
8007 {
8008 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8009 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8010 dofprov->dofpv_provattr);
8011 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8012 dofprov->dofpv_modattr);
8013 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8014 dofprov->dofpv_funcattr);
8015 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8016 dofprov->dofpv_nameattr);
8017 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8018 dofprov->dofpv_argsattr);
8019 }
8020
8021 static void
8022 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8023 {
8024 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8025 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8026 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8027 dof_provider_t *provider;
8028 dof_probe_t *probe;
8029 uint32_t *off, *enoff;
8030 uint8_t *arg;
8031 char *strtab;
8032 uint_t i, nprobes;
8033 dtrace_helper_provdesc_t dhpv;
8034 dtrace_helper_probedesc_t dhpb;
8035 dtrace_meta_t *meta = dtrace_meta_pid;
8036 dtrace_mops_t *mops = &meta->dtm_mops;
8037 void *parg;
8038
8039 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8040 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8041 provider->dofpv_strtab * dof->dofh_secsize);
8042 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8043 provider->dofpv_probes * dof->dofh_secsize);
8044 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8045 provider->dofpv_prargs * dof->dofh_secsize);
8046 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8047 provider->dofpv_proffs * dof->dofh_secsize);
8048
8049 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8050 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8051 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8052 enoff = NULL;
8053
8054 /*
8055 * See dtrace_helper_provider_validate().
8056 */
8057 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8058 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8059 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8060 provider->dofpv_prenoffs * dof->dofh_secsize);
8061 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8062 }
8063
8064 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8065
8066 /*
8067 * Create the provider.
8068 */
8069 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8070
8071 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8072 return;
8073
8074 meta->dtm_count++;
8075
8076 /*
8077 * Create the probes.
8078 */
8079 for (i = 0; i < nprobes; i++) {
8080 probe = (dof_probe_t *)(uintptr_t)(daddr +
8081 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8082
8083 dhpb.dthpb_mod = dhp->dofhp_mod;
8084 dhpb.dthpb_func = strtab + probe->dofpr_func;
8085 dhpb.dthpb_name = strtab + probe->dofpr_name;
8086 dhpb.dthpb_base = probe->dofpr_addr;
8087 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8088 dhpb.dthpb_noffs = probe->dofpr_noffs;
8089 if (enoff != NULL) {
8090 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8091 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8092 } else {
8093 dhpb.dthpb_enoffs = NULL;
8094 dhpb.dthpb_nenoffs = 0;
8095 }
8096 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8097 dhpb.dthpb_nargc = probe->dofpr_nargc;
8098 dhpb.dthpb_xargc = probe->dofpr_xargc;
8099 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8100 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8101
8102 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8103 }
8104 }
8105
8106 static void
8107 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8108 {
8109 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8110 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8111 int i;
8112
8113 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8114
8115 for (i = 0; i < dof->dofh_secnum; i++) {
8116 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8117 dof->dofh_secoff + i * dof->dofh_secsize);
8118
8119 if (sec->dofs_type != DOF_SECT_PROVIDER)
8120 continue;
8121
8122 dtrace_helper_provide_one(dhp, sec, pid);
8123 }
8124
8125 /*
8126 * We may have just created probes, so we must now rematch against
8127 * any retained enablings. Note that this call will acquire both
8128 * cpu_lock and dtrace_lock; the fact that we are holding
8129 * dtrace_meta_lock now is what defines the ordering with respect to
8130 * these three locks.
8131 */
8132 dtrace_enabling_matchall();
8133 }
8134
8135 static void
8136 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8137 {
8138 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8139 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8140 dof_sec_t *str_sec;
8141 dof_provider_t *provider;
8142 char *strtab;
8143 dtrace_helper_provdesc_t dhpv;
8144 dtrace_meta_t *meta = dtrace_meta_pid;
8145 dtrace_mops_t *mops = &meta->dtm_mops;
8146
8147 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8148 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8149 provider->dofpv_strtab * dof->dofh_secsize);
8150
8151 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8152
8153 /*
8154 * Create the provider.
8155 */
8156 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8157
8158 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8159
8160 meta->dtm_count--;
8161 }
8162
8163 static void
8164 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8165 {
8166 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8167 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8168 int i;
8169
8170 ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8171
8172 for (i = 0; i < dof->dofh_secnum; i++) {
8173 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8174 dof->dofh_secoff + i * dof->dofh_secsize);
8175
8176 if (sec->dofs_type != DOF_SECT_PROVIDER)
8177 continue;
8178
8179 dtrace_helper_provider_remove_one(dhp, sec, pid);
8180 }
8181 }
8182
8183 /*
8184 * DTrace Meta Provider-to-Framework API Functions
8185 *
8186 * These functions implement the Meta Provider-to-Framework API, as described
8187 * in <sys/dtrace.h>.
8188 */
8189 int
8190 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8191 dtrace_meta_provider_id_t *idp)
8192 {
8193 dtrace_meta_t *meta;
8194 dtrace_helpers_t *help, *next;
8195 int i;
8196
8197 *idp = DTRACE_METAPROVNONE;
8198
8199 /*
8200 * We strictly don't need the name, but we hold onto it for
8201 * debuggability. All hail error queues!
8202 */
8203 if (name == NULL) {
8204 cmn_err(CE_WARN, "failed to register meta-provider: "
8205 "invalid name");
8206 return (EINVAL);
8207 }
8208
8209 if (mops == NULL ||
8210 mops->dtms_create_probe == NULL ||
8211 mops->dtms_provide_pid == NULL ||
8212 mops->dtms_remove_pid == NULL) {
8213 cmn_err(CE_WARN, "failed to register meta-register %s: "
8214 "invalid ops", name);
8215 return (EINVAL);
8216 }
8217
8218 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8219 meta->dtm_mops = *mops;
8220 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8221 (void) strcpy(meta->dtm_name, name);
8222 meta->dtm_arg = arg;
8223
8224 mutex_enter(&dtrace_meta_lock);
8225 mutex_enter(&dtrace_lock);
8226
8227 if (dtrace_meta_pid != NULL) {
8228 mutex_exit(&dtrace_lock);
8229 mutex_exit(&dtrace_meta_lock);
8230 cmn_err(CE_WARN, "failed to register meta-register %s: "
8231 "user-land meta-provider exists", name);
8232 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8233 kmem_free(meta, sizeof (dtrace_meta_t));
8234 return (EINVAL);
8235 }
8236
8237 dtrace_meta_pid = meta;
8238 *idp = (dtrace_meta_provider_id_t)meta;
8239
8240 /*
8241 * If there are providers and probes ready to go, pass them
8242 * off to the new meta provider now.
8243 */
8244
8245 help = dtrace_deferred_pid;
8246 dtrace_deferred_pid = NULL;
8247
8248 mutex_exit(&dtrace_lock);
8249
8250 while (help != NULL) {
8251 for (i = 0; i < help->dthps_nprovs; i++) {
8252 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8253 help->dthps_pid);
8254 }
8255
8256 next = help->dthps_next;
8257 help->dthps_next = NULL;
8258 help->dthps_prev = NULL;
8259 help->dthps_deferred = 0;
8260 help = next;
8261 }
8262
8263 mutex_exit(&dtrace_meta_lock);
8264
8265 return (0);
8266 }
8267
8268 int
8269 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8270 {
8271 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8272
8273 mutex_enter(&dtrace_meta_lock);
8274 mutex_enter(&dtrace_lock);
8275
8276 if (old == dtrace_meta_pid) {
8277 pp = &dtrace_meta_pid;
8278 } else {
8279 panic("attempt to unregister non-existent "
8280 "dtrace meta-provider %p\n", (void *)old);
8281 }
8282
8283 if (old->dtm_count != 0) {
8284 mutex_exit(&dtrace_lock);
8285 mutex_exit(&dtrace_meta_lock);
8286 return (EBUSY);
8287 }
8288
8289 *pp = NULL;
8290
8291 mutex_exit(&dtrace_lock);
8292 mutex_exit(&dtrace_meta_lock);
8293
8294 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8295 kmem_free(old, sizeof (dtrace_meta_t));
8296
8297 return (0);
8298 }
8299
8300
8301 /*
8302 * DTrace DIF Object Functions
8303 */
8304 static int
8305 dtrace_difo_err(uint_t pc, const char *format, ...)
8306 {
8307 if (dtrace_err_verbose) {
8308 va_list alist;
8309
8310 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8311 va_start(alist, format);
8312 (void) vuprintf(format, alist);
8313 va_end(alist);
8314 }
8315
8316 #ifdef DTRACE_ERRDEBUG
8317 dtrace_errdebug(format);
8318 #endif
8319 return (1);
8320 }
8321
8322 /*
8323 * Validate a DTrace DIF object by checking the IR instructions. The following
8324 * rules are currently enforced by dtrace_difo_validate():
8325 *
8326 * 1. Each instruction must have a valid opcode
8327 * 2. Each register, string, variable, or subroutine reference must be valid
8328 * 3. No instruction can modify register %r0 (must be zero)
8329 * 4. All instruction reserved bits must be set to zero
8330 * 5. The last instruction must be a "ret" instruction
8331 * 6. All branch targets must reference a valid instruction _after_ the branch
8332 */
8333 static int
8334 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8335 cred_t *cr)
8336 {
8337 int err = 0, i;
8338 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8339 int kcheckload;
8340 uint_t pc;
8341
8342 kcheckload = cr == NULL ||
8343 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8344
8345 dp->dtdo_destructive = 0;
8346
8347 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8348 dif_instr_t instr = dp->dtdo_buf[pc];
8349
8350 uint_t r1 = DIF_INSTR_R1(instr);
8351 uint_t r2 = DIF_INSTR_R2(instr);
8352 uint_t rd = DIF_INSTR_RD(instr);
8353 uint_t rs = DIF_INSTR_RS(instr);
8354 uint_t label = DIF_INSTR_LABEL(instr);
8355 uint_t v = DIF_INSTR_VAR(instr);
8356 uint_t subr = DIF_INSTR_SUBR(instr);
8357 uint_t type = DIF_INSTR_TYPE(instr);
8358 uint_t op = DIF_INSTR_OP(instr);
8359
8360 switch (op) {
8361 case DIF_OP_OR:
8362 case DIF_OP_XOR:
8363 case DIF_OP_AND:
8364 case DIF_OP_SLL:
8365 case DIF_OP_SRL:
8366 case DIF_OP_SRA:
8367 case DIF_OP_SUB:
8368 case DIF_OP_ADD:
8369 case DIF_OP_MUL:
8370 case DIF_OP_SDIV:
8371 case DIF_OP_UDIV:
8372 case DIF_OP_SREM:
8373 case DIF_OP_UREM:
8374 case DIF_OP_COPYS:
8375 if (r1 >= nregs)
8376 err += efunc(pc, "invalid register %u\n", r1);
8377 if (r2 >= nregs)
8378 err += efunc(pc, "invalid register %u\n", r2);
8379 if (rd >= nregs)
8380 err += efunc(pc, "invalid register %u\n", rd);
8381 if (rd == 0)
8382 err += efunc(pc, "cannot write to %r0\n");
8383 break;
8384 case DIF_OP_NOT:
8385 case DIF_OP_MOV:
8386 case DIF_OP_ALLOCS:
8387 if (r1 >= nregs)
8388 err += efunc(pc, "invalid register %u\n", r1);
8389 if (r2 != 0)
8390 err += efunc(pc, "non-zero reserved bits\n");
8391 if (rd >= nregs)
8392 err += efunc(pc, "invalid register %u\n", rd);
8393 if (rd == 0)
8394 err += efunc(pc, "cannot write to %r0\n");
8395 break;
8396 case DIF_OP_LDSB:
8397 case DIF_OP_LDSH:
8398 case DIF_OP_LDSW:
8399 case DIF_OP_LDUB:
8400 case DIF_OP_LDUH:
8401 case DIF_OP_LDUW:
8402 case DIF_OP_LDX:
8403 if (r1 >= nregs)
8404 err += efunc(pc, "invalid register %u\n", r1);
8405 if (r2 != 0)
8406 err += efunc(pc, "non-zero reserved bits\n");
8407 if (rd >= nregs)
8408 err += efunc(pc, "invalid register %u\n", rd);
8409 if (rd == 0)
8410 err += efunc(pc, "cannot write to %r0\n");
8411 if (kcheckload)
8412 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8413 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8414 break;
8415 case DIF_OP_RLDSB:
8416 case DIF_OP_RLDSH:
8417 case DIF_OP_RLDSW:
8418 case DIF_OP_RLDUB:
8419 case DIF_OP_RLDUH:
8420 case DIF_OP_RLDUW:
8421 case DIF_OP_RLDX:
8422 if (r1 >= nregs)
8423 err += efunc(pc, "invalid register %u\n", r1);
8424 if (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 if (rd == 0)
8429 err += efunc(pc, "cannot write to %r0\n");
8430 break;
8431 case DIF_OP_ULDSB:
8432 case DIF_OP_ULDSH:
8433 case DIF_OP_ULDSW:
8434 case DIF_OP_ULDUB:
8435 case DIF_OP_ULDUH:
8436 case DIF_OP_ULDUW:
8437 case DIF_OP_ULDX:
8438 if (r1 >= nregs)
8439 err += efunc(pc, "invalid register %u\n", r1);
8440 if (r2 != 0)
8441 err += efunc(pc, "non-zero reserved bits\n");
8442 if (rd >= nregs)
8443 err += efunc(pc, "invalid register %u\n", rd);
8444 if (rd == 0)
8445 err += efunc(pc, "cannot write to %r0\n");
8446 break;
8447 case DIF_OP_STB:
8448 case DIF_OP_STH:
8449 case DIF_OP_STW:
8450 case DIF_OP_STX:
8451 if (r1 >= nregs)
8452 err += efunc(pc, "invalid register %u\n", r1);
8453 if (r2 != 0)
8454 err += efunc(pc, "non-zero reserved bits\n");
8455 if (rd >= nregs)
8456 err += efunc(pc, "invalid register %u\n", rd);
8457 if (rd == 0)
8458 err += efunc(pc, "cannot write to 0 address\n");
8459 break;
8460 case DIF_OP_CMP:
8461 case DIF_OP_SCMP:
8462 if (r1 >= nregs)
8463 err += efunc(pc, "invalid register %u\n", r1);
8464 if (r2 >= nregs)
8465 err += efunc(pc, "invalid register %u\n", r2);
8466 if (rd != 0)
8467 err += efunc(pc, "non-zero reserved bits\n");
8468 break;
8469 case DIF_OP_TST:
8470 if (r1 >= nregs)
8471 err += efunc(pc, "invalid register %u\n", r1);
8472 if (r2 != 0 || rd != 0)
8473 err += efunc(pc, "non-zero reserved bits\n");
8474 break;
8475 case DIF_OP_BA:
8476 case DIF_OP_BE:
8477 case DIF_OP_BNE:
8478 case DIF_OP_BG:
8479 case DIF_OP_BGU:
8480 case DIF_OP_BGE:
8481 case DIF_OP_BGEU:
8482 case DIF_OP_BL:
8483 case DIF_OP_BLU:
8484 case DIF_OP_BLE:
8485 case DIF_OP_BLEU:
8486 if (label >= dp->dtdo_len) {
8487 err += efunc(pc, "invalid branch target %u\n",
8488 label);
8489 }
8490 if (label <= pc) {
8491 err += efunc(pc, "backward branch to %u\n",
8492 label);
8493 }
8494 break;
8495 case DIF_OP_RET:
8496 if (r1 != 0 || r2 != 0)
8497 err += efunc(pc, "non-zero reserved bits\n");
8498 if (rd >= nregs)
8499 err += efunc(pc, "invalid register %u\n", rd);
8500 break;
8501 case DIF_OP_NOP:
8502 case DIF_OP_POPTS:
8503 case DIF_OP_FLUSHTS:
8504 if (r1 != 0 || r2 != 0 || rd != 0)
8505 err += efunc(pc, "non-zero reserved bits\n");
8506 break;
8507 case DIF_OP_SETX:
8508 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8509 err += efunc(pc, "invalid integer ref %u\n",
8510 DIF_INSTR_INTEGER(instr));
8511 }
8512 if (rd >= nregs)
8513 err += efunc(pc, "invalid register %u\n", rd);
8514 if (rd == 0)
8515 err += efunc(pc, "cannot write to %r0\n");
8516 break;
8517 case DIF_OP_SETS:
8518 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8519 err += efunc(pc, "invalid string ref %u\n",
8520 DIF_INSTR_STRING(instr));
8521 }
8522 if (rd >= nregs)
8523 err += efunc(pc, "invalid register %u\n", rd);
8524 if (rd == 0)
8525 err += efunc(pc, "cannot write to %r0\n");
8526 break;
8527 case DIF_OP_LDGA:
8528 case DIF_OP_LDTA:
8529 if (r1 > DIF_VAR_ARRAY_MAX)
8530 err += efunc(pc, "invalid array %u\n", r1);
8531 if (r2 >= nregs)
8532 err += efunc(pc, "invalid register %u\n", r2);
8533 if (rd >= nregs)
8534 err += efunc(pc, "invalid register %u\n", rd);
8535 if (rd == 0)
8536 err += efunc(pc, "cannot write to %r0\n");
8537 break;
8538 case DIF_OP_LDGS:
8539 case DIF_OP_LDTS:
8540 case DIF_OP_LDLS:
8541 case DIF_OP_LDGAA:
8542 case DIF_OP_LDTAA:
8543 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8544 err += efunc(pc, "invalid variable %u\n", v);
8545 if (rd >= nregs)
8546 err += efunc(pc, "invalid register %u\n", rd);
8547 if (rd == 0)
8548 err += efunc(pc, "cannot write to %r0\n");
8549 break;
8550 case DIF_OP_STGS:
8551 case DIF_OP_STTS:
8552 case DIF_OP_STLS:
8553 case DIF_OP_STGAA:
8554 case DIF_OP_STTAA:
8555 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8556 err += efunc(pc, "invalid variable %u\n", v);
8557 if (rs >= nregs)
8558 err += efunc(pc, "invalid register %u\n", rd);
8559 break;
8560 case DIF_OP_CALL:
8561 if (subr > DIF_SUBR_MAX)
8562 err += efunc(pc, "invalid subr %u\n", subr);
8563 if (rd >= nregs)
8564 err += efunc(pc, "invalid register %u\n", rd);
8565 if (rd == 0)
8566 err += efunc(pc, "cannot write to %r0\n");
8567
8568 if (subr == DIF_SUBR_COPYOUT ||
8569 subr == DIF_SUBR_COPYOUTSTR) {
8570 dp->dtdo_destructive = 1;
8571 }
8572
8573 if (subr == DIF_SUBR_GETF) {
8574 /*
8575 * If we have a getf() we need to record that
8576 * in our state. Note that our state can be
8577 * NULL if this is a helper -- but in that
8578 * case, the call to getf() is itself illegal,
8579 * and will be caught (slightly later) when
8580 * the helper is validated.
8581 */
8582 if (vstate->dtvs_state != NULL)
8583 vstate->dtvs_state->dts_getf++;
8584 }
8585
8586 break;
8587 case DIF_OP_PUSHTR:
8588 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8589 err += efunc(pc, "invalid ref type %u\n", type);
8590 if (r2 >= nregs)
8591 err += efunc(pc, "invalid register %u\n", r2);
8592 if (rs >= nregs)
8593 err += efunc(pc, "invalid register %u\n", rs);
8594 break;
8595 case DIF_OP_PUSHTV:
8596 if (type != DIF_TYPE_CTF)
8597 err += efunc(pc, "invalid val type %u\n", type);
8598 if (r2 >= nregs)
8599 err += efunc(pc, "invalid register %u\n", r2);
8600 if (rs >= nregs)
8601 err += efunc(pc, "invalid register %u\n", rs);
8602 break;
8603 default:
8604 err += efunc(pc, "invalid opcode %u\n",
8605 DIF_INSTR_OP(instr));
8606 }
8607 }
8608
8609 if (dp->dtdo_len != 0 &&
8610 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8611 err += efunc(dp->dtdo_len - 1,
8612 "expected 'ret' as last DIF instruction\n");
8613 }
8614
8615 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8616 /*
8617 * If we're not returning by reference, the size must be either
8618 * 0 or the size of one of the base types.
8619 */
8620 switch (dp->dtdo_rtype.dtdt_size) {
8621 case 0:
8622 case sizeof (uint8_t):
8623 case sizeof (uint16_t):
8624 case sizeof (uint32_t):
8625 case sizeof (uint64_t):
8626 break;
8627
8628 default:
8629 err += efunc(dp->dtdo_len - 1, "bad return size\n");
8630 }
8631 }
8632
8633 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8634 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8635 dtrace_diftype_t *vt, *et;
8636 uint_t id, ndx;
8637
8638 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8639 v->dtdv_scope != DIFV_SCOPE_THREAD &&
8640 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8641 err += efunc(i, "unrecognized variable scope %d\n",
8642 v->dtdv_scope);
8643 break;
8644 }
8645
8646 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8647 v->dtdv_kind != DIFV_KIND_SCALAR) {
8648 err += efunc(i, "unrecognized variable type %d\n",
8649 v->dtdv_kind);
8650 break;
8651 }
8652
8653 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8654 err += efunc(i, "%d exceeds variable id limit\n", id);
8655 break;
8656 }
8657
8658 if (id < DIF_VAR_OTHER_UBASE)
8659 continue;
8660
8661 /*
8662 * For user-defined variables, we need to check that this
8663 * definition is identical to any previous definition that we
8664 * encountered.
8665 */
8666 ndx = id - DIF_VAR_OTHER_UBASE;
8667
8668 switch (v->dtdv_scope) {
8669 case DIFV_SCOPE_GLOBAL:
8670 if (ndx < vstate->dtvs_nglobals) {
8671 dtrace_statvar_t *svar;
8672
8673 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8674 existing = &svar->dtsv_var;
8675 }
8676
8677 break;
8678
8679 case DIFV_SCOPE_THREAD:
8680 if (ndx < vstate->dtvs_ntlocals)
8681 existing = &vstate->dtvs_tlocals[ndx];
8682 break;
8683
8684 case DIFV_SCOPE_LOCAL:
8685 if (ndx < vstate->dtvs_nlocals) {
8686 dtrace_statvar_t *svar;
8687
8688 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8689 existing = &svar->dtsv_var;
8690 }
8691
8692 break;
8693 }
8694
8695 vt = &v->dtdv_type;
8696
8697 if (vt->dtdt_flags & DIF_TF_BYREF) {
8698 if (vt->dtdt_size == 0) {
8699 err += efunc(i, "zero-sized variable\n");
8700 break;
8701 }
8702
8703 if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8704 vt->dtdt_size > dtrace_global_maxsize) {
8705 err += efunc(i, "oversized by-ref global\n");
8706 break;
8707 }
8708 }
8709
8710 if (existing == NULL || existing->dtdv_id == 0)
8711 continue;
8712
8713 ASSERT(existing->dtdv_id == v->dtdv_id);
8714 ASSERT(existing->dtdv_scope == v->dtdv_scope);
8715
8716 if (existing->dtdv_kind != v->dtdv_kind)
8717 err += efunc(i, "%d changed variable kind\n", id);
8718
8719 et = &existing->dtdv_type;
8720
8721 if (vt->dtdt_flags != et->dtdt_flags) {
8722 err += efunc(i, "%d changed variable type flags\n", id);
8723 break;
8724 }
8725
8726 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8727 err += efunc(i, "%d changed variable type size\n", id);
8728 break;
8729 }
8730 }
8731
8732 return (err);
8733 }
8734
8735 /*
8736 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
8737 * are much more constrained than normal DIFOs. Specifically, they may
8738 * not:
8739 *
8740 * 1. Make calls to subroutines other than copyin(), copyinstr() or
8741 * miscellaneous string routines
8742 * 2. Access DTrace variables other than the args[] array, and the
8743 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8744 * 3. Have thread-local variables.
8745 * 4. Have dynamic variables.
8746 */
8747 static int
8748 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8749 {
8750 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8751 int err = 0;
8752 uint_t pc;
8753
8754 for (pc = 0; pc < dp->dtdo_len; pc++) {
8755 dif_instr_t instr = dp->dtdo_buf[pc];
8756
8757 uint_t v = DIF_INSTR_VAR(instr);
8758 uint_t subr = DIF_INSTR_SUBR(instr);
8759 uint_t op = DIF_INSTR_OP(instr);
8760
8761 switch (op) {
8762 case DIF_OP_OR:
8763 case DIF_OP_XOR:
8764 case DIF_OP_AND:
8765 case DIF_OP_SLL:
8766 case DIF_OP_SRL:
8767 case DIF_OP_SRA:
8768 case DIF_OP_SUB:
8769 case DIF_OP_ADD:
8770 case DIF_OP_MUL:
8771 case DIF_OP_SDIV:
8772 case DIF_OP_UDIV:
8773 case DIF_OP_SREM:
8774 case DIF_OP_UREM:
8775 case DIF_OP_COPYS:
8776 case DIF_OP_NOT:
8777 case DIF_OP_MOV:
8778 case DIF_OP_RLDSB:
8779 case DIF_OP_RLDSH:
8780 case DIF_OP_RLDSW:
8781 case DIF_OP_RLDUB:
8782 case DIF_OP_RLDUH:
8783 case DIF_OP_RLDUW:
8784 case DIF_OP_RLDX:
8785 case DIF_OP_ULDSB:
8786 case DIF_OP_ULDSH:
8787 case DIF_OP_ULDSW:
8788 case DIF_OP_ULDUB:
8789 case DIF_OP_ULDUH:
8790 case DIF_OP_ULDUW:
8791 case DIF_OP_ULDX:
8792 case DIF_OP_STB:
8793 case DIF_OP_STH:
8794 case DIF_OP_STW:
8795 case DIF_OP_STX:
8796 case DIF_OP_ALLOCS:
8797 case DIF_OP_CMP:
8798 case DIF_OP_SCMP:
8799 case DIF_OP_TST:
8800 case DIF_OP_BA:
8801 case DIF_OP_BE:
8802 case DIF_OP_BNE:
8803 case DIF_OP_BG:
8804 case DIF_OP_BGU:
8805 case DIF_OP_BGE:
8806 case DIF_OP_BGEU:
8807 case DIF_OP_BL:
8808 case DIF_OP_BLU:
8809 case DIF_OP_BLE:
8810 case DIF_OP_BLEU:
8811 case DIF_OP_RET:
8812 case DIF_OP_NOP:
8813 case DIF_OP_POPTS:
8814 case DIF_OP_FLUSHTS:
8815 case DIF_OP_SETX:
8816 case DIF_OP_SETS:
8817 case DIF_OP_LDGA:
8818 case DIF_OP_LDLS:
8819 case DIF_OP_STGS:
8820 case DIF_OP_STLS:
8821 case DIF_OP_PUSHTR:
8822 case DIF_OP_PUSHTV:
8823 break;
8824
8825 case DIF_OP_LDGS:
8826 if (v >= DIF_VAR_OTHER_UBASE)
8827 break;
8828
8829 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8830 break;
8831
8832 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8833 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8834 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8835 v == DIF_VAR_UID || v == DIF_VAR_GID)
8836 break;
8837
8838 err += efunc(pc, "illegal variable %u\n", v);
8839 break;
8840
8841 case DIF_OP_LDTA:
8842 case DIF_OP_LDTS:
8843 case DIF_OP_LDGAA:
8844 case DIF_OP_LDTAA:
8845 err += efunc(pc, "illegal dynamic variable load\n");
8846 break;
8847
8848 case DIF_OP_STTS:
8849 case DIF_OP_STGAA:
8850 case DIF_OP_STTAA:
8851 err += efunc(pc, "illegal dynamic variable store\n");
8852 break;
8853
8854 case DIF_OP_CALL:
8855 if (subr == DIF_SUBR_ALLOCA ||
8856 subr == DIF_SUBR_BCOPY ||
8857 subr == DIF_SUBR_COPYIN ||
8858 subr == DIF_SUBR_COPYINTO ||
8859 subr == DIF_SUBR_COPYINSTR ||
8860 subr == DIF_SUBR_INDEX ||
8861 subr == DIF_SUBR_INET_NTOA ||
8862 subr == DIF_SUBR_INET_NTOA6 ||
8863 subr == DIF_SUBR_INET_NTOP ||
8864 subr == DIF_SUBR_LLTOSTR ||
8865 subr == DIF_SUBR_RINDEX ||
8866 subr == DIF_SUBR_STRCHR ||
8867 subr == DIF_SUBR_STRJOIN ||
8868 subr == DIF_SUBR_STRRCHR ||
8869 subr == DIF_SUBR_STRSTR ||
8870 subr == DIF_SUBR_HTONS ||
8871 subr == DIF_SUBR_HTONL ||
8872 subr == DIF_SUBR_HTONLL ||
8873 subr == DIF_SUBR_NTOHS ||
8874 subr == DIF_SUBR_NTOHL ||
8875 subr == DIF_SUBR_NTOHLL)
8876 break;
8877
8878 err += efunc(pc, "invalid subr %u\n", subr);
8879 break;
8880
8881 default:
8882 err += efunc(pc, "invalid opcode %u\n",
8883 DIF_INSTR_OP(instr));
8884 }
8885 }
8886
8887 return (err);
8888 }
8889
8890 /*
8891 * Returns 1 if the expression in the DIF object can be cached on a per-thread
8892 * basis; 0 if not.
8893 */
8894 static int
8895 dtrace_difo_cacheable(dtrace_difo_t *dp)
8896 {
8897 int i;
8898
8899 if (dp == NULL)
8900 return (0);
8901
8902 for (i = 0; i < dp->dtdo_varlen; i++) {
8903 dtrace_difv_t *v = &dp->dtdo_vartab[i];
8904
8905 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8906 continue;
8907
8908 switch (v->dtdv_id) {
8909 case DIF_VAR_CURTHREAD:
8910 case DIF_VAR_PID:
8911 case DIF_VAR_TID:
8912 case DIF_VAR_EXECNAME:
8913 case DIF_VAR_ZONENAME:
8914 break;
8915
8916 default:
8917 return (0);
8918 }
8919 }
8920
8921 /*
8922 * This DIF object may be cacheable. Now we need to look for any
8923 * array loading instructions, any memory loading instructions, or
8924 * any stores to thread-local variables.
8925 */
8926 for (i = 0; i < dp->dtdo_len; i++) {
8927 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8928
8929 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8930 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8931 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8932 op == DIF_OP_LDGA || op == DIF_OP_STTS)
8933 return (0);
8934 }
8935
8936 return (1);
8937 }
8938
8939 static void
8940 dtrace_difo_hold(dtrace_difo_t *dp)
8941 {
8942 int i;
8943
8944 ASSERT(MUTEX_HELD(&dtrace_lock));
8945
8946 dp->dtdo_refcnt++;
8947 ASSERT(dp->dtdo_refcnt != 0);
8948
8949 /*
8950 * We need to check this DIF object for references to the variable
8951 * DIF_VAR_VTIMESTAMP.
8952 */
8953 for (i = 0; i < dp->dtdo_varlen; i++) {
8954 dtrace_difv_t *v = &dp->dtdo_vartab[i];
8955
8956 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8957 continue;
8958
8959 if (dtrace_vtime_references++ == 0)
8960 dtrace_vtime_enable();
8961 }
8962 }
8963
8964 /*
8965 * This routine calculates the dynamic variable chunksize for a given DIF
8966 * object. The calculation is not fool-proof, and can probably be tricked by
8967 * malicious DIF -- but it works for all compiler-generated DIF. Because this
8968 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8969 * if a dynamic variable size exceeds the chunksize.
8970 */
8971 static void
8972 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8973 {
8974 uint64_t sval;
8975 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8976 const dif_instr_t *text = dp->dtdo_buf;
8977 uint_t pc, srd = 0;
8978 uint_t ttop = 0;
8979 size_t size, ksize;
8980 uint_t id, i;
8981
8982 for (pc = 0; pc < dp->dtdo_len; pc++) {
8983 dif_instr_t instr = text[pc];
8984 uint_t op = DIF_INSTR_OP(instr);
8985 uint_t rd = DIF_INSTR_RD(instr);
8986 uint_t r1 = DIF_INSTR_R1(instr);
8987 uint_t nkeys = 0;
8988 uchar_t scope;
8989
8990 dtrace_key_t *key = tupregs;
8991
8992 switch (op) {
8993 case DIF_OP_SETX:
8994 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8995 srd = rd;
8996 continue;
8997
8998 case DIF_OP_STTS:
8999 key = &tupregs[DIF_DTR_NREGS];
9000 key[0].dttk_size = 0;
9001 key[1].dttk_size = 0;
9002 nkeys = 2;
9003 scope = DIFV_SCOPE_THREAD;
9004 break;
9005
9006 case DIF_OP_STGAA:
9007 case DIF_OP_STTAA:
9008 nkeys = ttop;
9009
9010 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9011 key[nkeys++].dttk_size = 0;
9012
9013 key[nkeys++].dttk_size = 0;
9014
9015 if (op == DIF_OP_STTAA) {
9016 scope = DIFV_SCOPE_THREAD;
9017 } else {
9018 scope = DIFV_SCOPE_GLOBAL;
9019 }
9020
9021 break;
9022
9023 case DIF_OP_PUSHTR:
9024 if (ttop == DIF_DTR_NREGS)
9025 return;
9026
9027 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9028 /*
9029 * If the register for the size of the "pushtr"
9030 * is %r0 (or the value is 0) and the type is
9031 * a string, we'll use the system-wide default
9032 * string size.
9033 */
9034 tupregs[ttop++].dttk_size =
9035 dtrace_strsize_default;
9036 } else {
9037 if (srd == 0)
9038 return;
9039
9040 tupregs[ttop++].dttk_size = sval;
9041 }
9042
9043 break;
9044
9045 case DIF_OP_PUSHTV:
9046 if (ttop == DIF_DTR_NREGS)
9047 return;
9048
9049 tupregs[ttop++].dttk_size = 0;
9050 break;
9051
9052 case DIF_OP_FLUSHTS:
9053 ttop = 0;
9054 break;
9055
9056 case DIF_OP_POPTS:
9057 if (ttop != 0)
9058 ttop--;
9059 break;
9060 }
9061
9062 sval = 0;
9063 srd = 0;
9064
9065 if (nkeys == 0)
9066 continue;
9067
9068 /*
9069 * We have a dynamic variable allocation; calculate its size.
9070 */
9071 for (ksize = 0, i = 0; i < nkeys; i++)
9072 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9073
9074 size = sizeof (dtrace_dynvar_t);
9075 size += sizeof (dtrace_key_t) * (nkeys - 1);
9076 size += ksize;
9077
9078 /*
9079 * Now we need to determine the size of the stored data.
9080 */
9081 id = DIF_INSTR_VAR(instr);
9082
9083 for (i = 0; i < dp->dtdo_varlen; i++) {
9084 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9085
9086 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9087 size += v->dtdv_type.dtdt_size;
9088 break;
9089 }
9090 }
9091
9092 if (i == dp->dtdo_varlen)
9093 return;
9094
9095 /*
9096 * We have the size. If this is larger than the chunk size
9097 * for our dynamic variable state, reset the chunk size.
9098 */
9099 size = P2ROUNDUP(size, sizeof (uint64_t));
9100
9101 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9102 vstate->dtvs_dynvars.dtds_chunksize = size;
9103 }
9104 }
9105
9106 static void
9107 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9108 {
9109 int i, oldsvars, osz, nsz, otlocals, ntlocals;
9110 uint_t id;
9111
9112 ASSERT(MUTEX_HELD(&dtrace_lock));
9113 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9114
9115 for (i = 0; i < dp->dtdo_varlen; i++) {
9116 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9117 dtrace_statvar_t *svar, ***svarp;
9118 size_t dsize = 0;
9119 uint8_t scope = v->dtdv_scope;
9120 int *np;
9121
9122 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9123 continue;
9124
9125 id -= DIF_VAR_OTHER_UBASE;
9126
9127 switch (scope) {
9128 case DIFV_SCOPE_THREAD:
9129 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9130 dtrace_difv_t *tlocals;
9131
9132 if ((ntlocals = (otlocals << 1)) == 0)
9133 ntlocals = 1;
9134
9135 osz = otlocals * sizeof (dtrace_difv_t);
9136 nsz = ntlocals * sizeof (dtrace_difv_t);
9137
9138 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9139
9140 if (osz != 0) {
9141 bcopy(vstate->dtvs_tlocals,
9142 tlocals, osz);
9143 kmem_free(vstate->dtvs_tlocals, osz);
9144 }
9145
9146 vstate->dtvs_tlocals = tlocals;
9147 vstate->dtvs_ntlocals = ntlocals;
9148 }
9149
9150 vstate->dtvs_tlocals[id] = *v;
9151 continue;
9152
9153 case DIFV_SCOPE_LOCAL:
9154 np = &vstate->dtvs_nlocals;
9155 svarp = &vstate->dtvs_locals;
9156
9157 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9158 dsize = NCPU * (v->dtdv_type.dtdt_size +
9159 sizeof (uint64_t));
9160 else
9161 dsize = NCPU * sizeof (uint64_t);
9162
9163 break;
9164
9165 case DIFV_SCOPE_GLOBAL:
9166 np = &vstate->dtvs_nglobals;
9167 svarp = &vstate->dtvs_globals;
9168
9169 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9170 dsize = v->dtdv_type.dtdt_size +
9171 sizeof (uint64_t);
9172
9173 break;
9174
9175 default:
9176 ASSERT(0);
9177 }
9178
9179 while (id >= (oldsvars = *np)) {
9180 dtrace_statvar_t **statics;
9181 int newsvars, oldsize, newsize;
9182
9183 if ((newsvars = (oldsvars << 1)) == 0)
9184 newsvars = 1;
9185
9186 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9187 newsize = newsvars * sizeof (dtrace_statvar_t *);
9188
9189 statics = kmem_zalloc(newsize, KM_SLEEP);
9190
9191 if (oldsize != 0) {
9192 bcopy(*svarp, statics, oldsize);
9193 kmem_free(*svarp, oldsize);
9194 }
9195
9196 *svarp = statics;
9197 *np = newsvars;
9198 }
9199
9200 if ((svar = (*svarp)[id]) == NULL) {
9201 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9202 svar->dtsv_var = *v;
9203
9204 if ((svar->dtsv_size = dsize) != 0) {
9205 svar->dtsv_data = (uint64_t)(uintptr_t)
9206 kmem_zalloc(dsize, KM_SLEEP);
9207 }
9208
9209 (*svarp)[id] = svar;
9210 }
9211
9212 svar->dtsv_refcnt++;
9213 }
9214
9215 dtrace_difo_chunksize(dp, vstate);
9216 dtrace_difo_hold(dp);
9217 }
9218
9219 static dtrace_difo_t *
9220 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9221 {
9222 dtrace_difo_t *new;
9223 size_t sz;
9224
9225 ASSERT(dp->dtdo_buf != NULL);
9226 ASSERT(dp->dtdo_refcnt != 0);
9227
9228 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9229
9230 ASSERT(dp->dtdo_buf != NULL);
9231 sz = dp->dtdo_len * sizeof (dif_instr_t);
9232 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9233 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9234 new->dtdo_len = dp->dtdo_len;
9235
9236 if (dp->dtdo_strtab != NULL) {
9237 ASSERT(dp->dtdo_strlen != 0);
9238 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9239 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9240 new->dtdo_strlen = dp->dtdo_strlen;
9241 }
9242
9243 if (dp->dtdo_inttab != NULL) {
9244 ASSERT(dp->dtdo_intlen != 0);
9245 sz = dp->dtdo_intlen * sizeof (uint64_t);
9246 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9247 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9248 new->dtdo_intlen = dp->dtdo_intlen;
9249 }
9250
9251 if (dp->dtdo_vartab != NULL) {
9252 ASSERT(dp->dtdo_varlen != 0);
9253 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9254 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9255 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9256 new->dtdo_varlen = dp->dtdo_varlen;
9257 }
9258
9259 dtrace_difo_init(new, vstate);
9260 return (new);
9261 }
9262
9263 static void
9264 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9265 {
9266 int i;
9267
9268 ASSERT(dp->dtdo_refcnt == 0);
9269
9270 for (i = 0; i < dp->dtdo_varlen; i++) {
9271 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9272 dtrace_statvar_t *svar, **svarp;
9273 uint_t id;
9274 uint8_t scope = v->dtdv_scope;
9275 int *np;
9276
9277 switch (scope) {
9278 case DIFV_SCOPE_THREAD:
9279 continue;
9280
9281 case DIFV_SCOPE_LOCAL:
9282 np = &vstate->dtvs_nlocals;
9283 svarp = vstate->dtvs_locals;
9284 break;
9285
9286 case DIFV_SCOPE_GLOBAL:
9287 np = &vstate->dtvs_nglobals;
9288 svarp = vstate->dtvs_globals;
9289 break;
9290
9291 default:
9292 ASSERT(0);
9293 }
9294
9295 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9296 continue;
9297
9298 id -= DIF_VAR_OTHER_UBASE;
9299 ASSERT(id < *np);
9300
9301 svar = svarp[id];
9302 ASSERT(svar != NULL);
9303 ASSERT(svar->dtsv_refcnt > 0);
9304
9305 if (--svar->dtsv_refcnt > 0)
9306 continue;
9307
9308 if (svar->dtsv_size != 0) {
9309 ASSERT(svar->dtsv_data != NULL);
9310 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9311 svar->dtsv_size);
9312 }
9313
9314 kmem_free(svar, sizeof (dtrace_statvar_t));
9315 svarp[id] = NULL;
9316 }
9317
9318 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9319 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9320 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9321 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9322
9323 kmem_free(dp, sizeof (dtrace_difo_t));
9324 }
9325
9326 static void
9327 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9328 {
9329 int i;
9330
9331 ASSERT(MUTEX_HELD(&dtrace_lock));
9332 ASSERT(dp->dtdo_refcnt != 0);
9333
9334 for (i = 0; i < dp->dtdo_varlen; i++) {
9335 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9336
9337 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9338 continue;
9339
9340 ASSERT(dtrace_vtime_references > 0);
9341 if (--dtrace_vtime_references == 0)
9342 dtrace_vtime_disable();
9343 }
9344
9345 if (--dp->dtdo_refcnt == 0)
9346 dtrace_difo_destroy(dp, vstate);
9347 }
9348
9349 /*
9350 * DTrace Format Functions
9351 */
9352 static uint16_t
9353 dtrace_format_add(dtrace_state_t *state, char *str)
9354 {
9355 char *fmt, **new;
9356 uint16_t ndx, len = strlen(str) + 1;
9357
9358 fmt = kmem_zalloc(len, KM_SLEEP);
9359 bcopy(str, fmt, len);
9360
9361 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9362 if (state->dts_formats[ndx] == NULL) {
9363 state->dts_formats[ndx] = fmt;
9364 return (ndx + 1);
9365 }
9366 }
9367
9368 if (state->dts_nformats == USHRT_MAX) {
9369 /*
9370 * This is only likely if a denial-of-service attack is being
9371 * attempted. As such, it's okay to fail silently here.
9372 */
9373 kmem_free(fmt, len);
9374 return (0);
9375 }
9376
9377 /*
9378 * For simplicity, we always resize the formats array to be exactly the
9379 * number of formats.
9380 */
9381 ndx = state->dts_nformats++;
9382 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9383
9384 if (state->dts_formats != NULL) {
9385 ASSERT(ndx != 0);
9386 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9387 kmem_free(state->dts_formats, ndx * sizeof (char *));
9388 }
9389
9390 state->dts_formats = new;
9391 state->dts_formats[ndx] = fmt;
9392
9393 return (ndx + 1);
9394 }
9395
9396 static void
9397 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9398 {
9399 char *fmt;
9400
9401 ASSERT(state->dts_formats != NULL);
9402 ASSERT(format <= state->dts_nformats);
9403 ASSERT(state->dts_formats[format - 1] != NULL);
9404
9405 fmt = state->dts_formats[format - 1];
9406 kmem_free(fmt, strlen(fmt) + 1);
9407 state->dts_formats[format - 1] = NULL;
9408 }
9409
9410 static void
9411 dtrace_format_destroy(dtrace_state_t *state)
9412 {
9413 int i;
9414
9415 if (state->dts_nformats == 0) {
9416 ASSERT(state->dts_formats == NULL);
9417 return;
9418 }
9419
9420 ASSERT(state->dts_formats != NULL);
9421
9422 for (i = 0; i < state->dts_nformats; i++) {
9423 char *fmt = state->dts_formats[i];
9424
9425 if (fmt == NULL)
9426 continue;
9427
9428 kmem_free(fmt, strlen(fmt) + 1);
9429 }
9430
9431 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9432 state->dts_nformats = 0;
9433 state->dts_formats = NULL;
9434 }
9435
9436 /*
9437 * DTrace Predicate Functions
9438 */
9439 static dtrace_predicate_t *
9440 dtrace_predicate_create(dtrace_difo_t *dp)
9441 {
9442 dtrace_predicate_t *pred;
9443
9444 ASSERT(MUTEX_HELD(&dtrace_lock));
9445 ASSERT(dp->dtdo_refcnt != 0);
9446
9447 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9448 pred->dtp_difo = dp;
9449 pred->dtp_refcnt = 1;
9450
9451 if (!dtrace_difo_cacheable(dp))
9452 return (pred);
9453
9454 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9455 /*
9456 * This is only theoretically possible -- we have had 2^32
9457 * cacheable predicates on this machine. We cannot allow any
9458 * more predicates to become cacheable: as unlikely as it is,
9459 * there may be a thread caching a (now stale) predicate cache
9460 * ID. (N.B.: the temptation is being successfully resisted to
9461 * have this cmn_err() "Holy shit -- we executed this code!")
9462 */
9463 return (pred);
9464 }
9465
9466 pred->dtp_cacheid = dtrace_predcache_id++;
9467
9468 return (pred);
9469 }
9470
9471 static void
9472 dtrace_predicate_hold(dtrace_predicate_t *pred)
9473 {
9474 ASSERT(MUTEX_HELD(&dtrace_lock));
9475 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9476 ASSERT(pred->dtp_refcnt > 0);
9477
9478 pred->dtp_refcnt++;
9479 }
9480
9481 static void
9482 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9483 {
9484 dtrace_difo_t *dp = pred->dtp_difo;
9485
9486 ASSERT(MUTEX_HELD(&dtrace_lock));
9487 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9488 ASSERT(pred->dtp_refcnt > 0);
9489
9490 if (--pred->dtp_refcnt == 0) {
9491 dtrace_difo_release(pred->dtp_difo, vstate);
9492 kmem_free(pred, sizeof (dtrace_predicate_t));
9493 }
9494 }
9495
9496 /*
9497 * DTrace Action Description Functions
9498 */
9499 static dtrace_actdesc_t *
9500 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9501 uint64_t uarg, uint64_t arg)
9502 {
9503 dtrace_actdesc_t *act;
9504
9505 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9506 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
9507
9508 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9509 act->dtad_kind = kind;
9510 act->dtad_ntuple = ntuple;
9511 act->dtad_uarg = uarg;
9512 act->dtad_arg = arg;
9513 act->dtad_refcnt = 1;
9514
9515 return (act);
9516 }
9517
9518 static void
9519 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9520 {
9521 ASSERT(act->dtad_refcnt >= 1);
9522 act->dtad_refcnt++;
9523 }
9524
9525 static void
9526 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9527 {
9528 dtrace_actkind_t kind = act->dtad_kind;
9529 dtrace_difo_t *dp;
9530
9531 ASSERT(act->dtad_refcnt >= 1);
9532
9533 if (--act->dtad_refcnt != 0)
9534 return;
9535
9536 if ((dp = act->dtad_difo) != NULL)
9537 dtrace_difo_release(dp, vstate);
9538
9539 if (DTRACEACT_ISPRINTFLIKE(kind)) {
9540 char *str = (char *)(uintptr_t)act->dtad_arg;
9541
9542 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9543 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9544
9545 if (str != NULL)
9546 kmem_free(str, strlen(str) + 1);
9547 }
9548
9549 kmem_free(act, sizeof (dtrace_actdesc_t));
9550 }
9551
9552 /*
9553 * DTrace ECB Functions
9554 */
9555 static dtrace_ecb_t *
9556 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9557 {
9558 dtrace_ecb_t *ecb;
9559 dtrace_epid_t epid;
9560
9561 ASSERT(MUTEX_HELD(&dtrace_lock));
9562
9563 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9564 ecb->dte_predicate = NULL;
9565 ecb->dte_probe = probe;
9566
9567 /*
9568 * The default size is the size of the default action: recording
9569 * the header.
9570 */
9571 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9572 ecb->dte_alignment = sizeof (dtrace_epid_t);
9573
9574 epid = state->dts_epid++;
9575
9576 if (epid - 1 >= state->dts_necbs) {
9577 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9578 int necbs = state->dts_necbs << 1;
9579
9580 ASSERT(epid == state->dts_necbs + 1);
9581
9582 if (necbs == 0) {
9583 ASSERT(oecbs == NULL);
9584 necbs = 1;
9585 }
9586
9587 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9588
9589 if (oecbs != NULL)
9590 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9591
9592 dtrace_membar_producer();
9593 state->dts_ecbs = ecbs;
9594
9595 if (oecbs != NULL) {
9596 /*
9597 * If this state is active, we must dtrace_sync()
9598 * before we can free the old dts_ecbs array: we're
9599 * coming in hot, and there may be active ring
9600 * buffer processing (which indexes into the dts_ecbs
9601 * array) on another CPU.
9602 */
9603 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9604 dtrace_sync();
9605
9606 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9607 }
9608
9609 dtrace_membar_producer();
9610 state->dts_necbs = necbs;
9611 }
9612
9613 ecb->dte_state = state;
9614
9615 ASSERT(state->dts_ecbs[epid - 1] == NULL);
9616 dtrace_membar_producer();
9617 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9618
9619 return (ecb);
9620 }
9621
9622 static int
9623 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9624 {
9625 dtrace_probe_t *probe = ecb->dte_probe;
9626
9627 ASSERT(MUTEX_HELD(&cpu_lock));
9628 ASSERT(MUTEX_HELD(&dtrace_lock));
9629 ASSERT(ecb->dte_next == NULL);
9630
9631 if (probe == NULL) {
9632 /*
9633 * This is the NULL probe -- there's nothing to do.
9634 */
9635 return (0);
9636 }
9637
9638 if (probe->dtpr_ecb == NULL) {
9639 dtrace_provider_t *prov = probe->dtpr_provider;
9640
9641 /*
9642 * We're the first ECB on this probe.
9643 */
9644 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9645
9646 if (ecb->dte_predicate != NULL)
9647 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9648
9649 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9650 probe->dtpr_id, probe->dtpr_arg));
9651 } else {
9652 /*
9653 * This probe is already active. Swing the last pointer to
9654 * point to the new ECB, and issue a dtrace_sync() to assure
9655 * that all CPUs have seen the change.
9656 */
9657 ASSERT(probe->dtpr_ecb_last != NULL);
9658 probe->dtpr_ecb_last->dte_next = ecb;
9659 probe->dtpr_ecb_last = ecb;
9660 probe->dtpr_predcache = 0;
9661
9662 dtrace_sync();
9663 return (0);
9664 }
9665 }
9666
9667 static void
9668 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9669 {
9670 dtrace_action_t *act;
9671 uint32_t curneeded = UINT32_MAX;
9672 uint32_t aggbase = UINT32_MAX;
9673
9674 /*
9675 * If we record anything, we always record the dtrace_rechdr_t. (And
9676 * we always record it first.)
9677 */
9678 ecb->dte_size = sizeof (dtrace_rechdr_t);
9679 ecb->dte_alignment = sizeof (dtrace_epid_t);
9680
9681 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9682 dtrace_recdesc_t *rec = &act->dta_rec;
9683 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
9684
9685 ecb->dte_alignment = MAX(ecb->dte_alignment,
9686 rec->dtrd_alignment);
9687
9688 if (DTRACEACT_ISAGG(act->dta_kind)) {
9689 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9690
9691 ASSERT(rec->dtrd_size != 0);
9692 ASSERT(agg->dtag_first != NULL);
9693 ASSERT(act->dta_prev->dta_intuple);
9694 ASSERT(aggbase != UINT32_MAX);
9695 ASSERT(curneeded != UINT32_MAX);
9696
9697 agg->dtag_base = aggbase;
9698
9699 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9700 rec->dtrd_offset = curneeded;
9701 curneeded += rec->dtrd_size;
9702 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
9703
9704 aggbase = UINT32_MAX;
9705 curneeded = UINT32_MAX;
9706 } else if (act->dta_intuple) {
9707 if (curneeded == UINT32_MAX) {
9708 /*
9709 * This is the first record in a tuple. Align
9710 * curneeded to be at offset 4 in an 8-byte
9711 * aligned block.
9712 */
9713 ASSERT(act->dta_prev == NULL ||
9714 !act->dta_prev->dta_intuple);
9715 ASSERT3U(aggbase, ==, UINT32_MAX);
9716 curneeded = P2PHASEUP(ecb->dte_size,
9717 sizeof (uint64_t), sizeof (dtrace_aggid_t));
9718
9719 aggbase = curneeded - sizeof (dtrace_aggid_t);
9720 ASSERT(IS_P2ALIGNED(aggbase,
9721 sizeof (uint64_t)));
9722 }
9723 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9724 rec->dtrd_offset = curneeded;
9725 curneeded += rec->dtrd_size;
9726 } else {
9727 /* tuples must be followed by an aggregation */
9728 ASSERT(act->dta_prev == NULL ||
9729 !act->dta_prev->dta_intuple);
9730
9731 ecb->dte_size = P2ROUNDUP(ecb->dte_size,
9732 rec->dtrd_alignment);
9733 rec->dtrd_offset = ecb->dte_size;
9734 ecb->dte_size += rec->dtrd_size;
9735 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
9736 }
9737 }
9738
9739 if ((act = ecb->dte_action) != NULL &&
9740 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9741 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
9742 /*
9743 * If the size is still sizeof (dtrace_rechdr_t), then all
9744 * actions store no data; set the size to 0.
9745 */
9746 ecb->dte_size = 0;
9747 }
9748
9749 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
9750 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
9751 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
9752 ecb->dte_needed);
9753 }
9754
9755 static dtrace_action_t *
9756 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9757 {
9758 dtrace_aggregation_t *agg;
9759 size_t size = sizeof (uint64_t);
9760 int ntuple = desc->dtad_ntuple;
9761 dtrace_action_t *act;
9762 dtrace_recdesc_t *frec;
9763 dtrace_aggid_t aggid;
9764 dtrace_state_t *state = ecb->dte_state;
9765
9766 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9767 agg->dtag_ecb = ecb;
9768
9769 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9770
9771 switch (desc->dtad_kind) {
9772 case DTRACEAGG_MIN:
9773 agg->dtag_initial = INT64_MAX;
9774 agg->dtag_aggregate = dtrace_aggregate_min;
9775 break;
9776
9777 case DTRACEAGG_MAX:
9778 agg->dtag_initial = INT64_MIN;
9779 agg->dtag_aggregate = dtrace_aggregate_max;
9780 break;
9781
9782 case DTRACEAGG_COUNT:
9783 agg->dtag_aggregate = dtrace_aggregate_count;
9784 break;
9785
9786 case DTRACEAGG_QUANTIZE:
9787 agg->dtag_aggregate = dtrace_aggregate_quantize;
9788 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9789 sizeof (uint64_t);
9790 break;
9791
9792 case DTRACEAGG_LQUANTIZE: {
9793 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9794 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9795
9796 agg->dtag_initial = desc->dtad_arg;
9797 agg->dtag_aggregate = dtrace_aggregate_lquantize;
9798
9799 if (step == 0 || levels == 0)
9800 goto err;
9801
9802 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9803 break;
9804 }
9805
9806 case DTRACEAGG_LLQUANTIZE: {
9807 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
9808 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
9809 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
9810 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
9811 int64_t v;
9812
9813 agg->dtag_initial = desc->dtad_arg;
9814 agg->dtag_aggregate = dtrace_aggregate_llquantize;
9815
9816 if (factor < 2 || low >= high || nsteps < factor)
9817 goto err;
9818
9819 /*
9820 * Now check that the number of steps evenly divides a power
9821 * of the factor. (This assures both integer bucket size and
9822 * linearity within each magnitude.)
9823 */
9824 for (v = factor; v < nsteps; v *= factor)
9825 continue;
9826
9827 if ((v % nsteps) || (nsteps % factor))
9828 goto err;
9829
9830 size = (dtrace_aggregate_llquantize_bucket(factor,
9831 low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
9832 break;
9833 }
9834
9835 case DTRACEAGG_AVG:
9836 agg->dtag_aggregate = dtrace_aggregate_avg;
9837 size = sizeof (uint64_t) * 2;
9838 break;
9839
9840 case DTRACEAGG_STDDEV:
9841 agg->dtag_aggregate = dtrace_aggregate_stddev;
9842 size = sizeof (uint64_t) * 4;
9843 break;
9844
9845 case DTRACEAGG_SUM:
9846 agg->dtag_aggregate = dtrace_aggregate_sum;
9847 break;
9848
9849 default:
9850 goto err;
9851 }
9852
9853 agg->dtag_action.dta_rec.dtrd_size = size;
9854
9855 if (ntuple == 0)
9856 goto err;
9857
9858 /*
9859 * We must make sure that we have enough actions for the n-tuple.
9860 */
9861 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9862 if (DTRACEACT_ISAGG(act->dta_kind))
9863 break;
9864
9865 if (--ntuple == 0) {
9866 /*
9867 * This is the action with which our n-tuple begins.
9868 */
9869 agg->dtag_first = act;
9870 goto success;
9871 }
9872 }
9873
9874 /*
9875 * This n-tuple is short by ntuple elements. Return failure.
9876 */
9877 ASSERT(ntuple != 0);
9878 err:
9879 kmem_free(agg, sizeof (dtrace_aggregation_t));
9880 return (NULL);
9881
9882 success:
9883 /*
9884 * If the last action in the tuple has a size of zero, it's actually
9885 * an expression argument for the aggregating action.
9886 */
9887 ASSERT(ecb->dte_action_last != NULL);
9888 act = ecb->dte_action_last;
9889
9890 if (act->dta_kind == DTRACEACT_DIFEXPR) {
9891 ASSERT(act->dta_difo != NULL);
9892
9893 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9894 agg->dtag_hasarg = 1;
9895 }
9896
9897 /*
9898 * We need to allocate an id for this aggregation.
9899 */
9900 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9901 VM_BESTFIT | VM_SLEEP);
9902
9903 if (aggid - 1 >= state->dts_naggregations) {
9904 dtrace_aggregation_t **oaggs = state->dts_aggregations;
9905 dtrace_aggregation_t **aggs;
9906 int naggs = state->dts_naggregations << 1;
9907 int onaggs = state->dts_naggregations;
9908
9909 ASSERT(aggid == state->dts_naggregations + 1);
9910
9911 if (naggs == 0) {
9912 ASSERT(oaggs == NULL);
9913 naggs = 1;
9914 }
9915
9916 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9917
9918 if (oaggs != NULL) {
9919 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9920 kmem_free(oaggs, onaggs * sizeof (*aggs));
9921 }
9922
9923 state->dts_aggregations = aggs;
9924 state->dts_naggregations = naggs;
9925 }
9926
9927 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9928 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9929
9930 frec = &agg->dtag_first->dta_rec;
9931 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9932 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9933
9934 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9935 ASSERT(!act->dta_intuple);
9936 act->dta_intuple = 1;
9937 }
9938
9939 return (&agg->dtag_action);
9940 }
9941
9942 static void
9943 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9944 {
9945 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9946 dtrace_state_t *state = ecb->dte_state;
9947 dtrace_aggid_t aggid = agg->dtag_id;
9948
9949 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9950 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9951
9952 ASSERT(state->dts_aggregations[aggid - 1] == agg);
9953 state->dts_aggregations[aggid - 1] = NULL;
9954
9955 kmem_free(agg, sizeof (dtrace_aggregation_t));
9956 }
9957
9958 static int
9959 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9960 {
9961 dtrace_action_t *action, *last;
9962 dtrace_difo_t *dp = desc->dtad_difo;
9963 uint32_t size = 0, align = sizeof (uint8_t), mask;
9964 uint16_t format = 0;
9965 dtrace_recdesc_t *rec;
9966 dtrace_state_t *state = ecb->dte_state;
9967 dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9968 uint64_t arg = desc->dtad_arg;
9969
9970 ASSERT(MUTEX_HELD(&dtrace_lock));
9971 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9972
9973 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9974 /*
9975 * If this is an aggregating action, there must be neither
9976 * a speculate nor a commit on the action chain.
9977 */
9978 dtrace_action_t *act;
9979
9980 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9981 if (act->dta_kind == DTRACEACT_COMMIT)
9982 return (EINVAL);
9983
9984 if (act->dta_kind == DTRACEACT_SPECULATE)
9985 return (EINVAL);
9986 }
9987
9988 action = dtrace_ecb_aggregation_create(ecb, desc);
9989
9990 if (action == NULL)
9991 return (EINVAL);
9992 } else {
9993 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9994 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9995 dp != NULL && dp->dtdo_destructive)) {
9996 state->dts_destructive = 1;
9997 }
9998
9999 switch (desc->dtad_kind) {
10000 case DTRACEACT_PRINTF:
10001 case DTRACEACT_PRINTA:
10002 case DTRACEACT_SYSTEM:
10003 case DTRACEACT_FREOPEN:
10004 case DTRACEACT_DIFEXPR:
10005 /*
10006 * We know that our arg is a string -- turn it into a
10007 * format.
10008 */
10009 if (arg == NULL) {
10010 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10011 desc->dtad_kind == DTRACEACT_DIFEXPR);
10012 format = 0;
10013 } else {
10014 ASSERT(arg != NULL);
10015 ASSERT(arg > KERNELBASE);
10016 format = dtrace_format_add(state,
10017 (char *)(uintptr_t)arg);
10018 }
10019
10020 /*FALLTHROUGH*/
10021 case DTRACEACT_LIBACT:
10022 case DTRACEACT_TRACEMEM:
10023 case DTRACEACT_TRACEMEM_DYNSIZE:
10024 if (dp == NULL)
10025 return (EINVAL);
10026
10027 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10028 break;
10029
10030 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10031 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10032 return (EINVAL);
10033
10034 size = opt[DTRACEOPT_STRSIZE];
10035 }
10036
10037 break;
10038
10039 case DTRACEACT_STACK:
10040 if ((nframes = arg) == 0) {
10041 nframes = opt[DTRACEOPT_STACKFRAMES];
10042 ASSERT(nframes > 0);
10043 arg = nframes;
10044 }
10045
10046 size = nframes * sizeof (pc_t);
10047 break;
10048
10049 case DTRACEACT_JSTACK:
10050 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10051 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10052
10053 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10054 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10055
10056 arg = DTRACE_USTACK_ARG(nframes, strsize);
10057
10058 /*FALLTHROUGH*/
10059 case DTRACEACT_USTACK:
10060 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10061 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10062 strsize = DTRACE_USTACK_STRSIZE(arg);
10063 nframes = opt[DTRACEOPT_USTACKFRAMES];
10064 ASSERT(nframes > 0);
10065 arg = DTRACE_USTACK_ARG(nframes, strsize);
10066 }
10067
10068 /*
10069 * Save a slot for the pid.
10070 */
10071 size = (nframes + 1) * sizeof (uint64_t);
10072 size += DTRACE_USTACK_STRSIZE(arg);
10073 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10074
10075 break;
10076
10077 case DTRACEACT_SYM:
10078 case DTRACEACT_MOD:
10079 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10080 sizeof (uint64_t)) ||
10081 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10082 return (EINVAL);
10083 break;
10084
10085 case DTRACEACT_USYM:
10086 case DTRACEACT_UMOD:
10087 case DTRACEACT_UADDR:
10088 if (dp == NULL ||
10089 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10090 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10091 return (EINVAL);
10092
10093 /*
10094 * We have a slot for the pid, plus a slot for the
10095 * argument. To keep things simple (aligned with
10096 * bitness-neutral sizing), we store each as a 64-bit
10097 * quantity.
10098 */
10099 size = 2 * sizeof (uint64_t);
10100 break;
10101
10102 case DTRACEACT_STOP:
10103 case DTRACEACT_BREAKPOINT:
10104 case DTRACEACT_PANIC:
10105 break;
10106
10107 case DTRACEACT_CHILL:
10108 case DTRACEACT_DISCARD:
10109 case DTRACEACT_RAISE:
10110 if (dp == NULL)
10111 return (EINVAL);
10112 break;
10113
10114 case DTRACEACT_EXIT:
10115 if (dp == NULL ||
10116 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10117 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10118 return (EINVAL);
10119 break;
10120
10121 case DTRACEACT_SPECULATE:
10122 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10123 return (EINVAL);
10124
10125 if (dp == NULL)
10126 return (EINVAL);
10127
10128 state->dts_speculates = 1;
10129 break;
10130
10131 case DTRACEACT_COMMIT: {
10132 dtrace_action_t *act = ecb->dte_action;
10133
10134 for (; act != NULL; act = act->dta_next) {
10135 if (act->dta_kind == DTRACEACT_COMMIT)
10136 return (EINVAL);
10137 }
10138
10139 if (dp == NULL)
10140 return (EINVAL);
10141 break;
10142 }
10143
10144 default:
10145 return (EINVAL);
10146 }
10147
10148 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10149 /*
10150 * If this is a data-storing action or a speculate,
10151 * we must be sure that there isn't a commit on the
10152 * action chain.
10153 */
10154 dtrace_action_t *act = ecb->dte_action;
10155
10156 for (; act != NULL; act = act->dta_next) {
10157 if (act->dta_kind == DTRACEACT_COMMIT)
10158 return (EINVAL);
10159 }
10160 }
10161
10162 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10163 action->dta_rec.dtrd_size = size;
10164 }
10165
10166 action->dta_refcnt = 1;
10167 rec = &action->dta_rec;
10168 size = rec->dtrd_size;
10169
10170 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10171 if (!(size & mask)) {
10172 align = mask + 1;
10173 break;
10174 }
10175 }
10176
10177 action->dta_kind = desc->dtad_kind;
10178
10179 if ((action->dta_difo = dp) != NULL)
10180 dtrace_difo_hold(dp);
10181
10182 rec->dtrd_action = action->dta_kind;
10183 rec->dtrd_arg = arg;
10184 rec->dtrd_uarg = desc->dtad_uarg;
10185 rec->dtrd_alignment = (uint16_t)align;
10186 rec->dtrd_format = format;
10187
10188 if ((last = ecb->dte_action_last) != NULL) {
10189 ASSERT(ecb->dte_action != NULL);
10190 action->dta_prev = last;
10191 last->dta_next = action;
10192 } else {
10193 ASSERT(ecb->dte_action == NULL);
10194 ecb->dte_action = action;
10195 }
10196
10197 ecb->dte_action_last = action;
10198
10199 return (0);
10200 }
10201
10202 static void
10203 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10204 {
10205 dtrace_action_t *act = ecb->dte_action, *next;
10206 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10207 dtrace_difo_t *dp;
10208 uint16_t format;
10209
10210 if (act != NULL && act->dta_refcnt > 1) {
10211 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10212 act->dta_refcnt--;
10213 } else {
10214 for (; act != NULL; act = next) {
10215 next = act->dta_next;
10216 ASSERT(next != NULL || act == ecb->dte_action_last);
10217 ASSERT(act->dta_refcnt == 1);
10218
10219 if ((format = act->dta_rec.dtrd_format) != 0)
10220 dtrace_format_remove(ecb->dte_state, format);
10221
10222 if ((dp = act->dta_difo) != NULL)
10223 dtrace_difo_release(dp, vstate);
10224
10225 if (DTRACEACT_ISAGG(act->dta_kind)) {
10226 dtrace_ecb_aggregation_destroy(ecb, act);
10227 } else {
10228 kmem_free(act, sizeof (dtrace_action_t));
10229 }
10230 }
10231 }
10232
10233 ecb->dte_action = NULL;
10234 ecb->dte_action_last = NULL;
10235 ecb->dte_size = 0;
10236 }
10237
10238 static void
10239 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10240 {
10241 /*
10242 * We disable the ECB by removing it from its probe.
10243 */
10244 dtrace_ecb_t *pecb, *prev = NULL;
10245 dtrace_probe_t *probe = ecb->dte_probe;
10246
10247 ASSERT(MUTEX_HELD(&dtrace_lock));
10248
10249 if (probe == NULL) {
10250 /*
10251 * This is the NULL probe; there is nothing to disable.
10252 */
10253 return;
10254 }
10255
10256 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10257 if (pecb == ecb)
10258 break;
10259 prev = pecb;
10260 }
10261
10262 ASSERT(pecb != NULL);
10263
10264 if (prev == NULL) {
10265 probe->dtpr_ecb = ecb->dte_next;
10266 } else {
10267 prev->dte_next = ecb->dte_next;
10268 }
10269
10270 if (ecb == probe->dtpr_ecb_last) {
10271 ASSERT(ecb->dte_next == NULL);
10272 probe->dtpr_ecb_last = prev;
10273 }
10274
10275 /*
10276 * The ECB has been disconnected from the probe; now sync to assure
10277 * that all CPUs have seen the change before returning.
10278 */
10279 dtrace_sync();
10280
10281 if (probe->dtpr_ecb == NULL) {
10282 /*
10283 * That was the last ECB on the probe; clear the predicate
10284 * cache ID for the probe, disable it and sync one more time
10285 * to assure that we'll never hit it again.
10286 */
10287 dtrace_provider_t *prov = probe->dtpr_provider;
10288
10289 ASSERT(ecb->dte_next == NULL);
10290 ASSERT(probe->dtpr_ecb_last == NULL);
10291 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10292 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10293 probe->dtpr_id, probe->dtpr_arg);
10294 dtrace_sync();
10295 } else {
10296 /*
10297 * There is at least one ECB remaining on the probe. If there
10298 * is _exactly_ one, set the probe's predicate cache ID to be
10299 * the predicate cache ID of the remaining ECB.
10300 */
10301 ASSERT(probe->dtpr_ecb_last != NULL);
10302 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10303
10304 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10305 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10306
10307 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10308
10309 if (p != NULL)
10310 probe->dtpr_predcache = p->dtp_cacheid;
10311 }
10312
10313 ecb->dte_next = NULL;
10314 }
10315 }
10316
10317 static void
10318 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10319 {
10320 dtrace_state_t *state = ecb->dte_state;
10321 dtrace_vstate_t *vstate = &state->dts_vstate;
10322 dtrace_predicate_t *pred;
10323 dtrace_epid_t epid = ecb->dte_epid;
10324
10325 ASSERT(MUTEX_HELD(&dtrace_lock));
10326 ASSERT(ecb->dte_next == NULL);
10327 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10328
10329 if ((pred = ecb->dte_predicate) != NULL)
10330 dtrace_predicate_release(pred, vstate);
10331
10332 dtrace_ecb_action_remove(ecb);
10333
10334 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10335 state->dts_ecbs[epid - 1] = NULL;
10336
10337 kmem_free(ecb, sizeof (dtrace_ecb_t));
10338 }
10339
10340 static dtrace_ecb_t *
10341 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10342 dtrace_enabling_t *enab)
10343 {
10344 dtrace_ecb_t *ecb;
10345 dtrace_predicate_t *pred;
10346 dtrace_actdesc_t *act;
10347 dtrace_provider_t *prov;
10348 dtrace_ecbdesc_t *desc = enab->dten_current;
10349
10350 ASSERT(MUTEX_HELD(&dtrace_lock));
10351 ASSERT(state != NULL);
10352
10353 ecb = dtrace_ecb_add(state, probe);
10354 ecb->dte_uarg = desc->dted_uarg;
10355
10356 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10357 dtrace_predicate_hold(pred);
10358 ecb->dte_predicate = pred;
10359 }
10360
10361 if (probe != NULL) {
10362 /*
10363 * If the provider shows more leg than the consumer is old
10364 * enough to see, we need to enable the appropriate implicit
10365 * predicate bits to prevent the ecb from activating at
10366 * revealing times.
10367 *
10368 * Providers specifying DTRACE_PRIV_USER at register time
10369 * are stating that they need the /proc-style privilege
10370 * model to be enforced, and this is what DTRACE_COND_OWNER
10371 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10372 */
10373 prov = probe->dtpr_provider;
10374 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10375 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10376 ecb->dte_cond |= DTRACE_COND_OWNER;
10377
10378 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10379 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10380 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10381
10382 /*
10383 * If the provider shows us kernel innards and the user
10384 * is lacking sufficient privilege, enable the
10385 * DTRACE_COND_USERMODE implicit predicate.
10386 */
10387 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10388 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10389 ecb->dte_cond |= DTRACE_COND_USERMODE;
10390 }
10391
10392 if (dtrace_ecb_create_cache != NULL) {
10393 /*
10394 * If we have a cached ecb, we'll use its action list instead
10395 * of creating our own (saving both time and space).
10396 */
10397 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10398 dtrace_action_t *act = cached->dte_action;
10399
10400 if (act != NULL) {
10401 ASSERT(act->dta_refcnt > 0);
10402 act->dta_refcnt++;
10403 ecb->dte_action = act;
10404 ecb->dte_action_last = cached->dte_action_last;
10405 ecb->dte_needed = cached->dte_needed;
10406 ecb->dte_size = cached->dte_size;
10407 ecb->dte_alignment = cached->dte_alignment;
10408 }
10409
10410 return (ecb);
10411 }
10412
10413 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10414 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10415 dtrace_ecb_destroy(ecb);
10416 return (NULL);
10417 }
10418 }
10419
10420 dtrace_ecb_resize(ecb);
10421
10422 return (dtrace_ecb_create_cache = ecb);
10423 }
10424
10425 static int
10426 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10427 {
10428 dtrace_ecb_t *ecb;
10429 dtrace_enabling_t *enab = arg;
10430 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10431
10432 ASSERT(state != NULL);
10433
10434 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10435 /*
10436 * This probe was created in a generation for which this
10437 * enabling has previously created ECBs; we don't want to
10438 * enable it again, so just kick out.
10439 */
10440 return (DTRACE_MATCH_NEXT);
10441 }
10442
10443 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10444 return (DTRACE_MATCH_DONE);
10445
10446 if (dtrace_ecb_enable(ecb) < 0)
10447 return (DTRACE_MATCH_FAIL);
10448
10449 return (DTRACE_MATCH_NEXT);
10450 }
10451
10452 static dtrace_ecb_t *
10453 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10454 {
10455 dtrace_ecb_t *ecb;
10456
10457 ASSERT(MUTEX_HELD(&dtrace_lock));
10458
10459 if (id == 0 || id > state->dts_necbs)
10460 return (NULL);
10461
10462 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10463 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10464
10465 return (state->dts_ecbs[id - 1]);
10466 }
10467
10468 static dtrace_aggregation_t *
10469 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10470 {
10471 dtrace_aggregation_t *agg;
10472
10473 ASSERT(MUTEX_HELD(&dtrace_lock));
10474
10475 if (id == 0 || id > state->dts_naggregations)
10476 return (NULL);
10477
10478 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10479 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10480 agg->dtag_id == id);
10481
10482 return (state->dts_aggregations[id - 1]);
10483 }
10484
10485 /*
10486 * DTrace Buffer Functions
10487 *
10488 * The following functions manipulate DTrace buffers. Most of these functions
10489 * are called in the context of establishing or processing consumer state;
10490 * exceptions are explicitly noted.
10491 */
10492
10493 /*
10494 * Note: called from cross call context. This function switches the two
10495 * buffers on a given CPU. The atomicity of this operation is assured by
10496 * disabling interrupts while the actual switch takes place; the disabling of
10497 * interrupts serializes the execution with any execution of dtrace_probe() on
10498 * the same CPU.
10499 */
10500 static void
10501 dtrace_buffer_switch(dtrace_buffer_t *buf)
10502 {
10503 caddr_t tomax = buf->dtb_tomax;
10504 caddr_t xamot = buf->dtb_xamot;
10505 dtrace_icookie_t cookie;
10506 hrtime_t now;
10507
10508 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10509 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10510
10511 cookie = dtrace_interrupt_disable();
10512 now = dtrace_gethrtime();
10513 buf->dtb_tomax = xamot;
10514 buf->dtb_xamot = tomax;
10515 buf->dtb_xamot_drops = buf->dtb_drops;
10516 buf->dtb_xamot_offset = buf->dtb_offset;
10517 buf->dtb_xamot_errors = buf->dtb_errors;
10518 buf->dtb_xamot_flags = buf->dtb_flags;
10519 buf->dtb_offset = 0;
10520 buf->dtb_drops = 0;
10521 buf->dtb_errors = 0;
10522 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10523 buf->dtb_interval = now - buf->dtb_switched;
10524 buf->dtb_switched = now;
10525 dtrace_interrupt_enable(cookie);
10526 }
10527
10528 /*
10529 * Note: called from cross call context. This function activates a buffer
10530 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
10531 * is guaranteed by the disabling of interrupts.
10532 */
10533 static void
10534 dtrace_buffer_activate(dtrace_state_t *state)
10535 {
10536 dtrace_buffer_t *buf;
10537 dtrace_icookie_t cookie = dtrace_interrupt_disable();
10538
10539 buf = &state->dts_buffer[CPU->cpu_id];
10540
10541 if (buf->dtb_tomax != NULL) {
10542 /*
10543 * We might like to assert that the buffer is marked inactive,
10544 * but this isn't necessarily true: the buffer for the CPU
10545 * that processes the BEGIN probe has its buffer activated
10546 * manually. In this case, we take the (harmless) action
10547 * re-clearing the bit INACTIVE bit.
10548 */
10549 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10550 }
10551
10552 dtrace_interrupt_enable(cookie);
10553 }
10554
10555 static int
10556 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10557 processorid_t cpu, int *factor)
10558 {
10559 cpu_t *cp;
10560 dtrace_buffer_t *buf;
10561 int allocated = 0, desired = 0;
10562
10563 ASSERT(MUTEX_HELD(&cpu_lock));
10564 ASSERT(MUTEX_HELD(&dtrace_lock));
10565
10566 *factor = 1;
10567
10568 if (size > dtrace_nonroot_maxsize &&
10569 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10570 return (EFBIG);
10571
10572 cp = cpu_list;
10573
10574 do {
10575 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10576 continue;
10577
10578 buf = &bufs[cp->cpu_id];
10579
10580 /*
10581 * If there is already a buffer allocated for this CPU, it
10582 * is only possible that this is a DR event. In this case,
10583 * the buffer size must match our specified size.
10584 */
10585 if (buf->dtb_tomax != NULL) {
10586 ASSERT(buf->dtb_size == size);
10587 continue;
10588 }
10589
10590 ASSERT(buf->dtb_xamot == NULL);
10591
10592 if ((buf->dtb_tomax = kmem_zalloc(size,
10593 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10594 goto err;
10595
10596 buf->dtb_size = size;
10597 buf->dtb_flags = flags;
10598 buf->dtb_offset = 0;
10599 buf->dtb_drops = 0;
10600
10601 if (flags & DTRACEBUF_NOSWITCH)
10602 continue;
10603
10604 if ((buf->dtb_xamot = kmem_zalloc(size,
10605 KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10606 goto err;
10607 } while ((cp = cp->cpu_next) != cpu_list);
10608
10609 return (0);
10610
10611 err:
10612 cp = cpu_list;
10613
10614 do {
10615 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10616 continue;
10617
10618 buf = &bufs[cp->cpu_id];
10619 desired += 2;
10620
10621 if (buf->dtb_xamot != NULL) {
10622 ASSERT(buf->dtb_tomax != NULL);
10623 ASSERT(buf->dtb_size == size);
10624 kmem_free(buf->dtb_xamot, size);
10625 allocated++;
10626 }
10627
10628 if (buf->dtb_tomax != NULL) {
10629 ASSERT(buf->dtb_size == size);
10630 kmem_free(buf->dtb_tomax, size);
10631 allocated++;
10632 }
10633
10634 buf->dtb_tomax = NULL;
10635 buf->dtb_xamot = NULL;
10636 buf->dtb_size = 0;
10637 } while ((cp = cp->cpu_next) != cpu_list);
10638
10639 *factor = desired / (allocated > 0 ? allocated : 1);
10640
10641 return (ENOMEM);
10642 }
10643
10644 /*
10645 * Note: called from probe context. This function just increments the drop
10646 * count on a buffer. It has been made a function to allow for the
10647 * possibility of understanding the source of mysterious drop counts. (A
10648 * problem for which one may be particularly disappointed that DTrace cannot
10649 * be used to understand DTrace.)
10650 */
10651 static void
10652 dtrace_buffer_drop(dtrace_buffer_t *buf)
10653 {
10654 buf->dtb_drops++;
10655 }
10656
10657 /*
10658 * Note: called from probe context. This function is called to reserve space
10659 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
10660 * mstate. Returns the new offset in the buffer, or a negative value if an
10661 * error has occurred.
10662 */
10663 static intptr_t
10664 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10665 dtrace_state_t *state, dtrace_mstate_t *mstate)
10666 {
10667 intptr_t offs = buf->dtb_offset, soffs;
10668 intptr_t woffs;
10669 caddr_t tomax;
10670 size_t total;
10671
10672 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10673 return (-1);
10674
10675 if ((tomax = buf->dtb_tomax) == NULL) {
10676 dtrace_buffer_drop(buf);
10677 return (-1);
10678 }
10679
10680 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10681 while (offs & (align - 1)) {
10682 /*
10683 * Assert that our alignment is off by a number which
10684 * is itself sizeof (uint32_t) aligned.
10685 */
10686 ASSERT(!((align - (offs & (align - 1))) &
10687 (sizeof (uint32_t) - 1)));
10688 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10689 offs += sizeof (uint32_t);
10690 }
10691
10692 if ((soffs = offs + needed) > buf->dtb_size) {
10693 dtrace_buffer_drop(buf);
10694 return (-1);
10695 }
10696
10697 if (mstate == NULL)
10698 return (offs);
10699
10700 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10701 mstate->dtms_scratch_size = buf->dtb_size - soffs;
10702 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10703
10704 return (offs);
10705 }
10706
10707 if (buf->dtb_flags & DTRACEBUF_FILL) {
10708 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10709 (buf->dtb_flags & DTRACEBUF_FULL))
10710 return (-1);
10711 goto out;
10712 }
10713
10714 total = needed + (offs & (align - 1));
10715
10716 /*
10717 * For a ring buffer, life is quite a bit more complicated. Before
10718 * we can store any padding, we need to adjust our wrapping offset.
10719 * (If we've never before wrapped or we're not about to, no adjustment
10720 * is required.)
10721 */
10722 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10723 offs + total > buf->dtb_size) {
10724 woffs = buf->dtb_xamot_offset;
10725
10726 if (offs + total > buf->dtb_size) {
10727 /*
10728 * We can't fit in the end of the buffer. First, a
10729 * sanity check that we can fit in the buffer at all.
10730 */
10731 if (total > buf->dtb_size) {
10732 dtrace_buffer_drop(buf);
10733 return (-1);
10734 }
10735
10736 /*
10737 * We're going to be storing at the top of the buffer,
10738 * so now we need to deal with the wrapped offset. We
10739 * only reset our wrapped offset to 0 if it is
10740 * currently greater than the current offset. If it
10741 * is less than the current offset, it is because a
10742 * previous allocation induced a wrap -- but the
10743 * allocation didn't subsequently take the space due
10744 * to an error or false predicate evaluation. In this
10745 * case, we'll just leave the wrapped offset alone: if
10746 * the wrapped offset hasn't been advanced far enough
10747 * for this allocation, it will be adjusted in the
10748 * lower loop.
10749 */
10750 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10751 if (woffs >= offs)
10752 woffs = 0;
10753 } else {
10754 woffs = 0;
10755 }
10756
10757 /*
10758 * Now we know that we're going to be storing to the
10759 * top of the buffer and that there is room for us
10760 * there. We need to clear the buffer from the current
10761 * offset to the end (there may be old gunk there).
10762 */
10763 while (offs < buf->dtb_size)
10764 tomax[offs++] = 0;
10765
10766 /*
10767 * We need to set our offset to zero. And because we
10768 * are wrapping, we need to set the bit indicating as
10769 * much. We can also adjust our needed space back
10770 * down to the space required by the ECB -- we know
10771 * that the top of the buffer is aligned.
10772 */
10773 offs = 0;
10774 total = needed;
10775 buf->dtb_flags |= DTRACEBUF_WRAPPED;
10776 } else {
10777 /*
10778 * There is room for us in the buffer, so we simply
10779 * need to check the wrapped offset.
10780 */
10781 if (woffs < offs) {
10782 /*
10783 * The wrapped offset is less than the offset.
10784 * This can happen if we allocated buffer space
10785 * that induced a wrap, but then we didn't
10786 * subsequently take the space due to an error
10787 * or false predicate evaluation. This is
10788 * okay; we know that _this_ allocation isn't
10789 * going to induce a wrap. We still can't
10790 * reset the wrapped offset to be zero,
10791 * however: the space may have been trashed in
10792 * the previous failed probe attempt. But at
10793 * least the wrapped offset doesn't need to
10794 * be adjusted at all...
10795 */
10796 goto out;
10797 }
10798 }
10799
10800 while (offs + total > woffs) {
10801 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10802 size_t size;
10803
10804 if (epid == DTRACE_EPIDNONE) {
10805 size = sizeof (uint32_t);
10806 } else {
10807 ASSERT3U(epid, <=, state->dts_necbs);
10808 ASSERT(state->dts_ecbs[epid - 1] != NULL);
10809
10810 size = state->dts_ecbs[epid - 1]->dte_size;
10811 }
10812
10813 ASSERT(woffs + size <= buf->dtb_size);
10814 ASSERT(size != 0);
10815
10816 if (woffs + size == buf->dtb_size) {
10817 /*
10818 * We've reached the end of the buffer; we want
10819 * to set the wrapped offset to 0 and break
10820 * out. However, if the offs is 0, then we're
10821 * in a strange edge-condition: the amount of
10822 * space that we want to reserve plus the size
10823 * of the record that we're overwriting is
10824 * greater than the size of the buffer. This
10825 * is problematic because if we reserve the
10826 * space but subsequently don't consume it (due
10827 * to a failed predicate or error) the wrapped
10828 * offset will be 0 -- yet the EPID at offset 0
10829 * will not be committed. This situation is
10830 * relatively easy to deal with: if we're in
10831 * this case, the buffer is indistinguishable
10832 * from one that hasn't wrapped; we need only
10833 * finish the job by clearing the wrapped bit,
10834 * explicitly setting the offset to be 0, and
10835 * zero'ing out the old data in the buffer.
10836 */
10837 if (offs == 0) {
10838 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10839 buf->dtb_offset = 0;
10840 woffs = total;
10841
10842 while (woffs < buf->dtb_size)
10843 tomax[woffs++] = 0;
10844 }
10845
10846 woffs = 0;
10847 break;
10848 }
10849
10850 woffs += size;
10851 }
10852
10853 /*
10854 * We have a wrapped offset. It may be that the wrapped offset
10855 * has become zero -- that's okay.
10856 */
10857 buf->dtb_xamot_offset = woffs;
10858 }
10859
10860 out:
10861 /*
10862 * Now we can plow the buffer with any necessary padding.
10863 */
10864 while (offs & (align - 1)) {
10865 /*
10866 * Assert that our alignment is off by a number which
10867 * is itself sizeof (uint32_t) aligned.
10868 */
10869 ASSERT(!((align - (offs & (align - 1))) &
10870 (sizeof (uint32_t) - 1)));
10871 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10872 offs += sizeof (uint32_t);
10873 }
10874
10875 if (buf->dtb_flags & DTRACEBUF_FILL) {
10876 if (offs + needed > buf->dtb_size - state->dts_reserve) {
10877 buf->dtb_flags |= DTRACEBUF_FULL;
10878 return (-1);
10879 }
10880 }
10881
10882 if (mstate == NULL)
10883 return (offs);
10884
10885 /*
10886 * For ring buffers and fill buffers, the scratch space is always
10887 * the inactive buffer.
10888 */
10889 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10890 mstate->dtms_scratch_size = buf->dtb_size;
10891 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10892
10893 return (offs);
10894 }
10895
10896 static void
10897 dtrace_buffer_polish(dtrace_buffer_t *buf)
10898 {
10899 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10900 ASSERT(MUTEX_HELD(&dtrace_lock));
10901
10902 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10903 return;
10904
10905 /*
10906 * We need to polish the ring buffer. There are three cases:
10907 *
10908 * - The first (and presumably most common) is that there is no gap
10909 * between the buffer offset and the wrapped offset. In this case,
10910 * there is nothing in the buffer that isn't valid data; we can
10911 * mark the buffer as polished and return.
10912 *
10913 * - The second (less common than the first but still more common
10914 * than the third) is that there is a gap between the buffer offset
10915 * and the wrapped offset, and the wrapped offset is larger than the
10916 * buffer offset. This can happen because of an alignment issue, or
10917 * can happen because of a call to dtrace_buffer_reserve() that
10918 * didn't subsequently consume the buffer space. In this case,
10919 * we need to zero the data from the buffer offset to the wrapped
10920 * offset.
10921 *
10922 * - The third (and least common) is that there is a gap between the
10923 * buffer offset and the wrapped offset, but the wrapped offset is
10924 * _less_ than the buffer offset. This can only happen because a
10925 * call to dtrace_buffer_reserve() induced a wrap, but the space
10926 * was not subsequently consumed. In this case, we need to zero the
10927 * space from the offset to the end of the buffer _and_ from the
10928 * top of the buffer to the wrapped offset.
10929 */
10930 if (buf->dtb_offset < buf->dtb_xamot_offset) {
10931 bzero(buf->dtb_tomax + buf->dtb_offset,
10932 buf->dtb_xamot_offset - buf->dtb_offset);
10933 }
10934
10935 if (buf->dtb_offset > buf->dtb_xamot_offset) {
10936 bzero(buf->dtb_tomax + buf->dtb_offset,
10937 buf->dtb_size - buf->dtb_offset);
10938 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10939 }
10940 }
10941
10942 /*
10943 * This routine determines if data generated at the specified time has likely
10944 * been entirely consumed at user-level. This routine is called to determine
10945 * if an ECB on a defunct probe (but for an active enabling) can be safely
10946 * disabled and destroyed.
10947 */
10948 static int
10949 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
10950 {
10951 int i;
10952
10953 for (i = 0; i < NCPU; i++) {
10954 dtrace_buffer_t *buf = &bufs[i];
10955
10956 if (buf->dtb_size == 0)
10957 continue;
10958
10959 if (buf->dtb_flags & DTRACEBUF_RING)
10960 return (0);
10961
10962 if (!buf->dtb_switched && buf->dtb_offset != 0)
10963 return (0);
10964
10965 if (buf->dtb_switched - buf->dtb_interval < when)
10966 return (0);
10967 }
10968
10969 return (1);
10970 }
10971
10972 static void
10973 dtrace_buffer_free(dtrace_buffer_t *bufs)
10974 {
10975 int i;
10976
10977 for (i = 0; i < NCPU; i++) {
10978 dtrace_buffer_t *buf = &bufs[i];
10979
10980 if (buf->dtb_tomax == NULL) {
10981 ASSERT(buf->dtb_xamot == NULL);
10982 ASSERT(buf->dtb_size == 0);
10983 continue;
10984 }
10985
10986 if (buf->dtb_xamot != NULL) {
10987 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10988 kmem_free(buf->dtb_xamot, buf->dtb_size);
10989 }
10990
10991 kmem_free(buf->dtb_tomax, buf->dtb_size);
10992 buf->dtb_size = 0;
10993 buf->dtb_tomax = NULL;
10994 buf->dtb_xamot = NULL;
10995 }
10996 }
10997
10998 /*
10999 * DTrace Enabling Functions
11000 */
11001 static dtrace_enabling_t *
11002 dtrace_enabling_create(dtrace_vstate_t *vstate)
11003 {
11004 dtrace_enabling_t *enab;
11005
11006 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11007 enab->dten_vstate = vstate;
11008
11009 return (enab);
11010 }
11011
11012 static void
11013 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11014 {
11015 dtrace_ecbdesc_t **ndesc;
11016 size_t osize, nsize;
11017
11018 /*
11019 * We can't add to enablings after we've enabled them, or after we've
11020 * retained them.
11021 */
11022 ASSERT(enab->dten_probegen == 0);
11023 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11024
11025 if (enab->dten_ndesc < enab->dten_maxdesc) {
11026 enab->dten_desc[enab->dten_ndesc++] = ecb;
11027 return;
11028 }
11029
11030 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11031
11032 if (enab->dten_maxdesc == 0) {
11033 enab->dten_maxdesc = 1;
11034 } else {
11035 enab->dten_maxdesc <<= 1;
11036 }
11037
11038 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11039
11040 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11041 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11042 bcopy(enab->dten_desc, ndesc, osize);
11043 kmem_free(enab->dten_desc, osize);
11044
11045 enab->dten_desc = ndesc;
11046 enab->dten_desc[enab->dten_ndesc++] = ecb;
11047 }
11048
11049 static void
11050 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11051 dtrace_probedesc_t *pd)
11052 {
11053 dtrace_ecbdesc_t *new;
11054 dtrace_predicate_t *pred;
11055 dtrace_actdesc_t *act;
11056
11057 /*
11058 * We're going to create a new ECB description that matches the
11059 * specified ECB in every way, but has the specified probe description.
11060 */
11061 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11062
11063 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11064 dtrace_predicate_hold(pred);
11065
11066 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11067 dtrace_actdesc_hold(act);
11068
11069 new->dted_action = ecb->dted_action;
11070 new->dted_pred = ecb->dted_pred;
11071 new->dted_probe = *pd;
11072 new->dted_uarg = ecb->dted_uarg;
11073
11074 dtrace_enabling_add(enab, new);
11075 }
11076
11077 static void
11078 dtrace_enabling_dump(dtrace_enabling_t *enab)
11079 {
11080 int i;
11081
11082 for (i = 0; i < enab->dten_ndesc; i++) {
11083 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11084
11085 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11086 desc->dtpd_provider, desc->dtpd_mod,
11087 desc->dtpd_func, desc->dtpd_name);
11088 }
11089 }
11090
11091 static void
11092 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11093 {
11094 int i;
11095 dtrace_ecbdesc_t *ep;
11096 dtrace_vstate_t *vstate = enab->dten_vstate;
11097
11098 ASSERT(MUTEX_HELD(&dtrace_lock));
11099
11100 for (i = 0; i < enab->dten_ndesc; i++) {
11101 dtrace_actdesc_t *act, *next;
11102 dtrace_predicate_t *pred;
11103
11104 ep = enab->dten_desc[i];
11105
11106 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11107 dtrace_predicate_release(pred, vstate);
11108
11109 for (act = ep->dted_action; act != NULL; act = next) {
11110 next = act->dtad_next;
11111 dtrace_actdesc_release(act, vstate);
11112 }
11113
11114 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11115 }
11116
11117 kmem_free(enab->dten_desc,
11118 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11119
11120 /*
11121 * If this was a retained enabling, decrement the dts_nretained count
11122 * and take it off of the dtrace_retained list.
11123 */
11124 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11125 dtrace_retained == enab) {
11126 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11127 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11128 enab->dten_vstate->dtvs_state->dts_nretained--;
11129 dtrace_retained_gen++;
11130 }
11131
11132 if (enab->dten_prev == NULL) {
11133 if (dtrace_retained == enab) {
11134 dtrace_retained = enab->dten_next;
11135
11136 if (dtrace_retained != NULL)
11137 dtrace_retained->dten_prev = NULL;
11138 }
11139 } else {
11140 ASSERT(enab != dtrace_retained);
11141 ASSERT(dtrace_retained != NULL);
11142 enab->dten_prev->dten_next = enab->dten_next;
11143 }
11144
11145 if (enab->dten_next != NULL) {
11146 ASSERT(dtrace_retained != NULL);
11147 enab->dten_next->dten_prev = enab->dten_prev;
11148 }
11149
11150 kmem_free(enab, sizeof (dtrace_enabling_t));
11151 }
11152
11153 static int
11154 dtrace_enabling_retain(dtrace_enabling_t *enab)
11155 {
11156 dtrace_state_t *state;
11157
11158 ASSERT(MUTEX_HELD(&dtrace_lock));
11159 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11160 ASSERT(enab->dten_vstate != NULL);
11161
11162 state = enab->dten_vstate->dtvs_state;
11163 ASSERT(state != NULL);
11164
11165 /*
11166 * We only allow each state to retain dtrace_retain_max enablings.
11167 */
11168 if (state->dts_nretained >= dtrace_retain_max)
11169 return (ENOSPC);
11170
11171 state->dts_nretained++;
11172 dtrace_retained_gen++;
11173
11174 if (dtrace_retained == NULL) {
11175 dtrace_retained = enab;
11176 return (0);
11177 }
11178
11179 enab->dten_next = dtrace_retained;
11180 dtrace_retained->dten_prev = enab;
11181 dtrace_retained = enab;
11182
11183 return (0);
11184 }
11185
11186 static int
11187 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11188 dtrace_probedesc_t *create)
11189 {
11190 dtrace_enabling_t *new, *enab;
11191 int found = 0, err = ENOENT;
11192
11193 ASSERT(MUTEX_HELD(&dtrace_lock));
11194 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11195 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11196 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11197 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11198
11199 new = dtrace_enabling_create(&state->dts_vstate);
11200
11201 /*
11202 * Iterate over all retained enablings, looking for enablings that
11203 * match the specified state.
11204 */
11205 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11206 int i;
11207
11208 /*
11209 * dtvs_state can only be NULL for helper enablings -- and
11210 * helper enablings can't be retained.
11211 */
11212 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11213
11214 if (enab->dten_vstate->dtvs_state != state)
11215 continue;
11216
11217 /*
11218 * Now iterate over each probe description; we're looking for
11219 * an exact match to the specified probe description.
11220 */
11221 for (i = 0; i < enab->dten_ndesc; i++) {
11222 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11223 dtrace_probedesc_t *pd = &ep->dted_probe;
11224
11225 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11226 continue;
11227
11228 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11229 continue;
11230
11231 if (strcmp(pd->dtpd_func, match->dtpd_func))
11232 continue;
11233
11234 if (strcmp(pd->dtpd_name, match->dtpd_name))
11235 continue;
11236
11237 /*
11238 * We have a winning probe! Add it to our growing
11239 * enabling.
11240 */
11241 found = 1;
11242 dtrace_enabling_addlike(new, ep, create);
11243 }
11244 }
11245
11246 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11247 dtrace_enabling_destroy(new);
11248 return (err);
11249 }
11250
11251 return (0);
11252 }
11253
11254 static void
11255 dtrace_enabling_retract(dtrace_state_t *state)
11256 {
11257 dtrace_enabling_t *enab, *next;
11258
11259 ASSERT(MUTEX_HELD(&dtrace_lock));
11260
11261 /*
11262 * Iterate over all retained enablings, destroy the enablings retained
11263 * for the specified state.
11264 */
11265 for (enab = dtrace_retained; enab != NULL; enab = next) {
11266 next = enab->dten_next;
11267
11268 /*
11269 * dtvs_state can only be NULL for helper enablings -- and
11270 * helper enablings can't be retained.
11271 */
11272 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11273
11274 if (enab->dten_vstate->dtvs_state == state) {
11275 ASSERT(state->dts_nretained > 0);
11276 dtrace_enabling_destroy(enab);
11277 }
11278 }
11279
11280 ASSERT(state->dts_nretained == 0);
11281 }
11282
11283 static int
11284 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11285 {
11286 int i = 0;
11287 int total_matched = 0, matched = 0;
11288
11289 ASSERT(MUTEX_HELD(&cpu_lock));
11290 ASSERT(MUTEX_HELD(&dtrace_lock));
11291
11292 for (i = 0; i < enab->dten_ndesc; i++) {
11293 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11294
11295 enab->dten_current = ep;
11296 enab->dten_error = 0;
11297
11298 /*
11299 * If a provider failed to enable a probe then get out and
11300 * let the consumer know we failed.
11301 */
11302 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11303 return (EBUSY);
11304
11305 total_matched += matched;
11306
11307 if (enab->dten_error != 0) {
11308 /*
11309 * If we get an error half-way through enabling the
11310 * probes, we kick out -- perhaps with some number of
11311 * them enabled. Leaving enabled probes enabled may
11312 * be slightly confusing for user-level, but we expect
11313 * that no one will attempt to actually drive on in
11314 * the face of such errors. If this is an anonymous
11315 * enabling (indicated with a NULL nmatched pointer),
11316 * we cmn_err() a message. We aren't expecting to
11317 * get such an error -- such as it can exist at all,
11318 * it would be a result of corrupted DOF in the driver
11319 * properties.
11320 */
11321 if (nmatched == NULL) {
11322 cmn_err(CE_WARN, "dtrace_enabling_match() "
11323 "error on %p: %d", (void *)ep,
11324 enab->dten_error);
11325 }
11326
11327 return (enab->dten_error);
11328 }
11329 }
11330
11331 enab->dten_probegen = dtrace_probegen;
11332 if (nmatched != NULL)
11333 *nmatched = total_matched;
11334
11335 return (0);
11336 }
11337
11338 static void
11339 dtrace_enabling_matchall(void)
11340 {
11341 dtrace_enabling_t *enab;
11342
11343 mutex_enter(&cpu_lock);
11344 mutex_enter(&dtrace_lock);
11345
11346 /*
11347 * Iterate over all retained enablings to see if any probes match
11348 * against them. We only perform this operation on enablings for which
11349 * we have sufficient permissions by virtue of being in the global zone
11350 * or in the same zone as the DTrace client. Because we can be called
11351 * after dtrace_detach() has been called, we cannot assert that there
11352 * are retained enablings. We can safely load from dtrace_retained,
11353 * however: the taskq_destroy() at the end of dtrace_detach() will
11354 * block pending our completion.
11355 */
11356 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11357 dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
11358 cred_t *cr = dcr->dcr_cred;
11359 zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
11360
11361 if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
11362 (zone == GLOBAL_ZONEID || getzoneid() == zone)))
11363 (void) dtrace_enabling_match(enab, NULL);
11364 }
11365
11366 mutex_exit(&dtrace_lock);
11367 mutex_exit(&cpu_lock);
11368 }
11369
11370 /*
11371 * If an enabling is to be enabled without having matched probes (that is, if
11372 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11373 * enabling must be _primed_ by creating an ECB for every ECB description.
11374 * This must be done to assure that we know the number of speculations, the
11375 * number of aggregations, the minimum buffer size needed, etc. before we
11376 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11377 * enabling any probes, we create ECBs for every ECB decription, but with a
11378 * NULL probe -- which is exactly what this function does.
11379 */
11380 static void
11381 dtrace_enabling_prime(dtrace_state_t *state)
11382 {
11383 dtrace_enabling_t *enab;
11384 int i;
11385
11386 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11387 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11388
11389 if (enab->dten_vstate->dtvs_state != state)
11390 continue;
11391
11392 /*
11393 * We don't want to prime an enabling more than once, lest
11394 * we allow a malicious user to induce resource exhaustion.
11395 * (The ECBs that result from priming an enabling aren't
11396 * leaked -- but they also aren't deallocated until the
11397 * consumer state is destroyed.)
11398 */
11399 if (enab->dten_primed)
11400 continue;
11401
11402 for (i = 0; i < enab->dten_ndesc; i++) {
11403 enab->dten_current = enab->dten_desc[i];
11404 (void) dtrace_probe_enable(NULL, enab);
11405 }
11406
11407 enab->dten_primed = 1;
11408 }
11409 }
11410
11411 /*
11412 * Called to indicate that probes should be provided due to retained
11413 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
11414 * must take an initial lap through the enabling calling the dtps_provide()
11415 * entry point explicitly to allow for autocreated probes.
11416 */
11417 static void
11418 dtrace_enabling_provide(dtrace_provider_t *prv)
11419 {
11420 int i, all = 0;
11421 dtrace_probedesc_t desc;
11422 dtrace_genid_t gen;
11423
11424 ASSERT(MUTEX_HELD(&dtrace_lock));
11425 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11426
11427 if (prv == NULL) {
11428 all = 1;
11429 prv = dtrace_provider;
11430 }
11431
11432 do {
11433 dtrace_enabling_t *enab;
11434 void *parg = prv->dtpv_arg;
11435
11436 retry:
11437 gen = dtrace_retained_gen;
11438 for (enab = dtrace_retained; enab != NULL;
11439 enab = enab->dten_next) {
11440 for (i = 0; i < enab->dten_ndesc; i++) {
11441 desc = enab->dten_desc[i]->dted_probe;
11442 mutex_exit(&dtrace_lock);
11443 prv->dtpv_pops.dtps_provide(parg, &desc);
11444 mutex_enter(&dtrace_lock);
11445 /*
11446 * Process the retained enablings again if
11447 * they have changed while we weren't holding
11448 * dtrace_lock.
11449 */
11450 if (gen != dtrace_retained_gen)
11451 goto retry;
11452 }
11453 }
11454 } while (all && (prv = prv->dtpv_next) != NULL);
11455
11456 mutex_exit(&dtrace_lock);
11457 dtrace_probe_provide(NULL, all ? NULL : prv);
11458 mutex_enter(&dtrace_lock);
11459 }
11460
11461 /*
11462 * Called to reap ECBs that are attached to probes from defunct providers.
11463 */
11464 static void
11465 dtrace_enabling_reap(void)
11466 {
11467 dtrace_provider_t *prov;
11468 dtrace_probe_t *probe;
11469 dtrace_ecb_t *ecb;
11470 hrtime_t when;
11471 int i;
11472
11473 mutex_enter(&cpu_lock);
11474 mutex_enter(&dtrace_lock);
11475
11476 for (i = 0; i < dtrace_nprobes; i++) {
11477 if ((probe = dtrace_probes[i]) == NULL)
11478 continue;
11479
11480 if (probe->dtpr_ecb == NULL)
11481 continue;
11482
11483 prov = probe->dtpr_provider;
11484
11485 if ((when = prov->dtpv_defunct) == 0)
11486 continue;
11487
11488 /*
11489 * We have ECBs on a defunct provider: we want to reap these
11490 * ECBs to allow the provider to unregister. The destruction
11491 * of these ECBs must be done carefully: if we destroy the ECB
11492 * and the consumer later wishes to consume an EPID that
11493 * corresponds to the destroyed ECB (and if the EPID metadata
11494 * has not been previously consumed), the consumer will abort
11495 * processing on the unknown EPID. To reduce (but not, sadly,
11496 * eliminate) the possibility of this, we will only destroy an
11497 * ECB for a defunct provider if, for the state that
11498 * corresponds to the ECB:
11499 *
11500 * (a) There is no speculative tracing (which can effectively
11501 * cache an EPID for an arbitrary amount of time).
11502 *
11503 * (b) The principal buffers have been switched twice since the
11504 * provider became defunct.
11505 *
11506 * (c) The aggregation buffers are of zero size or have been
11507 * switched twice since the provider became defunct.
11508 *
11509 * We use dts_speculates to determine (a) and call a function
11510 * (dtrace_buffer_consumed()) to determine (b) and (c). Note
11511 * that as soon as we've been unable to destroy one of the ECBs
11512 * associated with the probe, we quit trying -- reaping is only
11513 * fruitful in as much as we can destroy all ECBs associated
11514 * with the defunct provider's probes.
11515 */
11516 while ((ecb = probe->dtpr_ecb) != NULL) {
11517 dtrace_state_t *state = ecb->dte_state;
11518 dtrace_buffer_t *buf = state->dts_buffer;
11519 dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
11520
11521 if (state->dts_speculates)
11522 break;
11523
11524 if (!dtrace_buffer_consumed(buf, when))
11525 break;
11526
11527 if (!dtrace_buffer_consumed(aggbuf, when))
11528 break;
11529
11530 dtrace_ecb_disable(ecb);
11531 ASSERT(probe->dtpr_ecb != ecb);
11532 dtrace_ecb_destroy(ecb);
11533 }
11534 }
11535
11536 mutex_exit(&dtrace_lock);
11537 mutex_exit(&cpu_lock);
11538 }
11539
11540 /*
11541 * DTrace DOF Functions
11542 */
11543 /*ARGSUSED*/
11544 static void
11545 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11546 {
11547 if (dtrace_err_verbose)
11548 cmn_err(CE_WARN, "failed to process DOF: %s", str);
11549
11550 #ifdef DTRACE_ERRDEBUG
11551 dtrace_errdebug(str);
11552 #endif
11553 }
11554
11555 /*
11556 * Create DOF out of a currently enabled state. Right now, we only create
11557 * DOF containing the run-time options -- but this could be expanded to create
11558 * complete DOF representing the enabled state.
11559 */
11560 static dof_hdr_t *
11561 dtrace_dof_create(dtrace_state_t *state)
11562 {
11563 dof_hdr_t *dof;
11564 dof_sec_t *sec;
11565 dof_optdesc_t *opt;
11566 int i, len = sizeof (dof_hdr_t) +
11567 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11568 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11569
11570 ASSERT(MUTEX_HELD(&dtrace_lock));
11571
11572 dof = kmem_zalloc(len, KM_SLEEP);
11573 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11574 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11575 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11576 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11577
11578 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11579 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11580 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11581 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11582 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11583 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11584
11585 dof->dofh_flags = 0;
11586 dof->dofh_hdrsize = sizeof (dof_hdr_t);
11587 dof->dofh_secsize = sizeof (dof_sec_t);
11588 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
11589 dof->dofh_secoff = sizeof (dof_hdr_t);
11590 dof->dofh_loadsz = len;
11591 dof->dofh_filesz = len;
11592 dof->dofh_pad = 0;
11593
11594 /*
11595 * Fill in the option section header...
11596 */
11597 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11598 sec->dofs_type = DOF_SECT_OPTDESC;
11599 sec->dofs_align = sizeof (uint64_t);
11600 sec->dofs_flags = DOF_SECF_LOAD;
11601 sec->dofs_entsize = sizeof (dof_optdesc_t);
11602
11603 opt = (dof_optdesc_t *)((uintptr_t)sec +
11604 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11605
11606 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11607 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11608
11609 for (i = 0; i < DTRACEOPT_MAX; i++) {
11610 opt[i].dofo_option = i;
11611 opt[i].dofo_strtab = DOF_SECIDX_NONE;
11612 opt[i].dofo_value = state->dts_options[i];
11613 }
11614
11615 return (dof);
11616 }
11617
11618 static dof_hdr_t *
11619 dtrace_dof_copyin(uintptr_t uarg, int *errp)
11620 {
11621 dof_hdr_t hdr, *dof;
11622
11623 ASSERT(!MUTEX_HELD(&dtrace_lock));
11624
11625 /*
11626 * First, we're going to copyin() the sizeof (dof_hdr_t).
11627 */
11628 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11629 dtrace_dof_error(NULL, "failed to copyin DOF header");
11630 *errp = EFAULT;
11631 return (NULL);
11632 }
11633
11634 /*
11635 * Now we'll allocate the entire DOF and copy it in -- provided
11636 * that the length isn't outrageous.
11637 */
11638 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
11639 dtrace_dof_error(&hdr, "load size exceeds maximum");
11640 *errp = E2BIG;
11641 return (NULL);
11642 }
11643
11644 if (hdr.dofh_loadsz < sizeof (hdr)) {
11645 dtrace_dof_error(&hdr, "invalid load size");
11646 *errp = EINVAL;
11647 return (NULL);
11648 }
11649
11650 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
11651
11652 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
11653 dof->dofh_loadsz != hdr.dofh_loadsz) {
11654 kmem_free(dof, hdr.dofh_loadsz);
11655 *errp = EFAULT;
11656 return (NULL);
11657 }
11658
11659 return (dof);
11660 }
11661
11662 static dof_hdr_t *
11663 dtrace_dof_property(const char *name)
11664 {
11665 uchar_t *buf;
11666 uint64_t loadsz;
11667 unsigned int len, i;
11668 dof_hdr_t *dof;
11669
11670 /*
11671 * Unfortunately, array of values in .conf files are always (and
11672 * only) interpreted to be integer arrays. We must read our DOF
11673 * as an integer array, and then squeeze it into a byte array.
11674 */
11675 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
11676 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
11677 return (NULL);
11678
11679 for (i = 0; i < len; i++)
11680 buf[i] = (uchar_t)(((int *)buf)[i]);
11681
11682 if (len < sizeof (dof_hdr_t)) {
11683 ddi_prop_free(buf);
11684 dtrace_dof_error(NULL, "truncated header");
11685 return (NULL);
11686 }
11687
11688 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
11689 ddi_prop_free(buf);
11690 dtrace_dof_error(NULL, "truncated DOF");
11691 return (NULL);
11692 }
11693
11694 if (loadsz >= dtrace_dof_maxsize) {
11695 ddi_prop_free(buf);
11696 dtrace_dof_error(NULL, "oversized DOF");
11697 return (NULL);
11698 }
11699
11700 dof = kmem_alloc(loadsz, KM_SLEEP);
11701 bcopy(buf, dof, loadsz);
11702 ddi_prop_free(buf);
11703
11704 return (dof);
11705 }
11706
11707 static void
11708 dtrace_dof_destroy(dof_hdr_t *dof)
11709 {
11710 kmem_free(dof, dof->dofh_loadsz);
11711 }
11712
11713 /*
11714 * Return the dof_sec_t pointer corresponding to a given section index. If the
11715 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
11716 * a type other than DOF_SECT_NONE is specified, the header is checked against
11717 * this type and NULL is returned if the types do not match.
11718 */
11719 static dof_sec_t *
11720 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
11721 {
11722 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
11723 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
11724
11725 if (i >= dof->dofh_secnum) {
11726 dtrace_dof_error(dof, "referenced section index is invalid");
11727 return (NULL);
11728 }
11729
11730 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
11731 dtrace_dof_error(dof, "referenced section is not loadable");
11732 return (NULL);
11733 }
11734
11735 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
11736 dtrace_dof_error(dof, "referenced section is the wrong type");
11737 return (NULL);
11738 }
11739
11740 return (sec);
11741 }
11742
11743 static dtrace_probedesc_t *
11744 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
11745 {
11746 dof_probedesc_t *probe;
11747 dof_sec_t *strtab;
11748 uintptr_t daddr = (uintptr_t)dof;
11749 uintptr_t str;
11750 size_t size;
11751
11752 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
11753 dtrace_dof_error(dof, "invalid probe section");
11754 return (NULL);
11755 }
11756
11757 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11758 dtrace_dof_error(dof, "bad alignment in probe description");
11759 return (NULL);
11760 }
11761
11762 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
11763 dtrace_dof_error(dof, "truncated probe description");
11764 return (NULL);
11765 }
11766
11767 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
11768 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
11769
11770 if (strtab == NULL)
11771 return (NULL);
11772
11773 str = daddr + strtab->dofs_offset;
11774 size = strtab->dofs_size;
11775
11776 if (probe->dofp_provider >= strtab->dofs_size) {
11777 dtrace_dof_error(dof, "corrupt probe provider");
11778 return (NULL);
11779 }
11780
11781 (void) strncpy(desc->dtpd_provider,
11782 (char *)(str + probe->dofp_provider),
11783 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11784
11785 if (probe->dofp_mod >= strtab->dofs_size) {
11786 dtrace_dof_error(dof, "corrupt probe module");
11787 return (NULL);
11788 }
11789
11790 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11791 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11792
11793 if (probe->dofp_func >= strtab->dofs_size) {
11794 dtrace_dof_error(dof, "corrupt probe function");
11795 return (NULL);
11796 }
11797
11798 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11799 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11800
11801 if (probe->dofp_name >= strtab->dofs_size) {
11802 dtrace_dof_error(dof, "corrupt probe name");
11803 return (NULL);
11804 }
11805
11806 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11807 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11808
11809 return (desc);
11810 }
11811
11812 static dtrace_difo_t *
11813 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11814 cred_t *cr)
11815 {
11816 dtrace_difo_t *dp;
11817 size_t ttl = 0;
11818 dof_difohdr_t *dofd;
11819 uintptr_t daddr = (uintptr_t)dof;
11820 size_t max = dtrace_difo_maxsize;
11821 int i, l, n;
11822
11823 static const struct {
11824 int section;
11825 int bufoffs;
11826 int lenoffs;
11827 int entsize;
11828 int align;
11829 const char *msg;
11830 } difo[] = {
11831 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11832 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11833 sizeof (dif_instr_t), "multiple DIF sections" },
11834
11835 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11836 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11837 sizeof (uint64_t), "multiple integer tables" },
11838
11839 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11840 offsetof(dtrace_difo_t, dtdo_strlen), 0,
11841 sizeof (char), "multiple string tables" },
11842
11843 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11844 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11845 sizeof (uint_t), "multiple variable tables" },
11846
11847 { DOF_SECT_NONE, 0, 0, 0, NULL }
11848 };
11849
11850 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11851 dtrace_dof_error(dof, "invalid DIFO header section");
11852 return (NULL);
11853 }
11854
11855 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11856 dtrace_dof_error(dof, "bad alignment in DIFO header");
11857 return (NULL);
11858 }
11859
11860 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11861 sec->dofs_size % sizeof (dof_secidx_t)) {
11862 dtrace_dof_error(dof, "bad size in DIFO header");
11863 return (NULL);
11864 }
11865
11866 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11867 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11868
11869 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11870 dp->dtdo_rtype = dofd->dofd_rtype;
11871
11872 for (l = 0; l < n; l++) {
11873 dof_sec_t *subsec;
11874 void **bufp;
11875 uint32_t *lenp;
11876
11877 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11878 dofd->dofd_links[l])) == NULL)
11879 goto err; /* invalid section link */
11880
11881 if (ttl + subsec->dofs_size > max) {
11882 dtrace_dof_error(dof, "exceeds maximum size");
11883 goto err;
11884 }
11885
11886 ttl += subsec->dofs_size;
11887
11888 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11889 if (subsec->dofs_type != difo[i].section)
11890 continue;
11891
11892 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11893 dtrace_dof_error(dof, "section not loaded");
11894 goto err;
11895 }
11896
11897 if (subsec->dofs_align != difo[i].align) {
11898 dtrace_dof_error(dof, "bad alignment");
11899 goto err;
11900 }
11901
11902 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11903 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11904
11905 if (*bufp != NULL) {
11906 dtrace_dof_error(dof, difo[i].msg);
11907 goto err;
11908 }
11909
11910 if (difo[i].entsize != subsec->dofs_entsize) {
11911 dtrace_dof_error(dof, "entry size mismatch");
11912 goto err;
11913 }
11914
11915 if (subsec->dofs_entsize != 0 &&
11916 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11917 dtrace_dof_error(dof, "corrupt entry size");
11918 goto err;
11919 }
11920
11921 *lenp = subsec->dofs_size;
11922 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11923 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11924 *bufp, subsec->dofs_size);
11925
11926 if (subsec->dofs_entsize != 0)
11927 *lenp /= subsec->dofs_entsize;
11928
11929 break;
11930 }
11931
11932 /*
11933 * If we encounter a loadable DIFO sub-section that is not
11934 * known to us, assume this is a broken program and fail.
11935 */
11936 if (difo[i].section == DOF_SECT_NONE &&
11937 (subsec->dofs_flags & DOF_SECF_LOAD)) {
11938 dtrace_dof_error(dof, "unrecognized DIFO subsection");
11939 goto err;
11940 }
11941 }
11942
11943 if (dp->dtdo_buf == NULL) {
11944 /*
11945 * We can't have a DIF object without DIF text.
11946 */
11947 dtrace_dof_error(dof, "missing DIF text");
11948 goto err;
11949 }
11950
11951 /*
11952 * Before we validate the DIF object, run through the variable table
11953 * looking for the strings -- if any of their size are under, we'll set
11954 * their size to be the system-wide default string size. Note that
11955 * this should _not_ happen if the "strsize" option has been set --
11956 * in this case, the compiler should have set the size to reflect the
11957 * setting of the option.
11958 */
11959 for (i = 0; i < dp->dtdo_varlen; i++) {
11960 dtrace_difv_t *v = &dp->dtdo_vartab[i];
11961 dtrace_diftype_t *t = &v->dtdv_type;
11962
11963 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11964 continue;
11965
11966 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11967 t->dtdt_size = dtrace_strsize_default;
11968 }
11969
11970 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11971 goto err;
11972
11973 dtrace_difo_init(dp, vstate);
11974 return (dp);
11975
11976 err:
11977 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11978 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11979 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11980 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11981
11982 kmem_free(dp, sizeof (dtrace_difo_t));
11983 return (NULL);
11984 }
11985
11986 static dtrace_predicate_t *
11987 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11988 cred_t *cr)
11989 {
11990 dtrace_difo_t *dp;
11991
11992 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11993 return (NULL);
11994
11995 return (dtrace_predicate_create(dp));
11996 }
11997
11998 static dtrace_actdesc_t *
11999 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12000 cred_t *cr)
12001 {
12002 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12003 dof_actdesc_t *desc;
12004 dof_sec_t *difosec;
12005 size_t offs;
12006 uintptr_t daddr = (uintptr_t)dof;
12007 uint64_t arg;
12008 dtrace_actkind_t kind;
12009
12010 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12011 dtrace_dof_error(dof, "invalid action section");
12012 return (NULL);
12013 }
12014
12015 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12016 dtrace_dof_error(dof, "truncated action description");
12017 return (NULL);
12018 }
12019
12020 if (sec->dofs_align != sizeof (uint64_t)) {
12021 dtrace_dof_error(dof, "bad alignment in action description");
12022 return (NULL);
12023 }
12024
12025 if (sec->dofs_size < sec->dofs_entsize) {
12026 dtrace_dof_error(dof, "section entry size exceeds total size");
12027 return (NULL);
12028 }
12029
12030 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12031 dtrace_dof_error(dof, "bad entry size in action description");
12032 return (NULL);
12033 }
12034
12035 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12036 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12037 return (NULL);
12038 }
12039
12040 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12041 desc = (dof_actdesc_t *)(daddr +
12042 (uintptr_t)sec->dofs_offset + offs);
12043 kind = (dtrace_actkind_t)desc->dofa_kind;
12044
12045 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12046 (kind != DTRACEACT_PRINTA ||
12047 desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12048 (kind == DTRACEACT_DIFEXPR &&
12049 desc->dofa_strtab != DOF_SECIDX_NONE)) {
12050 dof_sec_t *strtab;
12051 char *str, *fmt;
12052 uint64_t i;
12053
12054 /*
12055 * The argument to these actions is an index into the
12056 * DOF string table. For printf()-like actions, this
12057 * is the format string. For print(), this is the
12058 * CTF type of the expression result.
12059 */
12060 if ((strtab = dtrace_dof_sect(dof,
12061 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12062 goto err;
12063
12064 str = (char *)((uintptr_t)dof +
12065 (uintptr_t)strtab->dofs_offset);
12066
12067 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12068 if (str[i] == '\0')
12069 break;
12070 }
12071
12072 if (i >= strtab->dofs_size) {
12073 dtrace_dof_error(dof, "bogus format string");
12074 goto err;
12075 }
12076
12077 if (i == desc->dofa_arg) {
12078 dtrace_dof_error(dof, "empty format string");
12079 goto err;
12080 }
12081
12082 i -= desc->dofa_arg;
12083 fmt = kmem_alloc(i + 1, KM_SLEEP);
12084 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12085 arg = (uint64_t)(uintptr_t)fmt;
12086 } else {
12087 if (kind == DTRACEACT_PRINTA) {
12088 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12089 arg = 0;
12090 } else {
12091 arg = desc->dofa_arg;
12092 }
12093 }
12094
12095 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12096 desc->dofa_uarg, arg);
12097
12098 if (last != NULL) {
12099 last->dtad_next = act;
12100 } else {
12101 first = act;
12102 }
12103
12104 last = act;
12105
12106 if (desc->dofa_difo == DOF_SECIDX_NONE)
12107 continue;
12108
12109 if ((difosec = dtrace_dof_sect(dof,
12110 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12111 goto err;
12112
12113 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12114
12115 if (act->dtad_difo == NULL)
12116 goto err;
12117 }
12118
12119 ASSERT(first != NULL);
12120 return (first);
12121
12122 err:
12123 for (act = first; act != NULL; act = next) {
12124 next = act->dtad_next;
12125 dtrace_actdesc_release(act, vstate);
12126 }
12127
12128 return (NULL);
12129 }
12130
12131 static dtrace_ecbdesc_t *
12132 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12133 cred_t *cr)
12134 {
12135 dtrace_ecbdesc_t *ep;
12136 dof_ecbdesc_t *ecb;
12137 dtrace_probedesc_t *desc;
12138 dtrace_predicate_t *pred = NULL;
12139
12140 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12141 dtrace_dof_error(dof, "truncated ECB description");
12142 return (NULL);
12143 }
12144
12145 if (sec->dofs_align != sizeof (uint64_t)) {
12146 dtrace_dof_error(dof, "bad alignment in ECB description");
12147 return (NULL);
12148 }
12149
12150 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12151 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12152
12153 if (sec == NULL)
12154 return (NULL);
12155
12156 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12157 ep->dted_uarg = ecb->dofe_uarg;
12158 desc = &ep->dted_probe;
12159
12160 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12161 goto err;
12162
12163 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12164 if ((sec = dtrace_dof_sect(dof,
12165 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12166 goto err;
12167
12168 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12169 goto err;
12170
12171 ep->dted_pred.dtpdd_predicate = pred;
12172 }
12173
12174 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12175 if ((sec = dtrace_dof_sect(dof,
12176 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12177 goto err;
12178
12179 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12180
12181 if (ep->dted_action == NULL)
12182 goto err;
12183 }
12184
12185 return (ep);
12186
12187 err:
12188 if (pred != NULL)
12189 dtrace_predicate_release(pred, vstate);
12190 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12191 return (NULL);
12192 }
12193
12194 /*
12195 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12196 * specified DOF. At present, this amounts to simply adding 'ubase' to the
12197 * site of any user SETX relocations to account for load object base address.
12198 * In the future, if we need other relocations, this function can be extended.
12199 */
12200 static int
12201 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12202 {
12203 uintptr_t daddr = (uintptr_t)dof;
12204 dof_relohdr_t *dofr =
12205 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12206 dof_sec_t *ss, *rs, *ts;
12207 dof_relodesc_t *r;
12208 uint_t i, n;
12209
12210 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12211 sec->dofs_align != sizeof (dof_secidx_t)) {
12212 dtrace_dof_error(dof, "invalid relocation header");
12213 return (-1);
12214 }
12215
12216 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12217 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12218 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12219
12220 if (ss == NULL || rs == NULL || ts == NULL)
12221 return (-1); /* dtrace_dof_error() has been called already */
12222
12223 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12224 rs->dofs_align != sizeof (uint64_t)) {
12225 dtrace_dof_error(dof, "invalid relocation section");
12226 return (-1);
12227 }
12228
12229 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12230 n = rs->dofs_size / rs->dofs_entsize;
12231
12232 for (i = 0; i < n; i++) {
12233 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12234
12235 switch (r->dofr_type) {
12236 case DOF_RELO_NONE:
12237 break;
12238 case DOF_RELO_SETX:
12239 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12240 sizeof (uint64_t) > ts->dofs_size) {
12241 dtrace_dof_error(dof, "bad relocation offset");
12242 return (-1);
12243 }
12244
12245 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12246 dtrace_dof_error(dof, "misaligned setx relo");
12247 return (-1);
12248 }
12249
12250 *(uint64_t *)taddr += ubase;
12251 break;
12252 default:
12253 dtrace_dof_error(dof, "invalid relocation type");
12254 return (-1);
12255 }
12256
12257 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12258 }
12259
12260 return (0);
12261 }
12262
12263 /*
12264 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12265 * header: it should be at the front of a memory region that is at least
12266 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12267 * size. It need not be validated in any other way.
12268 */
12269 static int
12270 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12271 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12272 {
12273 uint64_t len = dof->dofh_loadsz, seclen;
12274 uintptr_t daddr = (uintptr_t)dof;
12275 dtrace_ecbdesc_t *ep;
12276 dtrace_enabling_t *enab;
12277 uint_t i;
12278
12279 ASSERT(MUTEX_HELD(&dtrace_lock));
12280 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12281
12282 /*
12283 * Check the DOF header identification bytes. In addition to checking
12284 * valid settings, we also verify that unused bits/bytes are zeroed so
12285 * we can use them later without fear of regressing existing binaries.
12286 */
12287 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12288 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12289 dtrace_dof_error(dof, "DOF magic string mismatch");
12290 return (-1);
12291 }
12292
12293 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12294 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12295 dtrace_dof_error(dof, "DOF has invalid data model");
12296 return (-1);
12297 }
12298
12299 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12300 dtrace_dof_error(dof, "DOF encoding mismatch");
12301 return (-1);
12302 }
12303
12304 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12305 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12306 dtrace_dof_error(dof, "DOF version mismatch");
12307 return (-1);
12308 }
12309
12310 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12311 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12312 return (-1);
12313 }
12314
12315 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12316 dtrace_dof_error(dof, "DOF uses too many integer registers");
12317 return (-1);
12318 }
12319
12320 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12321 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12322 return (-1);
12323 }
12324
12325 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12326 if (dof->dofh_ident[i] != 0) {
12327 dtrace_dof_error(dof, "DOF has invalid ident byte set");
12328 return (-1);
12329 }
12330 }
12331
12332 if (dof->dofh_flags & ~DOF_FL_VALID) {
12333 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12334 return (-1);
12335 }
12336
12337 if (dof->dofh_secsize == 0) {
12338 dtrace_dof_error(dof, "zero section header size");
12339 return (-1);
12340 }
12341
12342 /*
12343 * Check that the section headers don't exceed the amount of DOF
12344 * data. Note that we cast the section size and number of sections
12345 * to uint64_t's to prevent possible overflow in the multiplication.
12346 */
12347 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12348
12349 if (dof->dofh_secoff > len || seclen > len ||
12350 dof->dofh_secoff + seclen > len) {
12351 dtrace_dof_error(dof, "truncated section headers");
12352 return (-1);
12353 }
12354
12355 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12356 dtrace_dof_error(dof, "misaligned section headers");
12357 return (-1);
12358 }
12359
12360 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12361 dtrace_dof_error(dof, "misaligned section size");
12362 return (-1);
12363 }
12364
12365 /*
12366 * Take an initial pass through the section headers to be sure that
12367 * the headers don't have stray offsets. If the 'noprobes' flag is
12368 * set, do not permit sections relating to providers, probes, or args.
12369 */
12370 for (i = 0; i < dof->dofh_secnum; i++) {
12371 dof_sec_t *sec = (dof_sec_t *)(daddr +
12372 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12373
12374 if (noprobes) {
12375 switch (sec->dofs_type) {
12376 case DOF_SECT_PROVIDER:
12377 case DOF_SECT_PROBES:
12378 case DOF_SECT_PRARGS:
12379 case DOF_SECT_PROFFS:
12380 dtrace_dof_error(dof, "illegal sections "
12381 "for enabling");
12382 return (-1);
12383 }
12384 }
12385
12386 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
12387 !(sec->dofs_flags & DOF_SECF_LOAD)) {
12388 dtrace_dof_error(dof, "loadable section with load "
12389 "flag unset");
12390 return (-1);
12391 }
12392
12393 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12394 continue; /* just ignore non-loadable sections */
12395
12396 if (sec->dofs_align & (sec->dofs_align - 1)) {
12397 dtrace_dof_error(dof, "bad section alignment");
12398 return (-1);
12399 }
12400
12401 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12402 dtrace_dof_error(dof, "misaligned section");
12403 return (-1);
12404 }
12405
12406 if (sec->dofs_offset > len || sec->dofs_size > len ||
12407 sec->dofs_offset + sec->dofs_size > len) {
12408 dtrace_dof_error(dof, "corrupt section header");
12409 return (-1);
12410 }
12411
12412 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12413 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12414 dtrace_dof_error(dof, "non-terminating string table");
12415 return (-1);
12416 }
12417 }
12418
12419 /*
12420 * Take a second pass through the sections and locate and perform any
12421 * relocations that are present. We do this after the first pass to
12422 * be sure that all sections have had their headers validated.
12423 */
12424 for (i = 0; i < dof->dofh_secnum; i++) {
12425 dof_sec_t *sec = (dof_sec_t *)(daddr +
12426 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12427
12428 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12429 continue; /* skip sections that are not loadable */
12430
12431 switch (sec->dofs_type) {
12432 case DOF_SECT_URELHDR:
12433 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12434 return (-1);
12435 break;
12436 }
12437 }
12438
12439 if ((enab = *enabp) == NULL)
12440 enab = *enabp = dtrace_enabling_create(vstate);
12441
12442 for (i = 0; i < dof->dofh_secnum; i++) {
12443 dof_sec_t *sec = (dof_sec_t *)(daddr +
12444 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12445
12446 if (sec->dofs_type != DOF_SECT_ECBDESC)
12447 continue;
12448
12449 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12450 dtrace_enabling_destroy(enab);
12451 *enabp = NULL;
12452 return (-1);
12453 }
12454
12455 dtrace_enabling_add(enab, ep);
12456 }
12457
12458 return (0);
12459 }
12460
12461 /*
12462 * Process DOF for any options. This routine assumes that the DOF has been
12463 * at least processed by dtrace_dof_slurp().
12464 */
12465 static int
12466 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12467 {
12468 int i, rval;
12469 uint32_t entsize;
12470 size_t offs;
12471 dof_optdesc_t *desc;
12472
12473 for (i = 0; i < dof->dofh_secnum; i++) {
12474 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12475 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12476
12477 if (sec->dofs_type != DOF_SECT_OPTDESC)
12478 continue;
12479
12480 if (sec->dofs_align != sizeof (uint64_t)) {
12481 dtrace_dof_error(dof, "bad alignment in "
12482 "option description");
12483 return (EINVAL);
12484 }
12485
12486 if ((entsize = sec->dofs_entsize) == 0) {
12487 dtrace_dof_error(dof, "zeroed option entry size");
12488 return (EINVAL);
12489 }
12490
12491 if (entsize < sizeof (dof_optdesc_t)) {
12492 dtrace_dof_error(dof, "bad option entry size");
12493 return (EINVAL);
12494 }
12495
12496 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12497 desc = (dof_optdesc_t *)((uintptr_t)dof +
12498 (uintptr_t)sec->dofs_offset + offs);
12499
12500 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12501 dtrace_dof_error(dof, "non-zero option string");
12502 return (EINVAL);
12503 }
12504
12505 if (desc->dofo_value == DTRACEOPT_UNSET) {
12506 dtrace_dof_error(dof, "unset option");
12507 return (EINVAL);
12508 }
12509
12510 if ((rval = dtrace_state_option(state,
12511 desc->dofo_option, desc->dofo_value)) != 0) {
12512 dtrace_dof_error(dof, "rejected option");
12513 return (rval);
12514 }
12515 }
12516 }
12517
12518 return (0);
12519 }
12520
12521 /*
12522 * DTrace Consumer State Functions
12523 */
12524 int
12525 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12526 {
12527 size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12528 void *base;
12529 uintptr_t limit;
12530 dtrace_dynvar_t *dvar, *next, *start;
12531 int i;
12532
12533 ASSERT(MUTEX_HELD(&dtrace_lock));
12534 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12535
12536 bzero(dstate, sizeof (dtrace_dstate_t));
12537
12538 if ((dstate->dtds_chunksize = chunksize) == 0)
12539 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12540
12541 if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12542 size = min;
12543
12544 if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12545 return (ENOMEM);
12546
12547 dstate->dtds_size = size;
12548 dstate->dtds_base = base;
12549 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12550 bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12551
12552 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12553
12554 if (hashsize != 1 && (hashsize & 1))
12555 hashsize--;
12556
12557 dstate->dtds_hashsize = hashsize;
12558 dstate->dtds_hash = dstate->dtds_base;
12559
12560 /*
12561 * Set all of our hash buckets to point to the single sink, and (if
12562 * it hasn't already been set), set the sink's hash value to be the
12563 * sink sentinel value. The sink is needed for dynamic variable
12564 * lookups to know that they have iterated over an entire, valid hash
12565 * chain.
12566 */
12567 for (i = 0; i < hashsize; i++)
12568 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12569
12570 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12571 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12572
12573 /*
12574 * Determine number of active CPUs. Divide free list evenly among
12575 * active CPUs.
12576 */
12577 start = (dtrace_dynvar_t *)
12578 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12579 limit = (uintptr_t)base + size;
12580
12581 maxper = (limit - (uintptr_t)start) / NCPU;
12582 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12583
12584 for (i = 0; i < NCPU; i++) {
12585 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12586
12587 /*
12588 * If we don't even have enough chunks to make it once through
12589 * NCPUs, we're just going to allocate everything to the first
12590 * CPU. And if we're on the last CPU, we're going to allocate
12591 * whatever is left over. In either case, we set the limit to
12592 * be the limit of the dynamic variable space.
12593 */
12594 if (maxper == 0 || i == NCPU - 1) {
12595 limit = (uintptr_t)base + size;
12596 start = NULL;
12597 } else {
12598 limit = (uintptr_t)start + maxper;
12599 start = (dtrace_dynvar_t *)limit;
12600 }
12601
12602 ASSERT(limit <= (uintptr_t)base + size);
12603
12604 for (;;) {
12605 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12606 dstate->dtds_chunksize);
12607
12608 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12609 break;
12610
12611 dvar->dtdv_next = next;
12612 dvar = next;
12613 }
12614
12615 if (maxper == 0)
12616 break;
12617 }
12618
12619 return (0);
12620 }
12621
12622 void
12623 dtrace_dstate_fini(dtrace_dstate_t *dstate)
12624 {
12625 ASSERT(MUTEX_HELD(&cpu_lock));
12626
12627 if (dstate->dtds_base == NULL)
12628 return;
12629
12630 kmem_free(dstate->dtds_base, dstate->dtds_size);
12631 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
12632 }
12633
12634 static void
12635 dtrace_vstate_fini(dtrace_vstate_t *vstate)
12636 {
12637 /*
12638 * Logical XOR, where are you?
12639 */
12640 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12641
12642 if (vstate->dtvs_nglobals > 0) {
12643 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12644 sizeof (dtrace_statvar_t *));
12645 }
12646
12647 if (vstate->dtvs_ntlocals > 0) {
12648 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12649 sizeof (dtrace_difv_t));
12650 }
12651
12652 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
12653
12654 if (vstate->dtvs_nlocals > 0) {
12655 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
12656 sizeof (dtrace_statvar_t *));
12657 }
12658 }
12659
12660 static void
12661 dtrace_state_clean(dtrace_state_t *state)
12662 {
12663 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
12664 return;
12665
12666 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
12667 dtrace_speculation_clean(state);
12668 }
12669
12670 static void
12671 dtrace_state_deadman(dtrace_state_t *state)
12672 {
12673 hrtime_t now;
12674
12675 dtrace_sync();
12676
12677 now = dtrace_gethrtime();
12678
12679 if (state != dtrace_anon.dta_state &&
12680 now - state->dts_laststatus >= dtrace_deadman_user)
12681 return;
12682
12683 /*
12684 * We must be sure that dts_alive never appears to be less than the
12685 * value upon entry to dtrace_state_deadman(), and because we lack a
12686 * dtrace_cas64(), we cannot store to it atomically. We thus instead
12687 * store INT64_MAX to it, followed by a memory barrier, followed by
12688 * the new value. This assures that dts_alive never appears to be
12689 * less than its true value, regardless of the order in which the
12690 * stores to the underlying storage are issued.
12691 */
12692 state->dts_alive = INT64_MAX;
12693 dtrace_membar_producer();
12694 state->dts_alive = now;
12695 }
12696
12697 dtrace_state_t *
12698 dtrace_state_create(dev_t *devp, cred_t *cr)
12699 {
12700 minor_t minor;
12701 major_t major;
12702 char c[30];
12703 dtrace_state_t *state;
12704 dtrace_optval_t *opt;
12705 int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
12706
12707 ASSERT(MUTEX_HELD(&dtrace_lock));
12708 ASSERT(MUTEX_HELD(&cpu_lock));
12709
12710 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
12711 VM_BESTFIT | VM_SLEEP);
12712
12713 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
12714 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12715 return (NULL);
12716 }
12717
12718 state = ddi_get_soft_state(dtrace_softstate, minor);
12719 state->dts_epid = DTRACE_EPIDNONE + 1;
12720
12721 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
12722 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
12723 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12724
12725 if (devp != NULL) {
12726 major = getemajor(*devp);
12727 } else {
12728 major = ddi_driver_major(dtrace_devi);
12729 }
12730
12731 state->dts_dev = makedevice(major, minor);
12732
12733 if (devp != NULL)
12734 *devp = state->dts_dev;
12735
12736 /*
12737 * We allocate NCPU buffers. On the one hand, this can be quite
12738 * a bit of memory per instance (nearly 36K on a Starcat). On the
12739 * other hand, it saves an additional memory reference in the probe
12740 * path.
12741 */
12742 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
12743 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
12744 state->dts_cleaner = CYCLIC_NONE;
12745 state->dts_deadman = CYCLIC_NONE;
12746 state->dts_vstate.dtvs_state = state;
12747
12748 for (i = 0; i < DTRACEOPT_MAX; i++)
12749 state->dts_options[i] = DTRACEOPT_UNSET;
12750
12751 /*
12752 * Set the default options.
12753 */
12754 opt = state->dts_options;
12755 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
12756 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
12757 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
12758 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
12759 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
12760 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
12761 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
12762 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
12763 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
12764 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
12765 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
12766 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
12767 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
12768 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
12769
12770 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
12771
12772 /*
12773 * Depending on the user credentials, we set flag bits which alter probe
12774 * visibility or the amount of destructiveness allowed. In the case of
12775 * actual anonymous tracing, or the possession of all privileges, all of
12776 * the normal checks are bypassed.
12777 */
12778 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
12779 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
12780 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
12781 } else {
12782 /*
12783 * Set up the credentials for this instantiation. We take a
12784 * hold on the credential to prevent it from disappearing on
12785 * us; this in turn prevents the zone_t referenced by this
12786 * credential from disappearing. This means that we can
12787 * examine the credential and the zone from probe context.
12788 */
12789 crhold(cr);
12790 state->dts_cred.dcr_cred = cr;
12791
12792 /*
12793 * CRA_PROC means "we have *some* privilege for dtrace" and
12794 * unlocks the use of variables like pid, zonename, etc.
12795 */
12796 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12797 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12798 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12799 }
12800
12801 /*
12802 * dtrace_user allows use of syscall and profile providers.
12803 * If the user also has proc_owner and/or proc_zone, we
12804 * extend the scope to include additional visibility and
12805 * destructive power.
12806 */
12807 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12808 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12809 state->dts_cred.dcr_visible |=
12810 DTRACE_CRV_ALLPROC;
12811
12812 state->dts_cred.dcr_action |=
12813 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12814 }
12815
12816 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12817 state->dts_cred.dcr_visible |=
12818 DTRACE_CRV_ALLZONE;
12819
12820 state->dts_cred.dcr_action |=
12821 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12822 }
12823
12824 /*
12825 * If we have all privs in whatever zone this is,
12826 * we can do destructive things to processes which
12827 * have altered credentials.
12828 */
12829 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12830 cr->cr_zone->zone_privset)) {
12831 state->dts_cred.dcr_action |=
12832 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12833 }
12834 }
12835
12836 /*
12837 * Holding the dtrace_kernel privilege also implies that
12838 * the user has the dtrace_user privilege from a visibility
12839 * perspective. But without further privileges, some
12840 * destructive actions are not available.
12841 */
12842 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12843 /*
12844 * Make all probes in all zones visible. However,
12845 * this doesn't mean that all actions become available
12846 * to all zones.
12847 */
12848 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12849 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12850
12851 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12852 DTRACE_CRA_PROC;
12853 /*
12854 * Holding proc_owner means that destructive actions
12855 * for *this* zone are allowed.
12856 */
12857 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12858 state->dts_cred.dcr_action |=
12859 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12860
12861 /*
12862 * Holding proc_zone means that destructive actions
12863 * for this user/group ID in all zones is allowed.
12864 */
12865 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12866 state->dts_cred.dcr_action |=
12867 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12868
12869 /*
12870 * If we have all privs in whatever zone this is,
12871 * we can do destructive things to processes which
12872 * have altered credentials.
12873 */
12874 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12875 cr->cr_zone->zone_privset)) {
12876 state->dts_cred.dcr_action |=
12877 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12878 }
12879 }
12880
12881 /*
12882 * Holding the dtrace_proc privilege gives control over fasttrap
12883 * and pid providers. We need to grant wider destructive
12884 * privileges in the event that the user has proc_owner and/or
12885 * proc_zone.
12886 */
12887 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12888 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12889 state->dts_cred.dcr_action |=
12890 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12891
12892 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12893 state->dts_cred.dcr_action |=
12894 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12895 }
12896 }
12897
12898 return (state);
12899 }
12900
12901 static int
12902 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12903 {
12904 dtrace_optval_t *opt = state->dts_options, size;
12905 processorid_t cpu;
12906 int flags = 0, rval, factor, divisor = 1;
12907
12908 ASSERT(MUTEX_HELD(&dtrace_lock));
12909 ASSERT(MUTEX_HELD(&cpu_lock));
12910 ASSERT(which < DTRACEOPT_MAX);
12911 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12912 (state == dtrace_anon.dta_state &&
12913 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12914
12915 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12916 return (0);
12917
12918 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12919 cpu = opt[DTRACEOPT_CPU];
12920
12921 if (which == DTRACEOPT_SPECSIZE)
12922 flags |= DTRACEBUF_NOSWITCH;
12923
12924 if (which == DTRACEOPT_BUFSIZE) {
12925 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12926 flags |= DTRACEBUF_RING;
12927
12928 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12929 flags |= DTRACEBUF_FILL;
12930
12931 if (state != dtrace_anon.dta_state ||
12932 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12933 flags |= DTRACEBUF_INACTIVE;
12934 }
12935
12936 for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
12937 /*
12938 * The size must be 8-byte aligned. If the size is not 8-byte
12939 * aligned, drop it down by the difference.
12940 */
12941 if (size & (sizeof (uint64_t) - 1))
12942 size -= size & (sizeof (uint64_t) - 1);
12943
12944 if (size < state->dts_reserve) {
12945 /*
12946 * Buffers always must be large enough to accommodate
12947 * their prereserved space. We return E2BIG instead
12948 * of ENOMEM in this case to allow for user-level
12949 * software to differentiate the cases.
12950 */
12951 return (E2BIG);
12952 }
12953
12954 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
12955
12956 if (rval != ENOMEM) {
12957 opt[which] = size;
12958 return (rval);
12959 }
12960
12961 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12962 return (rval);
12963
12964 for (divisor = 2; divisor < factor; divisor <<= 1)
12965 continue;
12966 }
12967
12968 return (ENOMEM);
12969 }
12970
12971 static int
12972 dtrace_state_buffers(dtrace_state_t *state)
12973 {
12974 dtrace_speculation_t *spec = state->dts_speculations;
12975 int rval, i;
12976
12977 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12978 DTRACEOPT_BUFSIZE)) != 0)
12979 return (rval);
12980
12981 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12982 DTRACEOPT_AGGSIZE)) != 0)
12983 return (rval);
12984
12985 for (i = 0; i < state->dts_nspeculations; i++) {
12986 if ((rval = dtrace_state_buffer(state,
12987 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12988 return (rval);
12989 }
12990
12991 return (0);
12992 }
12993
12994 static void
12995 dtrace_state_prereserve(dtrace_state_t *state)
12996 {
12997 dtrace_ecb_t *ecb;
12998 dtrace_probe_t *probe;
12999
13000 state->dts_reserve = 0;
13001
13002 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13003 return;
13004
13005 /*
13006 * If our buffer policy is a "fill" buffer policy, we need to set the
13007 * prereserved space to be the space required by the END probes.
13008 */
13009 probe = dtrace_probes[dtrace_probeid_end - 1];
13010 ASSERT(probe != NULL);
13011
13012 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13013 if (ecb->dte_state != state)
13014 continue;
13015
13016 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13017 }
13018 }
13019
13020 static int
13021 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13022 {
13023 dtrace_optval_t *opt = state->dts_options, sz, nspec;
13024 dtrace_speculation_t *spec;
13025 dtrace_buffer_t *buf;
13026 cyc_handler_t hdlr;
13027 cyc_time_t when;
13028 int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13029 dtrace_icookie_t cookie;
13030
13031 mutex_enter(&cpu_lock);
13032 mutex_enter(&dtrace_lock);
13033
13034 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13035 rval = EBUSY;
13036 goto out;
13037 }
13038
13039 /*
13040 * Before we can perform any checks, we must prime all of the
13041 * retained enablings that correspond to this state.
13042 */
13043 dtrace_enabling_prime(state);
13044
13045 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13046 rval = EACCES;
13047 goto out;
13048 }
13049
13050 dtrace_state_prereserve(state);
13051
13052 /*
13053 * Now we want to do is try to allocate our speculations.
13054 * We do not automatically resize the number of speculations; if
13055 * this fails, we will fail the operation.
13056 */
13057 nspec = opt[DTRACEOPT_NSPEC];
13058 ASSERT(nspec != DTRACEOPT_UNSET);
13059
13060 if (nspec > INT_MAX) {
13061 rval = ENOMEM;
13062 goto out;
13063 }
13064
13065 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13066 KM_NOSLEEP | KM_NORMALPRI);
13067
13068 if (spec == NULL) {
13069 rval = ENOMEM;
13070 goto out;
13071 }
13072
13073 state->dts_speculations = spec;
13074 state->dts_nspeculations = (int)nspec;
13075
13076 for (i = 0; i < nspec; i++) {
13077 if ((buf = kmem_zalloc(bufsize,
13078 KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13079 rval = ENOMEM;
13080 goto err;
13081 }
13082
13083 spec[i].dtsp_buffer = buf;
13084 }
13085
13086 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13087 if (dtrace_anon.dta_state == NULL) {
13088 rval = ENOENT;
13089 goto out;
13090 }
13091
13092 if (state->dts_necbs != 0) {
13093 rval = EALREADY;
13094 goto out;
13095 }
13096
13097 state->dts_anon = dtrace_anon_grab();
13098 ASSERT(state->dts_anon != NULL);
13099 state = state->dts_anon;
13100
13101 /*
13102 * We want "grabanon" to be set in the grabbed state, so we'll
13103 * copy that option value from the grabbing state into the
13104 * grabbed state.
13105 */
13106 state->dts_options[DTRACEOPT_GRABANON] =
13107 opt[DTRACEOPT_GRABANON];
13108
13109 *cpu = dtrace_anon.dta_beganon;
13110
13111 /*
13112 * If the anonymous state is active (as it almost certainly
13113 * is if the anonymous enabling ultimately matched anything),
13114 * we don't allow any further option processing -- but we
13115 * don't return failure.
13116 */
13117 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13118 goto out;
13119 }
13120
13121 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13122 opt[DTRACEOPT_AGGSIZE] != 0) {
13123 if (state->dts_aggregations == NULL) {
13124 /*
13125 * We're not going to create an aggregation buffer
13126 * because we don't have any ECBs that contain
13127 * aggregations -- set this option to 0.
13128 */
13129 opt[DTRACEOPT_AGGSIZE] = 0;
13130 } else {
13131 /*
13132 * If we have an aggregation buffer, we must also have
13133 * a buffer to use as scratch.
13134 */
13135 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13136 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13137 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13138 }
13139 }
13140 }
13141
13142 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13143 opt[DTRACEOPT_SPECSIZE] != 0) {
13144 if (!state->dts_speculates) {
13145 /*
13146 * We're not going to create speculation buffers
13147 * because we don't have any ECBs that actually
13148 * speculate -- set the speculation size to 0.
13149 */
13150 opt[DTRACEOPT_SPECSIZE] = 0;
13151 }
13152 }
13153
13154 /*
13155 * The bare minimum size for any buffer that we're actually going to
13156 * do anything to is sizeof (uint64_t).
13157 */
13158 sz = sizeof (uint64_t);
13159
13160 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13161 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13162 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13163 /*
13164 * A buffer size has been explicitly set to 0 (or to a size
13165 * that will be adjusted to 0) and we need the space -- we
13166 * need to return failure. We return ENOSPC to differentiate
13167 * it from failing to allocate a buffer due to failure to meet
13168 * the reserve (for which we return E2BIG).
13169 */
13170 rval = ENOSPC;
13171 goto out;
13172 }
13173
13174 if ((rval = dtrace_state_buffers(state)) != 0)
13175 goto err;
13176
13177 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13178 sz = dtrace_dstate_defsize;
13179
13180 do {
13181 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13182
13183 if (rval == 0)
13184 break;
13185
13186 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13187 goto err;
13188 } while (sz >>= 1);
13189
13190 opt[DTRACEOPT_DYNVARSIZE] = sz;
13191
13192 if (rval != 0)
13193 goto err;
13194
13195 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13196 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13197
13198 if (opt[DTRACEOPT_CLEANRATE] == 0)
13199 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13200
13201 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13202 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13203
13204 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13205 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13206
13207 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13208 hdlr.cyh_arg = state;
13209 hdlr.cyh_level = CY_LOW_LEVEL;
13210
13211 when.cyt_when = 0;
13212 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13213
13214 state->dts_cleaner = cyclic_add(&hdlr, &when);
13215
13216 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13217 hdlr.cyh_arg = state;
13218 hdlr.cyh_level = CY_LOW_LEVEL;
13219
13220 when.cyt_when = 0;
13221 when.cyt_interval = dtrace_deadman_interval;
13222
13223 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13224 state->dts_deadman = cyclic_add(&hdlr, &when);
13225
13226 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13227
13228 if (state->dts_getf != 0 &&
13229 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
13230 /*
13231 * We don't have kernel privs but we have at least one call
13232 * to getf(); we need to bump our zone's count, and (if
13233 * this is the first enabling to have an unprivileged call
13234 * to getf()) we need to hook into closef().
13235 */
13236 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
13237
13238 if (dtrace_getf++ == 0) {
13239 ASSERT(dtrace_closef == NULL);
13240 dtrace_closef = dtrace_getf_barrier;
13241 }
13242 }
13243
13244 /*
13245 * Now it's time to actually fire the BEGIN probe. We need to disable
13246 * interrupts here both to record the CPU on which we fired the BEGIN
13247 * probe (the data from this CPU will be processed first at user
13248 * level) and to manually activate the buffer for this CPU.
13249 */
13250 cookie = dtrace_interrupt_disable();
13251 *cpu = CPU->cpu_id;
13252 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13253 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13254
13255 dtrace_probe(dtrace_probeid_begin,
13256 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13257 dtrace_interrupt_enable(cookie);
13258 /*
13259 * We may have had an exit action from a BEGIN probe; only change our
13260 * state to ACTIVE if we're still in WARMUP.
13261 */
13262 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13263 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13264
13265 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13266 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13267
13268 /*
13269 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13270 * want each CPU to transition its principal buffer out of the
13271 * INACTIVE state. Doing this assures that no CPU will suddenly begin
13272 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13273 * atomically transition from processing none of a state's ECBs to
13274 * processing all of them.
13275 */
13276 dtrace_xcall(DTRACE_CPUALL,
13277 (dtrace_xcall_t)dtrace_buffer_activate, state);
13278 goto out;
13279
13280 err:
13281 dtrace_buffer_free(state->dts_buffer);
13282 dtrace_buffer_free(state->dts_aggbuffer);
13283
13284 if ((nspec = state->dts_nspeculations) == 0) {
13285 ASSERT(state->dts_speculations == NULL);
13286 goto out;
13287 }
13288
13289 spec = state->dts_speculations;
13290 ASSERT(spec != NULL);
13291
13292 for (i = 0; i < state->dts_nspeculations; i++) {
13293 if ((buf = spec[i].dtsp_buffer) == NULL)
13294 break;
13295
13296 dtrace_buffer_free(buf);
13297 kmem_free(buf, bufsize);
13298 }
13299
13300 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13301 state->dts_nspeculations = 0;
13302 state->dts_speculations = NULL;
13303
13304 out:
13305 mutex_exit(&dtrace_lock);
13306 mutex_exit(&cpu_lock);
13307
13308 return (rval);
13309 }
13310
13311 static int
13312 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13313 {
13314 dtrace_icookie_t cookie;
13315
13316 ASSERT(MUTEX_HELD(&dtrace_lock));
13317
13318 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13319 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13320 return (EINVAL);
13321
13322 /*
13323 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13324 * to be sure that every CPU has seen it. See below for the details
13325 * on why this is done.
13326 */
13327 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13328 dtrace_sync();
13329
13330 /*
13331 * By this point, it is impossible for any CPU to be still processing
13332 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
13333 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13334 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
13335 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13336 * iff we're in the END probe.
13337 */
13338 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13339 dtrace_sync();
13340 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13341
13342 /*
13343 * Finally, we can release the reserve and call the END probe. We
13344 * disable interrupts across calling the END probe to allow us to
13345 * return the CPU on which we actually called the END probe. This
13346 * allows user-land to be sure that this CPU's principal buffer is
13347 * processed last.
13348 */
13349 state->dts_reserve = 0;
13350
13351 cookie = dtrace_interrupt_disable();
13352 *cpu = CPU->cpu_id;
13353 dtrace_probe(dtrace_probeid_end,
13354 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13355 dtrace_interrupt_enable(cookie);
13356
13357 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13358 dtrace_sync();
13359
13360 if (state->dts_getf != 0 &&
13361 !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
13362 /*
13363 * We don't have kernel privs but we have at least one call
13364 * to getf(); we need to lower our zone's count, and (if
13365 * this is the last enabling to have an unprivileged call
13366 * to getf()) we need to clear the closef() hook.
13367 */
13368 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
13369 ASSERT(dtrace_closef == dtrace_getf_barrier);
13370 ASSERT(dtrace_getf > 0);
13371
13372 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
13373
13374 if (--dtrace_getf == 0)
13375 dtrace_closef = NULL;
13376 }
13377
13378 return (0);
13379 }
13380
13381 static int
13382 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13383 dtrace_optval_t val)
13384 {
13385 ASSERT(MUTEX_HELD(&dtrace_lock));
13386
13387 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13388 return (EBUSY);
13389
13390 if (option >= DTRACEOPT_MAX)
13391 return (EINVAL);
13392
13393 if (option != DTRACEOPT_CPU && val < 0)
13394 return (EINVAL);
13395
13396 switch (option) {
13397 case DTRACEOPT_DESTRUCTIVE:
13398 if (dtrace_destructive_disallow)
13399 return (EACCES);
13400
13401 state->dts_cred.dcr_destructive = 1;
13402 break;
13403
13404 case DTRACEOPT_BUFSIZE:
13405 case DTRACEOPT_DYNVARSIZE:
13406 case DTRACEOPT_AGGSIZE:
13407 case DTRACEOPT_SPECSIZE:
13408 case DTRACEOPT_STRSIZE:
13409 if (val < 0)
13410 return (EINVAL);
13411
13412 if (val >= LONG_MAX) {
13413 /*
13414 * If this is an otherwise negative value, set it to
13415 * the highest multiple of 128m less than LONG_MAX.
13416 * Technically, we're adjusting the size without
13417 * regard to the buffer resizing policy, but in fact,
13418 * this has no effect -- if we set the buffer size to
13419 * ~LONG_MAX and the buffer policy is ultimately set to
13420 * be "manual", the buffer allocation is guaranteed to
13421 * fail, if only because the allocation requires two
13422 * buffers. (We set the the size to the highest
13423 * multiple of 128m because it ensures that the size
13424 * will remain a multiple of a megabyte when
13425 * repeatedly halved -- all the way down to 15m.)
13426 */
13427 val = LONG_MAX - (1 << 27) + 1;
13428 }
13429 }
13430
13431 state->dts_options[option] = val;
13432
13433 return (0);
13434 }
13435
13436 static void
13437 dtrace_state_destroy(dtrace_state_t *state)
13438 {
13439 dtrace_ecb_t *ecb;
13440 dtrace_vstate_t *vstate = &state->dts_vstate;
13441 minor_t minor = getminor(state->dts_dev);
13442 int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13443 dtrace_speculation_t *spec = state->dts_speculations;
13444 int nspec = state->dts_nspeculations;
13445 uint32_t match;
13446
13447 ASSERT(MUTEX_HELD(&dtrace_lock));
13448 ASSERT(MUTEX_HELD(&cpu_lock));
13449
13450 /*
13451 * First, retract any retained enablings for this state.
13452 */
13453 dtrace_enabling_retract(state);
13454 ASSERT(state->dts_nretained == 0);
13455
13456 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13457 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13458 /*
13459 * We have managed to come into dtrace_state_destroy() on a
13460 * hot enabling -- almost certainly because of a disorderly
13461 * shutdown of a consumer. (That is, a consumer that is
13462 * exiting without having called dtrace_stop().) In this case,
13463 * we're going to set our activity to be KILLED, and then
13464 * issue a sync to be sure that everyone is out of probe
13465 * context before we start blowing away ECBs.
13466 */
13467 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13468 dtrace_sync();
13469 }
13470
13471 /*
13472 * Release the credential hold we took in dtrace_state_create().
13473 */
13474 if (state->dts_cred.dcr_cred != NULL)
13475 crfree(state->dts_cred.dcr_cred);
13476
13477 /*
13478 * Now we can safely disable and destroy any enabled probes. Because
13479 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13480 * (especially if they're all enabled), we take two passes through the
13481 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13482 * in the second we disable whatever is left over.
13483 */
13484 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13485 for (i = 0; i < state->dts_necbs; i++) {
13486 if ((ecb = state->dts_ecbs[i]) == NULL)
13487 continue;
13488
13489 if (match && ecb->dte_probe != NULL) {
13490 dtrace_probe_t *probe = ecb->dte_probe;
13491 dtrace_provider_t *prov = probe->dtpr_provider;
13492
13493 if (!(prov->dtpv_priv.dtpp_flags & match))
13494 continue;
13495 }
13496
13497 dtrace_ecb_disable(ecb);
13498 dtrace_ecb_destroy(ecb);
13499 }
13500
13501 if (!match)
13502 break;
13503 }
13504
13505 /*
13506 * Before we free the buffers, perform one more sync to assure that
13507 * every CPU is out of probe context.
13508 */
13509 dtrace_sync();
13510
13511 dtrace_buffer_free(state->dts_buffer);
13512 dtrace_buffer_free(state->dts_aggbuffer);
13513
13514 for (i = 0; i < nspec; i++)
13515 dtrace_buffer_free(spec[i].dtsp_buffer);
13516
13517 if (state->dts_cleaner != CYCLIC_NONE)
13518 cyclic_remove(state->dts_cleaner);
13519
13520 if (state->dts_deadman != CYCLIC_NONE)
13521 cyclic_remove(state->dts_deadman);
13522
13523 dtrace_dstate_fini(&vstate->dtvs_dynvars);
13524 dtrace_vstate_fini(vstate);
13525 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13526
13527 if (state->dts_aggregations != NULL) {
13528 #ifdef DEBUG
13529 for (i = 0; i < state->dts_naggregations; i++)
13530 ASSERT(state->dts_aggregations[i] == NULL);
13531 #endif
13532 ASSERT(state->dts_naggregations > 0);
13533 kmem_free(state->dts_aggregations,
13534 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13535 }
13536
13537 kmem_free(state->dts_buffer, bufsize);
13538 kmem_free(state->dts_aggbuffer, bufsize);
13539
13540 for (i = 0; i < nspec; i++)
13541 kmem_free(spec[i].dtsp_buffer, bufsize);
13542
13543 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13544
13545 dtrace_format_destroy(state);
13546
13547 vmem_destroy(state->dts_aggid_arena);
13548 ddi_soft_state_free(dtrace_softstate, minor);
13549 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13550 }
13551
13552 /*
13553 * DTrace Anonymous Enabling Functions
13554 */
13555 static dtrace_state_t *
13556 dtrace_anon_grab(void)
13557 {
13558 dtrace_state_t *state;
13559
13560 ASSERT(MUTEX_HELD(&dtrace_lock));
13561
13562 if ((state = dtrace_anon.dta_state) == NULL) {
13563 ASSERT(dtrace_anon.dta_enabling == NULL);
13564 return (NULL);
13565 }
13566
13567 ASSERT(dtrace_anon.dta_enabling != NULL);
13568 ASSERT(dtrace_retained != NULL);
13569
13570 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
13571 dtrace_anon.dta_enabling = NULL;
13572 dtrace_anon.dta_state = NULL;
13573
13574 return (state);
13575 }
13576
13577 static void
13578 dtrace_anon_property(void)
13579 {
13580 int i, rv;
13581 dtrace_state_t *state;
13582 dof_hdr_t *dof;
13583 char c[32]; /* enough for "dof-data-" + digits */
13584
13585 ASSERT(MUTEX_HELD(&dtrace_lock));
13586 ASSERT(MUTEX_HELD(&cpu_lock));
13587
13588 for (i = 0; ; i++) {
13589 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
13590
13591 dtrace_err_verbose = 1;
13592
13593 if ((dof = dtrace_dof_property(c)) == NULL) {
13594 dtrace_err_verbose = 0;
13595 break;
13596 }
13597
13598 /*
13599 * We want to create anonymous state, so we need to transition
13600 * the kernel debugger to indicate that DTrace is active. If
13601 * this fails (e.g. because the debugger has modified text in
13602 * some way), we won't continue with the processing.
13603 */
13604 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13605 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
13606 "enabling ignored.");
13607 dtrace_dof_destroy(dof);
13608 break;
13609 }
13610
13611 /*
13612 * If we haven't allocated an anonymous state, we'll do so now.
13613 */
13614 if ((state = dtrace_anon.dta_state) == NULL) {
13615 state = dtrace_state_create(NULL, NULL);
13616 dtrace_anon.dta_state = state;
13617
13618 if (state == NULL) {
13619 /*
13620 * This basically shouldn't happen: the only
13621 * failure mode from dtrace_state_create() is a
13622 * failure of ddi_soft_state_zalloc() that
13623 * itself should never happen. Still, the
13624 * interface allows for a failure mode, and
13625 * we want to fail as gracefully as possible:
13626 * we'll emit an error message and cease
13627 * processing anonymous state in this case.
13628 */
13629 cmn_err(CE_WARN, "failed to create "
13630 "anonymous state");
13631 dtrace_dof_destroy(dof);
13632 break;
13633 }
13634 }
13635
13636 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
13637 &dtrace_anon.dta_enabling, 0, B_TRUE);
13638
13639 if (rv == 0)
13640 rv = dtrace_dof_options(dof, state);
13641
13642 dtrace_err_verbose = 0;
13643 dtrace_dof_destroy(dof);
13644
13645 if (rv != 0) {
13646 /*
13647 * This is malformed DOF; chuck any anonymous state
13648 * that we created.
13649 */
13650 ASSERT(dtrace_anon.dta_enabling == NULL);
13651 dtrace_state_destroy(state);
13652 dtrace_anon.dta_state = NULL;
13653 break;
13654 }
13655
13656 ASSERT(dtrace_anon.dta_enabling != NULL);
13657 }
13658
13659 if (dtrace_anon.dta_enabling != NULL) {
13660 int rval;
13661
13662 /*
13663 * dtrace_enabling_retain() can only fail because we are
13664 * trying to retain more enablings than are allowed -- but
13665 * we only have one anonymous enabling, and we are guaranteed
13666 * to be allowed at least one retained enabling; we assert
13667 * that dtrace_enabling_retain() returns success.
13668 */
13669 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
13670 ASSERT(rval == 0);
13671
13672 dtrace_enabling_dump(dtrace_anon.dta_enabling);
13673 }
13674 }
13675
13676 /*
13677 * DTrace Helper Functions
13678 */
13679 static void
13680 dtrace_helper_trace(dtrace_helper_action_t *helper,
13681 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
13682 {
13683 uint32_t size, next, nnext, i;
13684 dtrace_helptrace_t *ent;
13685 uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13686
13687 if (!dtrace_helptrace_enabled)
13688 return;
13689
13690 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
13691
13692 /*
13693 * What would a tracing framework be without its own tracing
13694 * framework? (Well, a hell of a lot simpler, for starters...)
13695 */
13696 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
13697 sizeof (uint64_t) - sizeof (uint64_t);
13698
13699 /*
13700 * Iterate until we can allocate a slot in the trace buffer.
13701 */
13702 do {
13703 next = dtrace_helptrace_next;
13704
13705 if (next + size < dtrace_helptrace_bufsize) {
13706 nnext = next + size;
13707 } else {
13708 nnext = size;
13709 }
13710 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
13711
13712 /*
13713 * We have our slot; fill it in.
13714 */
13715 if (nnext == size)
13716 next = 0;
13717
13718 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
13719 ent->dtht_helper = helper;
13720 ent->dtht_where = where;
13721 ent->dtht_nlocals = vstate->dtvs_nlocals;
13722
13723 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
13724 mstate->dtms_fltoffs : -1;
13725 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
13726 ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
13727
13728 for (i = 0; i < vstate->dtvs_nlocals; i++) {
13729 dtrace_statvar_t *svar;
13730
13731 if ((svar = vstate->dtvs_locals[i]) == NULL)
13732 continue;
13733
13734 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
13735 ent->dtht_locals[i] =
13736 ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
13737 }
13738 }
13739
13740 static uint64_t
13741 dtrace_helper(int which, dtrace_mstate_t *mstate,
13742 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
13743 {
13744 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13745 uint64_t sarg0 = mstate->dtms_arg[0];
13746 uint64_t sarg1 = mstate->dtms_arg[1];
13747 uint64_t rval;
13748 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
13749 dtrace_helper_action_t *helper;
13750 dtrace_vstate_t *vstate;
13751 dtrace_difo_t *pred;
13752 int i, trace = dtrace_helptrace_enabled;
13753
13754 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
13755
13756 if (helpers == NULL)
13757 return (0);
13758
13759 if ((helper = helpers->dthps_actions[which]) == NULL)
13760 return (0);
13761
13762 vstate = &helpers->dthps_vstate;
13763 mstate->dtms_arg[0] = arg0;
13764 mstate->dtms_arg[1] = arg1;
13765
13766 /*
13767 * Now iterate over each helper. If its predicate evaluates to 'true',
13768 * we'll call the corresponding actions. Note that the below calls
13769 * to dtrace_dif_emulate() may set faults in machine state. This is
13770 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
13771 * the stored DIF offset with its own (which is the desired behavior).
13772 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
13773 * from machine state; this is okay, too.
13774 */
13775 for (; helper != NULL; helper = helper->dtha_next) {
13776 if ((pred = helper->dtha_predicate) != NULL) {
13777 if (trace)
13778 dtrace_helper_trace(helper, mstate, vstate, 0);
13779
13780 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
13781 goto next;
13782
13783 if (*flags & CPU_DTRACE_FAULT)
13784 goto err;
13785 }
13786
13787 for (i = 0; i < helper->dtha_nactions; i++) {
13788 if (trace)
13789 dtrace_helper_trace(helper,
13790 mstate, vstate, i + 1);
13791
13792 rval = dtrace_dif_emulate(helper->dtha_actions[i],
13793 mstate, vstate, state);
13794
13795 if (*flags & CPU_DTRACE_FAULT)
13796 goto err;
13797 }
13798
13799 next:
13800 if (trace)
13801 dtrace_helper_trace(helper, mstate, vstate,
13802 DTRACE_HELPTRACE_NEXT);
13803 }
13804
13805 if (trace)
13806 dtrace_helper_trace(helper, mstate, vstate,
13807 DTRACE_HELPTRACE_DONE);
13808
13809 /*
13810 * Restore the arg0 that we saved upon entry.
13811 */
13812 mstate->dtms_arg[0] = sarg0;
13813 mstate->dtms_arg[1] = sarg1;
13814
13815 return (rval);
13816
13817 err:
13818 if (trace)
13819 dtrace_helper_trace(helper, mstate, vstate,
13820 DTRACE_HELPTRACE_ERR);
13821
13822 /*
13823 * Restore the arg0 that we saved upon entry.
13824 */
13825 mstate->dtms_arg[0] = sarg0;
13826 mstate->dtms_arg[1] = sarg1;
13827
13828 return (NULL);
13829 }
13830
13831 static void
13832 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13833 dtrace_vstate_t *vstate)
13834 {
13835 int i;
13836
13837 if (helper->dtha_predicate != NULL)
13838 dtrace_difo_release(helper->dtha_predicate, vstate);
13839
13840 for (i = 0; i < helper->dtha_nactions; i++) {
13841 ASSERT(helper->dtha_actions[i] != NULL);
13842 dtrace_difo_release(helper->dtha_actions[i], vstate);
13843 }
13844
13845 kmem_free(helper->dtha_actions,
13846 helper->dtha_nactions * sizeof (dtrace_difo_t *));
13847 kmem_free(helper, sizeof (dtrace_helper_action_t));
13848 }
13849
13850 static int
13851 dtrace_helper_destroygen(int gen)
13852 {
13853 proc_t *p = curproc;
13854 dtrace_helpers_t *help = p->p_dtrace_helpers;
13855 dtrace_vstate_t *vstate;
13856 int i;
13857
13858 ASSERT(MUTEX_HELD(&dtrace_lock));
13859
13860 if (help == NULL || gen > help->dthps_generation)
13861 return (EINVAL);
13862
13863 vstate = &help->dthps_vstate;
13864
13865 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13866 dtrace_helper_action_t *last = NULL, *h, *next;
13867
13868 for (h = help->dthps_actions[i]; h != NULL; h = next) {
13869 next = h->dtha_next;
13870
13871 if (h->dtha_generation == gen) {
13872 if (last != NULL) {
13873 last->dtha_next = next;
13874 } else {
13875 help->dthps_actions[i] = next;
13876 }
13877
13878 dtrace_helper_action_destroy(h, vstate);
13879 } else {
13880 last = h;
13881 }
13882 }
13883 }
13884
13885 /*
13886 * Interate until we've cleared out all helper providers with the
13887 * given generation number.
13888 */
13889 for (;;) {
13890 dtrace_helper_provider_t *prov;
13891
13892 /*
13893 * Look for a helper provider with the right generation. We
13894 * have to start back at the beginning of the list each time
13895 * because we drop dtrace_lock. It's unlikely that we'll make
13896 * more than two passes.
13897 */
13898 for (i = 0; i < help->dthps_nprovs; i++) {
13899 prov = help->dthps_provs[i];
13900
13901 if (prov->dthp_generation == gen)
13902 break;
13903 }
13904
13905 /*
13906 * If there were no matches, we're done.
13907 */
13908 if (i == help->dthps_nprovs)
13909 break;
13910
13911 /*
13912 * Move the last helper provider into this slot.
13913 */
13914 help->dthps_nprovs--;
13915 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13916 help->dthps_provs[help->dthps_nprovs] = NULL;
13917
13918 mutex_exit(&dtrace_lock);
13919
13920 /*
13921 * If we have a meta provider, remove this helper provider.
13922 */
13923 mutex_enter(&dtrace_meta_lock);
13924 if (dtrace_meta_pid != NULL) {
13925 ASSERT(dtrace_deferred_pid == NULL);
13926 dtrace_helper_provider_remove(&prov->dthp_prov,
13927 p->p_pid);
13928 }
13929 mutex_exit(&dtrace_meta_lock);
13930
13931 dtrace_helper_provider_destroy(prov);
13932
13933 mutex_enter(&dtrace_lock);
13934 }
13935
13936 return (0);
13937 }
13938
13939 static int
13940 dtrace_helper_validate(dtrace_helper_action_t *helper)
13941 {
13942 int err = 0, i;
13943 dtrace_difo_t *dp;
13944
13945 if ((dp = helper->dtha_predicate) != NULL)
13946 err += dtrace_difo_validate_helper(dp);
13947
13948 for (i = 0; i < helper->dtha_nactions; i++)
13949 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13950
13951 return (err == 0);
13952 }
13953
13954 static int
13955 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13956 {
13957 dtrace_helpers_t *help;
13958 dtrace_helper_action_t *helper, *last;
13959 dtrace_actdesc_t *act;
13960 dtrace_vstate_t *vstate;
13961 dtrace_predicate_t *pred;
13962 int count = 0, nactions = 0, i;
13963
13964 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13965 return (EINVAL);
13966
13967 help = curproc->p_dtrace_helpers;
13968 last = help->dthps_actions[which];
13969 vstate = &help->dthps_vstate;
13970
13971 for (count = 0; last != NULL; last = last->dtha_next) {
13972 count++;
13973 if (last->dtha_next == NULL)
13974 break;
13975 }
13976
13977 /*
13978 * If we already have dtrace_helper_actions_max helper actions for this
13979 * helper action type, we'll refuse to add a new one.
13980 */
13981 if (count >= dtrace_helper_actions_max)
13982 return (ENOSPC);
13983
13984 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13985 helper->dtha_generation = help->dthps_generation;
13986
13987 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13988 ASSERT(pred->dtp_difo != NULL);
13989 dtrace_difo_hold(pred->dtp_difo);
13990 helper->dtha_predicate = pred->dtp_difo;
13991 }
13992
13993 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13994 if (act->dtad_kind != DTRACEACT_DIFEXPR)
13995 goto err;
13996
13997 if (act->dtad_difo == NULL)
13998 goto err;
13999
14000 nactions++;
14001 }
14002
14003 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14004 (helper->dtha_nactions = nactions), KM_SLEEP);
14005
14006 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14007 dtrace_difo_hold(act->dtad_difo);
14008 helper->dtha_actions[i++] = act->dtad_difo;
14009 }
14010
14011 if (!dtrace_helper_validate(helper))
14012 goto err;
14013
14014 if (last == NULL) {
14015 help->dthps_actions[which] = helper;
14016 } else {
14017 last->dtha_next = helper;
14018 }
14019
14020 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14021 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14022 dtrace_helptrace_next = 0;
14023 }
14024
14025 return (0);
14026 err:
14027 dtrace_helper_action_destroy(helper, vstate);
14028 return (EINVAL);
14029 }
14030
14031 static void
14032 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14033 dof_helper_t *dofhp)
14034 {
14035 ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14036
14037 mutex_enter(&dtrace_meta_lock);
14038 mutex_enter(&dtrace_lock);
14039
14040 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14041 /*
14042 * If the dtrace module is loaded but not attached, or if
14043 * there aren't isn't a meta provider registered to deal with
14044 * these provider descriptions, we need to postpone creating
14045 * the actual providers until later.
14046 */
14047
14048 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14049 dtrace_deferred_pid != help) {
14050 help->dthps_deferred = 1;
14051 help->dthps_pid = p->p_pid;
14052 help->dthps_next = dtrace_deferred_pid;
14053 help->dthps_prev = NULL;
14054 if (dtrace_deferred_pid != NULL)
14055 dtrace_deferred_pid->dthps_prev = help;
14056 dtrace_deferred_pid = help;
14057 }
14058
14059 mutex_exit(&dtrace_lock);
14060
14061 } else if (dofhp != NULL) {
14062 /*
14063 * If the dtrace module is loaded and we have a particular
14064 * helper provider description, pass that off to the
14065 * meta provider.
14066 */
14067
14068 mutex_exit(&dtrace_lock);
14069
14070 dtrace_helper_provide(dofhp, p->p_pid);
14071
14072 } else {
14073 /*
14074 * Otherwise, just pass all the helper provider descriptions
14075 * off to the meta provider.
14076 */
14077
14078 int i;
14079 mutex_exit(&dtrace_lock);
14080
14081 for (i = 0; i < help->dthps_nprovs; i++) {
14082 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14083 p->p_pid);
14084 }
14085 }
14086
14087 mutex_exit(&dtrace_meta_lock);
14088 }
14089
14090 static int
14091 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14092 {
14093 dtrace_helpers_t *help;
14094 dtrace_helper_provider_t *hprov, **tmp_provs;
14095 uint_t tmp_maxprovs, i;
14096
14097 ASSERT(MUTEX_HELD(&dtrace_lock));
14098
14099 help = curproc->p_dtrace_helpers;
14100 ASSERT(help != NULL);
14101
14102 /*
14103 * If we already have dtrace_helper_providers_max helper providers,
14104 * we're refuse to add a new one.
14105 */
14106 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14107 return (ENOSPC);
14108
14109 /*
14110 * Check to make sure this isn't a duplicate.
14111 */
14112 for (i = 0; i < help->dthps_nprovs; i++) {
14113 if (dofhp->dofhp_dof ==
14114 help->dthps_provs[i]->dthp_prov.dofhp_dof)
14115 return (EALREADY);
14116 }
14117
14118 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14119 hprov->dthp_prov = *dofhp;
14120 hprov->dthp_ref = 1;
14121 hprov->dthp_generation = gen;
14122
14123 /*
14124 * Allocate a bigger table for helper providers if it's already full.
14125 */
14126 if (help->dthps_maxprovs == help->dthps_nprovs) {
14127 tmp_maxprovs = help->dthps_maxprovs;
14128 tmp_provs = help->dthps_provs;
14129
14130 if (help->dthps_maxprovs == 0)
14131 help->dthps_maxprovs = 2;
14132 else
14133 help->dthps_maxprovs *= 2;
14134 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14135 help->dthps_maxprovs = dtrace_helper_providers_max;
14136
14137 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14138
14139 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14140 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14141
14142 if (tmp_provs != NULL) {
14143 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14144 sizeof (dtrace_helper_provider_t *));
14145 kmem_free(tmp_provs, tmp_maxprovs *
14146 sizeof (dtrace_helper_provider_t *));
14147 }
14148 }
14149
14150 help->dthps_provs[help->dthps_nprovs] = hprov;
14151 help->dthps_nprovs++;
14152
14153 return (0);
14154 }
14155
14156 static void
14157 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14158 {
14159 mutex_enter(&dtrace_lock);
14160
14161 if (--hprov->dthp_ref == 0) {
14162 dof_hdr_t *dof;
14163 mutex_exit(&dtrace_lock);
14164 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14165 dtrace_dof_destroy(dof);
14166 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14167 } else {
14168 mutex_exit(&dtrace_lock);
14169 }
14170 }
14171
14172 static int
14173 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14174 {
14175 uintptr_t daddr = (uintptr_t)dof;
14176 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14177 dof_provider_t *provider;
14178 dof_probe_t *probe;
14179 uint8_t *arg;
14180 char *strtab, *typestr;
14181 dof_stridx_t typeidx;
14182 size_t typesz;
14183 uint_t nprobes, j, k;
14184
14185 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14186
14187 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14188 dtrace_dof_error(dof, "misaligned section offset");
14189 return (-1);
14190 }
14191
14192 /*
14193 * The section needs to be large enough to contain the DOF provider
14194 * structure appropriate for the given version.
14195 */
14196 if (sec->dofs_size <
14197 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14198 offsetof(dof_provider_t, dofpv_prenoffs) :
14199 sizeof (dof_provider_t))) {
14200 dtrace_dof_error(dof, "provider section too small");
14201 return (-1);
14202 }
14203
14204 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14205 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14206 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14207 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14208 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14209
14210 if (str_sec == NULL || prb_sec == NULL ||
14211 arg_sec == NULL || off_sec == NULL)
14212 return (-1);
14213
14214 enoff_sec = NULL;
14215
14216 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14217 provider->dofpv_prenoffs != DOF_SECT_NONE &&
14218 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14219 provider->dofpv_prenoffs)) == NULL)
14220 return (-1);
14221
14222 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14223
14224 if (provider->dofpv_name >= str_sec->dofs_size ||
14225 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14226 dtrace_dof_error(dof, "invalid provider name");
14227 return (-1);
14228 }
14229
14230 if (prb_sec->dofs_entsize == 0 ||
14231 prb_sec->dofs_entsize > prb_sec->dofs_size) {
14232 dtrace_dof_error(dof, "invalid entry size");
14233 return (-1);
14234 }
14235
14236 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14237 dtrace_dof_error(dof, "misaligned entry size");
14238 return (-1);
14239 }
14240
14241 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14242 dtrace_dof_error(dof, "invalid entry size");
14243 return (-1);
14244 }
14245
14246 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14247 dtrace_dof_error(dof, "misaligned section offset");
14248 return (-1);
14249 }
14250
14251 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14252 dtrace_dof_error(dof, "invalid entry size");
14253 return (-1);
14254 }
14255
14256 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14257
14258 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14259
14260 /*
14261 * Take a pass through the probes to check for errors.
14262 */
14263 for (j = 0; j < nprobes; j++) {
14264 probe = (dof_probe_t *)(uintptr_t)(daddr +
14265 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14266
14267 if (probe->dofpr_func >= str_sec->dofs_size) {
14268 dtrace_dof_error(dof, "invalid function name");
14269 return (-1);
14270 }
14271
14272 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14273 dtrace_dof_error(dof, "function name too long");
14274 return (-1);
14275 }
14276
14277 if (probe->dofpr_name >= str_sec->dofs_size ||
14278 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14279 dtrace_dof_error(dof, "invalid probe name");
14280 return (-1);
14281 }
14282
14283 /*
14284 * The offset count must not wrap the index, and the offsets
14285 * must also not overflow the section's data.
14286 */
14287 if (probe->dofpr_offidx + probe->dofpr_noffs <
14288 probe->dofpr_offidx ||
14289 (probe->dofpr_offidx + probe->dofpr_noffs) *
14290 off_sec->dofs_entsize > off_sec->dofs_size) {
14291 dtrace_dof_error(dof, "invalid probe offset");
14292 return (-1);
14293 }
14294
14295 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14296 /*
14297 * If there's no is-enabled offset section, make sure
14298 * there aren't any is-enabled offsets. Otherwise
14299 * perform the same checks as for probe offsets
14300 * (immediately above).
14301 */
14302 if (enoff_sec == NULL) {
14303 if (probe->dofpr_enoffidx != 0 ||
14304 probe->dofpr_nenoffs != 0) {
14305 dtrace_dof_error(dof, "is-enabled "
14306 "offsets with null section");
14307 return (-1);
14308 }
14309 } else if (probe->dofpr_enoffidx +
14310 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14311 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14312 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14313 dtrace_dof_error(dof, "invalid is-enabled "
14314 "offset");
14315 return (-1);
14316 }
14317
14318 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14319 dtrace_dof_error(dof, "zero probe and "
14320 "is-enabled offsets");
14321 return (-1);
14322 }
14323 } else if (probe->dofpr_noffs == 0) {
14324 dtrace_dof_error(dof, "zero probe offsets");
14325 return (-1);
14326 }
14327
14328 if (probe->dofpr_argidx + probe->dofpr_xargc <
14329 probe->dofpr_argidx ||
14330 (probe->dofpr_argidx + probe->dofpr_xargc) *
14331 arg_sec->dofs_entsize > arg_sec->dofs_size) {
14332 dtrace_dof_error(dof, "invalid args");
14333 return (-1);
14334 }
14335
14336 typeidx = probe->dofpr_nargv;
14337 typestr = strtab + probe->dofpr_nargv;
14338 for (k = 0; k < probe->dofpr_nargc; k++) {
14339 if (typeidx >= str_sec->dofs_size) {
14340 dtrace_dof_error(dof, "bad "
14341 "native argument type");
14342 return (-1);
14343 }
14344
14345 typesz = strlen(typestr) + 1;
14346 if (typesz > DTRACE_ARGTYPELEN) {
14347 dtrace_dof_error(dof, "native "
14348 "argument type too long");
14349 return (-1);
14350 }
14351 typeidx += typesz;
14352 typestr += typesz;
14353 }
14354
14355 typeidx = probe->dofpr_xargv;
14356 typestr = strtab + probe->dofpr_xargv;
14357 for (k = 0; k < probe->dofpr_xargc; k++) {
14358 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14359 dtrace_dof_error(dof, "bad "
14360 "native argument index");
14361 return (-1);
14362 }
14363
14364 if (typeidx >= str_sec->dofs_size) {
14365 dtrace_dof_error(dof, "bad "
14366 "translated argument type");
14367 return (-1);
14368 }
14369
14370 typesz = strlen(typestr) + 1;
14371 if (typesz > DTRACE_ARGTYPELEN) {
14372 dtrace_dof_error(dof, "translated argument "
14373 "type too long");
14374 return (-1);
14375 }
14376
14377 typeidx += typesz;
14378 typestr += typesz;
14379 }
14380 }
14381
14382 return (0);
14383 }
14384
14385 static int
14386 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14387 {
14388 dtrace_helpers_t *help;
14389 dtrace_vstate_t *vstate;
14390 dtrace_enabling_t *enab = NULL;
14391 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14392 uintptr_t daddr = (uintptr_t)dof;
14393
14394 ASSERT(MUTEX_HELD(&dtrace_lock));
14395
14396 if ((help = curproc->p_dtrace_helpers) == NULL)
14397 help = dtrace_helpers_create(curproc);
14398
14399 vstate = &help->dthps_vstate;
14400
14401 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14402 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14403 dtrace_dof_destroy(dof);
14404 return (rv);
14405 }
14406
14407 /*
14408 * Look for helper providers and validate their descriptions.
14409 */
14410 if (dhp != NULL) {
14411 for (i = 0; i < dof->dofh_secnum; i++) {
14412 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14413 dof->dofh_secoff + i * dof->dofh_secsize);
14414
14415 if (sec->dofs_type != DOF_SECT_PROVIDER)
14416 continue;
14417
14418 if (dtrace_helper_provider_validate(dof, sec) != 0) {
14419 dtrace_enabling_destroy(enab);
14420 dtrace_dof_destroy(dof);
14421 return (-1);
14422 }
14423
14424 nprovs++;
14425 }
14426 }
14427
14428 /*
14429 * Now we need to walk through the ECB descriptions in the enabling.
14430 */
14431 for (i = 0; i < enab->dten_ndesc; i++) {
14432 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14433 dtrace_probedesc_t *desc = &ep->dted_probe;
14434
14435 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14436 continue;
14437
14438 if (strcmp(desc->dtpd_mod, "helper") != 0)
14439 continue;
14440
14441 if (strcmp(desc->dtpd_func, "ustack") != 0)
14442 continue;
14443
14444 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14445 ep)) != 0) {
14446 /*
14447 * Adding this helper action failed -- we are now going
14448 * to rip out the entire generation and return failure.
14449 */
14450 (void) dtrace_helper_destroygen(help->dthps_generation);
14451 dtrace_enabling_destroy(enab);
14452 dtrace_dof_destroy(dof);
14453 return (-1);
14454 }
14455
14456 nhelpers++;
14457 }
14458
14459 if (nhelpers < enab->dten_ndesc)
14460 dtrace_dof_error(dof, "unmatched helpers");
14461
14462 gen = help->dthps_generation++;
14463 dtrace_enabling_destroy(enab);
14464
14465 if (dhp != NULL && nprovs > 0) {
14466 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14467 if (dtrace_helper_provider_add(dhp, gen) == 0) {
14468 mutex_exit(&dtrace_lock);
14469 dtrace_helper_provider_register(curproc, help, dhp);
14470 mutex_enter(&dtrace_lock);
14471
14472 destroy = 0;
14473 }
14474 }
14475
14476 if (destroy)
14477 dtrace_dof_destroy(dof);
14478
14479 return (gen);
14480 }
14481
14482 static dtrace_helpers_t *
14483 dtrace_helpers_create(proc_t *p)
14484 {
14485 dtrace_helpers_t *help;
14486
14487 ASSERT(MUTEX_HELD(&dtrace_lock));
14488 ASSERT(p->p_dtrace_helpers == NULL);
14489
14490 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14491 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14492 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14493
14494 p->p_dtrace_helpers = help;
14495 dtrace_helpers++;
14496
14497 return (help);
14498 }
14499
14500 static void
14501 dtrace_helpers_destroy(void)
14502 {
14503 dtrace_helpers_t *help;
14504 dtrace_vstate_t *vstate;
14505 proc_t *p = curproc;
14506 int i;
14507
14508 mutex_enter(&dtrace_lock);
14509
14510 ASSERT(p->p_dtrace_helpers != NULL);
14511 ASSERT(dtrace_helpers > 0);
14512
14513 help = p->p_dtrace_helpers;
14514 vstate = &help->dthps_vstate;
14515
14516 /*
14517 * We're now going to lose the help from this process.
14518 */
14519 p->p_dtrace_helpers = NULL;
14520 dtrace_sync();
14521
14522 /*
14523 * Destory the helper actions.
14524 */
14525 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14526 dtrace_helper_action_t *h, *next;
14527
14528 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14529 next = h->dtha_next;
14530 dtrace_helper_action_destroy(h, vstate);
14531 h = next;
14532 }
14533 }
14534
14535 mutex_exit(&dtrace_lock);
14536
14537 /*
14538 * Destroy the helper providers.
14539 */
14540 if (help->dthps_maxprovs > 0) {
14541 mutex_enter(&dtrace_meta_lock);
14542 if (dtrace_meta_pid != NULL) {
14543 ASSERT(dtrace_deferred_pid == NULL);
14544
14545 for (i = 0; i < help->dthps_nprovs; i++) {
14546 dtrace_helper_provider_remove(
14547 &help->dthps_provs[i]->dthp_prov, p->p_pid);
14548 }
14549 } else {
14550 mutex_enter(&dtrace_lock);
14551 ASSERT(help->dthps_deferred == 0 ||
14552 help->dthps_next != NULL ||
14553 help->dthps_prev != NULL ||
14554 help == dtrace_deferred_pid);
14555
14556 /*
14557 * Remove the helper from the deferred list.
14558 */
14559 if (help->dthps_next != NULL)
14560 help->dthps_next->dthps_prev = help->dthps_prev;
14561 if (help->dthps_prev != NULL)
14562 help->dthps_prev->dthps_next = help->dthps_next;
14563 if (dtrace_deferred_pid == help) {
14564 dtrace_deferred_pid = help->dthps_next;
14565 ASSERT(help->dthps_prev == NULL);
14566 }
14567
14568 mutex_exit(&dtrace_lock);
14569 }
14570
14571 mutex_exit(&dtrace_meta_lock);
14572
14573 for (i = 0; i < help->dthps_nprovs; i++) {
14574 dtrace_helper_provider_destroy(help->dthps_provs[i]);
14575 }
14576
14577 kmem_free(help->dthps_provs, help->dthps_maxprovs *
14578 sizeof (dtrace_helper_provider_t *));
14579 }
14580
14581 mutex_enter(&dtrace_lock);
14582
14583 dtrace_vstate_fini(&help->dthps_vstate);
14584 kmem_free(help->dthps_actions,
14585 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
14586 kmem_free(help, sizeof (dtrace_helpers_t));
14587
14588 --dtrace_helpers;
14589 mutex_exit(&dtrace_lock);
14590 }
14591
14592 static void
14593 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
14594 {
14595 dtrace_helpers_t *help, *newhelp;
14596 dtrace_helper_action_t *helper, *new, *last;
14597 dtrace_difo_t *dp;
14598 dtrace_vstate_t *vstate;
14599 int i, j, sz, hasprovs = 0;
14600
14601 mutex_enter(&dtrace_lock);
14602 ASSERT(from->p_dtrace_helpers != NULL);
14603 ASSERT(dtrace_helpers > 0);
14604
14605 help = from->p_dtrace_helpers;
14606 newhelp = dtrace_helpers_create(to);
14607 ASSERT(to->p_dtrace_helpers != NULL);
14608
14609 newhelp->dthps_generation = help->dthps_generation;
14610 vstate = &newhelp->dthps_vstate;
14611
14612 /*
14613 * Duplicate the helper actions.
14614 */
14615 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14616 if ((helper = help->dthps_actions[i]) == NULL)
14617 continue;
14618
14619 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
14620 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
14621 KM_SLEEP);
14622 new->dtha_generation = helper->dtha_generation;
14623
14624 if ((dp = helper->dtha_predicate) != NULL) {
14625 dp = dtrace_difo_duplicate(dp, vstate);
14626 new->dtha_predicate = dp;
14627 }
14628
14629 new->dtha_nactions = helper->dtha_nactions;
14630 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
14631 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
14632
14633 for (j = 0; j < new->dtha_nactions; j++) {
14634 dtrace_difo_t *dp = helper->dtha_actions[j];
14635
14636 ASSERT(dp != NULL);
14637 dp = dtrace_difo_duplicate(dp, vstate);
14638 new->dtha_actions[j] = dp;
14639 }
14640
14641 if (last != NULL) {
14642 last->dtha_next = new;
14643 } else {
14644 newhelp->dthps_actions[i] = new;
14645 }
14646
14647 last = new;
14648 }
14649 }
14650
14651 /*
14652 * Duplicate the helper providers and register them with the
14653 * DTrace framework.
14654 */
14655 if (help->dthps_nprovs > 0) {
14656 newhelp->dthps_nprovs = help->dthps_nprovs;
14657 newhelp->dthps_maxprovs = help->dthps_nprovs;
14658 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
14659 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14660 for (i = 0; i < newhelp->dthps_nprovs; i++) {
14661 newhelp->dthps_provs[i] = help->dthps_provs[i];
14662 newhelp->dthps_provs[i]->dthp_ref++;
14663 }
14664
14665 hasprovs = 1;
14666 }
14667
14668 mutex_exit(&dtrace_lock);
14669
14670 if (hasprovs)
14671 dtrace_helper_provider_register(to, newhelp, NULL);
14672 }
14673
14674 /*
14675 * DTrace Hook Functions
14676 */
14677 static void
14678 dtrace_module_loaded(struct modctl *ctl)
14679 {
14680 dtrace_provider_t *prv;
14681
14682 mutex_enter(&dtrace_provider_lock);
14683 mutex_enter(&mod_lock);
14684
14685 ASSERT(ctl->mod_busy);
14686
14687 /*
14688 * We're going to call each providers per-module provide operation
14689 * specifying only this module.
14690 */
14691 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
14692 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
14693
14694 mutex_exit(&mod_lock);
14695 mutex_exit(&dtrace_provider_lock);
14696
14697 /*
14698 * If we have any retained enablings, we need to match against them.
14699 * Enabling probes requires that cpu_lock be held, and we cannot hold
14700 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
14701 * module. (In particular, this happens when loading scheduling
14702 * classes.) So if we have any retained enablings, we need to dispatch
14703 * our task queue to do the match for us.
14704 */
14705 mutex_enter(&dtrace_lock);
14706
14707 if (dtrace_retained == NULL) {
14708 mutex_exit(&dtrace_lock);
14709 return;
14710 }
14711
14712 (void) taskq_dispatch(dtrace_taskq,
14713 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
14714
14715 mutex_exit(&dtrace_lock);
14716
14717 /*
14718 * And now, for a little heuristic sleaze: in general, we want to
14719 * match modules as soon as they load. However, we cannot guarantee
14720 * this, because it would lead us to the lock ordering violation
14721 * outlined above. The common case, of course, is that cpu_lock is
14722 * _not_ held -- so we delay here for a clock tick, hoping that that's
14723 * long enough for the task queue to do its work. If it's not, it's
14724 * not a serious problem -- it just means that the module that we
14725 * just loaded may not be immediately instrumentable.
14726 */
14727 delay(1);
14728 }
14729
14730 static void
14731 dtrace_module_unloaded(struct modctl *ctl)
14732 {
14733 dtrace_probe_t template, *probe, *first, *next;
14734 dtrace_provider_t *prov;
14735
14736 template.dtpr_mod = ctl->mod_modname;
14737
14738 mutex_enter(&dtrace_provider_lock);
14739 mutex_enter(&mod_lock);
14740 mutex_enter(&dtrace_lock);
14741
14742 if (dtrace_bymod == NULL) {
14743 /*
14744 * The DTrace module is loaded (obviously) but not attached;
14745 * we don't have any work to do.
14746 */
14747 mutex_exit(&dtrace_provider_lock);
14748 mutex_exit(&mod_lock);
14749 mutex_exit(&dtrace_lock);
14750 return;
14751 }
14752
14753 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
14754 probe != NULL; probe = probe->dtpr_nextmod) {
14755 if (probe->dtpr_ecb != NULL) {
14756 mutex_exit(&dtrace_provider_lock);
14757 mutex_exit(&mod_lock);
14758 mutex_exit(&dtrace_lock);
14759
14760 /*
14761 * This shouldn't _actually_ be possible -- we're
14762 * unloading a module that has an enabled probe in it.
14763 * (It's normally up to the provider to make sure that
14764 * this can't happen.) However, because dtps_enable()
14765 * doesn't have a failure mode, there can be an
14766 * enable/unload race. Upshot: we don't want to
14767 * assert, but we're not going to disable the
14768 * probe, either.
14769 */
14770 if (dtrace_err_verbose) {
14771 cmn_err(CE_WARN, "unloaded module '%s' had "
14772 "enabled probes", ctl->mod_modname);
14773 }
14774
14775 return;
14776 }
14777 }
14778
14779 probe = first;
14780
14781 for (first = NULL; probe != NULL; probe = next) {
14782 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
14783
14784 dtrace_probes[probe->dtpr_id - 1] = NULL;
14785
14786 next = probe->dtpr_nextmod;
14787 dtrace_hash_remove(dtrace_bymod, probe);
14788 dtrace_hash_remove(dtrace_byfunc, probe);
14789 dtrace_hash_remove(dtrace_byname, probe);
14790
14791 if (first == NULL) {
14792 first = probe;
14793 probe->dtpr_nextmod = NULL;
14794 } else {
14795 probe->dtpr_nextmod = first;
14796 first = probe;
14797 }
14798 }
14799
14800 /*
14801 * We've removed all of the module's probes from the hash chains and
14802 * from the probe array. Now issue a dtrace_sync() to be sure that
14803 * everyone has cleared out from any probe array processing.
14804 */
14805 dtrace_sync();
14806
14807 for (probe = first; probe != NULL; probe = first) {
14808 first = probe->dtpr_nextmod;
14809 prov = probe->dtpr_provider;
14810 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
14811 probe->dtpr_arg);
14812 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
14813 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
14814 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
14815 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
14816 kmem_free(probe, sizeof (dtrace_probe_t));
14817 }
14818
14819 mutex_exit(&dtrace_lock);
14820 mutex_exit(&mod_lock);
14821 mutex_exit(&dtrace_provider_lock);
14822 }
14823
14824 void
14825 dtrace_suspend(void)
14826 {
14827 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
14828 }
14829
14830 void
14831 dtrace_resume(void)
14832 {
14833 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
14834 }
14835
14836 static int
14837 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
14838 {
14839 ASSERT(MUTEX_HELD(&cpu_lock));
14840 mutex_enter(&dtrace_lock);
14841
14842 switch (what) {
14843 case CPU_CONFIG: {
14844 dtrace_state_t *state;
14845 dtrace_optval_t *opt, rs, c;
14846
14847 /*
14848 * For now, we only allocate a new buffer for anonymous state.
14849 */
14850 if ((state = dtrace_anon.dta_state) == NULL)
14851 break;
14852
14853 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14854 break;
14855
14856 opt = state->dts_options;
14857 c = opt[DTRACEOPT_CPU];
14858
14859 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
14860 break;
14861
14862 /*
14863 * Regardless of what the actual policy is, we're going to
14864 * temporarily set our resize policy to be manual. We're
14865 * also going to temporarily set our CPU option to denote
14866 * the newly configured CPU.
14867 */
14868 rs = opt[DTRACEOPT_BUFRESIZE];
14869 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14870 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14871
14872 (void) dtrace_state_buffers(state);
14873
14874 opt[DTRACEOPT_BUFRESIZE] = rs;
14875 opt[DTRACEOPT_CPU] = c;
14876
14877 break;
14878 }
14879
14880 case CPU_UNCONFIG:
14881 /*
14882 * We don't free the buffer in the CPU_UNCONFIG case. (The
14883 * buffer will be freed when the consumer exits.)
14884 */
14885 break;
14886
14887 default:
14888 break;
14889 }
14890
14891 mutex_exit(&dtrace_lock);
14892 return (0);
14893 }
14894
14895 static void
14896 dtrace_cpu_setup_initial(processorid_t cpu)
14897 {
14898 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14899 }
14900
14901 static void
14902 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14903 {
14904 if (dtrace_toxranges >= dtrace_toxranges_max) {
14905 int osize, nsize;
14906 dtrace_toxrange_t *range;
14907
14908 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14909
14910 if (osize == 0) {
14911 ASSERT(dtrace_toxrange == NULL);
14912 ASSERT(dtrace_toxranges_max == 0);
14913 dtrace_toxranges_max = 1;
14914 } else {
14915 dtrace_toxranges_max <<= 1;
14916 }
14917
14918 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14919 range = kmem_zalloc(nsize, KM_SLEEP);
14920
14921 if (dtrace_toxrange != NULL) {
14922 ASSERT(osize != 0);
14923 bcopy(dtrace_toxrange, range, osize);
14924 kmem_free(dtrace_toxrange, osize);
14925 }
14926
14927 dtrace_toxrange = range;
14928 }
14929
14930 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14931 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14932
14933 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14934 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14935 dtrace_toxranges++;
14936 }
14937
14938 static void
14939 dtrace_getf_barrier()
14940 {
14941 /*
14942 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
14943 * that contain calls to getf(), this routine will be called on every
14944 * closef() before either the underlying vnode is released or the
14945 * file_t itself is freed. By the time we are here, it is essential
14946 * that the file_t can no longer be accessed from a call to getf()
14947 * in probe context -- that assures that a dtrace_sync() can be used
14948 * to clear out any enablings referring to the old structures.
14949 */
14950 if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
14951 kcred->cr_zone->zone_dtrace_getf != 0)
14952 dtrace_sync();
14953 }
14954
14955 /*
14956 * DTrace Driver Cookbook Functions
14957 */
14958 /*ARGSUSED*/
14959 static int
14960 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14961 {
14962 dtrace_provider_id_t id;
14963 dtrace_state_t *state = NULL;
14964 dtrace_enabling_t *enab;
14965
14966 mutex_enter(&cpu_lock);
14967 mutex_enter(&dtrace_provider_lock);
14968 mutex_enter(&dtrace_lock);
14969
14970 if (ddi_soft_state_init(&dtrace_softstate,
14971 sizeof (dtrace_state_t), 0) != 0) {
14972 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14973 mutex_exit(&cpu_lock);
14974 mutex_exit(&dtrace_provider_lock);
14975 mutex_exit(&dtrace_lock);
14976 return (DDI_FAILURE);
14977 }
14978
14979 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14980 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14981 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14982 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14983 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14984 ddi_remove_minor_node(devi, NULL);
14985 ddi_soft_state_fini(&dtrace_softstate);
14986 mutex_exit(&cpu_lock);
14987 mutex_exit(&dtrace_provider_lock);
14988 mutex_exit(&dtrace_lock);
14989 return (DDI_FAILURE);
14990 }
14991
14992 ddi_report_dev(devi);
14993 dtrace_devi = devi;
14994
14995 dtrace_modload = dtrace_module_loaded;
14996 dtrace_modunload = dtrace_module_unloaded;
14997 dtrace_cpu_init = dtrace_cpu_setup_initial;
14998 dtrace_helpers_cleanup = dtrace_helpers_destroy;
14999 dtrace_helpers_fork = dtrace_helpers_duplicate;
15000 dtrace_cpustart_init = dtrace_suspend;
15001 dtrace_cpustart_fini = dtrace_resume;
15002 dtrace_debugger_init = dtrace_suspend;
15003 dtrace_debugger_fini = dtrace_resume;
15004
15005 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15006
15007 ASSERT(MUTEX_HELD(&cpu_lock));
15008
15009 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15010 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15011 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15012 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15013 VM_SLEEP | VMC_IDENTIFIER);
15014 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15015 1, INT_MAX, 0);
15016
15017 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15018 sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15019 NULL, NULL, NULL, NULL, NULL, 0);
15020
15021 ASSERT(MUTEX_HELD(&cpu_lock));
15022 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15023 offsetof(dtrace_probe_t, dtpr_nextmod),
15024 offsetof(dtrace_probe_t, dtpr_prevmod));
15025
15026 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15027 offsetof(dtrace_probe_t, dtpr_nextfunc),
15028 offsetof(dtrace_probe_t, dtpr_prevfunc));
15029
15030 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15031 offsetof(dtrace_probe_t, dtpr_nextname),
15032 offsetof(dtrace_probe_t, dtpr_prevname));
15033
15034 if (dtrace_retain_max < 1) {
15035 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15036 "setting to 1", dtrace_retain_max);
15037 dtrace_retain_max = 1;
15038 }
15039
15040 /*
15041 * Now discover our toxic ranges.
15042 */
15043 dtrace_toxic_ranges(dtrace_toxrange_add);
15044
15045 /*
15046 * Before we register ourselves as a provider to our own framework,
15047 * we would like to assert that dtrace_provider is NULL -- but that's
15048 * not true if we were loaded as a dependency of a DTrace provider.
15049 * Once we've registered, we can assert that dtrace_provider is our
15050 * pseudo provider.
15051 */
15052 (void) dtrace_register("dtrace", &dtrace_provider_attr,
15053 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15054
15055 ASSERT(dtrace_provider != NULL);
15056 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15057
15058 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15059 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15060 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15061 dtrace_provider, NULL, NULL, "END", 0, NULL);
15062 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15063 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15064
15065 dtrace_anon_property();
15066 mutex_exit(&cpu_lock);
15067
15068 /*
15069 * If DTrace helper tracing is enabled, we need to allocate the
15070 * trace buffer and initialize the values.
15071 */
15072 if (dtrace_helptrace_enabled) {
15073 ASSERT(dtrace_helptrace_buffer == NULL);
15074 dtrace_helptrace_buffer =
15075 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15076 dtrace_helptrace_next = 0;
15077 }
15078
15079 /*
15080 * If there are already providers, we must ask them to provide their
15081 * probes, and then match any anonymous enabling against them. Note
15082 * that there should be no other retained enablings at this time:
15083 * the only retained enablings at this time should be the anonymous
15084 * enabling.
15085 */
15086 if (dtrace_anon.dta_enabling != NULL) {
15087 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15088
15089 dtrace_enabling_provide(NULL);
15090 state = dtrace_anon.dta_state;
15091
15092 /*
15093 * We couldn't hold cpu_lock across the above call to
15094 * dtrace_enabling_provide(), but we must hold it to actually
15095 * enable the probes. We have to drop all of our locks, pick
15096 * up cpu_lock, and regain our locks before matching the
15097 * retained anonymous enabling.
15098 */
15099 mutex_exit(&dtrace_lock);
15100 mutex_exit(&dtrace_provider_lock);
15101
15102 mutex_enter(&cpu_lock);
15103 mutex_enter(&dtrace_provider_lock);
15104 mutex_enter(&dtrace_lock);
15105
15106 if ((enab = dtrace_anon.dta_enabling) != NULL)
15107 (void) dtrace_enabling_match(enab, NULL);
15108
15109 mutex_exit(&cpu_lock);
15110 }
15111
15112 mutex_exit(&dtrace_lock);
15113 mutex_exit(&dtrace_provider_lock);
15114
15115 if (state != NULL) {
15116 /*
15117 * If we created any anonymous state, set it going now.
15118 */
15119 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15120 }
15121
15122 return (DDI_SUCCESS);
15123 }
15124
15125 /*ARGSUSED*/
15126 static int
15127 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15128 {
15129 dtrace_state_t *state;
15130 uint32_t priv;
15131 uid_t uid;
15132 zoneid_t zoneid;
15133
15134 if (getminor(*devp) == DTRACEMNRN_HELPER)
15135 return (0);
15136
15137 /*
15138 * If this wasn't an open with the "helper" minor, then it must be
15139 * the "dtrace" minor.
15140 */
15141 if (getminor(*devp) != DTRACEMNRN_DTRACE)
15142 return (ENXIO);
15143
15144 /*
15145 * If no DTRACE_PRIV_* bits are set in the credential, then the
15146 * caller lacks sufficient permission to do anything with DTrace.
15147 */
15148 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15149 if (priv == DTRACE_PRIV_NONE)
15150 return (EACCES);
15151
15152 /*
15153 * Ask all providers to provide all their probes.
15154 */
15155 mutex_enter(&dtrace_provider_lock);
15156 dtrace_probe_provide(NULL, NULL);
15157 mutex_exit(&dtrace_provider_lock);
15158
15159 mutex_enter(&cpu_lock);
15160 mutex_enter(&dtrace_lock);
15161 dtrace_opens++;
15162 dtrace_membar_producer();
15163
15164 /*
15165 * If the kernel debugger is active (that is, if the kernel debugger
15166 * modified text in some way), we won't allow the open.
15167 */
15168 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15169 dtrace_opens--;
15170 mutex_exit(&cpu_lock);
15171 mutex_exit(&dtrace_lock);
15172 return (EBUSY);
15173 }
15174
15175 state = dtrace_state_create(devp, cred_p);
15176 mutex_exit(&cpu_lock);
15177
15178 if (state == NULL) {
15179 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15180 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15181 mutex_exit(&dtrace_lock);
15182 return (EAGAIN);
15183 }
15184
15185 mutex_exit(&dtrace_lock);
15186
15187 return (0);
15188 }
15189
15190 /*ARGSUSED*/
15191 static int
15192 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15193 {
15194 minor_t minor = getminor(dev);
15195 dtrace_state_t *state;
15196
15197 if (minor == DTRACEMNRN_HELPER)
15198 return (0);
15199
15200 state = ddi_get_soft_state(dtrace_softstate, minor);
15201
15202 mutex_enter(&cpu_lock);
15203 mutex_enter(&dtrace_lock);
15204
15205 if (state->dts_anon) {
15206 /*
15207 * There is anonymous state. Destroy that first.
15208 */
15209 ASSERT(dtrace_anon.dta_state == NULL);
15210 dtrace_state_destroy(state->dts_anon);
15211 }
15212
15213 dtrace_state_destroy(state);
15214 ASSERT(dtrace_opens > 0);
15215
15216 /*
15217 * Only relinquish control of the kernel debugger interface when there
15218 * are no consumers and no anonymous enablings.
15219 */
15220 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15221 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15222
15223 mutex_exit(&dtrace_lock);
15224 mutex_exit(&cpu_lock);
15225
15226 return (0);
15227 }
15228
15229 /*ARGSUSED*/
15230 static int
15231 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15232 {
15233 int rval;
15234 dof_helper_t help, *dhp = NULL;
15235
15236 switch (cmd) {
15237 case DTRACEHIOC_ADDDOF:
15238 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15239 dtrace_dof_error(NULL, "failed to copyin DOF helper");
15240 return (EFAULT);
15241 }
15242
15243 dhp = &help;
15244 arg = (intptr_t)help.dofhp_dof;
15245 /*FALLTHROUGH*/
15246
15247 case DTRACEHIOC_ADD: {
15248 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15249
15250 if (dof == NULL)
15251 return (rval);
15252
15253 mutex_enter(&dtrace_lock);
15254
15255 /*
15256 * dtrace_helper_slurp() takes responsibility for the dof --
15257 * it may free it now or it may save it and free it later.
15258 */
15259 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15260 *rv = rval;
15261 rval = 0;
15262 } else {
15263 rval = EINVAL;
15264 }
15265
15266 mutex_exit(&dtrace_lock);
15267 return (rval);
15268 }
15269
15270 case DTRACEHIOC_REMOVE: {
15271 mutex_enter(&dtrace_lock);
15272 rval = dtrace_helper_destroygen(arg);
15273 mutex_exit(&dtrace_lock);
15274
15275 return (rval);
15276 }
15277
15278 default:
15279 break;
15280 }
15281
15282 return (ENOTTY);
15283 }
15284
15285 /*ARGSUSED*/
15286 static int
15287 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15288 {
15289 minor_t minor = getminor(dev);
15290 dtrace_state_t *state;
15291 int rval;
15292
15293 if (minor == DTRACEMNRN_HELPER)
15294 return (dtrace_ioctl_helper(cmd, arg, rv));
15295
15296 state = ddi_get_soft_state(dtrace_softstate, minor);
15297
15298 if (state->dts_anon) {
15299 ASSERT(dtrace_anon.dta_state == NULL);
15300 state = state->dts_anon;
15301 }
15302
15303 switch (cmd) {
15304 case DTRACEIOC_PROVIDER: {
15305 dtrace_providerdesc_t pvd;
15306 dtrace_provider_t *pvp;
15307
15308 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15309 return (EFAULT);
15310
15311 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15312 mutex_enter(&dtrace_provider_lock);
15313
15314 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15315 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15316 break;
15317 }
15318
15319 mutex_exit(&dtrace_provider_lock);
15320
15321 if (pvp == NULL)
15322 return (ESRCH);
15323
15324 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15325 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15326 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15327 return (EFAULT);
15328
15329 return (0);
15330 }
15331
15332 case DTRACEIOC_EPROBE: {
15333 dtrace_eprobedesc_t epdesc;
15334 dtrace_ecb_t *ecb;
15335 dtrace_action_t *act;
15336 void *buf;
15337 size_t size;
15338 uintptr_t dest;
15339 int nrecs;
15340
15341 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15342 return (EFAULT);
15343
15344 mutex_enter(&dtrace_lock);
15345
15346 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15347 mutex_exit(&dtrace_lock);
15348 return (EINVAL);
15349 }
15350
15351 if (ecb->dte_probe == NULL) {
15352 mutex_exit(&dtrace_lock);
15353 return (EINVAL);
15354 }
15355
15356 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15357 epdesc.dtepd_uarg = ecb->dte_uarg;
15358 epdesc.dtepd_size = ecb->dte_size;
15359
15360 nrecs = epdesc.dtepd_nrecs;
15361 epdesc.dtepd_nrecs = 0;
15362 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15363 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15364 continue;
15365
15366 epdesc.dtepd_nrecs++;
15367 }
15368
15369 /*
15370 * Now that we have the size, we need to allocate a temporary
15371 * buffer in which to store the complete description. We need
15372 * the temporary buffer to be able to drop dtrace_lock()
15373 * across the copyout(), below.
15374 */
15375 size = sizeof (dtrace_eprobedesc_t) +
15376 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
15377
15378 buf = kmem_alloc(size, KM_SLEEP);
15379 dest = (uintptr_t)buf;
15380
15381 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
15382 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
15383
15384 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15385 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15386 continue;
15387
15388 if (nrecs-- == 0)
15389 break;
15390
15391 bcopy(&act->dta_rec, (void *)dest,
15392 sizeof (dtrace_recdesc_t));
15393 dest += sizeof (dtrace_recdesc_t);
15394 }
15395
15396 mutex_exit(&dtrace_lock);
15397
15398 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15399 kmem_free(buf, size);
15400 return (EFAULT);
15401 }
15402
15403 kmem_free(buf, size);
15404 return (0);
15405 }
15406
15407 case DTRACEIOC_AGGDESC: {
15408 dtrace_aggdesc_t aggdesc;
15409 dtrace_action_t *act;
15410 dtrace_aggregation_t *agg;
15411 int nrecs;
15412 uint32_t offs;
15413 dtrace_recdesc_t *lrec;
15414 void *buf;
15415 size_t size;
15416 uintptr_t dest;
15417
15418 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
15419 return (EFAULT);
15420
15421 mutex_enter(&dtrace_lock);
15422
15423 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
15424 mutex_exit(&dtrace_lock);
15425 return (EINVAL);
15426 }
15427
15428 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
15429
15430 nrecs = aggdesc.dtagd_nrecs;
15431 aggdesc.dtagd_nrecs = 0;
15432
15433 offs = agg->dtag_base;
15434 lrec = &agg->dtag_action.dta_rec;
15435 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
15436
15437 for (act = agg->dtag_first; ; act = act->dta_next) {
15438 ASSERT(act->dta_intuple ||
15439 DTRACEACT_ISAGG(act->dta_kind));
15440
15441 /*
15442 * If this action has a record size of zero, it
15443 * denotes an argument to the aggregating action.
15444 * Because the presence of this record doesn't (or
15445 * shouldn't) affect the way the data is interpreted,
15446 * we don't copy it out to save user-level the
15447 * confusion of dealing with a zero-length record.
15448 */
15449 if (act->dta_rec.dtrd_size == 0) {
15450 ASSERT(agg->dtag_hasarg);
15451 continue;
15452 }
15453
15454 aggdesc.dtagd_nrecs++;
15455
15456 if (act == &agg->dtag_action)
15457 break;
15458 }
15459
15460 /*
15461 * Now that we have the size, we need to allocate a temporary
15462 * buffer in which to store the complete description. We need
15463 * the temporary buffer to be able to drop dtrace_lock()
15464 * across the copyout(), below.
15465 */
15466 size = sizeof (dtrace_aggdesc_t) +
15467 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
15468
15469 buf = kmem_alloc(size, KM_SLEEP);
15470 dest = (uintptr_t)buf;
15471
15472 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
15473 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
15474
15475 for (act = agg->dtag_first; ; act = act->dta_next) {
15476 dtrace_recdesc_t rec = act->dta_rec;
15477
15478 /*
15479 * See the comment in the above loop for why we pass
15480 * over zero-length records.
15481 */
15482 if (rec.dtrd_size == 0) {
15483 ASSERT(agg->dtag_hasarg);
15484 continue;
15485 }
15486
15487 if (nrecs-- == 0)
15488 break;
15489
15490 rec.dtrd_offset -= offs;
15491 bcopy(&rec, (void *)dest, sizeof (rec));
15492 dest += sizeof (dtrace_recdesc_t);
15493
15494 if (act == &agg->dtag_action)
15495 break;
15496 }
15497
15498 mutex_exit(&dtrace_lock);
15499
15500 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15501 kmem_free(buf, size);
15502 return (EFAULT);
15503 }
15504
15505 kmem_free(buf, size);
15506 return (0);
15507 }
15508
15509 case DTRACEIOC_ENABLE: {
15510 dof_hdr_t *dof;
15511 dtrace_enabling_t *enab = NULL;
15512 dtrace_vstate_t *vstate;
15513 int err = 0;
15514
15515 *rv = 0;
15516
15517 /*
15518 * If a NULL argument has been passed, we take this as our
15519 * cue to reevaluate our enablings.
15520 */
15521 if (arg == NULL) {
15522 dtrace_enabling_matchall();
15523
15524 return (0);
15525 }
15526
15527 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
15528 return (rval);
15529
15530 mutex_enter(&cpu_lock);
15531 mutex_enter(&dtrace_lock);
15532 vstate = &state->dts_vstate;
15533
15534 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
15535 mutex_exit(&dtrace_lock);
15536 mutex_exit(&cpu_lock);
15537 dtrace_dof_destroy(dof);
15538 return (EBUSY);
15539 }
15540
15541 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
15542 mutex_exit(&dtrace_lock);
15543 mutex_exit(&cpu_lock);
15544 dtrace_dof_destroy(dof);
15545 return (EINVAL);
15546 }
15547
15548 if ((rval = dtrace_dof_options(dof, state)) != 0) {
15549 dtrace_enabling_destroy(enab);
15550 mutex_exit(&dtrace_lock);
15551 mutex_exit(&cpu_lock);
15552 dtrace_dof_destroy(dof);
15553 return (rval);
15554 }
15555
15556 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
15557 err = dtrace_enabling_retain(enab);
15558 } else {
15559 dtrace_enabling_destroy(enab);
15560 }
15561
15562 mutex_exit(&cpu_lock);
15563 mutex_exit(&dtrace_lock);
15564 dtrace_dof_destroy(dof);
15565
15566 return (err);
15567 }
15568
15569 case DTRACEIOC_REPLICATE: {
15570 dtrace_repldesc_t desc;
15571 dtrace_probedesc_t *match = &desc.dtrpd_match;
15572 dtrace_probedesc_t *create = &desc.dtrpd_create;
15573 int err;
15574
15575 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15576 return (EFAULT);
15577
15578 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15579 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15580 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15581 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15582
15583 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15584 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15585 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15586 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15587
15588 mutex_enter(&dtrace_lock);
15589 err = dtrace_enabling_replicate(state, match, create);
15590 mutex_exit(&dtrace_lock);
15591
15592 return (err);
15593 }
15594
15595 case DTRACEIOC_PROBEMATCH:
15596 case DTRACEIOC_PROBES: {
15597 dtrace_probe_t *probe = NULL;
15598 dtrace_probedesc_t desc;
15599 dtrace_probekey_t pkey;
15600 dtrace_id_t i;
15601 int m = 0;
15602 uint32_t priv;
15603 uid_t uid;
15604 zoneid_t zoneid;
15605
15606 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15607 return (EFAULT);
15608
15609 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15610 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15611 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15612 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15613
15614 /*
15615 * Before we attempt to match this probe, we want to give
15616 * all providers the opportunity to provide it.
15617 */
15618 if (desc.dtpd_id == DTRACE_IDNONE) {
15619 mutex_enter(&dtrace_provider_lock);
15620 dtrace_probe_provide(&desc, NULL);
15621 mutex_exit(&dtrace_provider_lock);
15622 desc.dtpd_id++;
15623 }
15624
15625 if (cmd == DTRACEIOC_PROBEMATCH) {
15626 dtrace_probekey(&desc, &pkey);
15627 pkey.dtpk_id = DTRACE_IDNONE;
15628 }
15629
15630 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
15631
15632 mutex_enter(&dtrace_lock);
15633
15634 if (cmd == DTRACEIOC_PROBEMATCH) {
15635 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15636 if ((probe = dtrace_probes[i - 1]) != NULL &&
15637 (m = dtrace_match_probe(probe, &pkey,
15638 priv, uid, zoneid)) != 0)
15639 break;
15640 }
15641
15642 if (m < 0) {
15643 mutex_exit(&dtrace_lock);
15644 return (EINVAL);
15645 }
15646
15647 } else {
15648 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15649 if ((probe = dtrace_probes[i - 1]) != NULL &&
15650 dtrace_match_priv(probe, priv, uid, zoneid))
15651 break;
15652 }
15653 }
15654
15655 if (probe == NULL) {
15656 mutex_exit(&dtrace_lock);
15657 return (ESRCH);
15658 }
15659
15660 dtrace_probe_description(probe, &desc);
15661 mutex_exit(&dtrace_lock);
15662
15663 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15664 return (EFAULT);
15665
15666 return (0);
15667 }
15668
15669 case DTRACEIOC_PROBEARG: {
15670 dtrace_argdesc_t desc;
15671 dtrace_probe_t *probe;
15672 dtrace_provider_t *prov;
15673
15674 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15675 return (EFAULT);
15676
15677 if (desc.dtargd_id == DTRACE_IDNONE)
15678 return (EINVAL);
15679
15680 if (desc.dtargd_ndx == DTRACE_ARGNONE)
15681 return (EINVAL);
15682
15683 mutex_enter(&dtrace_provider_lock);
15684 mutex_enter(&mod_lock);
15685 mutex_enter(&dtrace_lock);
15686
15687 if (desc.dtargd_id > dtrace_nprobes) {
15688 mutex_exit(&dtrace_lock);
15689 mutex_exit(&mod_lock);
15690 mutex_exit(&dtrace_provider_lock);
15691 return (EINVAL);
15692 }
15693
15694 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
15695 mutex_exit(&dtrace_lock);
15696 mutex_exit(&mod_lock);
15697 mutex_exit(&dtrace_provider_lock);
15698 return (EINVAL);
15699 }
15700
15701 mutex_exit(&dtrace_lock);
15702
15703 prov = probe->dtpr_provider;
15704
15705 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
15706 /*
15707 * There isn't any typed information for this probe.
15708 * Set the argument number to DTRACE_ARGNONE.
15709 */
15710 desc.dtargd_ndx = DTRACE_ARGNONE;
15711 } else {
15712 desc.dtargd_native[0] = '\0';
15713 desc.dtargd_xlate[0] = '\0';
15714 desc.dtargd_mapping = desc.dtargd_ndx;
15715
15716 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
15717 probe->dtpr_id, probe->dtpr_arg, &desc);
15718 }
15719
15720 mutex_exit(&mod_lock);
15721 mutex_exit(&dtrace_provider_lock);
15722
15723 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15724 return (EFAULT);
15725
15726 return (0);
15727 }
15728
15729 case DTRACEIOC_GO: {
15730 processorid_t cpuid;
15731 rval = dtrace_state_go(state, &cpuid);
15732
15733 if (rval != 0)
15734 return (rval);
15735
15736 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15737 return (EFAULT);
15738
15739 return (0);
15740 }
15741
15742 case DTRACEIOC_STOP: {
15743 processorid_t cpuid;
15744
15745 mutex_enter(&dtrace_lock);
15746 rval = dtrace_state_stop(state, &cpuid);
15747 mutex_exit(&dtrace_lock);
15748
15749 if (rval != 0)
15750 return (rval);
15751
15752 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15753 return (EFAULT);
15754
15755 return (0);
15756 }
15757
15758 case DTRACEIOC_DOFGET: {
15759 dof_hdr_t hdr, *dof;
15760 uint64_t len;
15761
15762 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
15763 return (EFAULT);
15764
15765 mutex_enter(&dtrace_lock);
15766 dof = dtrace_dof_create(state);
15767 mutex_exit(&dtrace_lock);
15768
15769 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
15770 rval = copyout(dof, (void *)arg, len);
15771 dtrace_dof_destroy(dof);
15772
15773 return (rval == 0 ? 0 : EFAULT);
15774 }
15775
15776 case DTRACEIOC_AGGSNAP:
15777 case DTRACEIOC_BUFSNAP: {
15778 dtrace_bufdesc_t desc;
15779 caddr_t cached;
15780 dtrace_buffer_t *buf;
15781
15782 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15783 return (EFAULT);
15784
15785 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
15786 return (EINVAL);
15787
15788 mutex_enter(&dtrace_lock);
15789
15790 if (cmd == DTRACEIOC_BUFSNAP) {
15791 buf = &state->dts_buffer[desc.dtbd_cpu];
15792 } else {
15793 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
15794 }
15795
15796 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
15797 size_t sz = buf->dtb_offset;
15798
15799 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
15800 mutex_exit(&dtrace_lock);
15801 return (EBUSY);
15802 }
15803
15804 /*
15805 * If this buffer has already been consumed, we're
15806 * going to indicate that there's nothing left here
15807 * to consume.
15808 */
15809 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
15810 mutex_exit(&dtrace_lock);
15811
15812 desc.dtbd_size = 0;
15813 desc.dtbd_drops = 0;
15814 desc.dtbd_errors = 0;
15815 desc.dtbd_oldest = 0;
15816 sz = sizeof (desc);
15817
15818 if (copyout(&desc, (void *)arg, sz) != 0)
15819 return (EFAULT);
15820
15821 return (0);
15822 }
15823
15824 /*
15825 * If this is a ring buffer that has wrapped, we want
15826 * to copy the whole thing out.
15827 */
15828 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
15829 dtrace_buffer_polish(buf);
15830 sz = buf->dtb_size;
15831 }
15832
15833 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
15834 mutex_exit(&dtrace_lock);
15835 return (EFAULT);
15836 }
15837
15838 desc.dtbd_size = sz;
15839 desc.dtbd_drops = buf->dtb_drops;
15840 desc.dtbd_errors = buf->dtb_errors;
15841 desc.dtbd_oldest = buf->dtb_xamot_offset;
15842 desc.dtbd_timestamp = dtrace_gethrtime();
15843
15844 mutex_exit(&dtrace_lock);
15845
15846 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15847 return (EFAULT);
15848
15849 buf->dtb_flags |= DTRACEBUF_CONSUMED;
15850
15851 return (0);
15852 }
15853
15854 if (buf->dtb_tomax == NULL) {
15855 ASSERT(buf->dtb_xamot == NULL);
15856 mutex_exit(&dtrace_lock);
15857 return (ENOENT);
15858 }
15859
15860 cached = buf->dtb_tomax;
15861 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
15862
15863 dtrace_xcall(desc.dtbd_cpu,
15864 (dtrace_xcall_t)dtrace_buffer_switch, buf);
15865
15866 state->dts_errors += buf->dtb_xamot_errors;
15867
15868 /*
15869 * If the buffers did not actually switch, then the cross call
15870 * did not take place -- presumably because the given CPU is
15871 * not in the ready set. If this is the case, we'll return
15872 * ENOENT.
15873 */
15874 if (buf->dtb_tomax == cached) {
15875 ASSERT(buf->dtb_xamot != cached);
15876 mutex_exit(&dtrace_lock);
15877 return (ENOENT);
15878 }
15879
15880 ASSERT(cached == buf->dtb_xamot);
15881
15882 /*
15883 * We have our snapshot; now copy it out.
15884 */
15885 if (copyout(buf->dtb_xamot, desc.dtbd_data,
15886 buf->dtb_xamot_offset) != 0) {
15887 mutex_exit(&dtrace_lock);
15888 return (EFAULT);
15889 }
15890
15891 desc.dtbd_size = buf->dtb_xamot_offset;
15892 desc.dtbd_drops = buf->dtb_xamot_drops;
15893 desc.dtbd_errors = buf->dtb_xamot_errors;
15894 desc.dtbd_oldest = 0;
15895 desc.dtbd_timestamp = buf->dtb_switched;
15896
15897 mutex_exit(&dtrace_lock);
15898
15899 /*
15900 * Finally, copy out the buffer description.
15901 */
15902 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15903 return (EFAULT);
15904
15905 return (0);
15906 }
15907
15908 case DTRACEIOC_CONF: {
15909 dtrace_conf_t conf;
15910
15911 bzero(&conf, sizeof (conf));
15912 conf.dtc_difversion = DIF_VERSION;
15913 conf.dtc_difintregs = DIF_DIR_NREGS;
15914 conf.dtc_diftupregs = DIF_DTR_NREGS;
15915 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15916
15917 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15918 return (EFAULT);
15919
15920 return (0);
15921 }
15922
15923 case DTRACEIOC_STATUS: {
15924 dtrace_status_t stat;
15925 dtrace_dstate_t *dstate;
15926 int i, j;
15927 uint64_t nerrs;
15928
15929 /*
15930 * See the comment in dtrace_state_deadman() for the reason
15931 * for setting dts_laststatus to INT64_MAX before setting
15932 * it to the correct value.
15933 */
15934 state->dts_laststatus = INT64_MAX;
15935 dtrace_membar_producer();
15936 state->dts_laststatus = dtrace_gethrtime();
15937
15938 bzero(&stat, sizeof (stat));
15939
15940 mutex_enter(&dtrace_lock);
15941
15942 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15943 mutex_exit(&dtrace_lock);
15944 return (ENOENT);
15945 }
15946
15947 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15948 stat.dtst_exiting = 1;
15949
15950 nerrs = state->dts_errors;
15951 dstate = &state->dts_vstate.dtvs_dynvars;
15952
15953 for (i = 0; i < NCPU; i++) {
15954 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15955
15956 stat.dtst_dyndrops += dcpu->dtdsc_drops;
15957 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15958 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15959
15960 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15961 stat.dtst_filled++;
15962
15963 nerrs += state->dts_buffer[i].dtb_errors;
15964
15965 for (j = 0; j < state->dts_nspeculations; j++) {
15966 dtrace_speculation_t *spec;
15967 dtrace_buffer_t *buf;
15968
15969 spec = &state->dts_speculations[j];
15970 buf = &spec->dtsp_buffer[i];
15971 stat.dtst_specdrops += buf->dtb_xamot_drops;
15972 }
15973 }
15974
15975 stat.dtst_specdrops_busy = state->dts_speculations_busy;
15976 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15977 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15978 stat.dtst_dblerrors = state->dts_dblerrors;
15979 stat.dtst_killed =
15980 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15981 stat.dtst_errors = nerrs;
15982
15983 mutex_exit(&dtrace_lock);
15984
15985 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15986 return (EFAULT);
15987
15988 return (0);
15989 }
15990
15991 case DTRACEIOC_FORMAT: {
15992 dtrace_fmtdesc_t fmt;
15993 char *str;
15994 int len;
15995
15996 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15997 return (EFAULT);
15998
15999 mutex_enter(&dtrace_lock);
16000
16001 if (fmt.dtfd_format == 0 ||
16002 fmt.dtfd_format > state->dts_nformats) {
16003 mutex_exit(&dtrace_lock);
16004 return (EINVAL);
16005 }
16006
16007 /*
16008 * Format strings are allocated contiguously and they are
16009 * never freed; if a format index is less than the number
16010 * of formats, we can assert that the format map is non-NULL
16011 * and that the format for the specified index is non-NULL.
16012 */
16013 ASSERT(state->dts_formats != NULL);
16014 str = state->dts_formats[fmt.dtfd_format - 1];
16015 ASSERT(str != NULL);
16016
16017 len = strlen(str) + 1;
16018
16019 if (len > fmt.dtfd_length) {
16020 fmt.dtfd_length = len;
16021
16022 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16023 mutex_exit(&dtrace_lock);
16024 return (EINVAL);
16025 }
16026 } else {
16027 if (copyout(str, fmt.dtfd_string, len) != 0) {
16028 mutex_exit(&dtrace_lock);
16029 return (EINVAL);
16030 }
16031 }
16032
16033 mutex_exit(&dtrace_lock);
16034 return (0);
16035 }
16036
16037 default:
16038 break;
16039 }
16040
16041 return (ENOTTY);
16042 }
16043
16044 /*ARGSUSED*/
16045 static int
16046 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16047 {
16048 dtrace_state_t *state;
16049
16050 switch (cmd) {
16051 case DDI_DETACH:
16052 break;
16053
16054 case DDI_SUSPEND:
16055 return (DDI_SUCCESS);
16056
16057 default:
16058 return (DDI_FAILURE);
16059 }
16060
16061 mutex_enter(&cpu_lock);
16062 mutex_enter(&dtrace_provider_lock);
16063 mutex_enter(&dtrace_lock);
16064
16065 ASSERT(dtrace_opens == 0);
16066
16067 if (dtrace_helpers > 0) {
16068 mutex_exit(&dtrace_provider_lock);
16069 mutex_exit(&dtrace_lock);
16070 mutex_exit(&cpu_lock);
16071 return (DDI_FAILURE);
16072 }
16073
16074 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16075 mutex_exit(&dtrace_provider_lock);
16076 mutex_exit(&dtrace_lock);
16077 mutex_exit(&cpu_lock);
16078 return (DDI_FAILURE);
16079 }
16080
16081 dtrace_provider = NULL;
16082
16083 if ((state = dtrace_anon_grab()) != NULL) {
16084 /*
16085 * If there were ECBs on this state, the provider should
16086 * have not been allowed to detach; assert that there is
16087 * none.
16088 */
16089 ASSERT(state->dts_necbs == 0);
16090 dtrace_state_destroy(state);
16091
16092 /*
16093 * If we're being detached with anonymous state, we need to
16094 * indicate to the kernel debugger that DTrace is now inactive.
16095 */
16096 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16097 }
16098
16099 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
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
16111 ASSERT(dtrace_getf == 0);
16112 ASSERT(dtrace_closef == NULL);
16113
16114 mutex_exit(&cpu_lock);
16115
16116 if (dtrace_helptrace_enabled) {
16117 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
16118 dtrace_helptrace_buffer = NULL;
16119 }
16120
16121 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16122 dtrace_probes = NULL;
16123 dtrace_nprobes = 0;
16124
16125 dtrace_hash_destroy(dtrace_bymod);
16126 dtrace_hash_destroy(dtrace_byfunc);
16127 dtrace_hash_destroy(dtrace_byname);
16128 dtrace_bymod = NULL;
16129 dtrace_byfunc = NULL;
16130 dtrace_byname = NULL;
16131
16132 kmem_cache_destroy(dtrace_state_cache);
16133 vmem_destroy(dtrace_minor);
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 ddi_remove_minor_node(dtrace_devi, NULL);
16145 dtrace_devi = NULL;
16146
16147 ddi_soft_state_fini(&dtrace_softstate);
16148
16149 ASSERT(dtrace_vtime_references == 0);
16150 ASSERT(dtrace_opens == 0);
16151 ASSERT(dtrace_retained == NULL);
16152
16153 mutex_exit(&dtrace_lock);
16154 mutex_exit(&dtrace_provider_lock);
16155
16156 /*
16157 * We don't destroy the task queue until after we have dropped our
16158 * locks (taskq_destroy() may block on running tasks). To prevent
16159 * attempting to do work after we have effectively detached but before
16160 * the task queue has been destroyed, all tasks dispatched via the
16161 * task queue must check that DTrace is still attached before
16162 * performing any operation.
16163 */
16164 taskq_destroy(dtrace_taskq);
16165 dtrace_taskq = NULL;
16166
16167 return (DDI_SUCCESS);
16168 }
16169
16170 /*ARGSUSED*/
16171 static int
16172 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16173 {
16174 int error;
16175
16176 switch (infocmd) {
16177 case DDI_INFO_DEVT2DEVINFO:
16178 *result = (void *)dtrace_devi;
16179 error = DDI_SUCCESS;
16180 break;
16181 case DDI_INFO_DEVT2INSTANCE:
16182 *result = (void *)0;
16183 error = DDI_SUCCESS;
16184 break;
16185 default:
16186 error = DDI_FAILURE;
16187 }
16188 return (error);
16189 }
16190
16191 static struct cb_ops dtrace_cb_ops = {
16192 dtrace_open, /* open */
16193 dtrace_close, /* close */
16194 nulldev, /* strategy */
16195 nulldev, /* print */
16196 nodev, /* dump */
16197 nodev, /* read */
16198 nodev, /* write */
16199 dtrace_ioctl, /* ioctl */
16200 nodev, /* devmap */
16201 nodev, /* mmap */
16202 nodev, /* segmap */
16203 nochpoll, /* poll */
16204 ddi_prop_op, /* cb_prop_op */
16205 0, /* streamtab */
16206 D_NEW | D_MP /* Driver compatibility flag */
16207 };
16208
16209 static struct dev_ops dtrace_ops = {
16210 DEVO_REV, /* devo_rev */
16211 0, /* refcnt */
16212 dtrace_info, /* get_dev_info */
16213 nulldev, /* identify */
16214 nulldev, /* probe */
16215 dtrace_attach, /* attach */
16216 dtrace_detach, /* detach */
16217 nodev, /* reset */
16218 &dtrace_cb_ops, /* driver operations */
16219 NULL, /* bus operations */
16220 nodev, /* dev power */
16221 ddi_quiesce_not_needed, /* quiesce */
16222 };
16223
16224 static struct modldrv modldrv = {
16225 &mod_driverops, /* module type (this is a pseudo driver) */
16226 "Dynamic Tracing", /* name of module */
16227 &dtrace_ops, /* driver ops */
16228 };
16229
16230 static struct modlinkage modlinkage = {
16231 MODREV_1,
16232 (void *)&modldrv,
16233 NULL
16234 };
16235
16236 int
16237 _init(void)
16238 {
16239 return (mod_install(&modlinkage));
16240 }
16241
16242 int
16243 _info(struct modinfo *modinfop)
16244 {
16245 return (mod_info(&modlinkage, modinfop));
16246 }
16247
16248 int
16249 _fini(void)
16250 {
16251 return (mod_remove(&modlinkage));
16252 }