]> git.saurik.com Git - apple/xnu.git/blob - bsd/dev/dtrace/dtrace.c
xnu-2050.24.15.tar.gz
[apple/xnu.git] / bsd / dev / dtrace / dtrace.c
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 2009 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
25 */
26
27 /* #pragma ident "@(#)dtrace.c 1.65 08/07/02 SMI" */
28
29 /*
30 * DTrace - Dynamic Tracing for Solaris
31 *
32 * This is the implementation of the Solaris Dynamic Tracing framework
33 * (DTrace). The user-visible interface to DTrace is described at length in
34 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
35 * library, the in-kernel DTrace framework, and the DTrace providers are
36 * described in the block comments in the <sys/dtrace.h> header file. The
37 * internal architecture of DTrace is described in the block comments in the
38 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
39 * implementation very much assume mastery of all of these sources; if one has
40 * an unanswered question about the implementation, one should consult them
41 * first.
42 *
43 * The functions here are ordered roughly as follows:
44 *
45 * - Probe context functions
46 * - Probe hashing functions
47 * - Non-probe context utility functions
48 * - Matching functions
49 * - Provider-to-Framework API functions
50 * - Probe management functions
51 * - DIF object functions
52 * - Format functions
53 * - Predicate functions
54 * - ECB functions
55 * - Buffer functions
56 * - Enabling functions
57 * - DOF functions
58 * - Anonymous enabling functions
59 * - Consumer state functions
60 * - Helper functions
61 * - Hook functions
62 * - Driver cookbook functions
63 *
64 * Each group of functions begins with a block comment labelled the "DTrace
65 * [Group] Functions", allowing one to find each block by searching forward
66 * on capital-f functions.
67 */
68 #if !defined(__APPLE__)
69 #include <sys/errno.h>
70 #include <sys/stat.h>
71 #include <sys/modctl.h>
72 #include <sys/conf.h>
73 #include <sys/systm.h>
74 #include <sys/ddi.h>
75 #include <sys/sunddi.h>
76 #include <sys/cpuvar.h>
77 #include <sys/kmem.h>
78 #include <sys/strsubr.h>
79 #include <sys/sysmacros.h>
80 #include <sys/dtrace_impl.h>
81 #include <sys/atomic.h>
82 #include <sys/cmn_err.h>
83 #include <sys/mutex_impl.h>
84 #include <sys/rwlock_impl.h>
85 #include <sys/ctf_api.h>
86 #include <sys/panic.h>
87 #include <sys/priv_impl.h>
88 #include <sys/policy.h>
89 #include <sys/cred_impl.h>
90 #include <sys/procfs_isa.h>
91 #include <sys/taskq.h>
92 #include <sys/mkdev.h>
93 #include <sys/kdi.h>
94 #include <sys/zone.h>
95 #else
96 #include <sys/errno.h>
97 #include <sys/types.h>
98 #include <sys/stat.h>
99 #include <sys/conf.h>
100 #include <sys/systm.h>
101 #include <sys/dtrace_impl.h>
102 #include <sys/param.h>
103 #include <sys/proc_internal.h>
104 #include <sys/ioctl.h>
105 #include <sys/fcntl.h>
106 #include <miscfs/devfs/devfs.h>
107 #include <sys/malloc.h>
108 #include <sys/kernel_types.h>
109 #include <sys/proc_internal.h>
110 #include <sys/uio_internal.h>
111 #include <sys/kauth.h>
112 #include <vm/pmap.h>
113 #include <sys/user.h>
114 #include <mach/exception_types.h>
115 #include <sys/signalvar.h>
116 #include <mach/task.h>
117 #include <kern/zalloc.h>
118 #include <kern/ast.h>
119 #include <netinet/in.h>
120
121 #if defined(__APPLE__)
122 #include <kern/cpu_data.h>
123 extern uint32_t pmap_find_phys(void *, uint64_t);
124 extern boolean_t pmap_valid_page(uint32_t);
125 extern void OSKextRegisterKextsWithDTrace(void);
126 extern kmod_info_t g_kernel_kmod_info;
127 #endif /* __APPLE__ */
128
129
130 /* Solaris proc_t is the struct. Darwin's proc_t is a pointer to it. */
131 #define proc_t struct proc /* Steer clear of the Darwin typedef for proc_t */
132
133 #define t_predcache t_dtrace_predcache /* Cosmetic. Helps readability of thread.h */
134
135 extern void dtrace_suspend(void);
136 extern void dtrace_resume(void);
137 extern void dtrace_init(void);
138 extern void helper_init(void);
139 extern void fasttrap_init(void);
140 extern void dtrace_lazy_dofs_duplicate(proc_t *, proc_t *);
141 extern void dtrace_lazy_dofs_destroy(proc_t *);
142 extern void dtrace_postinit(void);
143
144 #include "../../../osfmk/chud/chud_dtrace.h"
145
146 extern kern_return_t chudxnu_dtrace_callback
147 (uint64_t selector, uint64_t *args, uint32_t count);
148
149 #endif /* __APPLE__ */
150
151 /*
152 * DTrace Tunable Variables
153 *
154 * The following variables may be tuned by adding a line to /etc/system that
155 * includes both the name of the DTrace module ("dtrace") and the name of the
156 * variable. For example:
157 *
158 * set dtrace:dtrace_destructive_disallow = 1
159 *
160 * In general, the only variables that one should be tuning this way are those
161 * that affect system-wide DTrace behavior, and for which the default behavior
162 * is undesirable. Most of these variables are tunable on a per-consumer
163 * basis using DTrace options, and need not be tuned on a system-wide basis.
164 * When tuning these variables, avoid pathological values; while some attempt
165 * is made to verify the integrity of these variables, they are not considered
166 * part of the supported interface to DTrace, and they are therefore not
167 * checked comprehensively. Further, these variables should not be tuned
168 * dynamically via "mdb -kw" or other means; they should only be tuned via
169 * /etc/system.
170 */
171 int dtrace_destructive_disallow = 0;
172 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
173 size_t dtrace_difo_maxsize = (256 * 1024);
174 dtrace_optval_t dtrace_dof_maxsize = (384 * 1024);
175 size_t dtrace_global_maxsize = (16 * 1024);
176 size_t dtrace_actions_max = (16 * 1024);
177 size_t dtrace_retain_max = 1024;
178 dtrace_optval_t dtrace_helper_actions_max = 32;
179 dtrace_optval_t dtrace_helper_providers_max = 64;
180 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
181 size_t dtrace_strsize_default = 256;
182 dtrace_optval_t dtrace_cleanrate_default = 9900990; /* 101 hz */
183 dtrace_optval_t dtrace_cleanrate_min = 200000; /* 5000 hz */
184 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
185 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
186 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
187 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
188 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
189 dtrace_optval_t dtrace_nspec_default = 1;
190 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
191 dtrace_optval_t dtrace_stackframes_default = 20;
192 dtrace_optval_t dtrace_ustackframes_default = 20;
193 dtrace_optval_t dtrace_jstackframes_default = 50;
194 dtrace_optval_t dtrace_jstackstrsize_default = 512;
195 int dtrace_msgdsize_max = 128;
196 hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
197 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
198 int dtrace_devdepth_max = 32;
199 int dtrace_err_verbose;
200 hrtime_t dtrace_deadman_interval = NANOSEC;
201 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
202 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
203
204 /*
205 * DTrace External Variables
206 *
207 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
208 * available to DTrace consumers via the backtick (`) syntax. One of these,
209 * dtrace_zero, is made deliberately so: it is provided as a source of
210 * well-known, zero-filled memory. While this variable is not documented,
211 * it is used by some translators as an implementation detail.
212 */
213 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
214
215 /*
216 * DTrace Internal Variables
217 */
218 static dev_info_t *dtrace_devi; /* device info */
219 static vmem_t *dtrace_arena; /* probe ID arena */
220 static vmem_t *dtrace_minor; /* minor number arena */
221 static taskq_t *dtrace_taskq; /* task queue */
222 static dtrace_probe_t **dtrace_probes; /* array of all probes */
223 static int dtrace_nprobes; /* number of probes */
224 static dtrace_provider_t *dtrace_provider; /* provider list */
225 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
226 static int dtrace_opens; /* number of opens */
227 static int dtrace_helpers; /* number of helpers */
228 static void *dtrace_softstate; /* softstate pointer */
229 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
230 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
231 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
232 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
233 static int dtrace_toxranges; /* number of toxic ranges */
234 static int dtrace_toxranges_max; /* size of toxic range array */
235 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
236 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
237 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
238 static kthread_t *dtrace_panicked; /* panicking thread */
239 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
240 static dtrace_genid_t dtrace_probegen; /* current probe generation */
241 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
242 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
243 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
244 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
245 #if defined(__APPLE__)
246 static int dtrace_dof_mode; /* See dtrace_impl.h for a description of Darwin's dof modes. */
247
248 /*
249 * This does't quite fit as an internal variable, as it must be accessed in
250 * fbt_provide and sdt_provide. Its clearly not a dtrace tunable variable either...
251 */
252 int dtrace_kernel_symbol_mode; /* See dtrace_impl.h for a description of Darwin's kernel symbol modes. */
253 #endif
254
255 #if defined(__APPLE__)
256 /*
257 * To save memory, some common memory allocations are given a
258 * unique zone. For example, dtrace_probe_t is 72 bytes in size,
259 * which means it would fall into the kalloc.128 bucket. With
260 * 20k elements allocated, the space saved is substantial.
261 */
262
263 struct zone *dtrace_probe_t_zone;
264
265 static int dtrace_module_unloaded(struct kmod_info *kmod);
266 #endif /* __APPLE__ */
267
268 /*
269 * DTrace Locking
270 * DTrace is protected by three (relatively coarse-grained) locks:
271 *
272 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
273 * including enabling state, probes, ECBs, consumer state, helper state,
274 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
275 * probe context is lock-free -- synchronization is handled via the
276 * dtrace_sync() cross call mechanism.
277 *
278 * (2) dtrace_provider_lock is required when manipulating provider state, or
279 * when provider state must be held constant.
280 *
281 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
282 * when meta provider state must be held constant.
283 *
284 * The lock ordering between these three locks is dtrace_meta_lock before
285 * dtrace_provider_lock before dtrace_lock. (In particular, there are
286 * several places where dtrace_provider_lock is held by the framework as it
287 * calls into the providers -- which then call back into the framework,
288 * grabbing dtrace_lock.)
289 *
290 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
291 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
292 * role as a coarse-grained lock; it is acquired before both of these locks.
293 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
294 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
295 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
296 * acquired _between_ dtrace_provider_lock and dtrace_lock.
297 */
298
299 #if !defined(__APPLE__)
300 static kmutex_t dtrace_lock; /* probe state lock */
301 static kmutex_t dtrace_provider_lock; /* provider state lock */
302 static kmutex_t dtrace_meta_lock; /* meta-provider state lock */
303 #else
304 /*
305 * APPLE NOTE:
306 *
307 * All kmutex_t vars have been changed to lck_mtx_t.
308 * Note that lck_mtx_t's require explicit initialization.
309 *
310 * mutex_enter() becomes lck_mtx_lock()
311 * mutex_exit() becomes lck_mtx_unlock()
312 *
313 * Lock asserts are changed like this:
314 *
315 * ASSERT(MUTEX_HELD(&cpu_lock));
316 * becomes:
317 * lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
318 *
319 * Due to the number of these changes, they are not called out explicitly.
320 */
321 static lck_mtx_t dtrace_lock; /* probe state lock */
322 static lck_mtx_t dtrace_provider_lock; /* provider state lock */
323 static lck_mtx_t dtrace_meta_lock; /* meta-provider state lock */
324 static lck_rw_t dtrace_dof_mode_lock; /* dof mode lock */
325 #endif /* __APPLE__ */
326
327 /*
328 * DTrace Provider Variables
329 *
330 * These are the variables relating to DTrace as a provider (that is, the
331 * provider of the BEGIN, END, and ERROR probes).
332 */
333 static dtrace_pattr_t dtrace_provider_attr = {
334 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
335 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
336 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
337 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
338 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
339 };
340
341 static void
342 dtrace_nullop(void)
343 {}
344
345 static int
346 dtrace_enable_nullop(void)
347 {
348 return (0);
349 }
350
351 static dtrace_pops_t dtrace_provider_ops = {
352 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
353 (void (*)(void *, struct modctl *))dtrace_nullop,
354 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
355 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
356 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
357 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
358 NULL,
359 NULL,
360 NULL,
361 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
362 };
363
364 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
365 static dtrace_id_t dtrace_probeid_end; /* special END probe */
366 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
367
368 /*
369 * DTrace Helper Tracing Variables
370 */
371 uint32_t dtrace_helptrace_next = 0;
372 uint32_t dtrace_helptrace_nlocals;
373 char *dtrace_helptrace_buffer;
374 #if !defined(__APPLE__) /* Quiet compiler warning */
375 int dtrace_helptrace_bufsize = 512 * 1024;
376 #else
377 size_t dtrace_helptrace_bufsize = 512 * 1024;
378 #endif /* __APPLE__ */
379
380 #if DEBUG
381 int dtrace_helptrace_enabled = 1;
382 #else
383 int dtrace_helptrace_enabled = 0;
384 #endif
385
386 /*
387 * DTrace Error Hashing
388 *
389 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
390 * table. This is very useful for checking coverage of tests that are
391 * expected to induce DIF or DOF processing errors, and may be useful for
392 * debugging problems in the DIF code generator or in DOF generation . The
393 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
394 */
395 #if DEBUG
396 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
397 static const char *dtrace_errlast;
398 static kthread_t *dtrace_errthread;
399 static lck_mtx_t dtrace_errlock;
400 #endif
401
402 /*
403 * DTrace Macros and Constants
404 *
405 * These are various macros that are useful in various spots in the
406 * implementation, along with a few random constants that have no meaning
407 * outside of the implementation. There is no real structure to this cpp
408 * mishmash -- but is there ever?
409 */
410 #define DTRACE_HASHSTR(hash, probe) \
411 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
412
413 #define DTRACE_HASHNEXT(hash, probe) \
414 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
415
416 #define DTRACE_HASHPREV(hash, probe) \
417 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
418
419 #define DTRACE_HASHEQ(hash, lhs, rhs) \
420 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
421 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
422
423 #define DTRACE_AGGHASHSIZE_SLEW 17
424
425 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
426
427 /*
428 * The key for a thread-local variable consists of the lower 61 bits of the
429 * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
430 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
431 * equal to a variable identifier. This is necessary (but not sufficient) to
432 * assure that global associative arrays never collide with thread-local
433 * variables. To guarantee that they cannot collide, we must also define the
434 * order for keying dynamic variables. That order is:
435 *
436 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
437 *
438 * Because the variable-key and the tls-key are in orthogonal spaces, there is
439 * no way for a global variable key signature to match a thread-local key
440 * signature.
441 */
442 #if !defined(__APPLE__)
443 #define DTRACE_TLS_THRKEY(where) { \
444 uint_t intr = 0; \
445 uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
446 for (; actv; actv >>= 1) \
447 intr++; \
448 ASSERT(intr < (1 << 3)); \
449 (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
450 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
451 }
452 #else
453 #if defined(__x86_64__)
454 /* FIXME: two function calls!! */
455 #define DTRACE_TLS_THRKEY(where) { \
456 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
457 uint64_t thr = (uintptr_t)current_thread(); \
458 ASSERT(intr < (1 << 3)); \
459 (where) = ((thr + DIF_VARIABLE_MAX) & \
460 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
461 }
462 #else
463 /* FIXME: three function calls!!! */
464 #define DTRACE_TLS_THRKEY(where) { \
465 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
466 uint64_t thr = (uintptr_t)current_thread(); \
467 uint_t pid = (uint_t)proc_selfpid(); \
468 ASSERT(intr < (1 << 3)); \
469 (where) = (((thr << 32 | pid) + DIF_VARIABLE_MAX) & \
470 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
471 }
472 #endif
473 #endif /* __APPLE__ */
474
475 #define DT_BSWAP_8(x) ((x) & 0xff)
476 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
477 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
478 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
479
480 #define DT_MASK_LO 0x00000000FFFFFFFFULL
481
482 #define DTRACE_STORE(type, tomax, offset, what) \
483 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
484
485 #if !defined(__APPLE__)
486 #ifndef __i386
487 #define DTRACE_ALIGNCHECK(addr, size, flags) \
488 if (addr & (size - 1)) { \
489 *flags |= CPU_DTRACE_BADALIGN; \
490 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
491 return (0); \
492 }
493 #else
494 #define DTRACE_ALIGNCHECK(addr, size, flags)
495 #endif
496 #else /* __APPLE__ */
497 #define DTRACE_ALIGNCHECK(addr, size, flags) \
498 if (addr & (MIN(size,4) - 1)) { \
499 *flags |= CPU_DTRACE_BADALIGN; \
500 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
501 return (0); \
502 }
503 #endif /* __APPLE__ */
504
505 /*
506 * Test whether a range of memory starting at testaddr of size testsz falls
507 * within the range of memory described by addr, sz. We take care to avoid
508 * problems with overflow and underflow of the unsigned quantities, and
509 * disallow all negative sizes. Ranges of size 0 are allowed.
510 */
511 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
512 ((testaddr) - (baseaddr) < (basesz) && \
513 (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
514 (testaddr) + (testsz) >= (testaddr))
515
516 /*
517 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
518 * alloc_sz on the righthand side of the comparison in order to avoid overflow
519 * or underflow in the comparison with it. This is simpler than the INRANGE
520 * check above, because we know that the dtms_scratch_ptr is valid in the
521 * range. Allocations of size zero are allowed.
522 */
523 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
524 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
525 (mstate)->dtms_scratch_ptr >= (alloc_sz))
526
527 #if !defined(__APPLE__)
528 #define DTRACE_LOADFUNC(bits) \
529 /*CSTYLED*/ \
530 uint##bits##_t \
531 dtrace_load##bits(uintptr_t addr) \
532 { \
533 size_t size = bits / NBBY; \
534 /*CSTYLED*/ \
535 uint##bits##_t rval; \
536 int i; \
537 volatile uint16_t *flags = (volatile uint16_t *) \
538 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
539 \
540 DTRACE_ALIGNCHECK(addr, size, flags); \
541 \
542 for (i = 0; i < dtrace_toxranges; i++) { \
543 if (addr >= dtrace_toxrange[i].dtt_limit) \
544 continue; \
545 \
546 if (addr + size <= dtrace_toxrange[i].dtt_base) \
547 continue; \
548 \
549 /* \
550 * This address falls within a toxic region; return 0. \
551 */ \
552 *flags |= CPU_DTRACE_BADADDR; \
553 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
554 return (0); \
555 } \
556 \
557 *flags |= CPU_DTRACE_NOFAULT; \
558 /*CSTYLED*/ \
559 rval = *((volatile uint##bits##_t *)addr); \
560 *flags &= ~CPU_DTRACE_NOFAULT; \
561 \
562 return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0); \
563 }
564 #else /* __APPLE__ */
565 #define RECOVER_LABEL(bits) dtraceLoadRecover##bits:
566
567 #if (defined(__i386__) || defined (__x86_64__))
568 #define DTRACE_LOADFUNC(bits) \
569 /*CSTYLED*/ \
570 uint##bits##_t dtrace_load##bits(uintptr_t addr); \
571 \
572 uint##bits##_t \
573 dtrace_load##bits(uintptr_t addr) \
574 { \
575 size_t size = bits / NBBY; \
576 /*CSTYLED*/ \
577 uint##bits##_t rval = 0; \
578 int i; \
579 volatile uint16_t *flags = (volatile uint16_t *) \
580 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
581 \
582 DTRACE_ALIGNCHECK(addr, size, flags); \
583 \
584 for (i = 0; i < dtrace_toxranges; i++) { \
585 if (addr >= dtrace_toxrange[i].dtt_limit) \
586 continue; \
587 \
588 if (addr + size <= dtrace_toxrange[i].dtt_base) \
589 continue; \
590 \
591 /* \
592 * This address falls within a toxic region; return 0. \
593 */ \
594 *flags |= CPU_DTRACE_BADADDR; \
595 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
596 return (0); \
597 } \
598 \
599 { \
600 volatile vm_offset_t recover = (vm_offset_t)&&dtraceLoadRecover##bits; \
601 *flags |= CPU_DTRACE_NOFAULT; \
602 recover = dtrace_set_thread_recover(current_thread(), recover); \
603 /*CSTYLED*/ \
604 /* \
605 * PR6394061 - avoid device memory that is unpredictably \
606 * mapped and unmapped \
607 */ \
608 if (pmap_valid_page(pmap_find_phys(kernel_pmap, addr))) \
609 rval = *((volatile uint##bits##_t *)addr); \
610 RECOVER_LABEL(bits); \
611 (void)dtrace_set_thread_recover(current_thread(), recover); \
612 *flags &= ~CPU_DTRACE_NOFAULT; \
613 } \
614 \
615 return (rval); \
616 }
617 #else /* all other architectures */
618 #define DTRACE_LOADFUNC(bits) \
619 /*CSTYLED*/ \
620 uint##bits##_t dtrace_load##bits(uintptr_t addr); \
621 \
622 uint##bits##_t \
623 dtrace_load##bits(uintptr_t addr) \
624 { \
625 size_t size = bits / NBBY; \
626 /*CSTYLED*/ \
627 uint##bits##_t rval = 0; \
628 int i; \
629 volatile uint16_t *flags = (volatile uint16_t *) \
630 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
631 \
632 DTRACE_ALIGNCHECK(addr, size, flags); \
633 \
634 for (i = 0; i < dtrace_toxranges; i++) { \
635 if (addr >= dtrace_toxrange[i].dtt_limit) \
636 continue; \
637 \
638 if (addr + size <= dtrace_toxrange[i].dtt_base) \
639 continue; \
640 \
641 /* \
642 * This address falls within a toxic region; return 0. \
643 */ \
644 *flags |= CPU_DTRACE_BADADDR; \
645 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
646 return (0); \
647 } \
648 \
649 { \
650 volatile vm_offset_t recover = (vm_offset_t)&&dtraceLoadRecover##bits; \
651 *flags |= CPU_DTRACE_NOFAULT; \
652 recover = dtrace_set_thread_recover(current_thread(), recover); \
653 /*CSTYLED*/ \
654 rval = *((volatile uint##bits##_t *)addr); \
655 RECOVER_LABEL(bits); \
656 (void)dtrace_set_thread_recover(current_thread(), recover); \
657 *flags &= ~CPU_DTRACE_NOFAULT; \
658 } \
659 \
660 return (rval); \
661 }
662 #endif
663 #endif /* __APPLE__ */
664
665 #ifdef __LP64__
666 #define dtrace_loadptr dtrace_load64
667 #else
668 #define dtrace_loadptr dtrace_load32
669 #endif
670
671 #define DTRACE_DYNHASH_FREE 0
672 #define DTRACE_DYNHASH_SINK 1
673 #define DTRACE_DYNHASH_VALID 2
674
675 #define DTRACE_MATCH_FAIL -1
676 #define DTRACE_MATCH_NEXT 0
677 #define DTRACE_MATCH_DONE 1
678 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
679 #define DTRACE_STATE_ALIGN 64
680
681 #define DTRACE_FLAGS2FLT(flags) \
682 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
683 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
684 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
685 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
686 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
687 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
688 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
689 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
690 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
691 DTRACEFLT_UNKNOWN)
692
693 #define DTRACEACT_ISSTRING(act) \
694 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
695 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
696
697
698 #if defined (__APPLE__)
699 /* Avoid compiler warnings when assigning regs[rd] = NULL */
700 #ifdef NULL
701 #undef NULL
702 #define NULL (uintptr_t)0
703 #endif
704 #endif /* __APPLE__ */
705
706 static size_t dtrace_strlen(const char *, size_t);
707 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
708 static void dtrace_enabling_provide(dtrace_provider_t *);
709 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
710 static void dtrace_enabling_matchall(void);
711 static dtrace_state_t *dtrace_anon_grab(void);
712 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
713 dtrace_state_t *, uint64_t, uint64_t);
714 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
715 static void dtrace_buffer_drop(dtrace_buffer_t *);
716 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
717 dtrace_state_t *, dtrace_mstate_t *);
718 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
719 dtrace_optval_t);
720 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
721 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
722
723 /*
724 * DTrace Probe Context Functions
725 *
726 * These functions are called from probe context. Because probe context is
727 * any context in which C may be called, arbitrarily locks may be held,
728 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
729 * As a result, functions called from probe context may only call other DTrace
730 * support functions -- they may not interact at all with the system at large.
731 * (Note that the ASSERT macro is made probe-context safe by redefining it in
732 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
733 * loads are to be performed from probe context, they _must_ be in terms of
734 * the safe dtrace_load*() variants.
735 *
736 * Some functions in this block are not actually called from probe context;
737 * for these functions, there will be a comment above the function reading
738 * "Note: not called from probe context."
739 */
740
741 int
742 dtrace_assfail(const char *a, const char *f, int l)
743 {
744 panic("dtrace: assertion failed: %s, file: %s, line: %d", a, f, l);
745
746 /*
747 * We just need something here that even the most clever compiler
748 * cannot optimize away.
749 */
750 return (a[(uintptr_t)f]);
751 }
752
753 /*
754 * Atomically increment a specified error counter from probe context.
755 */
756 static void
757 dtrace_error(uint32_t *counter)
758 {
759 /*
760 * Most counters stored to in probe context are per-CPU counters.
761 * However, there are some error conditions that are sufficiently
762 * arcane that they don't merit per-CPU storage. If these counters
763 * are incremented concurrently on different CPUs, scalability will be
764 * adversely affected -- but we don't expect them to be white-hot in a
765 * correctly constructed enabling...
766 */
767 uint32_t oval, nval;
768
769 do {
770 oval = *counter;
771
772 if ((nval = oval + 1) == 0) {
773 /*
774 * If the counter would wrap, set it to 1 -- assuring
775 * that the counter is never zero when we have seen
776 * errors. (The counter must be 32-bits because we
777 * aren't guaranteed a 64-bit compare&swap operation.)
778 * To save this code both the infamy of being fingered
779 * by a priggish news story and the indignity of being
780 * the target of a neo-puritan witch trial, we're
781 * carefully avoiding any colorful description of the
782 * likelihood of this condition -- but suffice it to
783 * say that it is only slightly more likely than the
784 * overflow of predicate cache IDs, as discussed in
785 * dtrace_predicate_create().
786 */
787 nval = 1;
788 }
789 } while (dtrace_cas32(counter, oval, nval) != oval);
790 }
791
792 /*
793 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
794 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
795 */
796 DTRACE_LOADFUNC(8)
797 DTRACE_LOADFUNC(16)
798 DTRACE_LOADFUNC(32)
799 DTRACE_LOADFUNC(64)
800
801 static int
802 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
803 {
804 if (dest < mstate->dtms_scratch_base)
805 return (0);
806
807 if (dest + size < dest)
808 return (0);
809
810 if (dest + size > mstate->dtms_scratch_ptr)
811 return (0);
812
813 return (1);
814 }
815
816 static int
817 dtrace_canstore_statvar(uint64_t addr, size_t sz,
818 dtrace_statvar_t **svars, int nsvars)
819 {
820 int i;
821
822 for (i = 0; i < nsvars; i++) {
823 dtrace_statvar_t *svar = svars[i];
824
825 if (svar == NULL || svar->dtsv_size == 0)
826 continue;
827
828 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
829 return (1);
830 }
831
832 return (0);
833 }
834
835 /*
836 * Check to see if the address is within a memory region to which a store may
837 * be issued. This includes the DTrace scratch areas, and any DTrace variable
838 * region. The caller of dtrace_canstore() is responsible for performing any
839 * alignment checks that are needed before stores are actually executed.
840 */
841 static int
842 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
843 dtrace_vstate_t *vstate)
844 {
845 /*
846 * First, check to see if the address is in scratch space...
847 */
848 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
849 mstate->dtms_scratch_size))
850 return (1);
851
852 /*
853 * Now check to see if it's a dynamic variable. This check will pick
854 * up both thread-local variables and any global dynamically-allocated
855 * variables.
856 */
857 if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
858 vstate->dtvs_dynvars.dtds_size)) {
859 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
860 uintptr_t base = (uintptr_t)dstate->dtds_base +
861 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
862 uintptr_t chunkoffs;
863
864 /*
865 * Before we assume that we can store here, we need to make
866 * sure that it isn't in our metadata -- storing to our
867 * dynamic variable metadata would corrupt our state. For
868 * the range to not include any dynamic variable metadata,
869 * it must:
870 *
871 * (1) Start above the hash table that is at the base of
872 * the dynamic variable space
873 *
874 * (2) Have a starting chunk offset that is beyond the
875 * dtrace_dynvar_t that is at the base of every chunk
876 *
877 * (3) Not span a chunk boundary
878 *
879 */
880 if (addr < base)
881 return (0);
882
883 chunkoffs = (addr - base) % dstate->dtds_chunksize;
884
885 if (chunkoffs < sizeof (dtrace_dynvar_t))
886 return (0);
887
888 if (chunkoffs + sz > dstate->dtds_chunksize)
889 return (0);
890
891 return (1);
892 }
893
894 /*
895 * Finally, check the static local and global variables. These checks
896 * take the longest, so we perform them last.
897 */
898 if (dtrace_canstore_statvar(addr, sz,
899 vstate->dtvs_locals, vstate->dtvs_nlocals))
900 return (1);
901
902 if (dtrace_canstore_statvar(addr, sz,
903 vstate->dtvs_globals, vstate->dtvs_nglobals))
904 return (1);
905
906 return (0);
907 }
908
909
910 /*
911 * Convenience routine to check to see if the address is within a memory
912 * region in which a load may be issued given the user's privilege level;
913 * if not, it sets the appropriate error flags and loads 'addr' into the
914 * illegal value slot.
915 *
916 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
917 * appropriate memory access protection.
918 */
919 static int
920 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
921 dtrace_vstate_t *vstate)
922 {
923 #if !defined(__APPLE__) /* Quiet compiler warning - matches dtrace_dif_emulate */
924 volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
925 #else
926 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
927 #endif /* __APPLE */
928
929 /*
930 * If we hold the privilege to read from kernel memory, then
931 * everything is readable.
932 */
933 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
934 return (1);
935
936 /*
937 * You can obviously read that which you can store.
938 */
939 if (dtrace_canstore(addr, sz, mstate, vstate))
940 return (1);
941
942 /*
943 * We're allowed to read from our own string table.
944 */
945 if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
946 mstate->dtms_difo->dtdo_strlen))
947 return (1);
948
949 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
950 *illval = addr;
951 return (0);
952 }
953
954 /*
955 * Convenience routine to check to see if a given string is within a memory
956 * region in which a load may be issued given the user's privilege level;
957 * this exists so that we don't need to issue unnecessary dtrace_strlen()
958 * calls in the event that the user has all privileges.
959 */
960 static int
961 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
962 dtrace_vstate_t *vstate)
963 {
964 size_t strsz;
965
966 /*
967 * If we hold the privilege to read from kernel memory, then
968 * everything is readable.
969 */
970 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
971 return (1);
972
973 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
974 if (dtrace_canload(addr, strsz, mstate, vstate))
975 return (1);
976
977 return (0);
978 }
979
980 /*
981 * Convenience routine to check to see if a given variable is within a memory
982 * region in which a load may be issued given the user's privilege level.
983 */
984 static int
985 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
986 dtrace_vstate_t *vstate)
987 {
988 size_t sz;
989 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
990
991 /*
992 * If we hold the privilege to read from kernel memory, then
993 * everything is readable.
994 */
995 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
996 return (1);
997
998 if (type->dtdt_kind == DIF_TYPE_STRING)
999 sz = dtrace_strlen(src,
1000 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
1001 else
1002 sz = type->dtdt_size;
1003
1004 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
1005 }
1006
1007 /*
1008 * Compare two strings using safe loads.
1009 */
1010 static int
1011 dtrace_strncmp(char *s1, char *s2, size_t limit)
1012 {
1013 uint8_t c1, c2;
1014 volatile uint16_t *flags;
1015
1016 if (s1 == s2 || limit == 0)
1017 return (0);
1018
1019 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1020
1021 do {
1022 if (s1 == NULL) {
1023 c1 = '\0';
1024 } else {
1025 c1 = dtrace_load8((uintptr_t)s1++);
1026 }
1027
1028 if (s2 == NULL) {
1029 c2 = '\0';
1030 } else {
1031 c2 = dtrace_load8((uintptr_t)s2++);
1032 }
1033
1034 if (c1 != c2)
1035 return (c1 - c2);
1036 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1037
1038 return (0);
1039 }
1040
1041 /*
1042 * Compute strlen(s) for a string using safe memory accesses. The additional
1043 * len parameter is used to specify a maximum length to ensure completion.
1044 */
1045 static size_t
1046 dtrace_strlen(const char *s, size_t lim)
1047 {
1048 uint_t len;
1049
1050 for (len = 0; len != lim; len++) {
1051 if (dtrace_load8((uintptr_t)s++) == '\0')
1052 break;
1053 }
1054
1055 return (len);
1056 }
1057
1058 /*
1059 * Check if an address falls within a toxic region.
1060 */
1061 static int
1062 dtrace_istoxic(uintptr_t kaddr, size_t size)
1063 {
1064 uintptr_t taddr, tsize;
1065 int i;
1066
1067 for (i = 0; i < dtrace_toxranges; i++) {
1068 taddr = dtrace_toxrange[i].dtt_base;
1069 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1070
1071 if (kaddr - taddr < tsize) {
1072 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1073 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1074 return (1);
1075 }
1076
1077 if (taddr - kaddr < size) {
1078 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1079 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1080 return (1);
1081 }
1082 }
1083
1084 return (0);
1085 }
1086
1087 /*
1088 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1089 * memory specified by the DIF program. The dst is assumed to be safe memory
1090 * that we can store to directly because it is managed by DTrace. As with
1091 * standard bcopy, overlapping copies are handled properly.
1092 */
1093 static void
1094 dtrace_bcopy(const void *src, void *dst, size_t len)
1095 {
1096 if (len != 0) {
1097 uint8_t *s1 = dst;
1098 const uint8_t *s2 = src;
1099
1100 if (s1 <= s2) {
1101 do {
1102 *s1++ = dtrace_load8((uintptr_t)s2++);
1103 } while (--len != 0);
1104 } else {
1105 s2 += len;
1106 s1 += len;
1107
1108 do {
1109 *--s1 = dtrace_load8((uintptr_t)--s2);
1110 } while (--len != 0);
1111 }
1112 }
1113 }
1114
1115 /*
1116 * Copy src to dst using safe memory accesses, up to either the specified
1117 * length, or the point that a nul byte is encountered. The src is assumed to
1118 * be unsafe memory specified by the DIF program. The dst is assumed to be
1119 * safe memory that we can store to directly because it is managed by DTrace.
1120 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1121 */
1122 static void
1123 dtrace_strcpy(const void *src, void *dst, size_t len)
1124 {
1125 if (len != 0) {
1126 uint8_t *s1 = dst, c;
1127 const uint8_t *s2 = src;
1128
1129 do {
1130 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1131 } while (--len != 0 && c != '\0');
1132 }
1133 }
1134
1135 /*
1136 * Copy src to dst, deriving the size and type from the specified (BYREF)
1137 * variable type. The src is assumed to be unsafe memory specified by the DIF
1138 * program. The dst is assumed to be DTrace variable memory that is of the
1139 * specified type; we assume that we can store to directly.
1140 */
1141 static void
1142 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1143 {
1144 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1145
1146 if (type->dtdt_kind == DIF_TYPE_STRING) {
1147 dtrace_strcpy(src, dst, type->dtdt_size);
1148 } else {
1149 dtrace_bcopy(src, dst, type->dtdt_size);
1150 }
1151 }
1152
1153 /*
1154 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1155 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1156 * safe memory that we can access directly because it is managed by DTrace.
1157 */
1158 static int
1159 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1160 {
1161 volatile uint16_t *flags;
1162
1163 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1164
1165 if (s1 == s2)
1166 return (0);
1167
1168 if (s1 == NULL || s2 == NULL)
1169 return (1);
1170
1171 if (s1 != s2 && len != 0) {
1172 const uint8_t *ps1 = s1;
1173 const uint8_t *ps2 = s2;
1174
1175 do {
1176 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1177 return (1);
1178 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1179 }
1180 return (0);
1181 }
1182
1183 /*
1184 * Zero the specified region using a simple byte-by-byte loop. Note that this
1185 * is for safe DTrace-managed memory only.
1186 */
1187 static void
1188 dtrace_bzero(void *dst, size_t len)
1189 {
1190 uchar_t *cp;
1191
1192 for (cp = dst; len != 0; len--)
1193 *cp++ = 0;
1194 }
1195
1196 static void
1197 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1198 {
1199 uint64_t result[2];
1200
1201 result[0] = addend1[0] + addend2[0];
1202 result[1] = addend1[1] + addend2[1] +
1203 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1204
1205 sum[0] = result[0];
1206 sum[1] = result[1];
1207 }
1208
1209 /*
1210 * Shift the 128-bit value in a by b. If b is positive, shift left.
1211 * If b is negative, shift right.
1212 */
1213 static void
1214 dtrace_shift_128(uint64_t *a, int b)
1215 {
1216 uint64_t mask;
1217
1218 if (b == 0)
1219 return;
1220
1221 if (b < 0) {
1222 b = -b;
1223 if (b >= 64) {
1224 a[0] = a[1] >> (b - 64);
1225 a[1] = 0;
1226 } else {
1227 a[0] >>= b;
1228 mask = 1LL << (64 - b);
1229 mask -= 1;
1230 a[0] |= ((a[1] & mask) << (64 - b));
1231 a[1] >>= b;
1232 }
1233 } else {
1234 if (b >= 64) {
1235 a[1] = a[0] << (b - 64);
1236 a[0] = 0;
1237 } else {
1238 a[1] <<= b;
1239 mask = a[0] >> (64 - b);
1240 a[1] |= mask;
1241 a[0] <<= b;
1242 }
1243 }
1244 }
1245
1246 /*
1247 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1248 * use native multiplication on those, and then re-combine into the
1249 * resulting 128-bit value.
1250 *
1251 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1252 * hi1 * hi2 << 64 +
1253 * hi1 * lo2 << 32 +
1254 * hi2 * lo1 << 32 +
1255 * lo1 * lo2
1256 */
1257 static void
1258 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1259 {
1260 uint64_t hi1, hi2, lo1, lo2;
1261 uint64_t tmp[2];
1262
1263 hi1 = factor1 >> 32;
1264 hi2 = factor2 >> 32;
1265
1266 lo1 = factor1 & DT_MASK_LO;
1267 lo2 = factor2 & DT_MASK_LO;
1268
1269 product[0] = lo1 * lo2;
1270 product[1] = hi1 * hi2;
1271
1272 tmp[0] = hi1 * lo2;
1273 tmp[1] = 0;
1274 dtrace_shift_128(tmp, 32);
1275 dtrace_add_128(product, tmp, product);
1276
1277 tmp[0] = hi2 * lo1;
1278 tmp[1] = 0;
1279 dtrace_shift_128(tmp, 32);
1280 dtrace_add_128(product, tmp, product);
1281 }
1282
1283 /*
1284 * This privilege check should be used by actions and subroutines to
1285 * verify that the user credentials of the process that enabled the
1286 * invoking ECB match the target credentials
1287 */
1288 static int
1289 dtrace_priv_proc_common_user(dtrace_state_t *state)
1290 {
1291 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1292
1293 /*
1294 * We should always have a non-NULL state cred here, since if cred
1295 * is null (anonymous tracing), we fast-path bypass this routine.
1296 */
1297 ASSERT(s_cr != NULL);
1298
1299 #if !defined(__APPLE__)
1300 if ((cr = CRED()) != NULL &&
1301 #else
1302 if ((cr = dtrace_CRED()) != NULL &&
1303 #endif /* __APPLE__ */
1304 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_uid &&
1305 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_ruid &&
1306 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_suid &&
1307 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_gid &&
1308 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_rgid &&
1309 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_sgid)
1310 return (1);
1311
1312 return (0);
1313 }
1314
1315 /*
1316 * This privilege check should be used by actions and subroutines to
1317 * verify that the zone of the process that enabled the invoking ECB
1318 * matches the target credentials
1319 */
1320 static int
1321 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1322 {
1323 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1324 #pragma unused(cr, s_cr) /* __APPLE__ */
1325
1326 /*
1327 * We should always have a non-NULL state cred here, since if cred
1328 * is null (anonymous tracing), we fast-path bypass this routine.
1329 */
1330 ASSERT(s_cr != NULL);
1331
1332 #if !defined(__APPLE__)
1333 if ((cr = CRED()) != NULL &&
1334 s_cr->cr_zone == cr->cr_zone)
1335 return (1);
1336
1337 return (0);
1338 #else
1339 #pragma unused(state)
1340
1341 return 1; /* Darwin doesn't do zones. */
1342 #endif /* __APPLE__ */
1343 }
1344
1345 /*
1346 * This privilege check should be used by actions and subroutines to
1347 * verify that the process has not setuid or changed credentials.
1348 */
1349 #if !defined(__APPLE__)
1350 static int
1351 dtrace_priv_proc_common_nocd()
1352 {
1353 proc_t *proc;
1354
1355 if ((proc = ttoproc(curthread)) != NULL &&
1356 !(proc->p_flag & SNOCD))
1357 return (1);
1358
1359 return (0);
1360 }
1361 #else
1362 static int
1363 dtrace_priv_proc_common_nocd(void)
1364 {
1365 return 1; /* Darwin omits "No Core Dump" flag. */
1366 }
1367 #endif /* __APPLE__ */
1368
1369 static int
1370 dtrace_priv_proc_destructive(dtrace_state_t *state)
1371 {
1372 int action = state->dts_cred.dcr_action;
1373
1374 #if defined(__APPLE__)
1375 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1376 goto bad;
1377 #endif /* __APPLE__ */
1378
1379 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1380 dtrace_priv_proc_common_zone(state) == 0)
1381 goto bad;
1382
1383 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1384 dtrace_priv_proc_common_user(state) == 0)
1385 goto bad;
1386
1387 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1388 dtrace_priv_proc_common_nocd() == 0)
1389 goto bad;
1390
1391 return (1);
1392
1393 bad:
1394 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1395
1396 return (0);
1397 }
1398
1399 static int
1400 dtrace_priv_proc_control(dtrace_state_t *state)
1401 {
1402 #if defined(__APPLE__)
1403 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1404 goto bad;
1405 #endif /* __APPLE__ */
1406
1407 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1408 return (1);
1409
1410 if (dtrace_priv_proc_common_zone(state) &&
1411 dtrace_priv_proc_common_user(state) &&
1412 dtrace_priv_proc_common_nocd())
1413 return (1);
1414
1415 #if defined(__APPLE__)
1416 bad:
1417 #endif /* __APPLE__ */
1418 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1419
1420 return (0);
1421 }
1422
1423 static int
1424 dtrace_priv_proc(dtrace_state_t *state)
1425 {
1426 #if defined(__APPLE__)
1427 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1428 goto bad;
1429 #endif /* __APPLE__ */
1430
1431 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1432 return (1);
1433
1434 #if defined(__APPLE__)
1435 bad:
1436 #endif /* __APPLE__ */
1437 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1438
1439 return (0);
1440 }
1441
1442 #if defined(__APPLE__)
1443 /* dtrace_priv_proc() omitting the P_LNOATTACH check. For PID and EXECNAME accesses. */
1444 static int
1445 dtrace_priv_proc_relaxed(dtrace_state_t *state)
1446 {
1447
1448 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1449 return (1);
1450
1451 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1452
1453 return (0);
1454 }
1455 #endif /* __APPLE__ */
1456
1457 static int
1458 dtrace_priv_kernel(dtrace_state_t *state)
1459 {
1460 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1461 return (1);
1462
1463 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1464
1465 return (0);
1466 }
1467
1468 static int
1469 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1470 {
1471 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1472 return (1);
1473
1474 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1475
1476 return (0);
1477 }
1478
1479 /*
1480 * Note: not called from probe context. This function is called
1481 * asynchronously (and at a regular interval) from outside of probe context to
1482 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1483 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1484 */
1485 #if defined(__APPLE__) /* Quiet compiler warning. */
1486 static
1487 #endif /* __APPLE__ */
1488 void
1489 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1490 {
1491 dtrace_dynvar_t *dirty;
1492 dtrace_dstate_percpu_t *dcpu;
1493 int i, work = 0;
1494
1495 for (i = 0; i < (int)NCPU; i++) {
1496 dcpu = &dstate->dtds_percpu[i];
1497
1498 ASSERT(dcpu->dtdsc_rinsing == NULL);
1499
1500 /*
1501 * If the dirty list is NULL, there is no dirty work to do.
1502 */
1503 if (dcpu->dtdsc_dirty == NULL)
1504 continue;
1505
1506 /*
1507 * If the clean list is non-NULL, then we're not going to do
1508 * any work for this CPU -- it means that there has not been
1509 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1510 * since the last time we cleaned house.
1511 */
1512 if (dcpu->dtdsc_clean != NULL)
1513 continue;
1514
1515 work = 1;
1516
1517 /*
1518 * Atomically move the dirty list aside.
1519 */
1520 do {
1521 dirty = dcpu->dtdsc_dirty;
1522
1523 /*
1524 * Before we zap the dirty list, set the rinsing list.
1525 * (This allows for a potential assertion in
1526 * dtrace_dynvar(): if a free dynamic variable appears
1527 * on a hash chain, either the dirty list or the
1528 * rinsing list for some CPU must be non-NULL.)
1529 */
1530 dcpu->dtdsc_rinsing = dirty;
1531 dtrace_membar_producer();
1532 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1533 dirty, NULL) != dirty);
1534 }
1535
1536 if (!work) {
1537 /*
1538 * We have no work to do; we can simply return.
1539 */
1540 return;
1541 }
1542
1543 dtrace_sync();
1544
1545 for (i = 0; i < (int)NCPU; i++) {
1546 dcpu = &dstate->dtds_percpu[i];
1547
1548 if (dcpu->dtdsc_rinsing == NULL)
1549 continue;
1550
1551 /*
1552 * We are now guaranteed that no hash chain contains a pointer
1553 * into this dirty list; we can make it clean.
1554 */
1555 ASSERT(dcpu->dtdsc_clean == NULL);
1556 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1557 dcpu->dtdsc_rinsing = NULL;
1558 }
1559
1560 /*
1561 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1562 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1563 * This prevents a race whereby a CPU incorrectly decides that
1564 * the state should be something other than DTRACE_DSTATE_CLEAN
1565 * after dtrace_dynvar_clean() has completed.
1566 */
1567 dtrace_sync();
1568
1569 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1570 }
1571
1572 /*
1573 * Depending on the value of the op parameter, this function looks-up,
1574 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1575 * allocation is requested, this function will return a pointer to a
1576 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1577 * variable can be allocated. If NULL is returned, the appropriate counter
1578 * will be incremented.
1579 */
1580 #if defined(__APPLE__) /* Quiet compiler warning. */
1581 static
1582 #endif /* __APPLE__ */
1583 dtrace_dynvar_t *
1584 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1585 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1586 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1587 {
1588 uint64_t hashval = DTRACE_DYNHASH_VALID;
1589 dtrace_dynhash_t *hash = dstate->dtds_hash;
1590 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1591 processorid_t me = CPU->cpu_id, cpu = me;
1592 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1593 size_t bucket, ksize;
1594 size_t chunksize = dstate->dtds_chunksize;
1595 uintptr_t kdata, lock, nstate;
1596 uint_t i;
1597
1598 ASSERT(nkeys != 0);
1599
1600 /*
1601 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1602 * algorithm. For the by-value portions, we perform the algorithm in
1603 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1604 * bit, and seems to have only a minute effect on distribution. For
1605 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1606 * over each referenced byte. It's painful to do this, but it's much
1607 * better than pathological hash distribution. The efficacy of the
1608 * hashing algorithm (and a comparison with other algorithms) may be
1609 * found by running the ::dtrace_dynstat MDB dcmd.
1610 */
1611 for (i = 0; i < nkeys; i++) {
1612 if (key[i].dttk_size == 0) {
1613 uint64_t val = key[i].dttk_value;
1614
1615 hashval += (val >> 48) & 0xffff;
1616 hashval += (hashval << 10);
1617 hashval ^= (hashval >> 6);
1618
1619 hashval += (val >> 32) & 0xffff;
1620 hashval += (hashval << 10);
1621 hashval ^= (hashval >> 6);
1622
1623 hashval += (val >> 16) & 0xffff;
1624 hashval += (hashval << 10);
1625 hashval ^= (hashval >> 6);
1626
1627 hashval += val & 0xffff;
1628 hashval += (hashval << 10);
1629 hashval ^= (hashval >> 6);
1630 } else {
1631 /*
1632 * This is incredibly painful, but it beats the hell
1633 * out of the alternative.
1634 */
1635 uint64_t j, size = key[i].dttk_size;
1636 uintptr_t base = (uintptr_t)key[i].dttk_value;
1637
1638 if (!dtrace_canload(base, size, mstate, vstate))
1639 break;
1640
1641 for (j = 0; j < size; j++) {
1642 hashval += dtrace_load8(base + j);
1643 hashval += (hashval << 10);
1644 hashval ^= (hashval >> 6);
1645 }
1646 }
1647 }
1648
1649 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1650 return (NULL);
1651
1652 hashval += (hashval << 3);
1653 hashval ^= (hashval >> 11);
1654 hashval += (hashval << 15);
1655
1656 /*
1657 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1658 * comes out to be one of our two sentinel hash values. If this
1659 * actually happens, we set the hashval to be a value known to be a
1660 * non-sentinel value.
1661 */
1662 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1663 hashval = DTRACE_DYNHASH_VALID;
1664
1665 /*
1666 * Yes, it's painful to do a divide here. If the cycle count becomes
1667 * important here, tricks can be pulled to reduce it. (However, it's
1668 * critical that hash collisions be kept to an absolute minimum;
1669 * they're much more painful than a divide.) It's better to have a
1670 * solution that generates few collisions and still keeps things
1671 * relatively simple.
1672 */
1673 bucket = hashval % dstate->dtds_hashsize;
1674
1675 if (op == DTRACE_DYNVAR_DEALLOC) {
1676 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1677
1678 for (;;) {
1679 while ((lock = *lockp) & 1)
1680 continue;
1681
1682 #if !defined(__APPLE__) /* Quiet compiler warning */
1683 if (dtrace_casptr((void *)lockp,
1684 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1685 break;
1686 #else
1687 if (dtrace_casptr((void *)(uintptr_t)lockp,
1688 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1689 break;
1690 #endif /* __APPLE__ */
1691 }
1692
1693 dtrace_membar_producer();
1694 }
1695
1696 top:
1697 prev = NULL;
1698 lock = hash[bucket].dtdh_lock;
1699
1700 dtrace_membar_consumer();
1701
1702 start = hash[bucket].dtdh_chain;
1703 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1704 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1705 op != DTRACE_DYNVAR_DEALLOC));
1706
1707 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1708 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1709 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1710
1711 if (dvar->dtdv_hashval != hashval) {
1712 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1713 /*
1714 * We've reached the sink, and therefore the
1715 * end of the hash chain; we can kick out of
1716 * the loop knowing that we have seen a valid
1717 * snapshot of state.
1718 */
1719 ASSERT(dvar->dtdv_next == NULL);
1720 ASSERT(dvar == &dtrace_dynhash_sink);
1721 break;
1722 }
1723
1724 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1725 /*
1726 * We've gone off the rails: somewhere along
1727 * the line, one of the members of this hash
1728 * chain was deleted. Note that we could also
1729 * detect this by simply letting this loop run
1730 * to completion, as we would eventually hit
1731 * the end of the dirty list. However, we
1732 * want to avoid running the length of the
1733 * dirty list unnecessarily (it might be quite
1734 * long), so we catch this as early as
1735 * possible by detecting the hash marker. In
1736 * this case, we simply set dvar to NULL and
1737 * break; the conditional after the loop will
1738 * send us back to top.
1739 */
1740 dvar = NULL;
1741 break;
1742 }
1743
1744 goto next;
1745 }
1746
1747 if (dtuple->dtt_nkeys != nkeys)
1748 goto next;
1749
1750 for (i = 0; i < nkeys; i++, dkey++) {
1751 if (dkey->dttk_size != key[i].dttk_size)
1752 goto next; /* size or type mismatch */
1753
1754 if (dkey->dttk_size != 0) {
1755 if (dtrace_bcmp(
1756 (void *)(uintptr_t)key[i].dttk_value,
1757 (void *)(uintptr_t)dkey->dttk_value,
1758 dkey->dttk_size))
1759 goto next;
1760 } else {
1761 if (dkey->dttk_value != key[i].dttk_value)
1762 goto next;
1763 }
1764 }
1765
1766 if (op != DTRACE_DYNVAR_DEALLOC)
1767 return (dvar);
1768
1769 ASSERT(dvar->dtdv_next == NULL ||
1770 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1771
1772 if (prev != NULL) {
1773 ASSERT(hash[bucket].dtdh_chain != dvar);
1774 ASSERT(start != dvar);
1775 ASSERT(prev->dtdv_next == dvar);
1776 prev->dtdv_next = dvar->dtdv_next;
1777 } else {
1778 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1779 start, dvar->dtdv_next) != start) {
1780 /*
1781 * We have failed to atomically swing the
1782 * hash table head pointer, presumably because
1783 * of a conflicting allocation on another CPU.
1784 * We need to reread the hash chain and try
1785 * again.
1786 */
1787 goto top;
1788 }
1789 }
1790
1791 dtrace_membar_producer();
1792
1793 /*
1794 * Now set the hash value to indicate that it's free.
1795 */
1796 ASSERT(hash[bucket].dtdh_chain != dvar);
1797 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1798
1799 dtrace_membar_producer();
1800
1801 /*
1802 * Set the next pointer to point at the dirty list, and
1803 * atomically swing the dirty pointer to the newly freed dvar.
1804 */
1805 do {
1806 next = dcpu->dtdsc_dirty;
1807 dvar->dtdv_next = next;
1808 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1809
1810 /*
1811 * Finally, unlock this hash bucket.
1812 */
1813 ASSERT(hash[bucket].dtdh_lock == lock);
1814 ASSERT(lock & 1);
1815 hash[bucket].dtdh_lock++;
1816
1817 return (NULL);
1818 next:
1819 prev = dvar;
1820 continue;
1821 }
1822
1823 if (dvar == NULL) {
1824 /*
1825 * If dvar is NULL, it is because we went off the rails:
1826 * one of the elements that we traversed in the hash chain
1827 * was deleted while we were traversing it. In this case,
1828 * we assert that we aren't doing a dealloc (deallocs lock
1829 * the hash bucket to prevent themselves from racing with
1830 * one another), and retry the hash chain traversal.
1831 */
1832 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1833 goto top;
1834 }
1835
1836 if (op != DTRACE_DYNVAR_ALLOC) {
1837 /*
1838 * If we are not to allocate a new variable, we want to
1839 * return NULL now. Before we return, check that the value
1840 * of the lock word hasn't changed. If it has, we may have
1841 * seen an inconsistent snapshot.
1842 */
1843 if (op == DTRACE_DYNVAR_NOALLOC) {
1844 if (hash[bucket].dtdh_lock != lock)
1845 goto top;
1846 } else {
1847 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1848 ASSERT(hash[bucket].dtdh_lock == lock);
1849 ASSERT(lock & 1);
1850 hash[bucket].dtdh_lock++;
1851 }
1852
1853 return (NULL);
1854 }
1855
1856 /*
1857 * We need to allocate a new dynamic variable. The size we need is the
1858 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1859 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1860 * the size of any referred-to data (dsize). We then round the final
1861 * size up to the chunksize for allocation.
1862 */
1863 for (ksize = 0, i = 0; i < nkeys; i++)
1864 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1865
1866 /*
1867 * This should be pretty much impossible, but could happen if, say,
1868 * strange DIF specified the tuple. Ideally, this should be an
1869 * assertion and not an error condition -- but that requires that the
1870 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1871 * bullet-proof. (That is, it must not be able to be fooled by
1872 * malicious DIF.) Given the lack of backwards branches in DIF,
1873 * solving this would presumably not amount to solving the Halting
1874 * Problem -- but it still seems awfully hard.
1875 */
1876 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1877 ksize + dsize > chunksize) {
1878 dcpu->dtdsc_drops++;
1879 return (NULL);
1880 }
1881
1882 nstate = DTRACE_DSTATE_EMPTY;
1883
1884 do {
1885 retry:
1886 free = dcpu->dtdsc_free;
1887
1888 if (free == NULL) {
1889 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1890 void *rval;
1891
1892 if (clean == NULL) {
1893 /*
1894 * We're out of dynamic variable space on
1895 * this CPU. Unless we have tried all CPUs,
1896 * we'll try to allocate from a different
1897 * CPU.
1898 */
1899 switch (dstate->dtds_state) {
1900 case DTRACE_DSTATE_CLEAN: {
1901 void *sp = &dstate->dtds_state;
1902
1903 if (++cpu >= (int)NCPU)
1904 cpu = 0;
1905
1906 if (dcpu->dtdsc_dirty != NULL &&
1907 nstate == DTRACE_DSTATE_EMPTY)
1908 nstate = DTRACE_DSTATE_DIRTY;
1909
1910 if (dcpu->dtdsc_rinsing != NULL)
1911 nstate = DTRACE_DSTATE_RINSING;
1912
1913 dcpu = &dstate->dtds_percpu[cpu];
1914
1915 if (cpu != me)
1916 goto retry;
1917
1918 (void) dtrace_cas32(sp,
1919 DTRACE_DSTATE_CLEAN, nstate);
1920
1921 /*
1922 * To increment the correct bean
1923 * counter, take another lap.
1924 */
1925 goto retry;
1926 }
1927
1928 case DTRACE_DSTATE_DIRTY:
1929 dcpu->dtdsc_dirty_drops++;
1930 break;
1931
1932 case DTRACE_DSTATE_RINSING:
1933 dcpu->dtdsc_rinsing_drops++;
1934 break;
1935
1936 case DTRACE_DSTATE_EMPTY:
1937 dcpu->dtdsc_drops++;
1938 break;
1939 }
1940
1941 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1942 return (NULL);
1943 }
1944
1945 /*
1946 * The clean list appears to be non-empty. We want to
1947 * move the clean list to the free list; we start by
1948 * moving the clean pointer aside.
1949 */
1950 if (dtrace_casptr(&dcpu->dtdsc_clean,
1951 clean, NULL) != clean) {
1952 /*
1953 * We are in one of two situations:
1954 *
1955 * (a) The clean list was switched to the
1956 * free list by another CPU.
1957 *
1958 * (b) The clean list was added to by the
1959 * cleansing cyclic.
1960 *
1961 * In either of these situations, we can
1962 * just reattempt the free list allocation.
1963 */
1964 goto retry;
1965 }
1966
1967 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1968
1969 /*
1970 * Now we'll move the clean list to the free list.
1971 * It's impossible for this to fail: the only way
1972 * the free list can be updated is through this
1973 * code path, and only one CPU can own the clean list.
1974 * Thus, it would only be possible for this to fail if
1975 * this code were racing with dtrace_dynvar_clean().
1976 * (That is, if dtrace_dynvar_clean() updated the clean
1977 * list, and we ended up racing to update the free
1978 * list.) This race is prevented by the dtrace_sync()
1979 * in dtrace_dynvar_clean() -- which flushes the
1980 * owners of the clean lists out before resetting
1981 * the clean lists.
1982 */
1983 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1984 ASSERT(rval == NULL);
1985 goto retry;
1986 }
1987
1988 dvar = free;
1989 new_free = dvar->dtdv_next;
1990 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1991
1992 /*
1993 * We have now allocated a new chunk. We copy the tuple keys into the
1994 * tuple array and copy any referenced key data into the data space
1995 * following the tuple array. As we do this, we relocate dttk_value
1996 * in the final tuple to point to the key data address in the chunk.
1997 */
1998 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1999 dvar->dtdv_data = (void *)(kdata + ksize);
2000 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2001
2002 for (i = 0; i < nkeys; i++) {
2003 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2004 size_t kesize = key[i].dttk_size;
2005
2006 if (kesize != 0) {
2007 dtrace_bcopy(
2008 (const void *)(uintptr_t)key[i].dttk_value,
2009 (void *)kdata, kesize);
2010 dkey->dttk_value = kdata;
2011 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2012 } else {
2013 dkey->dttk_value = key[i].dttk_value;
2014 }
2015
2016 dkey->dttk_size = kesize;
2017 }
2018
2019 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2020 dvar->dtdv_hashval = hashval;
2021 dvar->dtdv_next = start;
2022
2023 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2024 return (dvar);
2025
2026 /*
2027 * The cas has failed. Either another CPU is adding an element to
2028 * this hash chain, or another CPU is deleting an element from this
2029 * hash chain. The simplest way to deal with both of these cases
2030 * (though not necessarily the most efficient) is to free our
2031 * allocated block and tail-call ourselves. Note that the free is
2032 * to the dirty list and _not_ to the free list. This is to prevent
2033 * races with allocators, above.
2034 */
2035 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2036
2037 dtrace_membar_producer();
2038
2039 do {
2040 free = dcpu->dtdsc_dirty;
2041 dvar->dtdv_next = free;
2042 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2043
2044 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2045 }
2046
2047 /*ARGSUSED*/
2048 static void
2049 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2050 {
2051 #pragma unused(arg) /* __APPLE__ */
2052 if ((int64_t)nval < (int64_t)*oval)
2053 *oval = nval;
2054 }
2055
2056 /*ARGSUSED*/
2057 static void
2058 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2059 {
2060 #pragma unused(arg) /* __APPLE__ */
2061 if ((int64_t)nval > (int64_t)*oval)
2062 *oval = nval;
2063 }
2064
2065 static void
2066 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2067 {
2068 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2069 int64_t val = (int64_t)nval;
2070
2071 if (val < 0) {
2072 for (i = 0; i < zero; i++) {
2073 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2074 quanta[i] += incr;
2075 return;
2076 }
2077 }
2078 } else {
2079 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2080 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2081 quanta[i - 1] += incr;
2082 return;
2083 }
2084 }
2085
2086 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2087 return;
2088 }
2089
2090 ASSERT(0);
2091 }
2092
2093 static void
2094 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2095 {
2096 uint64_t arg = *lquanta++;
2097 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2098 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2099 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2100 int32_t val = (int32_t)nval, level;
2101
2102 ASSERT(step != 0);
2103 ASSERT(levels != 0);
2104
2105 if (val < base) {
2106 /*
2107 * This is an underflow.
2108 */
2109 lquanta[0] += incr;
2110 return;
2111 }
2112
2113 level = (val - base) / step;
2114
2115 if (level < levels) {
2116 lquanta[level + 1] += incr;
2117 return;
2118 }
2119
2120 /*
2121 * This is an overflow.
2122 */
2123 lquanta[levels + 1] += incr;
2124 }
2125
2126 /*ARGSUSED*/
2127 static void
2128 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2129 {
2130 #pragma unused(arg) /* __APPLE__ */
2131 data[0]++;
2132 data[1] += nval;
2133 }
2134
2135 /*ARGSUSED*/
2136 static void
2137 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2138 {
2139 #pragma unused(arg) /* __APPLE__ */
2140 int64_t snval = (int64_t)nval;
2141 uint64_t tmp[2];
2142
2143 data[0]++;
2144 data[1] += nval;
2145
2146 /*
2147 * What we want to say here is:
2148 *
2149 * data[2] += nval * nval;
2150 *
2151 * But given that nval is 64-bit, we could easily overflow, so
2152 * we do this as 128-bit arithmetic.
2153 */
2154 if (snval < 0)
2155 snval = -snval;
2156
2157 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2158 dtrace_add_128(data + 2, tmp, data + 2);
2159 }
2160
2161 /*ARGSUSED*/
2162 static void
2163 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2164 {
2165 #pragma unused(nval, arg) /* __APPLE__ */
2166 *oval = *oval + 1;
2167 }
2168
2169 /*ARGSUSED*/
2170 static void
2171 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2172 {
2173 #pragma unused(arg) /* __APPLE__ */
2174 *oval += nval;
2175 }
2176
2177 /*
2178 * Aggregate given the tuple in the principal data buffer, and the aggregating
2179 * action denoted by the specified dtrace_aggregation_t. The aggregation
2180 * buffer is specified as the buf parameter. This routine does not return
2181 * failure; if there is no space in the aggregation buffer, the data will be
2182 * dropped, and a corresponding counter incremented.
2183 */
2184 static void
2185 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2186 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2187 {
2188 #pragma unused(arg)
2189 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2190 uint32_t i, ndx, size, fsize;
2191 uint32_t align = sizeof (uint64_t) - 1;
2192 dtrace_aggbuffer_t *agb;
2193 dtrace_aggkey_t *key;
2194 uint32_t hashval = 0, limit, isstr;
2195 caddr_t tomax, data, kdata;
2196 dtrace_actkind_t action;
2197 dtrace_action_t *act;
2198 uintptr_t offs;
2199
2200 if (buf == NULL)
2201 return;
2202
2203 if (!agg->dtag_hasarg) {
2204 /*
2205 * Currently, only quantize() and lquantize() take additional
2206 * arguments, and they have the same semantics: an increment
2207 * value that defaults to 1 when not present. If additional
2208 * aggregating actions take arguments, the setting of the
2209 * default argument value will presumably have to become more
2210 * sophisticated...
2211 */
2212 arg = 1;
2213 }
2214
2215 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2216 size = rec->dtrd_offset - agg->dtag_base;
2217 fsize = size + rec->dtrd_size;
2218
2219 ASSERT(dbuf->dtb_tomax != NULL);
2220 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2221
2222 if ((tomax = buf->dtb_tomax) == NULL) {
2223 dtrace_buffer_drop(buf);
2224 return;
2225 }
2226
2227 /*
2228 * The metastructure is always at the bottom of the buffer.
2229 */
2230 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2231 sizeof (dtrace_aggbuffer_t));
2232
2233 if (buf->dtb_offset == 0) {
2234 /*
2235 * We just kludge up approximately 1/8th of the size to be
2236 * buckets. If this guess ends up being routinely
2237 * off-the-mark, we may need to dynamically readjust this
2238 * based on past performance.
2239 */
2240 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2241
2242 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2243 (uintptr_t)tomax || hashsize == 0) {
2244 /*
2245 * We've been given a ludicrously small buffer;
2246 * increment our drop count and leave.
2247 */
2248 dtrace_buffer_drop(buf);
2249 return;
2250 }
2251
2252 /*
2253 * And now, a pathetic attempt to try to get a an odd (or
2254 * perchance, a prime) hash size for better hash distribution.
2255 */
2256 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2257 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2258
2259 agb->dtagb_hashsize = hashsize;
2260 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2261 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2262 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2263
2264 for (i = 0; i < agb->dtagb_hashsize; i++)
2265 agb->dtagb_hash[i] = NULL;
2266 }
2267
2268 ASSERT(agg->dtag_first != NULL);
2269 ASSERT(agg->dtag_first->dta_intuple);
2270
2271 /*
2272 * Calculate the hash value based on the key. Note that we _don't_
2273 * include the aggid in the hashing (but we will store it as part of
2274 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2275 * algorithm: a simple, quick algorithm that has no known funnels, and
2276 * gets good distribution in practice. The efficacy of the hashing
2277 * algorithm (and a comparison with other algorithms) may be found by
2278 * running the ::dtrace_aggstat MDB dcmd.
2279 */
2280 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2281 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2282 limit = i + act->dta_rec.dtrd_size;
2283 ASSERT(limit <= size);
2284 isstr = DTRACEACT_ISSTRING(act);
2285
2286 for (; i < limit; i++) {
2287 hashval += data[i];
2288 hashval += (hashval << 10);
2289 hashval ^= (hashval >> 6);
2290
2291 if (isstr && data[i] == '\0')
2292 break;
2293 }
2294 }
2295
2296 hashval += (hashval << 3);
2297 hashval ^= (hashval >> 11);
2298 hashval += (hashval << 15);
2299
2300 /*
2301 * Yes, the divide here is expensive -- but it's generally the least
2302 * of the performance issues given the amount of data that we iterate
2303 * over to compute hash values, compare data, etc.
2304 */
2305 ndx = hashval % agb->dtagb_hashsize;
2306
2307 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2308 ASSERT((caddr_t)key >= tomax);
2309 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2310
2311 if (hashval != key->dtak_hashval || key->dtak_size != size)
2312 continue;
2313
2314 kdata = key->dtak_data;
2315 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2316
2317 for (act = agg->dtag_first; act->dta_intuple;
2318 act = act->dta_next) {
2319 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2320 limit = i + act->dta_rec.dtrd_size;
2321 ASSERT(limit <= size);
2322 isstr = DTRACEACT_ISSTRING(act);
2323
2324 for (; i < limit; i++) {
2325 if (kdata[i] != data[i])
2326 goto next;
2327
2328 if (isstr && data[i] == '\0')
2329 break;
2330 }
2331 }
2332
2333 if (action != key->dtak_action) {
2334 /*
2335 * We are aggregating on the same value in the same
2336 * aggregation with two different aggregating actions.
2337 * (This should have been picked up in the compiler,
2338 * so we may be dealing with errant or devious DIF.)
2339 * This is an error condition; we indicate as much,
2340 * and return.
2341 */
2342 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2343 return;
2344 }
2345
2346 /*
2347 * This is a hit: we need to apply the aggregator to
2348 * the value at this key.
2349 */
2350 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2351 return;
2352 next:
2353 continue;
2354 }
2355
2356 /*
2357 * We didn't find it. We need to allocate some zero-filled space,
2358 * link it into the hash table appropriately, and apply the aggregator
2359 * to the (zero-filled) value.
2360 */
2361 offs = buf->dtb_offset;
2362 while (offs & (align - 1))
2363 offs += sizeof (uint32_t);
2364
2365 /*
2366 * If we don't have enough room to both allocate a new key _and_
2367 * its associated data, increment the drop count and return.
2368 */
2369 if ((uintptr_t)tomax + offs + fsize >
2370 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2371 dtrace_buffer_drop(buf);
2372 return;
2373 }
2374
2375 /*CONSTCOND*/
2376 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2377 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2378 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2379
2380 key->dtak_data = kdata = tomax + offs;
2381 buf->dtb_offset = offs + fsize;
2382
2383 /*
2384 * Now copy the data across.
2385 */
2386 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2387
2388 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2389 kdata[i] = data[i];
2390
2391 /*
2392 * Because strings are not zeroed out by default, we need to iterate
2393 * looking for actions that store strings, and we need to explicitly
2394 * pad these strings out with zeroes.
2395 */
2396 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2397 int nul;
2398
2399 if (!DTRACEACT_ISSTRING(act))
2400 continue;
2401
2402 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2403 limit = i + act->dta_rec.dtrd_size;
2404 ASSERT(limit <= size);
2405
2406 for (nul = 0; i < limit; i++) {
2407 if (nul) {
2408 kdata[i] = '\0';
2409 continue;
2410 }
2411
2412 if (data[i] != '\0')
2413 continue;
2414
2415 nul = 1;
2416 }
2417 }
2418
2419 for (i = size; i < fsize; i++)
2420 kdata[i] = 0;
2421
2422 key->dtak_hashval = hashval;
2423 key->dtak_size = size;
2424 key->dtak_action = action;
2425 key->dtak_next = agb->dtagb_hash[ndx];
2426 agb->dtagb_hash[ndx] = key;
2427
2428 /*
2429 * Finally, apply the aggregator.
2430 */
2431 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2432 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2433 }
2434
2435 /*
2436 * Given consumer state, this routine finds a speculation in the INACTIVE
2437 * state and transitions it into the ACTIVE state. If there is no speculation
2438 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2439 * incremented -- it is up to the caller to take appropriate action.
2440 */
2441 static int
2442 dtrace_speculation(dtrace_state_t *state)
2443 {
2444 int i = 0;
2445 dtrace_speculation_state_t current;
2446 uint32_t *stat = &state->dts_speculations_unavail, count;
2447
2448 while (i < state->dts_nspeculations) {
2449 dtrace_speculation_t *spec = &state->dts_speculations[i];
2450
2451 current = spec->dtsp_state;
2452
2453 if (current != DTRACESPEC_INACTIVE) {
2454 if (current == DTRACESPEC_COMMITTINGMANY ||
2455 current == DTRACESPEC_COMMITTING ||
2456 current == DTRACESPEC_DISCARDING)
2457 stat = &state->dts_speculations_busy;
2458 i++;
2459 continue;
2460 }
2461
2462 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2463 current, DTRACESPEC_ACTIVE) == current)
2464 return (i + 1);
2465 }
2466
2467 /*
2468 * We couldn't find a speculation. If we found as much as a single
2469 * busy speculation buffer, we'll attribute this failure as "busy"
2470 * instead of "unavail".
2471 */
2472 do {
2473 count = *stat;
2474 } while (dtrace_cas32(stat, count, count + 1) != count);
2475
2476 return (0);
2477 }
2478
2479 /*
2480 * This routine commits an active speculation. If the specified speculation
2481 * is not in a valid state to perform a commit(), this routine will silently do
2482 * nothing. The state of the specified speculation is transitioned according
2483 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2484 */
2485 static void
2486 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2487 dtrace_specid_t which)
2488 {
2489 dtrace_speculation_t *spec;
2490 dtrace_buffer_t *src, *dest;
2491 uintptr_t daddr, saddr, dlimit;
2492 #if !defined(__APPLE__) /* Quiet compiler warning */
2493 dtrace_speculation_state_t current, new;
2494 #else
2495 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2496 #endif /* __APPLE__ */
2497 intptr_t offs;
2498
2499 if (which == 0)
2500 return;
2501
2502 #if !defined(__APPLE__) /* Quiet compiler warning */
2503 if (which > state->dts_nspeculations) {
2504 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2505 return;
2506 }
2507 #else
2508 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2509 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2510 return;
2511 }
2512 #endif /* __APPLE__ */
2513
2514 spec = &state->dts_speculations[which - 1];
2515 src = &spec->dtsp_buffer[cpu];
2516 dest = &state->dts_buffer[cpu];
2517
2518 do {
2519 current = spec->dtsp_state;
2520
2521 if (current == DTRACESPEC_COMMITTINGMANY)
2522 break;
2523
2524 switch (current) {
2525 case DTRACESPEC_INACTIVE:
2526 case DTRACESPEC_DISCARDING:
2527 return;
2528
2529 case DTRACESPEC_COMMITTING:
2530 /*
2531 * This is only possible if we are (a) commit()'ing
2532 * without having done a prior speculate() on this CPU
2533 * and (b) racing with another commit() on a different
2534 * CPU. There's nothing to do -- we just assert that
2535 * our offset is 0.
2536 */
2537 ASSERT(src->dtb_offset == 0);
2538 return;
2539
2540 case DTRACESPEC_ACTIVE:
2541 new = DTRACESPEC_COMMITTING;
2542 break;
2543
2544 case DTRACESPEC_ACTIVEONE:
2545 /*
2546 * This speculation is active on one CPU. If our
2547 * buffer offset is non-zero, we know that the one CPU
2548 * must be us. Otherwise, we are committing on a
2549 * different CPU from the speculate(), and we must
2550 * rely on being asynchronously cleaned.
2551 */
2552 if (src->dtb_offset != 0) {
2553 new = DTRACESPEC_COMMITTING;
2554 break;
2555 }
2556 /*FALLTHROUGH*/
2557
2558 case DTRACESPEC_ACTIVEMANY:
2559 new = DTRACESPEC_COMMITTINGMANY;
2560 break;
2561
2562 default:
2563 ASSERT(0);
2564 }
2565 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2566 current, new) != current);
2567
2568 /*
2569 * We have set the state to indicate that we are committing this
2570 * speculation. Now reserve the necessary space in the destination
2571 * buffer.
2572 */
2573 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2574 sizeof (uint64_t), state, NULL)) < 0) {
2575 dtrace_buffer_drop(dest);
2576 goto out;
2577 }
2578
2579 /*
2580 * We have the space; copy the buffer across. (Note that this is a
2581 * highly subobtimal bcopy(); in the unlikely event that this becomes
2582 * a serious performance issue, a high-performance DTrace-specific
2583 * bcopy() should obviously be invented.)
2584 */
2585 daddr = (uintptr_t)dest->dtb_tomax + offs;
2586 dlimit = daddr + src->dtb_offset;
2587 saddr = (uintptr_t)src->dtb_tomax;
2588
2589 /*
2590 * First, the aligned portion.
2591 */
2592 while (dlimit - daddr >= sizeof (uint64_t)) {
2593 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2594
2595 daddr += sizeof (uint64_t);
2596 saddr += sizeof (uint64_t);
2597 }
2598
2599 /*
2600 * Now any left-over bit...
2601 */
2602 while (dlimit - daddr)
2603 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2604
2605 /*
2606 * Finally, commit the reserved space in the destination buffer.
2607 */
2608 dest->dtb_offset = offs + src->dtb_offset;
2609
2610 out:
2611 /*
2612 * If we're lucky enough to be the only active CPU on this speculation
2613 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2614 */
2615 if (current == DTRACESPEC_ACTIVE ||
2616 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2617 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2618 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2619 #pragma unused(rval) /* __APPLE__ */
2620
2621 ASSERT(rval == DTRACESPEC_COMMITTING);
2622 }
2623
2624 src->dtb_offset = 0;
2625 src->dtb_xamot_drops += src->dtb_drops;
2626 src->dtb_drops = 0;
2627 }
2628
2629 /*
2630 * This routine discards an active speculation. If the specified speculation
2631 * is not in a valid state to perform a discard(), this routine will silently
2632 * do nothing. The state of the specified speculation is transitioned
2633 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2634 */
2635 static void
2636 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2637 dtrace_specid_t which)
2638 {
2639 dtrace_speculation_t *spec;
2640 #if !defined(__APPLE__) /* Quiet compiler warning */
2641 dtrace_speculation_state_t current, new;
2642 #else
2643 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2644 #endif /* __APPLE__ */
2645 dtrace_buffer_t *buf;
2646
2647 if (which == 0)
2648 return;
2649
2650 #if !defined(__APPLE__) /* Quiet compiler warning */
2651 if (which > state->dts_nspeculations) {
2652 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2653 return;
2654 }
2655 #else
2656 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2657 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2658 return;
2659 }
2660 #endif /* __APPLE__ */
2661
2662 spec = &state->dts_speculations[which - 1];
2663 buf = &spec->dtsp_buffer[cpu];
2664
2665 do {
2666 current = spec->dtsp_state;
2667
2668 switch (current) {
2669 case DTRACESPEC_INACTIVE:
2670 case DTRACESPEC_COMMITTINGMANY:
2671 case DTRACESPEC_COMMITTING:
2672 case DTRACESPEC_DISCARDING:
2673 return;
2674
2675 case DTRACESPEC_ACTIVE:
2676 case DTRACESPEC_ACTIVEMANY:
2677 new = DTRACESPEC_DISCARDING;
2678 break;
2679
2680 case DTRACESPEC_ACTIVEONE:
2681 if (buf->dtb_offset != 0) {
2682 new = DTRACESPEC_INACTIVE;
2683 } else {
2684 new = DTRACESPEC_DISCARDING;
2685 }
2686 break;
2687
2688 default:
2689 ASSERT(0);
2690 }
2691 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2692 current, new) != current);
2693
2694 buf->dtb_offset = 0;
2695 buf->dtb_drops = 0;
2696 }
2697
2698 /*
2699 * Note: not called from probe context. This function is called
2700 * asynchronously from cross call context to clean any speculations that are
2701 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2702 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2703 * speculation.
2704 */
2705 static void
2706 dtrace_speculation_clean_here(dtrace_state_t *state)
2707 {
2708 dtrace_icookie_t cookie;
2709 processorid_t cpu = CPU->cpu_id;
2710 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2711 dtrace_specid_t i;
2712
2713 cookie = dtrace_interrupt_disable();
2714
2715 if (dest->dtb_tomax == NULL) {
2716 dtrace_interrupt_enable(cookie);
2717 return;
2718 }
2719
2720 #if !defined(__APPLE__) /* Quiet compiler warning */
2721 for (i = 0; i < state->dts_nspeculations; i++) {
2722 #else
2723 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2724 #endif /* __APPLE__ */
2725 dtrace_speculation_t *spec = &state->dts_speculations[i];
2726 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2727
2728 if (src->dtb_tomax == NULL)
2729 continue;
2730
2731 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2732 src->dtb_offset = 0;
2733 continue;
2734 }
2735
2736 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2737 continue;
2738
2739 if (src->dtb_offset == 0)
2740 continue;
2741
2742 dtrace_speculation_commit(state, cpu, i + 1);
2743 }
2744
2745 dtrace_interrupt_enable(cookie);
2746 }
2747
2748 /*
2749 * Note: not called from probe context. This function is called
2750 * asynchronously (and at a regular interval) to clean any speculations that
2751 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2752 * is work to be done, it cross calls all CPUs to perform that work;
2753 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2754 * INACTIVE state until they have been cleaned by all CPUs.
2755 */
2756 static void
2757 dtrace_speculation_clean(dtrace_state_t *state)
2758 {
2759 #if !defined(__APPLE__) /* Quiet compiler warning */
2760 int work = 0, rv;
2761 #else
2762 int work = 0;
2763 uint32_t rv;
2764 #endif /* __APPLE__ */
2765 dtrace_specid_t i;
2766
2767 #if !defined(__APPLE__) /* Quiet compiler warning */
2768 for (i = 0; i < state->dts_nspeculations; i++) {
2769 #else
2770 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2771 #endif /* __APPLE__ */
2772 dtrace_speculation_t *spec = &state->dts_speculations[i];
2773
2774 ASSERT(!spec->dtsp_cleaning);
2775
2776 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2777 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2778 continue;
2779
2780 work++;
2781 spec->dtsp_cleaning = 1;
2782 }
2783
2784 if (!work)
2785 return;
2786
2787 dtrace_xcall(DTRACE_CPUALL,
2788 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2789
2790 /*
2791 * We now know that all CPUs have committed or discarded their
2792 * speculation buffers, as appropriate. We can now set the state
2793 * to inactive.
2794 */
2795 #if !defined(__APPLE__) /* Quiet compiler warning */
2796 for (i = 0; i < state->dts_nspeculations; i++) {
2797 #else
2798 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2799 #endif /* __APPLE__ */
2800 dtrace_speculation_t *spec = &state->dts_speculations[i];
2801 dtrace_speculation_state_t current, new;
2802
2803 if (!spec->dtsp_cleaning)
2804 continue;
2805
2806 current = spec->dtsp_state;
2807 ASSERT(current == DTRACESPEC_DISCARDING ||
2808 current == DTRACESPEC_COMMITTINGMANY);
2809
2810 new = DTRACESPEC_INACTIVE;
2811
2812 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2813 ASSERT(rv == current);
2814 spec->dtsp_cleaning = 0;
2815 }
2816 }
2817
2818 /*
2819 * Called as part of a speculate() to get the speculative buffer associated
2820 * with a given speculation. Returns NULL if the specified speculation is not
2821 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2822 * the active CPU is not the specified CPU -- the speculation will be
2823 * atomically transitioned into the ACTIVEMANY state.
2824 */
2825 static dtrace_buffer_t *
2826 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2827 dtrace_specid_t which)
2828 {
2829 dtrace_speculation_t *spec;
2830 #if !defined(__APPLE__) /* Quiet compiler warning */
2831 dtrace_speculation_state_t current, new;
2832 #else
2833 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2834 #endif /* __APPLE__ */
2835 dtrace_buffer_t *buf;
2836
2837 if (which == 0)
2838 return (NULL);
2839
2840 #if !defined(__APPLE__) /* Quiet compiler warning */
2841 if (which > state->dts_nspeculations) {
2842 #else
2843 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2844 #endif /* __APPLE__ */
2845 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2846 return (NULL);
2847 }
2848
2849 spec = &state->dts_speculations[which - 1];
2850 buf = &spec->dtsp_buffer[cpuid];
2851
2852 do {
2853 current = spec->dtsp_state;
2854
2855 switch (current) {
2856 case DTRACESPEC_INACTIVE:
2857 case DTRACESPEC_COMMITTINGMANY:
2858 case DTRACESPEC_DISCARDING:
2859 return (NULL);
2860
2861 case DTRACESPEC_COMMITTING:
2862 ASSERT(buf->dtb_offset == 0);
2863 return (NULL);
2864
2865 case DTRACESPEC_ACTIVEONE:
2866 /*
2867 * This speculation is currently active on one CPU.
2868 * Check the offset in the buffer; if it's non-zero,
2869 * that CPU must be us (and we leave the state alone).
2870 * If it's zero, assume that we're starting on a new
2871 * CPU -- and change the state to indicate that the
2872 * speculation is active on more than one CPU.
2873 */
2874 if (buf->dtb_offset != 0)
2875 return (buf);
2876
2877 new = DTRACESPEC_ACTIVEMANY;
2878 break;
2879
2880 case DTRACESPEC_ACTIVEMANY:
2881 return (buf);
2882
2883 case DTRACESPEC_ACTIVE:
2884 new = DTRACESPEC_ACTIVEONE;
2885 break;
2886
2887 default:
2888 ASSERT(0);
2889 }
2890 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2891 current, new) != current);
2892
2893 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2894 return (buf);
2895 }
2896
2897 /*
2898 * Return a string. In the event that the user lacks the privilege to access
2899 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2900 * don't fail access checking.
2901 *
2902 * dtrace_dif_variable() uses this routine as a helper for various
2903 * builtin values such as 'execname' and 'probefunc.'
2904 */
2905 #if defined(__APPLE__) /* Quiet compiler warning. */
2906 static
2907 #endif /* __APPLE__ */
2908 uintptr_t
2909 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2910 dtrace_mstate_t *mstate)
2911 {
2912 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2913 uintptr_t ret;
2914 size_t strsz;
2915
2916 /*
2917 * The easy case: this probe is allowed to read all of memory, so
2918 * we can just return this as a vanilla pointer.
2919 */
2920 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2921 return (addr);
2922
2923 /*
2924 * This is the tougher case: we copy the string in question from
2925 * kernel memory into scratch memory and return it that way: this
2926 * ensures that we won't trip up when access checking tests the
2927 * BYREF return value.
2928 */
2929 strsz = dtrace_strlen((char *)addr, size) + 1;
2930
2931 if (mstate->dtms_scratch_ptr + strsz >
2932 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2933 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2934 return (NULL);
2935 }
2936
2937 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2938 strsz);
2939 ret = mstate->dtms_scratch_ptr;
2940 mstate->dtms_scratch_ptr += strsz;
2941 return (ret);
2942 }
2943
2944 /*
2945 * This function implements the DIF emulator's variable lookups. The emulator
2946 * passes a reserved variable identifier and optional built-in array index.
2947 */
2948 static uint64_t
2949 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2950 uint64_t ndx)
2951 {
2952 /*
2953 * If we're accessing one of the uncached arguments, we'll turn this
2954 * into a reference in the args array.
2955 */
2956 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2957 ndx = v - DIF_VAR_ARG0;
2958 v = DIF_VAR_ARGS;
2959 }
2960
2961 switch (v) {
2962 case DIF_VAR_ARGS:
2963 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2964 if (ndx >= sizeof (mstate->dtms_arg) /
2965 sizeof (mstate->dtms_arg[0])) {
2966 #if !defined(__APPLE__)
2967 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2968 #else
2969 /* Account for introduction of __dtrace_probe() on xnu. */
2970 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
2971 #endif /* __APPLE__ */
2972 dtrace_provider_t *pv;
2973 uint64_t val;
2974
2975 pv = mstate->dtms_probe->dtpr_provider;
2976 if (pv->dtpv_pops.dtps_getargval != NULL)
2977 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2978 mstate->dtms_probe->dtpr_id,
2979 mstate->dtms_probe->dtpr_arg, ndx, aframes);
2980 #if defined(__APPLE__)
2981 /* Special case access of arg5 as passed to dtrace_probe_error() (which see.) */
2982 else if (mstate->dtms_probe->dtpr_id == dtrace_probeid_error && ndx == 5) {
2983 return ((dtrace_state_t *)(uintptr_t)(mstate->dtms_arg[0]))->dts_arg_error_illval;
2984 }
2985 #endif /* __APPLE__ */
2986 else
2987 val = dtrace_getarg(ndx, aframes);
2988
2989 /*
2990 * This is regrettably required to keep the compiler
2991 * from tail-optimizing the call to dtrace_getarg().
2992 * The condition always evaluates to true, but the
2993 * compiler has no way of figuring that out a priori.
2994 * (None of this would be necessary if the compiler
2995 * could be relied upon to _always_ tail-optimize
2996 * the call to dtrace_getarg() -- but it can't.)
2997 */
2998 if (mstate->dtms_probe != NULL)
2999 return (val);
3000
3001 ASSERT(0);
3002 }
3003
3004 return (mstate->dtms_arg[ndx]);
3005
3006 #if !defined(__APPLE__)
3007 case DIF_VAR_UREGS: {
3008 klwp_t *lwp;
3009
3010 if (!dtrace_priv_proc(state))
3011 return (0);
3012
3013 if ((lwp = curthread->t_lwp) == NULL) {
3014 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3015 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
3016 return (0);
3017 }
3018
3019 return (dtrace_getreg(lwp->lwp_regs, ndx));
3020 }
3021 #else
3022 case DIF_VAR_UREGS: {
3023 thread_t thread;
3024
3025 if (!dtrace_priv_proc(state))
3026 return (0);
3027
3028 if ((thread = current_thread()) == NULL) {
3029 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3030 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3031 return (0);
3032 }
3033
3034 return (dtrace_getreg(find_user_regs(thread), ndx));
3035 }
3036 #endif /* __APPLE__ */
3037
3038 #if !defined(__APPLE__)
3039 case DIF_VAR_CURTHREAD:
3040 if (!dtrace_priv_kernel(state))
3041 return (0);
3042 return ((uint64_t)(uintptr_t)curthread);
3043 #else
3044 case DIF_VAR_CURTHREAD:
3045 if (!dtrace_priv_kernel(state))
3046 return (0);
3047
3048 return ((uint64_t)(uintptr_t)current_thread());
3049 #endif /* __APPLE__ */
3050
3051 case DIF_VAR_TIMESTAMP:
3052 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3053 mstate->dtms_timestamp = dtrace_gethrtime();
3054 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3055 }
3056 return (mstate->dtms_timestamp);
3057
3058 #if !defined(__APPLE__)
3059 case DIF_VAR_VTIMESTAMP:
3060 ASSERT(dtrace_vtime_references != 0);
3061 return (curthread->t_dtrace_vtime);
3062 #else
3063 case DIF_VAR_VTIMESTAMP:
3064 ASSERT(dtrace_vtime_references != 0);
3065 return (dtrace_get_thread_vtime(current_thread()));
3066 #endif /* __APPLE__ */
3067
3068 case DIF_VAR_WALLTIMESTAMP:
3069 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3070 mstate->dtms_walltimestamp = dtrace_gethrestime();
3071 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3072 }
3073 return (mstate->dtms_walltimestamp);
3074
3075 case DIF_VAR_IPL:
3076 if (!dtrace_priv_kernel(state))
3077 return (0);
3078 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3079 mstate->dtms_ipl = dtrace_getipl();
3080 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3081 }
3082 return (mstate->dtms_ipl);
3083
3084 case DIF_VAR_EPID:
3085 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3086 return (mstate->dtms_epid);
3087
3088 case DIF_VAR_ID:
3089 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3090 return (mstate->dtms_probe->dtpr_id);
3091
3092 case DIF_VAR_STACKDEPTH:
3093 if (!dtrace_priv_kernel(state))
3094 return (0);
3095 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3096 #if !defined(__APPLE__)
3097 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3098 #else
3099 /* Account for introduction of __dtrace_probe() on xnu. */
3100 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3101 #endif /* __APPLE__ */
3102
3103 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3104 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3105 }
3106 return (mstate->dtms_stackdepth);
3107
3108 case DIF_VAR_USTACKDEPTH:
3109 if (!dtrace_priv_proc(state))
3110 return (0);
3111 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3112 /*
3113 * See comment in DIF_VAR_PID.
3114 */
3115 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3116 CPU_ON_INTR(CPU)) {
3117 mstate->dtms_ustackdepth = 0;
3118 } else {
3119 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3120 mstate->dtms_ustackdepth =
3121 dtrace_getustackdepth();
3122 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3123 }
3124 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3125 }
3126 return (mstate->dtms_ustackdepth);
3127
3128 case DIF_VAR_CALLER:
3129 if (!dtrace_priv_kernel(state))
3130 return (0);
3131 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3132 #if !defined(__APPLE__)
3133 int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3134 #else
3135 /* Account for introduction of __dtrace_probe() on xnu. */
3136 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3137 #endif /* __APPLE__ */
3138
3139 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3140 /*
3141 * If this is an unanchored probe, we are
3142 * required to go through the slow path:
3143 * dtrace_caller() only guarantees correct
3144 * results for anchored probes.
3145 */
3146 pc_t caller[2];
3147
3148 dtrace_getpcstack(caller, 2, aframes,
3149 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3150 mstate->dtms_caller = caller[1];
3151 } else if ((mstate->dtms_caller =
3152 #if !defined(__APPLE__) /* Quiet compiler warnings */
3153 dtrace_caller(aframes)) == -1) {
3154 #else
3155 dtrace_caller(aframes)) == (uintptr_t)-1) {
3156 #endif /* __APPLE__ */
3157 /*
3158 * We have failed to do this the quick way;
3159 * we must resort to the slower approach of
3160 * calling dtrace_getpcstack().
3161 */
3162 pc_t caller;
3163
3164 dtrace_getpcstack(&caller, 1, aframes, NULL);
3165 mstate->dtms_caller = caller;
3166 }
3167
3168 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3169 }
3170 return (mstate->dtms_caller);
3171
3172 case DIF_VAR_UCALLER:
3173 if (!dtrace_priv_proc(state))
3174 return (0);
3175
3176 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3177 uint64_t ustack[3];
3178
3179 /*
3180 * dtrace_getupcstack() fills in the first uint64_t
3181 * with the current PID. The second uint64_t will
3182 * be the program counter at user-level. The third
3183 * uint64_t will contain the caller, which is what
3184 * we're after.
3185 */
3186 ustack[2] = NULL;
3187 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3188 dtrace_getupcstack(ustack, 3);
3189 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3190 mstate->dtms_ucaller = ustack[2];
3191 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3192 }
3193
3194 return (mstate->dtms_ucaller);
3195
3196 case DIF_VAR_PROBEPROV:
3197 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3198 return (dtrace_dif_varstr(
3199 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3200 state, mstate));
3201
3202 case DIF_VAR_PROBEMOD:
3203 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3204 return (dtrace_dif_varstr(
3205 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3206 state, mstate));
3207
3208 case DIF_VAR_PROBEFUNC:
3209 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3210 return (dtrace_dif_varstr(
3211 (uintptr_t)mstate->dtms_probe->dtpr_func,
3212 state, mstate));
3213
3214 case DIF_VAR_PROBENAME:
3215 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3216 return (dtrace_dif_varstr(
3217 (uintptr_t)mstate->dtms_probe->dtpr_name,
3218 state, mstate));
3219
3220 #if !defined(__APPLE__)
3221 case DIF_VAR_PID:
3222 if (!dtrace_priv_proc(state))
3223 return (0);
3224
3225 /*
3226 * Note that we are assuming that an unanchored probe is
3227 * always due to a high-level interrupt. (And we're assuming
3228 * that there is only a single high level interrupt.)
3229 */
3230 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3231 return (pid0.pid_id);
3232
3233 /*
3234 * It is always safe to dereference one's own t_procp pointer:
3235 * it always points to a valid, allocated proc structure.
3236 * Further, it is always safe to dereference the p_pidp member
3237 * of one's own proc structure. (These are truisms becuase
3238 * threads and processes don't clean up their own state --
3239 * they leave that task to whomever reaps them.)
3240 */
3241 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3242
3243 #else
3244 case DIF_VAR_PID:
3245 if (!dtrace_priv_proc_relaxed(state))
3246 return (0);
3247
3248 /*
3249 * Note that we are assuming that an unanchored probe is
3250 * always due to a high-level interrupt. (And we're assuming
3251 * that there is only a single high level interrupt.)
3252 */
3253 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3254 /* Anchored probe that fires while on an interrupt accrues to process 0 */
3255 return 0;
3256
3257 return ((uint64_t)proc_selfpid());
3258 #endif /* __APPLE__ */
3259
3260 #if !defined(__APPLE__)
3261 case DIF_VAR_PPID:
3262 if (!dtrace_priv_proc(state))
3263 return (0);
3264
3265 /*
3266 * See comment in DIF_VAR_PID.
3267 */
3268 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3269 return (pid0.pid_id);
3270
3271 /*
3272 * It is always safe to dereference one's own t_procp pointer:
3273 * it always points to a valid, allocated proc structure.
3274 * (This is true because threads don't clean up their own
3275 * state -- they leave that task to whomever reaps them.)
3276 */
3277 return ((uint64_t)curthread->t_procp->p_ppid);
3278 #else
3279 case DIF_VAR_PPID:
3280 if (!dtrace_priv_proc_relaxed(state))
3281 return (0);
3282
3283 /*
3284 * See comment in DIF_VAR_PID.
3285 */
3286 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3287 return (0);
3288
3289 return ((uint64_t)proc_selfppid());
3290 #endif /* __APPLE__ */
3291
3292 #if !defined(__APPLE__)
3293 case DIF_VAR_TID:
3294 /*
3295 * See comment in DIF_VAR_PID.
3296 */
3297 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3298 return (0);
3299
3300 return ((uint64_t)curthread->t_tid);
3301 #else
3302 case DIF_VAR_TID:
3303 /* We do not need to check for null current_thread() */
3304 return thread_tid(current_thread()); /* globally unique */
3305
3306 case DIF_VAR_PTHREAD_SELF:
3307 if (!dtrace_priv_proc(state))
3308 return (0);
3309
3310 /* Not currently supported, but we should be able to delta the dispatchqaddr and dispatchqoffset to get pthread_self */
3311 return 0;
3312
3313 case DIF_VAR_DISPATCHQADDR:
3314 if (!dtrace_priv_proc(state))
3315 return (0);
3316
3317 /* We do not need to check for null current_thread() */
3318 return thread_dispatchqaddr(current_thread());
3319 #endif /* __APPLE__ */
3320
3321 #if !defined(__APPLE__)
3322 case DIF_VAR_EXECNAME:
3323 if (!dtrace_priv_proc(state))
3324 return (0);
3325
3326 /*
3327 * See comment in DIF_VAR_PID.
3328 */
3329 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3330 return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3331
3332 /*
3333 * It is always safe to dereference one's own t_procp pointer:
3334 * it always points to a valid, allocated proc structure.
3335 * (This is true because threads don't clean up their own
3336 * state -- they leave that task to whomever reaps them.)
3337 */
3338 return (dtrace_dif_varstr(
3339 (uintptr_t)curthread->t_procp->p_user.u_comm,
3340 state, mstate));
3341 #else
3342 case DIF_VAR_EXECNAME:
3343 {
3344 char *xname = (char *)mstate->dtms_scratch_ptr;
3345 size_t scratch_size = MAXCOMLEN+1;
3346
3347 /* The scratch allocation's lifetime is that of the clause. */
3348 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3349 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3350 return 0;
3351 }
3352
3353 if (!dtrace_priv_proc_relaxed(state))
3354 return (0);
3355
3356 mstate->dtms_scratch_ptr += scratch_size;
3357 proc_selfname( xname, MAXCOMLEN );
3358
3359 return ((uint64_t)(uintptr_t)xname);
3360 }
3361 #endif /* __APPLE__ */
3362 #if !defined(__APPLE__)
3363 case DIF_VAR_ZONENAME:
3364 if (!dtrace_priv_proc(state))
3365 return (0);
3366
3367 /*
3368 * See comment in DIF_VAR_PID.
3369 */
3370 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3371 return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3372
3373 /*
3374 * It is always safe to dereference one's own t_procp pointer:
3375 * it always points to a valid, allocated proc structure.
3376 * (This is true because threads don't clean up their own
3377 * state -- they leave that task to whomever reaps them.)
3378 */
3379 return (dtrace_dif_varstr(
3380 (uintptr_t)curthread->t_procp->p_zone->zone_name,
3381 state, mstate));
3382
3383 #else
3384 case DIF_VAR_ZONENAME:
3385 if (!dtrace_priv_proc(state))
3386 return (0);
3387
3388 /* FIXME: return e.g. "global" allocated from scratch a la execname. */
3389 return ((uint64_t)(uintptr_t)NULL); /* Darwin doesn't do "zones" */
3390 #endif /* __APPLE__ */
3391
3392 #if !defined(__APPLE__)
3393 case DIF_VAR_UID:
3394 if (!dtrace_priv_proc(state))
3395 return (0);
3396
3397 /*
3398 * See comment in DIF_VAR_PID.
3399 */
3400 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3401 return ((uint64_t)p0.p_cred->cr_uid);
3402
3403 /*
3404 * It is always safe to dereference one's own t_procp pointer:
3405 * it always points to a valid, allocated proc structure.
3406 * (This is true because threads don't clean up their own
3407 * state -- they leave that task to whomever reaps them.)
3408 *
3409 * Additionally, it is safe to dereference one's own process
3410 * credential, since this is never NULL after process birth.
3411 */
3412 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3413 #else
3414 case DIF_VAR_UID:
3415 if (!dtrace_priv_proc(state))
3416 return (0);
3417
3418 /*
3419 * See comment in DIF_VAR_PID.
3420 */
3421 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3422 return (0);
3423
3424 if (dtrace_CRED() != NULL)
3425 /* Credential does not require lazy initialization. */
3426 return ((uint64_t)kauth_getuid());
3427 else {
3428 /* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3429 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3430 return -1ULL;
3431 }
3432 #endif /* __APPLE__ */
3433
3434 #if !defined(__APPLE__)
3435 case DIF_VAR_GID:
3436 if (!dtrace_priv_proc(state))
3437 return (0);
3438
3439 /*
3440 * See comment in DIF_VAR_PID.
3441 */
3442 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3443 return ((uint64_t)p0.p_cred->cr_gid);
3444
3445 /*
3446 * It is always safe to dereference one's own t_procp pointer:
3447 * it always points to a valid, allocated proc structure.
3448 * (This is true because threads don't clean up their own
3449 * state -- they leave that task to whomever reaps them.)
3450 *
3451 * Additionally, it is safe to dereference one's own process
3452 * credential, since this is never NULL after process birth.
3453 */
3454 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3455 #else
3456 case DIF_VAR_GID:
3457 if (!dtrace_priv_proc(state))
3458 return (0);
3459
3460 /*
3461 * See comment in DIF_VAR_PID.
3462 */
3463 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3464 return (0);
3465
3466 if (dtrace_CRED() != NULL)
3467 /* Credential does not require lazy initialization. */
3468 return ((uint64_t)kauth_getgid());
3469 else {
3470 /* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3471 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3472 return -1ULL;
3473 }
3474 #endif /* __APPLE__ */
3475
3476 #if !defined(__APPLE__)
3477 case DIF_VAR_ERRNO: {
3478 klwp_t *lwp;
3479 if (!dtrace_priv_proc(state))
3480 return (0);
3481
3482 /*
3483 * See comment in DIF_VAR_PID.
3484 */
3485 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3486 return (0);
3487
3488 /*
3489 * It is always safe to dereference one's own t_lwp pointer in
3490 * the event that this pointer is non-NULL. (This is true
3491 * because threads and lwps don't clean up their own state --
3492 * they leave that task to whomever reaps them.)
3493 */
3494 if ((lwp = curthread->t_lwp) == NULL)
3495 return (0);
3496
3497 return ((uint64_t)lwp->lwp_errno);
3498 }
3499 #else
3500 case DIF_VAR_ERRNO: {
3501 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
3502 if (!dtrace_priv_proc(state))
3503 return (0);
3504
3505 /*
3506 * See comment in DIF_VAR_PID.
3507 */
3508 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3509 return (0);
3510
3511 if (uthread)
3512 return (uint64_t)uthread->t_dtrace_errno;
3513 else {
3514 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3515 return -1ULL;
3516 }
3517 }
3518 #endif /* __APPLE__ */
3519
3520 default:
3521 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3522 return (0);
3523 }
3524 }
3525
3526 /*
3527 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3528 * Notice that we don't bother validating the proper number of arguments or
3529 * their types in the tuple stack. This isn't needed because all argument
3530 * interpretation is safe because of our load safety -- the worst that can
3531 * happen is that a bogus program can obtain bogus results.
3532 */
3533 static void
3534 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3535 dtrace_key_t *tupregs, int nargs,
3536 dtrace_mstate_t *mstate, dtrace_state_t *state)
3537 {
3538 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3539 #if !defined(__APPLE__)
3540 volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3541 #else
3542 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3543 #endif /* __APPLE__ */
3544 dtrace_vstate_t *vstate = &state->dts_vstate;
3545
3546 #if !defined(__APPLE__)
3547 union {
3548 mutex_impl_t mi;
3549 uint64_t mx;
3550 } m;
3551
3552 union {
3553 krwlock_t ri;
3554 uintptr_t rw;
3555 } r;
3556 #else
3557 /* FIXME: awaits lock/mutex work */
3558 #endif /* __APPLE__ */
3559
3560 switch (subr) {
3561 case DIF_SUBR_RAND:
3562 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3563 break;
3564
3565 #if !defined(__APPLE__)
3566 case DIF_SUBR_MUTEX_OWNED:
3567 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3568 mstate, vstate)) {
3569 regs[rd] = NULL;
3570 break;
3571 }
3572
3573 m.mx = dtrace_load64(tupregs[0].dttk_value);
3574 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3575 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3576 else
3577 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3578 break;
3579
3580 case DIF_SUBR_MUTEX_OWNER:
3581 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3582 mstate, vstate)) {
3583 regs[rd] = NULL;
3584 break;
3585 }
3586
3587 m.mx = dtrace_load64(tupregs[0].dttk_value);
3588 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3589 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3590 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3591 else
3592 regs[rd] = 0;
3593 break;
3594
3595 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3596 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3597 mstate, vstate)) {
3598 regs[rd] = NULL;
3599 break;
3600 }
3601
3602 m.mx = dtrace_load64(tupregs[0].dttk_value);
3603 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3604 break;
3605
3606 case DIF_SUBR_MUTEX_TYPE_SPIN:
3607 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3608 mstate, vstate)) {
3609 regs[rd] = NULL;
3610 break;
3611 }
3612
3613 m.mx = dtrace_load64(tupregs[0].dttk_value);
3614 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3615 break;
3616
3617 case DIF_SUBR_RW_READ_HELD: {
3618 uintptr_t tmp;
3619
3620 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3621 mstate, vstate)) {
3622 regs[rd] = NULL;
3623 break;
3624 }
3625
3626 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3627 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3628 break;
3629 }
3630
3631 case DIF_SUBR_RW_WRITE_HELD:
3632 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3633 mstate, vstate)) {
3634 regs[rd] = NULL;
3635 break;
3636 }
3637
3638 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3639 regs[rd] = _RW_WRITE_HELD(&r.ri);
3640 break;
3641
3642 case DIF_SUBR_RW_ISWRITER:
3643 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3644 mstate, vstate)) {
3645 regs[rd] = NULL;
3646 break;
3647 }
3648
3649 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3650 regs[rd] = _RW_ISWRITER(&r.ri);
3651 break;
3652 #else
3653 /* FIXME: awaits lock/mutex work */
3654 #endif /* __APPLE__ */
3655
3656 case DIF_SUBR_BCOPY: {
3657 /*
3658 * We need to be sure that the destination is in the scratch
3659 * region -- no other region is allowed.
3660 */
3661 uintptr_t src = tupregs[0].dttk_value;
3662 uintptr_t dest = tupregs[1].dttk_value;
3663 size_t size = tupregs[2].dttk_value;
3664
3665 if (!dtrace_inscratch(dest, size, mstate)) {
3666 *flags |= CPU_DTRACE_BADADDR;
3667 *illval = regs[rd];
3668 break;
3669 }
3670
3671 if (!dtrace_canload(src, size, mstate, vstate)) {
3672 regs[rd] = NULL;
3673 break;
3674 }
3675
3676 dtrace_bcopy((void *)src, (void *)dest, size);
3677 break;
3678 }
3679
3680 case DIF_SUBR_ALLOCA:
3681 case DIF_SUBR_COPYIN: {
3682 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3683 uint64_t size =
3684 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3685 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3686
3687 /*
3688 * This action doesn't require any credential checks since
3689 * probes will not activate in user contexts to which the
3690 * enabling user does not have permissions.
3691 */
3692
3693 /*
3694 * Rounding up the user allocation size could have overflowed
3695 * a large, bogus allocation (like -1ULL) to 0.
3696 */
3697 if (scratch_size < size ||
3698 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3699 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3700 regs[rd] = NULL;
3701 break;
3702 }
3703
3704 if (subr == DIF_SUBR_COPYIN) {
3705 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3706 #if !defined(__APPLE__)
3707 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3708 #else
3709 if (dtrace_priv_proc(state))
3710 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3711 #endif /* __APPLE__ */
3712 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3713 }
3714
3715 mstate->dtms_scratch_ptr += scratch_size;
3716 regs[rd] = dest;
3717 break;
3718 }
3719
3720 case DIF_SUBR_COPYINTO: {
3721 uint64_t size = tupregs[1].dttk_value;
3722 uintptr_t dest = tupregs[2].dttk_value;
3723
3724 /*
3725 * This action doesn't require any credential checks since
3726 * probes will not activate in user contexts to which the
3727 * enabling user does not have permissions.
3728 */
3729 if (!dtrace_inscratch(dest, size, mstate)) {
3730 *flags |= CPU_DTRACE_BADADDR;
3731 *illval = regs[rd];
3732 break;
3733 }
3734
3735 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3736 #if !defined(__APPLE__)
3737 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3738 #else
3739 if (dtrace_priv_proc(state))
3740 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3741 #endif /* __APPLE__ */
3742 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3743 break;
3744 }
3745
3746 case DIF_SUBR_COPYINSTR: {
3747 uintptr_t dest = mstate->dtms_scratch_ptr;
3748 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3749
3750 if (nargs > 1 && tupregs[1].dttk_value < size)
3751 size = tupregs[1].dttk_value + 1;
3752
3753 /*
3754 * This action doesn't require any credential checks since
3755 * probes will not activate in user contexts to which the
3756 * enabling user does not have permissions.
3757 */
3758 if (!DTRACE_INSCRATCH(mstate, size)) {
3759 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3760 regs[rd] = NULL;
3761 break;
3762 }
3763
3764 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3765 #if !defined(__APPLE__)
3766 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3767 #else
3768 if (dtrace_priv_proc(state))
3769 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3770 #endif /* __APPLE__ */
3771 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3772
3773 ((char *)dest)[size - 1] = '\0';
3774 mstate->dtms_scratch_ptr += size;
3775 regs[rd] = dest;
3776 break;
3777 }
3778
3779 #if !defined(__APPLE__)
3780 case DIF_SUBR_MSGSIZE:
3781 case DIF_SUBR_MSGDSIZE: {
3782 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3783 uintptr_t wptr, rptr;
3784 size_t count = 0;
3785 int cont = 0;
3786
3787 while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3788
3789 if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3790 vstate)) {
3791 regs[rd] = NULL;
3792 break;
3793 }
3794
3795 wptr = dtrace_loadptr(baddr +
3796 offsetof(mblk_t, b_wptr));
3797
3798 rptr = dtrace_loadptr(baddr +
3799 offsetof(mblk_t, b_rptr));
3800
3801 if (wptr < rptr) {
3802 *flags |= CPU_DTRACE_BADADDR;
3803 *illval = tupregs[0].dttk_value;
3804 break;
3805 }
3806
3807 daddr = dtrace_loadptr(baddr +
3808 offsetof(mblk_t, b_datap));
3809
3810 baddr = dtrace_loadptr(baddr +
3811 offsetof(mblk_t, b_cont));
3812
3813 /*
3814 * We want to prevent against denial-of-service here,
3815 * so we're only going to search the list for
3816 * dtrace_msgdsize_max mblks.
3817 */
3818 if (cont++ > dtrace_msgdsize_max) {
3819 *flags |= CPU_DTRACE_ILLOP;
3820 break;
3821 }
3822
3823 if (subr == DIF_SUBR_MSGDSIZE) {
3824 if (dtrace_load8(daddr +
3825 offsetof(dblk_t, db_type)) != M_DATA)
3826 continue;
3827 }
3828
3829 count += wptr - rptr;
3830 }
3831
3832 if (!(*flags & CPU_DTRACE_FAULT))
3833 regs[rd] = count;
3834
3835 break;
3836 }
3837 #else
3838 case DIF_SUBR_MSGSIZE:
3839 case DIF_SUBR_MSGDSIZE: {
3840 /* Darwin does not implement SysV streams messages */
3841 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3842 regs[rd] = 0;
3843 break;
3844 }
3845 #endif /* __APPLE__ */
3846
3847 #if !defined(__APPLE__)
3848 case DIF_SUBR_PROGENYOF: {
3849 pid_t pid = tupregs[0].dttk_value;
3850 proc_t *p;
3851 int rval = 0;
3852
3853 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3854
3855 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3856 if (p->p_pidp->pid_id == pid) {
3857 rval = 1;
3858 break;
3859 }
3860 }
3861
3862 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3863
3864 regs[rd] = rval;
3865 break;
3866 }
3867 #else
3868 case DIF_SUBR_PROGENYOF: {
3869 pid_t pid = tupregs[0].dttk_value;
3870 struct proc *p = current_proc();
3871 int rval = 0, lim = nprocs;
3872
3873 while(p && (lim-- > 0)) {
3874 pid_t ppid;
3875
3876 ppid = (pid_t)dtrace_load32((uintptr_t)&(p->p_pid));
3877 if (*flags & CPU_DTRACE_FAULT)
3878 break;
3879
3880 if (ppid == pid) {
3881 rval = 1;
3882 break;
3883 }
3884
3885 if (ppid == 0)
3886 break; /* Can't climb process tree any further. */
3887
3888 p = (struct proc *)dtrace_loadptr((uintptr_t)&(p->p_pptr));
3889 if (*flags & CPU_DTRACE_FAULT)
3890 break;
3891 }
3892
3893 regs[rd] = rval;
3894 break;
3895 }
3896 #endif /* __APPLE__ */
3897
3898 case DIF_SUBR_SPECULATION:
3899 regs[rd] = dtrace_speculation(state);
3900 break;
3901
3902 #if !defined(__APPLE__)
3903 case DIF_SUBR_COPYOUT: {
3904 uintptr_t kaddr = tupregs[0].dttk_value;
3905 uintptr_t uaddr = tupregs[1].dttk_value;
3906 uint64_t size = tupregs[2].dttk_value;
3907
3908 if (!dtrace_destructive_disallow &&
3909 dtrace_priv_proc_control(state) &&
3910 !dtrace_istoxic(kaddr, size)) {
3911 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3912 dtrace_copyout(kaddr, uaddr, size, flags);
3913 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3914 }
3915 break;
3916 }
3917
3918 case DIF_SUBR_COPYOUTSTR: {
3919 uintptr_t kaddr = tupregs[0].dttk_value;
3920 uintptr_t uaddr = tupregs[1].dttk_value;
3921 uint64_t size = tupregs[2].dttk_value;
3922
3923 if (!dtrace_destructive_disallow &&
3924 dtrace_priv_proc_control(state) &&
3925 !dtrace_istoxic(kaddr, size)) {
3926 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3927 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3928 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3929 }
3930 break;
3931 }
3932 #else
3933 case DIF_SUBR_COPYOUT: {
3934 uintptr_t kaddr = tupregs[0].dttk_value;
3935 user_addr_t uaddr = tupregs[1].dttk_value;
3936 uint64_t size = tupregs[2].dttk_value;
3937
3938 if (!dtrace_destructive_disallow &&
3939 dtrace_priv_proc_control(state) &&
3940 !dtrace_istoxic(kaddr, size)) {
3941 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3942 dtrace_copyout(kaddr, uaddr, size, flags);
3943 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3944 }
3945 break;
3946 }
3947
3948 case DIF_SUBR_COPYOUTSTR: {
3949 uintptr_t kaddr = tupregs[0].dttk_value;
3950 user_addr_t uaddr = tupregs[1].dttk_value;
3951 uint64_t size = tupregs[2].dttk_value;
3952
3953 if (!dtrace_destructive_disallow &&
3954 dtrace_priv_proc_control(state) &&
3955 !dtrace_istoxic(kaddr, size)) {
3956 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3957 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3958 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3959 }
3960 break;
3961 }
3962 #endif /* __APPLE__ */
3963
3964 case DIF_SUBR_STRLEN: {
3965 size_t sz;
3966 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3967 sz = dtrace_strlen((char *)addr,
3968 state->dts_options[DTRACEOPT_STRSIZE]);
3969
3970 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3971 regs[rd] = NULL;
3972 break;
3973 }
3974
3975 regs[rd] = sz;
3976
3977 break;
3978 }
3979
3980 case DIF_SUBR_STRCHR:
3981 case DIF_SUBR_STRRCHR: {
3982 /*
3983 * We're going to iterate over the string looking for the
3984 * specified character. We will iterate until we have reached
3985 * the string length or we have found the character. If this
3986 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3987 * of the specified character instead of the first.
3988 */
3989 uintptr_t saddr = tupregs[0].dttk_value;
3990 uintptr_t addr = tupregs[0].dttk_value;
3991 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3992 char c, target = (char)tupregs[1].dttk_value;
3993
3994 for (regs[rd] = NULL; addr < limit; addr++) {
3995 if ((c = dtrace_load8(addr)) == target) {
3996 regs[rd] = addr;
3997
3998 if (subr == DIF_SUBR_STRCHR)
3999 break;
4000 }
4001
4002 if (c == '\0')
4003 break;
4004 }
4005
4006 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4007 regs[rd] = NULL;
4008 break;
4009 }
4010
4011 break;
4012 }
4013
4014 case DIF_SUBR_STRSTR:
4015 case DIF_SUBR_INDEX:
4016 case DIF_SUBR_RINDEX: {
4017 /*
4018 * We're going to iterate over the string looking for the
4019 * specified string. We will iterate until we have reached
4020 * the string length or we have found the string. (Yes, this
4021 * is done in the most naive way possible -- but considering
4022 * that the string we're searching for is likely to be
4023 * relatively short, the complexity of Rabin-Karp or similar
4024 * hardly seems merited.)
4025 */
4026 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4027 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4028 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4029 size_t len = dtrace_strlen(addr, size);
4030 size_t sublen = dtrace_strlen(substr, size);
4031 char *limit = addr + len, *orig = addr;
4032 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4033 int inc = 1;
4034
4035 regs[rd] = notfound;
4036
4037 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4038 regs[rd] = NULL;
4039 break;
4040 }
4041
4042 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4043 vstate)) {
4044 regs[rd] = NULL;
4045 break;
4046 }
4047
4048 /*
4049 * strstr() and index()/rindex() have similar semantics if
4050 * both strings are the empty string: strstr() returns a
4051 * pointer to the (empty) string, and index() and rindex()
4052 * both return index 0 (regardless of any position argument).
4053 */
4054 if (sublen == 0 && len == 0) {
4055 if (subr == DIF_SUBR_STRSTR)
4056 regs[rd] = (uintptr_t)addr;
4057 else
4058 regs[rd] = 0;
4059 break;
4060 }
4061
4062 if (subr != DIF_SUBR_STRSTR) {
4063 if (subr == DIF_SUBR_RINDEX) {
4064 limit = orig - 1;
4065 addr += len;
4066 inc = -1;
4067 }
4068
4069 /*
4070 * Both index() and rindex() take an optional position
4071 * argument that denotes the starting position.
4072 */
4073 if (nargs == 3) {
4074 int64_t pos = (int64_t)tupregs[2].dttk_value;
4075
4076 /*
4077 * If the position argument to index() is
4078 * negative, Perl implicitly clamps it at
4079 * zero. This semantic is a little surprising
4080 * given the special meaning of negative
4081 * positions to similar Perl functions like
4082 * substr(), but it appears to reflect a
4083 * notion that index() can start from a
4084 * negative index and increment its way up to
4085 * the string. Given this notion, Perl's
4086 * rindex() is at least self-consistent in
4087 * that it implicitly clamps positions greater
4088 * than the string length to be the string
4089 * length. Where Perl completely loses
4090 * coherence, however, is when the specified
4091 * substring is the empty string (""). In
4092 * this case, even if the position is
4093 * negative, rindex() returns 0 -- and even if
4094 * the position is greater than the length,
4095 * index() returns the string length. These
4096 * semantics violate the notion that index()
4097 * should never return a value less than the
4098 * specified position and that rindex() should
4099 * never return a value greater than the
4100 * specified position. (One assumes that
4101 * these semantics are artifacts of Perl's
4102 * implementation and not the results of
4103 * deliberate design -- it beggars belief that
4104 * even Larry Wall could desire such oddness.)
4105 * While in the abstract one would wish for
4106 * consistent position semantics across
4107 * substr(), index() and rindex() -- or at the
4108 * very least self-consistent position
4109 * semantics for index() and rindex() -- we
4110 * instead opt to keep with the extant Perl
4111 * semantics, in all their broken glory. (Do
4112 * we have more desire to maintain Perl's
4113 * semantics than Perl does? Probably.)
4114 */
4115 if (subr == DIF_SUBR_RINDEX) {
4116 if (pos < 0) {
4117 if (sublen == 0)
4118 regs[rd] = 0;
4119 break;
4120 }
4121
4122 #if !defined(__APPLE__) /* Quiet compiler warnings */
4123 if (pos > len)
4124 #else
4125 if ((size_t)pos > len)
4126 #endif /* __APPLE__ */
4127 pos = len;
4128 } else {
4129 if (pos < 0)
4130 pos = 0;
4131
4132 #if !defined(__APPLE__) /* Quiet compiler warnings */
4133 if (pos >= len) {
4134 #else
4135 if ((size_t)pos >= len) {
4136 #endif /* __APPLE__ */
4137 if (sublen == 0)
4138 regs[rd] = len;
4139 break;
4140 }
4141 }
4142
4143 addr = orig + pos;
4144 }
4145 }
4146
4147 for (regs[rd] = notfound; addr != limit; addr += inc) {
4148 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4149 if (subr != DIF_SUBR_STRSTR) {
4150 /*
4151 * As D index() and rindex() are
4152 * modeled on Perl (and not on awk),
4153 * we return a zero-based (and not a
4154 * one-based) index. (For you Perl
4155 * weenies: no, we're not going to add
4156 * $[ -- and shouldn't you be at a con
4157 * or something?)
4158 */
4159 regs[rd] = (uintptr_t)(addr - orig);
4160 break;
4161 }
4162
4163 ASSERT(subr == DIF_SUBR_STRSTR);
4164 regs[rd] = (uintptr_t)addr;
4165 break;
4166 }
4167 }
4168
4169 break;
4170 }
4171
4172 case DIF_SUBR_STRTOK: {
4173 uintptr_t addr = tupregs[0].dttk_value;
4174 uintptr_t tokaddr = tupregs[1].dttk_value;
4175 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4176 uintptr_t limit, toklimit = tokaddr + size;
4177 char *dest = (char *)mstate->dtms_scratch_ptr;
4178 #if !defined(__APPLE__) /* Quiet compiler warnings */
4179 uint8_t c, tokmap[32]; /* 256 / 8 */
4180 int i;
4181 #else
4182 uint8_t c='\0', tokmap[32]; /* 256 / 8 */
4183 uint64_t i = 0;
4184 #endif /* __APPLE__ */
4185
4186 /*
4187 * Check both the token buffer and (later) the input buffer,
4188 * since both could be non-scratch addresses.
4189 */
4190 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4191 regs[rd] = NULL;
4192 break;
4193 }
4194
4195 if (!DTRACE_INSCRATCH(mstate, size)) {
4196 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4197 regs[rd] = NULL;
4198 break;
4199 }
4200
4201 if (addr == NULL) {
4202 /*
4203 * If the address specified is NULL, we use our saved
4204 * strtok pointer from the mstate. Note that this
4205 * means that the saved strtok pointer is _only_
4206 * valid within multiple enablings of the same probe --
4207 * it behaves like an implicit clause-local variable.
4208 */
4209 addr = mstate->dtms_strtok;
4210 } else {
4211 /*
4212 * If the user-specified address is non-NULL we must
4213 * access check it. This is the only time we have
4214 * a chance to do so, since this address may reside
4215 * in the string table of this clause-- future calls
4216 * (when we fetch addr from mstate->dtms_strtok)
4217 * would fail this access check.
4218 */
4219 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4220 regs[rd] = NULL;
4221 break;
4222 }
4223 }
4224
4225 /*
4226 * First, zero the token map, and then process the token
4227 * string -- setting a bit in the map for every character
4228 * found in the token string.
4229 */
4230 for (i = 0; i < (int)sizeof (tokmap); i++)
4231 tokmap[i] = 0;
4232
4233 for (; tokaddr < toklimit; tokaddr++) {
4234 if ((c = dtrace_load8(tokaddr)) == '\0')
4235 break;
4236
4237 ASSERT((c >> 3) < sizeof (tokmap));
4238 tokmap[c >> 3] |= (1 << (c & 0x7));
4239 }
4240
4241 for (limit = addr + size; addr < limit; addr++) {
4242 /*
4243 * We're looking for a character that is _not_ contained
4244 * in the token string.
4245 */
4246 if ((c = dtrace_load8(addr)) == '\0')
4247 break;
4248
4249 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4250 break;
4251 }
4252
4253 if (c == '\0') {
4254 /*
4255 * We reached the end of the string without finding
4256 * any character that was not in the token string.
4257 * We return NULL in this case, and we set the saved
4258 * address to NULL as well.
4259 */
4260 regs[rd] = NULL;
4261 mstate->dtms_strtok = NULL;
4262 break;
4263 }
4264
4265 /*
4266 * From here on, we're copying into the destination string.
4267 */
4268 for (i = 0; addr < limit && i < size - 1; addr++) {
4269 if ((c = dtrace_load8(addr)) == '\0')
4270 break;
4271
4272 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4273 break;
4274
4275 ASSERT(i < size);
4276 dest[i++] = c;
4277 }
4278
4279 ASSERT(i < size);
4280 dest[i] = '\0';
4281 regs[rd] = (uintptr_t)dest;
4282 mstate->dtms_scratch_ptr += size;
4283 mstate->dtms_strtok = addr;
4284 break;
4285 }
4286
4287 case DIF_SUBR_SUBSTR: {
4288 uintptr_t s = tupregs[0].dttk_value;
4289 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4290 char *d = (char *)mstate->dtms_scratch_ptr;
4291 int64_t index = (int64_t)tupregs[1].dttk_value;
4292 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4293 size_t len = dtrace_strlen((char *)s, size);
4294 int64_t i = 0;
4295
4296 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4297 regs[rd] = NULL;
4298 break;
4299 }
4300
4301 if (!DTRACE_INSCRATCH(mstate, size)) {
4302 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4303 regs[rd] = NULL;
4304 break;
4305 }
4306
4307 if (nargs <= 2)
4308 remaining = (int64_t)size;
4309
4310 if (index < 0) {
4311 index += len;
4312
4313 if (index < 0 && index + remaining > 0) {
4314 remaining += index;
4315 index = 0;
4316 }
4317 }
4318
4319 #if !defined(__APPLE__) /* Quiet compiler warnings */
4320 if (index >= len || index < 0) {
4321 remaining = 0;
4322 } else if (remaining < 0) {
4323 remaining += len - index;
4324 } else if (index + remaining > size) {
4325 remaining = size - index;
4326 }
4327 #else
4328 if ((size_t)index >= len || index < 0) {
4329 remaining = 0;
4330 } else if (remaining < 0) {
4331 remaining += len - index;
4332 } else if ((uint64_t)index + (uint64_t)remaining > size) {
4333 remaining = size - index;
4334 }
4335 #endif /* __APPLE__ */
4336 for (i = 0; i < remaining; i++) {
4337 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4338 break;
4339 }
4340
4341 d[i] = '\0';
4342
4343 mstate->dtms_scratch_ptr += size;
4344 regs[rd] = (uintptr_t)d;
4345 break;
4346 }
4347
4348 #if !defined(__APPLE__)
4349 case DIF_SUBR_GETMAJOR:
4350 #ifdef _LP64
4351 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4352 #else
4353 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4354 #endif
4355 break;
4356
4357 #else /* __APPLE__ */
4358 case DIF_SUBR_GETMAJOR:
4359 regs[rd] = (uintptr_t)major( (dev_t)tupregs[0].dttk_value );
4360 break;
4361 #endif /* __APPLE__ */
4362
4363 #if !defined(__APPLE__)
4364 case DIF_SUBR_GETMINOR:
4365 #ifdef _LP64
4366 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4367 #else
4368 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4369 #endif
4370 break;
4371
4372 #else /* __APPLE__ */
4373 case DIF_SUBR_GETMINOR:
4374 regs[rd] = (uintptr_t)minor( (dev_t)tupregs[0].dttk_value );
4375 break;
4376 #endif /* __APPLE__ */
4377
4378 #if !defined(__APPLE__)
4379 case DIF_SUBR_DDI_PATHNAME: {
4380 /*
4381 * This one is a galactic mess. We are going to roughly
4382 * emulate ddi_pathname(), but it's made more complicated
4383 * by the fact that we (a) want to include the minor name and
4384 * (b) must proceed iteratively instead of recursively.
4385 */
4386 uintptr_t dest = mstate->dtms_scratch_ptr;
4387 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4388 char *start = (char *)dest, *end = start + size - 1;
4389 uintptr_t daddr = tupregs[0].dttk_value;
4390 int64_t minor = (int64_t)tupregs[1].dttk_value;
4391 char *s;
4392 int i, len, depth = 0;
4393
4394 /*
4395 * Due to all the pointer jumping we do and context we must
4396 * rely upon, we just mandate that the user must have kernel
4397 * read privileges to use this routine.
4398 */
4399 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4400 *flags |= CPU_DTRACE_KPRIV;
4401 *illval = daddr;
4402 regs[rd] = NULL;
4403 }
4404
4405 if (!DTRACE_INSCRATCH(mstate, size)) {
4406 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4407 regs[rd] = NULL;
4408 break;
4409 }
4410
4411 *end = '\0';
4412
4413 /*
4414 * We want to have a name for the minor. In order to do this,
4415 * we need to walk the minor list from the devinfo. We want
4416 * to be sure that we don't infinitely walk a circular list,
4417 * so we check for circularity by sending a scout pointer
4418 * ahead two elements for every element that we iterate over;
4419 * if the list is circular, these will ultimately point to the
4420 * same element. You may recognize this little trick as the
4421 * answer to a stupid interview question -- one that always
4422 * seems to be asked by those who had to have it laboriously
4423 * explained to them, and who can't even concisely describe
4424 * the conditions under which one would be forced to resort to
4425 * this technique. Needless to say, those conditions are
4426 * found here -- and probably only here. Is this the only use
4427 * of this infamous trick in shipping, production code? If it
4428 * isn't, it probably should be...
4429 */
4430 if (minor != -1) {
4431 uintptr_t maddr = dtrace_loadptr(daddr +
4432 offsetof(struct dev_info, devi_minor));
4433
4434 uintptr_t next = offsetof(struct ddi_minor_data, next);
4435 uintptr_t name = offsetof(struct ddi_minor_data,
4436 d_minor) + offsetof(struct ddi_minor, name);
4437 uintptr_t dev = offsetof(struct ddi_minor_data,
4438 d_minor) + offsetof(struct ddi_minor, dev);
4439 uintptr_t scout;
4440
4441 if (maddr != NULL)
4442 scout = dtrace_loadptr(maddr + next);
4443
4444 while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4445 uint64_t m;
4446 #ifdef _LP64
4447 m = dtrace_load64(maddr + dev) & MAXMIN64;
4448 #else
4449 m = dtrace_load32(maddr + dev) & MAXMIN;
4450 #endif
4451 if (m != minor) {
4452 maddr = dtrace_loadptr(maddr + next);
4453
4454 if (scout == NULL)
4455 continue;
4456
4457 scout = dtrace_loadptr(scout + next);
4458
4459 if (scout == NULL)
4460 continue;
4461
4462 scout = dtrace_loadptr(scout + next);
4463
4464 if (scout == NULL)
4465 continue;
4466
4467 if (scout == maddr) {
4468 *flags |= CPU_DTRACE_ILLOP;
4469 break;
4470 }
4471
4472 continue;
4473 }
4474
4475 /*
4476 * We have the minor data. Now we need to
4477 * copy the minor's name into the end of the
4478 * pathname.
4479 */
4480 s = (char *)dtrace_loadptr(maddr + name);
4481 len = dtrace_strlen(s, size);
4482
4483 if (*flags & CPU_DTRACE_FAULT)
4484 break;
4485
4486 if (len != 0) {
4487 if ((end -= (len + 1)) < start)
4488 break;
4489
4490 *end = ':';
4491 }
4492
4493 for (i = 1; i <= len; i++)
4494 end[i] = dtrace_load8((uintptr_t)s++);
4495 break;
4496 }
4497 }
4498
4499 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4500 ddi_node_state_t devi_state;
4501
4502 devi_state = dtrace_load32(daddr +
4503 offsetof(struct dev_info, devi_node_state));
4504
4505 if (*flags & CPU_DTRACE_FAULT)
4506 break;
4507
4508 if (devi_state >= DS_INITIALIZED) {
4509 s = (char *)dtrace_loadptr(daddr +
4510 offsetof(struct dev_info, devi_addr));
4511 len = dtrace_strlen(s, size);
4512
4513 if (*flags & CPU_DTRACE_FAULT)
4514 break;
4515
4516 if (len != 0) {
4517 if ((end -= (len + 1)) < start)
4518 break;
4519
4520 *end = '@';
4521 }
4522
4523 for (i = 1; i <= len; i++)
4524 end[i] = dtrace_load8((uintptr_t)s++);
4525 }
4526
4527 /*
4528 * Now for the node name...
4529 */
4530 s = (char *)dtrace_loadptr(daddr +
4531 offsetof(struct dev_info, devi_node_name));
4532
4533 daddr = dtrace_loadptr(daddr +
4534 offsetof(struct dev_info, devi_parent));
4535
4536 /*
4537 * If our parent is NULL (that is, if we're the root
4538 * node), we're going to use the special path
4539 * "devices".
4540 */
4541 if (daddr == NULL)
4542 s = "devices";
4543
4544 len = dtrace_strlen(s, size);
4545 if (*flags & CPU_DTRACE_FAULT)
4546 break;
4547
4548 if ((end -= (len + 1)) < start)
4549 break;
4550
4551 for (i = 1; i <= len; i++)
4552 end[i] = dtrace_load8((uintptr_t)s++);
4553 *end = '/';
4554
4555 if (depth++ > dtrace_devdepth_max) {
4556 *flags |= CPU_DTRACE_ILLOP;
4557 break;
4558 }
4559 }
4560
4561 if (end < start)
4562 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4563
4564 if (daddr == NULL) {
4565 regs[rd] = (uintptr_t)end;
4566 mstate->dtms_scratch_ptr += size;
4567 }
4568
4569 break;
4570 }
4571 #else
4572 case DIF_SUBR_DDI_PATHNAME: {
4573 /* FIXME: awaits galactic disentanglement ;-} */
4574 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4575 regs[rd] = NULL;
4576 break;
4577 }
4578 #endif /* __APPLE__ */
4579
4580 case DIF_SUBR_STRJOIN: {
4581 char *d = (char *)mstate->dtms_scratch_ptr;
4582 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4583 uintptr_t s1 = tupregs[0].dttk_value;
4584 uintptr_t s2 = tupregs[1].dttk_value;
4585 #if !defined(__APPLE__) /* Quiet compiler warnings */
4586 int i = 0;
4587 #else
4588 uint64_t i = 0;
4589 #endif /* __APPLE__ */
4590
4591 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4592 !dtrace_strcanload(s2, size, mstate, vstate)) {
4593 regs[rd] = NULL;
4594 break;
4595 }
4596
4597 if (!DTRACE_INSCRATCH(mstate, size)) {
4598 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4599 regs[rd] = NULL;
4600 break;
4601 }
4602
4603 for (;;) {
4604 if (i >= size) {
4605 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4606 regs[rd] = NULL;
4607 break;
4608 }
4609
4610 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4611 i--;
4612 break;
4613 }
4614 }
4615
4616 for (;;) {
4617 if (i >= size) {
4618 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4619 regs[rd] = NULL;
4620 break;
4621 }
4622
4623 if ((d[i++] = dtrace_load8(s2++)) == '\0')
4624 break;
4625 }
4626
4627 if (i < size) {
4628 mstate->dtms_scratch_ptr += i;
4629 regs[rd] = (uintptr_t)d;
4630 }
4631
4632 break;
4633 }
4634
4635 case DIF_SUBR_LLTOSTR: {
4636 int64_t i = (int64_t)tupregs[0].dttk_value;
4637 int64_t val = i < 0 ? i * -1 : i;
4638 uint64_t size = 22; /* enough room for 2^64 in decimal */
4639 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4640
4641 if (!DTRACE_INSCRATCH(mstate, size)) {
4642 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4643 regs[rd] = NULL;
4644 break;
4645 }
4646
4647 for (*end-- = '\0'; val; val /= 10)
4648 *end-- = '0' + (val % 10);
4649
4650 if (i == 0)
4651 *end-- = '0';
4652
4653 if (i < 0)
4654 *end-- = '-';
4655
4656 regs[rd] = (uintptr_t)end + 1;
4657 mstate->dtms_scratch_ptr += size;
4658 break;
4659 }
4660
4661 case DIF_SUBR_HTONS:
4662 case DIF_SUBR_NTOHS:
4663 #ifdef _BIG_ENDIAN
4664 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4665 #else
4666 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4667 #endif
4668 break;
4669
4670
4671 case DIF_SUBR_HTONL:
4672 case DIF_SUBR_NTOHL:
4673 #ifdef _BIG_ENDIAN
4674 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4675 #else
4676 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4677 #endif
4678 break;
4679
4680
4681 case DIF_SUBR_HTONLL:
4682 case DIF_SUBR_NTOHLL:
4683 #ifdef _BIG_ENDIAN
4684 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4685 #else
4686 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4687 #endif
4688 break;
4689
4690
4691 case DIF_SUBR_DIRNAME:
4692 case DIF_SUBR_BASENAME: {
4693 char *dest = (char *)mstate->dtms_scratch_ptr;
4694 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4695 uintptr_t src = tupregs[0].dttk_value;
4696 int i, j, len = dtrace_strlen((char *)src, size);
4697 int lastbase = -1, firstbase = -1, lastdir = -1;
4698 int start, end;
4699
4700 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4701 regs[rd] = NULL;
4702 break;
4703 }
4704
4705 if (!DTRACE_INSCRATCH(mstate, size)) {
4706 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4707 regs[rd] = NULL;
4708 break;
4709 }
4710
4711 /*
4712 * The basename and dirname for a zero-length string is
4713 * defined to be "."
4714 */
4715 if (len == 0) {
4716 len = 1;
4717 src = (uintptr_t)".";
4718 }
4719
4720 /*
4721 * Start from the back of the string, moving back toward the
4722 * front until we see a character that isn't a slash. That
4723 * character is the last character in the basename.
4724 */
4725 for (i = len - 1; i >= 0; i--) {
4726 if (dtrace_load8(src + i) != '/')
4727 break;
4728 }
4729
4730 if (i >= 0)
4731 lastbase = i;
4732
4733 /*
4734 * Starting from the last character in the basename, move
4735 * towards the front until we find a slash. The character
4736 * that we processed immediately before that is the first
4737 * character in the basename.
4738 */
4739 for (; i >= 0; i--) {
4740 if (dtrace_load8(src + i) == '/')
4741 break;
4742 }
4743
4744 if (i >= 0)
4745 firstbase = i + 1;
4746
4747 /*
4748 * Now keep going until we find a non-slash character. That
4749 * character is the last character in the dirname.
4750 */
4751 for (; i >= 0; i--) {
4752 if (dtrace_load8(src + i) != '/')
4753 break;
4754 }
4755
4756 if (i >= 0)
4757 lastdir = i;
4758
4759 ASSERT(!(lastbase == -1 && firstbase != -1));
4760 ASSERT(!(firstbase == -1 && lastdir != -1));
4761
4762 if (lastbase == -1) {
4763 /*
4764 * We didn't find a non-slash character. We know that
4765 * the length is non-zero, so the whole string must be
4766 * slashes. In either the dirname or the basename
4767 * case, we return '/'.
4768 */
4769 ASSERT(firstbase == -1);
4770 firstbase = lastbase = lastdir = 0;
4771 }
4772
4773 if (firstbase == -1) {
4774 /*
4775 * The entire string consists only of a basename
4776 * component. If we're looking for dirname, we need
4777 * to change our string to be just "."; if we're
4778 * looking for a basename, we'll just set the first
4779 * character of the basename to be 0.
4780 */
4781 if (subr == DIF_SUBR_DIRNAME) {
4782 ASSERT(lastdir == -1);
4783 src = (uintptr_t)".";
4784 lastdir = 0;
4785 } else {
4786 firstbase = 0;
4787 }
4788 }
4789
4790 if (subr == DIF_SUBR_DIRNAME) {
4791 if (lastdir == -1) {
4792 /*
4793 * We know that we have a slash in the name --
4794 * or lastdir would be set to 0, above. And
4795 * because lastdir is -1, we know that this
4796 * slash must be the first character. (That
4797 * is, the full string must be of the form
4798 * "/basename".) In this case, the last
4799 * character of the directory name is 0.
4800 */
4801 lastdir = 0;
4802 }
4803
4804 start = 0;
4805 end = lastdir;
4806 } else {
4807 ASSERT(subr == DIF_SUBR_BASENAME);
4808 ASSERT(firstbase != -1 && lastbase != -1);
4809 start = firstbase;
4810 end = lastbase;
4811 }
4812
4813 #if !defined(__APPLE__) /* Quiet compiler warnings */
4814 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4815 dest[j] = dtrace_load8(src + i);
4816 #else
4817 for (i = start, j = 0; i <= end && (uint64_t)j < size - 1; i++, j++)
4818 dest[j] = dtrace_load8(src + i);
4819 #endif /* __APPLE__ */
4820
4821 dest[j] = '\0';
4822 regs[rd] = (uintptr_t)dest;
4823 mstate->dtms_scratch_ptr += size;
4824 break;
4825 }
4826
4827 case DIF_SUBR_CLEANPATH: {
4828 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4829 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4830 uintptr_t src = tupregs[0].dttk_value;
4831 int i = 0, j = 0;
4832
4833 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4834 regs[rd] = NULL;
4835 break;
4836 }
4837
4838 if (!DTRACE_INSCRATCH(mstate, size)) {
4839 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4840 regs[rd] = NULL;
4841 break;
4842 }
4843
4844 /*
4845 * Move forward, loading each character.
4846 */
4847 do {
4848 c = dtrace_load8(src + i++);
4849 next:
4850 #if !defined(__APPLE__) /* Quiet compiler warnings */
4851 if (j + 5 >= size) /* 5 = strlen("/..c\0") */
4852 break;
4853 #else
4854 if ((uint64_t)(j + 5) >= size) /* 5 = strlen("/..c\0") */
4855 break;
4856 #endif /* __APPLE__ */
4857
4858 if (c != '/') {
4859 dest[j++] = c;
4860 continue;
4861 }
4862
4863 c = dtrace_load8(src + i++);
4864
4865 if (c == '/') {
4866 /*
4867 * We have two slashes -- we can just advance
4868 * to the next character.
4869 */
4870 goto next;
4871 }
4872
4873 if (c != '.') {
4874 /*
4875 * This is not "." and it's not ".." -- we can
4876 * just store the "/" and this character and
4877 * drive on.
4878 */
4879 dest[j++] = '/';
4880 dest[j++] = c;
4881 continue;
4882 }
4883
4884 c = dtrace_load8(src + i++);
4885
4886 if (c == '/') {
4887 /*
4888 * This is a "/./" component. We're not going
4889 * to store anything in the destination buffer;
4890 * we're just going to go to the next component.
4891 */
4892 goto next;
4893 }
4894
4895 if (c != '.') {
4896 /*
4897 * This is not ".." -- we can just store the
4898 * "/." and this character and continue
4899 * processing.
4900 */
4901 dest[j++] = '/';
4902 dest[j++] = '.';
4903 dest[j++] = c;
4904 continue;
4905 }
4906
4907 c = dtrace_load8(src + i++);
4908
4909 if (c != '/' && c != '\0') {
4910 /*
4911 * This is not ".." -- it's "..[mumble]".
4912 * We'll store the "/.." and this character
4913 * and continue processing.
4914 */
4915 dest[j++] = '/';
4916 dest[j++] = '.';
4917 dest[j++] = '.';
4918 dest[j++] = c;
4919 continue;
4920 }
4921
4922 /*
4923 * This is "/../" or "/..\0". We need to back up
4924 * our destination pointer until we find a "/".
4925 */
4926 i--;
4927 while (j != 0 && dest[--j] != '/')
4928 continue;
4929
4930 if (c == '\0')
4931 dest[++j] = '/';
4932 } while (c != '\0');
4933
4934 dest[j] = '\0';
4935 regs[rd] = (uintptr_t)dest;
4936 mstate->dtms_scratch_ptr += size;
4937 break;
4938 }
4939
4940 case DIF_SUBR_INET_NTOA:
4941 case DIF_SUBR_INET_NTOA6:
4942 case DIF_SUBR_INET_NTOP: {
4943 size_t size;
4944 int af, argi, i;
4945 char *base, *end;
4946
4947 if (subr == DIF_SUBR_INET_NTOP) {
4948 af = (int)tupregs[0].dttk_value;
4949 argi = 1;
4950 } else {
4951 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4952 argi = 0;
4953 }
4954
4955 if (af == AF_INET) {
4956 #if !defined(__APPLE__)
4957 ipaddr_t ip4;
4958 #else
4959 uint32_t ip4;
4960 #endif /* __APPLE__ */
4961 uint8_t *ptr8, val;
4962
4963 /*
4964 * Safely load the IPv4 address.
4965 */
4966 #if !defined(__APPLE__)
4967 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4968 #else
4969 dtrace_bcopy(
4970 (void *)(uintptr_t)tupregs[argi].dttk_value,
4971 (void *)(uintptr_t)&ip4, sizeof (ip4));
4972 #endif /* __APPLE__ */
4973 /*
4974 * Check an IPv4 string will fit in scratch.
4975 */
4976 #if !defined(__APPLE__)
4977 size = INET_ADDRSTRLEN;
4978 #else
4979 size = MAX_IPv4_STR_LEN;
4980 #endif /* __APPLE__ */
4981 if (!DTRACE_INSCRATCH(mstate, size)) {
4982 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4983 regs[rd] = NULL;
4984 break;
4985 }
4986 base = (char *)mstate->dtms_scratch_ptr;
4987 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4988
4989 /*
4990 * Stringify as a dotted decimal quad.
4991 */
4992 *end-- = '\0';
4993 ptr8 = (uint8_t *)&ip4;
4994 for (i = 3; i >= 0; i--) {
4995 val = ptr8[i];
4996
4997 if (val == 0) {
4998 *end-- = '0';
4999 } else {
5000 for (; val; val /= 10) {
5001 *end-- = '0' + (val % 10);
5002 }
5003 }
5004
5005 if (i > 0)
5006 *end-- = '.';
5007 }
5008 ASSERT(end + 1 >= base);
5009
5010 } else if (af == AF_INET6) {
5011 #if defined(__APPLE__)
5012 #define _S6_un __u6_addr
5013 #define _S6_u8 __u6_addr8
5014 #endif /* __APPLE__ */
5015 struct in6_addr ip6;
5016 int firstzero, tryzero, numzero, v6end;
5017 uint16_t val;
5018 const char digits[] = "0123456789abcdef";
5019
5020 /*
5021 * Stringify using RFC 1884 convention 2 - 16 bit
5022 * hexadecimal values with a zero-run compression.
5023 * Lower case hexadecimal digits are used.
5024 * eg, fe80::214:4fff:fe0b:76c8.
5025 * The IPv4 embedded form is returned for inet_ntop,
5026 * just the IPv4 string is returned for inet_ntoa6.
5027 */
5028
5029 /*
5030 * Safely load the IPv6 address.
5031 */
5032 dtrace_bcopy(
5033 (void *)(uintptr_t)tupregs[argi].dttk_value,
5034 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5035
5036 /*
5037 * Check an IPv6 string will fit in scratch.
5038 */
5039 size = INET6_ADDRSTRLEN;
5040 if (!DTRACE_INSCRATCH(mstate, size)) {
5041 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5042 regs[rd] = NULL;
5043 break;
5044 }
5045 base = (char *)mstate->dtms_scratch_ptr;
5046 end = (char *)mstate->dtms_scratch_ptr + size - 1;
5047 *end-- = '\0';
5048
5049 /*
5050 * Find the longest run of 16 bit zero values
5051 * for the single allowed zero compression - "::".
5052 */
5053 firstzero = -1;
5054 tryzero = -1;
5055 numzero = 1;
5056 #if !defined(__APPLE__) /* Quiet compiler warnings */
5057 for (i = 0; i < sizeof (struct in6_addr); i++) {
5058 #else
5059 for (i = 0; i < (int)sizeof (struct in6_addr); i++) {
5060 #endif /* __APPLE__ */
5061 if (ip6._S6_un._S6_u8[i] == 0 &&
5062 tryzero == -1 && i % 2 == 0) {
5063 tryzero = i;
5064 continue;
5065 }
5066
5067 if (tryzero != -1 &&
5068 (ip6._S6_un._S6_u8[i] != 0 ||
5069 i == sizeof (struct in6_addr) - 1)) {
5070
5071 if (i - tryzero <= numzero) {
5072 tryzero = -1;
5073 continue;
5074 }
5075
5076 firstzero = tryzero;
5077 numzero = i - i % 2 - tryzero;
5078 tryzero = -1;
5079
5080 if (ip6._S6_un._S6_u8[i] == 0 &&
5081 i == sizeof (struct in6_addr) - 1)
5082 numzero += 2;
5083 }
5084 }
5085 #if !defined(__APPLE__) /* Quiet compiler warnings */
5086 ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5087 #else
5088 ASSERT(firstzero + numzero <= (int)sizeof (struct in6_addr));
5089 #endif /* __APPLE__ */
5090
5091 /*
5092 * Check for an IPv4 embedded address.
5093 */
5094 v6end = sizeof (struct in6_addr) - 2;
5095 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5096 IN6_IS_ADDR_V4COMPAT(&ip6)) {
5097 #if !defined(__APPLE__) /* Quiet compiler warnings */
5098 for (i = sizeof (struct in6_addr) - 1;
5099 i >= DTRACE_V4MAPPED_OFFSET; i--) {
5100 #else
5101 for (i = sizeof (struct in6_addr) - 1;
5102 i >= (int)DTRACE_V4MAPPED_OFFSET; i--) {
5103 #endif /* __APPLE__ */
5104 ASSERT(end >= base);
5105
5106 val = ip6._S6_un._S6_u8[i];
5107
5108 if (val == 0) {
5109 *end-- = '0';
5110 } else {
5111 for (; val; val /= 10) {
5112 *end-- = '0' + val % 10;
5113 }
5114 }
5115
5116 #if !defined(__APPLE__) /* Quiet compiler warnings */
5117 if (i > DTRACE_V4MAPPED_OFFSET)
5118 *end-- = '.';
5119 #else
5120 if (i > (int)DTRACE_V4MAPPED_OFFSET)
5121 *end-- = '.';
5122 #endif /* __APPLE__ */
5123 }
5124
5125 if (subr == DIF_SUBR_INET_NTOA6)
5126 goto inetout;
5127
5128 /*
5129 * Set v6end to skip the IPv4 address that
5130 * we have already stringified.
5131 */
5132 v6end = 10;
5133 }
5134
5135 /*
5136 * Build the IPv6 string by working through the
5137 * address in reverse.
5138 */
5139 for (i = v6end; i >= 0; i -= 2) {
5140 ASSERT(end >= base);
5141
5142 if (i == firstzero + numzero - 2) {
5143 *end-- = ':';
5144 *end-- = ':';
5145 i -= numzero - 2;
5146 continue;
5147 }
5148
5149 if (i < 14 && i != firstzero - 2)
5150 *end-- = ':';
5151
5152 val = (ip6._S6_un._S6_u8[i] << 8) +
5153 ip6._S6_un._S6_u8[i + 1];
5154
5155 if (val == 0) {
5156 *end-- = '0';
5157 } else {
5158 for (; val; val /= 16) {
5159 *end-- = digits[val % 16];
5160 }
5161 }
5162 }
5163 ASSERT(end + 1 >= base);
5164
5165 #if defined(__APPLE__)
5166 #undef _S6_un
5167 #undef _S6_u8
5168 #endif /* __APPLE__ */
5169 } else {
5170 /*
5171 * The user didn't use AH_INET or AH_INET6.
5172 */
5173 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5174 regs[rd] = NULL;
5175 break;
5176 }
5177
5178 inetout: regs[rd] = (uintptr_t)end + 1;
5179 mstate->dtms_scratch_ptr += size;
5180 break;
5181 }
5182
5183 #ifdef __APPLE__
5184
5185 /* CoreProfile callback ('core_profile(uint64_t, [uint64_t], [uint64_t] ...)') */
5186 case DIF_SUBR_COREPROFILE: {
5187 uint64_t selector = tupregs[0].dttk_value;
5188 uint64_t args[DIF_DTR_NREGS-1] = {0ULL};
5189 uint32_t ii;
5190 uint32_t count = (uint32_t)nargs;
5191
5192 if (count < 1) {
5193 regs[rd] = KERN_FAILURE;
5194 break;
5195 }
5196
5197 if(count > DIF_DTR_NREGS)
5198 count = DIF_DTR_NREGS;
5199
5200 /* copy in any variadic argument list, bounded by DIF_DTR_NREGS */
5201 for(ii = 0; ii < count-1; ii++) {
5202 args[ii] = tupregs[ii+1].dttk_value;
5203 }
5204
5205 kern_return_t ret =
5206 chudxnu_dtrace_callback(selector, args, count-1);
5207 if(KERN_SUCCESS != ret) {
5208 /* error */
5209 }
5210
5211 regs[rd] = ret;
5212 break;
5213 }
5214
5215 #endif /* __APPLE__ */
5216
5217 }
5218 }
5219
5220 /*
5221 * Emulate the execution of DTrace IR instructions specified by the given
5222 * DIF object. This function is deliberately void of assertions as all of
5223 * the necessary checks are handled by a call to dtrace_difo_validate().
5224 */
5225 static uint64_t
5226 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5227 dtrace_vstate_t *vstate, dtrace_state_t *state)
5228 {
5229 const dif_instr_t *text = difo->dtdo_buf;
5230 const uint_t textlen = difo->dtdo_len;
5231 const char *strtab = difo->dtdo_strtab;
5232 const uint64_t *inttab = difo->dtdo_inttab;
5233
5234 uint64_t rval = 0;
5235 dtrace_statvar_t *svar;
5236 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5237 dtrace_difv_t *v;
5238 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5239 #if !defined(__APPLE__)
5240 volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5241 #else
5242 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5243 #endif /* __APPLE__ */
5244
5245 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5246 uint64_t regs[DIF_DIR_NREGS];
5247 uint64_t *tmp;
5248
5249 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5250 int64_t cc_r;
5251 #if !defined(__APPLE__) /* Quiet compiler warnings */
5252 uint_t pc = 0, id, opc;
5253 #else
5254 uint_t pc = 0, id, opc = 0;
5255 #endif /* __APPLE__ */
5256 uint8_t ttop = 0;
5257 dif_instr_t instr;
5258 uint_t r1, r2, rd;
5259
5260 /*
5261 * We stash the current DIF object into the machine state: we need it
5262 * for subsequent access checking.
5263 */
5264 mstate->dtms_difo = difo;
5265
5266 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
5267
5268 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5269 opc = pc;
5270
5271 instr = text[pc++];
5272 r1 = DIF_INSTR_R1(instr);
5273 r2 = DIF_INSTR_R2(instr);
5274 rd = DIF_INSTR_RD(instr);
5275
5276 switch (DIF_INSTR_OP(instr)) {
5277 case DIF_OP_OR:
5278 regs[rd] = regs[r1] | regs[r2];
5279 break;
5280 case DIF_OP_XOR:
5281 regs[rd] = regs[r1] ^ regs[r2];
5282 break;
5283 case DIF_OP_AND:
5284 regs[rd] = regs[r1] & regs[r2];
5285 break;
5286 case DIF_OP_SLL:
5287 regs[rd] = regs[r1] << regs[r2];
5288 break;
5289 case DIF_OP_SRL:
5290 regs[rd] = regs[r1] >> regs[r2];
5291 break;
5292 case DIF_OP_SUB:
5293 regs[rd] = regs[r1] - regs[r2];
5294 break;
5295 case DIF_OP_ADD:
5296 regs[rd] = regs[r1] + regs[r2];
5297 break;
5298 case DIF_OP_MUL:
5299 regs[rd] = regs[r1] * regs[r2];
5300 break;
5301 case DIF_OP_SDIV:
5302 if (regs[r2] == 0) {
5303 regs[rd] = 0;
5304 *flags |= CPU_DTRACE_DIVZERO;
5305 } else {
5306 regs[rd] = (int64_t)regs[r1] /
5307 (int64_t)regs[r2];
5308 }
5309 break;
5310
5311 case DIF_OP_UDIV:
5312 if (regs[r2] == 0) {
5313 regs[rd] = 0;
5314 *flags |= CPU_DTRACE_DIVZERO;
5315 } else {
5316 regs[rd] = regs[r1] / regs[r2];
5317 }
5318 break;
5319
5320 case DIF_OP_SREM:
5321 if (regs[r2] == 0) {
5322 regs[rd] = 0;
5323 *flags |= CPU_DTRACE_DIVZERO;
5324 } else {
5325 regs[rd] = (int64_t)regs[r1] %
5326 (int64_t)regs[r2];
5327 }
5328 break;
5329
5330 case DIF_OP_UREM:
5331 if (regs[r2] == 0) {
5332 regs[rd] = 0;
5333 *flags |= CPU_DTRACE_DIVZERO;
5334 } else {
5335 regs[rd] = regs[r1] % regs[r2];
5336 }
5337 break;
5338
5339 case DIF_OP_NOT:
5340 regs[rd] = ~regs[r1];
5341 break;
5342 case DIF_OP_MOV:
5343 regs[rd] = regs[r1];
5344 break;
5345 case DIF_OP_CMP:
5346 cc_r = regs[r1] - regs[r2];
5347 cc_n = cc_r < 0;
5348 cc_z = cc_r == 0;
5349 cc_v = 0;
5350 cc_c = regs[r1] < regs[r2];
5351 break;
5352 case DIF_OP_TST:
5353 cc_n = cc_v = cc_c = 0;
5354 cc_z = regs[r1] == 0;
5355 break;
5356 case DIF_OP_BA:
5357 pc = DIF_INSTR_LABEL(instr);
5358 break;
5359 case DIF_OP_BE:
5360 if (cc_z)
5361 pc = DIF_INSTR_LABEL(instr);
5362 break;
5363 case DIF_OP_BNE:
5364 if (cc_z == 0)
5365 pc = DIF_INSTR_LABEL(instr);
5366 break;
5367 case DIF_OP_BG:
5368 if ((cc_z | (cc_n ^ cc_v)) == 0)
5369 pc = DIF_INSTR_LABEL(instr);
5370 break;
5371 case DIF_OP_BGU:
5372 if ((cc_c | cc_z) == 0)
5373 pc = DIF_INSTR_LABEL(instr);
5374 break;
5375 case DIF_OP_BGE:
5376 if ((cc_n ^ cc_v) == 0)
5377 pc = DIF_INSTR_LABEL(instr);
5378 break;
5379 case DIF_OP_BGEU:
5380 if (cc_c == 0)
5381 pc = DIF_INSTR_LABEL(instr);
5382 break;
5383 case DIF_OP_BL:
5384 if (cc_n ^ cc_v)
5385 pc = DIF_INSTR_LABEL(instr);
5386 break;
5387 case DIF_OP_BLU:
5388 if (cc_c)
5389 pc = DIF_INSTR_LABEL(instr);
5390 break;
5391 case DIF_OP_BLE:
5392 if (cc_z | (cc_n ^ cc_v))
5393 pc = DIF_INSTR_LABEL(instr);
5394 break;
5395 case DIF_OP_BLEU:
5396 if (cc_c | cc_z)
5397 pc = DIF_INSTR_LABEL(instr);
5398 break;
5399 case DIF_OP_RLDSB:
5400 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5401 *flags |= CPU_DTRACE_KPRIV;
5402 *illval = regs[r1];
5403 break;
5404 }
5405 /*FALLTHROUGH*/
5406 case DIF_OP_LDSB:
5407 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5408 break;
5409 case DIF_OP_RLDSH:
5410 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5411 *flags |= CPU_DTRACE_KPRIV;
5412 *illval = regs[r1];
5413 break;
5414 }
5415 /*FALLTHROUGH*/
5416 case DIF_OP_LDSH:
5417 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5418 break;
5419 case DIF_OP_RLDSW:
5420 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5421 *flags |= CPU_DTRACE_KPRIV;
5422 *illval = regs[r1];
5423 break;
5424 }
5425 /*FALLTHROUGH*/
5426 case DIF_OP_LDSW:
5427 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5428 break;
5429 case DIF_OP_RLDUB:
5430 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5431 *flags |= CPU_DTRACE_KPRIV;
5432 *illval = regs[r1];
5433 break;
5434 }
5435 /*FALLTHROUGH*/
5436 case DIF_OP_LDUB:
5437 regs[rd] = dtrace_load8(regs[r1]);
5438 break;
5439 case DIF_OP_RLDUH:
5440 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5441 *flags |= CPU_DTRACE_KPRIV;
5442 *illval = regs[r1];
5443 break;
5444 }
5445 /*FALLTHROUGH*/
5446 case DIF_OP_LDUH:
5447 regs[rd] = dtrace_load16(regs[r1]);
5448 break;
5449 case DIF_OP_RLDUW:
5450 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5451 *flags |= CPU_DTRACE_KPRIV;
5452 *illval = regs[r1];
5453 break;
5454 }
5455 /*FALLTHROUGH*/
5456 case DIF_OP_LDUW:
5457 regs[rd] = dtrace_load32(regs[r1]);
5458 break;
5459 case DIF_OP_RLDX:
5460 if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5461 *flags |= CPU_DTRACE_KPRIV;
5462 *illval = regs[r1];
5463 break;
5464 }
5465 /*FALLTHROUGH*/
5466 case DIF_OP_LDX:
5467 regs[rd] = dtrace_load64(regs[r1]);
5468 break;
5469 #if !defined(__APPLE__)
5470 case DIF_OP_ULDSB:
5471 regs[rd] = (int8_t)
5472 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5473 break;
5474 case DIF_OP_ULDSH:
5475 regs[rd] = (int16_t)
5476 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5477 break;
5478 case DIF_OP_ULDSW:
5479 regs[rd] = (int32_t)
5480 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5481 break;
5482 case DIF_OP_ULDUB:
5483 regs[rd] =
5484 dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5485 break;
5486 case DIF_OP_ULDUH:
5487 regs[rd] =
5488 dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5489 break;
5490 case DIF_OP_ULDUW:
5491 regs[rd] =
5492 dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5493 break;
5494 case DIF_OP_ULDX:
5495 regs[rd] =
5496 dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5497 break;
5498 #else /* Darwin 32-bit kernel may fetch from 64-bit user. Don't want uintptr_t cast. */
5499 case DIF_OP_ULDSB:
5500 regs[rd] = (int8_t)
5501 dtrace_fuword8(regs[r1]);
5502 break;
5503 case DIF_OP_ULDSH:
5504 regs[rd] = (int16_t)
5505 dtrace_fuword16(regs[r1]);
5506 break;
5507 case DIF_OP_ULDSW:
5508 regs[rd] = (int32_t)
5509 dtrace_fuword32(regs[r1]);
5510 break;
5511 case DIF_OP_ULDUB:
5512 regs[rd] =
5513 dtrace_fuword8(regs[r1]);
5514 break;
5515 case DIF_OP_ULDUH:
5516 regs[rd] =
5517 dtrace_fuword16(regs[r1]);
5518 break;
5519 case DIF_OP_ULDUW:
5520 regs[rd] =
5521 dtrace_fuword32(regs[r1]);
5522 break;
5523 case DIF_OP_ULDX:
5524 regs[rd] =
5525 dtrace_fuword64(regs[r1]);
5526 #endif /* __APPLE__ */
5527 break;
5528 case DIF_OP_RET:
5529 rval = regs[rd];
5530 pc = textlen;
5531 break;
5532 case DIF_OP_NOP:
5533 break;
5534 case DIF_OP_SETX:
5535 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5536 break;
5537 case DIF_OP_SETS:
5538 regs[rd] = (uint64_t)(uintptr_t)
5539 (strtab + DIF_INSTR_STRING(instr));
5540 break;
5541 case DIF_OP_SCMP: {
5542 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5543 uintptr_t s1 = regs[r1];
5544 uintptr_t s2 = regs[r2];
5545
5546 if (s1 != NULL &&
5547 !dtrace_strcanload(s1, sz, mstate, vstate))
5548 break;
5549 if (s2 != NULL &&
5550 !dtrace_strcanload(s2, sz, mstate, vstate))
5551 break;
5552
5553 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5554
5555 cc_n = cc_r < 0;
5556 cc_z = cc_r == 0;
5557 cc_v = cc_c = 0;
5558 break;
5559 }
5560 case DIF_OP_LDGA:
5561 regs[rd] = dtrace_dif_variable(mstate, state,
5562 r1, regs[r2]);
5563 break;
5564 case DIF_OP_LDGS:
5565 id = DIF_INSTR_VAR(instr);
5566
5567 if (id >= DIF_VAR_OTHER_UBASE) {
5568 uintptr_t a;
5569
5570 id -= DIF_VAR_OTHER_UBASE;
5571 svar = vstate->dtvs_globals[id];
5572 ASSERT(svar != NULL);
5573 v = &svar->dtsv_var;
5574
5575 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5576 regs[rd] = svar->dtsv_data;
5577 break;
5578 }
5579
5580 a = (uintptr_t)svar->dtsv_data;
5581
5582 if (*(uint8_t *)a == UINT8_MAX) {
5583 /*
5584 * If the 0th byte is set to UINT8_MAX
5585 * then this is to be treated as a
5586 * reference to a NULL variable.
5587 */
5588 regs[rd] = NULL;
5589 } else {
5590 regs[rd] = a + sizeof (uint64_t);
5591 }
5592
5593 break;
5594 }
5595
5596 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5597 break;
5598
5599 case DIF_OP_STGS:
5600 id = DIF_INSTR_VAR(instr);
5601
5602 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5603 id -= DIF_VAR_OTHER_UBASE;
5604
5605 svar = vstate->dtvs_globals[id];
5606 ASSERT(svar != NULL);
5607 v = &svar->dtsv_var;
5608
5609 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5610 uintptr_t a = (uintptr_t)svar->dtsv_data;
5611
5612 ASSERT(a != NULL);
5613 ASSERT(svar->dtsv_size != 0);
5614
5615 if (regs[rd] == NULL) {
5616 *(uint8_t *)a = UINT8_MAX;
5617 break;
5618 } else {
5619 *(uint8_t *)a = 0;
5620 a += sizeof (uint64_t);
5621 }
5622 if (!dtrace_vcanload(
5623 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5624 mstate, vstate))
5625 break;
5626
5627 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5628 (void *)a, &v->dtdv_type);
5629 break;
5630 }
5631
5632 svar->dtsv_data = regs[rd];
5633 break;
5634
5635 case DIF_OP_LDTA:
5636 /*
5637 * There are no DTrace built-in thread-local arrays at
5638 * present. This opcode is saved for future work.
5639 */
5640 *flags |= CPU_DTRACE_ILLOP;
5641 regs[rd] = 0;
5642 break;
5643
5644 case DIF_OP_LDLS:
5645 id = DIF_INSTR_VAR(instr);
5646
5647 if (id < DIF_VAR_OTHER_UBASE) {
5648 /*
5649 * For now, this has no meaning.
5650 */
5651 regs[rd] = 0;
5652 break;
5653 }
5654
5655 id -= DIF_VAR_OTHER_UBASE;
5656
5657 #if !defined(__APPLE__) /* Quiet compiler warnings */
5658 ASSERT(id < vstate->dtvs_nlocals);
5659 #else
5660 ASSERT(id < (uint_t)vstate->dtvs_nlocals);
5661 #endif /* __APPLE__ */
5662 ASSERT(vstate->dtvs_locals != NULL);
5663
5664 svar = vstate->dtvs_locals[id];
5665 ASSERT(svar != NULL);
5666 v = &svar->dtsv_var;
5667
5668 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5669 uintptr_t a = (uintptr_t)svar->dtsv_data;
5670 size_t sz = v->dtdv_type.dtdt_size;
5671
5672 sz += sizeof (uint64_t);
5673 ASSERT(svar->dtsv_size == (int)NCPU * sz);
5674 a += CPU->cpu_id * sz;
5675
5676 if (*(uint8_t *)a == UINT8_MAX) {
5677 /*
5678 * If the 0th byte is set to UINT8_MAX
5679 * then this is to be treated as a
5680 * reference to a NULL variable.
5681 */
5682 regs[rd] = NULL;
5683 } else {
5684 regs[rd] = a + sizeof (uint64_t);
5685 }
5686
5687 break;
5688 }
5689
5690 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5691 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5692 regs[rd] = tmp[CPU->cpu_id];
5693 break;
5694
5695 case DIF_OP_STLS:
5696 id = DIF_INSTR_VAR(instr);
5697
5698 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5699 id -= DIF_VAR_OTHER_UBASE;
5700 #if !defined(__APPLE__) /* Quiet compiler warnings */
5701 ASSERT(id < vstate->dtvs_nlocals);
5702 #else
5703 ASSERT(id < (uint_t)vstate->dtvs_nlocals);
5704 #endif /* __APPLE__ */
5705
5706 ASSERT(vstate->dtvs_locals != NULL);
5707 svar = vstate->dtvs_locals[id];
5708 ASSERT(svar != NULL);
5709 v = &svar->dtsv_var;
5710
5711 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5712 uintptr_t a = (uintptr_t)svar->dtsv_data;
5713 size_t sz = v->dtdv_type.dtdt_size;
5714
5715 sz += sizeof (uint64_t);
5716 ASSERT(svar->dtsv_size == (int)NCPU * sz);
5717 a += CPU->cpu_id * sz;
5718
5719 if (regs[rd] == NULL) {
5720 *(uint8_t *)a = UINT8_MAX;
5721 break;
5722 } else {
5723 *(uint8_t *)a = 0;
5724 a += sizeof (uint64_t);
5725 }
5726
5727 if (!dtrace_vcanload(
5728 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5729 mstate, vstate))
5730 break;
5731
5732 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5733 (void *)a, &v->dtdv_type);
5734 break;
5735 }
5736
5737 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5738 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5739 tmp[CPU->cpu_id] = regs[rd];
5740 break;
5741
5742 case DIF_OP_LDTS: {
5743 dtrace_dynvar_t *dvar;
5744 dtrace_key_t *key;
5745
5746 id = DIF_INSTR_VAR(instr);
5747 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5748 id -= DIF_VAR_OTHER_UBASE;
5749 v = &vstate->dtvs_tlocals[id];
5750
5751 key = &tupregs[DIF_DTR_NREGS];
5752 key[0].dttk_value = (uint64_t)id;
5753 key[0].dttk_size = 0;
5754 DTRACE_TLS_THRKEY(key[1].dttk_value);
5755 key[1].dttk_size = 0;
5756
5757 dvar = dtrace_dynvar(dstate, 2, key,
5758 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5759 mstate, vstate);
5760
5761 if (dvar == NULL) {
5762 regs[rd] = 0;
5763 break;
5764 }
5765
5766 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5767 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5768 } else {
5769 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5770 }
5771
5772 break;
5773 }
5774
5775 case DIF_OP_STTS: {
5776 dtrace_dynvar_t *dvar;
5777 dtrace_key_t *key;
5778
5779 id = DIF_INSTR_VAR(instr);
5780 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5781 id -= DIF_VAR_OTHER_UBASE;
5782
5783 key = &tupregs[DIF_DTR_NREGS];
5784 key[0].dttk_value = (uint64_t)id;
5785 key[0].dttk_size = 0;
5786 DTRACE_TLS_THRKEY(key[1].dttk_value);
5787 key[1].dttk_size = 0;
5788 v = &vstate->dtvs_tlocals[id];
5789
5790 dvar = dtrace_dynvar(dstate, 2, key,
5791 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5792 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5793 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5794 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5795
5796 /*
5797 * Given that we're storing to thread-local data,
5798 * we need to flush our predicate cache.
5799 */
5800 #if !defined(__APPLE__)
5801 curthread->t_predcache = NULL;
5802 #else
5803 dtrace_set_thread_predcache(current_thread(), 0);
5804 #endif /* __APPLE__ */
5805
5806 if (dvar == NULL)
5807 break;
5808
5809 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5810 if (!dtrace_vcanload(
5811 (void *)(uintptr_t)regs[rd],
5812 &v->dtdv_type, mstate, vstate))
5813 break;
5814
5815 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5816 dvar->dtdv_data, &v->dtdv_type);
5817 } else {
5818 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5819 }
5820
5821 break;
5822 }
5823
5824 case DIF_OP_SRA:
5825 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5826 break;
5827
5828 case DIF_OP_CALL:
5829 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5830 regs, tupregs, ttop, mstate, state);
5831 break;
5832
5833 case DIF_OP_PUSHTR:
5834 if (ttop == DIF_DTR_NREGS) {
5835 *flags |= CPU_DTRACE_TUPOFLOW;
5836 break;
5837 }
5838
5839 if (r1 == DIF_TYPE_STRING) {
5840 /*
5841 * If this is a string type and the size is 0,
5842 * we'll use the system-wide default string
5843 * size. Note that we are _not_ looking at
5844 * the value of the DTRACEOPT_STRSIZE option;
5845 * had this been set, we would expect to have
5846 * a non-zero size value in the "pushtr".
5847 */
5848 tupregs[ttop].dttk_size =
5849 dtrace_strlen((char *)(uintptr_t)regs[rd],
5850 regs[r2] ? regs[r2] :
5851 dtrace_strsize_default) + 1;
5852 } else {
5853 tupregs[ttop].dttk_size = regs[r2];
5854 }
5855
5856 tupregs[ttop++].dttk_value = regs[rd];
5857 break;
5858
5859 case DIF_OP_PUSHTV:
5860 if (ttop == DIF_DTR_NREGS) {
5861 *flags |= CPU_DTRACE_TUPOFLOW;
5862 break;
5863 }
5864
5865 tupregs[ttop].dttk_value = regs[rd];
5866 tupregs[ttop++].dttk_size = 0;
5867 break;
5868
5869 case DIF_OP_POPTS:
5870 if (ttop != 0)
5871 ttop--;
5872 break;
5873
5874 case DIF_OP_FLUSHTS:
5875 ttop = 0;
5876 break;
5877
5878 case DIF_OP_LDGAA:
5879 case DIF_OP_LDTAA: {
5880 dtrace_dynvar_t *dvar;
5881 dtrace_key_t *key = tupregs;
5882 uint_t nkeys = ttop;
5883
5884 id = DIF_INSTR_VAR(instr);
5885 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5886 id -= DIF_VAR_OTHER_UBASE;
5887
5888 key[nkeys].dttk_value = (uint64_t)id;
5889 key[nkeys++].dttk_size = 0;
5890
5891 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5892 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5893 key[nkeys++].dttk_size = 0;
5894 v = &vstate->dtvs_tlocals[id];
5895 } else {
5896 v = &vstate->dtvs_globals[id]->dtsv_var;
5897 }
5898
5899 dvar = dtrace_dynvar(dstate, nkeys, key,
5900 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5901 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5902 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5903
5904 if (dvar == NULL) {
5905 regs[rd] = 0;
5906 break;
5907 }
5908
5909 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5910 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5911 } else {
5912 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5913 }
5914
5915 break;
5916 }
5917
5918 case DIF_OP_STGAA:
5919 case DIF_OP_STTAA: {
5920 dtrace_dynvar_t *dvar;
5921 dtrace_key_t *key = tupregs;
5922 uint_t nkeys = ttop;
5923
5924 id = DIF_INSTR_VAR(instr);
5925 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5926 id -= DIF_VAR_OTHER_UBASE;
5927
5928 key[nkeys].dttk_value = (uint64_t)id;
5929 key[nkeys++].dttk_size = 0;
5930
5931 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5932 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5933 key[nkeys++].dttk_size = 0;
5934 v = &vstate->dtvs_tlocals[id];
5935 } else {
5936 v = &vstate->dtvs_globals[id]->dtsv_var;
5937 }
5938
5939 dvar = dtrace_dynvar(dstate, nkeys, key,
5940 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5941 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5942 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5943 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5944
5945 if (dvar == NULL)
5946 break;
5947
5948 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5949 if (!dtrace_vcanload(
5950 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5951 mstate, vstate))
5952 break;
5953
5954 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5955 dvar->dtdv_data, &v->dtdv_type);
5956 } else {
5957 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5958 }
5959
5960 break;
5961 }
5962
5963 case DIF_OP_ALLOCS: {
5964 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5965 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5966
5967 /*
5968 * Rounding up the user allocation size could have
5969 * overflowed large, bogus allocations (like -1ULL) to
5970 * 0.
5971 */
5972 if (size < regs[r1] ||
5973 !DTRACE_INSCRATCH(mstate, size)) {
5974 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5975 regs[rd] = NULL;
5976 break;
5977 }
5978
5979 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5980 mstate->dtms_scratch_ptr += size;
5981 regs[rd] = ptr;
5982 break;
5983 }
5984
5985 case DIF_OP_COPYS:
5986 if (!dtrace_canstore(regs[rd], regs[r2],
5987 mstate, vstate)) {
5988 *flags |= CPU_DTRACE_BADADDR;
5989 *illval = regs[rd];
5990 break;
5991 }
5992
5993 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5994 break;
5995
5996 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5997 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5998 break;
5999
6000 case DIF_OP_STB:
6001 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6002 *flags |= CPU_DTRACE_BADADDR;
6003 *illval = regs[rd];
6004 break;
6005 }
6006 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6007 break;
6008
6009 case DIF_OP_STH:
6010 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6011 *flags |= CPU_DTRACE_BADADDR;
6012 *illval = regs[rd];
6013 break;
6014 }
6015 if (regs[rd] & 1) {
6016 *flags |= CPU_DTRACE_BADALIGN;
6017 *illval = regs[rd];
6018 break;
6019 }
6020 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6021 break;
6022
6023 case DIF_OP_STW:
6024 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6025 *flags |= CPU_DTRACE_BADADDR;
6026 *illval = regs[rd];
6027 break;
6028 }
6029 if (regs[rd] & 3) {
6030 *flags |= CPU_DTRACE_BADALIGN;
6031 *illval = regs[rd];
6032 break;
6033 }
6034 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6035 break;
6036
6037 case DIF_OP_STX:
6038 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6039 *flags |= CPU_DTRACE_BADADDR;
6040 *illval = regs[rd];
6041 break;
6042 }
6043 #if !defined(__APPLE__)
6044 if (regs[rd] & 7) {
6045 #else
6046 if (regs[rd] & 3) { /* Darwin kmem_zalloc() called from dtrace_difo_init() is 4-byte aligned. */
6047 #endif /* __APPLE__ */
6048 *flags |= CPU_DTRACE_BADALIGN;
6049 *illval = regs[rd];
6050 break;
6051 }
6052 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6053 break;
6054 }
6055 }
6056
6057 if (!(*flags & CPU_DTRACE_FAULT))
6058 return (rval);
6059
6060 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6061 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6062
6063 return (0);
6064 }
6065
6066 static void
6067 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6068 {
6069 dtrace_probe_t *probe = ecb->dte_probe;
6070 dtrace_provider_t *prov = probe->dtpr_provider;
6071 char c[DTRACE_FULLNAMELEN + 80], *str;
6072 #if !defined(__APPLE__) /* Quiet compiler warnings */
6073 char *msg = "dtrace: breakpoint action at probe ";
6074 char *ecbmsg = " (ecb ";
6075 #else
6076 const char *msg = "dtrace: breakpoint action at probe ";
6077 const char *ecbmsg = " (ecb ";
6078 #endif /* __APPLE__ */
6079 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6080 uintptr_t val = (uintptr_t)ecb;
6081 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6082
6083 if (dtrace_destructive_disallow)
6084 return;
6085
6086 /*
6087 * It's impossible to be taking action on the NULL probe.
6088 */
6089 ASSERT(probe != NULL);
6090
6091 /*
6092 * This is a poor man's (destitute man's?) sprintf(): we want to
6093 * print the provider name, module name, function name and name of
6094 * the probe, along with the hex address of the ECB with the breakpoint
6095 * action -- all of which we must place in the character buffer by
6096 * hand.
6097 */
6098 while (*msg != '\0')
6099 c[i++] = *msg++;
6100
6101 for (str = prov->dtpv_name; *str != '\0'; str++)
6102 c[i++] = *str;
6103 c[i++] = ':';
6104
6105 for (str = probe->dtpr_mod; *str != '\0'; str++)
6106 c[i++] = *str;
6107 c[i++] = ':';
6108
6109 for (str = probe->dtpr_func; *str != '\0'; str++)
6110 c[i++] = *str;
6111 c[i++] = ':';
6112
6113 for (str = probe->dtpr_name; *str != '\0'; str++)
6114 c[i++] = *str;
6115
6116 while (*ecbmsg != '\0')
6117 c[i++] = *ecbmsg++;
6118
6119 while (shift >= 0) {
6120 mask = (uintptr_t)0xf << shift;
6121
6122 if (val >= ((uintptr_t)1 << shift))
6123 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6124 shift -= 4;
6125 }
6126
6127 c[i++] = ')';
6128 c[i] = '\0';
6129
6130 debug_enter(c);
6131 }
6132
6133 static void
6134 dtrace_action_panic(dtrace_ecb_t *ecb)
6135 {
6136 dtrace_probe_t *probe = ecb->dte_probe;
6137
6138 /*
6139 * It's impossible to be taking action on the NULL probe.
6140 */
6141 ASSERT(probe != NULL);
6142
6143 if (dtrace_destructive_disallow)
6144 return;
6145
6146 if (dtrace_panicked != NULL)
6147 return;
6148
6149 #if !defined(__APPLE__)
6150 if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6151 return;
6152 #else
6153 if (dtrace_casptr(&dtrace_panicked, NULL, current_thread()) != NULL)
6154 return;
6155 #endif /* __APPLE__ */
6156
6157 /*
6158 * We won the right to panic. (We want to be sure that only one
6159 * thread calls panic() from dtrace_probe(), and that panic() is
6160 * called exactly once.)
6161 */
6162 panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6163 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6164 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6165
6166 #if defined(__APPLE__)
6167 /* Mac OS X debug feature -- can return from panic() */
6168 dtrace_panicked = NULL;
6169 #endif /* __APPLE__ */
6170 }
6171
6172 static void
6173 dtrace_action_raise(uint64_t sig)
6174 {
6175 if (dtrace_destructive_disallow)
6176 return;
6177
6178 if (sig >= NSIG) {
6179 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6180 return;
6181 }
6182
6183 #if !defined(__APPLE__)
6184 /*
6185 * raise() has a queue depth of 1 -- we ignore all subsequent
6186 * invocations of the raise() action.
6187 */
6188 if (curthread->t_dtrace_sig == 0)
6189 curthread->t_dtrace_sig = (uint8_t)sig;
6190
6191 curthread->t_sig_check = 1;
6192 aston(curthread);
6193 #else
6194 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
6195
6196 if (uthread && uthread->t_dtrace_sig == 0) {
6197 uthread->t_dtrace_sig = sig;
6198 act_set_astbsd(current_thread());
6199 }
6200 #endif /* __APPLE__ */
6201 }
6202
6203 static void
6204 dtrace_action_stop(void)
6205 {
6206 if (dtrace_destructive_disallow)
6207 return;
6208
6209 #if !defined(__APPLE__)
6210 if (!curthread->t_dtrace_stop) {
6211 curthread->t_dtrace_stop = 1;
6212 curthread->t_sig_check = 1;
6213 aston(curthread);
6214 }
6215 #else
6216 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
6217 if (uthread) {
6218 /*
6219 * The currently running process will be set to task_suspend
6220 * when it next leaves the kernel.
6221 */
6222 uthread->t_dtrace_stop = 1;
6223 act_set_astbsd(current_thread());
6224 }
6225 #endif /* __APPLE__ */
6226 }
6227
6228 #if defined(__APPLE__)
6229 static void
6230 dtrace_action_pidresume(uint64_t pid)
6231 {
6232 if (dtrace_destructive_disallow)
6233 return;
6234
6235 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
6236 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6237 return;
6238 }
6239 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
6240
6241 /*
6242 * When the currently running process leaves the kernel, it attempts to
6243 * task_resume the process (denoted by pid), if that pid appears to have
6244 * been stopped by dtrace_action_stop().
6245 * The currently running process has a pidresume() queue depth of 1 --
6246 * subsequent invocations of the pidresume() action are ignored.
6247 */
6248
6249 if (pid != 0 && uthread && uthread->t_dtrace_resumepid == 0) {
6250 uthread->t_dtrace_resumepid = pid;
6251 act_set_astbsd(current_thread());
6252 }
6253 }
6254 #endif /* __APPLE__ */
6255
6256
6257 static void
6258 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6259 {
6260 hrtime_t now;
6261 volatile uint16_t *flags;
6262 dtrace_cpu_t *cpu = CPU;
6263
6264 if (dtrace_destructive_disallow)
6265 return;
6266
6267 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6268
6269 now = dtrace_gethrtime();
6270
6271 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6272 /*
6273 * We need to advance the mark to the current time.
6274 */
6275 cpu->cpu_dtrace_chillmark = now;
6276 cpu->cpu_dtrace_chilled = 0;
6277 }
6278
6279 /*
6280 * Now check to see if the requested chill time would take us over
6281 * the maximum amount of time allowed in the chill interval. (Or
6282 * worse, if the calculation itself induces overflow.)
6283 */
6284 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6285 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6286 *flags |= CPU_DTRACE_ILLOP;
6287 return;
6288 }
6289
6290 while (dtrace_gethrtime() - now < val)
6291 continue;
6292
6293 /*
6294 * Normally, we assure that the value of the variable "timestamp" does
6295 * not change within an ECB. The presence of chill() represents an
6296 * exception to this rule, however.
6297 */
6298 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6299 cpu->cpu_dtrace_chilled += val;
6300 }
6301
6302 static void
6303 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6304 uint64_t *buf, uint64_t arg)
6305 {
6306 int nframes = DTRACE_USTACK_NFRAMES(arg);
6307 int strsize = DTRACE_USTACK_STRSIZE(arg);
6308 uint64_t *pcs = &buf[1], *fps;
6309 char *str = (char *)&pcs[nframes];
6310 int size, offs = 0, i, j;
6311 uintptr_t old = mstate->dtms_scratch_ptr, saved;
6312 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6313 char *sym;
6314
6315 /*
6316 * Should be taking a faster path if string space has not been
6317 * allocated.
6318 */
6319 ASSERT(strsize != 0);
6320
6321 /*
6322 * We will first allocate some temporary space for the frame pointers.
6323 */
6324 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6325 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6326 (nframes * sizeof (uint64_t));
6327
6328 #if !defined(__APPLE__) /* Quiet compiler warnings */
6329 if (!DTRACE_INSCRATCH(mstate, size)) {
6330 #else
6331 if (!DTRACE_INSCRATCH(mstate, (uintptr_t)size)) {
6332 #endif /* __APPLE__ */
6333 /*
6334 * Not enough room for our frame pointers -- need to indicate
6335 * that we ran out of scratch space.
6336 */
6337 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6338 return;
6339 }
6340
6341 mstate->dtms_scratch_ptr += size;
6342 saved = mstate->dtms_scratch_ptr;
6343
6344 /*
6345 * Now get a stack with both program counters and frame pointers.
6346 */
6347 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6348 dtrace_getufpstack(buf, fps, nframes + 1);
6349 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6350
6351 /*
6352 * If that faulted, we're cooked.
6353 */
6354 if (*flags & CPU_DTRACE_FAULT)
6355 goto out;
6356
6357 /*
6358 * Now we want to walk up the stack, calling the USTACK helper. For
6359 * each iteration, we restore the scratch pointer.
6360 */
6361 for (i = 0; i < nframes; i++) {
6362 mstate->dtms_scratch_ptr = saved;
6363
6364 if (offs >= strsize)
6365 break;
6366
6367 sym = (char *)(uintptr_t)dtrace_helper(
6368 DTRACE_HELPER_ACTION_USTACK,
6369 mstate, state, pcs[i], fps[i]);
6370
6371 /*
6372 * If we faulted while running the helper, we're going to
6373 * clear the fault and null out the corresponding string.
6374 */
6375 if (*flags & CPU_DTRACE_FAULT) {
6376 *flags &= ~CPU_DTRACE_FAULT;
6377 str[offs++] = '\0';
6378 continue;
6379 }
6380
6381 if (sym == NULL) {
6382 str[offs++] = '\0';
6383 continue;
6384 }
6385
6386 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6387
6388 /*
6389 * Now copy in the string that the helper returned to us.
6390 */
6391 for (j = 0; offs + j < strsize; j++) {
6392 if ((str[offs + j] = sym[j]) == '\0')
6393 break;
6394 }
6395
6396 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6397
6398 offs += j + 1;
6399 }
6400
6401 if (offs >= strsize) {
6402 /*
6403 * If we didn't have room for all of the strings, we don't
6404 * abort processing -- this needn't be a fatal error -- but we
6405 * still want to increment a counter (dts_stkstroverflows) to
6406 * allow this condition to be warned about. (If this is from
6407 * a jstack() action, it is easily tuned via jstackstrsize.)
6408 */
6409 dtrace_error(&state->dts_stkstroverflows);
6410 }
6411
6412 while (offs < strsize)
6413 str[offs++] = '\0';
6414
6415 out:
6416 mstate->dtms_scratch_ptr = old;
6417 }
6418
6419 /*
6420 * If you're looking for the epicenter of DTrace, you just found it. This
6421 * is the function called by the provider to fire a probe -- from which all
6422 * subsequent probe-context DTrace activity emanates.
6423 */
6424 #if !defined(__APPLE__)
6425 void
6426 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6427 uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6428 #else
6429 static void
6430 __dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
6431 uint64_t arg2, uint64_t arg3, uint64_t arg4)
6432 #endif /* __APPLE__ */
6433 {
6434 processorid_t cpuid;
6435 dtrace_icookie_t cookie;
6436 dtrace_probe_t *probe;
6437 dtrace_mstate_t mstate;
6438 dtrace_ecb_t *ecb;
6439 dtrace_action_t *act;
6440 intptr_t offs;
6441 size_t size;
6442 int vtime, onintr;
6443 volatile uint16_t *flags;
6444 hrtime_t now;
6445
6446 #if !defined(__APPLE__)
6447 /*
6448 * Kick out immediately if this CPU is still being born (in which case
6449 * curthread will be set to -1) or the current thread can't allow
6450 * probes in its current context.
6451 */
6452 if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6453 return;
6454 #else
6455 /* Not a concern for Darwin */
6456 #endif /* __APPLE__ */
6457
6458 cookie = dtrace_interrupt_disable();
6459 probe = dtrace_probes[id - 1];
6460 cpuid = CPU->cpu_id;
6461 onintr = CPU_ON_INTR(CPU);
6462
6463 #if !defined(__APPLE__)
6464 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6465 probe->dtpr_predcache == curthread->t_predcache) {
6466 #else
6467 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6468 probe->dtpr_predcache == dtrace_get_thread_predcache(current_thread())) {
6469 #endif /* __APPLE__ */
6470 /*
6471 * We have hit in the predicate cache; we know that
6472 * this predicate would evaluate to be false.
6473 */
6474 dtrace_interrupt_enable(cookie);
6475 return;
6476 }
6477
6478 if (panic_quiesce) {
6479 /*
6480 * We don't trace anything if we're panicking.
6481 */
6482 dtrace_interrupt_enable(cookie);
6483 return;
6484 }
6485
6486 #if !defined(__APPLE__)
6487 now = dtrace_gethrtime();
6488 vtime = dtrace_vtime_references != 0;
6489
6490 if (vtime && curthread->t_dtrace_start)
6491 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6492 #else
6493 /* FIXME: the time spent entering DTrace and arriving to this point is attributed
6494 to the current thread. Instead it should accrue to DTrace. */
6495 vtime = dtrace_vtime_references != 0;
6496
6497 if (vtime)
6498 {
6499 int64_t dtrace_accum_time, recent_vtime;
6500 thread_t thread = current_thread();
6501
6502 dtrace_accum_time = dtrace_get_thread_tracing(thread); /* Time spent inside DTrace so far (nanoseconds) */
6503
6504 if (dtrace_accum_time >= 0) {
6505 recent_vtime = dtrace_abs_to_nano(dtrace_calc_thread_recent_vtime(thread)); /* up to the moment thread vtime */
6506
6507 recent_vtime = recent_vtime - dtrace_accum_time; /* Time without DTrace contribution */
6508
6509 dtrace_set_thread_vtime(thread, recent_vtime);
6510 }
6511 }
6512
6513 now = dtrace_gethrtime(); /* must not precede dtrace_calc_thread_recent_vtime() call! */
6514 #endif /* __APPLE__ */
6515
6516 #if defined(__APPLE__)
6517 /*
6518 * A provider may call dtrace_probe_error() in lieu of dtrace_probe() in some circumstances.
6519 * See, e.g. fasttrap_isa.c. However the provider has no access to ECB context, so passes
6520 * 0 through "arg0" and the probe_id of the overridden probe as arg1. Detect that here
6521 * and cons up a viable state (from the probe_id).
6522 */
6523 if (dtrace_probeid_error == id && 0 == arg0) {
6524 dtrace_id_t ftp_id = (dtrace_id_t)arg1;
6525 dtrace_probe_t *ftp_probe = dtrace_probes[ftp_id - 1];
6526 dtrace_ecb_t *ftp_ecb = ftp_probe->dtpr_ecb;
6527
6528 if (NULL != ftp_ecb) {
6529 dtrace_state_t *ftp_state = ftp_ecb->dte_state;
6530
6531 arg0 = (uint64_t)(uintptr_t)ftp_state;
6532 arg1 = ftp_ecb->dte_epid;
6533 /*
6534 * args[2-4] established by caller.
6535 */
6536 ftp_state->dts_arg_error_illval = -1; /* arg5 */
6537 }
6538 }
6539 #endif /* __APPLE__ */
6540
6541 mstate.dtms_difo = NULL;
6542 mstate.dtms_probe = probe;
6543 mstate.dtms_strtok = NULL;
6544 mstate.dtms_arg[0] = arg0;
6545 mstate.dtms_arg[1] = arg1;
6546 mstate.dtms_arg[2] = arg2;
6547 mstate.dtms_arg[3] = arg3;
6548 mstate.dtms_arg[4] = arg4;
6549
6550 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6551
6552 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6553 dtrace_predicate_t *pred = ecb->dte_predicate;
6554 dtrace_state_t *state = ecb->dte_state;
6555 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6556 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6557 dtrace_vstate_t *vstate = &state->dts_vstate;
6558 dtrace_provider_t *prov = probe->dtpr_provider;
6559 int committed = 0;
6560 caddr_t tomax;
6561
6562 /*
6563 * A little subtlety with the following (seemingly innocuous)
6564 * declaration of the automatic 'val': by looking at the
6565 * code, you might think that it could be declared in the
6566 * action processing loop, below. (That is, it's only used in
6567 * the action processing loop.) However, it must be declared
6568 * out of that scope because in the case of DIF expression
6569 * arguments to aggregating actions, one iteration of the
6570 * action loop will use the last iteration's value.
6571 */
6572 #ifdef lint
6573 uint64_t val = 0;
6574 #else
6575 uint64_t val = 0;
6576 #endif
6577
6578 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6579 *flags &= ~CPU_DTRACE_ERROR;
6580
6581 if (prov == dtrace_provider) {
6582 /*
6583 * If dtrace itself is the provider of this probe,
6584 * we're only going to continue processing the ECB if
6585 * arg0 (the dtrace_state_t) is equal to the ECB's
6586 * creating state. (This prevents disjoint consumers
6587 * from seeing one another's metaprobes.)
6588 */
6589 if (arg0 != (uint64_t)(uintptr_t)state)
6590 continue;
6591 }
6592
6593 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6594 /*
6595 * We're not currently active. If our provider isn't
6596 * the dtrace pseudo provider, we're not interested.
6597 */
6598 if (prov != dtrace_provider)
6599 continue;
6600
6601 /*
6602 * Now we must further check if we are in the BEGIN
6603 * probe. If we are, we will only continue processing
6604 * if we're still in WARMUP -- if one BEGIN enabling
6605 * has invoked the exit() action, we don't want to
6606 * evaluate subsequent BEGIN enablings.
6607 */
6608 if (probe->dtpr_id == dtrace_probeid_begin &&
6609 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6610 ASSERT(state->dts_activity ==
6611 DTRACE_ACTIVITY_DRAINING);
6612 continue;
6613 }
6614 }
6615
6616 if (ecb->dte_cond) {
6617 /*
6618 * If the dte_cond bits indicate that this
6619 * consumer is only allowed to see user-mode firings
6620 * of this probe, call the provider's dtps_usermode()
6621 * entry point to check that the probe was fired
6622 * while in a user context. Skip this ECB if that's
6623 * not the case.
6624 */
6625 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6626 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6627 probe->dtpr_id, probe->dtpr_arg) == 0)
6628 continue;
6629
6630 /*
6631 * This is more subtle than it looks. We have to be
6632 * absolutely certain that CRED() isn't going to
6633 * change out from under us so it's only legit to
6634 * examine that structure if we're in constrained
6635 * situations. Currently, the only times we'll this
6636 * check is if a non-super-user has enabled the
6637 * profile or syscall providers -- providers that
6638 * allow visibility of all processes. For the
6639 * profile case, the check above will ensure that
6640 * we're examining a user context.
6641 */
6642 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6643 cred_t *cr;
6644 cred_t *s_cr =
6645 ecb->dte_state->dts_cred.dcr_cred;
6646 proc_t *proc;
6647 #pragma unused(proc) /* __APPLE__ */
6648
6649 ASSERT(s_cr != NULL);
6650
6651 /*
6652 * XXX this is hackish, but so is setting a variable
6653 * XXX in a McCarthy OR...
6654 */
6655 #if !defined(__APPLE__)
6656 if ((cr = CRED()) == NULL ||
6657 #else
6658 if ((cr = dtrace_CRED()) == NULL ||
6659 #endif /* __APPLE__ */
6660 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_uid ||
6661 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_ruid ||
6662 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_suid ||
6663 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_gid ||
6664 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_rgid ||
6665 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_sgid ||
6666 #if !defined(__APPLE__)
6667 (proc = ttoproc(curthread)) == NULL ||
6668 (proc->p_flag & SNOCD))
6669 #else
6670 1) /* Darwin omits "No Core Dump" flag. */
6671 #endif /* __APPLE__ */
6672 continue;
6673 }
6674
6675 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6676 cred_t *cr;
6677 cred_t *s_cr =
6678 ecb->dte_state->dts_cred.dcr_cred;
6679 #pragma unused(cr, s_cr) /* __APPLE__ */
6680
6681 ASSERT(s_cr != NULL);
6682
6683 #if !defined(__APPLE__)
6684 if ((cr = CRED()) == NULL ||
6685 s_cr->cr_zone->zone_id !=
6686 cr->cr_zone->zone_id)
6687 continue;
6688 #else
6689 /* Darwin doesn't do zones. */
6690 #endif /* __APPLE__ */
6691 }
6692 }
6693
6694 if (now - state->dts_alive > dtrace_deadman_timeout) {
6695 /*
6696 * We seem to be dead. Unless we (a) have kernel
6697 * destructive permissions (b) have expicitly enabled
6698 * destructive actions and (c) destructive actions have
6699 * not been disabled, we're going to transition into
6700 * the KILLED state, from which no further processing
6701 * on this state will be performed.
6702 */
6703 if (!dtrace_priv_kernel_destructive(state) ||
6704 !state->dts_cred.dcr_destructive ||
6705 dtrace_destructive_disallow) {
6706 void *activity = &state->dts_activity;
6707 dtrace_activity_t current;
6708
6709 do {
6710 current = state->dts_activity;
6711 } while (dtrace_cas32(activity, current,
6712 DTRACE_ACTIVITY_KILLED) != current);
6713
6714 continue;
6715 }
6716 }
6717
6718 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6719 ecb->dte_alignment, state, &mstate)) < 0)
6720 continue;
6721
6722 tomax = buf->dtb_tomax;
6723 ASSERT(tomax != NULL);
6724
6725 if (ecb->dte_size != 0)
6726 DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
6727
6728 mstate.dtms_epid = ecb->dte_epid;
6729 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6730
6731 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6732 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6733 else
6734 mstate.dtms_access = 0;
6735
6736 if (pred != NULL) {
6737 dtrace_difo_t *dp = pred->dtp_difo;
6738 int rval;
6739
6740 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6741
6742 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6743 dtrace_cacheid_t cid = probe->dtpr_predcache;
6744
6745 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6746 /*
6747 * Update the predicate cache...
6748 */
6749 ASSERT(cid == pred->dtp_cacheid);
6750 #if !defined(__APPLE__)
6751 curthread->t_predcache = cid;
6752 #else
6753 dtrace_set_thread_predcache(current_thread(), cid);
6754 #endif /* __APPLE__ */
6755 }
6756
6757 continue;
6758 }
6759 }
6760
6761 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6762 act != NULL; act = act->dta_next) {
6763 size_t valoffs;
6764 dtrace_difo_t *dp;
6765 dtrace_recdesc_t *rec = &act->dta_rec;
6766
6767 size = rec->dtrd_size;
6768 valoffs = offs + rec->dtrd_offset;
6769
6770 if (DTRACEACT_ISAGG(act->dta_kind)) {
6771 uint64_t v = 0xbad;
6772 dtrace_aggregation_t *agg;
6773
6774 agg = (dtrace_aggregation_t *)act;
6775
6776 if ((dp = act->dta_difo) != NULL)
6777 v = dtrace_dif_emulate(dp,
6778 &mstate, vstate, state);
6779
6780 if (*flags & CPU_DTRACE_ERROR)
6781 continue;
6782
6783 /*
6784 * Note that we always pass the expression
6785 * value from the previous iteration of the
6786 * action loop. This value will only be used
6787 * if there is an expression argument to the
6788 * aggregating action, denoted by the
6789 * dtag_hasarg field.
6790 */
6791 dtrace_aggregate(agg, buf,
6792 offs, aggbuf, v, val);
6793 continue;
6794 }
6795
6796 switch (act->dta_kind) {
6797 case DTRACEACT_STOP:
6798 if (dtrace_priv_proc_destructive(state))
6799 dtrace_action_stop();
6800 continue;
6801
6802 case DTRACEACT_BREAKPOINT:
6803 if (dtrace_priv_kernel_destructive(state))
6804 dtrace_action_breakpoint(ecb);
6805 continue;
6806
6807 case DTRACEACT_PANIC:
6808 if (dtrace_priv_kernel_destructive(state))
6809 dtrace_action_panic(ecb);
6810 continue;
6811
6812 case DTRACEACT_STACK:
6813 if (!dtrace_priv_kernel(state))
6814 continue;
6815
6816 #if !defined(__APPLE__) /* Quiet compiler warnings */
6817 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6818 size / sizeof (pc_t), probe->dtpr_aframes,
6819 DTRACE_ANCHORED(probe) ? NULL :
6820 (uint32_t *)arg0);
6821 #else
6822 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6823 size / sizeof (pc_t), probe->dtpr_aframes,
6824 DTRACE_ANCHORED(probe) ? NULL :
6825 (uint32_t *)(uintptr_t)arg0);
6826 #endif /* __APPLE__ */
6827
6828 continue;
6829
6830 case DTRACEACT_JSTACK:
6831 case DTRACEACT_USTACK:
6832 if (!dtrace_priv_proc(state))
6833 continue;
6834
6835 /*
6836 * See comment in DIF_VAR_PID.
6837 */
6838 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6839 CPU_ON_INTR(CPU)) {
6840 int depth = DTRACE_USTACK_NFRAMES(
6841 rec->dtrd_arg) + 1;
6842
6843 dtrace_bzero((void *)(tomax + valoffs),
6844 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6845 + depth * sizeof (uint64_t));
6846
6847 continue;
6848 }
6849
6850 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6851 curproc->p_dtrace_helpers != NULL) {
6852 /*
6853 * This is the slow path -- we have
6854 * allocated string space, and we're
6855 * getting the stack of a process that
6856 * has helpers. Call into a separate
6857 * routine to perform this processing.
6858 */
6859 dtrace_action_ustack(&mstate, state,
6860 (uint64_t *)(tomax + valoffs),
6861 rec->dtrd_arg);
6862 continue;
6863 }
6864
6865 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6866 dtrace_getupcstack((uint64_t *)
6867 (tomax + valoffs),
6868 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6869 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6870 continue;
6871
6872 default:
6873 break;
6874 }
6875
6876 dp = act->dta_difo;
6877 ASSERT(dp != NULL);
6878
6879 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6880
6881 if (*flags & CPU_DTRACE_ERROR)
6882 continue;
6883
6884 switch (act->dta_kind) {
6885 case DTRACEACT_SPECULATE:
6886 ASSERT(buf == &state->dts_buffer[cpuid]);
6887 buf = dtrace_speculation_buffer(state,
6888 cpuid, val);
6889
6890 if (buf == NULL) {
6891 *flags |= CPU_DTRACE_DROP;
6892 continue;
6893 }
6894
6895 offs = dtrace_buffer_reserve(buf,
6896 ecb->dte_needed, ecb->dte_alignment,
6897 state, NULL);
6898
6899 if (offs < 0) {
6900 *flags |= CPU_DTRACE_DROP;
6901 continue;
6902 }
6903
6904 tomax = buf->dtb_tomax;
6905 ASSERT(tomax != NULL);
6906
6907 if (ecb->dte_size != 0)
6908 DTRACE_STORE(uint32_t, tomax, offs,
6909 ecb->dte_epid);
6910 continue;
6911
6912 case DTRACEACT_CHILL:
6913 if (dtrace_priv_kernel_destructive(state))
6914 dtrace_action_chill(&mstate, val);
6915 continue;
6916
6917 case DTRACEACT_RAISE:
6918 if (dtrace_priv_proc_destructive(state))
6919 dtrace_action_raise(val);
6920 continue;
6921
6922 #if defined(__APPLE__)
6923 case DTRACEACT_PIDRESUME:
6924 if (dtrace_priv_proc_destructive(state))
6925 dtrace_action_pidresume(val);
6926 continue;
6927 #endif /* __APPLE__ */
6928
6929 case DTRACEACT_COMMIT:
6930 ASSERT(!committed);
6931
6932 /*
6933 * We need to commit our buffer state.
6934 */
6935 if (ecb->dte_size)
6936 buf->dtb_offset = offs + ecb->dte_size;
6937 buf = &state->dts_buffer[cpuid];
6938 dtrace_speculation_commit(state, cpuid, val);
6939 committed = 1;
6940 continue;
6941
6942 case DTRACEACT_DISCARD:
6943 dtrace_speculation_discard(state, cpuid, val);
6944 continue;
6945
6946 case DTRACEACT_DIFEXPR:
6947 case DTRACEACT_LIBACT:
6948 case DTRACEACT_PRINTF:
6949 case DTRACEACT_PRINTA:
6950 case DTRACEACT_SYSTEM:
6951 case DTRACEACT_FREOPEN:
6952 #if defined(__APPLE__)
6953 case DTRACEACT_APPLEBINARY:
6954 #endif /* __APPLE__ */
6955 break;
6956
6957 case DTRACEACT_SYM:
6958 case DTRACEACT_MOD:
6959 if (!dtrace_priv_kernel(state))
6960 continue;
6961 break;
6962
6963 #if !defined(__APPLE__)
6964 case DTRACEACT_USYM:
6965 case DTRACEACT_UMOD:
6966 case DTRACEACT_UADDR: {
6967 struct pid *pid = curthread->t_procp->p_pidp;
6968
6969 if (!dtrace_priv_proc(state))
6970 continue;
6971
6972 DTRACE_STORE(uint64_t, tomax,
6973 valoffs, (uint64_t)pid->pid_id);
6974 DTRACE_STORE(uint64_t, tomax,
6975 valoffs + sizeof (uint64_t), val);
6976
6977 continue;
6978 }
6979 #else
6980 case DTRACEACT_USYM:
6981 case DTRACEACT_UMOD:
6982 case DTRACEACT_UADDR: {
6983 if (!dtrace_priv_proc(state))
6984 continue;
6985
6986 DTRACE_STORE(uint64_t, tomax,
6987 valoffs, (uint64_t)proc_selfpid());
6988 DTRACE_STORE(uint64_t, tomax,
6989 valoffs + sizeof (uint64_t), val);
6990
6991 continue;
6992 }
6993 #endif /* __APPLE__ */
6994
6995 case DTRACEACT_EXIT: {
6996 /*
6997 * For the exit action, we are going to attempt
6998 * to atomically set our activity to be
6999 * draining. If this fails (either because
7000 * another CPU has beat us to the exit action,
7001 * or because our current activity is something
7002 * other than ACTIVE or WARMUP), we will
7003 * continue. This assures that the exit action
7004 * can be successfully recorded at most once
7005 * when we're in the ACTIVE state. If we're
7006 * encountering the exit() action while in
7007 * COOLDOWN, however, we want to honor the new
7008 * status code. (We know that we're the only
7009 * thread in COOLDOWN, so there is no race.)
7010 */
7011 void *activity = &state->dts_activity;
7012 dtrace_activity_t current = state->dts_activity;
7013
7014 if (current == DTRACE_ACTIVITY_COOLDOWN)
7015 break;
7016
7017 if (current != DTRACE_ACTIVITY_WARMUP)
7018 current = DTRACE_ACTIVITY_ACTIVE;
7019
7020 if (dtrace_cas32(activity, current,
7021 DTRACE_ACTIVITY_DRAINING) != current) {
7022 *flags |= CPU_DTRACE_DROP;
7023 continue;
7024 }
7025
7026 break;
7027 }
7028
7029 default:
7030 ASSERT(0);
7031 }
7032
7033 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
7034 uintptr_t end = valoffs + size;
7035
7036 if (!dtrace_vcanload((void *)(uintptr_t)val,
7037 &dp->dtdo_rtype, &mstate, vstate))
7038 continue;
7039
7040 /*
7041 * If this is a string, we're going to only
7042 * load until we find the zero byte -- after
7043 * which we'll store zero bytes.
7044 */
7045 if (dp->dtdo_rtype.dtdt_kind ==
7046 DIF_TYPE_STRING) {
7047 char c = '\0' + 1;
7048 int intuple = act->dta_intuple;
7049 size_t s;
7050
7051 for (s = 0; s < size; s++) {
7052 if (c != '\0')
7053 c = dtrace_load8(val++);
7054
7055 DTRACE_STORE(uint8_t, tomax,
7056 valoffs++, c);
7057
7058 if (c == '\0' && intuple)
7059 break;
7060 }
7061
7062 continue;
7063 }
7064
7065 while (valoffs < end) {
7066 DTRACE_STORE(uint8_t, tomax, valoffs++,
7067 dtrace_load8(val++));
7068 }
7069
7070 continue;
7071 }
7072
7073 switch (size) {
7074 case 0:
7075 break;
7076
7077 case sizeof (uint8_t):
7078 DTRACE_STORE(uint8_t, tomax, valoffs, val);
7079 break;
7080 case sizeof (uint16_t):
7081 DTRACE_STORE(uint16_t, tomax, valoffs, val);
7082 break;
7083 case sizeof (uint32_t):
7084 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7085 break;
7086 case sizeof (uint64_t):
7087 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7088 break;
7089 default:
7090 /*
7091 * Any other size should have been returned by
7092 * reference, not by value.
7093 */
7094 ASSERT(0);
7095 break;
7096 }
7097 }
7098
7099 if (*flags & CPU_DTRACE_DROP)
7100 continue;
7101
7102 if (*flags & CPU_DTRACE_FAULT) {
7103 int ndx;
7104 dtrace_action_t *err;
7105
7106 buf->dtb_errors++;
7107
7108 if (probe->dtpr_id == dtrace_probeid_error) {
7109 /*
7110 * There's nothing we can do -- we had an
7111 * error on the error probe. We bump an
7112 * error counter to at least indicate that
7113 * this condition happened.
7114 */
7115 dtrace_error(&state->dts_dblerrors);
7116 continue;
7117 }
7118
7119 if (vtime) {
7120 /*
7121 * Before recursing on dtrace_probe(), we
7122 * need to explicitly clear out our start
7123 * time to prevent it from being accumulated
7124 * into t_dtrace_vtime.
7125 */
7126 #if !defined(__APPLE__)
7127 curthread->t_dtrace_start = 0;
7128 #else
7129 /* Set the sign bit on t_dtrace_tracing to suspend accumulation to it. */
7130 dtrace_set_thread_tracing(current_thread(),
7131 (1ULL<<63) | dtrace_get_thread_tracing(current_thread()));
7132 #endif /* __APPLE__ */
7133 }
7134
7135 /*
7136 * Iterate over the actions to figure out which action
7137 * we were processing when we experienced the error.
7138 * Note that act points _past_ the faulting action; if
7139 * act is ecb->dte_action, the fault was in the
7140 * predicate, if it's ecb->dte_action->dta_next it's
7141 * in action #1, and so on.
7142 */
7143 for (err = ecb->dte_action, ndx = 0;
7144 err != act; err = err->dta_next, ndx++)
7145 continue;
7146
7147 dtrace_probe_error(state, ecb->dte_epid, ndx,
7148 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7149 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7150 cpu_core[cpuid].cpuc_dtrace_illval);
7151
7152 continue;
7153 }
7154
7155 if (!committed)
7156 buf->dtb_offset = offs + ecb->dte_size;
7157 }
7158
7159 #if !defined(__APPLE__)
7160 if (vtime)
7161 curthread->t_dtrace_start = dtrace_gethrtime();
7162 #else
7163 /* FIXME: the time spent leaving DTrace from this point to the rti is attributed
7164 to the current thread. Instead it should accrue to DTrace. */
7165 if (vtime) {
7166 thread_t thread = current_thread();
7167 int64_t t = dtrace_get_thread_tracing(thread);
7168
7169 if (t >= 0) {
7170 /* Usual case, accumulate time spent here into t_dtrace_tracing */
7171 dtrace_set_thread_tracing(thread, t + (dtrace_gethrtime() - now));
7172 } else {
7173 /* Return from error recursion. No accumulation, just clear the sign bit on t_dtrace_tracing. */
7174 dtrace_set_thread_tracing(thread, (~(1ULL<<63)) & t);
7175 }
7176 }
7177 #endif /* __APPLE__ */
7178
7179 dtrace_interrupt_enable(cookie);
7180 }
7181
7182 #if defined(__APPLE__)
7183 /* Don't allow a thread to re-enter dtrace_probe(). This could occur if a probe is encountered
7184 on some function in the transitive closure of the call to dtrace_probe(). Solaris has some
7185 strong guarantees that this won't happen, the Darwin implementation is not so mature as to
7186 make those guarantees. */
7187
7188 void
7189 dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
7190 uint64_t arg2, uint64_t arg3, uint64_t arg4)
7191 {
7192 thread_t thread = current_thread();
7193 disable_preemption();
7194 if (id == dtrace_probeid_error) {
7195 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
7196 dtrace_getipl(); /* Defeat tail-call optimization of __dtrace_probe() */
7197 } else if (!dtrace_get_thread_reentering(thread)) {
7198 dtrace_set_thread_reentering(thread, TRUE);
7199 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
7200 dtrace_set_thread_reentering(thread, FALSE);
7201 }
7202 #if DEBUG
7203 else __dtrace_probe(dtrace_probeid_error, 0, id, 1, -1, DTRACEFLT_UNKNOWN);
7204 #endif
7205 enable_preemption();
7206 }
7207 #endif /* __APPLE__ */
7208
7209 /*
7210 * DTrace Probe Hashing Functions
7211 *
7212 * The functions in this section (and indeed, the functions in remaining
7213 * sections) are not _called_ from probe context. (Any exceptions to this are
7214 * marked with a "Note:".) Rather, they are called from elsewhere in the
7215 * DTrace framework to look-up probes in, add probes to and remove probes from
7216 * the DTrace probe hashes. (Each probe is hashed by each element of the
7217 * probe tuple -- allowing for fast lookups, regardless of what was
7218 * specified.)
7219 */
7220 static uint_t
7221 #if !defined(__APPLE__) /* Quiet compiler warnings */
7222 dtrace_hash_str(char *p)
7223 #else
7224 dtrace_hash_str(const char *p)
7225 #endif /* __APPLE__ */
7226 {
7227 unsigned int g;
7228 uint_t hval = 0;
7229
7230 while (*p) {
7231 hval = (hval << 4) + *p++;
7232 if ((g = (hval & 0xf0000000)) != 0)
7233 hval ^= g >> 24;
7234 hval &= ~g;
7235 }
7236 return (hval);
7237 }
7238
7239 static dtrace_hash_t *
7240 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7241 {
7242 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7243
7244 hash->dth_stroffs = stroffs;
7245 hash->dth_nextoffs = nextoffs;
7246 hash->dth_prevoffs = prevoffs;
7247
7248 hash->dth_size = 1;
7249 hash->dth_mask = hash->dth_size - 1;
7250
7251 hash->dth_tab = kmem_zalloc(hash->dth_size *
7252 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7253
7254 return (hash);
7255 }
7256
7257 #if !defined(__APPLE__) /* Unused. Quiet compiler warning. */
7258 static void
7259 dtrace_hash_destroy(dtrace_hash_t *hash)
7260 {
7261 #if DEBUG
7262 int i;
7263
7264 for (i = 0; i < hash->dth_size; i++)
7265 ASSERT(hash->dth_tab[i] == NULL);
7266 #endif
7267
7268 kmem_free(hash->dth_tab,
7269 hash->dth_size * sizeof (dtrace_hashbucket_t *));
7270 kmem_free(hash, sizeof (dtrace_hash_t));
7271 }
7272 #endif /* __APPLE__ */
7273
7274 static void
7275 dtrace_hash_resize(dtrace_hash_t *hash)
7276 {
7277 int size = hash->dth_size, i, ndx;
7278 int new_size = hash->dth_size << 1;
7279 int new_mask = new_size - 1;
7280 dtrace_hashbucket_t **new_tab, *bucket, *next;
7281
7282 ASSERT((new_size & new_mask) == 0);
7283
7284 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7285
7286 for (i = 0; i < size; i++) {
7287 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7288 dtrace_probe_t *probe = bucket->dthb_chain;
7289
7290 ASSERT(probe != NULL);
7291 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7292
7293 next = bucket->dthb_next;
7294 bucket->dthb_next = new_tab[ndx];
7295 new_tab[ndx] = bucket;
7296 }
7297 }
7298
7299 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7300 hash->dth_tab = new_tab;
7301 hash->dth_size = new_size;
7302 hash->dth_mask = new_mask;
7303 }
7304
7305 static void
7306 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7307 {
7308 int hashval = DTRACE_HASHSTR(hash, new);
7309 int ndx = hashval & hash->dth_mask;
7310 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7311 dtrace_probe_t **nextp, **prevp;
7312
7313 for (; bucket != NULL; bucket = bucket->dthb_next) {
7314 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7315 goto add;
7316 }
7317
7318 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7319 dtrace_hash_resize(hash);
7320 dtrace_hash_add(hash, new);
7321 return;
7322 }
7323
7324 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7325 bucket->dthb_next = hash->dth_tab[ndx];
7326 hash->dth_tab[ndx] = bucket;
7327 hash->dth_nbuckets++;
7328
7329 add:
7330 nextp = DTRACE_HASHNEXT(hash, new);
7331 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7332 *nextp = bucket->dthb_chain;
7333
7334 if (bucket->dthb_chain != NULL) {
7335 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7336 ASSERT(*prevp == NULL);
7337 *prevp = new;
7338 }
7339
7340 bucket->dthb_chain = new;
7341 bucket->dthb_len++;
7342 }
7343
7344 static dtrace_probe_t *
7345 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7346 {
7347 int hashval = DTRACE_HASHSTR(hash, template);
7348 int ndx = hashval & hash->dth_mask;
7349 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7350
7351 for (; bucket != NULL; bucket = bucket->dthb_next) {
7352 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7353 return (bucket->dthb_chain);
7354 }
7355
7356 return (NULL);
7357 }
7358
7359 static int
7360 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7361 {
7362 int hashval = DTRACE_HASHSTR(hash, template);
7363 int ndx = hashval & hash->dth_mask;
7364 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7365
7366 for (; bucket != NULL; bucket = bucket->dthb_next) {
7367 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7368 return (bucket->dthb_len);
7369 }
7370
7371 return (NULL);
7372 }
7373
7374 static void
7375 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7376 {
7377 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7378 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7379
7380 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7381 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7382
7383 /*
7384 * Find the bucket that we're removing this probe from.
7385 */
7386 for (; bucket != NULL; bucket = bucket->dthb_next) {
7387 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7388 break;
7389 }
7390
7391 ASSERT(bucket != NULL);
7392
7393 if (*prevp == NULL) {
7394 if (*nextp == NULL) {
7395 /*
7396 * The removed probe was the only probe on this
7397 * bucket; we need to remove the bucket.
7398 */
7399 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7400
7401 ASSERT(bucket->dthb_chain == probe);
7402 ASSERT(b != NULL);
7403
7404 if (b == bucket) {
7405 hash->dth_tab[ndx] = bucket->dthb_next;
7406 } else {
7407 while (b->dthb_next != bucket)
7408 b = b->dthb_next;
7409 b->dthb_next = bucket->dthb_next;
7410 }
7411
7412 ASSERT(hash->dth_nbuckets > 0);
7413 hash->dth_nbuckets--;
7414 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7415 return;
7416 }
7417
7418 bucket->dthb_chain = *nextp;
7419 } else {
7420 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7421 }
7422
7423 if (*nextp != NULL)
7424 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7425 }
7426
7427 /*
7428 * DTrace Utility Functions
7429 *
7430 * These are random utility functions that are _not_ called from probe context.
7431 */
7432 static int
7433 dtrace_badattr(const dtrace_attribute_t *a)
7434 {
7435 return (a->dtat_name > DTRACE_STABILITY_MAX ||
7436 a->dtat_data > DTRACE_STABILITY_MAX ||
7437 a->dtat_class > DTRACE_CLASS_MAX);
7438 }
7439
7440 /*
7441 * Return a duplicate copy of a string. If the specified string is NULL,
7442 * this function returns a zero-length string.
7443 */
7444 #if !defined(__APPLE__)
7445 static char *
7446 dtrace_strdup(const char *str)
7447 {
7448 char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7449
7450 if (str != NULL)
7451 (void) strcpy(new, str);
7452
7453 return (new);
7454 }
7455 #else /* Employ size bounded string operation. */
7456 static char *
7457 dtrace_strdup(const char *str)
7458 {
7459 size_t bufsize = (str != NULL ? strlen(str) : 0) + 1;
7460 char *new = kmem_zalloc(bufsize, KM_SLEEP);
7461
7462 if (str != NULL)
7463 (void) strlcpy(new, str, bufsize);
7464
7465 return (new);
7466 }
7467 #endif /* __APPLE__ */
7468
7469 #define DTRACE_ISALPHA(c) \
7470 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7471
7472 static int
7473 dtrace_badname(const char *s)
7474 {
7475 char c;
7476
7477 if (s == NULL || (c = *s++) == '\0')
7478 return (0);
7479
7480 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7481 return (1);
7482
7483 while ((c = *s++) != '\0') {
7484 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7485 c != '-' && c != '_' && c != '.' && c != '`')
7486 return (1);
7487 }
7488
7489 return (0);
7490 }
7491
7492 static void
7493 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7494 {
7495 uint32_t priv;
7496
7497 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7498 /*
7499 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7500 */
7501 priv = DTRACE_PRIV_ALL;
7502 } else {
7503 *uidp = crgetuid(cr);
7504 *zoneidp = crgetzoneid(cr);
7505
7506 priv = 0;
7507 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7508 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7509 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7510 priv |= DTRACE_PRIV_USER;
7511 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7512 priv |= DTRACE_PRIV_PROC;
7513 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7514 priv |= DTRACE_PRIV_OWNER;
7515 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7516 priv |= DTRACE_PRIV_ZONEOWNER;
7517 }
7518
7519 *privp = priv;
7520 }
7521
7522 #ifdef DTRACE_ERRDEBUG
7523 static void
7524 dtrace_errdebug(const char *str)
7525 {
7526 #if !defined(__APPLE__) /* Quiet compiler warnings */
7527 int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
7528 #else
7529 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7530 #endif /* __APPLE__ */
7531 int occupied = 0;
7532
7533 lck_mtx_lock(&dtrace_errlock);
7534 dtrace_errlast = str;
7535 #if !defined(__APPLE__)
7536 dtrace_errthread = curthread;
7537 #else
7538 dtrace_errthread = (kthread_t *)current_thread();
7539 #endif /* __APPLE__ */
7540
7541 while (occupied++ < DTRACE_ERRHASHSZ) {
7542 if (dtrace_errhash[hval].dter_msg == str) {
7543 dtrace_errhash[hval].dter_count++;
7544 goto out;
7545 }
7546
7547 if (dtrace_errhash[hval].dter_msg != NULL) {
7548 hval = (hval + 1) % DTRACE_ERRHASHSZ;
7549 continue;
7550 }
7551
7552 dtrace_errhash[hval].dter_msg = str;
7553 dtrace_errhash[hval].dter_count = 1;
7554 goto out;
7555 }
7556
7557 panic("dtrace: undersized error hash");
7558 out:
7559 lck_mtx_unlock(&dtrace_errlock);
7560 }
7561 #endif
7562
7563 /*
7564 * DTrace Matching Functions
7565 *
7566 * These functions are used to match groups of probes, given some elements of
7567 * a probe tuple, or some globbed expressions for elements of a probe tuple.
7568 */
7569 static int
7570 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7571 zoneid_t zoneid)
7572 {
7573 if (priv != DTRACE_PRIV_ALL) {
7574 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7575 uint32_t match = priv & ppriv;
7576
7577 /*
7578 * No PRIV_DTRACE_* privileges...
7579 */
7580 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7581 DTRACE_PRIV_KERNEL)) == 0)
7582 return (0);
7583
7584 /*
7585 * No matching bits, but there were bits to match...
7586 */
7587 if (match == 0 && ppriv != 0)
7588 return (0);
7589
7590 /*
7591 * Need to have permissions to the process, but don't...
7592 */
7593 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7594 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7595 return (0);
7596 }
7597
7598 /*
7599 * Need to be in the same zone unless we possess the
7600 * privilege to examine all zones.
7601 */
7602 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7603 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7604 return (0);
7605 }
7606 }
7607
7608 return (1);
7609 }
7610
7611 /*
7612 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7613 * consists of input pattern strings and an ops-vector to evaluate them.
7614 * This function returns >0 for match, 0 for no match, and <0 for error.
7615 */
7616 static int
7617 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7618 uint32_t priv, uid_t uid, zoneid_t zoneid)
7619 {
7620 dtrace_provider_t *pvp = prp->dtpr_provider;
7621 int rv;
7622
7623 if (pvp->dtpv_defunct)
7624 return (0);
7625
7626 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7627 return (rv);
7628
7629 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7630 return (rv);
7631
7632 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7633 return (rv);
7634
7635 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7636 return (rv);
7637
7638 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7639 return (0);
7640
7641 return (rv);
7642 }
7643
7644 /*
7645 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7646 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7647 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7648 * In addition, all of the recursion cases except for '*' matching have been
7649 * unwound. For '*', we still implement recursive evaluation, but a depth
7650 * counter is maintained and matching is aborted if we recurse too deep.
7651 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7652 */
7653 static int
7654 dtrace_match_glob(const char *s, const char *p, int depth)
7655 {
7656 const char *olds;
7657 char s1, c;
7658 int gs;
7659
7660 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7661 return (-1);
7662
7663 if (s == NULL)
7664 s = ""; /* treat NULL as empty string */
7665
7666 top:
7667 olds = s;
7668 s1 = *s++;
7669
7670 if (p == NULL)
7671 return (0);
7672
7673 if ((c = *p++) == '\0')
7674 return (s1 == '\0');
7675
7676 switch (c) {
7677 case '[': {
7678 int ok = 0, notflag = 0;
7679 char lc = '\0';
7680
7681 if (s1 == '\0')
7682 return (0);
7683
7684 if (*p == '!') {
7685 notflag = 1;
7686 p++;
7687 }
7688
7689 if ((c = *p++) == '\0')
7690 return (0);
7691
7692 do {
7693 if (c == '-' && lc != '\0' && *p != ']') {
7694 if ((c = *p++) == '\0')
7695 return (0);
7696 if (c == '\\' && (c = *p++) == '\0')
7697 return (0);
7698
7699 if (notflag) {
7700 if (s1 < lc || s1 > c)
7701 ok++;
7702 else
7703 return (0);
7704 } else if (lc <= s1 && s1 <= c)
7705 ok++;
7706
7707 } else if (c == '\\' && (c = *p++) == '\0')
7708 return (0);
7709
7710 lc = c; /* save left-hand 'c' for next iteration */
7711
7712 if (notflag) {
7713 if (s1 != c)
7714 ok++;
7715 else
7716 return (0);
7717 } else if (s1 == c)
7718 ok++;
7719
7720 if ((c = *p++) == '\0')
7721 return (0);
7722
7723 } while (c != ']');
7724
7725 if (ok)
7726 goto top;
7727
7728 return (0);
7729 }
7730
7731 case '\\':
7732 if ((c = *p++) == '\0')
7733 return (0);
7734 /*FALLTHRU*/
7735
7736 default:
7737 if (c != s1)
7738 return (0);
7739 /*FALLTHRU*/
7740
7741 case '?':
7742 if (s1 != '\0')
7743 goto top;
7744 return (0);
7745
7746 case '*':
7747 while (*p == '*')
7748 p++; /* consecutive *'s are identical to a single one */
7749
7750 if (*p == '\0')
7751 return (1);
7752
7753 for (s = olds; *s != '\0'; s++) {
7754 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7755 return (gs);
7756 }
7757
7758 return (0);
7759 }
7760 }
7761
7762 /*ARGSUSED*/
7763 static int
7764 dtrace_match_string(const char *s, const char *p, int depth)
7765 {
7766 #pragma unused(depth) /* __APPLE__ */
7767 #if !defined(__APPLE__)
7768 return (s != NULL && strcmp(s, p) == 0);
7769 #else /* Employ size bounded string operation. */
7770 return (s != NULL && strncmp(s, p, strlen(s) + 1) == 0);
7771 #endif /* __APPLE__ */
7772 }
7773
7774 /*ARGSUSED*/
7775 static int
7776 dtrace_match_nul(const char *s, const char *p, int depth)
7777 {
7778 #pragma unused(s, p, depth) /* __APPLE__ */
7779 return (1); /* always match the empty pattern */
7780 }
7781
7782 /*ARGSUSED*/
7783 static int
7784 dtrace_match_nonzero(const char *s, const char *p, int depth)
7785 {
7786 #pragma unused(p, depth) /* __APPLE__ */
7787 return (s != NULL && s[0] != '\0');
7788 }
7789
7790 static int
7791 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7792 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7793 {
7794 dtrace_probe_t template, *probe;
7795 dtrace_hash_t *hash = NULL;
7796 int len, rc, best = INT_MAX, nmatched = 0;
7797 dtrace_id_t i;
7798
7799 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7800
7801 /*
7802 * If the probe ID is specified in the key, just lookup by ID and
7803 * invoke the match callback once if a matching probe is found.
7804 */
7805 if (pkp->dtpk_id != DTRACE_IDNONE) {
7806 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7807 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7808 if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7809 return (DTRACE_MATCH_FAIL);
7810 nmatched++;
7811 }
7812 return (nmatched);
7813 }
7814
7815 #if !defined(__APPLE__) /* Quiet compiler warnings */
7816 template.dtpr_mod = (char *)pkp->dtpk_mod;
7817 template.dtpr_func = (char *)pkp->dtpk_func;
7818 template.dtpr_name = (char *)pkp->dtpk_name;
7819 #else
7820 template.dtpr_mod = (char *)(uintptr_t)pkp->dtpk_mod;
7821 template.dtpr_func = (char *)(uintptr_t)pkp->dtpk_func;
7822 template.dtpr_name = (char *)(uintptr_t)pkp->dtpk_name;
7823 #endif /* __APPLE__ */
7824
7825 /*
7826 * We want to find the most distinct of the module name, function
7827 * name, and name. So for each one that is not a glob pattern or
7828 * empty string, we perform a lookup in the corresponding hash and
7829 * use the hash table with the fewest collisions to do our search.
7830 */
7831 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7832 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7833 best = len;
7834 hash = dtrace_bymod;
7835 }
7836
7837 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7838 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7839 best = len;
7840 hash = dtrace_byfunc;
7841 }
7842
7843 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7844 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7845 best = len;
7846 hash = dtrace_byname;
7847 }
7848
7849 /*
7850 * If we did not select a hash table, iterate over every probe and
7851 * invoke our callback for each one that matches our input probe key.
7852 */
7853 if (hash == NULL) {
7854 #if !defined(__APPLE__) /* Quiet compiler warning */
7855 for (i = 0; i < dtrace_nprobes; i++) {
7856 #else
7857 for (i = 0; i < (dtrace_id_t)dtrace_nprobes; i++) {
7858 #endif /* __APPLE__ */
7859 if ((probe = dtrace_probes[i]) == NULL ||
7860 dtrace_match_probe(probe, pkp, priv, uid,
7861 zoneid) <= 0)
7862 continue;
7863
7864 nmatched++;
7865
7866 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7867 if (rc == DTRACE_MATCH_FAIL)
7868 return (DTRACE_MATCH_FAIL);
7869 break;
7870 }
7871 }
7872
7873 return (nmatched);
7874 }
7875
7876 /*
7877 * If we selected a hash table, iterate over each probe of the same key
7878 * name and invoke the callback for every probe that matches the other
7879 * attributes of our input probe key.
7880 */
7881 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7882 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7883
7884 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7885 continue;
7886
7887 nmatched++;
7888
7889 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7890 if (rc == DTRACE_MATCH_FAIL)
7891 return (DTRACE_MATCH_FAIL);
7892 break;
7893 }
7894 }
7895
7896 return (nmatched);
7897 }
7898
7899 /*
7900 * Return the function pointer dtrace_probecmp() should use to compare the
7901 * specified pattern with a string. For NULL or empty patterns, we select
7902 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7903 * For non-empty non-glob strings, we use dtrace_match_string().
7904 */
7905 static dtrace_probekey_f *
7906 dtrace_probekey_func(const char *p)
7907 {
7908 char c;
7909
7910 if (p == NULL || *p == '\0')
7911 return (&dtrace_match_nul);
7912
7913 while ((c = *p++) != '\0') {
7914 if (c == '[' || c == '?' || c == '*' || c == '\\')
7915 return (&dtrace_match_glob);
7916 }
7917
7918 return (&dtrace_match_string);
7919 }
7920
7921 /*
7922 * Build a probe comparison key for use with dtrace_match_probe() from the
7923 * given probe description. By convention, a null key only matches anchored
7924 * probes: if each field is the empty string, reset dtpk_fmatch to
7925 * dtrace_match_nonzero().
7926 */
7927 static void
7928 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7929 {
7930 pkp->dtpk_prov = pdp->dtpd_provider;
7931 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7932
7933 pkp->dtpk_mod = pdp->dtpd_mod;
7934 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7935
7936 pkp->dtpk_func = pdp->dtpd_func;
7937 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7938
7939 pkp->dtpk_name = pdp->dtpd_name;
7940 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7941
7942 pkp->dtpk_id = pdp->dtpd_id;
7943
7944 if (pkp->dtpk_id == DTRACE_IDNONE &&
7945 pkp->dtpk_pmatch == &dtrace_match_nul &&
7946 pkp->dtpk_mmatch == &dtrace_match_nul &&
7947 pkp->dtpk_fmatch == &dtrace_match_nul &&
7948 pkp->dtpk_nmatch == &dtrace_match_nul)
7949 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7950 }
7951
7952 /*
7953 * DTrace Provider-to-Framework API Functions
7954 *
7955 * These functions implement much of the Provider-to-Framework API, as
7956 * described in <sys/dtrace.h>. The parts of the API not in this section are
7957 * the functions in the API for probe management (found below), and
7958 * dtrace_probe() itself (found above).
7959 */
7960
7961 /*
7962 * Register the calling provider with the DTrace framework. This should
7963 * generally be called by DTrace providers in their attach(9E) entry point.
7964 */
7965 int
7966 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7967 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7968 {
7969 dtrace_provider_t *provider;
7970
7971 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7972 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7973 "arguments", name ? name : "<NULL>");
7974 return (EINVAL);
7975 }
7976
7977 if (name[0] == '\0' || dtrace_badname(name)) {
7978 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7979 "provider name", name);
7980 return (EINVAL);
7981 }
7982
7983 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7984 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7985 pops->dtps_destroy == NULL ||
7986 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7987 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7988 "provider ops", name);
7989 return (EINVAL);
7990 }
7991
7992 if (dtrace_badattr(&pap->dtpa_provider) ||
7993 dtrace_badattr(&pap->dtpa_mod) ||
7994 dtrace_badattr(&pap->dtpa_func) ||
7995 dtrace_badattr(&pap->dtpa_name) ||
7996 dtrace_badattr(&pap->dtpa_args)) {
7997 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7998 "provider attributes", name);
7999 return (EINVAL);
8000 }
8001
8002 if (priv & ~DTRACE_PRIV_ALL) {
8003 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8004 "privilege attributes", name);
8005 return (EINVAL);
8006 }
8007
8008 if ((priv & DTRACE_PRIV_KERNEL) &&
8009 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8010 pops->dtps_usermode == NULL) {
8011 cmn_err(CE_WARN, "failed to register provider '%s': need "
8012 "dtps_usermode() op for given privilege attributes", name);
8013 return (EINVAL);
8014 }
8015
8016 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8017 #if !defined(__APPLE__)
8018 provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8019 (void) strcpy(provider->dtpv_name, name);
8020 #else /* Employ size bounded string operation. */
8021 {
8022 size_t bufsize = strlen(name) + 1;
8023 provider->dtpv_name = kmem_alloc(bufsize, KM_SLEEP);
8024 (void) strlcpy(provider->dtpv_name, name, bufsize);
8025 }
8026 #endif /* __APPLE__ */
8027
8028 provider->dtpv_attr = *pap;
8029 provider->dtpv_priv.dtpp_flags = priv;
8030 if (cr != NULL) {
8031 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8032 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8033 }
8034 provider->dtpv_pops = *pops;
8035
8036 if (pops->dtps_provide == NULL) {
8037 ASSERT(pops->dtps_provide_module != NULL);
8038 provider->dtpv_pops.dtps_provide =
8039 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
8040 }
8041
8042 if (pops->dtps_provide_module == NULL) {
8043 ASSERT(pops->dtps_provide != NULL);
8044 provider->dtpv_pops.dtps_provide_module =
8045 (void (*)(void *, struct modctl *))dtrace_nullop;
8046 }
8047
8048 if (pops->dtps_suspend == NULL) {
8049 ASSERT(pops->dtps_resume == NULL);
8050 provider->dtpv_pops.dtps_suspend =
8051 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8052 provider->dtpv_pops.dtps_resume =
8053 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8054 }
8055
8056 provider->dtpv_arg = arg;
8057 *idp = (dtrace_provider_id_t)provider;
8058
8059 if (pops == &dtrace_provider_ops) {
8060 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8061 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8062 ASSERT(dtrace_anon.dta_enabling == NULL);
8063
8064 /*
8065 * We make sure that the DTrace provider is at the head of
8066 * the provider chain.
8067 */
8068 provider->dtpv_next = dtrace_provider;
8069 dtrace_provider = provider;
8070 return (0);
8071 }
8072
8073 lck_mtx_lock(&dtrace_provider_lock);
8074 lck_mtx_lock(&dtrace_lock);
8075
8076 /*
8077 * If there is at least one provider registered, we'll add this
8078 * provider after the first provider.
8079 */
8080 if (dtrace_provider != NULL) {
8081 provider->dtpv_next = dtrace_provider->dtpv_next;
8082 dtrace_provider->dtpv_next = provider;
8083 } else {
8084 dtrace_provider = provider;
8085 }
8086
8087 if (dtrace_retained != NULL) {
8088 dtrace_enabling_provide(provider);
8089
8090 /*
8091 * Now we need to call dtrace_enabling_matchall() -- which
8092 * will acquire cpu_lock and dtrace_lock. We therefore need
8093 * to drop all of our locks before calling into it...
8094 */
8095 lck_mtx_unlock(&dtrace_lock);
8096 lck_mtx_unlock(&dtrace_provider_lock);
8097 dtrace_enabling_matchall();
8098
8099 return (0);
8100 }
8101
8102 lck_mtx_unlock(&dtrace_lock);
8103 lck_mtx_unlock(&dtrace_provider_lock);
8104
8105 return (0);
8106 }
8107
8108 /*
8109 * Unregister the specified provider from the DTrace framework. This should
8110 * generally be called by DTrace providers in their detach(9E) entry point.
8111 */
8112 int
8113 dtrace_unregister(dtrace_provider_id_t id)
8114 {
8115 dtrace_provider_t *old = (dtrace_provider_t *)id;
8116 dtrace_provider_t *prev = NULL;
8117 int i, self = 0;
8118 dtrace_probe_t *probe, *first = NULL;
8119
8120 if (old->dtpv_pops.dtps_enable ==
8121 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
8122 /*
8123 * If DTrace itself is the provider, we're called with locks
8124 * already held.
8125 */
8126 ASSERT(old == dtrace_provider);
8127 ASSERT(dtrace_devi != NULL);
8128 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8129 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8130 self = 1;
8131
8132 if (dtrace_provider->dtpv_next != NULL) {
8133 /*
8134 * There's another provider here; return failure.
8135 */
8136 return (EBUSY);
8137 }
8138 } else {
8139 lck_mtx_lock(&dtrace_provider_lock);
8140 lck_mtx_lock(&mod_lock);
8141 lck_mtx_lock(&dtrace_lock);
8142 }
8143
8144 /*
8145 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8146 * probes, we refuse to let providers slither away, unless this
8147 * provider has already been explicitly invalidated.
8148 */
8149 if (!old->dtpv_defunct &&
8150 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8151 dtrace_anon.dta_state->dts_necbs > 0))) {
8152 if (!self) {
8153 lck_mtx_unlock(&dtrace_lock);
8154 lck_mtx_unlock(&mod_lock);
8155 lck_mtx_unlock(&dtrace_provider_lock);
8156 }
8157 return (EBUSY);
8158 }
8159
8160 /*
8161 * Attempt to destroy the probes associated with this provider.
8162 */
8163 for (i = 0; i < dtrace_nprobes; i++) {
8164 if ((probe = dtrace_probes[i]) == NULL)
8165 continue;
8166
8167 if (probe->dtpr_provider != old)
8168 continue;
8169
8170 if (probe->dtpr_ecb == NULL)
8171 continue;
8172
8173 /*
8174 * We have at least one ECB; we can't remove this provider.
8175 */
8176 if (!self) {
8177 lck_mtx_unlock(&dtrace_lock);
8178 lck_mtx_unlock(&mod_lock);
8179 lck_mtx_unlock(&dtrace_provider_lock);
8180 }
8181 return (EBUSY);
8182 }
8183
8184 /*
8185 * All of the probes for this provider are disabled; we can safely
8186 * remove all of them from their hash chains and from the probe array.
8187 */
8188 for (i = 0; i < dtrace_nprobes; i++) {
8189 if ((probe = dtrace_probes[i]) == NULL)
8190 continue;
8191
8192 if (probe->dtpr_provider != old)
8193 continue;
8194
8195 dtrace_probes[i] = NULL;
8196
8197 dtrace_hash_remove(dtrace_bymod, probe);
8198 dtrace_hash_remove(dtrace_byfunc, probe);
8199 dtrace_hash_remove(dtrace_byname, probe);
8200
8201 if (first == NULL) {
8202 first = probe;
8203 probe->dtpr_nextmod = NULL;
8204 } else {
8205 probe->dtpr_nextmod = first;
8206 first = probe;
8207 }
8208 }
8209
8210 /*
8211 * The provider's probes have been removed from the hash chains and
8212 * from the probe array. Now issue a dtrace_sync() to be sure that
8213 * everyone has cleared out from any probe array processing.
8214 */
8215 dtrace_sync();
8216
8217 for (probe = first; probe != NULL; probe = first) {
8218 first = probe->dtpr_nextmod;
8219
8220 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8221 probe->dtpr_arg);
8222 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8223 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8224 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8225 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8226 #if !defined(__APPLE__)
8227 kmem_free(probe, sizeof (dtrace_probe_t));
8228 #else
8229 zfree(dtrace_probe_t_zone, probe);
8230 #endif
8231 }
8232
8233 if ((prev = dtrace_provider) == old) {
8234 ASSERT(self || dtrace_devi == NULL);
8235 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8236 dtrace_provider = old->dtpv_next;
8237 } else {
8238 while (prev != NULL && prev->dtpv_next != old)
8239 prev = prev->dtpv_next;
8240
8241 if (prev == NULL) {
8242 panic("attempt to unregister non-existent "
8243 "dtrace provider %p\n", (void *)id);
8244 }
8245
8246 prev->dtpv_next = old->dtpv_next;
8247 }
8248
8249 if (!self) {
8250 lck_mtx_unlock(&dtrace_lock);
8251 lck_mtx_unlock(&mod_lock);
8252 lck_mtx_unlock(&dtrace_provider_lock);
8253 }
8254
8255 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8256 kmem_free(old, sizeof (dtrace_provider_t));
8257
8258 return (0);
8259 }
8260
8261 /*
8262 * Invalidate the specified provider. All subsequent probe lookups for the
8263 * specified provider will fail, but its probes will not be removed.
8264 */
8265 void
8266 dtrace_invalidate(dtrace_provider_id_t id)
8267 {
8268 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8269
8270 ASSERT(pvp->dtpv_pops.dtps_enable !=
8271 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8272
8273 lck_mtx_lock(&dtrace_provider_lock);
8274 lck_mtx_lock(&dtrace_lock);
8275
8276 pvp->dtpv_defunct = 1;
8277
8278 lck_mtx_unlock(&dtrace_lock);
8279 lck_mtx_unlock(&dtrace_provider_lock);
8280 }
8281
8282 /*
8283 * Indicate whether or not DTrace has attached.
8284 */
8285 int
8286 dtrace_attached(void)
8287 {
8288 /*
8289 * dtrace_provider will be non-NULL iff the DTrace driver has
8290 * attached. (It's non-NULL because DTrace is always itself a
8291 * provider.)
8292 */
8293 return (dtrace_provider != NULL);
8294 }
8295
8296 /*
8297 * Remove all the unenabled probes for the given provider. This function is
8298 * not unlike dtrace_unregister(), except that it doesn't remove the provider
8299 * -- just as many of its associated probes as it can.
8300 */
8301 int
8302 dtrace_condense(dtrace_provider_id_t id)
8303 {
8304 dtrace_provider_t *prov = (dtrace_provider_t *)id;
8305 int i;
8306 dtrace_probe_t *probe;
8307
8308 /*
8309 * Make sure this isn't the dtrace provider itself.
8310 */
8311 ASSERT(prov->dtpv_pops.dtps_enable !=
8312 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8313
8314 lck_mtx_lock(&dtrace_provider_lock);
8315 lck_mtx_lock(&dtrace_lock);
8316
8317 /*
8318 * Attempt to destroy the probes associated with this provider.
8319 */
8320 for (i = 0; i < dtrace_nprobes; i++) {
8321 if ((probe = dtrace_probes[i]) == NULL)
8322 continue;
8323
8324 if (probe->dtpr_provider != prov)
8325 continue;
8326
8327 if (probe->dtpr_ecb != NULL)
8328 continue;
8329
8330 dtrace_probes[i] = NULL;
8331
8332 dtrace_hash_remove(dtrace_bymod, probe);
8333 dtrace_hash_remove(dtrace_byfunc, probe);
8334 dtrace_hash_remove(dtrace_byname, probe);
8335
8336 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8337 probe->dtpr_arg);
8338 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8339 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8340 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8341 #if !defined(__APPLE__)
8342 kmem_free(probe, sizeof (dtrace_probe_t));
8343 #else
8344 zfree(dtrace_probe_t_zone, probe);
8345 #endif
8346 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8347 }
8348
8349 lck_mtx_unlock(&dtrace_lock);
8350 lck_mtx_unlock(&dtrace_provider_lock);
8351
8352 return (0);
8353 }
8354
8355 /*
8356 * DTrace Probe Management Functions
8357 *
8358 * The functions in this section perform the DTrace probe management,
8359 * including functions to create probes, look-up probes, and call into the
8360 * providers to request that probes be provided. Some of these functions are
8361 * in the Provider-to-Framework API; these functions can be identified by the
8362 * fact that they are not declared "static".
8363 */
8364
8365 /*
8366 * Create a probe with the specified module name, function name, and name.
8367 */
8368 dtrace_id_t
8369 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8370 const char *func, const char *name, int aframes, void *arg)
8371 {
8372 dtrace_probe_t *probe, **probes;
8373 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8374 dtrace_id_t id;
8375
8376 if (provider == dtrace_provider) {
8377 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8378 } else {
8379 lck_mtx_lock(&dtrace_lock);
8380 }
8381
8382 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8383 VM_BESTFIT | VM_SLEEP);
8384 #if !defined(__APPLE__)
8385 probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8386 #else
8387 probe = zalloc(dtrace_probe_t_zone);
8388 bzero(probe, sizeof (dtrace_probe_t));
8389 #endif
8390
8391 probe->dtpr_id = id;
8392 probe->dtpr_gen = dtrace_probegen++;
8393 probe->dtpr_mod = dtrace_strdup(mod);
8394 probe->dtpr_func = dtrace_strdup(func);
8395 probe->dtpr_name = dtrace_strdup(name);
8396 probe->dtpr_arg = arg;
8397 probe->dtpr_aframes = aframes;
8398 probe->dtpr_provider = provider;
8399
8400 dtrace_hash_add(dtrace_bymod, probe);
8401 dtrace_hash_add(dtrace_byfunc, probe);
8402 dtrace_hash_add(dtrace_byname, probe);
8403
8404 #if !defined(__APPLE__) /* Quiet compiler warning */
8405 if (id - 1 >= dtrace_nprobes) {
8406 #else
8407 if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
8408 #endif /* __APPLE__ */
8409 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8410 size_t nsize = osize << 1;
8411
8412 if (nsize == 0) {
8413 ASSERT(osize == 0);
8414 ASSERT(dtrace_probes == NULL);
8415 nsize = sizeof (dtrace_probe_t *);
8416 }
8417
8418 probes = kmem_zalloc(nsize, KM_SLEEP);
8419
8420 if (dtrace_probes == NULL) {
8421 ASSERT(osize == 0);
8422 dtrace_probes = probes;
8423 dtrace_nprobes = 1;
8424 } else {
8425 dtrace_probe_t **oprobes = dtrace_probes;
8426
8427 bcopy(oprobes, probes, osize);
8428 dtrace_membar_producer();
8429 dtrace_probes = probes;
8430
8431 dtrace_sync();
8432
8433 /*
8434 * All CPUs are now seeing the new probes array; we can
8435 * safely free the old array.
8436 */
8437 kmem_free(oprobes, osize);
8438 dtrace_nprobes <<= 1;
8439 }
8440
8441 #if !defined(__APPLE__) /* Quiet compiler warning */
8442 ASSERT(id - 1 < dtrace_nprobes);
8443 #else
8444 ASSERT(id - 1 < (dtrace_id_t)dtrace_nprobes);
8445 #endif /* __APPLE__ */
8446 }
8447
8448 ASSERT(dtrace_probes[id - 1] == NULL);
8449 dtrace_probes[id - 1] = probe;
8450
8451 if (provider != dtrace_provider)
8452 lck_mtx_unlock(&dtrace_lock);
8453
8454 return (id);
8455 }
8456
8457 static dtrace_probe_t *
8458 dtrace_probe_lookup_id(dtrace_id_t id)
8459 {
8460 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8461
8462 #if !defined(__APPLE__) /* Quiet compiler warning */
8463 if (id == 0 || id > dtrace_nprobes)
8464 return (NULL);
8465 #else
8466 if (id == 0 || id > (dtrace_id_t)dtrace_nprobes)
8467 return (NULL);
8468 #endif /* __APPLE__ */
8469
8470 return (dtrace_probes[id - 1]);
8471 }
8472
8473 static int
8474 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8475 {
8476 *((dtrace_id_t *)arg) = probe->dtpr_id;
8477
8478 return (DTRACE_MATCH_DONE);
8479 }
8480
8481 /*
8482 * Look up a probe based on provider and one or more of module name, function
8483 * name and probe name.
8484 */
8485 dtrace_id_t
8486 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8487 const char *func, const char *name)
8488 {
8489 dtrace_probekey_t pkey;
8490 dtrace_id_t id;
8491 int match;
8492
8493 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8494 pkey.dtpk_pmatch = &dtrace_match_string;
8495 pkey.dtpk_mod = mod;
8496 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8497 pkey.dtpk_func = func;
8498 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8499 pkey.dtpk_name = name;
8500 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8501 pkey.dtpk_id = DTRACE_IDNONE;
8502
8503 lck_mtx_lock(&dtrace_lock);
8504 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8505 dtrace_probe_lookup_match, &id);
8506 lck_mtx_unlock(&dtrace_lock);
8507
8508 ASSERT(match == 1 || match == 0);
8509 return (match ? id : 0);
8510 }
8511
8512 /*
8513 * Returns the probe argument associated with the specified probe.
8514 */
8515 void *
8516 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8517 {
8518 dtrace_probe_t *probe;
8519 void *rval = NULL;
8520
8521 lck_mtx_lock(&dtrace_lock);
8522
8523 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8524 probe->dtpr_provider == (dtrace_provider_t *)id)
8525 rval = probe->dtpr_arg;
8526
8527 lck_mtx_unlock(&dtrace_lock);
8528
8529 return (rval);
8530 }
8531
8532 /*
8533 * Copy a probe into a probe description.
8534 */
8535 static void
8536 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8537 {
8538 bzero(pdp, sizeof (dtrace_probedesc_t));
8539 pdp->dtpd_id = prp->dtpr_id;
8540
8541 #if !defined(__APPLE__)
8542 (void) strncpy(pdp->dtpd_provider,
8543 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8544
8545 (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8546 (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8547 (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8548 #else /* Employ size bounded string operation. */
8549 (void) strlcpy(pdp->dtpd_provider,
8550 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN);
8551
8552 (void) strlcpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN);
8553 (void) strlcpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN);
8554 (void) strlcpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN);
8555 #endif /* __APPLE__ */
8556 }
8557
8558 /*
8559 * Called to indicate that a probe -- or probes -- should be provided by a
8560 * specfied provider. If the specified description is NULL, the provider will
8561 * be told to provide all of its probes. (This is done whenever a new
8562 * consumer comes along, or whenever a retained enabling is to be matched.) If
8563 * the specified description is non-NULL, the provider is given the
8564 * opportunity to dynamically provide the specified probe, allowing providers
8565 * to support the creation of probes on-the-fly. (So-called _autocreated_
8566 * probes.) If the provider is NULL, the operations will be applied to all
8567 * providers; if the provider is non-NULL the operations will only be applied
8568 * to the specified provider. The dtrace_provider_lock must be held, and the
8569 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8570 * will need to grab the dtrace_lock when it reenters the framework through
8571 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8572 */
8573 static void
8574 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8575 {
8576 struct modctl *ctl;
8577 int all = 0;
8578
8579 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8580
8581 if (prv == NULL) {
8582 all = 1;
8583 prv = dtrace_provider;
8584 }
8585
8586 do {
8587 /*
8588 * First, call the blanket provide operation.
8589 */
8590 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8591
8592 /*
8593 * Now call the per-module provide operation. We will grab
8594 * mod_lock to prevent the list from being modified. Note
8595 * that this also prevents the mod_busy bits from changing.
8596 * (mod_busy can only be changed with mod_lock held.)
8597 */
8598 lck_mtx_lock(&mod_lock);
8599
8600 #if !defined(__APPLE__)
8601 ctl = &modules;
8602 do {
8603 if (ctl->mod_busy || ctl->mod_mp == NULL)
8604 continue;
8605
8606 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8607
8608 } while ((ctl = ctl->mod_next) != &modules);
8609 #else
8610 ctl = dtrace_modctl_list;
8611 while (ctl) {
8612 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8613 ctl = ctl->mod_next;
8614 }
8615 #endif
8616
8617 lck_mtx_unlock(&mod_lock);
8618 } while (all && (prv = prv->dtpv_next) != NULL);
8619 }
8620
8621 /*
8622 * Iterate over each probe, and call the Framework-to-Provider API function
8623 * denoted by offs.
8624 */
8625 static void
8626 dtrace_probe_foreach(uintptr_t offs)
8627 {
8628 dtrace_provider_t *prov;
8629 void (*func)(void *, dtrace_id_t, void *);
8630 dtrace_probe_t *probe;
8631 dtrace_icookie_t cookie;
8632 int i;
8633
8634 /*
8635 * We disable interrupts to walk through the probe array. This is
8636 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8637 * won't see stale data.
8638 */
8639 cookie = dtrace_interrupt_disable();
8640
8641 for (i = 0; i < dtrace_nprobes; i++) {
8642 if ((probe = dtrace_probes[i]) == NULL)
8643 continue;
8644
8645 if (probe->dtpr_ecb == NULL) {
8646 /*
8647 * This probe isn't enabled -- don't call the function.
8648 */
8649 continue;
8650 }
8651
8652 prov = probe->dtpr_provider;
8653 func = *((void(**)(void *, dtrace_id_t, void *))
8654 ((uintptr_t)&prov->dtpv_pops + offs));
8655
8656 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8657 }
8658
8659 dtrace_interrupt_enable(cookie);
8660 }
8661
8662 static int
8663 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8664 {
8665 dtrace_probekey_t pkey;
8666 uint32_t priv;
8667 uid_t uid;
8668 zoneid_t zoneid;
8669
8670 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8671
8672 dtrace_ecb_create_cache = NULL;
8673
8674 if (desc == NULL) {
8675 /*
8676 * If we're passed a NULL description, we're being asked to
8677 * create an ECB with a NULL probe.
8678 */
8679 (void) dtrace_ecb_create_enable(NULL, enab);
8680 return (0);
8681 }
8682
8683 dtrace_probekey(desc, &pkey);
8684 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8685 &priv, &uid, &zoneid);
8686
8687 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8688 enab));
8689 }
8690
8691 /*
8692 * DTrace Helper Provider Functions
8693 */
8694 static void
8695 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8696 {
8697 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8698 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8699 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8700 }
8701
8702 static void
8703 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8704 const dof_provider_t *dofprov, char *strtab)
8705 {
8706 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8707 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8708 dofprov->dofpv_provattr);
8709 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8710 dofprov->dofpv_modattr);
8711 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8712 dofprov->dofpv_funcattr);
8713 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8714 dofprov->dofpv_nameattr);
8715 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8716 dofprov->dofpv_argsattr);
8717 }
8718
8719 static void
8720 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8721 {
8722 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8723 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8724 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8725 dof_provider_t *provider;
8726 dof_probe_t *probe;
8727 uint32_t *off, *enoff;
8728 uint8_t *arg;
8729 char *strtab;
8730 uint_t i, nprobes;
8731 dtrace_helper_provdesc_t dhpv;
8732 dtrace_helper_probedesc_t dhpb;
8733 dtrace_meta_t *meta = dtrace_meta_pid;
8734 dtrace_mops_t *mops = &meta->dtm_mops;
8735 void *parg;
8736
8737 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8738 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8739 provider->dofpv_strtab * dof->dofh_secsize);
8740 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8741 provider->dofpv_probes * dof->dofh_secsize);
8742 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8743 provider->dofpv_prargs * dof->dofh_secsize);
8744 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8745 provider->dofpv_proffs * dof->dofh_secsize);
8746
8747 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8748 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8749 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8750 enoff = NULL;
8751
8752 /*
8753 * See dtrace_helper_provider_validate().
8754 */
8755 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8756 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8757 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8758 provider->dofpv_prenoffs * dof->dofh_secsize);
8759 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8760 }
8761
8762 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8763
8764 /*
8765 * Create the provider.
8766 */
8767 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8768
8769 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8770 return;
8771
8772 meta->dtm_count++;
8773
8774 /*
8775 * Create the probes.
8776 */
8777 for (i = 0; i < nprobes; i++) {
8778 probe = (dof_probe_t *)(uintptr_t)(daddr +
8779 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8780
8781 dhpb.dthpb_mod = dhp->dofhp_mod;
8782 dhpb.dthpb_func = strtab + probe->dofpr_func;
8783 dhpb.dthpb_name = strtab + probe->dofpr_name;
8784 #if !defined(__APPLE__)
8785 dhpb.dthpb_base = probe->dofpr_addr;
8786 #else
8787 dhpb.dthpb_base = dhp->dofhp_addr; /* FIXME: James, why? */
8788 #endif
8789 #if !defined(__APPLE__) /* Quiet compiler warning */
8790 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8791 #else
8792 dhpb.dthpb_offs = (int32_t *)(off + probe->dofpr_offidx);
8793 #endif /* __APPLE__ */
8794 dhpb.dthpb_noffs = probe->dofpr_noffs;
8795 if (enoff != NULL) {
8796 #if !defined(__APPLE__) /* Quiet compiler warning */
8797 dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8798 #else
8799 dhpb.dthpb_enoffs = (int32_t *)(enoff + probe->dofpr_enoffidx);
8800 #endif /* __APPLE__ */
8801 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8802 } else {
8803 dhpb.dthpb_enoffs = NULL;
8804 dhpb.dthpb_nenoffs = 0;
8805 }
8806 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8807 dhpb.dthpb_nargc = probe->dofpr_nargc;
8808 dhpb.dthpb_xargc = probe->dofpr_xargc;
8809 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8810 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8811
8812 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8813 }
8814 }
8815
8816 static void
8817 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8818 {
8819 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8820 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8821 #if !defined(__APPLE__) /* Quiet compiler warning */
8822 int i;
8823 #else
8824 uint32_t i;
8825 #endif /* __APPLE__ */
8826
8827 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8828
8829 for (i = 0; i < dof->dofh_secnum; i++) {
8830 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8831 dof->dofh_secoff + i * dof->dofh_secsize);
8832
8833 if (sec->dofs_type != DOF_SECT_PROVIDER)
8834 continue;
8835
8836 dtrace_helper_provide_one(dhp, sec, pid);
8837 }
8838
8839 /*
8840 * We may have just created probes, so we must now rematch against
8841 * any retained enablings. Note that this call will acquire both
8842 * cpu_lock and dtrace_lock; the fact that we are holding
8843 * dtrace_meta_lock now is what defines the ordering with respect to
8844 * these three locks.
8845 */
8846 dtrace_enabling_matchall();
8847 }
8848
8849 static void
8850 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8851 {
8852 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8853 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8854 dof_sec_t *str_sec;
8855 dof_provider_t *provider;
8856 char *strtab;
8857 dtrace_helper_provdesc_t dhpv;
8858 dtrace_meta_t *meta = dtrace_meta_pid;
8859 dtrace_mops_t *mops = &meta->dtm_mops;
8860
8861 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8862 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8863 provider->dofpv_strtab * dof->dofh_secsize);
8864
8865 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8866
8867 /*
8868 * Create the provider.
8869 */
8870 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8871
8872 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8873
8874 meta->dtm_count--;
8875 }
8876
8877 static void
8878 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8879 {
8880 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8881 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8882 #if !defined(__APPLE__) /* Quiet compiler warning */
8883 int i;
8884 #else
8885 uint32_t i;
8886 #endif /* __APPLE__ */
8887
8888 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8889
8890 for (i = 0; i < dof->dofh_secnum; i++) {
8891 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8892 dof->dofh_secoff + i * dof->dofh_secsize);
8893
8894 if (sec->dofs_type != DOF_SECT_PROVIDER)
8895 continue;
8896
8897 dtrace_helper_provider_remove_one(dhp, sec, pid);
8898 }
8899 }
8900
8901 /*
8902 * DTrace Meta Provider-to-Framework API Functions
8903 *
8904 * These functions implement the Meta Provider-to-Framework API, as described
8905 * in <sys/dtrace.h>.
8906 */
8907 int
8908 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8909 dtrace_meta_provider_id_t *idp)
8910 {
8911 dtrace_meta_t *meta;
8912 dtrace_helpers_t *help, *next;
8913 #if !defined(__APPLE__) /* Quiet compiler warning */
8914 int i;
8915 #else
8916 uint_t i;
8917 #endif /* __APPLE__ */
8918
8919 *idp = DTRACE_METAPROVNONE;
8920
8921 /*
8922 * We strictly don't need the name, but we hold onto it for
8923 * debuggability. All hail error queues!
8924 */
8925 if (name == NULL) {
8926 cmn_err(CE_WARN, "failed to register meta-provider: "
8927 "invalid name");
8928 return (EINVAL);
8929 }
8930
8931 if (mops == NULL ||
8932 mops->dtms_create_probe == NULL ||
8933 mops->dtms_provide_pid == NULL ||
8934 mops->dtms_remove_pid == NULL) {
8935 cmn_err(CE_WARN, "failed to register meta-register %s: "
8936 "invalid ops", name);
8937 return (EINVAL);
8938 }
8939
8940 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8941 meta->dtm_mops = *mops;
8942 #if !defined(__APPLE__)
8943 meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8944 (void) strcpy(meta->dtm_name, name);
8945 #else /* Employ size bounded string operation. */
8946 {
8947 size_t bufsize = strlen(name) + 1;
8948 meta->dtm_name = kmem_alloc(bufsize, KM_SLEEP);
8949 (void) strlcpy(meta->dtm_name, name, bufsize);
8950 }
8951 #endif /* __APPLE__ */
8952 meta->dtm_arg = arg;
8953
8954 lck_mtx_lock(&dtrace_meta_lock);
8955 lck_mtx_lock(&dtrace_lock);
8956
8957 if (dtrace_meta_pid != NULL) {
8958 lck_mtx_unlock(&dtrace_lock);
8959 lck_mtx_unlock(&dtrace_meta_lock);
8960 cmn_err(CE_WARN, "failed to register meta-register %s: "
8961 "user-land meta-provider exists", name);
8962 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8963 kmem_free(meta, sizeof (dtrace_meta_t));
8964 return (EINVAL);
8965 }
8966
8967 dtrace_meta_pid = meta;
8968 *idp = (dtrace_meta_provider_id_t)meta;
8969
8970 /*
8971 * If there are providers and probes ready to go, pass them
8972 * off to the new meta provider now.
8973 */
8974
8975 help = dtrace_deferred_pid;
8976 dtrace_deferred_pid = NULL;
8977
8978 lck_mtx_unlock(&dtrace_lock);
8979
8980 while (help != NULL) {
8981 for (i = 0; i < help->dthps_nprovs; i++) {
8982 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8983 help->dthps_pid);
8984 }
8985
8986 next = help->dthps_next;
8987 help->dthps_next = NULL;
8988 help->dthps_prev = NULL;
8989 help->dthps_deferred = 0;
8990 help = next;
8991 }
8992
8993 lck_mtx_unlock(&dtrace_meta_lock);
8994
8995 return (0);
8996 }
8997
8998 int
8999 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9000 {
9001 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9002
9003 lck_mtx_lock(&dtrace_meta_lock);
9004 lck_mtx_lock(&dtrace_lock);
9005
9006 if (old == dtrace_meta_pid) {
9007 pp = &dtrace_meta_pid;
9008 } else {
9009 panic("attempt to unregister non-existent "
9010 "dtrace meta-provider %p\n", (void *)old);
9011 }
9012
9013 if (old->dtm_count != 0) {
9014 lck_mtx_unlock(&dtrace_lock);
9015 lck_mtx_unlock(&dtrace_meta_lock);
9016 return (EBUSY);
9017 }
9018
9019 *pp = NULL;
9020
9021 lck_mtx_unlock(&dtrace_lock);
9022 lck_mtx_unlock(&dtrace_meta_lock);
9023
9024 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9025 kmem_free(old, sizeof (dtrace_meta_t));
9026
9027 return (0);
9028 }
9029
9030
9031 /*
9032 * DTrace DIF Object Functions
9033 */
9034 static int
9035 dtrace_difo_err(uint_t pc, const char *format, ...)
9036 {
9037 if (dtrace_err_verbose) {
9038 va_list alist;
9039
9040 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
9041 va_start(alist, format);
9042 (void) vuprintf(format, alist);
9043 va_end(alist);
9044 }
9045
9046 #ifdef DTRACE_ERRDEBUG
9047 dtrace_errdebug(format);
9048 #endif
9049 return (1);
9050 }
9051
9052 /*
9053 * Validate a DTrace DIF object by checking the IR instructions. The following
9054 * rules are currently enforced by dtrace_difo_validate():
9055 *
9056 * 1. Each instruction must have a valid opcode
9057 * 2. Each register, string, variable, or subroutine reference must be valid
9058 * 3. No instruction can modify register %r0 (must be zero)
9059 * 4. All instruction reserved bits must be set to zero
9060 * 5. The last instruction must be a "ret" instruction
9061 * 6. All branch targets must reference a valid instruction _after_ the branch
9062 */
9063 static int
9064 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9065 cred_t *cr)
9066 {
9067 #if !defined(__APPLE__) /* Quiet compiler warnings */
9068 int err = 0, i;
9069 #else
9070 int err = 0;
9071 uint_t i;
9072 #endif /* __APPLE__ */
9073 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9074 int kcheckload;
9075 uint_t pc;
9076
9077 kcheckload = cr == NULL ||
9078 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9079
9080 dp->dtdo_destructive = 0;
9081
9082 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9083 dif_instr_t instr = dp->dtdo_buf[pc];
9084
9085 uint_t r1 = DIF_INSTR_R1(instr);
9086 uint_t r2 = DIF_INSTR_R2(instr);
9087 uint_t rd = DIF_INSTR_RD(instr);
9088 uint_t rs = DIF_INSTR_RS(instr);
9089 uint_t label = DIF_INSTR_LABEL(instr);
9090 uint_t v = DIF_INSTR_VAR(instr);
9091 uint_t subr = DIF_INSTR_SUBR(instr);
9092 uint_t type = DIF_INSTR_TYPE(instr);
9093 uint_t op = DIF_INSTR_OP(instr);
9094
9095 switch (op) {
9096 case DIF_OP_OR:
9097 case DIF_OP_XOR:
9098 case DIF_OP_AND:
9099 case DIF_OP_SLL:
9100 case DIF_OP_SRL:
9101 case DIF_OP_SRA:
9102 case DIF_OP_SUB:
9103 case DIF_OP_ADD:
9104 case DIF_OP_MUL:
9105 case DIF_OP_SDIV:
9106 case DIF_OP_UDIV:
9107 case DIF_OP_SREM:
9108 case DIF_OP_UREM:
9109 case DIF_OP_COPYS:
9110 if (r1 >= nregs)
9111 err += efunc(pc, "invalid register %u\n", r1);
9112 if (r2 >= nregs)
9113 err += efunc(pc, "invalid register %u\n", r2);
9114 if (rd >= nregs)
9115 err += efunc(pc, "invalid register %u\n", rd);
9116 if (rd == 0)
9117 err += efunc(pc, "cannot write to %r0\n");
9118 break;
9119 case DIF_OP_NOT:
9120 case DIF_OP_MOV:
9121 case DIF_OP_ALLOCS:
9122 if (r1 >= nregs)
9123 err += efunc(pc, "invalid register %u\n", r1);
9124 if (r2 != 0)
9125 err += efunc(pc, "non-zero reserved bits\n");
9126 if (rd >= nregs)
9127 err += efunc(pc, "invalid register %u\n", rd);
9128 if (rd == 0)
9129 err += efunc(pc, "cannot write to %r0\n");
9130 break;
9131 case DIF_OP_LDSB:
9132 case DIF_OP_LDSH:
9133 case DIF_OP_LDSW:
9134 case DIF_OP_LDUB:
9135 case DIF_OP_LDUH:
9136 case DIF_OP_LDUW:
9137 case DIF_OP_LDX:
9138 if (r1 >= nregs)
9139 err += efunc(pc, "invalid register %u\n", r1);
9140 if (r2 != 0)
9141 err += efunc(pc, "non-zero reserved bits\n");
9142 if (rd >= nregs)
9143 err += efunc(pc, "invalid register %u\n", rd);
9144 if (rd == 0)
9145 err += efunc(pc, "cannot write to %r0\n");
9146 if (kcheckload)
9147 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9148 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9149 break;
9150 case DIF_OP_RLDSB:
9151 case DIF_OP_RLDSH:
9152 case DIF_OP_RLDSW:
9153 case DIF_OP_RLDUB:
9154 case DIF_OP_RLDUH:
9155 case DIF_OP_RLDUW:
9156 case DIF_OP_RLDX:
9157 if (r1 >= nregs)
9158 err += efunc(pc, "invalid register %u\n", r1);
9159 if (r2 != 0)
9160 err += efunc(pc, "non-zero reserved bits\n");
9161 if (rd >= nregs)
9162 err += efunc(pc, "invalid register %u\n", rd);
9163 if (rd == 0)
9164 err += efunc(pc, "cannot write to %r0\n");
9165 break;
9166 case DIF_OP_ULDSB:
9167 case DIF_OP_ULDSH:
9168 case DIF_OP_ULDSW:
9169 case DIF_OP_ULDUB:
9170 case DIF_OP_ULDUH:
9171 case DIF_OP_ULDUW:
9172 case DIF_OP_ULDX:
9173 if (r1 >= nregs)
9174 err += efunc(pc, "invalid register %u\n", r1);
9175 if (r2 != 0)
9176 err += efunc(pc, "non-zero reserved bits\n");
9177 if (rd >= nregs)
9178 err += efunc(pc, "invalid register %u\n", rd);
9179 if (rd == 0)
9180 err += efunc(pc, "cannot write to %r0\n");
9181 break;
9182 case DIF_OP_STB:
9183 case DIF_OP_STH:
9184 case DIF_OP_STW:
9185 case DIF_OP_STX:
9186 if (r1 >= nregs)
9187 err += efunc(pc, "invalid register %u\n", r1);
9188 if (r2 != 0)
9189 err += efunc(pc, "non-zero reserved bits\n");
9190 if (rd >= nregs)
9191 err += efunc(pc, "invalid register %u\n", rd);
9192 if (rd == 0)
9193 err += efunc(pc, "cannot write to 0 address\n");
9194 break;
9195 case DIF_OP_CMP:
9196 case DIF_OP_SCMP:
9197 if (r1 >= nregs)
9198 err += efunc(pc, "invalid register %u\n", r1);
9199 if (r2 >= nregs)
9200 err += efunc(pc, "invalid register %u\n", r2);
9201 if (rd != 0)
9202 err += efunc(pc, "non-zero reserved bits\n");
9203 break;
9204 case DIF_OP_TST:
9205 if (r1 >= nregs)
9206 err += efunc(pc, "invalid register %u\n", r1);
9207 if (r2 != 0 || rd != 0)
9208 err += efunc(pc, "non-zero reserved bits\n");
9209 break;
9210 case DIF_OP_BA:
9211 case DIF_OP_BE:
9212 case DIF_OP_BNE:
9213 case DIF_OP_BG:
9214 case DIF_OP_BGU:
9215 case DIF_OP_BGE:
9216 case DIF_OP_BGEU:
9217 case DIF_OP_BL:
9218 case DIF_OP_BLU:
9219 case DIF_OP_BLE:
9220 case DIF_OP_BLEU:
9221 if (label >= dp->dtdo_len) {
9222 err += efunc(pc, "invalid branch target %u\n",
9223 label);
9224 }
9225 if (label <= pc) {
9226 err += efunc(pc, "backward branch to %u\n",
9227 label);
9228 }
9229 break;
9230 case DIF_OP_RET:
9231 if (r1 != 0 || r2 != 0)
9232 err += efunc(pc, "non-zero reserved bits\n");
9233 if (rd >= nregs)
9234 err += efunc(pc, "invalid register %u\n", rd);
9235 break;
9236 case DIF_OP_NOP:
9237 case DIF_OP_POPTS:
9238 case DIF_OP_FLUSHTS:
9239 if (r1 != 0 || r2 != 0 || rd != 0)
9240 err += efunc(pc, "non-zero reserved bits\n");
9241 break;
9242 case DIF_OP_SETX:
9243 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9244 err += efunc(pc, "invalid integer ref %u\n",
9245 DIF_INSTR_INTEGER(instr));
9246 }
9247 if (rd >= nregs)
9248 err += efunc(pc, "invalid register %u\n", rd);
9249 if (rd == 0)
9250 err += efunc(pc, "cannot write to %r0\n");
9251 break;
9252 case DIF_OP_SETS:
9253 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9254 err += efunc(pc, "invalid string ref %u\n",
9255 DIF_INSTR_STRING(instr));
9256 }
9257 if (rd >= nregs)
9258 err += efunc(pc, "invalid register %u\n", rd);
9259 if (rd == 0)
9260 err += efunc(pc, "cannot write to %r0\n");
9261 break;
9262 case DIF_OP_LDGA:
9263 case DIF_OP_LDTA:
9264 if (r1 > DIF_VAR_ARRAY_MAX)
9265 err += efunc(pc, "invalid array %u\n", r1);
9266 if (r2 >= nregs)
9267 err += efunc(pc, "invalid register %u\n", r2);
9268 if (rd >= nregs)
9269 err += efunc(pc, "invalid register %u\n", rd);
9270 if (rd == 0)
9271 err += efunc(pc, "cannot write to %r0\n");
9272 break;
9273 case DIF_OP_LDGS:
9274 case DIF_OP_LDTS:
9275 case DIF_OP_LDLS:
9276 case DIF_OP_LDGAA:
9277 case DIF_OP_LDTAA:
9278 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9279 err += efunc(pc, "invalid variable %u\n", v);
9280 if (rd >= nregs)
9281 err += efunc(pc, "invalid register %u\n", rd);
9282 if (rd == 0)
9283 err += efunc(pc, "cannot write to %r0\n");
9284 break;
9285 case DIF_OP_STGS:
9286 case DIF_OP_STTS:
9287 case DIF_OP_STLS:
9288 case DIF_OP_STGAA:
9289 case DIF_OP_STTAA:
9290 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9291 err += efunc(pc, "invalid variable %u\n", v);
9292 if (rs >= nregs)
9293 err += efunc(pc, "invalid register %u\n", rd);
9294 break;
9295 case DIF_OP_CALL:
9296 if (subr > DIF_SUBR_MAX)
9297 err += efunc(pc, "invalid subr %u\n", subr);
9298 if (rd >= nregs)
9299 err += efunc(pc, "invalid register %u\n", rd);
9300 if (rd == 0)
9301 err += efunc(pc, "cannot write to %r0\n");
9302
9303 if (subr == DIF_SUBR_COPYOUT ||
9304 subr == DIF_SUBR_COPYOUTSTR) {
9305 dp->dtdo_destructive = 1;
9306 }
9307 break;
9308 case DIF_OP_PUSHTR:
9309 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9310 err += efunc(pc, "invalid ref type %u\n", type);
9311 if (r2 >= nregs)
9312 err += efunc(pc, "invalid register %u\n", r2);
9313 if (rs >= nregs)
9314 err += efunc(pc, "invalid register %u\n", rs);
9315 break;
9316 case DIF_OP_PUSHTV:
9317 if (type != DIF_TYPE_CTF)
9318 err += efunc(pc, "invalid val type %u\n", type);
9319 if (r2 >= nregs)
9320 err += efunc(pc, "invalid register %u\n", r2);
9321 if (rs >= nregs)
9322 err += efunc(pc, "invalid register %u\n", rs);
9323 break;
9324 default:
9325 err += efunc(pc, "invalid opcode %u\n",
9326 DIF_INSTR_OP(instr));
9327 }
9328 }
9329
9330 if (dp->dtdo_len != 0 &&
9331 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9332 err += efunc(dp->dtdo_len - 1,
9333 "expected 'ret' as last DIF instruction\n");
9334 }
9335
9336 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
9337 /*
9338 * If we're not returning by reference, the size must be either
9339 * 0 or the size of one of the base types.
9340 */
9341 switch (dp->dtdo_rtype.dtdt_size) {
9342 case 0:
9343 case sizeof (uint8_t):
9344 case sizeof (uint16_t):
9345 case sizeof (uint32_t):
9346 case sizeof (uint64_t):
9347 break;
9348
9349 default:
9350 err += efunc(dp->dtdo_len - 1, "bad return size\n");
9351 }
9352 }
9353
9354 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9355 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9356 dtrace_diftype_t *vt, *et;
9357 #if !defined(__APPLE__) /* Quiet compiler warnings */
9358 uint_t id, ndx;
9359 #else
9360 uint_t id;
9361 int ndx;
9362 #endif /* __APPLE__ */
9363
9364 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9365 v->dtdv_scope != DIFV_SCOPE_THREAD &&
9366 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9367 err += efunc(i, "unrecognized variable scope %d\n",
9368 v->dtdv_scope);
9369 break;
9370 }
9371
9372 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9373 v->dtdv_kind != DIFV_KIND_SCALAR) {
9374 err += efunc(i, "unrecognized variable type %d\n",
9375 v->dtdv_kind);
9376 break;
9377 }
9378
9379 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9380 err += efunc(i, "%d exceeds variable id limit\n", id);
9381 break;
9382 }
9383
9384 if (id < DIF_VAR_OTHER_UBASE)
9385 continue;
9386
9387 /*
9388 * For user-defined variables, we need to check that this
9389 * definition is identical to any previous definition that we
9390 * encountered.
9391 */
9392 ndx = id - DIF_VAR_OTHER_UBASE;
9393
9394 switch (v->dtdv_scope) {
9395 case DIFV_SCOPE_GLOBAL:
9396 if (ndx < vstate->dtvs_nglobals) {
9397 dtrace_statvar_t *svar;
9398
9399 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9400 existing = &svar->dtsv_var;
9401 }
9402
9403 break;
9404
9405 case DIFV_SCOPE_THREAD:
9406 if (ndx < vstate->dtvs_ntlocals)
9407 existing = &vstate->dtvs_tlocals[ndx];
9408 break;
9409
9410 case DIFV_SCOPE_LOCAL:
9411 if (ndx < vstate->dtvs_nlocals) {
9412 dtrace_statvar_t *svar;
9413
9414 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9415 existing = &svar->dtsv_var;
9416 }
9417
9418 break;
9419 }
9420
9421 vt = &v->dtdv_type;
9422
9423 if (vt->dtdt_flags & DIF_TF_BYREF) {
9424 if (vt->dtdt_size == 0) {
9425 err += efunc(i, "zero-sized variable\n");
9426 break;
9427 }
9428
9429 if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
9430 vt->dtdt_size > dtrace_global_maxsize) {
9431 err += efunc(i, "oversized by-ref global\n");
9432 break;
9433 }
9434 }
9435
9436 if (existing == NULL || existing->dtdv_id == 0)
9437 continue;
9438
9439 ASSERT(existing->dtdv_id == v->dtdv_id);
9440 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9441
9442 if (existing->dtdv_kind != v->dtdv_kind)
9443 err += efunc(i, "%d changed variable kind\n", id);
9444
9445 et = &existing->dtdv_type;
9446
9447 if (vt->dtdt_flags != et->dtdt_flags) {
9448 err += efunc(i, "%d changed variable type flags\n", id);
9449 break;
9450 }
9451
9452 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9453 err += efunc(i, "%d changed variable type size\n", id);
9454 break;
9455 }
9456 }
9457
9458 return (err);
9459 }
9460
9461 /*
9462 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
9463 * are much more constrained than normal DIFOs. Specifically, they may
9464 * not:
9465 *
9466 * 1. Make calls to subroutines other than copyin(), copyinstr() or
9467 * miscellaneous string routines
9468 * 2. Access DTrace variables other than the args[] array, and the
9469 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9470 * 3. Have thread-local variables.
9471 * 4. Have dynamic variables.
9472 */
9473 static int
9474 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9475 {
9476 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9477 int err = 0;
9478 uint_t pc;
9479
9480 for (pc = 0; pc < dp->dtdo_len; pc++) {
9481 dif_instr_t instr = dp->dtdo_buf[pc];
9482
9483 uint_t v = DIF_INSTR_VAR(instr);
9484 uint_t subr = DIF_INSTR_SUBR(instr);
9485 uint_t op = DIF_INSTR_OP(instr);
9486
9487 switch (op) {
9488 case DIF_OP_OR:
9489 case DIF_OP_XOR:
9490 case DIF_OP_AND:
9491 case DIF_OP_SLL:
9492 case DIF_OP_SRL:
9493 case DIF_OP_SRA:
9494 case DIF_OP_SUB:
9495 case DIF_OP_ADD:
9496 case DIF_OP_MUL:
9497 case DIF_OP_SDIV:
9498 case DIF_OP_UDIV:
9499 case DIF_OP_SREM:
9500 case DIF_OP_UREM:
9501 case DIF_OP_COPYS:
9502 case DIF_OP_NOT:
9503 case DIF_OP_MOV:
9504 case DIF_OP_RLDSB:
9505 case DIF_OP_RLDSH:
9506 case DIF_OP_RLDSW:
9507 case DIF_OP_RLDUB:
9508 case DIF_OP_RLDUH:
9509 case DIF_OP_RLDUW:
9510 case DIF_OP_RLDX:
9511 case DIF_OP_ULDSB:
9512 case DIF_OP_ULDSH:
9513 case DIF_OP_ULDSW:
9514 case DIF_OP_ULDUB:
9515 case DIF_OP_ULDUH:
9516 case DIF_OP_ULDUW:
9517 case DIF_OP_ULDX:
9518 case DIF_OP_STB:
9519 case DIF_OP_STH:
9520 case DIF_OP_STW:
9521 case DIF_OP_STX:
9522 case DIF_OP_ALLOCS:
9523 case DIF_OP_CMP:
9524 case DIF_OP_SCMP:
9525 case DIF_OP_TST:
9526 case DIF_OP_BA:
9527 case DIF_OP_BE:
9528 case DIF_OP_BNE:
9529 case DIF_OP_BG:
9530 case DIF_OP_BGU:
9531 case DIF_OP_BGE:
9532 case DIF_OP_BGEU:
9533 case DIF_OP_BL:
9534 case DIF_OP_BLU:
9535 case DIF_OP_BLE:
9536 case DIF_OP_BLEU:
9537 case DIF_OP_RET:
9538 case DIF_OP_NOP:
9539 case DIF_OP_POPTS:
9540 case DIF_OP_FLUSHTS:
9541 case DIF_OP_SETX:
9542 case DIF_OP_SETS:
9543 case DIF_OP_LDGA:
9544 case DIF_OP_LDLS:
9545 case DIF_OP_STGS:
9546 case DIF_OP_STLS:
9547 case DIF_OP_PUSHTR:
9548 case DIF_OP_PUSHTV:
9549 break;
9550
9551 case DIF_OP_LDGS:
9552 if (v >= DIF_VAR_OTHER_UBASE)
9553 break;
9554
9555 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9556 break;
9557
9558 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9559 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9560 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9561 v == DIF_VAR_UID || v == DIF_VAR_GID)
9562 break;
9563
9564 err += efunc(pc, "illegal variable %u\n", v);
9565 break;
9566
9567 case DIF_OP_LDTA:
9568 case DIF_OP_LDTS:
9569 case DIF_OP_LDGAA:
9570 case DIF_OP_LDTAA:
9571 err += efunc(pc, "illegal dynamic variable load\n");
9572 break;
9573
9574 case DIF_OP_STTS:
9575 case DIF_OP_STGAA:
9576 case DIF_OP_STTAA:
9577 err += efunc(pc, "illegal dynamic variable store\n");
9578 break;
9579
9580 case DIF_OP_CALL:
9581 if (subr == DIF_SUBR_ALLOCA ||
9582 subr == DIF_SUBR_BCOPY ||
9583 subr == DIF_SUBR_COPYIN ||
9584 subr == DIF_SUBR_COPYINTO ||
9585 subr == DIF_SUBR_COPYINSTR ||
9586 subr == DIF_SUBR_INDEX ||
9587 subr == DIF_SUBR_INET_NTOA ||
9588 subr == DIF_SUBR_INET_NTOA6 ||
9589 subr == DIF_SUBR_INET_NTOP ||
9590 subr == DIF_SUBR_LLTOSTR ||
9591 subr == DIF_SUBR_RINDEX ||
9592 subr == DIF_SUBR_STRCHR ||
9593 subr == DIF_SUBR_STRJOIN ||
9594 subr == DIF_SUBR_STRRCHR ||
9595 subr == DIF_SUBR_STRSTR ||
9596 #if defined(__APPLE__)
9597 subr == DIF_SUBR_COREPROFILE ||
9598 #endif /* __APPLE__ */
9599 subr == DIF_SUBR_HTONS ||
9600 subr == DIF_SUBR_HTONL ||
9601 subr == DIF_SUBR_HTONLL ||
9602 subr == DIF_SUBR_NTOHS ||
9603 subr == DIF_SUBR_NTOHL ||
9604 subr == DIF_SUBR_NTOHLL)
9605 break;
9606
9607 err += efunc(pc, "invalid subr %u\n", subr);
9608 break;
9609
9610 default:
9611 err += efunc(pc, "invalid opcode %u\n",
9612 DIF_INSTR_OP(instr));
9613 }
9614 }
9615
9616 return (err);
9617 }
9618
9619 /*
9620 * Returns 1 if the expression in the DIF object can be cached on a per-thread
9621 * basis; 0 if not.
9622 */
9623 static int
9624 dtrace_difo_cacheable(dtrace_difo_t *dp)
9625 {
9626 #if !defined(__APPLE__) /* Quiet compiler warnings */
9627 int i;
9628 #else
9629 uint_t i;
9630 #endif /* __APPLE__ */
9631
9632 if (dp == NULL)
9633 return (0);
9634
9635 for (i = 0; i < dp->dtdo_varlen; i++) {
9636 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9637
9638 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9639 continue;
9640
9641 switch (v->dtdv_id) {
9642 case DIF_VAR_CURTHREAD:
9643 case DIF_VAR_PID:
9644 case DIF_VAR_TID:
9645 case DIF_VAR_EXECNAME:
9646 case DIF_VAR_ZONENAME:
9647 break;
9648
9649 default:
9650 return (0);
9651 }
9652 }
9653
9654 /*
9655 * This DIF object may be cacheable. Now we need to look for any
9656 * array loading instructions, any memory loading instructions, or
9657 * any stores to thread-local variables.
9658 */
9659 for (i = 0; i < dp->dtdo_len; i++) {
9660 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9661
9662 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9663 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9664 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9665 op == DIF_OP_LDGA || op == DIF_OP_STTS)
9666 return (0);
9667 }
9668
9669 return (1);
9670 }
9671
9672 static void
9673 dtrace_difo_hold(dtrace_difo_t *dp)
9674 {
9675 #if !defined(__APPLE__) /* Quiet compiler warnings */
9676 int i;
9677 #else
9678 uint_t i;
9679 #endif /* __APPLE__ */
9680
9681 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9682
9683 dp->dtdo_refcnt++;
9684 ASSERT(dp->dtdo_refcnt != 0);
9685
9686 /*
9687 * We need to check this DIF object for references to the variable
9688 * DIF_VAR_VTIMESTAMP.
9689 */
9690 for (i = 0; i < dp->dtdo_varlen; i++) {
9691 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9692
9693 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9694 continue;
9695
9696 if (dtrace_vtime_references++ == 0)
9697 dtrace_vtime_enable();
9698 }
9699 }
9700
9701 /*
9702 * This routine calculates the dynamic variable chunksize for a given DIF
9703 * object. The calculation is not fool-proof, and can probably be tricked by
9704 * malicious DIF -- but it works for all compiler-generated DIF. Because this
9705 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9706 * if a dynamic variable size exceeds the chunksize.
9707 */
9708 static void
9709 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9710 {
9711 #if !defined(__APPLE__) /* Quiet compiler warnings */
9712 uint64_t sval;
9713 #else
9714 uint64_t sval = 0;
9715 #endif /* __APPLE__ */
9716 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9717 const dif_instr_t *text = dp->dtdo_buf;
9718 uint_t pc, srd = 0;
9719 uint_t ttop = 0;
9720 size_t size, ksize;
9721 uint_t id, i;
9722
9723 for (pc = 0; pc < dp->dtdo_len; pc++) {
9724 dif_instr_t instr = text[pc];
9725 uint_t op = DIF_INSTR_OP(instr);
9726 uint_t rd = DIF_INSTR_RD(instr);
9727 uint_t r1 = DIF_INSTR_R1(instr);
9728 uint_t nkeys = 0;
9729 uchar_t scope;
9730
9731 dtrace_key_t *key = tupregs;
9732
9733 switch (op) {
9734 case DIF_OP_SETX:
9735 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9736 srd = rd;
9737 continue;
9738
9739 case DIF_OP_STTS:
9740 key = &tupregs[DIF_DTR_NREGS];
9741 key[0].dttk_size = 0;
9742 key[1].dttk_size = 0;
9743 nkeys = 2;
9744 scope = DIFV_SCOPE_THREAD;
9745 break;
9746
9747 case DIF_OP_STGAA:
9748 case DIF_OP_STTAA:
9749 nkeys = ttop;
9750
9751 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9752 key[nkeys++].dttk_size = 0;
9753
9754 key[nkeys++].dttk_size = 0;
9755
9756 if (op == DIF_OP_STTAA) {
9757 scope = DIFV_SCOPE_THREAD;
9758 } else {
9759 scope = DIFV_SCOPE_GLOBAL;
9760 }
9761
9762 break;
9763
9764 case DIF_OP_PUSHTR:
9765 if (ttop == DIF_DTR_NREGS)
9766 return;
9767
9768 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9769 /*
9770 * If the register for the size of the "pushtr"
9771 * is %r0 (or the value is 0) and the type is
9772 * a string, we'll use the system-wide default
9773 * string size.
9774 */
9775 tupregs[ttop++].dttk_size =
9776 dtrace_strsize_default;
9777 } else {
9778 if (srd == 0)
9779 return;
9780
9781 tupregs[ttop++].dttk_size = sval;
9782 }
9783
9784 break;
9785
9786 case DIF_OP_PUSHTV:
9787 if (ttop == DIF_DTR_NREGS)
9788 return;
9789
9790 tupregs[ttop++].dttk_size = 0;
9791 break;
9792
9793 case DIF_OP_FLUSHTS:
9794 ttop = 0;
9795 break;
9796
9797 case DIF_OP_POPTS:
9798 if (ttop != 0)
9799 ttop--;
9800 break;
9801 }
9802
9803 sval = 0;
9804 srd = 0;
9805
9806 if (nkeys == 0)
9807 continue;
9808
9809 /*
9810 * We have a dynamic variable allocation; calculate its size.
9811 */
9812 for (ksize = 0, i = 0; i < nkeys; i++)
9813 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9814
9815 size = sizeof (dtrace_dynvar_t);
9816 size += sizeof (dtrace_key_t) * (nkeys - 1);
9817 size += ksize;
9818
9819 /*
9820 * Now we need to determine the size of the stored data.
9821 */
9822 id = DIF_INSTR_VAR(instr);
9823
9824 for (i = 0; i < dp->dtdo_varlen; i++) {
9825 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9826
9827 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9828 size += v->dtdv_type.dtdt_size;
9829 break;
9830 }
9831 }
9832
9833 if (i == dp->dtdo_varlen)
9834 return;
9835
9836 /*
9837 * We have the size. If this is larger than the chunk size
9838 * for our dynamic variable state, reset the chunk size.
9839 */
9840 size = P2ROUNDUP(size, sizeof (uint64_t));
9841
9842 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9843 vstate->dtvs_dynvars.dtds_chunksize = size;
9844 }
9845 }
9846
9847 static void
9848 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9849 {
9850 #if !defined(__APPLE__) /* Quiet compiler warnings */
9851 int i, oldsvars, osz, nsz, otlocals, ntlocals;
9852 uint_t id;
9853 #else
9854 int oldsvars, osz, nsz, otlocals, ntlocals;
9855 uint_t i, id;
9856 #endif /* __APPLE__ */
9857
9858 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9859 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9860
9861 for (i = 0; i < dp->dtdo_varlen; i++) {
9862 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9863 #if !defined(__APPLE__) /* Quiet compiler warnings */
9864 dtrace_statvar_t *svar, ***svarp;
9865 #else
9866 dtrace_statvar_t *svar;
9867 dtrace_statvar_t ***svarp = NULL;
9868 #endif /* __APPLE__ */
9869 size_t dsize = 0;
9870 uint8_t scope = v->dtdv_scope;
9871 int *np = (int *)NULL;
9872
9873 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9874 continue;
9875
9876 id -= DIF_VAR_OTHER_UBASE;
9877
9878 switch (scope) {
9879 case DIFV_SCOPE_THREAD:
9880 #if !defined(__APPLE__) /* Quiet compiler warnings */
9881 while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9882 #else
9883 while (id >= (uint_t)(otlocals = vstate->dtvs_ntlocals)) {
9884 #endif /* __APPLE__ */
9885 dtrace_difv_t *tlocals;
9886
9887 if ((ntlocals = (otlocals << 1)) == 0)
9888 ntlocals = 1;
9889
9890 osz = otlocals * sizeof (dtrace_difv_t);
9891 nsz = ntlocals * sizeof (dtrace_difv_t);
9892
9893 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9894
9895 if (osz != 0) {
9896 bcopy(vstate->dtvs_tlocals,
9897 tlocals, osz);
9898 kmem_free(vstate->dtvs_tlocals, osz);
9899 }
9900
9901 vstate->dtvs_tlocals = tlocals;
9902 vstate->dtvs_ntlocals = ntlocals;
9903 }
9904
9905 vstate->dtvs_tlocals[id] = *v;
9906 continue;
9907
9908 case DIFV_SCOPE_LOCAL:
9909 np = &vstate->dtvs_nlocals;
9910 svarp = &vstate->dtvs_locals;
9911
9912 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9913 dsize = (int)NCPU * (v->dtdv_type.dtdt_size +
9914 sizeof (uint64_t));
9915 else
9916 dsize = (int)NCPU * sizeof (uint64_t);
9917
9918 break;
9919
9920 case DIFV_SCOPE_GLOBAL:
9921 np = &vstate->dtvs_nglobals;
9922 svarp = &vstate->dtvs_globals;
9923
9924 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9925 dsize = v->dtdv_type.dtdt_size +
9926 sizeof (uint64_t);
9927
9928 break;
9929
9930 default:
9931 ASSERT(0);
9932 }
9933
9934 #if !defined(__APPLE__) /* Quiet compiler warnings */
9935 while (id >= (oldsvars = *np)) {
9936 #else
9937 while (id >= (uint_t)(oldsvars = *np)) {
9938 #endif /* __APPLE__ */
9939 dtrace_statvar_t **statics;
9940 int newsvars, oldsize, newsize;
9941
9942 if ((newsvars = (oldsvars << 1)) == 0)
9943 newsvars = 1;
9944
9945 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9946 newsize = newsvars * sizeof (dtrace_statvar_t *);
9947
9948 statics = kmem_zalloc(newsize, KM_SLEEP);
9949
9950 if (oldsize != 0) {
9951 bcopy(*svarp, statics, oldsize);
9952 kmem_free(*svarp, oldsize);
9953 }
9954
9955 *svarp = statics;
9956 *np = newsvars;
9957 }
9958
9959 if ((svar = (*svarp)[id]) == NULL) {
9960 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9961 svar->dtsv_var = *v;
9962
9963 if ((svar->dtsv_size = dsize) != 0) {
9964 svar->dtsv_data = (uint64_t)(uintptr_t)
9965 kmem_zalloc(dsize, KM_SLEEP);
9966 }
9967
9968 (*svarp)[id] = svar;
9969 }
9970
9971 svar->dtsv_refcnt++;
9972 }
9973
9974 dtrace_difo_chunksize(dp, vstate);
9975 dtrace_difo_hold(dp);
9976 }
9977
9978 static dtrace_difo_t *
9979 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9980 {
9981 dtrace_difo_t *new;
9982 size_t sz;
9983
9984 ASSERT(dp->dtdo_buf != NULL);
9985 ASSERT(dp->dtdo_refcnt != 0);
9986
9987 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9988
9989 ASSERT(dp->dtdo_buf != NULL);
9990 sz = dp->dtdo_len * sizeof (dif_instr_t);
9991 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9992 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9993 new->dtdo_len = dp->dtdo_len;
9994
9995 if (dp->dtdo_strtab != NULL) {
9996 ASSERT(dp->dtdo_strlen != 0);
9997 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9998 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9999 new->dtdo_strlen = dp->dtdo_strlen;
10000 }
10001
10002 if (dp->dtdo_inttab != NULL) {
10003 ASSERT(dp->dtdo_intlen != 0);
10004 sz = dp->dtdo_intlen * sizeof (uint64_t);
10005 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10006 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10007 new->dtdo_intlen = dp->dtdo_intlen;
10008 }
10009
10010 if (dp->dtdo_vartab != NULL) {
10011 ASSERT(dp->dtdo_varlen != 0);
10012 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10013 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10014 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10015 new->dtdo_varlen = dp->dtdo_varlen;
10016 }
10017
10018 dtrace_difo_init(new, vstate);
10019 return (new);
10020 }
10021
10022 static void
10023 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10024 {
10025 #if !defined(__APPLE__) /* Quiet compiler warnings */
10026 int i;
10027 #else
10028 uint_t i;
10029 #endif /* __APPLE__ */
10030
10031 ASSERT(dp->dtdo_refcnt == 0);
10032
10033 for (i = 0; i < dp->dtdo_varlen; i++) {
10034 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10035 #if !defined(__APPLE__) /* Quiet compiler warnings */
10036 dtrace_statvar_t *svar, **svarp;
10037 uint_t id;
10038 uint8_t scope = v->dtdv_scope;
10039 int *np;
10040 #else
10041 dtrace_statvar_t *svar;
10042 dtrace_statvar_t **svarp = NULL;
10043 uint_t id;
10044 uint8_t scope = v->dtdv_scope;
10045 int *np = NULL;
10046 #endif /* __APPLE__ */
10047
10048 switch (scope) {
10049 case DIFV_SCOPE_THREAD:
10050 continue;
10051
10052 case DIFV_SCOPE_LOCAL:
10053 np = &vstate->dtvs_nlocals;
10054 svarp = vstate->dtvs_locals;
10055 break;
10056
10057 case DIFV_SCOPE_GLOBAL:
10058 np = &vstate->dtvs_nglobals;
10059 svarp = vstate->dtvs_globals;
10060 break;
10061
10062 default:
10063 ASSERT(0);
10064 }
10065
10066 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10067 continue;
10068
10069 id -= DIF_VAR_OTHER_UBASE;
10070
10071 #if !defined(__APPLE__) /* Quiet compiler warnings */
10072 ASSERT(id < *np);
10073 #else
10074 ASSERT(id < (uint_t)*np);
10075 #endif /* __APPLE__ */
10076
10077 svar = svarp[id];
10078 ASSERT(svar != NULL);
10079 ASSERT(svar->dtsv_refcnt > 0);
10080
10081 if (--svar->dtsv_refcnt > 0)
10082 continue;
10083
10084 if (svar->dtsv_size != 0) {
10085 ASSERT(svar->dtsv_data != NULL);
10086 kmem_free((void *)(uintptr_t)svar->dtsv_data,
10087 svar->dtsv_size);
10088 }
10089
10090 kmem_free(svar, sizeof (dtrace_statvar_t));
10091 svarp[id] = NULL;
10092 }
10093
10094 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10095 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10096 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10097 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10098
10099 kmem_free(dp, sizeof (dtrace_difo_t));
10100 }
10101
10102 static void
10103 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10104 {
10105 #if !defined(__APPLE__) /* Quiet compiler warnings */
10106 int i;
10107 #else
10108 uint_t i;
10109 #endif /* __APPLE__ */
10110
10111 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10112 ASSERT(dp->dtdo_refcnt != 0);
10113
10114 for (i = 0; i < dp->dtdo_varlen; i++) {
10115 dtrace_difv_t *v = &dp->dtdo_vartab[i];
10116
10117 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10118 continue;
10119
10120 ASSERT(dtrace_vtime_references > 0);
10121 if (--dtrace_vtime_references == 0)
10122 dtrace_vtime_disable();
10123 }
10124
10125 if (--dp->dtdo_refcnt == 0)
10126 dtrace_difo_destroy(dp, vstate);
10127 }
10128
10129 /*
10130 * DTrace Format Functions
10131 */
10132 static uint16_t
10133 dtrace_format_add(dtrace_state_t *state, char *str)
10134 {
10135 char *fmt, **new;
10136 uint16_t ndx, len = strlen(str) + 1;
10137
10138 fmt = kmem_zalloc(len, KM_SLEEP);
10139 bcopy(str, fmt, len);
10140
10141 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10142 if (state->dts_formats[ndx] == NULL) {
10143 state->dts_formats[ndx] = fmt;
10144 return (ndx + 1);
10145 }
10146 }
10147
10148 if (state->dts_nformats == USHRT_MAX) {
10149 /*
10150 * This is only likely if a denial-of-service attack is being
10151 * attempted. As such, it's okay to fail silently here.
10152 */
10153 kmem_free(fmt, len);
10154 return (0);
10155 }
10156
10157 /*
10158 * For simplicity, we always resize the formats array to be exactly the
10159 * number of formats.
10160 */
10161 ndx = state->dts_nformats++;
10162 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10163
10164 if (state->dts_formats != NULL) {
10165 ASSERT(ndx != 0);
10166 bcopy(state->dts_formats, new, ndx * sizeof (char *));
10167 kmem_free(state->dts_formats, ndx * sizeof (char *));
10168 }
10169
10170 state->dts_formats = new;
10171 state->dts_formats[ndx] = fmt;
10172
10173 return (ndx + 1);
10174 }
10175
10176 static void
10177 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10178 {
10179 char *fmt;
10180
10181 ASSERT(state->dts_formats != NULL);
10182 ASSERT(format <= state->dts_nformats);
10183 ASSERT(state->dts_formats[format - 1] != NULL);
10184
10185 fmt = state->dts_formats[format - 1];
10186 kmem_free(fmt, strlen(fmt) + 1);
10187 state->dts_formats[format - 1] = NULL;
10188 }
10189
10190 static void
10191 dtrace_format_destroy(dtrace_state_t *state)
10192 {
10193 int i;
10194
10195 if (state->dts_nformats == 0) {
10196 ASSERT(state->dts_formats == NULL);
10197 return;
10198 }
10199
10200 ASSERT(state->dts_formats != NULL);
10201
10202 for (i = 0; i < state->dts_nformats; i++) {
10203 char *fmt = state->dts_formats[i];
10204
10205 if (fmt == NULL)
10206 continue;
10207
10208 kmem_free(fmt, strlen(fmt) + 1);
10209 }
10210
10211 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10212 state->dts_nformats = 0;
10213 state->dts_formats = NULL;
10214 }
10215
10216 /*
10217 * DTrace Predicate Functions
10218 */
10219 static dtrace_predicate_t *
10220 dtrace_predicate_create(dtrace_difo_t *dp)
10221 {
10222 dtrace_predicate_t *pred;
10223
10224 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10225 ASSERT(dp->dtdo_refcnt != 0);
10226
10227 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10228 pred->dtp_difo = dp;
10229 pred->dtp_refcnt = 1;
10230
10231 if (!dtrace_difo_cacheable(dp))
10232 return (pred);
10233
10234 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10235 /*
10236 * This is only theoretically possible -- we have had 2^32
10237 * cacheable predicates on this machine. We cannot allow any
10238 * more predicates to become cacheable: as unlikely as it is,
10239 * there may be a thread caching a (now stale) predicate cache
10240 * ID. (N.B.: the temptation is being successfully resisted to
10241 * have this cmn_err() "Holy shit -- we executed this code!")
10242 */
10243 return (pred);
10244 }
10245
10246 pred->dtp_cacheid = dtrace_predcache_id++;
10247
10248 return (pred);
10249 }
10250
10251 static void
10252 dtrace_predicate_hold(dtrace_predicate_t *pred)
10253 {
10254 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10255 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10256 ASSERT(pred->dtp_refcnt > 0);
10257
10258 pred->dtp_refcnt++;
10259 }
10260
10261 static void
10262 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10263 {
10264 dtrace_difo_t *dp = pred->dtp_difo;
10265 #pragma unused(dp) /* __APPLE__ */
10266
10267 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10268 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10269 ASSERT(pred->dtp_refcnt > 0);
10270
10271 if (--pred->dtp_refcnt == 0) {
10272 dtrace_difo_release(pred->dtp_difo, vstate);
10273 kmem_free(pred, sizeof (dtrace_predicate_t));
10274 }
10275 }
10276
10277 /*
10278 * DTrace Action Description Functions
10279 */
10280 static dtrace_actdesc_t *
10281 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10282 uint64_t uarg, uint64_t arg)
10283 {
10284 dtrace_actdesc_t *act;
10285
10286 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10287 arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10288
10289 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10290 act->dtad_kind = kind;
10291 act->dtad_ntuple = ntuple;
10292 act->dtad_uarg = uarg;
10293 act->dtad_arg = arg;
10294 act->dtad_refcnt = 1;
10295
10296 return (act);
10297 }
10298
10299 static void
10300 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10301 {
10302 ASSERT(act->dtad_refcnt >= 1);
10303 act->dtad_refcnt++;
10304 }
10305
10306 static void
10307 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10308 {
10309 dtrace_actkind_t kind = act->dtad_kind;
10310 dtrace_difo_t *dp;
10311
10312 ASSERT(act->dtad_refcnt >= 1);
10313
10314 if (--act->dtad_refcnt != 0)
10315 return;
10316
10317 if ((dp = act->dtad_difo) != NULL)
10318 dtrace_difo_release(dp, vstate);
10319
10320 if (DTRACEACT_ISPRINTFLIKE(kind)) {
10321 char *str = (char *)(uintptr_t)act->dtad_arg;
10322
10323 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10324 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10325
10326 if (str != NULL)
10327 kmem_free(str, strlen(str) + 1);
10328 }
10329
10330 kmem_free(act, sizeof (dtrace_actdesc_t));
10331 }
10332
10333 /*
10334 * DTrace ECB Functions
10335 */
10336 static dtrace_ecb_t *
10337 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10338 {
10339 dtrace_ecb_t *ecb;
10340 dtrace_epid_t epid;
10341
10342 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10343
10344 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10345 ecb->dte_predicate = NULL;
10346 ecb->dte_probe = probe;
10347
10348 /*
10349 * The default size is the size of the default action: recording
10350 * the epid.
10351 */
10352 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
10353 ecb->dte_alignment = sizeof (dtrace_epid_t);
10354
10355 epid = state->dts_epid++;
10356
10357 #if !defined(__APPLE__) /* Quiet compiler warnings */
10358 if (epid - 1 >= state->dts_necbs) {
10359 #else
10360 if (epid - 1 >= (dtrace_epid_t)state->dts_necbs) {
10361 #endif /* __APPLE__ */
10362 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10363 int necbs = state->dts_necbs << 1;
10364
10365 #if !defined(__APPLE__) /* Quiet compiler warnings */
10366 ASSERT(epid == state->dts_necbs + 1);
10367 #else
10368 ASSERT(epid == (dtrace_epid_t)state->dts_necbs + 1);
10369 #endif /* __APPLE__ */
10370
10371 if (necbs == 0) {
10372 ASSERT(oecbs == NULL);
10373 necbs = 1;
10374 }
10375
10376 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10377
10378 if (oecbs != NULL)
10379 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10380
10381 dtrace_membar_producer();
10382 state->dts_ecbs = ecbs;
10383
10384 if (oecbs != NULL) {
10385 /*
10386 * If this state is active, we must dtrace_sync()
10387 * before we can free the old dts_ecbs array: we're
10388 * coming in hot, and there may be active ring
10389 * buffer processing (which indexes into the dts_ecbs
10390 * array) on another CPU.
10391 */
10392 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10393 dtrace_sync();
10394
10395 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10396 }
10397
10398 dtrace_membar_producer();
10399 state->dts_necbs = necbs;
10400 }
10401
10402 ecb->dte_state = state;
10403
10404 ASSERT(state->dts_ecbs[epid - 1] == NULL);
10405 dtrace_membar_producer();
10406 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10407
10408 return (ecb);
10409 }
10410
10411 static int
10412 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10413 {
10414 dtrace_probe_t *probe = ecb->dte_probe;
10415
10416 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
10417 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10418 ASSERT(ecb->dte_next == NULL);
10419
10420 if (probe == NULL) {
10421 /*
10422 * This is the NULL probe -- there's nothing to do.
10423 */
10424 return(0);
10425 }
10426
10427 if (probe->dtpr_ecb == NULL) {
10428 dtrace_provider_t *prov = probe->dtpr_provider;
10429
10430 /*
10431 * We're the first ECB on this probe.
10432 */
10433 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10434
10435 if (ecb->dte_predicate != NULL)
10436 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10437
10438 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10439 probe->dtpr_id, probe->dtpr_arg));
10440 } else {
10441 /*
10442 * This probe is already active. Swing the last pointer to
10443 * point to the new ECB, and issue a dtrace_sync() to assure
10444 * that all CPUs have seen the change.
10445 */
10446 ASSERT(probe->dtpr_ecb_last != NULL);
10447 probe->dtpr_ecb_last->dte_next = ecb;
10448 probe->dtpr_ecb_last = ecb;
10449 probe->dtpr_predcache = 0;
10450
10451 dtrace_sync();
10452 return(0);
10453 }
10454 }
10455
10456 static void
10457 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10458 {
10459 uint32_t maxalign = sizeof (dtrace_epid_t);
10460 uint32_t align = sizeof (uint8_t), offs, diff;
10461 dtrace_action_t *act;
10462 int wastuple = 0;
10463 uint32_t aggbase = UINT32_MAX;
10464 dtrace_state_t *state = ecb->dte_state;
10465
10466 /*
10467 * If we record anything, we always record the epid. (And we always
10468 * record it first.)
10469 */
10470 offs = sizeof (dtrace_epid_t);
10471 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
10472
10473 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10474 dtrace_recdesc_t *rec = &act->dta_rec;
10475
10476 if ((align = rec->dtrd_alignment) > maxalign)
10477 maxalign = align;
10478
10479 if (!wastuple && act->dta_intuple) {
10480 /*
10481 * This is the first record in a tuple. Align the
10482 * offset to be at offset 4 in an 8-byte aligned
10483 * block.
10484 */
10485 diff = offs + sizeof (dtrace_aggid_t);
10486
10487 if ((diff = (diff & (sizeof (uint64_t) - 1))))
10488 offs += sizeof (uint64_t) - diff;
10489
10490 aggbase = offs - sizeof (dtrace_aggid_t);
10491 ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
10492 }
10493
10494 /*LINTED*/
10495 if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
10496 /*
10497 * The current offset is not properly aligned; align it.
10498 */
10499 offs += align - diff;
10500 }
10501
10502 rec->dtrd_offset = offs;
10503
10504 if (offs + rec->dtrd_size > ecb->dte_needed) {
10505 ecb->dte_needed = offs + rec->dtrd_size;
10506
10507 if (ecb->dte_needed > state->dts_needed)
10508 state->dts_needed = ecb->dte_needed;
10509 }
10510
10511 if (DTRACEACT_ISAGG(act->dta_kind)) {
10512 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10513 dtrace_action_t *first = agg->dtag_first, *prev;
10514
10515 ASSERT(rec->dtrd_size != 0 && first != NULL);
10516 ASSERT(wastuple);
10517 ASSERT(aggbase != UINT32_MAX);
10518
10519 agg->dtag_base = aggbase;
10520
10521 while ((prev = first->dta_prev) != NULL &&
10522 DTRACEACT_ISAGG(prev->dta_kind)) {
10523 agg = (dtrace_aggregation_t *)prev;
10524 first = agg->dtag_first;
10525 }
10526
10527 if (prev != NULL) {
10528 offs = prev->dta_rec.dtrd_offset +
10529 prev->dta_rec.dtrd_size;
10530 } else {
10531 offs = sizeof (dtrace_epid_t);
10532 }
10533 wastuple = 0;
10534 } else {
10535 if (!act->dta_intuple)
10536 ecb->dte_size = offs + rec->dtrd_size;
10537
10538 offs += rec->dtrd_size;
10539 }
10540
10541 wastuple = act->dta_intuple;
10542 }
10543
10544 if ((act = ecb->dte_action) != NULL &&
10545 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10546 ecb->dte_size == sizeof (dtrace_epid_t)) {
10547 /*
10548 * If the size is still sizeof (dtrace_epid_t), then all
10549 * actions store no data; set the size to 0.
10550 */
10551 ecb->dte_alignment = maxalign;
10552 ecb->dte_size = 0;
10553
10554 /*
10555 * If the needed space is still sizeof (dtrace_epid_t), then
10556 * all actions need no additional space; set the needed
10557 * size to 0.
10558 */
10559 if (ecb->dte_needed == sizeof (dtrace_epid_t))
10560 ecb->dte_needed = 0;
10561
10562 return;
10563 }
10564
10565 /*
10566 * Set our alignment, and make sure that the dte_size and dte_needed
10567 * are aligned to the size of an EPID.
10568 */
10569 ecb->dte_alignment = maxalign;
10570 ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
10571 ~(sizeof (dtrace_epid_t) - 1);
10572 ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
10573 ~(sizeof (dtrace_epid_t) - 1);
10574 ASSERT(ecb->dte_size <= ecb->dte_needed);
10575 }
10576
10577 static dtrace_action_t *
10578 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10579 {
10580 dtrace_aggregation_t *agg;
10581 size_t size = sizeof (uint64_t);
10582 int ntuple = desc->dtad_ntuple;
10583 dtrace_action_t *act;
10584 dtrace_recdesc_t *frec;
10585 dtrace_aggid_t aggid;
10586 dtrace_state_t *state = ecb->dte_state;
10587
10588 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10589 agg->dtag_ecb = ecb;
10590
10591 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10592
10593 switch (desc->dtad_kind) {
10594 case DTRACEAGG_MIN:
10595 agg->dtag_initial = INT64_MAX;
10596 agg->dtag_aggregate = dtrace_aggregate_min;
10597 break;
10598
10599 case DTRACEAGG_MAX:
10600 agg->dtag_initial = INT64_MIN;
10601 agg->dtag_aggregate = dtrace_aggregate_max;
10602 break;
10603
10604 case DTRACEAGG_COUNT:
10605 agg->dtag_aggregate = dtrace_aggregate_count;
10606 break;
10607
10608 case DTRACEAGG_QUANTIZE:
10609 agg->dtag_aggregate = dtrace_aggregate_quantize;
10610 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10611 sizeof (uint64_t);
10612 break;
10613
10614 case DTRACEAGG_LQUANTIZE: {
10615 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10616 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10617
10618 agg->dtag_initial = desc->dtad_arg;
10619 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10620
10621 if (step == 0 || levels == 0)
10622 goto err;
10623
10624 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10625 break;
10626 }
10627
10628 case DTRACEAGG_AVG:
10629 agg->dtag_aggregate = dtrace_aggregate_avg;
10630 size = sizeof (uint64_t) * 2;
10631 break;
10632
10633 case DTRACEAGG_STDDEV:
10634 agg->dtag_aggregate = dtrace_aggregate_stddev;
10635 size = sizeof (uint64_t) * 4;
10636 break;
10637
10638 case DTRACEAGG_SUM:
10639 agg->dtag_aggregate = dtrace_aggregate_sum;
10640 break;
10641
10642 default:
10643 goto err;
10644 }
10645
10646 agg->dtag_action.dta_rec.dtrd_size = size;
10647
10648 if (ntuple == 0)
10649 goto err;
10650
10651 /*
10652 * We must make sure that we have enough actions for the n-tuple.
10653 */
10654 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10655 if (DTRACEACT_ISAGG(act->dta_kind))
10656 break;
10657
10658 if (--ntuple == 0) {
10659 /*
10660 * This is the action with which our n-tuple begins.
10661 */
10662 agg->dtag_first = act;
10663 goto success;
10664 }
10665 }
10666
10667 /*
10668 * This n-tuple is short by ntuple elements. Return failure.
10669 */
10670 ASSERT(ntuple != 0);
10671 err:
10672 kmem_free(agg, sizeof (dtrace_aggregation_t));
10673 return (NULL);
10674
10675 success:
10676 /*
10677 * If the last action in the tuple has a size of zero, it's actually
10678 * an expression argument for the aggregating action.
10679 */
10680 ASSERT(ecb->dte_action_last != NULL);
10681 act = ecb->dte_action_last;
10682
10683 if (act->dta_kind == DTRACEACT_DIFEXPR) {
10684 ASSERT(act->dta_difo != NULL);
10685
10686 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10687 agg->dtag_hasarg = 1;
10688 }
10689
10690 /*
10691 * We need to allocate an id for this aggregation.
10692 */
10693 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10694 VM_BESTFIT | VM_SLEEP);
10695
10696 #if !defined(__APPLE__) /* Quiet compiler warnings */
10697 if (aggid - 1 >= state->dts_naggregations) {
10698 #else
10699 if (aggid - 1 >= (dtrace_aggid_t)state->dts_naggregations) {
10700 #endif /* __APPLE__ */
10701 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10702 dtrace_aggregation_t **aggs;
10703 int naggs = state->dts_naggregations << 1;
10704 int onaggs = state->dts_naggregations;
10705
10706 #if !defined(__APPLE__) /* Quiet compiler warnings */
10707 ASSERT(aggid == state->dts_naggregations + 1);
10708 #else
10709 ASSERT(aggid == (dtrace_aggid_t)state->dts_naggregations + 1);
10710 #endif /* __APPLE */
10711
10712 if (naggs == 0) {
10713 ASSERT(oaggs == NULL);
10714 naggs = 1;
10715 }
10716
10717 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10718
10719 if (oaggs != NULL) {
10720 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10721 kmem_free(oaggs, onaggs * sizeof (*aggs));
10722 }
10723
10724 state->dts_aggregations = aggs;
10725 state->dts_naggregations = naggs;
10726 }
10727
10728 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10729 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10730
10731 frec = &agg->dtag_first->dta_rec;
10732 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10733 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10734
10735 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10736 ASSERT(!act->dta_intuple);
10737 act->dta_intuple = 1;
10738 }
10739
10740 return (&agg->dtag_action);
10741 }
10742
10743 static void
10744 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10745 {
10746 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10747 dtrace_state_t *state = ecb->dte_state;
10748 dtrace_aggid_t aggid = agg->dtag_id;
10749
10750 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10751 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10752
10753 ASSERT(state->dts_aggregations[aggid - 1] == agg);
10754 state->dts_aggregations[aggid - 1] = NULL;
10755
10756 kmem_free(agg, sizeof (dtrace_aggregation_t));
10757 }
10758
10759 static int
10760 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10761 {
10762 dtrace_action_t *action, *last;
10763 dtrace_difo_t *dp = desc->dtad_difo;
10764 uint32_t size = 0, align = sizeof (uint8_t), mask;
10765 uint16_t format = 0;
10766 dtrace_recdesc_t *rec;
10767 dtrace_state_t *state = ecb->dte_state;
10768 #if !defined(__APPLE__) /* Quiet compiler warnings */
10769 dtrace_optval_t *opt = state->dts_options, nframes, strsize;
10770 #else
10771 dtrace_optval_t *opt = state->dts_options;
10772 dtrace_optval_t nframes=0, strsize;
10773 #endif /* __APPLE__ */
10774 uint64_t arg = desc->dtad_arg;
10775
10776 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10777 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10778
10779 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10780 /*
10781 * If this is an aggregating action, there must be neither
10782 * a speculate nor a commit on the action chain.
10783 */
10784 dtrace_action_t *act;
10785
10786 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10787 if (act->dta_kind == DTRACEACT_COMMIT)
10788 return (EINVAL);
10789
10790 if (act->dta_kind == DTRACEACT_SPECULATE)
10791 return (EINVAL);
10792 }
10793
10794 action = dtrace_ecb_aggregation_create(ecb, desc);
10795
10796 if (action == NULL)
10797 return (EINVAL);
10798 } else {
10799 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10800 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10801 dp != NULL && dp->dtdo_destructive)) {
10802 state->dts_destructive = 1;
10803 }
10804
10805 switch (desc->dtad_kind) {
10806 case DTRACEACT_PRINTF:
10807 case DTRACEACT_PRINTA:
10808 case DTRACEACT_SYSTEM:
10809 case DTRACEACT_FREOPEN:
10810 /*
10811 * We know that our arg is a string -- turn it into a
10812 * format.
10813 */
10814 if (arg == NULL) {
10815 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
10816 format = 0;
10817 } else {
10818 ASSERT(arg != NULL);
10819 ASSERT(arg > KERNELBASE);
10820 format = dtrace_format_add(state,
10821 (char *)(uintptr_t)arg);
10822 }
10823
10824 /*FALLTHROUGH*/
10825 case DTRACEACT_LIBACT:
10826 case DTRACEACT_DIFEXPR:
10827 #if defined(__APPLE__)
10828 case DTRACEACT_APPLEBINARY:
10829 #endif /* __APPLE__ */
10830 if (dp == NULL)
10831 return (EINVAL);
10832
10833 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10834 break;
10835
10836 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10837 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10838 return (EINVAL);
10839
10840 size = opt[DTRACEOPT_STRSIZE];
10841 }
10842
10843 break;
10844
10845 case DTRACEACT_STACK:
10846 if ((nframes = arg) == 0) {
10847 nframes = opt[DTRACEOPT_STACKFRAMES];
10848 ASSERT(nframes > 0);
10849 arg = nframes;
10850 }
10851
10852 size = nframes * sizeof (pc_t);
10853 break;
10854
10855 case DTRACEACT_JSTACK:
10856 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10857 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10858
10859 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10860 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10861
10862 arg = DTRACE_USTACK_ARG(nframes, strsize);
10863
10864 /*FALLTHROUGH*/
10865 case DTRACEACT_USTACK:
10866 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10867 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10868 strsize = DTRACE_USTACK_STRSIZE(arg);
10869 nframes = opt[DTRACEOPT_USTACKFRAMES];
10870 ASSERT(nframes > 0);
10871 arg = DTRACE_USTACK_ARG(nframes, strsize);
10872 }
10873
10874 /*
10875 * Save a slot for the pid.
10876 */
10877 size = (nframes + 1) * sizeof (uint64_t);
10878 size += DTRACE_USTACK_STRSIZE(arg);
10879 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10880
10881 break;
10882
10883 case DTRACEACT_SYM:
10884 case DTRACEACT_MOD:
10885 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10886 sizeof (uint64_t)) ||
10887 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10888 return (EINVAL);
10889 break;
10890
10891 case DTRACEACT_USYM:
10892 case DTRACEACT_UMOD:
10893 case DTRACEACT_UADDR:
10894 if (dp == NULL ||
10895 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10896 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10897 return (EINVAL);
10898
10899 /*
10900 * We have a slot for the pid, plus a slot for the
10901 * argument. To keep things simple (aligned with
10902 * bitness-neutral sizing), we store each as a 64-bit
10903 * quantity.
10904 */
10905 size = 2 * sizeof (uint64_t);
10906 break;
10907
10908 case DTRACEACT_STOP:
10909 case DTRACEACT_BREAKPOINT:
10910 case DTRACEACT_PANIC:
10911 break;
10912
10913 case DTRACEACT_CHILL:
10914 case DTRACEACT_DISCARD:
10915 case DTRACEACT_RAISE:
10916 #if defined(__APPLE__)
10917 case DTRACEACT_PIDRESUME:
10918 #endif /* __APPLE__ */
10919 if (dp == NULL)
10920 return (EINVAL);
10921 break;
10922
10923 case DTRACEACT_EXIT:
10924 if (dp == NULL ||
10925 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10926 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10927 return (EINVAL);
10928 break;
10929
10930 case DTRACEACT_SPECULATE:
10931 if (ecb->dte_size > sizeof (dtrace_epid_t))
10932 return (EINVAL);
10933
10934 if (dp == NULL)
10935 return (EINVAL);
10936
10937 state->dts_speculates = 1;
10938 break;
10939
10940 case DTRACEACT_COMMIT: {
10941 dtrace_action_t *act = ecb->dte_action;
10942
10943 for (; act != NULL; act = act->dta_next) {
10944 if (act->dta_kind == DTRACEACT_COMMIT)
10945 return (EINVAL);
10946 }
10947
10948 if (dp == NULL)
10949 return (EINVAL);
10950 break;
10951 }
10952
10953 default:
10954 return (EINVAL);
10955 }
10956
10957 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10958 /*
10959 * If this is a data-storing action or a speculate,
10960 * we must be sure that there isn't a commit on the
10961 * action chain.
10962 */
10963 dtrace_action_t *act = ecb->dte_action;
10964
10965 for (; act != NULL; act = act->dta_next) {
10966 if (act->dta_kind == DTRACEACT_COMMIT)
10967 return (EINVAL);
10968 }
10969 }
10970
10971 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10972 action->dta_rec.dtrd_size = size;
10973 }
10974
10975 action->dta_refcnt = 1;
10976 rec = &action->dta_rec;
10977 size = rec->dtrd_size;
10978
10979 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10980 if (!(size & mask)) {
10981 align = mask + 1;
10982 break;
10983 }
10984 }
10985
10986 action->dta_kind = desc->dtad_kind;
10987
10988 if ((action->dta_difo = dp) != NULL)
10989 dtrace_difo_hold(dp);
10990
10991 rec->dtrd_action = action->dta_kind;
10992 rec->dtrd_arg = arg;
10993 rec->dtrd_uarg = desc->dtad_uarg;
10994 rec->dtrd_alignment = (uint16_t)align;
10995 rec->dtrd_format = format;
10996
10997 if ((last = ecb->dte_action_last) != NULL) {
10998 ASSERT(ecb->dte_action != NULL);
10999 action->dta_prev = last;
11000 last->dta_next = action;
11001 } else {
11002 ASSERT(ecb->dte_action == NULL);
11003 ecb->dte_action = action;
11004 }
11005
11006 ecb->dte_action_last = action;
11007
11008 return (0);
11009 }
11010
11011 static void
11012 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11013 {
11014 dtrace_action_t *act = ecb->dte_action, *next;
11015 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11016 dtrace_difo_t *dp;
11017 uint16_t format;
11018
11019 if (act != NULL && act->dta_refcnt > 1) {
11020 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11021 act->dta_refcnt--;
11022 } else {
11023 for (; act != NULL; act = next) {
11024 next = act->dta_next;
11025 ASSERT(next != NULL || act == ecb->dte_action_last);
11026 ASSERT(act->dta_refcnt == 1);
11027
11028 if ((format = act->dta_rec.dtrd_format) != 0)
11029 dtrace_format_remove(ecb->dte_state, format);
11030
11031 if ((dp = act->dta_difo) != NULL)
11032 dtrace_difo_release(dp, vstate);
11033
11034 if (DTRACEACT_ISAGG(act->dta_kind)) {
11035 dtrace_ecb_aggregation_destroy(ecb, act);
11036 } else {
11037 kmem_free(act, sizeof (dtrace_action_t));
11038 }
11039 }
11040 }
11041
11042 ecb->dte_action = NULL;
11043 ecb->dte_action_last = NULL;
11044 ecb->dte_size = sizeof (dtrace_epid_t);
11045 }
11046
11047 static void
11048 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11049 {
11050 /*
11051 * We disable the ECB by removing it from its probe.
11052 */
11053 dtrace_ecb_t *pecb, *prev = NULL;
11054 dtrace_probe_t *probe = ecb->dte_probe;
11055
11056 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11057
11058 if (probe == NULL) {
11059 /*
11060 * This is the NULL probe; there is nothing to disable.
11061 */
11062 return;
11063 }
11064
11065 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11066 if (pecb == ecb)
11067 break;
11068 prev = pecb;
11069 }
11070
11071 ASSERT(pecb != NULL);
11072
11073 if (prev == NULL) {
11074 probe->dtpr_ecb = ecb->dte_next;
11075 } else {
11076 prev->dte_next = ecb->dte_next;
11077 }
11078
11079 if (ecb == probe->dtpr_ecb_last) {
11080 ASSERT(ecb->dte_next == NULL);
11081 probe->dtpr_ecb_last = prev;
11082 }
11083
11084 /*
11085 * The ECB has been disconnected from the probe; now sync to assure
11086 * that all CPUs have seen the change before returning.
11087 */
11088 dtrace_sync();
11089
11090 if (probe->dtpr_ecb == NULL) {
11091 /*
11092 * That was the last ECB on the probe; clear the predicate
11093 * cache ID for the probe, disable it and sync one more time
11094 * to assure that we'll never hit it again.
11095 */
11096 dtrace_provider_t *prov = probe->dtpr_provider;
11097
11098 ASSERT(ecb->dte_next == NULL);
11099 ASSERT(probe->dtpr_ecb_last == NULL);
11100 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11101 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11102 probe->dtpr_id, probe->dtpr_arg);
11103 dtrace_sync();
11104 } else {
11105 /*
11106 * There is at least one ECB remaining on the probe. If there
11107 * is _exactly_ one, set the probe's predicate cache ID to be
11108 * the predicate cache ID of the remaining ECB.
11109 */
11110 ASSERT(probe->dtpr_ecb_last != NULL);
11111 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11112
11113 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11114 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11115
11116 ASSERT(probe->dtpr_ecb->dte_next == NULL);
11117
11118 if (p != NULL)
11119 probe->dtpr_predcache = p->dtp_cacheid;
11120 }
11121
11122 ecb->dte_next = NULL;
11123 }
11124 }
11125
11126 static void
11127 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11128 {
11129 dtrace_state_t *state = ecb->dte_state;
11130 dtrace_vstate_t *vstate = &state->dts_vstate;
11131 dtrace_predicate_t *pred;
11132 dtrace_epid_t epid = ecb->dte_epid;
11133
11134 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11135 ASSERT(ecb->dte_next == NULL);
11136 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11137
11138 if ((pred = ecb->dte_predicate) != NULL)
11139 dtrace_predicate_release(pred, vstate);
11140
11141 dtrace_ecb_action_remove(ecb);
11142
11143 ASSERT(state->dts_ecbs[epid - 1] == ecb);
11144 state->dts_ecbs[epid - 1] = NULL;
11145
11146 kmem_free(ecb, sizeof (dtrace_ecb_t));
11147 }
11148
11149 static dtrace_ecb_t *
11150 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11151 dtrace_enabling_t *enab)
11152 {
11153 dtrace_ecb_t *ecb;
11154 dtrace_predicate_t *pred;
11155 dtrace_actdesc_t *act;
11156 dtrace_provider_t *prov;
11157 dtrace_ecbdesc_t *desc = enab->dten_current;
11158
11159 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11160 ASSERT(state != NULL);
11161
11162 ecb = dtrace_ecb_add(state, probe);
11163 ecb->dte_uarg = desc->dted_uarg;
11164
11165 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11166 dtrace_predicate_hold(pred);
11167 ecb->dte_predicate = pred;
11168 }
11169
11170 if (probe != NULL) {
11171 /*
11172 * If the provider shows more leg than the consumer is old
11173 * enough to see, we need to enable the appropriate implicit
11174 * predicate bits to prevent the ecb from activating at
11175 * revealing times.
11176 *
11177 * Providers specifying DTRACE_PRIV_USER at register time
11178 * are stating that they need the /proc-style privilege
11179 * model to be enforced, and this is what DTRACE_COND_OWNER
11180 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11181 */
11182 prov = probe->dtpr_provider;
11183 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11184 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11185 ecb->dte_cond |= DTRACE_COND_OWNER;
11186
11187 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11188 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11189 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11190
11191 /*
11192 * If the provider shows us kernel innards and the user
11193 * is lacking sufficient privilege, enable the
11194 * DTRACE_COND_USERMODE implicit predicate.
11195 */
11196 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11197 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11198 ecb->dte_cond |= DTRACE_COND_USERMODE;
11199 }
11200
11201 if (dtrace_ecb_create_cache != NULL) {
11202 /*
11203 * If we have a cached ecb, we'll use its action list instead
11204 * of creating our own (saving both time and space).
11205 */
11206 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11207 dtrace_action_t *act_if = cached->dte_action;
11208
11209 if (act_if != NULL) {
11210 ASSERT(act_if->dta_refcnt > 0);
11211 act_if->dta_refcnt++;
11212 ecb->dte_action = act_if;
11213 ecb->dte_action_last = cached->dte_action_last;
11214 ecb->dte_needed = cached->dte_needed;
11215 ecb->dte_size = cached->dte_size;
11216 ecb->dte_alignment = cached->dte_alignment;
11217 }
11218
11219 return (ecb);
11220 }
11221
11222 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11223 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11224 dtrace_ecb_destroy(ecb);
11225 return (NULL);
11226 }
11227 }
11228
11229 dtrace_ecb_resize(ecb);
11230
11231 return (dtrace_ecb_create_cache = ecb);
11232 }
11233
11234 static int
11235 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11236 {
11237 dtrace_ecb_t *ecb;
11238 dtrace_enabling_t *enab = arg;
11239 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11240
11241 ASSERT(state != NULL);
11242
11243 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11244 /*
11245 * This probe was created in a generation for which this
11246 * enabling has previously created ECBs; we don't want to
11247 * enable it again, so just kick out.
11248 */
11249 return (DTRACE_MATCH_NEXT);
11250 }
11251
11252 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11253 return (DTRACE_MATCH_DONE);
11254
11255 if (dtrace_ecb_enable(ecb) < 0)
11256 return (DTRACE_MATCH_FAIL);
11257
11258 return (DTRACE_MATCH_NEXT);
11259 }
11260
11261 static dtrace_ecb_t *
11262 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11263 {
11264 dtrace_ecb_t *ecb;
11265 #pragma unused(ecb) /* __APPLE__ */
11266
11267 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11268
11269 #if !defined(__APPLE__) /* Quiet compiler warnings */
11270 if (id == 0 || id > state->dts_necbs)
11271 #else
11272 if (id == 0 || id > (dtrace_epid_t)state->dts_necbs)
11273 #endif /* __APPLE__ */
11274 return (NULL);
11275
11276 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11277 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11278
11279 return (state->dts_ecbs[id - 1]);
11280 }
11281
11282 static dtrace_aggregation_t *
11283 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11284 {
11285 dtrace_aggregation_t *agg;
11286 #pragma unused(agg) /* __APPLE__ */
11287
11288 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11289
11290 #if !defined(__APPLE__) /* Quiet compiler warnings */
11291 if (id == 0 || id > state->dts_naggregations)
11292 #else
11293 if (id == 0 || id > (dtrace_aggid_t)state->dts_naggregations)
11294 #endif /* __APPLE__ */
11295 return (NULL);
11296
11297 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11298 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11299 agg->dtag_id == id);
11300
11301 return (state->dts_aggregations[id - 1]);
11302 }
11303
11304 /*
11305 * DTrace Buffer Functions
11306 *
11307 * The following functions manipulate DTrace buffers. Most of these functions
11308 * are called in the context of establishing or processing consumer state;
11309 * exceptions are explicitly noted.
11310 */
11311
11312 /*
11313 * Note: called from cross call context. This function switches the two
11314 * buffers on a given CPU. The atomicity of this operation is assured by
11315 * disabling interrupts while the actual switch takes place; the disabling of
11316 * interrupts serializes the execution with any execution of dtrace_probe() on
11317 * the same CPU.
11318 */
11319 static void
11320 dtrace_buffer_switch(dtrace_buffer_t *buf)
11321 {
11322 caddr_t tomax = buf->dtb_tomax;
11323 caddr_t xamot = buf->dtb_xamot;
11324 dtrace_icookie_t cookie;
11325
11326 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11327 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11328
11329 cookie = dtrace_interrupt_disable();
11330 buf->dtb_tomax = xamot;
11331 buf->dtb_xamot = tomax;
11332 buf->dtb_xamot_drops = buf->dtb_drops;
11333 buf->dtb_xamot_offset = buf->dtb_offset;
11334 buf->dtb_xamot_errors = buf->dtb_errors;
11335 buf->dtb_xamot_flags = buf->dtb_flags;
11336 buf->dtb_offset = 0;
11337 buf->dtb_drops = 0;
11338 buf->dtb_errors = 0;
11339 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11340 dtrace_interrupt_enable(cookie);
11341 }
11342
11343 /*
11344 * Note: called from cross call context. This function activates a buffer
11345 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
11346 * is guaranteed by the disabling of interrupts.
11347 */
11348 static void
11349 dtrace_buffer_activate(dtrace_state_t *state)
11350 {
11351 dtrace_buffer_t *buf;
11352 dtrace_icookie_t cookie = dtrace_interrupt_disable();
11353
11354 buf = &state->dts_buffer[CPU->cpu_id];
11355
11356 if (buf->dtb_tomax != NULL) {
11357 /*
11358 * We might like to assert that the buffer is marked inactive,
11359 * but this isn't necessarily true: the buffer for the CPU
11360 * that processes the BEGIN probe has its buffer activated
11361 * manually. In this case, we take the (harmless) action
11362 * re-clearing the bit INACTIVE bit.
11363 */
11364 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11365 }
11366
11367 dtrace_interrupt_enable(cookie);
11368 }
11369
11370 static int
11371 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11372 processorid_t cpu)
11373 {
11374 dtrace_cpu_t *cp;
11375 dtrace_buffer_t *buf;
11376
11377 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11378 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11379
11380 #if !defined(__APPLE__) /* Quiet compiler warnings */
11381 if (size > dtrace_nonroot_maxsize &&
11382 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11383 return (EFBIG);
11384 #else
11385 if (size > (size_t)dtrace_nonroot_maxsize &&
11386 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11387 return (EFBIG);
11388 #endif /* __APPLE__ */
11389
11390
11391 #if defined(__APPLE__)
11392 if (size > (sane_size / 8) / (int)NCPU) /* As in kdbg_set_nkdbufs(), roughly. */
11393 return (ENOMEM);
11394 #endif /* __APPLE__ */
11395
11396 cp = cpu_list;
11397
11398 do {
11399 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11400 continue;
11401
11402 buf = &bufs[cp->cpu_id];
11403
11404 /*
11405 * If there is already a buffer allocated for this CPU, it
11406 * is only possible that this is a DR event. In this case,
11407 * the buffer size must match our specified size.
11408 */
11409 if (buf->dtb_tomax != NULL) {
11410 ASSERT(buf->dtb_size == size);
11411 continue;
11412 }
11413
11414 ASSERT(buf->dtb_xamot == NULL);
11415
11416 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11417 goto err;
11418
11419 buf->dtb_size = size;
11420 buf->dtb_flags = flags;
11421 buf->dtb_offset = 0;
11422 buf->dtb_drops = 0;
11423
11424 if (flags & DTRACEBUF_NOSWITCH)
11425 continue;
11426
11427 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11428 goto err;
11429 } while ((cp = cp->cpu_next) != cpu_list);
11430
11431 return (0);
11432
11433 err:
11434 cp = cpu_list;
11435
11436 do {
11437 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11438 continue;
11439
11440 buf = &bufs[cp->cpu_id];
11441
11442 if (buf->dtb_xamot != NULL) {
11443 ASSERT(buf->dtb_tomax != NULL);
11444 ASSERT(buf->dtb_size == size);
11445 kmem_free(buf->dtb_xamot, size);
11446 }
11447
11448 if (buf->dtb_tomax != NULL) {
11449 ASSERT(buf->dtb_size == size);
11450 kmem_free(buf->dtb_tomax, size);
11451 }
11452
11453 buf->dtb_tomax = NULL;
11454 buf->dtb_xamot = NULL;
11455 buf->dtb_size = 0;
11456 } while ((cp = cp->cpu_next) != cpu_list);
11457
11458 return (ENOMEM);
11459 }
11460
11461 /*
11462 * Note: called from probe context. This function just increments the drop
11463 * count on a buffer. It has been made a function to allow for the
11464 * possibility of understanding the source of mysterious drop counts. (A
11465 * problem for which one may be particularly disappointed that DTrace cannot
11466 * be used to understand DTrace.)
11467 */
11468 static void
11469 dtrace_buffer_drop(dtrace_buffer_t *buf)
11470 {
11471 buf->dtb_drops++;
11472 }
11473
11474 /*
11475 * Note: called from probe context. This function is called to reserve space
11476 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
11477 * mstate. Returns the new offset in the buffer, or a negative value if an
11478 * error has occurred.
11479 */
11480 static intptr_t
11481 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11482 dtrace_state_t *state, dtrace_mstate_t *mstate)
11483 {
11484 intptr_t offs = buf->dtb_offset, soffs;
11485 intptr_t woffs;
11486 caddr_t tomax;
11487 size_t total_off;
11488
11489 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11490 return (-1);
11491
11492 if ((tomax = buf->dtb_tomax) == NULL) {
11493 dtrace_buffer_drop(buf);
11494 return (-1);
11495 }
11496
11497 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11498 while (offs & (align - 1)) {
11499 /*
11500 * Assert that our alignment is off by a number which
11501 * is itself sizeof (uint32_t) aligned.
11502 */
11503 ASSERT(!((align - (offs & (align - 1))) &
11504 (sizeof (uint32_t) - 1)));
11505 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11506 offs += sizeof (uint32_t);
11507 }
11508
11509 #if !defined(__APPLE__) /* Quiet compiler warnings */
11510 if ((soffs = offs + needed) > buf->dtb_size) {
11511 #else
11512 if ((uint64_t)(soffs = offs + needed) > buf->dtb_size) {
11513 #endif /* __APPLE__ */
11514 dtrace_buffer_drop(buf);
11515 return (-1);
11516 }
11517
11518 if (mstate == NULL)
11519 return (offs);
11520
11521 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11522 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11523 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11524
11525 return (offs);
11526 }
11527
11528 if (buf->dtb_flags & DTRACEBUF_FILL) {
11529 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11530 (buf->dtb_flags & DTRACEBUF_FULL))
11531 return (-1);
11532 goto out;
11533 }
11534
11535 total_off = needed + (offs & (align - 1));
11536
11537 /*
11538 * For a ring buffer, life is quite a bit more complicated. Before
11539 * we can store any padding, we need to adjust our wrapping offset.
11540 * (If we've never before wrapped or we're not about to, no adjustment
11541 * is required.)
11542 */
11543 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11544 offs + total_off > buf->dtb_size) {
11545 woffs = buf->dtb_xamot_offset;
11546
11547 if (offs + total_off > buf->dtb_size) {
11548 /*
11549 * We can't fit in the end of the buffer. First, a
11550 * sanity check that we can fit in the buffer at all.
11551 */
11552 if (total_off > buf->dtb_size) {
11553 dtrace_buffer_drop(buf);
11554 return (-1);
11555 }
11556
11557 /*
11558 * We're going to be storing at the top of the buffer,
11559 * so now we need to deal with the wrapped offset. We
11560 * only reset our wrapped offset to 0 if it is
11561 * currently greater than the current offset. If it
11562 * is less than the current offset, it is because a
11563 * previous allocation induced a wrap -- but the
11564 * allocation didn't subsequently take the space due
11565 * to an error or false predicate evaluation. In this
11566 * case, we'll just leave the wrapped offset alone: if
11567 * the wrapped offset hasn't been advanced far enough
11568 * for this allocation, it will be adjusted in the
11569 * lower loop.
11570 */
11571 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11572 if (woffs >= offs)
11573 woffs = 0;
11574 } else {
11575 woffs = 0;
11576 }
11577
11578 /*
11579 * Now we know that we're going to be storing to the
11580 * top of the buffer and that there is room for us
11581 * there. We need to clear the buffer from the current
11582 * offset to the end (there may be old gunk there).
11583 */
11584 #if !defined(__APPLE__) /* Quiet compiler warnings */
11585 while (offs < buf->dtb_size)
11586 #else
11587 while ((uint64_t)offs < buf->dtb_size)
11588 #endif /* __APPLE__ */
11589 tomax[offs++] = 0;
11590
11591 /*
11592 * We need to set our offset to zero. And because we
11593 * are wrapping, we need to set the bit indicating as
11594 * much. We can also adjust our needed space back
11595 * down to the space required by the ECB -- we know
11596 * that the top of the buffer is aligned.
11597 */
11598 offs = 0;
11599 total_off = needed;
11600 buf->dtb_flags |= DTRACEBUF_WRAPPED;
11601 } else {
11602 /*
11603 * There is room for us in the buffer, so we simply
11604 * need to check the wrapped offset.
11605 */
11606 if (woffs < offs) {
11607 /*
11608 * The wrapped offset is less than the offset.
11609 * This can happen if we allocated buffer space
11610 * that induced a wrap, but then we didn't
11611 * subsequently take the space due to an error
11612 * or false predicate evaluation. This is
11613 * okay; we know that _this_ allocation isn't
11614 * going to induce a wrap. We still can't
11615 * reset the wrapped offset to be zero,
11616 * however: the space may have been trashed in
11617 * the previous failed probe attempt. But at
11618 * least the wrapped offset doesn't need to
11619 * be adjusted at all...
11620 */
11621 goto out;
11622 }
11623 }
11624
11625 #if !defined(__APPLE__) /* Quiet compiler warnings */
11626 while (offs + total_off > woffs) {
11627 #else
11628 while (offs + total_off > (size_t)woffs) {
11629 #endif /* __APPLE__ */
11630 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11631 size_t size;
11632
11633 if (epid == DTRACE_EPIDNONE) {
11634 size = sizeof (uint32_t);
11635 } else {
11636 #if !defined(__APPLE__) /* Quiet compiler warnings */
11637 ASSERT(epid <= state->dts_necbs);
11638 #else
11639 ASSERT(epid <= (dtrace_epid_t)state->dts_necbs);
11640 #endif /* __APPLE__ */
11641 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11642
11643 size = state->dts_ecbs[epid - 1]->dte_size;
11644 }
11645
11646 ASSERT(woffs + size <= buf->dtb_size);
11647 ASSERT(size != 0);
11648
11649 if (woffs + size == buf->dtb_size) {
11650 /*
11651 * We've reached the end of the buffer; we want
11652 * to set the wrapped offset to 0 and break
11653 * out. However, if the offs is 0, then we're
11654 * in a strange edge-condition: the amount of
11655 * space that we want to reserve plus the size
11656 * of the record that we're overwriting is
11657 * greater than the size of the buffer. This
11658 * is problematic because if we reserve the
11659 * space but subsequently don't consume it (due
11660 * to a failed predicate or error) the wrapped
11661 * offset will be 0 -- yet the EPID at offset 0
11662 * will not be committed. This situation is
11663 * relatively easy to deal with: if we're in
11664 * this case, the buffer is indistinguishable
11665 * from one that hasn't wrapped; we need only
11666 * finish the job by clearing the wrapped bit,
11667 * explicitly setting the offset to be 0, and
11668 * zero'ing out the old data in the buffer.
11669 */
11670 if (offs == 0) {
11671 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11672 buf->dtb_offset = 0;
11673 woffs = total_off;
11674
11675 #if !defined(__APPLE__) /* Quiet compiler warnings */
11676 while (woffs < buf->dtb_size)
11677 #else
11678 while ((uint64_t)woffs < buf->dtb_size)
11679 #endif /* __APPLE__ */
11680
11681 tomax[woffs++] = 0;
11682 }
11683
11684 woffs = 0;
11685 break;
11686 }
11687
11688 woffs += size;
11689 }
11690
11691 /*
11692 * We have a wrapped offset. It may be that the wrapped offset
11693 * has become zero -- that's okay.
11694 */
11695 buf->dtb_xamot_offset = woffs;
11696 }
11697
11698 out:
11699 /*
11700 * Now we can plow the buffer with any necessary padding.
11701 */
11702 while (offs & (align - 1)) {
11703 /*
11704 * Assert that our alignment is off by a number which
11705 * is itself sizeof (uint32_t) aligned.
11706 */
11707 ASSERT(!((align - (offs & (align - 1))) &
11708 (sizeof (uint32_t) - 1)));
11709 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11710 offs += sizeof (uint32_t);
11711 }
11712
11713 if (buf->dtb_flags & DTRACEBUF_FILL) {
11714 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11715 buf->dtb_flags |= DTRACEBUF_FULL;
11716 return (-1);
11717 }
11718 }
11719
11720 if (mstate == NULL)
11721 return (offs);
11722
11723 /*
11724 * For ring buffers and fill buffers, the scratch space is always
11725 * the inactive buffer.
11726 */
11727 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11728 mstate->dtms_scratch_size = buf->dtb_size;
11729 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11730
11731 return (offs);
11732 }
11733
11734 static void
11735 dtrace_buffer_polish(dtrace_buffer_t *buf)
11736 {
11737 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11738 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11739
11740 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11741 return;
11742
11743 /*
11744 * We need to polish the ring buffer. There are three cases:
11745 *
11746 * - The first (and presumably most common) is that there is no gap
11747 * between the buffer offset and the wrapped offset. In this case,
11748 * there is nothing in the buffer that isn't valid data; we can
11749 * mark the buffer as polished and return.
11750 *
11751 * - The second (less common than the first but still more common
11752 * than the third) is that there is a gap between the buffer offset
11753 * and the wrapped offset, and the wrapped offset is larger than the
11754 * buffer offset. This can happen because of an alignment issue, or
11755 * can happen because of a call to dtrace_buffer_reserve() that
11756 * didn't subsequently consume the buffer space. In this case,
11757 * we need to zero the data from the buffer offset to the wrapped
11758 * offset.
11759 *
11760 * - The third (and least common) is that there is a gap between the
11761 * buffer offset and the wrapped offset, but the wrapped offset is
11762 * _less_ than the buffer offset. This can only happen because a
11763 * call to dtrace_buffer_reserve() induced a wrap, but the space
11764 * was not subsequently consumed. In this case, we need to zero the
11765 * space from the offset to the end of the buffer _and_ from the
11766 * top of the buffer to the wrapped offset.
11767 */
11768 if (buf->dtb_offset < buf->dtb_xamot_offset) {
11769 bzero(buf->dtb_tomax + buf->dtb_offset,
11770 buf->dtb_xamot_offset - buf->dtb_offset);
11771 }
11772
11773 if (buf->dtb_offset > buf->dtb_xamot_offset) {
11774 bzero(buf->dtb_tomax + buf->dtb_offset,
11775 buf->dtb_size - buf->dtb_offset);
11776 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11777 }
11778 }
11779
11780 static void
11781 dtrace_buffer_free(dtrace_buffer_t *bufs)
11782 {
11783 int i;
11784
11785 for (i = 0; i < (int)NCPU; i++) {
11786 dtrace_buffer_t *buf = &bufs[i];
11787
11788 if (buf->dtb_tomax == NULL) {
11789 ASSERT(buf->dtb_xamot == NULL);
11790 ASSERT(buf->dtb_size == 0);
11791 continue;
11792 }
11793
11794 if (buf->dtb_xamot != NULL) {
11795 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11796 kmem_free(buf->dtb_xamot, buf->dtb_size);
11797 }
11798
11799 kmem_free(buf->dtb_tomax, buf->dtb_size);
11800 buf->dtb_size = 0;
11801 buf->dtb_tomax = NULL;
11802 buf->dtb_xamot = NULL;
11803 }
11804 }
11805
11806 /*
11807 * DTrace Enabling Functions
11808 */
11809 static dtrace_enabling_t *
11810 dtrace_enabling_create(dtrace_vstate_t *vstate)
11811 {
11812 dtrace_enabling_t *enab;
11813
11814 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11815 enab->dten_vstate = vstate;
11816
11817 return (enab);
11818 }
11819
11820 static void
11821 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11822 {
11823 dtrace_ecbdesc_t **ndesc;
11824 size_t osize, nsize;
11825
11826 /*
11827 * We can't add to enablings after we've enabled them, or after we've
11828 * retained them.
11829 */
11830 ASSERT(enab->dten_probegen == 0);
11831 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11832
11833 #if defined(__APPLE__)
11834 if (ecb == NULL) return; /* Note: protection against gcc 4.0 botch on x86 */
11835 #endif /* __APPLE__ */
11836
11837 if (enab->dten_ndesc < enab->dten_maxdesc) {
11838 enab->dten_desc[enab->dten_ndesc++] = ecb;
11839 return;
11840 }
11841
11842 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11843
11844 if (enab->dten_maxdesc == 0) {
11845 enab->dten_maxdesc = 1;
11846 } else {
11847 enab->dten_maxdesc <<= 1;
11848 }
11849
11850 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11851
11852 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11853 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11854 bcopy(enab->dten_desc, ndesc, osize);
11855 kmem_free(enab->dten_desc, osize);
11856
11857 enab->dten_desc = ndesc;
11858 enab->dten_desc[enab->dten_ndesc++] = ecb;
11859 }
11860
11861 static void
11862 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11863 dtrace_probedesc_t *pd)
11864 {
11865 dtrace_ecbdesc_t *new;
11866 dtrace_predicate_t *pred;
11867 dtrace_actdesc_t *act;
11868
11869 /*
11870 * We're going to create a new ECB description that matches the
11871 * specified ECB in every way, but has the specified probe description.
11872 */
11873 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11874
11875 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11876 dtrace_predicate_hold(pred);
11877
11878 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11879 dtrace_actdesc_hold(act);
11880
11881 new->dted_action = ecb->dted_action;
11882 new->dted_pred = ecb->dted_pred;
11883 new->dted_probe = *pd;
11884 new->dted_uarg = ecb->dted_uarg;
11885
11886 dtrace_enabling_add(enab, new);
11887 }
11888
11889 static void
11890 dtrace_enabling_dump(dtrace_enabling_t *enab)
11891 {
11892 int i;
11893
11894 for (i = 0; i < enab->dten_ndesc; i++) {
11895 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11896
11897 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11898 desc->dtpd_provider, desc->dtpd_mod,
11899 desc->dtpd_func, desc->dtpd_name);
11900 }
11901 }
11902
11903 static void
11904 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11905 {
11906 int i;
11907 dtrace_ecbdesc_t *ep;
11908 dtrace_vstate_t *vstate = enab->dten_vstate;
11909
11910 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11911
11912 for (i = 0; i < enab->dten_ndesc; i++) {
11913 dtrace_actdesc_t *act, *next;
11914 dtrace_predicate_t *pred;
11915
11916 ep = enab->dten_desc[i];
11917
11918 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11919 dtrace_predicate_release(pred, vstate);
11920
11921 for (act = ep->dted_action; act != NULL; act = next) {
11922 next = act->dtad_next;
11923 dtrace_actdesc_release(act, vstate);
11924 }
11925
11926 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11927 }
11928
11929 kmem_free(enab->dten_desc,
11930 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11931
11932 /*
11933 * If this was a retained enabling, decrement the dts_nretained count
11934 * and take it off of the dtrace_retained list.
11935 */
11936 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11937 dtrace_retained == enab) {
11938 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11939 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11940 enab->dten_vstate->dtvs_state->dts_nretained--;
11941 dtrace_retained_gen++;
11942 }
11943
11944 if (enab->dten_prev == NULL) {
11945 if (dtrace_retained == enab) {
11946 dtrace_retained = enab->dten_next;
11947
11948 if (dtrace_retained != NULL)
11949 dtrace_retained->dten_prev = NULL;
11950 }
11951 } else {
11952 ASSERT(enab != dtrace_retained);
11953 ASSERT(dtrace_retained != NULL);
11954 enab->dten_prev->dten_next = enab->dten_next;
11955 }
11956
11957 if (enab->dten_next != NULL) {
11958 ASSERT(dtrace_retained != NULL);
11959 enab->dten_next->dten_prev = enab->dten_prev;
11960 }
11961
11962 kmem_free(enab, sizeof (dtrace_enabling_t));
11963 }
11964
11965 static int
11966 dtrace_enabling_retain(dtrace_enabling_t *enab)
11967 {
11968 dtrace_state_t *state;
11969
11970 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11971 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11972 ASSERT(enab->dten_vstate != NULL);
11973
11974 state = enab->dten_vstate->dtvs_state;
11975 ASSERT(state != NULL);
11976
11977 /*
11978 * We only allow each state to retain dtrace_retain_max enablings.
11979 */
11980 if (state->dts_nretained >= dtrace_retain_max)
11981 return (ENOSPC);
11982
11983 state->dts_nretained++;
11984 dtrace_retained_gen++;
11985
11986 if (dtrace_retained == NULL) {
11987 dtrace_retained = enab;
11988 return (0);
11989 }
11990
11991 enab->dten_next = dtrace_retained;
11992 dtrace_retained->dten_prev = enab;
11993 dtrace_retained = enab;
11994
11995 return (0);
11996 }
11997
11998 static int
11999 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12000 dtrace_probedesc_t *create)
12001 {
12002 dtrace_enabling_t *new, *enab;
12003 int found = 0, err = ENOENT;
12004
12005 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12006 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12007 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12008 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12009 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12010
12011 new = dtrace_enabling_create(&state->dts_vstate);
12012
12013 /*
12014 * Iterate over all retained enablings, looking for enablings that
12015 * match the specified state.
12016 */
12017 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12018 int i;
12019
12020 /*
12021 * dtvs_state can only be NULL for helper enablings -- and
12022 * helper enablings can't be retained.
12023 */
12024 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12025
12026 if (enab->dten_vstate->dtvs_state != state)
12027 continue;
12028
12029 /*
12030 * Now iterate over each probe description; we're looking for
12031 * an exact match to the specified probe description.
12032 */
12033 for (i = 0; i < enab->dten_ndesc; i++) {
12034 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12035 dtrace_probedesc_t *pd = &ep->dted_probe;
12036
12037 #if !defined(__APPLE__)
12038 if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12039 continue;
12040
12041 if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12042 continue;
12043
12044 if (strcmp(pd->dtpd_func, match->dtpd_func))
12045 continue;
12046
12047 if (strcmp(pd->dtpd_name, match->dtpd_name))
12048 continue;
12049 #else /* Employ size bounded string operation. */
12050 if (strncmp(pd->dtpd_provider, match->dtpd_provider, DTRACE_PROVNAMELEN))
12051 continue;
12052
12053 if (strncmp(pd->dtpd_mod, match->dtpd_mod, DTRACE_MODNAMELEN))
12054 continue;
12055
12056 if (strncmp(pd->dtpd_func, match->dtpd_func, DTRACE_FUNCNAMELEN))
12057 continue;
12058
12059 if (strncmp(pd->dtpd_name, match->dtpd_name, DTRACE_NAMELEN))
12060 continue;
12061 #endif /* __APPLE__ */
12062
12063 /*
12064 * We have a winning probe! Add it to our growing
12065 * enabling.
12066 */
12067 found = 1;
12068 dtrace_enabling_addlike(new, ep, create);
12069 }
12070 }
12071
12072 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12073 dtrace_enabling_destroy(new);
12074 return (err);
12075 }
12076
12077 return (0);
12078 }
12079
12080 static void
12081 dtrace_enabling_retract(dtrace_state_t *state)
12082 {
12083 dtrace_enabling_t *enab, *next;
12084
12085 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12086
12087 /*
12088 * Iterate over all retained enablings, destroy the enablings retained
12089 * for the specified state.
12090 */
12091 for (enab = dtrace_retained; enab != NULL; enab = next) {
12092 next = enab->dten_next;
12093
12094 /*
12095 * dtvs_state can only be NULL for helper enablings -- and
12096 * helper enablings can't be retained.
12097 */
12098 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12099
12100 if (enab->dten_vstate->dtvs_state == state) {
12101 ASSERT(state->dts_nretained > 0);
12102 dtrace_enabling_destroy(enab);
12103 }
12104 }
12105
12106 ASSERT(state->dts_nretained == 0);
12107 }
12108
12109 static int
12110 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12111 {
12112 int i = 0;
12113 int total_matched = 0, matched = 0;
12114
12115 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12116 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12117
12118 for (i = 0; i < enab->dten_ndesc; i++) {
12119 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12120
12121 enab->dten_current = ep;
12122 enab->dten_error = 0;
12123
12124 /*
12125 * If a provider failed to enable a probe then get out and
12126 * let the consumer know we failed.
12127 */
12128 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
12129 return (EBUSY);
12130
12131 total_matched += matched;
12132
12133 if (enab->dten_error != 0) {
12134 /*
12135 * If we get an error half-way through enabling the
12136 * probes, we kick out -- perhaps with some number of
12137 * them enabled. Leaving enabled probes enabled may
12138 * be slightly confusing for user-level, but we expect
12139 * that no one will attempt to actually drive on in
12140 * the face of such errors. If this is an anonymous
12141 * enabling (indicated with a NULL nmatched pointer),
12142 * we cmn_err() a message. We aren't expecting to
12143 * get such an error -- such as it can exist at all,
12144 * it would be a result of corrupted DOF in the driver
12145 * properties.
12146 */
12147 if (nmatched == NULL) {
12148 cmn_err(CE_WARN, "dtrace_enabling_match() "
12149 "error on %p: %d", (void *)ep,
12150 enab->dten_error);
12151 }
12152
12153 return (enab->dten_error);
12154 }
12155 }
12156
12157 enab->dten_probegen = dtrace_probegen;
12158 if (nmatched != NULL)
12159 *nmatched = total_matched;
12160
12161 return (0);
12162 }
12163
12164 static void
12165 dtrace_enabling_matchall(void)
12166 {
12167 dtrace_enabling_t *enab;
12168
12169 lck_mtx_lock(&cpu_lock);
12170 lck_mtx_lock(&dtrace_lock);
12171
12172 /*
12173 * Iterate over all retained enablings to see if any probes match
12174 * against them. We only perform this operation on enablings for which
12175 * we have sufficient permissions by virtue of being in the global zone
12176 * or in the same zone as the DTrace client. Because we can be called
12177 * after dtrace_detach() has been called, we cannot assert that there
12178 * are retained enablings. We can safely load from dtrace_retained,
12179 * however: the taskq_destroy() at the end of dtrace_detach() will
12180 * block pending our completion.
12181 */
12182 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12183 #if !defined(__APPLE__)
12184 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
12185
12186 if (INGLOBALZONE(curproc) ||
12187 cr != NULL && getzoneid() == crgetzoneid(cr))
12188 (void) dtrace_enabling_match(enab, NULL);
12189 #else
12190 (void) dtrace_enabling_match(enab, NULL); /* As if always in "global" zone." */
12191 #endif /* __APPLE__ */
12192 }
12193
12194 lck_mtx_unlock(&dtrace_lock);
12195 lck_mtx_unlock(&cpu_lock);
12196 }
12197
12198 /*
12199 * If an enabling is to be enabled without having matched probes (that is, if
12200 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12201 * enabling must be _primed_ by creating an ECB for every ECB description.
12202 * This must be done to assure that we know the number of speculations, the
12203 * number of aggregations, the minimum buffer size needed, etc. before we
12204 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
12205 * enabling any probes, we create ECBs for every ECB decription, but with a
12206 * NULL probe -- which is exactly what this function does.
12207 */
12208 static void
12209 dtrace_enabling_prime(dtrace_state_t *state)
12210 {
12211 dtrace_enabling_t *enab;
12212 int i;
12213
12214 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12215 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12216
12217 if (enab->dten_vstate->dtvs_state != state)
12218 continue;
12219
12220 /*
12221 * We don't want to prime an enabling more than once, lest
12222 * we allow a malicious user to induce resource exhaustion.
12223 * (The ECBs that result from priming an enabling aren't
12224 * leaked -- but they also aren't deallocated until the
12225 * consumer state is destroyed.)
12226 */
12227 if (enab->dten_primed)
12228 continue;
12229
12230 for (i = 0; i < enab->dten_ndesc; i++) {
12231 enab->dten_current = enab->dten_desc[i];
12232 (void) dtrace_probe_enable(NULL, enab);
12233 }
12234
12235 enab->dten_primed = 1;
12236 }
12237 }
12238
12239 /*
12240 * Called to indicate that probes should be provided due to retained
12241 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
12242 * must take an initial lap through the enabling calling the dtps_provide()
12243 * entry point explicitly to allow for autocreated probes.
12244 */
12245 static void
12246 dtrace_enabling_provide(dtrace_provider_t *prv)
12247 {
12248 int i, all = 0;
12249 dtrace_probedesc_t desc;
12250 dtrace_genid_t gen;
12251
12252 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12253 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
12254
12255 if (prv == NULL) {
12256 all = 1;
12257 prv = dtrace_provider;
12258 }
12259
12260 do {
12261 dtrace_enabling_t *enab;
12262 void *parg = prv->dtpv_arg;
12263
12264 retry:
12265 gen = dtrace_retained_gen;
12266 for (enab = dtrace_retained; enab != NULL;
12267 enab = enab->dten_next) {
12268 for (i = 0; i < enab->dten_ndesc; i++) {
12269 desc = enab->dten_desc[i]->dted_probe;
12270 lck_mtx_unlock(&dtrace_lock);
12271 prv->dtpv_pops.dtps_provide(parg, &desc);
12272 lck_mtx_lock(&dtrace_lock);
12273 /*
12274 * Process the retained enablings again if
12275 * they have changed while we weren't holding
12276 * dtrace_lock.
12277 */
12278 if (gen != dtrace_retained_gen)
12279 goto retry;
12280 }
12281 }
12282 } while (all && (prv = prv->dtpv_next) != NULL);
12283
12284 lck_mtx_unlock(&dtrace_lock);
12285 dtrace_probe_provide(NULL, all ? NULL : prv);
12286 lck_mtx_lock(&dtrace_lock);
12287 }
12288
12289 /*
12290 * DTrace DOF Functions
12291 */
12292 /*ARGSUSED*/
12293 static void
12294 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12295 {
12296 #pragma unused(dof) /* __APPLE__ */
12297 if (dtrace_err_verbose)
12298 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12299
12300 #ifdef DTRACE_ERRDEBUG
12301 dtrace_errdebug(str);
12302 #endif
12303 }
12304
12305 /*
12306 * Create DOF out of a currently enabled state. Right now, we only create
12307 * DOF containing the run-time options -- but this could be expanded to create
12308 * complete DOF representing the enabled state.
12309 */
12310 static dof_hdr_t *
12311 dtrace_dof_create(dtrace_state_t *state)
12312 {
12313 dof_hdr_t *dof;
12314 dof_sec_t *sec;
12315 dof_optdesc_t *opt;
12316 int i, len = sizeof (dof_hdr_t) +
12317 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12318 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12319
12320 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12321
12322 #if !defined(__APPLE__)
12323 dof = kmem_zalloc(len, KM_SLEEP);
12324 #else
12325 dof = dt_kmem_zalloc_aligned(len, 8, KM_SLEEP);
12326 #endif /* __APPLE__ */
12327 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12328 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12329 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12330 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12331
12332 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12333 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12334 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12335 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12336 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12337 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12338
12339 dof->dofh_flags = 0;
12340 dof->dofh_hdrsize = sizeof (dof_hdr_t);
12341 dof->dofh_secsize = sizeof (dof_sec_t);
12342 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
12343 dof->dofh_secoff = sizeof (dof_hdr_t);
12344 dof->dofh_loadsz = len;
12345 dof->dofh_filesz = len;
12346 dof->dofh_pad = 0;
12347
12348 /*
12349 * Fill in the option section header...
12350 */
12351 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12352 sec->dofs_type = DOF_SECT_OPTDESC;
12353 sec->dofs_align = sizeof (uint64_t);
12354 sec->dofs_flags = DOF_SECF_LOAD;
12355 sec->dofs_entsize = sizeof (dof_optdesc_t);
12356
12357 opt = (dof_optdesc_t *)((uintptr_t)sec +
12358 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12359
12360 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12361 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12362
12363 for (i = 0; i < DTRACEOPT_MAX; i++) {
12364 opt[i].dofo_option = i;
12365 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12366 opt[i].dofo_value = state->dts_options[i];
12367 }
12368
12369 return (dof);
12370 }
12371
12372 static dof_hdr_t *
12373 #if !defined(__APPLE__)
12374 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12375 #else
12376 dtrace_dof_copyin(user_addr_t uarg, int *errp)
12377 #endif
12378 {
12379 dof_hdr_t hdr, *dof;
12380
12381 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
12382
12383 /*
12384 * First, we're going to copyin() the sizeof (dof_hdr_t).
12385 */
12386 #if !defined(__APPLE__)
12387 if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12388 #else
12389 if (copyin(uarg, &hdr, sizeof (hdr)) != 0) {
12390 #endif
12391 dtrace_dof_error(NULL, "failed to copyin DOF header");
12392 *errp = EFAULT;
12393 return (NULL);
12394 }
12395
12396 /*
12397 * Now we'll allocate the entire DOF and copy it in -- provided
12398 * that the length isn't outrageous.
12399 */
12400 #if !defined(__APPLE__) /* Quiet compiler warnings */
12401 if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12402 #else
12403 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
12404 #endif /* __APPLE__ */
12405 dtrace_dof_error(&hdr, "load size exceeds maximum");
12406 *errp = E2BIG;
12407 return (NULL);
12408 }
12409
12410 if (hdr.dofh_loadsz < sizeof (hdr)) {
12411 dtrace_dof_error(&hdr, "invalid load size");
12412 *errp = EINVAL;
12413 return (NULL);
12414 }
12415
12416 #if !defined(__APPLE__)
12417 dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12418
12419 if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12420 dof->dofh_loadsz != hdr.dofh_loadsz) {
12421 kmem_free(dof, hdr.dofh_loadsz);
12422 *errp = EFAULT;
12423 return (NULL);
12424 }
12425 #else
12426 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
12427
12428 if (copyin(uarg, dof, hdr.dofh_loadsz) != 0 ||
12429 dof->dofh_loadsz != hdr.dofh_loadsz) {
12430 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
12431 *errp = EFAULT;
12432 return (NULL);
12433 }
12434 #endif
12435
12436 return (dof);
12437 }
12438
12439 #if defined(__APPLE__)
12440
12441 static dof_hdr_t *
12442 dtrace_dof_copyin_from_proc(proc_t* p, user_addr_t uarg, int *errp)
12443 {
12444 dof_hdr_t hdr, *dof;
12445
12446 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
12447
12448 /*
12449 * First, we're going to copyin() the sizeof (dof_hdr_t).
12450 */
12451 if (uread(p, &hdr, sizeof(hdr), uarg) != KERN_SUCCESS) {
12452 dtrace_dof_error(NULL, "failed to copyin DOF header");
12453 *errp = EFAULT;
12454 return (NULL);
12455 }
12456
12457 /*
12458 * Now we'll allocate the entire DOF and copy it in -- provided
12459 * that the length isn't outrageous.
12460 */
12461 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
12462 dtrace_dof_error(&hdr, "load size exceeds maximum");
12463 *errp = E2BIG;
12464 return (NULL);
12465 }
12466
12467 if (hdr.dofh_loadsz < sizeof (hdr)) {
12468 dtrace_dof_error(&hdr, "invalid load size");
12469 *errp = EINVAL;
12470 return (NULL);
12471 }
12472
12473 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
12474
12475 if (uread(p, dof, hdr.dofh_loadsz, uarg) != KERN_SUCCESS) {
12476 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
12477 *errp = EFAULT;
12478 return (NULL);
12479 }
12480
12481 return (dof);
12482 }
12483
12484 #endif /* __APPLE__ */
12485
12486 static dof_hdr_t *
12487 dtrace_dof_property(const char *name)
12488 {
12489 uchar_t *buf;
12490 uint64_t loadsz;
12491 unsigned int len, i;
12492 dof_hdr_t *dof;
12493
12494 /*
12495 * Unfortunately, array of values in .conf files are always (and
12496 * only) interpreted to be integer arrays. We must read our DOF
12497 * as an integer array, and then squeeze it into a byte array.
12498 */
12499 #if !defined(__APPLE__) /* Quiet compiler warnings */
12500 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12501 (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12502 return (NULL);
12503 #else
12504 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12505 name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12506 return (NULL);
12507 #endif /* __APPLE__ */
12508
12509 for (i = 0; i < len; i++)
12510 buf[i] = (uchar_t)(((int *)buf)[i]);
12511
12512 if (len < sizeof (dof_hdr_t)) {
12513 ddi_prop_free(buf);
12514 dtrace_dof_error(NULL, "truncated header");
12515 return (NULL);
12516 }
12517
12518 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12519 ddi_prop_free(buf);
12520 dtrace_dof_error(NULL, "truncated DOF");
12521 return (NULL);
12522 }
12523
12524 #if !defined(__APPLE__) /* Quiet compiler warnings */
12525 if (loadsz >= dtrace_dof_maxsize) {
12526 #else
12527 if (loadsz >= (uint64_t)dtrace_dof_maxsize) {
12528 #endif /* __APPLE__ */
12529 ddi_prop_free(buf);
12530 dtrace_dof_error(NULL, "oversized DOF");
12531 return (NULL);
12532 }
12533
12534 #if !defined(__APPLE__)
12535 dof = kmem_alloc(loadsz, KM_SLEEP);
12536 #else
12537 dof = dt_kmem_alloc_aligned(loadsz, 8, KM_SLEEP);
12538 #endif /* __APPLE__ */
12539 bcopy(buf, dof, loadsz);
12540 ddi_prop_free(buf);
12541
12542 return (dof);
12543 }
12544
12545 static void
12546 dtrace_dof_destroy(dof_hdr_t *dof)
12547 {
12548 #if !defined(__APPLE__)
12549 kmem_free(dof, dof->dofh_loadsz);
12550 #else
12551 dt_kmem_free_aligned(dof, dof->dofh_loadsz);
12552 #endif /* __APPLE__ */
12553 }
12554
12555 /*
12556 * Return the dof_sec_t pointer corresponding to a given section index. If the
12557 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
12558 * a type other than DOF_SECT_NONE is specified, the header is checked against
12559 * this type and NULL is returned if the types do not match.
12560 */
12561 static dof_sec_t *
12562 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12563 {
12564 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12565 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12566
12567 if (i >= dof->dofh_secnum) {
12568 dtrace_dof_error(dof, "referenced section index is invalid");
12569 return (NULL);
12570 }
12571
12572 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12573 dtrace_dof_error(dof, "referenced section is not loadable");
12574 return (NULL);
12575 }
12576
12577 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12578 dtrace_dof_error(dof, "referenced section is the wrong type");
12579 return (NULL);
12580 }
12581
12582 return (sec);
12583 }
12584
12585 static dtrace_probedesc_t *
12586 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12587 {
12588 dof_probedesc_t *probe;
12589 dof_sec_t *strtab;
12590 uintptr_t daddr = (uintptr_t)dof;
12591 uintptr_t str;
12592 size_t size;
12593
12594 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12595 dtrace_dof_error(dof, "invalid probe section");
12596 return (NULL);
12597 }
12598
12599 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12600 dtrace_dof_error(dof, "bad alignment in probe description");
12601 return (NULL);
12602 }
12603
12604 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12605 dtrace_dof_error(dof, "truncated probe description");
12606 return (NULL);
12607 }
12608
12609 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12610 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12611
12612 if (strtab == NULL)
12613 return (NULL);
12614
12615 str = daddr + strtab->dofs_offset;
12616 size = strtab->dofs_size;
12617
12618 if (probe->dofp_provider >= strtab->dofs_size) {
12619 dtrace_dof_error(dof, "corrupt probe provider");
12620 return (NULL);
12621 }
12622
12623 (void) strncpy(desc->dtpd_provider,
12624 (char *)(str + probe->dofp_provider),
12625 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12626 #if defined(__APPLE__) /* Employ size bounded string operation. */
12627 desc->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
12628 #endif /* __APPLE__ */
12629
12630 if (probe->dofp_mod >= strtab->dofs_size) {
12631 dtrace_dof_error(dof, "corrupt probe module");
12632 return (NULL);
12633 }
12634
12635 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12636 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12637 #if defined(__APPLE__) /* Employ size bounded string operation. */
12638 desc->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
12639 #endif /* __APPLE__ */
12640
12641 if (probe->dofp_func >= strtab->dofs_size) {
12642 dtrace_dof_error(dof, "corrupt probe function");
12643 return (NULL);
12644 }
12645
12646 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12647 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12648 #if defined(__APPLE__) /* Employ size bounded string operation. */
12649 desc->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
12650 #endif /* __APPLE__ */
12651
12652 if (probe->dofp_name >= strtab->dofs_size) {
12653 dtrace_dof_error(dof, "corrupt probe name");
12654 return (NULL);
12655 }
12656
12657 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12658 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12659 #if defined(__APPLE__) /* Employ size bounded string operation. */
12660 desc->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
12661 #endif /* __APPLE__ */
12662
12663 return (desc);
12664 }
12665
12666 static dtrace_difo_t *
12667 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12668 cred_t *cr)
12669 {
12670 dtrace_difo_t *dp;
12671 size_t ttl = 0;
12672 dof_difohdr_t *dofd;
12673 uintptr_t daddr = (uintptr_t)dof;
12674 size_t max_size = dtrace_difo_maxsize;
12675 #if !defined(__APPLE__) /* Quiet compiler warnings */
12676 int i, l, n;
12677 #else
12678 uint_t i;
12679 int l, n;
12680 #endif /* __APPLE__ */
12681
12682
12683 static const struct {
12684 int section;
12685 int bufoffs;
12686 int lenoffs;
12687 int entsize;
12688 int align;
12689 const char *msg;
12690 } difo[] = {
12691 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12692 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12693 sizeof (dif_instr_t), "multiple DIF sections" },
12694
12695 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12696 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12697 sizeof (uint64_t), "multiple integer tables" },
12698
12699 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12700 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12701 sizeof (char), "multiple string tables" },
12702
12703 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12704 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12705 sizeof (uint_t), "multiple variable tables" },
12706
12707 #if !defined(__APPLE__)
12708 { DOF_SECT_NONE, 0, 0, 0, NULL }
12709 #else
12710 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12711 #endif /* __APPLE__ */
12712 };
12713
12714 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12715 dtrace_dof_error(dof, "invalid DIFO header section");
12716 return (NULL);
12717 }
12718
12719 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12720 dtrace_dof_error(dof, "bad alignment in DIFO header");
12721 return (NULL);
12722 }
12723
12724 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12725 sec->dofs_size % sizeof (dof_secidx_t)) {
12726 dtrace_dof_error(dof, "bad size in DIFO header");
12727 return (NULL);
12728 }
12729
12730 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12731 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12732
12733 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12734 dp->dtdo_rtype = dofd->dofd_rtype;
12735
12736 for (l = 0; l < n; l++) {
12737 dof_sec_t *subsec;
12738 void **bufp;
12739 uint32_t *lenp;
12740
12741 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12742 dofd->dofd_links[l])) == NULL)
12743 goto err; /* invalid section link */
12744
12745 if (ttl + subsec->dofs_size > max_size) {
12746 dtrace_dof_error(dof, "exceeds maximum size");
12747 goto err;
12748 }
12749
12750 ttl += subsec->dofs_size;
12751
12752 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12753
12754 #if !defined(__APPLE__) /* Quiet compiler warnings */
12755 if (subsec->dofs_type != difo[i].section)
12756 continue;
12757 #else
12758 if (subsec->dofs_type != (uint32_t)difo[i].section)
12759 continue;
12760 #endif /* __APPLE __ */
12761
12762 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12763 dtrace_dof_error(dof, "section not loaded");
12764 goto err;
12765 }
12766
12767 #if !defined(__APPLE__) /* Quiet compiler warnings */
12768 if (subsec->dofs_align != difo[i].align) {
12769 dtrace_dof_error(dof, "bad alignment");
12770 goto err;
12771 }
12772 #else
12773 if (subsec->dofs_align != (uint32_t)difo[i].align) {
12774 dtrace_dof_error(dof, "bad alignment");
12775 goto err;
12776 }
12777 #endif /* __APPLE__ */
12778
12779 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12780 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12781
12782 if (*bufp != NULL) {
12783 dtrace_dof_error(dof, difo[i].msg);
12784 goto err;
12785 }
12786
12787 #if !defined(__APPLE__) /* Quiet compiler warnings */
12788 if (difo[i].entsize != subsec->dofs_entsize) {
12789 dtrace_dof_error(dof, "entry size mismatch");
12790 goto err;
12791 }
12792 #else
12793 if ((uint32_t)difo[i].entsize != subsec->dofs_entsize) {
12794 dtrace_dof_error(dof, "entry size mismatch");
12795 goto err;
12796 }
12797 #endif /* __APPLE__ */
12798
12799 if (subsec->dofs_entsize != 0 &&
12800 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12801 dtrace_dof_error(dof, "corrupt entry size");
12802 goto err;
12803 }
12804
12805 *lenp = subsec->dofs_size;
12806 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12807 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12808 *bufp, subsec->dofs_size);
12809
12810 if (subsec->dofs_entsize != 0)
12811 *lenp /= subsec->dofs_entsize;
12812
12813 break;
12814 }
12815
12816 /*
12817 * If we encounter a loadable DIFO sub-section that is not
12818 * known to us, assume this is a broken program and fail.
12819 */
12820 if (difo[i].section == DOF_SECT_NONE &&
12821 (subsec->dofs_flags & DOF_SECF_LOAD)) {
12822 dtrace_dof_error(dof, "unrecognized DIFO subsection");
12823 goto err;
12824 }
12825 }
12826
12827 if (dp->dtdo_buf == NULL) {
12828 /*
12829 * We can't have a DIF object without DIF text.
12830 */
12831 dtrace_dof_error(dof, "missing DIF text");
12832 goto err;
12833 }
12834
12835 /*
12836 * Before we validate the DIF object, run through the variable table
12837 * looking for the strings -- if any of their size are under, we'll set
12838 * their size to be the system-wide default string size. Note that
12839 * this should _not_ happen if the "strsize" option has been set --
12840 * in this case, the compiler should have set the size to reflect the
12841 * setting of the option.
12842 */
12843 for (i = 0; i < dp->dtdo_varlen; i++) {
12844 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12845 dtrace_diftype_t *t = &v->dtdv_type;
12846
12847 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12848 continue;
12849
12850 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12851 t->dtdt_size = dtrace_strsize_default;
12852 }
12853
12854 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12855 goto err;
12856
12857 dtrace_difo_init(dp, vstate);
12858 return (dp);
12859
12860 err:
12861 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12862 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12863 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12864 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12865
12866 kmem_free(dp, sizeof (dtrace_difo_t));
12867 return (NULL);
12868 }
12869
12870 static dtrace_predicate_t *
12871 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12872 cred_t *cr)
12873 {
12874 dtrace_difo_t *dp;
12875
12876 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12877 return (NULL);
12878
12879 return (dtrace_predicate_create(dp));
12880 }
12881
12882 static dtrace_actdesc_t *
12883 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12884 cred_t *cr)
12885 {
12886 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12887 dof_actdesc_t *desc;
12888 dof_sec_t *difosec;
12889 size_t offs;
12890 uintptr_t daddr = (uintptr_t)dof;
12891 uint64_t arg;
12892 dtrace_actkind_t kind;
12893
12894 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12895 dtrace_dof_error(dof, "invalid action section");
12896 return (NULL);
12897 }
12898
12899 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12900 dtrace_dof_error(dof, "truncated action description");
12901 return (NULL);
12902 }
12903
12904 if (sec->dofs_align != sizeof (uint64_t)) {
12905 dtrace_dof_error(dof, "bad alignment in action description");
12906 return (NULL);
12907 }
12908
12909 if (sec->dofs_size < sec->dofs_entsize) {
12910 dtrace_dof_error(dof, "section entry size exceeds total size");
12911 return (NULL);
12912 }
12913
12914 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12915 dtrace_dof_error(dof, "bad entry size in action description");
12916 return (NULL);
12917 }
12918
12919 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12920 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12921 return (NULL);
12922 }
12923
12924 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12925 desc = (dof_actdesc_t *)(daddr +
12926 (uintptr_t)sec->dofs_offset + offs);
12927 kind = (dtrace_actkind_t)desc->dofa_kind;
12928
12929 if (DTRACEACT_ISPRINTFLIKE(kind) &&
12930 (kind != DTRACEACT_PRINTA ||
12931 desc->dofa_strtab != DOF_SECIDX_NONE)) {
12932 dof_sec_t *strtab;
12933 char *str, *fmt;
12934 uint64_t i;
12935
12936 /*
12937 * printf()-like actions must have a format string.
12938 */
12939 if ((strtab = dtrace_dof_sect(dof,
12940 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12941 goto err;
12942
12943 str = (char *)((uintptr_t)dof +
12944 (uintptr_t)strtab->dofs_offset);
12945
12946 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12947 if (str[i] == '\0')
12948 break;
12949 }
12950
12951 if (i >= strtab->dofs_size) {
12952 dtrace_dof_error(dof, "bogus format string");
12953 goto err;
12954 }
12955
12956 if (i == desc->dofa_arg) {
12957 dtrace_dof_error(dof, "empty format string");
12958 goto err;
12959 }
12960
12961 i -= desc->dofa_arg;
12962 fmt = kmem_alloc(i + 1, KM_SLEEP);
12963 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12964 arg = (uint64_t)(uintptr_t)fmt;
12965 } else {
12966 if (kind == DTRACEACT_PRINTA) {
12967 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12968 arg = 0;
12969 } else {
12970 arg = desc->dofa_arg;
12971 }
12972 }
12973
12974 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12975 desc->dofa_uarg, arg);
12976
12977 if (last != NULL) {
12978 last->dtad_next = act;
12979 } else {
12980 first = act;
12981 }
12982
12983 last = act;
12984
12985 if (desc->dofa_difo == DOF_SECIDX_NONE)
12986 continue;
12987
12988 if ((difosec = dtrace_dof_sect(dof,
12989 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12990 goto err;
12991
12992 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12993
12994 if (act->dtad_difo == NULL)
12995 goto err;
12996 }
12997
12998 ASSERT(first != NULL);
12999 return (first);
13000
13001 err:
13002 for (act = first; act != NULL; act = next) {
13003 next = act->dtad_next;
13004 dtrace_actdesc_release(act, vstate);
13005 }
13006
13007 return (NULL);
13008 }
13009
13010 static dtrace_ecbdesc_t *
13011 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13012 cred_t *cr)
13013 {
13014 dtrace_ecbdesc_t *ep;
13015 dof_ecbdesc_t *ecb;
13016 dtrace_probedesc_t *desc;
13017 dtrace_predicate_t *pred = NULL;
13018
13019 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13020 dtrace_dof_error(dof, "truncated ECB description");
13021 return (NULL);
13022 }
13023
13024 if (sec->dofs_align != sizeof (uint64_t)) {
13025 dtrace_dof_error(dof, "bad alignment in ECB description");
13026 return (NULL);
13027 }
13028
13029 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13030 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13031
13032 if (sec == NULL)
13033 return (NULL);
13034
13035 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13036 ep->dted_uarg = ecb->dofe_uarg;
13037 desc = &ep->dted_probe;
13038
13039 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13040 goto err;
13041
13042 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13043 if ((sec = dtrace_dof_sect(dof,
13044 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13045 goto err;
13046
13047 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13048 goto err;
13049
13050 ep->dted_pred.dtpdd_predicate = pred;
13051 }
13052
13053 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13054 if ((sec = dtrace_dof_sect(dof,
13055 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13056 goto err;
13057
13058 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13059
13060 if (ep->dted_action == NULL)
13061 goto err;
13062 }
13063
13064 return (ep);
13065
13066 err:
13067 if (pred != NULL)
13068 dtrace_predicate_release(pred, vstate);
13069 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13070 return (NULL);
13071 }
13072
13073 #if !defined(__APPLE__) /* APPLE dyld has already done this for us */
13074 /*
13075 * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13076 * specified DOF. At present, this amounts to simply adding 'ubase' to the
13077 * site of any user SETX relocations to account for load object base address.
13078 * In the future, if we need other relocations, this function can be extended.
13079 */
13080 static int
13081 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
13082 {
13083 uintptr_t daddr = (uintptr_t)dof;
13084 dof_relohdr_t *dofr =
13085 (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13086 dof_sec_t *ss, *rs, *ts;
13087 dof_relodesc_t *r;
13088 uint_t i, n;
13089
13090 if (sec->dofs_size < sizeof (dof_relohdr_t) ||
13091 sec->dofs_align != sizeof (dof_secidx_t)) {
13092 dtrace_dof_error(dof, "invalid relocation header");
13093 return (-1);
13094 }
13095
13096 ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
13097 rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
13098 ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
13099
13100 if (ss == NULL || rs == NULL || ts == NULL)
13101 return (-1); /* dtrace_dof_error() has been called already */
13102
13103 if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
13104 rs->dofs_align != sizeof (uint64_t)) {
13105 dtrace_dof_error(dof, "invalid relocation section");
13106 return (-1);
13107 }
13108
13109 r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
13110 n = rs->dofs_size / rs->dofs_entsize;
13111
13112 for (i = 0; i < n; i++) {
13113 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
13114
13115 switch (r->dofr_type) {
13116 case DOF_RELO_NONE:
13117 break;
13118 case DOF_RELO_SETX:
13119 if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13120 sizeof (uint64_t) > ts->dofs_size) {
13121 dtrace_dof_error(dof, "bad relocation offset");
13122 return (-1);
13123 }
13124
13125 if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13126 dtrace_dof_error(dof, "misaligned setx relo");
13127 return (-1);
13128 }
13129
13130 *(uint64_t *)taddr += ubase;
13131 break;
13132 default:
13133 dtrace_dof_error(dof, "invalid relocation type");
13134 return (-1);
13135 }
13136
13137 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13138 }
13139
13140 return (0);
13141 }
13142 #endif /* __APPLE__ */
13143
13144 /*
13145 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13146 * header: it should be at the front of a memory region that is at least
13147 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13148 * size. It need not be validated in any other way.
13149 */
13150 static int
13151 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13152 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13153 {
13154 #pragma unused(ubase) /* __APPLE__ */
13155 uint64_t len = dof->dofh_loadsz, seclen;
13156 uintptr_t daddr = (uintptr_t)dof;
13157 dtrace_ecbdesc_t *ep;
13158 dtrace_enabling_t *enab;
13159 uint_t i;
13160
13161 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13162 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13163
13164 /*
13165 * Check the DOF header identification bytes. In addition to checking
13166 * valid settings, we also verify that unused bits/bytes are zeroed so
13167 * we can use them later without fear of regressing existing binaries.
13168 */
13169 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13170 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13171 dtrace_dof_error(dof, "DOF magic string mismatch");
13172 return (-1);
13173 }
13174
13175 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13176 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13177 dtrace_dof_error(dof, "DOF has invalid data model");
13178 return (-1);
13179 }
13180
13181 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13182 dtrace_dof_error(dof, "DOF encoding mismatch");
13183 return (-1);
13184 }
13185
13186 #if !defined(__APPLE__)
13187 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13188 dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13189 dtrace_dof_error(dof, "DOF version mismatch");
13190 return (-1);
13191 }
13192 #else
13193 /*
13194 * We only support DOF_VERSION_3 for now.
13195 */
13196 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_3) {
13197 dtrace_dof_error(dof, "DOF version mismatch");
13198 return (-1);
13199 }
13200 #endif
13201
13202 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13203 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13204 return (-1);
13205 }
13206
13207 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13208 dtrace_dof_error(dof, "DOF uses too many integer registers");
13209 return (-1);
13210 }
13211
13212 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13213 dtrace_dof_error(dof, "DOF uses too many tuple registers");
13214 return (-1);
13215 }
13216
13217 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13218 if (dof->dofh_ident[i] != 0) {
13219 dtrace_dof_error(dof, "DOF has invalid ident byte set");
13220 return (-1);
13221 }
13222 }
13223
13224 if (dof->dofh_flags & ~DOF_FL_VALID) {
13225 dtrace_dof_error(dof, "DOF has invalid flag bits set");
13226 return (-1);
13227 }
13228
13229 if (dof->dofh_secsize == 0) {
13230 dtrace_dof_error(dof, "zero section header size");
13231 return (-1);
13232 }
13233
13234 /*
13235 * Check that the section headers don't exceed the amount of DOF
13236 * data. Note that we cast the section size and number of sections
13237 * to uint64_t's to prevent possible overflow in the multiplication.
13238 */
13239 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13240
13241 if (dof->dofh_secoff > len || seclen > len ||
13242 dof->dofh_secoff + seclen > len) {
13243 dtrace_dof_error(dof, "truncated section headers");
13244 return (-1);
13245 }
13246
13247 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13248 dtrace_dof_error(dof, "misaligned section headers");
13249 return (-1);
13250 }
13251
13252 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13253 dtrace_dof_error(dof, "misaligned section size");
13254 return (-1);
13255 }
13256
13257 /*
13258 * Take an initial pass through the section headers to be sure that
13259 * the headers don't have stray offsets. If the 'noprobes' flag is
13260 * set, do not permit sections relating to providers, probes, or args.
13261 */
13262 for (i = 0; i < dof->dofh_secnum; i++) {
13263 dof_sec_t *sec = (dof_sec_t *)(daddr +
13264 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13265
13266 if (noprobes) {
13267 switch (sec->dofs_type) {
13268 case DOF_SECT_PROVIDER:
13269 case DOF_SECT_PROBES:
13270 case DOF_SECT_PRARGS:
13271 case DOF_SECT_PROFFS:
13272 dtrace_dof_error(dof, "illegal sections "
13273 "for enabling");
13274 return (-1);
13275 }
13276 }
13277
13278 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13279 continue; /* just ignore non-loadable sections */
13280
13281 if (sec->dofs_align & (sec->dofs_align - 1)) {
13282 dtrace_dof_error(dof, "bad section alignment");
13283 return (-1);
13284 }
13285
13286 if (sec->dofs_offset & (sec->dofs_align - 1)) {
13287 dtrace_dof_error(dof, "misaligned section");
13288 return (-1);
13289 }
13290
13291 if (sec->dofs_offset > len || sec->dofs_size > len ||
13292 sec->dofs_offset + sec->dofs_size > len) {
13293 dtrace_dof_error(dof, "corrupt section header");
13294 return (-1);
13295 }
13296
13297 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13298 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13299 dtrace_dof_error(dof, "non-terminating string table");
13300 return (-1);
13301 }
13302 }
13303
13304 #if !defined(__APPLE__)
13305 /*
13306 * Take a second pass through the sections and locate and perform any
13307 * relocations that are present. We do this after the first pass to
13308 * be sure that all sections have had their headers validated.
13309 */
13310 for (i = 0; i < dof->dofh_secnum; i++) {
13311 dof_sec_t *sec = (dof_sec_t *)(daddr +
13312 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13313
13314 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13315 continue; /* skip sections that are not loadable */
13316
13317 switch (sec->dofs_type) {
13318 case DOF_SECT_URELHDR:
13319 if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13320 return (-1);
13321 break;
13322 }
13323 }
13324 #else
13325 /*
13326 * APPLE NOTE: We have no relocation to perform. All dof values are
13327 * relative offsets.
13328 */
13329 #endif /* __APPLE__ */
13330
13331 if ((enab = *enabp) == NULL)
13332 enab = *enabp = dtrace_enabling_create(vstate);
13333
13334 for (i = 0; i < dof->dofh_secnum; i++) {
13335 dof_sec_t *sec = (dof_sec_t *)(daddr +
13336 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13337
13338 if (sec->dofs_type != DOF_SECT_ECBDESC)
13339 continue;
13340
13341 #if !defined(__APPLE__)
13342 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13343 dtrace_enabling_destroy(enab);
13344 *enabp = NULL;
13345 return (-1);
13346 }
13347 #else
13348 /* Note: Defend against gcc 4.0 botch on x86 (not all paths out of inlined dtrace_dof_ecbdesc
13349 are checked for the NULL return value.) */
13350 ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr);
13351 if (ep == NULL) {
13352 dtrace_enabling_destroy(enab);
13353 *enabp = NULL;
13354 return (-1);
13355 }
13356 #endif /* __APPLE__ */
13357
13358 dtrace_enabling_add(enab, ep);
13359 }
13360
13361 return (0);
13362 }
13363
13364 /*
13365 * Process DOF for any options. This routine assumes that the DOF has been
13366 * at least processed by dtrace_dof_slurp().
13367 */
13368 static int
13369 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13370 {
13371 #if !defined(__APPLE__) /* Quiet compiler warnings */
13372 int i, rval;
13373 #else
13374 uint_t i;
13375 int rval;
13376 #endif /* __APPLE__ */
13377 uint32_t entsize;
13378 size_t offs;
13379 dof_optdesc_t *desc;
13380
13381 for (i = 0; i < dof->dofh_secnum; i++) {
13382 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13383 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13384
13385 if (sec->dofs_type != DOF_SECT_OPTDESC)
13386 continue;
13387
13388 if (sec->dofs_align != sizeof (uint64_t)) {
13389 dtrace_dof_error(dof, "bad alignment in "
13390 "option description");
13391 return (EINVAL);
13392 }
13393
13394 if ((entsize = sec->dofs_entsize) == 0) {
13395 dtrace_dof_error(dof, "zeroed option entry size");
13396 return (EINVAL);
13397 }
13398
13399 if (entsize < sizeof (dof_optdesc_t)) {
13400 dtrace_dof_error(dof, "bad option entry size");
13401 return (EINVAL);
13402 }
13403
13404 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13405 desc = (dof_optdesc_t *)((uintptr_t)dof +
13406 (uintptr_t)sec->dofs_offset + offs);
13407
13408 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13409 dtrace_dof_error(dof, "non-zero option string");
13410 return (EINVAL);
13411 }
13412
13413 #if !defined(__APPLE__) /* Quiet compiler warnings */
13414 if (desc->dofo_value == DTRACEOPT_UNSET) {
13415 #else
13416 if (desc->dofo_value == (uint64_t)DTRACEOPT_UNSET) {
13417 #endif /* __APPLE __ */
13418 dtrace_dof_error(dof, "unset option");
13419 return (EINVAL);
13420 }
13421
13422 if ((rval = dtrace_state_option(state,
13423 desc->dofo_option, desc->dofo_value)) != 0) {
13424 dtrace_dof_error(dof, "rejected option");
13425 return (rval);
13426 }
13427 }
13428 }
13429
13430 return (0);
13431 }
13432
13433 /*
13434 * DTrace Consumer State Functions
13435 */
13436 #if defined(__APPLE__) /* Quiet compiler warning. */
13437 static
13438 #endif /* __APPLE__ */
13439 int
13440 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13441 {
13442 size_t hashsize, maxper, min_size, chunksize = dstate->dtds_chunksize;
13443 void *base;
13444 uintptr_t limit;
13445 dtrace_dynvar_t *dvar, *next, *start;
13446 #if !defined(__APPLE__) /* Quiet compiler warning */
13447 int i;
13448 #else
13449 size_t i;
13450 #endif /* __APPLE__ */
13451
13452 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13453 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13454
13455 bzero(dstate, sizeof (dtrace_dstate_t));
13456
13457 if ((dstate->dtds_chunksize = chunksize) == 0)
13458 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13459
13460 if (size < (min_size = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13461 size = min_size;
13462
13463 if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
13464 return (ENOMEM);
13465
13466 dstate->dtds_size = size;
13467 dstate->dtds_base = base;
13468 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13469 bzero(dstate->dtds_percpu, (int)NCPU * sizeof (dtrace_dstate_percpu_t));
13470
13471 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13472
13473 if (hashsize != 1 && (hashsize & 1))
13474 hashsize--;
13475
13476 dstate->dtds_hashsize = hashsize;
13477 dstate->dtds_hash = dstate->dtds_base;
13478
13479 /*
13480 * Set all of our hash buckets to point to the single sink, and (if
13481 * it hasn't already been set), set the sink's hash value to be the
13482 * sink sentinel value. The sink is needed for dynamic variable
13483 * lookups to know that they have iterated over an entire, valid hash
13484 * chain.
13485 */
13486 for (i = 0; i < hashsize; i++)
13487 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13488
13489 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13490 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13491
13492 /*
13493 * Determine number of active CPUs. Divide free list evenly among
13494 * active CPUs.
13495 */
13496 start = (dtrace_dynvar_t *)
13497 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13498 limit = (uintptr_t)base + size;
13499
13500 maxper = (limit - (uintptr_t)start) / (int)NCPU;
13501 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13502
13503 for (i = 0; i < NCPU; i++) {
13504 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13505
13506 /*
13507 * If we don't even have enough chunks to make it once through
13508 * NCPUs, we're just going to allocate everything to the first
13509 * CPU. And if we're on the last CPU, we're going to allocate
13510 * whatever is left over. In either case, we set the limit to
13511 * be the limit of the dynamic variable space.
13512 */
13513 if (maxper == 0 || i == NCPU - 1) {
13514 limit = (uintptr_t)base + size;
13515 start = NULL;
13516 } else {
13517 limit = (uintptr_t)start + maxper;
13518 start = (dtrace_dynvar_t *)limit;
13519 }
13520
13521 ASSERT(limit <= (uintptr_t)base + size);
13522
13523 for (;;) {
13524 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13525 dstate->dtds_chunksize);
13526
13527 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13528 break;
13529
13530 dvar->dtdv_next = next;
13531 dvar = next;
13532 }
13533
13534 if (maxper == 0)
13535 break;
13536 }
13537
13538 return (0);
13539 }
13540
13541 #if defined(__APPLE__) /* Quiet compiler warning. */
13542 static
13543 #endif /* __APPLE__ */
13544 void
13545 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13546 {
13547 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13548
13549 if (dstate->dtds_base == NULL)
13550 return;
13551
13552 kmem_free(dstate->dtds_base, dstate->dtds_size);
13553 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13554 }
13555
13556 static void
13557 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13558 {
13559 /*
13560 * Logical XOR, where are you?
13561 */
13562 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13563
13564 if (vstate->dtvs_nglobals > 0) {
13565 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13566 sizeof (dtrace_statvar_t *));
13567 }
13568
13569 if (vstate->dtvs_ntlocals > 0) {
13570 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13571 sizeof (dtrace_difv_t));
13572 }
13573
13574 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13575
13576 if (vstate->dtvs_nlocals > 0) {
13577 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13578 sizeof (dtrace_statvar_t *));
13579 }
13580 }
13581
13582 static void
13583 dtrace_state_clean(dtrace_state_t *state)
13584 {
13585 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13586 return;
13587
13588 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13589 dtrace_speculation_clean(state);
13590 }
13591
13592 static void
13593 dtrace_state_deadman(dtrace_state_t *state)
13594 {
13595 hrtime_t now;
13596
13597 dtrace_sync();
13598
13599 now = dtrace_gethrtime();
13600
13601 if (state != dtrace_anon.dta_state &&
13602 now - state->dts_laststatus >= dtrace_deadman_user)
13603 return;
13604
13605 /*
13606 * We must be sure that dts_alive never appears to be less than the
13607 * value upon entry to dtrace_state_deadman(), and because we lack a
13608 * dtrace_cas64(), we cannot store to it atomically. We thus instead
13609 * store INT64_MAX to it, followed by a memory barrier, followed by
13610 * the new value. This assures that dts_alive never appears to be
13611 * less than its true value, regardless of the order in which the
13612 * stores to the underlying storage are issued.
13613 */
13614 state->dts_alive = INT64_MAX;
13615 dtrace_membar_producer();
13616 state->dts_alive = now;
13617 }
13618
13619 #if !defined(__APPLE__)
13620 dtrace_state_t *
13621 dtrace_state_create(dev_t *devp, cred_t *cr)
13622 #else
13623 static int
13624 dtrace_state_create(dev_t *devp, cred_t *cr, dtrace_state_t **new_state)
13625 #endif /* __APPLE__ */
13626 {
13627 minor_t minor;
13628 major_t major;
13629 char c[30];
13630 dtrace_state_t *state;
13631 dtrace_optval_t *opt;
13632 int bufsize = (int)NCPU * sizeof (dtrace_buffer_t), i;
13633
13634 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13635 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13636
13637 #if !defined(__APPLE__)
13638 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13639 VM_BESTFIT | VM_SLEEP);
13640
13641 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13642 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13643 return (NULL);
13644 }
13645 #else
13646 /* Cause restart */
13647 *new_state = NULL;
13648
13649 /*
13650 * Darwin's DEVFS layer acquired the minor number for this "device" when it called
13651 * dtrace_devfs_clone_func(). At that time, dtrace_devfs_clone_func() proposed a minor number
13652 * (next unused according to vmem_alloc()) and then immediately put the number back in play
13653 * (by calling vmem_free()). Now that minor number is being used for an open, so committing it
13654 * to use. The following vmem_alloc() must deliver that same minor number. FIXME.
13655 */
13656
13657 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13658 VM_BESTFIT | VM_SLEEP);
13659
13660 if (NULL != devp) {
13661 ASSERT(getminor(*devp) == minor);
13662 if (getminor(*devp) != minor) {
13663 printf("dtrace_open: couldn't re-acquire vended minor number %d. Instead got %d\n",
13664 getminor(*devp), minor);
13665 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13666 return (ERESTART); /* can't reacquire */
13667 }
13668 } else {
13669 /* NULL==devp iff "Anonymous state" (see dtrace_anon_property),
13670 * so just vend the minor device number here de novo since no "open" has occurred. */
13671 }
13672
13673 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13674 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13675 return (EAGAIN); /* temporary resource shortage */
13676 }
13677
13678 #endif /* __APPLE__ */
13679
13680 state = ddi_get_soft_state(dtrace_softstate, minor);
13681 state->dts_epid = DTRACE_EPIDNONE + 1;
13682
13683 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13684 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13685 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13686
13687 if (devp != NULL) {
13688 major = getemajor(*devp);
13689 } else {
13690 major = ddi_driver_major(dtrace_devi);
13691 }
13692
13693 state->dts_dev = makedevice(major, minor);
13694
13695 if (devp != NULL)
13696 *devp = state->dts_dev;
13697
13698 /*
13699 * We allocate NCPU buffers. On the one hand, this can be quite
13700 * a bit of memory per instance (nearly 36K on a Starcat). On the
13701 * other hand, it saves an additional memory reference in the probe
13702 * path.
13703 */
13704 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13705 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13706 state->dts_cleaner = CYCLIC_NONE;
13707 state->dts_deadman = CYCLIC_NONE;
13708 state->dts_vstate.dtvs_state = state;
13709
13710 for (i = 0; i < DTRACEOPT_MAX; i++)
13711 state->dts_options[i] = DTRACEOPT_UNSET;
13712
13713 /*
13714 * Set the default options.
13715 */
13716 opt = state->dts_options;
13717 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13718 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13719 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13720 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13721 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13722 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13723 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13724 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13725 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13726 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13727 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13728 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13729 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13730 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13731
13732 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13733
13734 /*
13735 * Depending on the user credentials, we set flag bits which alter probe
13736 * visibility or the amount of destructiveness allowed. In the case of
13737 * actual anonymous tracing, or the possession of all privileges, all of
13738 * the normal checks are bypassed.
13739 */
13740 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13741 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13742 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13743 } else {
13744 /*
13745 * Set up the credentials for this instantiation. We take a
13746 * hold on the credential to prevent it from disappearing on
13747 * us; this in turn prevents the zone_t referenced by this
13748 * credential from disappearing. This means that we can
13749 * examine the credential and the zone from probe context.
13750 */
13751 crhold(cr);
13752 state->dts_cred.dcr_cred = cr;
13753
13754 /*
13755 * CRA_PROC means "we have *some* privilege for dtrace" and
13756 * unlocks the use of variables like pid, zonename, etc.
13757 */
13758 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13759 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13760 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13761 }
13762
13763 /*
13764 * dtrace_user allows use of syscall and profile providers.
13765 * If the user also has proc_owner and/or proc_zone, we
13766 * extend the scope to include additional visibility and
13767 * destructive power.
13768 */
13769 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13770 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13771 state->dts_cred.dcr_visible |=
13772 DTRACE_CRV_ALLPROC;
13773
13774 state->dts_cred.dcr_action |=
13775 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13776 }
13777
13778 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13779 state->dts_cred.dcr_visible |=
13780 DTRACE_CRV_ALLZONE;
13781
13782 state->dts_cred.dcr_action |=
13783 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13784 }
13785
13786 /*
13787 * If we have all privs in whatever zone this is,
13788 * we can do destructive things to processes which
13789 * have altered credentials.
13790 */
13791 #if !defined(__APPLE__)
13792 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13793 cr->cr_zone->zone_privset)) {
13794 state->dts_cred.dcr_action |=
13795 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13796 }
13797 #else
13798 /* Darwin doesn't do zones. */
13799 state->dts_cred.dcr_action |=
13800 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13801 #endif /* __APPLE__ */
13802 }
13803
13804 /*
13805 * Holding the dtrace_kernel privilege also implies that
13806 * the user has the dtrace_user privilege from a visibility
13807 * perspective. But without further privileges, some
13808 * destructive actions are not available.
13809 */
13810 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13811 /*
13812 * Make all probes in all zones visible. However,
13813 * this doesn't mean that all actions become available
13814 * to all zones.
13815 */
13816 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13817 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13818
13819 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13820 DTRACE_CRA_PROC;
13821 /*
13822 * Holding proc_owner means that destructive actions
13823 * for *this* zone are allowed.
13824 */
13825 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13826 state->dts_cred.dcr_action |=
13827 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13828
13829 /*
13830 * Holding proc_zone means that destructive actions
13831 * for this user/group ID in all zones is allowed.
13832 */
13833 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13834 state->dts_cred.dcr_action |=
13835 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13836
13837 /*
13838 * If we have all privs in whatever zone this is,
13839 * we can do destructive things to processes which
13840 * have altered credentials.
13841 */
13842 #if !defined(__APPLE__)
13843 if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13844 cr->cr_zone->zone_privset)) {
13845 state->dts_cred.dcr_action |=
13846 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13847 }
13848 #else
13849 /* Darwin doesn't do zones. */
13850 state->dts_cred.dcr_action |=
13851 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13852 #endif /* __APPLE__ */
13853 }
13854
13855 /*
13856 * Holding the dtrace_proc privilege gives control over fasttrap
13857 * and pid providers. We need to grant wider destructive
13858 * privileges in the event that the user has proc_owner and/or
13859 * proc_zone.
13860 */
13861 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13862 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13863 state->dts_cred.dcr_action |=
13864 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13865
13866 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13867 state->dts_cred.dcr_action |=
13868 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13869 }
13870 }
13871
13872 #if !defined(__APPLE__)
13873 return (state);
13874 #else
13875 *new_state = state;
13876 return(0); /* Success */
13877 #endif /* __APPLE__ */
13878 }
13879
13880 static int
13881 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13882 {
13883 dtrace_optval_t *opt = state->dts_options, size;
13884 processorid_t cpu = 0;
13885 int flags = 0, rval;
13886
13887 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13888 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13889 ASSERT(which < DTRACEOPT_MAX);
13890 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13891 (state == dtrace_anon.dta_state &&
13892 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13893
13894 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13895 return (0);
13896
13897 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13898 cpu = opt[DTRACEOPT_CPU];
13899
13900 if (which == DTRACEOPT_SPECSIZE)
13901 flags |= DTRACEBUF_NOSWITCH;
13902
13903 if (which == DTRACEOPT_BUFSIZE) {
13904 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13905 flags |= DTRACEBUF_RING;
13906
13907 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13908 flags |= DTRACEBUF_FILL;
13909
13910 if (state != dtrace_anon.dta_state ||
13911 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13912 flags |= DTRACEBUF_INACTIVE;
13913 }
13914
13915 #if !defined(__APPLE__) /* Quiet compiler warning */
13916 for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
13917 #else
13918 for (size = opt[which]; (size_t)size >= sizeof (uint64_t); size >>= 1) {
13919 #endif /* __APPLE__ */
13920 /*
13921 * The size must be 8-byte aligned. If the size is not 8-byte
13922 * aligned, drop it down by the difference.
13923 */
13924 if (size & (sizeof (uint64_t) - 1))
13925 size -= size & (sizeof (uint64_t) - 1);
13926
13927 if (size < state->dts_reserve) {
13928 /*
13929 * Buffers always must be large enough to accommodate
13930 * their prereserved space. We return E2BIG instead
13931 * of ENOMEM in this case to allow for user-level
13932 * software to differentiate the cases.
13933 */
13934 return (E2BIG);
13935 }
13936
13937 rval = dtrace_buffer_alloc(buf, size, flags, cpu);
13938
13939 if (rval != ENOMEM) {
13940 opt[which] = size;
13941 return (rval);
13942 }
13943
13944 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13945 return (rval);
13946 }
13947
13948 return (ENOMEM);
13949 }
13950
13951 static int
13952 dtrace_state_buffers(dtrace_state_t *state)
13953 {
13954 dtrace_speculation_t *spec = state->dts_speculations;
13955 int rval, i;
13956
13957 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13958 DTRACEOPT_BUFSIZE)) != 0)
13959 return (rval);
13960
13961 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13962 DTRACEOPT_AGGSIZE)) != 0)
13963 return (rval);
13964
13965 for (i = 0; i < state->dts_nspeculations; i++) {
13966 if ((rval = dtrace_state_buffer(state,
13967 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13968 return (rval);
13969 }
13970
13971 return (0);
13972 }
13973
13974 static void
13975 dtrace_state_prereserve(dtrace_state_t *state)
13976 {
13977 dtrace_ecb_t *ecb;
13978 dtrace_probe_t *probe;
13979
13980 state->dts_reserve = 0;
13981
13982 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13983 return;
13984
13985 /*
13986 * If our buffer policy is a "fill" buffer policy, we need to set the
13987 * prereserved space to be the space required by the END probes.
13988 */
13989 probe = dtrace_probes[dtrace_probeid_end - 1];
13990 ASSERT(probe != NULL);
13991
13992 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13993 if (ecb->dte_state != state)
13994 continue;
13995
13996 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13997 }
13998 }
13999
14000 static int
14001 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14002 {
14003 dtrace_optval_t *opt = state->dts_options, sz, nspec;
14004 dtrace_speculation_t *spec;
14005 dtrace_buffer_t *buf;
14006 cyc_handler_t hdlr;
14007 cyc_time_t when;
14008 int rval = 0, i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
14009 dtrace_icookie_t cookie;
14010
14011 lck_mtx_lock(&cpu_lock);
14012 lck_mtx_lock(&dtrace_lock);
14013
14014 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14015 rval = EBUSY;
14016 goto out;
14017 }
14018
14019 /*
14020 * Before we can perform any checks, we must prime all of the
14021 * retained enablings that correspond to this state.
14022 */
14023 dtrace_enabling_prime(state);
14024
14025 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14026 rval = EACCES;
14027 goto out;
14028 }
14029
14030 dtrace_state_prereserve(state);
14031
14032 /*
14033 * Now we want to do is try to allocate our speculations.
14034 * We do not automatically resize the number of speculations; if
14035 * this fails, we will fail the operation.
14036 */
14037 nspec = opt[DTRACEOPT_NSPEC];
14038 ASSERT(nspec != DTRACEOPT_UNSET);
14039
14040 if (nspec > INT_MAX) {
14041 rval = ENOMEM;
14042 goto out;
14043 }
14044
14045 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
14046
14047 if (spec == NULL) {
14048 rval = ENOMEM;
14049 goto out;
14050 }
14051
14052 state->dts_speculations = spec;
14053 state->dts_nspeculations = (int)nspec;
14054
14055 for (i = 0; i < nspec; i++) {
14056 if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
14057 rval = ENOMEM;
14058 goto err;
14059 }
14060
14061 spec[i].dtsp_buffer = buf;
14062 }
14063
14064 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14065 if (dtrace_anon.dta_state == NULL) {
14066 rval = ENOENT;
14067 goto out;
14068 }
14069
14070 if (state->dts_necbs != 0) {
14071 rval = EALREADY;
14072 goto out;
14073 }
14074
14075 state->dts_anon = dtrace_anon_grab();
14076 ASSERT(state->dts_anon != NULL);
14077 state = state->dts_anon;
14078
14079 /*
14080 * We want "grabanon" to be set in the grabbed state, so we'll
14081 * copy that option value from the grabbing state into the
14082 * grabbed state.
14083 */
14084 state->dts_options[DTRACEOPT_GRABANON] =
14085 opt[DTRACEOPT_GRABANON];
14086
14087 *cpu = dtrace_anon.dta_beganon;
14088
14089 /*
14090 * If the anonymous state is active (as it almost certainly
14091 * is if the anonymous enabling ultimately matched anything),
14092 * we don't allow any further option processing -- but we
14093 * don't return failure.
14094 */
14095 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14096 goto out;
14097 }
14098
14099 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14100 opt[DTRACEOPT_AGGSIZE] != 0) {
14101 if (state->dts_aggregations == NULL) {
14102 /*
14103 * We're not going to create an aggregation buffer
14104 * because we don't have any ECBs that contain
14105 * aggregations -- set this option to 0.
14106 */
14107 opt[DTRACEOPT_AGGSIZE] = 0;
14108 } else {
14109 /*
14110 * If we have an aggregation buffer, we must also have
14111 * a buffer to use as scratch.
14112 */
14113 #if !defined(__APPLE__) /* Quiet compiler warning */
14114 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14115 opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14116 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14117 }
14118 #else
14119 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14120 (size_t)opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14121 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14122 }
14123 #endif /* __APPLE__ */
14124 }
14125 }
14126
14127 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14128 opt[DTRACEOPT_SPECSIZE] != 0) {
14129 if (!state->dts_speculates) {
14130 /*
14131 * We're not going to create speculation buffers
14132 * because we don't have any ECBs that actually
14133 * speculate -- set the speculation size to 0.
14134 */
14135 opt[DTRACEOPT_SPECSIZE] = 0;
14136 }
14137 }
14138
14139 /*
14140 * The bare minimum size for any buffer that we're actually going to
14141 * do anything to is sizeof (uint64_t).
14142 */
14143 sz = sizeof (uint64_t);
14144
14145 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14146 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14147 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14148 /*
14149 * A buffer size has been explicitly set to 0 (or to a size
14150 * that will be adjusted to 0) and we need the space -- we
14151 * need to return failure. We return ENOSPC to differentiate
14152 * it from failing to allocate a buffer due to failure to meet
14153 * the reserve (for which we return E2BIG).
14154 */
14155 rval = ENOSPC;
14156 goto out;
14157 }
14158
14159 if ((rval = dtrace_state_buffers(state)) != 0)
14160 goto err;
14161
14162 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14163 sz = dtrace_dstate_defsize;
14164
14165 do {
14166 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14167
14168 if (rval == 0)
14169 break;
14170
14171 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14172 goto err;
14173 } while (sz >>= 1);
14174
14175 opt[DTRACEOPT_DYNVARSIZE] = sz;
14176
14177 if (rval != 0)
14178 goto err;
14179
14180 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14181 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14182
14183 if (opt[DTRACEOPT_CLEANRATE] == 0)
14184 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14185
14186 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14187 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14188
14189 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14190 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14191
14192 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14193 hdlr.cyh_arg = state;
14194 hdlr.cyh_level = CY_LOW_LEVEL;
14195
14196 when.cyt_when = 0;
14197 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14198
14199 state->dts_cleaner = cyclic_add(&hdlr, &when);
14200
14201 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14202 hdlr.cyh_arg = state;
14203 hdlr.cyh_level = CY_LOW_LEVEL;
14204
14205 when.cyt_when = 0;
14206 when.cyt_interval = dtrace_deadman_interval;
14207
14208 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14209 state->dts_deadman = cyclic_add(&hdlr, &when);
14210
14211 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14212
14213 /*
14214 * Now it's time to actually fire the BEGIN probe. We need to disable
14215 * interrupts here both to record the CPU on which we fired the BEGIN
14216 * probe (the data from this CPU will be processed first at user
14217 * level) and to manually activate the buffer for this CPU.
14218 */
14219 cookie = dtrace_interrupt_disable();
14220 *cpu = CPU->cpu_id;
14221 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14222 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14223
14224 dtrace_probe(dtrace_probeid_begin,
14225 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14226 dtrace_interrupt_enable(cookie);
14227 /*
14228 * We may have had an exit action from a BEGIN probe; only change our
14229 * state to ACTIVE if we're still in WARMUP.
14230 */
14231 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14232 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14233
14234 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14235 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14236
14237 /*
14238 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14239 * want each CPU to transition its principal buffer out of the
14240 * INACTIVE state. Doing this assures that no CPU will suddenly begin
14241 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14242 * atomically transition from processing none of a state's ECBs to
14243 * processing all of them.
14244 */
14245 dtrace_xcall(DTRACE_CPUALL,
14246 (dtrace_xcall_t)dtrace_buffer_activate, state);
14247 goto out;
14248
14249 err:
14250 dtrace_buffer_free(state->dts_buffer);
14251 dtrace_buffer_free(state->dts_aggbuffer);
14252
14253 if ((nspec = state->dts_nspeculations) == 0) {
14254 ASSERT(state->dts_speculations == NULL);
14255 goto out;
14256 }
14257
14258 spec = state->dts_speculations;
14259 ASSERT(spec != NULL);
14260
14261 for (i = 0; i < state->dts_nspeculations; i++) {
14262 if ((buf = spec[i].dtsp_buffer) == NULL)
14263 break;
14264
14265 dtrace_buffer_free(buf);
14266 kmem_free(buf, bufsize);
14267 }
14268
14269 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14270 state->dts_nspeculations = 0;
14271 state->dts_speculations = NULL;
14272
14273 out:
14274 lck_mtx_unlock(&dtrace_lock);
14275 lck_mtx_unlock(&cpu_lock);
14276
14277 return (rval);
14278 }
14279
14280 static int
14281 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14282 {
14283 dtrace_icookie_t cookie;
14284
14285 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14286
14287 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14288 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14289 return (EINVAL);
14290
14291 /*
14292 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14293 * to be sure that every CPU has seen it. See below for the details
14294 * on why this is done.
14295 */
14296 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14297 dtrace_sync();
14298
14299 /*
14300 * By this point, it is impossible for any CPU to be still processing
14301 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
14302 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14303 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
14304 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14305 * iff we're in the END probe.
14306 */
14307 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14308 dtrace_sync();
14309 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14310
14311 /*
14312 * Finally, we can release the reserve and call the END probe. We
14313 * disable interrupts across calling the END probe to allow us to
14314 * return the CPU on which we actually called the END probe. This
14315 * allows user-land to be sure that this CPU's principal buffer is
14316 * processed last.
14317 */
14318 state->dts_reserve = 0;
14319
14320 cookie = dtrace_interrupt_disable();
14321 *cpu = CPU->cpu_id;
14322 dtrace_probe(dtrace_probeid_end,
14323 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14324 dtrace_interrupt_enable(cookie);
14325
14326 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14327 dtrace_sync();
14328
14329 return (0);
14330 }
14331
14332 static int
14333 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14334 dtrace_optval_t val)
14335 {
14336 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14337
14338 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14339 return (EBUSY);
14340
14341 if (option >= DTRACEOPT_MAX)
14342 return (EINVAL);
14343
14344 if (option != DTRACEOPT_CPU && val < 0)
14345 return (EINVAL);
14346
14347 switch (option) {
14348 case DTRACEOPT_DESTRUCTIVE:
14349 if (dtrace_destructive_disallow)
14350 return (EACCES);
14351
14352 state->dts_cred.dcr_destructive = 1;
14353 break;
14354
14355 case DTRACEOPT_BUFSIZE:
14356 case DTRACEOPT_DYNVARSIZE:
14357 case DTRACEOPT_AGGSIZE:
14358 case DTRACEOPT_SPECSIZE:
14359 case DTRACEOPT_STRSIZE:
14360 if (val < 0)
14361 return (EINVAL);
14362
14363 if (val >= LONG_MAX) {
14364 /*
14365 * If this is an otherwise negative value, set it to
14366 * the highest multiple of 128m less than LONG_MAX.
14367 * Technically, we're adjusting the size without
14368 * regard to the buffer resizing policy, but in fact,
14369 * this has no effect -- if we set the buffer size to
14370 * ~LONG_MAX and the buffer policy is ultimately set to
14371 * be "manual", the buffer allocation is guaranteed to
14372 * fail, if only because the allocation requires two
14373 * buffers. (We set the the size to the highest
14374 * multiple of 128m because it ensures that the size
14375 * will remain a multiple of a megabyte when
14376 * repeatedly halved -- all the way down to 15m.)
14377 */
14378 val = LONG_MAX - (1 << 27) + 1;
14379 }
14380 }
14381
14382 state->dts_options[option] = val;
14383
14384 return (0);
14385 }
14386
14387 static void
14388 dtrace_state_destroy(dtrace_state_t *state)
14389 {
14390 dtrace_ecb_t *ecb;
14391 dtrace_vstate_t *vstate = &state->dts_vstate;
14392 minor_t minor = getminor(state->dts_dev);
14393 int i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
14394 dtrace_speculation_t *spec = state->dts_speculations;
14395 int nspec = state->dts_nspeculations;
14396 uint32_t match;
14397
14398 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14399 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14400
14401 /*
14402 * First, retract any retained enablings for this state.
14403 */
14404 dtrace_enabling_retract(state);
14405 ASSERT(state->dts_nretained == 0);
14406
14407 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14408 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14409 /*
14410 * We have managed to come into dtrace_state_destroy() on a
14411 * hot enabling -- almost certainly because of a disorderly
14412 * shutdown of a consumer. (That is, a consumer that is
14413 * exiting without having called dtrace_stop().) In this case,
14414 * we're going to set our activity to be KILLED, and then
14415 * issue a sync to be sure that everyone is out of probe
14416 * context before we start blowing away ECBs.
14417 */
14418 state->dts_activity = DTRACE_ACTIVITY_KILLED;
14419 dtrace_sync();
14420 }
14421
14422 /*
14423 * Release the credential hold we took in dtrace_state_create().
14424 */
14425 if (state->dts_cred.dcr_cred != NULL)
14426 crfree(state->dts_cred.dcr_cred);
14427
14428 /*
14429 * Now we can safely disable and destroy any enabled probes. Because
14430 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14431 * (especially if they're all enabled), we take two passes through the
14432 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14433 * in the second we disable whatever is left over.
14434 */
14435 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14436 for (i = 0; i < state->dts_necbs; i++) {
14437 if ((ecb = state->dts_ecbs[i]) == NULL)
14438 continue;
14439
14440 if (match && ecb->dte_probe != NULL) {
14441 dtrace_probe_t *probe = ecb->dte_probe;
14442 dtrace_provider_t *prov = probe->dtpr_provider;
14443
14444 if (!(prov->dtpv_priv.dtpp_flags & match))
14445 continue;
14446 }
14447
14448 dtrace_ecb_disable(ecb);
14449 dtrace_ecb_destroy(ecb);
14450 }
14451
14452 if (!match)
14453 break;
14454 }
14455
14456 /*
14457 * Before we free the buffers, perform one more sync to assure that
14458 * every CPU is out of probe context.
14459 */
14460 dtrace_sync();
14461
14462 dtrace_buffer_free(state->dts_buffer);
14463 dtrace_buffer_free(state->dts_aggbuffer);
14464
14465 for (i = 0; i < nspec; i++)
14466 dtrace_buffer_free(spec[i].dtsp_buffer);
14467
14468 if (state->dts_cleaner != CYCLIC_NONE)
14469 cyclic_remove(state->dts_cleaner);
14470
14471 if (state->dts_deadman != CYCLIC_NONE)
14472 cyclic_remove(state->dts_deadman);
14473
14474 dtrace_dstate_fini(&vstate->dtvs_dynvars);
14475 dtrace_vstate_fini(vstate);
14476 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14477
14478 if (state->dts_aggregations != NULL) {
14479 #if DEBUG
14480 for (i = 0; i < state->dts_naggregations; i++)
14481 ASSERT(state->dts_aggregations[i] == NULL);
14482 #endif
14483 ASSERT(state->dts_naggregations > 0);
14484 kmem_free(state->dts_aggregations,
14485 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14486 }
14487
14488 kmem_free(state->dts_buffer, bufsize);
14489 kmem_free(state->dts_aggbuffer, bufsize);
14490
14491 for (i = 0; i < nspec; i++)
14492 kmem_free(spec[i].dtsp_buffer, bufsize);
14493
14494 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14495
14496 dtrace_format_destroy(state);
14497
14498 vmem_destroy(state->dts_aggid_arena);
14499 ddi_soft_state_free(dtrace_softstate, minor);
14500 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14501 }
14502
14503 /*
14504 * DTrace Anonymous Enabling Functions
14505 */
14506 static dtrace_state_t *
14507 dtrace_anon_grab(void)
14508 {
14509 dtrace_state_t *state;
14510
14511 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14512
14513 if ((state = dtrace_anon.dta_state) == NULL) {
14514 ASSERT(dtrace_anon.dta_enabling == NULL);
14515 return (NULL);
14516 }
14517
14518 ASSERT(dtrace_anon.dta_enabling != NULL);
14519 ASSERT(dtrace_retained != NULL);
14520
14521 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14522 dtrace_anon.dta_enabling = NULL;
14523 dtrace_anon.dta_state = NULL;
14524
14525 return (state);
14526 }
14527
14528 static void
14529 dtrace_anon_property(void)
14530 {
14531 int i, rv;
14532 dtrace_state_t *state;
14533 dof_hdr_t *dof;
14534 char c[32]; /* enough for "dof-data-" + digits */
14535
14536 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14537 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
14538
14539 for (i = 0; ; i++) {
14540 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14541
14542 dtrace_err_verbose = 1;
14543
14544 if ((dof = dtrace_dof_property(c)) == NULL) {
14545 dtrace_err_verbose = 0;
14546 break;
14547 }
14548
14549 /*
14550 * We want to create anonymous state, so we need to transition
14551 * the kernel debugger to indicate that DTrace is active. If
14552 * this fails (e.g. because the debugger has modified text in
14553 * some way), we won't continue with the processing.
14554 */
14555 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14556 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14557 "enabling ignored.");
14558 dtrace_dof_destroy(dof);
14559 break;
14560 }
14561
14562 /*
14563 * If we haven't allocated an anonymous state, we'll do so now.
14564 */
14565 if ((state = dtrace_anon.dta_state) == NULL) {
14566 #if !defined(__APPLE__)
14567 state = dtrace_state_create(NULL, NULL);
14568 dtrace_anon.dta_state = state;
14569 if (state == NULL) {
14570 #else
14571 rv = dtrace_state_create(NULL, NULL, &state);
14572 dtrace_anon.dta_state = state;
14573 if (rv != 0 || state == NULL) {
14574 #endif /* __APPLE__ */
14575 /*
14576 * This basically shouldn't happen: the only
14577 * failure mode from dtrace_state_create() is a
14578 * failure of ddi_soft_state_zalloc() that
14579 * itself should never happen. Still, the
14580 * interface allows for a failure mode, and
14581 * we want to fail as gracefully as possible:
14582 * we'll emit an error message and cease
14583 * processing anonymous state in this case.
14584 */
14585 cmn_err(CE_WARN, "failed to create "
14586 "anonymous state");
14587 dtrace_dof_destroy(dof);
14588 break;
14589 }
14590 }
14591
14592 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14593 &dtrace_anon.dta_enabling, 0, B_TRUE);
14594
14595 if (rv == 0)
14596 rv = dtrace_dof_options(dof, state);
14597
14598 dtrace_err_verbose = 0;
14599 dtrace_dof_destroy(dof);
14600
14601 if (rv != 0) {
14602 /*
14603 * This is malformed DOF; chuck any anonymous state
14604 * that we created.
14605 */
14606 ASSERT(dtrace_anon.dta_enabling == NULL);
14607 dtrace_state_destroy(state);
14608 dtrace_anon.dta_state = NULL;
14609 break;
14610 }
14611
14612 ASSERT(dtrace_anon.dta_enabling != NULL);
14613 }
14614
14615 if (dtrace_anon.dta_enabling != NULL) {
14616 int rval;
14617
14618 /*
14619 * dtrace_enabling_retain() can only fail because we are
14620 * trying to retain more enablings than are allowed -- but
14621 * we only have one anonymous enabling, and we are guaranteed
14622 * to be allowed at least one retained enabling; we assert
14623 * that dtrace_enabling_retain() returns success.
14624 */
14625 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14626 ASSERT(rval == 0);
14627
14628 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14629 }
14630 }
14631
14632 /*
14633 * DTrace Helper Functions
14634 */
14635 static void
14636 dtrace_helper_trace(dtrace_helper_action_t *helper,
14637 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14638 {
14639 #if !defined(__APPLE__) /* Quiet compiler warning */
14640 uint32_t size, next, nnext, i;
14641 #else
14642 uint32_t size, next, nnext;
14643 int i;
14644 #endif /* __APPLE__ */
14645 dtrace_helptrace_t *ent;
14646 uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14647
14648 if (!dtrace_helptrace_enabled)
14649 return;
14650
14651 #if !defined(__APPLE__) /* Quiet compiler warning */
14652 ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14653 #else
14654 ASSERT((uint32_t)vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14655 #endif /* __APPLE__ */
14656
14657 /*
14658 * What would a tracing framework be without its own tracing
14659 * framework? (Well, a hell of a lot simpler, for starters...)
14660 */
14661 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14662 sizeof (uint64_t) - sizeof (uint64_t);
14663
14664 /*
14665 * Iterate until we can allocate a slot in the trace buffer.
14666 */
14667 do {
14668 next = dtrace_helptrace_next;
14669
14670 if (next + size < dtrace_helptrace_bufsize) {
14671 nnext = next + size;
14672 } else {
14673 nnext = size;
14674 }
14675 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14676
14677 /*
14678 * We have our slot; fill it in.
14679 */
14680 if (nnext == size)
14681 next = 0;
14682
14683 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14684 ent->dtht_helper = helper;
14685 ent->dtht_where = where;
14686 ent->dtht_nlocals = vstate->dtvs_nlocals;
14687
14688 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14689 mstate->dtms_fltoffs : -1;
14690 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14691 ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14692
14693 for (i = 0; i < vstate->dtvs_nlocals; i++) {
14694 dtrace_statvar_t *svar;
14695
14696 if ((svar = vstate->dtvs_locals[i]) == NULL)
14697 continue;
14698
14699 ASSERT(svar->dtsv_size >= (int)NCPU * sizeof (uint64_t));
14700 ent->dtht_locals[i] =
14701 ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14702 }
14703 }
14704
14705 static uint64_t
14706 dtrace_helper(int which, dtrace_mstate_t *mstate,
14707 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14708 {
14709 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14710 uint64_t sarg0 = mstate->dtms_arg[0];
14711 uint64_t sarg1 = mstate->dtms_arg[1];
14712 uint64_t rval = 0;
14713 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14714 dtrace_helper_action_t *helper;
14715 dtrace_vstate_t *vstate;
14716 dtrace_difo_t *pred;
14717 int i, trace = dtrace_helptrace_enabled;
14718
14719 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14720
14721 if (helpers == NULL)
14722 return (0);
14723
14724 if ((helper = helpers->dthps_actions[which]) == NULL)
14725 return (0);
14726
14727 vstate = &helpers->dthps_vstate;
14728 mstate->dtms_arg[0] = arg0;
14729 mstate->dtms_arg[1] = arg1;
14730
14731 /*
14732 * Now iterate over each helper. If its predicate evaluates to 'true',
14733 * we'll call the corresponding actions. Note that the below calls
14734 * to dtrace_dif_emulate() may set faults in machine state. This is
14735 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
14736 * the stored DIF offset with its own (which is the desired behavior).
14737 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14738 * from machine state; this is okay, too.
14739 */
14740 for (; helper != NULL; helper = helper->dtha_next) {
14741 if ((pred = helper->dtha_predicate) != NULL) {
14742 if (trace)
14743 dtrace_helper_trace(helper, mstate, vstate, 0);
14744
14745 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14746 goto next;
14747
14748 if (*flags & CPU_DTRACE_FAULT)
14749 goto err;
14750 }
14751
14752 for (i = 0; i < helper->dtha_nactions; i++) {
14753 if (trace)
14754 dtrace_helper_trace(helper,
14755 mstate, vstate, i + 1);
14756
14757 rval = dtrace_dif_emulate(helper->dtha_actions[i],
14758 mstate, vstate, state);
14759
14760 if (*flags & CPU_DTRACE_FAULT)
14761 goto err;
14762 }
14763
14764 next:
14765 if (trace)
14766 dtrace_helper_trace(helper, mstate, vstate,
14767 DTRACE_HELPTRACE_NEXT);
14768 }
14769
14770 if (trace)
14771 dtrace_helper_trace(helper, mstate, vstate,
14772 DTRACE_HELPTRACE_DONE);
14773
14774 /*
14775 * Restore the arg0 that we saved upon entry.
14776 */
14777 mstate->dtms_arg[0] = sarg0;
14778 mstate->dtms_arg[1] = sarg1;
14779
14780 return (rval);
14781
14782 err:
14783 if (trace)
14784 dtrace_helper_trace(helper, mstate, vstate,
14785 DTRACE_HELPTRACE_ERR);
14786
14787 /*
14788 * Restore the arg0 that we saved upon entry.
14789 */
14790 mstate->dtms_arg[0] = sarg0;
14791 mstate->dtms_arg[1] = sarg1;
14792
14793 return (NULL);
14794 }
14795
14796 static void
14797 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14798 dtrace_vstate_t *vstate)
14799 {
14800 int i;
14801
14802 if (helper->dtha_predicate != NULL)
14803 dtrace_difo_release(helper->dtha_predicate, vstate);
14804
14805 for (i = 0; i < helper->dtha_nactions; i++) {
14806 ASSERT(helper->dtha_actions[i] != NULL);
14807 dtrace_difo_release(helper->dtha_actions[i], vstate);
14808 }
14809
14810 kmem_free(helper->dtha_actions,
14811 helper->dtha_nactions * sizeof (dtrace_difo_t *));
14812 kmem_free(helper, sizeof (dtrace_helper_action_t));
14813 }
14814
14815 #if !defined(__APPLE__)
14816 static int
14817 dtrace_helper_destroygen(int gen)
14818 {
14819 proc_t *p = curproc;
14820 #else
14821 static int
14822 dtrace_helper_destroygen(proc_t* p, int gen)
14823 {
14824 #endif
14825 dtrace_helpers_t *help = p->p_dtrace_helpers;
14826 dtrace_vstate_t *vstate;
14827 #if !defined(__APPLE__) /* Quiet compiler warning */
14828 int i;
14829 #else
14830 uint_t i;
14831 #endif /* __APPLE__ */
14832
14833 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14834
14835 if (help == NULL || gen > help->dthps_generation)
14836 return (EINVAL);
14837
14838 vstate = &help->dthps_vstate;
14839
14840 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14841 dtrace_helper_action_t *last = NULL, *h, *next;
14842
14843 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14844 next = h->dtha_next;
14845
14846 if (h->dtha_generation == gen) {
14847 if (last != NULL) {
14848 last->dtha_next = next;
14849 } else {
14850 help->dthps_actions[i] = next;
14851 }
14852
14853 dtrace_helper_action_destroy(h, vstate);
14854 } else {
14855 last = h;
14856 }
14857 }
14858 }
14859
14860 /*
14861 * Interate until we've cleared out all helper providers with the
14862 * given generation number.
14863 */
14864 for (;;) {
14865 dtrace_helper_provider_t *prov = NULL;
14866
14867 /*
14868 * Look for a helper provider with the right generation. We
14869 * have to start back at the beginning of the list each time
14870 * because we drop dtrace_lock. It's unlikely that we'll make
14871 * more than two passes.
14872 */
14873 for (i = 0; i < help->dthps_nprovs; i++) {
14874 prov = help->dthps_provs[i];
14875
14876 if (prov->dthp_generation == gen)
14877 break;
14878 }
14879
14880 /*
14881 * If there were no matches, we're done.
14882 */
14883 if (i == help->dthps_nprovs)
14884 break;
14885
14886 /*
14887 * Move the last helper provider into this slot.
14888 */
14889 help->dthps_nprovs--;
14890 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14891 help->dthps_provs[help->dthps_nprovs] = NULL;
14892
14893 lck_mtx_unlock(&dtrace_lock);
14894
14895 /*
14896 * If we have a meta provider, remove this helper provider.
14897 */
14898 lck_mtx_lock(&dtrace_meta_lock);
14899 if (dtrace_meta_pid != NULL) {
14900 ASSERT(dtrace_deferred_pid == NULL);
14901 dtrace_helper_provider_remove(&prov->dthp_prov,
14902 p->p_pid);
14903 }
14904 lck_mtx_unlock(&dtrace_meta_lock);
14905
14906 dtrace_helper_provider_destroy(prov);
14907
14908 lck_mtx_lock(&dtrace_lock);
14909 }
14910
14911 return (0);
14912 }
14913
14914 static int
14915 dtrace_helper_validate(dtrace_helper_action_t *helper)
14916 {
14917 int err = 0, i;
14918 dtrace_difo_t *dp;
14919
14920 if ((dp = helper->dtha_predicate) != NULL)
14921 err += dtrace_difo_validate_helper(dp);
14922
14923 for (i = 0; i < helper->dtha_nactions; i++)
14924 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14925
14926 return (err == 0);
14927 }
14928
14929 #if !defined(__APPLE__)
14930 static int
14931 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14932 #else
14933 static int
14934 dtrace_helper_action_add(proc_t* p, int which, dtrace_ecbdesc_t *ep)
14935 #endif
14936 {
14937 dtrace_helpers_t *help;
14938 dtrace_helper_action_t *helper, *last;
14939 dtrace_actdesc_t *act;
14940 dtrace_vstate_t *vstate;
14941 dtrace_predicate_t *pred;
14942 int count = 0, nactions = 0, i;
14943
14944 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14945 return (EINVAL);
14946
14947 #if !defined(__APPLE__)
14948 help = curproc->p_dtrace_helpers;
14949 #else
14950 help = p->p_dtrace_helpers;
14951 #endif
14952 last = help->dthps_actions[which];
14953 vstate = &help->dthps_vstate;
14954
14955 for (count = 0; last != NULL; last = last->dtha_next) {
14956 count++;
14957 if (last->dtha_next == NULL)
14958 break;
14959 }
14960
14961 /*
14962 * If we already have dtrace_helper_actions_max helper actions for this
14963 * helper action type, we'll refuse to add a new one.
14964 */
14965 if (count >= dtrace_helper_actions_max)
14966 return (ENOSPC);
14967
14968 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14969 helper->dtha_generation = help->dthps_generation;
14970
14971 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14972 ASSERT(pred->dtp_difo != NULL);
14973 dtrace_difo_hold(pred->dtp_difo);
14974 helper->dtha_predicate = pred->dtp_difo;
14975 }
14976
14977 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14978 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14979 goto err;
14980
14981 if (act->dtad_difo == NULL)
14982 goto err;
14983
14984 nactions++;
14985 }
14986
14987 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14988 (helper->dtha_nactions = nactions), KM_SLEEP);
14989
14990 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14991 dtrace_difo_hold(act->dtad_difo);
14992 helper->dtha_actions[i++] = act->dtad_difo;
14993 }
14994
14995 if (!dtrace_helper_validate(helper))
14996 goto err;
14997
14998 if (last == NULL) {
14999 help->dthps_actions[which] = helper;
15000 } else {
15001 last->dtha_next = helper;
15002 }
15003
15004 #if !defined(__APPLE__) /* Quiet compiler warning */
15005 if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15006 #else
15007 if ((uint32_t)vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15008 #endif /* __APPLE__ */
15009 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15010 dtrace_helptrace_next = 0;
15011 }
15012
15013 return (0);
15014 err:
15015 dtrace_helper_action_destroy(helper, vstate);
15016 return (EINVAL);
15017 }
15018
15019 static void
15020 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15021 dof_helper_t *dofhp)
15022 {
15023 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
15024
15025 lck_mtx_lock(&dtrace_meta_lock);
15026 lck_mtx_lock(&dtrace_lock);
15027
15028 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15029 /*
15030 * If the dtrace module is loaded but not attached, or if
15031 * there aren't isn't a meta provider registered to deal with
15032 * these provider descriptions, we need to postpone creating
15033 * the actual providers until later.
15034 */
15035
15036 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15037 dtrace_deferred_pid != help) {
15038 help->dthps_deferred = 1;
15039 help->dthps_pid = p->p_pid;
15040 help->dthps_next = dtrace_deferred_pid;
15041 help->dthps_prev = NULL;
15042 if (dtrace_deferred_pid != NULL)
15043 dtrace_deferred_pid->dthps_prev = help;
15044 dtrace_deferred_pid = help;
15045 }
15046
15047 lck_mtx_unlock(&dtrace_lock);
15048
15049 } else if (dofhp != NULL) {
15050 /*
15051 * If the dtrace module is loaded and we have a particular
15052 * helper provider description, pass that off to the
15053 * meta provider.
15054 */
15055
15056 lck_mtx_unlock(&dtrace_lock);
15057
15058 dtrace_helper_provide(dofhp, p->p_pid);
15059
15060 } else {
15061 /*
15062 * Otherwise, just pass all the helper provider descriptions
15063 * off to the meta provider.
15064 */
15065
15066 #if !defined(__APPLE__) /* Quiet compiler warning */
15067 int i;
15068 #else
15069 uint_t i;
15070 #endif /* __APPLE__ */
15071 lck_mtx_unlock(&dtrace_lock);
15072
15073 for (i = 0; i < help->dthps_nprovs; i++) {
15074 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15075 p->p_pid);
15076 }
15077 }
15078
15079 lck_mtx_unlock(&dtrace_meta_lock);
15080 }
15081
15082 #if !defined(__APPLE__)
15083 static int
15084 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
15085 #else
15086 static int
15087 dtrace_helper_provider_add(proc_t* p, dof_helper_t *dofhp, int gen)
15088 #endif
15089 {
15090 dtrace_helpers_t *help;
15091 dtrace_helper_provider_t *hprov, **tmp_provs;
15092 uint_t tmp_maxprovs, i;
15093
15094 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15095
15096 #if !defined(__APPLE__)
15097 help = curproc->p_dtrace_helpers;
15098 #else
15099 help = p->p_dtrace_helpers;
15100 #endif
15101 ASSERT(help != NULL);
15102
15103 /*
15104 * If we already have dtrace_helper_providers_max helper providers,
15105 * we're refuse to add a new one.
15106 */
15107 if (help->dthps_nprovs >= dtrace_helper_providers_max)
15108 return (ENOSPC);
15109
15110 /*
15111 * Check to make sure this isn't a duplicate.
15112 */
15113 for (i = 0; i < help->dthps_nprovs; i++) {
15114 if (dofhp->dofhp_addr ==
15115 help->dthps_provs[i]->dthp_prov.dofhp_addr)
15116 return (EALREADY);
15117 }
15118
15119 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15120 hprov->dthp_prov = *dofhp;
15121 hprov->dthp_ref = 1;
15122 hprov->dthp_generation = gen;
15123
15124 /*
15125 * Allocate a bigger table for helper providers if it's already full.
15126 */
15127 if (help->dthps_maxprovs == help->dthps_nprovs) {
15128 tmp_maxprovs = help->dthps_maxprovs;
15129 tmp_provs = help->dthps_provs;
15130
15131 if (help->dthps_maxprovs == 0)
15132 help->dthps_maxprovs = 2;
15133 else
15134 help->dthps_maxprovs *= 2;
15135 if (help->dthps_maxprovs > dtrace_helper_providers_max)
15136 help->dthps_maxprovs = dtrace_helper_providers_max;
15137
15138 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15139
15140 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15141 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15142
15143 if (tmp_provs != NULL) {
15144 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15145 sizeof (dtrace_helper_provider_t *));
15146 kmem_free(tmp_provs, tmp_maxprovs *
15147 sizeof (dtrace_helper_provider_t *));
15148 }
15149 }
15150
15151 help->dthps_provs[help->dthps_nprovs] = hprov;
15152 help->dthps_nprovs++;
15153
15154 return (0);
15155 }
15156
15157 static void
15158 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15159 {
15160 lck_mtx_lock(&dtrace_lock);
15161
15162 if (--hprov->dthp_ref == 0) {
15163 dof_hdr_t *dof;
15164 lck_mtx_unlock(&dtrace_lock);
15165 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15166 dtrace_dof_destroy(dof);
15167 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15168 } else {
15169 lck_mtx_unlock(&dtrace_lock);
15170 }
15171 }
15172
15173 static int
15174 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15175 {
15176 uintptr_t daddr = (uintptr_t)dof;
15177 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15178 dof_provider_t *provider;
15179 dof_probe_t *probe;
15180 uint8_t *arg;
15181 char *strtab, *typestr;
15182 dof_stridx_t typeidx;
15183 size_t typesz;
15184 uint_t nprobes, j, k;
15185
15186 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15187
15188 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15189 dtrace_dof_error(dof, "misaligned section offset");
15190 return (-1);
15191 }
15192
15193 /*
15194 * The section needs to be large enough to contain the DOF provider
15195 * structure appropriate for the given version.
15196 */
15197 if (sec->dofs_size <
15198 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15199 offsetof(dof_provider_t, dofpv_prenoffs) :
15200 sizeof (dof_provider_t))) {
15201 dtrace_dof_error(dof, "provider section too small");
15202 return (-1);
15203 }
15204
15205 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15206 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15207 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15208 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15209 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15210
15211 if (str_sec == NULL || prb_sec == NULL ||
15212 arg_sec == NULL || off_sec == NULL)
15213 return (-1);
15214
15215 enoff_sec = NULL;
15216
15217 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15218 provider->dofpv_prenoffs != DOF_SECT_NONE &&
15219 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15220 provider->dofpv_prenoffs)) == NULL)
15221 return (-1);
15222
15223 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15224
15225 if (provider->dofpv_name >= str_sec->dofs_size ||
15226 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15227 dtrace_dof_error(dof, "invalid provider name");
15228 return (-1);
15229 }
15230
15231 if (prb_sec->dofs_entsize == 0 ||
15232 prb_sec->dofs_entsize > prb_sec->dofs_size) {
15233 dtrace_dof_error(dof, "invalid entry size");
15234 return (-1);
15235 }
15236
15237 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15238 dtrace_dof_error(dof, "misaligned entry size");
15239 return (-1);
15240 }
15241
15242 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15243 dtrace_dof_error(dof, "invalid entry size");
15244 return (-1);
15245 }
15246
15247 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15248 dtrace_dof_error(dof, "misaligned section offset");
15249 return (-1);
15250 }
15251
15252 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15253 dtrace_dof_error(dof, "invalid entry size");
15254 return (-1);
15255 }
15256
15257 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15258
15259 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15260
15261 /*
15262 * Take a pass through the probes to check for errors.
15263 */
15264 for (j = 0; j < nprobes; j++) {
15265 probe = (dof_probe_t *)(uintptr_t)(daddr +
15266 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15267
15268 if (probe->dofpr_func >= str_sec->dofs_size) {
15269 dtrace_dof_error(dof, "invalid function name");
15270 return (-1);
15271 }
15272
15273 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15274 dtrace_dof_error(dof, "function name too long");
15275 return (-1);
15276 }
15277
15278 if (probe->dofpr_name >= str_sec->dofs_size ||
15279 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15280 dtrace_dof_error(dof, "invalid probe name");
15281 return (-1);
15282 }
15283
15284 /*
15285 * The offset count must not wrap the index, and the offsets
15286 * must also not overflow the section's data.
15287 */
15288 if (probe->dofpr_offidx + probe->dofpr_noffs <
15289 probe->dofpr_offidx ||
15290 (probe->dofpr_offidx + probe->dofpr_noffs) *
15291 off_sec->dofs_entsize > off_sec->dofs_size) {
15292 dtrace_dof_error(dof, "invalid probe offset");
15293 return (-1);
15294 }
15295
15296 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15297 /*
15298 * If there's no is-enabled offset section, make sure
15299 * there aren't any is-enabled offsets. Otherwise
15300 * perform the same checks as for probe offsets
15301 * (immediately above).
15302 */
15303 if (enoff_sec == NULL) {
15304 if (probe->dofpr_enoffidx != 0 ||
15305 probe->dofpr_nenoffs != 0) {
15306 dtrace_dof_error(dof, "is-enabled "
15307 "offsets with null section");
15308 return (-1);
15309 }
15310 } else if (probe->dofpr_enoffidx +
15311 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15312 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15313 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15314 dtrace_dof_error(dof, "invalid is-enabled "
15315 "offset");
15316 return (-1);
15317 }
15318
15319 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15320 dtrace_dof_error(dof, "zero probe and "
15321 "is-enabled offsets");
15322 return (-1);
15323 }
15324 } else if (probe->dofpr_noffs == 0) {
15325 dtrace_dof_error(dof, "zero probe offsets");
15326 return (-1);
15327 }
15328
15329 if (probe->dofpr_argidx + probe->dofpr_xargc <
15330 probe->dofpr_argidx ||
15331 (probe->dofpr_argidx + probe->dofpr_xargc) *
15332 arg_sec->dofs_entsize > arg_sec->dofs_size) {
15333 dtrace_dof_error(dof, "invalid args");
15334 return (-1);
15335 }
15336
15337 typeidx = probe->dofpr_nargv;
15338 typestr = strtab + probe->dofpr_nargv;
15339 for (k = 0; k < probe->dofpr_nargc; k++) {
15340 if (typeidx >= str_sec->dofs_size) {
15341 dtrace_dof_error(dof, "bad "
15342 "native argument type");
15343 return (-1);
15344 }
15345
15346 typesz = strlen(typestr) + 1;
15347 if (typesz > DTRACE_ARGTYPELEN) {
15348 dtrace_dof_error(dof, "native "
15349 "argument type too long");
15350 return (-1);
15351 }
15352 typeidx += typesz;
15353 typestr += typesz;
15354 }
15355
15356 typeidx = probe->dofpr_xargv;
15357 typestr = strtab + probe->dofpr_xargv;
15358 for (k = 0; k < probe->dofpr_xargc; k++) {
15359 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15360 dtrace_dof_error(dof, "bad "
15361 "native argument index");
15362 return (-1);
15363 }
15364
15365 if (typeidx >= str_sec->dofs_size) {
15366 dtrace_dof_error(dof, "bad "
15367 "translated argument type");
15368 return (-1);
15369 }
15370
15371 typesz = strlen(typestr) + 1;
15372 if (typesz > DTRACE_ARGTYPELEN) {
15373 dtrace_dof_error(dof, "translated argument "
15374 "type too long");
15375 return (-1);
15376 }
15377
15378 typeidx += typesz;
15379 typestr += typesz;
15380 }
15381 }
15382
15383 return (0);
15384 }
15385
15386 #if !defined(__APPLE__)
15387 static int
15388 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15389 #else
15390 static int
15391 dtrace_helper_slurp(proc_t* p, dof_hdr_t *dof, dof_helper_t *dhp)
15392 #endif
15393 {
15394 dtrace_helpers_t *help;
15395 dtrace_vstate_t *vstate;
15396 dtrace_enabling_t *enab = NULL;
15397 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15398 uintptr_t daddr = (uintptr_t)dof;
15399
15400 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15401
15402 #if !defined(__APPLE__)
15403 if ((help = curproc->p_dtrace_helpers) == NULL)
15404 help = dtrace_helpers_create(curproc);
15405 #else
15406 if ((help = p->p_dtrace_helpers) == NULL)
15407 help = dtrace_helpers_create(p);
15408 #endif
15409
15410 vstate = &help->dthps_vstate;
15411
15412 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15413 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15414 dtrace_dof_destroy(dof);
15415 return (rv);
15416 }
15417
15418 /*
15419 * Look for helper providers and validate their descriptions.
15420 */
15421 if (dhp != NULL) {
15422 #if !defined(__APPLE__) /* Quiet compiler warning */
15423 for (i = 0; i < dof->dofh_secnum; i++) {
15424 #else
15425 for (i = 0; (uint32_t)i < dof->dofh_secnum; i++) {
15426 #endif /* __APPLE__ */
15427 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15428 dof->dofh_secoff + i * dof->dofh_secsize);
15429
15430 if (sec->dofs_type != DOF_SECT_PROVIDER)
15431 continue;
15432
15433 if (dtrace_helper_provider_validate(dof, sec) != 0) {
15434 dtrace_enabling_destroy(enab);
15435 dtrace_dof_destroy(dof);
15436 return (-1);
15437 }
15438
15439 nprovs++;
15440 }
15441 }
15442
15443 /*
15444 * Now we need to walk through the ECB descriptions in the enabling.
15445 */
15446 for (i = 0; i < enab->dten_ndesc; i++) {
15447 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15448 dtrace_probedesc_t *desc = &ep->dted_probe;
15449
15450 #if !defined(__APPLE__)
15451 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15452 continue;
15453
15454 if (strcmp(desc->dtpd_mod, "helper") != 0)
15455 continue;
15456
15457 if (strcmp(desc->dtpd_func, "ustack") != 0)
15458 continue;
15459 #else /* Employ size bounded string operation. */
15460 if (!LIT_STRNEQL(desc->dtpd_provider, "dtrace"))
15461 continue;
15462
15463 if (!LIT_STRNEQL(desc->dtpd_mod, "helper"))
15464 continue;
15465
15466 if (!LIT_STRNEQL(desc->dtpd_func, "ustack"))
15467 continue;
15468 #endif /* __APPLE__ */
15469
15470 #if !defined(__APPLE__)
15471 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15472 ep)) != 0) {
15473 #else
15474 if ((rv = dtrace_helper_action_add(p, DTRACE_HELPER_ACTION_USTACK,
15475 ep)) != 0) {
15476 #endif
15477 /*
15478 * Adding this helper action failed -- we are now going
15479 * to rip out the entire generation and return failure.
15480 */
15481 #if !defined(__APPLE__)
15482 (void) dtrace_helper_destroygen(help->dthps_generation);
15483 #else
15484 (void) dtrace_helper_destroygen(p, help->dthps_generation);
15485 #endif
15486 dtrace_enabling_destroy(enab);
15487 dtrace_dof_destroy(dof);
15488 return (-1);
15489 }
15490
15491 nhelpers++;
15492 }
15493
15494 if (nhelpers < enab->dten_ndesc)
15495 dtrace_dof_error(dof, "unmatched helpers");
15496
15497 gen = help->dthps_generation++;
15498 dtrace_enabling_destroy(enab);
15499
15500 if (dhp != NULL && nprovs > 0) {
15501 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15502 #if !defined(__APPLE__)
15503 if (dtrace_helper_provider_add(dhp, gen) == 0) {
15504 #else
15505 if (dtrace_helper_provider_add(p, dhp, gen) == 0) {
15506 #endif
15507 lck_mtx_unlock(&dtrace_lock);
15508 #if !defined(__APPLE__)
15509 dtrace_helper_provider_register(curproc, help, dhp);
15510 #else
15511 dtrace_helper_provider_register(p, help, dhp);
15512 #endif
15513 lck_mtx_lock(&dtrace_lock);
15514
15515 destroy = 0;
15516 }
15517 }
15518
15519 if (destroy)
15520 dtrace_dof_destroy(dof);
15521
15522 return (gen);
15523 }
15524
15525 #if defined(__APPLE__)
15526
15527 /*
15528 * DTrace lazy dof
15529 *
15530 * DTrace user static probes (USDT probes) and helper actions are loaded
15531 * in a process by proccessing dof sections. The dof sections are passed
15532 * into the kernel by dyld, in a dof_ioctl_data_t block. It is rather
15533 * expensive to process dof for a process that will never use it. There
15534 * is a memory cost (allocating the providers/probes), and a cpu cost
15535 * (creating the providers/probes).
15536 *
15537 * To reduce this cost, we use "lazy dof". The normal proceedure for
15538 * dof processing is to copyin the dof(s) pointed to by the dof_ioctl_data_t
15539 * block, and invoke dof_slurp_helper() on them. When "lazy dof" is
15540 * used, each process retains the dof_ioctl_data_t block, instead of
15541 * copying in the data it points to.
15542 *
15543 * The dof_ioctl_data_t blocks are managed as if they were the actual
15544 * processed dof; on fork the block is copied to the child, on exec and
15545 * exit the block is freed.
15546 *
15547 * If the process loads library(s) containing additional dof, the
15548 * new dof_ioctl_data_t is merged with the existing block.
15549 *
15550 * There are a few catches that make this slightly more difficult.
15551 * When dyld registers dof_ioctl_data_t blocks, it expects a unique
15552 * identifier value for each dof in the block. In non-lazy dof terms,
15553 * this is the generation that dof was loaded in. If we hand back
15554 * a UID for a lazy dof, that same UID must be able to unload the
15555 * dof once it has become non-lazy. To meet this requirement, the
15556 * code that loads lazy dof requires that the UID's for dof(s) in
15557 * the lazy dof be sorted, and in ascending order. It is okay to skip
15558 * UID's, I.E., 1 -> 5 -> 6 is legal.
15559 *
15560 * Once a process has become non-lazy, it will stay non-lazy. All
15561 * future dof operations for that process will be non-lazy, even
15562 * if the dof mode transitions back to lazy.
15563 *
15564 * Always do lazy dof checks before non-lazy (I.E. In fork, exit, exec.).
15565 * That way if the lazy check fails due to transitioning to non-lazy, the
15566 * right thing is done with the newly faulted in dof.
15567 */
15568
15569 /*
15570 * This method is a bit squicky. It must handle:
15571 *
15572 * dof should not be lazy.
15573 * dof should have been handled lazily, but there was an error
15574 * dof was handled lazily, and needs to be freed.
15575 * dof was handled lazily, and must not be freed.
15576 *
15577 *
15578 * Returns EACCESS if dof should be handled non-lazily.
15579 *
15580 * KERN_SUCCESS and all other return codes indicate lazy handling of dof.
15581 *
15582 * If the dofs data is claimed by this method, dofs_claimed will be set.
15583 * Callers should not free claimed dofs.
15584 */
15585 static int
15586 dtrace_lazy_dofs_add(proc_t *p, dof_ioctl_data_t* incoming_dofs, int *dofs_claimed)
15587 {
15588 ASSERT(p);
15589 ASSERT(incoming_dofs && incoming_dofs->dofiod_count > 0);
15590
15591 int rval = 0;
15592 *dofs_claimed = 0;
15593
15594 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15595
15596 /*
15597 * If we have lazy dof, dof mode better be LAZY_ON.
15598 */
15599 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
15600 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15601 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
15602
15603 /*
15604 * Any existing helpers force non-lazy behavior.
15605 */
15606 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
15607 lck_mtx_lock(&p->p_dtrace_sprlock);
15608
15609 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
15610 unsigned int existing_dofs_count = (existing_dofs) ? existing_dofs->dofiod_count : 0;
15611 unsigned int i, merged_dofs_count = incoming_dofs->dofiod_count + existing_dofs_count;
15612
15613 /*
15614 * Range check...
15615 */
15616 if (merged_dofs_count == 0 || merged_dofs_count > 1024) {
15617 dtrace_dof_error(NULL, "lazy_dofs_add merged_dofs_count out of range");
15618 rval = EINVAL;
15619 goto unlock;
15620 }
15621
15622 /*
15623 * Each dof being added must be assigned a unique generation.
15624 */
15625 uint64_t generation = (existing_dofs) ? existing_dofs->dofiod_helpers[existing_dofs_count - 1].dofhp_dof + 1 : 1;
15626 for (i=0; i<incoming_dofs->dofiod_count; i++) {
15627 /*
15628 * We rely on these being the same so we can overwrite dofhp_dof and not lose info.
15629 */
15630 ASSERT(incoming_dofs->dofiod_helpers[i].dofhp_dof == incoming_dofs->dofiod_helpers[i].dofhp_addr);
15631 incoming_dofs->dofiod_helpers[i].dofhp_dof = generation++;
15632 }
15633
15634
15635 if (existing_dofs) {
15636 /*
15637 * Merge the existing and incoming dofs
15638 */
15639 size_t merged_dofs_size = DOF_IOCTL_DATA_T_SIZE(merged_dofs_count);
15640 dof_ioctl_data_t* merged_dofs = kmem_alloc(merged_dofs_size, KM_SLEEP);
15641
15642 bcopy(&existing_dofs->dofiod_helpers[0],
15643 &merged_dofs->dofiod_helpers[0],
15644 sizeof(dof_helper_t) * existing_dofs_count);
15645 bcopy(&incoming_dofs->dofiod_helpers[0],
15646 &merged_dofs->dofiod_helpers[existing_dofs_count],
15647 sizeof(dof_helper_t) * incoming_dofs->dofiod_count);
15648
15649 merged_dofs->dofiod_count = merged_dofs_count;
15650
15651 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
15652
15653 p->p_dtrace_lazy_dofs = merged_dofs;
15654 } else {
15655 /*
15656 * Claim the incoming dofs
15657 */
15658 *dofs_claimed = 1;
15659 p->p_dtrace_lazy_dofs = incoming_dofs;
15660 }
15661
15662 #if DEBUG
15663 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
15664 for (i=0; i<all_dofs->dofiod_count-1; i++) {
15665 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
15666 }
15667 #endif /* DEBUG */
15668
15669 unlock:
15670 lck_mtx_unlock(&p->p_dtrace_sprlock);
15671 } else {
15672 rval = EACCES;
15673 }
15674
15675 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15676
15677 return rval;
15678 }
15679
15680 /*
15681 * Returns:
15682 *
15683 * EINVAL: lazy dof is enabled, but the requested generation was not found.
15684 * EACCES: This removal needs to be handled non-lazily.
15685 */
15686 static int
15687 dtrace_lazy_dofs_remove(proc_t *p, int generation)
15688 {
15689 int rval = EINVAL;
15690
15691 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15692
15693 /*
15694 * If we have lazy dof, dof mode better be LAZY_ON.
15695 */
15696 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
15697 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15698 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
15699
15700 /*
15701 * Any existing helpers force non-lazy behavior.
15702 */
15703 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
15704 lck_mtx_lock(&p->p_dtrace_sprlock);
15705
15706 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
15707
15708 if (existing_dofs) {
15709 int index, existing_dofs_count = existing_dofs->dofiod_count;
15710 for (index=0; index<existing_dofs_count; index++) {
15711 if ((int)existing_dofs->dofiod_helpers[index].dofhp_dof == generation) {
15712 dof_ioctl_data_t* removed_dofs = NULL;
15713
15714 /*
15715 * If there is only 1 dof, we'll delete it and swap in NULL.
15716 */
15717 if (existing_dofs_count > 1) {
15718 int removed_dofs_count = existing_dofs_count - 1;
15719 size_t removed_dofs_size = DOF_IOCTL_DATA_T_SIZE(removed_dofs_count);
15720
15721 removed_dofs = kmem_alloc(removed_dofs_size, KM_SLEEP);
15722 removed_dofs->dofiod_count = removed_dofs_count;
15723
15724 /*
15725 * copy the remaining data.
15726 */
15727 if (index > 0) {
15728 bcopy(&existing_dofs->dofiod_helpers[0],
15729 &removed_dofs->dofiod_helpers[0],
15730 index * sizeof(dof_helper_t));
15731 }
15732
15733 if (index < existing_dofs_count-1) {
15734 bcopy(&existing_dofs->dofiod_helpers[index+1],
15735 &removed_dofs->dofiod_helpers[index],
15736 (existing_dofs_count - index - 1) * sizeof(dof_helper_t));
15737 }
15738 }
15739
15740 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
15741
15742 p->p_dtrace_lazy_dofs = removed_dofs;
15743
15744 rval = KERN_SUCCESS;
15745
15746 break;
15747 }
15748 }
15749
15750 #if DEBUG
15751 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
15752 if (all_dofs) {
15753 unsigned int i;
15754 for (i=0; i<all_dofs->dofiod_count-1; i++) {
15755 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
15756 }
15757 }
15758 #endif
15759
15760 }
15761
15762 lck_mtx_unlock(&p->p_dtrace_sprlock);
15763 } else {
15764 rval = EACCES;
15765 }
15766
15767 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15768
15769 return rval;
15770 }
15771
15772 void
15773 dtrace_lazy_dofs_destroy(proc_t *p)
15774 {
15775 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15776 lck_mtx_lock(&p->p_dtrace_sprlock);
15777
15778 /*
15779 * If we have lazy dof, dof mode better be LAZY_ON, or we must be exiting.
15780 * We cannot assert against DTRACE_DOF_MODE_NEVER here, because we are called from
15781 * kern_exit.c and kern_exec.c.
15782 */
15783 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON || p->p_lflag & P_LEXIT);
15784 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15785
15786 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
15787 p->p_dtrace_lazy_dofs = NULL;
15788
15789 lck_mtx_unlock(&p->p_dtrace_sprlock);
15790 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15791
15792 if (lazy_dofs) {
15793 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
15794 }
15795 }
15796
15797 void
15798 dtrace_lazy_dofs_duplicate(proc_t *parent, proc_t *child)
15799 {
15800 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
15801 lck_mtx_assert(&parent->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
15802 lck_mtx_assert(&child->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
15803
15804 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15805 lck_mtx_lock(&parent->p_dtrace_sprlock);
15806
15807 /*
15808 * If we have lazy dof, dof mode better be LAZY_ON, or we must be exiting.
15809 * We cannot assert against DTRACE_DOF_MODE_NEVER here, because we are called from
15810 * kern_fork.c
15811 */
15812 ASSERT(parent->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
15813 ASSERT(parent->p_dtrace_lazy_dofs == NULL || parent->p_dtrace_helpers == NULL);
15814 /*
15815 * In theory we should hold the child sprlock, but this is safe...
15816 */
15817 ASSERT(child->p_dtrace_lazy_dofs == NULL && child->p_dtrace_helpers == NULL);
15818
15819 dof_ioctl_data_t* parent_dofs = parent->p_dtrace_lazy_dofs;
15820 dof_ioctl_data_t* child_dofs = NULL;
15821 if (parent_dofs) {
15822 size_t parent_dofs_size = DOF_IOCTL_DATA_T_SIZE(parent_dofs->dofiod_count);
15823 child_dofs = kmem_alloc(parent_dofs_size, KM_SLEEP);
15824 bcopy(parent_dofs, child_dofs, parent_dofs_size);
15825 }
15826
15827 lck_mtx_unlock(&parent->p_dtrace_sprlock);
15828
15829 if (child_dofs) {
15830 lck_mtx_lock(&child->p_dtrace_sprlock);
15831 child->p_dtrace_lazy_dofs = child_dofs;
15832 lck_mtx_unlock(&child->p_dtrace_sprlock);
15833 }
15834
15835 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15836 }
15837
15838 static int
15839 dtrace_lazy_dofs_proc_iterate_filter(proc_t *p, void* ignored)
15840 {
15841 #pragma unused(ignored)
15842 /*
15843 * Okay to NULL test without taking the sprlock.
15844 */
15845 return p->p_dtrace_lazy_dofs != NULL;
15846 }
15847
15848 static int
15849 dtrace_lazy_dofs_proc_iterate_doit(proc_t *p, void* ignored)
15850 {
15851 #pragma unused(ignored)
15852 /*
15853 * It is possible this process may exit during our attempt to
15854 * fault in the dof. We could fix this by holding locks longer,
15855 * but the errors are benign.
15856 */
15857 lck_mtx_lock(&p->p_dtrace_sprlock);
15858
15859 /*
15860 * In this case only, it is okay to have lazy dof when dof mode is DTRACE_DOF_MODE_LAZY_OFF
15861 */
15862 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15863 ASSERT(dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF);
15864
15865
15866 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
15867 p->p_dtrace_lazy_dofs = NULL;
15868
15869 lck_mtx_unlock(&p->p_dtrace_sprlock);
15870
15871 /*
15872 * Process each dof_helper_t
15873 */
15874 if (lazy_dofs != NULL) {
15875 unsigned int i;
15876 int rval;
15877
15878 for (i=0; i<lazy_dofs->dofiod_count; i++) {
15879 /*
15880 * When loading lazy dof, we depend on the generations being sorted in ascending order.
15881 */
15882 ASSERT(i >= (lazy_dofs->dofiod_count - 1) || lazy_dofs->dofiod_helpers[i].dofhp_dof < lazy_dofs->dofiod_helpers[i+1].dofhp_dof);
15883
15884 dof_helper_t *dhp = &lazy_dofs->dofiod_helpers[i];
15885
15886 /*
15887 * We stored the generation in dofhp_dof. Save it, and restore the original value.
15888 */
15889 int generation = dhp->dofhp_dof;
15890 dhp->dofhp_dof = dhp->dofhp_addr;
15891
15892 dof_hdr_t *dof = dtrace_dof_copyin_from_proc(p, dhp->dofhp_dof, &rval);
15893
15894 if (dof != NULL) {
15895 dtrace_helpers_t *help;
15896
15897 lck_mtx_lock(&dtrace_lock);
15898
15899 /*
15900 * This must be done with the dtrace_lock held
15901 */
15902 if ((help = p->p_dtrace_helpers) == NULL)
15903 help = dtrace_helpers_create(p);
15904
15905 /*
15906 * If the generation value has been bumped, someone snuck in
15907 * when we released the dtrace lock. We have to dump this generation,
15908 * there is no safe way to load it.
15909 */
15910 if (help->dthps_generation <= generation) {
15911 help->dthps_generation = generation;
15912
15913 /*
15914 * dtrace_helper_slurp() takes responsibility for the dof --
15915 * it may free it now or it may save it and free it later.
15916 */
15917 if ((rval = dtrace_helper_slurp(p, dof, dhp)) != generation) {
15918 dtrace_dof_error(NULL, "returned value did not match expected generation");
15919 }
15920 }
15921
15922 lck_mtx_unlock(&dtrace_lock);
15923 }
15924 }
15925
15926 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
15927 }
15928
15929 return PROC_RETURNED;
15930 }
15931
15932 #endif /* __APPLE__ */
15933
15934 static dtrace_helpers_t *
15935 dtrace_helpers_create(proc_t *p)
15936 {
15937 dtrace_helpers_t *help;
15938
15939 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15940 ASSERT(p->p_dtrace_helpers == NULL);
15941
15942 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15943 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15944 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15945
15946 p->p_dtrace_helpers = help;
15947 dtrace_helpers++;
15948
15949 return (help);
15950 }
15951
15952 #if !defined(__APPLE__)
15953 static void
15954 dtrace_helpers_destroy(void)
15955 {
15956 dtrace_helpers_t *help;
15957 dtrace_vstate_t *vstate;
15958 proc_t *p = curproc;
15959 int i;
15960 #else
15961 static void
15962 dtrace_helpers_destroy(proc_t* p)
15963 {
15964 dtrace_helpers_t *help;
15965 dtrace_vstate_t *vstate;
15966 uint_t i;
15967 #endif
15968
15969 lck_mtx_lock(&dtrace_lock);
15970
15971 ASSERT(p->p_dtrace_helpers != NULL);
15972 ASSERT(dtrace_helpers > 0);
15973
15974 help = p->p_dtrace_helpers;
15975 vstate = &help->dthps_vstate;
15976
15977 /*
15978 * We're now going to lose the help from this process.
15979 */
15980 p->p_dtrace_helpers = NULL;
15981 dtrace_sync();
15982
15983 /*
15984 * Destory the helper actions.
15985 */
15986 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15987 dtrace_helper_action_t *h, *next;
15988
15989 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15990 next = h->dtha_next;
15991 dtrace_helper_action_destroy(h, vstate);
15992 h = next;
15993 }
15994 }
15995
15996 lck_mtx_unlock(&dtrace_lock);
15997
15998 /*
15999 * Destroy the helper providers.
16000 */
16001 if (help->dthps_maxprovs > 0) {
16002 lck_mtx_lock(&dtrace_meta_lock);
16003 if (dtrace_meta_pid != NULL) {
16004 ASSERT(dtrace_deferred_pid == NULL);
16005
16006 for (i = 0; i < help->dthps_nprovs; i++) {
16007 dtrace_helper_provider_remove(
16008 &help->dthps_provs[i]->dthp_prov, p->p_pid);
16009 }
16010 } else {
16011 lck_mtx_lock(&dtrace_lock);
16012 ASSERT(help->dthps_deferred == 0 ||
16013 help->dthps_next != NULL ||
16014 help->dthps_prev != NULL ||
16015 help == dtrace_deferred_pid);
16016
16017 /*
16018 * Remove the helper from the deferred list.
16019 */
16020 if (help->dthps_next != NULL)
16021 help->dthps_next->dthps_prev = help->dthps_prev;
16022 if (help->dthps_prev != NULL)
16023 help->dthps_prev->dthps_next = help->dthps_next;
16024 if (dtrace_deferred_pid == help) {
16025 dtrace_deferred_pid = help->dthps_next;
16026 ASSERT(help->dthps_prev == NULL);
16027 }
16028
16029 lck_mtx_unlock(&dtrace_lock);
16030 }
16031
16032 lck_mtx_unlock(&dtrace_meta_lock);
16033
16034 for (i = 0; i < help->dthps_nprovs; i++) {
16035 dtrace_helper_provider_destroy(help->dthps_provs[i]);
16036 }
16037
16038 kmem_free(help->dthps_provs, help->dthps_maxprovs *
16039 sizeof (dtrace_helper_provider_t *));
16040 }
16041
16042 lck_mtx_lock(&dtrace_lock);
16043
16044 dtrace_vstate_fini(&help->dthps_vstate);
16045 kmem_free(help->dthps_actions,
16046 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
16047 kmem_free(help, sizeof (dtrace_helpers_t));
16048
16049 --dtrace_helpers;
16050 lck_mtx_unlock(&dtrace_lock);
16051 }
16052
16053 static void
16054 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
16055 {
16056 dtrace_helpers_t *help, *newhelp;
16057 dtrace_helper_action_t *helper, *new, *last;
16058 dtrace_difo_t *dp;
16059 dtrace_vstate_t *vstate;
16060 #if !defined(__APPLE__) /* Quiet compiler warning */
16061 int i, j, sz, hasprovs = 0;
16062 #else
16063 uint_t i;
16064 int j, sz, hasprovs = 0;
16065 #endif /* __APPLE__ */
16066
16067 lck_mtx_lock(&dtrace_lock);
16068 ASSERT(from->p_dtrace_helpers != NULL);
16069 ASSERT(dtrace_helpers > 0);
16070
16071 help = from->p_dtrace_helpers;
16072 newhelp = dtrace_helpers_create(to);
16073 ASSERT(to->p_dtrace_helpers != NULL);
16074
16075 newhelp->dthps_generation = help->dthps_generation;
16076 vstate = &newhelp->dthps_vstate;
16077
16078 /*
16079 * Duplicate the helper actions.
16080 */
16081 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
16082 if ((helper = help->dthps_actions[i]) == NULL)
16083 continue;
16084
16085 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
16086 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
16087 KM_SLEEP);
16088 new->dtha_generation = helper->dtha_generation;
16089
16090 if ((dp = helper->dtha_predicate) != NULL) {
16091 dp = dtrace_difo_duplicate(dp, vstate);
16092 new->dtha_predicate = dp;
16093 }
16094
16095 new->dtha_nactions = helper->dtha_nactions;
16096 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
16097 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
16098
16099 #if !defined(__APPLE__) /* Quiet compiler warning */
16100 for (j = 0; j < new->dtha_nactions; j++) {
16101 dtrace_difo_t *dp = helper->dtha_actions[j];
16102
16103 ASSERT(dp != NULL);
16104 dp = dtrace_difo_duplicate(dp, vstate);
16105 new->dtha_actions[j] = dp;
16106 }
16107 #else
16108 for (j = 0; j < new->dtha_nactions; j++) {
16109 dtrace_difo_t *dpj = helper->dtha_actions[j];
16110
16111 ASSERT(dpj != NULL);
16112 dpj = dtrace_difo_duplicate(dpj, vstate);
16113 new->dtha_actions[j] = dpj;
16114 }
16115 #endif /* __APPLE__ */
16116
16117 if (last != NULL) {
16118 last->dtha_next = new;
16119 } else {
16120 newhelp->dthps_actions[i] = new;
16121 }
16122
16123 last = new;
16124 }
16125 }
16126
16127 /*
16128 * Duplicate the helper providers and register them with the
16129 * DTrace framework.
16130 */
16131 if (help->dthps_nprovs > 0) {
16132 newhelp->dthps_nprovs = help->dthps_nprovs;
16133 newhelp->dthps_maxprovs = help->dthps_nprovs;
16134 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
16135 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
16136 for (i = 0; i < newhelp->dthps_nprovs; i++) {
16137 newhelp->dthps_provs[i] = help->dthps_provs[i];
16138 newhelp->dthps_provs[i]->dthp_ref++;
16139 }
16140
16141 hasprovs = 1;
16142 }
16143
16144 lck_mtx_unlock(&dtrace_lock);
16145
16146 if (hasprovs)
16147 dtrace_helper_provider_register(to, newhelp, NULL);
16148 }
16149
16150 /*
16151 * DTrace Hook Functions
16152 */
16153
16154 #if defined(__APPLE__)
16155 /*
16156 * Routines to manipulate the modctl list within dtrace
16157 */
16158
16159 modctl_t *dtrace_modctl_list;
16160
16161 static void
16162 dtrace_modctl_add(struct modctl * newctl)
16163 {
16164 struct modctl *nextp, *prevp;
16165
16166 ASSERT(newctl != NULL);
16167 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
16168
16169 // Insert new module at the front of the list,
16170
16171 newctl->mod_next = dtrace_modctl_list;
16172 dtrace_modctl_list = newctl;
16173
16174 /*
16175 * If a module exists with the same name, then that module
16176 * must have been unloaded with enabled probes. We will move
16177 * the unloaded module to the new module's stale chain and
16178 * then stop traversing the list.
16179 */
16180
16181 prevp = newctl;
16182 nextp = newctl->mod_next;
16183
16184 while (nextp != NULL) {
16185 if (nextp->mod_loaded) {
16186 /* This is a loaded module. Keep traversing. */
16187 prevp = nextp;
16188 nextp = nextp->mod_next;
16189 continue;
16190 }
16191 else {
16192 /* Found an unloaded module */
16193 if (strncmp (newctl->mod_modname, nextp->mod_modname, KMOD_MAX_NAME)) {
16194 /* Names don't match. Keep traversing. */
16195 prevp = nextp;
16196 nextp = nextp->mod_next;
16197 continue;
16198 }
16199 else {
16200 /* We found a stale entry, move it. We're done. */
16201 prevp->mod_next = nextp->mod_next;
16202 newctl->mod_stale = nextp;
16203 nextp->mod_next = NULL;
16204 break;
16205 }
16206 }
16207 }
16208 }
16209
16210 static modctl_t *
16211 dtrace_modctl_lookup(struct kmod_info * kmod)
16212 {
16213 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
16214
16215 struct modctl * ctl;
16216
16217 for (ctl = dtrace_modctl_list; ctl; ctl=ctl->mod_next) {
16218 if (ctl->mod_id == kmod->id)
16219 return(ctl);
16220 }
16221 return (NULL);
16222 }
16223
16224 /*
16225 * This routine is called from dtrace_module_unloaded().
16226 * It removes a modctl structure and its stale chain
16227 * from the kext shadow list.
16228 */
16229 static void
16230 dtrace_modctl_remove(struct modctl * ctl)
16231 {
16232 ASSERT(ctl != NULL);
16233 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
16234 modctl_t *prevp, *nextp, *curp;
16235
16236 // Remove stale chain first
16237 for (curp=ctl->mod_stale; curp != NULL; curp=nextp) {
16238 nextp = curp->mod_stale;
16239 /* There should NEVER be user symbols allocated at this point */
16240 ASSERT(curp->mod_user_symbols == NULL);
16241 kmem_free(curp, sizeof(modctl_t));
16242 }
16243
16244 prevp = NULL;
16245 curp = dtrace_modctl_list;
16246
16247 while (curp != ctl) {
16248 prevp = curp;
16249 curp = curp->mod_next;
16250 }
16251
16252 if (prevp != NULL) {
16253 prevp->mod_next = ctl->mod_next;
16254 }
16255 else {
16256 dtrace_modctl_list = ctl->mod_next;
16257 }
16258
16259 /* There should NEVER be user symbols allocated at this point */
16260 ASSERT(ctl->mod_user_symbols == NULL);
16261
16262 kmem_free (ctl, sizeof(modctl_t));
16263 }
16264
16265 #endif /* __APPLE__ */
16266
16267 /*
16268 * APPLE NOTE: The kext loader will call dtrace_module_loaded
16269 * when the kext is loaded in memory, but before calling the
16270 * kext's start routine.
16271 *
16272 * Return 0 on success
16273 * Return -1 on failure
16274 */
16275
16276 #if !defined (__APPLE__)
16277 static void
16278 dtrace_module_loaded(struct modctl *ctl)
16279 #else
16280 static int
16281 dtrace_module_loaded(struct kmod_info *kmod, uint32_t flag)
16282 #endif /* __APPLE__ */
16283 {
16284 dtrace_provider_t *prv;
16285
16286 #if !defined(__APPLE__)
16287 mutex_enter(&dtrace_provider_lock);
16288 mutex_enter(&mod_lock);
16289
16290 ASSERT(ctl->mod_busy);
16291 #else
16292
16293 /*
16294 * If kernel symbols have been disabled, return immediately
16295 * DTRACE_KERNEL_SYMBOLS_NEVER is a permanent mode, it is safe to test without holding locks
16296 */
16297 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER)
16298 return 0;
16299
16300 struct modctl *ctl = NULL;
16301 if (!kmod || kmod->address == 0 || kmod->size == 0)
16302 return(-1);
16303
16304 lck_mtx_lock(&dtrace_provider_lock);
16305 lck_mtx_lock(&mod_lock);
16306
16307 /*
16308 * Have we seen this kext before?
16309 */
16310
16311 ctl = dtrace_modctl_lookup(kmod);
16312
16313 if (ctl != NULL) {
16314 /* bail... we already have this kext in the modctl list */
16315 lck_mtx_unlock(&mod_lock);
16316 lck_mtx_unlock(&dtrace_provider_lock);
16317 if (dtrace_err_verbose)
16318 cmn_err(CE_WARN, "dtrace load module already exists '%s %u' is failing against '%s %u'", kmod->name, (uint_t)kmod->id, ctl->mod_modname, ctl->mod_id);
16319 return(-1);
16320 }
16321 else {
16322 ctl = kmem_alloc(sizeof(struct modctl), KM_SLEEP);
16323 if (ctl == NULL) {
16324 if (dtrace_err_verbose)
16325 cmn_err(CE_WARN, "dtrace module load '%s %u' is failing ", kmod->name, (uint_t)kmod->id);
16326 lck_mtx_unlock(&mod_lock);
16327 lck_mtx_unlock(&dtrace_provider_lock);
16328 return (-1);
16329 }
16330 ctl->mod_next = NULL;
16331 ctl->mod_stale = NULL;
16332 strlcpy (ctl->mod_modname, kmod->name, sizeof(ctl->mod_modname));
16333 ctl->mod_loadcnt = kmod->id;
16334 ctl->mod_nenabled = 0;
16335 ctl->mod_address = kmod->address;
16336 ctl->mod_size = kmod->size;
16337 ctl->mod_id = kmod->id;
16338 ctl->mod_loaded = 1;
16339 ctl->mod_flags = 0;
16340 ctl->mod_user_symbols = NULL;
16341
16342 /*
16343 * Find the UUID for this module, if it has one
16344 */
16345 kernel_mach_header_t* header = (kernel_mach_header_t *)ctl->mod_address;
16346 struct load_command* load_cmd = (struct load_command *)&header[1];
16347 uint32_t i;
16348 for (i = 0; i < header->ncmds; i++) {
16349 if (load_cmd->cmd == LC_UUID) {
16350 struct uuid_command* uuid_cmd = (struct uuid_command *)load_cmd;
16351 memcpy(ctl->mod_uuid, uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
16352 ctl->mod_flags |= MODCTL_HAS_UUID;
16353 break;
16354 }
16355 load_cmd = (struct load_command *)((caddr_t)load_cmd + load_cmd->cmdsize);
16356 }
16357
16358 if (ctl->mod_address == g_kernel_kmod_info.address) {
16359 ctl->mod_flags |= MODCTL_IS_MACH_KERNEL;
16360 }
16361 }
16362 dtrace_modctl_add(ctl);
16363
16364 /*
16365 * We must hold the dtrace_lock to safely test non permanent dtrace_fbt_symbol_mode(s)
16366 */
16367 lck_mtx_lock(&dtrace_lock);
16368
16369 /*
16370 * DTrace must decide if it will instrument modules lazily via
16371 * userspace symbols (default mode), or instrument immediately via
16372 * kernel symbols (non-default mode)
16373 *
16374 * When in default/lazy mode, DTrace will only support modules
16375 * built with a valid UUID.
16376 *
16377 * Overriding the default can be done explicitly in one of
16378 * the following two ways.
16379 *
16380 * A module can force symbols from kernel space using the plist key,
16381 * OSBundleForceDTraceInit (see kmod.h). If this per kext state is set,
16382 * we fall through and instrument this module now.
16383 *
16384 * Or, the boot-arg, dtrace_kernel_symbol_mode, can be set to force symbols
16385 * from kernel space (see dtrace_impl.h). If this system state is set
16386 * to a non-userspace mode, we fall through and instrument the module now.
16387 */
16388
16389 if ((dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) &&
16390 (!(flag & KMOD_DTRACE_FORCE_INIT)))
16391 {
16392 /* We will instrument the module lazily -- this is the default */
16393 lck_mtx_unlock(&dtrace_lock);
16394 lck_mtx_unlock(&mod_lock);
16395 lck_mtx_unlock(&dtrace_provider_lock);
16396 return 0;
16397 }
16398
16399 /* We will instrument the module immediately using kernel symbols */
16400 ctl->mod_flags |= MODCTL_HAS_KERNEL_SYMBOLS;
16401
16402 lck_mtx_unlock(&dtrace_lock);
16403 #endif /* __APPLE__ */
16404
16405 /*
16406 * We're going to call each providers per-module provide operation
16407 * specifying only this module.
16408 */
16409 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
16410 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
16411
16412 #if defined(__APPLE__)
16413 /*
16414 * The contract with the kext loader is that once this function has completed,
16415 * it may delete kernel symbols at will. We must set this while still holding
16416 * the mod_lock.
16417 */
16418 ctl->mod_flags &= ~MODCTL_HAS_KERNEL_SYMBOLS;
16419 #endif
16420
16421 lck_mtx_unlock(&mod_lock);
16422 lck_mtx_unlock(&dtrace_provider_lock);
16423
16424 /*
16425 * If we have any retained enablings, we need to match against them.
16426 * Enabling probes requires that cpu_lock be held, and we cannot hold
16427 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
16428 * module. (In particular, this happens when loading scheduling
16429 * classes.) So if we have any retained enablings, we need to dispatch
16430 * our task queue to do the match for us.
16431 */
16432 lck_mtx_lock(&dtrace_lock);
16433
16434 if (dtrace_retained == NULL) {
16435 lck_mtx_unlock(&dtrace_lock);
16436 #if !defined(__APPLE__)
16437 return;
16438 #else
16439 return 0;
16440 #endif
16441 }
16442
16443 #if !defined(__APPLE__)
16444 (void) taskq_dispatch(dtrace_taskq,
16445 (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
16446
16447 mutex_exit(&dtrace_lock);
16448
16449 /*
16450 * And now, for a little heuristic sleaze: in general, we want to
16451 * match modules as soon as they load. However, we cannot guarantee
16452 * this, because it would lead us to the lock ordering violation
16453 * outlined above. The common case, of course, is that cpu_lock is
16454 * _not_ held -- so we delay here for a clock tick, hoping that that's
16455 * long enough for the task queue to do its work. If it's not, it's
16456 * not a serious problem -- it just means that the module that we
16457 * just loaded may not be immediately instrumentable.
16458 */
16459 delay(1);
16460 #else
16461 /* APPLE NOTE!
16462 *
16463 * The cpu_lock mentioned above is only held by dtrace code, Apple's xnu never actually
16464 * holds it for any reason. Thus the comment above is invalid, we can directly invoke
16465 * dtrace_enabling_matchall without jumping through all the hoops, and we can avoid
16466 * the delay call as well.
16467 */
16468 lck_mtx_unlock(&dtrace_lock);
16469
16470 dtrace_enabling_matchall();
16471
16472 return 0;
16473 #endif /* __APPLE__ */
16474 }
16475
16476 #if !defined(__APPLE__)
16477 static void
16478 dtrace_module_unloaded(struct modctl *ctl)
16479 {
16480 dtrace_probe_t template, *probe, *first, *next;
16481 dtrace_provider_t *prov;
16482
16483 template.dtpr_mod = ctl->mod_modname;
16484
16485 mutex_enter(&dtrace_provider_lock);
16486 mutex_enter(&mod_lock);
16487 mutex_enter(&dtrace_lock);
16488
16489 if (dtrace_bymod == NULL) {
16490 /*
16491 * The DTrace module is loaded (obviously) but not attached;
16492 * we don't have any work to do.
16493 */
16494 mutex_exit(&dtrace_provider_lock);
16495 mutex_exit(&mod_lock);
16496 mutex_exit(&dtrace_lock);
16497 return;
16498 }
16499
16500 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16501 probe != NULL; probe = probe->dtpr_nextmod) {
16502 if (probe->dtpr_ecb != NULL) {
16503 mutex_exit(&dtrace_provider_lock);
16504 mutex_exit(&mod_lock);
16505 mutex_exit(&dtrace_lock);
16506
16507 /*
16508 * This shouldn't _actually_ be possible -- we're
16509 * unloading a module that has an enabled probe in it.
16510 * (It's normally up to the provider to make sure that
16511 * this can't happen.) However, because dtps_enable()
16512 * doesn't have a failure mode, there can be an
16513 * enable/unload race. Upshot: we don't want to
16514 * assert, but we're not going to disable the
16515 * probe, either.
16516 */
16517 if (dtrace_err_verbose) {
16518 cmn_err(CE_WARN, "unloaded module '%s' had "
16519 "enabled probes", ctl->mod_modname);
16520 }
16521
16522 return;
16523 }
16524 }
16525
16526 probe = first;
16527
16528 for (first = NULL; probe != NULL; probe = next) {
16529 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16530
16531 dtrace_probes[probe->dtpr_id - 1] = NULL;
16532
16533 next = probe->dtpr_nextmod;
16534 dtrace_hash_remove(dtrace_bymod, probe);
16535 dtrace_hash_remove(dtrace_byfunc, probe);
16536 dtrace_hash_remove(dtrace_byname, probe);
16537
16538 if (first == NULL) {
16539 first = probe;
16540 probe->dtpr_nextmod = NULL;
16541 } else {
16542 probe->dtpr_nextmod = first;
16543 first = probe;
16544 }
16545 }
16546
16547 /*
16548 * We've removed all of the module's probes from the hash chains and
16549 * from the probe array. Now issue a dtrace_sync() to be sure that
16550 * everyone has cleared out from any probe array processing.
16551 */
16552 dtrace_sync();
16553
16554 for (probe = first; probe != NULL; probe = first) {
16555 first = probe->dtpr_nextmod;
16556 prov = probe->dtpr_provider;
16557 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16558 probe->dtpr_arg);
16559 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16560 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16561 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16562 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16563 kmem_free(probe, sizeof (dtrace_probe_t));
16564 }
16565
16566 mutex_exit(&dtrace_lock);
16567 mutex_exit(&mod_lock);
16568 mutex_exit(&dtrace_provider_lock);
16569 }
16570 #else /* __APPLE__ */
16571
16572 /*
16573 * Return 0 on success
16574 * Return -1 on failure
16575 */
16576 static int
16577 dtrace_module_unloaded(struct kmod_info *kmod)
16578 {
16579 dtrace_probe_t template, *probe, *first, *next;
16580 dtrace_provider_t *prov;
16581 struct modctl *ctl = NULL;
16582 struct modctl *syncctl = NULL;
16583 struct modctl *nextsyncctl = NULL;
16584 int syncmode = 0;
16585
16586 lck_mtx_lock(&dtrace_provider_lock);
16587 lck_mtx_lock(&mod_lock);
16588 lck_mtx_lock(&dtrace_lock);
16589
16590 if (kmod == NULL) {
16591 syncmode = 1;
16592 }
16593 else {
16594 ctl = dtrace_modctl_lookup(kmod);
16595 if (ctl == NULL)
16596 {
16597 lck_mtx_unlock(&dtrace_lock);
16598 lck_mtx_unlock(&mod_lock);
16599 lck_mtx_unlock(&dtrace_provider_lock);
16600 return (-1);
16601 }
16602 ctl->mod_loaded = 0;
16603 ctl->mod_address = 0;
16604 ctl->mod_size = 0;
16605 }
16606
16607 if (dtrace_bymod == NULL) {
16608 /*
16609 * The DTrace module is loaded (obviously) but not attached;
16610 * we don't have any work to do.
16611 */
16612 if (ctl != NULL)
16613 (void)dtrace_modctl_remove(ctl);
16614 lck_mtx_unlock(&dtrace_provider_lock);
16615 lck_mtx_unlock(&mod_lock);
16616 lck_mtx_unlock(&dtrace_lock);
16617 return(0);
16618 }
16619
16620 /* Syncmode set means we target and traverse entire modctl list. */
16621 if (syncmode)
16622 nextsyncctl = dtrace_modctl_list;
16623
16624 syncloop:
16625 if (syncmode)
16626 {
16627 /* find a stale modctl struct */
16628 for (syncctl = nextsyncctl; syncctl != NULL; syncctl=syncctl->mod_next) {
16629 if (syncctl->mod_address == 0)
16630 break;
16631 }
16632 if (syncctl==NULL)
16633 {
16634 /* We have no more work to do */
16635 lck_mtx_unlock(&dtrace_provider_lock);
16636 lck_mtx_unlock(&mod_lock);
16637 lck_mtx_unlock(&dtrace_lock);
16638 return(0);
16639 }
16640 else {
16641 /* keep track of next syncctl in case this one is removed */
16642 nextsyncctl = syncctl->mod_next;
16643 ctl = syncctl;
16644 }
16645 }
16646
16647 template.dtpr_mod = ctl->mod_modname;
16648
16649 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
16650 probe != NULL; probe = probe->dtpr_nextmod) {
16651 if (probe->dtpr_ecb != NULL) {
16652 /*
16653 * This shouldn't _actually_ be possible -- we're
16654 * unloading a module that has an enabled probe in it.
16655 * (It's normally up to the provider to make sure that
16656 * this can't happen.) However, because dtps_enable()
16657 * doesn't have a failure mode, there can be an
16658 * enable/unload race. Upshot: we don't want to
16659 * assert, but we're not going to disable the
16660 * probe, either.
16661 */
16662
16663
16664 if (syncmode) {
16665 /* We're syncing, let's look at next in list */
16666 goto syncloop;
16667 }
16668
16669 lck_mtx_unlock(&dtrace_provider_lock);
16670 lck_mtx_unlock(&mod_lock);
16671 lck_mtx_unlock(&dtrace_lock);
16672
16673 if (dtrace_err_verbose) {
16674 cmn_err(CE_WARN, "unloaded module '%s' had "
16675 "enabled probes", ctl->mod_modname);
16676 }
16677 return(-1);
16678 }
16679 }
16680
16681 probe = first;
16682
16683 for (first = NULL; probe != NULL; probe = next) {
16684 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
16685
16686 dtrace_probes[probe->dtpr_id - 1] = NULL;
16687
16688 next = probe->dtpr_nextmod;
16689 dtrace_hash_remove(dtrace_bymod, probe);
16690 dtrace_hash_remove(dtrace_byfunc, probe);
16691 dtrace_hash_remove(dtrace_byname, probe);
16692
16693 if (first == NULL) {
16694 first = probe;
16695 probe->dtpr_nextmod = NULL;
16696 } else {
16697 probe->dtpr_nextmod = first;
16698 first = probe;
16699 }
16700 }
16701
16702 /*
16703 * We've removed all of the module's probes from the hash chains and
16704 * from the probe array. Now issue a dtrace_sync() to be sure that
16705 * everyone has cleared out from any probe array processing.
16706 */
16707 dtrace_sync();
16708
16709 for (probe = first; probe != NULL; probe = first) {
16710 first = probe->dtpr_nextmod;
16711 prov = probe->dtpr_provider;
16712 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16713 probe->dtpr_arg);
16714 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16715 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16716 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16717 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16718
16719 zfree(dtrace_probe_t_zone, probe);
16720 }
16721
16722 dtrace_modctl_remove(ctl);
16723
16724 if (syncmode)
16725 goto syncloop;
16726
16727 lck_mtx_unlock(&dtrace_lock);
16728 lck_mtx_unlock(&mod_lock);
16729 lck_mtx_unlock(&dtrace_provider_lock);
16730
16731 return(0);
16732 }
16733 #endif /* __APPLE__ */
16734
16735 void
16736 dtrace_suspend(void)
16737 {
16738 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16739 }
16740
16741 void
16742 dtrace_resume(void)
16743 {
16744 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16745 }
16746
16747 static int
16748 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16749 {
16750 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
16751 lck_mtx_lock(&dtrace_lock);
16752
16753 switch (what) {
16754 case CPU_CONFIG: {
16755 dtrace_state_t *state;
16756 dtrace_optval_t *opt, rs, c;
16757
16758 /*
16759 * For now, we only allocate a new buffer for anonymous state.
16760 */
16761 if ((state = dtrace_anon.dta_state) == NULL)
16762 break;
16763
16764 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16765 break;
16766
16767 opt = state->dts_options;
16768 c = opt[DTRACEOPT_CPU];
16769
16770 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16771 break;
16772
16773 /*
16774 * Regardless of what the actual policy is, we're going to
16775 * temporarily set our resize policy to be manual. We're
16776 * also going to temporarily set our CPU option to denote
16777 * the newly configured CPU.
16778 */
16779 rs = opt[DTRACEOPT_BUFRESIZE];
16780 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16781 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16782
16783 (void) dtrace_state_buffers(state);
16784
16785 opt[DTRACEOPT_BUFRESIZE] = rs;
16786 opt[DTRACEOPT_CPU] = c;
16787
16788 break;
16789 }
16790
16791 case CPU_UNCONFIG:
16792 /*
16793 * We don't free the buffer in the CPU_UNCONFIG case. (The
16794 * buffer will be freed when the consumer exits.)
16795 */
16796 break;
16797
16798 default:
16799 break;
16800 }
16801
16802 lck_mtx_unlock(&dtrace_lock);
16803 return (0);
16804 }
16805
16806 static void
16807 dtrace_cpu_setup_initial(processorid_t cpu)
16808 {
16809 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16810 }
16811
16812 static void
16813 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16814 {
16815 if (dtrace_toxranges >= dtrace_toxranges_max) {
16816 int osize, nsize;
16817 dtrace_toxrange_t *range;
16818
16819 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16820
16821 if (osize == 0) {
16822 ASSERT(dtrace_toxrange == NULL);
16823 ASSERT(dtrace_toxranges_max == 0);
16824 dtrace_toxranges_max = 1;
16825 } else {
16826 dtrace_toxranges_max <<= 1;
16827 }
16828
16829 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16830 range = kmem_zalloc(nsize, KM_SLEEP);
16831
16832 if (dtrace_toxrange != NULL) {
16833 ASSERT(osize != 0);
16834 bcopy(dtrace_toxrange, range, osize);
16835 kmem_free(dtrace_toxrange, osize);
16836 }
16837
16838 dtrace_toxrange = range;
16839 }
16840
16841 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
16842 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
16843
16844 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16845 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16846 dtrace_toxranges++;
16847 }
16848
16849 /*
16850 * DTrace Driver Cookbook Functions
16851 */
16852 /*ARGSUSED*/
16853 static int
16854 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16855 {
16856 #pragma unused(cmd) /* __APPLE__ */
16857 dtrace_provider_id_t id;
16858 dtrace_state_t *state = NULL;
16859 dtrace_enabling_t *enab;
16860
16861 lck_mtx_lock(&cpu_lock);
16862 lck_mtx_lock(&dtrace_provider_lock);
16863 lck_mtx_lock(&dtrace_lock);
16864
16865 if (ddi_soft_state_init(&dtrace_softstate,
16866 sizeof (dtrace_state_t), 0) != 0) {
16867 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
16868 lck_mtx_unlock(&cpu_lock);
16869 lck_mtx_unlock(&dtrace_provider_lock);
16870 lck_mtx_unlock(&dtrace_lock);
16871 return (DDI_FAILURE);
16872 }
16873
16874 #if !defined(__APPLE__)
16875 if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
16876 DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
16877 ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
16878 DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
16879 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
16880 ddi_remove_minor_node(devi, NULL);
16881 ddi_soft_state_fini(&dtrace_softstate);
16882 lck_mtx_unlock(&cpu_lock);
16883 lck_mtx_unlock(&dtrace_provider_lock);
16884 lck_mtx_unlock(&dtrace_lock);
16885 return (DDI_FAILURE);
16886 }
16887 #else
16888 /* Darwin uses BSD cloning device driver to automagically obtain minor device number. */
16889 #endif /* __APPLE__ */
16890
16891 ddi_report_dev(devi);
16892 dtrace_devi = devi;
16893
16894 dtrace_modload = dtrace_module_loaded;
16895 dtrace_modunload = dtrace_module_unloaded;
16896 dtrace_cpu_init = dtrace_cpu_setup_initial;
16897 dtrace_helpers_cleanup = dtrace_helpers_destroy;
16898 dtrace_helpers_fork = dtrace_helpers_duplicate;
16899 dtrace_cpustart_init = dtrace_suspend;
16900 dtrace_cpustart_fini = dtrace_resume;
16901 dtrace_debugger_init = dtrace_suspend;
16902 dtrace_debugger_fini = dtrace_resume;
16903
16904 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16905
16906 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
16907
16908 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16909 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16910 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
16911 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
16912 VM_SLEEP | VMC_IDENTIFIER);
16913 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16914 1, INT_MAX, 0);
16915
16916 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16917 sizeof (dtrace_dstate_percpu_t) * (int)NCPU, DTRACE_STATE_ALIGN,
16918 NULL, NULL, NULL, NULL, NULL, 0);
16919
16920 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
16921 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16922 offsetof(dtrace_probe_t, dtpr_nextmod),
16923 offsetof(dtrace_probe_t, dtpr_prevmod));
16924
16925 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16926 offsetof(dtrace_probe_t, dtpr_nextfunc),
16927 offsetof(dtrace_probe_t, dtpr_prevfunc));
16928
16929 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16930 offsetof(dtrace_probe_t, dtpr_nextname),
16931 offsetof(dtrace_probe_t, dtpr_prevname));
16932
16933 if (dtrace_retain_max < 1) {
16934 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16935 "setting to 1", dtrace_retain_max);
16936 dtrace_retain_max = 1;
16937 }
16938
16939 /*
16940 * Now discover our toxic ranges.
16941 */
16942 dtrace_toxic_ranges(dtrace_toxrange_add);
16943
16944 /*
16945 * Before we register ourselves as a provider to our own framework,
16946 * we would like to assert that dtrace_provider is NULL -- but that's
16947 * not true if we were loaded as a dependency of a DTrace provider.
16948 * Once we've registered, we can assert that dtrace_provider is our
16949 * pseudo provider.
16950 */
16951 (void) dtrace_register("dtrace", &dtrace_provider_attr,
16952 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16953
16954 ASSERT(dtrace_provider != NULL);
16955 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16956
16957 #if !defined(__APPLE__)
16958 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16959 dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
16960 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16961 dtrace_provider, NULL, NULL, "END", 0, NULL);
16962 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16963 dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
16964 #elif (defined(__i386__) || defined (__x86_64__))
16965 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16966 dtrace_provider, NULL, NULL, "BEGIN", 1, NULL);
16967 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16968 dtrace_provider, NULL, NULL, "END", 0, NULL);
16969 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16970 dtrace_provider, NULL, NULL, "ERROR", 3, NULL);
16971 #else
16972 #error Unknown Architecture
16973 #endif /* __APPLE__ */
16974
16975 dtrace_anon_property();
16976 lck_mtx_unlock(&cpu_lock);
16977
16978 /*
16979 * If DTrace helper tracing is enabled, we need to allocate the
16980 * trace buffer and initialize the values.
16981 */
16982 if (dtrace_helptrace_enabled) {
16983 ASSERT(dtrace_helptrace_buffer == NULL);
16984 dtrace_helptrace_buffer =
16985 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16986 dtrace_helptrace_next = 0;
16987 }
16988
16989 /*
16990 * If there are already providers, we must ask them to provide their
16991 * probes, and then match any anonymous enabling against them. Note
16992 * that there should be no other retained enablings at this time:
16993 * the only retained enablings at this time should be the anonymous
16994 * enabling.
16995 */
16996 if (dtrace_anon.dta_enabling != NULL) {
16997 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16998
16999 #if defined(__APPLE__)
17000 /*
17001 * If there is anonymous dof, we should switch symbol modes.
17002 */
17003 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
17004 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
17005 }
17006 #endif
17007
17008 dtrace_enabling_provide(NULL);
17009 state = dtrace_anon.dta_state;
17010
17011 /*
17012 * We couldn't hold cpu_lock across the above call to
17013 * dtrace_enabling_provide(), but we must hold it to actually
17014 * enable the probes. We have to drop all of our locks, pick
17015 * up cpu_lock, and regain our locks before matching the
17016 * retained anonymous enabling.
17017 */
17018 lck_mtx_unlock(&dtrace_lock);
17019 lck_mtx_unlock(&dtrace_provider_lock);
17020
17021 lck_mtx_lock(&cpu_lock);
17022 lck_mtx_lock(&dtrace_provider_lock);
17023 lck_mtx_lock(&dtrace_lock);
17024
17025 if ((enab = dtrace_anon.dta_enabling) != NULL)
17026 (void) dtrace_enabling_match(enab, NULL);
17027
17028 lck_mtx_unlock(&cpu_lock);
17029 }
17030
17031 lck_mtx_unlock(&dtrace_lock);
17032 lck_mtx_unlock(&dtrace_provider_lock);
17033
17034 if (state != NULL) {
17035 /*
17036 * If we created any anonymous state, set it going now.
17037 */
17038 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
17039 }
17040
17041 return (DDI_SUCCESS);
17042 }
17043
17044 /*ARGSUSED*/
17045 static int
17046 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
17047 {
17048 #pragma unused(flag, otyp)
17049 dtrace_state_t *state;
17050 uint32_t priv;
17051 uid_t uid;
17052 zoneid_t zoneid;
17053 #if defined (__APPLE__)
17054 int rv;
17055 #endif /* __APPLE__ */
17056
17057 #if !defined(__APPLE__)
17058 if (getminor(*devp) == DTRACEMNRN_HELPER)
17059 return (0);
17060
17061 /*
17062 * If this wasn't an open with the "helper" minor, then it must be
17063 * the "dtrace" minor.
17064 */
17065 if (getminor(*devp) != DTRACEMNRN_DTRACE)
17066 return (ENXIO);
17067 #else
17068 /* Darwin puts Helper on its own major device. */
17069 #endif /* __APPLE__ */
17070
17071 /*
17072 * If no DTRACE_PRIV_* bits are set in the credential, then the
17073 * caller lacks sufficient permission to do anything with DTrace.
17074 */
17075 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
17076 if (priv == DTRACE_PRIV_NONE)
17077 return (EACCES);
17078
17079 #if defined(__APPLE__)
17080 /*
17081 * We delay the initialization of fasttrap as late as possible.
17082 * It certainly can't be later than now!
17083 */
17084 fasttrap_init();
17085 #endif /* __APPLE__ */
17086
17087 /*
17088 * Ask all providers to provide all their probes.
17089 */
17090 lck_mtx_lock(&dtrace_provider_lock);
17091 dtrace_probe_provide(NULL, NULL);
17092 lck_mtx_unlock(&dtrace_provider_lock);
17093
17094 lck_mtx_lock(&cpu_lock);
17095 lck_mtx_lock(&dtrace_lock);
17096 dtrace_opens++;
17097 dtrace_membar_producer();
17098
17099 /*
17100 * If the kernel debugger is active (that is, if the kernel debugger
17101 * modified text in some way), we won't allow the open.
17102 */
17103 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
17104 dtrace_opens--;
17105 lck_mtx_unlock(&cpu_lock);
17106 lck_mtx_unlock(&dtrace_lock);
17107 return (EBUSY);
17108 }
17109
17110 #if !defined(__APPLE__)
17111 state = dtrace_state_create(devp, cred_p);
17112 lck_mtx_unlock(&cpu_lock);
17113
17114 if (state == NULL) {
17115 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17116 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17117 lck_mtx_unlock(&dtrace_lock);
17118 return (EAGAIN);
17119 }
17120
17121 lck_mtx_unlock(&dtrace_lock);
17122 #else
17123 rv = dtrace_state_create(devp, cred_p, &state);
17124 lck_mtx_unlock(&cpu_lock);
17125
17126 if (rv != 0 || state == NULL) {
17127 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17128 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17129 lck_mtx_unlock(&dtrace_lock);
17130 /* propagate EAGAIN or ERESTART */
17131 return (rv);
17132 }
17133
17134 lck_mtx_unlock(&dtrace_lock);
17135
17136 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
17137
17138 /*
17139 * If we are currently lazy, transition states.
17140 *
17141 * Unlike dtrace_close, we do not need to check the
17142 * value of dtrace_opens, as any positive value (and
17143 * we count as 1) means we transition states.
17144 */
17145 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON) {
17146 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_OFF;
17147
17148 /*
17149 * Iterate all existing processes and load lazy dofs.
17150 */
17151 proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS,
17152 dtrace_lazy_dofs_proc_iterate_doit,
17153 NULL,
17154 dtrace_lazy_dofs_proc_iterate_filter,
17155 NULL);
17156 }
17157
17158 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
17159
17160 /*
17161 * Update kernel symbol state.
17162 *
17163 * We must own the provider and dtrace locks.
17164 *
17165 * NOTE! It may appear there is a race by setting this value so late
17166 * after dtrace_probe_provide. However, any kext loaded after the
17167 * call to probe provide and before we set LAZY_OFF will be marked as
17168 * eligible for symbols from userspace. The same dtrace that is currently
17169 * calling dtrace_open() (this call!) will get a list of kexts needing
17170 * symbols and fill them in, thus closing the race window.
17171 *
17172 * We want to set this value only after it certain it will succeed, as
17173 * this significantly reduces the complexity of error exits.
17174 */
17175 lck_mtx_lock(&dtrace_lock);
17176 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
17177 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
17178 }
17179 lck_mtx_unlock(&dtrace_lock);
17180 #endif /* __APPLE__ */
17181
17182 return (0);
17183 }
17184
17185 /*ARGSUSED*/
17186 static int
17187 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
17188 {
17189 #pragma unused(flag, otyp, cred_p) /* __APPLE__ */
17190 minor_t minor = getminor(dev);
17191 dtrace_state_t *state;
17192
17193 #if !defined(__APPLE__)
17194 if (minor == DTRACEMNRN_HELPER)
17195 return (0);
17196 #else
17197 /* Darwin puts Helper on its own major device. */
17198 #endif /* __APPLE__ */
17199
17200 state = ddi_get_soft_state(dtrace_softstate, minor);
17201
17202 lck_mtx_lock(&cpu_lock);
17203 lck_mtx_lock(&dtrace_lock);
17204
17205 if (state->dts_anon) {
17206 /*
17207 * There is anonymous state. Destroy that first.
17208 */
17209 ASSERT(dtrace_anon.dta_state == NULL);
17210 dtrace_state_destroy(state->dts_anon);
17211 }
17212
17213 dtrace_state_destroy(state);
17214 ASSERT(dtrace_opens > 0);
17215
17216 /*
17217 * Only relinquish control of the kernel debugger interface when there
17218 * are no consumers and no anonymous enablings.
17219 */
17220 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
17221 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17222
17223 lck_mtx_unlock(&dtrace_lock);
17224 lck_mtx_unlock(&cpu_lock);
17225
17226 #if defined(__APPLE__)
17227 /*
17228 * Lock ordering requires the dof mode lock be taken before
17229 * the dtrace_lock.
17230 */
17231 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
17232 lck_mtx_lock(&dtrace_lock);
17233
17234 if (dtrace_opens == 0) {
17235 /*
17236 * If we are currently lazy-off, and this is the last close, transition to
17237 * lazy state.
17238 */
17239 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
17240 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
17241 }
17242
17243 /*
17244 * If we are the last dtrace client, switch back to lazy (from userspace) symbols
17245 */
17246 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_KERNEL) {
17247 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
17248 }
17249 }
17250
17251 lck_mtx_unlock(&dtrace_lock);
17252 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
17253
17254 /*
17255 * Kext probes may be retained past the end of the kext's lifespan. The
17256 * probes are kept until the last reference to them has been removed.
17257 * Since closing an active dtrace context is likely to drop that last reference,
17258 * lets take a shot at cleaning out the orphaned probes now.
17259 */
17260 dtrace_module_unloaded(NULL);
17261 #endif /* __APPLE__ */
17262
17263 return (0);
17264 }
17265
17266 #if !defined(__APPLE__)
17267 /*ARGSUSED*/
17268 static int
17269 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
17270 {
17271 int rval;
17272 dof_helper_t help, *dhp = NULL;
17273
17274 switch (cmd) {
17275 case DTRACEHIOC_ADDDOF:
17276 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
17277 dtrace_dof_error(NULL, "failed to copyin DOF helper");
17278 return (EFAULT);
17279 }
17280
17281 dhp = &help;
17282 arg = (intptr_t)help.dofhp_dof;
17283 /*FALLTHROUGH*/
17284
17285 case DTRACEHIOC_ADD: {
17286 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
17287
17288 if (dof == NULL)
17289 return (rval);
17290
17291 mutex_enter(&dtrace_lock);
17292
17293 /*
17294 * dtrace_helper_slurp() takes responsibility for the dof --
17295 * it may free it now or it may save it and free it later.
17296 */
17297 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
17298 *rv = rval;
17299 rval = 0;
17300 } else {
17301 rval = EINVAL;
17302 }
17303
17304 mutex_exit(&dtrace_lock);
17305 return (rval);
17306 }
17307
17308 case DTRACEHIOC_REMOVE: {
17309 mutex_enter(&dtrace_lock);
17310 rval = dtrace_helper_destroygen(arg);
17311 mutex_exit(&dtrace_lock);
17312
17313 return (rval);
17314 }
17315
17316 default:
17317 break;
17318 }
17319
17320 return (ENOTTY);
17321 }
17322
17323 /*ARGSUSED*/
17324 static int
17325 dtrace_ioctl(dev_t dev, u_long cmd, intptr_t arg, int md, cred_t *cr, int *rv)
17326 {
17327 minor_t minor = getminor(dev);
17328 dtrace_state_t *state;
17329 int rval;
17330
17331 if (minor == DTRACEMNRN_HELPER)
17332 return (dtrace_ioctl_helper(cmd, arg, rv));
17333
17334 state = ddi_get_soft_state(dtrace_softstate, minor);
17335
17336 if (state->dts_anon) {
17337 ASSERT(dtrace_anon.dta_state == NULL);
17338 state = state->dts_anon;
17339 }
17340
17341 switch (cmd) {
17342 case DTRACEIOC_PROVIDER: {
17343 dtrace_providerdesc_t pvd;
17344 dtrace_provider_t *pvp;
17345
17346 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
17347 return (EFAULT);
17348
17349 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
17350 lck_mtx_lock(&dtrace_provider_lock);
17351
17352 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
17353 if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
17354 break;
17355 }
17356
17357 lck_mtx_unlock(&dtrace_provider_lock);
17358
17359 if (pvp == NULL)
17360 return (ESRCH);
17361
17362 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
17363 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
17364 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
17365 return (EFAULT);
17366
17367 return (0);
17368 }
17369
17370 case DTRACEIOC_EPROBE: {
17371 dtrace_eprobedesc_t epdesc;
17372 dtrace_ecb_t *ecb;
17373 dtrace_action_t *act;
17374 void *buf;
17375 size_t size;
17376 uintptr_t dest;
17377 int nrecs;
17378
17379 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
17380 return (EFAULT);
17381
17382 lck_mtx_lock(&dtrace_lock);
17383
17384 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
17385 lck_mtx_unlock(&dtrace_lock);
17386 return (EINVAL);
17387 }
17388
17389 if (ecb->dte_probe == NULL) {
17390 lck_mtx_unlock(&dtrace_lock);
17391 return (EINVAL);
17392 }
17393
17394 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
17395 epdesc.dtepd_uarg = ecb->dte_uarg;
17396 epdesc.dtepd_size = ecb->dte_size;
17397
17398 nrecs = epdesc.dtepd_nrecs;
17399 epdesc.dtepd_nrecs = 0;
17400 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17401 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17402 continue;
17403
17404 epdesc.dtepd_nrecs++;
17405 }
17406
17407 /*
17408 * Now that we have the size, we need to allocate a temporary
17409 * buffer in which to store the complete description. We need
17410 * the temporary buffer to be able to drop dtrace_lock()
17411 * across the copyout(), below.
17412 */
17413 size = sizeof (dtrace_eprobedesc_t) +
17414 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
17415
17416 buf = kmem_alloc(size, KM_SLEEP);
17417 dest = (uintptr_t)buf;
17418
17419 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
17420 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
17421
17422 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
17423 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
17424 continue;
17425
17426 if (nrecs-- == 0)
17427 break;
17428
17429 bcopy(&act->dta_rec, (void *)dest,
17430 sizeof (dtrace_recdesc_t));
17431 dest += sizeof (dtrace_recdesc_t);
17432 }
17433
17434 lck_mtx_unlock(&dtrace_lock);
17435
17436 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17437 kmem_free(buf, size);
17438 return (EFAULT);
17439 }
17440
17441 kmem_free(buf, size);
17442 return (0);
17443 }
17444
17445 case DTRACEIOC_AGGDESC: {
17446 dtrace_aggdesc_t aggdesc;
17447 dtrace_action_t *act;
17448 dtrace_aggregation_t *agg;
17449 int nrecs;
17450 uint32_t offs;
17451 dtrace_recdesc_t *lrec;
17452 void *buf;
17453 size_t size;
17454 uintptr_t dest;
17455
17456 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
17457 return (EFAULT);
17458
17459 lck_mtx_lock(&dtrace_lock);
17460
17461 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
17462 lck_mtx_unlock(&dtrace_lock);
17463 return (EINVAL);
17464 }
17465
17466 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
17467
17468 nrecs = aggdesc.dtagd_nrecs;
17469 aggdesc.dtagd_nrecs = 0;
17470
17471 offs = agg->dtag_base;
17472 lrec = &agg->dtag_action.dta_rec;
17473 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
17474
17475 for (act = agg->dtag_first; ; act = act->dta_next) {
17476 ASSERT(act->dta_intuple ||
17477 DTRACEACT_ISAGG(act->dta_kind));
17478
17479 /*
17480 * If this action has a record size of zero, it
17481 * denotes an argument to the aggregating action.
17482 * Because the presence of this record doesn't (or
17483 * shouldn't) affect the way the data is interpreted,
17484 * we don't copy it out to save user-level the
17485 * confusion of dealing with a zero-length record.
17486 */
17487 if (act->dta_rec.dtrd_size == 0) {
17488 ASSERT(agg->dtag_hasarg);
17489 continue;
17490 }
17491
17492 aggdesc.dtagd_nrecs++;
17493
17494 if (act == &agg->dtag_action)
17495 break;
17496 }
17497
17498 /*
17499 * Now that we have the size, we need to allocate a temporary
17500 * buffer in which to store the complete description. We need
17501 * the temporary buffer to be able to drop dtrace_lock()
17502 * across the copyout(), below.
17503 */
17504 size = sizeof (dtrace_aggdesc_t) +
17505 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
17506
17507 buf = kmem_alloc(size, KM_SLEEP);
17508 dest = (uintptr_t)buf;
17509
17510 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
17511 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
17512
17513 for (act = agg->dtag_first; ; act = act->dta_next) {
17514 dtrace_recdesc_t rec = act->dta_rec;
17515
17516 /*
17517 * See the comment in the above loop for why we pass
17518 * over zero-length records.
17519 */
17520 if (rec.dtrd_size == 0) {
17521 ASSERT(agg->dtag_hasarg);
17522 continue;
17523 }
17524
17525 if (nrecs-- == 0)
17526 break;
17527
17528 rec.dtrd_offset -= offs;
17529 bcopy(&rec, (void *)dest, sizeof (rec));
17530 dest += sizeof (dtrace_recdesc_t);
17531
17532 if (act == &agg->dtag_action)
17533 break;
17534 }
17535
17536 lck_mtx_unlock(&dtrace_lock);
17537
17538 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
17539 kmem_free(buf, size);
17540 return (EFAULT);
17541 }
17542
17543 kmem_free(buf, size);
17544 return (0);
17545 }
17546
17547 case DTRACEIOC_ENABLE: {
17548 dof_hdr_t *dof;
17549 dtrace_enabling_t *enab = NULL;
17550 dtrace_vstate_t *vstate;
17551 int err = 0;
17552
17553 *rv = 0;
17554
17555 /*
17556 * If a NULL argument has been passed, we take this as our
17557 * cue to reevaluate our enablings.
17558 */
17559 if (arg == NULL) {
17560 dtrace_enabling_matchall();
17561
17562 return (0);
17563 }
17564
17565 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
17566 return (rval);
17567
17568 lck_mtx_lock(&cpu_lock);
17569 lck_mtx_lock(&dtrace_lock);
17570 vstate = &state->dts_vstate;
17571
17572 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
17573 lck_mtx_unlock(&dtrace_lock);
17574 lck_mtx_unlock(&cpu_lock);
17575 dtrace_dof_destroy(dof);
17576 return (EBUSY);
17577 }
17578
17579 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
17580 lck_mtx_unlock(&dtrace_lock);
17581 lck_mtx_unlock(&cpu_lock);
17582 dtrace_dof_destroy(dof);
17583 return (EINVAL);
17584 }
17585
17586 if ((rval = dtrace_dof_options(dof, state)) != 0) {
17587 dtrace_enabling_destroy(enab);
17588 lck_mtx_unlock(&dtrace_lock);
17589 lck_mtx_unlock(&cpu_lock);
17590 dtrace_dof_destroy(dof);
17591 return (rval);
17592 }
17593
17594 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
17595 err = dtrace_enabling_retain(enab);
17596 } else {
17597 dtrace_enabling_destroy(enab);
17598 }
17599
17600 lck_mtx_unlock(&cpu_lock);
17601 lck_mtx_unlock(&dtrace_lock);
17602 dtrace_dof_destroy(dof);
17603
17604 return (err);
17605 }
17606
17607 case DTRACEIOC_REPLICATE: {
17608 dtrace_repldesc_t desc;
17609 dtrace_probedesc_t *match = &desc.dtrpd_match;
17610 dtrace_probedesc_t *create = &desc.dtrpd_create;
17611 int err;
17612
17613 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17614 return (EFAULT);
17615
17616 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17617 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17618 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17619 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17620
17621 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17622 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17623 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17624 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17625
17626 lck_mtx_lock(&dtrace_lock);
17627 err = dtrace_enabling_replicate(state, match, create);
17628 lck_mtx_unlock(&dtrace_lock);
17629
17630 return (err);
17631 }
17632
17633 case DTRACEIOC_PROBEMATCH:
17634 case DTRACEIOC_PROBES: {
17635 dtrace_probe_t *probe = NULL;
17636 dtrace_probedesc_t desc;
17637 dtrace_probekey_t pkey;
17638 dtrace_id_t i;
17639 int m = 0;
17640 uint32_t priv;
17641 uid_t uid;
17642 zoneid_t zoneid;
17643
17644 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17645 return (EFAULT);
17646
17647 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
17648 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
17649 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
17650 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
17651
17652 /*
17653 * Before we attempt to match this probe, we want to give
17654 * all providers the opportunity to provide it.
17655 */
17656 if (desc.dtpd_id == DTRACE_IDNONE) {
17657 lck_mtx_lock(&dtrace_provider_lock);
17658 dtrace_probe_provide(&desc, NULL);
17659 lck_mtx_unlock(&dtrace_provider_lock);
17660 desc.dtpd_id++;
17661 }
17662
17663 if (cmd == DTRACEIOC_PROBEMATCH) {
17664 dtrace_probekey(&desc, &pkey);
17665 pkey.dtpk_id = DTRACE_IDNONE;
17666 }
17667
17668 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
17669
17670 lck_mtx_lock(&dtrace_lock);
17671
17672 if (cmd == DTRACEIOC_PROBEMATCH) {
17673 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17674 if ((probe = dtrace_probes[i - 1]) != NULL &&
17675 (m = dtrace_match_probe(probe, &pkey,
17676 priv, uid, zoneid)) != 0)
17677 break;
17678 }
17679
17680 if (m < 0) {
17681 lck_mtx_unlock(&dtrace_lock);
17682 return (EINVAL);
17683 }
17684
17685 } else {
17686 for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
17687 if ((probe = dtrace_probes[i - 1]) != NULL &&
17688 dtrace_match_priv(probe, priv, uid, zoneid))
17689 break;
17690 }
17691 }
17692
17693 if (probe == NULL) {
17694 lck_mtx_unlock(&dtrace_lock);
17695 return (ESRCH);
17696 }
17697
17698 dtrace_probe_description(probe, &desc);
17699 lck_mtx_unlock(&dtrace_lock);
17700
17701 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17702 return (EFAULT);
17703
17704 return (0);
17705 }
17706
17707 case DTRACEIOC_PROBEARG: {
17708 dtrace_argdesc_t desc;
17709 dtrace_probe_t *probe;
17710 dtrace_provider_t *prov;
17711
17712 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17713 return (EFAULT);
17714
17715 if (desc.dtargd_id == DTRACE_IDNONE)
17716 return (EINVAL);
17717
17718 if (desc.dtargd_ndx == DTRACE_ARGNONE)
17719 return (EINVAL);
17720
17721 lck_mtx_lock(&dtrace_provider_lock);
17722 lck_mtx_lock(&mod_lock);
17723 lck_mtx_lock(&dtrace_lock);
17724
17725 if (desc.dtargd_id > dtrace_nprobes) {
17726 lck_mtx_unlock(&dtrace_lock);
17727 lck_mtx_unlock(&mod_lock);
17728 lck_mtx_unlock(&dtrace_provider_lock);
17729 return (EINVAL);
17730 }
17731
17732 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17733 lck_mtx_unlock(&dtrace_lock);
17734 lck_mtx_unlock(&mod_lock);
17735 lck_mtx_unlock(&dtrace_provider_lock);
17736 return (EINVAL);
17737 }
17738
17739 lck_mtx_unlock(&dtrace_lock);
17740
17741 prov = probe->dtpr_provider;
17742
17743 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17744 /*
17745 * There isn't any typed information for this probe.
17746 * Set the argument number to DTRACE_ARGNONE.
17747 */
17748 desc.dtargd_ndx = DTRACE_ARGNONE;
17749 } else {
17750 desc.dtargd_native[0] = '\0';
17751 desc.dtargd_xlate[0] = '\0';
17752 desc.dtargd_mapping = desc.dtargd_ndx;
17753
17754 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17755 probe->dtpr_id, probe->dtpr_arg, &desc);
17756 }
17757
17758 lck_mtx_unlock(&mod_lock);
17759 lck_mtx_unlock(&dtrace_provider_lock);
17760
17761 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17762 return (EFAULT);
17763
17764 return (0);
17765 }
17766
17767 case DTRACEIOC_GO: {
17768 processorid_t cpuid;
17769 rval = dtrace_state_go(state, &cpuid);
17770
17771 if (rval != 0)
17772 return (rval);
17773
17774 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17775 return (EFAULT);
17776
17777 return (0);
17778 }
17779
17780 case DTRACEIOC_STOP: {
17781 processorid_t cpuid;
17782
17783 lck_mtx_lock(&dtrace_lock);
17784 rval = dtrace_state_stop(state, &cpuid);
17785 lck_mtx_unlock(&dtrace_lock);
17786
17787 if (rval != 0)
17788 return (rval);
17789
17790 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
17791 return (EFAULT);
17792
17793 return (0);
17794 }
17795
17796 case DTRACEIOC_DOFGET: {
17797 dof_hdr_t hdr, *dof;
17798 uint64_t len;
17799
17800 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
17801 return (EFAULT);
17802
17803 lck_mtx_lock(&dtrace_lock);
17804 dof = dtrace_dof_create(state);
17805 lck_mtx_unlock(&dtrace_lock);
17806
17807 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17808 rval = copyout(dof, (void *)arg, len);
17809 dtrace_dof_destroy(dof);
17810
17811 return (rval == 0 ? 0 : EFAULT);
17812 }
17813
17814 case DTRACEIOC_AGGSNAP:
17815 case DTRACEIOC_BUFSNAP: {
17816 dtrace_bufdesc_t desc;
17817 caddr_t cached;
17818 dtrace_buffer_t *buf;
17819
17820 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
17821 return (EFAULT);
17822
17823 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17824 return (EINVAL);
17825
17826 lck_mtx_lock(&dtrace_lock);
17827
17828 if (cmd == DTRACEIOC_BUFSNAP) {
17829 buf = &state->dts_buffer[desc.dtbd_cpu];
17830 } else {
17831 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17832 }
17833
17834 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17835 size_t sz = buf->dtb_offset;
17836
17837 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17838 lck_mtx_unlock(&dtrace_lock);
17839 return (EBUSY);
17840 }
17841
17842 /*
17843 * If this buffer has already been consumed, we're
17844 * going to indicate that there's nothing left here
17845 * to consume.
17846 */
17847 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17848 lck_mtx_unlock(&dtrace_lock);
17849
17850 desc.dtbd_size = 0;
17851 desc.dtbd_drops = 0;
17852 desc.dtbd_errors = 0;
17853 desc.dtbd_oldest = 0;
17854 sz = sizeof (desc);
17855
17856 if (copyout(&desc, (void *)arg, sz) != 0)
17857 return (EFAULT);
17858
17859 return (0);
17860 }
17861
17862 /*
17863 * If this is a ring buffer that has wrapped, we want
17864 * to copy the whole thing out.
17865 */
17866 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17867 dtrace_buffer_polish(buf);
17868 sz = buf->dtb_size;
17869 }
17870
17871 if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
17872 lck_mtx_unlock(&dtrace_lock);
17873 return (EFAULT);
17874 }
17875
17876 desc.dtbd_size = sz;
17877 desc.dtbd_drops = buf->dtb_drops;
17878 desc.dtbd_errors = buf->dtb_errors;
17879 desc.dtbd_oldest = buf->dtb_xamot_offset;
17880
17881 lck_mtx_unlock(&dtrace_lock);
17882
17883 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17884 return (EFAULT);
17885
17886 buf->dtb_flags |= DTRACEBUF_CONSUMED;
17887
17888 return (0);
17889 }
17890
17891 if (buf->dtb_tomax == NULL) {
17892 ASSERT(buf->dtb_xamot == NULL);
17893 lck_mtx_unlock(&dtrace_lock);
17894 return (ENOENT);
17895 }
17896
17897 cached = buf->dtb_tomax;
17898 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17899
17900 dtrace_xcall(desc.dtbd_cpu,
17901 (dtrace_xcall_t)dtrace_buffer_switch, buf);
17902
17903 state->dts_errors += buf->dtb_xamot_errors;
17904
17905 /*
17906 * If the buffers did not actually switch, then the cross call
17907 * did not take place -- presumably because the given CPU is
17908 * not in the ready set. If this is the case, we'll return
17909 * ENOENT.
17910 */
17911 if (buf->dtb_tomax == cached) {
17912 ASSERT(buf->dtb_xamot != cached);
17913 lck_mtx_unlock(&dtrace_lock);
17914 return (ENOENT);
17915 }
17916
17917 ASSERT(cached == buf->dtb_xamot);
17918
17919 /*
17920 * We have our snapshot; now copy it out.
17921 */
17922 if (copyout(buf->dtb_xamot, desc.dtbd_data,
17923 buf->dtb_xamot_offset) != 0) {
17924 lck_mtx_unlock(&dtrace_lock);
17925 return (EFAULT);
17926 }
17927
17928 desc.dtbd_size = buf->dtb_xamot_offset;
17929 desc.dtbd_drops = buf->dtb_xamot_drops;
17930 desc.dtbd_errors = buf->dtb_xamot_errors;
17931 desc.dtbd_oldest = 0;
17932
17933 lck_mtx_unlock(&dtrace_lock);
17934
17935 /*
17936 * Finally, copy out the buffer description.
17937 */
17938 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
17939 return (EFAULT);
17940
17941 return (0);
17942 }
17943
17944 case DTRACEIOC_CONF: {
17945 dtrace_conf_t conf;
17946
17947 bzero(&conf, sizeof (conf));
17948 conf.dtc_difversion = DIF_VERSION;
17949 conf.dtc_difintregs = DIF_DIR_NREGS;
17950 conf.dtc_diftupregs = DIF_DTR_NREGS;
17951 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17952
17953 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
17954 return (EFAULT);
17955
17956 return (0);
17957 }
17958
17959 case DTRACEIOC_STATUS: {
17960 dtrace_status_t stat;
17961 dtrace_dstate_t *dstate;
17962 int i, j;
17963 uint64_t nerrs;
17964
17965 /*
17966 * See the comment in dtrace_state_deadman() for the reason
17967 * for setting dts_laststatus to INT64_MAX before setting
17968 * it to the correct value.
17969 */
17970 state->dts_laststatus = INT64_MAX;
17971 dtrace_membar_producer();
17972 state->dts_laststatus = dtrace_gethrtime();
17973
17974 bzero(&stat, sizeof (stat));
17975
17976 lck_mtx_lock(&dtrace_lock);
17977
17978 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17979 lck_mtx_unlock(&dtrace_lock);
17980 return (ENOENT);
17981 }
17982
17983 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17984 stat.dtst_exiting = 1;
17985
17986 nerrs = state->dts_errors;
17987 dstate = &state->dts_vstate.dtvs_dynvars;
17988
17989 for (i = 0; i < NCPU; i++) {
17990 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17991
17992 stat.dtst_dyndrops += dcpu->dtdsc_drops;
17993 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17994 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17995
17996 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17997 stat.dtst_filled++;
17998
17999 nerrs += state->dts_buffer[i].dtb_errors;
18000
18001 for (j = 0; j < state->dts_nspeculations; j++) {
18002 dtrace_speculation_t *spec;
18003 dtrace_buffer_t *buf;
18004
18005 spec = &state->dts_speculations[j];
18006 buf = &spec->dtsp_buffer[i];
18007 stat.dtst_specdrops += buf->dtb_xamot_drops;
18008 }
18009 }
18010
18011 stat.dtst_specdrops_busy = state->dts_speculations_busy;
18012 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18013 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18014 stat.dtst_dblerrors = state->dts_dblerrors;
18015 stat.dtst_killed =
18016 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18017 stat.dtst_errors = nerrs;
18018
18019 lck_mtx_unlock(&dtrace_lock);
18020
18021 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
18022 return (EFAULT);
18023
18024 return (0);
18025 }
18026
18027 case DTRACEIOC_FORMAT: {
18028 dtrace_fmtdesc_t fmt;
18029 char *str;
18030 int len;
18031
18032 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
18033 return (EFAULT);
18034
18035 lck_mtx_lock(&dtrace_lock);
18036
18037 if (fmt.dtfd_format == 0 ||
18038 fmt.dtfd_format > state->dts_nformats) {
18039 lck_mtx_unlock(&dtrace_lock);
18040 return (EINVAL);
18041 }
18042
18043 /*
18044 * Format strings are allocated contiguously and they are
18045 * never freed; if a format index is less than the number
18046 * of formats, we can assert that the format map is non-NULL
18047 * and that the format for the specified index is non-NULL.
18048 */
18049 ASSERT(state->dts_formats != NULL);
18050 str = state->dts_formats[fmt.dtfd_format - 1];
18051 ASSERT(str != NULL);
18052
18053 len = strlen(str) + 1;
18054
18055 if (len > fmt.dtfd_length) {
18056 fmt.dtfd_length = len;
18057
18058 if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
18059 lck_mtx_unlock(&dtrace_lock);
18060 return (EINVAL);
18061 }
18062 } else {
18063 if (copyout(str, fmt.dtfd_string, len) != 0) {
18064 lck_mtx_unlock(&dtrace_lock);
18065 return (EINVAL);
18066 }
18067 }
18068
18069 lck_mtx_unlock(&dtrace_lock);
18070 return (0);
18071 }
18072
18073 default:
18074 break;
18075 }
18076
18077 return (ENOTTY);
18078 }
18079 #else
18080 /*ARGSUSED*/
18081 static int
18082 dtrace_ioctl_helper(u_long cmd, caddr_t arg, int *rv)
18083 {
18084 #pragma unused(rv)
18085 /*
18086 * Safe to check this outside the dof mode lock
18087 */
18088 if (dtrace_dof_mode == DTRACE_DOF_MODE_NEVER)
18089 return KERN_SUCCESS;
18090
18091 switch (cmd) {
18092 case DTRACEHIOC_ADDDOF: {
18093 dof_helper_t *dhp = NULL;
18094 size_t dof_ioctl_data_size;
18095 dof_ioctl_data_t* multi_dof;
18096 unsigned int i;
18097 int rval = 0;
18098 user_addr_t user_address = *(user_addr_t*)arg;
18099 uint64_t dof_count;
18100 int multi_dof_claimed = 0;
18101 proc_t* p = current_proc();
18102
18103 /*
18104 * Read the number of DOF sections being passed in.
18105 */
18106 if (copyin(user_address + offsetof(dof_ioctl_data_t, dofiod_count),
18107 &dof_count,
18108 sizeof(dof_count))) {
18109 dtrace_dof_error(NULL, "failed to copyin dofiod_count");
18110 return (EFAULT);
18111 }
18112
18113 /*
18114 * Range check the count.
18115 */
18116 if (dof_count == 0 || dof_count > 1024) {
18117 dtrace_dof_error(NULL, "dofiod_count is not valid");
18118 return (EINVAL);
18119 }
18120
18121 /*
18122 * Allocate a correctly sized structure and copyin the data.
18123 */
18124 dof_ioctl_data_size = DOF_IOCTL_DATA_T_SIZE(dof_count);
18125 if ((multi_dof = kmem_alloc(dof_ioctl_data_size, KM_SLEEP)) == NULL)
18126 return (ENOMEM);
18127
18128 /* NOTE! We can no longer exit this method via return */
18129 if (copyin(user_address, multi_dof, dof_ioctl_data_size) != 0) {
18130 dtrace_dof_error(NULL, "failed copyin of dof_ioctl_data_t");
18131 rval = EFAULT;
18132 goto cleanup;
18133 }
18134
18135 /*
18136 * Check that the count didn't change between the first copyin and the second.
18137 */
18138 if (multi_dof->dofiod_count != dof_count) {
18139 rval = EINVAL;
18140 goto cleanup;
18141 }
18142
18143 /*
18144 * Try to process lazily first.
18145 */
18146 rval = dtrace_lazy_dofs_add(p, multi_dof, &multi_dof_claimed);
18147
18148 /*
18149 * If rval is EACCES, we must be non-lazy.
18150 */
18151 if (rval == EACCES) {
18152 rval = 0;
18153 /*
18154 * Process each dof_helper_t
18155 */
18156 i = 0;
18157 do {
18158 dhp = &multi_dof->dofiod_helpers[i];
18159
18160 dof_hdr_t *dof = dtrace_dof_copyin(dhp->dofhp_dof, &rval);
18161
18162 if (dof != NULL) {
18163 lck_mtx_lock(&dtrace_lock);
18164
18165 /*
18166 * dtrace_helper_slurp() takes responsibility for the dof --
18167 * it may free it now or it may save it and free it later.
18168 */
18169 if ((dhp->dofhp_dof = (uint64_t)dtrace_helper_slurp(p, dof, dhp)) == -1ULL) {
18170 rval = EINVAL;
18171 }
18172
18173 lck_mtx_unlock(&dtrace_lock);
18174 }
18175 } while (++i < multi_dof->dofiod_count && rval == 0);
18176 }
18177
18178 /*
18179 * We need to copyout the multi_dof struct, because it contains
18180 * the generation (unique id) values needed to call DTRACEHIOC_REMOVE
18181 *
18182 * This could certainly be better optimized.
18183 */
18184 if (copyout(multi_dof, user_address, dof_ioctl_data_size) != 0) {
18185 dtrace_dof_error(NULL, "failed copyout of dof_ioctl_data_t");
18186 /* Don't overwrite pre-existing error code */
18187 if (rval == 0) rval = EFAULT;
18188 }
18189
18190 cleanup:
18191 /*
18192 * If we had to allocate struct memory, free it.
18193 */
18194 if (multi_dof != NULL && !multi_dof_claimed) {
18195 kmem_free(multi_dof, dof_ioctl_data_size);
18196 }
18197
18198 return rval;
18199 }
18200
18201 case DTRACEHIOC_REMOVE: {
18202 int generation = *(int*)arg;
18203 proc_t* p = current_proc();
18204
18205 /*
18206 * Try lazy first.
18207 */
18208 int rval = dtrace_lazy_dofs_remove(p, generation);
18209
18210 /*
18211 * EACCES means non-lazy
18212 */
18213 if (rval == EACCES) {
18214 lck_mtx_lock(&dtrace_lock);
18215 rval = dtrace_helper_destroygen(p, generation);
18216 lck_mtx_unlock(&dtrace_lock);
18217 }
18218
18219 return (rval);
18220 }
18221
18222 default:
18223 break;
18224 }
18225
18226 return ENOTTY;
18227 }
18228
18229 /*ARGSUSED*/
18230 static int
18231 dtrace_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
18232 {
18233 #pragma unused(md)
18234 minor_t minor = getminor(dev);
18235 dtrace_state_t *state;
18236 int rval;
18237
18238 /* Darwin puts Helper on its own major device. */
18239
18240 state = ddi_get_soft_state(dtrace_softstate, minor);
18241
18242 if (state->dts_anon) {
18243 ASSERT(dtrace_anon.dta_state == NULL);
18244 state = state->dts_anon;
18245 }
18246
18247 switch (cmd) {
18248 case DTRACEIOC_PROVIDER: {
18249 dtrace_providerdesc_t pvd;
18250 dtrace_provider_t *pvp;
18251
18252 if (copyin(arg, &pvd, sizeof (pvd)) != 0)
18253 return (EFAULT);
18254
18255 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
18256 lck_mtx_lock(&dtrace_provider_lock);
18257
18258 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
18259 if (strncmp(pvp->dtpv_name, pvd.dtvd_name, DTRACE_PROVNAMELEN) == 0)
18260 break;
18261 }
18262
18263 lck_mtx_unlock(&dtrace_provider_lock);
18264
18265 if (pvp == NULL)
18266 return (ESRCH);
18267
18268 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
18269 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
18270 if (copyout(&pvd, arg, sizeof (pvd)) != 0)
18271 return (EFAULT);
18272
18273 return (0);
18274 }
18275
18276 case DTRACEIOC_EPROBE: {
18277 dtrace_eprobedesc_t epdesc;
18278 dtrace_ecb_t *ecb;
18279 dtrace_action_t *act;
18280 void *buf;
18281 size_t size;
18282 uintptr_t dest;
18283 int nrecs;
18284
18285 if (copyin(arg, &epdesc, sizeof (epdesc)) != 0)
18286 return (EFAULT);
18287
18288 lck_mtx_lock(&dtrace_lock);
18289
18290 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
18291 lck_mtx_unlock(&dtrace_lock);
18292 return (EINVAL);
18293 }
18294
18295 if (ecb->dte_probe == NULL) {
18296 lck_mtx_unlock(&dtrace_lock);
18297 return (EINVAL);
18298 }
18299
18300 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
18301 epdesc.dtepd_uarg = ecb->dte_uarg;
18302 epdesc.dtepd_size = ecb->dte_size;
18303
18304 nrecs = epdesc.dtepd_nrecs;
18305 epdesc.dtepd_nrecs = 0;
18306 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
18307 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
18308 continue;
18309
18310 epdesc.dtepd_nrecs++;
18311 }
18312
18313 /*
18314 * Now that we have the size, we need to allocate a temporary
18315 * buffer in which to store the complete description. We need
18316 * the temporary buffer to be able to drop dtrace_lock()
18317 * across the copyout(), below.
18318 */
18319 size = sizeof (dtrace_eprobedesc_t) +
18320 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
18321
18322 buf = kmem_alloc(size, KM_SLEEP);
18323 dest = (uintptr_t)buf;
18324
18325 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
18326 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
18327
18328 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
18329 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
18330 continue;
18331
18332 if (nrecs-- == 0)
18333 break;
18334
18335 bcopy(&act->dta_rec, (void *)dest,
18336 sizeof (dtrace_recdesc_t));
18337 dest += sizeof (dtrace_recdesc_t);
18338 }
18339
18340 lck_mtx_unlock(&dtrace_lock);
18341
18342 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
18343 kmem_free(buf, size);
18344 return (EFAULT);
18345 }
18346
18347 kmem_free(buf, size);
18348 return (0);
18349 }
18350
18351 case DTRACEIOC_AGGDESC: {
18352 dtrace_aggdesc_t aggdesc;
18353 dtrace_action_t *act;
18354 dtrace_aggregation_t *agg;
18355 int nrecs;
18356 uint32_t offs;
18357 dtrace_recdesc_t *lrec;
18358 void *buf;
18359 size_t size;
18360 uintptr_t dest;
18361
18362 if (copyin(arg, &aggdesc, sizeof (aggdesc)) != 0)
18363 return (EFAULT);
18364
18365 lck_mtx_lock(&dtrace_lock);
18366
18367 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
18368 lck_mtx_unlock(&dtrace_lock);
18369 return (EINVAL);
18370 }
18371
18372 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
18373
18374 nrecs = aggdesc.dtagd_nrecs;
18375 aggdesc.dtagd_nrecs = 0;
18376
18377 offs = agg->dtag_base;
18378 lrec = &agg->dtag_action.dta_rec;
18379 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
18380
18381 for (act = agg->dtag_first; ; act = act->dta_next) {
18382 ASSERT(act->dta_intuple ||
18383 DTRACEACT_ISAGG(act->dta_kind));
18384
18385 /*
18386 * If this action has a record size of zero, it
18387 * denotes an argument to the aggregating action.
18388 * Because the presence of this record doesn't (or
18389 * shouldn't) affect the way the data is interpreted,
18390 * we don't copy it out to save user-level the
18391 * confusion of dealing with a zero-length record.
18392 */
18393 if (act->dta_rec.dtrd_size == 0) {
18394 ASSERT(agg->dtag_hasarg);
18395 continue;
18396 }
18397
18398 aggdesc.dtagd_nrecs++;
18399
18400 if (act == &agg->dtag_action)
18401 break;
18402 }
18403
18404 /*
18405 * Now that we have the size, we need to allocate a temporary
18406 * buffer in which to store the complete description. We need
18407 * the temporary buffer to be able to drop dtrace_lock()
18408 * across the copyout(), below.
18409 */
18410 size = sizeof (dtrace_aggdesc_t) +
18411 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
18412
18413 buf = kmem_alloc(size, KM_SLEEP);
18414 dest = (uintptr_t)buf;
18415
18416 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
18417 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
18418
18419 for (act = agg->dtag_first; ; act = act->dta_next) {
18420 dtrace_recdesc_t rec = act->dta_rec;
18421
18422 /*
18423 * See the comment in the above loop for why we pass
18424 * over zero-length records.
18425 */
18426 if (rec.dtrd_size == 0) {
18427 ASSERT(agg->dtag_hasarg);
18428 continue;
18429 }
18430
18431 if (nrecs-- == 0)
18432 break;
18433
18434 rec.dtrd_offset -= offs;
18435 bcopy(&rec, (void *)dest, sizeof (rec));
18436 dest += sizeof (dtrace_recdesc_t);
18437
18438 if (act == &agg->dtag_action)
18439 break;
18440 }
18441
18442 lck_mtx_unlock(&dtrace_lock);
18443
18444 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
18445 kmem_free(buf, size);
18446 return (EFAULT);
18447 }
18448
18449 kmem_free(buf, size);
18450 return (0);
18451 }
18452
18453 case DTRACEIOC_ENABLE: {
18454 dof_hdr_t *dof;
18455 dtrace_enabling_t *enab = NULL;
18456 dtrace_vstate_t *vstate;
18457 int err = 0;
18458
18459 *rv = 0;
18460
18461 /*
18462 * If a NULL argument has been passed, we take this as our
18463 * cue to reevaluate our enablings.
18464 */
18465 if (arg == NULL) {
18466 dtrace_enabling_matchall();
18467
18468 return (0);
18469 }
18470
18471 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
18472 return (rval);
18473
18474 lck_mtx_lock(&cpu_lock);
18475 lck_mtx_lock(&dtrace_lock);
18476 vstate = &state->dts_vstate;
18477
18478 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
18479 lck_mtx_unlock(&dtrace_lock);
18480 lck_mtx_unlock(&cpu_lock);
18481 dtrace_dof_destroy(dof);
18482 return (EBUSY);
18483 }
18484
18485 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
18486 lck_mtx_unlock(&dtrace_lock);
18487 lck_mtx_unlock(&cpu_lock);
18488 dtrace_dof_destroy(dof);
18489 return (EINVAL);
18490 }
18491
18492 if ((rval = dtrace_dof_options(dof, state)) != 0) {
18493 dtrace_enabling_destroy(enab);
18494 lck_mtx_unlock(&dtrace_lock);
18495 lck_mtx_unlock(&cpu_lock);
18496 dtrace_dof_destroy(dof);
18497 return (rval);
18498 }
18499
18500 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
18501 err = dtrace_enabling_retain(enab);
18502 } else {
18503 dtrace_enabling_destroy(enab);
18504 }
18505
18506 lck_mtx_unlock(&cpu_lock);
18507 lck_mtx_unlock(&dtrace_lock);
18508 dtrace_dof_destroy(dof);
18509
18510 return (err);
18511 }
18512
18513 case DTRACEIOC_REPLICATE: {
18514 dtrace_repldesc_t desc;
18515 dtrace_probedesc_t *match = &desc.dtrpd_match;
18516 dtrace_probedesc_t *create = &desc.dtrpd_create;
18517 int err;
18518
18519 if (copyin(arg, &desc, sizeof (desc)) != 0)
18520 return (EFAULT);
18521
18522 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18523 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18524 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18525 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18526
18527 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18528 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18529 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18530 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18531
18532 lck_mtx_lock(&dtrace_lock);
18533 err = dtrace_enabling_replicate(state, match, create);
18534 lck_mtx_unlock(&dtrace_lock);
18535
18536 return (err);
18537 }
18538
18539 case DTRACEIOC_PROBEMATCH:
18540 case DTRACEIOC_PROBES: {
18541 dtrace_probe_t *probe = NULL;
18542 dtrace_probedesc_t desc;
18543 dtrace_probekey_t pkey;
18544 dtrace_id_t i;
18545 int m = 0;
18546 uint32_t priv;
18547 uid_t uid;
18548 zoneid_t zoneid;
18549
18550 if (copyin(arg, &desc, sizeof (desc)) != 0)
18551 return (EFAULT);
18552
18553 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
18554 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
18555 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
18556 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
18557
18558 /*
18559 * Before we attempt to match this probe, we want to give
18560 * all providers the opportunity to provide it.
18561 */
18562 if (desc.dtpd_id == DTRACE_IDNONE) {
18563 lck_mtx_lock(&dtrace_provider_lock);
18564 dtrace_probe_provide(&desc, NULL);
18565 lck_mtx_unlock(&dtrace_provider_lock);
18566 desc.dtpd_id++;
18567 }
18568
18569 if (cmd == DTRACEIOC_PROBEMATCH) {
18570 dtrace_probekey(&desc, &pkey);
18571 pkey.dtpk_id = DTRACE_IDNONE;
18572 }
18573
18574 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
18575
18576 lck_mtx_lock(&dtrace_lock);
18577
18578 if (cmd == DTRACEIOC_PROBEMATCH) {
18579 /* Quiet compiler warning */
18580 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
18581 if ((probe = dtrace_probes[i - 1]) != NULL &&
18582 (m = dtrace_match_probe(probe, &pkey,
18583 priv, uid, zoneid)) != 0)
18584 break;
18585 }
18586
18587 if (m < 0) {
18588 lck_mtx_unlock(&dtrace_lock);
18589 return (EINVAL);
18590 }
18591
18592 } else {
18593 /* Quiet compiler warning */
18594 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
18595 if ((probe = dtrace_probes[i - 1]) != NULL &&
18596 dtrace_match_priv(probe, priv, uid, zoneid))
18597 break;
18598 }
18599 }
18600
18601 if (probe == NULL) {
18602 lck_mtx_unlock(&dtrace_lock);
18603 return (ESRCH);
18604 }
18605
18606 dtrace_probe_description(probe, &desc);
18607 lck_mtx_unlock(&dtrace_lock);
18608
18609 if (copyout(&desc, arg, sizeof (desc)) != 0)
18610 return (EFAULT);
18611
18612 return (0);
18613 }
18614
18615 case DTRACEIOC_PROBEARG: {
18616 dtrace_argdesc_t desc;
18617 dtrace_probe_t *probe;
18618 dtrace_provider_t *prov;
18619
18620 if (copyin(arg, &desc, sizeof (desc)) != 0)
18621 return (EFAULT);
18622
18623 if (desc.dtargd_id == DTRACE_IDNONE)
18624 return (EINVAL);
18625
18626 if (desc.dtargd_ndx == DTRACE_ARGNONE)
18627 return (EINVAL);
18628
18629 lck_mtx_lock(&dtrace_provider_lock);
18630 lck_mtx_lock(&mod_lock);
18631 lck_mtx_lock(&dtrace_lock);
18632
18633 /* Quiet compiler warning */
18634 if (desc.dtargd_id > (dtrace_id_t)dtrace_nprobes) {
18635 lck_mtx_unlock(&dtrace_lock);
18636 lck_mtx_unlock(&mod_lock);
18637 lck_mtx_unlock(&dtrace_provider_lock);
18638 return (EINVAL);
18639 }
18640
18641 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
18642 lck_mtx_unlock(&dtrace_lock);
18643 lck_mtx_unlock(&mod_lock);
18644 lck_mtx_unlock(&dtrace_provider_lock);
18645 return (EINVAL);
18646 }
18647
18648 lck_mtx_unlock(&dtrace_lock);
18649
18650 prov = probe->dtpr_provider;
18651
18652 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
18653 /*
18654 * There isn't any typed information for this probe.
18655 * Set the argument number to DTRACE_ARGNONE.
18656 */
18657 desc.dtargd_ndx = DTRACE_ARGNONE;
18658 } else {
18659 desc.dtargd_native[0] = '\0';
18660 desc.dtargd_xlate[0] = '\0';
18661 desc.dtargd_mapping = desc.dtargd_ndx;
18662
18663 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
18664 probe->dtpr_id, probe->dtpr_arg, &desc);
18665 }
18666
18667 lck_mtx_unlock(&mod_lock);
18668 lck_mtx_unlock(&dtrace_provider_lock);
18669
18670 if (copyout(&desc, arg, sizeof (desc)) != 0)
18671 return (EFAULT);
18672
18673 return (0);
18674 }
18675
18676 case DTRACEIOC_GO: {
18677 processorid_t cpuid;
18678 rval = dtrace_state_go(state, &cpuid);
18679
18680 if (rval != 0)
18681 return (rval);
18682
18683 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
18684 return (EFAULT);
18685
18686 return (0);
18687 }
18688
18689 case DTRACEIOC_STOP: {
18690 processorid_t cpuid;
18691
18692 lck_mtx_lock(&dtrace_lock);
18693 rval = dtrace_state_stop(state, &cpuid);
18694 lck_mtx_unlock(&dtrace_lock);
18695
18696 if (rval != 0)
18697 return (rval);
18698
18699 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
18700 return (EFAULT);
18701
18702 return (0);
18703 }
18704
18705 case DTRACEIOC_DOFGET: {
18706 dof_hdr_t hdr, *dof;
18707 uint64_t len;
18708
18709 if (copyin(arg, &hdr, sizeof (hdr)) != 0)
18710 return (EFAULT);
18711
18712 lck_mtx_lock(&dtrace_lock);
18713 dof = dtrace_dof_create(state);
18714 lck_mtx_unlock(&dtrace_lock);
18715
18716 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
18717 rval = copyout(dof, arg, len);
18718 dtrace_dof_destroy(dof);
18719
18720 return (rval == 0 ? 0 : EFAULT);
18721 }
18722
18723 case DTRACEIOC_AGGSNAP:
18724 case DTRACEIOC_BUFSNAP: {
18725 dtrace_bufdesc_t desc;
18726 caddr_t cached;
18727 dtrace_buffer_t *buf;
18728
18729 if (copyin(arg, &desc, sizeof (desc)) != 0)
18730 return (EFAULT);
18731
18732 if ((int)desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
18733 return (EINVAL);
18734
18735 lck_mtx_lock(&dtrace_lock);
18736
18737 if (cmd == DTRACEIOC_BUFSNAP) {
18738 buf = &state->dts_buffer[desc.dtbd_cpu];
18739 } else {
18740 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
18741 }
18742
18743 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
18744 size_t sz = buf->dtb_offset;
18745
18746 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
18747 lck_mtx_unlock(&dtrace_lock);
18748 return (EBUSY);
18749 }
18750
18751 /*
18752 * If this buffer has already been consumed, we're
18753 * going to indicate that there's nothing left here
18754 * to consume.
18755 */
18756 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
18757 lck_mtx_unlock(&dtrace_lock);
18758
18759 desc.dtbd_size = 0;
18760 desc.dtbd_drops = 0;
18761 desc.dtbd_errors = 0;
18762 desc.dtbd_oldest = 0;
18763 sz = sizeof (desc);
18764
18765 if (copyout(&desc, arg, sz) != 0)
18766 return (EFAULT);
18767
18768 return (0);
18769 }
18770
18771 /*
18772 * If this is a ring buffer that has wrapped, we want
18773 * to copy the whole thing out.
18774 */
18775 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
18776 dtrace_buffer_polish(buf);
18777 sz = buf->dtb_size;
18778 }
18779
18780 if (copyout(buf->dtb_tomax, (user_addr_t)desc.dtbd_data, sz) != 0) {
18781 lck_mtx_unlock(&dtrace_lock);
18782 return (EFAULT);
18783 }
18784
18785 desc.dtbd_size = sz;
18786 desc.dtbd_drops = buf->dtb_drops;
18787 desc.dtbd_errors = buf->dtb_errors;
18788 desc.dtbd_oldest = buf->dtb_xamot_offset;
18789
18790 lck_mtx_unlock(&dtrace_lock);
18791
18792 if (copyout(&desc, arg, sizeof (desc)) != 0)
18793 return (EFAULT);
18794
18795 buf->dtb_flags |= DTRACEBUF_CONSUMED;
18796
18797 return (0);
18798 }
18799
18800 if (buf->dtb_tomax == NULL) {
18801 ASSERT(buf->dtb_xamot == NULL);
18802 lck_mtx_unlock(&dtrace_lock);
18803 return (ENOENT);
18804 }
18805
18806 cached = buf->dtb_tomax;
18807 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
18808
18809 dtrace_xcall(desc.dtbd_cpu,
18810 (dtrace_xcall_t)dtrace_buffer_switch, buf);
18811
18812 state->dts_errors += buf->dtb_xamot_errors;
18813
18814 /*
18815 * If the buffers did not actually switch, then the cross call
18816 * did not take place -- presumably because the given CPU is
18817 * not in the ready set. If this is the case, we'll return
18818 * ENOENT.
18819 */
18820 if (buf->dtb_tomax == cached) {
18821 ASSERT(buf->dtb_xamot != cached);
18822 lck_mtx_unlock(&dtrace_lock);
18823 return (ENOENT);
18824 }
18825
18826 ASSERT(cached == buf->dtb_xamot);
18827
18828 /*
18829 * We have our snapshot; now copy it out.
18830 */
18831 if (copyout(buf->dtb_xamot, (user_addr_t)desc.dtbd_data,
18832 buf->dtb_xamot_offset) != 0) {
18833 lck_mtx_unlock(&dtrace_lock);
18834 return (EFAULT);
18835 }
18836
18837 desc.dtbd_size = buf->dtb_xamot_offset;
18838 desc.dtbd_drops = buf->dtb_xamot_drops;
18839 desc.dtbd_errors = buf->dtb_xamot_errors;
18840 desc.dtbd_oldest = 0;
18841
18842 lck_mtx_unlock(&dtrace_lock);
18843
18844 /*
18845 * Finally, copy out the buffer description.
18846 */
18847 if (copyout(&desc, arg, sizeof (desc)) != 0)
18848 return (EFAULT);
18849
18850 return (0);
18851 }
18852
18853 case DTRACEIOC_CONF: {
18854 dtrace_conf_t conf;
18855
18856 bzero(&conf, sizeof (conf));
18857 conf.dtc_difversion = DIF_VERSION;
18858 conf.dtc_difintregs = DIF_DIR_NREGS;
18859 conf.dtc_diftupregs = DIF_DTR_NREGS;
18860 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
18861
18862 if (copyout(&conf, arg, sizeof (conf)) != 0)
18863 return (EFAULT);
18864
18865 return (0);
18866 }
18867
18868 case DTRACEIOC_STATUS: {
18869 dtrace_status_t stat;
18870 dtrace_dstate_t *dstate;
18871 int i, j;
18872 uint64_t nerrs;
18873
18874 /*
18875 * See the comment in dtrace_state_deadman() for the reason
18876 * for setting dts_laststatus to INT64_MAX before setting
18877 * it to the correct value.
18878 */
18879 state->dts_laststatus = INT64_MAX;
18880 dtrace_membar_producer();
18881 state->dts_laststatus = dtrace_gethrtime();
18882
18883 bzero(&stat, sizeof (stat));
18884
18885 lck_mtx_lock(&dtrace_lock);
18886
18887 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
18888 lck_mtx_unlock(&dtrace_lock);
18889 return (ENOENT);
18890 }
18891
18892 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
18893 stat.dtst_exiting = 1;
18894
18895 nerrs = state->dts_errors;
18896 dstate = &state->dts_vstate.dtvs_dynvars;
18897
18898 for (i = 0; i < (int)NCPU; i++) {
18899 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
18900
18901 stat.dtst_dyndrops += dcpu->dtdsc_drops;
18902 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
18903 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
18904
18905 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
18906 stat.dtst_filled++;
18907
18908 nerrs += state->dts_buffer[i].dtb_errors;
18909
18910 for (j = 0; j < state->dts_nspeculations; j++) {
18911 dtrace_speculation_t *spec;
18912 dtrace_buffer_t *buf;
18913
18914 spec = &state->dts_speculations[j];
18915 buf = &spec->dtsp_buffer[i];
18916 stat.dtst_specdrops += buf->dtb_xamot_drops;
18917 }
18918 }
18919
18920 stat.dtst_specdrops_busy = state->dts_speculations_busy;
18921 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
18922 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
18923 stat.dtst_dblerrors = state->dts_dblerrors;
18924 stat.dtst_killed =
18925 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
18926 stat.dtst_errors = nerrs;
18927
18928 lck_mtx_unlock(&dtrace_lock);
18929
18930 if (copyout(&stat, arg, sizeof (stat)) != 0)
18931 return (EFAULT);
18932
18933 return (0);
18934 }
18935
18936 case DTRACEIOC_FORMAT: {
18937 dtrace_fmtdesc_t fmt;
18938 char *str;
18939 int len;
18940
18941 if (copyin(arg, &fmt, sizeof (fmt)) != 0)
18942 return (EFAULT);
18943
18944 lck_mtx_lock(&dtrace_lock);
18945
18946 if (fmt.dtfd_format == 0 ||
18947 fmt.dtfd_format > state->dts_nformats) {
18948 lck_mtx_unlock(&dtrace_lock);
18949 return (EINVAL);
18950 }
18951
18952 /*
18953 * Format strings are allocated contiguously and they are
18954 * never freed; if a format index is less than the number
18955 * of formats, we can assert that the format map is non-NULL
18956 * and that the format for the specified index is non-NULL.
18957 */
18958 ASSERT(state->dts_formats != NULL);
18959 str = state->dts_formats[fmt.dtfd_format - 1];
18960 ASSERT(str != NULL);
18961
18962 len = strlen(str) + 1;
18963
18964 if (len > fmt.dtfd_length) {
18965 fmt.dtfd_length = len;
18966
18967 if (copyout(&fmt, arg, sizeof (fmt)) != 0) {
18968 lck_mtx_unlock(&dtrace_lock);
18969 return (EINVAL);
18970 }
18971 } else {
18972 if (copyout(str, (user_addr_t)fmt.dtfd_string, len) != 0) {
18973 lck_mtx_unlock(&dtrace_lock);
18974 return (EINVAL);
18975 }
18976 }
18977
18978 lck_mtx_unlock(&dtrace_lock);
18979 return (0);
18980 }
18981
18982 case DTRACEIOC_MODUUIDSLIST: {
18983 size_t module_uuids_list_size;
18984 dtrace_module_uuids_list_t* uuids_list;
18985 uint64_t dtmul_count;
18986
18987 /*
18988 * Fail if the kernel symbol mode makes this operation illegal.
18989 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
18990 * for them without holding the dtrace_lock.
18991 */
18992 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
18993 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
18994 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_MODUUIDSLIST", dtrace_kernel_symbol_mode);
18995 return (EPERM);
18996 }
18997
18998 /*
18999 * Read the number of symbolsdesc structs being passed in.
19000 */
19001 if (copyin(arg + offsetof(dtrace_module_uuids_list_t, dtmul_count),
19002 &dtmul_count,
19003 sizeof(dtmul_count))) {
19004 cmn_err(CE_WARN, "failed to copyin dtmul_count");
19005 return (EFAULT);
19006 }
19007
19008 /*
19009 * Range check the count. More than 2k kexts is probably an error.
19010 */
19011 if (dtmul_count > 2048) {
19012 cmn_err(CE_WARN, "dtmul_count is not valid");
19013 return (EINVAL);
19014 }
19015
19016 /*
19017 * For all queries, we return EINVAL when the user specified
19018 * count does not match the actual number of modules we find
19019 * available.
19020 *
19021 * If the user specified count is zero, then this serves as a
19022 * simple query to count the available modules in need of symbols.
19023 */
19024
19025 rval = 0;
19026
19027 if (dtmul_count == 0)
19028 {
19029 lck_mtx_lock(&mod_lock);
19030 struct modctl* ctl = dtrace_modctl_list;
19031 while (ctl) {
19032 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
19033 if (!MOD_SYMBOLS_DONE(ctl)) {
19034 dtmul_count++;
19035 rval = EINVAL;
19036 }
19037 ctl = ctl->mod_next;
19038 }
19039 lck_mtx_unlock(&mod_lock);
19040
19041 if (copyout(&dtmul_count, arg, sizeof (dtmul_count)) != 0)
19042 return (EFAULT);
19043 else
19044 return (rval);
19045 }
19046
19047 /*
19048 * If we reach this point, then we have a request for full list data.
19049 * Allocate a correctly sized structure and copyin the data.
19050 */
19051 module_uuids_list_size = DTRACE_MODULE_UUIDS_LIST_SIZE(dtmul_count);
19052 if ((uuids_list = kmem_alloc(module_uuids_list_size, KM_SLEEP)) == NULL)
19053 return (ENOMEM);
19054
19055 /* NOTE! We can no longer exit this method via return */
19056 if (copyin(arg, uuids_list, module_uuids_list_size) != 0) {
19057 cmn_err(CE_WARN, "failed copyin of dtrace_module_uuids_list_t");
19058 rval = EFAULT;
19059 goto moduuidslist_cleanup;
19060 }
19061
19062 /*
19063 * Check that the count didn't change between the first copyin and the second.
19064 */
19065 if (uuids_list->dtmul_count != dtmul_count) {
19066 rval = EINVAL;
19067 goto moduuidslist_cleanup;
19068 }
19069
19070 /*
19071 * Build the list of UUID's that need symbols
19072 */
19073 lck_mtx_lock(&mod_lock);
19074
19075 dtmul_count = 0;
19076
19077 struct modctl* ctl = dtrace_modctl_list;
19078 while (ctl) {
19079 /*
19080 * We assume that userspace symbols will be "better" than kernel level symbols,
19081 * as userspace can search for dSYM(s) and symbol'd binaries. Even if kernel syms
19082 * are available, add user syms if the module might use them.
19083 */
19084 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
19085 if (!MOD_SYMBOLS_DONE(ctl)) {
19086 UUID* uuid = &uuids_list->dtmul_uuid[dtmul_count];
19087 if (dtmul_count++ < uuids_list->dtmul_count) {
19088 memcpy(uuid, ctl->mod_uuid, sizeof(UUID));
19089 }
19090 }
19091 ctl = ctl->mod_next;
19092 }
19093
19094 lck_mtx_unlock(&mod_lock);
19095
19096 if (uuids_list->dtmul_count < dtmul_count)
19097 rval = EINVAL;
19098
19099 uuids_list->dtmul_count = dtmul_count;
19100
19101 /*
19102 * Copyout the symbols list (or at least the count!)
19103 */
19104 if (copyout(uuids_list, arg, module_uuids_list_size) != 0) {
19105 cmn_err(CE_WARN, "failed copyout of dtrace_symbolsdesc_list_t");
19106 rval = EFAULT;
19107 }
19108
19109 moduuidslist_cleanup:
19110 /*
19111 * If we had to allocate struct memory, free it.
19112 */
19113 if (uuids_list != NULL) {
19114 kmem_free(uuids_list, module_uuids_list_size);
19115 }
19116
19117 return rval;
19118 }
19119
19120 case DTRACEIOC_PROVMODSYMS: {
19121 size_t module_symbols_size;
19122 dtrace_module_symbols_t* module_symbols;
19123 uint64_t dtmodsyms_count;
19124
19125 /*
19126 * Fail if the kernel symbol mode makes this operation illegal.
19127 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
19128 * for them without holding the dtrace_lock.
19129 */
19130 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
19131 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
19132 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_PROVMODSYMS", dtrace_kernel_symbol_mode);
19133 return (EPERM);
19134 }
19135
19136 /*
19137 * Read the number of module symbols structs being passed in.
19138 */
19139 if (copyin(arg + offsetof(dtrace_module_symbols_t, dtmodsyms_count),
19140 &dtmodsyms_count,
19141 sizeof(dtmodsyms_count))) {
19142 cmn_err(CE_WARN, "failed to copyin dtmodsyms_count");
19143 return (EFAULT);
19144 }
19145
19146 /*
19147 * Range check the count. How much data can we pass around?
19148 * FIX ME!
19149 */
19150 if (dtmodsyms_count == 0 || (dtmodsyms_count > 100 * 1024)) {
19151 cmn_err(CE_WARN, "dtmodsyms_count is not valid");
19152 return (EINVAL);
19153 }
19154
19155 /*
19156 * Allocate a correctly sized structure and copyin the data.
19157 */
19158 module_symbols_size = DTRACE_MODULE_SYMBOLS_SIZE(dtmodsyms_count);
19159 if ((module_symbols = kmem_alloc(module_symbols_size, KM_SLEEP)) == NULL)
19160 return (ENOMEM);
19161
19162 rval = 0;
19163
19164 /* NOTE! We can no longer exit this method via return */
19165 if (copyin(arg, module_symbols, module_symbols_size) != 0) {
19166 cmn_err(CE_WARN, "failed copyin of dtrace_module_symbols_t, symbol count %llu", module_symbols->dtmodsyms_count);
19167 rval = EFAULT;
19168 goto module_symbols_cleanup;
19169 }
19170
19171 /*
19172 * Check that the count didn't change between the first copyin and the second.
19173 */
19174 if (module_symbols->dtmodsyms_count != dtmodsyms_count) {
19175 rval = EINVAL;
19176 goto module_symbols_cleanup;
19177 }
19178
19179 /*
19180 * Find the modctl to add symbols to.
19181 */
19182 lck_mtx_lock(&dtrace_provider_lock);
19183 lck_mtx_lock(&mod_lock);
19184
19185 struct modctl* ctl = dtrace_modctl_list;
19186 while (ctl) {
19187 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
19188 if (MOD_HAS_UUID(ctl) && !MOD_SYMBOLS_DONE(ctl)) {
19189 if (memcmp(module_symbols->dtmodsyms_uuid, ctl->mod_uuid, sizeof(UUID)) == 0) {
19190 /* BINGO! */
19191 ctl->mod_user_symbols = module_symbols;
19192 break;
19193 }
19194 }
19195 ctl = ctl->mod_next;
19196 }
19197
19198 if (ctl) {
19199 dtrace_provider_t *prv;
19200
19201 /*
19202 * We're going to call each providers per-module provide operation
19203 * specifying only this module.
19204 */
19205 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
19206 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
19207
19208 /*
19209 * We gave every provider a chance to provide with the user syms, go ahead and clear them
19210 */
19211 ctl->mod_user_symbols = NULL; /* MUST reset this to clear HAS_USERSPACE_SYMBOLS */
19212 }
19213
19214 lck_mtx_unlock(&mod_lock);
19215 lck_mtx_unlock(&dtrace_provider_lock);
19216
19217 module_symbols_cleanup:
19218 /*
19219 * If we had to allocate struct memory, free it.
19220 */
19221 if (module_symbols != NULL) {
19222 kmem_free(module_symbols, module_symbols_size);
19223 }
19224
19225 return rval;
19226 }
19227
19228 default:
19229 break;
19230 }
19231
19232 return (ENOTTY);
19233 }
19234 #endif /* __APPLE__ */
19235
19236 #if !defined(__APPLE__)
19237 /*ARGSUSED*/
19238 static int
19239 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
19240 {
19241 dtrace_state_t *state;
19242
19243 switch (cmd) {
19244 case DDI_DETACH:
19245 break;
19246
19247 case DDI_SUSPEND:
19248 return (DDI_SUCCESS);
19249
19250 default:
19251 return (DDI_FAILURE);
19252 }
19253
19254 lck_mtx_lock(&cpu_lock);
19255 lck_mtx_lock(&dtrace_provider_lock);
19256 lck_mtx_lock(&dtrace_lock);
19257
19258 ASSERT(dtrace_opens == 0);
19259
19260 if (dtrace_helpers > 0) {
19261 lck_mtx_unlock(&dtrace_provider_lock);
19262 lck_mtx_unlock(&dtrace_lock);
19263 lck_mtx_unlock(&cpu_lock);
19264 return (DDI_FAILURE);
19265 }
19266
19267 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
19268 lck_mtx_unlock(&dtrace_provider_lock);
19269 lck_mtx_unlock(&dtrace_lock);
19270 lck_mtx_unlock(&cpu_lock);
19271 return (DDI_FAILURE);
19272 }
19273
19274 dtrace_provider = NULL;
19275
19276 if ((state = dtrace_anon_grab()) != NULL) {
19277 /*
19278 * If there were ECBs on this state, the provider should
19279 * have not been allowed to detach; assert that there is
19280 * none.
19281 */
19282 ASSERT(state->dts_necbs == 0);
19283 dtrace_state_destroy(state);
19284
19285 /*
19286 * If we're being detached with anonymous state, we need to
19287 * indicate to the kernel debugger that DTrace is now inactive.
19288 */
19289 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
19290 }
19291
19292 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
19293 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
19294 dtrace_cpu_init = NULL;
19295 dtrace_helpers_cleanup = NULL;
19296 dtrace_helpers_fork = NULL;
19297 dtrace_cpustart_init = NULL;
19298 dtrace_cpustart_fini = NULL;
19299 dtrace_debugger_init = NULL;
19300 dtrace_debugger_fini = NULL;
19301 dtrace_kreloc_init = NULL;
19302 dtrace_kreloc_fini = NULL;
19303 dtrace_modload = NULL;
19304 dtrace_modunload = NULL;
19305
19306 lck_mtx_unlock(&cpu_lock);
19307
19308 if (dtrace_helptrace_enabled) {
19309 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
19310 dtrace_helptrace_buffer = NULL;
19311 }
19312
19313 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
19314 dtrace_probes = NULL;
19315 dtrace_nprobes = 0;
19316
19317 dtrace_hash_destroy(dtrace_bymod);
19318 dtrace_hash_destroy(dtrace_byfunc);
19319 dtrace_hash_destroy(dtrace_byname);
19320 dtrace_bymod = NULL;
19321 dtrace_byfunc = NULL;
19322 dtrace_byname = NULL;
19323
19324 kmem_cache_destroy(dtrace_state_cache);
19325 vmem_destroy(dtrace_minor);
19326 vmem_destroy(dtrace_arena);
19327
19328 if (dtrace_toxrange != NULL) {
19329 kmem_free(dtrace_toxrange,
19330 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
19331 dtrace_toxrange = NULL;
19332 dtrace_toxranges = 0;
19333 dtrace_toxranges_max = 0;
19334 }
19335
19336 ddi_remove_minor_node(dtrace_devi, NULL);
19337 dtrace_devi = NULL;
19338
19339 ddi_soft_state_fini(&dtrace_softstate);
19340
19341 ASSERT(dtrace_vtime_references == 0);
19342 ASSERT(dtrace_opens == 0);
19343 ASSERT(dtrace_retained == NULL);
19344
19345 lck_mtx_unlock(&dtrace_lock);
19346 lck_mtx_unlock(&dtrace_provider_lock);
19347
19348 /*
19349 * We don't destroy the task queue until after we have dropped our
19350 * locks (taskq_destroy() may block on running tasks). To prevent
19351 * attempting to do work after we have effectively detached but before
19352 * the task queue has been destroyed, all tasks dispatched via the
19353 * task queue must check that DTrace is still attached before
19354 * performing any operation.
19355 */
19356 taskq_destroy(dtrace_taskq);
19357 dtrace_taskq = NULL;
19358
19359 return (DDI_SUCCESS);
19360 }
19361
19362 /*ARGSUSED*/
19363 static int
19364 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
19365 {
19366 int error;
19367
19368 switch (infocmd) {
19369 case DDI_INFO_DEVT2DEVINFO:
19370 *result = (void *)dtrace_devi;
19371 error = DDI_SUCCESS;
19372 break;
19373 case DDI_INFO_DEVT2INSTANCE:
19374 *result = (void *)0;
19375 error = DDI_SUCCESS;
19376 break;
19377 default:
19378 error = DDI_FAILURE;
19379 }
19380 return (error);
19381 }
19382
19383 static struct cb_ops dtrace_cb_ops = {
19384 dtrace_open, /* open */
19385 dtrace_close, /* close */
19386 nulldev, /* strategy */
19387 nulldev, /* print */
19388 nodev, /* dump */
19389 nodev, /* read */
19390 nodev, /* write */
19391 dtrace_ioctl, /* ioctl */
19392 nodev, /* devmap */
19393 nodev, /* mmap */
19394 nodev, /* segmap */
19395 nochpoll, /* poll */
19396 ddi_prop_op, /* cb_prop_op */
19397 0, /* streamtab */
19398 D_NEW | D_MP /* Driver compatibility flag */
19399 };
19400
19401 static struct dev_ops dtrace_ops = {
19402 DEVO_REV, /* devo_rev */
19403 0, /* refcnt */
19404 dtrace_info, /* get_dev_info */
19405 nulldev, /* identify */
19406 nulldev, /* probe */
19407 dtrace_attach, /* attach */
19408 dtrace_detach, /* detach */
19409 nodev, /* reset */
19410 &dtrace_cb_ops, /* driver operations */
19411 NULL, /* bus operations */
19412 nodev /* dev power */
19413 };
19414
19415 static struct modldrv modldrv = {
19416 &mod_driverops, /* module type (this is a pseudo driver) */
19417 "Dynamic Tracing", /* name of module */
19418 &dtrace_ops, /* driver ops */
19419 };
19420
19421 static struct modlinkage modlinkage = {
19422 MODREV_1,
19423 (void *)&modldrv,
19424 NULL
19425 };
19426
19427 int
19428 _init(void)
19429 {
19430 return (mod_install(&modlinkage));
19431 }
19432
19433 int
19434 _info(struct modinfo *modinfop)
19435 {
19436 return (mod_info(&modlinkage, modinfop));
19437 }
19438
19439 int
19440 _fini(void)
19441 {
19442 return (mod_remove(&modlinkage));
19443 }
19444 #else /* Darwin BSD driver model. */
19445
19446 d_open_t _dtrace_open, helper_open;
19447 d_close_t _dtrace_close, helper_close;
19448 d_ioctl_t _dtrace_ioctl, helper_ioctl;
19449
19450 int
19451 _dtrace_open(dev_t dev, int flags, int devtype, struct proc *p)
19452 {
19453 #pragma unused(p)
19454 dev_t locdev = dev;
19455
19456 return dtrace_open( &locdev, flags, devtype, CRED());
19457 }
19458
19459 int
19460 helper_open(dev_t dev, int flags, int devtype, struct proc *p)
19461 {
19462 #pragma unused(dev,flags,devtype,p)
19463 return 0;
19464 }
19465
19466 int
19467 _dtrace_close(dev_t dev, int flags, int devtype, struct proc *p)
19468 {
19469 #pragma unused(p)
19470 return dtrace_close( dev, flags, devtype, CRED());
19471 }
19472
19473 int
19474 helper_close(dev_t dev, int flags, int devtype, struct proc *p)
19475 {
19476 #pragma unused(dev,flags,devtype,p)
19477 return 0;
19478 }
19479
19480 int
19481 _dtrace_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
19482 {
19483 #pragma unused(p)
19484 int err, rv = 0;
19485 user_addr_t uaddrp;
19486
19487 if (proc_is64bit(p))
19488 uaddrp = *(user_addr_t *)data;
19489 else
19490 uaddrp = (user_addr_t) *(uint32_t *)data;
19491
19492 err = dtrace_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
19493
19494 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
19495 if (err != 0) {
19496 ASSERT( (err & 0xfffff000) == 0 );
19497 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
19498 } else if (rv != 0) {
19499 ASSERT( (rv & 0xfff00000) == 0 );
19500 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
19501 } else
19502 return 0;
19503 }
19504
19505 int
19506 helper_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
19507 {
19508 #pragma unused(dev,fflag,p)
19509 int err, rv = 0;
19510
19511 err = dtrace_ioctl_helper(cmd, data, &rv);
19512 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
19513 if (err != 0) {
19514 ASSERT( (err & 0xfffff000) == 0 );
19515 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
19516 } else if (rv != 0) {
19517 ASSERT( (rv & 0xfff00000) == 0 );
19518 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
19519 } else
19520 return 0;
19521 }
19522
19523 #define HELPER_MAJOR -24 /* let the kernel pick the device number */
19524
19525 /*
19526 * A struct describing which functions will get invoked for certain
19527 * actions.
19528 */
19529 static struct cdevsw helper_cdevsw =
19530 {
19531 helper_open, /* open */
19532 helper_close, /* close */
19533 eno_rdwrt, /* read */
19534 eno_rdwrt, /* write */
19535 helper_ioctl, /* ioctl */
19536 (stop_fcn_t *)nulldev, /* stop */
19537 (reset_fcn_t *)nulldev, /* reset */
19538 NULL, /* tty's */
19539 eno_select, /* select */
19540 eno_mmap, /* mmap */
19541 eno_strat, /* strategy */
19542 eno_getc, /* getc */
19543 eno_putc, /* putc */
19544 0 /* type */
19545 };
19546
19547 static int helper_majdevno = 0;
19548
19549 static int gDTraceInited = 0;
19550
19551 void
19552 helper_init( void )
19553 {
19554 /*
19555 * Once the "helper" is initialized, it can take ioctl calls that use locks
19556 * and zones initialized in dtrace_init. Make certain dtrace_init was called
19557 * before us.
19558 */
19559
19560 if (!gDTraceInited) {
19561 panic("helper_init before dtrace_init\n");
19562 }
19563
19564 if (0 >= helper_majdevno)
19565 {
19566 helper_majdevno = cdevsw_add(HELPER_MAJOR, &helper_cdevsw);
19567
19568 if (helper_majdevno < 0) {
19569 printf("helper_init: failed to allocate a major number!\n");
19570 return;
19571 }
19572
19573 if (NULL == devfs_make_node( makedev(helper_majdevno, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
19574 DTRACEMNR_HELPER, 0 )) {
19575 printf("dtrace_init: failed to devfs_make_node for helper!\n");
19576 return;
19577 }
19578 } else
19579 panic("helper_init: called twice!\n");
19580 }
19581
19582 #undef HELPER_MAJOR
19583
19584 /*
19585 * Called with DEVFS_LOCK held, so vmem_alloc's underlying blist structures are protected.
19586 */
19587 static int
19588 dtrace_clone_func(dev_t dev, int action)
19589 {
19590 #pragma unused(dev)
19591
19592 if (action == DEVFS_CLONE_ALLOC) {
19593 if (NULL == dtrace_minor) /* Arena not created yet!?! */
19594 return 0;
19595 else {
19596 /*
19597 * Propose a minor number, namely the next number that vmem_alloc() will return.
19598 * Immediately put it back in play by calling vmem_free(). FIXME.
19599 */
19600 int ret = (int)(uintptr_t)vmem_alloc(dtrace_minor, 1, VM_BESTFIT | VM_SLEEP);
19601
19602 vmem_free(dtrace_minor, (void *)(uintptr_t)ret, 1);
19603
19604 return ret;
19605 }
19606 }
19607 else if (action == DEVFS_CLONE_FREE) {
19608 return 0;
19609 }
19610 else return -1;
19611 }
19612
19613 #define DTRACE_MAJOR -24 /* let the kernel pick the device number */
19614
19615 static struct cdevsw dtrace_cdevsw =
19616 {
19617 _dtrace_open, /* open */
19618 _dtrace_close, /* close */
19619 eno_rdwrt, /* read */
19620 eno_rdwrt, /* write */
19621 _dtrace_ioctl, /* ioctl */
19622 (stop_fcn_t *)nulldev, /* stop */
19623 (reset_fcn_t *)nulldev, /* reset */
19624 NULL, /* tty's */
19625 eno_select, /* select */
19626 eno_mmap, /* mmap */
19627 eno_strat, /* strategy */
19628 eno_getc, /* getc */
19629 eno_putc, /* putc */
19630 0 /* type */
19631 };
19632
19633 lck_attr_t* dtrace_lck_attr;
19634 lck_grp_attr_t* dtrace_lck_grp_attr;
19635 lck_grp_t* dtrace_lck_grp;
19636
19637 static int gMajDevNo;
19638
19639 void
19640 dtrace_init( void )
19641 {
19642 if (0 == gDTraceInited) {
19643 int i, ncpu = NCPU;
19644
19645 gMajDevNo = cdevsw_add(DTRACE_MAJOR, &dtrace_cdevsw);
19646
19647 if (gMajDevNo < 0) {
19648 printf("dtrace_init: failed to allocate a major number!\n");
19649 gDTraceInited = 0;
19650 return;
19651 }
19652
19653 if (NULL == devfs_make_node_clone( makedev(gMajDevNo, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
19654 dtrace_clone_func, DTRACEMNR_DTRACE, 0 )) {
19655 printf("dtrace_init: failed to devfs_make_node_clone for dtrace!\n");
19656 gDTraceInited = 0;
19657 return;
19658 }
19659
19660 #if defined(DTRACE_MEMORY_ZONES)
19661 /*
19662 * Initialize the dtrace kalloc-emulation zones.
19663 */
19664 dtrace_alloc_init();
19665 #endif /* DTRACE_MEMORY_ZONES */
19666
19667 /*
19668 * Allocate the dtrace_probe_t zone
19669 */
19670 dtrace_probe_t_zone = zinit(sizeof(dtrace_probe_t),
19671 1024 * sizeof(dtrace_probe_t),
19672 sizeof(dtrace_probe_t),
19673 "dtrace.dtrace_probe_t");
19674
19675 /*
19676 * Create the dtrace lock group and attrs.
19677 */
19678 dtrace_lck_attr = lck_attr_alloc_init();
19679 dtrace_lck_grp_attr= lck_grp_attr_alloc_init();
19680 dtrace_lck_grp = lck_grp_alloc_init("dtrace", dtrace_lck_grp_attr);
19681
19682 /*
19683 * We have to initialize all locks explicitly
19684 */
19685 lck_mtx_init(&dtrace_lock, dtrace_lck_grp, dtrace_lck_attr);
19686 lck_mtx_init(&dtrace_provider_lock, dtrace_lck_grp, dtrace_lck_attr);
19687 lck_mtx_init(&dtrace_meta_lock, dtrace_lck_grp, dtrace_lck_attr);
19688 #if DEBUG
19689 lck_mtx_init(&dtrace_errlock, dtrace_lck_grp, dtrace_lck_attr);
19690 #endif
19691 lck_rw_init(&dtrace_dof_mode_lock, dtrace_lck_grp, dtrace_lck_attr);
19692
19693 /*
19694 * The cpu_core structure consists of per-CPU state available in any context.
19695 * On some architectures, this may mean that the page(s) containing the
19696 * NCPU-sized array of cpu_core structures must be locked in the TLB -- it
19697 * is up to the platform to assure that this is performed properly. Note that
19698 * the structure is sized to avoid false sharing.
19699 */
19700 lck_mtx_init(&cpu_lock, dtrace_lck_grp, dtrace_lck_attr);
19701 lck_mtx_init(&mod_lock, dtrace_lck_grp, dtrace_lck_attr);
19702
19703 dtrace_modctl_list = NULL;
19704
19705 cpu_core = (cpu_core_t *)kmem_zalloc( ncpu * sizeof(cpu_core_t), KM_SLEEP );
19706 for (i = 0; i < ncpu; ++i) {
19707 lck_mtx_init(&cpu_core[i].cpuc_pid_lock, dtrace_lck_grp, dtrace_lck_attr);
19708 }
19709
19710 cpu_list = (dtrace_cpu_t *)kmem_zalloc( ncpu * sizeof(dtrace_cpu_t), KM_SLEEP );
19711 for (i = 0; i < ncpu; ++i) {
19712 cpu_list[i].cpu_id = (processorid_t)i;
19713 cpu_list[i].cpu_next = &(cpu_list[(i+1) % ncpu]);
19714 lck_rw_init(&cpu_list[i].cpu_ft_lock, dtrace_lck_grp, dtrace_lck_attr);
19715 }
19716
19717 lck_mtx_lock(&cpu_lock);
19718 for (i = 0; i < ncpu; ++i)
19719 /* FIXME: track CPU configuration a la CHUD Processor Pref Pane. */
19720 dtrace_cpu_setup_initial( (processorid_t)i ); /* In lieu of register_cpu_setup_func() callback */
19721 lck_mtx_unlock(&cpu_lock);
19722
19723 (void)dtrace_abs_to_nano(0LL); /* Force once only call to clock_timebase_info (which can take a lock) */
19724
19725 dtrace_isa_init();
19726
19727 /*
19728 * See dtrace_impl.h for a description of dof modes.
19729 * The default is lazy dof.
19730 *
19731 * FIXME: Warn if state is LAZY_OFF? It won't break anything, but
19732 * makes no sense...
19733 */
19734 if (!PE_parse_boot_argn("dtrace_dof_mode", &dtrace_dof_mode, sizeof (dtrace_dof_mode))) {
19735 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
19736 }
19737
19738 /*
19739 * Sanity check of dof mode value.
19740 */
19741 switch (dtrace_dof_mode) {
19742 case DTRACE_DOF_MODE_NEVER:
19743 case DTRACE_DOF_MODE_LAZY_ON:
19744 /* valid modes, but nothing else we need to do */
19745 break;
19746
19747 case DTRACE_DOF_MODE_LAZY_OFF:
19748 case DTRACE_DOF_MODE_NON_LAZY:
19749 /* Cannot wait for a dtrace_open to init fasttrap */
19750 fasttrap_init();
19751 break;
19752
19753 default:
19754 /* Invalid, clamp to non lazy */
19755 dtrace_dof_mode = DTRACE_DOF_MODE_NON_LAZY;
19756 fasttrap_init();
19757 break;
19758 }
19759
19760 /*
19761 * See dtrace_impl.h for a description of kernel symbol modes.
19762 * The default is to wait for symbols from userspace (lazy symbols).
19763 */
19764 if (!PE_parse_boot_argn("dtrace_kernel_symbol_mode", &dtrace_kernel_symbol_mode, sizeof (dtrace_kernel_symbol_mode))) {
19765 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
19766 }
19767
19768 gDTraceInited = 1;
19769
19770 } else
19771 panic("dtrace_init: called twice!\n");
19772 }
19773
19774 void
19775 dtrace_postinit(void)
19776 {
19777 /*
19778 * Called from bsd_init after all provider's *_init() routines have been
19779 * run. That way, anonymous DOF enabled under dtrace_attach() is safe
19780 * to go.
19781 */
19782 dtrace_attach( (dev_info_t *)(uintptr_t)makedev(gMajDevNo, 0), 0 ); /* Punning a dev_t to a dev_info_t* */
19783
19784 /*
19785 * Add the mach_kernel to the module list for lazy processing
19786 */
19787 struct kmod_info fake_kernel_kmod;
19788 memset(&fake_kernel_kmod, 0, sizeof(fake_kernel_kmod));
19789
19790 strlcpy(fake_kernel_kmod.name, "mach_kernel", sizeof(fake_kernel_kmod.name));
19791 fake_kernel_kmod.id = 1;
19792 fake_kernel_kmod.address = g_kernel_kmod_info.address;
19793 fake_kernel_kmod.size = g_kernel_kmod_info.size;
19794
19795 if (dtrace_module_loaded(&fake_kernel_kmod, 0) != 0) {
19796 printf("dtrace_postinit: Could not register mach_kernel modctl\n");
19797 }
19798
19799 (void)OSKextRegisterKextsWithDTrace();
19800 }
19801 #undef DTRACE_MAJOR
19802
19803 /*
19804 * Routines used to register interest in cpu's being added to or removed
19805 * from the system.
19806 */
19807 void
19808 register_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
19809 {
19810 #pragma unused(ignore1,ignore2)
19811 }
19812
19813 void
19814 unregister_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
19815 {
19816 #pragma unused(ignore1,ignore2)
19817 }
19818 #endif /* __APPLE__ */