]> git.saurik.com Git - apple/xnu.git/blob - bsd/dev/dtrace/dtrace.c
dd02ad5026d4b620eec8e57ce1ad157ce37152ca
[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 * Portions Copyright (c) 2011, Joyent, Inc. All rights reserved.
24 * Portions Copyright (c) 2012 by Delphix. All rights reserved.
25 */
26
27 /*
28 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
29 * Use is subject to license terms.
30 */
31
32 /* #pragma ident "@(#)dtrace.c 1.65 08/07/02 SMI" */
33
34 /*
35 * DTrace - Dynamic Tracing for Solaris
36 *
37 * This is the implementation of the Solaris Dynamic Tracing framework
38 * (DTrace). The user-visible interface to DTrace is described at length in
39 * the "Solaris Dynamic Tracing Guide". The interfaces between the libdtrace
40 * library, the in-kernel DTrace framework, and the DTrace providers are
41 * described in the block comments in the <sys/dtrace.h> header file. The
42 * internal architecture of DTrace is described in the block comments in the
43 * <sys/dtrace_impl.h> header file. The comments contained within the DTrace
44 * implementation very much assume mastery of all of these sources; if one has
45 * an unanswered question about the implementation, one should consult them
46 * first.
47 *
48 * The functions here are ordered roughly as follows:
49 *
50 * - Probe context functions
51 * - Probe hashing functions
52 * - Non-probe context utility functions
53 * - Matching functions
54 * - Provider-to-Framework API functions
55 * - Probe management functions
56 * - DIF object functions
57 * - Format functions
58 * - Predicate functions
59 * - ECB functions
60 * - Buffer functions
61 * - Enabling functions
62 * - DOF functions
63 * - Anonymous enabling functions
64 * - Consumer state functions
65 * - Helper functions
66 * - Hook functions
67 * - Driver cookbook functions
68 *
69 * Each group of functions begins with a block comment labelled the "DTrace
70 * [Group] Functions", allowing one to find each block by searching forward
71 * on capital-f functions.
72 */
73 #include <sys/errno.h>
74 #include <sys/types.h>
75 #include <sys/stat.h>
76 #include <sys/conf.h>
77 #include <sys/systm.h>
78 #include <sys/dtrace_impl.h>
79 #include <sys/param.h>
80 #include <sys/proc_internal.h>
81 #include <sys/ioctl.h>
82 #include <sys/fcntl.h>
83 #include <miscfs/devfs/devfs.h>
84 #include <sys/malloc.h>
85 #include <sys/kernel_types.h>
86 #include <sys/proc_internal.h>
87 #include <sys/uio_internal.h>
88 #include <sys/kauth.h>
89 #include <vm/pmap.h>
90 #include <sys/user.h>
91 #include <mach/exception_types.h>
92 #include <sys/signalvar.h>
93 #include <mach/task.h>
94 #include <kern/zalloc.h>
95 #include <kern/ast.h>
96 #include <kern/task.h>
97 #include <netinet/in.h>
98
99 #include <kern/cpu_data.h>
100 extern uint32_t pmap_find_phys(void *, uint64_t);
101 extern boolean_t pmap_valid_page(uint32_t);
102 extern void OSKextRegisterKextsWithDTrace(void);
103 extern kmod_info_t g_kernel_kmod_info;
104
105 /* Solaris proc_t is the struct. Darwin's proc_t is a pointer to it. */
106 #define proc_t struct proc /* Steer clear of the Darwin typedef for proc_t */
107
108 #define t_predcache t_dtrace_predcache /* Cosmetic. Helps readability of thread.h */
109
110 extern void dtrace_suspend(void);
111 extern void dtrace_resume(void);
112 extern void dtrace_init(void);
113 extern void helper_init(void);
114 extern void fasttrap_init(void);
115 extern void dtrace_lazy_dofs_duplicate(proc_t *, proc_t *);
116 extern void dtrace_lazy_dofs_destroy(proc_t *);
117 extern void dtrace_postinit(void);
118
119 #include "../../../osfmk/chud/chud_dtrace.h"
120
121 extern kern_return_t chudxnu_dtrace_callback
122 (uint64_t selector, uint64_t *args, uint32_t count);
123
124 /* Import this function to retrieve the physical memory. */
125 extern int kernel_sysctlbyname(const char *name, void *oldp,
126 size_t *oldlenp, void *newp, size_t newlen);
127
128 /*
129 * DTrace Tunable Variables
130 *
131 * The following variables may be dynamically tuned by using sysctl(8), the
132 * variables being stored in the kern.dtrace namespace. For example:
133 * sysctl kern.dtrace.dof_maxsize = 1048575 # 1M
134 *
135 * In general, the only variables that one should be tuning this way are those
136 * that affect system-wide DTrace behavior, and for which the default behavior
137 * is undesirable. Most of these variables are tunable on a per-consumer
138 * basis using DTrace options, and need not be tuned on a system-wide basis.
139 * When tuning these variables, avoid pathological values; while some attempt
140 * is made to verify the integrity of these variables, they are not considered
141 * part of the supported interface to DTrace, and they are therefore not
142 * checked comprehensively.
143 */
144 uint64_t dtrace_buffer_memory_maxsize = 0; /* initialized in dtrace_init */
145 uint64_t dtrace_buffer_memory_inuse = 0;
146 int dtrace_destructive_disallow = 0;
147 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
148 size_t dtrace_difo_maxsize = (256 * 1024);
149 dtrace_optval_t dtrace_dof_maxsize = (384 * 1024);
150 size_t dtrace_global_maxsize = (16 * 1024);
151 size_t dtrace_actions_max = (16 * 1024);
152 size_t dtrace_retain_max = 1024;
153 dtrace_optval_t dtrace_helper_actions_max = 32;
154 dtrace_optval_t dtrace_helper_providers_max = 64;
155 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
156 size_t dtrace_strsize_default = 256;
157 dtrace_optval_t dtrace_cleanrate_default = 990099000; /* 1.1 hz */
158 dtrace_optval_t dtrace_cleanrate_min = 20000000; /* 50 hz */
159 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
160 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
161 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
162 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
163 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
164 dtrace_optval_t dtrace_nspec_default = 1;
165 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
166 dtrace_optval_t dtrace_stackframes_default = 20;
167 dtrace_optval_t dtrace_ustackframes_default = 20;
168 dtrace_optval_t dtrace_jstackframes_default = 50;
169 dtrace_optval_t dtrace_jstackstrsize_default = 512;
170 int dtrace_msgdsize_max = 128;
171 hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
172 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
173 int dtrace_devdepth_max = 32;
174 int dtrace_err_verbose;
175 int dtrace_provide_private_probes = 0;
176 hrtime_t dtrace_deadman_interval = NANOSEC;
177 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
178 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
179
180 /*
181 * DTrace External Variables
182 *
183 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
184 * available to DTrace consumers via the backtick (`) syntax. One of these,
185 * dtrace_zero, is made deliberately so: it is provided as a source of
186 * well-known, zero-filled memory. While this variable is not documented,
187 * it is used by some translators as an implementation detail.
188 */
189 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
190 unsigned int dtrace_max_cpus = 0; /* number of enabled cpus */
191 /*
192 * DTrace Internal Variables
193 */
194 static dev_info_t *dtrace_devi; /* device info */
195 static vmem_t *dtrace_arena; /* probe ID arena */
196 static vmem_t *dtrace_minor; /* minor number arena */
197 static taskq_t *dtrace_taskq; /* task queue */
198 static dtrace_probe_t **dtrace_probes; /* array of all probes */
199 static int dtrace_nprobes; /* number of probes */
200 static dtrace_provider_t *dtrace_provider; /* provider list */
201 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
202 static int dtrace_opens; /* number of opens */
203 static int dtrace_helpers; /* number of helpers */
204 static void *dtrace_softstate; /* softstate pointer */
205 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
206 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
207 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
208 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
209 static int dtrace_toxranges; /* number of toxic ranges */
210 static int dtrace_toxranges_max; /* size of toxic range array */
211 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
212 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
213 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
214 static kthread_t *dtrace_panicked; /* panicking thread */
215 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
216 static dtrace_genid_t dtrace_probegen; /* current probe generation */
217 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
218 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
219 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
220 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
221
222 static int dtrace_dof_mode; /* See dtrace_impl.h for a description of Darwin's dof modes. */
223
224 /*
225 * This does't quite fit as an internal variable, as it must be accessed in
226 * fbt_provide and sdt_provide. Its clearly not a dtrace tunable variable either...
227 */
228 int dtrace_kernel_symbol_mode; /* See dtrace_impl.h for a description of Darwin's kernel symbol modes. */
229
230
231 /*
232 * To save memory, some common memory allocations are given a
233 * unique zone. For example, dtrace_probe_t is 72 bytes in size,
234 * which means it would fall into the kalloc.128 bucket. With
235 * 20k elements allocated, the space saved is substantial.
236 */
237
238 struct zone *dtrace_probe_t_zone;
239
240 static int dtrace_module_unloaded(struct kmod_info *kmod);
241
242 /*
243 * DTrace Locking
244 * DTrace is protected by three (relatively coarse-grained) locks:
245 *
246 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
247 * including enabling state, probes, ECBs, consumer state, helper state,
248 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
249 * probe context is lock-free -- synchronization is handled via the
250 * dtrace_sync() cross call mechanism.
251 *
252 * (2) dtrace_provider_lock is required when manipulating provider state, or
253 * when provider state must be held constant.
254 *
255 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
256 * when meta provider state must be held constant.
257 *
258 * The lock ordering between these three locks is dtrace_meta_lock before
259 * dtrace_provider_lock before dtrace_lock. (In particular, there are
260 * several places where dtrace_provider_lock is held by the framework as it
261 * calls into the providers -- which then call back into the framework,
262 * grabbing dtrace_lock.)
263 *
264 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
265 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
266 * role as a coarse-grained lock; it is acquired before both of these locks.
267 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
268 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
269 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
270 * acquired _between_ dtrace_provider_lock and dtrace_lock.
271 */
272
273
274 /*
275 * APPLE NOTE:
276 *
277 * For porting purposes, all kmutex_t vars have been changed
278 * to lck_mtx_t, which require explicit initialization.
279 *
280 * kmutex_t becomes lck_mtx_t
281 * mutex_enter() becomes lck_mtx_lock()
282 * mutex_exit() becomes lck_mtx_unlock()
283 *
284 * Lock asserts are changed like this:
285 *
286 * ASSERT(MUTEX_HELD(&cpu_lock));
287 * becomes:
288 * lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
289 *
290 */
291 static lck_mtx_t dtrace_lock; /* probe state lock */
292 static lck_mtx_t dtrace_provider_lock; /* provider state lock */
293 static lck_mtx_t dtrace_meta_lock; /* meta-provider state lock */
294 static lck_rw_t dtrace_dof_mode_lock; /* dof mode lock */
295
296 /*
297 * DTrace Provider Variables
298 *
299 * These are the variables relating to DTrace as a provider (that is, the
300 * provider of the BEGIN, END, and ERROR probes).
301 */
302 static dtrace_pattr_t dtrace_provider_attr = {
303 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
304 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
305 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
306 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
307 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
308 };
309
310 static void
311 dtrace_nullop(void)
312 {}
313
314 static int
315 dtrace_enable_nullop(void)
316 {
317 return (0);
318 }
319
320 static dtrace_pops_t dtrace_provider_ops = {
321 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
322 (void (*)(void *, struct modctl *))dtrace_nullop,
323 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
324 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
325 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
326 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
327 NULL,
328 NULL,
329 NULL,
330 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
331 };
332
333 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
334 static dtrace_id_t dtrace_probeid_end; /* special END probe */
335 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
336
337 /*
338 * DTrace Helper Tracing Variables
339 */
340 uint32_t dtrace_helptrace_next = 0;
341 uint32_t dtrace_helptrace_nlocals;
342 char *dtrace_helptrace_buffer;
343 size_t dtrace_helptrace_bufsize = 512 * 1024;
344
345 #if DEBUG
346 int dtrace_helptrace_enabled = 1;
347 #else
348 int dtrace_helptrace_enabled = 0;
349 #endif
350
351
352 /*
353 * DTrace Error Hashing
354 *
355 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
356 * table. This is very useful for checking coverage of tests that are
357 * expected to induce DIF or DOF processing errors, and may be useful for
358 * debugging problems in the DIF code generator or in DOF generation . The
359 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
360 */
361 #if DEBUG
362 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
363 static const char *dtrace_errlast;
364 static kthread_t *dtrace_errthread;
365 static lck_mtx_t dtrace_errlock;
366 #endif
367
368 /*
369 * DTrace Macros and Constants
370 *
371 * These are various macros that are useful in various spots in the
372 * implementation, along with a few random constants that have no meaning
373 * outside of the implementation. There is no real structure to this cpp
374 * mishmash -- but is there ever?
375 */
376 #define DTRACE_HASHSTR(hash, probe) \
377 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
378
379 #define DTRACE_HASHNEXT(hash, probe) \
380 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
381
382 #define DTRACE_HASHPREV(hash, probe) \
383 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
384
385 #define DTRACE_HASHEQ(hash, lhs, rhs) \
386 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
387 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
388
389 #define DTRACE_AGGHASHSIZE_SLEW 17
390
391 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
392
393 /*
394 * The key for a thread-local variable consists of the lower 61 bits of the
395 * current_thread(), plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
396 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
397 * equal to a variable identifier. This is necessary (but not sufficient) to
398 * assure that global associative arrays never collide with thread-local
399 * variables. To guarantee that they cannot collide, we must also define the
400 * order for keying dynamic variables. That order is:
401 *
402 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
403 *
404 * Because the variable-key and the tls-key are in orthogonal spaces, there is
405 * no way for a global variable key signature to match a thread-local key
406 * signature.
407 */
408 #if defined (__x86_64__)
409 /* FIXME: two function calls!! */
410 #define DTRACE_TLS_THRKEY(where) { \
411 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
412 uint64_t thr = (uintptr_t)current_thread(); \
413 ASSERT(intr < (1 << 3)); \
414 (where) = ((thr + DIF_VARIABLE_MAX) & \
415 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
416 }
417 #else
418 #error Unknown architecture
419 #endif
420
421 #define DT_BSWAP_8(x) ((x) & 0xff)
422 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
423 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
424 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
425
426 #define DT_MASK_LO 0x00000000FFFFFFFFULL
427
428 #define DTRACE_STORE(type, tomax, offset, what) \
429 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
430
431
432 #define DTRACE_ALIGNCHECK(addr, size, flags) \
433 if (addr & (MIN(size,4) - 1)) { \
434 *flags |= CPU_DTRACE_BADALIGN; \
435 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
436 return (0); \
437 }
438
439 /*
440 * Test whether a range of memory starting at testaddr of size testsz falls
441 * within the range of memory described by addr, sz. We take care to avoid
442 * problems with overflow and underflow of the unsigned quantities, and
443 * disallow all negative sizes. Ranges of size 0 are allowed.
444 */
445 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
446 ((testaddr) - (baseaddr) < (basesz) && \
447 (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
448 (testaddr) + (testsz) >= (testaddr))
449
450 /*
451 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
452 * alloc_sz on the righthand side of the comparison in order to avoid overflow
453 * or underflow in the comparison with it. This is simpler than the INRANGE
454 * check above, because we know that the dtms_scratch_ptr is valid in the
455 * range. Allocations of size zero are allowed.
456 */
457 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
458 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
459 (mstate)->dtms_scratch_ptr >= (alloc_sz))
460
461 #define RECOVER_LABEL(bits) dtraceLoadRecover##bits:
462
463 #if defined (__x86_64__)
464 #define DTRACE_LOADFUNC(bits) \
465 /*CSTYLED*/ \
466 uint##bits##_t dtrace_load##bits(uintptr_t addr); \
467 \
468 uint##bits##_t \
469 dtrace_load##bits(uintptr_t addr) \
470 { \
471 size_t size = bits / NBBY; \
472 /*CSTYLED*/ \
473 uint##bits##_t rval = 0; \
474 int i; \
475 volatile uint16_t *flags = (volatile uint16_t *) \
476 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
477 \
478 DTRACE_ALIGNCHECK(addr, size, flags); \
479 \
480 for (i = 0; i < dtrace_toxranges; i++) { \
481 if (addr >= dtrace_toxrange[i].dtt_limit) \
482 continue; \
483 \
484 if (addr + size <= dtrace_toxrange[i].dtt_base) \
485 continue; \
486 \
487 /* \
488 * This address falls within a toxic region; return 0. \
489 */ \
490 *flags |= CPU_DTRACE_BADADDR; \
491 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
492 return (0); \
493 } \
494 \
495 { \
496 volatile vm_offset_t recover = (vm_offset_t)&&dtraceLoadRecover##bits; \
497 *flags |= CPU_DTRACE_NOFAULT; \
498 recover = dtrace_set_thread_recover(current_thread(), recover); \
499 /*CSTYLED*/ \
500 /* \
501 * PR6394061 - avoid device memory that is unpredictably \
502 * mapped and unmapped \
503 */ \
504 if (pmap_valid_page(pmap_find_phys(kernel_pmap, addr))) \
505 rval = *((volatile uint##bits##_t *)addr); \
506 RECOVER_LABEL(bits); \
507 (void)dtrace_set_thread_recover(current_thread(), recover); \
508 *flags &= ~CPU_DTRACE_NOFAULT; \
509 } \
510 \
511 return (rval); \
512 }
513 #else /* all other architectures */
514 #error Unknown Architecture
515 #endif
516
517 #ifdef __LP64__
518 #define dtrace_loadptr dtrace_load64
519 #else
520 #define dtrace_loadptr dtrace_load32
521 #endif
522
523 #define DTRACE_DYNHASH_FREE 0
524 #define DTRACE_DYNHASH_SINK 1
525 #define DTRACE_DYNHASH_VALID 2
526
527 #define DTRACE_MATCH_FAIL -1
528 #define DTRACE_MATCH_NEXT 0
529 #define DTRACE_MATCH_DONE 1
530 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
531 #define DTRACE_STATE_ALIGN 64
532
533 #define DTRACE_FLAGS2FLT(flags) \
534 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
535 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
536 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
537 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
538 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
539 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
540 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
541 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
542 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
543 DTRACEFLT_UNKNOWN)
544
545 #define DTRACEACT_ISSTRING(act) \
546 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
547 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
548
549
550 static size_t dtrace_strlen(const char *, size_t);
551 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
552 static void dtrace_enabling_provide(dtrace_provider_t *);
553 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
554 static void dtrace_enabling_matchall(void);
555 static dtrace_state_t *dtrace_anon_grab(void);
556 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
557 dtrace_state_t *, uint64_t, uint64_t);
558 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
559 static void dtrace_buffer_drop(dtrace_buffer_t *);
560 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
561 dtrace_state_t *, dtrace_mstate_t *);
562 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
563 dtrace_optval_t);
564 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
565 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
566
567
568 /*
569 * DTrace sysctl handlers
570 *
571 * These declarations and functions are used for a deeper DTrace configuration.
572 * Most of them are not per-consumer basis and may impact the other DTrace
573 * consumers. Correctness may not be supported for all the variables, so you
574 * should be careful about what values you are using.
575 */
576
577 SYSCTL_DECL(_kern_dtrace);
578 SYSCTL_NODE(_kern, OID_AUTO, dtrace, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "dtrace");
579
580 static int
581 sysctl_dtrace_err_verbose SYSCTL_HANDLER_ARGS
582 {
583 #pragma unused(oidp, arg2)
584 int changed, error;
585 int value = *(int *) arg1;
586
587 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
588 if (error || !changed)
589 return (error);
590
591 if (value != 0 && value != 1)
592 return (ERANGE);
593
594 lck_mtx_lock(&dtrace_lock);
595 dtrace_err_verbose = value;
596 lck_mtx_unlock(&dtrace_lock);
597
598 return (0);
599 }
600
601 /*
602 * kern.dtrace.err_verbose
603 *
604 * Set DTrace verbosity when an error occured (0 = disabled, 1 = enabld).
605 * Errors are reported when a DIFO or a DOF has been rejected by the kernel.
606 */
607 SYSCTL_PROC(_kern_dtrace, OID_AUTO, err_verbose,
608 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
609 &dtrace_err_verbose, 0,
610 sysctl_dtrace_err_verbose, "I", "dtrace error verbose");
611
612 static int
613 sysctl_dtrace_buffer_memory_maxsize SYSCTL_HANDLER_ARGS
614 {
615 #pragma unused(oidp, arg2, req)
616 int changed, error;
617 uint64_t value = *(uint64_t *) arg1;
618
619 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
620 if (error || !changed)
621 return (error);
622
623 if (value <= dtrace_buffer_memory_inuse)
624 return (ERANGE);
625
626 lck_mtx_lock(&dtrace_lock);
627 dtrace_buffer_memory_maxsize = value;
628 lck_mtx_unlock(&dtrace_lock);
629
630 return (0);
631 }
632
633 /*
634 * kern.dtrace.buffer_memory_maxsize
635 *
636 * Set DTrace maximal size in bytes used by all the consumers' state buffers. By default
637 * the limit is PHYS_MEM / 3 for *all* consumers. Attempting to set a null, a negative value
638 * or a value <= to dtrace_buffer_memory_inuse will result in a failure.
639 */
640 SYSCTL_PROC(_kern_dtrace, OID_AUTO, buffer_memory_maxsize,
641 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
642 &dtrace_buffer_memory_maxsize, 0,
643 sysctl_dtrace_buffer_memory_maxsize, "Q", "dtrace state buffer memory maxsize");
644
645 /*
646 * kern.dtrace.buffer_memory_inuse
647 *
648 * Current state buffer memory used, in bytes, by all the DTrace consumers.
649 * This value is read-only.
650 */
651 SYSCTL_QUAD(_kern_dtrace, OID_AUTO, buffer_memory_inuse, CTLFLAG_RD | CTLFLAG_LOCKED,
652 &dtrace_buffer_memory_inuse, "dtrace state buffer memory in-use");
653
654 static int
655 sysctl_dtrace_difo_maxsize SYSCTL_HANDLER_ARGS
656 {
657 #pragma unused(oidp, arg2, req)
658 int changed, error;
659 size_t value = *(size_t*) arg1;
660
661 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
662 if (error || !changed)
663 return (error);
664
665 if (value <= 0)
666 return (ERANGE);
667
668 lck_mtx_lock(&dtrace_lock);
669 dtrace_difo_maxsize = value;
670 lck_mtx_unlock(&dtrace_lock);
671
672 return (0);
673 }
674
675 /*
676 * kern.dtrace.difo_maxsize
677 *
678 * Set the DIFO max size in bytes, check the definition of dtrace_difo_maxsize
679 * to get the default value. Attempting to set a null or negative size will
680 * result in a failure.
681 */
682 SYSCTL_PROC(_kern_dtrace, OID_AUTO, difo_maxsize,
683 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
684 &dtrace_difo_maxsize, 0,
685 sysctl_dtrace_difo_maxsize, "Q", "dtrace difo maxsize");
686
687 static int
688 sysctl_dtrace_dof_maxsize SYSCTL_HANDLER_ARGS
689 {
690 #pragma unused(oidp, arg2, req)
691 int changed, error;
692 dtrace_optval_t value = *(dtrace_optval_t *) arg1;
693
694 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
695 if (error || !changed)
696 return (error);
697
698 if (value <= 0)
699 return (ERANGE);
700
701 lck_mtx_lock(&dtrace_lock);
702 dtrace_dof_maxsize = value;
703 lck_mtx_unlock(&dtrace_lock);
704
705 return (0);
706 }
707
708 /*
709 * kern.dtrace.dof_maxsize
710 *
711 * Set the DOF max size in bytes, check the definition of dtrace_dof_maxsize to
712 * get the default value. Attempting to set a null or negative size will result
713 * in a failure.
714 */
715 SYSCTL_PROC(_kern_dtrace, OID_AUTO, dof_maxsize,
716 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
717 &dtrace_dof_maxsize, 0,
718 sysctl_dtrace_dof_maxsize, "Q", "dtrace dof maxsize");
719
720 static int
721 sysctl_dtrace_global_maxsize SYSCTL_HANDLER_ARGS
722 {
723 #pragma unused(oidp, arg2, req)
724 int changed, error;
725 dtrace_optval_t value = *(dtrace_optval_t*) arg1;
726
727 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
728 if (error || !changed)
729 return (error);
730
731 if (value <= 0)
732 return (ERANGE);
733
734 lck_mtx_lock(&dtrace_lock);
735 dtrace_global_maxsize = value;
736 lck_mtx_unlock(&dtrace_lock);
737
738 return (0);
739 }
740
741 /*
742 * kern.dtrace.global_maxsize
743 *
744 * Set the global variable max size in bytes, check the definition of
745 * dtrace_global_maxsize to get the default value. Attempting to set a null or
746 * negative size will result in a failure.
747 */
748 SYSCTL_PROC(_kern_dtrace, OID_AUTO, global_maxsize,
749 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
750 &dtrace_global_maxsize, 0,
751 sysctl_dtrace_global_maxsize, "Q", "dtrace global maxsize");
752
753 static int
754 sysctl_dtrace_provide_private_probes SYSCTL_HANDLER_ARGS
755 {
756 #pragma unused(oidp, arg2)
757 int error;
758 int value = *(int *) arg1;
759
760 error = sysctl_io_number(req, value, sizeof(value), &value, NULL);
761 if (error)
762 return (error);
763
764 if (value != 0 && value != 1)
765 return (ERANGE);
766
767 lck_mtx_lock(&dtrace_lock);
768 dtrace_provide_private_probes = value;
769 lck_mtx_unlock(&dtrace_lock);
770
771 return (0);
772 }
773
774 /*
775 * kern.dtrace.provide_private_probes
776 *
777 * Set whether the providers must provide the private probes. This is
778 * mainly used by the FBT provider to request probes for the private/static
779 * symbols.
780 */
781 SYSCTL_PROC(_kern_dtrace, OID_AUTO, provide_private_probes,
782 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
783 &dtrace_provide_private_probes, 0,
784 sysctl_dtrace_provide_private_probes, "I", "provider must provide the private probes");
785
786 /*
787 * DTrace Probe Context Functions
788 *
789 * These functions are called from probe context. Because probe context is
790 * any context in which C may be called, arbitrarily locks may be held,
791 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
792 * As a result, functions called from probe context may only call other DTrace
793 * support functions -- they may not interact at all with the system at large.
794 * (Note that the ASSERT macro is made probe-context safe by redefining it in
795 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
796 * loads are to be performed from probe context, they _must_ be in terms of
797 * the safe dtrace_load*() variants.
798 *
799 * Some functions in this block are not actually called from probe context;
800 * for these functions, there will be a comment above the function reading
801 * "Note: not called from probe context."
802 */
803
804 int
805 dtrace_assfail(const char *a, const char *f, int l)
806 {
807 panic("dtrace: assertion failed: %s, file: %s, line: %d", a, f, l);
808
809 /*
810 * We just need something here that even the most clever compiler
811 * cannot optimize away.
812 */
813 return (a[(uintptr_t)f]);
814 }
815
816 /*
817 * Atomically increment a specified error counter from probe context.
818 */
819 static void
820 dtrace_error(uint32_t *counter)
821 {
822 /*
823 * Most counters stored to in probe context are per-CPU counters.
824 * However, there are some error conditions that are sufficiently
825 * arcane that they don't merit per-CPU storage. If these counters
826 * are incremented concurrently on different CPUs, scalability will be
827 * adversely affected -- but we don't expect them to be white-hot in a
828 * correctly constructed enabling...
829 */
830 uint32_t oval, nval;
831
832 do {
833 oval = *counter;
834
835 if ((nval = oval + 1) == 0) {
836 /*
837 * If the counter would wrap, set it to 1 -- assuring
838 * that the counter is never zero when we have seen
839 * errors. (The counter must be 32-bits because we
840 * aren't guaranteed a 64-bit compare&swap operation.)
841 * To save this code both the infamy of being fingered
842 * by a priggish news story and the indignity of being
843 * the target of a neo-puritan witch trial, we're
844 * carefully avoiding any colorful description of the
845 * likelihood of this condition -- but suffice it to
846 * say that it is only slightly more likely than the
847 * overflow of predicate cache IDs, as discussed in
848 * dtrace_predicate_create().
849 */
850 nval = 1;
851 }
852 } while (dtrace_cas32(counter, oval, nval) != oval);
853 }
854
855 /*
856 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
857 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
858 */
859 DTRACE_LOADFUNC(8)
860 DTRACE_LOADFUNC(16)
861 DTRACE_LOADFUNC(32)
862 DTRACE_LOADFUNC(64)
863
864 static int
865 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
866 {
867 if (dest < mstate->dtms_scratch_base)
868 return (0);
869
870 if (dest + size < dest)
871 return (0);
872
873 if (dest + size > mstate->dtms_scratch_ptr)
874 return (0);
875
876 return (1);
877 }
878
879 static int
880 dtrace_canstore_statvar(uint64_t addr, size_t sz,
881 dtrace_statvar_t **svars, int nsvars)
882 {
883 int i;
884
885 for (i = 0; i < nsvars; i++) {
886 dtrace_statvar_t *svar = svars[i];
887
888 if (svar == NULL || svar->dtsv_size == 0)
889 continue;
890
891 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
892 return (1);
893 }
894
895 return (0);
896 }
897
898 /*
899 * Check to see if the address is within a memory region to which a store may
900 * be issued. This includes the DTrace scratch areas, and any DTrace variable
901 * region. The caller of dtrace_canstore() is responsible for performing any
902 * alignment checks that are needed before stores are actually executed.
903 */
904 static int
905 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
906 dtrace_vstate_t *vstate)
907 {
908 /*
909 * First, check to see if the address is in scratch space...
910 */
911 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
912 mstate->dtms_scratch_size))
913 return (1);
914
915 /*
916 * Now check to see if it's a dynamic variable. This check will pick
917 * up both thread-local variables and any global dynamically-allocated
918 * variables.
919 */
920 if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
921 vstate->dtvs_dynvars.dtds_size)) {
922 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
923 uintptr_t base = (uintptr_t)dstate->dtds_base +
924 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
925 uintptr_t chunkoffs;
926
927 /*
928 * Before we assume that we can store here, we need to make
929 * sure that it isn't in our metadata -- storing to our
930 * dynamic variable metadata would corrupt our state. For
931 * the range to not include any dynamic variable metadata,
932 * it must:
933 *
934 * (1) Start above the hash table that is at the base of
935 * the dynamic variable space
936 *
937 * (2) Have a starting chunk offset that is beyond the
938 * dtrace_dynvar_t that is at the base of every chunk
939 *
940 * (3) Not span a chunk boundary
941 *
942 */
943 if (addr < base)
944 return (0);
945
946 chunkoffs = (addr - base) % dstate->dtds_chunksize;
947
948 if (chunkoffs < sizeof (dtrace_dynvar_t))
949 return (0);
950
951 if (chunkoffs + sz > dstate->dtds_chunksize)
952 return (0);
953
954 return (1);
955 }
956
957 /*
958 * Finally, check the static local and global variables. These checks
959 * take the longest, so we perform them last.
960 */
961 if (dtrace_canstore_statvar(addr, sz,
962 vstate->dtvs_locals, vstate->dtvs_nlocals))
963 return (1);
964
965 if (dtrace_canstore_statvar(addr, sz,
966 vstate->dtvs_globals, vstate->dtvs_nglobals))
967 return (1);
968
969 return (0);
970 }
971
972
973 /*
974 * Convenience routine to check to see if the address is within a memory
975 * region in which a load may be issued given the user's privilege level;
976 * if not, it sets the appropriate error flags and loads 'addr' into the
977 * illegal value slot.
978 *
979 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
980 * appropriate memory access protection.
981 */
982 static int
983 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
984 dtrace_vstate_t *vstate)
985 {
986 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
987
988 /*
989 * If we hold the privilege to read from kernel memory, then
990 * everything is readable.
991 */
992 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
993 return (1);
994
995 /*
996 * You can obviously read that which you can store.
997 */
998 if (dtrace_canstore(addr, sz, mstate, vstate))
999 return (1);
1000
1001 /*
1002 * We're allowed to read from our own string table.
1003 */
1004 if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
1005 mstate->dtms_difo->dtdo_strlen))
1006 return (1);
1007
1008 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1009 *illval = addr;
1010 return (0);
1011 }
1012
1013 /*
1014 * Convenience routine to check to see if a given string is within a memory
1015 * region in which a load may be issued given the user's privilege level;
1016 * this exists so that we don't need to issue unnecessary dtrace_strlen()
1017 * calls in the event that the user has all privileges.
1018 */
1019 static int
1020 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1021 dtrace_vstate_t *vstate)
1022 {
1023 size_t strsz;
1024
1025 /*
1026 * If we hold the privilege to read from kernel memory, then
1027 * everything is readable.
1028 */
1029 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
1030 return (1);
1031
1032 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
1033 if (dtrace_canload(addr, strsz, mstate, vstate))
1034 return (1);
1035
1036 return (0);
1037 }
1038
1039 /*
1040 * Convenience routine to check to see if a given variable is within a memory
1041 * region in which a load may be issued given the user's privilege level.
1042 */
1043 static int
1044 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
1045 dtrace_vstate_t *vstate)
1046 {
1047 size_t sz;
1048 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1049
1050 /*
1051 * If we hold the privilege to read from kernel memory, then
1052 * everything is readable.
1053 */
1054 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
1055 return (1);
1056
1057 if (type->dtdt_kind == DIF_TYPE_STRING)
1058 sz = dtrace_strlen(src,
1059 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
1060 else
1061 sz = type->dtdt_size;
1062
1063 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
1064 }
1065
1066 /*
1067 * Compare two strings using safe loads.
1068 */
1069 static int
1070 dtrace_strncmp(char *s1, char *s2, size_t limit)
1071 {
1072 uint8_t c1, c2;
1073 volatile uint16_t *flags;
1074
1075 if (s1 == s2 || limit == 0)
1076 return (0);
1077
1078 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1079
1080 do {
1081 if (s1 == NULL) {
1082 c1 = '\0';
1083 } else {
1084 c1 = dtrace_load8((uintptr_t)s1++);
1085 }
1086
1087 if (s2 == NULL) {
1088 c2 = '\0';
1089 } else {
1090 c2 = dtrace_load8((uintptr_t)s2++);
1091 }
1092
1093 if (c1 != c2)
1094 return (c1 - c2);
1095 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1096
1097 return (0);
1098 }
1099
1100 /*
1101 * Compute strlen(s) for a string using safe memory accesses. The additional
1102 * len parameter is used to specify a maximum length to ensure completion.
1103 */
1104 static size_t
1105 dtrace_strlen(const char *s, size_t lim)
1106 {
1107 uint_t len;
1108
1109 for (len = 0; len != lim; len++) {
1110 if (dtrace_load8((uintptr_t)s++) == '\0')
1111 break;
1112 }
1113
1114 return (len);
1115 }
1116
1117 /*
1118 * Check if an address falls within a toxic region.
1119 */
1120 static int
1121 dtrace_istoxic(uintptr_t kaddr, size_t size)
1122 {
1123 uintptr_t taddr, tsize;
1124 int i;
1125
1126 for (i = 0; i < dtrace_toxranges; i++) {
1127 taddr = dtrace_toxrange[i].dtt_base;
1128 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1129
1130 if (kaddr - taddr < tsize) {
1131 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1132 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1133 return (1);
1134 }
1135
1136 if (taddr - kaddr < size) {
1137 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1138 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1139 return (1);
1140 }
1141 }
1142
1143 return (0);
1144 }
1145
1146 /*
1147 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1148 * memory specified by the DIF program. The dst is assumed to be safe memory
1149 * that we can store to directly because it is managed by DTrace. As with
1150 * standard bcopy, overlapping copies are handled properly.
1151 */
1152 static void
1153 dtrace_bcopy(const void *src, void *dst, size_t len)
1154 {
1155 if (len != 0) {
1156 uint8_t *s1 = dst;
1157 const uint8_t *s2 = src;
1158
1159 if (s1 <= s2) {
1160 do {
1161 *s1++ = dtrace_load8((uintptr_t)s2++);
1162 } while (--len != 0);
1163 } else {
1164 s2 += len;
1165 s1 += len;
1166
1167 do {
1168 *--s1 = dtrace_load8((uintptr_t)--s2);
1169 } while (--len != 0);
1170 }
1171 }
1172 }
1173
1174 /*
1175 * Copy src to dst using safe memory accesses, up to either the specified
1176 * length, or the point that a nul byte is encountered. The src is assumed to
1177 * be unsafe memory specified by the DIF program. The dst is assumed to be
1178 * safe memory that we can store to directly because it is managed by DTrace.
1179 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1180 */
1181 static void
1182 dtrace_strcpy(const void *src, void *dst, size_t len)
1183 {
1184 if (len != 0) {
1185 uint8_t *s1 = dst, c;
1186 const uint8_t *s2 = src;
1187
1188 do {
1189 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1190 } while (--len != 0 && c != '\0');
1191 }
1192 }
1193
1194 /*
1195 * Copy src to dst, deriving the size and type from the specified (BYREF)
1196 * variable type. The src is assumed to be unsafe memory specified by the DIF
1197 * program. The dst is assumed to be DTrace variable memory that is of the
1198 * specified type; we assume that we can store to directly.
1199 */
1200 static void
1201 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1202 {
1203 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1204
1205 if (type->dtdt_kind == DIF_TYPE_STRING) {
1206 dtrace_strcpy(src, dst, type->dtdt_size);
1207 } else {
1208 dtrace_bcopy(src, dst, type->dtdt_size);
1209 }
1210 }
1211
1212 /*
1213 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1214 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1215 * safe memory that we can access directly because it is managed by DTrace.
1216 */
1217 static int
1218 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1219 {
1220 volatile uint16_t *flags;
1221
1222 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1223
1224 if (s1 == s2)
1225 return (0);
1226
1227 if (s1 == NULL || s2 == NULL)
1228 return (1);
1229
1230 if (s1 != s2 && len != 0) {
1231 const uint8_t *ps1 = s1;
1232 const uint8_t *ps2 = s2;
1233
1234 do {
1235 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1236 return (1);
1237 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1238 }
1239 return (0);
1240 }
1241
1242 /*
1243 * Zero the specified region using a simple byte-by-byte loop. Note that this
1244 * is for safe DTrace-managed memory only.
1245 */
1246 static void
1247 dtrace_bzero(void *dst, size_t len)
1248 {
1249 uchar_t *cp;
1250
1251 for (cp = dst; len != 0; len--)
1252 *cp++ = 0;
1253 }
1254
1255 static void
1256 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1257 {
1258 uint64_t result[2];
1259
1260 result[0] = addend1[0] + addend2[0];
1261 result[1] = addend1[1] + addend2[1] +
1262 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1263
1264 sum[0] = result[0];
1265 sum[1] = result[1];
1266 }
1267
1268 /*
1269 * Shift the 128-bit value in a by b. If b is positive, shift left.
1270 * If b is negative, shift right.
1271 */
1272 static void
1273 dtrace_shift_128(uint64_t *a, int b)
1274 {
1275 uint64_t mask;
1276
1277 if (b == 0)
1278 return;
1279
1280 if (b < 0) {
1281 b = -b;
1282 if (b >= 64) {
1283 a[0] = a[1] >> (b - 64);
1284 a[1] = 0;
1285 } else {
1286 a[0] >>= b;
1287 mask = 1LL << (64 - b);
1288 mask -= 1;
1289 a[0] |= ((a[1] & mask) << (64 - b));
1290 a[1] >>= b;
1291 }
1292 } else {
1293 if (b >= 64) {
1294 a[1] = a[0] << (b - 64);
1295 a[0] = 0;
1296 } else {
1297 a[1] <<= b;
1298 mask = a[0] >> (64 - b);
1299 a[1] |= mask;
1300 a[0] <<= b;
1301 }
1302 }
1303 }
1304
1305 /*
1306 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1307 * use native multiplication on those, and then re-combine into the
1308 * resulting 128-bit value.
1309 *
1310 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1311 * hi1 * hi2 << 64 +
1312 * hi1 * lo2 << 32 +
1313 * hi2 * lo1 << 32 +
1314 * lo1 * lo2
1315 */
1316 static void
1317 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1318 {
1319 uint64_t hi1, hi2, lo1, lo2;
1320 uint64_t tmp[2];
1321
1322 hi1 = factor1 >> 32;
1323 hi2 = factor2 >> 32;
1324
1325 lo1 = factor1 & DT_MASK_LO;
1326 lo2 = factor2 & DT_MASK_LO;
1327
1328 product[0] = lo1 * lo2;
1329 product[1] = hi1 * hi2;
1330
1331 tmp[0] = hi1 * lo2;
1332 tmp[1] = 0;
1333 dtrace_shift_128(tmp, 32);
1334 dtrace_add_128(product, tmp, product);
1335
1336 tmp[0] = hi2 * lo1;
1337 tmp[1] = 0;
1338 dtrace_shift_128(tmp, 32);
1339 dtrace_add_128(product, tmp, product);
1340 }
1341
1342 /*
1343 * This privilege check should be used by actions and subroutines to
1344 * verify that the user credentials of the process that enabled the
1345 * invoking ECB match the target credentials
1346 */
1347 static int
1348 dtrace_priv_proc_common_user(dtrace_state_t *state)
1349 {
1350 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1351
1352 /*
1353 * We should always have a non-NULL state cred here, since if cred
1354 * is null (anonymous tracing), we fast-path bypass this routine.
1355 */
1356 ASSERT(s_cr != NULL);
1357
1358 if ((cr = dtrace_CRED()) != NULL &&
1359 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_uid &&
1360 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_ruid &&
1361 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_suid &&
1362 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_gid &&
1363 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_rgid &&
1364 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_sgid)
1365 return (1);
1366
1367 return (0);
1368 }
1369
1370 /*
1371 * This privilege check should be used by actions and subroutines to
1372 * verify that the zone of the process that enabled the invoking ECB
1373 * matches the target credentials
1374 */
1375 static int
1376 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1377 {
1378 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1379 #pragma unused(cr, s_cr, state) /* __APPLE__ */
1380
1381 /*
1382 * We should always have a non-NULL state cred here, since if cred
1383 * is null (anonymous tracing), we fast-path bypass this routine.
1384 */
1385 ASSERT(s_cr != NULL);
1386
1387 return 1; /* APPLE NOTE: Darwin doesn't do zones. */
1388 }
1389
1390 /*
1391 * This privilege check should be used by actions and subroutines to
1392 * verify that the process has not setuid or changed credentials.
1393 */
1394 static int
1395 dtrace_priv_proc_common_nocd(void)
1396 {
1397 return 1; /* Darwin omits "No Core Dump" flag. */
1398 }
1399
1400 static int
1401 dtrace_priv_proc_destructive(dtrace_state_t *state)
1402 {
1403 int action = state->dts_cred.dcr_action;
1404
1405 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1406 goto bad;
1407
1408 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1409 goto bad;
1410
1411 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1412 dtrace_priv_proc_common_zone(state) == 0)
1413 goto bad;
1414
1415 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1416 dtrace_priv_proc_common_user(state) == 0)
1417 goto bad;
1418
1419 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1420 dtrace_priv_proc_common_nocd() == 0)
1421 goto bad;
1422
1423 return (1);
1424
1425 bad:
1426 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1427
1428 return (0);
1429 }
1430
1431 static int
1432 dtrace_priv_proc_control(dtrace_state_t *state)
1433 {
1434 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1435 goto bad;
1436
1437 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1438 goto bad;
1439
1440 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1441 return (1);
1442
1443 if (dtrace_priv_proc_common_zone(state) &&
1444 dtrace_priv_proc_common_user(state) &&
1445 dtrace_priv_proc_common_nocd())
1446 return (1);
1447
1448 bad:
1449 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1450
1451 return (0);
1452 }
1453
1454 static int
1455 dtrace_priv_proc(dtrace_state_t *state)
1456 {
1457 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1458 goto bad;
1459
1460 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1461 goto bad;
1462
1463 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1464 return (1);
1465
1466 bad:
1467 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1468
1469 return (0);
1470 }
1471
1472 /*
1473 * The P_LNOATTACH check is an Apple specific check.
1474 * We need a version of dtrace_priv_proc() that omits
1475 * that check for PID and EXECNAME accesses
1476 */
1477 static int
1478 dtrace_priv_proc_relaxed(dtrace_state_t *state)
1479 {
1480
1481 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1482 return (1);
1483
1484 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1485
1486 return (0);
1487 }
1488
1489 static int
1490 dtrace_priv_kernel(dtrace_state_t *state)
1491 {
1492 if (dtrace_is_restricted())
1493 goto bad;
1494
1495 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1496 return (1);
1497
1498 bad:
1499 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1500
1501 return (0);
1502 }
1503
1504 static int
1505 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1506 {
1507 if (dtrace_is_restricted())
1508 goto bad;
1509
1510 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1511 return (1);
1512
1513 bad:
1514 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1515
1516 return (0);
1517 }
1518
1519 /*
1520 * Note: not called from probe context. This function is called
1521 * asynchronously (and at a regular interval) from outside of probe context to
1522 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1523 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1524 */
1525 static void
1526 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1527 {
1528 dtrace_dynvar_t *dirty;
1529 dtrace_dstate_percpu_t *dcpu;
1530 int i, work = 0;
1531
1532 for (i = 0; i < (int)NCPU; i++) {
1533 dcpu = &dstate->dtds_percpu[i];
1534
1535 ASSERT(dcpu->dtdsc_rinsing == NULL);
1536
1537 /*
1538 * If the dirty list is NULL, there is no dirty work to do.
1539 */
1540 if (dcpu->dtdsc_dirty == NULL)
1541 continue;
1542
1543 /*
1544 * If the clean list is non-NULL, then we're not going to do
1545 * any work for this CPU -- it means that there has not been
1546 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1547 * since the last time we cleaned house.
1548 */
1549 if (dcpu->dtdsc_clean != NULL)
1550 continue;
1551
1552 work = 1;
1553
1554 /*
1555 * Atomically move the dirty list aside.
1556 */
1557 do {
1558 dirty = dcpu->dtdsc_dirty;
1559
1560 /*
1561 * Before we zap the dirty list, set the rinsing list.
1562 * (This allows for a potential assertion in
1563 * dtrace_dynvar(): if a free dynamic variable appears
1564 * on a hash chain, either the dirty list or the
1565 * rinsing list for some CPU must be non-NULL.)
1566 */
1567 dcpu->dtdsc_rinsing = dirty;
1568 dtrace_membar_producer();
1569 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1570 dirty, NULL) != dirty);
1571 }
1572
1573 if (!work) {
1574 /*
1575 * We have no work to do; we can simply return.
1576 */
1577 return;
1578 }
1579
1580 dtrace_sync();
1581
1582 for (i = 0; i < (int)NCPU; i++) {
1583 dcpu = &dstate->dtds_percpu[i];
1584
1585 if (dcpu->dtdsc_rinsing == NULL)
1586 continue;
1587
1588 /*
1589 * We are now guaranteed that no hash chain contains a pointer
1590 * into this dirty list; we can make it clean.
1591 */
1592 ASSERT(dcpu->dtdsc_clean == NULL);
1593 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1594 dcpu->dtdsc_rinsing = NULL;
1595 }
1596
1597 /*
1598 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1599 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1600 * This prevents a race whereby a CPU incorrectly decides that
1601 * the state should be something other than DTRACE_DSTATE_CLEAN
1602 * after dtrace_dynvar_clean() has completed.
1603 */
1604 dtrace_sync();
1605
1606 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1607 }
1608
1609 /*
1610 * Depending on the value of the op parameter, this function looks-up,
1611 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1612 * allocation is requested, this function will return a pointer to a
1613 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1614 * variable can be allocated. If NULL is returned, the appropriate counter
1615 * will be incremented.
1616 */
1617 static dtrace_dynvar_t *
1618 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1619 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1620 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1621 {
1622 uint64_t hashval = DTRACE_DYNHASH_VALID;
1623 dtrace_dynhash_t *hash = dstate->dtds_hash;
1624 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1625 processorid_t me = CPU->cpu_id, cpu = me;
1626 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1627 size_t bucket, ksize;
1628 size_t chunksize = dstate->dtds_chunksize;
1629 uintptr_t kdata, lock, nstate;
1630 uint_t i;
1631
1632 ASSERT(nkeys != 0);
1633
1634 /*
1635 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1636 * algorithm. For the by-value portions, we perform the algorithm in
1637 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1638 * bit, and seems to have only a minute effect on distribution. For
1639 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1640 * over each referenced byte. It's painful to do this, but it's much
1641 * better than pathological hash distribution. The efficacy of the
1642 * hashing algorithm (and a comparison with other algorithms) may be
1643 * found by running the ::dtrace_dynstat MDB dcmd.
1644 */
1645 for (i = 0; i < nkeys; i++) {
1646 if (key[i].dttk_size == 0) {
1647 uint64_t val = key[i].dttk_value;
1648
1649 hashval += (val >> 48) & 0xffff;
1650 hashval += (hashval << 10);
1651 hashval ^= (hashval >> 6);
1652
1653 hashval += (val >> 32) & 0xffff;
1654 hashval += (hashval << 10);
1655 hashval ^= (hashval >> 6);
1656
1657 hashval += (val >> 16) & 0xffff;
1658 hashval += (hashval << 10);
1659 hashval ^= (hashval >> 6);
1660
1661 hashval += val & 0xffff;
1662 hashval += (hashval << 10);
1663 hashval ^= (hashval >> 6);
1664 } else {
1665 /*
1666 * This is incredibly painful, but it beats the hell
1667 * out of the alternative.
1668 */
1669 uint64_t j, size = key[i].dttk_size;
1670 uintptr_t base = (uintptr_t)key[i].dttk_value;
1671
1672 if (!dtrace_canload(base, size, mstate, vstate))
1673 break;
1674
1675 for (j = 0; j < size; j++) {
1676 hashval += dtrace_load8(base + j);
1677 hashval += (hashval << 10);
1678 hashval ^= (hashval >> 6);
1679 }
1680 }
1681 }
1682
1683 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1684 return (NULL);
1685
1686 hashval += (hashval << 3);
1687 hashval ^= (hashval >> 11);
1688 hashval += (hashval << 15);
1689
1690 /*
1691 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1692 * comes out to be one of our two sentinel hash values. If this
1693 * actually happens, we set the hashval to be a value known to be a
1694 * non-sentinel value.
1695 */
1696 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1697 hashval = DTRACE_DYNHASH_VALID;
1698
1699 /*
1700 * Yes, it's painful to do a divide here. If the cycle count becomes
1701 * important here, tricks can be pulled to reduce it. (However, it's
1702 * critical that hash collisions be kept to an absolute minimum;
1703 * they're much more painful than a divide.) It's better to have a
1704 * solution that generates few collisions and still keeps things
1705 * relatively simple.
1706 */
1707 bucket = hashval % dstate->dtds_hashsize;
1708
1709 if (op == DTRACE_DYNVAR_DEALLOC) {
1710 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1711
1712 for (;;) {
1713 while ((lock = *lockp) & 1)
1714 continue;
1715
1716 if (dtrace_casptr((void *)(uintptr_t)lockp,
1717 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1718 break;
1719 }
1720
1721 dtrace_membar_producer();
1722 }
1723
1724 top:
1725 prev = NULL;
1726 lock = hash[bucket].dtdh_lock;
1727
1728 dtrace_membar_consumer();
1729
1730 start = hash[bucket].dtdh_chain;
1731 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1732 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1733 op != DTRACE_DYNVAR_DEALLOC));
1734
1735 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1736 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1737 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1738
1739 if (dvar->dtdv_hashval != hashval) {
1740 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1741 /*
1742 * We've reached the sink, and therefore the
1743 * end of the hash chain; we can kick out of
1744 * the loop knowing that we have seen a valid
1745 * snapshot of state.
1746 */
1747 ASSERT(dvar->dtdv_next == NULL);
1748 ASSERT(dvar == &dtrace_dynhash_sink);
1749 break;
1750 }
1751
1752 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1753 /*
1754 * We've gone off the rails: somewhere along
1755 * the line, one of the members of this hash
1756 * chain was deleted. Note that we could also
1757 * detect this by simply letting this loop run
1758 * to completion, as we would eventually hit
1759 * the end of the dirty list. However, we
1760 * want to avoid running the length of the
1761 * dirty list unnecessarily (it might be quite
1762 * long), so we catch this as early as
1763 * possible by detecting the hash marker. In
1764 * this case, we simply set dvar to NULL and
1765 * break; the conditional after the loop will
1766 * send us back to top.
1767 */
1768 dvar = NULL;
1769 break;
1770 }
1771
1772 goto next;
1773 }
1774
1775 if (dtuple->dtt_nkeys != nkeys)
1776 goto next;
1777
1778 for (i = 0; i < nkeys; i++, dkey++) {
1779 if (dkey->dttk_size != key[i].dttk_size)
1780 goto next; /* size or type mismatch */
1781
1782 if (dkey->dttk_size != 0) {
1783 if (dtrace_bcmp(
1784 (void *)(uintptr_t)key[i].dttk_value,
1785 (void *)(uintptr_t)dkey->dttk_value,
1786 dkey->dttk_size))
1787 goto next;
1788 } else {
1789 if (dkey->dttk_value != key[i].dttk_value)
1790 goto next;
1791 }
1792 }
1793
1794 if (op != DTRACE_DYNVAR_DEALLOC)
1795 return (dvar);
1796
1797 ASSERT(dvar->dtdv_next == NULL ||
1798 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1799
1800 if (prev != NULL) {
1801 ASSERT(hash[bucket].dtdh_chain != dvar);
1802 ASSERT(start != dvar);
1803 ASSERT(prev->dtdv_next == dvar);
1804 prev->dtdv_next = dvar->dtdv_next;
1805 } else {
1806 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1807 start, dvar->dtdv_next) != start) {
1808 /*
1809 * We have failed to atomically swing the
1810 * hash table head pointer, presumably because
1811 * of a conflicting allocation on another CPU.
1812 * We need to reread the hash chain and try
1813 * again.
1814 */
1815 goto top;
1816 }
1817 }
1818
1819 dtrace_membar_producer();
1820
1821 /*
1822 * Now set the hash value to indicate that it's free.
1823 */
1824 ASSERT(hash[bucket].dtdh_chain != dvar);
1825 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1826
1827 dtrace_membar_producer();
1828
1829 /*
1830 * Set the next pointer to point at the dirty list, and
1831 * atomically swing the dirty pointer to the newly freed dvar.
1832 */
1833 do {
1834 next = dcpu->dtdsc_dirty;
1835 dvar->dtdv_next = next;
1836 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1837
1838 /*
1839 * Finally, unlock this hash bucket.
1840 */
1841 ASSERT(hash[bucket].dtdh_lock == lock);
1842 ASSERT(lock & 1);
1843 hash[bucket].dtdh_lock++;
1844
1845 return (NULL);
1846 next:
1847 prev = dvar;
1848 continue;
1849 }
1850
1851 if (dvar == NULL) {
1852 /*
1853 * If dvar is NULL, it is because we went off the rails:
1854 * one of the elements that we traversed in the hash chain
1855 * was deleted while we were traversing it. In this case,
1856 * we assert that we aren't doing a dealloc (deallocs lock
1857 * the hash bucket to prevent themselves from racing with
1858 * one another), and retry the hash chain traversal.
1859 */
1860 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1861 goto top;
1862 }
1863
1864 if (op != DTRACE_DYNVAR_ALLOC) {
1865 /*
1866 * If we are not to allocate a new variable, we want to
1867 * return NULL now. Before we return, check that the value
1868 * of the lock word hasn't changed. If it has, we may have
1869 * seen an inconsistent snapshot.
1870 */
1871 if (op == DTRACE_DYNVAR_NOALLOC) {
1872 if (hash[bucket].dtdh_lock != lock)
1873 goto top;
1874 } else {
1875 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1876 ASSERT(hash[bucket].dtdh_lock == lock);
1877 ASSERT(lock & 1);
1878 hash[bucket].dtdh_lock++;
1879 }
1880
1881 return (NULL);
1882 }
1883
1884 /*
1885 * We need to allocate a new dynamic variable. The size we need is the
1886 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1887 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1888 * the size of any referred-to data (dsize). We then round the final
1889 * size up to the chunksize for allocation.
1890 */
1891 for (ksize = 0, i = 0; i < nkeys; i++)
1892 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1893
1894 /*
1895 * This should be pretty much impossible, but could happen if, say,
1896 * strange DIF specified the tuple. Ideally, this should be an
1897 * assertion and not an error condition -- but that requires that the
1898 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1899 * bullet-proof. (That is, it must not be able to be fooled by
1900 * malicious DIF.) Given the lack of backwards branches in DIF,
1901 * solving this would presumably not amount to solving the Halting
1902 * Problem -- but it still seems awfully hard.
1903 */
1904 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1905 ksize + dsize > chunksize) {
1906 dcpu->dtdsc_drops++;
1907 return (NULL);
1908 }
1909
1910 nstate = DTRACE_DSTATE_EMPTY;
1911
1912 do {
1913 retry:
1914 free = dcpu->dtdsc_free;
1915
1916 if (free == NULL) {
1917 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1918 void *rval;
1919
1920 if (clean == NULL) {
1921 /*
1922 * We're out of dynamic variable space on
1923 * this CPU. Unless we have tried all CPUs,
1924 * we'll try to allocate from a different
1925 * CPU.
1926 */
1927 switch (dstate->dtds_state) {
1928 case DTRACE_DSTATE_CLEAN: {
1929 void *sp = &dstate->dtds_state;
1930
1931 if (++cpu >= (int)NCPU)
1932 cpu = 0;
1933
1934 if (dcpu->dtdsc_dirty != NULL &&
1935 nstate == DTRACE_DSTATE_EMPTY)
1936 nstate = DTRACE_DSTATE_DIRTY;
1937
1938 if (dcpu->dtdsc_rinsing != NULL)
1939 nstate = DTRACE_DSTATE_RINSING;
1940
1941 dcpu = &dstate->dtds_percpu[cpu];
1942
1943 if (cpu != me)
1944 goto retry;
1945
1946 (void) dtrace_cas32(sp,
1947 DTRACE_DSTATE_CLEAN, nstate);
1948
1949 /*
1950 * To increment the correct bean
1951 * counter, take another lap.
1952 */
1953 goto retry;
1954 }
1955
1956 case DTRACE_DSTATE_DIRTY:
1957 dcpu->dtdsc_dirty_drops++;
1958 break;
1959
1960 case DTRACE_DSTATE_RINSING:
1961 dcpu->dtdsc_rinsing_drops++;
1962 break;
1963
1964 case DTRACE_DSTATE_EMPTY:
1965 dcpu->dtdsc_drops++;
1966 break;
1967 }
1968
1969 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1970 return (NULL);
1971 }
1972
1973 /*
1974 * The clean list appears to be non-empty. We want to
1975 * move the clean list to the free list; we start by
1976 * moving the clean pointer aside.
1977 */
1978 if (dtrace_casptr(&dcpu->dtdsc_clean,
1979 clean, NULL) != clean) {
1980 /*
1981 * We are in one of two situations:
1982 *
1983 * (a) The clean list was switched to the
1984 * free list by another CPU.
1985 *
1986 * (b) The clean list was added to by the
1987 * cleansing cyclic.
1988 *
1989 * In either of these situations, we can
1990 * just reattempt the free list allocation.
1991 */
1992 goto retry;
1993 }
1994
1995 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1996
1997 /*
1998 * Now we'll move the clean list to the free list.
1999 * It's impossible for this to fail: the only way
2000 * the free list can be updated is through this
2001 * code path, and only one CPU can own the clean list.
2002 * Thus, it would only be possible for this to fail if
2003 * this code were racing with dtrace_dynvar_clean().
2004 * (That is, if dtrace_dynvar_clean() updated the clean
2005 * list, and we ended up racing to update the free
2006 * list.) This race is prevented by the dtrace_sync()
2007 * in dtrace_dynvar_clean() -- which flushes the
2008 * owners of the clean lists out before resetting
2009 * the clean lists.
2010 */
2011 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2012 ASSERT(rval == NULL);
2013 goto retry;
2014 }
2015
2016 dvar = free;
2017 new_free = dvar->dtdv_next;
2018 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2019
2020 /*
2021 * We have now allocated a new chunk. We copy the tuple keys into the
2022 * tuple array and copy any referenced key data into the data space
2023 * following the tuple array. As we do this, we relocate dttk_value
2024 * in the final tuple to point to the key data address in the chunk.
2025 */
2026 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2027 dvar->dtdv_data = (void *)(kdata + ksize);
2028 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2029
2030 for (i = 0; i < nkeys; i++) {
2031 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2032 size_t kesize = key[i].dttk_size;
2033
2034 if (kesize != 0) {
2035 dtrace_bcopy(
2036 (const void *)(uintptr_t)key[i].dttk_value,
2037 (void *)kdata, kesize);
2038 dkey->dttk_value = kdata;
2039 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2040 } else {
2041 dkey->dttk_value = key[i].dttk_value;
2042 }
2043
2044 dkey->dttk_size = kesize;
2045 }
2046
2047 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2048 dvar->dtdv_hashval = hashval;
2049 dvar->dtdv_next = start;
2050
2051 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2052 return (dvar);
2053
2054 /*
2055 * The cas has failed. Either another CPU is adding an element to
2056 * this hash chain, or another CPU is deleting an element from this
2057 * hash chain. The simplest way to deal with both of these cases
2058 * (though not necessarily the most efficient) is to free our
2059 * allocated block and tail-call ourselves. Note that the free is
2060 * to the dirty list and _not_ to the free list. This is to prevent
2061 * races with allocators, above.
2062 */
2063 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2064
2065 dtrace_membar_producer();
2066
2067 do {
2068 free = dcpu->dtdsc_dirty;
2069 dvar->dtdv_next = free;
2070 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2071
2072 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2073 }
2074
2075 /*ARGSUSED*/
2076 static void
2077 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2078 {
2079 #pragma unused(arg) /* __APPLE__ */
2080 if ((int64_t)nval < (int64_t)*oval)
2081 *oval = nval;
2082 }
2083
2084 /*ARGSUSED*/
2085 static void
2086 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2087 {
2088 #pragma unused(arg) /* __APPLE__ */
2089 if ((int64_t)nval > (int64_t)*oval)
2090 *oval = nval;
2091 }
2092
2093 static void
2094 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2095 {
2096 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2097 int64_t val = (int64_t)nval;
2098
2099 if (val < 0) {
2100 for (i = 0; i < zero; i++) {
2101 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2102 quanta[i] += incr;
2103 return;
2104 }
2105 }
2106 } else {
2107 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2108 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2109 quanta[i - 1] += incr;
2110 return;
2111 }
2112 }
2113
2114 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2115 return;
2116 }
2117
2118 ASSERT(0);
2119 }
2120
2121 static void
2122 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2123 {
2124 uint64_t arg = *lquanta++;
2125 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2126 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2127 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2128 int32_t val = (int32_t)nval, level;
2129
2130 ASSERT(step != 0);
2131 ASSERT(levels != 0);
2132
2133 if (val < base) {
2134 /*
2135 * This is an underflow.
2136 */
2137 lquanta[0] += incr;
2138 return;
2139 }
2140
2141 level = (val - base) / step;
2142
2143 if (level < levels) {
2144 lquanta[level + 1] += incr;
2145 return;
2146 }
2147
2148 /*
2149 * This is an overflow.
2150 */
2151 lquanta[levels + 1] += incr;
2152 }
2153
2154 static int
2155 dtrace_aggregate_llquantize_bucket(int16_t factor, int16_t low, int16_t high,
2156 int16_t nsteps, int64_t value)
2157 {
2158 int64_t this = 1, last, next;
2159 int base = 1, order;
2160
2161 for (order = 0; order < low; ++order)
2162 this *= factor;
2163
2164 /*
2165 * If our value is less than our factor taken to the power of the
2166 * low order of magnitude, it goes into the zeroth bucket.
2167 */
2168 if (value < this)
2169 return 0;
2170 else
2171 last = this;
2172
2173 for (this *= factor; order <= high; ++order) {
2174 int nbuckets = this > nsteps ? nsteps : this;
2175
2176 /*
2177 * We should not generally get log/linear quantizations
2178 * with a high magnitude that allows 64-bits to
2179 * overflow, but we nonetheless protect against this
2180 * by explicitly checking for overflow, and clamping
2181 * our value accordingly.
2182 */
2183 next = this * factor;
2184 if (next < this) {
2185 value = this - 1;
2186 }
2187
2188 /*
2189 * If our value lies within this order of magnitude,
2190 * determine its position by taking the offset within
2191 * the order of magnitude, dividing by the bucket
2192 * width, and adding to our (accumulated) base.
2193 */
2194 if (value < this) {
2195 return (base + (value - last) / (this / nbuckets));
2196 }
2197
2198 base += nbuckets - (nbuckets / factor);
2199 last = this;
2200 this = next;
2201 }
2202
2203 /*
2204 * Our value is greater than or equal to our factor taken to the
2205 * power of one plus the high magnitude -- return the top bucket.
2206 */
2207 return base;
2208 }
2209
2210 static void
2211 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2212 {
2213 uint64_t arg = *llquanta++;
2214 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2215 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2216 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2217 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2218
2219 llquanta[dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, nval)] += incr;
2220 }
2221
2222 /*ARGSUSED*/
2223 static void
2224 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2225 {
2226 #pragma unused(arg) /* __APPLE__ */
2227 data[0]++;
2228 data[1] += nval;
2229 }
2230
2231 /*ARGSUSED*/
2232 static void
2233 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2234 {
2235 #pragma unused(arg) /* __APPLE__ */
2236 int64_t snval = (int64_t)nval;
2237 uint64_t tmp[2];
2238
2239 data[0]++;
2240 data[1] += nval;
2241
2242 /*
2243 * What we want to say here is:
2244 *
2245 * data[2] += nval * nval;
2246 *
2247 * But given that nval is 64-bit, we could easily overflow, so
2248 * we do this as 128-bit arithmetic.
2249 */
2250 if (snval < 0)
2251 snval = -snval;
2252
2253 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2254 dtrace_add_128(data + 2, tmp, data + 2);
2255 }
2256
2257 /*ARGSUSED*/
2258 static void
2259 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2260 {
2261 #pragma unused(nval, arg) /* __APPLE__ */
2262 *oval = *oval + 1;
2263 }
2264
2265 /*ARGSUSED*/
2266 static void
2267 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2268 {
2269 #pragma unused(arg) /* __APPLE__ */
2270 *oval += nval;
2271 }
2272
2273 /*
2274 * Aggregate given the tuple in the principal data buffer, and the aggregating
2275 * action denoted by the specified dtrace_aggregation_t. The aggregation
2276 * buffer is specified as the buf parameter. This routine does not return
2277 * failure; if there is no space in the aggregation buffer, the data will be
2278 * dropped, and a corresponding counter incremented.
2279 */
2280 static void
2281 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2282 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2283 {
2284 #pragma unused(arg)
2285 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2286 uint32_t i, ndx, size, fsize;
2287 uint32_t align = sizeof (uint64_t) - 1;
2288 dtrace_aggbuffer_t *agb;
2289 dtrace_aggkey_t *key;
2290 uint32_t hashval = 0, limit, isstr;
2291 caddr_t tomax, data, kdata;
2292 dtrace_actkind_t action;
2293 dtrace_action_t *act;
2294 uintptr_t offs;
2295
2296 if (buf == NULL)
2297 return;
2298
2299 if (!agg->dtag_hasarg) {
2300 /*
2301 * Currently, only quantize() and lquantize() take additional
2302 * arguments, and they have the same semantics: an increment
2303 * value that defaults to 1 when not present. If additional
2304 * aggregating actions take arguments, the setting of the
2305 * default argument value will presumably have to become more
2306 * sophisticated...
2307 */
2308 arg = 1;
2309 }
2310
2311 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2312 size = rec->dtrd_offset - agg->dtag_base;
2313 fsize = size + rec->dtrd_size;
2314
2315 ASSERT(dbuf->dtb_tomax != NULL);
2316 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2317
2318 if ((tomax = buf->dtb_tomax) == NULL) {
2319 dtrace_buffer_drop(buf);
2320 return;
2321 }
2322
2323 /*
2324 * The metastructure is always at the bottom of the buffer.
2325 */
2326 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2327 sizeof (dtrace_aggbuffer_t));
2328
2329 if (buf->dtb_offset == 0) {
2330 /*
2331 * We just kludge up approximately 1/8th of the size to be
2332 * buckets. If this guess ends up being routinely
2333 * off-the-mark, we may need to dynamically readjust this
2334 * based on past performance.
2335 */
2336 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2337
2338 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2339 (uintptr_t)tomax || hashsize == 0) {
2340 /*
2341 * We've been given a ludicrously small buffer;
2342 * increment our drop count and leave.
2343 */
2344 dtrace_buffer_drop(buf);
2345 return;
2346 }
2347
2348 /*
2349 * And now, a pathetic attempt to try to get a an odd (or
2350 * perchance, a prime) hash size for better hash distribution.
2351 */
2352 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2353 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2354
2355 agb->dtagb_hashsize = hashsize;
2356 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2357 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2358 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2359
2360 for (i = 0; i < agb->dtagb_hashsize; i++)
2361 agb->dtagb_hash[i] = NULL;
2362 }
2363
2364 ASSERT(agg->dtag_first != NULL);
2365 ASSERT(agg->dtag_first->dta_intuple);
2366
2367 /*
2368 * Calculate the hash value based on the key. Note that we _don't_
2369 * include the aggid in the hashing (but we will store it as part of
2370 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2371 * algorithm: a simple, quick algorithm that has no known funnels, and
2372 * gets good distribution in practice. The efficacy of the hashing
2373 * algorithm (and a comparison with other algorithms) may be found by
2374 * running the ::dtrace_aggstat MDB dcmd.
2375 */
2376 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2377 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2378 limit = i + act->dta_rec.dtrd_size;
2379 ASSERT(limit <= size);
2380 isstr = DTRACEACT_ISSTRING(act);
2381
2382 for (; i < limit; i++) {
2383 hashval += data[i];
2384 hashval += (hashval << 10);
2385 hashval ^= (hashval >> 6);
2386
2387 if (isstr && data[i] == '\0')
2388 break;
2389 }
2390 }
2391
2392 hashval += (hashval << 3);
2393 hashval ^= (hashval >> 11);
2394 hashval += (hashval << 15);
2395
2396 /*
2397 * Yes, the divide here is expensive -- but it's generally the least
2398 * of the performance issues given the amount of data that we iterate
2399 * over to compute hash values, compare data, etc.
2400 */
2401 ndx = hashval % agb->dtagb_hashsize;
2402
2403 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2404 ASSERT((caddr_t)key >= tomax);
2405 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2406
2407 if (hashval != key->dtak_hashval || key->dtak_size != size)
2408 continue;
2409
2410 kdata = key->dtak_data;
2411 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2412
2413 for (act = agg->dtag_first; act->dta_intuple;
2414 act = act->dta_next) {
2415 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2416 limit = i + act->dta_rec.dtrd_size;
2417 ASSERT(limit <= size);
2418 isstr = DTRACEACT_ISSTRING(act);
2419
2420 for (; i < limit; i++) {
2421 if (kdata[i] != data[i])
2422 goto next;
2423
2424 if (isstr && data[i] == '\0')
2425 break;
2426 }
2427 }
2428
2429 if (action != key->dtak_action) {
2430 /*
2431 * We are aggregating on the same value in the same
2432 * aggregation with two different aggregating actions.
2433 * (This should have been picked up in the compiler,
2434 * so we may be dealing with errant or devious DIF.)
2435 * This is an error condition; we indicate as much,
2436 * and return.
2437 */
2438 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2439 return;
2440 }
2441
2442 /*
2443 * This is a hit: we need to apply the aggregator to
2444 * the value at this key.
2445 */
2446 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2447 return;
2448 next:
2449 continue;
2450 }
2451
2452 /*
2453 * We didn't find it. We need to allocate some zero-filled space,
2454 * link it into the hash table appropriately, and apply the aggregator
2455 * to the (zero-filled) value.
2456 */
2457 offs = buf->dtb_offset;
2458 while (offs & (align - 1))
2459 offs += sizeof (uint32_t);
2460
2461 /*
2462 * If we don't have enough room to both allocate a new key _and_
2463 * its associated data, increment the drop count and return.
2464 */
2465 if ((uintptr_t)tomax + offs + fsize >
2466 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2467 dtrace_buffer_drop(buf);
2468 return;
2469 }
2470
2471 /*CONSTCOND*/
2472 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2473 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2474 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2475
2476 key->dtak_data = kdata = tomax + offs;
2477 buf->dtb_offset = offs + fsize;
2478
2479 /*
2480 * Now copy the data across.
2481 */
2482 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2483
2484 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2485 kdata[i] = data[i];
2486
2487 /*
2488 * Because strings are not zeroed out by default, we need to iterate
2489 * looking for actions that store strings, and we need to explicitly
2490 * pad these strings out with zeroes.
2491 */
2492 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2493 int nul;
2494
2495 if (!DTRACEACT_ISSTRING(act))
2496 continue;
2497
2498 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2499 limit = i + act->dta_rec.dtrd_size;
2500 ASSERT(limit <= size);
2501
2502 for (nul = 0; i < limit; i++) {
2503 if (nul) {
2504 kdata[i] = '\0';
2505 continue;
2506 }
2507
2508 if (data[i] != '\0')
2509 continue;
2510
2511 nul = 1;
2512 }
2513 }
2514
2515 for (i = size; i < fsize; i++)
2516 kdata[i] = 0;
2517
2518 key->dtak_hashval = hashval;
2519 key->dtak_size = size;
2520 key->dtak_action = action;
2521 key->dtak_next = agb->dtagb_hash[ndx];
2522 agb->dtagb_hash[ndx] = key;
2523
2524 /*
2525 * Finally, apply the aggregator.
2526 */
2527 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2528 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2529 }
2530
2531 /*
2532 * Given consumer state, this routine finds a speculation in the INACTIVE
2533 * state and transitions it into the ACTIVE state. If there is no speculation
2534 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2535 * incremented -- it is up to the caller to take appropriate action.
2536 */
2537 static int
2538 dtrace_speculation(dtrace_state_t *state)
2539 {
2540 int i = 0;
2541 dtrace_speculation_state_t current;
2542 uint32_t *stat = &state->dts_speculations_unavail, count;
2543
2544 while (i < state->dts_nspeculations) {
2545 dtrace_speculation_t *spec = &state->dts_speculations[i];
2546
2547 current = spec->dtsp_state;
2548
2549 if (current != DTRACESPEC_INACTIVE) {
2550 if (current == DTRACESPEC_COMMITTINGMANY ||
2551 current == DTRACESPEC_COMMITTING ||
2552 current == DTRACESPEC_DISCARDING)
2553 stat = &state->dts_speculations_busy;
2554 i++;
2555 continue;
2556 }
2557
2558 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2559 current, DTRACESPEC_ACTIVE) == current)
2560 return (i + 1);
2561 }
2562
2563 /*
2564 * We couldn't find a speculation. If we found as much as a single
2565 * busy speculation buffer, we'll attribute this failure as "busy"
2566 * instead of "unavail".
2567 */
2568 do {
2569 count = *stat;
2570 } while (dtrace_cas32(stat, count, count + 1) != count);
2571
2572 return (0);
2573 }
2574
2575 /*
2576 * This routine commits an active speculation. If the specified speculation
2577 * is not in a valid state to perform a commit(), this routine will silently do
2578 * nothing. The state of the specified speculation is transitioned according
2579 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2580 */
2581 static void
2582 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2583 dtrace_specid_t which)
2584 {
2585 dtrace_speculation_t *spec;
2586 dtrace_buffer_t *src, *dest;
2587 uintptr_t daddr, saddr, dlimit, slimit;
2588 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2589 intptr_t offs;
2590 uint64_t timestamp;
2591
2592 if (which == 0)
2593 return;
2594
2595 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2596 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2597 return;
2598 }
2599
2600 spec = &state->dts_speculations[which - 1];
2601 src = &spec->dtsp_buffer[cpu];
2602 dest = &state->dts_buffer[cpu];
2603
2604 do {
2605 current = spec->dtsp_state;
2606
2607 if (current == DTRACESPEC_COMMITTINGMANY)
2608 break;
2609
2610 switch (current) {
2611 case DTRACESPEC_INACTIVE:
2612 case DTRACESPEC_DISCARDING:
2613 return;
2614
2615 case DTRACESPEC_COMMITTING:
2616 /*
2617 * This is only possible if we are (a) commit()'ing
2618 * without having done a prior speculate() on this CPU
2619 * and (b) racing with another commit() on a different
2620 * CPU. There's nothing to do -- we just assert that
2621 * our offset is 0.
2622 */
2623 ASSERT(src->dtb_offset == 0);
2624 return;
2625
2626 case DTRACESPEC_ACTIVE:
2627 new = DTRACESPEC_COMMITTING;
2628 break;
2629
2630 case DTRACESPEC_ACTIVEONE:
2631 /*
2632 * This speculation is active on one CPU. If our
2633 * buffer offset is non-zero, we know that the one CPU
2634 * must be us. Otherwise, we are committing on a
2635 * different CPU from the speculate(), and we must
2636 * rely on being asynchronously cleaned.
2637 */
2638 if (src->dtb_offset != 0) {
2639 new = DTRACESPEC_COMMITTING;
2640 break;
2641 }
2642 /*FALLTHROUGH*/
2643
2644 case DTRACESPEC_ACTIVEMANY:
2645 new = DTRACESPEC_COMMITTINGMANY;
2646 break;
2647
2648 default:
2649 ASSERT(0);
2650 }
2651 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2652 current, new) != current);
2653
2654 /*
2655 * We have set the state to indicate that we are committing this
2656 * speculation. Now reserve the necessary space in the destination
2657 * buffer.
2658 */
2659 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2660 sizeof (uint64_t), state, NULL)) < 0) {
2661 dtrace_buffer_drop(dest);
2662 goto out;
2663 }
2664
2665 /*
2666 * We have sufficient space to copy the speculative buffer into the
2667 * primary buffer. First, modify the speculative buffer, filling
2668 * in the timestamp of all entries with the current time. The data
2669 * must have the commit() time rather than the time it was traced,
2670 * so that all entries in the primary buffer are in timestamp order.
2671 */
2672 timestamp = dtrace_gethrtime();
2673 saddr = (uintptr_t)src->dtb_tomax;
2674 slimit = saddr + src->dtb_offset;
2675 while (saddr < slimit) {
2676 size_t size;
2677 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2678
2679 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2680 saddr += sizeof (dtrace_epid_t);
2681 continue;
2682 }
2683
2684 ASSERT(dtrh->dtrh_epid <= ((dtrace_epid_t) state->dts_necbs));
2685 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2686
2687 ASSERT(saddr + size <= slimit);
2688 ASSERT(size >= sizeof(dtrace_rechdr_t));
2689 ASSERT(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh) == UINT64_MAX);
2690
2691 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2692
2693 saddr += size;
2694 }
2695
2696 /*
2697 * Copy the buffer across. (Note that this is a
2698 * highly subobtimal bcopy(); in the unlikely event that this becomes
2699 * a serious performance issue, a high-performance DTrace-specific
2700 * bcopy() should obviously be invented.)
2701 */
2702 daddr = (uintptr_t)dest->dtb_tomax + offs;
2703 dlimit = daddr + src->dtb_offset;
2704 saddr = (uintptr_t)src->dtb_tomax;
2705
2706 /*
2707 * First, the aligned portion.
2708 */
2709 while (dlimit - daddr >= sizeof (uint64_t)) {
2710 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2711
2712 daddr += sizeof (uint64_t);
2713 saddr += sizeof (uint64_t);
2714 }
2715
2716 /*
2717 * Now any left-over bit...
2718 */
2719 while (dlimit - daddr)
2720 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2721
2722 /*
2723 * Finally, commit the reserved space in the destination buffer.
2724 */
2725 dest->dtb_offset = offs + src->dtb_offset;
2726
2727 out:
2728 /*
2729 * If we're lucky enough to be the only active CPU on this speculation
2730 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2731 */
2732 if (current == DTRACESPEC_ACTIVE ||
2733 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2734 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2735 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2736 #pragma unused(rval) /* __APPLE__ */
2737
2738 ASSERT(rval == DTRACESPEC_COMMITTING);
2739 }
2740
2741 src->dtb_offset = 0;
2742 src->dtb_xamot_drops += src->dtb_drops;
2743 src->dtb_drops = 0;
2744 }
2745
2746 /*
2747 * This routine discards an active speculation. If the specified speculation
2748 * is not in a valid state to perform a discard(), this routine will silently
2749 * do nothing. The state of the specified speculation is transitioned
2750 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2751 */
2752 static void
2753 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2754 dtrace_specid_t which)
2755 {
2756 dtrace_speculation_t *spec;
2757 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2758 dtrace_buffer_t *buf;
2759
2760 if (which == 0)
2761 return;
2762
2763 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2764 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2765 return;
2766 }
2767
2768 spec = &state->dts_speculations[which - 1];
2769 buf = &spec->dtsp_buffer[cpu];
2770
2771 do {
2772 current = spec->dtsp_state;
2773
2774 switch (current) {
2775 case DTRACESPEC_INACTIVE:
2776 case DTRACESPEC_COMMITTINGMANY:
2777 case DTRACESPEC_COMMITTING:
2778 case DTRACESPEC_DISCARDING:
2779 return;
2780
2781 case DTRACESPEC_ACTIVE:
2782 case DTRACESPEC_ACTIVEMANY:
2783 new = DTRACESPEC_DISCARDING;
2784 break;
2785
2786 case DTRACESPEC_ACTIVEONE:
2787 if (buf->dtb_offset != 0) {
2788 new = DTRACESPEC_INACTIVE;
2789 } else {
2790 new = DTRACESPEC_DISCARDING;
2791 }
2792 break;
2793
2794 default:
2795 ASSERT(0);
2796 }
2797 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2798 current, new) != current);
2799
2800 buf->dtb_offset = 0;
2801 buf->dtb_drops = 0;
2802 }
2803
2804 /*
2805 * Note: not called from probe context. This function is called
2806 * asynchronously from cross call context to clean any speculations that are
2807 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2808 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2809 * speculation.
2810 */
2811 static void
2812 dtrace_speculation_clean_here(dtrace_state_t *state)
2813 {
2814 dtrace_icookie_t cookie;
2815 processorid_t cpu = CPU->cpu_id;
2816 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2817 dtrace_specid_t i;
2818
2819 cookie = dtrace_interrupt_disable();
2820
2821 if (dest->dtb_tomax == NULL) {
2822 dtrace_interrupt_enable(cookie);
2823 return;
2824 }
2825
2826 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2827 dtrace_speculation_t *spec = &state->dts_speculations[i];
2828 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2829
2830 if (src->dtb_tomax == NULL)
2831 continue;
2832
2833 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2834 src->dtb_offset = 0;
2835 continue;
2836 }
2837
2838 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2839 continue;
2840
2841 if (src->dtb_offset == 0)
2842 continue;
2843
2844 dtrace_speculation_commit(state, cpu, i + 1);
2845 }
2846
2847 dtrace_interrupt_enable(cookie);
2848 }
2849
2850 /*
2851 * Note: not called from probe context. This function is called
2852 * asynchronously (and at a regular interval) to clean any speculations that
2853 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2854 * is work to be done, it cross calls all CPUs to perform that work;
2855 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2856 * INACTIVE state until they have been cleaned by all CPUs.
2857 */
2858 static void
2859 dtrace_speculation_clean(dtrace_state_t *state)
2860 {
2861 int work = 0;
2862 uint32_t rv;
2863 dtrace_specid_t i;
2864
2865 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2866 dtrace_speculation_t *spec = &state->dts_speculations[i];
2867
2868 ASSERT(!spec->dtsp_cleaning);
2869
2870 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2871 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2872 continue;
2873
2874 work++;
2875 spec->dtsp_cleaning = 1;
2876 }
2877
2878 if (!work)
2879 return;
2880
2881 dtrace_xcall(DTRACE_CPUALL,
2882 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2883
2884 /*
2885 * We now know that all CPUs have committed or discarded their
2886 * speculation buffers, as appropriate. We can now set the state
2887 * to inactive.
2888 */
2889 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2890 dtrace_speculation_t *spec = &state->dts_speculations[i];
2891 dtrace_speculation_state_t current, new;
2892
2893 if (!spec->dtsp_cleaning)
2894 continue;
2895
2896 current = spec->dtsp_state;
2897 ASSERT(current == DTRACESPEC_DISCARDING ||
2898 current == DTRACESPEC_COMMITTINGMANY);
2899
2900 new = DTRACESPEC_INACTIVE;
2901
2902 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2903 ASSERT(rv == current);
2904 spec->dtsp_cleaning = 0;
2905 }
2906 }
2907
2908 /*
2909 * Called as part of a speculate() to get the speculative buffer associated
2910 * with a given speculation. Returns NULL if the specified speculation is not
2911 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2912 * the active CPU is not the specified CPU -- the speculation will be
2913 * atomically transitioned into the ACTIVEMANY state.
2914 */
2915 static dtrace_buffer_t *
2916 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2917 dtrace_specid_t which)
2918 {
2919 dtrace_speculation_t *spec;
2920 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2921 dtrace_buffer_t *buf;
2922
2923 if (which == 0)
2924 return (NULL);
2925
2926 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2927 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2928 return (NULL);
2929 }
2930
2931 spec = &state->dts_speculations[which - 1];
2932 buf = &spec->dtsp_buffer[cpuid];
2933
2934 do {
2935 current = spec->dtsp_state;
2936
2937 switch (current) {
2938 case DTRACESPEC_INACTIVE:
2939 case DTRACESPEC_COMMITTINGMANY:
2940 case DTRACESPEC_DISCARDING:
2941 return (NULL);
2942
2943 case DTRACESPEC_COMMITTING:
2944 ASSERT(buf->dtb_offset == 0);
2945 return (NULL);
2946
2947 case DTRACESPEC_ACTIVEONE:
2948 /*
2949 * This speculation is currently active on one CPU.
2950 * Check the offset in the buffer; if it's non-zero,
2951 * that CPU must be us (and we leave the state alone).
2952 * If it's zero, assume that we're starting on a new
2953 * CPU -- and change the state to indicate that the
2954 * speculation is active on more than one CPU.
2955 */
2956 if (buf->dtb_offset != 0)
2957 return (buf);
2958
2959 new = DTRACESPEC_ACTIVEMANY;
2960 break;
2961
2962 case DTRACESPEC_ACTIVEMANY:
2963 return (buf);
2964
2965 case DTRACESPEC_ACTIVE:
2966 new = DTRACESPEC_ACTIVEONE;
2967 break;
2968
2969 default:
2970 ASSERT(0);
2971 }
2972 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2973 current, new) != current);
2974
2975 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2976 return (buf);
2977 }
2978
2979 /*
2980 * Return a string. In the event that the user lacks the privilege to access
2981 * arbitrary kernel memory, we copy the string out to scratch memory so that we
2982 * don't fail access checking.
2983 *
2984 * dtrace_dif_variable() uses this routine as a helper for various
2985 * builtin values such as 'execname' and 'probefunc.'
2986 */
2987 static
2988 uintptr_t
2989 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2990 dtrace_mstate_t *mstate)
2991 {
2992 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2993 uintptr_t ret;
2994 size_t strsz;
2995
2996 /*
2997 * The easy case: this probe is allowed to read all of memory, so
2998 * we can just return this as a vanilla pointer.
2999 */
3000 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3001 return (addr);
3002
3003 /*
3004 * This is the tougher case: we copy the string in question from
3005 * kernel memory into scratch memory and return it that way: this
3006 * ensures that we won't trip up when access checking tests the
3007 * BYREF return value.
3008 */
3009 strsz = dtrace_strlen((char *)addr, size) + 1;
3010
3011 if (mstate->dtms_scratch_ptr + strsz >
3012 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3013 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3014 return (0);
3015 }
3016
3017 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3018 strsz);
3019 ret = mstate->dtms_scratch_ptr;
3020 mstate->dtms_scratch_ptr += strsz;
3021 return (ret);
3022 }
3023
3024 /*
3025 * This function implements the DIF emulator's variable lookups. The emulator
3026 * passes a reserved variable identifier and optional built-in array index.
3027 */
3028 static uint64_t
3029 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3030 uint64_t ndx)
3031 {
3032 /*
3033 * If we're accessing one of the uncached arguments, we'll turn this
3034 * into a reference in the args array.
3035 */
3036 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3037 ndx = v - DIF_VAR_ARG0;
3038 v = DIF_VAR_ARGS;
3039 }
3040
3041 switch (v) {
3042 case DIF_VAR_ARGS:
3043 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3044 if (ndx >= sizeof (mstate->dtms_arg) /
3045 sizeof (mstate->dtms_arg[0])) {
3046 /*
3047 * APPLE NOTE: Account for introduction of __dtrace_probe()
3048 */
3049 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3050 dtrace_provider_t *pv;
3051 uint64_t val;
3052
3053 pv = mstate->dtms_probe->dtpr_provider;
3054 if (pv->dtpv_pops.dtps_getargval != NULL)
3055 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3056 mstate->dtms_probe->dtpr_id,
3057 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3058 /* Special case access of arg5 as passed to dtrace_probe_error() (which see.) */
3059 else if (mstate->dtms_probe->dtpr_id == dtrace_probeid_error && ndx == 5) {
3060 return ((dtrace_state_t *)(uintptr_t)(mstate->dtms_arg[0]))->dts_arg_error_illval;
3061 }
3062
3063 else
3064 val = dtrace_getarg(ndx, aframes);
3065
3066 /*
3067 * This is regrettably required to keep the compiler
3068 * from tail-optimizing the call to dtrace_getarg().
3069 * The condition always evaluates to true, but the
3070 * compiler has no way of figuring that out a priori.
3071 * (None of this would be necessary if the compiler
3072 * could be relied upon to _always_ tail-optimize
3073 * the call to dtrace_getarg() -- but it can't.)
3074 */
3075 if (mstate->dtms_probe != NULL)
3076 return (val);
3077
3078 ASSERT(0);
3079 }
3080
3081 return (mstate->dtms_arg[ndx]);
3082
3083 case DIF_VAR_UREGS: {
3084 thread_t thread;
3085
3086 if (!dtrace_priv_proc(state))
3087 return (0);
3088
3089 if ((thread = current_thread()) == NULL) {
3090 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3091 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3092 return (0);
3093 }
3094
3095 return (dtrace_getreg(find_user_regs(thread), ndx));
3096 }
3097
3098
3099 case DIF_VAR_CURTHREAD:
3100 if (!dtrace_priv_kernel(state))
3101 return (0);
3102
3103 return ((uint64_t)(uintptr_t)current_thread());
3104
3105 case DIF_VAR_TIMESTAMP:
3106 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3107 mstate->dtms_timestamp = dtrace_gethrtime();
3108 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3109 }
3110 return (mstate->dtms_timestamp);
3111
3112 case DIF_VAR_VTIMESTAMP:
3113 ASSERT(dtrace_vtime_references != 0);
3114 return (dtrace_get_thread_vtime(current_thread()));
3115
3116 case DIF_VAR_WALLTIMESTAMP:
3117 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3118 mstate->dtms_walltimestamp = dtrace_gethrestime();
3119 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3120 }
3121 return (mstate->dtms_walltimestamp);
3122
3123 case DIF_VAR_MACHTIMESTAMP:
3124 if (!(mstate->dtms_present & DTRACE_MSTATE_MACHTIMESTAMP)) {
3125 mstate->dtms_machtimestamp = mach_absolute_time();
3126 mstate->dtms_present |= DTRACE_MSTATE_MACHTIMESTAMP;
3127 }
3128 return (mstate->dtms_machtimestamp);
3129
3130 case DIF_VAR_IPL:
3131 if (!dtrace_priv_kernel(state))
3132 return (0);
3133 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3134 mstate->dtms_ipl = dtrace_getipl();
3135 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3136 }
3137 return (mstate->dtms_ipl);
3138
3139 case DIF_VAR_EPID:
3140 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3141 return (mstate->dtms_epid);
3142
3143 case DIF_VAR_ID:
3144 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3145 return (mstate->dtms_probe->dtpr_id);
3146
3147 case DIF_VAR_STACKDEPTH:
3148 if (!dtrace_priv_kernel(state))
3149 return (0);
3150 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3151 /*
3152 * APPLE NOTE: Account for introduction of __dtrace_probe()
3153 */
3154 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3155
3156 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3157 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3158 }
3159 return (mstate->dtms_stackdepth);
3160
3161 case DIF_VAR_USTACKDEPTH:
3162 if (!dtrace_priv_proc(state))
3163 return (0);
3164 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3165 /*
3166 * See comment in DIF_VAR_PID.
3167 */
3168 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3169 CPU_ON_INTR(CPU)) {
3170 mstate->dtms_ustackdepth = 0;
3171 } else {
3172 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3173 mstate->dtms_ustackdepth =
3174 dtrace_getustackdepth();
3175 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3176 }
3177 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3178 }
3179 return (mstate->dtms_ustackdepth);
3180
3181 case DIF_VAR_CALLER:
3182 if (!dtrace_priv_kernel(state))
3183 return (0);
3184 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3185 /*
3186 * APPLE NOTE: Account for introduction of __dtrace_probe()
3187 */
3188 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3189
3190 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3191 /*
3192 * If this is an unanchored probe, we are
3193 * required to go through the slow path:
3194 * dtrace_caller() only guarantees correct
3195 * results for anchored probes.
3196 */
3197 pc_t caller[2];
3198
3199 dtrace_getpcstack(caller, 2, aframes,
3200 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3201 mstate->dtms_caller = caller[1];
3202 } else if ((mstate->dtms_caller =
3203 dtrace_caller(aframes)) == (uintptr_t)-1) {
3204 /*
3205 * We have failed to do this the quick way;
3206 * we must resort to the slower approach of
3207 * calling dtrace_getpcstack().
3208 */
3209 pc_t caller;
3210
3211 dtrace_getpcstack(&caller, 1, aframes, NULL);
3212 mstate->dtms_caller = caller;
3213 }
3214
3215 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3216 }
3217 return (mstate->dtms_caller);
3218
3219 case DIF_VAR_UCALLER:
3220 if (!dtrace_priv_proc(state))
3221 return (0);
3222
3223 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3224 uint64_t ustack[3];
3225
3226 /*
3227 * dtrace_getupcstack() fills in the first uint64_t
3228 * with the current PID. The second uint64_t will
3229 * be the program counter at user-level. The third
3230 * uint64_t will contain the caller, which is what
3231 * we're after.
3232 */
3233 ustack[2] = 0;
3234 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3235 dtrace_getupcstack(ustack, 3);
3236 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3237 mstate->dtms_ucaller = ustack[2];
3238 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3239 }
3240
3241 return (mstate->dtms_ucaller);
3242
3243 case DIF_VAR_PROBEPROV:
3244 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3245 return (dtrace_dif_varstr(
3246 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3247 state, mstate));
3248
3249 case DIF_VAR_PROBEMOD:
3250 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3251 return (dtrace_dif_varstr(
3252 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3253 state, mstate));
3254
3255 case DIF_VAR_PROBEFUNC:
3256 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3257 return (dtrace_dif_varstr(
3258 (uintptr_t)mstate->dtms_probe->dtpr_func,
3259 state, mstate));
3260
3261 case DIF_VAR_PROBENAME:
3262 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3263 return (dtrace_dif_varstr(
3264 (uintptr_t)mstate->dtms_probe->dtpr_name,
3265 state, mstate));
3266
3267 case DIF_VAR_PID:
3268 if (!dtrace_priv_proc_relaxed(state))
3269 return (0);
3270
3271 /*
3272 * Note that we are assuming that an unanchored probe is
3273 * always due to a high-level interrupt. (And we're assuming
3274 * that there is only a single high level interrupt.)
3275 */
3276 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3277 /* Anchored probe that fires while on an interrupt accrues to process 0 */
3278 return 0;
3279
3280 return ((uint64_t)dtrace_proc_selfpid());
3281
3282 case DIF_VAR_PPID:
3283 if (!dtrace_priv_proc_relaxed(state))
3284 return (0);
3285
3286 /*
3287 * See comment in DIF_VAR_PID.
3288 */
3289 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3290 return (0);
3291
3292 return ((uint64_t)dtrace_proc_selfppid());
3293
3294 case DIF_VAR_TID:
3295 /* We do not need to check for null current_thread() */
3296 return thread_tid(current_thread()); /* globally unique */
3297
3298 case DIF_VAR_PTHREAD_SELF:
3299 if (!dtrace_priv_proc(state))
3300 return (0);
3301
3302 /* Not currently supported, but we should be able to delta the dispatchqaddr and dispatchqoffset to get pthread_self */
3303 return 0;
3304
3305 case DIF_VAR_DISPATCHQADDR:
3306 if (!dtrace_priv_proc(state))
3307 return (0);
3308
3309 /* We do not need to check for null current_thread() */
3310 return thread_dispatchqaddr(current_thread());
3311
3312 case DIF_VAR_EXECNAME:
3313 {
3314 char *xname = (char *)mstate->dtms_scratch_ptr;
3315 size_t scratch_size = MAXCOMLEN+1;
3316
3317 /* The scratch allocation's lifetime is that of the clause. */
3318 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3319 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3320 return 0;
3321 }
3322
3323 if (!dtrace_priv_proc_relaxed(state))
3324 return (0);
3325
3326 mstate->dtms_scratch_ptr += scratch_size;
3327 proc_selfname( xname, MAXCOMLEN );
3328
3329 return ((uint64_t)(uintptr_t)xname);
3330 }
3331
3332
3333 case DIF_VAR_ZONENAME:
3334 {
3335 /* scratch_size is equal to length('global') + 1 for the null-terminator. */
3336 char *zname = (char *)mstate->dtms_scratch_ptr;
3337 size_t scratch_size = 6 + 1;
3338
3339 if (!dtrace_priv_proc(state))
3340 return (0);
3341
3342 /* The scratch allocation's lifetime is that of the clause. */
3343 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3344 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3345 return 0;
3346 }
3347
3348 mstate->dtms_scratch_ptr += scratch_size;
3349
3350 /* The kernel does not provide zonename, it will always return 'global'. */
3351 strlcpy(zname, "global", scratch_size);
3352
3353 return ((uint64_t)(uintptr_t)zname);
3354 }
3355
3356 case DIF_VAR_UID:
3357 if (!dtrace_priv_proc_relaxed(state))
3358 return (0);
3359
3360 /*
3361 * See comment in DIF_VAR_PID.
3362 */
3363 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3364 return (0);
3365
3366 return ((uint64_t) dtrace_proc_selfruid());
3367
3368 case DIF_VAR_GID:
3369 if (!dtrace_priv_proc(state))
3370 return (0);
3371
3372 /*
3373 * See comment in DIF_VAR_PID.
3374 */
3375 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3376 return (0);
3377
3378 if (dtrace_CRED() != NULL)
3379 /* Credential does not require lazy initialization. */
3380 return ((uint64_t)kauth_getgid());
3381 else {
3382 /* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3383 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3384 return -1ULL;
3385 }
3386
3387 case DIF_VAR_ERRNO: {
3388 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
3389 if (!dtrace_priv_proc(state))
3390 return (0);
3391
3392 /*
3393 * See comment in DIF_VAR_PID.
3394 */
3395 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3396 return (0);
3397
3398 if (uthread)
3399 return (uint64_t)uthread->t_dtrace_errno;
3400 else {
3401 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3402 return -1ULL;
3403 }
3404 }
3405
3406 default:
3407 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3408 return (0);
3409 }
3410 }
3411
3412 /*
3413 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3414 * Notice that we don't bother validating the proper number of arguments or
3415 * their types in the tuple stack. This isn't needed because all argument
3416 * interpretation is safe because of our load safety -- the worst that can
3417 * happen is that a bogus program can obtain bogus results.
3418 */
3419 static void
3420 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3421 dtrace_key_t *tupregs, int nargs,
3422 dtrace_mstate_t *mstate, dtrace_state_t *state)
3423 {
3424 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3425 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3426 dtrace_vstate_t *vstate = &state->dts_vstate;
3427
3428 #if !defined(__APPLE__)
3429 union {
3430 mutex_impl_t mi;
3431 uint64_t mx;
3432 } m;
3433
3434 union {
3435 krwlock_t ri;
3436 uintptr_t rw;
3437 } r;
3438 #else
3439 /* FIXME: awaits lock/mutex work */
3440 #endif /* __APPLE__ */
3441
3442 switch (subr) {
3443 case DIF_SUBR_RAND:
3444 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3445 break;
3446
3447 #if !defined(__APPLE__)
3448 case DIF_SUBR_MUTEX_OWNED:
3449 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3450 mstate, vstate)) {
3451 regs[rd] = 0;
3452 break;
3453 }
3454
3455 m.mx = dtrace_load64(tupregs[0].dttk_value);
3456 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3457 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3458 else
3459 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3460 break;
3461
3462 case DIF_SUBR_MUTEX_OWNER:
3463 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3464 mstate, vstate)) {
3465 regs[rd] = 0;
3466 break;
3467 }
3468
3469 m.mx = dtrace_load64(tupregs[0].dttk_value);
3470 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3471 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3472 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3473 else
3474 regs[rd] = 0;
3475 break;
3476
3477 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3478 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3479 mstate, vstate)) {
3480 regs[rd] = 0;
3481 break;
3482 }
3483
3484 m.mx = dtrace_load64(tupregs[0].dttk_value);
3485 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3486 break;
3487
3488 case DIF_SUBR_MUTEX_TYPE_SPIN:
3489 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3490 mstate, vstate)) {
3491 regs[rd] = 0;
3492 break;
3493 }
3494
3495 m.mx = dtrace_load64(tupregs[0].dttk_value);
3496 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3497 break;
3498
3499 case DIF_SUBR_RW_READ_HELD: {
3500 uintptr_t tmp;
3501
3502 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3503 mstate, vstate)) {
3504 regs[rd] = 0;
3505 break;
3506 }
3507
3508 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3509 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3510 break;
3511 }
3512
3513 case DIF_SUBR_RW_WRITE_HELD:
3514 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3515 mstate, vstate)) {
3516 regs[rd] = 0;
3517 break;
3518 }
3519
3520 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3521 regs[rd] = _RW_WRITE_HELD(&r.ri);
3522 break;
3523
3524 case DIF_SUBR_RW_ISWRITER:
3525 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3526 mstate, vstate)) {
3527 regs[rd] = 0;
3528 break;
3529 }
3530
3531 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3532 regs[rd] = _RW_ISWRITER(&r.ri);
3533 break;
3534 #else
3535 /* FIXME: awaits lock/mutex work */
3536 #endif /* __APPLE__ */
3537
3538 case DIF_SUBR_BCOPY: {
3539 /*
3540 * We need to be sure that the destination is in the scratch
3541 * region -- no other region is allowed.
3542 */
3543 uintptr_t src = tupregs[0].dttk_value;
3544 uintptr_t dest = tupregs[1].dttk_value;
3545 size_t size = tupregs[2].dttk_value;
3546
3547 if (!dtrace_inscratch(dest, size, mstate)) {
3548 *flags |= CPU_DTRACE_BADADDR;
3549 *illval = regs[rd];
3550 break;
3551 }
3552
3553 if (!dtrace_canload(src, size, mstate, vstate)) {
3554 regs[rd] = 0;
3555 break;
3556 }
3557
3558 dtrace_bcopy((void *)src, (void *)dest, size);
3559 break;
3560 }
3561
3562 case DIF_SUBR_ALLOCA:
3563 case DIF_SUBR_COPYIN: {
3564 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3565 uint64_t size =
3566 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3567 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3568
3569 /*
3570 * This action doesn't require any credential checks since
3571 * probes will not activate in user contexts to which the
3572 * enabling user does not have permissions.
3573 */
3574
3575 /*
3576 * Rounding up the user allocation size could have overflowed
3577 * a large, bogus allocation (like -1ULL) to 0.
3578 */
3579 if (scratch_size < size ||
3580 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3581 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3582 regs[rd] = 0;
3583 break;
3584 }
3585
3586 if (subr == DIF_SUBR_COPYIN) {
3587 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3588 if (dtrace_priv_proc(state))
3589 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3590 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3591 }
3592
3593 mstate->dtms_scratch_ptr += scratch_size;
3594 regs[rd] = dest;
3595 break;
3596 }
3597
3598 case DIF_SUBR_COPYINTO: {
3599 uint64_t size = tupregs[1].dttk_value;
3600 uintptr_t dest = tupregs[2].dttk_value;
3601
3602 /*
3603 * This action doesn't require any credential checks since
3604 * probes will not activate in user contexts to which the
3605 * enabling user does not have permissions.
3606 */
3607 if (!dtrace_inscratch(dest, size, mstate)) {
3608 *flags |= CPU_DTRACE_BADADDR;
3609 *illval = regs[rd];
3610 break;
3611 }
3612
3613 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3614 if (dtrace_priv_proc(state))
3615 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3616 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3617 break;
3618 }
3619
3620 case DIF_SUBR_COPYINSTR: {
3621 uintptr_t dest = mstate->dtms_scratch_ptr;
3622 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3623
3624 if (nargs > 1 && tupregs[1].dttk_value < size)
3625 size = tupregs[1].dttk_value + 1;
3626
3627 /*
3628 * This action doesn't require any credential checks since
3629 * probes will not activate in user contexts to which the
3630 * enabling user does not have permissions.
3631 */
3632 if (!DTRACE_INSCRATCH(mstate, size)) {
3633 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3634 regs[rd] = 0;
3635 break;
3636 }
3637
3638 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3639 if (dtrace_priv_proc(state))
3640 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3641 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3642
3643 ((char *)dest)[size - 1] = '\0';
3644 mstate->dtms_scratch_ptr += size;
3645 regs[rd] = dest;
3646 break;
3647 }
3648
3649 case DIF_SUBR_MSGSIZE:
3650 case DIF_SUBR_MSGDSIZE: {
3651 /* Darwin does not implement SysV streams messages */
3652 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3653 regs[rd] = 0;
3654 break;
3655 }
3656
3657 case DIF_SUBR_PROGENYOF: {
3658 pid_t pid = tupregs[0].dttk_value;
3659 struct proc *p = current_proc();
3660 int rval = 0, lim = nprocs;
3661
3662 while(p && (lim-- > 0)) {
3663 pid_t ppid;
3664
3665 ppid = (pid_t)dtrace_load32((uintptr_t)&(p->p_pid));
3666 if (*flags & CPU_DTRACE_FAULT)
3667 break;
3668
3669 if (ppid == pid) {
3670 rval = 1;
3671 break;
3672 }
3673
3674 if (ppid == 0)
3675 break; /* Can't climb process tree any further. */
3676
3677 p = (struct proc *)dtrace_loadptr((uintptr_t)&(p->p_pptr));
3678 if (*flags & CPU_DTRACE_FAULT)
3679 break;
3680 }
3681
3682 regs[rd] = rval;
3683 break;
3684 }
3685
3686 case DIF_SUBR_SPECULATION:
3687 regs[rd] = dtrace_speculation(state);
3688 break;
3689
3690
3691 case DIF_SUBR_COPYOUT: {
3692 uintptr_t kaddr = tupregs[0].dttk_value;
3693 user_addr_t uaddr = tupregs[1].dttk_value;
3694 uint64_t size = tupregs[2].dttk_value;
3695
3696 if (!dtrace_destructive_disallow &&
3697 dtrace_priv_proc_control(state) &&
3698 !dtrace_istoxic(kaddr, size)) {
3699 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3700 dtrace_copyout(kaddr, uaddr, size, flags);
3701 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3702 }
3703 break;
3704 }
3705
3706 case DIF_SUBR_COPYOUTSTR: {
3707 uintptr_t kaddr = tupregs[0].dttk_value;
3708 user_addr_t uaddr = tupregs[1].dttk_value;
3709 uint64_t size = tupregs[2].dttk_value;
3710
3711 if (!dtrace_destructive_disallow &&
3712 dtrace_priv_proc_control(state) &&
3713 !dtrace_istoxic(kaddr, size)) {
3714 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3715 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3716 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3717 }
3718 break;
3719 }
3720
3721 case DIF_SUBR_STRLEN: {
3722 size_t sz;
3723 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3724 sz = dtrace_strlen((char *)addr,
3725 state->dts_options[DTRACEOPT_STRSIZE]);
3726
3727 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3728 regs[rd] = 0;
3729 break;
3730 }
3731
3732 regs[rd] = sz;
3733
3734 break;
3735 }
3736
3737 case DIF_SUBR_STRCHR:
3738 case DIF_SUBR_STRRCHR: {
3739 /*
3740 * We're going to iterate over the string looking for the
3741 * specified character. We will iterate until we have reached
3742 * the string length or we have found the character. If this
3743 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3744 * of the specified character instead of the first.
3745 */
3746 uintptr_t saddr = tupregs[0].dttk_value;
3747 uintptr_t addr = tupregs[0].dttk_value;
3748 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3749 char c, target = (char)tupregs[1].dttk_value;
3750
3751 for (regs[rd] = 0; addr < limit; addr++) {
3752 if ((c = dtrace_load8(addr)) == target) {
3753 regs[rd] = addr;
3754
3755 if (subr == DIF_SUBR_STRCHR)
3756 break;
3757 }
3758
3759 if (c == '\0')
3760 break;
3761 }
3762
3763 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3764 regs[rd] = 0;
3765 break;
3766 }
3767
3768 break;
3769 }
3770
3771 case DIF_SUBR_STRSTR:
3772 case DIF_SUBR_INDEX:
3773 case DIF_SUBR_RINDEX: {
3774 /*
3775 * We're going to iterate over the string looking for the
3776 * specified string. We will iterate until we have reached
3777 * the string length or we have found the string. (Yes, this
3778 * is done in the most naive way possible -- but considering
3779 * that the string we're searching for is likely to be
3780 * relatively short, the complexity of Rabin-Karp or similar
3781 * hardly seems merited.)
3782 */
3783 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3784 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3785 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3786 size_t len = dtrace_strlen(addr, size);
3787 size_t sublen = dtrace_strlen(substr, size);
3788 char *limit = addr + len, *orig = addr;
3789 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3790 int inc = 1;
3791
3792 regs[rd] = notfound;
3793
3794 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3795 regs[rd] = 0;
3796 break;
3797 }
3798
3799 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3800 vstate)) {
3801 regs[rd] = 0;
3802 break;
3803 }
3804
3805 /*
3806 * strstr() and index()/rindex() have similar semantics if
3807 * both strings are the empty string: strstr() returns a
3808 * pointer to the (empty) string, and index() and rindex()
3809 * both return index 0 (regardless of any position argument).
3810 */
3811 if (sublen == 0 && len == 0) {
3812 if (subr == DIF_SUBR_STRSTR)
3813 regs[rd] = (uintptr_t)addr;
3814 else
3815 regs[rd] = 0;
3816 break;
3817 }
3818
3819 if (subr != DIF_SUBR_STRSTR) {
3820 if (subr == DIF_SUBR_RINDEX) {
3821 limit = orig - 1;
3822 addr += len;
3823 inc = -1;
3824 }
3825
3826 /*
3827 * Both index() and rindex() take an optional position
3828 * argument that denotes the starting position.
3829 */
3830 if (nargs == 3) {
3831 int64_t pos = (int64_t)tupregs[2].dttk_value;
3832
3833 /*
3834 * If the position argument to index() is
3835 * negative, Perl implicitly clamps it at
3836 * zero. This semantic is a little surprising
3837 * given the special meaning of negative
3838 * positions to similar Perl functions like
3839 * substr(), but it appears to reflect a
3840 * notion that index() can start from a
3841 * negative index and increment its way up to
3842 * the string. Given this notion, Perl's
3843 * rindex() is at least self-consistent in
3844 * that it implicitly clamps positions greater
3845 * than the string length to be the string
3846 * length. Where Perl completely loses
3847 * coherence, however, is when the specified
3848 * substring is the empty string (""). In
3849 * this case, even if the position is
3850 * negative, rindex() returns 0 -- and even if
3851 * the position is greater than the length,
3852 * index() returns the string length. These
3853 * semantics violate the notion that index()
3854 * should never return a value less than the
3855 * specified position and that rindex() should
3856 * never return a value greater than the
3857 * specified position. (One assumes that
3858 * these semantics are artifacts of Perl's
3859 * implementation and not the results of
3860 * deliberate design -- it beggars belief that
3861 * even Larry Wall could desire such oddness.)
3862 * While in the abstract one would wish for
3863 * consistent position semantics across
3864 * substr(), index() and rindex() -- or at the
3865 * very least self-consistent position
3866 * semantics for index() and rindex() -- we
3867 * instead opt to keep with the extant Perl
3868 * semantics, in all their broken glory. (Do
3869 * we have more desire to maintain Perl's
3870 * semantics than Perl does? Probably.)
3871 */
3872 if (subr == DIF_SUBR_RINDEX) {
3873 if (pos < 0) {
3874 if (sublen == 0)
3875 regs[rd] = 0;
3876 break;
3877 }
3878
3879 if ((size_t)pos > len)
3880 pos = len;
3881 } else {
3882 if (pos < 0)
3883 pos = 0;
3884
3885 if ((size_t)pos >= len) {
3886 if (sublen == 0)
3887 regs[rd] = len;
3888 break;
3889 }
3890 }
3891
3892 addr = orig + pos;
3893 }
3894 }
3895
3896 for (regs[rd] = notfound; addr != limit; addr += inc) {
3897 if (dtrace_strncmp(addr, substr, sublen) == 0) {
3898 if (subr != DIF_SUBR_STRSTR) {
3899 /*
3900 * As D index() and rindex() are
3901 * modeled on Perl (and not on awk),
3902 * we return a zero-based (and not a
3903 * one-based) index. (For you Perl
3904 * weenies: no, we're not going to add
3905 * $[ -- and shouldn't you be at a con
3906 * or something?)
3907 */
3908 regs[rd] = (uintptr_t)(addr - orig);
3909 break;
3910 }
3911
3912 ASSERT(subr == DIF_SUBR_STRSTR);
3913 regs[rd] = (uintptr_t)addr;
3914 break;
3915 }
3916 }
3917
3918 break;
3919 }
3920
3921 case DIF_SUBR_STRTOK: {
3922 uintptr_t addr = tupregs[0].dttk_value;
3923 uintptr_t tokaddr = tupregs[1].dttk_value;
3924 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3925 uintptr_t limit, toklimit = tokaddr + size;
3926 char *dest = (char *)mstate->dtms_scratch_ptr;
3927 uint8_t c='\0', tokmap[32]; /* 256 / 8 */
3928 uint64_t i = 0;
3929
3930 /*
3931 * Check both the token buffer and (later) the input buffer,
3932 * since both could be non-scratch addresses.
3933 */
3934 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3935 regs[rd] = 0;
3936 break;
3937 }
3938
3939 if (!DTRACE_INSCRATCH(mstate, size)) {
3940 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3941 regs[rd] = 0;
3942 break;
3943 }
3944
3945 if (addr == 0) {
3946 /*
3947 * If the address specified is NULL, we use our saved
3948 * strtok pointer from the mstate. Note that this
3949 * means that the saved strtok pointer is _only_
3950 * valid within multiple enablings of the same probe --
3951 * it behaves like an implicit clause-local variable.
3952 */
3953 addr = mstate->dtms_strtok;
3954 } else {
3955 /*
3956 * If the user-specified address is non-NULL we must
3957 * access check it. This is the only time we have
3958 * a chance to do so, since this address may reside
3959 * in the string table of this clause-- future calls
3960 * (when we fetch addr from mstate->dtms_strtok)
3961 * would fail this access check.
3962 */
3963 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3964 regs[rd] = 0;
3965 break;
3966 }
3967 }
3968
3969 /*
3970 * First, zero the token map, and then process the token
3971 * string -- setting a bit in the map for every character
3972 * found in the token string.
3973 */
3974 for (i = 0; i < (int)sizeof (tokmap); i++)
3975 tokmap[i] = 0;
3976
3977 for (; tokaddr < toklimit; tokaddr++) {
3978 if ((c = dtrace_load8(tokaddr)) == '\0')
3979 break;
3980
3981 ASSERT((c >> 3) < sizeof (tokmap));
3982 tokmap[c >> 3] |= (1 << (c & 0x7));
3983 }
3984
3985 for (limit = addr + size; addr < limit; addr++) {
3986 /*
3987 * We're looking for a character that is _not_ contained
3988 * in the token string.
3989 */
3990 if ((c = dtrace_load8(addr)) == '\0')
3991 break;
3992
3993 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3994 break;
3995 }
3996
3997 if (c == '\0') {
3998 /*
3999 * We reached the end of the string without finding
4000 * any character that was not in the token string.
4001 * We return NULL in this case, and we set the saved
4002 * address to NULL as well.
4003 */
4004 regs[rd] = 0;
4005 mstate->dtms_strtok = 0;
4006 break;
4007 }
4008
4009 /*
4010 * From here on, we're copying into the destination string.
4011 */
4012 for (i = 0; addr < limit && i < size - 1; addr++) {
4013 if ((c = dtrace_load8(addr)) == '\0')
4014 break;
4015
4016 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4017 break;
4018
4019 ASSERT(i < size);
4020 dest[i++] = c;
4021 }
4022
4023 ASSERT(i < size);
4024 dest[i] = '\0';
4025 regs[rd] = (uintptr_t)dest;
4026 mstate->dtms_scratch_ptr += size;
4027 mstate->dtms_strtok = addr;
4028 break;
4029 }
4030
4031 case DIF_SUBR_SUBSTR: {
4032 uintptr_t s = tupregs[0].dttk_value;
4033 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4034 char *d = (char *)mstate->dtms_scratch_ptr;
4035 int64_t index = (int64_t)tupregs[1].dttk_value;
4036 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4037 size_t len = dtrace_strlen((char *)s, size);
4038 int64_t i = 0;
4039
4040 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4041 regs[rd] = 0;
4042 break;
4043 }
4044
4045 if (!DTRACE_INSCRATCH(mstate, size)) {
4046 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4047 regs[rd] = 0;
4048 break;
4049 }
4050
4051 if (nargs <= 2)
4052 remaining = (int64_t)size;
4053
4054 if (index < 0) {
4055 index += len;
4056
4057 if (index < 0 && index + remaining > 0) {
4058 remaining += index;
4059 index = 0;
4060 }
4061 }
4062
4063 if ((size_t)index >= len || index < 0) {
4064 remaining = 0;
4065 } else if (remaining < 0) {
4066 remaining += len - index;
4067 } else if ((uint64_t)index + (uint64_t)remaining > size) {
4068 remaining = size - index;
4069 }
4070
4071 for (i = 0; i < remaining; i++) {
4072 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4073 break;
4074 }
4075
4076 d[i] = '\0';
4077
4078 mstate->dtms_scratch_ptr += size;
4079 regs[rd] = (uintptr_t)d;
4080 break;
4081 }
4082
4083 case DIF_SUBR_GETMAJOR:
4084 regs[rd] = (uintptr_t)major( (dev_t)tupregs[0].dttk_value );
4085 break;
4086
4087 case DIF_SUBR_GETMINOR:
4088 regs[rd] = (uintptr_t)minor( (dev_t)tupregs[0].dttk_value );
4089 break;
4090
4091 case DIF_SUBR_DDI_PATHNAME: {
4092 /* APPLE NOTE: currently unsupported on Darwin */
4093 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4094 regs[rd] = 0;
4095 break;
4096 }
4097
4098 case DIF_SUBR_STRJOIN: {
4099 char *d = (char *)mstate->dtms_scratch_ptr;
4100 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4101 uintptr_t s1 = tupregs[0].dttk_value;
4102 uintptr_t s2 = tupregs[1].dttk_value;
4103 uint64_t i = 0;
4104
4105 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4106 !dtrace_strcanload(s2, size, mstate, vstate)) {
4107 regs[rd] = 0;
4108 break;
4109 }
4110
4111 if (!DTRACE_INSCRATCH(mstate, size)) {
4112 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4113 regs[rd] = 0;
4114 break;
4115 }
4116
4117 for (;;) {
4118 if (i >= size) {
4119 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4120 regs[rd] = 0;
4121 break;
4122 }
4123
4124 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4125 i--;
4126 break;
4127 }
4128 }
4129
4130 for (;;) {
4131 if (i >= size) {
4132 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4133 regs[rd] = 0;
4134 break;
4135 }
4136
4137 if ((d[i++] = dtrace_load8(s2++)) == '\0')
4138 break;
4139 }
4140
4141 if (i < size) {
4142 mstate->dtms_scratch_ptr += i;
4143 regs[rd] = (uintptr_t)d;
4144 }
4145
4146 break;
4147 }
4148
4149 case DIF_SUBR_LLTOSTR: {
4150 int64_t i = (int64_t)tupregs[0].dttk_value;
4151 int64_t val = i < 0 ? i * -1 : i;
4152 uint64_t size = 22; /* enough room for 2^64 in decimal */
4153 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4154
4155 if (!DTRACE_INSCRATCH(mstate, size)) {
4156 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4157 regs[rd] = 0;
4158 break;
4159 }
4160
4161 for (*end-- = '\0'; val; val /= 10)
4162 *end-- = '0' + (val % 10);
4163
4164 if (i == 0)
4165 *end-- = '0';
4166
4167 if (i < 0)
4168 *end-- = '-';
4169
4170 regs[rd] = (uintptr_t)end + 1;
4171 mstate->dtms_scratch_ptr += size;
4172 break;
4173 }
4174
4175 case DIF_SUBR_HTONS:
4176 case DIF_SUBR_NTOHS:
4177 #ifdef _BIG_ENDIAN
4178 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4179 #else
4180 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4181 #endif
4182 break;
4183
4184
4185 case DIF_SUBR_HTONL:
4186 case DIF_SUBR_NTOHL:
4187 #ifdef _BIG_ENDIAN
4188 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4189 #else
4190 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4191 #endif
4192 break;
4193
4194
4195 case DIF_SUBR_HTONLL:
4196 case DIF_SUBR_NTOHLL:
4197 #ifdef _BIG_ENDIAN
4198 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4199 #else
4200 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4201 #endif
4202 break;
4203
4204
4205 case DIF_SUBR_DIRNAME:
4206 case DIF_SUBR_BASENAME: {
4207 char *dest = (char *)mstate->dtms_scratch_ptr;
4208 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4209 uintptr_t src = tupregs[0].dttk_value;
4210 int i, j, len = dtrace_strlen((char *)src, size);
4211 int lastbase = -1, firstbase = -1, lastdir = -1;
4212 int start, end;
4213
4214 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4215 regs[rd] = 0;
4216 break;
4217 }
4218
4219 if (!DTRACE_INSCRATCH(mstate, size)) {
4220 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4221 regs[rd] = 0;
4222 break;
4223 }
4224
4225 /*
4226 * The basename and dirname for a zero-length string is
4227 * defined to be "."
4228 */
4229 if (len == 0) {
4230 len = 1;
4231 src = (uintptr_t)".";
4232 }
4233
4234 /*
4235 * Start from the back of the string, moving back toward the
4236 * front until we see a character that isn't a slash. That
4237 * character is the last character in the basename.
4238 */
4239 for (i = len - 1; i >= 0; i--) {
4240 if (dtrace_load8(src + i) != '/')
4241 break;
4242 }
4243
4244 if (i >= 0)
4245 lastbase = i;
4246
4247 /*
4248 * Starting from the last character in the basename, move
4249 * towards the front until we find a slash. The character
4250 * that we processed immediately before that is the first
4251 * character in the basename.
4252 */
4253 for (; i >= 0; i--) {
4254 if (dtrace_load8(src + i) == '/')
4255 break;
4256 }
4257
4258 if (i >= 0)
4259 firstbase = i + 1;
4260
4261 /*
4262 * Now keep going until we find a non-slash character. That
4263 * character is the last character in the dirname.
4264 */
4265 for (; i >= 0; i--) {
4266 if (dtrace_load8(src + i) != '/')
4267 break;
4268 }
4269
4270 if (i >= 0)
4271 lastdir = i;
4272
4273 ASSERT(!(lastbase == -1 && firstbase != -1));
4274 ASSERT(!(firstbase == -1 && lastdir != -1));
4275
4276 if (lastbase == -1) {
4277 /*
4278 * We didn't find a non-slash character. We know that
4279 * the length is non-zero, so the whole string must be
4280 * slashes. In either the dirname or the basename
4281 * case, we return '/'.
4282 */
4283 ASSERT(firstbase == -1);
4284 firstbase = lastbase = lastdir = 0;
4285 }
4286
4287 if (firstbase == -1) {
4288 /*
4289 * The entire string consists only of a basename
4290 * component. If we're looking for dirname, we need
4291 * to change our string to be just "."; if we're
4292 * looking for a basename, we'll just set the first
4293 * character of the basename to be 0.
4294 */
4295 if (subr == DIF_SUBR_DIRNAME) {
4296 ASSERT(lastdir == -1);
4297 src = (uintptr_t)".";
4298 lastdir = 0;
4299 } else {
4300 firstbase = 0;
4301 }
4302 }
4303
4304 if (subr == DIF_SUBR_DIRNAME) {
4305 if (lastdir == -1) {
4306 /*
4307 * We know that we have a slash in the name --
4308 * or lastdir would be set to 0, above. And
4309 * because lastdir is -1, we know that this
4310 * slash must be the first character. (That
4311 * is, the full string must be of the form
4312 * "/basename".) In this case, the last
4313 * character of the directory name is 0.
4314 */
4315 lastdir = 0;
4316 }
4317
4318 start = 0;
4319 end = lastdir;
4320 } else {
4321 ASSERT(subr == DIF_SUBR_BASENAME);
4322 ASSERT(firstbase != -1 && lastbase != -1);
4323 start = firstbase;
4324 end = lastbase;
4325 }
4326
4327 for (i = start, j = 0; i <= end && (uint64_t)j < size - 1; i++, j++)
4328 dest[j] = dtrace_load8(src + i);
4329
4330 dest[j] = '\0';
4331 regs[rd] = (uintptr_t)dest;
4332 mstate->dtms_scratch_ptr += size;
4333 break;
4334 }
4335
4336 case DIF_SUBR_CLEANPATH: {
4337 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4338 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4339 uintptr_t src = tupregs[0].dttk_value;
4340 int i = 0, j = 0;
4341
4342 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4343 regs[rd] = 0;
4344 break;
4345 }
4346
4347 if (!DTRACE_INSCRATCH(mstate, size)) {
4348 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4349 regs[rd] = 0;
4350 break;
4351 }
4352
4353 /*
4354 * Move forward, loading each character.
4355 */
4356 do {
4357 c = dtrace_load8(src + i++);
4358 next:
4359 if ((uint64_t)(j + 5) >= size) /* 5 = strlen("/..c\0") */
4360 break;
4361
4362 if (c != '/') {
4363 dest[j++] = c;
4364 continue;
4365 }
4366
4367 c = dtrace_load8(src + i++);
4368
4369 if (c == '/') {
4370 /*
4371 * We have two slashes -- we can just advance
4372 * to the next character.
4373 */
4374 goto next;
4375 }
4376
4377 if (c != '.') {
4378 /*
4379 * This is not "." and it's not ".." -- we can
4380 * just store the "/" and this character and
4381 * drive on.
4382 */
4383 dest[j++] = '/';
4384 dest[j++] = c;
4385 continue;
4386 }
4387
4388 c = dtrace_load8(src + i++);
4389
4390 if (c == '/') {
4391 /*
4392 * This is a "/./" component. We're not going
4393 * to store anything in the destination buffer;
4394 * we're just going to go to the next component.
4395 */
4396 goto next;
4397 }
4398
4399 if (c != '.') {
4400 /*
4401 * This is not ".." -- we can just store the
4402 * "/." and this character and continue
4403 * processing.
4404 */
4405 dest[j++] = '/';
4406 dest[j++] = '.';
4407 dest[j++] = c;
4408 continue;
4409 }
4410
4411 c = dtrace_load8(src + i++);
4412
4413 if (c != '/' && c != '\0') {
4414 /*
4415 * This is not ".." -- it's "..[mumble]".
4416 * We'll store the "/.." and this character
4417 * and continue processing.
4418 */
4419 dest[j++] = '/';
4420 dest[j++] = '.';
4421 dest[j++] = '.';
4422 dest[j++] = c;
4423 continue;
4424 }
4425
4426 /*
4427 * This is "/../" or "/..\0". We need to back up
4428 * our destination pointer until we find a "/".
4429 */
4430 i--;
4431 while (j != 0 && dest[--j] != '/')
4432 continue;
4433
4434 if (c == '\0')
4435 dest[++j] = '/';
4436 } while (c != '\0');
4437
4438 dest[j] = '\0';
4439 regs[rd] = (uintptr_t)dest;
4440 mstate->dtms_scratch_ptr += size;
4441 break;
4442 }
4443
4444 case DIF_SUBR_INET_NTOA:
4445 case DIF_SUBR_INET_NTOA6:
4446 case DIF_SUBR_INET_NTOP: {
4447 size_t size;
4448 int af, argi, i;
4449 char *base, *end;
4450
4451 if (subr == DIF_SUBR_INET_NTOP) {
4452 af = (int)tupregs[0].dttk_value;
4453 argi = 1;
4454 } else {
4455 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4456 argi = 0;
4457 }
4458
4459 if (af == AF_INET) {
4460 #if !defined(__APPLE__)
4461 ipaddr_t ip4;
4462 #else
4463 uint32_t ip4;
4464 #endif /* __APPLE__ */
4465 uint8_t *ptr8, val;
4466
4467 /*
4468 * Safely load the IPv4 address.
4469 */
4470 #if !defined(__APPLE__)
4471 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4472 #else
4473 dtrace_bcopy(
4474 (void *)(uintptr_t)tupregs[argi].dttk_value,
4475 (void *)(uintptr_t)&ip4, sizeof (ip4));
4476 #endif /* __APPLE__ */
4477 /*
4478 * Check an IPv4 string will fit in scratch.
4479 */
4480 #if !defined(__APPLE__)
4481 size = INET_ADDRSTRLEN;
4482 #else
4483 size = MAX_IPv4_STR_LEN;
4484 #endif /* __APPLE__ */
4485 if (!DTRACE_INSCRATCH(mstate, size)) {
4486 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4487 regs[rd] = 0;
4488 break;
4489 }
4490 base = (char *)mstate->dtms_scratch_ptr;
4491 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4492
4493 /*
4494 * Stringify as a dotted decimal quad.
4495 */
4496 *end-- = '\0';
4497 ptr8 = (uint8_t *)&ip4;
4498 for (i = 3; i >= 0; i--) {
4499 val = ptr8[i];
4500
4501 if (val == 0) {
4502 *end-- = '0';
4503 } else {
4504 for (; val; val /= 10) {
4505 *end-- = '0' + (val % 10);
4506 }
4507 }
4508
4509 if (i > 0)
4510 *end-- = '.';
4511 }
4512 ASSERT(end + 1 >= base);
4513
4514 } else if (af == AF_INET6) {
4515 #if defined(__APPLE__)
4516 #define _S6_un __u6_addr
4517 #define _S6_u8 __u6_addr8
4518 #endif /* __APPLE__ */
4519 struct in6_addr ip6;
4520 int firstzero, tryzero, numzero, v6end;
4521 uint16_t val;
4522 const char digits[] = "0123456789abcdef";
4523
4524 /*
4525 * Stringify using RFC 1884 convention 2 - 16 bit
4526 * hexadecimal values with a zero-run compression.
4527 * Lower case hexadecimal digits are used.
4528 * eg, fe80::214:4fff:fe0b:76c8.
4529 * The IPv4 embedded form is returned for inet_ntop,
4530 * just the IPv4 string is returned for inet_ntoa6.
4531 */
4532
4533 /*
4534 * Safely load the IPv6 address.
4535 */
4536 dtrace_bcopy(
4537 (void *)(uintptr_t)tupregs[argi].dttk_value,
4538 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4539
4540 /*
4541 * Check an IPv6 string will fit in scratch.
4542 */
4543 size = INET6_ADDRSTRLEN;
4544 if (!DTRACE_INSCRATCH(mstate, size)) {
4545 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4546 regs[rd] = 0;
4547 break;
4548 }
4549 base = (char *)mstate->dtms_scratch_ptr;
4550 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4551 *end-- = '\0';
4552
4553 /*
4554 * Find the longest run of 16 bit zero values
4555 * for the single allowed zero compression - "::".
4556 */
4557 firstzero = -1;
4558 tryzero = -1;
4559 numzero = 1;
4560 for (i = 0; i < (int)sizeof (struct in6_addr); i++) {
4561 if (ip6._S6_un._S6_u8[i] == 0 &&
4562 tryzero == -1 && i % 2 == 0) {
4563 tryzero = i;
4564 continue;
4565 }
4566
4567 if (tryzero != -1 &&
4568 (ip6._S6_un._S6_u8[i] != 0 ||
4569 i == sizeof (struct in6_addr) - 1)) {
4570
4571 if (i - tryzero <= numzero) {
4572 tryzero = -1;
4573 continue;
4574 }
4575
4576 firstzero = tryzero;
4577 numzero = i - i % 2 - tryzero;
4578 tryzero = -1;
4579
4580 if (ip6._S6_un._S6_u8[i] == 0 &&
4581 i == sizeof (struct in6_addr) - 1)
4582 numzero += 2;
4583 }
4584 }
4585 ASSERT(firstzero + numzero <= (int)sizeof (struct in6_addr));
4586
4587 /*
4588 * Check for an IPv4 embedded address.
4589 */
4590 v6end = sizeof (struct in6_addr) - 2;
4591 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4592 IN6_IS_ADDR_V4COMPAT(&ip6)) {
4593 for (i = sizeof (struct in6_addr) - 1;
4594 i >= (int)DTRACE_V4MAPPED_OFFSET; i--) {
4595 ASSERT(end >= base);
4596
4597 val = ip6._S6_un._S6_u8[i];
4598
4599 if (val == 0) {
4600 *end-- = '0';
4601 } else {
4602 for (; val; val /= 10) {
4603 *end-- = '0' + val % 10;
4604 }
4605 }
4606
4607 if (i > (int)DTRACE_V4MAPPED_OFFSET)
4608 *end-- = '.';
4609 }
4610
4611 if (subr == DIF_SUBR_INET_NTOA6)
4612 goto inetout;
4613
4614 /*
4615 * Set v6end to skip the IPv4 address that
4616 * we have already stringified.
4617 */
4618 v6end = 10;
4619 }
4620
4621 /*
4622 * Build the IPv6 string by working through the
4623 * address in reverse.
4624 */
4625 for (i = v6end; i >= 0; i -= 2) {
4626 ASSERT(end >= base);
4627
4628 if (i == firstzero + numzero - 2) {
4629 *end-- = ':';
4630 *end-- = ':';
4631 i -= numzero - 2;
4632 continue;
4633 }
4634
4635 if (i < 14 && i != firstzero - 2)
4636 *end-- = ':';
4637
4638 val = (ip6._S6_un._S6_u8[i] << 8) +
4639 ip6._S6_un._S6_u8[i + 1];
4640
4641 if (val == 0) {
4642 *end-- = '0';
4643 } else {
4644 for (; val; val /= 16) {
4645 *end-- = digits[val % 16];
4646 }
4647 }
4648 }
4649 ASSERT(end + 1 >= base);
4650
4651 #if defined(__APPLE__)
4652 #undef _S6_un
4653 #undef _S6_u8
4654 #endif /* __APPLE__ */
4655 } else {
4656 /*
4657 * The user didn't use AH_INET or AH_INET6.
4658 */
4659 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4660 regs[rd] = 0;
4661 break;
4662 }
4663
4664 inetout: regs[rd] = (uintptr_t)end + 1;
4665 mstate->dtms_scratch_ptr += size;
4666 break;
4667 }
4668
4669 case DIF_SUBR_TOUPPER:
4670 case DIF_SUBR_TOLOWER: {
4671 uintptr_t src = tupregs[0].dttk_value;
4672 char *dest = (char *)mstate->dtms_scratch_ptr;
4673 char lower, upper, base, c;
4674 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4675 size_t len = dtrace_strlen((char*) src, size);
4676 size_t i = 0;
4677
4678 lower = (subr == DIF_SUBR_TOUPPER) ? 'a' : 'A';
4679 upper = (subr == DIF_SUBR_TOUPPER) ? 'z' : 'Z';
4680 base = (subr == DIF_SUBR_TOUPPER) ? 'A' : 'a';
4681
4682 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4683 regs[rd] = 0;
4684 break;
4685 }
4686
4687 if (!DTRACE_INSCRATCH(mstate, size)) {
4688 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4689 regs[rd] = 0;
4690 break;
4691 }
4692
4693 for (i = 0; i < size - 1; ++i) {
4694 if ((c = dtrace_load8(src + i)) == '\0')
4695 break;
4696 if (c >= lower && c <= upper)
4697 c = base + (c - lower);
4698 dest[i] = c;
4699 }
4700
4701 ASSERT(i < size);
4702
4703 dest[i] = '\0';
4704 regs[rd] = (uintptr_t) dest;
4705 mstate->dtms_scratch_ptr += size;
4706
4707 break;
4708 }
4709
4710 /*
4711 * APPLE NOTE:
4712 * CoreProfile callback ('core_profile (uint64_t, [uint64_t], [uint64_t] ...)')
4713 */
4714 case DIF_SUBR_COREPROFILE: {
4715 uint64_t selector = tupregs[0].dttk_value;
4716 uint64_t args[DIF_DTR_NREGS-1] = {0ULL};
4717 uint32_t ii;
4718 uint32_t count = (uint32_t)nargs;
4719
4720 if (count < 1) {
4721 regs[rd] = KERN_FAILURE;
4722 break;
4723 }
4724
4725 if(count > DIF_DTR_NREGS)
4726 count = DIF_DTR_NREGS;
4727
4728 /* copy in any variadic argument list, bounded by DIF_DTR_NREGS */
4729 for(ii = 0; ii < count-1; ii++) {
4730 args[ii] = tupregs[ii+1].dttk_value;
4731 }
4732
4733 kern_return_t ret =
4734 chudxnu_dtrace_callback(selector, args, count-1);
4735 if(KERN_SUCCESS != ret) {
4736 /* error */
4737 }
4738
4739 regs[rd] = ret;
4740 break;
4741 }
4742 }
4743 }
4744
4745 /*
4746 * Emulate the execution of DTrace IR instructions specified by the given
4747 * DIF object. This function is deliberately void of assertions as all of
4748 * the necessary checks are handled by a call to dtrace_difo_validate().
4749 */
4750 static uint64_t
4751 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4752 dtrace_vstate_t *vstate, dtrace_state_t *state)
4753 {
4754 const dif_instr_t *text = difo->dtdo_buf;
4755 const uint_t textlen = difo->dtdo_len;
4756 const char *strtab = difo->dtdo_strtab;
4757 const uint64_t *inttab = difo->dtdo_inttab;
4758
4759 uint64_t rval = 0;
4760 dtrace_statvar_t *svar;
4761 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4762 dtrace_difv_t *v;
4763 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4764 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4765
4766 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4767 uint64_t regs[DIF_DIR_NREGS];
4768 uint64_t *tmp;
4769
4770 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4771 int64_t cc_r;
4772 uint_t pc = 0, id, opc = 0;
4773 uint8_t ttop = 0;
4774 dif_instr_t instr;
4775 uint_t r1, r2, rd;
4776
4777 /*
4778 * We stash the current DIF object into the machine state: we need it
4779 * for subsequent access checking.
4780 */
4781 mstate->dtms_difo = difo;
4782
4783 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
4784
4785 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4786 opc = pc;
4787
4788 instr = text[pc++];
4789 r1 = DIF_INSTR_R1(instr);
4790 r2 = DIF_INSTR_R2(instr);
4791 rd = DIF_INSTR_RD(instr);
4792
4793 switch (DIF_INSTR_OP(instr)) {
4794 case DIF_OP_OR:
4795 regs[rd] = regs[r1] | regs[r2];
4796 break;
4797 case DIF_OP_XOR:
4798 regs[rd] = regs[r1] ^ regs[r2];
4799 break;
4800 case DIF_OP_AND:
4801 regs[rd] = regs[r1] & regs[r2];
4802 break;
4803 case DIF_OP_SLL:
4804 regs[rd] = regs[r1] << regs[r2];
4805 break;
4806 case DIF_OP_SRL:
4807 regs[rd] = regs[r1] >> regs[r2];
4808 break;
4809 case DIF_OP_SUB:
4810 regs[rd] = regs[r1] - regs[r2];
4811 break;
4812 case DIF_OP_ADD:
4813 regs[rd] = regs[r1] + regs[r2];
4814 break;
4815 case DIF_OP_MUL:
4816 regs[rd] = regs[r1] * regs[r2];
4817 break;
4818 case DIF_OP_SDIV:
4819 if (regs[r2] == 0) {
4820 regs[rd] = 0;
4821 *flags |= CPU_DTRACE_DIVZERO;
4822 } else {
4823 regs[rd] = (int64_t)regs[r1] /
4824 (int64_t)regs[r2];
4825 }
4826 break;
4827
4828 case DIF_OP_UDIV:
4829 if (regs[r2] == 0) {
4830 regs[rd] = 0;
4831 *flags |= CPU_DTRACE_DIVZERO;
4832 } else {
4833 regs[rd] = regs[r1] / regs[r2];
4834 }
4835 break;
4836
4837 case DIF_OP_SREM:
4838 if (regs[r2] == 0) {
4839 regs[rd] = 0;
4840 *flags |= CPU_DTRACE_DIVZERO;
4841 } else {
4842 regs[rd] = (int64_t)regs[r1] %
4843 (int64_t)regs[r2];
4844 }
4845 break;
4846
4847 case DIF_OP_UREM:
4848 if (regs[r2] == 0) {
4849 regs[rd] = 0;
4850 *flags |= CPU_DTRACE_DIVZERO;
4851 } else {
4852 regs[rd] = regs[r1] % regs[r2];
4853 }
4854 break;
4855
4856 case DIF_OP_NOT:
4857 regs[rd] = ~regs[r1];
4858 break;
4859 case DIF_OP_MOV:
4860 regs[rd] = regs[r1];
4861 break;
4862 case DIF_OP_CMP:
4863 cc_r = regs[r1] - regs[r2];
4864 cc_n = cc_r < 0;
4865 cc_z = cc_r == 0;
4866 cc_v = 0;
4867 cc_c = regs[r1] < regs[r2];
4868 break;
4869 case DIF_OP_TST:
4870 cc_n = cc_v = cc_c = 0;
4871 cc_z = regs[r1] == 0;
4872 break;
4873 case DIF_OP_BA:
4874 pc = DIF_INSTR_LABEL(instr);
4875 break;
4876 case DIF_OP_BE:
4877 if (cc_z)
4878 pc = DIF_INSTR_LABEL(instr);
4879 break;
4880 case DIF_OP_BNE:
4881 if (cc_z == 0)
4882 pc = DIF_INSTR_LABEL(instr);
4883 break;
4884 case DIF_OP_BG:
4885 if ((cc_z | (cc_n ^ cc_v)) == 0)
4886 pc = DIF_INSTR_LABEL(instr);
4887 break;
4888 case DIF_OP_BGU:
4889 if ((cc_c | cc_z) == 0)
4890 pc = DIF_INSTR_LABEL(instr);
4891 break;
4892 case DIF_OP_BGE:
4893 if ((cc_n ^ cc_v) == 0)
4894 pc = DIF_INSTR_LABEL(instr);
4895 break;
4896 case DIF_OP_BGEU:
4897 if (cc_c == 0)
4898 pc = DIF_INSTR_LABEL(instr);
4899 break;
4900 case DIF_OP_BL:
4901 if (cc_n ^ cc_v)
4902 pc = DIF_INSTR_LABEL(instr);
4903 break;
4904 case DIF_OP_BLU:
4905 if (cc_c)
4906 pc = DIF_INSTR_LABEL(instr);
4907 break;
4908 case DIF_OP_BLE:
4909 if (cc_z | (cc_n ^ cc_v))
4910 pc = DIF_INSTR_LABEL(instr);
4911 break;
4912 case DIF_OP_BLEU:
4913 if (cc_c | cc_z)
4914 pc = DIF_INSTR_LABEL(instr);
4915 break;
4916 case DIF_OP_RLDSB:
4917 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4918 *flags |= CPU_DTRACE_KPRIV;
4919 *illval = regs[r1];
4920 break;
4921 }
4922 /*FALLTHROUGH*/
4923 case DIF_OP_LDSB:
4924 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4925 break;
4926 case DIF_OP_RLDSH:
4927 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4928 *flags |= CPU_DTRACE_KPRIV;
4929 *illval = regs[r1];
4930 break;
4931 }
4932 /*FALLTHROUGH*/
4933 case DIF_OP_LDSH:
4934 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4935 break;
4936 case DIF_OP_RLDSW:
4937 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4938 *flags |= CPU_DTRACE_KPRIV;
4939 *illval = regs[r1];
4940 break;
4941 }
4942 /*FALLTHROUGH*/
4943 case DIF_OP_LDSW:
4944 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4945 break;
4946 case DIF_OP_RLDUB:
4947 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4948 *flags |= CPU_DTRACE_KPRIV;
4949 *illval = regs[r1];
4950 break;
4951 }
4952 /*FALLTHROUGH*/
4953 case DIF_OP_LDUB:
4954 regs[rd] = dtrace_load8(regs[r1]);
4955 break;
4956 case DIF_OP_RLDUH:
4957 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4958 *flags |= CPU_DTRACE_KPRIV;
4959 *illval = regs[r1];
4960 break;
4961 }
4962 /*FALLTHROUGH*/
4963 case DIF_OP_LDUH:
4964 regs[rd] = dtrace_load16(regs[r1]);
4965 break;
4966 case DIF_OP_RLDUW:
4967 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4968 *flags |= CPU_DTRACE_KPRIV;
4969 *illval = regs[r1];
4970 break;
4971 }
4972 /*FALLTHROUGH*/
4973 case DIF_OP_LDUW:
4974 regs[rd] = dtrace_load32(regs[r1]);
4975 break;
4976 case DIF_OP_RLDX:
4977 if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4978 *flags |= CPU_DTRACE_KPRIV;
4979 *illval = regs[r1];
4980 break;
4981 }
4982 /*FALLTHROUGH*/
4983 case DIF_OP_LDX:
4984 regs[rd] = dtrace_load64(regs[r1]);
4985 break;
4986 /*
4987 * Darwin 32-bit kernel may fetch from 64-bit user.
4988 * Do not cast regs to uintptr_t
4989 * DIF_OP_ULDSB,DIF_OP_ULDSH, DIF_OP_ULDSW, DIF_OP_ULDUB
4990 * DIF_OP_ULDUH, DIF_OP_ULDUW, DIF_OP_ULDX
4991 */
4992 case DIF_OP_ULDSB:
4993 regs[rd] = (int8_t)
4994 dtrace_fuword8(regs[r1]);
4995 break;
4996 case DIF_OP_ULDSH:
4997 regs[rd] = (int16_t)
4998 dtrace_fuword16(regs[r1]);
4999 break;
5000 case DIF_OP_ULDSW:
5001 regs[rd] = (int32_t)
5002 dtrace_fuword32(regs[r1]);
5003 break;
5004 case DIF_OP_ULDUB:
5005 regs[rd] =
5006 dtrace_fuword8(regs[r1]);
5007 break;
5008 case DIF_OP_ULDUH:
5009 regs[rd] =
5010 dtrace_fuword16(regs[r1]);
5011 break;
5012 case DIF_OP_ULDUW:
5013 regs[rd] =
5014 dtrace_fuword32(regs[r1]);
5015 break;
5016 case DIF_OP_ULDX:
5017 regs[rd] =
5018 dtrace_fuword64(regs[r1]);
5019 break;
5020 case DIF_OP_RET:
5021 rval = regs[rd];
5022 pc = textlen;
5023 break;
5024 case DIF_OP_NOP:
5025 break;
5026 case DIF_OP_SETX:
5027 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5028 break;
5029 case DIF_OP_SETS:
5030 regs[rd] = (uint64_t)(uintptr_t)
5031 (strtab + DIF_INSTR_STRING(instr));
5032 break;
5033 case DIF_OP_SCMP: {
5034 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5035 uintptr_t s1 = regs[r1];
5036 uintptr_t s2 = regs[r2];
5037
5038 if (s1 != 0 &&
5039 !dtrace_strcanload(s1, sz, mstate, vstate))
5040 break;
5041 if (s2 != 0 &&
5042 !dtrace_strcanload(s2, sz, mstate, vstate))
5043 break;
5044
5045 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5046
5047 cc_n = cc_r < 0;
5048 cc_z = cc_r == 0;
5049 cc_v = cc_c = 0;
5050 break;
5051 }
5052 case DIF_OP_LDGA:
5053 regs[rd] = dtrace_dif_variable(mstate, state,
5054 r1, regs[r2]);
5055 break;
5056 case DIF_OP_LDGS:
5057 id = DIF_INSTR_VAR(instr);
5058
5059 if (id >= DIF_VAR_OTHER_UBASE) {
5060 uintptr_t a;
5061
5062 id -= DIF_VAR_OTHER_UBASE;
5063 svar = vstate->dtvs_globals[id];
5064 ASSERT(svar != NULL);
5065 v = &svar->dtsv_var;
5066
5067 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5068 regs[rd] = svar->dtsv_data;
5069 break;
5070 }
5071
5072 a = (uintptr_t)svar->dtsv_data;
5073
5074 if (*(uint8_t *)a == UINT8_MAX) {
5075 /*
5076 * If the 0th byte is set to UINT8_MAX
5077 * then this is to be treated as a
5078 * reference to a NULL variable.
5079 */
5080 regs[rd] = 0;
5081 } else {
5082 regs[rd] = a + sizeof (uint64_t);
5083 }
5084
5085 break;
5086 }
5087
5088 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5089 break;
5090
5091 case DIF_OP_STGS:
5092 id = DIF_INSTR_VAR(instr);
5093
5094 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5095 id -= DIF_VAR_OTHER_UBASE;
5096
5097 svar = vstate->dtvs_globals[id];
5098 ASSERT(svar != NULL);
5099 v = &svar->dtsv_var;
5100
5101 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5102 uintptr_t a = (uintptr_t)svar->dtsv_data;
5103
5104 ASSERT(a != 0);
5105 ASSERT(svar->dtsv_size != 0);
5106
5107 if (regs[rd] == 0) {
5108 *(uint8_t *)a = UINT8_MAX;
5109 break;
5110 } else {
5111 *(uint8_t *)a = 0;
5112 a += sizeof (uint64_t);
5113 }
5114 if (!dtrace_vcanload(
5115 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5116 mstate, vstate))
5117 break;
5118
5119 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5120 (void *)a, &v->dtdv_type);
5121 break;
5122 }
5123
5124 svar->dtsv_data = regs[rd];
5125 break;
5126
5127 case DIF_OP_LDTA:
5128 /*
5129 * There are no DTrace built-in thread-local arrays at
5130 * present. This opcode is saved for future work.
5131 */
5132 *flags |= CPU_DTRACE_ILLOP;
5133 regs[rd] = 0;
5134 break;
5135
5136 case DIF_OP_LDLS:
5137 id = DIF_INSTR_VAR(instr);
5138
5139 if (id < DIF_VAR_OTHER_UBASE) {
5140 /*
5141 * For now, this has no meaning.
5142 */
5143 regs[rd] = 0;
5144 break;
5145 }
5146
5147 id -= DIF_VAR_OTHER_UBASE;
5148
5149 ASSERT(id < (uint_t)vstate->dtvs_nlocals);
5150 ASSERT(vstate->dtvs_locals != NULL);
5151 svar = vstate->dtvs_locals[id];
5152 ASSERT(svar != NULL);
5153 v = &svar->dtsv_var;
5154
5155 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5156 uintptr_t a = (uintptr_t)svar->dtsv_data;
5157 size_t sz = v->dtdv_type.dtdt_size;
5158
5159 sz += sizeof (uint64_t);
5160 ASSERT(svar->dtsv_size == (int)NCPU * sz);
5161 a += CPU->cpu_id * sz;
5162
5163 if (*(uint8_t *)a == UINT8_MAX) {
5164 /*
5165 * If the 0th byte is set to UINT8_MAX
5166 * then this is to be treated as a
5167 * reference to a NULL variable.
5168 */
5169 regs[rd] = 0;
5170 } else {
5171 regs[rd] = a + sizeof (uint64_t);
5172 }
5173
5174 break;
5175 }
5176
5177 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5178 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5179 regs[rd] = tmp[CPU->cpu_id];
5180 break;
5181
5182 case DIF_OP_STLS:
5183 id = DIF_INSTR_VAR(instr);
5184
5185 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5186 id -= DIF_VAR_OTHER_UBASE;
5187 ASSERT(id < (uint_t)vstate->dtvs_nlocals);
5188 ASSERT(vstate->dtvs_locals != NULL);
5189 svar = vstate->dtvs_locals[id];
5190 ASSERT(svar != NULL);
5191 v = &svar->dtsv_var;
5192
5193 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5194 uintptr_t a = (uintptr_t)svar->dtsv_data;
5195 size_t sz = v->dtdv_type.dtdt_size;
5196
5197 sz += sizeof (uint64_t);
5198 ASSERT(svar->dtsv_size == (int)NCPU * sz);
5199 a += CPU->cpu_id * sz;
5200
5201 if (regs[rd] == 0) {
5202 *(uint8_t *)a = UINT8_MAX;
5203 break;
5204 } else {
5205 *(uint8_t *)a = 0;
5206 a += sizeof (uint64_t);
5207 }
5208
5209 if (!dtrace_vcanload(
5210 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5211 mstate, vstate))
5212 break;
5213
5214 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5215 (void *)a, &v->dtdv_type);
5216 break;
5217 }
5218
5219 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5220 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5221 tmp[CPU->cpu_id] = regs[rd];
5222 break;
5223
5224 case DIF_OP_LDTS: {
5225 dtrace_dynvar_t *dvar;
5226 dtrace_key_t *key;
5227
5228 id = DIF_INSTR_VAR(instr);
5229 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5230 id -= DIF_VAR_OTHER_UBASE;
5231 v = &vstate->dtvs_tlocals[id];
5232
5233 key = &tupregs[DIF_DTR_NREGS];
5234 key[0].dttk_value = (uint64_t)id;
5235 key[0].dttk_size = 0;
5236 DTRACE_TLS_THRKEY(key[1].dttk_value);
5237 key[1].dttk_size = 0;
5238
5239 dvar = dtrace_dynvar(dstate, 2, key,
5240 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5241 mstate, vstate);
5242
5243 if (dvar == NULL) {
5244 regs[rd] = 0;
5245 break;
5246 }
5247
5248 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5249 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5250 } else {
5251 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5252 }
5253
5254 break;
5255 }
5256
5257 case DIF_OP_STTS: {
5258 dtrace_dynvar_t *dvar;
5259 dtrace_key_t *key;
5260
5261 id = DIF_INSTR_VAR(instr);
5262 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5263 id -= DIF_VAR_OTHER_UBASE;
5264
5265 key = &tupregs[DIF_DTR_NREGS];
5266 key[0].dttk_value = (uint64_t)id;
5267 key[0].dttk_size = 0;
5268 DTRACE_TLS_THRKEY(key[1].dttk_value);
5269 key[1].dttk_size = 0;
5270 v = &vstate->dtvs_tlocals[id];
5271
5272 dvar = dtrace_dynvar(dstate, 2, key,
5273 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5274 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5275 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5276 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5277
5278 /*
5279 * Given that we're storing to thread-local data,
5280 * we need to flush our predicate cache.
5281 */
5282 dtrace_set_thread_predcache(current_thread(), 0);
5283
5284 if (dvar == NULL)
5285 break;
5286
5287 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5288 if (!dtrace_vcanload(
5289 (void *)(uintptr_t)regs[rd],
5290 &v->dtdv_type, mstate, vstate))
5291 break;
5292
5293 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5294 dvar->dtdv_data, &v->dtdv_type);
5295 } else {
5296 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5297 }
5298
5299 break;
5300 }
5301
5302 case DIF_OP_SRA:
5303 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5304 break;
5305
5306 case DIF_OP_CALL:
5307 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5308 regs, tupregs, ttop, mstate, state);
5309 break;
5310
5311 case DIF_OP_PUSHTR:
5312 if (ttop == DIF_DTR_NREGS) {
5313 *flags |= CPU_DTRACE_TUPOFLOW;
5314 break;
5315 }
5316
5317 if (r1 == DIF_TYPE_STRING) {
5318 /*
5319 * If this is a string type and the size is 0,
5320 * we'll use the system-wide default string
5321 * size. Note that we are _not_ looking at
5322 * the value of the DTRACEOPT_STRSIZE option;
5323 * had this been set, we would expect to have
5324 * a non-zero size value in the "pushtr".
5325 */
5326 tupregs[ttop].dttk_size =
5327 dtrace_strlen((char *)(uintptr_t)regs[rd],
5328 regs[r2] ? regs[r2] :
5329 dtrace_strsize_default) + 1;
5330 } else {
5331 tupregs[ttop].dttk_size = regs[r2];
5332 }
5333
5334 tupregs[ttop++].dttk_value = regs[rd];
5335 break;
5336
5337 case DIF_OP_PUSHTV:
5338 if (ttop == DIF_DTR_NREGS) {
5339 *flags |= CPU_DTRACE_TUPOFLOW;
5340 break;
5341 }
5342
5343 tupregs[ttop].dttk_value = regs[rd];
5344 tupregs[ttop++].dttk_size = 0;
5345 break;
5346
5347 case DIF_OP_POPTS:
5348 if (ttop != 0)
5349 ttop--;
5350 break;
5351
5352 case DIF_OP_FLUSHTS:
5353 ttop = 0;
5354 break;
5355
5356 case DIF_OP_LDGAA:
5357 case DIF_OP_LDTAA: {
5358 dtrace_dynvar_t *dvar;
5359 dtrace_key_t *key = tupregs;
5360 uint_t nkeys = ttop;
5361
5362 id = DIF_INSTR_VAR(instr);
5363 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5364 id -= DIF_VAR_OTHER_UBASE;
5365
5366 key[nkeys].dttk_value = (uint64_t)id;
5367 key[nkeys++].dttk_size = 0;
5368
5369 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5370 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5371 key[nkeys++].dttk_size = 0;
5372 v = &vstate->dtvs_tlocals[id];
5373 } else {
5374 v = &vstate->dtvs_globals[id]->dtsv_var;
5375 }
5376
5377 dvar = dtrace_dynvar(dstate, nkeys, key,
5378 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5379 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5380 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5381
5382 if (dvar == NULL) {
5383 regs[rd] = 0;
5384 break;
5385 }
5386
5387 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5388 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5389 } else {
5390 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5391 }
5392
5393 break;
5394 }
5395
5396 case DIF_OP_STGAA:
5397 case DIF_OP_STTAA: {
5398 dtrace_dynvar_t *dvar;
5399 dtrace_key_t *key = tupregs;
5400 uint_t nkeys = ttop;
5401
5402 id = DIF_INSTR_VAR(instr);
5403 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5404 id -= DIF_VAR_OTHER_UBASE;
5405
5406 key[nkeys].dttk_value = (uint64_t)id;
5407 key[nkeys++].dttk_size = 0;
5408
5409 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5410 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5411 key[nkeys++].dttk_size = 0;
5412 v = &vstate->dtvs_tlocals[id];
5413 } else {
5414 v = &vstate->dtvs_globals[id]->dtsv_var;
5415 }
5416
5417 dvar = dtrace_dynvar(dstate, nkeys, key,
5418 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5419 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5420 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5421 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5422
5423 if (dvar == NULL)
5424 break;
5425
5426 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5427 if (!dtrace_vcanload(
5428 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5429 mstate, vstate))
5430 break;
5431
5432 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5433 dvar->dtdv_data, &v->dtdv_type);
5434 } else {
5435 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5436 }
5437
5438 break;
5439 }
5440
5441 case DIF_OP_ALLOCS: {
5442 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5443 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5444
5445 /*
5446 * Rounding up the user allocation size could have
5447 * overflowed large, bogus allocations (like -1ULL) to
5448 * 0.
5449 */
5450 if (size < regs[r1] ||
5451 !DTRACE_INSCRATCH(mstate, size)) {
5452 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5453 regs[rd] = 0;
5454 break;
5455 }
5456
5457 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5458 mstate->dtms_scratch_ptr += size;
5459 regs[rd] = ptr;
5460 break;
5461 }
5462
5463 case DIF_OP_COPYS:
5464 if (!dtrace_canstore(regs[rd], regs[r2],
5465 mstate, vstate)) {
5466 *flags |= CPU_DTRACE_BADADDR;
5467 *illval = regs[rd];
5468 break;
5469 }
5470
5471 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5472 break;
5473
5474 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5475 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5476 break;
5477
5478 case DIF_OP_STB:
5479 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5480 *flags |= CPU_DTRACE_BADADDR;
5481 *illval = regs[rd];
5482 break;
5483 }
5484 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5485 break;
5486
5487 case DIF_OP_STH:
5488 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5489 *flags |= CPU_DTRACE_BADADDR;
5490 *illval = regs[rd];
5491 break;
5492 }
5493 if (regs[rd] & 1) {
5494 *flags |= CPU_DTRACE_BADALIGN;
5495 *illval = regs[rd];
5496 break;
5497 }
5498 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5499 break;
5500
5501 case DIF_OP_STW:
5502 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5503 *flags |= CPU_DTRACE_BADADDR;
5504 *illval = regs[rd];
5505 break;
5506 }
5507 if (regs[rd] & 3) {
5508 *flags |= CPU_DTRACE_BADALIGN;
5509 *illval = regs[rd];
5510 break;
5511 }
5512 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5513 break;
5514
5515 case DIF_OP_STX:
5516 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5517 *flags |= CPU_DTRACE_BADADDR;
5518 *illval = regs[rd];
5519 break;
5520 }
5521
5522 /*
5523 * Darwin kmem_zalloc() called from
5524 * dtrace_difo_init() is 4-byte aligned.
5525 */
5526 if (regs[rd] & 3) {
5527 *flags |= CPU_DTRACE_BADALIGN;
5528 *illval = regs[rd];
5529 break;
5530 }
5531 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5532 break;
5533 }
5534 }
5535
5536 if (!(*flags & CPU_DTRACE_FAULT))
5537 return (rval);
5538
5539 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5540 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5541
5542 return (0);
5543 }
5544
5545 static void
5546 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5547 {
5548 dtrace_probe_t *probe = ecb->dte_probe;
5549 dtrace_provider_t *prov = probe->dtpr_provider;
5550 char c[DTRACE_FULLNAMELEN + 80], *str;
5551 const char *msg = "dtrace: breakpoint action at probe ";
5552 const char *ecbmsg = " (ecb ";
5553 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5554 uintptr_t val = (uintptr_t)ecb;
5555 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5556
5557 if (dtrace_destructive_disallow)
5558 return;
5559
5560 /*
5561 * It's impossible to be taking action on the NULL probe.
5562 */
5563 ASSERT(probe != NULL);
5564
5565 /*
5566 * This is a poor man's (destitute man's?) sprintf(): we want to
5567 * print the provider name, module name, function name and name of
5568 * the probe, along with the hex address of the ECB with the breakpoint
5569 * action -- all of which we must place in the character buffer by
5570 * hand.
5571 */
5572 while (*msg != '\0')
5573 c[i++] = *msg++;
5574
5575 for (str = prov->dtpv_name; *str != '\0'; str++)
5576 c[i++] = *str;
5577 c[i++] = ':';
5578
5579 for (str = probe->dtpr_mod; *str != '\0'; str++)
5580 c[i++] = *str;
5581 c[i++] = ':';
5582
5583 for (str = probe->dtpr_func; *str != '\0'; str++)
5584 c[i++] = *str;
5585 c[i++] = ':';
5586
5587 for (str = probe->dtpr_name; *str != '\0'; str++)
5588 c[i++] = *str;
5589
5590 while (*ecbmsg != '\0')
5591 c[i++] = *ecbmsg++;
5592
5593 while (shift >= 0) {
5594 mask = (uintptr_t)0xf << shift;
5595
5596 if (val >= ((uintptr_t)1 << shift))
5597 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5598 shift -= 4;
5599 }
5600
5601 c[i++] = ')';
5602 c[i] = '\0';
5603
5604 debug_enter(c);
5605 }
5606
5607 static void
5608 dtrace_action_panic(dtrace_ecb_t *ecb)
5609 {
5610 dtrace_probe_t *probe = ecb->dte_probe;
5611
5612 /*
5613 * It's impossible to be taking action on the NULL probe.
5614 */
5615 ASSERT(probe != NULL);
5616
5617 if (dtrace_destructive_disallow)
5618 return;
5619
5620 if (dtrace_panicked != NULL)
5621 return;
5622
5623 if (dtrace_casptr(&dtrace_panicked, NULL, current_thread()) != NULL)
5624 return;
5625
5626 /*
5627 * We won the right to panic. (We want to be sure that only one
5628 * thread calls panic() from dtrace_probe(), and that panic() is
5629 * called exactly once.)
5630 */
5631 panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5632 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5633 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5634
5635 /*
5636 * APPLE NOTE: this was for an old Mac OS X debug feature
5637 * allowing a return from panic(). Revisit someday.
5638 */
5639 dtrace_panicked = NULL;
5640 }
5641
5642 static void
5643 dtrace_action_raise(uint64_t sig)
5644 {
5645 if (dtrace_destructive_disallow)
5646 return;
5647
5648 if (sig >= NSIG) {
5649 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5650 return;
5651 }
5652
5653 /*
5654 * raise() has a queue depth of 1 -- we ignore all subsequent
5655 * invocations of the raise() action.
5656 */
5657
5658 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5659
5660 if (uthread && uthread->t_dtrace_sig == 0) {
5661 uthread->t_dtrace_sig = sig;
5662 act_set_astbsd(current_thread());
5663 }
5664 }
5665
5666 static void
5667 dtrace_action_stop(void)
5668 {
5669 if (dtrace_destructive_disallow)
5670 return;
5671
5672 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5673 if (uthread) {
5674 /*
5675 * The currently running process will be set to task_suspend
5676 * when it next leaves the kernel.
5677 */
5678 uthread->t_dtrace_stop = 1;
5679 act_set_astbsd(current_thread());
5680 }
5681 }
5682
5683
5684 /*
5685 * APPLE NOTE: pidresume works in conjunction with the dtrace stop action.
5686 * Both activate only when the currently running process next leaves the
5687 * kernel.
5688 */
5689 static void
5690 dtrace_action_pidresume(uint64_t pid)
5691 {
5692 if (dtrace_destructive_disallow)
5693 return;
5694
5695 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
5696 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5697 return;
5698 }
5699 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5700
5701 /*
5702 * When the currently running process leaves the kernel, it attempts to
5703 * task_resume the process (denoted by pid), if that pid appears to have
5704 * been stopped by dtrace_action_stop().
5705 * The currently running process has a pidresume() queue depth of 1 --
5706 * subsequent invocations of the pidresume() action are ignored.
5707 */
5708
5709 if (pid != 0 && uthread && uthread->t_dtrace_resumepid == 0) {
5710 uthread->t_dtrace_resumepid = pid;
5711 act_set_astbsd(current_thread());
5712 }
5713 }
5714
5715 static void
5716 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5717 {
5718 hrtime_t now;
5719 volatile uint16_t *flags;
5720 dtrace_cpu_t *cpu = CPU;
5721
5722 if (dtrace_destructive_disallow)
5723 return;
5724
5725 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5726
5727 now = dtrace_gethrtime();
5728
5729 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5730 /*
5731 * We need to advance the mark to the current time.
5732 */
5733 cpu->cpu_dtrace_chillmark = now;
5734 cpu->cpu_dtrace_chilled = 0;
5735 }
5736
5737 /*
5738 * Now check to see if the requested chill time would take us over
5739 * the maximum amount of time allowed in the chill interval. (Or
5740 * worse, if the calculation itself induces overflow.)
5741 */
5742 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5743 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5744 *flags |= CPU_DTRACE_ILLOP;
5745 return;
5746 }
5747
5748 while (dtrace_gethrtime() - now < val)
5749 continue;
5750
5751 /*
5752 * Normally, we assure that the value of the variable "timestamp" does
5753 * not change within an ECB. The presence of chill() represents an
5754 * exception to this rule, however.
5755 */
5756 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5757 cpu->cpu_dtrace_chilled += val;
5758 }
5759
5760 static void
5761 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5762 uint64_t *buf, uint64_t arg)
5763 {
5764 int nframes = DTRACE_USTACK_NFRAMES(arg);
5765 int strsize = DTRACE_USTACK_STRSIZE(arg);
5766 uint64_t *pcs = &buf[1], *fps;
5767 char *str = (char *)&pcs[nframes];
5768 int size, offs = 0, i, j;
5769 uintptr_t old = mstate->dtms_scratch_ptr, saved;
5770 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5771 char *sym;
5772
5773 /*
5774 * Should be taking a faster path if string space has not been
5775 * allocated.
5776 */
5777 ASSERT(strsize != 0);
5778
5779 /*
5780 * We will first allocate some temporary space for the frame pointers.
5781 */
5782 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5783 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5784 (nframes * sizeof (uint64_t));
5785
5786 if (!DTRACE_INSCRATCH(mstate, (uintptr_t)size)) {
5787 /*
5788 * Not enough room for our frame pointers -- need to indicate
5789 * that we ran out of scratch space.
5790 */
5791 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5792 return;
5793 }
5794
5795 mstate->dtms_scratch_ptr += size;
5796 saved = mstate->dtms_scratch_ptr;
5797
5798 /*
5799 * Now get a stack with both program counters and frame pointers.
5800 */
5801 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5802 dtrace_getufpstack(buf, fps, nframes + 1);
5803 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5804
5805 /*
5806 * If that faulted, we're cooked.
5807 */
5808 if (*flags & CPU_DTRACE_FAULT)
5809 goto out;
5810
5811 /*
5812 * Now we want to walk up the stack, calling the USTACK helper. For
5813 * each iteration, we restore the scratch pointer.
5814 */
5815 for (i = 0; i < nframes; i++) {
5816 mstate->dtms_scratch_ptr = saved;
5817
5818 if (offs >= strsize)
5819 break;
5820
5821 sym = (char *)(uintptr_t)dtrace_helper(
5822 DTRACE_HELPER_ACTION_USTACK,
5823 mstate, state, pcs[i], fps[i]);
5824
5825 /*
5826 * If we faulted while running the helper, we're going to
5827 * clear the fault and null out the corresponding string.
5828 */
5829 if (*flags & CPU_DTRACE_FAULT) {
5830 *flags &= ~CPU_DTRACE_FAULT;
5831 str[offs++] = '\0';
5832 continue;
5833 }
5834
5835 if (sym == NULL) {
5836 str[offs++] = '\0';
5837 continue;
5838 }
5839
5840 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5841
5842 /*
5843 * Now copy in the string that the helper returned to us.
5844 */
5845 for (j = 0; offs + j < strsize; j++) {
5846 if ((str[offs + j] = sym[j]) == '\0')
5847 break;
5848 }
5849
5850 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5851
5852 offs += j + 1;
5853 }
5854
5855 if (offs >= strsize) {
5856 /*
5857 * If we didn't have room for all of the strings, we don't
5858 * abort processing -- this needn't be a fatal error -- but we
5859 * still want to increment a counter (dts_stkstroverflows) to
5860 * allow this condition to be warned about. (If this is from
5861 * a jstack() action, it is easily tuned via jstackstrsize.)
5862 */
5863 dtrace_error(&state->dts_stkstroverflows);
5864 }
5865
5866 while (offs < strsize)
5867 str[offs++] = '\0';
5868
5869 out:
5870 mstate->dtms_scratch_ptr = old;
5871 }
5872
5873 /*
5874 * If you're looking for the epicenter of DTrace, you just found it. This
5875 * is the function called by the provider to fire a probe -- from which all
5876 * subsequent probe-context DTrace activity emanates.
5877 */
5878 static void
5879 __dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
5880 uint64_t arg2, uint64_t arg3, uint64_t arg4)
5881 {
5882 processorid_t cpuid;
5883 dtrace_icookie_t cookie;
5884 dtrace_probe_t *probe;
5885 dtrace_mstate_t mstate;
5886 dtrace_ecb_t *ecb;
5887 dtrace_action_t *act;
5888 intptr_t offs;
5889 size_t size;
5890 int vtime, onintr;
5891 volatile uint16_t *flags;
5892 hrtime_t now;
5893
5894 cookie = dtrace_interrupt_disable();
5895 probe = dtrace_probes[id - 1];
5896 cpuid = CPU->cpu_id;
5897 onintr = CPU_ON_INTR(CPU);
5898
5899 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5900 probe->dtpr_predcache == dtrace_get_thread_predcache(current_thread())) {
5901 /*
5902 * We have hit in the predicate cache; we know that
5903 * this predicate would evaluate to be false.
5904 */
5905 dtrace_interrupt_enable(cookie);
5906 return;
5907 }
5908
5909 if (panic_quiesce) {
5910 /*
5911 * We don't trace anything if we're panicking.
5912 */
5913 dtrace_interrupt_enable(cookie);
5914 return;
5915 }
5916
5917 #if !defined(__APPLE__)
5918 now = dtrace_gethrtime();
5919 vtime = dtrace_vtime_references != 0;
5920
5921 if (vtime && curthread->t_dtrace_start)
5922 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5923 #else
5924 /*
5925 * APPLE NOTE: The time spent entering DTrace and arriving
5926 * to this point, is attributed to the current thread.
5927 * Instead it should accrue to DTrace. FIXME
5928 */
5929 vtime = dtrace_vtime_references != 0;
5930
5931 if (vtime)
5932 {
5933 int64_t dtrace_accum_time, recent_vtime;
5934 thread_t thread = current_thread();
5935
5936 dtrace_accum_time = dtrace_get_thread_tracing(thread); /* Time spent inside DTrace so far (nanoseconds) */
5937
5938 if (dtrace_accum_time >= 0) {
5939 recent_vtime = dtrace_abs_to_nano(dtrace_calc_thread_recent_vtime(thread)); /* up to the moment thread vtime */
5940
5941 recent_vtime = recent_vtime - dtrace_accum_time; /* Time without DTrace contribution */
5942
5943 dtrace_set_thread_vtime(thread, recent_vtime);
5944 }
5945 }
5946
5947 now = dtrace_gethrtime(); /* must not precede dtrace_calc_thread_recent_vtime() call! */
5948 #endif /* __APPLE__ */
5949
5950 /*
5951 * APPLE NOTE: A provider may call dtrace_probe_error() in lieu of
5952 * dtrace_probe() in some circumstances. See, e.g. fasttrap_isa.c.
5953 * However the provider has no access to ECB context, so passes
5954 * 0 through "arg0" and the probe_id of the overridden probe as arg1.
5955 * Detect that here and cons up a viable state (from the probe_id).
5956 */
5957 if (dtrace_probeid_error == id && 0 == arg0) {
5958 dtrace_id_t ftp_id = (dtrace_id_t)arg1;
5959 dtrace_probe_t *ftp_probe = dtrace_probes[ftp_id - 1];
5960 dtrace_ecb_t *ftp_ecb = ftp_probe->dtpr_ecb;
5961
5962 if (NULL != ftp_ecb) {
5963 dtrace_state_t *ftp_state = ftp_ecb->dte_state;
5964
5965 arg0 = (uint64_t)(uintptr_t)ftp_state;
5966 arg1 = ftp_ecb->dte_epid;
5967 /*
5968 * args[2-4] established by caller.
5969 */
5970 ftp_state->dts_arg_error_illval = -1; /* arg5 */
5971 }
5972 }
5973
5974 mstate.dtms_difo = NULL;
5975 mstate.dtms_probe = probe;
5976 mstate.dtms_strtok = 0;
5977 mstate.dtms_arg[0] = arg0;
5978 mstate.dtms_arg[1] = arg1;
5979 mstate.dtms_arg[2] = arg2;
5980 mstate.dtms_arg[3] = arg3;
5981 mstate.dtms_arg[4] = arg4;
5982
5983 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5984
5985 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5986 dtrace_predicate_t *pred = ecb->dte_predicate;
5987 dtrace_state_t *state = ecb->dte_state;
5988 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5989 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5990 dtrace_vstate_t *vstate = &state->dts_vstate;
5991 dtrace_provider_t *prov = probe->dtpr_provider;
5992 uint64_t tracememsize = 0;
5993 int committed = 0;
5994 caddr_t tomax;
5995
5996 /*
5997 * A little subtlety with the following (seemingly innocuous)
5998 * declaration of the automatic 'val': by looking at the
5999 * code, you might think that it could be declared in the
6000 * action processing loop, below. (That is, it's only used in
6001 * the action processing loop.) However, it must be declared
6002 * out of that scope because in the case of DIF expression
6003 * arguments to aggregating actions, one iteration of the
6004 * action loop will use the last iteration's value.
6005 */
6006 #ifdef lint
6007 uint64_t val = 0;
6008 #else
6009 uint64_t val = 0;
6010 #endif
6011
6012 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6013 *flags &= ~CPU_DTRACE_ERROR;
6014
6015 if (prov == dtrace_provider) {
6016 /*
6017 * If dtrace itself is the provider of this probe,
6018 * we're only going to continue processing the ECB if
6019 * arg0 (the dtrace_state_t) is equal to the ECB's
6020 * creating state. (This prevents disjoint consumers
6021 * from seeing one another's metaprobes.)
6022 */
6023 if (arg0 != (uint64_t)(uintptr_t)state)
6024 continue;
6025 }
6026
6027 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6028 /*
6029 * We're not currently active. If our provider isn't
6030 * the dtrace pseudo provider, we're not interested.
6031 */
6032 if (prov != dtrace_provider)
6033 continue;
6034
6035 /*
6036 * Now we must further check if we are in the BEGIN
6037 * probe. If we are, we will only continue processing
6038 * if we're still in WARMUP -- if one BEGIN enabling
6039 * has invoked the exit() action, we don't want to
6040 * evaluate subsequent BEGIN enablings.
6041 */
6042 if (probe->dtpr_id == dtrace_probeid_begin &&
6043 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6044 ASSERT(state->dts_activity ==
6045 DTRACE_ACTIVITY_DRAINING);
6046 continue;
6047 }
6048 }
6049
6050 if (ecb->dte_cond) {
6051 /*
6052 * If the dte_cond bits indicate that this
6053 * consumer is only allowed to see user-mode firings
6054 * of this probe, call the provider's dtps_usermode()
6055 * entry point to check that the probe was fired
6056 * while in a user context. Skip this ECB if that's
6057 * not the case.
6058 */
6059 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6060 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6061 probe->dtpr_id, probe->dtpr_arg) == 0)
6062 continue;
6063
6064 /*
6065 * This is more subtle than it looks. We have to be
6066 * absolutely certain that CRED() isn't going to
6067 * change out from under us so it's only legit to
6068 * examine that structure if we're in constrained
6069 * situations. Currently, the only times we'll this
6070 * check is if a non-super-user has enabled the
6071 * profile or syscall providers -- providers that
6072 * allow visibility of all processes. For the
6073 * profile case, the check above will ensure that
6074 * we're examining a user context.
6075 */
6076 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6077 cred_t *cr;
6078 cred_t *s_cr =
6079 ecb->dte_state->dts_cred.dcr_cred;
6080 proc_t *proc;
6081 #pragma unused(proc) /* __APPLE__ */
6082
6083 ASSERT(s_cr != NULL);
6084
6085 /*
6086 * XXX this is hackish, but so is setting a variable
6087 * XXX in a McCarthy OR...
6088 */
6089 if ((cr = dtrace_CRED()) == NULL ||
6090 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_uid ||
6091 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_ruid ||
6092 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_suid ||
6093 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_gid ||
6094 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_rgid ||
6095 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_sgid ||
6096 #if !defined(__APPLE__)
6097 (proc = ttoproc(curthread)) == NULL ||
6098 (proc->p_flag & SNOCD))
6099 #else
6100 1) /* APPLE NOTE: Darwin omits "No Core Dump" flag */
6101 #endif /* __APPLE__ */
6102 continue;
6103 }
6104
6105 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6106 cred_t *cr;
6107 cred_t *s_cr =
6108 ecb->dte_state->dts_cred.dcr_cred;
6109 #pragma unused(cr, s_cr) /* __APPLE__ */
6110
6111 ASSERT(s_cr != NULL);
6112
6113 #if !defined(__APPLE__)
6114 if ((cr = CRED()) == NULL ||
6115 s_cr->cr_zone->zone_id !=
6116 cr->cr_zone->zone_id)
6117 continue;
6118 #else
6119 /* APPLE NOTE: Darwin doesn't do zones. */
6120 #endif /* __APPLE__ */
6121 }
6122 }
6123
6124 if (now - state->dts_alive > dtrace_deadman_timeout) {
6125 /*
6126 * We seem to be dead. Unless we (a) have kernel
6127 * destructive permissions (b) have expicitly enabled
6128 * destructive actions and (c) destructive actions have
6129 * not been disabled, we're going to transition into
6130 * the KILLED state, from which no further processing
6131 * on this state will be performed.
6132 */
6133 if (!dtrace_priv_kernel_destructive(state) ||
6134 !state->dts_cred.dcr_destructive ||
6135 dtrace_destructive_disallow) {
6136 void *activity = &state->dts_activity;
6137 dtrace_activity_t current;
6138
6139 do {
6140 current = state->dts_activity;
6141 } while (dtrace_cas32(activity, current,
6142 DTRACE_ACTIVITY_KILLED) != current);
6143
6144 continue;
6145 }
6146 }
6147
6148 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6149 ecb->dte_alignment, state, &mstate)) < 0)
6150 continue;
6151
6152 tomax = buf->dtb_tomax;
6153 ASSERT(tomax != NULL);
6154
6155 /*
6156 * Build and store the record header corresponding to the ECB.
6157 */
6158 if (ecb->dte_size != 0) {
6159 dtrace_rechdr_t dtrh;
6160
6161 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6162 mstate.dtms_timestamp = dtrace_gethrtime();
6163 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6164 }
6165
6166 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6167
6168 dtrh.dtrh_epid = ecb->dte_epid;
6169 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh, mstate.dtms_timestamp);
6170 DTRACE_STORE(dtrace_rechdr_t, tomax, offs, dtrh);
6171 }
6172
6173 mstate.dtms_epid = ecb->dte_epid;
6174 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6175
6176 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6177 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6178 else
6179 mstate.dtms_access = 0;
6180
6181 if (pred != NULL) {
6182 dtrace_difo_t *dp = pred->dtp_difo;
6183 int rval;
6184
6185 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6186
6187 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6188 dtrace_cacheid_t cid = probe->dtpr_predcache;
6189
6190 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6191 /*
6192 * Update the predicate cache...
6193 */
6194 ASSERT(cid == pred->dtp_cacheid);
6195
6196 dtrace_set_thread_predcache(current_thread(), cid);
6197 }
6198
6199 continue;
6200 }
6201 }
6202
6203 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6204 act != NULL; act = act->dta_next) {
6205 size_t valoffs;
6206 dtrace_difo_t *dp;
6207 dtrace_recdesc_t *rec = &act->dta_rec;
6208
6209 size = rec->dtrd_size;
6210 valoffs = offs + rec->dtrd_offset;
6211
6212 if (DTRACEACT_ISAGG(act->dta_kind)) {
6213 uint64_t v = 0xbad;
6214 dtrace_aggregation_t *agg;
6215
6216 agg = (dtrace_aggregation_t *)act;
6217
6218 if ((dp = act->dta_difo) != NULL)
6219 v = dtrace_dif_emulate(dp,
6220 &mstate, vstate, state);
6221
6222 if (*flags & CPU_DTRACE_ERROR)
6223 continue;
6224
6225 /*
6226 * Note that we always pass the expression
6227 * value from the previous iteration of the
6228 * action loop. This value will only be used
6229 * if there is an expression argument to the
6230 * aggregating action, denoted by the
6231 * dtag_hasarg field.
6232 */
6233 dtrace_aggregate(agg, buf,
6234 offs, aggbuf, v, val);
6235 continue;
6236 }
6237
6238 switch (act->dta_kind) {
6239 case DTRACEACT_STOP:
6240 if (dtrace_priv_proc_destructive(state))
6241 dtrace_action_stop();
6242 continue;
6243
6244 case DTRACEACT_BREAKPOINT:
6245 if (dtrace_priv_kernel_destructive(state))
6246 dtrace_action_breakpoint(ecb);
6247 continue;
6248
6249 case DTRACEACT_PANIC:
6250 if (dtrace_priv_kernel_destructive(state))
6251 dtrace_action_panic(ecb);
6252 continue;
6253
6254 case DTRACEACT_STACK:
6255 if (!dtrace_priv_kernel(state))
6256 continue;
6257
6258 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6259 size / sizeof (pc_t), probe->dtpr_aframes,
6260 DTRACE_ANCHORED(probe) ? NULL :
6261 (uint32_t *)(uintptr_t)arg0);
6262 continue;
6263
6264 case DTRACEACT_JSTACK:
6265 case DTRACEACT_USTACK:
6266 if (!dtrace_priv_proc(state))
6267 continue;
6268
6269 /*
6270 * See comment in DIF_VAR_PID.
6271 */
6272 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6273 CPU_ON_INTR(CPU)) {
6274 int depth = DTRACE_USTACK_NFRAMES(
6275 rec->dtrd_arg) + 1;
6276
6277 dtrace_bzero((void *)(tomax + valoffs),
6278 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6279 + depth * sizeof (uint64_t));
6280
6281 continue;
6282 }
6283
6284 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6285 curproc->p_dtrace_helpers != NULL) {
6286 /*
6287 * This is the slow path -- we have
6288 * allocated string space, and we're
6289 * getting the stack of a process that
6290 * has helpers. Call into a separate
6291 * routine to perform this processing.
6292 */
6293 dtrace_action_ustack(&mstate, state,
6294 (uint64_t *)(tomax + valoffs),
6295 rec->dtrd_arg);
6296 continue;
6297 }
6298
6299 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6300 dtrace_getupcstack((uint64_t *)
6301 (tomax + valoffs),
6302 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6303 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6304 continue;
6305
6306 default:
6307 break;
6308 }
6309
6310 dp = act->dta_difo;
6311 ASSERT(dp != NULL);
6312
6313 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6314
6315 if (*flags & CPU_DTRACE_ERROR)
6316 continue;
6317
6318 switch (act->dta_kind) {
6319 case DTRACEACT_SPECULATE: {
6320 dtrace_rechdr_t *dtrh = NULL;
6321
6322 ASSERT(buf == &state->dts_buffer[cpuid]);
6323 buf = dtrace_speculation_buffer(state,
6324 cpuid, val);
6325
6326 if (buf == NULL) {
6327 *flags |= CPU_DTRACE_DROP;
6328 continue;
6329 }
6330
6331 offs = dtrace_buffer_reserve(buf,
6332 ecb->dte_needed, ecb->dte_alignment,
6333 state, NULL);
6334
6335 if (offs < 0) {
6336 *flags |= CPU_DTRACE_DROP;
6337 continue;
6338 }
6339
6340 tomax = buf->dtb_tomax;
6341 ASSERT(tomax != NULL);
6342
6343 if (ecb->dte_size != 0)
6344 continue;
6345
6346 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6347 dtrh = ((void *)(tomax + offs));
6348 dtrh->dtrh_epid = ecb->dte_epid;
6349
6350 /*
6351 * When the speculation is committed, all of
6352 * the records in the speculative buffer will
6353 * have their timestamps set to the commit
6354 * time. Until then, it is set to a sentinel
6355 * value, for debugability.
6356 */
6357 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6358
6359 continue;
6360 }
6361
6362 case DTRACEACT_CHILL:
6363 if (dtrace_priv_kernel_destructive(state))
6364 dtrace_action_chill(&mstate, val);
6365 continue;
6366
6367 case DTRACEACT_RAISE:
6368 if (dtrace_priv_proc_destructive(state))
6369 dtrace_action_raise(val);
6370 continue;
6371
6372 case DTRACEACT_PIDRESUME: /* __APPLE__ */
6373 if (dtrace_priv_proc_destructive(state))
6374 dtrace_action_pidresume(val);
6375 continue;
6376
6377 case DTRACEACT_COMMIT:
6378 ASSERT(!committed);
6379
6380 /*
6381 * We need to commit our buffer state.
6382 */
6383 if (ecb->dte_size)
6384 buf->dtb_offset = offs + ecb->dte_size;
6385 buf = &state->dts_buffer[cpuid];
6386 dtrace_speculation_commit(state, cpuid, val);
6387 committed = 1;
6388 continue;
6389
6390 case DTRACEACT_DISCARD:
6391 dtrace_speculation_discard(state, cpuid, val);
6392 continue;
6393
6394 case DTRACEACT_DIFEXPR:
6395 case DTRACEACT_LIBACT:
6396 case DTRACEACT_PRINTF:
6397 case DTRACEACT_PRINTA:
6398 case DTRACEACT_SYSTEM:
6399 case DTRACEACT_FREOPEN:
6400 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
6401 case DTRACEACT_TRACEMEM:
6402 break;
6403
6404 case DTRACEACT_TRACEMEM_DYNSIZE:
6405 tracememsize = val;
6406 break;
6407
6408 case DTRACEACT_SYM:
6409 case DTRACEACT_MOD:
6410 if (!dtrace_priv_kernel(state))
6411 continue;
6412 break;
6413
6414 case DTRACEACT_USYM:
6415 case DTRACEACT_UMOD:
6416 case DTRACEACT_UADDR: {
6417 if (!dtrace_priv_proc(state))
6418 continue;
6419
6420 DTRACE_STORE(uint64_t, tomax,
6421 valoffs, (uint64_t)dtrace_proc_selfpid());
6422 DTRACE_STORE(uint64_t, tomax,
6423 valoffs + sizeof (uint64_t), val);
6424
6425 continue;
6426 }
6427
6428 case DTRACEACT_EXIT: {
6429 /*
6430 * For the exit action, we are going to attempt
6431 * to atomically set our activity to be
6432 * draining. If this fails (either because
6433 * another CPU has beat us to the exit action,
6434 * or because our current activity is something
6435 * other than ACTIVE or WARMUP), we will
6436 * continue. This assures that the exit action
6437 * can be successfully recorded at most once
6438 * when we're in the ACTIVE state. If we're
6439 * encountering the exit() action while in
6440 * COOLDOWN, however, we want to honor the new
6441 * status code. (We know that we're the only
6442 * thread in COOLDOWN, so there is no race.)
6443 */
6444 void *activity = &state->dts_activity;
6445 dtrace_activity_t current = state->dts_activity;
6446
6447 if (current == DTRACE_ACTIVITY_COOLDOWN)
6448 break;
6449
6450 if (current != DTRACE_ACTIVITY_WARMUP)
6451 current = DTRACE_ACTIVITY_ACTIVE;
6452
6453 if (dtrace_cas32(activity, current,
6454 DTRACE_ACTIVITY_DRAINING) != current) {
6455 *flags |= CPU_DTRACE_DROP;
6456 continue;
6457 }
6458
6459 break;
6460 }
6461
6462 default:
6463 ASSERT(0);
6464 }
6465
6466 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6467 uintptr_t end = valoffs + size;
6468
6469 if (tracememsize != 0 &&
6470 valoffs + tracememsize < end)
6471 {
6472 end = valoffs + tracememsize;
6473 tracememsize = 0;
6474 }
6475
6476 if (!dtrace_vcanload((void *)(uintptr_t)val,
6477 &dp->dtdo_rtype, &mstate, vstate))
6478 continue;
6479
6480 /*
6481 * If this is a string, we're going to only
6482 * load until we find the zero byte -- after
6483 * which we'll store zero bytes.
6484 */
6485 if (dp->dtdo_rtype.dtdt_kind ==
6486 DIF_TYPE_STRING) {
6487 char c = '\0' + 1;
6488 int intuple = act->dta_intuple;
6489 size_t s;
6490
6491 for (s = 0; s < size; s++) {
6492 if (c != '\0')
6493 c = dtrace_load8(val++);
6494
6495 DTRACE_STORE(uint8_t, tomax,
6496 valoffs++, c);
6497
6498 if (c == '\0' && intuple)
6499 break;
6500 }
6501
6502 continue;
6503 }
6504
6505 while (valoffs < end) {
6506 DTRACE_STORE(uint8_t, tomax, valoffs++,
6507 dtrace_load8(val++));
6508 }
6509
6510 continue;
6511 }
6512
6513 switch (size) {
6514 case 0:
6515 break;
6516
6517 case sizeof (uint8_t):
6518 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6519 break;
6520 case sizeof (uint16_t):
6521 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6522 break;
6523 case sizeof (uint32_t):
6524 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6525 break;
6526 case sizeof (uint64_t):
6527 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6528 break;
6529 default:
6530 /*
6531 * Any other size should have been returned by
6532 * reference, not by value.
6533 */
6534 ASSERT(0);
6535 break;
6536 }
6537 }
6538
6539 if (*flags & CPU_DTRACE_DROP)
6540 continue;
6541
6542 if (*flags & CPU_DTRACE_FAULT) {
6543 int ndx;
6544 dtrace_action_t *err;
6545
6546 buf->dtb_errors++;
6547
6548 if (probe->dtpr_id == dtrace_probeid_error) {
6549 /*
6550 * There's nothing we can do -- we had an
6551 * error on the error probe. We bump an
6552 * error counter to at least indicate that
6553 * this condition happened.
6554 */
6555 dtrace_error(&state->dts_dblerrors);
6556 continue;
6557 }
6558
6559 if (vtime) {
6560 /*
6561 * Before recursing on dtrace_probe(), we
6562 * need to explicitly clear out our start
6563 * time to prevent it from being accumulated
6564 * into t_dtrace_vtime.
6565 */
6566
6567 /*
6568 * Darwin sets the sign bit on t_dtrace_tracing
6569 * to suspend accumulation to it.
6570 */
6571 dtrace_set_thread_tracing(current_thread(),
6572 (1ULL<<63) | dtrace_get_thread_tracing(current_thread()));
6573
6574 }
6575
6576 /*
6577 * Iterate over the actions to figure out which action
6578 * we were processing when we experienced the error.
6579 * Note that act points _past_ the faulting action; if
6580 * act is ecb->dte_action, the fault was in the
6581 * predicate, if it's ecb->dte_action->dta_next it's
6582 * in action #1, and so on.
6583 */
6584 for (err = ecb->dte_action, ndx = 0;
6585 err != act; err = err->dta_next, ndx++)
6586 continue;
6587
6588 dtrace_probe_error(state, ecb->dte_epid, ndx,
6589 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6590 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6591 cpu_core[cpuid].cpuc_dtrace_illval);
6592
6593 continue;
6594 }
6595
6596 if (!committed)
6597 buf->dtb_offset = offs + ecb->dte_size;
6598 }
6599
6600 /* FIXME: On Darwin the time spent leaving DTrace from this point to the rti is attributed
6601 to the current thread. Instead it should accrue to DTrace. */
6602 if (vtime) {
6603 thread_t thread = current_thread();
6604 int64_t t = dtrace_get_thread_tracing(thread);
6605
6606 if (t >= 0) {
6607 /* Usual case, accumulate time spent here into t_dtrace_tracing */
6608 dtrace_set_thread_tracing(thread, t + (dtrace_gethrtime() - now));
6609 } else {
6610 /* Return from error recursion. No accumulation, just clear the sign bit on t_dtrace_tracing. */
6611 dtrace_set_thread_tracing(thread, (~(1ULL<<63)) & t);
6612 }
6613 }
6614
6615 dtrace_interrupt_enable(cookie);
6616 }
6617
6618 /*
6619 * APPLE NOTE: Don't allow a thread to re-enter dtrace_probe().
6620 * This could occur if a probe is encountered on some function in the
6621 * transitive closure of the call to dtrace_probe().
6622 * Solaris has some strong guarantees that this won't happen.
6623 * The Darwin implementation is not so mature as to make those guarantees.
6624 * Hence, the introduction of __dtrace_probe() on xnu.
6625 */
6626
6627 void
6628 dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
6629 uint64_t arg2, uint64_t arg3, uint64_t arg4)
6630 {
6631 thread_t thread = current_thread();
6632 disable_preemption();
6633 if (id == dtrace_probeid_error) {
6634 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
6635 dtrace_getipl(); /* Defeat tail-call optimization of __dtrace_probe() */
6636 } else if (!dtrace_get_thread_reentering(thread)) {
6637 dtrace_set_thread_reentering(thread, TRUE);
6638 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
6639 dtrace_set_thread_reentering(thread, FALSE);
6640 }
6641 #if DEBUG
6642 else __dtrace_probe(dtrace_probeid_error, 0, id, 1, -1, DTRACEFLT_UNKNOWN);
6643 #endif
6644 enable_preemption();
6645 }
6646
6647 /*
6648 * DTrace Probe Hashing Functions
6649 *
6650 * The functions in this section (and indeed, the functions in remaining
6651 * sections) are not _called_ from probe context. (Any exceptions to this are
6652 * marked with a "Note:".) Rather, they are called from elsewhere in the
6653 * DTrace framework to look-up probes in, add probes to and remove probes from
6654 * the DTrace probe hashes. (Each probe is hashed by each element of the
6655 * probe tuple -- allowing for fast lookups, regardless of what was
6656 * specified.)
6657 */
6658 static uint_t
6659 dtrace_hash_str(const char *p)
6660 {
6661 unsigned int g;
6662 uint_t hval = 0;
6663
6664 while (*p) {
6665 hval = (hval << 4) + *p++;
6666 if ((g = (hval & 0xf0000000)) != 0)
6667 hval ^= g >> 24;
6668 hval &= ~g;
6669 }
6670 return (hval);
6671 }
6672
6673 static dtrace_hash_t *
6674 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6675 {
6676 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6677
6678 hash->dth_stroffs = stroffs;
6679 hash->dth_nextoffs = nextoffs;
6680 hash->dth_prevoffs = prevoffs;
6681
6682 hash->dth_size = 1;
6683 hash->dth_mask = hash->dth_size - 1;
6684
6685 hash->dth_tab = kmem_zalloc(hash->dth_size *
6686 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6687
6688 return (hash);
6689 }
6690
6691 /*
6692 * APPLE NOTE: dtrace_hash_destroy is not used.
6693 * It is called by dtrace_detach which is not
6694 * currently implemented. Revisit someday.
6695 */
6696 #if !defined(__APPLE__)
6697 static void
6698 dtrace_hash_destroy(dtrace_hash_t *hash)
6699 {
6700 #if DEBUG
6701 int i;
6702
6703 for (i = 0; i < hash->dth_size; i++)
6704 ASSERT(hash->dth_tab[i] == NULL);
6705 #endif
6706
6707 kmem_free(hash->dth_tab,
6708 hash->dth_size * sizeof (dtrace_hashbucket_t *));
6709 kmem_free(hash, sizeof (dtrace_hash_t));
6710 }
6711 #endif /* __APPLE__ */
6712
6713 static void
6714 dtrace_hash_resize(dtrace_hash_t *hash)
6715 {
6716 int size = hash->dth_size, i, ndx;
6717 int new_size = hash->dth_size << 1;
6718 int new_mask = new_size - 1;
6719 dtrace_hashbucket_t **new_tab, *bucket, *next;
6720
6721 ASSERT((new_size & new_mask) == 0);
6722
6723 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6724
6725 for (i = 0; i < size; i++) {
6726 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6727 dtrace_probe_t *probe = bucket->dthb_chain;
6728
6729 ASSERT(probe != NULL);
6730 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6731
6732 next = bucket->dthb_next;
6733 bucket->dthb_next = new_tab[ndx];
6734 new_tab[ndx] = bucket;
6735 }
6736 }
6737
6738 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6739 hash->dth_tab = new_tab;
6740 hash->dth_size = new_size;
6741 hash->dth_mask = new_mask;
6742 }
6743
6744 static void
6745 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6746 {
6747 int hashval = DTRACE_HASHSTR(hash, new);
6748 int ndx = hashval & hash->dth_mask;
6749 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6750 dtrace_probe_t **nextp, **prevp;
6751
6752 for (; bucket != NULL; bucket = bucket->dthb_next) {
6753 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6754 goto add;
6755 }
6756
6757 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6758 dtrace_hash_resize(hash);
6759 dtrace_hash_add(hash, new);
6760 return;
6761 }
6762
6763 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6764 bucket->dthb_next = hash->dth_tab[ndx];
6765 hash->dth_tab[ndx] = bucket;
6766 hash->dth_nbuckets++;
6767
6768 add:
6769 nextp = DTRACE_HASHNEXT(hash, new);
6770 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6771 *nextp = bucket->dthb_chain;
6772
6773 if (bucket->dthb_chain != NULL) {
6774 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6775 ASSERT(*prevp == NULL);
6776 *prevp = new;
6777 }
6778
6779 bucket->dthb_chain = new;
6780 bucket->dthb_len++;
6781 }
6782
6783 static dtrace_probe_t *
6784 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6785 {
6786 int hashval = DTRACE_HASHSTR(hash, template);
6787 int ndx = hashval & hash->dth_mask;
6788 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6789
6790 for (; bucket != NULL; bucket = bucket->dthb_next) {
6791 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6792 return (bucket->dthb_chain);
6793 }
6794
6795 return (NULL);
6796 }
6797
6798 static int
6799 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6800 {
6801 int hashval = DTRACE_HASHSTR(hash, template);
6802 int ndx = hashval & hash->dth_mask;
6803 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6804
6805 for (; bucket != NULL; bucket = bucket->dthb_next) {
6806 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6807 return (bucket->dthb_len);
6808 }
6809
6810 return (0);
6811 }
6812
6813 static void
6814 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6815 {
6816 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6817 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6818
6819 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6820 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6821
6822 /*
6823 * Find the bucket that we're removing this probe from.
6824 */
6825 for (; bucket != NULL; bucket = bucket->dthb_next) {
6826 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6827 break;
6828 }
6829
6830 ASSERT(bucket != NULL);
6831
6832 if (*prevp == NULL) {
6833 if (*nextp == NULL) {
6834 /*
6835 * The removed probe was the only probe on this
6836 * bucket; we need to remove the bucket.
6837 */
6838 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6839
6840 ASSERT(bucket->dthb_chain == probe);
6841 ASSERT(b != NULL);
6842
6843 if (b == bucket) {
6844 hash->dth_tab[ndx] = bucket->dthb_next;
6845 } else {
6846 while (b->dthb_next != bucket)
6847 b = b->dthb_next;
6848 b->dthb_next = bucket->dthb_next;
6849 }
6850
6851 ASSERT(hash->dth_nbuckets > 0);
6852 hash->dth_nbuckets--;
6853 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6854 return;
6855 }
6856
6857 bucket->dthb_chain = *nextp;
6858 } else {
6859 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6860 }
6861
6862 if (*nextp != NULL)
6863 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6864 }
6865
6866 /*
6867 * DTrace Utility Functions
6868 *
6869 * These are random utility functions that are _not_ called from probe context.
6870 */
6871 static int
6872 dtrace_badattr(const dtrace_attribute_t *a)
6873 {
6874 return (a->dtat_name > DTRACE_STABILITY_MAX ||
6875 a->dtat_data > DTRACE_STABILITY_MAX ||
6876 a->dtat_class > DTRACE_CLASS_MAX);
6877 }
6878
6879 /*
6880 * Return a duplicate copy of a string. If the specified string is NULL,
6881 * this function returns a zero-length string.
6882 * APPLE NOTE: Darwin employs size bounded string operation.
6883 */
6884 static char *
6885 dtrace_strdup(const char *str)
6886 {
6887 size_t bufsize = (str != NULL ? strlen(str) : 0) + 1;
6888 char *new = kmem_zalloc(bufsize, KM_SLEEP);
6889
6890 if (str != NULL)
6891 (void) strlcpy(new, str, bufsize);
6892
6893 return (new);
6894 }
6895
6896 #define DTRACE_ISALPHA(c) \
6897 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6898
6899 static int
6900 dtrace_badname(const char *s)
6901 {
6902 char c;
6903
6904 if (s == NULL || (c = *s++) == '\0')
6905 return (0);
6906
6907 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6908 return (1);
6909
6910 while ((c = *s++) != '\0') {
6911 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6912 c != '-' && c != '_' && c != '.' && c != '`')
6913 return (1);
6914 }
6915
6916 return (0);
6917 }
6918
6919 static void
6920 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6921 {
6922 uint32_t priv;
6923
6924 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6925 /*
6926 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6927 */
6928 priv = DTRACE_PRIV_ALL;
6929 } else {
6930 *uidp = crgetuid(cr);
6931 *zoneidp = crgetzoneid(cr);
6932
6933 priv = 0;
6934 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6935 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6936 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6937 priv |= DTRACE_PRIV_USER;
6938 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6939 priv |= DTRACE_PRIV_PROC;
6940 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6941 priv |= DTRACE_PRIV_OWNER;
6942 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6943 priv |= DTRACE_PRIV_ZONEOWNER;
6944 }
6945
6946 *privp = priv;
6947 }
6948
6949 #ifdef DTRACE_ERRDEBUG
6950 static void
6951 dtrace_errdebug(const char *str)
6952 {
6953 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
6954 int occupied = 0;
6955
6956 lck_mtx_lock(&dtrace_errlock);
6957 dtrace_errlast = str;
6958 dtrace_errthread = (kthread_t *)current_thread();
6959
6960 while (occupied++ < DTRACE_ERRHASHSZ) {
6961 if (dtrace_errhash[hval].dter_msg == str) {
6962 dtrace_errhash[hval].dter_count++;
6963 goto out;
6964 }
6965
6966 if (dtrace_errhash[hval].dter_msg != NULL) {
6967 hval = (hval + 1) % DTRACE_ERRHASHSZ;
6968 continue;
6969 }
6970
6971 dtrace_errhash[hval].dter_msg = str;
6972 dtrace_errhash[hval].dter_count = 1;
6973 goto out;
6974 }
6975
6976 panic("dtrace: undersized error hash");
6977 out:
6978 lck_mtx_unlock(&dtrace_errlock);
6979 }
6980 #endif
6981
6982 /*
6983 * DTrace Matching Functions
6984 *
6985 * These functions are used to match groups of probes, given some elements of
6986 * a probe tuple, or some globbed expressions for elements of a probe tuple.
6987 */
6988 static int
6989 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6990 zoneid_t zoneid)
6991 {
6992 if (priv != DTRACE_PRIV_ALL) {
6993 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6994 uint32_t match = priv & ppriv;
6995
6996 /*
6997 * No PRIV_DTRACE_* privileges...
6998 */
6999 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7000 DTRACE_PRIV_KERNEL)) == 0)
7001 return (0);
7002
7003 /*
7004 * No matching bits, but there were bits to match...
7005 */
7006 if (match == 0 && ppriv != 0)
7007 return (0);
7008
7009 /*
7010 * Need to have permissions to the process, but don't...
7011 */
7012 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7013 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7014 return (0);
7015 }
7016
7017 /*
7018 * Need to be in the same zone unless we possess the
7019 * privilege to examine all zones.
7020 */
7021 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7022 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7023 return (0);
7024 }
7025 }
7026
7027 return (1);
7028 }
7029
7030 /*
7031 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7032 * consists of input pattern strings and an ops-vector to evaluate them.
7033 * This function returns >0 for match, 0 for no match, and <0 for error.
7034 */
7035 static int
7036 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7037 uint32_t priv, uid_t uid, zoneid_t zoneid)
7038 {
7039 dtrace_provider_t *pvp = prp->dtpr_provider;
7040 int rv;
7041
7042 if (pvp->dtpv_defunct)
7043 return (0);
7044
7045 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7046 return (rv);
7047
7048 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7049 return (rv);
7050
7051 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7052 return (rv);
7053
7054 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7055 return (rv);
7056
7057 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7058 return (0);
7059
7060 return (rv);
7061 }
7062
7063 /*
7064 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7065 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7066 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7067 * In addition, all of the recursion cases except for '*' matching have been
7068 * unwound. For '*', we still implement recursive evaluation, but a depth
7069 * counter is maintained and matching is aborted if we recurse too deep.
7070 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7071 */
7072 static int
7073 dtrace_match_glob(const char *s, const char *p, int depth)
7074 {
7075 const char *olds;
7076 char s1, c;
7077 int gs;
7078
7079 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7080 return (-1);
7081
7082 if (s == NULL)
7083 s = ""; /* treat NULL as empty string */
7084
7085 top:
7086 olds = s;
7087 s1 = *s++;
7088
7089 if (p == NULL)
7090 return (0);
7091
7092 if ((c = *p++) == '\0')
7093 return (s1 == '\0');
7094
7095 switch (c) {
7096 case '[': {
7097 int ok = 0, notflag = 0;
7098 char lc = '\0';
7099
7100 if (s1 == '\0')
7101 return (0);
7102
7103 if (*p == '!') {
7104 notflag = 1;
7105 p++;
7106 }
7107
7108 if ((c = *p++) == '\0')
7109 return (0);
7110
7111 do {
7112 if (c == '-' && lc != '\0' && *p != ']') {
7113 if ((c = *p++) == '\0')
7114 return (0);
7115 if (c == '\\' && (c = *p++) == '\0')
7116 return (0);
7117
7118 if (notflag) {
7119 if (s1 < lc || s1 > c)
7120 ok++;
7121 else
7122 return (0);
7123 } else if (lc <= s1 && s1 <= c)
7124 ok++;
7125
7126 } else if (c == '\\' && (c = *p++) == '\0')
7127 return (0);
7128
7129 lc = c; /* save left-hand 'c' for next iteration */
7130
7131 if (notflag) {
7132 if (s1 != c)
7133 ok++;
7134 else
7135 return (0);
7136 } else if (s1 == c)
7137 ok++;
7138
7139 if ((c = *p++) == '\0')
7140 return (0);
7141
7142 } while (c != ']');
7143
7144 if (ok)
7145 goto top;
7146
7147 return (0);
7148 }
7149
7150 case '\\':
7151 if ((c = *p++) == '\0')
7152 return (0);
7153 /*FALLTHRU*/
7154
7155 default:
7156 if (c != s1)
7157 return (0);
7158 /*FALLTHRU*/
7159
7160 case '?':
7161 if (s1 != '\0')
7162 goto top;
7163 return (0);
7164
7165 case '*':
7166 while (*p == '*')
7167 p++; /* consecutive *'s are identical to a single one */
7168
7169 if (*p == '\0')
7170 return (1);
7171
7172 for (s = olds; *s != '\0'; s++) {
7173 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7174 return (gs);
7175 }
7176
7177 return (0);
7178 }
7179 }
7180
7181 /*ARGSUSED*/
7182 static int
7183 dtrace_match_string(const char *s, const char *p, int depth)
7184 {
7185 #pragma unused(depth) /* __APPLE__ */
7186
7187 /* APPLE NOTE: Darwin employs size bounded string operation. */
7188 return (s != NULL && strncmp(s, p, strlen(s) + 1) == 0);
7189 }
7190
7191 /*ARGSUSED*/
7192 static int
7193 dtrace_match_nul(const char *s, const char *p, int depth)
7194 {
7195 #pragma unused(s, p, depth) /* __APPLE__ */
7196 return (1); /* always match the empty pattern */
7197 }
7198
7199 /*ARGSUSED*/
7200 static int
7201 dtrace_match_nonzero(const char *s, const char *p, int depth)
7202 {
7203 #pragma unused(p, depth) /* __APPLE__ */
7204 return (s != NULL && s[0] != '\0');
7205 }
7206
7207 static int
7208 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7209 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7210 {
7211 dtrace_probe_t template, *probe;
7212 dtrace_hash_t *hash = NULL;
7213 int len, rc, best = INT_MAX, nmatched = 0;
7214 dtrace_id_t i;
7215
7216 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7217
7218 /*
7219 * If the probe ID is specified in the key, just lookup by ID and
7220 * invoke the match callback once if a matching probe is found.
7221 */
7222 if (pkp->dtpk_id != DTRACE_IDNONE) {
7223 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7224 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7225 if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7226 return (DTRACE_MATCH_FAIL);
7227 nmatched++;
7228 }
7229 return (nmatched);
7230 }
7231
7232 template.dtpr_mod = (char *)(uintptr_t)pkp->dtpk_mod;
7233 template.dtpr_func = (char *)(uintptr_t)pkp->dtpk_func;
7234 template.dtpr_name = (char *)(uintptr_t)pkp->dtpk_name;
7235
7236 /*
7237 * We want to find the most distinct of the module name, function
7238 * name, and name. So for each one that is not a glob pattern or
7239 * empty string, we perform a lookup in the corresponding hash and
7240 * use the hash table with the fewest collisions to do our search.
7241 */
7242 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7243 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7244 best = len;
7245 hash = dtrace_bymod;
7246 }
7247
7248 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7249 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7250 best = len;
7251 hash = dtrace_byfunc;
7252 }
7253
7254 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7255 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7256 best = len;
7257 hash = dtrace_byname;
7258 }
7259
7260 /*
7261 * If we did not select a hash table, iterate over every probe and
7262 * invoke our callback for each one that matches our input probe key.
7263 */
7264 if (hash == NULL) {
7265 for (i = 0; i < (dtrace_id_t)dtrace_nprobes; i++) {
7266 if ((probe = dtrace_probes[i]) == NULL ||
7267 dtrace_match_probe(probe, pkp, priv, uid,
7268 zoneid) <= 0)
7269 continue;
7270
7271 nmatched++;
7272
7273 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7274 if (rc == DTRACE_MATCH_FAIL)
7275 return (DTRACE_MATCH_FAIL);
7276 break;
7277 }
7278 }
7279
7280 return (nmatched);
7281 }
7282
7283 /*
7284 * If we selected a hash table, iterate over each probe of the same key
7285 * name and invoke the callback for every probe that matches the other
7286 * attributes of our input probe key.
7287 */
7288 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7289 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7290
7291 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7292 continue;
7293
7294 nmatched++;
7295
7296 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7297 if (rc == DTRACE_MATCH_FAIL)
7298 return (DTRACE_MATCH_FAIL);
7299 break;
7300 }
7301 }
7302
7303 return (nmatched);
7304 }
7305
7306 /*
7307 * Return the function pointer dtrace_probecmp() should use to compare the
7308 * specified pattern with a string. For NULL or empty patterns, we select
7309 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7310 * For non-empty non-glob strings, we use dtrace_match_string().
7311 */
7312 static dtrace_probekey_f *
7313 dtrace_probekey_func(const char *p)
7314 {
7315 char c;
7316
7317 if (p == NULL || *p == '\0')
7318 return (&dtrace_match_nul);
7319
7320 while ((c = *p++) != '\0') {
7321 if (c == '[' || c == '?' || c == '*' || c == '\\')
7322 return (&dtrace_match_glob);
7323 }
7324
7325 return (&dtrace_match_string);
7326 }
7327
7328 /*
7329 * Build a probe comparison key for use with dtrace_match_probe() from the
7330 * given probe description. By convention, a null key only matches anchored
7331 * probes: if each field is the empty string, reset dtpk_fmatch to
7332 * dtrace_match_nonzero().
7333 */
7334 static void
7335 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7336 {
7337 pkp->dtpk_prov = pdp->dtpd_provider;
7338 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7339
7340 pkp->dtpk_mod = pdp->dtpd_mod;
7341 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7342
7343 pkp->dtpk_func = pdp->dtpd_func;
7344 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7345
7346 pkp->dtpk_name = pdp->dtpd_name;
7347 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7348
7349 pkp->dtpk_id = pdp->dtpd_id;
7350
7351 if (pkp->dtpk_id == DTRACE_IDNONE &&
7352 pkp->dtpk_pmatch == &dtrace_match_nul &&
7353 pkp->dtpk_mmatch == &dtrace_match_nul &&
7354 pkp->dtpk_fmatch == &dtrace_match_nul &&
7355 pkp->dtpk_nmatch == &dtrace_match_nul)
7356 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7357 }
7358
7359 /*
7360 * DTrace Provider-to-Framework API Functions
7361 *
7362 * These functions implement much of the Provider-to-Framework API, as
7363 * described in <sys/dtrace.h>. The parts of the API not in this section are
7364 * the functions in the API for probe management (found below), and
7365 * dtrace_probe() itself (found above).
7366 */
7367
7368 /*
7369 * Register the calling provider with the DTrace framework. This should
7370 * generally be called by DTrace providers in their attach(9E) entry point.
7371 */
7372 int
7373 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7374 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7375 {
7376 dtrace_provider_t *provider;
7377
7378 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7379 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7380 "arguments", name ? name : "<NULL>");
7381 return (EINVAL);
7382 }
7383
7384 if (name[0] == '\0' || dtrace_badname(name)) {
7385 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7386 "provider name", name);
7387 return (EINVAL);
7388 }
7389
7390 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7391 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7392 pops->dtps_destroy == NULL ||
7393 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7394 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7395 "provider ops", name);
7396 return (EINVAL);
7397 }
7398
7399 if (dtrace_badattr(&pap->dtpa_provider) ||
7400 dtrace_badattr(&pap->dtpa_mod) ||
7401 dtrace_badattr(&pap->dtpa_func) ||
7402 dtrace_badattr(&pap->dtpa_name) ||
7403 dtrace_badattr(&pap->dtpa_args)) {
7404 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7405 "provider attributes", name);
7406 return (EINVAL);
7407 }
7408
7409 if (priv & ~DTRACE_PRIV_ALL) {
7410 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7411 "privilege attributes", name);
7412 return (EINVAL);
7413 }
7414
7415 if ((priv & DTRACE_PRIV_KERNEL) &&
7416 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7417 pops->dtps_usermode == NULL) {
7418 cmn_err(CE_WARN, "failed to register provider '%s': need "
7419 "dtps_usermode() op for given privilege attributes", name);
7420 return (EINVAL);
7421 }
7422
7423 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7424
7425 /* APPLE NOTE: Darwin employs size bounded string operation. */
7426 {
7427 size_t bufsize = strlen(name) + 1;
7428 provider->dtpv_name = kmem_alloc(bufsize, KM_SLEEP);
7429 (void) strlcpy(provider->dtpv_name, name, bufsize);
7430 }
7431
7432 provider->dtpv_attr = *pap;
7433 provider->dtpv_priv.dtpp_flags = priv;
7434 if (cr != NULL) {
7435 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7436 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7437 }
7438 provider->dtpv_pops = *pops;
7439
7440 if (pops->dtps_provide == NULL) {
7441 ASSERT(pops->dtps_provide_module != NULL);
7442 provider->dtpv_pops.dtps_provide =
7443 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7444 }
7445
7446 if (pops->dtps_provide_module == NULL) {
7447 ASSERT(pops->dtps_provide != NULL);
7448 provider->dtpv_pops.dtps_provide_module =
7449 (void (*)(void *, struct modctl *))dtrace_nullop;
7450 }
7451
7452 if (pops->dtps_suspend == NULL) {
7453 ASSERT(pops->dtps_resume == NULL);
7454 provider->dtpv_pops.dtps_suspend =
7455 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7456 provider->dtpv_pops.dtps_resume =
7457 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7458 }
7459
7460 provider->dtpv_arg = arg;
7461 *idp = (dtrace_provider_id_t)provider;
7462
7463 if (pops == &dtrace_provider_ops) {
7464 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7465 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7466 ASSERT(dtrace_anon.dta_enabling == NULL);
7467
7468 /*
7469 * We make sure that the DTrace provider is at the head of
7470 * the provider chain.
7471 */
7472 provider->dtpv_next = dtrace_provider;
7473 dtrace_provider = provider;
7474 return (0);
7475 }
7476
7477 lck_mtx_lock(&dtrace_provider_lock);
7478 lck_mtx_lock(&dtrace_lock);
7479
7480 /*
7481 * If there is at least one provider registered, we'll add this
7482 * provider after the first provider.
7483 */
7484 if (dtrace_provider != NULL) {
7485 provider->dtpv_next = dtrace_provider->dtpv_next;
7486 dtrace_provider->dtpv_next = provider;
7487 } else {
7488 dtrace_provider = provider;
7489 }
7490
7491 if (dtrace_retained != NULL) {
7492 dtrace_enabling_provide(provider);
7493
7494 /*
7495 * Now we need to call dtrace_enabling_matchall() -- which
7496 * will acquire cpu_lock and dtrace_lock. We therefore need
7497 * to drop all of our locks before calling into it...
7498 */
7499 lck_mtx_unlock(&dtrace_lock);
7500 lck_mtx_unlock(&dtrace_provider_lock);
7501 dtrace_enabling_matchall();
7502
7503 return (0);
7504 }
7505
7506 lck_mtx_unlock(&dtrace_lock);
7507 lck_mtx_unlock(&dtrace_provider_lock);
7508
7509 return (0);
7510 }
7511
7512 /*
7513 * Unregister the specified provider from the DTrace framework. This should
7514 * generally be called by DTrace providers in their detach(9E) entry point.
7515 */
7516 int
7517 dtrace_unregister(dtrace_provider_id_t id)
7518 {
7519 dtrace_provider_t *old = (dtrace_provider_t *)id;
7520 dtrace_provider_t *prev = NULL;
7521 int i, self = 0;
7522 dtrace_probe_t *probe, *first = NULL;
7523
7524 if (old->dtpv_pops.dtps_enable ==
7525 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7526 /*
7527 * If DTrace itself is the provider, we're called with locks
7528 * already held.
7529 */
7530 ASSERT(old == dtrace_provider);
7531 ASSERT(dtrace_devi != NULL);
7532 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7533 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7534 self = 1;
7535
7536 if (dtrace_provider->dtpv_next != NULL) {
7537 /*
7538 * There's another provider here; return failure.
7539 */
7540 return (EBUSY);
7541 }
7542 } else {
7543 lck_mtx_lock(&dtrace_provider_lock);
7544 lck_mtx_lock(&mod_lock);
7545 lck_mtx_lock(&dtrace_lock);
7546 }
7547
7548 /*
7549 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7550 * probes, we refuse to let providers slither away, unless this
7551 * provider has already been explicitly invalidated.
7552 */
7553 if (!old->dtpv_defunct &&
7554 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7555 dtrace_anon.dta_state->dts_necbs > 0))) {
7556 if (!self) {
7557 lck_mtx_unlock(&dtrace_lock);
7558 lck_mtx_unlock(&mod_lock);
7559 lck_mtx_unlock(&dtrace_provider_lock);
7560 }
7561 return (EBUSY);
7562 }
7563
7564 /*
7565 * Attempt to destroy the probes associated with this provider.
7566 */
7567 if (old->dtpv_ecb_count!=0) {
7568 /*
7569 * We have at least one ECB; we can't remove this provider.
7570 */
7571 if (!self) {
7572 lck_mtx_unlock(&dtrace_lock);
7573 lck_mtx_unlock(&mod_lock);
7574 lck_mtx_unlock(&dtrace_provider_lock);
7575 }
7576 return (EBUSY);
7577 }
7578
7579 /*
7580 * All of the probes for this provider are disabled; we can safely
7581 * remove all of them from their hash chains and from the probe array.
7582 */
7583 for (i = 0; i < dtrace_nprobes && old->dtpv_probe_count!=0; i++) {
7584 if ((probe = dtrace_probes[i]) == NULL)
7585 continue;
7586
7587 if (probe->dtpr_provider != old)
7588 continue;
7589
7590 dtrace_probes[i] = NULL;
7591 old->dtpv_probe_count--;
7592
7593 dtrace_hash_remove(dtrace_bymod, probe);
7594 dtrace_hash_remove(dtrace_byfunc, probe);
7595 dtrace_hash_remove(dtrace_byname, probe);
7596
7597 if (first == NULL) {
7598 first = probe;
7599 probe->dtpr_nextmod = NULL;
7600 } else {
7601 probe->dtpr_nextmod = first;
7602 first = probe;
7603 }
7604 }
7605
7606 /*
7607 * The provider's probes have been removed from the hash chains and
7608 * from the probe array. Now issue a dtrace_sync() to be sure that
7609 * everyone has cleared out from any probe array processing.
7610 */
7611 dtrace_sync();
7612
7613 for (probe = first; probe != NULL; probe = first) {
7614 first = probe->dtpr_nextmod;
7615
7616 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7617 probe->dtpr_arg);
7618 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7619 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7620 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7621 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7622 zfree(dtrace_probe_t_zone, probe);
7623 }
7624
7625 if ((prev = dtrace_provider) == old) {
7626 ASSERT(self || dtrace_devi == NULL);
7627 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7628 dtrace_provider = old->dtpv_next;
7629 } else {
7630 while (prev != NULL && prev->dtpv_next != old)
7631 prev = prev->dtpv_next;
7632
7633 if (prev == NULL) {
7634 panic("attempt to unregister non-existent "
7635 "dtrace provider %p\n", (void *)id);
7636 }
7637
7638 prev->dtpv_next = old->dtpv_next;
7639 }
7640
7641 if (!self) {
7642 lck_mtx_unlock(&dtrace_lock);
7643 lck_mtx_unlock(&mod_lock);
7644 lck_mtx_unlock(&dtrace_provider_lock);
7645 }
7646
7647 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7648 kmem_free(old, sizeof (dtrace_provider_t));
7649
7650 return (0);
7651 }
7652
7653 /*
7654 * Invalidate the specified provider. All subsequent probe lookups for the
7655 * specified provider will fail, but its probes will not be removed.
7656 */
7657 void
7658 dtrace_invalidate(dtrace_provider_id_t id)
7659 {
7660 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7661
7662 ASSERT(pvp->dtpv_pops.dtps_enable !=
7663 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7664
7665 lck_mtx_lock(&dtrace_provider_lock);
7666 lck_mtx_lock(&dtrace_lock);
7667
7668 pvp->dtpv_defunct = 1;
7669
7670 lck_mtx_unlock(&dtrace_lock);
7671 lck_mtx_unlock(&dtrace_provider_lock);
7672 }
7673
7674 /*
7675 * Indicate whether or not DTrace has attached.
7676 */
7677 int
7678 dtrace_attached(void)
7679 {
7680 /*
7681 * dtrace_provider will be non-NULL iff the DTrace driver has
7682 * attached. (It's non-NULL because DTrace is always itself a
7683 * provider.)
7684 */
7685 return (dtrace_provider != NULL);
7686 }
7687
7688 /*
7689 * Remove all the unenabled probes for the given provider. This function is
7690 * not unlike dtrace_unregister(), except that it doesn't remove the provider
7691 * -- just as many of its associated probes as it can.
7692 */
7693 int
7694 dtrace_condense(dtrace_provider_id_t id)
7695 {
7696 dtrace_provider_t *prov = (dtrace_provider_t *)id;
7697 int i;
7698 dtrace_probe_t *probe;
7699
7700 /*
7701 * Make sure this isn't the dtrace provider itself.
7702 */
7703 ASSERT(prov->dtpv_pops.dtps_enable !=
7704 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7705
7706 lck_mtx_lock(&dtrace_provider_lock);
7707 lck_mtx_lock(&dtrace_lock);
7708
7709 /*
7710 * Attempt to destroy the probes associated with this provider.
7711 */
7712 for (i = 0; i < dtrace_nprobes; i++) {
7713 if ((probe = dtrace_probes[i]) == NULL)
7714 continue;
7715
7716 if (probe->dtpr_provider != prov)
7717 continue;
7718
7719 if (probe->dtpr_ecb != NULL)
7720 continue;
7721
7722 dtrace_probes[i] = NULL;
7723 prov->dtpv_probe_count--;
7724
7725 dtrace_hash_remove(dtrace_bymod, probe);
7726 dtrace_hash_remove(dtrace_byfunc, probe);
7727 dtrace_hash_remove(dtrace_byname, probe);
7728
7729 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7730 probe->dtpr_arg);
7731 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7732 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7733 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7734 zfree(dtrace_probe_t_zone, probe);
7735 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7736 }
7737
7738 lck_mtx_unlock(&dtrace_lock);
7739 lck_mtx_unlock(&dtrace_provider_lock);
7740
7741 return (0);
7742 }
7743
7744 /*
7745 * DTrace Probe Management Functions
7746 *
7747 * The functions in this section perform the DTrace probe management,
7748 * including functions to create probes, look-up probes, and call into the
7749 * providers to request that probes be provided. Some of these functions are
7750 * in the Provider-to-Framework API; these functions can be identified by the
7751 * fact that they are not declared "static".
7752 */
7753
7754 /*
7755 * Create a probe with the specified module name, function name, and name.
7756 */
7757 dtrace_id_t
7758 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7759 const char *func, const char *name, int aframes, void *arg)
7760 {
7761 dtrace_probe_t *probe, **probes;
7762 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7763 dtrace_id_t id;
7764
7765 if (provider == dtrace_provider) {
7766 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7767 } else {
7768 lck_mtx_lock(&dtrace_lock);
7769 }
7770
7771 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7772 VM_BESTFIT | VM_SLEEP);
7773
7774 probe = zalloc(dtrace_probe_t_zone);
7775 bzero(probe, sizeof (dtrace_probe_t));
7776
7777 probe->dtpr_id = id;
7778 probe->dtpr_gen = dtrace_probegen++;
7779 probe->dtpr_mod = dtrace_strdup(mod);
7780 probe->dtpr_func = dtrace_strdup(func);
7781 probe->dtpr_name = dtrace_strdup(name);
7782 probe->dtpr_arg = arg;
7783 probe->dtpr_aframes = aframes;
7784 probe->dtpr_provider = provider;
7785
7786 dtrace_hash_add(dtrace_bymod, probe);
7787 dtrace_hash_add(dtrace_byfunc, probe);
7788 dtrace_hash_add(dtrace_byname, probe);
7789
7790 if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
7791 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7792 size_t nsize = osize << 1;
7793
7794 if (nsize == 0) {
7795 ASSERT(osize == 0);
7796 ASSERT(dtrace_probes == NULL);
7797 nsize = sizeof (dtrace_probe_t *);
7798 }
7799
7800 probes = kmem_zalloc(nsize, KM_SLEEP);
7801
7802 if (dtrace_probes == NULL) {
7803 ASSERT(osize == 0);
7804 dtrace_probes = probes;
7805 dtrace_nprobes = 1;
7806 } else {
7807 dtrace_probe_t **oprobes = dtrace_probes;
7808
7809 bcopy(oprobes, probes, osize);
7810 dtrace_membar_producer();
7811 dtrace_probes = probes;
7812
7813 dtrace_sync();
7814
7815 /*
7816 * All CPUs are now seeing the new probes array; we can
7817 * safely free the old array.
7818 */
7819 kmem_free(oprobes, osize);
7820 dtrace_nprobes <<= 1;
7821 }
7822
7823 ASSERT(id - 1 < (dtrace_id_t)dtrace_nprobes);
7824 }
7825
7826 ASSERT(dtrace_probes[id - 1] == NULL);
7827 dtrace_probes[id - 1] = probe;
7828 provider->dtpv_probe_count++;
7829
7830 if (provider != dtrace_provider)
7831 lck_mtx_unlock(&dtrace_lock);
7832
7833 return (id);
7834 }
7835
7836 static dtrace_probe_t *
7837 dtrace_probe_lookup_id(dtrace_id_t id)
7838 {
7839 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7840
7841 if (id == 0 || id > (dtrace_id_t)dtrace_nprobes)
7842 return (NULL);
7843
7844 return (dtrace_probes[id - 1]);
7845 }
7846
7847 static int
7848 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7849 {
7850 *((dtrace_id_t *)arg) = probe->dtpr_id;
7851
7852 return (DTRACE_MATCH_DONE);
7853 }
7854
7855 /*
7856 * Look up a probe based on provider and one or more of module name, function
7857 * name and probe name.
7858 */
7859 dtrace_id_t
7860 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7861 const char *func, const char *name)
7862 {
7863 dtrace_probekey_t pkey;
7864 dtrace_id_t id;
7865 int match;
7866
7867 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7868 pkey.dtpk_pmatch = &dtrace_match_string;
7869 pkey.dtpk_mod = mod;
7870 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7871 pkey.dtpk_func = func;
7872 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7873 pkey.dtpk_name = name;
7874 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7875 pkey.dtpk_id = DTRACE_IDNONE;
7876
7877 lck_mtx_lock(&dtrace_lock);
7878 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7879 dtrace_probe_lookup_match, &id);
7880 lck_mtx_unlock(&dtrace_lock);
7881
7882 ASSERT(match == 1 || match == 0);
7883 return (match ? id : 0);
7884 }
7885
7886 /*
7887 * Returns the probe argument associated with the specified probe.
7888 */
7889 void *
7890 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7891 {
7892 dtrace_probe_t *probe;
7893 void *rval = NULL;
7894
7895 lck_mtx_lock(&dtrace_lock);
7896
7897 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7898 probe->dtpr_provider == (dtrace_provider_t *)id)
7899 rval = probe->dtpr_arg;
7900
7901 lck_mtx_unlock(&dtrace_lock);
7902
7903 return (rval);
7904 }
7905
7906 /*
7907 * Copy a probe into a probe description.
7908 */
7909 static void
7910 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7911 {
7912 bzero(pdp, sizeof (dtrace_probedesc_t));
7913 pdp->dtpd_id = prp->dtpr_id;
7914
7915 /* APPLE NOTE: Darwin employs size bounded string operation. */
7916 (void) strlcpy(pdp->dtpd_provider,
7917 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN);
7918
7919 (void) strlcpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN);
7920 (void) strlcpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN);
7921 (void) strlcpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN);
7922 }
7923
7924 /*
7925 * Called to indicate that a probe -- or probes -- should be provided by a
7926 * specfied provider. If the specified description is NULL, the provider will
7927 * be told to provide all of its probes. (This is done whenever a new
7928 * consumer comes along, or whenever a retained enabling is to be matched.) If
7929 * the specified description is non-NULL, the provider is given the
7930 * opportunity to dynamically provide the specified probe, allowing providers
7931 * to support the creation of probes on-the-fly. (So-called _autocreated_
7932 * probes.) If the provider is NULL, the operations will be applied to all
7933 * providers; if the provider is non-NULL the operations will only be applied
7934 * to the specified provider. The dtrace_provider_lock must be held, and the
7935 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7936 * will need to grab the dtrace_lock when it reenters the framework through
7937 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7938 */
7939 static void
7940 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7941 {
7942 struct modctl *ctl;
7943 int all = 0;
7944
7945 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7946
7947 if (prv == NULL) {
7948 all = 1;
7949 prv = dtrace_provider;
7950 }
7951
7952 do {
7953 /*
7954 * First, call the blanket provide operation.
7955 */
7956 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7957
7958 /*
7959 * Now call the per-module provide operation. We will grab
7960 * mod_lock to prevent the list from being modified. Note
7961 * that this also prevents the mod_busy bits from changing.
7962 * (mod_busy can only be changed with mod_lock held.)
7963 */
7964 lck_mtx_lock(&mod_lock);
7965
7966 ctl = dtrace_modctl_list;
7967 while (ctl) {
7968 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7969 ctl = ctl->mod_next;
7970 }
7971
7972 lck_mtx_unlock(&mod_lock);
7973 } while (all && (prv = prv->dtpv_next) != NULL);
7974 }
7975
7976 /*
7977 * Iterate over each probe, and call the Framework-to-Provider API function
7978 * denoted by offs.
7979 */
7980 static void
7981 dtrace_probe_foreach(uintptr_t offs)
7982 {
7983 dtrace_provider_t *prov;
7984 void (*func)(void *, dtrace_id_t, void *);
7985 dtrace_probe_t *probe;
7986 dtrace_icookie_t cookie;
7987 int i;
7988
7989 /*
7990 * We disable interrupts to walk through the probe array. This is
7991 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7992 * won't see stale data.
7993 */
7994 cookie = dtrace_interrupt_disable();
7995
7996 for (i = 0; i < dtrace_nprobes; i++) {
7997 if ((probe = dtrace_probes[i]) == NULL)
7998 continue;
7999
8000 if (probe->dtpr_ecb == NULL) {
8001 /*
8002 * This probe isn't enabled -- don't call the function.
8003 */
8004 continue;
8005 }
8006
8007 prov = probe->dtpr_provider;
8008 func = *((void(**)(void *, dtrace_id_t, void *))
8009 ((uintptr_t)&prov->dtpv_pops + offs));
8010
8011 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8012 }
8013
8014 dtrace_interrupt_enable(cookie);
8015 }
8016
8017 static int
8018 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8019 {
8020 dtrace_probekey_t pkey;
8021 uint32_t priv;
8022 uid_t uid;
8023 zoneid_t zoneid;
8024
8025 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8026
8027 dtrace_ecb_create_cache = NULL;
8028
8029 if (desc == NULL) {
8030 /*
8031 * If we're passed a NULL description, we're being asked to
8032 * create an ECB with a NULL probe.
8033 */
8034 (void) dtrace_ecb_create_enable(NULL, enab);
8035 return (0);
8036 }
8037
8038 dtrace_probekey(desc, &pkey);
8039 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8040 &priv, &uid, &zoneid);
8041
8042 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8043 enab));
8044 }
8045
8046 /*
8047 * DTrace Helper Provider Functions
8048 */
8049 static void
8050 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8051 {
8052 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8053 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8054 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8055 }
8056
8057 static void
8058 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8059 const dof_provider_t *dofprov, char *strtab)
8060 {
8061 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8062 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8063 dofprov->dofpv_provattr);
8064 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8065 dofprov->dofpv_modattr);
8066 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8067 dofprov->dofpv_funcattr);
8068 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8069 dofprov->dofpv_nameattr);
8070 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8071 dofprov->dofpv_argsattr);
8072 }
8073
8074 static void
8075 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8076 {
8077 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8078 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8079 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8080 dof_provider_t *provider;
8081 dof_probe_t *probe;
8082 uint32_t *off, *enoff;
8083 uint8_t *arg;
8084 char *strtab;
8085 uint_t i, nprobes;
8086 dtrace_helper_provdesc_t dhpv;
8087 dtrace_helper_probedesc_t dhpb;
8088 dtrace_meta_t *meta = dtrace_meta_pid;
8089 dtrace_mops_t *mops = &meta->dtm_mops;
8090 void *parg;
8091
8092 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8093 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8094 provider->dofpv_strtab * dof->dofh_secsize);
8095 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8096 provider->dofpv_probes * dof->dofh_secsize);
8097 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8098 provider->dofpv_prargs * dof->dofh_secsize);
8099 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8100 provider->dofpv_proffs * dof->dofh_secsize);
8101
8102 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8103 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8104 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8105 enoff = NULL;
8106
8107 /*
8108 * See dtrace_helper_provider_validate().
8109 */
8110 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8111 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8112 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8113 provider->dofpv_prenoffs * dof->dofh_secsize);
8114 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8115 }
8116
8117 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8118
8119 /*
8120 * Create the provider.
8121 */
8122 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8123
8124 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8125 return;
8126
8127 meta->dtm_count++;
8128
8129 /*
8130 * Create the probes.
8131 */
8132 for (i = 0; i < nprobes; i++) {
8133 probe = (dof_probe_t *)(uintptr_t)(daddr +
8134 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8135
8136 dhpb.dthpb_mod = dhp->dofhp_mod;
8137 dhpb.dthpb_func = strtab + probe->dofpr_func;
8138 dhpb.dthpb_name = strtab + probe->dofpr_name;
8139 #if !defined(__APPLE__)
8140 dhpb.dthpb_base = probe->dofpr_addr;
8141 #else
8142 dhpb.dthpb_base = dhp->dofhp_addr; /* FIXME: James, why? */
8143 #endif
8144 dhpb.dthpb_offs = (int32_t *)(off + probe->dofpr_offidx);
8145 dhpb.dthpb_noffs = probe->dofpr_noffs;
8146 if (enoff != NULL) {
8147 dhpb.dthpb_enoffs = (int32_t *)(enoff + probe->dofpr_enoffidx);
8148 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8149 } else {
8150 dhpb.dthpb_enoffs = NULL;
8151 dhpb.dthpb_nenoffs = 0;
8152 }
8153 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8154 dhpb.dthpb_nargc = probe->dofpr_nargc;
8155 dhpb.dthpb_xargc = probe->dofpr_xargc;
8156 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8157 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8158
8159 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8160 }
8161 }
8162
8163 static void
8164 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8165 {
8166 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8167 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8168 uint32_t i;
8169
8170 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8171
8172 for (i = 0; i < dof->dofh_secnum; i++) {
8173 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8174 dof->dofh_secoff + i * dof->dofh_secsize);
8175
8176 if (sec->dofs_type != DOF_SECT_PROVIDER)
8177 continue;
8178
8179 dtrace_helper_provide_one(dhp, sec, pid);
8180 }
8181
8182 /*
8183 * We may have just created probes, so we must now rematch against
8184 * any retained enablings. Note that this call will acquire both
8185 * cpu_lock and dtrace_lock; the fact that we are holding
8186 * dtrace_meta_lock now is what defines the ordering with respect to
8187 * these three locks.
8188 */
8189 dtrace_enabling_matchall();
8190 }
8191
8192 static void
8193 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8194 {
8195 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8196 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8197 dof_sec_t *str_sec;
8198 dof_provider_t *provider;
8199 char *strtab;
8200 dtrace_helper_provdesc_t dhpv;
8201 dtrace_meta_t *meta = dtrace_meta_pid;
8202 dtrace_mops_t *mops = &meta->dtm_mops;
8203
8204 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8205 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8206 provider->dofpv_strtab * dof->dofh_secsize);
8207
8208 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8209
8210 /*
8211 * Create the provider.
8212 */
8213 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8214
8215 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8216
8217 meta->dtm_count--;
8218 }
8219
8220 static void
8221 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8222 {
8223 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8224 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8225 uint32_t i;
8226
8227 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8228
8229 for (i = 0; i < dof->dofh_secnum; i++) {
8230 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8231 dof->dofh_secoff + i * dof->dofh_secsize);
8232
8233 if (sec->dofs_type != DOF_SECT_PROVIDER)
8234 continue;
8235
8236 dtrace_helper_provider_remove_one(dhp, sec, pid);
8237 }
8238 }
8239
8240 /*
8241 * DTrace Meta Provider-to-Framework API Functions
8242 *
8243 * These functions implement the Meta Provider-to-Framework API, as described
8244 * in <sys/dtrace.h>.
8245 */
8246 int
8247 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8248 dtrace_meta_provider_id_t *idp)
8249 {
8250 dtrace_meta_t *meta;
8251 dtrace_helpers_t *help, *next;
8252 uint_t i;
8253
8254 *idp = DTRACE_METAPROVNONE;
8255
8256 /*
8257 * We strictly don't need the name, but we hold onto it for
8258 * debuggability. All hail error queues!
8259 */
8260 if (name == NULL) {
8261 cmn_err(CE_WARN, "failed to register meta-provider: "
8262 "invalid name");
8263 return (EINVAL);
8264 }
8265
8266 if (mops == NULL ||
8267 mops->dtms_create_probe == NULL ||
8268 mops->dtms_provide_pid == NULL ||
8269 mops->dtms_remove_pid == NULL) {
8270 cmn_err(CE_WARN, "failed to register meta-register %s: "
8271 "invalid ops", name);
8272 return (EINVAL);
8273 }
8274
8275 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8276 meta->dtm_mops = *mops;
8277
8278 /* APPLE NOTE: Darwin employs size bounded string operation. */
8279 {
8280 size_t bufsize = strlen(name) + 1;
8281 meta->dtm_name = kmem_alloc(bufsize, KM_SLEEP);
8282 (void) strlcpy(meta->dtm_name, name, bufsize);
8283 }
8284
8285 meta->dtm_arg = arg;
8286
8287 lck_mtx_lock(&dtrace_meta_lock);
8288 lck_mtx_lock(&dtrace_lock);
8289
8290 if (dtrace_meta_pid != NULL) {
8291 lck_mtx_unlock(&dtrace_lock);
8292 lck_mtx_unlock(&dtrace_meta_lock);
8293 cmn_err(CE_WARN, "failed to register meta-register %s: "
8294 "user-land meta-provider exists", name);
8295 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8296 kmem_free(meta, sizeof (dtrace_meta_t));
8297 return (EINVAL);
8298 }
8299
8300 dtrace_meta_pid = meta;
8301 *idp = (dtrace_meta_provider_id_t)meta;
8302
8303 /*
8304 * If there are providers and probes ready to go, pass them
8305 * off to the new meta provider now.
8306 */
8307
8308 help = dtrace_deferred_pid;
8309 dtrace_deferred_pid = NULL;
8310
8311 lck_mtx_unlock(&dtrace_lock);
8312
8313 while (help != NULL) {
8314 for (i = 0; i < help->dthps_nprovs; i++) {
8315 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8316 help->dthps_pid);
8317 }
8318
8319 next = help->dthps_next;
8320 help->dthps_next = NULL;
8321 help->dthps_prev = NULL;
8322 help->dthps_deferred = 0;
8323 help = next;
8324 }
8325
8326 lck_mtx_unlock(&dtrace_meta_lock);
8327
8328 return (0);
8329 }
8330
8331 int
8332 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8333 {
8334 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8335
8336 lck_mtx_lock(&dtrace_meta_lock);
8337 lck_mtx_lock(&dtrace_lock);
8338
8339 if (old == dtrace_meta_pid) {
8340 pp = &dtrace_meta_pid;
8341 } else {
8342 panic("attempt to unregister non-existent "
8343 "dtrace meta-provider %p\n", (void *)old);
8344 }
8345
8346 if (old->dtm_count != 0) {
8347 lck_mtx_unlock(&dtrace_lock);
8348 lck_mtx_unlock(&dtrace_meta_lock);
8349 return (EBUSY);
8350 }
8351
8352 *pp = NULL;
8353
8354 lck_mtx_unlock(&dtrace_lock);
8355 lck_mtx_unlock(&dtrace_meta_lock);
8356
8357 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8358 kmem_free(old, sizeof (dtrace_meta_t));
8359
8360 return (0);
8361 }
8362
8363
8364 /*
8365 * DTrace DIF Object Functions
8366 */
8367 static int
8368 dtrace_difo_err(uint_t pc, const char *format, ...)
8369 {
8370 if (dtrace_err_verbose) {
8371 va_list alist;
8372
8373 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8374 va_start(alist, format);
8375 (void) vuprintf(format, alist);
8376 va_end(alist);
8377 }
8378
8379 #ifdef DTRACE_ERRDEBUG
8380 dtrace_errdebug(format);
8381 #endif
8382 return (1);
8383 }
8384
8385 /*
8386 * Validate a DTrace DIF object by checking the IR instructions. The following
8387 * rules are currently enforced by dtrace_difo_validate():
8388 *
8389 * 1. Each instruction must have a valid opcode
8390 * 2. Each register, string, variable, or subroutine reference must be valid
8391 * 3. No instruction can modify register %r0 (must be zero)
8392 * 4. All instruction reserved bits must be set to zero
8393 * 5. The last instruction must be a "ret" instruction
8394 * 6. All branch targets must reference a valid instruction _after_ the branch
8395 */
8396 static int
8397 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8398 cred_t *cr)
8399 {
8400 int err = 0;
8401 uint_t i;
8402
8403 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8404 int kcheckload;
8405 uint_t pc;
8406
8407 kcheckload = cr == NULL ||
8408 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8409
8410 dp->dtdo_destructive = 0;
8411
8412 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8413 dif_instr_t instr = dp->dtdo_buf[pc];
8414
8415 uint_t r1 = DIF_INSTR_R1(instr);
8416 uint_t r2 = DIF_INSTR_R2(instr);
8417 uint_t rd = DIF_INSTR_RD(instr);
8418 uint_t rs = DIF_INSTR_RS(instr);
8419 uint_t label = DIF_INSTR_LABEL(instr);
8420 uint_t v = DIF_INSTR_VAR(instr);
8421 uint_t subr = DIF_INSTR_SUBR(instr);
8422 uint_t type = DIF_INSTR_TYPE(instr);
8423 uint_t op = DIF_INSTR_OP(instr);
8424
8425 switch (op) {
8426 case DIF_OP_OR:
8427 case DIF_OP_XOR:
8428 case DIF_OP_AND:
8429 case DIF_OP_SLL:
8430 case DIF_OP_SRL:
8431 case DIF_OP_SRA:
8432 case DIF_OP_SUB:
8433 case DIF_OP_ADD:
8434 case DIF_OP_MUL:
8435 case DIF_OP_SDIV:
8436 case DIF_OP_UDIV:
8437 case DIF_OP_SREM:
8438 case DIF_OP_UREM:
8439 case DIF_OP_COPYS:
8440 if (r1 >= nregs)
8441 err += efunc(pc, "invalid register %u\n", r1);
8442 if (r2 >= nregs)
8443 err += efunc(pc, "invalid register %u\n", r2);
8444 if (rd >= nregs)
8445 err += efunc(pc, "invalid register %u\n", rd);
8446 if (rd == 0)
8447 err += efunc(pc, "cannot write to %r0\n");
8448 break;
8449 case DIF_OP_NOT:
8450 case DIF_OP_MOV:
8451 case DIF_OP_ALLOCS:
8452 if (r1 >= nregs)
8453 err += efunc(pc, "invalid register %u\n", r1);
8454 if (r2 != 0)
8455 err += efunc(pc, "non-zero reserved bits\n");
8456 if (rd >= nregs)
8457 err += efunc(pc, "invalid register %u\n", rd);
8458 if (rd == 0)
8459 err += efunc(pc, "cannot write to %r0\n");
8460 break;
8461 case DIF_OP_LDSB:
8462 case DIF_OP_LDSH:
8463 case DIF_OP_LDSW:
8464 case DIF_OP_LDUB:
8465 case DIF_OP_LDUH:
8466 case DIF_OP_LDUW:
8467 case DIF_OP_LDX:
8468 if (r1 >= nregs)
8469 err += efunc(pc, "invalid register %u\n", r1);
8470 if (r2 != 0)
8471 err += efunc(pc, "non-zero reserved bits\n");
8472 if (rd >= nregs)
8473 err += efunc(pc, "invalid register %u\n", rd);
8474 if (rd == 0)
8475 err += efunc(pc, "cannot write to %r0\n");
8476 if (kcheckload)
8477 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8478 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8479 break;
8480 case DIF_OP_RLDSB:
8481 case DIF_OP_RLDSH:
8482 case DIF_OP_RLDSW:
8483 case DIF_OP_RLDUB:
8484 case DIF_OP_RLDUH:
8485 case DIF_OP_RLDUW:
8486 case DIF_OP_RLDX:
8487 if (r1 >= nregs)
8488 err += efunc(pc, "invalid register %u\n", r1);
8489 if (r2 != 0)
8490 err += efunc(pc, "non-zero reserved bits\n");
8491 if (rd >= nregs)
8492 err += efunc(pc, "invalid register %u\n", rd);
8493 if (rd == 0)
8494 err += efunc(pc, "cannot write to %r0\n");
8495 break;
8496 case DIF_OP_ULDSB:
8497 case DIF_OP_ULDSH:
8498 case DIF_OP_ULDSW:
8499 case DIF_OP_ULDUB:
8500 case DIF_OP_ULDUH:
8501 case DIF_OP_ULDUW:
8502 case DIF_OP_ULDX:
8503 if (r1 >= nregs)
8504 err += efunc(pc, "invalid register %u\n", r1);
8505 if (r2 != 0)
8506 err += efunc(pc, "non-zero reserved bits\n");
8507 if (rd >= nregs)
8508 err += efunc(pc, "invalid register %u\n", rd);
8509 if (rd == 0)
8510 err += efunc(pc, "cannot write to %r0\n");
8511 break;
8512 case DIF_OP_STB:
8513 case DIF_OP_STH:
8514 case DIF_OP_STW:
8515 case DIF_OP_STX:
8516 if (r1 >= nregs)
8517 err += efunc(pc, "invalid register %u\n", r1);
8518 if (r2 != 0)
8519 err += efunc(pc, "non-zero reserved bits\n");
8520 if (rd >= nregs)
8521 err += efunc(pc, "invalid register %u\n", rd);
8522 if (rd == 0)
8523 err += efunc(pc, "cannot write to 0 address\n");
8524 break;
8525 case DIF_OP_CMP:
8526 case DIF_OP_SCMP:
8527 if (r1 >= nregs)
8528 err += efunc(pc, "invalid register %u\n", r1);
8529 if (r2 >= nregs)
8530 err += efunc(pc, "invalid register %u\n", r2);
8531 if (rd != 0)
8532 err += efunc(pc, "non-zero reserved bits\n");
8533 break;
8534 case DIF_OP_TST:
8535 if (r1 >= nregs)
8536 err += efunc(pc, "invalid register %u\n", r1);
8537 if (r2 != 0 || rd != 0)
8538 err += efunc(pc, "non-zero reserved bits\n");
8539 break;
8540 case DIF_OP_BA:
8541 case DIF_OP_BE:
8542 case DIF_OP_BNE:
8543 case DIF_OP_BG:
8544 case DIF_OP_BGU:
8545 case DIF_OP_BGE:
8546 case DIF_OP_BGEU:
8547 case DIF_OP_BL:
8548 case DIF_OP_BLU:
8549 case DIF_OP_BLE:
8550 case DIF_OP_BLEU:
8551 if (label >= dp->dtdo_len) {
8552 err += efunc(pc, "invalid branch target %u\n",
8553 label);
8554 }
8555 if (label <= pc) {
8556 err += efunc(pc, "backward branch to %u\n",
8557 label);
8558 }
8559 break;
8560 case DIF_OP_RET:
8561 if (r1 != 0 || r2 != 0)
8562 err += efunc(pc, "non-zero reserved bits\n");
8563 if (rd >= nregs)
8564 err += efunc(pc, "invalid register %u\n", rd);
8565 break;
8566 case DIF_OP_NOP:
8567 case DIF_OP_POPTS:
8568 case DIF_OP_FLUSHTS:
8569 if (r1 != 0 || r2 != 0 || rd != 0)
8570 err += efunc(pc, "non-zero reserved bits\n");
8571 break;
8572 case DIF_OP_SETX:
8573 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8574 err += efunc(pc, "invalid integer ref %u\n",
8575 DIF_INSTR_INTEGER(instr));
8576 }
8577 if (rd >= nregs)
8578 err += efunc(pc, "invalid register %u\n", rd);
8579 if (rd == 0)
8580 err += efunc(pc, "cannot write to %r0\n");
8581 break;
8582 case DIF_OP_SETS:
8583 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8584 err += efunc(pc, "invalid string ref %u\n",
8585 DIF_INSTR_STRING(instr));
8586 }
8587 if (rd >= nregs)
8588 err += efunc(pc, "invalid register %u\n", rd);
8589 if (rd == 0)
8590 err += efunc(pc, "cannot write to %r0\n");
8591 break;
8592 case DIF_OP_LDGA:
8593 case DIF_OP_LDTA:
8594 if (r1 > DIF_VAR_ARRAY_MAX)
8595 err += efunc(pc, "invalid array %u\n", r1);
8596 if (r2 >= nregs)
8597 err += efunc(pc, "invalid register %u\n", r2);
8598 if (rd >= nregs)
8599 err += efunc(pc, "invalid register %u\n", rd);
8600 if (rd == 0)
8601 err += efunc(pc, "cannot write to %r0\n");
8602 break;
8603 case DIF_OP_LDGS:
8604 case DIF_OP_LDTS:
8605 case DIF_OP_LDLS:
8606 case DIF_OP_LDGAA:
8607 case DIF_OP_LDTAA:
8608 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8609 err += efunc(pc, "invalid variable %u\n", v);
8610 if (rd >= nregs)
8611 err += efunc(pc, "invalid register %u\n", rd);
8612 if (rd == 0)
8613 err += efunc(pc, "cannot write to %r0\n");
8614 break;
8615 case DIF_OP_STGS:
8616 case DIF_OP_STTS:
8617 case DIF_OP_STLS:
8618 case DIF_OP_STGAA:
8619 case DIF_OP_STTAA:
8620 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8621 err += efunc(pc, "invalid variable %u\n", v);
8622 if (rs >= nregs)
8623 err += efunc(pc, "invalid register %u\n", rd);
8624 break;
8625 case DIF_OP_CALL:
8626 if (subr > DIF_SUBR_MAX)
8627 err += efunc(pc, "invalid subr %u\n", subr);
8628 if (rd >= nregs)
8629 err += efunc(pc, "invalid register %u\n", rd);
8630 if (rd == 0)
8631 err += efunc(pc, "cannot write to %r0\n");
8632
8633 if (subr == DIF_SUBR_COPYOUT ||
8634 subr == DIF_SUBR_COPYOUTSTR) {
8635 dp->dtdo_destructive = 1;
8636 }
8637 break;
8638 case DIF_OP_PUSHTR:
8639 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8640 err += efunc(pc, "invalid ref type %u\n", type);
8641 if (r2 >= nregs)
8642 err += efunc(pc, "invalid register %u\n", r2);
8643 if (rs >= nregs)
8644 err += efunc(pc, "invalid register %u\n", rs);
8645 break;
8646 case DIF_OP_PUSHTV:
8647 if (type != DIF_TYPE_CTF)
8648 err += efunc(pc, "invalid val type %u\n", type);
8649 if (r2 >= nregs)
8650 err += efunc(pc, "invalid register %u\n", r2);
8651 if (rs >= nregs)
8652 err += efunc(pc, "invalid register %u\n", rs);
8653 break;
8654 default:
8655 err += efunc(pc, "invalid opcode %u\n",
8656 DIF_INSTR_OP(instr));
8657 }
8658 }
8659
8660 if (dp->dtdo_len != 0 &&
8661 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8662 err += efunc(dp->dtdo_len - 1,
8663 "expected 'ret' as last DIF instruction\n");
8664 }
8665
8666 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8667 /*
8668 * If we're not returning by reference, the size must be either
8669 * 0 or the size of one of the base types.
8670 */
8671 switch (dp->dtdo_rtype.dtdt_size) {
8672 case 0:
8673 case sizeof (uint8_t):
8674 case sizeof (uint16_t):
8675 case sizeof (uint32_t):
8676 case sizeof (uint64_t):
8677 break;
8678
8679 default:
8680 err += efunc(dp->dtdo_len - 1, "bad return size\n");
8681 }
8682 }
8683
8684 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8685 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8686 dtrace_diftype_t *vt, *et;
8687 uint_t id;
8688 int ndx;
8689
8690 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8691 v->dtdv_scope != DIFV_SCOPE_THREAD &&
8692 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8693 err += efunc(i, "unrecognized variable scope %d\n",
8694 v->dtdv_scope);
8695 break;
8696 }
8697
8698 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8699 v->dtdv_kind != DIFV_KIND_SCALAR) {
8700 err += efunc(i, "unrecognized variable type %d\n",
8701 v->dtdv_kind);
8702 break;
8703 }
8704
8705 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8706 err += efunc(i, "%d exceeds variable id limit\n", id);
8707 break;
8708 }
8709
8710 if (id < DIF_VAR_OTHER_UBASE)
8711 continue;
8712
8713 /*
8714 * For user-defined variables, we need to check that this
8715 * definition is identical to any previous definition that we
8716 * encountered.
8717 */
8718 ndx = id - DIF_VAR_OTHER_UBASE;
8719
8720 switch (v->dtdv_scope) {
8721 case DIFV_SCOPE_GLOBAL:
8722 if (ndx < vstate->dtvs_nglobals) {
8723 dtrace_statvar_t *svar;
8724
8725 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8726 existing = &svar->dtsv_var;
8727 }
8728
8729 break;
8730
8731 case DIFV_SCOPE_THREAD:
8732 if (ndx < vstate->dtvs_ntlocals)
8733 existing = &vstate->dtvs_tlocals[ndx];
8734 break;
8735
8736 case DIFV_SCOPE_LOCAL:
8737 if (ndx < vstate->dtvs_nlocals) {
8738 dtrace_statvar_t *svar;
8739
8740 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8741 existing = &svar->dtsv_var;
8742 }
8743
8744 break;
8745 }
8746
8747 vt = &v->dtdv_type;
8748
8749 if (vt->dtdt_flags & DIF_TF_BYREF) {
8750 if (vt->dtdt_size == 0) {
8751 err += efunc(i, "zero-sized variable\n");
8752 break;
8753 }
8754
8755 if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8756 vt->dtdt_size > dtrace_global_maxsize) {
8757 err += efunc(i, "oversized by-ref global\n");
8758 break;
8759 }
8760 }
8761
8762 if (existing == NULL || existing->dtdv_id == 0)
8763 continue;
8764
8765 ASSERT(existing->dtdv_id == v->dtdv_id);
8766 ASSERT(existing->dtdv_scope == v->dtdv_scope);
8767
8768 if (existing->dtdv_kind != v->dtdv_kind)
8769 err += efunc(i, "%d changed variable kind\n", id);
8770
8771 et = &existing->dtdv_type;
8772
8773 if (vt->dtdt_flags != et->dtdt_flags) {
8774 err += efunc(i, "%d changed variable type flags\n", id);
8775 break;
8776 }
8777
8778 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8779 err += efunc(i, "%d changed variable type size\n", id);
8780 break;
8781 }
8782 }
8783
8784 return (err);
8785 }
8786
8787 /*
8788 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
8789 * are much more constrained than normal DIFOs. Specifically, they may
8790 * not:
8791 *
8792 * 1. Make calls to subroutines other than copyin(), copyinstr() or
8793 * miscellaneous string routines
8794 * 2. Access DTrace variables other than the args[] array, and the
8795 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8796 * 3. Have thread-local variables.
8797 * 4. Have dynamic variables.
8798 */
8799 static int
8800 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8801 {
8802 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8803 int err = 0;
8804 uint_t pc;
8805
8806 for (pc = 0; pc < dp->dtdo_len; pc++) {
8807 dif_instr_t instr = dp->dtdo_buf[pc];
8808
8809 uint_t v = DIF_INSTR_VAR(instr);
8810 uint_t subr = DIF_INSTR_SUBR(instr);
8811 uint_t op = DIF_INSTR_OP(instr);
8812
8813 switch (op) {
8814 case DIF_OP_OR:
8815 case DIF_OP_XOR:
8816 case DIF_OP_AND:
8817 case DIF_OP_SLL:
8818 case DIF_OP_SRL:
8819 case DIF_OP_SRA:
8820 case DIF_OP_SUB:
8821 case DIF_OP_ADD:
8822 case DIF_OP_MUL:
8823 case DIF_OP_SDIV:
8824 case DIF_OP_UDIV:
8825 case DIF_OP_SREM:
8826 case DIF_OP_UREM:
8827 case DIF_OP_COPYS:
8828 case DIF_OP_NOT:
8829 case DIF_OP_MOV:
8830 case DIF_OP_RLDSB:
8831 case DIF_OP_RLDSH:
8832 case DIF_OP_RLDSW:
8833 case DIF_OP_RLDUB:
8834 case DIF_OP_RLDUH:
8835 case DIF_OP_RLDUW:
8836 case DIF_OP_RLDX:
8837 case DIF_OP_ULDSB:
8838 case DIF_OP_ULDSH:
8839 case DIF_OP_ULDSW:
8840 case DIF_OP_ULDUB:
8841 case DIF_OP_ULDUH:
8842 case DIF_OP_ULDUW:
8843 case DIF_OP_ULDX:
8844 case DIF_OP_STB:
8845 case DIF_OP_STH:
8846 case DIF_OP_STW:
8847 case DIF_OP_STX:
8848 case DIF_OP_ALLOCS:
8849 case DIF_OP_CMP:
8850 case DIF_OP_SCMP:
8851 case DIF_OP_TST:
8852 case DIF_OP_BA:
8853 case DIF_OP_BE:
8854 case DIF_OP_BNE:
8855 case DIF_OP_BG:
8856 case DIF_OP_BGU:
8857 case DIF_OP_BGE:
8858 case DIF_OP_BGEU:
8859 case DIF_OP_BL:
8860 case DIF_OP_BLU:
8861 case DIF_OP_BLE:
8862 case DIF_OP_BLEU:
8863 case DIF_OP_RET:
8864 case DIF_OP_NOP:
8865 case DIF_OP_POPTS:
8866 case DIF_OP_FLUSHTS:
8867 case DIF_OP_SETX:
8868 case DIF_OP_SETS:
8869 case DIF_OP_LDGA:
8870 case DIF_OP_LDLS:
8871 case DIF_OP_STGS:
8872 case DIF_OP_STLS:
8873 case DIF_OP_PUSHTR:
8874 case DIF_OP_PUSHTV:
8875 break;
8876
8877 case DIF_OP_LDGS:
8878 if (v >= DIF_VAR_OTHER_UBASE)
8879 break;
8880
8881 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8882 break;
8883
8884 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8885 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8886 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8887 v == DIF_VAR_UID || v == DIF_VAR_GID)
8888 break;
8889
8890 err += efunc(pc, "illegal variable %u\n", v);
8891 break;
8892
8893 case DIF_OP_LDTA:
8894 case DIF_OP_LDTS:
8895 case DIF_OP_LDGAA:
8896 case DIF_OP_LDTAA:
8897 err += efunc(pc, "illegal dynamic variable load\n");
8898 break;
8899
8900 case DIF_OP_STTS:
8901 case DIF_OP_STGAA:
8902 case DIF_OP_STTAA:
8903 err += efunc(pc, "illegal dynamic variable store\n");
8904 break;
8905
8906 case DIF_OP_CALL:
8907 if (subr == DIF_SUBR_ALLOCA ||
8908 subr == DIF_SUBR_BCOPY ||
8909 subr == DIF_SUBR_COPYIN ||
8910 subr == DIF_SUBR_COPYINTO ||
8911 subr == DIF_SUBR_COPYINSTR ||
8912 subr == DIF_SUBR_INDEX ||
8913 subr == DIF_SUBR_INET_NTOA ||
8914 subr == DIF_SUBR_INET_NTOA6 ||
8915 subr == DIF_SUBR_INET_NTOP ||
8916 subr == DIF_SUBR_LLTOSTR ||
8917 subr == DIF_SUBR_RINDEX ||
8918 subr == DIF_SUBR_STRCHR ||
8919 subr == DIF_SUBR_STRJOIN ||
8920 subr == DIF_SUBR_STRRCHR ||
8921 subr == DIF_SUBR_STRSTR ||
8922 subr == DIF_SUBR_COREPROFILE ||
8923 subr == DIF_SUBR_HTONS ||
8924 subr == DIF_SUBR_HTONL ||
8925 subr == DIF_SUBR_HTONLL ||
8926 subr == DIF_SUBR_NTOHS ||
8927 subr == DIF_SUBR_NTOHL ||
8928 subr == DIF_SUBR_NTOHLL)
8929 break;
8930
8931 err += efunc(pc, "invalid subr %u\n", subr);
8932 break;
8933
8934 default:
8935 err += efunc(pc, "invalid opcode %u\n",
8936 DIF_INSTR_OP(instr));
8937 }
8938 }
8939
8940 return (err);
8941 }
8942
8943 /*
8944 * Returns 1 if the expression in the DIF object can be cached on a per-thread
8945 * basis; 0 if not.
8946 */
8947 static int
8948 dtrace_difo_cacheable(dtrace_difo_t *dp)
8949 {
8950 uint_t i;
8951
8952 if (dp == NULL)
8953 return (0);
8954
8955 for (i = 0; i < dp->dtdo_varlen; i++) {
8956 dtrace_difv_t *v = &dp->dtdo_vartab[i];
8957
8958 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8959 continue;
8960
8961 switch (v->dtdv_id) {
8962 case DIF_VAR_CURTHREAD:
8963 case DIF_VAR_PID:
8964 case DIF_VAR_TID:
8965 case DIF_VAR_EXECNAME:
8966 case DIF_VAR_ZONENAME:
8967 break;
8968
8969 default:
8970 return (0);
8971 }
8972 }
8973
8974 /*
8975 * This DIF object may be cacheable. Now we need to look for any
8976 * array loading instructions, any memory loading instructions, or
8977 * any stores to thread-local variables.
8978 */
8979 for (i = 0; i < dp->dtdo_len; i++) {
8980 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8981
8982 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8983 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8984 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8985 op == DIF_OP_LDGA || op == DIF_OP_STTS)
8986 return (0);
8987 }
8988
8989 return (1);
8990 }
8991
8992 static void
8993 dtrace_difo_hold(dtrace_difo_t *dp)
8994 {
8995 uint_t i;
8996
8997 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8998
8999 dp->dtdo_refcnt++;
9000 ASSERT(dp->dtdo_refcnt != 0);
9001
9002 /*
9003 * We need to check this DIF object for references to the variable
9004 * DIF_VAR_VTIMESTAMP.
9005 */
9006 for (i = 0; i < dp->dtdo_varlen; i++) {
9007 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9008
9009 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9010 continue;
9011
9012 if (dtrace_vtime_references++ == 0)
9013 dtrace_vtime_enable();
9014 }
9015 }
9016
9017 /*
9018 * This routine calculates the dynamic variable chunksize for a given DIF
9019 * object. The calculation is not fool-proof, and can probably be tricked by
9020 * malicious DIF -- but it works for all compiler-generated DIF. Because this
9021 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9022 * if a dynamic variable size exceeds the chunksize.
9023 */
9024 static void
9025 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9026 {
9027 uint64_t sval = 0;
9028 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9029 const dif_instr_t *text = dp->dtdo_buf;
9030 uint_t pc, srd = 0;
9031 uint_t ttop = 0;
9032 size_t size, ksize;
9033 uint_t id, i;
9034
9035 for (pc = 0; pc < dp->dtdo_len; pc++) {
9036 dif_instr_t instr = text[pc];
9037 uint_t op = DIF_INSTR_OP(instr);
9038 uint_t rd = DIF_INSTR_RD(instr);
9039 uint_t r1 = DIF_INSTR_R1(instr);
9040 uint_t nkeys = 0;
9041 uchar_t scope;
9042
9043 dtrace_key_t *key = tupregs;
9044
9045 switch (op) {
9046 case DIF_OP_SETX:
9047 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9048 srd = rd;
9049 continue;
9050
9051 case DIF_OP_STTS:
9052 key = &tupregs[DIF_DTR_NREGS];
9053 key[0].dttk_size = 0;
9054 key[1].dttk_size = 0;
9055 nkeys = 2;
9056 scope = DIFV_SCOPE_THREAD;
9057 break;
9058
9059 case DIF_OP_STGAA:
9060 case DIF_OP_STTAA:
9061 nkeys = ttop;
9062
9063 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9064 key[nkeys++].dttk_size = 0;
9065
9066 key[nkeys++].dttk_size = 0;
9067
9068 if (op == DIF_OP_STTAA) {
9069 scope = DIFV_SCOPE_THREAD;
9070 } else {
9071 scope = DIFV_SCOPE_GLOBAL;
9072 }
9073
9074 break;
9075
9076 case DIF_OP_PUSHTR:
9077 if (ttop == DIF_DTR_NREGS)
9078 return;
9079
9080 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9081 /*
9082 * If the register for the size of the "pushtr"
9083 * is %r0 (or the value is 0) and the type is
9084 * a string, we'll use the system-wide default
9085 * string size.
9086 */
9087 tupregs[ttop++].dttk_size =
9088 dtrace_strsize_default;
9089 } else {
9090 if (srd == 0)
9091 return;
9092
9093 tupregs[ttop++].dttk_size = sval;
9094 }
9095
9096 break;
9097
9098 case DIF_OP_PUSHTV:
9099 if (ttop == DIF_DTR_NREGS)
9100 return;
9101
9102 tupregs[ttop++].dttk_size = 0;
9103 break;
9104
9105 case DIF_OP_FLUSHTS:
9106 ttop = 0;
9107 break;
9108
9109 case DIF_OP_POPTS:
9110 if (ttop != 0)
9111 ttop--;
9112 break;
9113 }
9114
9115 sval = 0;
9116 srd = 0;
9117
9118 if (nkeys == 0)
9119 continue;
9120
9121 /*
9122 * We have a dynamic variable allocation; calculate its size.
9123 */
9124 for (ksize = 0, i = 0; i < nkeys; i++)
9125 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9126
9127 size = sizeof (dtrace_dynvar_t);
9128 size += sizeof (dtrace_key_t) * (nkeys - 1);
9129 size += ksize;
9130
9131 /*
9132 * Now we need to determine the size of the stored data.
9133 */
9134 id = DIF_INSTR_VAR(instr);
9135
9136 for (i = 0; i < dp->dtdo_varlen; i++) {
9137 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9138
9139 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9140 size += v->dtdv_type.dtdt_size;
9141 break;
9142 }
9143 }
9144
9145 if (i == dp->dtdo_varlen)
9146 return;
9147
9148 /*
9149 * We have the size. If this is larger than the chunk size
9150 * for our dynamic variable state, reset the chunk size.
9151 */
9152 size = P2ROUNDUP(size, sizeof (uint64_t));
9153
9154 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9155 vstate->dtvs_dynvars.dtds_chunksize = size;
9156 }
9157 }
9158
9159 static void
9160 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9161 {
9162 int oldsvars, osz, nsz, otlocals, ntlocals;
9163 uint_t i, id;
9164
9165 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9166 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9167
9168 for (i = 0; i < dp->dtdo_varlen; i++) {
9169 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9170 dtrace_statvar_t *svar;
9171 dtrace_statvar_t ***svarp = NULL;
9172 size_t dsize = 0;
9173 uint8_t scope = v->dtdv_scope;
9174 int *np = (int *)NULL;
9175
9176 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9177 continue;
9178
9179 id -= DIF_VAR_OTHER_UBASE;
9180
9181 switch (scope) {
9182 case DIFV_SCOPE_THREAD:
9183 while (id >= (uint_t)(otlocals = vstate->dtvs_ntlocals)) {
9184 dtrace_difv_t *tlocals;
9185
9186 if ((ntlocals = (otlocals << 1)) == 0)
9187 ntlocals = 1;
9188
9189 osz = otlocals * sizeof (dtrace_difv_t);
9190 nsz = ntlocals * sizeof (dtrace_difv_t);
9191
9192 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9193
9194 if (osz != 0) {
9195 bcopy(vstate->dtvs_tlocals,
9196 tlocals, osz);
9197 kmem_free(vstate->dtvs_tlocals, osz);
9198 }
9199
9200 vstate->dtvs_tlocals = tlocals;
9201 vstate->dtvs_ntlocals = ntlocals;
9202 }
9203
9204 vstate->dtvs_tlocals[id] = *v;
9205 continue;
9206
9207 case DIFV_SCOPE_LOCAL:
9208 np = &vstate->dtvs_nlocals;
9209 svarp = &vstate->dtvs_locals;
9210
9211 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9212 dsize = (int)NCPU * (v->dtdv_type.dtdt_size +
9213 sizeof (uint64_t));
9214 else
9215 dsize = (int)NCPU * sizeof (uint64_t);
9216
9217 break;
9218
9219 case DIFV_SCOPE_GLOBAL:
9220 np = &vstate->dtvs_nglobals;
9221 svarp = &vstate->dtvs_globals;
9222
9223 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9224 dsize = v->dtdv_type.dtdt_size +
9225 sizeof (uint64_t);
9226
9227 break;
9228
9229 default:
9230 ASSERT(0);
9231 }
9232
9233 while (id >= (uint_t)(oldsvars = *np)) {
9234 dtrace_statvar_t **statics;
9235 int newsvars, oldsize, newsize;
9236
9237 if ((newsvars = (oldsvars << 1)) == 0)
9238 newsvars = 1;
9239
9240 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9241 newsize = newsvars * sizeof (dtrace_statvar_t *);
9242
9243 statics = kmem_zalloc(newsize, KM_SLEEP);
9244
9245 if (oldsize != 0) {
9246 bcopy(*svarp, statics, oldsize);
9247 kmem_free(*svarp, oldsize);
9248 }
9249
9250 *svarp = statics;
9251 *np = newsvars;
9252 }
9253
9254 if ((svar = (*svarp)[id]) == NULL) {
9255 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9256 svar->dtsv_var = *v;
9257
9258 if ((svar->dtsv_size = dsize) != 0) {
9259 svar->dtsv_data = (uint64_t)(uintptr_t)
9260 kmem_zalloc(dsize, KM_SLEEP);
9261 }
9262
9263 (*svarp)[id] = svar;
9264 }
9265
9266 svar->dtsv_refcnt++;
9267 }
9268
9269 dtrace_difo_chunksize(dp, vstate);
9270 dtrace_difo_hold(dp);
9271 }
9272
9273 static dtrace_difo_t *
9274 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9275 {
9276 dtrace_difo_t *new;
9277 size_t sz;
9278
9279 ASSERT(dp->dtdo_buf != NULL);
9280 ASSERT(dp->dtdo_refcnt != 0);
9281
9282 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9283
9284 ASSERT(dp->dtdo_buf != NULL);
9285 sz = dp->dtdo_len * sizeof (dif_instr_t);
9286 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9287 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9288 new->dtdo_len = dp->dtdo_len;
9289
9290 if (dp->dtdo_strtab != NULL) {
9291 ASSERT(dp->dtdo_strlen != 0);
9292 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9293 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9294 new->dtdo_strlen = dp->dtdo_strlen;
9295 }
9296
9297 if (dp->dtdo_inttab != NULL) {
9298 ASSERT(dp->dtdo_intlen != 0);
9299 sz = dp->dtdo_intlen * sizeof (uint64_t);
9300 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9301 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9302 new->dtdo_intlen = dp->dtdo_intlen;
9303 }
9304
9305 if (dp->dtdo_vartab != NULL) {
9306 ASSERT(dp->dtdo_varlen != 0);
9307 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9308 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9309 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9310 new->dtdo_varlen = dp->dtdo_varlen;
9311 }
9312
9313 dtrace_difo_init(new, vstate);
9314 return (new);
9315 }
9316
9317 static void
9318 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9319 {
9320 uint_t i;
9321
9322 ASSERT(dp->dtdo_refcnt == 0);
9323
9324 for (i = 0; i < dp->dtdo_varlen; i++) {
9325 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9326 dtrace_statvar_t *svar;
9327 dtrace_statvar_t **svarp = NULL;
9328 uint_t id;
9329 uint8_t scope = v->dtdv_scope;
9330 int *np = NULL;
9331
9332 switch (scope) {
9333 case DIFV_SCOPE_THREAD:
9334 continue;
9335
9336 case DIFV_SCOPE_LOCAL:
9337 np = &vstate->dtvs_nlocals;
9338 svarp = vstate->dtvs_locals;
9339 break;
9340
9341 case DIFV_SCOPE_GLOBAL:
9342 np = &vstate->dtvs_nglobals;
9343 svarp = vstate->dtvs_globals;
9344 break;
9345
9346 default:
9347 ASSERT(0);
9348 }
9349
9350 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9351 continue;
9352
9353 id -= DIF_VAR_OTHER_UBASE;
9354
9355 ASSERT(id < (uint_t)*np);
9356
9357 svar = svarp[id];
9358 ASSERT(svar != NULL);
9359 ASSERT(svar->dtsv_refcnt > 0);
9360
9361 if (--svar->dtsv_refcnt > 0)
9362 continue;
9363
9364 if (svar->dtsv_size != 0) {
9365 ASSERT(svar->dtsv_data != 0);
9366 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9367 svar->dtsv_size);
9368 }
9369
9370 kmem_free(svar, sizeof (dtrace_statvar_t));
9371 svarp[id] = NULL;
9372 }
9373
9374 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9375 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9376 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9377 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9378
9379 kmem_free(dp, sizeof (dtrace_difo_t));
9380 }
9381
9382 static void
9383 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9384 {
9385 uint_t i;
9386
9387 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9388 ASSERT(dp->dtdo_refcnt != 0);
9389
9390 for (i = 0; i < dp->dtdo_varlen; i++) {
9391 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9392
9393 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9394 continue;
9395
9396 ASSERT(dtrace_vtime_references > 0);
9397 if (--dtrace_vtime_references == 0)
9398 dtrace_vtime_disable();
9399 }
9400
9401 if (--dp->dtdo_refcnt == 0)
9402 dtrace_difo_destroy(dp, vstate);
9403 }
9404
9405 /*
9406 * DTrace Format Functions
9407 */
9408 static uint16_t
9409 dtrace_format_add(dtrace_state_t *state, char *str)
9410 {
9411 char *fmt, **new;
9412 uint16_t ndx, len = strlen(str) + 1;
9413
9414 fmt = kmem_zalloc(len, KM_SLEEP);
9415 bcopy(str, fmt, len);
9416
9417 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9418 if (state->dts_formats[ndx] == NULL) {
9419 state->dts_formats[ndx] = fmt;
9420 return (ndx + 1);
9421 }
9422 }
9423
9424 if (state->dts_nformats == USHRT_MAX) {
9425 /*
9426 * This is only likely if a denial-of-service attack is being
9427 * attempted. As such, it's okay to fail silently here.
9428 */
9429 kmem_free(fmt, len);
9430 return (0);
9431 }
9432
9433 /*
9434 * For simplicity, we always resize the formats array to be exactly the
9435 * number of formats.
9436 */
9437 ndx = state->dts_nformats++;
9438 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9439
9440 if (state->dts_formats != NULL) {
9441 ASSERT(ndx != 0);
9442 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9443 kmem_free(state->dts_formats, ndx * sizeof (char *));
9444 }
9445
9446 state->dts_formats = new;
9447 state->dts_formats[ndx] = fmt;
9448
9449 return (ndx + 1);
9450 }
9451
9452 static void
9453 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9454 {
9455 char *fmt;
9456
9457 ASSERT(state->dts_formats != NULL);
9458 ASSERT(format <= state->dts_nformats);
9459 ASSERT(state->dts_formats[format - 1] != NULL);
9460
9461 fmt = state->dts_formats[format - 1];
9462 kmem_free(fmt, strlen(fmt) + 1);
9463 state->dts_formats[format - 1] = NULL;
9464 }
9465
9466 static void
9467 dtrace_format_destroy(dtrace_state_t *state)
9468 {
9469 int i;
9470
9471 if (state->dts_nformats == 0) {
9472 ASSERT(state->dts_formats == NULL);
9473 return;
9474 }
9475
9476 ASSERT(state->dts_formats != NULL);
9477
9478 for (i = 0; i < state->dts_nformats; i++) {
9479 char *fmt = state->dts_formats[i];
9480
9481 if (fmt == NULL)
9482 continue;
9483
9484 kmem_free(fmt, strlen(fmt) + 1);
9485 }
9486
9487 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9488 state->dts_nformats = 0;
9489 state->dts_formats = NULL;
9490 }
9491
9492 /*
9493 * DTrace Predicate Functions
9494 */
9495 static dtrace_predicate_t *
9496 dtrace_predicate_create(dtrace_difo_t *dp)
9497 {
9498 dtrace_predicate_t *pred;
9499
9500 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9501 ASSERT(dp->dtdo_refcnt != 0);
9502
9503 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9504 pred->dtp_difo = dp;
9505 pred->dtp_refcnt = 1;
9506
9507 if (!dtrace_difo_cacheable(dp))
9508 return (pred);
9509
9510 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9511 /*
9512 * This is only theoretically possible -- we have had 2^32
9513 * cacheable predicates on this machine. We cannot allow any
9514 * more predicates to become cacheable: as unlikely as it is,
9515 * there may be a thread caching a (now stale) predicate cache
9516 * ID. (N.B.: the temptation is being successfully resisted to
9517 * have this cmn_err() "Holy shit -- we executed this code!")
9518 */
9519 return (pred);
9520 }
9521
9522 pred->dtp_cacheid = dtrace_predcache_id++;
9523
9524 return (pred);
9525 }
9526
9527 static void
9528 dtrace_predicate_hold(dtrace_predicate_t *pred)
9529 {
9530 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9531 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9532 ASSERT(pred->dtp_refcnt > 0);
9533
9534 pred->dtp_refcnt++;
9535 }
9536
9537 static void
9538 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9539 {
9540 dtrace_difo_t *dp = pred->dtp_difo;
9541 #pragma unused(dp) /* __APPLE__ */
9542
9543 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9544 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9545 ASSERT(pred->dtp_refcnt > 0);
9546
9547 if (--pred->dtp_refcnt == 0) {
9548 dtrace_difo_release(pred->dtp_difo, vstate);
9549 kmem_free(pred, sizeof (dtrace_predicate_t));
9550 }
9551 }
9552
9553 /*
9554 * DTrace Action Description Functions
9555 */
9556 static dtrace_actdesc_t *
9557 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9558 uint64_t uarg, uint64_t arg)
9559 {
9560 dtrace_actdesc_t *act;
9561
9562 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
9563 arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
9564
9565 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9566 act->dtad_kind = kind;
9567 act->dtad_ntuple = ntuple;
9568 act->dtad_uarg = uarg;
9569 act->dtad_arg = arg;
9570 act->dtad_refcnt = 1;
9571
9572 return (act);
9573 }
9574
9575 static void
9576 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9577 {
9578 ASSERT(act->dtad_refcnt >= 1);
9579 act->dtad_refcnt++;
9580 }
9581
9582 static void
9583 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9584 {
9585 dtrace_actkind_t kind = act->dtad_kind;
9586 dtrace_difo_t *dp;
9587
9588 ASSERT(act->dtad_refcnt >= 1);
9589
9590 if (--act->dtad_refcnt != 0)
9591 return;
9592
9593 if ((dp = act->dtad_difo) != NULL)
9594 dtrace_difo_release(dp, vstate);
9595
9596 if (DTRACEACT_ISPRINTFLIKE(kind)) {
9597 char *str = (char *)(uintptr_t)act->dtad_arg;
9598
9599 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9600 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9601
9602 if (str != NULL)
9603 kmem_free(str, strlen(str) + 1);
9604 }
9605
9606 kmem_free(act, sizeof (dtrace_actdesc_t));
9607 }
9608
9609 /*
9610 * DTrace ECB Functions
9611 */
9612 static dtrace_ecb_t *
9613 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9614 {
9615 dtrace_ecb_t *ecb;
9616 dtrace_epid_t epid;
9617
9618 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9619
9620 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9621 ecb->dte_predicate = NULL;
9622 ecb->dte_probe = probe;
9623
9624 /*
9625 * The default size is the size of the default action: recording
9626 * the header.
9627 */
9628 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9629 ecb->dte_alignment = sizeof (dtrace_epid_t);
9630
9631 epid = state->dts_epid++;
9632
9633 if (epid - 1 >= (dtrace_epid_t)state->dts_necbs) {
9634 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9635 int necbs = state->dts_necbs << 1;
9636
9637 ASSERT(epid == (dtrace_epid_t)state->dts_necbs + 1);
9638
9639 if (necbs == 0) {
9640 ASSERT(oecbs == NULL);
9641 necbs = 1;
9642 }
9643
9644 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9645
9646 if (oecbs != NULL)
9647 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9648
9649 dtrace_membar_producer();
9650 state->dts_ecbs = ecbs;
9651
9652 if (oecbs != NULL) {
9653 /*
9654 * If this state is active, we must dtrace_sync()
9655 * before we can free the old dts_ecbs array: we're
9656 * coming in hot, and there may be active ring
9657 * buffer processing (which indexes into the dts_ecbs
9658 * array) on another CPU.
9659 */
9660 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9661 dtrace_sync();
9662
9663 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9664 }
9665
9666 dtrace_membar_producer();
9667 state->dts_necbs = necbs;
9668 }
9669
9670 ecb->dte_state = state;
9671
9672 ASSERT(state->dts_ecbs[epid - 1] == NULL);
9673 dtrace_membar_producer();
9674 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9675
9676 return (ecb);
9677 }
9678
9679 static int
9680 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9681 {
9682 dtrace_probe_t *probe = ecb->dte_probe;
9683
9684 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
9685 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9686 ASSERT(ecb->dte_next == NULL);
9687
9688 if (probe == NULL) {
9689 /*
9690 * This is the NULL probe -- there's nothing to do.
9691 */
9692 return(0);
9693 }
9694
9695 probe->dtpr_provider->dtpv_ecb_count++;
9696 if (probe->dtpr_ecb == NULL) {
9697 dtrace_provider_t *prov = probe->dtpr_provider;
9698
9699 /*
9700 * We're the first ECB on this probe.
9701 */
9702 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9703
9704 if (ecb->dte_predicate != NULL)
9705 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9706
9707 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9708 probe->dtpr_id, probe->dtpr_arg));
9709 } else {
9710 /*
9711 * This probe is already active. Swing the last pointer to
9712 * point to the new ECB, and issue a dtrace_sync() to assure
9713 * that all CPUs have seen the change.
9714 */
9715 ASSERT(probe->dtpr_ecb_last != NULL);
9716 probe->dtpr_ecb_last->dte_next = ecb;
9717 probe->dtpr_ecb_last = ecb;
9718 probe->dtpr_predcache = 0;
9719
9720 dtrace_sync();
9721 return(0);
9722 }
9723 }
9724
9725 static void
9726 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9727 {
9728 dtrace_action_t *act;
9729 uint32_t curneeded = UINT32_MAX;
9730 uint32_t aggbase = UINT32_MAX;
9731
9732 /*
9733 * If we record anything, we always record the dtrace_rechdr_t. (And
9734 * we always record it first.)
9735 */
9736 ecb->dte_size = sizeof (dtrace_rechdr_t);
9737 ecb->dte_alignment = sizeof (dtrace_epid_t);
9738
9739 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9740 dtrace_recdesc_t *rec = &act->dta_rec;
9741 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
9742
9743 ecb->dte_alignment = MAX(ecb->dte_alignment, rec->dtrd_alignment);
9744
9745 if (DTRACEACT_ISAGG(act->dta_kind)) {
9746 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9747
9748 ASSERT(rec->dtrd_size != 0);
9749 ASSERT(agg->dtag_first != NULL);
9750 ASSERT(act->dta_prev->dta_intuple);
9751 ASSERT(aggbase != UINT32_MAX);
9752 ASSERT(curneeded != UINT32_MAX);
9753
9754 agg->dtag_base = aggbase;
9755
9756 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9757 rec->dtrd_offset = curneeded;
9758 curneeded += rec->dtrd_size;
9759 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
9760
9761 aggbase = UINT32_MAX;
9762 curneeded = UINT32_MAX;
9763 } else if (act->dta_intuple) {
9764 if (curneeded == UINT32_MAX) {
9765 /*
9766 * This is the first record in a tuple. Align
9767 * curneeded to be at offset 4 in an 8-byte
9768 * aligned block.
9769 */
9770 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
9771 ASSERT(aggbase == UINT32_MAX);
9772
9773 curneeded = P2PHASEUP(ecb->dte_size,
9774 sizeof (uint64_t), sizeof (dtrace_aggid_t));
9775
9776 aggbase = curneeded - sizeof (dtrace_aggid_t);
9777 ASSERT(IS_P2ALIGNED(aggbase,
9778 sizeof (uint64_t)));
9779 }
9780
9781 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9782 rec->dtrd_offset = curneeded;
9783 curneeded += rec->dtrd_size;
9784 } else {
9785 /* tuples must be followed by an aggregation */
9786 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
9787 ecb->dte_size = P2ROUNDUP(ecb->dte_size, rec->dtrd_alignment);
9788 rec->dtrd_offset = ecb->dte_size;
9789 ecb->dte_size += rec->dtrd_size;
9790 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
9791 }
9792 }
9793
9794 if ((act = ecb->dte_action) != NULL &&
9795 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9796 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
9797 /*
9798 * If the size is still sizeof (dtrace_rechdr_t), then all
9799 * actions store no data; set the size to 0.
9800 */
9801 ecb->dte_size = 0;
9802 }
9803
9804 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
9805 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
9806 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed, ecb->dte_needed);
9807 }
9808
9809 static dtrace_action_t *
9810 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9811 {
9812 dtrace_aggregation_t *agg;
9813 size_t size = sizeof (uint64_t);
9814 int ntuple = desc->dtad_ntuple;
9815 dtrace_action_t *act;
9816 dtrace_recdesc_t *frec;
9817 dtrace_aggid_t aggid;
9818 dtrace_state_t *state = ecb->dte_state;
9819
9820 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9821 agg->dtag_ecb = ecb;
9822
9823 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9824
9825 switch (desc->dtad_kind) {
9826 case DTRACEAGG_MIN:
9827 agg->dtag_initial = INT64_MAX;
9828 agg->dtag_aggregate = dtrace_aggregate_min;
9829 break;
9830
9831 case DTRACEAGG_MAX:
9832 agg->dtag_initial = INT64_MIN;
9833 agg->dtag_aggregate = dtrace_aggregate_max;
9834 break;
9835
9836 case DTRACEAGG_COUNT:
9837 agg->dtag_aggregate = dtrace_aggregate_count;
9838 break;
9839
9840 case DTRACEAGG_QUANTIZE:
9841 agg->dtag_aggregate = dtrace_aggregate_quantize;
9842 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9843 sizeof (uint64_t);
9844 break;
9845
9846 case DTRACEAGG_LQUANTIZE: {
9847 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9848 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9849
9850 agg->dtag_initial = desc->dtad_arg;
9851 agg->dtag_aggregate = dtrace_aggregate_lquantize;
9852
9853 if (step == 0 || levels == 0)
9854 goto err;
9855
9856 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9857 break;
9858 }
9859
9860 case DTRACEAGG_LLQUANTIZE: {
9861 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
9862 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
9863 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
9864 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
9865 int64_t v;
9866
9867 agg->dtag_initial = desc->dtad_arg;
9868 agg->dtag_aggregate = dtrace_aggregate_llquantize;
9869
9870 if (factor < 2 || low >= high || nsteps < factor)
9871 goto err;
9872
9873 /*
9874 * Now check that the number of steps evenly divides a power
9875 * of the factor. (This assures both integer bucket size and
9876 * linearity within each magnitude.)
9877 */
9878 for (v = factor; v < nsteps; v *= factor)
9879 continue;
9880
9881 if ((v % nsteps) || (nsteps % factor))
9882 goto err;
9883
9884 size = (dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
9885 break;
9886 }
9887
9888 case DTRACEAGG_AVG:
9889 agg->dtag_aggregate = dtrace_aggregate_avg;
9890 size = sizeof (uint64_t) * 2;
9891 break;
9892
9893 case DTRACEAGG_STDDEV:
9894 agg->dtag_aggregate = dtrace_aggregate_stddev;
9895 size = sizeof (uint64_t) * 4;
9896 break;
9897
9898 case DTRACEAGG_SUM:
9899 agg->dtag_aggregate = dtrace_aggregate_sum;
9900 break;
9901
9902 default:
9903 goto err;
9904 }
9905
9906 agg->dtag_action.dta_rec.dtrd_size = size;
9907
9908 if (ntuple == 0)
9909 goto err;
9910
9911 /*
9912 * We must make sure that we have enough actions for the n-tuple.
9913 */
9914 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9915 if (DTRACEACT_ISAGG(act->dta_kind))
9916 break;
9917
9918 if (--ntuple == 0) {
9919 /*
9920 * This is the action with which our n-tuple begins.
9921 */
9922 agg->dtag_first = act;
9923 goto success;
9924 }
9925 }
9926
9927 /*
9928 * This n-tuple is short by ntuple elements. Return failure.
9929 */
9930 ASSERT(ntuple != 0);
9931 err:
9932 kmem_free(agg, sizeof (dtrace_aggregation_t));
9933 return (NULL);
9934
9935 success:
9936 /*
9937 * If the last action in the tuple has a size of zero, it's actually
9938 * an expression argument for the aggregating action.
9939 */
9940 ASSERT(ecb->dte_action_last != NULL);
9941 act = ecb->dte_action_last;
9942
9943 if (act->dta_kind == DTRACEACT_DIFEXPR) {
9944 ASSERT(act->dta_difo != NULL);
9945
9946 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9947 agg->dtag_hasarg = 1;
9948 }
9949
9950 /*
9951 * We need to allocate an id for this aggregation.
9952 */
9953 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9954 VM_BESTFIT | VM_SLEEP);
9955
9956 if (aggid - 1 >= (dtrace_aggid_t)state->dts_naggregations) {
9957 dtrace_aggregation_t **oaggs = state->dts_aggregations;
9958 dtrace_aggregation_t **aggs;
9959 int naggs = state->dts_naggregations << 1;
9960 int onaggs = state->dts_naggregations;
9961
9962 ASSERT(aggid == (dtrace_aggid_t)state->dts_naggregations + 1);
9963
9964 if (naggs == 0) {
9965 ASSERT(oaggs == NULL);
9966 naggs = 1;
9967 }
9968
9969 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9970
9971 if (oaggs != NULL) {
9972 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9973 kmem_free(oaggs, onaggs * sizeof (*aggs));
9974 }
9975
9976 state->dts_aggregations = aggs;
9977 state->dts_naggregations = naggs;
9978 }
9979
9980 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9981 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9982
9983 frec = &agg->dtag_first->dta_rec;
9984 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9985 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9986
9987 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9988 ASSERT(!act->dta_intuple);
9989 act->dta_intuple = 1;
9990 }
9991
9992 return (&agg->dtag_action);
9993 }
9994
9995 static void
9996 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9997 {
9998 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9999 dtrace_state_t *state = ecb->dte_state;
10000 dtrace_aggid_t aggid = agg->dtag_id;
10001
10002 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10003 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10004
10005 ASSERT(state->dts_aggregations[aggid - 1] == agg);
10006 state->dts_aggregations[aggid - 1] = NULL;
10007
10008 kmem_free(agg, sizeof (dtrace_aggregation_t));
10009 }
10010
10011 static int
10012 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10013 {
10014 dtrace_action_t *action, *last;
10015 dtrace_difo_t *dp = desc->dtad_difo;
10016 uint32_t size = 0, align = sizeof (uint8_t), mask;
10017 uint16_t format = 0;
10018 dtrace_recdesc_t *rec;
10019 dtrace_state_t *state = ecb->dte_state;
10020 dtrace_optval_t *opt = state->dts_options;
10021 dtrace_optval_t nframes=0, strsize;
10022 uint64_t arg = desc->dtad_arg;
10023
10024 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10025 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10026
10027 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10028 /*
10029 * If this is an aggregating action, there must be neither
10030 * a speculate nor a commit on the action chain.
10031 */
10032 dtrace_action_t *act;
10033
10034 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10035 if (act->dta_kind == DTRACEACT_COMMIT)
10036 return (EINVAL);
10037
10038 if (act->dta_kind == DTRACEACT_SPECULATE)
10039 return (EINVAL);
10040 }
10041
10042 action = dtrace_ecb_aggregation_create(ecb, desc);
10043
10044 if (action == NULL)
10045 return (EINVAL);
10046 } else {
10047 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10048 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10049 dp != NULL && dp->dtdo_destructive)) {
10050 state->dts_destructive = 1;
10051 }
10052
10053 switch (desc->dtad_kind) {
10054 case DTRACEACT_PRINTF:
10055 case DTRACEACT_PRINTA:
10056 case DTRACEACT_SYSTEM:
10057 case DTRACEACT_FREOPEN:
10058 /*
10059 * We know that our arg is a string -- turn it into a
10060 * format.
10061 */
10062 if (arg == 0) {
10063 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
10064 format = 0;
10065 } else {
10066 ASSERT(arg != 0);
10067 ASSERT(arg > KERNELBASE);
10068 format = dtrace_format_add(state,
10069 (char *)(uintptr_t)arg);
10070 }
10071
10072 /*FALLTHROUGH*/
10073 case DTRACEACT_LIBACT:
10074 case DTRACEACT_DIFEXPR:
10075 case DTRACEACT_TRACEMEM:
10076 case DTRACEACT_TRACEMEM_DYNSIZE:
10077 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
10078 if (dp == NULL)
10079 return (EINVAL);
10080
10081 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10082 break;
10083
10084 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10085 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10086 return (EINVAL);
10087
10088 size = opt[DTRACEOPT_STRSIZE];
10089 }
10090
10091 break;
10092
10093 case DTRACEACT_STACK:
10094 if ((nframes = arg) == 0) {
10095 nframes = opt[DTRACEOPT_STACKFRAMES];
10096 ASSERT(nframes > 0);
10097 arg = nframes;
10098 }
10099
10100 size = nframes * sizeof (pc_t);
10101 break;
10102
10103 case DTRACEACT_JSTACK:
10104 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10105 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10106
10107 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10108 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10109
10110 arg = DTRACE_USTACK_ARG(nframes, strsize);
10111
10112 /*FALLTHROUGH*/
10113 case DTRACEACT_USTACK:
10114 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10115 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10116 strsize = DTRACE_USTACK_STRSIZE(arg);
10117 nframes = opt[DTRACEOPT_USTACKFRAMES];
10118 ASSERT(nframes > 0);
10119 arg = DTRACE_USTACK_ARG(nframes, strsize);
10120 }
10121
10122 /*
10123 * Save a slot for the pid.
10124 */
10125 size = (nframes + 1) * sizeof (uint64_t);
10126 size += DTRACE_USTACK_STRSIZE(arg);
10127 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10128
10129 break;
10130
10131 case DTRACEACT_SYM:
10132 case DTRACEACT_MOD:
10133 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10134 sizeof (uint64_t)) ||
10135 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10136 return (EINVAL);
10137 break;
10138
10139 case DTRACEACT_USYM:
10140 case DTRACEACT_UMOD:
10141 case DTRACEACT_UADDR:
10142 if (dp == NULL ||
10143 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10144 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10145 return (EINVAL);
10146
10147 /*
10148 * We have a slot for the pid, plus a slot for the
10149 * argument. To keep things simple (aligned with
10150 * bitness-neutral sizing), we store each as a 64-bit
10151 * quantity.
10152 */
10153 size = 2 * sizeof (uint64_t);
10154 break;
10155
10156 case DTRACEACT_STOP:
10157 case DTRACEACT_BREAKPOINT:
10158 case DTRACEACT_PANIC:
10159 break;
10160
10161 case DTRACEACT_CHILL:
10162 case DTRACEACT_DISCARD:
10163 case DTRACEACT_RAISE:
10164 case DTRACEACT_PIDRESUME: /* __APPLE__ */
10165 if (dp == NULL)
10166 return (EINVAL);
10167 break;
10168
10169 case DTRACEACT_EXIT:
10170 if (dp == NULL ||
10171 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10172 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10173 return (EINVAL);
10174 break;
10175
10176 case DTRACEACT_SPECULATE:
10177 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10178 return (EINVAL);
10179
10180 if (dp == NULL)
10181 return (EINVAL);
10182
10183 state->dts_speculates = 1;
10184 break;
10185
10186 case DTRACEACT_COMMIT: {
10187 dtrace_action_t *act = ecb->dte_action;
10188
10189 for (; act != NULL; act = act->dta_next) {
10190 if (act->dta_kind == DTRACEACT_COMMIT)
10191 return (EINVAL);
10192 }
10193
10194 if (dp == NULL)
10195 return (EINVAL);
10196 break;
10197 }
10198
10199 default:
10200 return (EINVAL);
10201 }
10202
10203 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10204 /*
10205 * If this is a data-storing action or a speculate,
10206 * we must be sure that there isn't a commit on the
10207 * action chain.
10208 */
10209 dtrace_action_t *act = ecb->dte_action;
10210
10211 for (; act != NULL; act = act->dta_next) {
10212 if (act->dta_kind == DTRACEACT_COMMIT)
10213 return (EINVAL);
10214 }
10215 }
10216
10217 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10218 action->dta_rec.dtrd_size = size;
10219 }
10220
10221 action->dta_refcnt = 1;
10222 rec = &action->dta_rec;
10223 size = rec->dtrd_size;
10224
10225 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10226 if (!(size & mask)) {
10227 align = mask + 1;
10228 break;
10229 }
10230 }
10231
10232 action->dta_kind = desc->dtad_kind;
10233
10234 if ((action->dta_difo = dp) != NULL)
10235 dtrace_difo_hold(dp);
10236
10237 rec->dtrd_action = action->dta_kind;
10238 rec->dtrd_arg = arg;
10239 rec->dtrd_uarg = desc->dtad_uarg;
10240 rec->dtrd_alignment = (uint16_t)align;
10241 rec->dtrd_format = format;
10242
10243 if ((last = ecb->dte_action_last) != NULL) {
10244 ASSERT(ecb->dte_action != NULL);
10245 action->dta_prev = last;
10246 last->dta_next = action;
10247 } else {
10248 ASSERT(ecb->dte_action == NULL);
10249 ecb->dte_action = action;
10250 }
10251
10252 ecb->dte_action_last = action;
10253
10254 return (0);
10255 }
10256
10257 static void
10258 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10259 {
10260 dtrace_action_t *act = ecb->dte_action, *next;
10261 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10262 dtrace_difo_t *dp;
10263 uint16_t format;
10264
10265 if (act != NULL && act->dta_refcnt > 1) {
10266 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10267 act->dta_refcnt--;
10268 } else {
10269 for (; act != NULL; act = next) {
10270 next = act->dta_next;
10271 ASSERT(next != NULL || act == ecb->dte_action_last);
10272 ASSERT(act->dta_refcnt == 1);
10273
10274 if ((format = act->dta_rec.dtrd_format) != 0)
10275 dtrace_format_remove(ecb->dte_state, format);
10276
10277 if ((dp = act->dta_difo) != NULL)
10278 dtrace_difo_release(dp, vstate);
10279
10280 if (DTRACEACT_ISAGG(act->dta_kind)) {
10281 dtrace_ecb_aggregation_destroy(ecb, act);
10282 } else {
10283 kmem_free(act, sizeof (dtrace_action_t));
10284 }
10285 }
10286 }
10287
10288 ecb->dte_action = NULL;
10289 ecb->dte_action_last = NULL;
10290 ecb->dte_size = 0;
10291 }
10292
10293 static void
10294 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10295 {
10296 /*
10297 * We disable the ECB by removing it from its probe.
10298 */
10299 dtrace_ecb_t *pecb, *prev = NULL;
10300 dtrace_probe_t *probe = ecb->dte_probe;
10301
10302 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10303
10304 if (probe == NULL) {
10305 /*
10306 * This is the NULL probe; there is nothing to disable.
10307 */
10308 return;
10309 }
10310
10311 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10312 if (pecb == ecb)
10313 break;
10314 prev = pecb;
10315 }
10316
10317 ASSERT(pecb != NULL);
10318
10319 if (prev == NULL) {
10320 probe->dtpr_ecb = ecb->dte_next;
10321 } else {
10322 prev->dte_next = ecb->dte_next;
10323 }
10324
10325 if (ecb == probe->dtpr_ecb_last) {
10326 ASSERT(ecb->dte_next == NULL);
10327 probe->dtpr_ecb_last = prev;
10328 }
10329
10330 probe->dtpr_provider->dtpv_ecb_count--;
10331 /*
10332 * The ECB has been disconnected from the probe; now sync to assure
10333 * that all CPUs have seen the change before returning.
10334 */
10335 dtrace_sync();
10336
10337 if (probe->dtpr_ecb == NULL) {
10338 /*
10339 * That was the last ECB on the probe; clear the predicate
10340 * cache ID for the probe, disable it and sync one more time
10341 * to assure that we'll never hit it again.
10342 */
10343 dtrace_provider_t *prov = probe->dtpr_provider;
10344
10345 ASSERT(ecb->dte_next == NULL);
10346 ASSERT(probe->dtpr_ecb_last == NULL);
10347 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10348 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10349 probe->dtpr_id, probe->dtpr_arg);
10350 dtrace_sync();
10351 } else {
10352 /*
10353 * There is at least one ECB remaining on the probe. If there
10354 * is _exactly_ one, set the probe's predicate cache ID to be
10355 * the predicate cache ID of the remaining ECB.
10356 */
10357 ASSERT(probe->dtpr_ecb_last != NULL);
10358 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10359
10360 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10361 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10362
10363 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10364
10365 if (p != NULL)
10366 probe->dtpr_predcache = p->dtp_cacheid;
10367 }
10368
10369 ecb->dte_next = NULL;
10370 }
10371 }
10372
10373 static void
10374 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10375 {
10376 dtrace_state_t *state = ecb->dte_state;
10377 dtrace_vstate_t *vstate = &state->dts_vstate;
10378 dtrace_predicate_t *pred;
10379 dtrace_epid_t epid = ecb->dte_epid;
10380
10381 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10382 ASSERT(ecb->dte_next == NULL);
10383 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10384
10385 if ((pred = ecb->dte_predicate) != NULL)
10386 dtrace_predicate_release(pred, vstate);
10387
10388 dtrace_ecb_action_remove(ecb);
10389
10390 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10391 state->dts_ecbs[epid - 1] = NULL;
10392
10393 kmem_free(ecb, sizeof (dtrace_ecb_t));
10394 }
10395
10396 static dtrace_ecb_t *
10397 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10398 dtrace_enabling_t *enab)
10399 {
10400 dtrace_ecb_t *ecb;
10401 dtrace_predicate_t *pred;
10402 dtrace_actdesc_t *act;
10403 dtrace_provider_t *prov;
10404 dtrace_ecbdesc_t *desc = enab->dten_current;
10405
10406 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10407 ASSERT(state != NULL);
10408
10409 ecb = dtrace_ecb_add(state, probe);
10410 ecb->dte_uarg = desc->dted_uarg;
10411
10412 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10413 dtrace_predicate_hold(pred);
10414 ecb->dte_predicate = pred;
10415 }
10416
10417 if (probe != NULL) {
10418 /*
10419 * If the provider shows more leg than the consumer is old
10420 * enough to see, we need to enable the appropriate implicit
10421 * predicate bits to prevent the ecb from activating at
10422 * revealing times.
10423 *
10424 * Providers specifying DTRACE_PRIV_USER at register time
10425 * are stating that they need the /proc-style privilege
10426 * model to be enforced, and this is what DTRACE_COND_OWNER
10427 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10428 */
10429 prov = probe->dtpr_provider;
10430 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10431 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10432 ecb->dte_cond |= DTRACE_COND_OWNER;
10433
10434 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10435 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10436 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10437
10438 /*
10439 * If the provider shows us kernel innards and the user
10440 * is lacking sufficient privilege, enable the
10441 * DTRACE_COND_USERMODE implicit predicate.
10442 */
10443 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10444 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10445 ecb->dte_cond |= DTRACE_COND_USERMODE;
10446 }
10447
10448 if (dtrace_ecb_create_cache != NULL) {
10449 /*
10450 * If we have a cached ecb, we'll use its action list instead
10451 * of creating our own (saving both time and space).
10452 */
10453 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10454 dtrace_action_t *act_if = cached->dte_action;
10455
10456 if (act_if != NULL) {
10457 ASSERT(act_if->dta_refcnt > 0);
10458 act_if->dta_refcnt++;
10459 ecb->dte_action = act_if;
10460 ecb->dte_action_last = cached->dte_action_last;
10461 ecb->dte_needed = cached->dte_needed;
10462 ecb->dte_size = cached->dte_size;
10463 ecb->dte_alignment = cached->dte_alignment;
10464 }
10465
10466 return (ecb);
10467 }
10468
10469 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10470 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10471 dtrace_ecb_destroy(ecb);
10472 return (NULL);
10473 }
10474 }
10475
10476 dtrace_ecb_resize(ecb);
10477
10478 return (dtrace_ecb_create_cache = ecb);
10479 }
10480
10481 static int
10482 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10483 {
10484 dtrace_ecb_t *ecb;
10485 dtrace_enabling_t *enab = arg;
10486 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10487
10488 ASSERT(state != NULL);
10489
10490 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10491 /*
10492 * This probe was created in a generation for which this
10493 * enabling has previously created ECBs; we don't want to
10494 * enable it again, so just kick out.
10495 */
10496 return (DTRACE_MATCH_NEXT);
10497 }
10498
10499 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10500 return (DTRACE_MATCH_DONE);
10501
10502 if (dtrace_ecb_enable(ecb) < 0)
10503 return (DTRACE_MATCH_FAIL);
10504
10505 return (DTRACE_MATCH_NEXT);
10506 }
10507
10508 static dtrace_ecb_t *
10509 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10510 {
10511 dtrace_ecb_t *ecb;
10512 #pragma unused(ecb) /* __APPLE__ */
10513
10514 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10515
10516 if (id == 0 || id > (dtrace_epid_t)state->dts_necbs)
10517 return (NULL);
10518
10519 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10520 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10521
10522 return (state->dts_ecbs[id - 1]);
10523 }
10524
10525 static dtrace_aggregation_t *
10526 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10527 {
10528 dtrace_aggregation_t *agg;
10529 #pragma unused(agg) /* __APPLE__ */
10530
10531 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10532
10533 if (id == 0 || id > (dtrace_aggid_t)state->dts_naggregations)
10534 return (NULL);
10535
10536 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10537 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10538 agg->dtag_id == id);
10539
10540 return (state->dts_aggregations[id - 1]);
10541 }
10542
10543 /*
10544 * DTrace Buffer Functions
10545 *
10546 * The following functions manipulate DTrace buffers. Most of these functions
10547 * are called in the context of establishing or processing consumer state;
10548 * exceptions are explicitly noted.
10549 */
10550
10551 /*
10552 * Note: called from cross call context. This function switches the two
10553 * buffers on a given CPU. The atomicity of this operation is assured by
10554 * disabling interrupts while the actual switch takes place; the disabling of
10555 * interrupts serializes the execution with any execution of dtrace_probe() on
10556 * the same CPU.
10557 */
10558 static void
10559 dtrace_buffer_switch(dtrace_buffer_t *buf)
10560 {
10561 caddr_t tomax = buf->dtb_tomax;
10562 caddr_t xamot = buf->dtb_xamot;
10563 dtrace_icookie_t cookie;
10564 hrtime_t now;
10565
10566 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10567 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10568
10569 cookie = dtrace_interrupt_disable();
10570 now = dtrace_gethrtime();
10571 buf->dtb_tomax = xamot;
10572 buf->dtb_xamot = tomax;
10573 buf->dtb_xamot_drops = buf->dtb_drops;
10574 buf->dtb_xamot_offset = buf->dtb_offset;
10575 buf->dtb_xamot_errors = buf->dtb_errors;
10576 buf->dtb_xamot_flags = buf->dtb_flags;
10577 buf->dtb_offset = 0;
10578 buf->dtb_drops = 0;
10579 buf->dtb_errors = 0;
10580 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10581 buf->dtb_interval = now - buf->dtb_switched;
10582 buf->dtb_switched = now;
10583 dtrace_interrupt_enable(cookie);
10584 }
10585
10586 /*
10587 * Note: called from cross call context. This function activates a buffer
10588 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
10589 * is guaranteed by the disabling of interrupts.
10590 */
10591 static void
10592 dtrace_buffer_activate(dtrace_state_t *state)
10593 {
10594 dtrace_buffer_t *buf;
10595 dtrace_icookie_t cookie = dtrace_interrupt_disable();
10596
10597 buf = &state->dts_buffer[CPU->cpu_id];
10598
10599 if (buf->dtb_tomax != NULL) {
10600 /*
10601 * We might like to assert that the buffer is marked inactive,
10602 * but this isn't necessarily true: the buffer for the CPU
10603 * that processes the BEGIN probe has its buffer activated
10604 * manually. In this case, we take the (harmless) action
10605 * re-clearing the bit INACTIVE bit.
10606 */
10607 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10608 }
10609
10610 dtrace_interrupt_enable(cookie);
10611 }
10612
10613 static int
10614 dtrace_buffer_canalloc(size_t size)
10615 {
10616 if (size > (UINT64_MAX - dtrace_buffer_memory_inuse))
10617 return (B_FALSE);
10618 if ((size + dtrace_buffer_memory_inuse) > dtrace_buffer_memory_maxsize)
10619 return (B_FALSE);
10620
10621 return (B_TRUE);
10622 }
10623
10624 static int
10625 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10626 processorid_t cpu)
10627 {
10628 dtrace_cpu_t *cp;
10629 dtrace_buffer_t *buf;
10630 size_t size_before_alloc = dtrace_buffer_memory_inuse;
10631
10632 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
10633 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10634
10635 if (size > (size_t)dtrace_nonroot_maxsize &&
10636 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10637 return (EFBIG);
10638
10639 cp = cpu_list;
10640
10641 do {
10642 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10643 continue;
10644
10645 buf = &bufs[cp->cpu_id];
10646
10647 /*
10648 * If there is already a buffer allocated for this CPU, it
10649 * is only possible that this is a DR event. In this case,
10650 * the buffer size must match our specified size.
10651 */
10652 if (buf->dtb_tomax != NULL) {
10653 ASSERT(buf->dtb_size == size);
10654 continue;
10655 }
10656
10657 ASSERT(buf->dtb_xamot == NULL);
10658
10659 /* DTrace, please do not eat all the memory. */
10660 if (dtrace_buffer_canalloc(size) == B_FALSE)
10661 goto err;
10662 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10663 goto err;
10664 dtrace_buffer_memory_inuse += size;
10665
10666 buf->dtb_size = size;
10667 buf->dtb_flags = flags;
10668 buf->dtb_offset = 0;
10669 buf->dtb_drops = 0;
10670
10671 if (flags & DTRACEBUF_NOSWITCH)
10672 continue;
10673
10674 /* DTrace, please do not eat all the memory. */
10675 if (dtrace_buffer_canalloc(size) == B_FALSE)
10676 goto err;
10677 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10678 goto err;
10679 dtrace_buffer_memory_inuse += size;
10680 } while ((cp = cp->cpu_next) != cpu_list);
10681
10682 ASSERT(dtrace_buffer_memory_inuse <= dtrace_buffer_memory_maxsize);
10683
10684 return (0);
10685
10686 err:
10687 cp = cpu_list;
10688
10689 do {
10690 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10691 continue;
10692
10693 buf = &bufs[cp->cpu_id];
10694
10695 if (buf->dtb_xamot != NULL) {
10696 ASSERT(buf->dtb_tomax != NULL);
10697 ASSERT(buf->dtb_size == size);
10698 kmem_free(buf->dtb_xamot, size);
10699 }
10700
10701 if (buf->dtb_tomax != NULL) {
10702 ASSERT(buf->dtb_size == size);
10703 kmem_free(buf->dtb_tomax, size);
10704 }
10705
10706 buf->dtb_tomax = NULL;
10707 buf->dtb_xamot = NULL;
10708 buf->dtb_size = 0;
10709 } while ((cp = cp->cpu_next) != cpu_list);
10710
10711 /* Restore the size saved before allocating memory */
10712 dtrace_buffer_memory_inuse = size_before_alloc;
10713
10714 return (ENOMEM);
10715 }
10716
10717 /*
10718 * Note: called from probe context. This function just increments the drop
10719 * count on a buffer. It has been made a function to allow for the
10720 * possibility of understanding the source of mysterious drop counts. (A
10721 * problem for which one may be particularly disappointed that DTrace cannot
10722 * be used to understand DTrace.)
10723 */
10724 static void
10725 dtrace_buffer_drop(dtrace_buffer_t *buf)
10726 {
10727 buf->dtb_drops++;
10728 }
10729
10730 /*
10731 * Note: called from probe context. This function is called to reserve space
10732 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
10733 * mstate. Returns the new offset in the buffer, or a negative value if an
10734 * error has occurred.
10735 */
10736 static intptr_t
10737 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10738 dtrace_state_t *state, dtrace_mstate_t *mstate)
10739 {
10740 intptr_t offs = buf->dtb_offset, soffs;
10741 intptr_t woffs;
10742 caddr_t tomax;
10743 size_t total_off;
10744
10745 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10746 return (-1);
10747
10748 if ((tomax = buf->dtb_tomax) == NULL) {
10749 dtrace_buffer_drop(buf);
10750 return (-1);
10751 }
10752
10753 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10754 while (offs & (align - 1)) {
10755 /*
10756 * Assert that our alignment is off by a number which
10757 * is itself sizeof (uint32_t) aligned.
10758 */
10759 ASSERT(!((align - (offs & (align - 1))) &
10760 (sizeof (uint32_t) - 1)));
10761 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10762 offs += sizeof (uint32_t);
10763 }
10764
10765 if ((uint64_t)(soffs = offs + needed) > buf->dtb_size) {
10766 dtrace_buffer_drop(buf);
10767 return (-1);
10768 }
10769
10770 if (mstate == NULL)
10771 return (offs);
10772
10773 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10774 mstate->dtms_scratch_size = buf->dtb_size - soffs;
10775 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10776
10777 return (offs);
10778 }
10779
10780 if (buf->dtb_flags & DTRACEBUF_FILL) {
10781 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10782 (buf->dtb_flags & DTRACEBUF_FULL))
10783 return (-1);
10784 goto out;
10785 }
10786
10787 total_off = needed + (offs & (align - 1));
10788
10789 /*
10790 * For a ring buffer, life is quite a bit more complicated. Before
10791 * we can store any padding, we need to adjust our wrapping offset.
10792 * (If we've never before wrapped or we're not about to, no adjustment
10793 * is required.)
10794 */
10795 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10796 offs + total_off > buf->dtb_size) {
10797 woffs = buf->dtb_xamot_offset;
10798
10799 if (offs + total_off > buf->dtb_size) {
10800 /*
10801 * We can't fit in the end of the buffer. First, a
10802 * sanity check that we can fit in the buffer at all.
10803 */
10804 if (total_off > buf->dtb_size) {
10805 dtrace_buffer_drop(buf);
10806 return (-1);
10807 }
10808
10809 /*
10810 * We're going to be storing at the top of the buffer,
10811 * so now we need to deal with the wrapped offset. We
10812 * only reset our wrapped offset to 0 if it is
10813 * currently greater than the current offset. If it
10814 * is less than the current offset, it is because a
10815 * previous allocation induced a wrap -- but the
10816 * allocation didn't subsequently take the space due
10817 * to an error or false predicate evaluation. In this
10818 * case, we'll just leave the wrapped offset alone: if
10819 * the wrapped offset hasn't been advanced far enough
10820 * for this allocation, it will be adjusted in the
10821 * lower loop.
10822 */
10823 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10824 if (woffs >= offs)
10825 woffs = 0;
10826 } else {
10827 woffs = 0;
10828 }
10829
10830 /*
10831 * Now we know that we're going to be storing to the
10832 * top of the buffer and that there is room for us
10833 * there. We need to clear the buffer from the current
10834 * offset to the end (there may be old gunk there).
10835 */
10836 while ((uint64_t)offs < buf->dtb_size)
10837 tomax[offs++] = 0;
10838
10839 /*
10840 * We need to set our offset to zero. And because we
10841 * are wrapping, we need to set the bit indicating as
10842 * much. We can also adjust our needed space back
10843 * down to the space required by the ECB -- we know
10844 * that the top of the buffer is aligned.
10845 */
10846 offs = 0;
10847 total_off = needed;
10848 buf->dtb_flags |= DTRACEBUF_WRAPPED;
10849 } else {
10850 /*
10851 * There is room for us in the buffer, so we simply
10852 * need to check the wrapped offset.
10853 */
10854 if (woffs < offs) {
10855 /*
10856 * The wrapped offset is less than the offset.
10857 * This can happen if we allocated buffer space
10858 * that induced a wrap, but then we didn't
10859 * subsequently take the space due to an error
10860 * or false predicate evaluation. This is
10861 * okay; we know that _this_ allocation isn't
10862 * going to induce a wrap. We still can't
10863 * reset the wrapped offset to be zero,
10864 * however: the space may have been trashed in
10865 * the previous failed probe attempt. But at
10866 * least the wrapped offset doesn't need to
10867 * be adjusted at all...
10868 */
10869 goto out;
10870 }
10871 }
10872
10873 while (offs + total_off > (size_t)woffs) {
10874 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10875 size_t size;
10876
10877 if (epid == DTRACE_EPIDNONE) {
10878 size = sizeof (uint32_t);
10879 } else {
10880 ASSERT(epid <= (dtrace_epid_t)state->dts_necbs);
10881 ASSERT(state->dts_ecbs[epid - 1] != NULL);
10882
10883 size = state->dts_ecbs[epid - 1]->dte_size;
10884 }
10885
10886 ASSERT(woffs + size <= buf->dtb_size);
10887 ASSERT(size != 0);
10888
10889 if (woffs + size == buf->dtb_size) {
10890 /*
10891 * We've reached the end of the buffer; we want
10892 * to set the wrapped offset to 0 and break
10893 * out. However, if the offs is 0, then we're
10894 * in a strange edge-condition: the amount of
10895 * space that we want to reserve plus the size
10896 * of the record that we're overwriting is
10897 * greater than the size of the buffer. This
10898 * is problematic because if we reserve the
10899 * space but subsequently don't consume it (due
10900 * to a failed predicate or error) the wrapped
10901 * offset will be 0 -- yet the EPID at offset 0
10902 * will not be committed. This situation is
10903 * relatively easy to deal with: if we're in
10904 * this case, the buffer is indistinguishable
10905 * from one that hasn't wrapped; we need only
10906 * finish the job by clearing the wrapped bit,
10907 * explicitly setting the offset to be 0, and
10908 * zero'ing out the old data in the buffer.
10909 */
10910 if (offs == 0) {
10911 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10912 buf->dtb_offset = 0;
10913 woffs = total_off;
10914
10915 while ((uint64_t)woffs < buf->dtb_size)
10916 tomax[woffs++] = 0;
10917 }
10918
10919 woffs = 0;
10920 break;
10921 }
10922
10923 woffs += size;
10924 }
10925
10926 /*
10927 * We have a wrapped offset. It may be that the wrapped offset
10928 * has become zero -- that's okay.
10929 */
10930 buf->dtb_xamot_offset = woffs;
10931 }
10932
10933 out:
10934 /*
10935 * Now we can plow the buffer with any necessary padding.
10936 */
10937 while (offs & (align - 1)) {
10938 /*
10939 * Assert that our alignment is off by a number which
10940 * is itself sizeof (uint32_t) aligned.
10941 */
10942 ASSERT(!((align - (offs & (align - 1))) &
10943 (sizeof (uint32_t) - 1)));
10944 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10945 offs += sizeof (uint32_t);
10946 }
10947
10948 if (buf->dtb_flags & DTRACEBUF_FILL) {
10949 if (offs + needed > buf->dtb_size - state->dts_reserve) {
10950 buf->dtb_flags |= DTRACEBUF_FULL;
10951 return (-1);
10952 }
10953 }
10954
10955 if (mstate == NULL)
10956 return (offs);
10957
10958 /*
10959 * For ring buffers and fill buffers, the scratch space is always
10960 * the inactive buffer.
10961 */
10962 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10963 mstate->dtms_scratch_size = buf->dtb_size;
10964 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10965
10966 return (offs);
10967 }
10968
10969 static void
10970 dtrace_buffer_polish(dtrace_buffer_t *buf)
10971 {
10972 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10973 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10974
10975 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10976 return;
10977
10978 /*
10979 * We need to polish the ring buffer. There are three cases:
10980 *
10981 * - The first (and presumably most common) is that there is no gap
10982 * between the buffer offset and the wrapped offset. In this case,
10983 * there is nothing in the buffer that isn't valid data; we can
10984 * mark the buffer as polished and return.
10985 *
10986 * - The second (less common than the first but still more common
10987 * than the third) is that there is a gap between the buffer offset
10988 * and the wrapped offset, and the wrapped offset is larger than the
10989 * buffer offset. This can happen because of an alignment issue, or
10990 * can happen because of a call to dtrace_buffer_reserve() that
10991 * didn't subsequently consume the buffer space. In this case,
10992 * we need to zero the data from the buffer offset to the wrapped
10993 * offset.
10994 *
10995 * - The third (and least common) is that there is a gap between the
10996 * buffer offset and the wrapped offset, but the wrapped offset is
10997 * _less_ than the buffer offset. This can only happen because a
10998 * call to dtrace_buffer_reserve() induced a wrap, but the space
10999 * was not subsequently consumed. In this case, we need to zero the
11000 * space from the offset to the end of the buffer _and_ from the
11001 * top of the buffer to the wrapped offset.
11002 */
11003 if (buf->dtb_offset < buf->dtb_xamot_offset) {
11004 bzero(buf->dtb_tomax + buf->dtb_offset,
11005 buf->dtb_xamot_offset - buf->dtb_offset);
11006 }
11007
11008 if (buf->dtb_offset > buf->dtb_xamot_offset) {
11009 bzero(buf->dtb_tomax + buf->dtb_offset,
11010 buf->dtb_size - buf->dtb_offset);
11011 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11012 }
11013 }
11014
11015 static void
11016 dtrace_buffer_free(dtrace_buffer_t *bufs)
11017 {
11018 int i;
11019
11020 for (i = 0; i < (int)NCPU; i++) {
11021 dtrace_buffer_t *buf = &bufs[i];
11022
11023 if (buf->dtb_tomax == NULL) {
11024 ASSERT(buf->dtb_xamot == NULL);
11025 ASSERT(buf->dtb_size == 0);
11026 continue;
11027 }
11028
11029 if (buf->dtb_xamot != NULL) {
11030 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11031 kmem_free(buf->dtb_xamot, buf->dtb_size);
11032
11033 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11034 dtrace_buffer_memory_inuse -= buf->dtb_size;
11035 }
11036
11037 kmem_free(buf->dtb_tomax, buf->dtb_size);
11038 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11039 dtrace_buffer_memory_inuse -= buf->dtb_size;
11040
11041 buf->dtb_size = 0;
11042 buf->dtb_tomax = NULL;
11043 buf->dtb_xamot = NULL;
11044 }
11045 }
11046
11047 /*
11048 * DTrace Enabling Functions
11049 */
11050 static dtrace_enabling_t *
11051 dtrace_enabling_create(dtrace_vstate_t *vstate)
11052 {
11053 dtrace_enabling_t *enab;
11054
11055 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11056 enab->dten_vstate = vstate;
11057
11058 return (enab);
11059 }
11060
11061 static void
11062 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11063 {
11064 dtrace_ecbdesc_t **ndesc;
11065 size_t osize, nsize;
11066
11067 /*
11068 * We can't add to enablings after we've enabled them, or after we've
11069 * retained them.
11070 */
11071 ASSERT(enab->dten_probegen == 0);
11072 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11073
11074 /* APPLE NOTE: this protects against gcc 4.0 botch on x86 */
11075 if (ecb == NULL) return;
11076
11077 if (enab->dten_ndesc < enab->dten_maxdesc) {
11078 enab->dten_desc[enab->dten_ndesc++] = ecb;
11079 return;
11080 }
11081
11082 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11083
11084 if (enab->dten_maxdesc == 0) {
11085 enab->dten_maxdesc = 1;
11086 } else {
11087 enab->dten_maxdesc <<= 1;
11088 }
11089
11090 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11091
11092 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11093 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11094 bcopy(enab->dten_desc, ndesc, osize);
11095 kmem_free(enab->dten_desc, osize);
11096
11097 enab->dten_desc = ndesc;
11098 enab->dten_desc[enab->dten_ndesc++] = ecb;
11099 }
11100
11101 static void
11102 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11103 dtrace_probedesc_t *pd)
11104 {
11105 dtrace_ecbdesc_t *new;
11106 dtrace_predicate_t *pred;
11107 dtrace_actdesc_t *act;
11108
11109 /*
11110 * We're going to create a new ECB description that matches the
11111 * specified ECB in every way, but has the specified probe description.
11112 */
11113 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11114
11115 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11116 dtrace_predicate_hold(pred);
11117
11118 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11119 dtrace_actdesc_hold(act);
11120
11121 new->dted_action = ecb->dted_action;
11122 new->dted_pred = ecb->dted_pred;
11123 new->dted_probe = *pd;
11124 new->dted_uarg = ecb->dted_uarg;
11125
11126 dtrace_enabling_add(enab, new);
11127 }
11128
11129 static void
11130 dtrace_enabling_dump(dtrace_enabling_t *enab)
11131 {
11132 int i;
11133
11134 for (i = 0; i < enab->dten_ndesc; i++) {
11135 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11136
11137 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11138 desc->dtpd_provider, desc->dtpd_mod,
11139 desc->dtpd_func, desc->dtpd_name);
11140 }
11141 }
11142
11143 static void
11144 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11145 {
11146 int i;
11147 dtrace_ecbdesc_t *ep;
11148 dtrace_vstate_t *vstate = enab->dten_vstate;
11149
11150 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11151
11152 for (i = 0; i < enab->dten_ndesc; i++) {
11153 dtrace_actdesc_t *act, *next;
11154 dtrace_predicate_t *pred;
11155
11156 ep = enab->dten_desc[i];
11157
11158 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11159 dtrace_predicate_release(pred, vstate);
11160
11161 for (act = ep->dted_action; act != NULL; act = next) {
11162 next = act->dtad_next;
11163 dtrace_actdesc_release(act, vstate);
11164 }
11165
11166 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11167 }
11168
11169 kmem_free(enab->dten_desc,
11170 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11171
11172 /*
11173 * If this was a retained enabling, decrement the dts_nretained count
11174 * and take it off of the dtrace_retained list.
11175 */
11176 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11177 dtrace_retained == enab) {
11178 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11179 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11180 enab->dten_vstate->dtvs_state->dts_nretained--;
11181 dtrace_retained_gen++;
11182 }
11183
11184 if (enab->dten_prev == NULL) {
11185 if (dtrace_retained == enab) {
11186 dtrace_retained = enab->dten_next;
11187
11188 if (dtrace_retained != NULL)
11189 dtrace_retained->dten_prev = NULL;
11190 }
11191 } else {
11192 ASSERT(enab != dtrace_retained);
11193 ASSERT(dtrace_retained != NULL);
11194 enab->dten_prev->dten_next = enab->dten_next;
11195 }
11196
11197 if (enab->dten_next != NULL) {
11198 ASSERT(dtrace_retained != NULL);
11199 enab->dten_next->dten_prev = enab->dten_prev;
11200 }
11201
11202 kmem_free(enab, sizeof (dtrace_enabling_t));
11203 }
11204
11205 static int
11206 dtrace_enabling_retain(dtrace_enabling_t *enab)
11207 {
11208 dtrace_state_t *state;
11209
11210 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11211 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11212 ASSERT(enab->dten_vstate != NULL);
11213
11214 state = enab->dten_vstate->dtvs_state;
11215 ASSERT(state != NULL);
11216
11217 /*
11218 * We only allow each state to retain dtrace_retain_max enablings.
11219 */
11220 if (state->dts_nretained >= dtrace_retain_max)
11221 return (ENOSPC);
11222
11223 state->dts_nretained++;
11224 dtrace_retained_gen++;
11225
11226 if (dtrace_retained == NULL) {
11227 dtrace_retained = enab;
11228 return (0);
11229 }
11230
11231 enab->dten_next = dtrace_retained;
11232 dtrace_retained->dten_prev = enab;
11233 dtrace_retained = enab;
11234
11235 return (0);
11236 }
11237
11238 static int
11239 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11240 dtrace_probedesc_t *create)
11241 {
11242 dtrace_enabling_t *new, *enab;
11243 int found = 0, err = ENOENT;
11244
11245 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11246 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11247 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11248 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11249 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11250
11251 new = dtrace_enabling_create(&state->dts_vstate);
11252
11253 /*
11254 * Iterate over all retained enablings, looking for enablings that
11255 * match the specified state.
11256 */
11257 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11258 int i;
11259
11260 /*
11261 * dtvs_state can only be NULL for helper enablings -- and
11262 * helper enablings can't be retained.
11263 */
11264 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11265
11266 if (enab->dten_vstate->dtvs_state != state)
11267 continue;
11268
11269 /*
11270 * Now iterate over each probe description; we're looking for
11271 * an exact match to the specified probe description.
11272 */
11273 for (i = 0; i < enab->dten_ndesc; i++) {
11274 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11275 dtrace_probedesc_t *pd = &ep->dted_probe;
11276
11277 /* APPLE NOTE: Darwin employs size bounded string operation. */
11278 if (strncmp(pd->dtpd_provider, match->dtpd_provider, DTRACE_PROVNAMELEN))
11279 continue;
11280
11281 if (strncmp(pd->dtpd_mod, match->dtpd_mod, DTRACE_MODNAMELEN))
11282 continue;
11283
11284 if (strncmp(pd->dtpd_func, match->dtpd_func, DTRACE_FUNCNAMELEN))
11285 continue;
11286
11287 if (strncmp(pd->dtpd_name, match->dtpd_name, DTRACE_NAMELEN))
11288 continue;
11289
11290 /*
11291 * We have a winning probe! Add it to our growing
11292 * enabling.
11293 */
11294 found = 1;
11295 dtrace_enabling_addlike(new, ep, create);
11296 }
11297 }
11298
11299 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11300 dtrace_enabling_destroy(new);
11301 return (err);
11302 }
11303
11304 return (0);
11305 }
11306
11307 static void
11308 dtrace_enabling_retract(dtrace_state_t *state)
11309 {
11310 dtrace_enabling_t *enab, *next;
11311
11312 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11313
11314 /*
11315 * Iterate over all retained enablings, destroy the enablings retained
11316 * for the specified state.
11317 */
11318 for (enab = dtrace_retained; enab != NULL; enab = next) {
11319 next = enab->dten_next;
11320
11321 /*
11322 * dtvs_state can only be NULL for helper enablings -- and
11323 * helper enablings can't be retained.
11324 */
11325 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11326
11327 if (enab->dten_vstate->dtvs_state == state) {
11328 ASSERT(state->dts_nretained > 0);
11329 dtrace_enabling_destroy(enab);
11330 }
11331 }
11332
11333 ASSERT(state->dts_nretained == 0);
11334 }
11335
11336 static int
11337 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11338 {
11339 int i = 0;
11340 int total_matched = 0, matched = 0;
11341
11342 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11343 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11344
11345 for (i = 0; i < enab->dten_ndesc; i++) {
11346 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11347
11348 enab->dten_current = ep;
11349 enab->dten_error = 0;
11350
11351 /*
11352 * If a provider failed to enable a probe then get out and
11353 * let the consumer know we failed.
11354 */
11355 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11356 return (EBUSY);
11357
11358 total_matched += matched;
11359
11360 if (enab->dten_error != 0) {
11361 /*
11362 * If we get an error half-way through enabling the
11363 * probes, we kick out -- perhaps with some number of
11364 * them enabled. Leaving enabled probes enabled may
11365 * be slightly confusing for user-level, but we expect
11366 * that no one will attempt to actually drive on in
11367 * the face of such errors. If this is an anonymous
11368 * enabling (indicated with a NULL nmatched pointer),
11369 * we cmn_err() a message. We aren't expecting to
11370 * get such an error -- such as it can exist at all,
11371 * it would be a result of corrupted DOF in the driver
11372 * properties.
11373 */
11374 if (nmatched == NULL) {
11375 cmn_err(CE_WARN, "dtrace_enabling_match() "
11376 "error on %p: %d", (void *)ep,
11377 enab->dten_error);
11378 }
11379
11380 return (enab->dten_error);
11381 }
11382 }
11383
11384 enab->dten_probegen = dtrace_probegen;
11385 if (nmatched != NULL)
11386 *nmatched = total_matched;
11387
11388 return (0);
11389 }
11390
11391 static void
11392 dtrace_enabling_matchall(void)
11393 {
11394 dtrace_enabling_t *enab;
11395
11396 lck_mtx_lock(&cpu_lock);
11397 lck_mtx_lock(&dtrace_lock);
11398
11399 /*
11400 * Iterate over all retained enablings to see if any probes match
11401 * against them. We only perform this operation on enablings for which
11402 * we have sufficient permissions by virtue of being in the global zone
11403 * or in the same zone as the DTrace client. Because we can be called
11404 * after dtrace_detach() has been called, we cannot assert that there
11405 * are retained enablings. We can safely load from dtrace_retained,
11406 * however: the taskq_destroy() at the end of dtrace_detach() will
11407 * block pending our completion.
11408 */
11409
11410 /*
11411 * Darwin doesn't do zones.
11412 * Behave as if always in "global" zone."
11413 */
11414 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11415 (void) dtrace_enabling_match(enab, NULL);
11416 }
11417
11418 lck_mtx_unlock(&dtrace_lock);
11419 lck_mtx_unlock(&cpu_lock);
11420 }
11421
11422 /*
11423 * If an enabling is to be enabled without having matched probes (that is, if
11424 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11425 * enabling must be _primed_ by creating an ECB for every ECB description.
11426 * This must be done to assure that we know the number of speculations, the
11427 * number of aggregations, the minimum buffer size needed, etc. before we
11428 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11429 * enabling any probes, we create ECBs for every ECB decription, but with a
11430 * NULL probe -- which is exactly what this function does.
11431 */
11432 static void
11433 dtrace_enabling_prime(dtrace_state_t *state)
11434 {
11435 dtrace_enabling_t *enab;
11436 int i;
11437
11438 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11439 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11440
11441 if (enab->dten_vstate->dtvs_state != state)
11442 continue;
11443
11444 /*
11445 * We don't want to prime an enabling more than once, lest
11446 * we allow a malicious user to induce resource exhaustion.
11447 * (The ECBs that result from priming an enabling aren't
11448 * leaked -- but they also aren't deallocated until the
11449 * consumer state is destroyed.)
11450 */
11451 if (enab->dten_primed)
11452 continue;
11453
11454 for (i = 0; i < enab->dten_ndesc; i++) {
11455 enab->dten_current = enab->dten_desc[i];
11456 (void) dtrace_probe_enable(NULL, enab);
11457 }
11458
11459 enab->dten_primed = 1;
11460 }
11461 }
11462
11463 /*
11464 * Called to indicate that probes should be provided due to retained
11465 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
11466 * must take an initial lap through the enabling calling the dtps_provide()
11467 * entry point explicitly to allow for autocreated probes.
11468 */
11469 static void
11470 dtrace_enabling_provide(dtrace_provider_t *prv)
11471 {
11472 int i, all = 0;
11473 dtrace_probedesc_t desc;
11474 dtrace_genid_t gen;
11475
11476 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11477 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
11478
11479 if (prv == NULL) {
11480 all = 1;
11481 prv = dtrace_provider;
11482 }
11483
11484 do {
11485 dtrace_enabling_t *enab;
11486 void *parg = prv->dtpv_arg;
11487
11488 retry:
11489 gen = dtrace_retained_gen;
11490 for (enab = dtrace_retained; enab != NULL;
11491 enab = enab->dten_next) {
11492 for (i = 0; i < enab->dten_ndesc; i++) {
11493 desc = enab->dten_desc[i]->dted_probe;
11494 lck_mtx_unlock(&dtrace_lock);
11495 prv->dtpv_pops.dtps_provide(parg, &desc);
11496 lck_mtx_lock(&dtrace_lock);
11497 /*
11498 * Process the retained enablings again if
11499 * they have changed while we weren't holding
11500 * dtrace_lock.
11501 */
11502 if (gen != dtrace_retained_gen)
11503 goto retry;
11504 }
11505 }
11506 } while (all && (prv = prv->dtpv_next) != NULL);
11507
11508 lck_mtx_unlock(&dtrace_lock);
11509 dtrace_probe_provide(NULL, all ? NULL : prv);
11510 lck_mtx_lock(&dtrace_lock);
11511 }
11512
11513 /*
11514 * DTrace DOF Functions
11515 */
11516 /*ARGSUSED*/
11517 static void
11518 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11519 {
11520 #pragma unused(dof) /* __APPLE__ */
11521 if (dtrace_err_verbose)
11522 cmn_err(CE_WARN, "failed to process DOF: %s", str);
11523
11524 #ifdef DTRACE_ERRDEBUG
11525 dtrace_errdebug(str);
11526 #endif
11527 }
11528
11529 /*
11530 * Create DOF out of a currently enabled state. Right now, we only create
11531 * DOF containing the run-time options -- but this could be expanded to create
11532 * complete DOF representing the enabled state.
11533 */
11534 static dof_hdr_t *
11535 dtrace_dof_create(dtrace_state_t *state)
11536 {
11537 dof_hdr_t *dof;
11538 dof_sec_t *sec;
11539 dof_optdesc_t *opt;
11540 int i, len = sizeof (dof_hdr_t) +
11541 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11542 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11543
11544 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11545
11546 dof = dt_kmem_zalloc_aligned(len, 8, KM_SLEEP);
11547 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11548 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11549 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11550 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11551
11552 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11553 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11554 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11555 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11556 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11557 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11558
11559 dof->dofh_flags = 0;
11560 dof->dofh_hdrsize = sizeof (dof_hdr_t);
11561 dof->dofh_secsize = sizeof (dof_sec_t);
11562 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
11563 dof->dofh_secoff = sizeof (dof_hdr_t);
11564 dof->dofh_loadsz = len;
11565 dof->dofh_filesz = len;
11566 dof->dofh_pad = 0;
11567
11568 /*
11569 * Fill in the option section header...
11570 */
11571 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11572 sec->dofs_type = DOF_SECT_OPTDESC;
11573 sec->dofs_align = sizeof (uint64_t);
11574 sec->dofs_flags = DOF_SECF_LOAD;
11575 sec->dofs_entsize = sizeof (dof_optdesc_t);
11576
11577 opt = (dof_optdesc_t *)((uintptr_t)sec +
11578 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11579
11580 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11581 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11582
11583 for (i = 0; i < DTRACEOPT_MAX; i++) {
11584 opt[i].dofo_option = i;
11585 opt[i].dofo_strtab = DOF_SECIDX_NONE;
11586 opt[i].dofo_value = state->dts_options[i];
11587 }
11588
11589 return (dof);
11590 }
11591
11592 static dof_hdr_t *
11593 dtrace_dof_copyin(user_addr_t uarg, int *errp)
11594 {
11595 dof_hdr_t hdr, *dof;
11596
11597 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
11598
11599 /*
11600 * First, we're going to copyin() the sizeof (dof_hdr_t).
11601 */
11602 if (copyin(uarg, &hdr, sizeof (hdr)) != 0) {
11603 dtrace_dof_error(NULL, "failed to copyin DOF header");
11604 *errp = EFAULT;
11605 return (NULL);
11606 }
11607
11608 /*
11609 * Now we'll allocate the entire DOF and copy it in -- provided
11610 * that the length isn't outrageous.
11611 */
11612 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
11613 dtrace_dof_error(&hdr, "load size exceeds maximum");
11614 *errp = E2BIG;
11615 return (NULL);
11616 }
11617
11618 if (hdr.dofh_loadsz < sizeof (hdr)) {
11619 dtrace_dof_error(&hdr, "invalid load size");
11620 *errp = EINVAL;
11621 return (NULL);
11622 }
11623
11624 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
11625
11626 if (copyin(uarg, dof, hdr.dofh_loadsz) != 0 ||
11627 dof->dofh_loadsz != hdr.dofh_loadsz) {
11628 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
11629 *errp = EFAULT;
11630 return (NULL);
11631 }
11632
11633 return (dof);
11634 }
11635
11636 static dof_hdr_t *
11637 dtrace_dof_copyin_from_proc(proc_t* p, user_addr_t uarg, int *errp)
11638 {
11639 dof_hdr_t hdr, *dof;
11640
11641 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
11642
11643 /*
11644 * First, we're going to copyin() the sizeof (dof_hdr_t).
11645 */
11646 if (uread(p, &hdr, sizeof(hdr), uarg) != KERN_SUCCESS) {
11647 dtrace_dof_error(NULL, "failed to copyin DOF header");
11648 *errp = EFAULT;
11649 return (NULL);
11650 }
11651
11652 /*
11653 * Now we'll allocate the entire DOF and copy it in -- provided
11654 * that the length isn't outrageous.
11655 */
11656 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
11657 dtrace_dof_error(&hdr, "load size exceeds maximum");
11658 *errp = E2BIG;
11659 return (NULL);
11660 }
11661
11662 if (hdr.dofh_loadsz < sizeof (hdr)) {
11663 dtrace_dof_error(&hdr, "invalid load size");
11664 *errp = EINVAL;
11665 return (NULL);
11666 }
11667
11668 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
11669
11670 if (uread(p, dof, hdr.dofh_loadsz, uarg) != KERN_SUCCESS) {
11671 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
11672 *errp = EFAULT;
11673 return (NULL);
11674 }
11675
11676 return (dof);
11677 }
11678
11679 static dof_hdr_t *
11680 dtrace_dof_property(const char *name)
11681 {
11682 uchar_t *buf;
11683 uint64_t loadsz;
11684 unsigned int len, i;
11685 dof_hdr_t *dof;
11686
11687 /*
11688 * Unfortunately, array of values in .conf files are always (and
11689 * only) interpreted to be integer arrays. We must read our DOF
11690 * as an integer array, and then squeeze it into a byte array.
11691 */
11692 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
11693 name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
11694 return (NULL);
11695
11696 for (i = 0; i < len; i++)
11697 buf[i] = (uchar_t)(((int *)buf)[i]);
11698
11699 if (len < sizeof (dof_hdr_t)) {
11700 ddi_prop_free(buf);
11701 dtrace_dof_error(NULL, "truncated header");
11702 return (NULL);
11703 }
11704
11705 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
11706 ddi_prop_free(buf);
11707 dtrace_dof_error(NULL, "truncated DOF");
11708 return (NULL);
11709 }
11710
11711 if (loadsz >= (uint64_t)dtrace_dof_maxsize) {
11712 ddi_prop_free(buf);
11713 dtrace_dof_error(NULL, "oversized DOF");
11714 return (NULL);
11715 }
11716
11717 dof = dt_kmem_alloc_aligned(loadsz, 8, KM_SLEEP);
11718 bcopy(buf, dof, loadsz);
11719 ddi_prop_free(buf);
11720
11721 return (dof);
11722 }
11723
11724 static void
11725 dtrace_dof_destroy(dof_hdr_t *dof)
11726 {
11727 dt_kmem_free_aligned(dof, dof->dofh_loadsz);
11728 }
11729
11730 /*
11731 * Return the dof_sec_t pointer corresponding to a given section index. If the
11732 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
11733 * a type other than DOF_SECT_NONE is specified, the header is checked against
11734 * this type and NULL is returned if the types do not match.
11735 */
11736 static dof_sec_t *
11737 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
11738 {
11739 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
11740 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
11741
11742 if (i >= dof->dofh_secnum) {
11743 dtrace_dof_error(dof, "referenced section index is invalid");
11744 return (NULL);
11745 }
11746
11747 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
11748 dtrace_dof_error(dof, "referenced section is not loadable");
11749 return (NULL);
11750 }
11751
11752 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
11753 dtrace_dof_error(dof, "referenced section is the wrong type");
11754 return (NULL);
11755 }
11756
11757 return (sec);
11758 }
11759
11760 static dtrace_probedesc_t *
11761 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
11762 {
11763 dof_probedesc_t *probe;
11764 dof_sec_t *strtab;
11765 uintptr_t daddr = (uintptr_t)dof;
11766 uintptr_t str;
11767 size_t size;
11768
11769 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
11770 dtrace_dof_error(dof, "invalid probe section");
11771 return (NULL);
11772 }
11773
11774 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11775 dtrace_dof_error(dof, "bad alignment in probe description");
11776 return (NULL);
11777 }
11778
11779 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
11780 dtrace_dof_error(dof, "truncated probe description");
11781 return (NULL);
11782 }
11783
11784 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
11785 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
11786
11787 if (strtab == NULL)
11788 return (NULL);
11789
11790 str = daddr + strtab->dofs_offset;
11791 size = strtab->dofs_size;
11792
11793 if (probe->dofp_provider >= strtab->dofs_size) {
11794 dtrace_dof_error(dof, "corrupt probe provider");
11795 return (NULL);
11796 }
11797
11798 (void) strncpy(desc->dtpd_provider,
11799 (char *)(str + probe->dofp_provider),
11800 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11801
11802 /* APPLE NOTE: Darwin employs size bounded string operation. */
11803 desc->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
11804
11805 if (probe->dofp_mod >= strtab->dofs_size) {
11806 dtrace_dof_error(dof, "corrupt probe module");
11807 return (NULL);
11808 }
11809
11810 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11811 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11812
11813 /* APPLE NOTE: Darwin employs size bounded string operation. */
11814 desc->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
11815
11816 if (probe->dofp_func >= strtab->dofs_size) {
11817 dtrace_dof_error(dof, "corrupt probe function");
11818 return (NULL);
11819 }
11820
11821 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11822 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11823
11824 /* APPLE NOTE: Darwin employs size bounded string operation. */
11825 desc->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
11826
11827 if (probe->dofp_name >= strtab->dofs_size) {
11828 dtrace_dof_error(dof, "corrupt probe name");
11829 return (NULL);
11830 }
11831
11832 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11833 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11834
11835 /* APPLE NOTE: Darwin employs size bounded string operation. */
11836 desc->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
11837
11838 return (desc);
11839 }
11840
11841 static dtrace_difo_t *
11842 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11843 cred_t *cr)
11844 {
11845 dtrace_difo_t *dp;
11846 size_t ttl = 0;
11847 dof_difohdr_t *dofd;
11848 uintptr_t daddr = (uintptr_t)dof;
11849 size_t max_size = dtrace_difo_maxsize;
11850 uint_t i;
11851 int l, n;
11852
11853
11854 static const struct {
11855 int section;
11856 int bufoffs;
11857 int lenoffs;
11858 int entsize;
11859 int align;
11860 const char *msg;
11861 } difo[] = {
11862 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11863 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11864 sizeof (dif_instr_t), "multiple DIF sections" },
11865
11866 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11867 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11868 sizeof (uint64_t), "multiple integer tables" },
11869
11870 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11871 offsetof(dtrace_difo_t, dtdo_strlen), 0,
11872 sizeof (char), "multiple string tables" },
11873
11874 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11875 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11876 sizeof (uint_t), "multiple variable tables" },
11877
11878 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
11879 };
11880
11881 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11882 dtrace_dof_error(dof, "invalid DIFO header section");
11883 return (NULL);
11884 }
11885
11886 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11887 dtrace_dof_error(dof, "bad alignment in DIFO header");
11888 return (NULL);
11889 }
11890
11891 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11892 sec->dofs_size % sizeof (dof_secidx_t)) {
11893 dtrace_dof_error(dof, "bad size in DIFO header");
11894 return (NULL);
11895 }
11896
11897 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11898 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11899
11900 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11901 dp->dtdo_rtype = dofd->dofd_rtype;
11902
11903 for (l = 0; l < n; l++) {
11904 dof_sec_t *subsec;
11905 void **bufp;
11906 uint32_t *lenp;
11907
11908 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11909 dofd->dofd_links[l])) == NULL)
11910 goto err; /* invalid section link */
11911
11912 if (ttl + subsec->dofs_size > max_size) {
11913 dtrace_dof_error(dof, "exceeds maximum size");
11914 goto err;
11915 }
11916
11917 ttl += subsec->dofs_size;
11918
11919 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11920
11921 if (subsec->dofs_type != (uint32_t)difo[i].section)
11922 continue;
11923
11924 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11925 dtrace_dof_error(dof, "section not loaded");
11926 goto err;
11927 }
11928
11929 if (subsec->dofs_align != (uint32_t)difo[i].align) {
11930 dtrace_dof_error(dof, "bad alignment");
11931 goto err;
11932 }
11933
11934 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11935 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11936
11937 if (*bufp != NULL) {
11938 dtrace_dof_error(dof, difo[i].msg);
11939 goto err;
11940 }
11941
11942 if ((uint32_t)difo[i].entsize != subsec->dofs_entsize) {
11943 dtrace_dof_error(dof, "entry size mismatch");
11944 goto err;
11945 }
11946
11947 if (subsec->dofs_entsize != 0 &&
11948 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11949 dtrace_dof_error(dof, "corrupt entry size");
11950 goto err;
11951 }
11952
11953 *lenp = subsec->dofs_size;
11954 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11955 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11956 *bufp, subsec->dofs_size);
11957
11958 if (subsec->dofs_entsize != 0)
11959 *lenp /= subsec->dofs_entsize;
11960
11961 break;
11962 }
11963
11964 /*
11965 * If we encounter a loadable DIFO sub-section that is not
11966 * known to us, assume this is a broken program and fail.
11967 */
11968 if (difo[i].section == DOF_SECT_NONE &&
11969 (subsec->dofs_flags & DOF_SECF_LOAD)) {
11970 dtrace_dof_error(dof, "unrecognized DIFO subsection");
11971 goto err;
11972 }
11973 }
11974
11975 if (dp->dtdo_buf == NULL) {
11976 /*
11977 * We can't have a DIF object without DIF text.
11978 */
11979 dtrace_dof_error(dof, "missing DIF text");
11980 goto err;
11981 }
11982
11983 /*
11984 * Before we validate the DIF object, run through the variable table
11985 * looking for the strings -- if any of their size are under, we'll set
11986 * their size to be the system-wide default string size. Note that
11987 * this should _not_ happen if the "strsize" option has been set --
11988 * in this case, the compiler should have set the size to reflect the
11989 * setting of the option.
11990 */
11991 for (i = 0; i < dp->dtdo_varlen; i++) {
11992 dtrace_difv_t *v = &dp->dtdo_vartab[i];
11993 dtrace_diftype_t *t = &v->dtdv_type;
11994
11995 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11996 continue;
11997
11998 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11999 t->dtdt_size = dtrace_strsize_default;
12000 }
12001
12002 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12003 goto err;
12004
12005 dtrace_difo_init(dp, vstate);
12006 return (dp);
12007
12008 err:
12009 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12010 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12011 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12012 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12013
12014 kmem_free(dp, sizeof (dtrace_difo_t));
12015 return (NULL);
12016 }
12017
12018 static dtrace_predicate_t *
12019 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12020 cred_t *cr)
12021 {
12022 dtrace_difo_t *dp;
12023
12024 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12025 return (NULL);
12026
12027 return (dtrace_predicate_create(dp));
12028 }
12029
12030 static dtrace_actdesc_t *
12031 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12032 cred_t *cr)
12033 {
12034 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12035 dof_actdesc_t *desc;
12036 dof_sec_t *difosec;
12037 size_t offs;
12038 uintptr_t daddr = (uintptr_t)dof;
12039 uint64_t arg;
12040 dtrace_actkind_t kind;
12041
12042 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12043 dtrace_dof_error(dof, "invalid action section");
12044 return (NULL);
12045 }
12046
12047 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12048 dtrace_dof_error(dof, "truncated action description");
12049 return (NULL);
12050 }
12051
12052 if (sec->dofs_align != sizeof (uint64_t)) {
12053 dtrace_dof_error(dof, "bad alignment in action description");
12054 return (NULL);
12055 }
12056
12057 if (sec->dofs_size < sec->dofs_entsize) {
12058 dtrace_dof_error(dof, "section entry size exceeds total size");
12059 return (NULL);
12060 }
12061
12062 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12063 dtrace_dof_error(dof, "bad entry size in action description");
12064 return (NULL);
12065 }
12066
12067 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12068 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12069 return (NULL);
12070 }
12071
12072 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12073 desc = (dof_actdesc_t *)(daddr +
12074 (uintptr_t)sec->dofs_offset + offs);
12075 kind = (dtrace_actkind_t)desc->dofa_kind;
12076
12077 if (DTRACEACT_ISPRINTFLIKE(kind) &&
12078 (kind != DTRACEACT_PRINTA ||
12079 desc->dofa_strtab != DOF_SECIDX_NONE)) {
12080 dof_sec_t *strtab;
12081 char *str, *fmt;
12082 uint64_t i;
12083
12084 /*
12085 * printf()-like actions must have a format string.
12086 */
12087 if ((strtab = dtrace_dof_sect(dof,
12088 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12089 goto err;
12090
12091 str = (char *)((uintptr_t)dof +
12092 (uintptr_t)strtab->dofs_offset);
12093
12094 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12095 if (str[i] == '\0')
12096 break;
12097 }
12098
12099 if (i >= strtab->dofs_size) {
12100 dtrace_dof_error(dof, "bogus format string");
12101 goto err;
12102 }
12103
12104 if (i == desc->dofa_arg) {
12105 dtrace_dof_error(dof, "empty format string");
12106 goto err;
12107 }
12108
12109 i -= desc->dofa_arg;
12110 fmt = kmem_alloc(i + 1, KM_SLEEP);
12111 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12112 arg = (uint64_t)(uintptr_t)fmt;
12113 } else {
12114 if (kind == DTRACEACT_PRINTA) {
12115 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12116 arg = 0;
12117 } else {
12118 arg = desc->dofa_arg;
12119 }
12120 }
12121
12122 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12123 desc->dofa_uarg, arg);
12124
12125 if (last != NULL) {
12126 last->dtad_next = act;
12127 } else {
12128 first = act;
12129 }
12130
12131 last = act;
12132
12133 if (desc->dofa_difo == DOF_SECIDX_NONE)
12134 continue;
12135
12136 if ((difosec = dtrace_dof_sect(dof,
12137 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12138 goto err;
12139
12140 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12141
12142 if (act->dtad_difo == NULL)
12143 goto err;
12144 }
12145
12146 ASSERT(first != NULL);
12147 return (first);
12148
12149 err:
12150 for (act = first; act != NULL; act = next) {
12151 next = act->dtad_next;
12152 dtrace_actdesc_release(act, vstate);
12153 }
12154
12155 return (NULL);
12156 }
12157
12158 static dtrace_ecbdesc_t *
12159 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12160 cred_t *cr)
12161 {
12162 dtrace_ecbdesc_t *ep;
12163 dof_ecbdesc_t *ecb;
12164 dtrace_probedesc_t *desc;
12165 dtrace_predicate_t *pred = NULL;
12166
12167 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12168 dtrace_dof_error(dof, "truncated ECB description");
12169 return (NULL);
12170 }
12171
12172 if (sec->dofs_align != sizeof (uint64_t)) {
12173 dtrace_dof_error(dof, "bad alignment in ECB description");
12174 return (NULL);
12175 }
12176
12177 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12178 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12179
12180 if (sec == NULL)
12181 return (NULL);
12182
12183 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12184 ep->dted_uarg = ecb->dofe_uarg;
12185 desc = &ep->dted_probe;
12186
12187 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12188 goto err;
12189
12190 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12191 if ((sec = dtrace_dof_sect(dof,
12192 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12193 goto err;
12194
12195 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12196 goto err;
12197
12198 ep->dted_pred.dtpdd_predicate = pred;
12199 }
12200
12201 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12202 if ((sec = dtrace_dof_sect(dof,
12203 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12204 goto err;
12205
12206 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12207
12208 if (ep->dted_action == NULL)
12209 goto err;
12210 }
12211
12212 return (ep);
12213
12214 err:
12215 if (pred != NULL)
12216 dtrace_predicate_release(pred, vstate);
12217 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12218 return (NULL);
12219 }
12220
12221 /*
12222 * APPLE NOTE: dyld handles dof relocation.
12223 * Darwin does not need dtrace_dof_relocate()
12224 */
12225
12226 /*
12227 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12228 * header: it should be at the front of a memory region that is at least
12229 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12230 * size. It need not be validated in any other way.
12231 */
12232 static int
12233 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12234 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12235 {
12236 #pragma unused(ubase) /* __APPLE__ */
12237 uint64_t len = dof->dofh_loadsz, seclen;
12238 uintptr_t daddr = (uintptr_t)dof;
12239 dtrace_ecbdesc_t *ep;
12240 dtrace_enabling_t *enab;
12241 uint_t i;
12242
12243 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12244 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12245
12246 /*
12247 * Check the DOF header identification bytes. In addition to checking
12248 * valid settings, we also verify that unused bits/bytes are zeroed so
12249 * we can use them later without fear of regressing existing binaries.
12250 */
12251 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12252 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12253 dtrace_dof_error(dof, "DOF magic string mismatch");
12254 return (-1);
12255 }
12256
12257 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12258 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12259 dtrace_dof_error(dof, "DOF has invalid data model");
12260 return (-1);
12261 }
12262
12263 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12264 dtrace_dof_error(dof, "DOF encoding mismatch");
12265 return (-1);
12266 }
12267
12268 /*
12269 * APPLE NOTE: Darwin only supports DOF_VERSION_3 for now.
12270 */
12271 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_3) {
12272 dtrace_dof_error(dof, "DOF version mismatch");
12273 return (-1);
12274 }
12275
12276 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12277 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12278 return (-1);
12279 }
12280
12281 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12282 dtrace_dof_error(dof, "DOF uses too many integer registers");
12283 return (-1);
12284 }
12285
12286 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12287 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12288 return (-1);
12289 }
12290
12291 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12292 if (dof->dofh_ident[i] != 0) {
12293 dtrace_dof_error(dof, "DOF has invalid ident byte set");
12294 return (-1);
12295 }
12296 }
12297
12298 if (dof->dofh_flags & ~DOF_FL_VALID) {
12299 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12300 return (-1);
12301 }
12302
12303 if (dof->dofh_secsize == 0) {
12304 dtrace_dof_error(dof, "zero section header size");
12305 return (-1);
12306 }
12307
12308 /*
12309 * Check that the section headers don't exceed the amount of DOF
12310 * data. Note that we cast the section size and number of sections
12311 * to uint64_t's to prevent possible overflow in the multiplication.
12312 */
12313 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12314
12315 if (dof->dofh_secoff > len || seclen > len ||
12316 dof->dofh_secoff + seclen > len) {
12317 dtrace_dof_error(dof, "truncated section headers");
12318 return (-1);
12319 }
12320
12321 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12322 dtrace_dof_error(dof, "misaligned section headers");
12323 return (-1);
12324 }
12325
12326 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12327 dtrace_dof_error(dof, "misaligned section size");
12328 return (-1);
12329 }
12330
12331 /*
12332 * Take an initial pass through the section headers to be sure that
12333 * the headers don't have stray offsets. If the 'noprobes' flag is
12334 * set, do not permit sections relating to providers, probes, or args.
12335 */
12336 for (i = 0; i < dof->dofh_secnum; i++) {
12337 dof_sec_t *sec = (dof_sec_t *)(daddr +
12338 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12339
12340 if (noprobes) {
12341 switch (sec->dofs_type) {
12342 case DOF_SECT_PROVIDER:
12343 case DOF_SECT_PROBES:
12344 case DOF_SECT_PRARGS:
12345 case DOF_SECT_PROFFS:
12346 dtrace_dof_error(dof, "illegal sections "
12347 "for enabling");
12348 return (-1);
12349 }
12350 }
12351
12352 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12353 continue; /* just ignore non-loadable sections */
12354
12355 if (sec->dofs_align & (sec->dofs_align - 1)) {
12356 dtrace_dof_error(dof, "bad section alignment");
12357 return (-1);
12358 }
12359
12360 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12361 dtrace_dof_error(dof, "misaligned section");
12362 return (-1);
12363 }
12364
12365 if (sec->dofs_offset > len || sec->dofs_size > len ||
12366 sec->dofs_offset + sec->dofs_size > len) {
12367 dtrace_dof_error(dof, "corrupt section header");
12368 return (-1);
12369 }
12370
12371 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12372 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12373 dtrace_dof_error(dof, "non-terminating string table");
12374 return (-1);
12375 }
12376 }
12377
12378 /*
12379 * APPLE NOTE: We have no further relocation to perform.
12380 * All dof values are relative offsets.
12381 */
12382
12383 if ((enab = *enabp) == NULL)
12384 enab = *enabp = dtrace_enabling_create(vstate);
12385
12386 for (i = 0; i < dof->dofh_secnum; i++) {
12387 dof_sec_t *sec = (dof_sec_t *)(daddr +
12388 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12389
12390 if (sec->dofs_type != DOF_SECT_ECBDESC)
12391 continue;
12392
12393 /*
12394 * APPLE NOTE: Defend against gcc 4.0 botch on x86.
12395 * not all paths out of inlined dtrace_dof_ecbdesc
12396 * are checked for the NULL return value.
12397 * Check for NULL explicitly here.
12398 */
12399 ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr);
12400 if (ep == NULL) {
12401 dtrace_enabling_destroy(enab);
12402 *enabp = NULL;
12403 return (-1);
12404 }
12405
12406 dtrace_enabling_add(enab, ep);
12407 }
12408
12409 return (0);
12410 }
12411
12412 /*
12413 * Process DOF for any options. This routine assumes that the DOF has been
12414 * at least processed by dtrace_dof_slurp().
12415 */
12416 static int
12417 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12418 {
12419 uint_t i;
12420 int rval;
12421 uint32_t entsize;
12422 size_t offs;
12423 dof_optdesc_t *desc;
12424
12425 for (i = 0; i < dof->dofh_secnum; i++) {
12426 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12427 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12428
12429 if (sec->dofs_type != DOF_SECT_OPTDESC)
12430 continue;
12431
12432 if (sec->dofs_align != sizeof (uint64_t)) {
12433 dtrace_dof_error(dof, "bad alignment in "
12434 "option description");
12435 return (EINVAL);
12436 }
12437
12438 if ((entsize = sec->dofs_entsize) == 0) {
12439 dtrace_dof_error(dof, "zeroed option entry size");
12440 return (EINVAL);
12441 }
12442
12443 if (entsize < sizeof (dof_optdesc_t)) {
12444 dtrace_dof_error(dof, "bad option entry size");
12445 return (EINVAL);
12446 }
12447
12448 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12449 desc = (dof_optdesc_t *)((uintptr_t)dof +
12450 (uintptr_t)sec->dofs_offset + offs);
12451
12452 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12453 dtrace_dof_error(dof, "non-zero option string");
12454 return (EINVAL);
12455 }
12456
12457 if (desc->dofo_value == (uint64_t)DTRACEOPT_UNSET) {
12458 dtrace_dof_error(dof, "unset option");
12459 return (EINVAL);
12460 }
12461
12462 if ((rval = dtrace_state_option(state,
12463 desc->dofo_option, desc->dofo_value)) != 0) {
12464 dtrace_dof_error(dof, "rejected option");
12465 return (rval);
12466 }
12467 }
12468 }
12469
12470 return (0);
12471 }
12472
12473 /*
12474 * DTrace Consumer State Functions
12475 */
12476 static int
12477 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12478 {
12479 size_t hashsize, maxper, min_size, chunksize = dstate->dtds_chunksize;
12480 void *base;
12481 uintptr_t limit;
12482 dtrace_dynvar_t *dvar, *next, *start;
12483 size_t i;
12484
12485 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12486 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12487
12488 bzero(dstate, sizeof (dtrace_dstate_t));
12489
12490 if ((dstate->dtds_chunksize = chunksize) == 0)
12491 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12492
12493 if (size < (min_size = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12494 size = min_size;
12495
12496 if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12497 return (ENOMEM);
12498
12499 dstate->dtds_size = size;
12500 dstate->dtds_base = base;
12501 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12502 bzero(dstate->dtds_percpu, (int)NCPU * sizeof (dtrace_dstate_percpu_t));
12503
12504 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12505
12506 if (hashsize != 1 && (hashsize & 1))
12507 hashsize--;
12508
12509 dstate->dtds_hashsize = hashsize;
12510 dstate->dtds_hash = dstate->dtds_base;
12511
12512 /*
12513 * Set all of our hash buckets to point to the single sink, and (if
12514 * it hasn't already been set), set the sink's hash value to be the
12515 * sink sentinel value. The sink is needed for dynamic variable
12516 * lookups to know that they have iterated over an entire, valid hash
12517 * chain.
12518 */
12519 for (i = 0; i < hashsize; i++)
12520 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12521
12522 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12523 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12524
12525 /*
12526 * Determine number of active CPUs. Divide free list evenly among
12527 * active CPUs.
12528 */
12529 start = (dtrace_dynvar_t *)
12530 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12531 limit = (uintptr_t)base + size;
12532
12533 maxper = (limit - (uintptr_t)start) / (int)NCPU;
12534 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12535
12536 for (i = 0; i < NCPU; i++) {
12537 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12538
12539 /*
12540 * If we don't even have enough chunks to make it once through
12541 * NCPUs, we're just going to allocate everything to the first
12542 * CPU. And if we're on the last CPU, we're going to allocate
12543 * whatever is left over. In either case, we set the limit to
12544 * be the limit of the dynamic variable space.
12545 */
12546 if (maxper == 0 || i == NCPU - 1) {
12547 limit = (uintptr_t)base + size;
12548 start = NULL;
12549 } else {
12550 limit = (uintptr_t)start + maxper;
12551 start = (dtrace_dynvar_t *)limit;
12552 }
12553
12554 ASSERT(limit <= (uintptr_t)base + size);
12555
12556 for (;;) {
12557 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12558 dstate->dtds_chunksize);
12559
12560 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12561 break;
12562
12563 dvar->dtdv_next = next;
12564 dvar = next;
12565 }
12566
12567 if (maxper == 0)
12568 break;
12569 }
12570
12571 return (0);
12572 }
12573
12574 static void
12575 dtrace_dstate_fini(dtrace_dstate_t *dstate)
12576 {
12577 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12578
12579 if (dstate->dtds_base == NULL)
12580 return;
12581
12582 kmem_free(dstate->dtds_base, dstate->dtds_size);
12583 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
12584 }
12585
12586 static void
12587 dtrace_vstate_fini(dtrace_vstate_t *vstate)
12588 {
12589 /*
12590 * Logical XOR, where are you?
12591 */
12592 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12593
12594 if (vstate->dtvs_nglobals > 0) {
12595 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12596 sizeof (dtrace_statvar_t *));
12597 }
12598
12599 if (vstate->dtvs_ntlocals > 0) {
12600 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12601 sizeof (dtrace_difv_t));
12602 }
12603
12604 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
12605
12606 if (vstate->dtvs_nlocals > 0) {
12607 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
12608 sizeof (dtrace_statvar_t *));
12609 }
12610 }
12611
12612 static void
12613 dtrace_state_clean(dtrace_state_t *state)
12614 {
12615 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
12616 return;
12617
12618 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
12619 dtrace_speculation_clean(state);
12620 }
12621
12622 static void
12623 dtrace_state_deadman(dtrace_state_t *state)
12624 {
12625 hrtime_t now;
12626
12627 dtrace_sync();
12628
12629 now = dtrace_gethrtime();
12630
12631 if (state != dtrace_anon.dta_state &&
12632 now - state->dts_laststatus >= dtrace_deadman_user)
12633 return;
12634
12635 /*
12636 * We must be sure that dts_alive never appears to be less than the
12637 * value upon entry to dtrace_state_deadman(), and because we lack a
12638 * dtrace_cas64(), we cannot store to it atomically. We thus instead
12639 * store INT64_MAX to it, followed by a memory barrier, followed by
12640 * the new value. This assures that dts_alive never appears to be
12641 * less than its true value, regardless of the order in which the
12642 * stores to the underlying storage are issued.
12643 */
12644 state->dts_alive = INT64_MAX;
12645 dtrace_membar_producer();
12646 state->dts_alive = now;
12647 }
12648
12649 static int
12650 dtrace_state_create(dev_t *devp, cred_t *cr, dtrace_state_t **new_state)
12651 {
12652 minor_t minor;
12653 major_t major;
12654 char c[30];
12655 dtrace_state_t *state;
12656 dtrace_optval_t *opt;
12657 int bufsize = (int)NCPU * sizeof (dtrace_buffer_t), i;
12658
12659 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12660 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12661
12662 /* Cause restart */
12663 *new_state = NULL;
12664
12665 /*
12666 * Darwin's DEVFS layer acquired the minor number for this "device" when it called
12667 * dtrace_devfs_clone_func(). At that time, dtrace_devfs_clone_func() proposed a minor number
12668 * (next unused according to vmem_alloc()) and then immediately put the number back in play
12669 * (by calling vmem_free()). Now that minor number is being used for an open, so committing it
12670 * to use. The following vmem_alloc() must deliver that same minor number. FIXME.
12671 */
12672
12673 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
12674 VM_BESTFIT | VM_SLEEP);
12675
12676 if (NULL != devp) {
12677 ASSERT(getminor(*devp) == minor);
12678 if (getminor(*devp) != minor) {
12679 printf("dtrace_open: couldn't re-acquire vended minor number %d. Instead got %d\n",
12680 getminor(*devp), minor);
12681 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12682 return (ERESTART); /* can't reacquire */
12683 }
12684 } else {
12685 /* NULL==devp iff "Anonymous state" (see dtrace_anon_property),
12686 * so just vend the minor device number here de novo since no "open" has occurred. */
12687 }
12688
12689 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
12690 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12691 return (EAGAIN); /* temporary resource shortage */
12692 }
12693
12694 state = ddi_get_soft_state(dtrace_softstate, minor);
12695 state->dts_epid = DTRACE_EPIDNONE + 1;
12696
12697 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
12698 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
12699 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12700
12701 if (devp != NULL) {
12702 major = getemajor(*devp);
12703 } else {
12704 major = ddi_driver_major(dtrace_devi);
12705 }
12706
12707 state->dts_dev = makedevice(major, minor);
12708
12709 if (devp != NULL)
12710 *devp = state->dts_dev;
12711
12712 /*
12713 * We allocate NCPU buffers. On the one hand, this can be quite
12714 * a bit of memory per instance (nearly 36K on a Starcat). On the
12715 * other hand, it saves an additional memory reference in the probe
12716 * path.
12717 */
12718 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
12719 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
12720 state->dts_cleaner = CYCLIC_NONE;
12721 state->dts_deadman = CYCLIC_NONE;
12722 state->dts_vstate.dtvs_state = state;
12723
12724 for (i = 0; i < DTRACEOPT_MAX; i++)
12725 state->dts_options[i] = DTRACEOPT_UNSET;
12726
12727 /*
12728 * Set the default options.
12729 */
12730 opt = state->dts_options;
12731 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
12732 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
12733 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
12734 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
12735 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
12736 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
12737 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
12738 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
12739 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
12740 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
12741 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
12742 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
12743 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
12744 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
12745
12746 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
12747
12748 /*
12749 * Depending on the user credentials, we set flag bits which alter probe
12750 * visibility or the amount of destructiveness allowed. In the case of
12751 * actual anonymous tracing, or the possession of all privileges, all of
12752 * the normal checks are bypassed.
12753 */
12754 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
12755 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
12756 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
12757 } else {
12758 /*
12759 * Set up the credentials for this instantiation. We take a
12760 * hold on the credential to prevent it from disappearing on
12761 * us; this in turn prevents the zone_t referenced by this
12762 * credential from disappearing. This means that we can
12763 * examine the credential and the zone from probe context.
12764 */
12765 crhold(cr);
12766 state->dts_cred.dcr_cred = cr;
12767
12768 /*
12769 * CRA_PROC means "we have *some* privilege for dtrace" and
12770 * unlocks the use of variables like pid, zonename, etc.
12771 */
12772 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12773 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12774 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12775 }
12776
12777 /*
12778 * dtrace_user allows use of syscall and profile providers.
12779 * If the user also has proc_owner and/or proc_zone, we
12780 * extend the scope to include additional visibility and
12781 * destructive power.
12782 */
12783 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12784 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12785 state->dts_cred.dcr_visible |=
12786 DTRACE_CRV_ALLPROC;
12787
12788 state->dts_cred.dcr_action |=
12789 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12790 }
12791
12792 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12793 state->dts_cred.dcr_visible |=
12794 DTRACE_CRV_ALLZONE;
12795
12796 state->dts_cred.dcr_action |=
12797 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12798 }
12799
12800 /*
12801 * If we have all privs in whatever zone this is,
12802 * we can do destructive things to processes which
12803 * have altered credentials.
12804 *
12805 * APPLE NOTE: Darwin doesn't do zones.
12806 * Behave as if zone always has destructive privs.
12807 */
12808
12809 state->dts_cred.dcr_action |=
12810 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12811 }
12812
12813 /*
12814 * Holding the dtrace_kernel privilege also implies that
12815 * the user has the dtrace_user privilege from a visibility
12816 * perspective. But without further privileges, some
12817 * destructive actions are not available.
12818 */
12819 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12820 /*
12821 * Make all probes in all zones visible. However,
12822 * this doesn't mean that all actions become available
12823 * to all zones.
12824 */
12825 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12826 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12827
12828 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12829 DTRACE_CRA_PROC;
12830 /*
12831 * Holding proc_owner means that destructive actions
12832 * for *this* zone are allowed.
12833 */
12834 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12835 state->dts_cred.dcr_action |=
12836 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12837
12838 /*
12839 * Holding proc_zone means that destructive actions
12840 * for this user/group ID in all zones is allowed.
12841 */
12842 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12843 state->dts_cred.dcr_action |=
12844 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12845
12846 /*
12847 * If we have all privs in whatever zone this is,
12848 * we can do destructive things to processes which
12849 * have altered credentials.
12850 *
12851 * APPLE NOTE: Darwin doesn't do zones.
12852 * Behave as if zone always has destructive privs.
12853 */
12854 state->dts_cred.dcr_action |=
12855 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12856 }
12857
12858 /*
12859 * Holding the dtrace_proc privilege gives control over fasttrap
12860 * and pid providers. We need to grant wider destructive
12861 * privileges in the event that the user has proc_owner and/or
12862 * proc_zone.
12863 */
12864 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12865 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12866 state->dts_cred.dcr_action |=
12867 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12868
12869 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12870 state->dts_cred.dcr_action |=
12871 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12872 }
12873 }
12874
12875 *new_state = state;
12876 return(0); /* Success */
12877 }
12878
12879 static int
12880 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12881 {
12882 dtrace_optval_t *opt = state->dts_options, size;
12883 processorid_t cpu = 0;
12884 int flags = 0, rval;
12885
12886 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12887 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12888 ASSERT(which < DTRACEOPT_MAX);
12889 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12890 (state == dtrace_anon.dta_state &&
12891 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12892
12893 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12894 return (0);
12895
12896 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12897 cpu = opt[DTRACEOPT_CPU];
12898
12899 if (which == DTRACEOPT_SPECSIZE)
12900 flags |= DTRACEBUF_NOSWITCH;
12901
12902 if (which == DTRACEOPT_BUFSIZE) {
12903 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12904 flags |= DTRACEBUF_RING;
12905
12906 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12907 flags |= DTRACEBUF_FILL;
12908
12909 if (state != dtrace_anon.dta_state ||
12910 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12911 flags |= DTRACEBUF_INACTIVE;
12912 }
12913
12914 for (size = opt[which]; (size_t)size >= sizeof (uint64_t); size >>= 1) {
12915 /*
12916 * The size must be 8-byte aligned. If the size is not 8-byte
12917 * aligned, drop it down by the difference.
12918 */
12919 if (size & (sizeof (uint64_t) - 1))
12920 size -= size & (sizeof (uint64_t) - 1);
12921
12922 if (size < state->dts_reserve) {
12923 /*
12924 * Buffers always must be large enough to accommodate
12925 * their prereserved space. We return E2BIG instead
12926 * of ENOMEM in this case to allow for user-level
12927 * software to differentiate the cases.
12928 */
12929 return (E2BIG);
12930 }
12931
12932 rval = dtrace_buffer_alloc(buf, size, flags, cpu);
12933
12934 if (rval != ENOMEM) {
12935 opt[which] = size;
12936 return (rval);
12937 }
12938
12939 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12940 return (rval);
12941 }
12942
12943 return (ENOMEM);
12944 }
12945
12946 static int
12947 dtrace_state_buffers(dtrace_state_t *state)
12948 {
12949 dtrace_speculation_t *spec = state->dts_speculations;
12950 int rval, i;
12951
12952 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12953 DTRACEOPT_BUFSIZE)) != 0)
12954 return (rval);
12955
12956 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12957 DTRACEOPT_AGGSIZE)) != 0)
12958 return (rval);
12959
12960 for (i = 0; i < state->dts_nspeculations; i++) {
12961 if ((rval = dtrace_state_buffer(state,
12962 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12963 return (rval);
12964 }
12965
12966 return (0);
12967 }
12968
12969 static void
12970 dtrace_state_prereserve(dtrace_state_t *state)
12971 {
12972 dtrace_ecb_t *ecb;
12973 dtrace_probe_t *probe;
12974
12975 state->dts_reserve = 0;
12976
12977 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12978 return;
12979
12980 /*
12981 * If our buffer policy is a "fill" buffer policy, we need to set the
12982 * prereserved space to be the space required by the END probes.
12983 */
12984 probe = dtrace_probes[dtrace_probeid_end - 1];
12985 ASSERT(probe != NULL);
12986
12987 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12988 if (ecb->dte_state != state)
12989 continue;
12990
12991 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
12992 }
12993 }
12994
12995 static int
12996 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12997 {
12998 dtrace_optval_t *opt = state->dts_options, sz, nspec;
12999 dtrace_speculation_t *spec;
13000 dtrace_buffer_t *buf;
13001 cyc_handler_t hdlr;
13002 cyc_time_t when;
13003 int rval = 0, i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
13004 dtrace_icookie_t cookie;
13005
13006 lck_mtx_lock(&cpu_lock);
13007 lck_mtx_lock(&dtrace_lock);
13008
13009 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13010 rval = EBUSY;
13011 goto out;
13012 }
13013
13014 /*
13015 * Before we can perform any checks, we must prime all of the
13016 * retained enablings that correspond to this state.
13017 */
13018 dtrace_enabling_prime(state);
13019
13020 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13021 rval = EACCES;
13022 goto out;
13023 }
13024
13025 dtrace_state_prereserve(state);
13026
13027 /*
13028 * Now we want to do is try to allocate our speculations.
13029 * We do not automatically resize the number of speculations; if
13030 * this fails, we will fail the operation.
13031 */
13032 nspec = opt[DTRACEOPT_NSPEC];
13033 ASSERT(nspec != DTRACEOPT_UNSET);
13034
13035 if (nspec > INT_MAX) {
13036 rval = ENOMEM;
13037 goto out;
13038 }
13039
13040 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
13041
13042 if (spec == NULL) {
13043 rval = ENOMEM;
13044 goto out;
13045 }
13046
13047 state->dts_speculations = spec;
13048 state->dts_nspeculations = (int)nspec;
13049
13050 for (i = 0; i < nspec; i++) {
13051 if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
13052 rval = ENOMEM;
13053 goto err;
13054 }
13055
13056 spec[i].dtsp_buffer = buf;
13057 }
13058
13059 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13060 if (dtrace_anon.dta_state == NULL) {
13061 rval = ENOENT;
13062 goto out;
13063 }
13064
13065 if (state->dts_necbs != 0) {
13066 rval = EALREADY;
13067 goto out;
13068 }
13069
13070 state->dts_anon = dtrace_anon_grab();
13071 ASSERT(state->dts_anon != NULL);
13072 state = state->dts_anon;
13073
13074 /*
13075 * We want "grabanon" to be set in the grabbed state, so we'll
13076 * copy that option value from the grabbing state into the
13077 * grabbed state.
13078 */
13079 state->dts_options[DTRACEOPT_GRABANON] =
13080 opt[DTRACEOPT_GRABANON];
13081
13082 *cpu = dtrace_anon.dta_beganon;
13083
13084 /*
13085 * If the anonymous state is active (as it almost certainly
13086 * is if the anonymous enabling ultimately matched anything),
13087 * we don't allow any further option processing -- but we
13088 * don't return failure.
13089 */
13090 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13091 goto out;
13092 }
13093
13094 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13095 opt[DTRACEOPT_AGGSIZE] != 0) {
13096 if (state->dts_aggregations == NULL) {
13097 /*
13098 * We're not going to create an aggregation buffer
13099 * because we don't have any ECBs that contain
13100 * aggregations -- set this option to 0.
13101 */
13102 opt[DTRACEOPT_AGGSIZE] = 0;
13103 } else {
13104 /*
13105 * If we have an aggregation buffer, we must also have
13106 * a buffer to use as scratch.
13107 */
13108 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13109 (size_t)opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13110 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13111 }
13112 }
13113 }
13114
13115 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13116 opt[DTRACEOPT_SPECSIZE] != 0) {
13117 if (!state->dts_speculates) {
13118 /*
13119 * We're not going to create speculation buffers
13120 * because we don't have any ECBs that actually
13121 * speculate -- set the speculation size to 0.
13122 */
13123 opt[DTRACEOPT_SPECSIZE] = 0;
13124 }
13125 }
13126
13127 /*
13128 * The bare minimum size for any buffer that we're actually going to
13129 * do anything to is sizeof (uint64_t).
13130 */
13131 sz = sizeof (uint64_t);
13132
13133 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13134 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13135 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13136 /*
13137 * A buffer size has been explicitly set to 0 (or to a size
13138 * that will be adjusted to 0) and we need the space -- we
13139 * need to return failure. We return ENOSPC to differentiate
13140 * it from failing to allocate a buffer due to failure to meet
13141 * the reserve (for which we return E2BIG).
13142 */
13143 rval = ENOSPC;
13144 goto out;
13145 }
13146
13147 if ((rval = dtrace_state_buffers(state)) != 0)
13148 goto err;
13149
13150 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13151 sz = dtrace_dstate_defsize;
13152
13153 do {
13154 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13155
13156 if (rval == 0)
13157 break;
13158
13159 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13160 goto err;
13161 } while (sz >>= 1);
13162
13163 opt[DTRACEOPT_DYNVARSIZE] = sz;
13164
13165 if (rval != 0)
13166 goto err;
13167
13168 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13169 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13170
13171 if (opt[DTRACEOPT_CLEANRATE] == 0)
13172 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13173
13174 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13175 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13176
13177 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13178 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13179
13180 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13181 hdlr.cyh_arg = state;
13182 hdlr.cyh_level = CY_LOW_LEVEL;
13183
13184 when.cyt_when = 0;
13185 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13186
13187 state->dts_cleaner = cyclic_add(&hdlr, &when);
13188
13189 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13190 hdlr.cyh_arg = state;
13191 hdlr.cyh_level = CY_LOW_LEVEL;
13192
13193 when.cyt_when = 0;
13194 when.cyt_interval = dtrace_deadman_interval;
13195
13196 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13197 state->dts_deadman = cyclic_add(&hdlr, &when);
13198
13199 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13200
13201 /*
13202 * Now it's time to actually fire the BEGIN probe. We need to disable
13203 * interrupts here both to record the CPU on which we fired the BEGIN
13204 * probe (the data from this CPU will be processed first at user
13205 * level) and to manually activate the buffer for this CPU.
13206 */
13207 cookie = dtrace_interrupt_disable();
13208 *cpu = CPU->cpu_id;
13209 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13210 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13211
13212 dtrace_probe(dtrace_probeid_begin,
13213 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13214 dtrace_interrupt_enable(cookie);
13215 /*
13216 * We may have had an exit action from a BEGIN probe; only change our
13217 * state to ACTIVE if we're still in WARMUP.
13218 */
13219 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13220 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13221
13222 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13223 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13224
13225 /*
13226 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13227 * want each CPU to transition its principal buffer out of the
13228 * INACTIVE state. Doing this assures that no CPU will suddenly begin
13229 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13230 * atomically transition from processing none of a state's ECBs to
13231 * processing all of them.
13232 */
13233 dtrace_xcall(DTRACE_CPUALL,
13234 (dtrace_xcall_t)dtrace_buffer_activate, state);
13235 goto out;
13236
13237 err:
13238 dtrace_buffer_free(state->dts_buffer);
13239 dtrace_buffer_free(state->dts_aggbuffer);
13240
13241 if ((nspec = state->dts_nspeculations) == 0) {
13242 ASSERT(state->dts_speculations == NULL);
13243 goto out;
13244 }
13245
13246 spec = state->dts_speculations;
13247 ASSERT(spec != NULL);
13248
13249 for (i = 0; i < state->dts_nspeculations; i++) {
13250 if ((buf = spec[i].dtsp_buffer) == NULL)
13251 break;
13252
13253 dtrace_buffer_free(buf);
13254 kmem_free(buf, bufsize);
13255 }
13256
13257 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13258 state->dts_nspeculations = 0;
13259 state->dts_speculations = NULL;
13260
13261 out:
13262 lck_mtx_unlock(&dtrace_lock);
13263 lck_mtx_unlock(&cpu_lock);
13264
13265 return (rval);
13266 }
13267
13268 static int
13269 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13270 {
13271 dtrace_icookie_t cookie;
13272
13273 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13274
13275 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13276 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13277 return (EINVAL);
13278
13279 /*
13280 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13281 * to be sure that every CPU has seen it. See below for the details
13282 * on why this is done.
13283 */
13284 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13285 dtrace_sync();
13286
13287 /*
13288 * By this point, it is impossible for any CPU to be still processing
13289 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
13290 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13291 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
13292 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13293 * iff we're in the END probe.
13294 */
13295 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13296 dtrace_sync();
13297 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13298
13299 /*
13300 * Finally, we can release the reserve and call the END probe. We
13301 * disable interrupts across calling the END probe to allow us to
13302 * return the CPU on which we actually called the END probe. This
13303 * allows user-land to be sure that this CPU's principal buffer is
13304 * processed last.
13305 */
13306 state->dts_reserve = 0;
13307
13308 cookie = dtrace_interrupt_disable();
13309 *cpu = CPU->cpu_id;
13310 dtrace_probe(dtrace_probeid_end,
13311 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13312 dtrace_interrupt_enable(cookie);
13313
13314 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13315 dtrace_sync();
13316
13317 return (0);
13318 }
13319
13320 static int
13321 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13322 dtrace_optval_t val)
13323 {
13324 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13325
13326 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13327 return (EBUSY);
13328
13329 if (option >= DTRACEOPT_MAX)
13330 return (EINVAL);
13331
13332 if (option != DTRACEOPT_CPU && val < 0)
13333 return (EINVAL);
13334
13335 switch (option) {
13336 case DTRACEOPT_DESTRUCTIVE:
13337 /*
13338 * Prevent consumers from enabling destructive actions if DTrace
13339 * is running in a restricted environment, or if actions are
13340 * disallowed.
13341 */
13342 if (dtrace_is_restricted() || dtrace_destructive_disallow)
13343 return (EACCES);
13344
13345 state->dts_cred.dcr_destructive = 1;
13346 break;
13347
13348 case DTRACEOPT_BUFSIZE:
13349 case DTRACEOPT_DYNVARSIZE:
13350 case DTRACEOPT_AGGSIZE:
13351 case DTRACEOPT_SPECSIZE:
13352 case DTRACEOPT_STRSIZE:
13353 if (val < 0)
13354 return (EINVAL);
13355
13356 if (val >= LONG_MAX) {
13357 /*
13358 * If this is an otherwise negative value, set it to
13359 * the highest multiple of 128m less than LONG_MAX.
13360 * Technically, we're adjusting the size without
13361 * regard to the buffer resizing policy, but in fact,
13362 * this has no effect -- if we set the buffer size to
13363 * ~LONG_MAX and the buffer policy is ultimately set to
13364 * be "manual", the buffer allocation is guaranteed to
13365 * fail, if only because the allocation requires two
13366 * buffers. (We set the the size to the highest
13367 * multiple of 128m because it ensures that the size
13368 * will remain a multiple of a megabyte when
13369 * repeatedly halved -- all the way down to 15m.)
13370 */
13371 val = LONG_MAX - (1 << 27) + 1;
13372 }
13373 }
13374
13375 state->dts_options[option] = val;
13376
13377 return (0);
13378 }
13379
13380 static void
13381 dtrace_state_destroy(dtrace_state_t *state)
13382 {
13383 dtrace_ecb_t *ecb;
13384 dtrace_vstate_t *vstate = &state->dts_vstate;
13385 minor_t minor = getminor(state->dts_dev);
13386 int i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
13387 dtrace_speculation_t *spec = state->dts_speculations;
13388 int nspec = state->dts_nspeculations;
13389 uint32_t match;
13390
13391 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13392 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13393
13394 /*
13395 * First, retract any retained enablings for this state.
13396 */
13397 dtrace_enabling_retract(state);
13398 ASSERT(state->dts_nretained == 0);
13399
13400 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13401 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13402 /*
13403 * We have managed to come into dtrace_state_destroy() on a
13404 * hot enabling -- almost certainly because of a disorderly
13405 * shutdown of a consumer. (That is, a consumer that is
13406 * exiting without having called dtrace_stop().) In this case,
13407 * we're going to set our activity to be KILLED, and then
13408 * issue a sync to be sure that everyone is out of probe
13409 * context before we start blowing away ECBs.
13410 */
13411 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13412 dtrace_sync();
13413 }
13414
13415 /*
13416 * Release the credential hold we took in dtrace_state_create().
13417 */
13418 if (state->dts_cred.dcr_cred != NULL)
13419 crfree(state->dts_cred.dcr_cred);
13420
13421 /*
13422 * Now we can safely disable and destroy any enabled probes. Because
13423 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13424 * (especially if they're all enabled), we take two passes through the
13425 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13426 * in the second we disable whatever is left over.
13427 */
13428 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13429 for (i = 0; i < state->dts_necbs; i++) {
13430 if ((ecb = state->dts_ecbs[i]) == NULL)
13431 continue;
13432
13433 if (match && ecb->dte_probe != NULL) {
13434 dtrace_probe_t *probe = ecb->dte_probe;
13435 dtrace_provider_t *prov = probe->dtpr_provider;
13436
13437 if (!(prov->dtpv_priv.dtpp_flags & match))
13438 continue;
13439 }
13440
13441 dtrace_ecb_disable(ecb);
13442 dtrace_ecb_destroy(ecb);
13443 }
13444
13445 if (!match)
13446 break;
13447 }
13448
13449 /*
13450 * Before we free the buffers, perform one more sync to assure that
13451 * every CPU is out of probe context.
13452 */
13453 dtrace_sync();
13454
13455 dtrace_buffer_free(state->dts_buffer);
13456 dtrace_buffer_free(state->dts_aggbuffer);
13457
13458 for (i = 0; i < nspec; i++)
13459 dtrace_buffer_free(spec[i].dtsp_buffer);
13460
13461 if (state->dts_cleaner != CYCLIC_NONE)
13462 cyclic_remove(state->dts_cleaner);
13463
13464 if (state->dts_deadman != CYCLIC_NONE)
13465 cyclic_remove(state->dts_deadman);
13466
13467 dtrace_dstate_fini(&vstate->dtvs_dynvars);
13468 dtrace_vstate_fini(vstate);
13469 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13470
13471 if (state->dts_aggregations != NULL) {
13472 #if DEBUG
13473 for (i = 0; i < state->dts_naggregations; i++)
13474 ASSERT(state->dts_aggregations[i] == NULL);
13475 #endif
13476 ASSERT(state->dts_naggregations > 0);
13477 kmem_free(state->dts_aggregations,
13478 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13479 }
13480
13481 kmem_free(state->dts_buffer, bufsize);
13482 kmem_free(state->dts_aggbuffer, bufsize);
13483
13484 for (i = 0; i < nspec; i++)
13485 kmem_free(spec[i].dtsp_buffer, bufsize);
13486
13487 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13488
13489 dtrace_format_destroy(state);
13490
13491 vmem_destroy(state->dts_aggid_arena);
13492 ddi_soft_state_free(dtrace_softstate, minor);
13493 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13494 }
13495
13496 /*
13497 * DTrace Anonymous Enabling Functions
13498 */
13499 static dtrace_state_t *
13500 dtrace_anon_grab(void)
13501 {
13502 dtrace_state_t *state;
13503
13504 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13505
13506 if ((state = dtrace_anon.dta_state) == NULL) {
13507 ASSERT(dtrace_anon.dta_enabling == NULL);
13508 return (NULL);
13509 }
13510
13511 ASSERT(dtrace_anon.dta_enabling != NULL);
13512 ASSERT(dtrace_retained != NULL);
13513
13514 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
13515 dtrace_anon.dta_enabling = NULL;
13516 dtrace_anon.dta_state = NULL;
13517
13518 return (state);
13519 }
13520
13521 static void
13522 dtrace_anon_property(void)
13523 {
13524 int i, rv;
13525 dtrace_state_t *state;
13526 dof_hdr_t *dof;
13527 char c[32]; /* enough for "dof-data-" + digits */
13528
13529 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13530 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13531
13532 for (i = 0; ; i++) {
13533 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
13534
13535 dtrace_err_verbose = 1;
13536
13537 if ((dof = dtrace_dof_property(c)) == NULL) {
13538 dtrace_err_verbose = 0;
13539 break;
13540 }
13541
13542 /*
13543 * We want to create anonymous state, so we need to transition
13544 * the kernel debugger to indicate that DTrace is active. If
13545 * this fails (e.g. because the debugger has modified text in
13546 * some way), we won't continue with the processing.
13547 */
13548 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13549 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
13550 "enabling ignored.");
13551 dtrace_dof_destroy(dof);
13552 break;
13553 }
13554
13555 /*
13556 * If we haven't allocated an anonymous state, we'll do so now.
13557 */
13558 if ((state = dtrace_anon.dta_state) == NULL) {
13559 rv = dtrace_state_create(NULL, NULL, &state);
13560 dtrace_anon.dta_state = state;
13561 if (rv != 0 || state == NULL) {
13562 /*
13563 * This basically shouldn't happen: the only
13564 * failure mode from dtrace_state_create() is a
13565 * failure of ddi_soft_state_zalloc() that
13566 * itself should never happen. Still, the
13567 * interface allows for a failure mode, and
13568 * we want to fail as gracefully as possible:
13569 * we'll emit an error message and cease
13570 * processing anonymous state in this case.
13571 */
13572 cmn_err(CE_WARN, "failed to create "
13573 "anonymous state");
13574 dtrace_dof_destroy(dof);
13575 break;
13576 }
13577 }
13578
13579 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
13580 &dtrace_anon.dta_enabling, 0, B_TRUE);
13581
13582 if (rv == 0)
13583 rv = dtrace_dof_options(dof, state);
13584
13585 dtrace_err_verbose = 0;
13586 dtrace_dof_destroy(dof);
13587
13588 if (rv != 0) {
13589 /*
13590 * This is malformed DOF; chuck any anonymous state
13591 * that we created.
13592 */
13593 ASSERT(dtrace_anon.dta_enabling == NULL);
13594 dtrace_state_destroy(state);
13595 dtrace_anon.dta_state = NULL;
13596 break;
13597 }
13598
13599 ASSERT(dtrace_anon.dta_enabling != NULL);
13600 }
13601
13602 if (dtrace_anon.dta_enabling != NULL) {
13603 int rval;
13604
13605 /*
13606 * dtrace_enabling_retain() can only fail because we are
13607 * trying to retain more enablings than are allowed -- but
13608 * we only have one anonymous enabling, and we are guaranteed
13609 * to be allowed at least one retained enabling; we assert
13610 * that dtrace_enabling_retain() returns success.
13611 */
13612 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
13613 ASSERT(rval == 0);
13614
13615 dtrace_enabling_dump(dtrace_anon.dta_enabling);
13616 }
13617 }
13618
13619 /*
13620 * DTrace Helper Functions
13621 */
13622 static void
13623 dtrace_helper_trace(dtrace_helper_action_t *helper,
13624 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
13625 {
13626 uint32_t size, next, nnext;
13627 int i;
13628 dtrace_helptrace_t *ent;
13629 uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13630
13631 if (!dtrace_helptrace_enabled)
13632 return;
13633
13634 ASSERT((uint32_t)vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
13635
13636 /*
13637 * What would a tracing framework be without its own tracing
13638 * framework? (Well, a hell of a lot simpler, for starters...)
13639 */
13640 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
13641 sizeof (uint64_t) - sizeof (uint64_t);
13642
13643 /*
13644 * Iterate until we can allocate a slot in the trace buffer.
13645 */
13646 do {
13647 next = dtrace_helptrace_next;
13648
13649 if (next + size < dtrace_helptrace_bufsize) {
13650 nnext = next + size;
13651 } else {
13652 nnext = size;
13653 }
13654 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
13655
13656 /*
13657 * We have our slot; fill it in.
13658 */
13659 if (nnext == size)
13660 next = 0;
13661
13662 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
13663 ent->dtht_helper = helper;
13664 ent->dtht_where = where;
13665 ent->dtht_nlocals = vstate->dtvs_nlocals;
13666
13667 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
13668 mstate->dtms_fltoffs : -1;
13669 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
13670 ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
13671
13672 for (i = 0; i < vstate->dtvs_nlocals; i++) {
13673 dtrace_statvar_t *svar;
13674
13675 if ((svar = vstate->dtvs_locals[i]) == NULL)
13676 continue;
13677
13678 ASSERT(svar->dtsv_size >= (int)NCPU * sizeof (uint64_t));
13679 ent->dtht_locals[i] =
13680 ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
13681 }
13682 }
13683
13684 static uint64_t
13685 dtrace_helper(int which, dtrace_mstate_t *mstate,
13686 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
13687 {
13688 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13689 uint64_t sarg0 = mstate->dtms_arg[0];
13690 uint64_t sarg1 = mstate->dtms_arg[1];
13691 uint64_t rval = 0;
13692 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
13693 dtrace_helper_action_t *helper;
13694 dtrace_vstate_t *vstate;
13695 dtrace_difo_t *pred;
13696 int i, trace = dtrace_helptrace_enabled;
13697
13698 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
13699
13700 if (helpers == NULL)
13701 return (0);
13702
13703 if ((helper = helpers->dthps_actions[which]) == NULL)
13704 return (0);
13705
13706 vstate = &helpers->dthps_vstate;
13707 mstate->dtms_arg[0] = arg0;
13708 mstate->dtms_arg[1] = arg1;
13709
13710 /*
13711 * Now iterate over each helper. If its predicate evaluates to 'true',
13712 * we'll call the corresponding actions. Note that the below calls
13713 * to dtrace_dif_emulate() may set faults in machine state. This is
13714 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
13715 * the stored DIF offset with its own (which is the desired behavior).
13716 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
13717 * from machine state; this is okay, too.
13718 */
13719 for (; helper != NULL; helper = helper->dtha_next) {
13720 if ((pred = helper->dtha_predicate) != NULL) {
13721 if (trace)
13722 dtrace_helper_trace(helper, mstate, vstate, 0);
13723
13724 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
13725 goto next;
13726
13727 if (*flags & CPU_DTRACE_FAULT)
13728 goto err;
13729 }
13730
13731 for (i = 0; i < helper->dtha_nactions; i++) {
13732 if (trace)
13733 dtrace_helper_trace(helper,
13734 mstate, vstate, i + 1);
13735
13736 rval = dtrace_dif_emulate(helper->dtha_actions[i],
13737 mstate, vstate, state);
13738
13739 if (*flags & CPU_DTRACE_FAULT)
13740 goto err;
13741 }
13742
13743 next:
13744 if (trace)
13745 dtrace_helper_trace(helper, mstate, vstate,
13746 DTRACE_HELPTRACE_NEXT);
13747 }
13748
13749 if (trace)
13750 dtrace_helper_trace(helper, mstate, vstate,
13751 DTRACE_HELPTRACE_DONE);
13752
13753 /*
13754 * Restore the arg0 that we saved upon entry.
13755 */
13756 mstate->dtms_arg[0] = sarg0;
13757 mstate->dtms_arg[1] = sarg1;
13758
13759 return (rval);
13760
13761 err:
13762 if (trace)
13763 dtrace_helper_trace(helper, mstate, vstate,
13764 DTRACE_HELPTRACE_ERR);
13765
13766 /*
13767 * Restore the arg0 that we saved upon entry.
13768 */
13769 mstate->dtms_arg[0] = sarg0;
13770 mstate->dtms_arg[1] = sarg1;
13771
13772 return (0);
13773 }
13774
13775 static void
13776 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13777 dtrace_vstate_t *vstate)
13778 {
13779 int i;
13780
13781 if (helper->dtha_predicate != NULL)
13782 dtrace_difo_release(helper->dtha_predicate, vstate);
13783
13784 for (i = 0; i < helper->dtha_nactions; i++) {
13785 ASSERT(helper->dtha_actions[i] != NULL);
13786 dtrace_difo_release(helper->dtha_actions[i], vstate);
13787 }
13788
13789 kmem_free(helper->dtha_actions,
13790 helper->dtha_nactions * sizeof (dtrace_difo_t *));
13791 kmem_free(helper, sizeof (dtrace_helper_action_t));
13792 }
13793
13794 static int
13795 dtrace_helper_destroygen(proc_t* p, int gen)
13796 {
13797 dtrace_helpers_t *help = p->p_dtrace_helpers;
13798 dtrace_vstate_t *vstate;
13799 uint_t i;
13800
13801 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13802
13803 if (help == NULL || gen > help->dthps_generation)
13804 return (EINVAL);
13805
13806 vstate = &help->dthps_vstate;
13807
13808 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13809 dtrace_helper_action_t *last = NULL, *h, *next;
13810
13811 for (h = help->dthps_actions[i]; h != NULL; h = next) {
13812 next = h->dtha_next;
13813
13814 if (h->dtha_generation == gen) {
13815 if (last != NULL) {
13816 last->dtha_next = next;
13817 } else {
13818 help->dthps_actions[i] = next;
13819 }
13820
13821 dtrace_helper_action_destroy(h, vstate);
13822 } else {
13823 last = h;
13824 }
13825 }
13826 }
13827
13828 /*
13829 * Interate until we've cleared out all helper providers with the
13830 * given generation number.
13831 */
13832 for (;;) {
13833 dtrace_helper_provider_t *prov = NULL;
13834
13835 /*
13836 * Look for a helper provider with the right generation. We
13837 * have to start back at the beginning of the list each time
13838 * because we drop dtrace_lock. It's unlikely that we'll make
13839 * more than two passes.
13840 */
13841 for (i = 0; i < help->dthps_nprovs; i++) {
13842 prov = help->dthps_provs[i];
13843
13844 if (prov->dthp_generation == gen)
13845 break;
13846 }
13847
13848 /*
13849 * If there were no matches, we're done.
13850 */
13851 if (i == help->dthps_nprovs)
13852 break;
13853
13854 /*
13855 * Move the last helper provider into this slot.
13856 */
13857 help->dthps_nprovs--;
13858 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13859 help->dthps_provs[help->dthps_nprovs] = NULL;
13860
13861 lck_mtx_unlock(&dtrace_lock);
13862
13863 /*
13864 * If we have a meta provider, remove this helper provider.
13865 */
13866 lck_mtx_lock(&dtrace_meta_lock);
13867 if (dtrace_meta_pid != NULL) {
13868 ASSERT(dtrace_deferred_pid == NULL);
13869 dtrace_helper_provider_remove(&prov->dthp_prov,
13870 p->p_pid);
13871 }
13872 lck_mtx_unlock(&dtrace_meta_lock);
13873
13874 dtrace_helper_provider_destroy(prov);
13875
13876 lck_mtx_lock(&dtrace_lock);
13877 }
13878
13879 return (0);
13880 }
13881
13882 static int
13883 dtrace_helper_validate(dtrace_helper_action_t *helper)
13884 {
13885 int err = 0, i;
13886 dtrace_difo_t *dp;
13887
13888 if ((dp = helper->dtha_predicate) != NULL)
13889 err += dtrace_difo_validate_helper(dp);
13890
13891 for (i = 0; i < helper->dtha_nactions; i++)
13892 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13893
13894 return (err == 0);
13895 }
13896
13897 static int
13898 dtrace_helper_action_add(proc_t* p, int which, dtrace_ecbdesc_t *ep)
13899 {
13900 dtrace_helpers_t *help;
13901 dtrace_helper_action_t *helper, *last;
13902 dtrace_actdesc_t *act;
13903 dtrace_vstate_t *vstate;
13904 dtrace_predicate_t *pred;
13905 int count = 0, nactions = 0, i;
13906
13907 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13908 return (EINVAL);
13909
13910 help = p->p_dtrace_helpers;
13911 last = help->dthps_actions[which];
13912 vstate = &help->dthps_vstate;
13913
13914 for (count = 0; last != NULL; last = last->dtha_next) {
13915 count++;
13916 if (last->dtha_next == NULL)
13917 break;
13918 }
13919
13920 /*
13921 * If we already have dtrace_helper_actions_max helper actions for this
13922 * helper action type, we'll refuse to add a new one.
13923 */
13924 if (count >= dtrace_helper_actions_max)
13925 return (ENOSPC);
13926
13927 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13928 helper->dtha_generation = help->dthps_generation;
13929
13930 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13931 ASSERT(pred->dtp_difo != NULL);
13932 dtrace_difo_hold(pred->dtp_difo);
13933 helper->dtha_predicate = pred->dtp_difo;
13934 }
13935
13936 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13937 if (act->dtad_kind != DTRACEACT_DIFEXPR)
13938 goto err;
13939
13940 if (act->dtad_difo == NULL)
13941 goto err;
13942
13943 nactions++;
13944 }
13945
13946 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13947 (helper->dtha_nactions = nactions), KM_SLEEP);
13948
13949 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13950 dtrace_difo_hold(act->dtad_difo);
13951 helper->dtha_actions[i++] = act->dtad_difo;
13952 }
13953
13954 if (!dtrace_helper_validate(helper))
13955 goto err;
13956
13957 if (last == NULL) {
13958 help->dthps_actions[which] = helper;
13959 } else {
13960 last->dtha_next = helper;
13961 }
13962
13963 if ((uint32_t)vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
13964 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13965 dtrace_helptrace_next = 0;
13966 }
13967
13968 return (0);
13969 err:
13970 dtrace_helper_action_destroy(helper, vstate);
13971 return (EINVAL);
13972 }
13973
13974 static void
13975 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13976 dof_helper_t *dofhp)
13977 {
13978 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
13979
13980 lck_mtx_lock(&dtrace_meta_lock);
13981 lck_mtx_lock(&dtrace_lock);
13982
13983 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13984 /*
13985 * If the dtrace module is loaded but not attached, or if
13986 * there aren't isn't a meta provider registered to deal with
13987 * these provider descriptions, we need to postpone creating
13988 * the actual providers until later.
13989 */
13990
13991 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13992 dtrace_deferred_pid != help) {
13993 help->dthps_deferred = 1;
13994 help->dthps_pid = p->p_pid;
13995 help->dthps_next = dtrace_deferred_pid;
13996 help->dthps_prev = NULL;
13997 if (dtrace_deferred_pid != NULL)
13998 dtrace_deferred_pid->dthps_prev = help;
13999 dtrace_deferred_pid = help;
14000 }
14001
14002 lck_mtx_unlock(&dtrace_lock);
14003
14004 } else if (dofhp != NULL) {
14005 /*
14006 * If the dtrace module is loaded and we have a particular
14007 * helper provider description, pass that off to the
14008 * meta provider.
14009 */
14010
14011 lck_mtx_unlock(&dtrace_lock);
14012
14013 dtrace_helper_provide(dofhp, p->p_pid);
14014
14015 } else {
14016 /*
14017 * Otherwise, just pass all the helper provider descriptions
14018 * off to the meta provider.
14019 */
14020
14021 uint_t i;
14022 lck_mtx_unlock(&dtrace_lock);
14023
14024 for (i = 0; i < help->dthps_nprovs; i++) {
14025 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14026 p->p_pid);
14027 }
14028 }
14029
14030 lck_mtx_unlock(&dtrace_meta_lock);
14031 }
14032
14033 static int
14034 dtrace_helper_provider_add(proc_t* p, dof_helper_t *dofhp, int gen)
14035 {
14036 dtrace_helpers_t *help;
14037 dtrace_helper_provider_t *hprov, **tmp_provs;
14038 uint_t tmp_maxprovs, i;
14039
14040 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14041 help = p->p_dtrace_helpers;
14042 ASSERT(help != NULL);
14043
14044 /*
14045 * If we already have dtrace_helper_providers_max helper providers,
14046 * we're refuse to add a new one.
14047 */
14048 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14049 return (ENOSPC);
14050
14051 /*
14052 * Check to make sure this isn't a duplicate.
14053 */
14054 for (i = 0; i < help->dthps_nprovs; i++) {
14055 if (dofhp->dofhp_addr ==
14056 help->dthps_provs[i]->dthp_prov.dofhp_addr)
14057 return (EALREADY);
14058 }
14059
14060 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14061 hprov->dthp_prov = *dofhp;
14062 hprov->dthp_ref = 1;
14063 hprov->dthp_generation = gen;
14064
14065 /*
14066 * Allocate a bigger table for helper providers if it's already full.
14067 */
14068 if (help->dthps_maxprovs == help->dthps_nprovs) {
14069 tmp_maxprovs = help->dthps_maxprovs;
14070 tmp_provs = help->dthps_provs;
14071
14072 if (help->dthps_maxprovs == 0)
14073 help->dthps_maxprovs = 2;
14074 else
14075 help->dthps_maxprovs *= 2;
14076 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14077 help->dthps_maxprovs = dtrace_helper_providers_max;
14078
14079 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14080
14081 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14082 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14083
14084 if (tmp_provs != NULL) {
14085 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14086 sizeof (dtrace_helper_provider_t *));
14087 kmem_free(tmp_provs, tmp_maxprovs *
14088 sizeof (dtrace_helper_provider_t *));
14089 }
14090 }
14091
14092 help->dthps_provs[help->dthps_nprovs] = hprov;
14093 help->dthps_nprovs++;
14094
14095 return (0);
14096 }
14097
14098 static void
14099 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14100 {
14101 lck_mtx_lock(&dtrace_lock);
14102
14103 if (--hprov->dthp_ref == 0) {
14104 dof_hdr_t *dof;
14105 lck_mtx_unlock(&dtrace_lock);
14106 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14107 dtrace_dof_destroy(dof);
14108 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14109 } else {
14110 lck_mtx_unlock(&dtrace_lock);
14111 }
14112 }
14113
14114 static int
14115 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14116 {
14117 uintptr_t daddr = (uintptr_t)dof;
14118 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14119 dof_provider_t *provider;
14120 dof_probe_t *probe;
14121 uint8_t *arg;
14122 char *strtab, *typestr;
14123 dof_stridx_t typeidx;
14124 size_t typesz;
14125 uint_t nprobes, j, k;
14126
14127 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14128
14129 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14130 dtrace_dof_error(dof, "misaligned section offset");
14131 return (-1);
14132 }
14133
14134 /*
14135 * The section needs to be large enough to contain the DOF provider
14136 * structure appropriate for the given version.
14137 */
14138 if (sec->dofs_size <
14139 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14140 offsetof(dof_provider_t, dofpv_prenoffs) :
14141 sizeof (dof_provider_t))) {
14142 dtrace_dof_error(dof, "provider section too small");
14143 return (-1);
14144 }
14145
14146 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14147 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14148 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14149 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14150 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14151
14152 if (str_sec == NULL || prb_sec == NULL ||
14153 arg_sec == NULL || off_sec == NULL)
14154 return (-1);
14155
14156 enoff_sec = NULL;
14157
14158 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14159 provider->dofpv_prenoffs != DOF_SECT_NONE &&
14160 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14161 provider->dofpv_prenoffs)) == NULL)
14162 return (-1);
14163
14164 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14165
14166 if (provider->dofpv_name >= str_sec->dofs_size ||
14167 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14168 dtrace_dof_error(dof, "invalid provider name");
14169 return (-1);
14170 }
14171
14172 if (prb_sec->dofs_entsize == 0 ||
14173 prb_sec->dofs_entsize > prb_sec->dofs_size) {
14174 dtrace_dof_error(dof, "invalid entry size");
14175 return (-1);
14176 }
14177
14178 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14179 dtrace_dof_error(dof, "misaligned entry size");
14180 return (-1);
14181 }
14182
14183 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14184 dtrace_dof_error(dof, "invalid entry size");
14185 return (-1);
14186 }
14187
14188 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14189 dtrace_dof_error(dof, "misaligned section offset");
14190 return (-1);
14191 }
14192
14193 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14194 dtrace_dof_error(dof, "invalid entry size");
14195 return (-1);
14196 }
14197
14198 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14199
14200 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14201
14202 /*
14203 * Take a pass through the probes to check for errors.
14204 */
14205 for (j = 0; j < nprobes; j++) {
14206 probe = (dof_probe_t *)(uintptr_t)(daddr +
14207 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14208
14209 if (probe->dofpr_func >= str_sec->dofs_size) {
14210 dtrace_dof_error(dof, "invalid function name");
14211 return (-1);
14212 }
14213
14214 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14215 dtrace_dof_error(dof, "function name too long");
14216 return (-1);
14217 }
14218
14219 if (probe->dofpr_name >= str_sec->dofs_size ||
14220 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14221 dtrace_dof_error(dof, "invalid probe name");
14222 return (-1);
14223 }
14224
14225 /*
14226 * The offset count must not wrap the index, and the offsets
14227 * must also not overflow the section's data.
14228 */
14229 if (probe->dofpr_offidx + probe->dofpr_noffs <
14230 probe->dofpr_offidx ||
14231 (probe->dofpr_offidx + probe->dofpr_noffs) *
14232 off_sec->dofs_entsize > off_sec->dofs_size) {
14233 dtrace_dof_error(dof, "invalid probe offset");
14234 return (-1);
14235 }
14236
14237 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14238 /*
14239 * If there's no is-enabled offset section, make sure
14240 * there aren't any is-enabled offsets. Otherwise
14241 * perform the same checks as for probe offsets
14242 * (immediately above).
14243 */
14244 if (enoff_sec == NULL) {
14245 if (probe->dofpr_enoffidx != 0 ||
14246 probe->dofpr_nenoffs != 0) {
14247 dtrace_dof_error(dof, "is-enabled "
14248 "offsets with null section");
14249 return (-1);
14250 }
14251 } else if (probe->dofpr_enoffidx +
14252 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14253 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14254 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14255 dtrace_dof_error(dof, "invalid is-enabled "
14256 "offset");
14257 return (-1);
14258 }
14259
14260 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14261 dtrace_dof_error(dof, "zero probe and "
14262 "is-enabled offsets");
14263 return (-1);
14264 }
14265 } else if (probe->dofpr_noffs == 0) {
14266 dtrace_dof_error(dof, "zero probe offsets");
14267 return (-1);
14268 }
14269
14270 if (probe->dofpr_argidx + probe->dofpr_xargc <
14271 probe->dofpr_argidx ||
14272 (probe->dofpr_argidx + probe->dofpr_xargc) *
14273 arg_sec->dofs_entsize > arg_sec->dofs_size) {
14274 dtrace_dof_error(dof, "invalid args");
14275 return (-1);
14276 }
14277
14278 typeidx = probe->dofpr_nargv;
14279 typestr = strtab + probe->dofpr_nargv;
14280 for (k = 0; k < probe->dofpr_nargc; k++) {
14281 if (typeidx >= str_sec->dofs_size) {
14282 dtrace_dof_error(dof, "bad "
14283 "native argument type");
14284 return (-1);
14285 }
14286
14287 typesz = strlen(typestr) + 1;
14288 if (typesz > DTRACE_ARGTYPELEN) {
14289 dtrace_dof_error(dof, "native "
14290 "argument type too long");
14291 return (-1);
14292 }
14293 typeidx += typesz;
14294 typestr += typesz;
14295 }
14296
14297 typeidx = probe->dofpr_xargv;
14298 typestr = strtab + probe->dofpr_xargv;
14299 for (k = 0; k < probe->dofpr_xargc; k++) {
14300 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14301 dtrace_dof_error(dof, "bad "
14302 "native argument index");
14303 return (-1);
14304 }
14305
14306 if (typeidx >= str_sec->dofs_size) {
14307 dtrace_dof_error(dof, "bad "
14308 "translated argument type");
14309 return (-1);
14310 }
14311
14312 typesz = strlen(typestr) + 1;
14313 if (typesz > DTRACE_ARGTYPELEN) {
14314 dtrace_dof_error(dof, "translated argument "
14315 "type too long");
14316 return (-1);
14317 }
14318
14319 typeidx += typesz;
14320 typestr += typesz;
14321 }
14322 }
14323
14324 return (0);
14325 }
14326
14327 static int
14328 dtrace_helper_slurp(proc_t* p, dof_hdr_t *dof, dof_helper_t *dhp)
14329 {
14330 dtrace_helpers_t *help;
14331 dtrace_vstate_t *vstate;
14332 dtrace_enabling_t *enab = NULL;
14333 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14334 uintptr_t daddr = (uintptr_t)dof;
14335
14336 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14337
14338 if ((help = p->p_dtrace_helpers) == NULL)
14339 help = dtrace_helpers_create(p);
14340
14341 vstate = &help->dthps_vstate;
14342
14343 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14344 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14345 dtrace_dof_destroy(dof);
14346 return (rv);
14347 }
14348
14349 /*
14350 * Look for helper providers and validate their descriptions.
14351 */
14352 if (dhp != NULL) {
14353 for (i = 0; (uint32_t)i < dof->dofh_secnum; i++) {
14354 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14355 dof->dofh_secoff + i * dof->dofh_secsize);
14356
14357 if (sec->dofs_type != DOF_SECT_PROVIDER)
14358 continue;
14359
14360 if (dtrace_helper_provider_validate(dof, sec) != 0) {
14361 dtrace_enabling_destroy(enab);
14362 dtrace_dof_destroy(dof);
14363 return (-1);
14364 }
14365
14366 nprovs++;
14367 }
14368 }
14369
14370 /*
14371 * Now we need to walk through the ECB descriptions in the enabling.
14372 */
14373 for (i = 0; i < enab->dten_ndesc; i++) {
14374 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14375 dtrace_probedesc_t *desc = &ep->dted_probe;
14376
14377 /* APPLE NOTE: Darwin employs size bounded string operation. */
14378 if (!LIT_STRNEQL(desc->dtpd_provider, "dtrace"))
14379 continue;
14380
14381 if (!LIT_STRNEQL(desc->dtpd_mod, "helper"))
14382 continue;
14383
14384 if (!LIT_STRNEQL(desc->dtpd_func, "ustack"))
14385 continue;
14386
14387 if ((rv = dtrace_helper_action_add(p, DTRACE_HELPER_ACTION_USTACK,
14388 ep)) != 0) {
14389 /*
14390 * Adding this helper action failed -- we are now going
14391 * to rip out the entire generation and return failure.
14392 */
14393 (void) dtrace_helper_destroygen(p, help->dthps_generation);
14394 dtrace_enabling_destroy(enab);
14395 dtrace_dof_destroy(dof);
14396 return (-1);
14397 }
14398
14399 nhelpers++;
14400 }
14401
14402 if (nhelpers < enab->dten_ndesc)
14403 dtrace_dof_error(dof, "unmatched helpers");
14404
14405 gen = help->dthps_generation++;
14406 dtrace_enabling_destroy(enab);
14407
14408 if (dhp != NULL && nprovs > 0) {
14409 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14410 if (dtrace_helper_provider_add(p, dhp, gen) == 0) {
14411 lck_mtx_unlock(&dtrace_lock);
14412 dtrace_helper_provider_register(p, help, dhp);
14413 lck_mtx_lock(&dtrace_lock);
14414
14415 destroy = 0;
14416 }
14417 }
14418
14419 if (destroy)
14420 dtrace_dof_destroy(dof);
14421
14422 return (gen);
14423 }
14424
14425 /*
14426 * APPLE NOTE: DTrace lazy dof implementation
14427 *
14428 * DTrace user static probes (USDT probes) and helper actions are loaded
14429 * in a process by proccessing dof sections. The dof sections are passed
14430 * into the kernel by dyld, in a dof_ioctl_data_t block. It is rather
14431 * expensive to process dof for a process that will never use it. There
14432 * is a memory cost (allocating the providers/probes), and a cpu cost
14433 * (creating the providers/probes).
14434 *
14435 * To reduce this cost, we use "lazy dof". The normal proceedure for
14436 * dof processing is to copyin the dof(s) pointed to by the dof_ioctl_data_t
14437 * block, and invoke dof_slurp_helper() on them. When "lazy dof" is
14438 * used, each process retains the dof_ioctl_data_t block, instead of
14439 * copying in the data it points to.
14440 *
14441 * The dof_ioctl_data_t blocks are managed as if they were the actual
14442 * processed dof; on fork the block is copied to the child, on exec and
14443 * exit the block is freed.
14444 *
14445 * If the process loads library(s) containing additional dof, the
14446 * new dof_ioctl_data_t is merged with the existing block.
14447 *
14448 * There are a few catches that make this slightly more difficult.
14449 * When dyld registers dof_ioctl_data_t blocks, it expects a unique
14450 * identifier value for each dof in the block. In non-lazy dof terms,
14451 * this is the generation that dof was loaded in. If we hand back
14452 * a UID for a lazy dof, that same UID must be able to unload the
14453 * dof once it has become non-lazy. To meet this requirement, the
14454 * code that loads lazy dof requires that the UID's for dof(s) in
14455 * the lazy dof be sorted, and in ascending order. It is okay to skip
14456 * UID's, I.E., 1 -> 5 -> 6 is legal.
14457 *
14458 * Once a process has become non-lazy, it will stay non-lazy. All
14459 * future dof operations for that process will be non-lazy, even
14460 * if the dof mode transitions back to lazy.
14461 *
14462 * Always do lazy dof checks before non-lazy (I.E. In fork, exit, exec.).
14463 * That way if the lazy check fails due to transitioning to non-lazy, the
14464 * right thing is done with the newly faulted in dof.
14465 */
14466
14467 /*
14468 * This method is a bit squicky. It must handle:
14469 *
14470 * dof should not be lazy.
14471 * dof should have been handled lazily, but there was an error
14472 * dof was handled lazily, and needs to be freed.
14473 * dof was handled lazily, and must not be freed.
14474 *
14475 *
14476 * Returns EACCESS if dof should be handled non-lazily.
14477 *
14478 * KERN_SUCCESS and all other return codes indicate lazy handling of dof.
14479 *
14480 * If the dofs data is claimed by this method, dofs_claimed will be set.
14481 * Callers should not free claimed dofs.
14482 */
14483 static int
14484 dtrace_lazy_dofs_add(proc_t *p, dof_ioctl_data_t* incoming_dofs, int *dofs_claimed)
14485 {
14486 ASSERT(p);
14487 ASSERT(incoming_dofs && incoming_dofs->dofiod_count > 0);
14488
14489 int rval = 0;
14490 *dofs_claimed = 0;
14491
14492 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14493
14494 /*
14495 * If we have lazy dof, dof mode better be LAZY_ON.
14496 */
14497 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
14498 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14499 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
14500
14501 /*
14502 * Any existing helpers force non-lazy behavior.
14503 */
14504 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
14505 lck_mtx_lock(&p->p_dtrace_sprlock);
14506
14507 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
14508 unsigned int existing_dofs_count = (existing_dofs) ? existing_dofs->dofiod_count : 0;
14509 unsigned int i, merged_dofs_count = incoming_dofs->dofiod_count + existing_dofs_count;
14510
14511 /*
14512 * Range check...
14513 */
14514 if (merged_dofs_count == 0 || merged_dofs_count > 1024) {
14515 dtrace_dof_error(NULL, "lazy_dofs_add merged_dofs_count out of range");
14516 rval = EINVAL;
14517 goto unlock;
14518 }
14519
14520 /*
14521 * Each dof being added must be assigned a unique generation.
14522 */
14523 uint64_t generation = (existing_dofs) ? existing_dofs->dofiod_helpers[existing_dofs_count - 1].dofhp_dof + 1 : 1;
14524 for (i=0; i<incoming_dofs->dofiod_count; i++) {
14525 /*
14526 * We rely on these being the same so we can overwrite dofhp_dof and not lose info.
14527 */
14528 ASSERT(incoming_dofs->dofiod_helpers[i].dofhp_dof == incoming_dofs->dofiod_helpers[i].dofhp_addr);
14529 incoming_dofs->dofiod_helpers[i].dofhp_dof = generation++;
14530 }
14531
14532
14533 if (existing_dofs) {
14534 /*
14535 * Merge the existing and incoming dofs
14536 */
14537 size_t merged_dofs_size = DOF_IOCTL_DATA_T_SIZE(merged_dofs_count);
14538 dof_ioctl_data_t* merged_dofs = kmem_alloc(merged_dofs_size, KM_SLEEP);
14539
14540 bcopy(&existing_dofs->dofiod_helpers[0],
14541 &merged_dofs->dofiod_helpers[0],
14542 sizeof(dof_helper_t) * existing_dofs_count);
14543 bcopy(&incoming_dofs->dofiod_helpers[0],
14544 &merged_dofs->dofiod_helpers[existing_dofs_count],
14545 sizeof(dof_helper_t) * incoming_dofs->dofiod_count);
14546
14547 merged_dofs->dofiod_count = merged_dofs_count;
14548
14549 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
14550
14551 p->p_dtrace_lazy_dofs = merged_dofs;
14552 } else {
14553 /*
14554 * Claim the incoming dofs
14555 */
14556 *dofs_claimed = 1;
14557 p->p_dtrace_lazy_dofs = incoming_dofs;
14558 }
14559
14560 #if DEBUG
14561 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
14562 for (i=0; i<all_dofs->dofiod_count-1; i++) {
14563 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
14564 }
14565 #endif /* DEBUG */
14566
14567 unlock:
14568 lck_mtx_unlock(&p->p_dtrace_sprlock);
14569 } else {
14570 rval = EACCES;
14571 }
14572
14573 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14574
14575 return rval;
14576 }
14577
14578 /*
14579 * Returns:
14580 *
14581 * EINVAL: lazy dof is enabled, but the requested generation was not found.
14582 * EACCES: This removal needs to be handled non-lazily.
14583 */
14584 static int
14585 dtrace_lazy_dofs_remove(proc_t *p, int generation)
14586 {
14587 int rval = EINVAL;
14588
14589 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14590
14591 /*
14592 * If we have lazy dof, dof mode better be LAZY_ON.
14593 */
14594 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
14595 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14596 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
14597
14598 /*
14599 * Any existing helpers force non-lazy behavior.
14600 */
14601 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
14602 lck_mtx_lock(&p->p_dtrace_sprlock);
14603
14604 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
14605
14606 if (existing_dofs) {
14607 int index, existing_dofs_count = existing_dofs->dofiod_count;
14608 for (index=0; index<existing_dofs_count; index++) {
14609 if ((int)existing_dofs->dofiod_helpers[index].dofhp_dof == generation) {
14610 dof_ioctl_data_t* removed_dofs = NULL;
14611
14612 /*
14613 * If there is only 1 dof, we'll delete it and swap in NULL.
14614 */
14615 if (existing_dofs_count > 1) {
14616 int removed_dofs_count = existing_dofs_count - 1;
14617 size_t removed_dofs_size = DOF_IOCTL_DATA_T_SIZE(removed_dofs_count);
14618
14619 removed_dofs = kmem_alloc(removed_dofs_size, KM_SLEEP);
14620 removed_dofs->dofiod_count = removed_dofs_count;
14621
14622 /*
14623 * copy the remaining data.
14624 */
14625 if (index > 0) {
14626 bcopy(&existing_dofs->dofiod_helpers[0],
14627 &removed_dofs->dofiod_helpers[0],
14628 index * sizeof(dof_helper_t));
14629 }
14630
14631 if (index < existing_dofs_count-1) {
14632 bcopy(&existing_dofs->dofiod_helpers[index+1],
14633 &removed_dofs->dofiod_helpers[index],
14634 (existing_dofs_count - index - 1) * sizeof(dof_helper_t));
14635 }
14636 }
14637
14638 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
14639
14640 p->p_dtrace_lazy_dofs = removed_dofs;
14641
14642 rval = KERN_SUCCESS;
14643
14644 break;
14645 }
14646 }
14647
14648 #if DEBUG
14649 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
14650 if (all_dofs) {
14651 unsigned int i;
14652 for (i=0; i<all_dofs->dofiod_count-1; i++) {
14653 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
14654 }
14655 }
14656 #endif
14657
14658 }
14659
14660 lck_mtx_unlock(&p->p_dtrace_sprlock);
14661 } else {
14662 rval = EACCES;
14663 }
14664
14665 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14666
14667 return rval;
14668 }
14669
14670 void
14671 dtrace_lazy_dofs_destroy(proc_t *p)
14672 {
14673 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14674 lck_mtx_lock(&p->p_dtrace_sprlock);
14675
14676 /*
14677 * If we have lazy dof, dof mode better be LAZY_ON, or we must be exiting.
14678 * We cannot assert against DTRACE_DOF_MODE_NEVER here, because we are called from
14679 * kern_exit.c and kern_exec.c.
14680 */
14681 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON || p->p_lflag & P_LEXIT);
14682 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14683
14684 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
14685 p->p_dtrace_lazy_dofs = NULL;
14686
14687 lck_mtx_unlock(&p->p_dtrace_sprlock);
14688 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14689
14690 if (lazy_dofs) {
14691 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
14692 }
14693 }
14694
14695 void
14696 dtrace_lazy_dofs_duplicate(proc_t *parent, proc_t *child)
14697 {
14698 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
14699 lck_mtx_assert(&parent->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
14700 lck_mtx_assert(&child->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
14701
14702 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14703 lck_mtx_lock(&parent->p_dtrace_sprlock);
14704
14705 /*
14706 * If we have lazy dof, dof mode better be LAZY_ON, or we must be exiting.
14707 * We cannot assert against DTRACE_DOF_MODE_NEVER here, because we are called from
14708 * kern_fork.c
14709 */
14710 ASSERT(parent->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
14711 ASSERT(parent->p_dtrace_lazy_dofs == NULL || parent->p_dtrace_helpers == NULL);
14712 /*
14713 * In theory we should hold the child sprlock, but this is safe...
14714 */
14715 ASSERT(child->p_dtrace_lazy_dofs == NULL && child->p_dtrace_helpers == NULL);
14716
14717 dof_ioctl_data_t* parent_dofs = parent->p_dtrace_lazy_dofs;
14718 dof_ioctl_data_t* child_dofs = NULL;
14719 if (parent_dofs) {
14720 size_t parent_dofs_size = DOF_IOCTL_DATA_T_SIZE(parent_dofs->dofiod_count);
14721 child_dofs = kmem_alloc(parent_dofs_size, KM_SLEEP);
14722 bcopy(parent_dofs, child_dofs, parent_dofs_size);
14723 }
14724
14725 lck_mtx_unlock(&parent->p_dtrace_sprlock);
14726
14727 if (child_dofs) {
14728 lck_mtx_lock(&child->p_dtrace_sprlock);
14729 child->p_dtrace_lazy_dofs = child_dofs;
14730 lck_mtx_unlock(&child->p_dtrace_sprlock);
14731 }
14732
14733 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14734 }
14735
14736 static int
14737 dtrace_lazy_dofs_proc_iterate_filter(proc_t *p, void* ignored)
14738 {
14739 #pragma unused(ignored)
14740 /*
14741 * Okay to NULL test without taking the sprlock.
14742 */
14743 return p->p_dtrace_lazy_dofs != NULL;
14744 }
14745
14746 static int
14747 dtrace_lazy_dofs_proc_iterate_doit(proc_t *p, void* ignored)
14748 {
14749 #pragma unused(ignored)
14750 /*
14751 * It is possible this process may exit during our attempt to
14752 * fault in the dof. We could fix this by holding locks longer,
14753 * but the errors are benign.
14754 */
14755 lck_mtx_lock(&p->p_dtrace_sprlock);
14756
14757 /*
14758 * In this case only, it is okay to have lazy dof when dof mode is DTRACE_DOF_MODE_LAZY_OFF
14759 */
14760 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14761 ASSERT(dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF);
14762
14763
14764 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
14765 p->p_dtrace_lazy_dofs = NULL;
14766
14767 lck_mtx_unlock(&p->p_dtrace_sprlock);
14768
14769 /*
14770 * Process each dof_helper_t
14771 */
14772 if (lazy_dofs != NULL) {
14773 unsigned int i;
14774 int rval;
14775
14776 for (i=0; i<lazy_dofs->dofiod_count; i++) {
14777 /*
14778 * When loading lazy dof, we depend on the generations being sorted in ascending order.
14779 */
14780 ASSERT(i >= (lazy_dofs->dofiod_count - 1) || lazy_dofs->dofiod_helpers[i].dofhp_dof < lazy_dofs->dofiod_helpers[i+1].dofhp_dof);
14781
14782 dof_helper_t *dhp = &lazy_dofs->dofiod_helpers[i];
14783
14784 /*
14785 * We stored the generation in dofhp_dof. Save it, and restore the original value.
14786 */
14787 int generation = dhp->dofhp_dof;
14788 dhp->dofhp_dof = dhp->dofhp_addr;
14789
14790 dof_hdr_t *dof = dtrace_dof_copyin_from_proc(p, dhp->dofhp_dof, &rval);
14791
14792 if (dof != NULL) {
14793 dtrace_helpers_t *help;
14794
14795 lck_mtx_lock(&dtrace_lock);
14796
14797 /*
14798 * This must be done with the dtrace_lock held
14799 */
14800 if ((help = p->p_dtrace_helpers) == NULL)
14801 help = dtrace_helpers_create(p);
14802
14803 /*
14804 * If the generation value has been bumped, someone snuck in
14805 * when we released the dtrace lock. We have to dump this generation,
14806 * there is no safe way to load it.
14807 */
14808 if (help->dthps_generation <= generation) {
14809 help->dthps_generation = generation;
14810
14811 /*
14812 * dtrace_helper_slurp() takes responsibility for the dof --
14813 * it may free it now or it may save it and free it later.
14814 */
14815 if ((rval = dtrace_helper_slurp(p, dof, dhp)) != generation) {
14816 dtrace_dof_error(NULL, "returned value did not match expected generation");
14817 }
14818 }
14819
14820 lck_mtx_unlock(&dtrace_lock);
14821 }
14822 }
14823
14824 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
14825 }
14826
14827 return PROC_RETURNED;
14828 }
14829
14830 static dtrace_helpers_t *
14831 dtrace_helpers_create(proc_t *p)
14832 {
14833 dtrace_helpers_t *help;
14834
14835 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14836 ASSERT(p->p_dtrace_helpers == NULL);
14837
14838 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14839 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14840 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14841
14842 p->p_dtrace_helpers = help;
14843 dtrace_helpers++;
14844
14845 return (help);
14846 }
14847
14848 static void
14849 dtrace_helpers_destroy(proc_t* p)
14850 {
14851 dtrace_helpers_t *help;
14852 dtrace_vstate_t *vstate;
14853 uint_t i;
14854
14855 lck_mtx_lock(&dtrace_lock);
14856
14857 ASSERT(p->p_dtrace_helpers != NULL);
14858 ASSERT(dtrace_helpers > 0);
14859
14860 help = p->p_dtrace_helpers;
14861 vstate = &help->dthps_vstate;
14862
14863 /*
14864 * We're now going to lose the help from this process.
14865 */
14866 p->p_dtrace_helpers = NULL;
14867 dtrace_sync();
14868
14869 /*
14870 * Destory the helper actions.
14871 */
14872 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14873 dtrace_helper_action_t *h, *next;
14874
14875 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14876 next = h->dtha_next;
14877 dtrace_helper_action_destroy(h, vstate);
14878 h = next;
14879 }
14880 }
14881
14882 lck_mtx_unlock(&dtrace_lock);
14883
14884 /*
14885 * Destroy the helper providers.
14886 */
14887 if (help->dthps_maxprovs > 0) {
14888 lck_mtx_lock(&dtrace_meta_lock);
14889 if (dtrace_meta_pid != NULL) {
14890 ASSERT(dtrace_deferred_pid == NULL);
14891
14892 for (i = 0; i < help->dthps_nprovs; i++) {
14893 dtrace_helper_provider_remove(
14894 &help->dthps_provs[i]->dthp_prov, p->p_pid);
14895 }
14896 } else {
14897 lck_mtx_lock(&dtrace_lock);
14898 ASSERT(help->dthps_deferred == 0 ||
14899 help->dthps_next != NULL ||
14900 help->dthps_prev != NULL ||
14901 help == dtrace_deferred_pid);
14902
14903 /*
14904 * Remove the helper from the deferred list.
14905 */
14906 if (help->dthps_next != NULL)
14907 help->dthps_next->dthps_prev = help->dthps_prev;
14908 if (help->dthps_prev != NULL)
14909 help->dthps_prev->dthps_next = help->dthps_next;
14910 if (dtrace_deferred_pid == help) {
14911 dtrace_deferred_pid = help->dthps_next;
14912 ASSERT(help->dthps_prev == NULL);
14913 }
14914
14915 lck_mtx_unlock(&dtrace_lock);
14916 }
14917
14918 lck_mtx_unlock(&dtrace_meta_lock);
14919
14920 for (i = 0; i < help->dthps_nprovs; i++) {
14921 dtrace_helper_provider_destroy(help->dthps_provs[i]);
14922 }
14923
14924 kmem_free(help->dthps_provs, help->dthps_maxprovs *
14925 sizeof (dtrace_helper_provider_t *));
14926 }
14927
14928 lck_mtx_lock(&dtrace_lock);
14929
14930 dtrace_vstate_fini(&help->dthps_vstate);
14931 kmem_free(help->dthps_actions,
14932 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
14933 kmem_free(help, sizeof (dtrace_helpers_t));
14934
14935 --dtrace_helpers;
14936 lck_mtx_unlock(&dtrace_lock);
14937 }
14938
14939 static void
14940 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
14941 {
14942 dtrace_helpers_t *help, *newhelp;
14943 dtrace_helper_action_t *helper, *new, *last;
14944 dtrace_difo_t *dp;
14945 dtrace_vstate_t *vstate;
14946 uint_t i;
14947 int j, sz, hasprovs = 0;
14948
14949 lck_mtx_lock(&dtrace_lock);
14950 ASSERT(from->p_dtrace_helpers != NULL);
14951 ASSERT(dtrace_helpers > 0);
14952
14953 help = from->p_dtrace_helpers;
14954 newhelp = dtrace_helpers_create(to);
14955 ASSERT(to->p_dtrace_helpers != NULL);
14956
14957 newhelp->dthps_generation = help->dthps_generation;
14958 vstate = &newhelp->dthps_vstate;
14959
14960 /*
14961 * Duplicate the helper actions.
14962 */
14963 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14964 if ((helper = help->dthps_actions[i]) == NULL)
14965 continue;
14966
14967 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
14968 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
14969 KM_SLEEP);
14970 new->dtha_generation = helper->dtha_generation;
14971
14972 if ((dp = helper->dtha_predicate) != NULL) {
14973 dp = dtrace_difo_duplicate(dp, vstate);
14974 new->dtha_predicate = dp;
14975 }
14976
14977 new->dtha_nactions = helper->dtha_nactions;
14978 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
14979 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
14980
14981 for (j = 0; j < new->dtha_nactions; j++) {
14982 dtrace_difo_t *dpj = helper->dtha_actions[j];
14983
14984 ASSERT(dpj != NULL);
14985 dpj = dtrace_difo_duplicate(dpj, vstate);
14986 new->dtha_actions[j] = dpj;
14987 }
14988
14989 if (last != NULL) {
14990 last->dtha_next = new;
14991 } else {
14992 newhelp->dthps_actions[i] = new;
14993 }
14994
14995 last = new;
14996 }
14997 }
14998
14999 /*
15000 * Duplicate the helper providers and register them with the
15001 * DTrace framework.
15002 */
15003 if (help->dthps_nprovs > 0) {
15004 newhelp->dthps_nprovs = help->dthps_nprovs;
15005 newhelp->dthps_maxprovs = help->dthps_nprovs;
15006 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15007 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15008 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15009 newhelp->dthps_provs[i] = help->dthps_provs[i];
15010 newhelp->dthps_provs[i]->dthp_ref++;
15011 }
15012
15013 hasprovs = 1;
15014 }
15015
15016 lck_mtx_unlock(&dtrace_lock);
15017
15018 if (hasprovs)
15019 dtrace_helper_provider_register(to, newhelp, NULL);
15020 }
15021
15022 /*
15023 * DTrace Hook Functions
15024 */
15025
15026 /*
15027 * APPLE NOTE: dtrace_modctl_* routines for kext support.
15028 * Used to manipulate the modctl list within dtrace xnu.
15029 */
15030
15031 modctl_t *dtrace_modctl_list;
15032
15033 static void
15034 dtrace_modctl_add(struct modctl * newctl)
15035 {
15036 struct modctl *nextp, *prevp;
15037
15038 ASSERT(newctl != NULL);
15039 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15040
15041 // Insert new module at the front of the list,
15042
15043 newctl->mod_next = dtrace_modctl_list;
15044 dtrace_modctl_list = newctl;
15045
15046 /*
15047 * If a module exists with the same name, then that module
15048 * must have been unloaded with enabled probes. We will move
15049 * the unloaded module to the new module's stale chain and
15050 * then stop traversing the list.
15051 */
15052
15053 prevp = newctl;
15054 nextp = newctl->mod_next;
15055
15056 while (nextp != NULL) {
15057 if (nextp->mod_loaded) {
15058 /* This is a loaded module. Keep traversing. */
15059 prevp = nextp;
15060 nextp = nextp->mod_next;
15061 continue;
15062 }
15063 else {
15064 /* Found an unloaded module */
15065 if (strncmp (newctl->mod_modname, nextp->mod_modname, KMOD_MAX_NAME)) {
15066 /* Names don't match. Keep traversing. */
15067 prevp = nextp;
15068 nextp = nextp->mod_next;
15069 continue;
15070 }
15071 else {
15072 /* We found a stale entry, move it. We're done. */
15073 prevp->mod_next = nextp->mod_next;
15074 newctl->mod_stale = nextp;
15075 nextp->mod_next = NULL;
15076 break;
15077 }
15078 }
15079 }
15080 }
15081
15082 static modctl_t *
15083 dtrace_modctl_lookup(struct kmod_info * kmod)
15084 {
15085 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15086
15087 struct modctl * ctl;
15088
15089 for (ctl = dtrace_modctl_list; ctl; ctl=ctl->mod_next) {
15090 if (ctl->mod_id == kmod->id)
15091 return(ctl);
15092 }
15093 return (NULL);
15094 }
15095
15096 /*
15097 * This routine is called from dtrace_module_unloaded().
15098 * It removes a modctl structure and its stale chain
15099 * from the kext shadow list.
15100 */
15101 static void
15102 dtrace_modctl_remove(struct modctl * ctl)
15103 {
15104 ASSERT(ctl != NULL);
15105 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15106 modctl_t *prevp, *nextp, *curp;
15107
15108 // Remove stale chain first
15109 for (curp=ctl->mod_stale; curp != NULL; curp=nextp) {
15110 nextp = curp->mod_stale;
15111 /* There should NEVER be user symbols allocated at this point */
15112 ASSERT(curp->mod_user_symbols == NULL);
15113 kmem_free(curp, sizeof(modctl_t));
15114 }
15115
15116 prevp = NULL;
15117 curp = dtrace_modctl_list;
15118
15119 while (curp != ctl) {
15120 prevp = curp;
15121 curp = curp->mod_next;
15122 }
15123
15124 if (prevp != NULL) {
15125 prevp->mod_next = ctl->mod_next;
15126 }
15127 else {
15128 dtrace_modctl_list = ctl->mod_next;
15129 }
15130
15131 /* There should NEVER be user symbols allocated at this point */
15132 ASSERT(ctl->mod_user_symbols == NULL);
15133
15134 kmem_free (ctl, sizeof(modctl_t));
15135 }
15136
15137 /*
15138 * APPLE NOTE: The kext loader will call dtrace_module_loaded
15139 * when the kext is loaded in memory, but before calling the
15140 * kext's start routine.
15141 *
15142 * Return 0 on success
15143 * Return -1 on failure
15144 */
15145
15146 static int
15147 dtrace_module_loaded(struct kmod_info *kmod, uint32_t flag)
15148 {
15149 dtrace_provider_t *prv;
15150
15151 /*
15152 * If kernel symbols have been disabled, return immediately
15153 * DTRACE_KERNEL_SYMBOLS_NEVER is a permanent mode, it is safe to test without holding locks
15154 */
15155 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER)
15156 return 0;
15157
15158 struct modctl *ctl = NULL;
15159 if (!kmod || kmod->address == 0 || kmod->size == 0)
15160 return(-1);
15161
15162 lck_mtx_lock(&dtrace_provider_lock);
15163 lck_mtx_lock(&mod_lock);
15164
15165 /*
15166 * Have we seen this kext before?
15167 */
15168
15169 ctl = dtrace_modctl_lookup(kmod);
15170
15171 if (ctl != NULL) {
15172 /* bail... we already have this kext in the modctl list */
15173 lck_mtx_unlock(&mod_lock);
15174 lck_mtx_unlock(&dtrace_provider_lock);
15175 if (dtrace_err_verbose)
15176 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);
15177 return(-1);
15178 }
15179 else {
15180 ctl = kmem_alloc(sizeof(struct modctl), KM_SLEEP);
15181 if (ctl == NULL) {
15182 if (dtrace_err_verbose)
15183 cmn_err(CE_WARN, "dtrace module load '%s %u' is failing ", kmod->name, (uint_t)kmod->id);
15184 lck_mtx_unlock(&mod_lock);
15185 lck_mtx_unlock(&dtrace_provider_lock);
15186 return (-1);
15187 }
15188 ctl->mod_next = NULL;
15189 ctl->mod_stale = NULL;
15190 strlcpy (ctl->mod_modname, kmod->name, sizeof(ctl->mod_modname));
15191 ctl->mod_loadcnt = kmod->id;
15192 ctl->mod_nenabled = 0;
15193 ctl->mod_address = kmod->address;
15194 ctl->mod_size = kmod->size;
15195 ctl->mod_id = kmod->id;
15196 ctl->mod_loaded = 1;
15197 ctl->mod_flags = 0;
15198 ctl->mod_user_symbols = NULL;
15199
15200 /*
15201 * Find the UUID for this module, if it has one
15202 */
15203 kernel_mach_header_t* header = (kernel_mach_header_t *)ctl->mod_address;
15204 struct load_command* load_cmd = (struct load_command *)&header[1];
15205 uint32_t i;
15206 for (i = 0; i < header->ncmds; i++) {
15207 if (load_cmd->cmd == LC_UUID) {
15208 struct uuid_command* uuid_cmd = (struct uuid_command *)load_cmd;
15209 memcpy(ctl->mod_uuid, uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
15210 ctl->mod_flags |= MODCTL_HAS_UUID;
15211 break;
15212 }
15213 load_cmd = (struct load_command *)((caddr_t)load_cmd + load_cmd->cmdsize);
15214 }
15215
15216 if (ctl->mod_address == g_kernel_kmod_info.address) {
15217 ctl->mod_flags |= MODCTL_IS_MACH_KERNEL;
15218 }
15219 }
15220 dtrace_modctl_add(ctl);
15221
15222 /*
15223 * We must hold the dtrace_lock to safely test non permanent dtrace_fbt_symbol_mode(s)
15224 */
15225 lck_mtx_lock(&dtrace_lock);
15226
15227 /*
15228 * DTrace must decide if it will instrument modules lazily via
15229 * userspace symbols (default mode), or instrument immediately via
15230 * kernel symbols (non-default mode)
15231 *
15232 * When in default/lazy mode, DTrace will only support modules
15233 * built with a valid UUID.
15234 *
15235 * Overriding the default can be done explicitly in one of
15236 * the following two ways.
15237 *
15238 * A module can force symbols from kernel space using the plist key,
15239 * OSBundleForceDTraceInit (see kmod.h). If this per kext state is set,
15240 * we fall through and instrument this module now.
15241 *
15242 * Or, the boot-arg, dtrace_kernel_symbol_mode, can be set to force symbols
15243 * from kernel space (see dtrace_impl.h). If this system state is set
15244 * to a non-userspace mode, we fall through and instrument the module now.
15245 */
15246
15247 if ((dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) &&
15248 (!(flag & KMOD_DTRACE_FORCE_INIT)))
15249 {
15250 /* We will instrument the module lazily -- this is the default */
15251 lck_mtx_unlock(&dtrace_lock);
15252 lck_mtx_unlock(&mod_lock);
15253 lck_mtx_unlock(&dtrace_provider_lock);
15254 return 0;
15255 }
15256
15257 /* We will instrument the module immediately using kernel symbols */
15258 ctl->mod_flags |= MODCTL_HAS_KERNEL_SYMBOLS;
15259
15260 lck_mtx_unlock(&dtrace_lock);
15261
15262 /*
15263 * We're going to call each providers per-module provide operation
15264 * specifying only this module.
15265 */
15266 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15267 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15268
15269 /*
15270 * APPLE NOTE: The contract with the kext loader is that once this function
15271 * has completed, it may delete kernel symbols at will.
15272 * We must set this while still holding the mod_lock.
15273 */
15274 ctl->mod_flags &= ~MODCTL_HAS_KERNEL_SYMBOLS;
15275
15276 lck_mtx_unlock(&mod_lock);
15277 lck_mtx_unlock(&dtrace_provider_lock);
15278
15279 /*
15280 * If we have any retained enablings, we need to match against them.
15281 * Enabling probes requires that cpu_lock be held, and we cannot hold
15282 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15283 * module. (In particular, this happens when loading scheduling
15284 * classes.) So if we have any retained enablings, we need to dispatch
15285 * our task queue to do the match for us.
15286 */
15287 lck_mtx_lock(&dtrace_lock);
15288
15289 if (dtrace_retained == NULL) {
15290 lck_mtx_unlock(&dtrace_lock);
15291 return 0;
15292 }
15293
15294 /* APPLE NOTE!
15295 *
15296 * The cpu_lock mentioned above is only held by dtrace code, Apple's xnu never actually
15297 * holds it for any reason. Thus the comment above is invalid, we can directly invoke
15298 * dtrace_enabling_matchall without jumping through all the hoops, and we can avoid
15299 * the delay call as well.
15300 */
15301 lck_mtx_unlock(&dtrace_lock);
15302
15303 dtrace_enabling_matchall();
15304
15305 return 0;
15306 }
15307
15308 /*
15309 * Return 0 on success
15310 * Return -1 on failure
15311 */
15312 static int
15313 dtrace_module_unloaded(struct kmod_info *kmod)
15314 {
15315 dtrace_probe_t template, *probe, *first, *next;
15316 dtrace_provider_t *prov;
15317 struct modctl *ctl = NULL;
15318 struct modctl *syncctl = NULL;
15319 struct modctl *nextsyncctl = NULL;
15320 int syncmode = 0;
15321
15322 lck_mtx_lock(&dtrace_provider_lock);
15323 lck_mtx_lock(&mod_lock);
15324 lck_mtx_lock(&dtrace_lock);
15325
15326 if (kmod == NULL) {
15327 syncmode = 1;
15328 }
15329 else {
15330 ctl = dtrace_modctl_lookup(kmod);
15331 if (ctl == NULL)
15332 {
15333 lck_mtx_unlock(&dtrace_lock);
15334 lck_mtx_unlock(&mod_lock);
15335 lck_mtx_unlock(&dtrace_provider_lock);
15336 return (-1);
15337 }
15338 ctl->mod_loaded = 0;
15339 ctl->mod_address = 0;
15340 ctl->mod_size = 0;
15341 }
15342
15343 if (dtrace_bymod == NULL) {
15344 /*
15345 * The DTrace module is loaded (obviously) but not attached;
15346 * we don't have any work to do.
15347 */
15348 if (ctl != NULL)
15349 (void)dtrace_modctl_remove(ctl);
15350 lck_mtx_unlock(&dtrace_lock);
15351 lck_mtx_unlock(&mod_lock);
15352 lck_mtx_unlock(&dtrace_provider_lock);
15353 return(0);
15354 }
15355
15356 /* Syncmode set means we target and traverse entire modctl list. */
15357 if (syncmode)
15358 nextsyncctl = dtrace_modctl_list;
15359
15360 syncloop:
15361 if (syncmode)
15362 {
15363 /* find a stale modctl struct */
15364 for (syncctl = nextsyncctl; syncctl != NULL; syncctl=syncctl->mod_next) {
15365 if (syncctl->mod_address == 0)
15366 break;
15367 }
15368 if (syncctl==NULL)
15369 {
15370 /* We have no more work to do */
15371 lck_mtx_unlock(&dtrace_lock);
15372 lck_mtx_unlock(&mod_lock);
15373 lck_mtx_unlock(&dtrace_provider_lock);
15374 return(0);
15375 }
15376 else {
15377 /* keep track of next syncctl in case this one is removed */
15378 nextsyncctl = syncctl->mod_next;
15379 ctl = syncctl;
15380 }
15381 }
15382
15383 template.dtpr_mod = ctl->mod_modname;
15384
15385 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15386 probe != NULL; probe = probe->dtpr_nextmod) {
15387 if (probe->dtpr_ecb != NULL) {
15388 /*
15389 * This shouldn't _actually_ be possible -- we're
15390 * unloading a module that has an enabled probe in it.
15391 * (It's normally up to the provider to make sure that
15392 * this can't happen.) However, because dtps_enable()
15393 * doesn't have a failure mode, there can be an
15394 * enable/unload race. Upshot: we don't want to
15395 * assert, but we're not going to disable the
15396 * probe, either.
15397 */
15398
15399
15400 if (syncmode) {
15401 /* We're syncing, let's look at next in list */
15402 goto syncloop;
15403 }
15404
15405 lck_mtx_unlock(&dtrace_lock);
15406 lck_mtx_unlock(&mod_lock);
15407 lck_mtx_unlock(&dtrace_provider_lock);
15408
15409 if (dtrace_err_verbose) {
15410 cmn_err(CE_WARN, "unloaded module '%s' had "
15411 "enabled probes", ctl->mod_modname);
15412 }
15413 return(-1);
15414 }
15415 }
15416
15417 probe = first;
15418
15419 for (first = NULL; probe != NULL; probe = next) {
15420 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15421
15422 dtrace_probes[probe->dtpr_id - 1] = NULL;
15423 probe->dtpr_provider->dtpv_probe_count--;
15424
15425 next = probe->dtpr_nextmod;
15426 dtrace_hash_remove(dtrace_bymod, probe);
15427 dtrace_hash_remove(dtrace_byfunc, probe);
15428 dtrace_hash_remove(dtrace_byname, probe);
15429
15430 if (first == NULL) {
15431 first = probe;
15432 probe->dtpr_nextmod = NULL;
15433 } else {
15434 probe->dtpr_nextmod = first;
15435 first = probe;
15436 }
15437 }
15438
15439 /*
15440 * We've removed all of the module's probes from the hash chains and
15441 * from the probe array. Now issue a dtrace_sync() to be sure that
15442 * everyone has cleared out from any probe array processing.
15443 */
15444 dtrace_sync();
15445
15446 for (probe = first; probe != NULL; probe = first) {
15447 first = probe->dtpr_nextmod;
15448 prov = probe->dtpr_provider;
15449 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15450 probe->dtpr_arg);
15451 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15452 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15453 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15454 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15455
15456 zfree(dtrace_probe_t_zone, probe);
15457 }
15458
15459 dtrace_modctl_remove(ctl);
15460
15461 if (syncmode)
15462 goto syncloop;
15463
15464 lck_mtx_unlock(&dtrace_lock);
15465 lck_mtx_unlock(&mod_lock);
15466 lck_mtx_unlock(&dtrace_provider_lock);
15467
15468 return(0);
15469 }
15470
15471 void
15472 dtrace_suspend(void)
15473 {
15474 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15475 }
15476
15477 void
15478 dtrace_resume(void)
15479 {
15480 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15481 }
15482
15483 static int
15484 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15485 {
15486 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15487 lck_mtx_lock(&dtrace_lock);
15488
15489 switch (what) {
15490 case CPU_CONFIG: {
15491 dtrace_state_t *state;
15492 dtrace_optval_t *opt, rs, c;
15493
15494 /*
15495 * For now, we only allocate a new buffer for anonymous state.
15496 */
15497 if ((state = dtrace_anon.dta_state) == NULL)
15498 break;
15499
15500 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15501 break;
15502
15503 opt = state->dts_options;
15504 c = opt[DTRACEOPT_CPU];
15505
15506 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15507 break;
15508
15509 /*
15510 * Regardless of what the actual policy is, we're going to
15511 * temporarily set our resize policy to be manual. We're
15512 * also going to temporarily set our CPU option to denote
15513 * the newly configured CPU.
15514 */
15515 rs = opt[DTRACEOPT_BUFRESIZE];
15516 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15517 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15518
15519 (void) dtrace_state_buffers(state);
15520
15521 opt[DTRACEOPT_BUFRESIZE] = rs;
15522 opt[DTRACEOPT_CPU] = c;
15523
15524 break;
15525 }
15526
15527 case CPU_UNCONFIG:
15528 /*
15529 * We don't free the buffer in the CPU_UNCONFIG case. (The
15530 * buffer will be freed when the consumer exits.)
15531 */
15532 break;
15533
15534 default:
15535 break;
15536 }
15537
15538 lck_mtx_unlock(&dtrace_lock);
15539 return (0);
15540 }
15541
15542 static void
15543 dtrace_cpu_setup_initial(processorid_t cpu)
15544 {
15545 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15546 }
15547
15548 static void
15549 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15550 {
15551 if (dtrace_toxranges >= dtrace_toxranges_max) {
15552 int osize, nsize;
15553 dtrace_toxrange_t *range;
15554
15555 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15556
15557 if (osize == 0) {
15558 ASSERT(dtrace_toxrange == NULL);
15559 ASSERT(dtrace_toxranges_max == 0);
15560 dtrace_toxranges_max = 1;
15561 } else {
15562 dtrace_toxranges_max <<= 1;
15563 }
15564
15565 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15566 range = kmem_zalloc(nsize, KM_SLEEP);
15567
15568 if (dtrace_toxrange != NULL) {
15569 ASSERT(osize != 0);
15570 bcopy(dtrace_toxrange, range, osize);
15571 kmem_free(dtrace_toxrange, osize);
15572 }
15573
15574 dtrace_toxrange = range;
15575 }
15576
15577 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15578 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15579
15580 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15581 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15582 dtrace_toxranges++;
15583 }
15584
15585 /*
15586 * DTrace Driver Cookbook Functions
15587 */
15588 /*ARGSUSED*/
15589 static int
15590 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15591 {
15592 #pragma unused(cmd) /* __APPLE__ */
15593 dtrace_provider_id_t id;
15594 dtrace_state_t *state = NULL;
15595 dtrace_enabling_t *enab;
15596
15597 lck_mtx_lock(&cpu_lock);
15598 lck_mtx_lock(&dtrace_provider_lock);
15599 lck_mtx_lock(&dtrace_lock);
15600
15601 if (ddi_soft_state_init(&dtrace_softstate,
15602 sizeof (dtrace_state_t), 0) != 0) {
15603 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15604 lck_mtx_unlock(&dtrace_lock);
15605 lck_mtx_unlock(&dtrace_provider_lock);
15606 lck_mtx_unlock(&cpu_lock);
15607 return (DDI_FAILURE);
15608 }
15609
15610 /* Darwin uses BSD cloning device driver to automagically obtain minor device number. */
15611
15612 ddi_report_dev(devi);
15613 dtrace_devi = devi;
15614
15615 dtrace_modload = dtrace_module_loaded;
15616 dtrace_modunload = dtrace_module_unloaded;
15617 dtrace_cpu_init = dtrace_cpu_setup_initial;
15618 dtrace_helpers_cleanup = dtrace_helpers_destroy;
15619 dtrace_helpers_fork = dtrace_helpers_duplicate;
15620 dtrace_cpustart_init = dtrace_suspend;
15621 dtrace_cpustart_fini = dtrace_resume;
15622 dtrace_debugger_init = dtrace_suspend;
15623 dtrace_debugger_fini = dtrace_resume;
15624
15625 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15626
15627 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15628
15629 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15630 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15631 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15632 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15633 VM_SLEEP | VMC_IDENTIFIER);
15634 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15635 1, INT_MAX, 0);
15636
15637 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15638 sizeof (dtrace_dstate_percpu_t) * (int)NCPU, DTRACE_STATE_ALIGN,
15639 NULL, NULL, NULL, NULL, NULL, 0);
15640
15641 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15642 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15643 offsetof(dtrace_probe_t, dtpr_nextmod),
15644 offsetof(dtrace_probe_t, dtpr_prevmod));
15645
15646 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15647 offsetof(dtrace_probe_t, dtpr_nextfunc),
15648 offsetof(dtrace_probe_t, dtpr_prevfunc));
15649
15650 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15651 offsetof(dtrace_probe_t, dtpr_nextname),
15652 offsetof(dtrace_probe_t, dtpr_prevname));
15653
15654 if (dtrace_retain_max < 1) {
15655 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15656 "setting to 1", dtrace_retain_max);
15657 dtrace_retain_max = 1;
15658 }
15659
15660 /*
15661 * Now discover our toxic ranges.
15662 */
15663 dtrace_toxic_ranges(dtrace_toxrange_add);
15664
15665 /*
15666 * Before we register ourselves as a provider to our own framework,
15667 * we would like to assert that dtrace_provider is NULL -- but that's
15668 * not true if we were loaded as a dependency of a DTrace provider.
15669 * Once we've registered, we can assert that dtrace_provider is our
15670 * pseudo provider.
15671 */
15672 (void) dtrace_register("dtrace", &dtrace_provider_attr,
15673 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15674
15675 ASSERT(dtrace_provider != NULL);
15676 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15677
15678 #if defined (__x86_64__)
15679 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15680 dtrace_provider, NULL, NULL, "BEGIN", 1, NULL);
15681 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15682 dtrace_provider, NULL, NULL, "END", 0, NULL);
15683 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15684 dtrace_provider, NULL, NULL, "ERROR", 3, NULL);
15685 #else
15686 #error Unknown Architecture
15687 #endif
15688
15689 dtrace_anon_property();
15690 lck_mtx_unlock(&cpu_lock);
15691
15692 /*
15693 * If DTrace helper tracing is enabled, we need to allocate the
15694 * trace buffer and initialize the values.
15695 */
15696 if (dtrace_helptrace_enabled) {
15697 ASSERT(dtrace_helptrace_buffer == NULL);
15698 dtrace_helptrace_buffer =
15699 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15700 dtrace_helptrace_next = 0;
15701 }
15702
15703 /*
15704 * If there are already providers, we must ask them to provide their
15705 * probes, and then match any anonymous enabling against them. Note
15706 * that there should be no other retained enablings at this time:
15707 * the only retained enablings at this time should be the anonymous
15708 * enabling.
15709 */
15710 if (dtrace_anon.dta_enabling != NULL) {
15711 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15712
15713 /*
15714 * APPLE NOTE: if handling anonymous dof, switch symbol modes.
15715 */
15716 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
15717 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
15718 }
15719
15720 dtrace_enabling_provide(NULL);
15721 state = dtrace_anon.dta_state;
15722
15723 /*
15724 * We couldn't hold cpu_lock across the above call to
15725 * dtrace_enabling_provide(), but we must hold it to actually
15726 * enable the probes. We have to drop all of our locks, pick
15727 * up cpu_lock, and regain our locks before matching the
15728 * retained anonymous enabling.
15729 */
15730 lck_mtx_unlock(&dtrace_lock);
15731 lck_mtx_unlock(&dtrace_provider_lock);
15732
15733 lck_mtx_lock(&cpu_lock);
15734 lck_mtx_lock(&dtrace_provider_lock);
15735 lck_mtx_lock(&dtrace_lock);
15736
15737 if ((enab = dtrace_anon.dta_enabling) != NULL)
15738 (void) dtrace_enabling_match(enab, NULL);
15739
15740 lck_mtx_unlock(&cpu_lock);
15741 }
15742
15743 lck_mtx_unlock(&dtrace_lock);
15744 lck_mtx_unlock(&dtrace_provider_lock);
15745
15746 if (state != NULL) {
15747 /*
15748 * If we created any anonymous state, set it going now.
15749 */
15750 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15751 }
15752
15753 return (DDI_SUCCESS);
15754 }
15755
15756 /*ARGSUSED*/
15757 static int
15758 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15759 {
15760 #pragma unused(flag, otyp)
15761 dtrace_state_t *state;
15762 uint32_t priv;
15763 uid_t uid;
15764 zoneid_t zoneid;
15765 int rv;
15766
15767 /* APPLE: Darwin puts Helper on its own major device. */
15768
15769 /*
15770 * If no DTRACE_PRIV_* bits are set in the credential, then the
15771 * caller lacks sufficient permission to do anything with DTrace.
15772 */
15773 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15774 if (priv == DTRACE_PRIV_NONE)
15775 return (EACCES);
15776
15777 /*
15778 * APPLE NOTE: We delay the initialization of fasttrap as late as possible.
15779 * It certainly can't be later than now!
15780 */
15781 fasttrap_init();
15782
15783 /*
15784 * Ask all providers to provide all their probes.
15785 */
15786 lck_mtx_lock(&dtrace_provider_lock);
15787 dtrace_probe_provide(NULL, NULL);
15788 lck_mtx_unlock(&dtrace_provider_lock);
15789
15790 lck_mtx_lock(&cpu_lock);
15791 lck_mtx_lock(&dtrace_lock);
15792 dtrace_opens++;
15793 dtrace_membar_producer();
15794
15795 /*
15796 * If the kernel debugger is active (that is, if the kernel debugger
15797 * modified text in some way), we won't allow the open.
15798 */
15799 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15800 dtrace_opens--;
15801 lck_mtx_unlock(&dtrace_lock);
15802 lck_mtx_unlock(&cpu_lock);
15803 return (EBUSY);
15804 }
15805
15806 rv = dtrace_state_create(devp, cred_p, &state);
15807 lck_mtx_unlock(&cpu_lock);
15808
15809 if (rv != 0 || state == NULL) {
15810 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15811 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15812 lck_mtx_unlock(&dtrace_lock);
15813 /* propagate EAGAIN or ERESTART */
15814 return (rv);
15815 }
15816
15817 lck_mtx_unlock(&dtrace_lock);
15818
15819 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
15820
15821 /*
15822 * If we are currently lazy, transition states.
15823 *
15824 * Unlike dtrace_close, we do not need to check the
15825 * value of dtrace_opens, as any positive value (and
15826 * we count as 1) means we transition states.
15827 */
15828 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON) {
15829 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_OFF;
15830
15831 /*
15832 * Iterate all existing processes and load lazy dofs.
15833 */
15834 proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS,
15835 dtrace_lazy_dofs_proc_iterate_doit,
15836 NULL,
15837 dtrace_lazy_dofs_proc_iterate_filter,
15838 NULL);
15839 }
15840
15841 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
15842
15843 /*
15844 * Update kernel symbol state.
15845 *
15846 * We must own the provider and dtrace locks.
15847 *
15848 * NOTE! It may appear there is a race by setting this value so late
15849 * after dtrace_probe_provide. However, any kext loaded after the
15850 * call to probe provide and before we set LAZY_OFF will be marked as
15851 * eligible for symbols from userspace. The same dtrace that is currently
15852 * calling dtrace_open() (this call!) will get a list of kexts needing
15853 * symbols and fill them in, thus closing the race window.
15854 *
15855 * We want to set this value only after it certain it will succeed, as
15856 * this significantly reduces the complexity of error exits.
15857 */
15858 lck_mtx_lock(&dtrace_lock);
15859 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
15860 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
15861 }
15862 lck_mtx_unlock(&dtrace_lock);
15863
15864 return (0);
15865 }
15866
15867 /*ARGSUSED*/
15868 static int
15869 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15870 {
15871 #pragma unused(flag, otyp, cred_p) /* __APPLE__ */
15872 minor_t minor = getminor(dev);
15873 dtrace_state_t *state;
15874
15875 /* APPLE NOTE: Darwin puts Helper on its own major device. */
15876
15877 state = ddi_get_soft_state(dtrace_softstate, minor);
15878
15879 lck_mtx_lock(&cpu_lock);
15880 lck_mtx_lock(&dtrace_lock);
15881
15882 if (state->dts_anon) {
15883 /*
15884 * There is anonymous state. Destroy that first.
15885 */
15886 ASSERT(dtrace_anon.dta_state == NULL);
15887 dtrace_state_destroy(state->dts_anon);
15888 }
15889
15890 dtrace_state_destroy(state);
15891 ASSERT(dtrace_opens > 0);
15892
15893 /*
15894 * Only relinquish control of the kernel debugger interface when there
15895 * are no consumers and no anonymous enablings.
15896 */
15897 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15898 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15899
15900 lck_mtx_unlock(&dtrace_lock);
15901 lck_mtx_unlock(&cpu_lock);
15902
15903 /*
15904 * Lock ordering requires the dof mode lock be taken before
15905 * the dtrace_lock.
15906 */
15907 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
15908 lck_mtx_lock(&dtrace_lock);
15909
15910 if (dtrace_opens == 0) {
15911 /*
15912 * If we are currently lazy-off, and this is the last close, transition to
15913 * lazy state.
15914 */
15915 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
15916 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
15917 }
15918
15919 /*
15920 * If we are the last dtrace client, switch back to lazy (from userspace) symbols
15921 */
15922 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_KERNEL) {
15923 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
15924 }
15925 }
15926
15927 lck_mtx_unlock(&dtrace_lock);
15928 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
15929
15930 /*
15931 * Kext probes may be retained past the end of the kext's lifespan. The
15932 * probes are kept until the last reference to them has been removed.
15933 * Since closing an active dtrace context is likely to drop that last reference,
15934 * lets take a shot at cleaning out the orphaned probes now.
15935 */
15936 dtrace_module_unloaded(NULL);
15937
15938 return (0);
15939 }
15940
15941 /*ARGSUSED*/
15942 static int
15943 dtrace_ioctl_helper(u_long cmd, caddr_t arg, int *rv)
15944 {
15945 #pragma unused(rv)
15946 /*
15947 * Safe to check this outside the dof mode lock
15948 */
15949 if (dtrace_dof_mode == DTRACE_DOF_MODE_NEVER)
15950 return KERN_SUCCESS;
15951
15952 switch (cmd) {
15953 case DTRACEHIOC_ADDDOF:
15954 {
15955 dof_helper_t *dhp = NULL;
15956 size_t dof_ioctl_data_size;
15957 dof_ioctl_data_t* multi_dof;
15958 unsigned int i;
15959 int rval = 0;
15960 user_addr_t user_address = *(user_addr_t*)arg;
15961 uint64_t dof_count;
15962 int multi_dof_claimed = 0;
15963 proc_t* p = current_proc();
15964
15965 /*
15966 * Read the number of DOF sections being passed in.
15967 */
15968 if (copyin(user_address + offsetof(dof_ioctl_data_t, dofiod_count),
15969 &dof_count,
15970 sizeof(dof_count))) {
15971 dtrace_dof_error(NULL, "failed to copyin dofiod_count");
15972 return (EFAULT);
15973 }
15974
15975 /*
15976 * Range check the count.
15977 */
15978 if (dof_count == 0 || dof_count > 1024) {
15979 dtrace_dof_error(NULL, "dofiod_count is not valid");
15980 return (EINVAL);
15981 }
15982
15983 /*
15984 * Allocate a correctly sized structure and copyin the data.
15985 */
15986 dof_ioctl_data_size = DOF_IOCTL_DATA_T_SIZE(dof_count);
15987 if ((multi_dof = kmem_alloc(dof_ioctl_data_size, KM_SLEEP)) == NULL)
15988 return (ENOMEM);
15989
15990 /* NOTE! We can no longer exit this method via return */
15991 if (copyin(user_address, multi_dof, dof_ioctl_data_size) != 0) {
15992 dtrace_dof_error(NULL, "failed copyin of dof_ioctl_data_t");
15993 rval = EFAULT;
15994 goto cleanup;
15995 }
15996
15997 /*
15998 * Check that the count didn't change between the first copyin and the second.
15999 */
16000 if (multi_dof->dofiod_count != dof_count) {
16001 rval = EINVAL;
16002 goto cleanup;
16003 }
16004
16005 /*
16006 * Try to process lazily first.
16007 */
16008 rval = dtrace_lazy_dofs_add(p, multi_dof, &multi_dof_claimed);
16009
16010 /*
16011 * If rval is EACCES, we must be non-lazy.
16012 */
16013 if (rval == EACCES) {
16014 rval = 0;
16015 /*
16016 * Process each dof_helper_t
16017 */
16018 i = 0;
16019 do {
16020 dhp = &multi_dof->dofiod_helpers[i];
16021
16022 dof_hdr_t *dof = dtrace_dof_copyin(dhp->dofhp_dof, &rval);
16023
16024 if (dof != NULL) {
16025 lck_mtx_lock(&dtrace_lock);
16026
16027 /*
16028 * dtrace_helper_slurp() takes responsibility for the dof --
16029 * it may free it now or it may save it and free it later.
16030 */
16031 if ((dhp->dofhp_dof = (uint64_t)dtrace_helper_slurp(p, dof, dhp)) == -1ULL) {
16032 rval = EINVAL;
16033 }
16034
16035 lck_mtx_unlock(&dtrace_lock);
16036 }
16037 } while (++i < multi_dof->dofiod_count && rval == 0);
16038 }
16039
16040 /*
16041 * We need to copyout the multi_dof struct, because it contains
16042 * the generation (unique id) values needed to call DTRACEHIOC_REMOVE
16043 *
16044 * This could certainly be better optimized.
16045 */
16046 if (copyout(multi_dof, user_address, dof_ioctl_data_size) != 0) {
16047 dtrace_dof_error(NULL, "failed copyout of dof_ioctl_data_t");
16048 /* Don't overwrite pre-existing error code */
16049 if (rval == 0) rval = EFAULT;
16050 }
16051
16052 cleanup:
16053 /*
16054 * If we had to allocate struct memory, free it.
16055 */
16056 if (multi_dof != NULL && !multi_dof_claimed) {
16057 kmem_free(multi_dof, dof_ioctl_data_size);
16058 }
16059
16060 return rval;
16061 }
16062
16063 case DTRACEHIOC_REMOVE: {
16064 int generation = *(int*)arg;
16065 proc_t* p = current_proc();
16066
16067 /*
16068 * Try lazy first.
16069 */
16070 int rval = dtrace_lazy_dofs_remove(p, generation);
16071
16072 /*
16073 * EACCES means non-lazy
16074 */
16075 if (rval == EACCES) {
16076 lck_mtx_lock(&dtrace_lock);
16077 rval = dtrace_helper_destroygen(p, generation);
16078 lck_mtx_unlock(&dtrace_lock);
16079 }
16080
16081 return (rval);
16082 }
16083
16084 default:
16085 break;
16086 }
16087
16088 return ENOTTY;
16089 }
16090
16091 /*ARGSUSED*/
16092 static int
16093 dtrace_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
16094 {
16095 #pragma unused(md)
16096 minor_t minor = getminor(dev);
16097 dtrace_state_t *state;
16098 int rval;
16099
16100 /* Darwin puts Helper on its own major device. */
16101
16102 state = ddi_get_soft_state(dtrace_softstate, minor);
16103
16104 if (state->dts_anon) {
16105 ASSERT(dtrace_anon.dta_state == NULL);
16106 state = state->dts_anon;
16107 }
16108
16109 switch (cmd) {
16110 case DTRACEIOC_PROVIDER: {
16111 dtrace_providerdesc_t pvd;
16112 dtrace_provider_t *pvp;
16113
16114 if (copyin(arg, &pvd, sizeof (pvd)) != 0)
16115 return (EFAULT);
16116
16117 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16118 lck_mtx_lock(&dtrace_provider_lock);
16119
16120 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16121 if (strncmp(pvp->dtpv_name, pvd.dtvd_name, DTRACE_PROVNAMELEN) == 0)
16122 break;
16123 }
16124
16125 lck_mtx_unlock(&dtrace_provider_lock);
16126
16127 if (pvp == NULL)
16128 return (ESRCH);
16129
16130 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16131 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16132 if (copyout(&pvd, arg, sizeof (pvd)) != 0)
16133 return (EFAULT);
16134
16135 return (0);
16136 }
16137
16138 case DTRACEIOC_EPROBE: {
16139 dtrace_eprobedesc_t epdesc;
16140 dtrace_ecb_t *ecb;
16141 dtrace_action_t *act;
16142 void *buf;
16143 size_t size;
16144 uintptr_t dest;
16145 int nrecs;
16146
16147 if (copyin(arg, &epdesc, sizeof (epdesc)) != 0)
16148 return (EFAULT);
16149
16150 lck_mtx_lock(&dtrace_lock);
16151
16152 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16153 lck_mtx_unlock(&dtrace_lock);
16154 return (EINVAL);
16155 }
16156
16157 if (ecb->dte_probe == NULL) {
16158 lck_mtx_unlock(&dtrace_lock);
16159 return (EINVAL);
16160 }
16161
16162 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16163 epdesc.dtepd_uarg = ecb->dte_uarg;
16164 epdesc.dtepd_size = ecb->dte_size;
16165
16166 nrecs = epdesc.dtepd_nrecs;
16167 epdesc.dtepd_nrecs = 0;
16168 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16169 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16170 continue;
16171
16172 epdesc.dtepd_nrecs++;
16173 }
16174
16175 /*
16176 * Now that we have the size, we need to allocate a temporary
16177 * buffer in which to store the complete description. We need
16178 * the temporary buffer to be able to drop dtrace_lock()
16179 * across the copyout(), below.
16180 */
16181 size = sizeof (dtrace_eprobedesc_t) +
16182 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16183
16184 buf = kmem_alloc(size, KM_SLEEP);
16185 dest = (uintptr_t)buf;
16186
16187 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16188 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16189
16190 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16191 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16192 continue;
16193
16194 if (nrecs-- == 0)
16195 break;
16196
16197 bcopy(&act->dta_rec, (void *)dest,
16198 sizeof (dtrace_recdesc_t));
16199 dest += sizeof (dtrace_recdesc_t);
16200 }
16201
16202 lck_mtx_unlock(&dtrace_lock);
16203
16204 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16205 kmem_free(buf, size);
16206 return (EFAULT);
16207 }
16208
16209 kmem_free(buf, size);
16210 return (0);
16211 }
16212
16213 case DTRACEIOC_AGGDESC: {
16214 dtrace_aggdesc_t aggdesc;
16215 dtrace_action_t *act;
16216 dtrace_aggregation_t *agg;
16217 int nrecs;
16218 uint32_t offs;
16219 dtrace_recdesc_t *lrec;
16220 void *buf;
16221 size_t size;
16222 uintptr_t dest;
16223
16224 if (copyin(arg, &aggdesc, sizeof (aggdesc)) != 0)
16225 return (EFAULT);
16226
16227 lck_mtx_lock(&dtrace_lock);
16228
16229 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16230 lck_mtx_unlock(&dtrace_lock);
16231 return (EINVAL);
16232 }
16233
16234 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16235
16236 nrecs = aggdesc.dtagd_nrecs;
16237 aggdesc.dtagd_nrecs = 0;
16238
16239 offs = agg->dtag_base;
16240 lrec = &agg->dtag_action.dta_rec;
16241 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16242
16243 for (act = agg->dtag_first; ; act = act->dta_next) {
16244 ASSERT(act->dta_intuple ||
16245 DTRACEACT_ISAGG(act->dta_kind));
16246
16247 /*
16248 * If this action has a record size of zero, it
16249 * denotes an argument to the aggregating action.
16250 * Because the presence of this record doesn't (or
16251 * shouldn't) affect the way the data is interpreted,
16252 * we don't copy it out to save user-level the
16253 * confusion of dealing with a zero-length record.
16254 */
16255 if (act->dta_rec.dtrd_size == 0) {
16256 ASSERT(agg->dtag_hasarg);
16257 continue;
16258 }
16259
16260 aggdesc.dtagd_nrecs++;
16261
16262 if (act == &agg->dtag_action)
16263 break;
16264 }
16265
16266 /*
16267 * Now that we have the size, we need to allocate a temporary
16268 * buffer in which to store the complete description. We need
16269 * the temporary buffer to be able to drop dtrace_lock()
16270 * across the copyout(), below.
16271 */
16272 size = sizeof (dtrace_aggdesc_t) +
16273 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16274
16275 buf = kmem_alloc(size, KM_SLEEP);
16276 dest = (uintptr_t)buf;
16277
16278 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16279 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16280
16281 for (act = agg->dtag_first; ; act = act->dta_next) {
16282 dtrace_recdesc_t rec = act->dta_rec;
16283
16284 /*
16285 * See the comment in the above loop for why we pass
16286 * over zero-length records.
16287 */
16288 if (rec.dtrd_size == 0) {
16289 ASSERT(agg->dtag_hasarg);
16290 continue;
16291 }
16292
16293 if (nrecs-- == 0)
16294 break;
16295
16296 rec.dtrd_offset -= offs;
16297 bcopy(&rec, (void *)dest, sizeof (rec));
16298 dest += sizeof (dtrace_recdesc_t);
16299
16300 if (act == &agg->dtag_action)
16301 break;
16302 }
16303
16304 lck_mtx_unlock(&dtrace_lock);
16305
16306 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16307 kmem_free(buf, size);
16308 return (EFAULT);
16309 }
16310
16311 kmem_free(buf, size);
16312 return (0);
16313 }
16314
16315 case DTRACEIOC_ENABLE: {
16316 dof_hdr_t *dof;
16317 dtrace_enabling_t *enab = NULL;
16318 dtrace_vstate_t *vstate;
16319 int err = 0;
16320
16321 *rv = 0;
16322
16323 /*
16324 * If a NULL argument has been passed, we take this as our
16325 * cue to reevaluate our enablings.
16326 */
16327 if (arg == 0) {
16328 dtrace_enabling_matchall();
16329
16330 return (0);
16331 }
16332
16333 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16334 return (rval);
16335
16336 lck_mtx_lock(&cpu_lock);
16337 lck_mtx_lock(&dtrace_lock);
16338 vstate = &state->dts_vstate;
16339
16340 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16341 lck_mtx_unlock(&dtrace_lock);
16342 lck_mtx_unlock(&cpu_lock);
16343 dtrace_dof_destroy(dof);
16344 return (EBUSY);
16345 }
16346
16347 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16348 lck_mtx_unlock(&dtrace_lock);
16349 lck_mtx_unlock(&cpu_lock);
16350 dtrace_dof_destroy(dof);
16351 return (EINVAL);
16352 }
16353
16354 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16355 dtrace_enabling_destroy(enab);
16356 lck_mtx_unlock(&dtrace_lock);
16357 lck_mtx_unlock(&cpu_lock);
16358 dtrace_dof_destroy(dof);
16359 return (rval);
16360 }
16361
16362 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16363 err = dtrace_enabling_retain(enab);
16364 } else {
16365 dtrace_enabling_destroy(enab);
16366 }
16367
16368 lck_mtx_unlock(&dtrace_lock);
16369 lck_mtx_unlock(&cpu_lock);
16370 dtrace_dof_destroy(dof);
16371
16372 return (err);
16373 }
16374
16375 case DTRACEIOC_REPLICATE: {
16376 dtrace_repldesc_t desc;
16377 dtrace_probedesc_t *match = &desc.dtrpd_match;
16378 dtrace_probedesc_t *create = &desc.dtrpd_create;
16379 int err;
16380
16381 if (copyin(arg, &desc, sizeof (desc)) != 0)
16382 return (EFAULT);
16383
16384 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16385 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16386 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16387 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16388
16389 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16390 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16391 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16392 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16393
16394 lck_mtx_lock(&dtrace_lock);
16395 err = dtrace_enabling_replicate(state, match, create);
16396 lck_mtx_unlock(&dtrace_lock);
16397
16398 return (err);
16399 }
16400
16401 case DTRACEIOC_PROBEMATCH:
16402 case DTRACEIOC_PROBES: {
16403 dtrace_probe_t *probe = NULL;
16404 dtrace_probedesc_t desc;
16405 dtrace_probekey_t pkey;
16406 dtrace_id_t i;
16407 int m = 0;
16408 uint32_t priv;
16409 uid_t uid;
16410 zoneid_t zoneid;
16411
16412 if (copyin(arg, &desc, sizeof (desc)) != 0)
16413 return (EFAULT);
16414
16415 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16416 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16417 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16418 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16419
16420 /*
16421 * Before we attempt to match this probe, we want to give
16422 * all providers the opportunity to provide it.
16423 */
16424 if (desc.dtpd_id == DTRACE_IDNONE) {
16425 lck_mtx_lock(&dtrace_provider_lock);
16426 dtrace_probe_provide(&desc, NULL);
16427 lck_mtx_unlock(&dtrace_provider_lock);
16428 desc.dtpd_id++;
16429 }
16430
16431 if (cmd == DTRACEIOC_PROBEMATCH) {
16432 dtrace_probekey(&desc, &pkey);
16433 pkey.dtpk_id = DTRACE_IDNONE;
16434 }
16435
16436 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16437
16438 lck_mtx_lock(&dtrace_lock);
16439
16440 if (cmd == DTRACEIOC_PROBEMATCH) {
16441 /* Quiet compiler warning */
16442 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
16443 if ((probe = dtrace_probes[i - 1]) != NULL &&
16444 (m = dtrace_match_probe(probe, &pkey,
16445 priv, uid, zoneid)) != 0)
16446 break;
16447 }
16448
16449 if (m < 0) {
16450 lck_mtx_unlock(&dtrace_lock);
16451 return (EINVAL);
16452 }
16453
16454 } else {
16455 /* Quiet compiler warning */
16456 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
16457 if ((probe = dtrace_probes[i - 1]) != NULL &&
16458 dtrace_match_priv(probe, priv, uid, zoneid))
16459 break;
16460 }
16461 }
16462
16463 if (probe == NULL) {
16464 lck_mtx_unlock(&dtrace_lock);
16465 return (ESRCH);
16466 }
16467
16468 dtrace_probe_description(probe, &desc);
16469 lck_mtx_unlock(&dtrace_lock);
16470
16471 if (copyout(&desc, arg, sizeof (desc)) != 0)
16472 return (EFAULT);
16473
16474 return (0);
16475 }
16476
16477 case DTRACEIOC_PROBEARG: {
16478 dtrace_argdesc_t desc;
16479 dtrace_probe_t *probe;
16480 dtrace_provider_t *prov;
16481
16482 if (copyin(arg, &desc, sizeof (desc)) != 0)
16483 return (EFAULT);
16484
16485 if (desc.dtargd_id == DTRACE_IDNONE)
16486 return (EINVAL);
16487
16488 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16489 return (EINVAL);
16490
16491 lck_mtx_lock(&dtrace_provider_lock);
16492 lck_mtx_lock(&mod_lock);
16493 lck_mtx_lock(&dtrace_lock);
16494
16495 /* Quiet compiler warning */
16496 if (desc.dtargd_id > (dtrace_id_t)dtrace_nprobes) {
16497 lck_mtx_unlock(&dtrace_lock);
16498 lck_mtx_unlock(&mod_lock);
16499 lck_mtx_unlock(&dtrace_provider_lock);
16500 return (EINVAL);
16501 }
16502
16503 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16504 lck_mtx_unlock(&dtrace_lock);
16505 lck_mtx_unlock(&mod_lock);
16506 lck_mtx_unlock(&dtrace_provider_lock);
16507 return (EINVAL);
16508 }
16509
16510 lck_mtx_unlock(&dtrace_lock);
16511
16512 prov = probe->dtpr_provider;
16513
16514 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16515 /*
16516 * There isn't any typed information for this probe.
16517 * Set the argument number to DTRACE_ARGNONE.
16518 */
16519 desc.dtargd_ndx = DTRACE_ARGNONE;
16520 } else {
16521 desc.dtargd_native[0] = '\0';
16522 desc.dtargd_xlate[0] = '\0';
16523 desc.dtargd_mapping = desc.dtargd_ndx;
16524
16525 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16526 probe->dtpr_id, probe->dtpr_arg, &desc);
16527 }
16528
16529 lck_mtx_unlock(&mod_lock);
16530 lck_mtx_unlock(&dtrace_provider_lock);
16531
16532 if (copyout(&desc, arg, sizeof (desc)) != 0)
16533 return (EFAULT);
16534
16535 return (0);
16536 }
16537
16538 case DTRACEIOC_GO: {
16539 processorid_t cpuid;
16540 rval = dtrace_state_go(state, &cpuid);
16541
16542 if (rval != 0)
16543 return (rval);
16544
16545 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
16546 return (EFAULT);
16547
16548 return (0);
16549 }
16550
16551 case DTRACEIOC_STOP: {
16552 processorid_t cpuid;
16553
16554 lck_mtx_lock(&dtrace_lock);
16555 rval = dtrace_state_stop(state, &cpuid);
16556 lck_mtx_unlock(&dtrace_lock);
16557
16558 if (rval != 0)
16559 return (rval);
16560
16561 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
16562 return (EFAULT);
16563
16564 return (0);
16565 }
16566
16567 case DTRACEIOC_DOFGET: {
16568 dof_hdr_t hdr, *dof;
16569 uint64_t len;
16570
16571 if (copyin(arg, &hdr, sizeof (hdr)) != 0)
16572 return (EFAULT);
16573
16574 lck_mtx_lock(&dtrace_lock);
16575 dof = dtrace_dof_create(state);
16576 lck_mtx_unlock(&dtrace_lock);
16577
16578 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16579 rval = copyout(dof, arg, len);
16580 dtrace_dof_destroy(dof);
16581
16582 return (rval == 0 ? 0 : EFAULT);
16583 }
16584
16585 case DTRACEIOC_AGGSNAP:
16586 case DTRACEIOC_BUFSNAP: {
16587 dtrace_bufdesc_t desc;
16588 caddr_t cached;
16589 dtrace_buffer_t *buf;
16590
16591 if (copyin(arg, &desc, sizeof (desc)) != 0)
16592 return (EFAULT);
16593
16594 if ((int)desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16595 return (EINVAL);
16596
16597 lck_mtx_lock(&dtrace_lock);
16598
16599 if (cmd == DTRACEIOC_BUFSNAP) {
16600 buf = &state->dts_buffer[desc.dtbd_cpu];
16601 } else {
16602 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16603 }
16604
16605 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16606 size_t sz = buf->dtb_offset;
16607
16608 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16609 lck_mtx_unlock(&dtrace_lock);
16610 return (EBUSY);
16611 }
16612
16613 /*
16614 * If this buffer has already been consumed, we're
16615 * going to indicate that there's nothing left here
16616 * to consume.
16617 */
16618 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16619 lck_mtx_unlock(&dtrace_lock);
16620
16621 desc.dtbd_size = 0;
16622 desc.dtbd_drops = 0;
16623 desc.dtbd_errors = 0;
16624 desc.dtbd_oldest = 0;
16625 sz = sizeof (desc);
16626
16627 if (copyout(&desc, arg, sz) != 0)
16628 return (EFAULT);
16629
16630 return (0);
16631 }
16632
16633 /*
16634 * If this is a ring buffer that has wrapped, we want
16635 * to copy the whole thing out.
16636 */
16637 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16638 dtrace_buffer_polish(buf);
16639 sz = buf->dtb_size;
16640 }
16641
16642 if (copyout(buf->dtb_tomax, (user_addr_t)desc.dtbd_data, sz) != 0) {
16643 lck_mtx_unlock(&dtrace_lock);
16644 return (EFAULT);
16645 }
16646
16647 desc.dtbd_size = sz;
16648 desc.dtbd_drops = buf->dtb_drops;
16649 desc.dtbd_errors = buf->dtb_errors;
16650 desc.dtbd_oldest = buf->dtb_xamot_offset;
16651 desc.dtbd_timestamp = dtrace_gethrtime();
16652
16653 lck_mtx_unlock(&dtrace_lock);
16654
16655 if (copyout(&desc, arg, sizeof (desc)) != 0)
16656 return (EFAULT);
16657
16658 buf->dtb_flags |= DTRACEBUF_CONSUMED;
16659
16660 return (0);
16661 }
16662
16663 if (buf->dtb_tomax == NULL) {
16664 ASSERT(buf->dtb_xamot == NULL);
16665 lck_mtx_unlock(&dtrace_lock);
16666 return (ENOENT);
16667 }
16668
16669 cached = buf->dtb_tomax;
16670 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16671
16672 dtrace_xcall(desc.dtbd_cpu,
16673 (dtrace_xcall_t)dtrace_buffer_switch, buf);
16674
16675 state->dts_errors += buf->dtb_xamot_errors;
16676
16677 /*
16678 * If the buffers did not actually switch, then the cross call
16679 * did not take place -- presumably because the given CPU is
16680 * not in the ready set. If this is the case, we'll return
16681 * ENOENT.
16682 */
16683 if (buf->dtb_tomax == cached) {
16684 ASSERT(buf->dtb_xamot != cached);
16685 lck_mtx_unlock(&dtrace_lock);
16686 return (ENOENT);
16687 }
16688
16689 ASSERT(cached == buf->dtb_xamot);
16690
16691 /*
16692 * We have our snapshot; now copy it out.
16693 */
16694 if (copyout(buf->dtb_xamot, (user_addr_t)desc.dtbd_data,
16695 buf->dtb_xamot_offset) != 0) {
16696 lck_mtx_unlock(&dtrace_lock);
16697 return (EFAULT);
16698 }
16699
16700 desc.dtbd_size = buf->dtb_xamot_offset;
16701 desc.dtbd_drops = buf->dtb_xamot_drops;
16702 desc.dtbd_errors = buf->dtb_xamot_errors;
16703 desc.dtbd_oldest = 0;
16704 desc.dtbd_timestamp = buf->dtb_switched;
16705
16706 lck_mtx_unlock(&dtrace_lock);
16707
16708 /*
16709 * Finally, copy out the buffer description.
16710 */
16711 if (copyout(&desc, arg, sizeof (desc)) != 0)
16712 return (EFAULT);
16713
16714 return (0);
16715 }
16716
16717 case DTRACEIOC_CONF: {
16718 dtrace_conf_t conf;
16719
16720 bzero(&conf, sizeof (conf));
16721 conf.dtc_difversion = DIF_VERSION;
16722 conf.dtc_difintregs = DIF_DIR_NREGS;
16723 conf.dtc_diftupregs = DIF_DTR_NREGS;
16724 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16725
16726 if (copyout(&conf, arg, sizeof (conf)) != 0)
16727 return (EFAULT);
16728
16729 return (0);
16730 }
16731
16732 case DTRACEIOC_STATUS: {
16733 dtrace_status_t stat;
16734 dtrace_dstate_t *dstate;
16735 int i, j;
16736 uint64_t nerrs;
16737
16738 /*
16739 * See the comment in dtrace_state_deadman() for the reason
16740 * for setting dts_laststatus to INT64_MAX before setting
16741 * it to the correct value.
16742 */
16743 state->dts_laststatus = INT64_MAX;
16744 dtrace_membar_producer();
16745 state->dts_laststatus = dtrace_gethrtime();
16746
16747 bzero(&stat, sizeof (stat));
16748
16749 lck_mtx_lock(&dtrace_lock);
16750
16751 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16752 lck_mtx_unlock(&dtrace_lock);
16753 return (ENOENT);
16754 }
16755
16756 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16757 stat.dtst_exiting = 1;
16758
16759 nerrs = state->dts_errors;
16760 dstate = &state->dts_vstate.dtvs_dynvars;
16761
16762 for (i = 0; i < (int)NCPU; i++) {
16763 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16764
16765 stat.dtst_dyndrops += dcpu->dtdsc_drops;
16766 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16767 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16768
16769 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16770 stat.dtst_filled++;
16771
16772 nerrs += state->dts_buffer[i].dtb_errors;
16773
16774 for (j = 0; j < state->dts_nspeculations; j++) {
16775 dtrace_speculation_t *spec;
16776 dtrace_buffer_t *buf;
16777
16778 spec = &state->dts_speculations[j];
16779 buf = &spec->dtsp_buffer[i];
16780 stat.dtst_specdrops += buf->dtb_xamot_drops;
16781 }
16782 }
16783
16784 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16785 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16786 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16787 stat.dtst_dblerrors = state->dts_dblerrors;
16788 stat.dtst_killed =
16789 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16790 stat.dtst_errors = nerrs;
16791
16792 lck_mtx_unlock(&dtrace_lock);
16793
16794 if (copyout(&stat, arg, sizeof (stat)) != 0)
16795 return (EFAULT);
16796
16797 return (0);
16798 }
16799
16800 case DTRACEIOC_FORMAT: {
16801 dtrace_fmtdesc_t fmt;
16802 char *str;
16803 int len;
16804
16805 if (copyin(arg, &fmt, sizeof (fmt)) != 0)
16806 return (EFAULT);
16807
16808 lck_mtx_lock(&dtrace_lock);
16809
16810 if (fmt.dtfd_format == 0 ||
16811 fmt.dtfd_format > state->dts_nformats) {
16812 lck_mtx_unlock(&dtrace_lock);
16813 return (EINVAL);
16814 }
16815
16816 /*
16817 * Format strings are allocated contiguously and they are
16818 * never freed; if a format index is less than the number
16819 * of formats, we can assert that the format map is non-NULL
16820 * and that the format for the specified index is non-NULL.
16821 */
16822 ASSERT(state->dts_formats != NULL);
16823 str = state->dts_formats[fmt.dtfd_format - 1];
16824 ASSERT(str != NULL);
16825
16826 len = strlen(str) + 1;
16827
16828 if (len > fmt.dtfd_length) {
16829 fmt.dtfd_length = len;
16830
16831 if (copyout(&fmt, arg, sizeof (fmt)) != 0) {
16832 lck_mtx_unlock(&dtrace_lock);
16833 return (EINVAL);
16834 }
16835 } else {
16836 if (copyout(str, (user_addr_t)fmt.dtfd_string, len) != 0) {
16837 lck_mtx_unlock(&dtrace_lock);
16838 return (EINVAL);
16839 }
16840 }
16841
16842 lck_mtx_unlock(&dtrace_lock);
16843 return (0);
16844 }
16845
16846 case DTRACEIOC_MODUUIDSLIST: {
16847 size_t module_uuids_list_size;
16848 dtrace_module_uuids_list_t* uuids_list;
16849 uint64_t dtmul_count;
16850
16851 /*
16852 * Security restrictions make this operation illegal, if this is enabled DTrace
16853 * must refuse to provide any fbt probes.
16854 */
16855 if (dtrace_is_restricted()) {
16856 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
16857 return (EPERM);
16858 }
16859
16860 /*
16861 * Fail if the kernel symbol mode makes this operation illegal.
16862 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
16863 * for them without holding the dtrace_lock.
16864 */
16865 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
16866 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
16867 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_MODUUIDSLIST", dtrace_kernel_symbol_mode);
16868 return (EPERM);
16869 }
16870
16871 /*
16872 * Read the number of symbolsdesc structs being passed in.
16873 */
16874 if (copyin(arg + offsetof(dtrace_module_uuids_list_t, dtmul_count),
16875 &dtmul_count,
16876 sizeof(dtmul_count))) {
16877 cmn_err(CE_WARN, "failed to copyin dtmul_count");
16878 return (EFAULT);
16879 }
16880
16881 /*
16882 * Range check the count. More than 2k kexts is probably an error.
16883 */
16884 if (dtmul_count > 2048) {
16885 cmn_err(CE_WARN, "dtmul_count is not valid");
16886 return (EINVAL);
16887 }
16888
16889 /*
16890 * For all queries, we return EINVAL when the user specified
16891 * count does not match the actual number of modules we find
16892 * available.
16893 *
16894 * If the user specified count is zero, then this serves as a
16895 * simple query to count the available modules in need of symbols.
16896 */
16897
16898 rval = 0;
16899
16900 if (dtmul_count == 0)
16901 {
16902 lck_mtx_lock(&mod_lock);
16903 struct modctl* ctl = dtrace_modctl_list;
16904 while (ctl) {
16905 /* Update the private probes bit */
16906 if (dtrace_provide_private_probes)
16907 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
16908
16909 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
16910 if (!MOD_SYMBOLS_DONE(ctl)) {
16911 dtmul_count++;
16912 rval = EINVAL;
16913 }
16914 ctl = ctl->mod_next;
16915 }
16916 lck_mtx_unlock(&mod_lock);
16917
16918 if (copyout(&dtmul_count, arg, sizeof (dtmul_count)) != 0)
16919 return (EFAULT);
16920 else
16921 return (rval);
16922 }
16923
16924 /*
16925 * If we reach this point, then we have a request for full list data.
16926 * Allocate a correctly sized structure and copyin the data.
16927 */
16928 module_uuids_list_size = DTRACE_MODULE_UUIDS_LIST_SIZE(dtmul_count);
16929 if ((uuids_list = kmem_alloc(module_uuids_list_size, KM_SLEEP)) == NULL)
16930 return (ENOMEM);
16931
16932 /* NOTE! We can no longer exit this method via return */
16933 if (copyin(arg, uuids_list, module_uuids_list_size) != 0) {
16934 cmn_err(CE_WARN, "failed copyin of dtrace_module_uuids_list_t");
16935 rval = EFAULT;
16936 goto moduuidslist_cleanup;
16937 }
16938
16939 /*
16940 * Check that the count didn't change between the first copyin and the second.
16941 */
16942 if (uuids_list->dtmul_count != dtmul_count) {
16943 rval = EINVAL;
16944 goto moduuidslist_cleanup;
16945 }
16946
16947 /*
16948 * Build the list of UUID's that need symbols
16949 */
16950 lck_mtx_lock(&mod_lock);
16951
16952 dtmul_count = 0;
16953
16954 struct modctl* ctl = dtrace_modctl_list;
16955 while (ctl) {
16956 /* Update the private probes bit */
16957 if (dtrace_provide_private_probes)
16958 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
16959
16960 /*
16961 * We assume that userspace symbols will be "better" than kernel level symbols,
16962 * as userspace can search for dSYM(s) and symbol'd binaries. Even if kernel syms
16963 * are available, add user syms if the module might use them.
16964 */
16965 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
16966 if (!MOD_SYMBOLS_DONE(ctl)) {
16967 UUID* uuid = &uuids_list->dtmul_uuid[dtmul_count];
16968 if (dtmul_count++ < uuids_list->dtmul_count) {
16969 memcpy(uuid, ctl->mod_uuid, sizeof(UUID));
16970 }
16971 }
16972 ctl = ctl->mod_next;
16973 }
16974
16975 lck_mtx_unlock(&mod_lock);
16976
16977 if (uuids_list->dtmul_count < dtmul_count)
16978 rval = EINVAL;
16979
16980 uuids_list->dtmul_count = dtmul_count;
16981
16982 /*
16983 * Copyout the symbols list (or at least the count!)
16984 */
16985 if (copyout(uuids_list, arg, module_uuids_list_size) != 0) {
16986 cmn_err(CE_WARN, "failed copyout of dtrace_symbolsdesc_list_t");
16987 rval = EFAULT;
16988 }
16989
16990 moduuidslist_cleanup:
16991 /*
16992 * If we had to allocate struct memory, free it.
16993 */
16994 if (uuids_list != NULL) {
16995 kmem_free(uuids_list, module_uuids_list_size);
16996 }
16997
16998 return rval;
16999 }
17000
17001 case DTRACEIOC_PROVMODSYMS: {
17002 size_t module_symbols_size;
17003 dtrace_module_symbols_t* module_symbols;
17004 uint64_t dtmodsyms_count;
17005
17006 /*
17007 * Security restrictions make this operation illegal, if this is enabled DTrace
17008 * must refuse to provide any fbt probes.
17009 */
17010 if (dtrace_is_restricted()) {
17011 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
17012 return (EPERM);
17013 }
17014
17015 /*
17016 * Fail if the kernel symbol mode makes this operation illegal.
17017 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
17018 * for them without holding the dtrace_lock.
17019 */
17020 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
17021 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
17022 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_PROVMODSYMS", dtrace_kernel_symbol_mode);
17023 return (EPERM);
17024 }
17025
17026 /*
17027 * Read the number of module symbols structs being passed in.
17028 */
17029 if (copyin(arg + offsetof(dtrace_module_symbols_t, dtmodsyms_count),
17030 &dtmodsyms_count,
17031 sizeof(dtmodsyms_count))) {
17032 cmn_err(CE_WARN, "failed to copyin dtmodsyms_count");
17033 return (EFAULT);
17034 }
17035
17036 /*
17037 * Range check the count. How much data can we pass around?
17038 * FIX ME!
17039 */
17040 if (dtmodsyms_count == 0 || (dtmodsyms_count > 100 * 1024)) {
17041 cmn_err(CE_WARN, "dtmodsyms_count is not valid");
17042 return (EINVAL);
17043 }
17044
17045 /*
17046 * Allocate a correctly sized structure and copyin the data.
17047 */
17048 module_symbols_size = DTRACE_MODULE_SYMBOLS_SIZE(dtmodsyms_count);
17049 if ((module_symbols = kmem_alloc(module_symbols_size, KM_SLEEP)) == NULL)
17050 return (ENOMEM);
17051
17052 rval = 0;
17053
17054 /* NOTE! We can no longer exit this method via return */
17055 if (copyin(arg, module_symbols, module_symbols_size) != 0) {
17056 cmn_err(CE_WARN, "failed copyin of dtrace_module_symbols_t, symbol count %llu", module_symbols->dtmodsyms_count);
17057 rval = EFAULT;
17058 goto module_symbols_cleanup;
17059 }
17060
17061 /*
17062 * Check that the count didn't change between the first copyin and the second.
17063 */
17064 if (module_symbols->dtmodsyms_count != dtmodsyms_count) {
17065 rval = EINVAL;
17066 goto module_symbols_cleanup;
17067 }
17068
17069 /*
17070 * Find the modctl to add symbols to.
17071 */
17072 lck_mtx_lock(&dtrace_provider_lock);
17073 lck_mtx_lock(&mod_lock);
17074
17075 struct modctl* ctl = dtrace_modctl_list;
17076 while (ctl) {
17077 /* Update the private probes bit */
17078 if (dtrace_provide_private_probes)
17079 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17080
17081 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17082 if (MOD_HAS_UUID(ctl) && !MOD_SYMBOLS_DONE(ctl)) {
17083 if (memcmp(module_symbols->dtmodsyms_uuid, ctl->mod_uuid, sizeof(UUID)) == 0) {
17084 /* BINGO! */
17085 ctl->mod_user_symbols = module_symbols;
17086 break;
17087 }
17088 }
17089 ctl = ctl->mod_next;
17090 }
17091
17092 if (ctl) {
17093 dtrace_provider_t *prv;
17094
17095 /*
17096 * We're going to call each providers per-module provide operation
17097 * specifying only this module.
17098 */
17099 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
17100 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
17101
17102 /*
17103 * We gave every provider a chance to provide with the user syms, go ahead and clear them
17104 */
17105 ctl->mod_user_symbols = NULL; /* MUST reset this to clear HAS_USERSPACE_SYMBOLS */
17106 }
17107
17108 lck_mtx_unlock(&mod_lock);
17109 lck_mtx_unlock(&dtrace_provider_lock);
17110
17111 module_symbols_cleanup:
17112 /*
17113 * If we had to allocate struct memory, free it.
17114 */
17115 if (module_symbols != NULL) {
17116 kmem_free(module_symbols, module_symbols_size);
17117 }
17118
17119 return rval;
17120 }
17121
17122 case DTRACEIOC_PROCWAITFOR: {
17123 dtrace_procdesc_t pdesc = {
17124 .p_comm = {0},
17125 .p_pid = -1
17126 };
17127
17128 if ((rval = copyin(arg, &pdesc, sizeof(pdesc))) != 0)
17129 goto proc_waitfor_error;
17130
17131 if ((rval = dtrace_proc_waitfor(&pdesc)) != 0)
17132 goto proc_waitfor_error;
17133
17134 if ((rval = copyout(&pdesc, arg, sizeof(pdesc))) != 0)
17135 goto proc_waitfor_error;
17136
17137 return 0;
17138
17139 proc_waitfor_error:
17140 /* The process was suspended, revert this since the client will not do it. */
17141 if (pdesc.p_pid != -1) {
17142 proc_t *proc = proc_find(pdesc.p_pid);
17143 if (proc != PROC_NULL) {
17144 task_pidresume(proc->task);
17145 proc_rele(proc);
17146 }
17147 }
17148
17149 return rval;
17150 }
17151
17152 default:
17153 break;
17154 }
17155
17156 return (ENOTTY);
17157 }
17158
17159 /*
17160 * APPLE NOTE: dtrace_detach not implemented
17161 */
17162 #if !defined(__APPLE__)
17163 /*ARGSUSED*/
17164 static int
17165 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17166 {
17167 dtrace_state_t *state;
17168
17169 switch (cmd) {
17170 case DDI_DETACH:
17171 break;
17172
17173 case DDI_SUSPEND:
17174 return (DDI_SUCCESS);
17175
17176 default:
17177 return (DDI_FAILURE);
17178 }
17179
17180 lck_mtx_lock(&cpu_lock);
17181 lck_mtx_lock(&dtrace_provider_lock);
17182 lck_mtx_lock(&dtrace_lock);
17183
17184 ASSERT(dtrace_opens == 0);
17185
17186 if (dtrace_helpers > 0) {
17187 lck_mtx_unlock(&dtrace_lock);
17188 lck_mtx_unlock(&dtrace_provider_lock);
17189 lck_mtx_unlock(&cpu_lock);
17190 return (DDI_FAILURE);
17191 }
17192
17193 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17194 lck_mtx_unlock(&dtrace_lock);
17195 lck_mtx_unlock(&dtrace_provider_lock);
17196 lck_mtx_unlock(&cpu_lock);
17197 return (DDI_FAILURE);
17198 }
17199
17200 dtrace_provider = NULL;
17201
17202 if ((state = dtrace_anon_grab()) != NULL) {
17203 /*
17204 * If there were ECBs on this state, the provider should
17205 * have not been allowed to detach; assert that there is
17206 * none.
17207 */
17208 ASSERT(state->dts_necbs == 0);
17209 dtrace_state_destroy(state);
17210
17211 /*
17212 * If we're being detached with anonymous state, we need to
17213 * indicate to the kernel debugger that DTrace is now inactive.
17214 */
17215 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17216 }
17217
17218 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17219 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17220 dtrace_cpu_init = NULL;
17221 dtrace_helpers_cleanup = NULL;
17222 dtrace_helpers_fork = NULL;
17223 dtrace_cpustart_init = NULL;
17224 dtrace_cpustart_fini = NULL;
17225 dtrace_debugger_init = NULL;
17226 dtrace_debugger_fini = NULL;
17227 dtrace_kreloc_init = NULL;
17228 dtrace_kreloc_fini = NULL;
17229 dtrace_modload = NULL;
17230 dtrace_modunload = NULL;
17231
17232 lck_mtx_unlock(&cpu_lock);
17233
17234 if (dtrace_helptrace_enabled) {
17235 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17236 dtrace_helptrace_buffer = NULL;
17237 }
17238
17239 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17240 dtrace_probes = NULL;
17241 dtrace_nprobes = 0;
17242
17243 dtrace_hash_destroy(dtrace_bymod);
17244 dtrace_hash_destroy(dtrace_byfunc);
17245 dtrace_hash_destroy(dtrace_byname);
17246 dtrace_bymod = NULL;
17247 dtrace_byfunc = NULL;
17248 dtrace_byname = NULL;
17249
17250 kmem_cache_destroy(dtrace_state_cache);
17251 vmem_destroy(dtrace_minor);
17252 vmem_destroy(dtrace_arena);
17253
17254 if (dtrace_toxrange != NULL) {
17255 kmem_free(dtrace_toxrange,
17256 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17257 dtrace_toxrange = NULL;
17258 dtrace_toxranges = 0;
17259 dtrace_toxranges_max = 0;
17260 }
17261
17262 ddi_remove_minor_node(dtrace_devi, NULL);
17263 dtrace_devi = NULL;
17264
17265 ddi_soft_state_fini(&dtrace_softstate);
17266
17267 ASSERT(dtrace_vtime_references == 0);
17268 ASSERT(dtrace_opens == 0);
17269 ASSERT(dtrace_retained == NULL);
17270
17271 lck_mtx_unlock(&dtrace_lock);
17272 lck_mtx_unlock(&dtrace_provider_lock);
17273
17274 /*
17275 * We don't destroy the task queue until after we have dropped our
17276 * locks (taskq_destroy() may block on running tasks). To prevent
17277 * attempting to do work after we have effectively detached but before
17278 * the task queue has been destroyed, all tasks dispatched via the
17279 * task queue must check that DTrace is still attached before
17280 * performing any operation.
17281 */
17282 taskq_destroy(dtrace_taskq);
17283 dtrace_taskq = NULL;
17284
17285 return (DDI_SUCCESS);
17286 }
17287 #endif /* __APPLE__ */
17288
17289 d_open_t _dtrace_open, helper_open;
17290 d_close_t _dtrace_close, helper_close;
17291 d_ioctl_t _dtrace_ioctl, helper_ioctl;
17292
17293 int
17294 _dtrace_open(dev_t dev, int flags, int devtype, struct proc *p)
17295 {
17296 #pragma unused(p)
17297 dev_t locdev = dev;
17298
17299 return dtrace_open( &locdev, flags, devtype, CRED());
17300 }
17301
17302 int
17303 helper_open(dev_t dev, int flags, int devtype, struct proc *p)
17304 {
17305 #pragma unused(dev,flags,devtype,p)
17306 return 0;
17307 }
17308
17309 int
17310 _dtrace_close(dev_t dev, int flags, int devtype, struct proc *p)
17311 {
17312 #pragma unused(p)
17313 return dtrace_close( dev, flags, devtype, CRED());
17314 }
17315
17316 int
17317 helper_close(dev_t dev, int flags, int devtype, struct proc *p)
17318 {
17319 #pragma unused(dev,flags,devtype,p)
17320 return 0;
17321 }
17322
17323 int
17324 _dtrace_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
17325 {
17326 #pragma unused(p)
17327 int err, rv = 0;
17328 user_addr_t uaddrp;
17329
17330 if (proc_is64bit(p))
17331 uaddrp = *(user_addr_t *)data;
17332 else
17333 uaddrp = (user_addr_t) *(uint32_t *)data;
17334
17335 err = dtrace_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
17336
17337 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
17338 if (err != 0) {
17339 ASSERT( (err & 0xfffff000) == 0 );
17340 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
17341 } else if (rv != 0) {
17342 ASSERT( (rv & 0xfff00000) == 0 );
17343 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
17344 } else
17345 return 0;
17346 }
17347
17348 int
17349 helper_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
17350 {
17351 #pragma unused(dev,fflag,p)
17352 int err, rv = 0;
17353
17354 err = dtrace_ioctl_helper(cmd, data, &rv);
17355 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
17356 if (err != 0) {
17357 ASSERT( (err & 0xfffff000) == 0 );
17358 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
17359 } else if (rv != 0) {
17360 ASSERT( (rv & 0xfff00000) == 0 );
17361 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
17362 } else
17363 return 0;
17364 }
17365
17366 #define HELPER_MAJOR -24 /* let the kernel pick the device number */
17367
17368 /*
17369 * A struct describing which functions will get invoked for certain
17370 * actions.
17371 */
17372 static struct cdevsw helper_cdevsw =
17373 {
17374 helper_open, /* open */
17375 helper_close, /* close */
17376 eno_rdwrt, /* read */
17377 eno_rdwrt, /* write */
17378 helper_ioctl, /* ioctl */
17379 (stop_fcn_t *)nulldev, /* stop */
17380 (reset_fcn_t *)nulldev, /* reset */
17381 NULL, /* tty's */
17382 eno_select, /* select */
17383 eno_mmap, /* mmap */
17384 eno_strat, /* strategy */
17385 eno_getc, /* getc */
17386 eno_putc, /* putc */
17387 0 /* type */
17388 };
17389
17390 static int helper_majdevno = 0;
17391
17392 static int gDTraceInited = 0;
17393
17394 void
17395 helper_init( void )
17396 {
17397 /*
17398 * Once the "helper" is initialized, it can take ioctl calls that use locks
17399 * and zones initialized in dtrace_init. Make certain dtrace_init was called
17400 * before us.
17401 */
17402
17403 if (!gDTraceInited) {
17404 panic("helper_init before dtrace_init\n");
17405 }
17406
17407 if (0 >= helper_majdevno)
17408 {
17409 helper_majdevno = cdevsw_add(HELPER_MAJOR, &helper_cdevsw);
17410
17411 if (helper_majdevno < 0) {
17412 printf("helper_init: failed to allocate a major number!\n");
17413 return;
17414 }
17415
17416 if (NULL == devfs_make_node( makedev(helper_majdevno, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
17417 DTRACEMNR_HELPER, 0 )) {
17418 printf("dtrace_init: failed to devfs_make_node for helper!\n");
17419 return;
17420 }
17421 } else
17422 panic("helper_init: called twice!\n");
17423 }
17424
17425 #undef HELPER_MAJOR
17426
17427 /*
17428 * Called with DEVFS_LOCK held, so vmem_alloc's underlying blist structures are protected.
17429 */
17430 static int
17431 dtrace_clone_func(dev_t dev, int action)
17432 {
17433 #pragma unused(dev)
17434
17435 if (action == DEVFS_CLONE_ALLOC) {
17436 if (NULL == dtrace_minor) /* Arena not created yet!?! */
17437 return 0;
17438 else {
17439 /*
17440 * Propose a minor number, namely the next number that vmem_alloc() will return.
17441 * Immediately put it back in play by calling vmem_free(). FIXME.
17442 */
17443 int ret = (int)(uintptr_t)vmem_alloc(dtrace_minor, 1, VM_BESTFIT | VM_SLEEP);
17444
17445 vmem_free(dtrace_minor, (void *)(uintptr_t)ret, 1);
17446
17447 return ret;
17448 }
17449 }
17450 else if (action == DEVFS_CLONE_FREE) {
17451 return 0;
17452 }
17453 else return -1;
17454 }
17455
17456 #define DTRACE_MAJOR -24 /* let the kernel pick the device number */
17457
17458 static struct cdevsw dtrace_cdevsw =
17459 {
17460 _dtrace_open, /* open */
17461 _dtrace_close, /* close */
17462 eno_rdwrt, /* read */
17463 eno_rdwrt, /* write */
17464 _dtrace_ioctl, /* ioctl */
17465 (stop_fcn_t *)nulldev, /* stop */
17466 (reset_fcn_t *)nulldev, /* reset */
17467 NULL, /* tty's */
17468 eno_select, /* select */
17469 eno_mmap, /* mmap */
17470 eno_strat, /* strategy */
17471 eno_getc, /* getc */
17472 eno_putc, /* putc */
17473 0 /* type */
17474 };
17475
17476 lck_attr_t* dtrace_lck_attr;
17477 lck_grp_attr_t* dtrace_lck_grp_attr;
17478 lck_grp_t* dtrace_lck_grp;
17479
17480 static int gMajDevNo;
17481
17482 void
17483 dtrace_init( void )
17484 {
17485 if (0 == gDTraceInited) {
17486 int i, ncpu;
17487 size_t size = sizeof(dtrace_buffer_memory_maxsize);
17488
17489 /*
17490 * DTrace allocates buffers based on the maximum number
17491 * of enabled cpus. This call avoids any race when finding
17492 * that count.
17493 */
17494 ASSERT(dtrace_max_cpus == 0);
17495 ncpu = dtrace_max_cpus = ml_get_max_cpus();
17496
17497 /*
17498 * Retrieve the size of the physical memory in order to define
17499 * the state buffer memory maximal size. If we cannot retrieve
17500 * this value, we'll consider that we have 1Gb of memory per CPU, that's
17501 * still better than raising a kernel panic.
17502 */
17503 if (0 != kernel_sysctlbyname("hw.memsize", &dtrace_buffer_memory_maxsize,
17504 &size, NULL, 0))
17505 {
17506 dtrace_buffer_memory_maxsize = ncpu * 1024 * 1024 * 1024;
17507 printf("dtrace_init: failed to retrieve the hw.memsize, defaulted to %lld bytes\n",
17508 dtrace_buffer_memory_maxsize);
17509 }
17510
17511 /*
17512 * Finally, divide by three to prevent DTrace from eating too
17513 * much memory.
17514 */
17515 dtrace_buffer_memory_maxsize /= 3;
17516 ASSERT(dtrace_buffer_memory_maxsize > 0);
17517
17518 gMajDevNo = cdevsw_add(DTRACE_MAJOR, &dtrace_cdevsw);
17519
17520 if (gMajDevNo < 0) {
17521 printf("dtrace_init: failed to allocate a major number!\n");
17522 gDTraceInited = 0;
17523 return;
17524 }
17525
17526 if (NULL == devfs_make_node_clone( makedev(gMajDevNo, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
17527 dtrace_clone_func, DTRACEMNR_DTRACE, 0 )) {
17528 printf("dtrace_init: failed to devfs_make_node_clone for dtrace!\n");
17529 gDTraceInited = 0;
17530 return;
17531 }
17532
17533 #if defined(DTRACE_MEMORY_ZONES)
17534 /*
17535 * Initialize the dtrace kalloc-emulation zones.
17536 */
17537 dtrace_alloc_init();
17538 #endif /* DTRACE_MEMORY_ZONES */
17539
17540 /*
17541 * Allocate the dtrace_probe_t zone
17542 */
17543 dtrace_probe_t_zone = zinit(sizeof(dtrace_probe_t),
17544 1024 * sizeof(dtrace_probe_t),
17545 sizeof(dtrace_probe_t),
17546 "dtrace.dtrace_probe_t");
17547
17548 /*
17549 * Create the dtrace lock group and attrs.
17550 */
17551 dtrace_lck_attr = lck_attr_alloc_init();
17552 dtrace_lck_grp_attr= lck_grp_attr_alloc_init();
17553 dtrace_lck_grp = lck_grp_alloc_init("dtrace", dtrace_lck_grp_attr);
17554
17555 /*
17556 * We have to initialize all locks explicitly
17557 */
17558 lck_mtx_init(&dtrace_lock, dtrace_lck_grp, dtrace_lck_attr);
17559 lck_mtx_init(&dtrace_provider_lock, dtrace_lck_grp, dtrace_lck_attr);
17560 lck_mtx_init(&dtrace_meta_lock, dtrace_lck_grp, dtrace_lck_attr);
17561 lck_mtx_init(&dtrace_procwaitfor_lock, dtrace_lck_grp, dtrace_lck_attr);
17562 #if DEBUG
17563 lck_mtx_init(&dtrace_errlock, dtrace_lck_grp, dtrace_lck_attr);
17564 #endif
17565 lck_rw_init(&dtrace_dof_mode_lock, dtrace_lck_grp, dtrace_lck_attr);
17566
17567 /*
17568 * The cpu_core structure consists of per-CPU state available in any context.
17569 * On some architectures, this may mean that the page(s) containing the
17570 * NCPU-sized array of cpu_core structures must be locked in the TLB -- it
17571 * is up to the platform to assure that this is performed properly. Note that
17572 * the structure is sized to avoid false sharing.
17573 */
17574 lck_mtx_init(&cpu_lock, dtrace_lck_grp, dtrace_lck_attr);
17575 lck_mtx_init(&cyc_lock, dtrace_lck_grp, dtrace_lck_attr);
17576 lck_mtx_init(&mod_lock, dtrace_lck_grp, dtrace_lck_attr);
17577
17578 /*
17579 * Initialize the CPU offline/online hooks.
17580 */
17581 dtrace_install_cpu_hooks();
17582
17583 dtrace_modctl_list = NULL;
17584
17585 cpu_core = (cpu_core_t *)kmem_zalloc( ncpu * sizeof(cpu_core_t), KM_SLEEP );
17586 for (i = 0; i < ncpu; ++i) {
17587 lck_mtx_init(&cpu_core[i].cpuc_pid_lock, dtrace_lck_grp, dtrace_lck_attr);
17588 }
17589
17590 cpu_list = (dtrace_cpu_t *)kmem_zalloc( ncpu * sizeof(dtrace_cpu_t), KM_SLEEP );
17591 for (i = 0; i < ncpu; ++i) {
17592 cpu_list[i].cpu_id = (processorid_t)i;
17593 cpu_list[i].cpu_next = &(cpu_list[(i+1) % ncpu]);
17594 LIST_INIT(&cpu_list[i].cpu_cyc_list);
17595 lck_rw_init(&cpu_list[i].cpu_ft_lock, dtrace_lck_grp, dtrace_lck_attr);
17596 }
17597
17598 lck_mtx_lock(&cpu_lock);
17599 for (i = 0; i < ncpu; ++i)
17600 /* FIXME: track CPU configuration a la CHUD Processor Pref Pane. */
17601 dtrace_cpu_setup_initial( (processorid_t)i ); /* In lieu of register_cpu_setup_func() callback */
17602 lck_mtx_unlock(&cpu_lock);
17603
17604 (void)dtrace_abs_to_nano(0LL); /* Force once only call to clock_timebase_info (which can take a lock) */
17605
17606 dtrace_isa_init();
17607
17608 /*
17609 * See dtrace_impl.h for a description of dof modes.
17610 * The default is lazy dof.
17611 *
17612 * FIXME: Warn if state is LAZY_OFF? It won't break anything, but
17613 * makes no sense...
17614 */
17615 if (!PE_parse_boot_argn("dtrace_dof_mode", &dtrace_dof_mode, sizeof (dtrace_dof_mode))) {
17616 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
17617 }
17618
17619 /*
17620 * Sanity check of dof mode value.
17621 */
17622 switch (dtrace_dof_mode) {
17623 case DTRACE_DOF_MODE_NEVER:
17624 case DTRACE_DOF_MODE_LAZY_ON:
17625 /* valid modes, but nothing else we need to do */
17626 break;
17627
17628 case DTRACE_DOF_MODE_LAZY_OFF:
17629 case DTRACE_DOF_MODE_NON_LAZY:
17630 /* Cannot wait for a dtrace_open to init fasttrap */
17631 fasttrap_init();
17632 break;
17633
17634 default:
17635 /* Invalid, clamp to non lazy */
17636 dtrace_dof_mode = DTRACE_DOF_MODE_NON_LAZY;
17637 fasttrap_init();
17638 break;
17639 }
17640
17641 /*
17642 * See dtrace_impl.h for a description of kernel symbol modes.
17643 * The default is to wait for symbols from userspace (lazy symbols).
17644 */
17645 if (!PE_parse_boot_argn("dtrace_kernel_symbol_mode", &dtrace_kernel_symbol_mode, sizeof (dtrace_kernel_symbol_mode))) {
17646 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
17647 }
17648
17649 gDTraceInited = 1;
17650
17651 } else
17652 panic("dtrace_init: called twice!\n");
17653 }
17654
17655 void
17656 dtrace_postinit(void)
17657 {
17658 /*
17659 * Called from bsd_init after all provider's *_init() routines have been
17660 * run. That way, anonymous DOF enabled under dtrace_attach() is safe
17661 * to go.
17662 */
17663 dtrace_attach( (dev_info_t *)(uintptr_t)makedev(gMajDevNo, 0), 0 ); /* Punning a dev_t to a dev_info_t* */
17664
17665 /*
17666 * Add the mach_kernel to the module list for lazy processing
17667 */
17668 struct kmod_info fake_kernel_kmod;
17669 memset(&fake_kernel_kmod, 0, sizeof(fake_kernel_kmod));
17670
17671 strlcpy(fake_kernel_kmod.name, "mach_kernel", sizeof(fake_kernel_kmod.name));
17672 fake_kernel_kmod.id = 1;
17673 fake_kernel_kmod.address = g_kernel_kmod_info.address;
17674 fake_kernel_kmod.size = g_kernel_kmod_info.size;
17675
17676 if (dtrace_module_loaded(&fake_kernel_kmod, 0) != 0) {
17677 printf("dtrace_postinit: Could not register mach_kernel modctl\n");
17678 }
17679
17680 (void)OSKextRegisterKextsWithDTrace();
17681 }
17682 #undef DTRACE_MAJOR
17683
17684 /*
17685 * Routines used to register interest in cpu's being added to or removed
17686 * from the system.
17687 */
17688 void
17689 register_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
17690 {
17691 #pragma unused(ignore1,ignore2)
17692 }
17693
17694 void
17695 unregister_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
17696 {
17697 #pragma unused(ignore1,ignore2)
17698 }