]> git.saurik.com Git - apple/xnu.git/blob - bsd/dev/dtrace/dtrace.c
4a2e5e23adbe8fbfd357d39a9022f104a2c87e56
[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) 2013, Joyent, Inc. All rights reserved.
24 * Portions Copyright (c) 2013 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 dtrace_optval_t dtrace_statvar_maxsize = (16 * 1024);
151 dtrace_optval_t dtrace_statvar_maxsize_max = (16 * 10 * 1024);
152 size_t dtrace_actions_max = (16 * 1024);
153 size_t dtrace_retain_max = 1024;
154 dtrace_optval_t dtrace_helper_actions_max = 32;
155 dtrace_optval_t dtrace_helper_providers_max = 64;
156 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
157 size_t dtrace_strsize_default = 256;
158 dtrace_optval_t dtrace_cleanrate_default = 990099000; /* 1.1 hz */
159 dtrace_optval_t dtrace_cleanrate_min = 20000000; /* 50 hz */
160 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
161 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
162 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
163 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
164 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
165 dtrace_optval_t dtrace_nspec_default = 1;
166 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
167 dtrace_optval_t dtrace_stackframes_default = 20;
168 dtrace_optval_t dtrace_ustackframes_default = 20;
169 dtrace_optval_t dtrace_jstackframes_default = 50;
170 dtrace_optval_t dtrace_jstackstrsize_default = 512;
171 int dtrace_msgdsize_max = 128;
172 hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
173 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
174 int dtrace_devdepth_max = 32;
175 int dtrace_err_verbose;
176 int dtrace_provide_private_probes = 0;
177 hrtime_t dtrace_deadman_interval = NANOSEC;
178 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
179 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
180
181 /*
182 * DTrace External Variables
183 *
184 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
185 * available to DTrace consumers via the backtick (`) syntax. One of these,
186 * dtrace_zero, is made deliberately so: it is provided as a source of
187 * well-known, zero-filled memory. While this variable is not documented,
188 * it is used by some translators as an implementation detail.
189 */
190 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
191 unsigned int dtrace_max_cpus = 0; /* number of enabled cpus */
192 /*
193 * DTrace Internal Variables
194 */
195 static dev_info_t *dtrace_devi; /* device info */
196 static vmem_t *dtrace_arena; /* probe ID arena */
197 static vmem_t *dtrace_minor; /* minor number arena */
198 static taskq_t *dtrace_taskq; /* task queue */
199 static dtrace_probe_t **dtrace_probes; /* array of all probes */
200 static int dtrace_nprobes; /* number of probes */
201 static dtrace_provider_t *dtrace_provider; /* provider list */
202 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
203 static int dtrace_opens; /* number of opens */
204 static int dtrace_helpers; /* number of helpers */
205 static void *dtrace_softstate; /* softstate pointer */
206 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
207 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
208 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
209 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
210 static int dtrace_toxranges; /* number of toxic ranges */
211 static int dtrace_toxranges_max; /* size of toxic range array */
212 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
213 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
214 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
215 static kthread_t *dtrace_panicked; /* panicking thread */
216 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
217 static dtrace_genid_t dtrace_probegen; /* current probe generation */
218 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
219 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
220 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
221 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
222
223 static int dtrace_dof_mode; /* See dtrace_impl.h for a description of Darwin's dof modes. */
224
225 /*
226 * This does't quite fit as an internal variable, as it must be accessed in
227 * fbt_provide and sdt_provide. Its clearly not a dtrace tunable variable either...
228 */
229 int dtrace_kernel_symbol_mode; /* See dtrace_impl.h for a description of Darwin's kernel symbol modes. */
230
231
232 /*
233 * To save memory, some common memory allocations are given a
234 * unique zone. For example, dtrace_probe_t is 72 bytes in size,
235 * which means it would fall into the kalloc.128 bucket. With
236 * 20k elements allocated, the space saved is substantial.
237 */
238
239 struct zone *dtrace_probe_t_zone;
240
241 static int dtrace_module_unloaded(struct kmod_info *kmod);
242
243 /*
244 * DTrace Locking
245 * DTrace is protected by three (relatively coarse-grained) locks:
246 *
247 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
248 * including enabling state, probes, ECBs, consumer state, helper state,
249 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
250 * probe context is lock-free -- synchronization is handled via the
251 * dtrace_sync() cross call mechanism.
252 *
253 * (2) dtrace_provider_lock is required when manipulating provider state, or
254 * when provider state must be held constant.
255 *
256 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
257 * when meta provider state must be held constant.
258 *
259 * The lock ordering between these three locks is dtrace_meta_lock before
260 * dtrace_provider_lock before dtrace_lock. (In particular, there are
261 * several places where dtrace_provider_lock is held by the framework as it
262 * calls into the providers -- which then call back into the framework,
263 * grabbing dtrace_lock.)
264 *
265 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
266 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
267 * role as a coarse-grained lock; it is acquired before both of these locks.
268 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
269 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
270 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
271 * acquired _between_ dtrace_provider_lock and dtrace_lock.
272 */
273
274
275 /*
276 * APPLE NOTE:
277 *
278 * For porting purposes, all kmutex_t vars have been changed
279 * to lck_mtx_t, which require explicit initialization.
280 *
281 * kmutex_t becomes lck_mtx_t
282 * mutex_enter() becomes lck_mtx_lock()
283 * mutex_exit() becomes lck_mtx_unlock()
284 *
285 * Lock asserts are changed like this:
286 *
287 * ASSERT(MUTEX_HELD(&cpu_lock));
288 * becomes:
289 * lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
290 *
291 */
292 static lck_mtx_t dtrace_lock; /* probe state lock */
293 static lck_mtx_t dtrace_provider_lock; /* provider state lock */
294 static lck_mtx_t dtrace_meta_lock; /* meta-provider state lock */
295 static lck_rw_t dtrace_dof_mode_lock; /* dof mode lock */
296
297 /*
298 * DTrace Provider Variables
299 *
300 * These are the variables relating to DTrace as a provider (that is, the
301 * provider of the BEGIN, END, and ERROR probes).
302 */
303 static dtrace_pattr_t dtrace_provider_attr = {
304 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
305 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
306 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
307 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
308 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
309 };
310
311 static void
312 dtrace_nullop(void)
313 {}
314
315 static int
316 dtrace_enable_nullop(void)
317 {
318 return (0);
319 }
320
321 static dtrace_pops_t dtrace_provider_ops = {
322 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
323 (void (*)(void *, struct modctl *))dtrace_nullop,
324 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
325 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
326 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
327 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
328 NULL,
329 NULL,
330 NULL,
331 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
332 };
333
334 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
335 static dtrace_id_t dtrace_probeid_end; /* special END probe */
336 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
337
338 /*
339 * DTrace Helper Tracing Variables
340 */
341 uint32_t dtrace_helptrace_next = 0;
342 uint32_t dtrace_helptrace_nlocals;
343 char *dtrace_helptrace_buffer;
344 size_t dtrace_helptrace_bufsize = 512 * 1024;
345
346 #if DEBUG
347 int dtrace_helptrace_enabled = 1;
348 #else
349 int dtrace_helptrace_enabled = 0;
350 #endif
351
352
353 /*
354 * DTrace Error Hashing
355 *
356 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
357 * table. This is very useful for checking coverage of tests that are
358 * expected to induce DIF or DOF processing errors, and may be useful for
359 * debugging problems in the DIF code generator or in DOF generation . The
360 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
361 */
362 #if DEBUG
363 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
364 static const char *dtrace_errlast;
365 static kthread_t *dtrace_errthread;
366 static lck_mtx_t dtrace_errlock;
367 #endif
368
369 /*
370 * DTrace Macros and Constants
371 *
372 * These are various macros that are useful in various spots in the
373 * implementation, along with a few random constants that have no meaning
374 * outside of the implementation. There is no real structure to this cpp
375 * mishmash -- but is there ever?
376 */
377 #define DTRACE_HASHSTR(hash, probe) \
378 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
379
380 #define DTRACE_HASHNEXT(hash, probe) \
381 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
382
383 #define DTRACE_HASHPREV(hash, probe) \
384 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
385
386 #define DTRACE_HASHEQ(hash, lhs, rhs) \
387 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
388 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
389
390 #define DTRACE_AGGHASHSIZE_SLEW 17
391
392 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
393
394 /*
395 * The key for a thread-local variable consists of the lower 61 bits of the
396 * current_thread(), plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
397 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
398 * equal to a variable identifier. This is necessary (but not sufficient) to
399 * assure that global associative arrays never collide with thread-local
400 * variables. To guarantee that they cannot collide, we must also define the
401 * order for keying dynamic variables. That order is:
402 *
403 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
404 *
405 * Because the variable-key and the tls-key are in orthogonal spaces, there is
406 * no way for a global variable key signature to match a thread-local key
407 * signature.
408 */
409 #if defined (__x86_64__)
410 /* FIXME: two function calls!! */
411 #define DTRACE_TLS_THRKEY(where) { \
412 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
413 uint64_t thr = (uintptr_t)current_thread(); \
414 ASSERT(intr < (1 << 3)); \
415 (where) = ((thr + DIF_VARIABLE_MAX) & \
416 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
417 }
418 #else
419 #error Unknown architecture
420 #endif
421
422 #define DT_BSWAP_8(x) ((x) & 0xff)
423 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
424 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
425 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
426
427 #define DT_MASK_LO 0x00000000FFFFFFFFULL
428
429 #define DTRACE_STORE(type, tomax, offset, what) \
430 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
431
432
433 #define DTRACE_ALIGNCHECK(addr, size, flags) \
434 if (addr & (MIN(size,4) - 1)) { \
435 *flags |= CPU_DTRACE_BADALIGN; \
436 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
437 return (0); \
438 }
439
440 /*
441 * Test whether a range of memory starting at testaddr of size testsz falls
442 * within the range of memory described by addr, sz. We take care to avoid
443 * problems with overflow and underflow of the unsigned quantities, and
444 * disallow all negative sizes. Ranges of size 0 are allowed.
445 */
446 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
447 ((testaddr) - (baseaddr) < (basesz) && \
448 (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
449 (testaddr) + (testsz) >= (testaddr))
450
451 /*
452 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
453 * alloc_sz on the righthand side of the comparison in order to avoid overflow
454 * or underflow in the comparison with it. This is simpler than the INRANGE
455 * check above, because we know that the dtms_scratch_ptr is valid in the
456 * range. Allocations of size zero are allowed.
457 */
458 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
459 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
460 (mstate)->dtms_scratch_ptr >= (alloc_sz))
461
462 #define RECOVER_LABEL(bits) dtraceLoadRecover##bits:
463
464 #if defined (__x86_64__)
465 #define DTRACE_LOADFUNC(bits) \
466 /*CSTYLED*/ \
467 uint##bits##_t dtrace_load##bits(uintptr_t addr); \
468 \
469 uint##bits##_t \
470 dtrace_load##bits(uintptr_t addr) \
471 { \
472 size_t size = bits / NBBY; \
473 /*CSTYLED*/ \
474 uint##bits##_t rval = 0; \
475 int i; \
476 volatile uint16_t *flags = (volatile uint16_t *) \
477 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
478 \
479 DTRACE_ALIGNCHECK(addr, size, flags); \
480 \
481 for (i = 0; i < dtrace_toxranges; i++) { \
482 if (addr >= dtrace_toxrange[i].dtt_limit) \
483 continue; \
484 \
485 if (addr + size <= dtrace_toxrange[i].dtt_base) \
486 continue; \
487 \
488 /* \
489 * This address falls within a toxic region; return 0. \
490 */ \
491 *flags |= CPU_DTRACE_BADADDR; \
492 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
493 return (0); \
494 } \
495 \
496 { \
497 volatile vm_offset_t recover = (vm_offset_t)&&dtraceLoadRecover##bits; \
498 *flags |= CPU_DTRACE_NOFAULT; \
499 recover = dtrace_set_thread_recover(current_thread(), recover); \
500 /*CSTYLED*/ \
501 /* \
502 * PR6394061 - avoid device memory that is unpredictably \
503 * mapped and unmapped \
504 */ \
505 if (pmap_valid_page(pmap_find_phys(kernel_pmap, addr))) \
506 rval = *((volatile uint##bits##_t *)addr); \
507 RECOVER_LABEL(bits); \
508 (void)dtrace_set_thread_recover(current_thread(), recover); \
509 *flags &= ~CPU_DTRACE_NOFAULT; \
510 } \
511 \
512 return (rval); \
513 }
514 #else /* all other architectures */
515 #error Unknown Architecture
516 #endif
517
518 #ifdef __LP64__
519 #define dtrace_loadptr dtrace_load64
520 #else
521 #define dtrace_loadptr dtrace_load32
522 #endif
523
524 #define DTRACE_DYNHASH_FREE 0
525 #define DTRACE_DYNHASH_SINK 1
526 #define DTRACE_DYNHASH_VALID 2
527
528 #define DTRACE_MATCH_FAIL -1
529 #define DTRACE_MATCH_NEXT 0
530 #define DTRACE_MATCH_DONE 1
531 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
532 #define DTRACE_STATE_ALIGN 64
533
534 #define DTRACE_FLAGS2FLT(flags) \
535 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
536 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
537 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
538 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
539 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
540 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
541 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
542 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
543 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
544 DTRACEFLT_UNKNOWN)
545
546 #define DTRACEACT_ISSTRING(act) \
547 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
548 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
549
550
551 static size_t dtrace_strlen(const char *, size_t);
552 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
553 static void dtrace_enabling_provide(dtrace_provider_t *);
554 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
555 static void dtrace_enabling_matchall(void);
556 static dtrace_state_t *dtrace_anon_grab(void);
557 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
558 dtrace_state_t *, uint64_t, uint64_t);
559 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
560 static void dtrace_buffer_drop(dtrace_buffer_t *);
561 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
562 dtrace_state_t *, dtrace_mstate_t *);
563 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
564 dtrace_optval_t);
565 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
566 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
567
568
569 /*
570 * DTrace sysctl handlers
571 *
572 * These declarations and functions are used for a deeper DTrace configuration.
573 * Most of them are not per-consumer basis and may impact the other DTrace
574 * consumers. Correctness may not be supported for all the variables, so you
575 * should be careful about what values you are using.
576 */
577
578 SYSCTL_DECL(_kern_dtrace);
579 SYSCTL_NODE(_kern, OID_AUTO, dtrace, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "dtrace");
580
581 static int
582 sysctl_dtrace_err_verbose SYSCTL_HANDLER_ARGS
583 {
584 #pragma unused(oidp, arg2)
585 int changed, error;
586 int value = *(int *) arg1;
587
588 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
589 if (error || !changed)
590 return (error);
591
592 if (value != 0 && value != 1)
593 return (ERANGE);
594
595 lck_mtx_lock(&dtrace_lock);
596 dtrace_err_verbose = value;
597 lck_mtx_unlock(&dtrace_lock);
598
599 return (0);
600 }
601
602 /*
603 * kern.dtrace.err_verbose
604 *
605 * Set DTrace verbosity when an error occured (0 = disabled, 1 = enabld).
606 * Errors are reported when a DIFO or a DOF has been rejected by the kernel.
607 */
608 SYSCTL_PROC(_kern_dtrace, OID_AUTO, err_verbose,
609 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
610 &dtrace_err_verbose, 0,
611 sysctl_dtrace_err_verbose, "I", "dtrace error verbose");
612
613 static int
614 sysctl_dtrace_buffer_memory_maxsize SYSCTL_HANDLER_ARGS
615 {
616 #pragma unused(oidp, arg2, req)
617 int changed, error;
618 uint64_t value = *(uint64_t *) arg1;
619
620 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
621 if (error || !changed)
622 return (error);
623
624 if (value <= dtrace_buffer_memory_inuse)
625 return (ERANGE);
626
627 lck_mtx_lock(&dtrace_lock);
628 dtrace_buffer_memory_maxsize = value;
629 lck_mtx_unlock(&dtrace_lock);
630
631 return (0);
632 }
633
634 /*
635 * kern.dtrace.buffer_memory_maxsize
636 *
637 * Set DTrace maximal size in bytes used by all the consumers' state buffers. By default
638 * the limit is PHYS_MEM / 3 for *all* consumers. Attempting to set a null, a negative value
639 * or a value <= to dtrace_buffer_memory_inuse will result in a failure.
640 */
641 SYSCTL_PROC(_kern_dtrace, OID_AUTO, buffer_memory_maxsize,
642 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
643 &dtrace_buffer_memory_maxsize, 0,
644 sysctl_dtrace_buffer_memory_maxsize, "Q", "dtrace state buffer memory maxsize");
645
646 /*
647 * kern.dtrace.buffer_memory_inuse
648 *
649 * Current state buffer memory used, in bytes, by all the DTrace consumers.
650 * This value is read-only.
651 */
652 SYSCTL_QUAD(_kern_dtrace, OID_AUTO, buffer_memory_inuse, CTLFLAG_RD | CTLFLAG_LOCKED,
653 &dtrace_buffer_memory_inuse, "dtrace state buffer memory in-use");
654
655 static int
656 sysctl_dtrace_difo_maxsize SYSCTL_HANDLER_ARGS
657 {
658 #pragma unused(oidp, arg2, req)
659 int changed, error;
660 size_t value = *(size_t*) arg1;
661
662 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
663 if (error || !changed)
664 return (error);
665
666 if (value <= 0)
667 return (ERANGE);
668
669 lck_mtx_lock(&dtrace_lock);
670 dtrace_difo_maxsize = value;
671 lck_mtx_unlock(&dtrace_lock);
672
673 return (0);
674 }
675
676 /*
677 * kern.dtrace.difo_maxsize
678 *
679 * Set the DIFO max size in bytes, check the definition of dtrace_difo_maxsize
680 * to get the default value. Attempting to set a null or negative size will
681 * result in a failure.
682 */
683 SYSCTL_PROC(_kern_dtrace, OID_AUTO, difo_maxsize,
684 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
685 &dtrace_difo_maxsize, 0,
686 sysctl_dtrace_difo_maxsize, "Q", "dtrace difo maxsize");
687
688 static int
689 sysctl_dtrace_dof_maxsize SYSCTL_HANDLER_ARGS
690 {
691 #pragma unused(oidp, arg2, req)
692 int changed, error;
693 dtrace_optval_t value = *(dtrace_optval_t *) arg1;
694
695 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
696 if (error || !changed)
697 return (error);
698
699 if (value <= 0)
700 return (ERANGE);
701
702 lck_mtx_lock(&dtrace_lock);
703 dtrace_dof_maxsize = value;
704 lck_mtx_unlock(&dtrace_lock);
705
706 return (0);
707 }
708
709 /*
710 * kern.dtrace.dof_maxsize
711 *
712 * Set the DOF max size in bytes, check the definition of dtrace_dof_maxsize to
713 * get the default value. Attempting to set a null or negative size will result
714 * in a failure.
715 */
716 SYSCTL_PROC(_kern_dtrace, OID_AUTO, dof_maxsize,
717 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
718 &dtrace_dof_maxsize, 0,
719 sysctl_dtrace_dof_maxsize, "Q", "dtrace dof maxsize");
720
721 static int
722 sysctl_dtrace_statvar_maxsize SYSCTL_HANDLER_ARGS
723 {
724 #pragma unused(oidp, arg2, req)
725 int changed, error;
726 dtrace_optval_t value = *(dtrace_optval_t*) arg1;
727
728 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
729 if (error || !changed)
730 return (error);
731
732 if (value <= 0)
733 return (ERANGE);
734 if (value > dtrace_statvar_maxsize_max)
735 return (ERANGE);
736
737 lck_mtx_lock(&dtrace_lock);
738 dtrace_statvar_maxsize = value;
739 lck_mtx_unlock(&dtrace_lock);
740
741 return (0);
742 }
743
744 /*
745 * kern.dtrace.global_maxsize
746 *
747 * Set the variable max size in bytes, check the definition of
748 * dtrace_statvar_maxsize to get the default value. Attempting to set a null,
749 * too high or negative size will result in a failure.
750 */
751 SYSCTL_PROC(_kern_dtrace, OID_AUTO, global_maxsize,
752 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
753 &dtrace_statvar_maxsize, 0,
754 sysctl_dtrace_statvar_maxsize, "Q", "dtrace statvar maxsize");
755
756 static int
757 sysctl_dtrace_provide_private_probes SYSCTL_HANDLER_ARGS
758 {
759 #pragma unused(oidp, arg2)
760 int error;
761 int value = *(int *) arg1;
762
763 error = sysctl_io_number(req, value, sizeof(value), &value, NULL);
764 if (error)
765 return (error);
766
767 if (value != 0 && value != 1)
768 return (ERANGE);
769
770 lck_mtx_lock(&dtrace_lock);
771 dtrace_provide_private_probes = value;
772 lck_mtx_unlock(&dtrace_lock);
773
774 return (0);
775 }
776
777 /*
778 * kern.dtrace.provide_private_probes
779 *
780 * Set whether the providers must provide the private probes. This is
781 * mainly used by the FBT provider to request probes for the private/static
782 * symbols.
783 */
784 SYSCTL_PROC(_kern_dtrace, OID_AUTO, provide_private_probes,
785 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
786 &dtrace_provide_private_probes, 0,
787 sysctl_dtrace_provide_private_probes, "I", "provider must provide the private probes");
788
789 /*
790 * DTrace Probe Context Functions
791 *
792 * These functions are called from probe context. Because probe context is
793 * any context in which C may be called, arbitrarily locks may be held,
794 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
795 * As a result, functions called from probe context may only call other DTrace
796 * support functions -- they may not interact at all with the system at large.
797 * (Note that the ASSERT macro is made probe-context safe by redefining it in
798 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
799 * loads are to be performed from probe context, they _must_ be in terms of
800 * the safe dtrace_load*() variants.
801 *
802 * Some functions in this block are not actually called from probe context;
803 * for these functions, there will be a comment above the function reading
804 * "Note: not called from probe context."
805 */
806
807 int
808 dtrace_assfail(const char *a, const char *f, int l)
809 {
810 panic("dtrace: assertion failed: %s, file: %s, line: %d", a, f, l);
811
812 /*
813 * We just need something here that even the most clever compiler
814 * cannot optimize away.
815 */
816 return (a[(uintptr_t)f]);
817 }
818
819 /*
820 * Atomically increment a specified error counter from probe context.
821 */
822 static void
823 dtrace_error(uint32_t *counter)
824 {
825 /*
826 * Most counters stored to in probe context are per-CPU counters.
827 * However, there are some error conditions that are sufficiently
828 * arcane that they don't merit per-CPU storage. If these counters
829 * are incremented concurrently on different CPUs, scalability will be
830 * adversely affected -- but we don't expect them to be white-hot in a
831 * correctly constructed enabling...
832 */
833 uint32_t oval, nval;
834
835 do {
836 oval = *counter;
837
838 if ((nval = oval + 1) == 0) {
839 /*
840 * If the counter would wrap, set it to 1 -- assuring
841 * that the counter is never zero when we have seen
842 * errors. (The counter must be 32-bits because we
843 * aren't guaranteed a 64-bit compare&swap operation.)
844 * To save this code both the infamy of being fingered
845 * by a priggish news story and the indignity of being
846 * the target of a neo-puritan witch trial, we're
847 * carefully avoiding any colorful description of the
848 * likelihood of this condition -- but suffice it to
849 * say that it is only slightly more likely than the
850 * overflow of predicate cache IDs, as discussed in
851 * dtrace_predicate_create().
852 */
853 nval = 1;
854 }
855 } while (dtrace_cas32(counter, oval, nval) != oval);
856 }
857
858 /*
859 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
860 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
861 */
862 DTRACE_LOADFUNC(8)
863 DTRACE_LOADFUNC(16)
864 DTRACE_LOADFUNC(32)
865 DTRACE_LOADFUNC(64)
866
867 static int
868 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
869 {
870 if (dest < mstate->dtms_scratch_base)
871 return (0);
872
873 if (dest + size < dest)
874 return (0);
875
876 if (dest + size > mstate->dtms_scratch_ptr)
877 return (0);
878
879 return (1);
880 }
881
882 static int
883 dtrace_canstore_statvar(uint64_t addr, size_t sz,
884 dtrace_statvar_t **svars, int nsvars)
885 {
886 int i;
887
888 size_t maxglobalsize, maxlocalsize;
889
890 maxglobalsize = dtrace_statvar_maxsize;
891 maxlocalsize = (maxglobalsize + sizeof (uint64_t)) * NCPU;
892
893 if (nsvars == 0)
894 return (0);
895
896 for (i = 0; i < nsvars; i++) {
897 dtrace_statvar_t *svar = svars[i];
898 uint8_t scope;
899 size_t size;
900
901 if (svar == NULL || (size = svar->dtsv_size) == 0)
902 continue;
903
904 scope = svar->dtsv_var.dtdv_scope;
905
906 /**
907 * We verify that our size is valid in the spirit of providing
908 * defense in depth: we want to prevent attackers from using
909 * DTrace to escalate an orthogonal kernel heap corruption bug
910 * into the ability to store to arbitrary locations in memory.
911 */
912 VERIFY((scope == DIFV_SCOPE_GLOBAL && size < maxglobalsize) ||
913 (scope == DIFV_SCOPE_LOCAL && size < maxlocalsize));
914
915 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
916 return (1);
917 }
918
919 return (0);
920 }
921
922 /*
923 * Check to see if the address is within a memory region to which a store may
924 * be issued. This includes the DTrace scratch areas, and any DTrace variable
925 * region. The caller of dtrace_canstore() is responsible for performing any
926 * alignment checks that are needed before stores are actually executed.
927 */
928 static int
929 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
930 dtrace_vstate_t *vstate)
931 {
932 /*
933 * First, check to see if the address is in scratch space...
934 */
935 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
936 mstate->dtms_scratch_size))
937 return (1);
938
939 /*
940 * Now check to see if it's a dynamic variable. This check will pick
941 * up both thread-local variables and any global dynamically-allocated
942 * variables.
943 */
944 if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
945 vstate->dtvs_dynvars.dtds_size)) {
946 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
947 uintptr_t base = (uintptr_t)dstate->dtds_base +
948 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
949 uintptr_t chunkoffs;
950
951 /*
952 * Before we assume that we can store here, we need to make
953 * sure that it isn't in our metadata -- storing to our
954 * dynamic variable metadata would corrupt our state. For
955 * the range to not include any dynamic variable metadata,
956 * it must:
957 *
958 * (1) Start above the hash table that is at the base of
959 * the dynamic variable space
960 *
961 * (2) Have a starting chunk offset that is beyond the
962 * dtrace_dynvar_t that is at the base of every chunk
963 *
964 * (3) Not span a chunk boundary
965 *
966 */
967 if (addr < base)
968 return (0);
969
970 chunkoffs = (addr - base) % dstate->dtds_chunksize;
971
972 if (chunkoffs < sizeof (dtrace_dynvar_t))
973 return (0);
974
975 if (chunkoffs + sz > dstate->dtds_chunksize)
976 return (0);
977
978 return (1);
979 }
980
981 /*
982 * Finally, check the static local and global variables. These checks
983 * take the longest, so we perform them last.
984 */
985 if (dtrace_canstore_statvar(addr, sz,
986 vstate->dtvs_locals, vstate->dtvs_nlocals))
987 return (1);
988
989 if (dtrace_canstore_statvar(addr, sz,
990 vstate->dtvs_globals, vstate->dtvs_nglobals))
991 return (1);
992
993 return (0);
994 }
995
996
997 /*
998 * Convenience routine to check to see if the address is within a memory
999 * region in which a load may be issued given the user's privilege level;
1000 * if not, it sets the appropriate error flags and loads 'addr' into the
1001 * illegal value slot.
1002 *
1003 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
1004 * appropriate memory access protection.
1005 */
1006 static int
1007 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1008 dtrace_vstate_t *vstate)
1009 {
1010 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
1011
1012 /*
1013 * If we hold the privilege to read from kernel memory, then
1014 * everything is readable.
1015 */
1016 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
1017 return (1);
1018
1019 /*
1020 * You can obviously read that which you can store.
1021 */
1022 if (dtrace_canstore(addr, sz, mstate, vstate))
1023 return (1);
1024
1025 /*
1026 * We're allowed to read from our own string table.
1027 */
1028 if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
1029 mstate->dtms_difo->dtdo_strlen))
1030 return (1);
1031
1032 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1033 *illval = addr;
1034 return (0);
1035 }
1036
1037 /*
1038 * Convenience routine to check to see if a given string is within a memory
1039 * region in which a load may be issued given the user's privilege level;
1040 * this exists so that we don't need to issue unnecessary dtrace_strlen()
1041 * calls in the event that the user has all privileges.
1042 */
1043 static int
1044 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1045 dtrace_vstate_t *vstate)
1046 {
1047 size_t strsz;
1048
1049 /*
1050 * If we hold the privilege to read from kernel memory, then
1051 * everything is readable.
1052 */
1053 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
1054 return (1);
1055
1056 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
1057 if (dtrace_canload(addr, strsz, mstate, vstate))
1058 return (1);
1059
1060 return (0);
1061 }
1062
1063 /*
1064 * Convenience routine to check to see if a given variable is within a memory
1065 * region in which a load may be issued given the user's privilege level.
1066 */
1067 static int
1068 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
1069 dtrace_vstate_t *vstate)
1070 {
1071 size_t sz;
1072 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1073
1074 /*
1075 * If we hold the privilege to read from kernel memory, then
1076 * everything is readable.
1077 */
1078 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
1079 return (1);
1080
1081 if (type->dtdt_kind == DIF_TYPE_STRING)
1082 sz = dtrace_strlen(src,
1083 vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
1084 else
1085 sz = type->dtdt_size;
1086
1087 return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
1088 }
1089
1090 /*
1091 * Compare two strings using safe loads.
1092 */
1093 static int
1094 dtrace_strncmp(char *s1, char *s2, size_t limit)
1095 {
1096 uint8_t c1, c2;
1097 volatile uint16_t *flags;
1098
1099 if (s1 == s2 || limit == 0)
1100 return (0);
1101
1102 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1103
1104 do {
1105 if (s1 == NULL) {
1106 c1 = '\0';
1107 } else {
1108 c1 = dtrace_load8((uintptr_t)s1++);
1109 }
1110
1111 if (s2 == NULL) {
1112 c2 = '\0';
1113 } else {
1114 c2 = dtrace_load8((uintptr_t)s2++);
1115 }
1116
1117 if (c1 != c2)
1118 return (c1 - c2);
1119 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1120
1121 return (0);
1122 }
1123
1124 /*
1125 * Compute strlen(s) for a string using safe memory accesses. The additional
1126 * len parameter is used to specify a maximum length to ensure completion.
1127 */
1128 static size_t
1129 dtrace_strlen(const char *s, size_t lim)
1130 {
1131 uint_t len;
1132
1133 for (len = 0; len != lim; len++) {
1134 if (dtrace_load8((uintptr_t)s++) == '\0')
1135 break;
1136 }
1137
1138 return (len);
1139 }
1140
1141 /*
1142 * Check if an address falls within a toxic region.
1143 */
1144 static int
1145 dtrace_istoxic(uintptr_t kaddr, size_t size)
1146 {
1147 uintptr_t taddr, tsize;
1148 int i;
1149
1150 for (i = 0; i < dtrace_toxranges; i++) {
1151 taddr = dtrace_toxrange[i].dtt_base;
1152 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1153
1154 if (kaddr - taddr < tsize) {
1155 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1156 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1157 return (1);
1158 }
1159
1160 if (taddr - kaddr < size) {
1161 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1162 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1163 return (1);
1164 }
1165 }
1166
1167 return (0);
1168 }
1169
1170 /*
1171 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1172 * memory specified by the DIF program. The dst is assumed to be safe memory
1173 * that we can store to directly because it is managed by DTrace. As with
1174 * standard bcopy, overlapping copies are handled properly.
1175 */
1176 static void
1177 dtrace_bcopy(const void *src, void *dst, size_t len)
1178 {
1179 if (len != 0) {
1180 uint8_t *s1 = dst;
1181 const uint8_t *s2 = src;
1182
1183 if (s1 <= s2) {
1184 do {
1185 *s1++ = dtrace_load8((uintptr_t)s2++);
1186 } while (--len != 0);
1187 } else {
1188 s2 += len;
1189 s1 += len;
1190
1191 do {
1192 *--s1 = dtrace_load8((uintptr_t)--s2);
1193 } while (--len != 0);
1194 }
1195 }
1196 }
1197
1198 /*
1199 * Copy src to dst using safe memory accesses, up to either the specified
1200 * length, or the point that a nul byte is encountered. The src is assumed to
1201 * be unsafe memory specified by the DIF program. The dst is assumed to be
1202 * safe memory that we can store to directly because it is managed by DTrace.
1203 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1204 */
1205 static void
1206 dtrace_strcpy(const void *src, void *dst, size_t len)
1207 {
1208 if (len != 0) {
1209 uint8_t *s1 = dst, c;
1210 const uint8_t *s2 = src;
1211
1212 do {
1213 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1214 } while (--len != 0 && c != '\0');
1215 }
1216 }
1217
1218 /*
1219 * Copy src to dst, deriving the size and type from the specified (BYREF)
1220 * variable type. The src is assumed to be unsafe memory specified by the DIF
1221 * program. The dst is assumed to be DTrace variable memory that is of the
1222 * specified type; we assume that we can store to directly.
1223 */
1224 static void
1225 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1226 {
1227 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1228
1229 if (type->dtdt_kind == DIF_TYPE_STRING) {
1230 dtrace_strcpy(src, dst, type->dtdt_size);
1231 } else {
1232 dtrace_bcopy(src, dst, type->dtdt_size);
1233 }
1234 }
1235
1236 /*
1237 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1238 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1239 * safe memory that we can access directly because it is managed by DTrace.
1240 */
1241 static int
1242 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1243 {
1244 volatile uint16_t *flags;
1245
1246 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1247
1248 if (s1 == s2)
1249 return (0);
1250
1251 if (s1 == NULL || s2 == NULL)
1252 return (1);
1253
1254 if (s1 != s2 && len != 0) {
1255 const uint8_t *ps1 = s1;
1256 const uint8_t *ps2 = s2;
1257
1258 do {
1259 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1260 return (1);
1261 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1262 }
1263 return (0);
1264 }
1265
1266 /*
1267 * Zero the specified region using a simple byte-by-byte loop. Note that this
1268 * is for safe DTrace-managed memory only.
1269 */
1270 static void
1271 dtrace_bzero(void *dst, size_t len)
1272 {
1273 uchar_t *cp;
1274
1275 for (cp = dst; len != 0; len--)
1276 *cp++ = 0;
1277 }
1278
1279 static void
1280 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1281 {
1282 uint64_t result[2];
1283
1284 result[0] = addend1[0] + addend2[0];
1285 result[1] = addend1[1] + addend2[1] +
1286 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1287
1288 sum[0] = result[0];
1289 sum[1] = result[1];
1290 }
1291
1292 /*
1293 * Shift the 128-bit value in a by b. If b is positive, shift left.
1294 * If b is negative, shift right.
1295 */
1296 static void
1297 dtrace_shift_128(uint64_t *a, int b)
1298 {
1299 uint64_t mask;
1300
1301 if (b == 0)
1302 return;
1303
1304 if (b < 0) {
1305 b = -b;
1306 if (b >= 64) {
1307 a[0] = a[1] >> (b - 64);
1308 a[1] = 0;
1309 } else {
1310 a[0] >>= b;
1311 mask = 1LL << (64 - b);
1312 mask -= 1;
1313 a[0] |= ((a[1] & mask) << (64 - b));
1314 a[1] >>= b;
1315 }
1316 } else {
1317 if (b >= 64) {
1318 a[1] = a[0] << (b - 64);
1319 a[0] = 0;
1320 } else {
1321 a[1] <<= b;
1322 mask = a[0] >> (64 - b);
1323 a[1] |= mask;
1324 a[0] <<= b;
1325 }
1326 }
1327 }
1328
1329 /*
1330 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1331 * use native multiplication on those, and then re-combine into the
1332 * resulting 128-bit value.
1333 *
1334 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1335 * hi1 * hi2 << 64 +
1336 * hi1 * lo2 << 32 +
1337 * hi2 * lo1 << 32 +
1338 * lo1 * lo2
1339 */
1340 static void
1341 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1342 {
1343 uint64_t hi1, hi2, lo1, lo2;
1344 uint64_t tmp[2];
1345
1346 hi1 = factor1 >> 32;
1347 hi2 = factor2 >> 32;
1348
1349 lo1 = factor1 & DT_MASK_LO;
1350 lo2 = factor2 & DT_MASK_LO;
1351
1352 product[0] = lo1 * lo2;
1353 product[1] = hi1 * hi2;
1354
1355 tmp[0] = hi1 * lo2;
1356 tmp[1] = 0;
1357 dtrace_shift_128(tmp, 32);
1358 dtrace_add_128(product, tmp, product);
1359
1360 tmp[0] = hi2 * lo1;
1361 tmp[1] = 0;
1362 dtrace_shift_128(tmp, 32);
1363 dtrace_add_128(product, tmp, product);
1364 }
1365
1366 /*
1367 * This privilege check should be used by actions and subroutines to
1368 * verify that the user credentials of the process that enabled the
1369 * invoking ECB match the target credentials
1370 */
1371 static int
1372 dtrace_priv_proc_common_user(dtrace_state_t *state)
1373 {
1374 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1375
1376 /*
1377 * We should always have a non-NULL state cred here, since if cred
1378 * is null (anonymous tracing), we fast-path bypass this routine.
1379 */
1380 ASSERT(s_cr != NULL);
1381
1382 if ((cr = dtrace_CRED()) != NULL &&
1383 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_uid &&
1384 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_ruid &&
1385 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_suid &&
1386 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_gid &&
1387 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_rgid &&
1388 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_sgid)
1389 return (1);
1390
1391 return (0);
1392 }
1393
1394 /*
1395 * This privilege check should be used by actions and subroutines to
1396 * verify that the zone of the process that enabled the invoking ECB
1397 * matches the target credentials
1398 */
1399 static int
1400 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1401 {
1402 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1403 #pragma unused(cr, s_cr, state) /* __APPLE__ */
1404
1405 /*
1406 * We should always have a non-NULL state cred here, since if cred
1407 * is null (anonymous tracing), we fast-path bypass this routine.
1408 */
1409 ASSERT(s_cr != NULL);
1410
1411 return 1; /* APPLE NOTE: Darwin doesn't do zones. */
1412 }
1413
1414 /*
1415 * This privilege check should be used by actions and subroutines to
1416 * verify that the process has not setuid or changed credentials.
1417 */
1418 static int
1419 dtrace_priv_proc_common_nocd(void)
1420 {
1421 return 1; /* Darwin omits "No Core Dump" flag. */
1422 }
1423
1424 static int
1425 dtrace_priv_proc_destructive(dtrace_state_t *state)
1426 {
1427 int action = state->dts_cred.dcr_action;
1428
1429 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1430 goto bad;
1431
1432 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1433 goto bad;
1434
1435 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1436 dtrace_priv_proc_common_zone(state) == 0)
1437 goto bad;
1438
1439 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1440 dtrace_priv_proc_common_user(state) == 0)
1441 goto bad;
1442
1443 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1444 dtrace_priv_proc_common_nocd() == 0)
1445 goto bad;
1446
1447 return (1);
1448
1449 bad:
1450 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1451
1452 return (0);
1453 }
1454
1455 static int
1456 dtrace_priv_proc_control(dtrace_state_t *state)
1457 {
1458 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1459 goto bad;
1460
1461 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1462 goto bad;
1463
1464 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1465 return (1);
1466
1467 if (dtrace_priv_proc_common_zone(state) &&
1468 dtrace_priv_proc_common_user(state) &&
1469 dtrace_priv_proc_common_nocd())
1470 return (1);
1471
1472 bad:
1473 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1474
1475 return (0);
1476 }
1477
1478 static int
1479 dtrace_priv_proc(dtrace_state_t *state)
1480 {
1481 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1482 goto bad;
1483
1484 if (dtrace_is_restricted() && !dtrace_is_running_apple_internal() && !dtrace_can_attach_to_proc(current_proc()))
1485 goto bad;
1486
1487 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1488 return (1);
1489
1490 bad:
1491 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1492
1493 return (0);
1494 }
1495
1496 /*
1497 * The P_LNOATTACH check is an Apple specific check.
1498 * We need a version of dtrace_priv_proc() that omits
1499 * that check for PID and EXECNAME accesses
1500 */
1501 static int
1502 dtrace_priv_proc_relaxed(dtrace_state_t *state)
1503 {
1504
1505 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1506 return (1);
1507
1508 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1509
1510 return (0);
1511 }
1512
1513 static int
1514 dtrace_priv_kernel(dtrace_state_t *state)
1515 {
1516 if (dtrace_is_restricted() && !dtrace_is_running_apple_internal())
1517 goto bad;
1518
1519 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1520 return (1);
1521
1522 bad:
1523 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1524
1525 return (0);
1526 }
1527
1528 static int
1529 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1530 {
1531 if (dtrace_is_restricted())
1532 goto bad;
1533
1534 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1535 return (1);
1536
1537 bad:
1538 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1539
1540 return (0);
1541 }
1542
1543 /*
1544 * Note: not called from probe context. This function is called
1545 * asynchronously (and at a regular interval) from outside of probe context to
1546 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1547 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1548 */
1549 static void
1550 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1551 {
1552 dtrace_dynvar_t *dirty;
1553 dtrace_dstate_percpu_t *dcpu;
1554 int i, work = 0;
1555
1556 for (i = 0; i < (int)NCPU; i++) {
1557 dcpu = &dstate->dtds_percpu[i];
1558
1559 ASSERT(dcpu->dtdsc_rinsing == NULL);
1560
1561 /*
1562 * If the dirty list is NULL, there is no dirty work to do.
1563 */
1564 if (dcpu->dtdsc_dirty == NULL)
1565 continue;
1566
1567 /*
1568 * If the clean list is non-NULL, then we're not going to do
1569 * any work for this CPU -- it means that there has not been
1570 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1571 * since the last time we cleaned house.
1572 */
1573 if (dcpu->dtdsc_clean != NULL)
1574 continue;
1575
1576 work = 1;
1577
1578 /*
1579 * Atomically move the dirty list aside.
1580 */
1581 do {
1582 dirty = dcpu->dtdsc_dirty;
1583
1584 /*
1585 * Before we zap the dirty list, set the rinsing list.
1586 * (This allows for a potential assertion in
1587 * dtrace_dynvar(): if a free dynamic variable appears
1588 * on a hash chain, either the dirty list or the
1589 * rinsing list for some CPU must be non-NULL.)
1590 */
1591 dcpu->dtdsc_rinsing = dirty;
1592 dtrace_membar_producer();
1593 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1594 dirty, NULL) != dirty);
1595 }
1596
1597 if (!work) {
1598 /*
1599 * We have no work to do; we can simply return.
1600 */
1601 return;
1602 }
1603
1604 dtrace_sync();
1605
1606 for (i = 0; i < (int)NCPU; i++) {
1607 dcpu = &dstate->dtds_percpu[i];
1608
1609 if (dcpu->dtdsc_rinsing == NULL)
1610 continue;
1611
1612 /*
1613 * We are now guaranteed that no hash chain contains a pointer
1614 * into this dirty list; we can make it clean.
1615 */
1616 ASSERT(dcpu->dtdsc_clean == NULL);
1617 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1618 dcpu->dtdsc_rinsing = NULL;
1619 }
1620
1621 /*
1622 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1623 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1624 * This prevents a race whereby a CPU incorrectly decides that
1625 * the state should be something other than DTRACE_DSTATE_CLEAN
1626 * after dtrace_dynvar_clean() has completed.
1627 */
1628 dtrace_sync();
1629
1630 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1631 }
1632
1633 /*
1634 * Depending on the value of the op parameter, this function looks-up,
1635 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1636 * allocation is requested, this function will return a pointer to a
1637 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1638 * variable can be allocated. If NULL is returned, the appropriate counter
1639 * will be incremented.
1640 */
1641 static dtrace_dynvar_t *
1642 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1643 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1644 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1645 {
1646 uint64_t hashval = DTRACE_DYNHASH_VALID;
1647 dtrace_dynhash_t *hash = dstate->dtds_hash;
1648 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1649 processorid_t me = CPU->cpu_id, cpu = me;
1650 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1651 size_t bucket, ksize;
1652 size_t chunksize = dstate->dtds_chunksize;
1653 uintptr_t kdata, lock, nstate;
1654 uint_t i;
1655
1656 ASSERT(nkeys != 0);
1657
1658 /*
1659 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1660 * algorithm. For the by-value portions, we perform the algorithm in
1661 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1662 * bit, and seems to have only a minute effect on distribution. For
1663 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1664 * over each referenced byte. It's painful to do this, but it's much
1665 * better than pathological hash distribution. The efficacy of the
1666 * hashing algorithm (and a comparison with other algorithms) may be
1667 * found by running the ::dtrace_dynstat MDB dcmd.
1668 */
1669 for (i = 0; i < nkeys; i++) {
1670 if (key[i].dttk_size == 0) {
1671 uint64_t val = key[i].dttk_value;
1672
1673 hashval += (val >> 48) & 0xffff;
1674 hashval += (hashval << 10);
1675 hashval ^= (hashval >> 6);
1676
1677 hashval += (val >> 32) & 0xffff;
1678 hashval += (hashval << 10);
1679 hashval ^= (hashval >> 6);
1680
1681 hashval += (val >> 16) & 0xffff;
1682 hashval += (hashval << 10);
1683 hashval ^= (hashval >> 6);
1684
1685 hashval += val & 0xffff;
1686 hashval += (hashval << 10);
1687 hashval ^= (hashval >> 6);
1688 } else {
1689 /*
1690 * This is incredibly painful, but it beats the hell
1691 * out of the alternative.
1692 */
1693 uint64_t j, size = key[i].dttk_size;
1694 uintptr_t base = (uintptr_t)key[i].dttk_value;
1695
1696 if (!dtrace_canload(base, size, mstate, vstate))
1697 break;
1698
1699 for (j = 0; j < size; j++) {
1700 hashval += dtrace_load8(base + j);
1701 hashval += (hashval << 10);
1702 hashval ^= (hashval >> 6);
1703 }
1704 }
1705 }
1706
1707 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1708 return (NULL);
1709
1710 hashval += (hashval << 3);
1711 hashval ^= (hashval >> 11);
1712 hashval += (hashval << 15);
1713
1714 /*
1715 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1716 * comes out to be one of our two sentinel hash values. If this
1717 * actually happens, we set the hashval to be a value known to be a
1718 * non-sentinel value.
1719 */
1720 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1721 hashval = DTRACE_DYNHASH_VALID;
1722
1723 /*
1724 * Yes, it's painful to do a divide here. If the cycle count becomes
1725 * important here, tricks can be pulled to reduce it. (However, it's
1726 * critical that hash collisions be kept to an absolute minimum;
1727 * they're much more painful than a divide.) It's better to have a
1728 * solution that generates few collisions and still keeps things
1729 * relatively simple.
1730 */
1731 bucket = hashval % dstate->dtds_hashsize;
1732
1733 if (op == DTRACE_DYNVAR_DEALLOC) {
1734 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1735
1736 for (;;) {
1737 while ((lock = *lockp) & 1)
1738 continue;
1739
1740 if (dtrace_casptr((void *)(uintptr_t)lockp,
1741 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1742 break;
1743 }
1744
1745 dtrace_membar_producer();
1746 }
1747
1748 top:
1749 prev = NULL;
1750 lock = hash[bucket].dtdh_lock;
1751
1752 dtrace_membar_consumer();
1753
1754 start = hash[bucket].dtdh_chain;
1755 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1756 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1757 op != DTRACE_DYNVAR_DEALLOC));
1758
1759 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1760 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1761 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1762
1763 if (dvar->dtdv_hashval != hashval) {
1764 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1765 /*
1766 * We've reached the sink, and therefore the
1767 * end of the hash chain; we can kick out of
1768 * the loop knowing that we have seen a valid
1769 * snapshot of state.
1770 */
1771 ASSERT(dvar->dtdv_next == NULL);
1772 ASSERT(dvar == &dtrace_dynhash_sink);
1773 break;
1774 }
1775
1776 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1777 /*
1778 * We've gone off the rails: somewhere along
1779 * the line, one of the members of this hash
1780 * chain was deleted. Note that we could also
1781 * detect this by simply letting this loop run
1782 * to completion, as we would eventually hit
1783 * the end of the dirty list. However, we
1784 * want to avoid running the length of the
1785 * dirty list unnecessarily (it might be quite
1786 * long), so we catch this as early as
1787 * possible by detecting the hash marker. In
1788 * this case, we simply set dvar to NULL and
1789 * break; the conditional after the loop will
1790 * send us back to top.
1791 */
1792 dvar = NULL;
1793 break;
1794 }
1795
1796 goto next;
1797 }
1798
1799 if (dtuple->dtt_nkeys != nkeys)
1800 goto next;
1801
1802 for (i = 0; i < nkeys; i++, dkey++) {
1803 if (dkey->dttk_size != key[i].dttk_size)
1804 goto next; /* size or type mismatch */
1805
1806 if (dkey->dttk_size != 0) {
1807 if (dtrace_bcmp(
1808 (void *)(uintptr_t)key[i].dttk_value,
1809 (void *)(uintptr_t)dkey->dttk_value,
1810 dkey->dttk_size))
1811 goto next;
1812 } else {
1813 if (dkey->dttk_value != key[i].dttk_value)
1814 goto next;
1815 }
1816 }
1817
1818 if (op != DTRACE_DYNVAR_DEALLOC)
1819 return (dvar);
1820
1821 ASSERT(dvar->dtdv_next == NULL ||
1822 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1823
1824 if (prev != NULL) {
1825 ASSERT(hash[bucket].dtdh_chain != dvar);
1826 ASSERT(start != dvar);
1827 ASSERT(prev->dtdv_next == dvar);
1828 prev->dtdv_next = dvar->dtdv_next;
1829 } else {
1830 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1831 start, dvar->dtdv_next) != start) {
1832 /*
1833 * We have failed to atomically swing the
1834 * hash table head pointer, presumably because
1835 * of a conflicting allocation on another CPU.
1836 * We need to reread the hash chain and try
1837 * again.
1838 */
1839 goto top;
1840 }
1841 }
1842
1843 dtrace_membar_producer();
1844
1845 /*
1846 * Now set the hash value to indicate that it's free.
1847 */
1848 ASSERT(hash[bucket].dtdh_chain != dvar);
1849 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1850
1851 dtrace_membar_producer();
1852
1853 /*
1854 * Set the next pointer to point at the dirty list, and
1855 * atomically swing the dirty pointer to the newly freed dvar.
1856 */
1857 do {
1858 next = dcpu->dtdsc_dirty;
1859 dvar->dtdv_next = next;
1860 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1861
1862 /*
1863 * Finally, unlock this hash bucket.
1864 */
1865 ASSERT(hash[bucket].dtdh_lock == lock);
1866 ASSERT(lock & 1);
1867 hash[bucket].dtdh_lock++;
1868
1869 return (NULL);
1870 next:
1871 prev = dvar;
1872 continue;
1873 }
1874
1875 if (dvar == NULL) {
1876 /*
1877 * If dvar is NULL, it is because we went off the rails:
1878 * one of the elements that we traversed in the hash chain
1879 * was deleted while we were traversing it. In this case,
1880 * we assert that we aren't doing a dealloc (deallocs lock
1881 * the hash bucket to prevent themselves from racing with
1882 * one another), and retry the hash chain traversal.
1883 */
1884 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1885 goto top;
1886 }
1887
1888 if (op != DTRACE_DYNVAR_ALLOC) {
1889 /*
1890 * If we are not to allocate a new variable, we want to
1891 * return NULL now. Before we return, check that the value
1892 * of the lock word hasn't changed. If it has, we may have
1893 * seen an inconsistent snapshot.
1894 */
1895 if (op == DTRACE_DYNVAR_NOALLOC) {
1896 if (hash[bucket].dtdh_lock != lock)
1897 goto top;
1898 } else {
1899 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1900 ASSERT(hash[bucket].dtdh_lock == lock);
1901 ASSERT(lock & 1);
1902 hash[bucket].dtdh_lock++;
1903 }
1904
1905 return (NULL);
1906 }
1907
1908 /*
1909 * We need to allocate a new dynamic variable. The size we need is the
1910 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1911 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1912 * the size of any referred-to data (dsize). We then round the final
1913 * size up to the chunksize for allocation.
1914 */
1915 for (ksize = 0, i = 0; i < nkeys; i++)
1916 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1917
1918 /*
1919 * This should be pretty much impossible, but could happen if, say,
1920 * strange DIF specified the tuple. Ideally, this should be an
1921 * assertion and not an error condition -- but that requires that the
1922 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1923 * bullet-proof. (That is, it must not be able to be fooled by
1924 * malicious DIF.) Given the lack of backwards branches in DIF,
1925 * solving this would presumably not amount to solving the Halting
1926 * Problem -- but it still seems awfully hard.
1927 */
1928 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1929 ksize + dsize > chunksize) {
1930 dcpu->dtdsc_drops++;
1931 return (NULL);
1932 }
1933
1934 nstate = DTRACE_DSTATE_EMPTY;
1935
1936 do {
1937 retry:
1938 free = dcpu->dtdsc_free;
1939
1940 if (free == NULL) {
1941 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1942 void *rval;
1943
1944 if (clean == NULL) {
1945 /*
1946 * We're out of dynamic variable space on
1947 * this CPU. Unless we have tried all CPUs,
1948 * we'll try to allocate from a different
1949 * CPU.
1950 */
1951 switch (dstate->dtds_state) {
1952 case DTRACE_DSTATE_CLEAN: {
1953 void *sp = &dstate->dtds_state;
1954
1955 if (++cpu >= (int)NCPU)
1956 cpu = 0;
1957
1958 if (dcpu->dtdsc_dirty != NULL &&
1959 nstate == DTRACE_DSTATE_EMPTY)
1960 nstate = DTRACE_DSTATE_DIRTY;
1961
1962 if (dcpu->dtdsc_rinsing != NULL)
1963 nstate = DTRACE_DSTATE_RINSING;
1964
1965 dcpu = &dstate->dtds_percpu[cpu];
1966
1967 if (cpu != me)
1968 goto retry;
1969
1970 (void) dtrace_cas32(sp,
1971 DTRACE_DSTATE_CLEAN, nstate);
1972
1973 /*
1974 * To increment the correct bean
1975 * counter, take another lap.
1976 */
1977 goto retry;
1978 }
1979
1980 case DTRACE_DSTATE_DIRTY:
1981 dcpu->dtdsc_dirty_drops++;
1982 break;
1983
1984 case DTRACE_DSTATE_RINSING:
1985 dcpu->dtdsc_rinsing_drops++;
1986 break;
1987
1988 case DTRACE_DSTATE_EMPTY:
1989 dcpu->dtdsc_drops++;
1990 break;
1991 }
1992
1993 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1994 return (NULL);
1995 }
1996
1997 /*
1998 * The clean list appears to be non-empty. We want to
1999 * move the clean list to the free list; we start by
2000 * moving the clean pointer aside.
2001 */
2002 if (dtrace_casptr(&dcpu->dtdsc_clean,
2003 clean, NULL) != clean) {
2004 /*
2005 * We are in one of two situations:
2006 *
2007 * (a) The clean list was switched to the
2008 * free list by another CPU.
2009 *
2010 * (b) The clean list was added to by the
2011 * cleansing cyclic.
2012 *
2013 * In either of these situations, we can
2014 * just reattempt the free list allocation.
2015 */
2016 goto retry;
2017 }
2018
2019 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2020
2021 /*
2022 * Now we'll move the clean list to the free list.
2023 * It's impossible for this to fail: the only way
2024 * the free list can be updated is through this
2025 * code path, and only one CPU can own the clean list.
2026 * Thus, it would only be possible for this to fail if
2027 * this code were racing with dtrace_dynvar_clean().
2028 * (That is, if dtrace_dynvar_clean() updated the clean
2029 * list, and we ended up racing to update the free
2030 * list.) This race is prevented by the dtrace_sync()
2031 * in dtrace_dynvar_clean() -- which flushes the
2032 * owners of the clean lists out before resetting
2033 * the clean lists.
2034 */
2035 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2036 ASSERT(rval == NULL);
2037 goto retry;
2038 }
2039
2040 dvar = free;
2041 new_free = dvar->dtdv_next;
2042 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2043
2044 /*
2045 * We have now allocated a new chunk. We copy the tuple keys into the
2046 * tuple array and copy any referenced key data into the data space
2047 * following the tuple array. As we do this, we relocate dttk_value
2048 * in the final tuple to point to the key data address in the chunk.
2049 */
2050 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2051 dvar->dtdv_data = (void *)(kdata + ksize);
2052 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2053
2054 for (i = 0; i < nkeys; i++) {
2055 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2056 size_t kesize = key[i].dttk_size;
2057
2058 if (kesize != 0) {
2059 dtrace_bcopy(
2060 (const void *)(uintptr_t)key[i].dttk_value,
2061 (void *)kdata, kesize);
2062 dkey->dttk_value = kdata;
2063 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2064 } else {
2065 dkey->dttk_value = key[i].dttk_value;
2066 }
2067
2068 dkey->dttk_size = kesize;
2069 }
2070
2071 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2072 dvar->dtdv_hashval = hashval;
2073 dvar->dtdv_next = start;
2074
2075 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2076 return (dvar);
2077
2078 /*
2079 * The cas has failed. Either another CPU is adding an element to
2080 * this hash chain, or another CPU is deleting an element from this
2081 * hash chain. The simplest way to deal with both of these cases
2082 * (though not necessarily the most efficient) is to free our
2083 * allocated block and tail-call ourselves. Note that the free is
2084 * to the dirty list and _not_ to the free list. This is to prevent
2085 * races with allocators, above.
2086 */
2087 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2088
2089 dtrace_membar_producer();
2090
2091 do {
2092 free = dcpu->dtdsc_dirty;
2093 dvar->dtdv_next = free;
2094 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2095
2096 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2097 }
2098
2099 /*ARGSUSED*/
2100 static void
2101 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2102 {
2103 #pragma unused(arg) /* __APPLE__ */
2104 if ((int64_t)nval < (int64_t)*oval)
2105 *oval = nval;
2106 }
2107
2108 /*ARGSUSED*/
2109 static void
2110 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2111 {
2112 #pragma unused(arg) /* __APPLE__ */
2113 if ((int64_t)nval > (int64_t)*oval)
2114 *oval = nval;
2115 }
2116
2117 static void
2118 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2119 {
2120 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2121 int64_t val = (int64_t)nval;
2122
2123 if (val < 0) {
2124 for (i = 0; i < zero; i++) {
2125 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2126 quanta[i] += incr;
2127 return;
2128 }
2129 }
2130 } else {
2131 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2132 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2133 quanta[i - 1] += incr;
2134 return;
2135 }
2136 }
2137
2138 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2139 return;
2140 }
2141
2142 ASSERT(0);
2143 }
2144
2145 static void
2146 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2147 {
2148 uint64_t arg = *lquanta++;
2149 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2150 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2151 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2152 int32_t val = (int32_t)nval, level;
2153
2154 ASSERT(step != 0);
2155 ASSERT(levels != 0);
2156
2157 if (val < base) {
2158 /*
2159 * This is an underflow.
2160 */
2161 lquanta[0] += incr;
2162 return;
2163 }
2164
2165 level = (val - base) / step;
2166
2167 if (level < levels) {
2168 lquanta[level + 1] += incr;
2169 return;
2170 }
2171
2172 /*
2173 * This is an overflow.
2174 */
2175 lquanta[levels + 1] += incr;
2176 }
2177
2178 static int
2179 dtrace_aggregate_llquantize_bucket(int16_t factor, int16_t low, int16_t high,
2180 int16_t nsteps, int64_t value)
2181 {
2182 int64_t this = 1, last, next;
2183 int base = 1, order;
2184
2185 for (order = 0; order < low; ++order)
2186 this *= factor;
2187
2188 /*
2189 * If our value is less than our factor taken to the power of the
2190 * low order of magnitude, it goes into the zeroth bucket.
2191 */
2192 if (value < this)
2193 return 0;
2194 else
2195 last = this;
2196
2197 for (this *= factor; order <= high; ++order) {
2198 int nbuckets = this > nsteps ? nsteps : this;
2199
2200 /*
2201 * We should not generally get log/linear quantizations
2202 * with a high magnitude that allows 64-bits to
2203 * overflow, but we nonetheless protect against this
2204 * by explicitly checking for overflow, and clamping
2205 * our value accordingly.
2206 */
2207 next = this * factor;
2208 if (next < this) {
2209 value = this - 1;
2210 }
2211
2212 /*
2213 * If our value lies within this order of magnitude,
2214 * determine its position by taking the offset within
2215 * the order of magnitude, dividing by the bucket
2216 * width, and adding to our (accumulated) base.
2217 */
2218 if (value < this) {
2219 return (base + (value - last) / (this / nbuckets));
2220 }
2221
2222 base += nbuckets - (nbuckets / factor);
2223 last = this;
2224 this = next;
2225 }
2226
2227 /*
2228 * Our value is greater than or equal to our factor taken to the
2229 * power of one plus the high magnitude -- return the top bucket.
2230 */
2231 return base;
2232 }
2233
2234 static void
2235 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2236 {
2237 uint64_t arg = *llquanta++;
2238 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2239 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2240 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2241 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2242
2243 llquanta[dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, nval)] += incr;
2244 }
2245
2246 /*ARGSUSED*/
2247 static void
2248 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2249 {
2250 #pragma unused(arg) /* __APPLE__ */
2251 data[0]++;
2252 data[1] += nval;
2253 }
2254
2255 /*ARGSUSED*/
2256 static void
2257 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2258 {
2259 #pragma unused(arg) /* __APPLE__ */
2260 int64_t snval = (int64_t)nval;
2261 uint64_t tmp[2];
2262
2263 data[0]++;
2264 data[1] += nval;
2265
2266 /*
2267 * What we want to say here is:
2268 *
2269 * data[2] += nval * nval;
2270 *
2271 * But given that nval is 64-bit, we could easily overflow, so
2272 * we do this as 128-bit arithmetic.
2273 */
2274 if (snval < 0)
2275 snval = -snval;
2276
2277 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2278 dtrace_add_128(data + 2, tmp, data + 2);
2279 }
2280
2281 /*ARGSUSED*/
2282 static void
2283 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2284 {
2285 #pragma unused(nval, arg) /* __APPLE__ */
2286 *oval = *oval + 1;
2287 }
2288
2289 /*ARGSUSED*/
2290 static void
2291 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2292 {
2293 #pragma unused(arg) /* __APPLE__ */
2294 *oval += nval;
2295 }
2296
2297 /*
2298 * Aggregate given the tuple in the principal data buffer, and the aggregating
2299 * action denoted by the specified dtrace_aggregation_t. The aggregation
2300 * buffer is specified as the buf parameter. This routine does not return
2301 * failure; if there is no space in the aggregation buffer, the data will be
2302 * dropped, and a corresponding counter incremented.
2303 */
2304 static void
2305 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2306 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2307 {
2308 #pragma unused(arg)
2309 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2310 uint32_t i, ndx, size, fsize;
2311 uint32_t align = sizeof (uint64_t) - 1;
2312 dtrace_aggbuffer_t *agb;
2313 dtrace_aggkey_t *key;
2314 uint32_t hashval = 0, limit, isstr;
2315 caddr_t tomax, data, kdata;
2316 dtrace_actkind_t action;
2317 dtrace_action_t *act;
2318 uintptr_t offs;
2319
2320 if (buf == NULL)
2321 return;
2322
2323 if (!agg->dtag_hasarg) {
2324 /*
2325 * Currently, only quantize() and lquantize() take additional
2326 * arguments, and they have the same semantics: an increment
2327 * value that defaults to 1 when not present. If additional
2328 * aggregating actions take arguments, the setting of the
2329 * default argument value will presumably have to become more
2330 * sophisticated...
2331 */
2332 arg = 1;
2333 }
2334
2335 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2336 size = rec->dtrd_offset - agg->dtag_base;
2337 fsize = size + rec->dtrd_size;
2338
2339 ASSERT(dbuf->dtb_tomax != NULL);
2340 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2341
2342 if ((tomax = buf->dtb_tomax) == NULL) {
2343 dtrace_buffer_drop(buf);
2344 return;
2345 }
2346
2347 /*
2348 * The metastructure is always at the bottom of the buffer.
2349 */
2350 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2351 sizeof (dtrace_aggbuffer_t));
2352
2353 if (buf->dtb_offset == 0) {
2354 /*
2355 * We just kludge up approximately 1/8th of the size to be
2356 * buckets. If this guess ends up being routinely
2357 * off-the-mark, we may need to dynamically readjust this
2358 * based on past performance.
2359 */
2360 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2361
2362 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2363 (uintptr_t)tomax || hashsize == 0) {
2364 /*
2365 * We've been given a ludicrously small buffer;
2366 * increment our drop count and leave.
2367 */
2368 dtrace_buffer_drop(buf);
2369 return;
2370 }
2371
2372 /*
2373 * And now, a pathetic attempt to try to get a an odd (or
2374 * perchance, a prime) hash size for better hash distribution.
2375 */
2376 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2377 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2378
2379 agb->dtagb_hashsize = hashsize;
2380 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2381 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2382 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2383
2384 for (i = 0; i < agb->dtagb_hashsize; i++)
2385 agb->dtagb_hash[i] = NULL;
2386 }
2387
2388 ASSERT(agg->dtag_first != NULL);
2389 ASSERT(agg->dtag_first->dta_intuple);
2390
2391 /*
2392 * Calculate the hash value based on the key. Note that we _don't_
2393 * include the aggid in the hashing (but we will store it as part of
2394 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2395 * algorithm: a simple, quick algorithm that has no known funnels, and
2396 * gets good distribution in practice. The efficacy of the hashing
2397 * algorithm (and a comparison with other algorithms) may be found by
2398 * running the ::dtrace_aggstat MDB dcmd.
2399 */
2400 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2401 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2402 limit = i + act->dta_rec.dtrd_size;
2403 ASSERT(limit <= size);
2404 isstr = DTRACEACT_ISSTRING(act);
2405
2406 for (; i < limit; i++) {
2407 hashval += data[i];
2408 hashval += (hashval << 10);
2409 hashval ^= (hashval >> 6);
2410
2411 if (isstr && data[i] == '\0')
2412 break;
2413 }
2414 }
2415
2416 hashval += (hashval << 3);
2417 hashval ^= (hashval >> 11);
2418 hashval += (hashval << 15);
2419
2420 /*
2421 * Yes, the divide here is expensive -- but it's generally the least
2422 * of the performance issues given the amount of data that we iterate
2423 * over to compute hash values, compare data, etc.
2424 */
2425 ndx = hashval % agb->dtagb_hashsize;
2426
2427 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2428 ASSERT((caddr_t)key >= tomax);
2429 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2430
2431 if (hashval != key->dtak_hashval || key->dtak_size != size)
2432 continue;
2433
2434 kdata = key->dtak_data;
2435 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2436
2437 for (act = agg->dtag_first; act->dta_intuple;
2438 act = act->dta_next) {
2439 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2440 limit = i + act->dta_rec.dtrd_size;
2441 ASSERT(limit <= size);
2442 isstr = DTRACEACT_ISSTRING(act);
2443
2444 for (; i < limit; i++) {
2445 if (kdata[i] != data[i])
2446 goto next;
2447
2448 if (isstr && data[i] == '\0')
2449 break;
2450 }
2451 }
2452
2453 if (action != key->dtak_action) {
2454 /*
2455 * We are aggregating on the same value in the same
2456 * aggregation with two different aggregating actions.
2457 * (This should have been picked up in the compiler,
2458 * so we may be dealing with errant or devious DIF.)
2459 * This is an error condition; we indicate as much,
2460 * and return.
2461 */
2462 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2463 return;
2464 }
2465
2466 /*
2467 * This is a hit: we need to apply the aggregator to
2468 * the value at this key.
2469 */
2470 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2471 return;
2472 next:
2473 continue;
2474 }
2475
2476 /*
2477 * We didn't find it. We need to allocate some zero-filled space,
2478 * link it into the hash table appropriately, and apply the aggregator
2479 * to the (zero-filled) value.
2480 */
2481 offs = buf->dtb_offset;
2482 while (offs & (align - 1))
2483 offs += sizeof (uint32_t);
2484
2485 /*
2486 * If we don't have enough room to both allocate a new key _and_
2487 * its associated data, increment the drop count and return.
2488 */
2489 if ((uintptr_t)tomax + offs + fsize >
2490 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2491 dtrace_buffer_drop(buf);
2492 return;
2493 }
2494
2495 /*CONSTCOND*/
2496 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2497 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2498 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2499
2500 key->dtak_data = kdata = tomax + offs;
2501 buf->dtb_offset = offs + fsize;
2502
2503 /*
2504 * Now copy the data across.
2505 */
2506 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2507
2508 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2509 kdata[i] = data[i];
2510
2511 /*
2512 * Because strings are not zeroed out by default, we need to iterate
2513 * looking for actions that store strings, and we need to explicitly
2514 * pad these strings out with zeroes.
2515 */
2516 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2517 int nul;
2518
2519 if (!DTRACEACT_ISSTRING(act))
2520 continue;
2521
2522 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2523 limit = i + act->dta_rec.dtrd_size;
2524 ASSERT(limit <= size);
2525
2526 for (nul = 0; i < limit; i++) {
2527 if (nul) {
2528 kdata[i] = '\0';
2529 continue;
2530 }
2531
2532 if (data[i] != '\0')
2533 continue;
2534
2535 nul = 1;
2536 }
2537 }
2538
2539 for (i = size; i < fsize; i++)
2540 kdata[i] = 0;
2541
2542 key->dtak_hashval = hashval;
2543 key->dtak_size = size;
2544 key->dtak_action = action;
2545 key->dtak_next = agb->dtagb_hash[ndx];
2546 agb->dtagb_hash[ndx] = key;
2547
2548 /*
2549 * Finally, apply the aggregator.
2550 */
2551 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2552 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2553 }
2554
2555 /*
2556 * Given consumer state, this routine finds a speculation in the INACTIVE
2557 * state and transitions it into the ACTIVE state. If there is no speculation
2558 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2559 * incremented -- it is up to the caller to take appropriate action.
2560 */
2561 static int
2562 dtrace_speculation(dtrace_state_t *state)
2563 {
2564 int i = 0;
2565 dtrace_speculation_state_t current;
2566 uint32_t *stat = &state->dts_speculations_unavail, count;
2567
2568 while (i < state->dts_nspeculations) {
2569 dtrace_speculation_t *spec = &state->dts_speculations[i];
2570
2571 current = spec->dtsp_state;
2572
2573 if (current != DTRACESPEC_INACTIVE) {
2574 if (current == DTRACESPEC_COMMITTINGMANY ||
2575 current == DTRACESPEC_COMMITTING ||
2576 current == DTRACESPEC_DISCARDING)
2577 stat = &state->dts_speculations_busy;
2578 i++;
2579 continue;
2580 }
2581
2582 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2583 current, DTRACESPEC_ACTIVE) == current)
2584 return (i + 1);
2585 }
2586
2587 /*
2588 * We couldn't find a speculation. If we found as much as a single
2589 * busy speculation buffer, we'll attribute this failure as "busy"
2590 * instead of "unavail".
2591 */
2592 do {
2593 count = *stat;
2594 } while (dtrace_cas32(stat, count, count + 1) != count);
2595
2596 return (0);
2597 }
2598
2599 /*
2600 * This routine commits an active speculation. If the specified speculation
2601 * is not in a valid state to perform a commit(), this routine will silently do
2602 * nothing. The state of the specified speculation is transitioned according
2603 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2604 */
2605 static void
2606 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2607 dtrace_specid_t which)
2608 {
2609 dtrace_speculation_t *spec;
2610 dtrace_buffer_t *src, *dest;
2611 uintptr_t daddr, saddr, dlimit, slimit;
2612 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2613 intptr_t offs;
2614 uint64_t timestamp;
2615
2616 if (which == 0)
2617 return;
2618
2619 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2620 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2621 return;
2622 }
2623
2624 spec = &state->dts_speculations[which - 1];
2625 src = &spec->dtsp_buffer[cpu];
2626 dest = &state->dts_buffer[cpu];
2627
2628 do {
2629 current = spec->dtsp_state;
2630
2631 if (current == DTRACESPEC_COMMITTINGMANY)
2632 break;
2633
2634 switch (current) {
2635 case DTRACESPEC_INACTIVE:
2636 case DTRACESPEC_DISCARDING:
2637 return;
2638
2639 case DTRACESPEC_COMMITTING:
2640 /*
2641 * This is only possible if we are (a) commit()'ing
2642 * without having done a prior speculate() on this CPU
2643 * and (b) racing with another commit() on a different
2644 * CPU. There's nothing to do -- we just assert that
2645 * our offset is 0.
2646 */
2647 ASSERT(src->dtb_offset == 0);
2648 return;
2649
2650 case DTRACESPEC_ACTIVE:
2651 new = DTRACESPEC_COMMITTING;
2652 break;
2653
2654 case DTRACESPEC_ACTIVEONE:
2655 /*
2656 * This speculation is active on one CPU. If our
2657 * buffer offset is non-zero, we know that the one CPU
2658 * must be us. Otherwise, we are committing on a
2659 * different CPU from the speculate(), and we must
2660 * rely on being asynchronously cleaned.
2661 */
2662 if (src->dtb_offset != 0) {
2663 new = DTRACESPEC_COMMITTING;
2664 break;
2665 }
2666 /*FALLTHROUGH*/
2667
2668 case DTRACESPEC_ACTIVEMANY:
2669 new = DTRACESPEC_COMMITTINGMANY;
2670 break;
2671
2672 default:
2673 ASSERT(0);
2674 }
2675 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2676 current, new) != current);
2677
2678 /*
2679 * We have set the state to indicate that we are committing this
2680 * speculation. Now reserve the necessary space in the destination
2681 * buffer.
2682 */
2683 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2684 sizeof (uint64_t), state, NULL)) < 0) {
2685 dtrace_buffer_drop(dest);
2686 goto out;
2687 }
2688
2689 /*
2690 * We have sufficient space to copy the speculative buffer into the
2691 * primary buffer. First, modify the speculative buffer, filling
2692 * in the timestamp of all entries with the current time. The data
2693 * must have the commit() time rather than the time it was traced,
2694 * so that all entries in the primary buffer are in timestamp order.
2695 */
2696 timestamp = dtrace_gethrtime();
2697 saddr = (uintptr_t)src->dtb_tomax;
2698 slimit = saddr + src->dtb_offset;
2699 while (saddr < slimit) {
2700 size_t size;
2701 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2702
2703 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2704 saddr += sizeof (dtrace_epid_t);
2705 continue;
2706 }
2707
2708 ASSERT(dtrh->dtrh_epid <= ((dtrace_epid_t) state->dts_necbs));
2709 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2710
2711 ASSERT(saddr + size <= slimit);
2712 ASSERT(size >= sizeof(dtrace_rechdr_t));
2713 ASSERT(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh) == UINT64_MAX);
2714
2715 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2716
2717 saddr += size;
2718 }
2719
2720 /*
2721 * Copy the buffer across. (Note that this is a
2722 * highly subobtimal bcopy(); in the unlikely event that this becomes
2723 * a serious performance issue, a high-performance DTrace-specific
2724 * bcopy() should obviously be invented.)
2725 */
2726 daddr = (uintptr_t)dest->dtb_tomax + offs;
2727 dlimit = daddr + src->dtb_offset;
2728 saddr = (uintptr_t)src->dtb_tomax;
2729
2730 /*
2731 * First, the aligned portion.
2732 */
2733 while (dlimit - daddr >= sizeof (uint64_t)) {
2734 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2735
2736 daddr += sizeof (uint64_t);
2737 saddr += sizeof (uint64_t);
2738 }
2739
2740 /*
2741 * Now any left-over bit...
2742 */
2743 while (dlimit - daddr)
2744 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2745
2746 /*
2747 * Finally, commit the reserved space in the destination buffer.
2748 */
2749 dest->dtb_offset = offs + src->dtb_offset;
2750
2751 out:
2752 /*
2753 * If we're lucky enough to be the only active CPU on this speculation
2754 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2755 */
2756 if (current == DTRACESPEC_ACTIVE ||
2757 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2758 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2759 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2760 #pragma unused(rval) /* __APPLE__ */
2761
2762 ASSERT(rval == DTRACESPEC_COMMITTING);
2763 }
2764
2765 src->dtb_offset = 0;
2766 src->dtb_xamot_drops += src->dtb_drops;
2767 src->dtb_drops = 0;
2768 }
2769
2770 /*
2771 * This routine discards an active speculation. If the specified speculation
2772 * is not in a valid state to perform a discard(), this routine will silently
2773 * do nothing. The state of the specified speculation is transitioned
2774 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2775 */
2776 static void
2777 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2778 dtrace_specid_t which)
2779 {
2780 dtrace_speculation_t *spec;
2781 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2782 dtrace_buffer_t *buf;
2783
2784 if (which == 0)
2785 return;
2786
2787 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2788 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2789 return;
2790 }
2791
2792 spec = &state->dts_speculations[which - 1];
2793 buf = &spec->dtsp_buffer[cpu];
2794
2795 do {
2796 current = spec->dtsp_state;
2797
2798 switch (current) {
2799 case DTRACESPEC_INACTIVE:
2800 case DTRACESPEC_COMMITTINGMANY:
2801 case DTRACESPEC_COMMITTING:
2802 case DTRACESPEC_DISCARDING:
2803 return;
2804
2805 case DTRACESPEC_ACTIVE:
2806 case DTRACESPEC_ACTIVEMANY:
2807 new = DTRACESPEC_DISCARDING;
2808 break;
2809
2810 case DTRACESPEC_ACTIVEONE:
2811 if (buf->dtb_offset != 0) {
2812 new = DTRACESPEC_INACTIVE;
2813 } else {
2814 new = DTRACESPEC_DISCARDING;
2815 }
2816 break;
2817
2818 default:
2819 ASSERT(0);
2820 }
2821 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2822 current, new) != current);
2823
2824 buf->dtb_offset = 0;
2825 buf->dtb_drops = 0;
2826 }
2827
2828 /*
2829 * Note: not called from probe context. This function is called
2830 * asynchronously from cross call context to clean any speculations that are
2831 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2832 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2833 * speculation.
2834 */
2835 static void
2836 dtrace_speculation_clean_here(dtrace_state_t *state)
2837 {
2838 dtrace_icookie_t cookie;
2839 processorid_t cpu = CPU->cpu_id;
2840 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2841 dtrace_specid_t i;
2842
2843 cookie = dtrace_interrupt_disable();
2844
2845 if (dest->dtb_tomax == NULL) {
2846 dtrace_interrupt_enable(cookie);
2847 return;
2848 }
2849
2850 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2851 dtrace_speculation_t *spec = &state->dts_speculations[i];
2852 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2853
2854 if (src->dtb_tomax == NULL)
2855 continue;
2856
2857 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2858 src->dtb_offset = 0;
2859 continue;
2860 }
2861
2862 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2863 continue;
2864
2865 if (src->dtb_offset == 0)
2866 continue;
2867
2868 dtrace_speculation_commit(state, cpu, i + 1);
2869 }
2870
2871 dtrace_interrupt_enable(cookie);
2872 }
2873
2874 /*
2875 * Note: not called from probe context. This function is called
2876 * asynchronously (and at a regular interval) to clean any speculations that
2877 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2878 * is work to be done, it cross calls all CPUs to perform that work;
2879 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2880 * INACTIVE state until they have been cleaned by all CPUs.
2881 */
2882 static void
2883 dtrace_speculation_clean(dtrace_state_t *state)
2884 {
2885 int work = 0;
2886 uint32_t rv;
2887 dtrace_specid_t i;
2888
2889 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2890 dtrace_speculation_t *spec = &state->dts_speculations[i];
2891
2892 ASSERT(!spec->dtsp_cleaning);
2893
2894 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2895 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2896 continue;
2897
2898 work++;
2899 spec->dtsp_cleaning = 1;
2900 }
2901
2902 if (!work)
2903 return;
2904
2905 dtrace_xcall(DTRACE_CPUALL,
2906 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2907
2908 /*
2909 * We now know that all CPUs have committed or discarded their
2910 * speculation buffers, as appropriate. We can now set the state
2911 * to inactive.
2912 */
2913 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2914 dtrace_speculation_t *spec = &state->dts_speculations[i];
2915 dtrace_speculation_state_t current, new;
2916
2917 if (!spec->dtsp_cleaning)
2918 continue;
2919
2920 current = spec->dtsp_state;
2921 ASSERT(current == DTRACESPEC_DISCARDING ||
2922 current == DTRACESPEC_COMMITTINGMANY);
2923
2924 new = DTRACESPEC_INACTIVE;
2925
2926 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2927 ASSERT(rv == current);
2928 spec->dtsp_cleaning = 0;
2929 }
2930 }
2931
2932 /*
2933 * Called as part of a speculate() to get the speculative buffer associated
2934 * with a given speculation. Returns NULL if the specified speculation is not
2935 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
2936 * the active CPU is not the specified CPU -- the speculation will be
2937 * atomically transitioned into the ACTIVEMANY state.
2938 */
2939 static dtrace_buffer_t *
2940 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2941 dtrace_specid_t which)
2942 {
2943 dtrace_speculation_t *spec;
2944 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2945 dtrace_buffer_t *buf;
2946
2947 if (which == 0)
2948 return (NULL);
2949
2950 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2951 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2952 return (NULL);
2953 }
2954
2955 spec = &state->dts_speculations[which - 1];
2956 buf = &spec->dtsp_buffer[cpuid];
2957
2958 do {
2959 current = spec->dtsp_state;
2960
2961 switch (current) {
2962 case DTRACESPEC_INACTIVE:
2963 case DTRACESPEC_COMMITTINGMANY:
2964 case DTRACESPEC_DISCARDING:
2965 return (NULL);
2966
2967 case DTRACESPEC_COMMITTING:
2968 ASSERT(buf->dtb_offset == 0);
2969 return (NULL);
2970
2971 case DTRACESPEC_ACTIVEONE:
2972 /*
2973 * This speculation is currently active on one CPU.
2974 * Check the offset in the buffer; if it's non-zero,
2975 * that CPU must be us (and we leave the state alone).
2976 * If it's zero, assume that we're starting on a new
2977 * CPU -- and change the state to indicate that the
2978 * speculation is active on more than one CPU.
2979 */
2980 if (buf->dtb_offset != 0)
2981 return (buf);
2982
2983 new = DTRACESPEC_ACTIVEMANY;
2984 break;
2985
2986 case DTRACESPEC_ACTIVEMANY:
2987 return (buf);
2988
2989 case DTRACESPEC_ACTIVE:
2990 new = DTRACESPEC_ACTIVEONE;
2991 break;
2992
2993 default:
2994 ASSERT(0);
2995 }
2996 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2997 current, new) != current);
2998
2999 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3000 return (buf);
3001 }
3002
3003 /*
3004 * Return a string. In the event that the user lacks the privilege to access
3005 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3006 * don't fail access checking.
3007 *
3008 * dtrace_dif_variable() uses this routine as a helper for various
3009 * builtin values such as 'execname' and 'probefunc.'
3010 */
3011 static
3012 uintptr_t
3013 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3014 dtrace_mstate_t *mstate)
3015 {
3016 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3017 uintptr_t ret;
3018 size_t strsz;
3019
3020 /*
3021 * The easy case: this probe is allowed to read all of memory, so
3022 * we can just return this as a vanilla pointer.
3023 */
3024 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3025 return (addr);
3026
3027 /*
3028 * This is the tougher case: we copy the string in question from
3029 * kernel memory into scratch memory and return it that way: this
3030 * ensures that we won't trip up when access checking tests the
3031 * BYREF return value.
3032 */
3033 strsz = dtrace_strlen((char *)addr, size) + 1;
3034
3035 if (mstate->dtms_scratch_ptr + strsz >
3036 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3037 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3038 return (0);
3039 }
3040
3041 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3042 strsz);
3043 ret = mstate->dtms_scratch_ptr;
3044 mstate->dtms_scratch_ptr += strsz;
3045 return (ret);
3046 }
3047
3048 /*
3049 * This function implements the DIF emulator's variable lookups. The emulator
3050 * passes a reserved variable identifier and optional built-in array index.
3051 */
3052 static uint64_t
3053 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3054 uint64_t ndx)
3055 {
3056 /*
3057 * If we're accessing one of the uncached arguments, we'll turn this
3058 * into a reference in the args array.
3059 */
3060 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3061 ndx = v - DIF_VAR_ARG0;
3062 v = DIF_VAR_ARGS;
3063 }
3064
3065 switch (v) {
3066 case DIF_VAR_ARGS:
3067 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3068 if (ndx >= sizeof (mstate->dtms_arg) /
3069 sizeof (mstate->dtms_arg[0])) {
3070 /*
3071 * APPLE NOTE: Account for introduction of __dtrace_probe()
3072 */
3073 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3074 dtrace_provider_t *pv;
3075 uint64_t val;
3076
3077 pv = mstate->dtms_probe->dtpr_provider;
3078 if (pv->dtpv_pops.dtps_getargval != NULL)
3079 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3080 mstate->dtms_probe->dtpr_id,
3081 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3082 /* Special case access of arg5 as passed to dtrace_probe_error() (which see.) */
3083 else if (mstate->dtms_probe->dtpr_id == dtrace_probeid_error && ndx == 5) {
3084 return ((dtrace_state_t *)(uintptr_t)(mstate->dtms_arg[0]))->dts_arg_error_illval;
3085 }
3086
3087 else
3088 val = dtrace_getarg(ndx, aframes);
3089
3090 /*
3091 * This is regrettably required to keep the compiler
3092 * from tail-optimizing the call to dtrace_getarg().
3093 * The condition always evaluates to true, but the
3094 * compiler has no way of figuring that out a priori.
3095 * (None of this would be necessary if the compiler
3096 * could be relied upon to _always_ tail-optimize
3097 * the call to dtrace_getarg() -- but it can't.)
3098 */
3099 if (mstate->dtms_probe != NULL)
3100 return (val);
3101
3102 ASSERT(0);
3103 }
3104
3105 return (mstate->dtms_arg[ndx]);
3106
3107 case DIF_VAR_UREGS: {
3108 thread_t thread;
3109
3110 if (!dtrace_priv_proc(state))
3111 return (0);
3112
3113 if ((thread = current_thread()) == NULL) {
3114 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3115 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3116 return (0);
3117 }
3118
3119 return (dtrace_getreg(find_user_regs(thread), ndx));
3120 }
3121
3122
3123 case DIF_VAR_CURTHREAD:
3124 if (!dtrace_priv_kernel(state))
3125 return (0);
3126
3127 return ((uint64_t)(uintptr_t)current_thread());
3128
3129 case DIF_VAR_TIMESTAMP:
3130 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3131 mstate->dtms_timestamp = dtrace_gethrtime();
3132 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3133 }
3134 return (mstate->dtms_timestamp);
3135
3136 case DIF_VAR_VTIMESTAMP:
3137 ASSERT(dtrace_vtime_references != 0);
3138 return (dtrace_get_thread_vtime(current_thread()));
3139
3140 case DIF_VAR_WALLTIMESTAMP:
3141 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3142 mstate->dtms_walltimestamp = dtrace_gethrestime();
3143 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3144 }
3145 return (mstate->dtms_walltimestamp);
3146
3147 case DIF_VAR_MACHTIMESTAMP:
3148 if (!(mstate->dtms_present & DTRACE_MSTATE_MACHTIMESTAMP)) {
3149 mstate->dtms_machtimestamp = mach_absolute_time();
3150 mstate->dtms_present |= DTRACE_MSTATE_MACHTIMESTAMP;
3151 }
3152 return (mstate->dtms_machtimestamp);
3153
3154 case DIF_VAR_CPU:
3155 return ((uint64_t) dtrace_get_thread_last_cpu_id(current_thread()));
3156
3157 case DIF_VAR_IPL:
3158 if (!dtrace_priv_kernel(state))
3159 return (0);
3160 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3161 mstate->dtms_ipl = dtrace_getipl();
3162 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3163 }
3164 return (mstate->dtms_ipl);
3165
3166 case DIF_VAR_EPID:
3167 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3168 return (mstate->dtms_epid);
3169
3170 case DIF_VAR_ID:
3171 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3172 return (mstate->dtms_probe->dtpr_id);
3173
3174 case DIF_VAR_STACKDEPTH:
3175 if (!dtrace_priv_kernel(state))
3176 return (0);
3177 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3178 /*
3179 * APPLE NOTE: Account for introduction of __dtrace_probe()
3180 */
3181 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3182
3183 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3184 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3185 }
3186 return (mstate->dtms_stackdepth);
3187
3188 case DIF_VAR_USTACKDEPTH:
3189 if (!dtrace_priv_proc(state))
3190 return (0);
3191 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3192 /*
3193 * See comment in DIF_VAR_PID.
3194 */
3195 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3196 CPU_ON_INTR(CPU)) {
3197 mstate->dtms_ustackdepth = 0;
3198 } else {
3199 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3200 mstate->dtms_ustackdepth =
3201 dtrace_getustackdepth();
3202 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3203 }
3204 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3205 }
3206 return (mstate->dtms_ustackdepth);
3207
3208 case DIF_VAR_CALLER:
3209 if (!dtrace_priv_kernel(state))
3210 return (0);
3211 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3212 /*
3213 * APPLE NOTE: Account for introduction of __dtrace_probe()
3214 */
3215 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3216
3217 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3218 /*
3219 * If this is an unanchored probe, we are
3220 * required to go through the slow path:
3221 * dtrace_caller() only guarantees correct
3222 * results for anchored probes.
3223 */
3224 pc_t caller[2];
3225
3226 dtrace_getpcstack(caller, 2, aframes,
3227 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3228 mstate->dtms_caller = caller[1];
3229 } else if ((mstate->dtms_caller =
3230 dtrace_caller(aframes)) == (uintptr_t)-1) {
3231 /*
3232 * We have failed to do this the quick way;
3233 * we must resort to the slower approach of
3234 * calling dtrace_getpcstack().
3235 */
3236 pc_t caller;
3237
3238 dtrace_getpcstack(&caller, 1, aframes, NULL);
3239 mstate->dtms_caller = caller;
3240 }
3241
3242 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3243 }
3244 return (mstate->dtms_caller);
3245
3246 case DIF_VAR_UCALLER:
3247 if (!dtrace_priv_proc(state))
3248 return (0);
3249
3250 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3251 uint64_t ustack[3];
3252
3253 /*
3254 * dtrace_getupcstack() fills in the first uint64_t
3255 * with the current PID. The second uint64_t will
3256 * be the program counter at user-level. The third
3257 * uint64_t will contain the caller, which is what
3258 * we're after.
3259 */
3260 ustack[2] = 0;
3261 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3262 dtrace_getupcstack(ustack, 3);
3263 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3264 mstate->dtms_ucaller = ustack[2];
3265 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3266 }
3267
3268 return (mstate->dtms_ucaller);
3269
3270 case DIF_VAR_PROBEPROV:
3271 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3272 return (dtrace_dif_varstr(
3273 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3274 state, mstate));
3275
3276 case DIF_VAR_PROBEMOD:
3277 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3278 return (dtrace_dif_varstr(
3279 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3280 state, mstate));
3281
3282 case DIF_VAR_PROBEFUNC:
3283 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3284 return (dtrace_dif_varstr(
3285 (uintptr_t)mstate->dtms_probe->dtpr_func,
3286 state, mstate));
3287
3288 case DIF_VAR_PROBENAME:
3289 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3290 return (dtrace_dif_varstr(
3291 (uintptr_t)mstate->dtms_probe->dtpr_name,
3292 state, mstate));
3293
3294 case DIF_VAR_PID:
3295 if (!dtrace_priv_proc_relaxed(state))
3296 return (0);
3297
3298 /*
3299 * Note that we are assuming that an unanchored probe is
3300 * always due to a high-level interrupt. (And we're assuming
3301 * that there is only a single high level interrupt.)
3302 */
3303 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3304 /* Anchored probe that fires while on an interrupt accrues to process 0 */
3305 return 0;
3306
3307 return ((uint64_t)dtrace_proc_selfpid());
3308
3309 case DIF_VAR_PPID:
3310 if (!dtrace_priv_proc_relaxed(state))
3311 return (0);
3312
3313 /*
3314 * See comment in DIF_VAR_PID.
3315 */
3316 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3317 return (0);
3318
3319 return ((uint64_t)dtrace_proc_selfppid());
3320
3321 case DIF_VAR_TID:
3322 /* We do not need to check for null current_thread() */
3323 return thread_tid(current_thread()); /* globally unique */
3324
3325 case DIF_VAR_PTHREAD_SELF:
3326 if (!dtrace_priv_proc(state))
3327 return (0);
3328
3329 /* Not currently supported, but we should be able to delta the dispatchqaddr and dispatchqoffset to get pthread_self */
3330 return 0;
3331
3332 case DIF_VAR_DISPATCHQADDR:
3333 if (!dtrace_priv_proc(state))
3334 return (0);
3335
3336 /* We do not need to check for null current_thread() */
3337 return thread_dispatchqaddr(current_thread());
3338
3339 case DIF_VAR_EXECNAME:
3340 {
3341 char *xname = (char *)mstate->dtms_scratch_ptr;
3342 size_t scratch_size = MAXCOMLEN+1;
3343
3344 /* The scratch allocation's lifetime is that of the clause. */
3345 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3346 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3347 return 0;
3348 }
3349
3350 if (!dtrace_priv_proc_relaxed(state))
3351 return (0);
3352
3353 mstate->dtms_scratch_ptr += scratch_size;
3354 proc_selfname( xname, scratch_size );
3355
3356 return ((uint64_t)(uintptr_t)xname);
3357 }
3358
3359
3360 case DIF_VAR_ZONENAME:
3361 {
3362 /* scratch_size is equal to length('global') + 1 for the null-terminator. */
3363 char *zname = (char *)mstate->dtms_scratch_ptr;
3364 size_t scratch_size = 6 + 1;
3365
3366 if (!dtrace_priv_proc(state))
3367 return (0);
3368
3369 /* The scratch allocation's lifetime is that of the clause. */
3370 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3371 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3372 return 0;
3373 }
3374
3375 mstate->dtms_scratch_ptr += scratch_size;
3376
3377 /* The kernel does not provide zonename, it will always return 'global'. */
3378 strlcpy(zname, "global", scratch_size);
3379
3380 return ((uint64_t)(uintptr_t)zname);
3381 }
3382
3383 case DIF_VAR_UID:
3384 if (!dtrace_priv_proc_relaxed(state))
3385 return (0);
3386
3387 /*
3388 * See comment in DIF_VAR_PID.
3389 */
3390 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3391 return (0);
3392
3393 return ((uint64_t) dtrace_proc_selfruid());
3394
3395 case DIF_VAR_GID:
3396 if (!dtrace_priv_proc(state))
3397 return (0);
3398
3399 /*
3400 * See comment in DIF_VAR_PID.
3401 */
3402 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3403 return (0);
3404
3405 if (dtrace_CRED() != NULL)
3406 /* Credential does not require lazy initialization. */
3407 return ((uint64_t)kauth_getgid());
3408 else {
3409 /* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3410 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3411 return -1ULL;
3412 }
3413
3414 case DIF_VAR_ERRNO: {
3415 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
3416 if (!dtrace_priv_proc(state))
3417 return (0);
3418
3419 /*
3420 * See comment in DIF_VAR_PID.
3421 */
3422 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3423 return (0);
3424
3425 if (uthread)
3426 return (uint64_t)uthread->t_dtrace_errno;
3427 else {
3428 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3429 return -1ULL;
3430 }
3431 }
3432
3433 default:
3434 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3435 return (0);
3436 }
3437 }
3438
3439 /*
3440 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3441 * Notice that we don't bother validating the proper number of arguments or
3442 * their types in the tuple stack. This isn't needed because all argument
3443 * interpretation is safe because of our load safety -- the worst that can
3444 * happen is that a bogus program can obtain bogus results.
3445 */
3446 static void
3447 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3448 dtrace_key_t *tupregs, int nargs,
3449 dtrace_mstate_t *mstate, dtrace_state_t *state)
3450 {
3451 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3452 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3453 dtrace_vstate_t *vstate = &state->dts_vstate;
3454
3455 #if !defined(__APPLE__)
3456 union {
3457 mutex_impl_t mi;
3458 uint64_t mx;
3459 } m;
3460
3461 union {
3462 krwlock_t ri;
3463 uintptr_t rw;
3464 } r;
3465 #else
3466 /* FIXME: awaits lock/mutex work */
3467 #endif /* __APPLE__ */
3468
3469 switch (subr) {
3470 case DIF_SUBR_RAND:
3471 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3472 break;
3473
3474 #if !defined(__APPLE__)
3475 case DIF_SUBR_MUTEX_OWNED:
3476 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3477 mstate, vstate)) {
3478 regs[rd] = 0;
3479 break;
3480 }
3481
3482 m.mx = dtrace_load64(tupregs[0].dttk_value);
3483 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3484 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3485 else
3486 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3487 break;
3488
3489 case DIF_SUBR_MUTEX_OWNER:
3490 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3491 mstate, vstate)) {
3492 regs[rd] = 0;
3493 break;
3494 }
3495
3496 m.mx = dtrace_load64(tupregs[0].dttk_value);
3497 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3498 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3499 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3500 else
3501 regs[rd] = 0;
3502 break;
3503
3504 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3505 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3506 mstate, vstate)) {
3507 regs[rd] = 0;
3508 break;
3509 }
3510
3511 m.mx = dtrace_load64(tupregs[0].dttk_value);
3512 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3513 break;
3514
3515 case DIF_SUBR_MUTEX_TYPE_SPIN:
3516 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3517 mstate, vstate)) {
3518 regs[rd] = 0;
3519 break;
3520 }
3521
3522 m.mx = dtrace_load64(tupregs[0].dttk_value);
3523 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3524 break;
3525
3526 case DIF_SUBR_RW_READ_HELD: {
3527 uintptr_t tmp;
3528
3529 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3530 mstate, vstate)) {
3531 regs[rd] = 0;
3532 break;
3533 }
3534
3535 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3536 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3537 break;
3538 }
3539
3540 case DIF_SUBR_RW_WRITE_HELD:
3541 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3542 mstate, vstate)) {
3543 regs[rd] = 0;
3544 break;
3545 }
3546
3547 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3548 regs[rd] = _RW_WRITE_HELD(&r.ri);
3549 break;
3550
3551 case DIF_SUBR_RW_ISWRITER:
3552 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3553 mstate, vstate)) {
3554 regs[rd] = 0;
3555 break;
3556 }
3557
3558 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3559 regs[rd] = _RW_ISWRITER(&r.ri);
3560 break;
3561 #else
3562 /* FIXME: awaits lock/mutex work */
3563 #endif /* __APPLE__ */
3564
3565 case DIF_SUBR_BCOPY: {
3566 /*
3567 * We need to be sure that the destination is in the scratch
3568 * region -- no other region is allowed.
3569 */
3570 uintptr_t src = tupregs[0].dttk_value;
3571 uintptr_t dest = tupregs[1].dttk_value;
3572 size_t size = tupregs[2].dttk_value;
3573
3574 if (!dtrace_inscratch(dest, size, mstate)) {
3575 *flags |= CPU_DTRACE_BADADDR;
3576 *illval = regs[rd];
3577 break;
3578 }
3579
3580 if (!dtrace_canload(src, size, mstate, vstate)) {
3581 regs[rd] = 0;
3582 break;
3583 }
3584
3585 dtrace_bcopy((void *)src, (void *)dest, size);
3586 break;
3587 }
3588
3589 case DIF_SUBR_ALLOCA:
3590 case DIF_SUBR_COPYIN: {
3591 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3592 uint64_t size =
3593 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3594 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3595
3596 /*
3597 * This action doesn't require any credential checks since
3598 * probes will not activate in user contexts to which the
3599 * enabling user does not have permissions.
3600 */
3601
3602 /*
3603 * Rounding up the user allocation size could have overflowed
3604 * a large, bogus allocation (like -1ULL) to 0.
3605 */
3606 if (scratch_size < size ||
3607 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3608 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3609 regs[rd] = 0;
3610 break;
3611 }
3612
3613 if (subr == DIF_SUBR_COPYIN) {
3614 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3615 if (dtrace_priv_proc(state))
3616 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3617 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3618 }
3619
3620 mstate->dtms_scratch_ptr += scratch_size;
3621 regs[rd] = dest;
3622 break;
3623 }
3624
3625 case DIF_SUBR_COPYINTO: {
3626 uint64_t size = tupregs[1].dttk_value;
3627 uintptr_t dest = tupregs[2].dttk_value;
3628
3629 /*
3630 * This action doesn't require any credential checks since
3631 * probes will not activate in user contexts to which the
3632 * enabling user does not have permissions.
3633 */
3634 if (!dtrace_inscratch(dest, size, mstate)) {
3635 *flags |= CPU_DTRACE_BADADDR;
3636 *illval = regs[rd];
3637 break;
3638 }
3639
3640 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3641 if (dtrace_priv_proc(state))
3642 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3643 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3644 break;
3645 }
3646
3647 case DIF_SUBR_COPYINSTR: {
3648 uintptr_t dest = mstate->dtms_scratch_ptr;
3649 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3650
3651 if (nargs > 1 && tupregs[1].dttk_value < size)
3652 size = tupregs[1].dttk_value + 1;
3653
3654 /*
3655 * This action doesn't require any credential checks since
3656 * probes will not activate in user contexts to which the
3657 * enabling user does not have permissions.
3658 */
3659 if (!DTRACE_INSCRATCH(mstate, size)) {
3660 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3661 regs[rd] = 0;
3662 break;
3663 }
3664
3665 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3666 if (dtrace_priv_proc(state))
3667 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3668 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3669
3670 ((char *)dest)[size - 1] = '\0';
3671 mstate->dtms_scratch_ptr += size;
3672 regs[rd] = dest;
3673 break;
3674 }
3675
3676 case DIF_SUBR_MSGSIZE:
3677 case DIF_SUBR_MSGDSIZE: {
3678 /* Darwin does not implement SysV streams messages */
3679 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3680 regs[rd] = 0;
3681 break;
3682 }
3683
3684 case DIF_SUBR_PROGENYOF: {
3685 pid_t pid = tupregs[0].dttk_value;
3686 struct proc *p = current_proc();
3687 int rval = 0, lim = nprocs;
3688
3689 while(p && (lim-- > 0)) {
3690 pid_t ppid;
3691
3692 ppid = (pid_t)dtrace_load32((uintptr_t)&(p->p_pid));
3693 if (*flags & CPU_DTRACE_FAULT)
3694 break;
3695
3696 if (ppid == pid) {
3697 rval = 1;
3698 break;
3699 }
3700
3701 if (ppid == 0)
3702 break; /* Can't climb process tree any further. */
3703
3704 p = (struct proc *)dtrace_loadptr((uintptr_t)&(p->p_pptr));
3705 if (*flags & CPU_DTRACE_FAULT)
3706 break;
3707 }
3708
3709 regs[rd] = rval;
3710 break;
3711 }
3712
3713 case DIF_SUBR_SPECULATION:
3714 regs[rd] = dtrace_speculation(state);
3715 break;
3716
3717
3718 case DIF_SUBR_COPYOUT: {
3719 uintptr_t kaddr = tupregs[0].dttk_value;
3720 user_addr_t uaddr = tupregs[1].dttk_value;
3721 uint64_t size = tupregs[2].dttk_value;
3722
3723 if (!dtrace_destructive_disallow &&
3724 dtrace_priv_proc_control(state) &&
3725 !dtrace_istoxic(kaddr, size) &&
3726 dtrace_canload(kaddr, size, mstate, vstate)) {
3727 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3728 dtrace_copyout(kaddr, uaddr, size, flags);
3729 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3730 }
3731 break;
3732 }
3733
3734 case DIF_SUBR_COPYOUTSTR: {
3735 uintptr_t kaddr = tupregs[0].dttk_value;
3736 user_addr_t uaddr = tupregs[1].dttk_value;
3737 uint64_t size = tupregs[2].dttk_value;
3738
3739 if (!dtrace_destructive_disallow &&
3740 dtrace_priv_proc_control(state) &&
3741 !dtrace_istoxic(kaddr, size) &&
3742 dtrace_strcanload(kaddr, size, mstate, vstate)) {
3743 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3744 dtrace_copyoutstr(kaddr, uaddr, size, flags);
3745 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3746 }
3747 break;
3748 }
3749
3750 case DIF_SUBR_STRLEN: {
3751 size_t sz;
3752 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3753 sz = dtrace_strlen((char *)addr,
3754 state->dts_options[DTRACEOPT_STRSIZE]);
3755
3756 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3757 regs[rd] = 0;
3758 break;
3759 }
3760
3761 regs[rd] = sz;
3762
3763 break;
3764 }
3765
3766 case DIF_SUBR_STRCHR:
3767 case DIF_SUBR_STRRCHR: {
3768 /*
3769 * We're going to iterate over the string looking for the
3770 * specified character. We will iterate until we have reached
3771 * the string length or we have found the character. If this
3772 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3773 * of the specified character instead of the first.
3774 */
3775 uintptr_t saddr = tupregs[0].dttk_value;
3776 uintptr_t addr = tupregs[0].dttk_value;
3777 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3778 char c, target = (char)tupregs[1].dttk_value;
3779
3780 for (regs[rd] = 0; addr < limit; addr++) {
3781 if ((c = dtrace_load8(addr)) == target) {
3782 regs[rd] = addr;
3783
3784 if (subr == DIF_SUBR_STRCHR)
3785 break;
3786 }
3787
3788 if (c == '\0')
3789 break;
3790 }
3791
3792 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3793 regs[rd] = 0;
3794 break;
3795 }
3796
3797 break;
3798 }
3799
3800 case DIF_SUBR_STRSTR:
3801 case DIF_SUBR_INDEX:
3802 case DIF_SUBR_RINDEX: {
3803 /*
3804 * We're going to iterate over the string looking for the
3805 * specified string. We will iterate until we have reached
3806 * the string length or we have found the string. (Yes, this
3807 * is done in the most naive way possible -- but considering
3808 * that the string we're searching for is likely to be
3809 * relatively short, the complexity of Rabin-Karp or similar
3810 * hardly seems merited.)
3811 */
3812 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3813 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3814 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3815 size_t len = dtrace_strlen(addr, size);
3816 size_t sublen = dtrace_strlen(substr, size);
3817 char *limit = addr + len, *orig = addr;
3818 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3819 int inc = 1;
3820
3821 regs[rd] = notfound;
3822
3823 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3824 regs[rd] = 0;
3825 break;
3826 }
3827
3828 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3829 vstate)) {
3830 regs[rd] = 0;
3831 break;
3832 }
3833
3834 /*
3835 * strstr() and index()/rindex() have similar semantics if
3836 * both strings are the empty string: strstr() returns a
3837 * pointer to the (empty) string, and index() and rindex()
3838 * both return index 0 (regardless of any position argument).
3839 */
3840 if (sublen == 0 && len == 0) {
3841 if (subr == DIF_SUBR_STRSTR)
3842 regs[rd] = (uintptr_t)addr;
3843 else
3844 regs[rd] = 0;
3845 break;
3846 }
3847
3848 if (subr != DIF_SUBR_STRSTR) {
3849 if (subr == DIF_SUBR_RINDEX) {
3850 limit = orig - 1;
3851 addr += len;
3852 inc = -1;
3853 }
3854
3855 /*
3856 * Both index() and rindex() take an optional position
3857 * argument that denotes the starting position.
3858 */
3859 if (nargs == 3) {
3860 int64_t pos = (int64_t)tupregs[2].dttk_value;
3861
3862 /*
3863 * If the position argument to index() is
3864 * negative, Perl implicitly clamps it at
3865 * zero. This semantic is a little surprising
3866 * given the special meaning of negative
3867 * positions to similar Perl functions like
3868 * substr(), but it appears to reflect a
3869 * notion that index() can start from a
3870 * negative index and increment its way up to
3871 * the string. Given this notion, Perl's
3872 * rindex() is at least self-consistent in
3873 * that it implicitly clamps positions greater
3874 * than the string length to be the string
3875 * length. Where Perl completely loses
3876 * coherence, however, is when the specified
3877 * substring is the empty string (""). In
3878 * this case, even if the position is
3879 * negative, rindex() returns 0 -- and even if
3880 * the position is greater than the length,
3881 * index() returns the string length. These
3882 * semantics violate the notion that index()
3883 * should never return a value less than the
3884 * specified position and that rindex() should
3885 * never return a value greater than the
3886 * specified position. (One assumes that
3887 * these semantics are artifacts of Perl's
3888 * implementation and not the results of
3889 * deliberate design -- it beggars belief that
3890 * even Larry Wall could desire such oddness.)
3891 * While in the abstract one would wish for
3892 * consistent position semantics across
3893 * substr(), index() and rindex() -- or at the
3894 * very least self-consistent position
3895 * semantics for index() and rindex() -- we
3896 * instead opt to keep with the extant Perl
3897 * semantics, in all their broken glory. (Do
3898 * we have more desire to maintain Perl's
3899 * semantics than Perl does? Probably.)
3900 */
3901 if (subr == DIF_SUBR_RINDEX) {
3902 if (pos < 0) {
3903 if (sublen == 0)
3904 regs[rd] = 0;
3905 break;
3906 }
3907
3908 if ((size_t)pos > len)
3909 pos = len;
3910 } else {
3911 if (pos < 0)
3912 pos = 0;
3913
3914 if ((size_t)pos >= len) {
3915 if (sublen == 0)
3916 regs[rd] = len;
3917 break;
3918 }
3919 }
3920
3921 addr = orig + pos;
3922 }
3923 }
3924
3925 for (regs[rd] = notfound; addr != limit; addr += inc) {
3926 if (dtrace_strncmp(addr, substr, sublen) == 0) {
3927 if (subr != DIF_SUBR_STRSTR) {
3928 /*
3929 * As D index() and rindex() are
3930 * modeled on Perl (and not on awk),
3931 * we return a zero-based (and not a
3932 * one-based) index. (For you Perl
3933 * weenies: no, we're not going to add
3934 * $[ -- and shouldn't you be at a con
3935 * or something?)
3936 */
3937 regs[rd] = (uintptr_t)(addr - orig);
3938 break;
3939 }
3940
3941 ASSERT(subr == DIF_SUBR_STRSTR);
3942 regs[rd] = (uintptr_t)addr;
3943 break;
3944 }
3945 }
3946
3947 break;
3948 }
3949
3950 case DIF_SUBR_STRTOK: {
3951 uintptr_t addr = tupregs[0].dttk_value;
3952 uintptr_t tokaddr = tupregs[1].dttk_value;
3953 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3954 uintptr_t limit, toklimit = tokaddr + size;
3955 char *dest = (char *)mstate->dtms_scratch_ptr;
3956 uint8_t c='\0', tokmap[32]; /* 256 / 8 */
3957 uint64_t i = 0;
3958
3959 /*
3960 * Check both the token buffer and (later) the input buffer,
3961 * since both could be non-scratch addresses.
3962 */
3963 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3964 regs[rd] = 0;
3965 break;
3966 }
3967
3968 if (!DTRACE_INSCRATCH(mstate, size)) {
3969 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3970 regs[rd] = 0;
3971 break;
3972 }
3973
3974 if (addr == 0) {
3975 /*
3976 * If the address specified is NULL, we use our saved
3977 * strtok pointer from the mstate. Note that this
3978 * means that the saved strtok pointer is _only_
3979 * valid within multiple enablings of the same probe --
3980 * it behaves like an implicit clause-local variable.
3981 */
3982 addr = mstate->dtms_strtok;
3983 } else {
3984 /*
3985 * If the user-specified address is non-NULL we must
3986 * access check it. This is the only time we have
3987 * a chance to do so, since this address may reside
3988 * in the string table of this clause-- future calls
3989 * (when we fetch addr from mstate->dtms_strtok)
3990 * would fail this access check.
3991 */
3992 if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3993 regs[rd] = 0;
3994 break;
3995 }
3996 }
3997
3998 /*
3999 * First, zero the token map, and then process the token
4000 * string -- setting a bit in the map for every character
4001 * found in the token string.
4002 */
4003 for (i = 0; i < (int)sizeof (tokmap); i++)
4004 tokmap[i] = 0;
4005
4006 for (; tokaddr < toklimit; tokaddr++) {
4007 if ((c = dtrace_load8(tokaddr)) == '\0')
4008 break;
4009
4010 ASSERT((c >> 3) < sizeof (tokmap));
4011 tokmap[c >> 3] |= (1 << (c & 0x7));
4012 }
4013
4014 for (limit = addr + size; addr < limit; addr++) {
4015 /*
4016 * We're looking for a character that is _not_ contained
4017 * in the token string.
4018 */
4019 if ((c = dtrace_load8(addr)) == '\0')
4020 break;
4021
4022 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4023 break;
4024 }
4025
4026 if (c == '\0') {
4027 /*
4028 * We reached the end of the string without finding
4029 * any character that was not in the token string.
4030 * We return NULL in this case, and we set the saved
4031 * address to NULL as well.
4032 */
4033 regs[rd] = 0;
4034 mstate->dtms_strtok = 0;
4035 break;
4036 }
4037
4038 /*
4039 * From here on, we're copying into the destination string.
4040 */
4041 for (i = 0; addr < limit && i < size - 1; addr++) {
4042 if ((c = dtrace_load8(addr)) == '\0')
4043 break;
4044
4045 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4046 break;
4047
4048 ASSERT(i < size);
4049 dest[i++] = c;
4050 }
4051
4052 ASSERT(i < size);
4053 dest[i] = '\0';
4054 regs[rd] = (uintptr_t)dest;
4055 mstate->dtms_scratch_ptr += size;
4056 mstate->dtms_strtok = addr;
4057 break;
4058 }
4059
4060 case DIF_SUBR_SUBSTR: {
4061 uintptr_t s = tupregs[0].dttk_value;
4062 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4063 char *d = (char *)mstate->dtms_scratch_ptr;
4064 int64_t index = (int64_t)tupregs[1].dttk_value;
4065 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4066 size_t len = dtrace_strlen((char *)s, size);
4067 int64_t i = 0;
4068
4069 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4070 regs[rd] = 0;
4071 break;
4072 }
4073
4074 if (!DTRACE_INSCRATCH(mstate, size)) {
4075 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4076 regs[rd] = 0;
4077 break;
4078 }
4079
4080 if (nargs <= 2)
4081 remaining = (int64_t)size;
4082
4083 if (index < 0) {
4084 index += len;
4085
4086 if (index < 0 && index + remaining > 0) {
4087 remaining += index;
4088 index = 0;
4089 }
4090 }
4091
4092 if ((size_t)index >= len || index < 0) {
4093 remaining = 0;
4094 } else if (remaining < 0) {
4095 remaining += len - index;
4096 } else if ((uint64_t)index + (uint64_t)remaining > size) {
4097 remaining = size - index;
4098 }
4099
4100 for (i = 0; i < remaining; i++) {
4101 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4102 break;
4103 }
4104
4105 d[i] = '\0';
4106
4107 mstate->dtms_scratch_ptr += size;
4108 regs[rd] = (uintptr_t)d;
4109 break;
4110 }
4111
4112 case DIF_SUBR_GETMAJOR:
4113 regs[rd] = (uintptr_t)major( (dev_t)tupregs[0].dttk_value );
4114 break;
4115
4116 case DIF_SUBR_GETMINOR:
4117 regs[rd] = (uintptr_t)minor( (dev_t)tupregs[0].dttk_value );
4118 break;
4119
4120 case DIF_SUBR_DDI_PATHNAME: {
4121 /* APPLE NOTE: currently unsupported on Darwin */
4122 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4123 regs[rd] = 0;
4124 break;
4125 }
4126
4127 case DIF_SUBR_STRJOIN: {
4128 char *d = (char *)mstate->dtms_scratch_ptr;
4129 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4130 uintptr_t s1 = tupregs[0].dttk_value;
4131 uintptr_t s2 = tupregs[1].dttk_value;
4132 uint64_t i = 0;
4133
4134 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4135 !dtrace_strcanload(s2, size, mstate, vstate)) {
4136 regs[rd] = 0;
4137 break;
4138 }
4139
4140 if (!DTRACE_INSCRATCH(mstate, size)) {
4141 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4142 regs[rd] = 0;
4143 break;
4144 }
4145
4146 for (;;) {
4147 if (i >= size) {
4148 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4149 regs[rd] = 0;
4150 break;
4151 }
4152
4153 if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4154 i--;
4155 break;
4156 }
4157 }
4158
4159 for (;;) {
4160 if (i >= size) {
4161 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4162 regs[rd] = 0;
4163 break;
4164 }
4165
4166 if ((d[i++] = dtrace_load8(s2++)) == '\0')
4167 break;
4168 }
4169
4170 if (i < size) {
4171 mstate->dtms_scratch_ptr += i;
4172 regs[rd] = (uintptr_t)d;
4173 }
4174
4175 break;
4176 }
4177
4178 case DIF_SUBR_LLTOSTR: {
4179 int64_t i = (int64_t)tupregs[0].dttk_value;
4180 int64_t val = i < 0 ? i * -1 : i;
4181 uint64_t size = 22; /* enough room for 2^64 in decimal */
4182 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4183
4184 if (!DTRACE_INSCRATCH(mstate, size)) {
4185 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4186 regs[rd] = 0;
4187 break;
4188 }
4189
4190 for (*end-- = '\0'; val; val /= 10)
4191 *end-- = '0' + (val % 10);
4192
4193 if (i == 0)
4194 *end-- = '0';
4195
4196 if (i < 0)
4197 *end-- = '-';
4198
4199 regs[rd] = (uintptr_t)end + 1;
4200 mstate->dtms_scratch_ptr += size;
4201 break;
4202 }
4203
4204 case DIF_SUBR_HTONS:
4205 case DIF_SUBR_NTOHS:
4206 #ifdef _BIG_ENDIAN
4207 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4208 #else
4209 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4210 #endif
4211 break;
4212
4213
4214 case DIF_SUBR_HTONL:
4215 case DIF_SUBR_NTOHL:
4216 #ifdef _BIG_ENDIAN
4217 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4218 #else
4219 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4220 #endif
4221 break;
4222
4223
4224 case DIF_SUBR_HTONLL:
4225 case DIF_SUBR_NTOHLL:
4226 #ifdef _BIG_ENDIAN
4227 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4228 #else
4229 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4230 #endif
4231 break;
4232
4233
4234 case DIF_SUBR_DIRNAME:
4235 case DIF_SUBR_BASENAME: {
4236 char *dest = (char *)mstate->dtms_scratch_ptr;
4237 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4238 uintptr_t src = tupregs[0].dttk_value;
4239 int i, j, len = dtrace_strlen((char *)src, size);
4240 int lastbase = -1, firstbase = -1, lastdir = -1;
4241 int start, end;
4242
4243 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4244 regs[rd] = 0;
4245 break;
4246 }
4247
4248 if (!DTRACE_INSCRATCH(mstate, size)) {
4249 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4250 regs[rd] = 0;
4251 break;
4252 }
4253
4254 /*
4255 * The basename and dirname for a zero-length string is
4256 * defined to be "."
4257 */
4258 if (len == 0) {
4259 len = 1;
4260 src = (uintptr_t)".";
4261 }
4262
4263 /*
4264 * Start from the back of the string, moving back toward the
4265 * front until we see a character that isn't a slash. That
4266 * character is the last character in the basename.
4267 */
4268 for (i = len - 1; i >= 0; i--) {
4269 if (dtrace_load8(src + i) != '/')
4270 break;
4271 }
4272
4273 if (i >= 0)
4274 lastbase = i;
4275
4276 /*
4277 * Starting from the last character in the basename, move
4278 * towards the front until we find a slash. The character
4279 * that we processed immediately before that is the first
4280 * character in the basename.
4281 */
4282 for (; i >= 0; i--) {
4283 if (dtrace_load8(src + i) == '/')
4284 break;
4285 }
4286
4287 if (i >= 0)
4288 firstbase = i + 1;
4289
4290 /*
4291 * Now keep going until we find a non-slash character. That
4292 * character is the last character in the dirname.
4293 */
4294 for (; i >= 0; i--) {
4295 if (dtrace_load8(src + i) != '/')
4296 break;
4297 }
4298
4299 if (i >= 0)
4300 lastdir = i;
4301
4302 ASSERT(!(lastbase == -1 && firstbase != -1));
4303 ASSERT(!(firstbase == -1 && lastdir != -1));
4304
4305 if (lastbase == -1) {
4306 /*
4307 * We didn't find a non-slash character. We know that
4308 * the length is non-zero, so the whole string must be
4309 * slashes. In either the dirname or the basename
4310 * case, we return '/'.
4311 */
4312 ASSERT(firstbase == -1);
4313 firstbase = lastbase = lastdir = 0;
4314 }
4315
4316 if (firstbase == -1) {
4317 /*
4318 * The entire string consists only of a basename
4319 * component. If we're looking for dirname, we need
4320 * to change our string to be just "."; if we're
4321 * looking for a basename, we'll just set the first
4322 * character of the basename to be 0.
4323 */
4324 if (subr == DIF_SUBR_DIRNAME) {
4325 ASSERT(lastdir == -1);
4326 src = (uintptr_t)".";
4327 lastdir = 0;
4328 } else {
4329 firstbase = 0;
4330 }
4331 }
4332
4333 if (subr == DIF_SUBR_DIRNAME) {
4334 if (lastdir == -1) {
4335 /*
4336 * We know that we have a slash in the name --
4337 * or lastdir would be set to 0, above. And
4338 * because lastdir is -1, we know that this
4339 * slash must be the first character. (That
4340 * is, the full string must be of the form
4341 * "/basename".) In this case, the last
4342 * character of the directory name is 0.
4343 */
4344 lastdir = 0;
4345 }
4346
4347 start = 0;
4348 end = lastdir;
4349 } else {
4350 ASSERT(subr == DIF_SUBR_BASENAME);
4351 ASSERT(firstbase != -1 && lastbase != -1);
4352 start = firstbase;
4353 end = lastbase;
4354 }
4355
4356 for (i = start, j = 0; i <= end && (uint64_t)j < size - 1; i++, j++)
4357 dest[j] = dtrace_load8(src + i);
4358
4359 dest[j] = '\0';
4360 regs[rd] = (uintptr_t)dest;
4361 mstate->dtms_scratch_ptr += size;
4362 break;
4363 }
4364
4365 case DIF_SUBR_CLEANPATH: {
4366 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4367 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4368 uintptr_t src = tupregs[0].dttk_value;
4369 int i = 0, j = 0;
4370
4371 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4372 regs[rd] = 0;
4373 break;
4374 }
4375
4376 if (!DTRACE_INSCRATCH(mstate, size)) {
4377 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4378 regs[rd] = 0;
4379 break;
4380 }
4381
4382 /*
4383 * Move forward, loading each character.
4384 */
4385 do {
4386 c = dtrace_load8(src + i++);
4387 next:
4388 if ((uint64_t)(j + 5) >= size) /* 5 = strlen("/..c\0") */
4389 break;
4390
4391 if (c != '/') {
4392 dest[j++] = c;
4393 continue;
4394 }
4395
4396 c = dtrace_load8(src + i++);
4397
4398 if (c == '/') {
4399 /*
4400 * We have two slashes -- we can just advance
4401 * to the next character.
4402 */
4403 goto next;
4404 }
4405
4406 if (c != '.') {
4407 /*
4408 * This is not "." and it's not ".." -- we can
4409 * just store the "/" and this character and
4410 * drive on.
4411 */
4412 dest[j++] = '/';
4413 dest[j++] = c;
4414 continue;
4415 }
4416
4417 c = dtrace_load8(src + i++);
4418
4419 if (c == '/') {
4420 /*
4421 * This is a "/./" component. We're not going
4422 * to store anything in the destination buffer;
4423 * we're just going to go to the next component.
4424 */
4425 goto next;
4426 }
4427
4428 if (c != '.') {
4429 /*
4430 * This is not ".." -- we can just store the
4431 * "/." and this character and continue
4432 * processing.
4433 */
4434 dest[j++] = '/';
4435 dest[j++] = '.';
4436 dest[j++] = c;
4437 continue;
4438 }
4439
4440 c = dtrace_load8(src + i++);
4441
4442 if (c != '/' && c != '\0') {
4443 /*
4444 * This is not ".." -- it's "..[mumble]".
4445 * We'll store the "/.." and this character
4446 * and continue processing.
4447 */
4448 dest[j++] = '/';
4449 dest[j++] = '.';
4450 dest[j++] = '.';
4451 dest[j++] = c;
4452 continue;
4453 }
4454
4455 /*
4456 * This is "/../" or "/..\0". We need to back up
4457 * our destination pointer until we find a "/".
4458 */
4459 i--;
4460 while (j != 0 && dest[--j] != '/')
4461 continue;
4462
4463 if (c == '\0')
4464 dest[++j] = '/';
4465 } while (c != '\0');
4466
4467 dest[j] = '\0';
4468 regs[rd] = (uintptr_t)dest;
4469 mstate->dtms_scratch_ptr += size;
4470 break;
4471 }
4472
4473 case DIF_SUBR_INET_NTOA:
4474 case DIF_SUBR_INET_NTOA6:
4475 case DIF_SUBR_INET_NTOP: {
4476 size_t size;
4477 int af, argi, i;
4478 char *base, *end;
4479
4480 if (subr == DIF_SUBR_INET_NTOP) {
4481 af = (int)tupregs[0].dttk_value;
4482 argi = 1;
4483 } else {
4484 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4485 argi = 0;
4486 }
4487
4488 if (af == AF_INET) {
4489 #if !defined(__APPLE__)
4490 ipaddr_t ip4;
4491 #else
4492 uint32_t ip4;
4493 #endif /* __APPLE__ */
4494 uint8_t *ptr8, val;
4495
4496 /*
4497 * Safely load the IPv4 address.
4498 */
4499 #if !defined(__APPLE__)
4500 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4501 #else
4502 dtrace_bcopy(
4503 (void *)(uintptr_t)tupregs[argi].dttk_value,
4504 (void *)(uintptr_t)&ip4, sizeof (ip4));
4505 #endif /* __APPLE__ */
4506 /*
4507 * Check an IPv4 string will fit in scratch.
4508 */
4509 #if !defined(__APPLE__)
4510 size = INET_ADDRSTRLEN;
4511 #else
4512 size = MAX_IPv4_STR_LEN;
4513 #endif /* __APPLE__ */
4514 if (!DTRACE_INSCRATCH(mstate, size)) {
4515 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4516 regs[rd] = 0;
4517 break;
4518 }
4519 base = (char *)mstate->dtms_scratch_ptr;
4520 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4521
4522 /*
4523 * Stringify as a dotted decimal quad.
4524 */
4525 *end-- = '\0';
4526 ptr8 = (uint8_t *)&ip4;
4527 for (i = 3; i >= 0; i--) {
4528 val = ptr8[i];
4529
4530 if (val == 0) {
4531 *end-- = '0';
4532 } else {
4533 for (; val; val /= 10) {
4534 *end-- = '0' + (val % 10);
4535 }
4536 }
4537
4538 if (i > 0)
4539 *end-- = '.';
4540 }
4541 ASSERT(end + 1 >= base);
4542
4543 } else if (af == AF_INET6) {
4544 #if defined(__APPLE__)
4545 #define _S6_un __u6_addr
4546 #define _S6_u8 __u6_addr8
4547 #endif /* __APPLE__ */
4548 struct in6_addr ip6;
4549 int firstzero, tryzero, numzero, v6end;
4550 uint16_t val;
4551 const char digits[] = "0123456789abcdef";
4552
4553 /*
4554 * Stringify using RFC 1884 convention 2 - 16 bit
4555 * hexadecimal values with a zero-run compression.
4556 * Lower case hexadecimal digits are used.
4557 * eg, fe80::214:4fff:fe0b:76c8.
4558 * The IPv4 embedded form is returned for inet_ntop,
4559 * just the IPv4 string is returned for inet_ntoa6.
4560 */
4561
4562 /*
4563 * Safely load the IPv6 address.
4564 */
4565 dtrace_bcopy(
4566 (void *)(uintptr_t)tupregs[argi].dttk_value,
4567 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4568
4569 /*
4570 * Check an IPv6 string will fit in scratch.
4571 */
4572 size = INET6_ADDRSTRLEN;
4573 if (!DTRACE_INSCRATCH(mstate, size)) {
4574 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4575 regs[rd] = 0;
4576 break;
4577 }
4578 base = (char *)mstate->dtms_scratch_ptr;
4579 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4580 *end-- = '\0';
4581
4582 /*
4583 * Find the longest run of 16 bit zero values
4584 * for the single allowed zero compression - "::".
4585 */
4586 firstzero = -1;
4587 tryzero = -1;
4588 numzero = 1;
4589 for (i = 0; i < (int)sizeof (struct in6_addr); i++) {
4590 if (ip6._S6_un._S6_u8[i] == 0 &&
4591 tryzero == -1 && i % 2 == 0) {
4592 tryzero = i;
4593 continue;
4594 }
4595
4596 if (tryzero != -1 &&
4597 (ip6._S6_un._S6_u8[i] != 0 ||
4598 i == sizeof (struct in6_addr) - 1)) {
4599
4600 if (i - tryzero <= numzero) {
4601 tryzero = -1;
4602 continue;
4603 }
4604
4605 firstzero = tryzero;
4606 numzero = i - i % 2 - tryzero;
4607 tryzero = -1;
4608
4609 if (ip6._S6_un._S6_u8[i] == 0 &&
4610 i == sizeof (struct in6_addr) - 1)
4611 numzero += 2;
4612 }
4613 }
4614 ASSERT(firstzero + numzero <= (int)sizeof (struct in6_addr));
4615
4616 /*
4617 * Check for an IPv4 embedded address.
4618 */
4619 v6end = sizeof (struct in6_addr) - 2;
4620 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4621 IN6_IS_ADDR_V4COMPAT(&ip6)) {
4622 for (i = sizeof (struct in6_addr) - 1;
4623 i >= (int)DTRACE_V4MAPPED_OFFSET; i--) {
4624 ASSERT(end >= base);
4625
4626 val = ip6._S6_un._S6_u8[i];
4627
4628 if (val == 0) {
4629 *end-- = '0';
4630 } else {
4631 for (; val; val /= 10) {
4632 *end-- = '0' + val % 10;
4633 }
4634 }
4635
4636 if (i > (int)DTRACE_V4MAPPED_OFFSET)
4637 *end-- = '.';
4638 }
4639
4640 if (subr == DIF_SUBR_INET_NTOA6)
4641 goto inetout;
4642
4643 /*
4644 * Set v6end to skip the IPv4 address that
4645 * we have already stringified.
4646 */
4647 v6end = 10;
4648 }
4649
4650 /*
4651 * Build the IPv6 string by working through the
4652 * address in reverse.
4653 */
4654 for (i = v6end; i >= 0; i -= 2) {
4655 ASSERT(end >= base);
4656
4657 if (i == firstzero + numzero - 2) {
4658 *end-- = ':';
4659 *end-- = ':';
4660 i -= numzero - 2;
4661 continue;
4662 }
4663
4664 if (i < 14 && i != firstzero - 2)
4665 *end-- = ':';
4666
4667 val = (ip6._S6_un._S6_u8[i] << 8) +
4668 ip6._S6_un._S6_u8[i + 1];
4669
4670 if (val == 0) {
4671 *end-- = '0';
4672 } else {
4673 for (; val; val /= 16) {
4674 *end-- = digits[val % 16];
4675 }
4676 }
4677 }
4678 ASSERT(end + 1 >= base);
4679
4680 #if defined(__APPLE__)
4681 #undef _S6_un
4682 #undef _S6_u8
4683 #endif /* __APPLE__ */
4684 } else {
4685 /*
4686 * The user didn't use AH_INET or AH_INET6.
4687 */
4688 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4689 regs[rd] = 0;
4690 break;
4691 }
4692
4693 inetout: regs[rd] = (uintptr_t)end + 1;
4694 mstate->dtms_scratch_ptr += size;
4695 break;
4696 }
4697
4698 case DIF_SUBR_TOUPPER:
4699 case DIF_SUBR_TOLOWER: {
4700 uintptr_t src = tupregs[0].dttk_value;
4701 char *dest = (char *)mstate->dtms_scratch_ptr;
4702 char lower, upper, base, c;
4703 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4704 size_t len = dtrace_strlen((char*) src, size);
4705 size_t i = 0;
4706
4707 lower = (subr == DIF_SUBR_TOUPPER) ? 'a' : 'A';
4708 upper = (subr == DIF_SUBR_TOUPPER) ? 'z' : 'Z';
4709 base = (subr == DIF_SUBR_TOUPPER) ? 'A' : 'a';
4710
4711 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4712 regs[rd] = 0;
4713 break;
4714 }
4715
4716 if (!DTRACE_INSCRATCH(mstate, size)) {
4717 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4718 regs[rd] = 0;
4719 break;
4720 }
4721
4722 for (i = 0; i < size - 1; ++i) {
4723 if ((c = dtrace_load8(src + i)) == '\0')
4724 break;
4725 if (c >= lower && c <= upper)
4726 c = base + (c - lower);
4727 dest[i] = c;
4728 }
4729
4730 ASSERT(i < size);
4731
4732 dest[i] = '\0';
4733 regs[rd] = (uintptr_t) dest;
4734 mstate->dtms_scratch_ptr += size;
4735
4736 break;
4737 }
4738
4739 case DIF_SUBR_VM_KERNEL_ADDRPERM: {
4740 if (!dtrace_priv_kernel(state)) {
4741 regs[rd] = 0;
4742 } else {
4743 regs[rd] = VM_KERNEL_ADDRPERM((vm_offset_t) tupregs[0].dttk_value);
4744 }
4745
4746 break;
4747 }
4748 /*
4749 * APPLE NOTE:
4750 * CoreProfile callback ('core_profile (uint64_t, [uint64_t], [uint64_t] ...)')
4751 */
4752 case DIF_SUBR_COREPROFILE: {
4753 uint64_t selector = tupregs[0].dttk_value;
4754 uint64_t args[DIF_DTR_NREGS-1] = {0ULL};
4755 uint32_t ii;
4756 uint32_t count = (uint32_t)nargs;
4757
4758 if (count < 1) {
4759 regs[rd] = KERN_FAILURE;
4760 break;
4761 }
4762
4763 if(count > DIF_DTR_NREGS)
4764 count = DIF_DTR_NREGS;
4765
4766 /* copy in any variadic argument list, bounded by DIF_DTR_NREGS */
4767 for(ii = 0; ii < count-1; ii++) {
4768 args[ii] = tupregs[ii+1].dttk_value;
4769 }
4770
4771 kern_return_t ret =
4772 chudxnu_dtrace_callback(selector, args, count-1);
4773 if(KERN_SUCCESS != ret) {
4774 /* error */
4775 }
4776
4777 regs[rd] = ret;
4778 break;
4779 }
4780 }
4781 }
4782
4783 /*
4784 * Emulate the execution of DTrace IR instructions specified by the given
4785 * DIF object. This function is deliberately void of assertions as all of
4786 * the necessary checks are handled by a call to dtrace_difo_validate().
4787 */
4788 static uint64_t
4789 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4790 dtrace_vstate_t *vstate, dtrace_state_t *state)
4791 {
4792 const dif_instr_t *text = difo->dtdo_buf;
4793 const uint_t textlen = difo->dtdo_len;
4794 const char *strtab = difo->dtdo_strtab;
4795 const uint64_t *inttab = difo->dtdo_inttab;
4796
4797 uint64_t rval = 0;
4798 dtrace_statvar_t *svar;
4799 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4800 dtrace_difv_t *v;
4801 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4802 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4803
4804 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4805 uint64_t regs[DIF_DIR_NREGS];
4806 uint64_t *tmp;
4807
4808 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4809 int64_t cc_r;
4810 uint_t pc = 0, id, opc = 0;
4811 uint8_t ttop = 0;
4812 dif_instr_t instr;
4813 uint_t r1, r2, rd;
4814
4815 /*
4816 * We stash the current DIF object into the machine state: we need it
4817 * for subsequent access checking.
4818 */
4819 mstate->dtms_difo = difo;
4820
4821 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
4822
4823 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4824 opc = pc;
4825
4826 instr = text[pc++];
4827 r1 = DIF_INSTR_R1(instr);
4828 r2 = DIF_INSTR_R2(instr);
4829 rd = DIF_INSTR_RD(instr);
4830
4831 switch (DIF_INSTR_OP(instr)) {
4832 case DIF_OP_OR:
4833 regs[rd] = regs[r1] | regs[r2];
4834 break;
4835 case DIF_OP_XOR:
4836 regs[rd] = regs[r1] ^ regs[r2];
4837 break;
4838 case DIF_OP_AND:
4839 regs[rd] = regs[r1] & regs[r2];
4840 break;
4841 case DIF_OP_SLL:
4842 regs[rd] = regs[r1] << regs[r2];
4843 break;
4844 case DIF_OP_SRL:
4845 regs[rd] = regs[r1] >> regs[r2];
4846 break;
4847 case DIF_OP_SUB:
4848 regs[rd] = regs[r1] - regs[r2];
4849 break;
4850 case DIF_OP_ADD:
4851 regs[rd] = regs[r1] + regs[r2];
4852 break;
4853 case DIF_OP_MUL:
4854 regs[rd] = regs[r1] * regs[r2];
4855 break;
4856 case DIF_OP_SDIV:
4857 if (regs[r2] == 0) {
4858 regs[rd] = 0;
4859 *flags |= CPU_DTRACE_DIVZERO;
4860 } else {
4861 regs[rd] = (int64_t)regs[r1] /
4862 (int64_t)regs[r2];
4863 }
4864 break;
4865
4866 case DIF_OP_UDIV:
4867 if (regs[r2] == 0) {
4868 regs[rd] = 0;
4869 *flags |= CPU_DTRACE_DIVZERO;
4870 } else {
4871 regs[rd] = regs[r1] / regs[r2];
4872 }
4873 break;
4874
4875 case DIF_OP_SREM:
4876 if (regs[r2] == 0) {
4877 regs[rd] = 0;
4878 *flags |= CPU_DTRACE_DIVZERO;
4879 } else {
4880 regs[rd] = (int64_t)regs[r1] %
4881 (int64_t)regs[r2];
4882 }
4883 break;
4884
4885 case DIF_OP_UREM:
4886 if (regs[r2] == 0) {
4887 regs[rd] = 0;
4888 *flags |= CPU_DTRACE_DIVZERO;
4889 } else {
4890 regs[rd] = regs[r1] % regs[r2];
4891 }
4892 break;
4893
4894 case DIF_OP_NOT:
4895 regs[rd] = ~regs[r1];
4896 break;
4897 case DIF_OP_MOV:
4898 regs[rd] = regs[r1];
4899 break;
4900 case DIF_OP_CMP:
4901 cc_r = regs[r1] - regs[r2];
4902 cc_n = cc_r < 0;
4903 cc_z = cc_r == 0;
4904 cc_v = 0;
4905 cc_c = regs[r1] < regs[r2];
4906 break;
4907 case DIF_OP_TST:
4908 cc_n = cc_v = cc_c = 0;
4909 cc_z = regs[r1] == 0;
4910 break;
4911 case DIF_OP_BA:
4912 pc = DIF_INSTR_LABEL(instr);
4913 break;
4914 case DIF_OP_BE:
4915 if (cc_z)
4916 pc = DIF_INSTR_LABEL(instr);
4917 break;
4918 case DIF_OP_BNE:
4919 if (cc_z == 0)
4920 pc = DIF_INSTR_LABEL(instr);
4921 break;
4922 case DIF_OP_BG:
4923 if ((cc_z | (cc_n ^ cc_v)) == 0)
4924 pc = DIF_INSTR_LABEL(instr);
4925 break;
4926 case DIF_OP_BGU:
4927 if ((cc_c | cc_z) == 0)
4928 pc = DIF_INSTR_LABEL(instr);
4929 break;
4930 case DIF_OP_BGE:
4931 if ((cc_n ^ cc_v) == 0)
4932 pc = DIF_INSTR_LABEL(instr);
4933 break;
4934 case DIF_OP_BGEU:
4935 if (cc_c == 0)
4936 pc = DIF_INSTR_LABEL(instr);
4937 break;
4938 case DIF_OP_BL:
4939 if (cc_n ^ cc_v)
4940 pc = DIF_INSTR_LABEL(instr);
4941 break;
4942 case DIF_OP_BLU:
4943 if (cc_c)
4944 pc = DIF_INSTR_LABEL(instr);
4945 break;
4946 case DIF_OP_BLE:
4947 if (cc_z | (cc_n ^ cc_v))
4948 pc = DIF_INSTR_LABEL(instr);
4949 break;
4950 case DIF_OP_BLEU:
4951 if (cc_c | cc_z)
4952 pc = DIF_INSTR_LABEL(instr);
4953 break;
4954 case DIF_OP_RLDSB:
4955 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4956 *flags |= CPU_DTRACE_KPRIV;
4957 *illval = regs[r1];
4958 break;
4959 }
4960 /*FALLTHROUGH*/
4961 case DIF_OP_LDSB:
4962 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4963 break;
4964 case DIF_OP_RLDSH:
4965 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4966 *flags |= CPU_DTRACE_KPRIV;
4967 *illval = regs[r1];
4968 break;
4969 }
4970 /*FALLTHROUGH*/
4971 case DIF_OP_LDSH:
4972 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4973 break;
4974 case DIF_OP_RLDSW:
4975 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4976 *flags |= CPU_DTRACE_KPRIV;
4977 *illval = regs[r1];
4978 break;
4979 }
4980 /*FALLTHROUGH*/
4981 case DIF_OP_LDSW:
4982 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4983 break;
4984 case DIF_OP_RLDUB:
4985 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4986 *flags |= CPU_DTRACE_KPRIV;
4987 *illval = regs[r1];
4988 break;
4989 }
4990 /*FALLTHROUGH*/
4991 case DIF_OP_LDUB:
4992 regs[rd] = dtrace_load8(regs[r1]);
4993 break;
4994 case DIF_OP_RLDUH:
4995 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4996 *flags |= CPU_DTRACE_KPRIV;
4997 *illval = regs[r1];
4998 break;
4999 }
5000 /*FALLTHROUGH*/
5001 case DIF_OP_LDUH:
5002 regs[rd] = dtrace_load16(regs[r1]);
5003 break;
5004 case DIF_OP_RLDUW:
5005 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5006 *flags |= CPU_DTRACE_KPRIV;
5007 *illval = regs[r1];
5008 break;
5009 }
5010 /*FALLTHROUGH*/
5011 case DIF_OP_LDUW:
5012 regs[rd] = dtrace_load32(regs[r1]);
5013 break;
5014 case DIF_OP_RLDX:
5015 if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5016 *flags |= CPU_DTRACE_KPRIV;
5017 *illval = regs[r1];
5018 break;
5019 }
5020 /*FALLTHROUGH*/
5021 case DIF_OP_LDX:
5022 regs[rd] = dtrace_load64(regs[r1]);
5023 break;
5024 /*
5025 * Darwin 32-bit kernel may fetch from 64-bit user.
5026 * Do not cast regs to uintptr_t
5027 * DIF_OP_ULDSB,DIF_OP_ULDSH, DIF_OP_ULDSW, DIF_OP_ULDUB
5028 * DIF_OP_ULDUH, DIF_OP_ULDUW, DIF_OP_ULDX
5029 */
5030 case DIF_OP_ULDSB:
5031 regs[rd] = (int8_t)
5032 dtrace_fuword8(regs[r1]);
5033 break;
5034 case DIF_OP_ULDSH:
5035 regs[rd] = (int16_t)
5036 dtrace_fuword16(regs[r1]);
5037 break;
5038 case DIF_OP_ULDSW:
5039 regs[rd] = (int32_t)
5040 dtrace_fuword32(regs[r1]);
5041 break;
5042 case DIF_OP_ULDUB:
5043 regs[rd] =
5044 dtrace_fuword8(regs[r1]);
5045 break;
5046 case DIF_OP_ULDUH:
5047 regs[rd] =
5048 dtrace_fuword16(regs[r1]);
5049 break;
5050 case DIF_OP_ULDUW:
5051 regs[rd] =
5052 dtrace_fuword32(regs[r1]);
5053 break;
5054 case DIF_OP_ULDX:
5055 regs[rd] =
5056 dtrace_fuword64(regs[r1]);
5057 break;
5058 case DIF_OP_RET:
5059 rval = regs[rd];
5060 pc = textlen;
5061 break;
5062 case DIF_OP_NOP:
5063 break;
5064 case DIF_OP_SETX:
5065 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5066 break;
5067 case DIF_OP_SETS:
5068 regs[rd] = (uint64_t)(uintptr_t)
5069 (strtab + DIF_INSTR_STRING(instr));
5070 break;
5071 case DIF_OP_SCMP: {
5072 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5073 uintptr_t s1 = regs[r1];
5074 uintptr_t s2 = regs[r2];
5075
5076 if (s1 != 0 &&
5077 !dtrace_strcanload(s1, sz, mstate, vstate))
5078 break;
5079 if (s2 != 0 &&
5080 !dtrace_strcanload(s2, sz, mstate, vstate))
5081 break;
5082
5083 cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5084
5085 cc_n = cc_r < 0;
5086 cc_z = cc_r == 0;
5087 cc_v = cc_c = 0;
5088 break;
5089 }
5090 case DIF_OP_LDGA:
5091 regs[rd] = dtrace_dif_variable(mstate, state,
5092 r1, regs[r2]);
5093 break;
5094 case DIF_OP_LDGS:
5095 id = DIF_INSTR_VAR(instr);
5096
5097 if (id >= DIF_VAR_OTHER_UBASE) {
5098 uintptr_t a;
5099
5100 id -= DIF_VAR_OTHER_UBASE;
5101 svar = vstate->dtvs_globals[id];
5102 ASSERT(svar != NULL);
5103 v = &svar->dtsv_var;
5104
5105 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5106 regs[rd] = svar->dtsv_data;
5107 break;
5108 }
5109
5110 a = (uintptr_t)svar->dtsv_data;
5111
5112 if (*(uint8_t *)a == UINT8_MAX) {
5113 /*
5114 * If the 0th byte is set to UINT8_MAX
5115 * then this is to be treated as a
5116 * reference to a NULL variable.
5117 */
5118 regs[rd] = 0;
5119 } else {
5120 regs[rd] = a + sizeof (uint64_t);
5121 }
5122
5123 break;
5124 }
5125
5126 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5127 break;
5128
5129 case DIF_OP_STGS:
5130 id = DIF_INSTR_VAR(instr);
5131
5132 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5133 id -= DIF_VAR_OTHER_UBASE;
5134
5135 svar = vstate->dtvs_globals[id];
5136 ASSERT(svar != NULL);
5137 v = &svar->dtsv_var;
5138
5139 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5140 uintptr_t a = (uintptr_t)svar->dtsv_data;
5141
5142 ASSERT(a != 0);
5143 ASSERT(svar->dtsv_size != 0);
5144
5145 if (regs[rd] == 0) {
5146 *(uint8_t *)a = UINT8_MAX;
5147 break;
5148 } else {
5149 *(uint8_t *)a = 0;
5150 a += sizeof (uint64_t);
5151 }
5152 if (!dtrace_vcanload(
5153 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5154 mstate, vstate))
5155 break;
5156
5157 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5158 (void *)a, &v->dtdv_type);
5159 break;
5160 }
5161
5162 svar->dtsv_data = regs[rd];
5163 break;
5164
5165 case DIF_OP_LDTA:
5166 /*
5167 * There are no DTrace built-in thread-local arrays at
5168 * present. This opcode is saved for future work.
5169 */
5170 *flags |= CPU_DTRACE_ILLOP;
5171 regs[rd] = 0;
5172 break;
5173
5174 case DIF_OP_LDLS:
5175 id = DIF_INSTR_VAR(instr);
5176
5177 if (id < DIF_VAR_OTHER_UBASE) {
5178 /*
5179 * For now, this has no meaning.
5180 */
5181 regs[rd] = 0;
5182 break;
5183 }
5184
5185 id -= DIF_VAR_OTHER_UBASE;
5186
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 (*(uint8_t *)a == UINT8_MAX) {
5202 /*
5203 * If the 0th byte is set to UINT8_MAX
5204 * then this is to be treated as a
5205 * reference to a NULL variable.
5206 */
5207 regs[rd] = 0;
5208 } else {
5209 regs[rd] = a + sizeof (uint64_t);
5210 }
5211
5212 break;
5213 }
5214
5215 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5216 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5217 regs[rd] = tmp[CPU->cpu_id];
5218 break;
5219
5220 case DIF_OP_STLS:
5221 id = DIF_INSTR_VAR(instr);
5222
5223 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5224 id -= DIF_VAR_OTHER_UBASE;
5225 ASSERT(id < (uint_t)vstate->dtvs_nlocals);
5226 ASSERT(vstate->dtvs_locals != NULL);
5227 svar = vstate->dtvs_locals[id];
5228 ASSERT(svar != NULL);
5229 v = &svar->dtsv_var;
5230
5231 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5232 uintptr_t a = (uintptr_t)svar->dtsv_data;
5233 size_t sz = v->dtdv_type.dtdt_size;
5234
5235 sz += sizeof (uint64_t);
5236 ASSERT(svar->dtsv_size == (int)NCPU * sz);
5237 a += CPU->cpu_id * sz;
5238
5239 if (regs[rd] == 0) {
5240 *(uint8_t *)a = UINT8_MAX;
5241 break;
5242 } else {
5243 *(uint8_t *)a = 0;
5244 a += sizeof (uint64_t);
5245 }
5246
5247 if (!dtrace_vcanload(
5248 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5249 mstate, vstate))
5250 break;
5251
5252 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5253 (void *)a, &v->dtdv_type);
5254 break;
5255 }
5256
5257 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5258 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5259 tmp[CPU->cpu_id] = regs[rd];
5260 break;
5261
5262 case DIF_OP_LDTS: {
5263 dtrace_dynvar_t *dvar;
5264 dtrace_key_t *key;
5265
5266 id = DIF_INSTR_VAR(instr);
5267 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5268 id -= DIF_VAR_OTHER_UBASE;
5269 v = &vstate->dtvs_tlocals[id];
5270
5271 key = &tupregs[DIF_DTR_NREGS];
5272 key[0].dttk_value = (uint64_t)id;
5273 key[0].dttk_size = 0;
5274 DTRACE_TLS_THRKEY(key[1].dttk_value);
5275 key[1].dttk_size = 0;
5276
5277 dvar = dtrace_dynvar(dstate, 2, key,
5278 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5279 mstate, vstate);
5280
5281 if (dvar == NULL) {
5282 regs[rd] = 0;
5283 break;
5284 }
5285
5286 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5287 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5288 } else {
5289 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5290 }
5291
5292 break;
5293 }
5294
5295 case DIF_OP_STTS: {
5296 dtrace_dynvar_t *dvar;
5297 dtrace_key_t *key;
5298
5299 id = DIF_INSTR_VAR(instr);
5300 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5301 id -= DIF_VAR_OTHER_UBASE;
5302
5303 key = &tupregs[DIF_DTR_NREGS];
5304 key[0].dttk_value = (uint64_t)id;
5305 key[0].dttk_size = 0;
5306 DTRACE_TLS_THRKEY(key[1].dttk_value);
5307 key[1].dttk_size = 0;
5308 v = &vstate->dtvs_tlocals[id];
5309
5310 dvar = dtrace_dynvar(dstate, 2, key,
5311 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5312 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5313 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5314 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5315
5316 /*
5317 * Given that we're storing to thread-local data,
5318 * we need to flush our predicate cache.
5319 */
5320 dtrace_set_thread_predcache(current_thread(), 0);
5321
5322 if (dvar == NULL)
5323 break;
5324
5325 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5326 if (!dtrace_vcanload(
5327 (void *)(uintptr_t)regs[rd],
5328 &v->dtdv_type, mstate, vstate))
5329 break;
5330
5331 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5332 dvar->dtdv_data, &v->dtdv_type);
5333 } else {
5334 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5335 }
5336
5337 break;
5338 }
5339
5340 case DIF_OP_SRA:
5341 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5342 break;
5343
5344 case DIF_OP_CALL:
5345 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5346 regs, tupregs, ttop, mstate, state);
5347 break;
5348
5349 case DIF_OP_PUSHTR:
5350 if (ttop == DIF_DTR_NREGS) {
5351 *flags |= CPU_DTRACE_TUPOFLOW;
5352 break;
5353 }
5354
5355 if (r1 == DIF_TYPE_STRING) {
5356 /*
5357 * If this is a string type and the size is 0,
5358 * we'll use the system-wide default string
5359 * size. Note that we are _not_ looking at
5360 * the value of the DTRACEOPT_STRSIZE option;
5361 * had this been set, we would expect to have
5362 * a non-zero size value in the "pushtr".
5363 */
5364 tupregs[ttop].dttk_size =
5365 dtrace_strlen((char *)(uintptr_t)regs[rd],
5366 regs[r2] ? regs[r2] :
5367 dtrace_strsize_default) + 1;
5368 } else {
5369 if (regs[r2] > LONG_MAX) {
5370 *flags |= CPU_DTRACE_ILLOP;
5371 break;
5372 }
5373 tupregs[ttop].dttk_size = regs[r2];
5374 }
5375
5376 tupregs[ttop++].dttk_value = regs[rd];
5377 break;
5378
5379 case DIF_OP_PUSHTV:
5380 if (ttop == DIF_DTR_NREGS) {
5381 *flags |= CPU_DTRACE_TUPOFLOW;
5382 break;
5383 }
5384
5385 tupregs[ttop].dttk_value = regs[rd];
5386 tupregs[ttop++].dttk_size = 0;
5387 break;
5388
5389 case DIF_OP_POPTS:
5390 if (ttop != 0)
5391 ttop--;
5392 break;
5393
5394 case DIF_OP_FLUSHTS:
5395 ttop = 0;
5396 break;
5397
5398 case DIF_OP_LDGAA:
5399 case DIF_OP_LDTAA: {
5400 dtrace_dynvar_t *dvar;
5401 dtrace_key_t *key = tupregs;
5402 uint_t nkeys = ttop;
5403
5404 id = DIF_INSTR_VAR(instr);
5405 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5406 id -= DIF_VAR_OTHER_UBASE;
5407
5408 key[nkeys].dttk_value = (uint64_t)id;
5409 key[nkeys++].dttk_size = 0;
5410
5411 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5412 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5413 key[nkeys++].dttk_size = 0;
5414 v = &vstate->dtvs_tlocals[id];
5415 } else {
5416 v = &vstate->dtvs_globals[id]->dtsv_var;
5417 }
5418
5419 dvar = dtrace_dynvar(dstate, nkeys, key,
5420 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5421 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5422 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5423
5424 if (dvar == NULL) {
5425 regs[rd] = 0;
5426 break;
5427 }
5428
5429 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5430 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5431 } else {
5432 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5433 }
5434
5435 break;
5436 }
5437
5438 case DIF_OP_STGAA:
5439 case DIF_OP_STTAA: {
5440 dtrace_dynvar_t *dvar;
5441 dtrace_key_t *key = tupregs;
5442 uint_t nkeys = ttop;
5443
5444 id = DIF_INSTR_VAR(instr);
5445 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5446 id -= DIF_VAR_OTHER_UBASE;
5447
5448 key[nkeys].dttk_value = (uint64_t)id;
5449 key[nkeys++].dttk_size = 0;
5450
5451 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5452 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5453 key[nkeys++].dttk_size = 0;
5454 v = &vstate->dtvs_tlocals[id];
5455 } else {
5456 v = &vstate->dtvs_globals[id]->dtsv_var;
5457 }
5458
5459 dvar = dtrace_dynvar(dstate, nkeys, key,
5460 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5461 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5462 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5463 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5464
5465 if (dvar == NULL)
5466 break;
5467
5468 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5469 if (!dtrace_vcanload(
5470 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5471 mstate, vstate))
5472 break;
5473
5474 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5475 dvar->dtdv_data, &v->dtdv_type);
5476 } else {
5477 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5478 }
5479
5480 break;
5481 }
5482
5483 case DIF_OP_ALLOCS: {
5484 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5485 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5486
5487 /*
5488 * Rounding up the user allocation size could have
5489 * overflowed large, bogus allocations (like -1ULL) to
5490 * 0.
5491 */
5492 if (size < regs[r1] ||
5493 !DTRACE_INSCRATCH(mstate, size)) {
5494 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5495 regs[rd] = 0;
5496 break;
5497 }
5498
5499 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5500 mstate->dtms_scratch_ptr += size;
5501 regs[rd] = ptr;
5502 break;
5503 }
5504
5505 case DIF_OP_COPYS:
5506 if (!dtrace_canstore(regs[rd], regs[r2],
5507 mstate, vstate)) {
5508 *flags |= CPU_DTRACE_BADADDR;
5509 *illval = regs[rd];
5510 break;
5511 }
5512
5513 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5514 break;
5515
5516 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5517 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5518 break;
5519
5520 case DIF_OP_STB:
5521 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5522 *flags |= CPU_DTRACE_BADADDR;
5523 *illval = regs[rd];
5524 break;
5525 }
5526 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5527 break;
5528
5529 case DIF_OP_STH:
5530 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5531 *flags |= CPU_DTRACE_BADADDR;
5532 *illval = regs[rd];
5533 break;
5534 }
5535 if (regs[rd] & 1) {
5536 *flags |= CPU_DTRACE_BADALIGN;
5537 *illval = regs[rd];
5538 break;
5539 }
5540 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5541 break;
5542
5543 case DIF_OP_STW:
5544 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5545 *flags |= CPU_DTRACE_BADADDR;
5546 *illval = regs[rd];
5547 break;
5548 }
5549 if (regs[rd] & 3) {
5550 *flags |= CPU_DTRACE_BADALIGN;
5551 *illval = regs[rd];
5552 break;
5553 }
5554 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5555 break;
5556
5557 case DIF_OP_STX:
5558 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5559 *flags |= CPU_DTRACE_BADADDR;
5560 *illval = regs[rd];
5561 break;
5562 }
5563
5564 /*
5565 * Darwin kmem_zalloc() called from
5566 * dtrace_difo_init() is 4-byte aligned.
5567 */
5568 if (regs[rd] & 3) {
5569 *flags |= CPU_DTRACE_BADALIGN;
5570 *illval = regs[rd];
5571 break;
5572 }
5573 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5574 break;
5575 }
5576 }
5577
5578 if (!(*flags & CPU_DTRACE_FAULT))
5579 return (rval);
5580
5581 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5582 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5583
5584 return (0);
5585 }
5586
5587 static void
5588 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5589 {
5590 dtrace_probe_t *probe = ecb->dte_probe;
5591 dtrace_provider_t *prov = probe->dtpr_provider;
5592 char c[DTRACE_FULLNAMELEN + 80], *str;
5593 const char *msg = "dtrace: breakpoint action at probe ";
5594 const char *ecbmsg = " (ecb ";
5595 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5596 uintptr_t val = (uintptr_t)ecb;
5597 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5598
5599 if (dtrace_destructive_disallow)
5600 return;
5601
5602 /*
5603 * It's impossible to be taking action on the NULL probe.
5604 */
5605 ASSERT(probe != NULL);
5606
5607 /*
5608 * This is a poor man's (destitute man's?) sprintf(): we want to
5609 * print the provider name, module name, function name and name of
5610 * the probe, along with the hex address of the ECB with the breakpoint
5611 * action -- all of which we must place in the character buffer by
5612 * hand.
5613 */
5614 while (*msg != '\0')
5615 c[i++] = *msg++;
5616
5617 for (str = prov->dtpv_name; *str != '\0'; str++)
5618 c[i++] = *str;
5619 c[i++] = ':';
5620
5621 for (str = probe->dtpr_mod; *str != '\0'; str++)
5622 c[i++] = *str;
5623 c[i++] = ':';
5624
5625 for (str = probe->dtpr_func; *str != '\0'; str++)
5626 c[i++] = *str;
5627 c[i++] = ':';
5628
5629 for (str = probe->dtpr_name; *str != '\0'; str++)
5630 c[i++] = *str;
5631
5632 while (*ecbmsg != '\0')
5633 c[i++] = *ecbmsg++;
5634
5635 while (shift >= 0) {
5636 mask = (uintptr_t)0xf << shift;
5637
5638 if (val >= ((uintptr_t)1 << shift))
5639 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5640 shift -= 4;
5641 }
5642
5643 c[i++] = ')';
5644 c[i] = '\0';
5645
5646 debug_enter(c);
5647 }
5648
5649 static void
5650 dtrace_action_panic(dtrace_ecb_t *ecb)
5651 {
5652 dtrace_probe_t *probe = ecb->dte_probe;
5653
5654 /*
5655 * It's impossible to be taking action on the NULL probe.
5656 */
5657 ASSERT(probe != NULL);
5658
5659 if (dtrace_destructive_disallow)
5660 return;
5661
5662 if (dtrace_panicked != NULL)
5663 return;
5664
5665 if (dtrace_casptr(&dtrace_panicked, NULL, current_thread()) != NULL)
5666 return;
5667
5668 /*
5669 * We won the right to panic. (We want to be sure that only one
5670 * thread calls panic() from dtrace_probe(), and that panic() is
5671 * called exactly once.)
5672 */
5673 panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5674 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5675 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5676
5677 /*
5678 * APPLE NOTE: this was for an old Mac OS X debug feature
5679 * allowing a return from panic(). Revisit someday.
5680 */
5681 dtrace_panicked = NULL;
5682 }
5683
5684 static void
5685 dtrace_action_raise(uint64_t sig)
5686 {
5687 if (dtrace_destructive_disallow)
5688 return;
5689
5690 if (sig >= NSIG) {
5691 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5692 return;
5693 }
5694
5695 /*
5696 * raise() has a queue depth of 1 -- we ignore all subsequent
5697 * invocations of the raise() action.
5698 */
5699
5700 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5701
5702 if (uthread && uthread->t_dtrace_sig == 0) {
5703 uthread->t_dtrace_sig = sig;
5704 act_set_astbsd(current_thread());
5705 }
5706 }
5707
5708 static void
5709 dtrace_action_stop(void)
5710 {
5711 if (dtrace_destructive_disallow)
5712 return;
5713
5714 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5715 if (uthread) {
5716 /*
5717 * The currently running process will be set to task_suspend
5718 * when it next leaves the kernel.
5719 */
5720 uthread->t_dtrace_stop = 1;
5721 act_set_astbsd(current_thread());
5722 }
5723 }
5724
5725
5726 /*
5727 * APPLE NOTE: pidresume works in conjunction with the dtrace stop action.
5728 * Both activate only when the currently running process next leaves the
5729 * kernel.
5730 */
5731 static void
5732 dtrace_action_pidresume(uint64_t pid)
5733 {
5734 if (dtrace_destructive_disallow)
5735 return;
5736
5737 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
5738 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5739 return;
5740 }
5741 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5742
5743 /*
5744 * When the currently running process leaves the kernel, it attempts to
5745 * task_resume the process (denoted by pid), if that pid appears to have
5746 * been stopped by dtrace_action_stop().
5747 * The currently running process has a pidresume() queue depth of 1 --
5748 * subsequent invocations of the pidresume() action are ignored.
5749 */
5750
5751 if (pid != 0 && uthread && uthread->t_dtrace_resumepid == 0) {
5752 uthread->t_dtrace_resumepid = pid;
5753 act_set_astbsd(current_thread());
5754 }
5755 }
5756
5757 static void
5758 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5759 {
5760 hrtime_t now;
5761 volatile uint16_t *flags;
5762 dtrace_cpu_t *cpu = CPU;
5763
5764 if (dtrace_destructive_disallow)
5765 return;
5766
5767 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5768
5769 now = dtrace_gethrtime();
5770
5771 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5772 /*
5773 * We need to advance the mark to the current time.
5774 */
5775 cpu->cpu_dtrace_chillmark = now;
5776 cpu->cpu_dtrace_chilled = 0;
5777 }
5778
5779 /*
5780 * Now check to see if the requested chill time would take us over
5781 * the maximum amount of time allowed in the chill interval. (Or
5782 * worse, if the calculation itself induces overflow.)
5783 */
5784 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5785 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5786 *flags |= CPU_DTRACE_ILLOP;
5787 return;
5788 }
5789
5790 while (dtrace_gethrtime() - now < val)
5791 continue;
5792
5793 /*
5794 * Normally, we assure that the value of the variable "timestamp" does
5795 * not change within an ECB. The presence of chill() represents an
5796 * exception to this rule, however.
5797 */
5798 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5799 cpu->cpu_dtrace_chilled += val;
5800 }
5801
5802 static void
5803 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5804 uint64_t *buf, uint64_t arg)
5805 {
5806 int nframes = DTRACE_USTACK_NFRAMES(arg);
5807 int strsize = DTRACE_USTACK_STRSIZE(arg);
5808 uint64_t *pcs = &buf[1], *fps;
5809 char *str = (char *)&pcs[nframes];
5810 int size, offs = 0, i, j;
5811 uintptr_t old = mstate->dtms_scratch_ptr, saved;
5812 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5813 char *sym;
5814
5815 /*
5816 * Should be taking a faster path if string space has not been
5817 * allocated.
5818 */
5819 ASSERT(strsize != 0);
5820
5821 /*
5822 * We will first allocate some temporary space for the frame pointers.
5823 */
5824 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5825 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5826 (nframes * sizeof (uint64_t));
5827
5828 if (!DTRACE_INSCRATCH(mstate, (uintptr_t)size)) {
5829 /*
5830 * Not enough room for our frame pointers -- need to indicate
5831 * that we ran out of scratch space.
5832 */
5833 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5834 return;
5835 }
5836
5837 mstate->dtms_scratch_ptr += size;
5838 saved = mstate->dtms_scratch_ptr;
5839
5840 /*
5841 * Now get a stack with both program counters and frame pointers.
5842 */
5843 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5844 dtrace_getufpstack(buf, fps, nframes + 1);
5845 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5846
5847 /*
5848 * If that faulted, we're cooked.
5849 */
5850 if (*flags & CPU_DTRACE_FAULT)
5851 goto out;
5852
5853 /*
5854 * Now we want to walk up the stack, calling the USTACK helper. For
5855 * each iteration, we restore the scratch pointer.
5856 */
5857 for (i = 0; i < nframes; i++) {
5858 mstate->dtms_scratch_ptr = saved;
5859
5860 if (offs >= strsize)
5861 break;
5862
5863 sym = (char *)(uintptr_t)dtrace_helper(
5864 DTRACE_HELPER_ACTION_USTACK,
5865 mstate, state, pcs[i], fps[i]);
5866
5867 /*
5868 * If we faulted while running the helper, we're going to
5869 * clear the fault and null out the corresponding string.
5870 */
5871 if (*flags & CPU_DTRACE_FAULT) {
5872 *flags &= ~CPU_DTRACE_FAULT;
5873 str[offs++] = '\0';
5874 continue;
5875 }
5876
5877 if (sym == NULL) {
5878 str[offs++] = '\0';
5879 continue;
5880 }
5881
5882 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5883
5884 /*
5885 * Now copy in the string that the helper returned to us.
5886 */
5887 for (j = 0; offs + j < strsize; j++) {
5888 if ((str[offs + j] = sym[j]) == '\0')
5889 break;
5890 }
5891
5892 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5893
5894 offs += j + 1;
5895 }
5896
5897 if (offs >= strsize) {
5898 /*
5899 * If we didn't have room for all of the strings, we don't
5900 * abort processing -- this needn't be a fatal error -- but we
5901 * still want to increment a counter (dts_stkstroverflows) to
5902 * allow this condition to be warned about. (If this is from
5903 * a jstack() action, it is easily tuned via jstackstrsize.)
5904 */
5905 dtrace_error(&state->dts_stkstroverflows);
5906 }
5907
5908 while (offs < strsize)
5909 str[offs++] = '\0';
5910
5911 out:
5912 mstate->dtms_scratch_ptr = old;
5913 }
5914
5915 static void
5916 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
5917 size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
5918 {
5919 volatile uint16_t *flags;
5920 uint64_t val = *valp;
5921 size_t valoffs = *valoffsp;
5922
5923 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5924 ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
5925
5926 /*
5927 * If this is a string, we're going to only load until we find the zero
5928 * byte -- after which we'll store zero bytes.
5929 */
5930 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
5931 char c = '\0' + 1;
5932 size_t s;
5933
5934 for (s = 0; s < size; s++) {
5935 if (c != '\0' && dtkind == DIF_TF_BYREF) {
5936 c = dtrace_load8(val++);
5937 } else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
5938 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5939 c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
5940 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5941 if (*flags & CPU_DTRACE_FAULT)
5942 break;
5943 }
5944
5945 DTRACE_STORE(uint8_t, tomax, valoffs++, c);
5946
5947 if (c == '\0' && intuple)
5948 break;
5949 }
5950 } else {
5951 uint8_t c;
5952 while (valoffs < end) {
5953 if (dtkind == DIF_TF_BYREF) {
5954 c = dtrace_load8(val++);
5955 } else if (dtkind == DIF_TF_BYUREF) {
5956 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5957 c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
5958 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5959 if (*flags & CPU_DTRACE_FAULT)
5960 break;
5961 }
5962
5963 DTRACE_STORE(uint8_t, tomax,
5964 valoffs++, c);
5965 }
5966 }
5967
5968 *valp = val;
5969 *valoffsp = valoffs;
5970 }
5971
5972 /*
5973 * If you're looking for the epicenter of DTrace, you just found it. This
5974 * is the function called by the provider to fire a probe -- from which all
5975 * subsequent probe-context DTrace activity emanates.
5976 */
5977 static void
5978 __dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
5979 uint64_t arg2, uint64_t arg3, uint64_t arg4)
5980 {
5981 processorid_t cpuid;
5982 dtrace_icookie_t cookie;
5983 dtrace_probe_t *probe;
5984 dtrace_mstate_t mstate;
5985 dtrace_ecb_t *ecb;
5986 dtrace_action_t *act;
5987 intptr_t offs;
5988 size_t size;
5989 int vtime, onintr;
5990 volatile uint16_t *flags;
5991 hrtime_t now;
5992
5993 cookie = dtrace_interrupt_disable();
5994 probe = dtrace_probes[id - 1];
5995 cpuid = CPU->cpu_id;
5996 onintr = CPU_ON_INTR(CPU);
5997
5998 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5999 probe->dtpr_predcache == dtrace_get_thread_predcache(current_thread())) {
6000 /*
6001 * We have hit in the predicate cache; we know that
6002 * this predicate would evaluate to be false.
6003 */
6004 dtrace_interrupt_enable(cookie);
6005 return;
6006 }
6007
6008 if (panic_quiesce) {
6009 /*
6010 * We don't trace anything if we're panicking.
6011 */
6012 dtrace_interrupt_enable(cookie);
6013 return;
6014 }
6015
6016 #if !defined(__APPLE__)
6017 now = dtrace_gethrtime();
6018 vtime = dtrace_vtime_references != 0;
6019
6020 if (vtime && curthread->t_dtrace_start)
6021 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6022 #else
6023 /*
6024 * APPLE NOTE: The time spent entering DTrace and arriving
6025 * to this point, is attributed to the current thread.
6026 * Instead it should accrue to DTrace. FIXME
6027 */
6028 vtime = dtrace_vtime_references != 0;
6029
6030 if (vtime)
6031 {
6032 int64_t dtrace_accum_time, recent_vtime;
6033 thread_t thread = current_thread();
6034
6035 dtrace_accum_time = dtrace_get_thread_tracing(thread); /* Time spent inside DTrace so far (nanoseconds) */
6036
6037 if (dtrace_accum_time >= 0) {
6038 recent_vtime = dtrace_abs_to_nano(dtrace_calc_thread_recent_vtime(thread)); /* up to the moment thread vtime */
6039
6040 recent_vtime = recent_vtime - dtrace_accum_time; /* Time without DTrace contribution */
6041
6042 dtrace_set_thread_vtime(thread, recent_vtime);
6043 }
6044 }
6045
6046 now = dtrace_gethrtime(); /* must not precede dtrace_calc_thread_recent_vtime() call! */
6047 #endif /* __APPLE__ */
6048
6049 /*
6050 * APPLE NOTE: A provider may call dtrace_probe_error() in lieu of
6051 * dtrace_probe() in some circumstances. See, e.g. fasttrap_isa.c.
6052 * However the provider has no access to ECB context, so passes
6053 * 0 through "arg0" and the probe_id of the overridden probe as arg1.
6054 * Detect that here and cons up a viable state (from the probe_id).
6055 */
6056 if (dtrace_probeid_error == id && 0 == arg0) {
6057 dtrace_id_t ftp_id = (dtrace_id_t)arg1;
6058 dtrace_probe_t *ftp_probe = dtrace_probes[ftp_id - 1];
6059 dtrace_ecb_t *ftp_ecb = ftp_probe->dtpr_ecb;
6060
6061 if (NULL != ftp_ecb) {
6062 dtrace_state_t *ftp_state = ftp_ecb->dte_state;
6063
6064 arg0 = (uint64_t)(uintptr_t)ftp_state;
6065 arg1 = ftp_ecb->dte_epid;
6066 /*
6067 * args[2-4] established by caller.
6068 */
6069 ftp_state->dts_arg_error_illval = -1; /* arg5 */
6070 }
6071 }
6072
6073 mstate.dtms_difo = NULL;
6074 mstate.dtms_probe = probe;
6075 mstate.dtms_strtok = 0;
6076 mstate.dtms_arg[0] = arg0;
6077 mstate.dtms_arg[1] = arg1;
6078 mstate.dtms_arg[2] = arg2;
6079 mstate.dtms_arg[3] = arg3;
6080 mstate.dtms_arg[4] = arg4;
6081
6082 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6083
6084 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6085 dtrace_predicate_t *pred = ecb->dte_predicate;
6086 dtrace_state_t *state = ecb->dte_state;
6087 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6088 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6089 dtrace_vstate_t *vstate = &state->dts_vstate;
6090 dtrace_provider_t *prov = probe->dtpr_provider;
6091 uint64_t tracememsize = 0;
6092 int committed = 0;
6093 caddr_t tomax;
6094
6095 /*
6096 * A little subtlety with the following (seemingly innocuous)
6097 * declaration of the automatic 'val': by looking at the
6098 * code, you might think that it could be declared in the
6099 * action processing loop, below. (That is, it's only used in
6100 * the action processing loop.) However, it must be declared
6101 * out of that scope because in the case of DIF expression
6102 * arguments to aggregating actions, one iteration of the
6103 * action loop will use the last iteration's value.
6104 */
6105 #ifdef lint
6106 uint64_t val = 0;
6107 #else
6108 uint64_t val = 0;
6109 #endif
6110
6111 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6112 *flags &= ~CPU_DTRACE_ERROR;
6113
6114 if (prov == dtrace_provider) {
6115 /*
6116 * If dtrace itself is the provider of this probe,
6117 * we're only going to continue processing the ECB if
6118 * arg0 (the dtrace_state_t) is equal to the ECB's
6119 * creating state. (This prevents disjoint consumers
6120 * from seeing one another's metaprobes.)
6121 */
6122 if (arg0 != (uint64_t)(uintptr_t)state)
6123 continue;
6124 }
6125
6126 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6127 /*
6128 * We're not currently active. If our provider isn't
6129 * the dtrace pseudo provider, we're not interested.
6130 */
6131 if (prov != dtrace_provider)
6132 continue;
6133
6134 /*
6135 * Now we must further check if we are in the BEGIN
6136 * probe. If we are, we will only continue processing
6137 * if we're still in WARMUP -- if one BEGIN enabling
6138 * has invoked the exit() action, we don't want to
6139 * evaluate subsequent BEGIN enablings.
6140 */
6141 if (probe->dtpr_id == dtrace_probeid_begin &&
6142 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6143 ASSERT(state->dts_activity ==
6144 DTRACE_ACTIVITY_DRAINING);
6145 continue;
6146 }
6147 }
6148
6149 if (ecb->dte_cond) {
6150 /*
6151 * If the dte_cond bits indicate that this
6152 * consumer is only allowed to see user-mode firings
6153 * of this probe, call the provider's dtps_usermode()
6154 * entry point to check that the probe was fired
6155 * while in a user context. Skip this ECB if that's
6156 * not the case.
6157 */
6158 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6159 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6160 probe->dtpr_id, probe->dtpr_arg) == 0)
6161 continue;
6162
6163 /*
6164 * This is more subtle than it looks. We have to be
6165 * absolutely certain that CRED() isn't going to
6166 * change out from under us so it's only legit to
6167 * examine that structure if we're in constrained
6168 * situations. Currently, the only times we'll this
6169 * check is if a non-super-user has enabled the
6170 * profile or syscall providers -- providers that
6171 * allow visibility of all processes. For the
6172 * profile case, the check above will ensure that
6173 * we're examining a user context.
6174 */
6175 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6176 cred_t *cr;
6177 cred_t *s_cr =
6178 ecb->dte_state->dts_cred.dcr_cred;
6179 proc_t *proc;
6180 #pragma unused(proc) /* __APPLE__ */
6181
6182 ASSERT(s_cr != NULL);
6183
6184 /*
6185 * XXX this is hackish, but so is setting a variable
6186 * XXX in a McCarthy OR...
6187 */
6188 if ((cr = dtrace_CRED()) == NULL ||
6189 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_uid ||
6190 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_ruid ||
6191 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_suid ||
6192 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_gid ||
6193 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_rgid ||
6194 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_sgid ||
6195 #if !defined(__APPLE__)
6196 (proc = ttoproc(curthread)) == NULL ||
6197 (proc->p_flag & SNOCD))
6198 #else
6199 1) /* APPLE NOTE: Darwin omits "No Core Dump" flag */
6200 #endif /* __APPLE__ */
6201 continue;
6202 }
6203
6204 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6205 cred_t *cr;
6206 cred_t *s_cr =
6207 ecb->dte_state->dts_cred.dcr_cred;
6208 #pragma unused(cr, s_cr) /* __APPLE__ */
6209
6210 ASSERT(s_cr != NULL);
6211
6212 #if !defined(__APPLE__)
6213 if ((cr = CRED()) == NULL ||
6214 s_cr->cr_zone->zone_id !=
6215 cr->cr_zone->zone_id)
6216 continue;
6217 #else
6218 /* APPLE NOTE: Darwin doesn't do zones. */
6219 #endif /* __APPLE__ */
6220 }
6221 }
6222
6223 if (now - state->dts_alive > dtrace_deadman_timeout) {
6224 /*
6225 * We seem to be dead. Unless we (a) have kernel
6226 * destructive permissions (b) have expicitly enabled
6227 * destructive actions and (c) destructive actions have
6228 * not been disabled, we're going to transition into
6229 * the KILLED state, from which no further processing
6230 * on this state will be performed.
6231 */
6232 if (!dtrace_priv_kernel_destructive(state) ||
6233 !state->dts_cred.dcr_destructive ||
6234 dtrace_destructive_disallow) {
6235 void *activity = &state->dts_activity;
6236 dtrace_activity_t current;
6237
6238 do {
6239 current = state->dts_activity;
6240 } while (dtrace_cas32(activity, current,
6241 DTRACE_ACTIVITY_KILLED) != current);
6242
6243 continue;
6244 }
6245 }
6246
6247 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6248 ecb->dte_alignment, state, &mstate)) < 0)
6249 continue;
6250
6251 tomax = buf->dtb_tomax;
6252 ASSERT(tomax != NULL);
6253
6254 /*
6255 * Build and store the record header corresponding to the ECB.
6256 */
6257 if (ecb->dte_size != 0) {
6258 dtrace_rechdr_t dtrh;
6259
6260 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6261 mstate.dtms_timestamp = dtrace_gethrtime();
6262 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6263 }
6264
6265 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6266
6267 dtrh.dtrh_epid = ecb->dte_epid;
6268 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh, mstate.dtms_timestamp);
6269 DTRACE_STORE(dtrace_rechdr_t, tomax, offs, dtrh);
6270 }
6271
6272 mstate.dtms_epid = ecb->dte_epid;
6273 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6274
6275 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6276 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6277 else
6278 mstate.dtms_access = 0;
6279
6280 if (pred != NULL) {
6281 dtrace_difo_t *dp = pred->dtp_difo;
6282 int rval;
6283
6284 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6285
6286 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6287 dtrace_cacheid_t cid = probe->dtpr_predcache;
6288
6289 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6290 /*
6291 * Update the predicate cache...
6292 */
6293 ASSERT(cid == pred->dtp_cacheid);
6294
6295 dtrace_set_thread_predcache(current_thread(), cid);
6296 }
6297
6298 continue;
6299 }
6300 }
6301
6302 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6303 act != NULL; act = act->dta_next) {
6304 size_t valoffs;
6305 dtrace_difo_t *dp;
6306 dtrace_recdesc_t *rec = &act->dta_rec;
6307
6308 size = rec->dtrd_size;
6309 valoffs = offs + rec->dtrd_offset;
6310
6311 if (DTRACEACT_ISAGG(act->dta_kind)) {
6312 uint64_t v = 0xbad;
6313 dtrace_aggregation_t *agg;
6314
6315 agg = (dtrace_aggregation_t *)act;
6316
6317 if ((dp = act->dta_difo) != NULL)
6318 v = dtrace_dif_emulate(dp,
6319 &mstate, vstate, state);
6320
6321 if (*flags & CPU_DTRACE_ERROR)
6322 continue;
6323
6324 /*
6325 * Note that we always pass the expression
6326 * value from the previous iteration of the
6327 * action loop. This value will only be used
6328 * if there is an expression argument to the
6329 * aggregating action, denoted by the
6330 * dtag_hasarg field.
6331 */
6332 dtrace_aggregate(agg, buf,
6333 offs, aggbuf, v, val);
6334 continue;
6335 }
6336
6337 switch (act->dta_kind) {
6338 case DTRACEACT_STOP:
6339 if (dtrace_priv_proc_destructive(state))
6340 dtrace_action_stop();
6341 continue;
6342
6343 case DTRACEACT_BREAKPOINT:
6344 if (dtrace_priv_kernel_destructive(state))
6345 dtrace_action_breakpoint(ecb);
6346 continue;
6347
6348 case DTRACEACT_PANIC:
6349 if (dtrace_priv_kernel_destructive(state))
6350 dtrace_action_panic(ecb);
6351 continue;
6352
6353 case DTRACEACT_STACK:
6354 if (!dtrace_priv_kernel(state))
6355 continue;
6356
6357 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6358 size / sizeof (pc_t), probe->dtpr_aframes,
6359 DTRACE_ANCHORED(probe) ? NULL :
6360 (uint32_t *)(uintptr_t)arg0);
6361 continue;
6362
6363 case DTRACEACT_JSTACK:
6364 case DTRACEACT_USTACK:
6365 if (!dtrace_priv_proc(state))
6366 continue;
6367
6368 /*
6369 * See comment in DIF_VAR_PID.
6370 */
6371 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6372 CPU_ON_INTR(CPU)) {
6373 int depth = DTRACE_USTACK_NFRAMES(
6374 rec->dtrd_arg) + 1;
6375
6376 dtrace_bzero((void *)(tomax + valoffs),
6377 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6378 + depth * sizeof (uint64_t));
6379
6380 continue;
6381 }
6382
6383 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6384 curproc->p_dtrace_helpers != NULL) {
6385 /*
6386 * This is the slow path -- we have
6387 * allocated string space, and we're
6388 * getting the stack of a process that
6389 * has helpers. Call into a separate
6390 * routine to perform this processing.
6391 */
6392 dtrace_action_ustack(&mstate, state,
6393 (uint64_t *)(tomax + valoffs),
6394 rec->dtrd_arg);
6395 continue;
6396 }
6397
6398 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6399 dtrace_getupcstack((uint64_t *)
6400 (tomax + valoffs),
6401 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6402 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6403 continue;
6404
6405 default:
6406 break;
6407 }
6408
6409 dp = act->dta_difo;
6410 ASSERT(dp != NULL);
6411
6412 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6413
6414 if (*flags & CPU_DTRACE_ERROR)
6415 continue;
6416
6417 switch (act->dta_kind) {
6418 case DTRACEACT_SPECULATE: {
6419 dtrace_rechdr_t *dtrh = NULL;
6420
6421 ASSERT(buf == &state->dts_buffer[cpuid]);
6422 buf = dtrace_speculation_buffer(state,
6423 cpuid, val);
6424
6425 if (buf == NULL) {
6426 *flags |= CPU_DTRACE_DROP;
6427 continue;
6428 }
6429
6430 offs = dtrace_buffer_reserve(buf,
6431 ecb->dte_needed, ecb->dte_alignment,
6432 state, NULL);
6433
6434 if (offs < 0) {
6435 *flags |= CPU_DTRACE_DROP;
6436 continue;
6437 }
6438
6439 tomax = buf->dtb_tomax;
6440 ASSERT(tomax != NULL);
6441
6442 if (ecb->dte_size != 0)
6443 continue;
6444
6445 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6446 dtrh = ((void *)(tomax + offs));
6447 dtrh->dtrh_epid = ecb->dte_epid;
6448
6449 /*
6450 * When the speculation is committed, all of
6451 * the records in the speculative buffer will
6452 * have their timestamps set to the commit
6453 * time. Until then, it is set to a sentinel
6454 * value, for debugability.
6455 */
6456 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6457
6458 continue;
6459 }
6460
6461 case DTRACEACT_CHILL:
6462 if (dtrace_priv_kernel_destructive(state))
6463 dtrace_action_chill(&mstate, val);
6464 continue;
6465
6466 case DTRACEACT_RAISE:
6467 if (dtrace_priv_proc_destructive(state))
6468 dtrace_action_raise(val);
6469 continue;
6470
6471 case DTRACEACT_PIDRESUME: /* __APPLE__ */
6472 if (dtrace_priv_proc_destructive(state))
6473 dtrace_action_pidresume(val);
6474 continue;
6475
6476 case DTRACEACT_COMMIT:
6477 ASSERT(!committed);
6478
6479 /*
6480 * We need to commit our buffer state.
6481 */
6482 if (ecb->dte_size)
6483 buf->dtb_offset = offs + ecb->dte_size;
6484 buf = &state->dts_buffer[cpuid];
6485 dtrace_speculation_commit(state, cpuid, val);
6486 committed = 1;
6487 continue;
6488
6489 case DTRACEACT_DISCARD:
6490 dtrace_speculation_discard(state, cpuid, val);
6491 continue;
6492
6493 case DTRACEACT_DIFEXPR:
6494 case DTRACEACT_LIBACT:
6495 case DTRACEACT_PRINTF:
6496 case DTRACEACT_PRINTA:
6497 case DTRACEACT_SYSTEM:
6498 case DTRACEACT_FREOPEN:
6499 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
6500 case DTRACEACT_TRACEMEM:
6501 break;
6502
6503 case DTRACEACT_TRACEMEM_DYNSIZE:
6504 tracememsize = val;
6505 break;
6506
6507 case DTRACEACT_SYM:
6508 case DTRACEACT_MOD:
6509 if (!dtrace_priv_kernel(state))
6510 continue;
6511 break;
6512
6513 case DTRACEACT_USYM:
6514 case DTRACEACT_UMOD:
6515 case DTRACEACT_UADDR: {
6516 if (!dtrace_priv_proc(state))
6517 continue;
6518
6519 DTRACE_STORE(uint64_t, tomax,
6520 valoffs, (uint64_t)dtrace_proc_selfpid());
6521 DTRACE_STORE(uint64_t, tomax,
6522 valoffs + sizeof (uint64_t), val);
6523
6524 continue;
6525 }
6526
6527 case DTRACEACT_EXIT: {
6528 /*
6529 * For the exit action, we are going to attempt
6530 * to atomically set our activity to be
6531 * draining. If this fails (either because
6532 * another CPU has beat us to the exit action,
6533 * or because our current activity is something
6534 * other than ACTIVE or WARMUP), we will
6535 * continue. This assures that the exit action
6536 * can be successfully recorded at most once
6537 * when we're in the ACTIVE state. If we're
6538 * encountering the exit() action while in
6539 * COOLDOWN, however, we want to honor the new
6540 * status code. (We know that we're the only
6541 * thread in COOLDOWN, so there is no race.)
6542 */
6543 void *activity = &state->dts_activity;
6544 dtrace_activity_t current = state->dts_activity;
6545
6546 if (current == DTRACE_ACTIVITY_COOLDOWN)
6547 break;
6548
6549 if (current != DTRACE_ACTIVITY_WARMUP)
6550 current = DTRACE_ACTIVITY_ACTIVE;
6551
6552 if (dtrace_cas32(activity, current,
6553 DTRACE_ACTIVITY_DRAINING) != current) {
6554 *flags |= CPU_DTRACE_DROP;
6555 continue;
6556 }
6557
6558 break;
6559 }
6560
6561 default:
6562 ASSERT(0);
6563 }
6564
6565 if (dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF)) {
6566 uintptr_t end = valoffs + size;
6567
6568 if (tracememsize != 0 &&
6569 valoffs + tracememsize < end)
6570 {
6571 end = valoffs + tracememsize;
6572 tracememsize = 0;
6573 }
6574
6575 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
6576 !dtrace_vcanload((void *)(uintptr_t)val,
6577 &dp->dtdo_rtype, &mstate, vstate))
6578 {
6579 continue;
6580 }
6581
6582 dtrace_store_by_ref(dp, tomax, size, &valoffs,
6583 &val, end, act->dta_intuple,
6584 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
6585 DIF_TF_BYREF: DIF_TF_BYUREF);
6586
6587 continue;
6588 }
6589
6590 switch (size) {
6591 case 0:
6592 break;
6593
6594 case sizeof (uint8_t):
6595 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6596 break;
6597 case sizeof (uint16_t):
6598 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6599 break;
6600 case sizeof (uint32_t):
6601 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6602 break;
6603 case sizeof (uint64_t):
6604 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6605 break;
6606 default:
6607 /*
6608 * Any other size should have been returned by
6609 * reference, not by value.
6610 */
6611 ASSERT(0);
6612 break;
6613 }
6614 }
6615
6616 if (*flags & CPU_DTRACE_DROP)
6617 continue;
6618
6619 if (*flags & CPU_DTRACE_FAULT) {
6620 int ndx;
6621 dtrace_action_t *err;
6622
6623 buf->dtb_errors++;
6624
6625 if (probe->dtpr_id == dtrace_probeid_error) {
6626 /*
6627 * There's nothing we can do -- we had an
6628 * error on the error probe. We bump an
6629 * error counter to at least indicate that
6630 * this condition happened.
6631 */
6632 dtrace_error(&state->dts_dblerrors);
6633 continue;
6634 }
6635
6636 if (vtime) {
6637 /*
6638 * Before recursing on dtrace_probe(), we
6639 * need to explicitly clear out our start
6640 * time to prevent it from being accumulated
6641 * into t_dtrace_vtime.
6642 */
6643
6644 /*
6645 * Darwin sets the sign bit on t_dtrace_tracing
6646 * to suspend accumulation to it.
6647 */
6648 dtrace_set_thread_tracing(current_thread(),
6649 (1ULL<<63) | dtrace_get_thread_tracing(current_thread()));
6650
6651 }
6652
6653 /*
6654 * Iterate over the actions to figure out which action
6655 * we were processing when we experienced the error.
6656 * Note that act points _past_ the faulting action; if
6657 * act is ecb->dte_action, the fault was in the
6658 * predicate, if it's ecb->dte_action->dta_next it's
6659 * in action #1, and so on.
6660 */
6661 for (err = ecb->dte_action, ndx = 0;
6662 err != act; err = err->dta_next, ndx++)
6663 continue;
6664
6665 dtrace_probe_error(state, ecb->dte_epid, ndx,
6666 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6667 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6668 cpu_core[cpuid].cpuc_dtrace_illval);
6669
6670 continue;
6671 }
6672
6673 if (!committed)
6674 buf->dtb_offset = offs + ecb->dte_size;
6675 }
6676
6677 /* FIXME: On Darwin the time spent leaving DTrace from this point to the rti is attributed
6678 to the current thread. Instead it should accrue to DTrace. */
6679 if (vtime) {
6680 thread_t thread = current_thread();
6681 int64_t t = dtrace_get_thread_tracing(thread);
6682
6683 if (t >= 0) {
6684 /* Usual case, accumulate time spent here into t_dtrace_tracing */
6685 dtrace_set_thread_tracing(thread, t + (dtrace_gethrtime() - now));
6686 } else {
6687 /* Return from error recursion. No accumulation, just clear the sign bit on t_dtrace_tracing. */
6688 dtrace_set_thread_tracing(thread, (~(1ULL<<63)) & t);
6689 }
6690 }
6691
6692 dtrace_interrupt_enable(cookie);
6693 }
6694
6695 /*
6696 * APPLE NOTE: Don't allow a thread to re-enter dtrace_probe().
6697 * This could occur if a probe is encountered on some function in the
6698 * transitive closure of the call to dtrace_probe().
6699 * Solaris has some strong guarantees that this won't happen.
6700 * The Darwin implementation is not so mature as to make those guarantees.
6701 * Hence, the introduction of __dtrace_probe() on xnu.
6702 */
6703
6704 void
6705 dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
6706 uint64_t arg2, uint64_t arg3, uint64_t arg4)
6707 {
6708 thread_t thread = current_thread();
6709 disable_preemption();
6710 if (id == dtrace_probeid_error) {
6711 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
6712 dtrace_getipl(); /* Defeat tail-call optimization of __dtrace_probe() */
6713 } else if (!dtrace_get_thread_reentering(thread)) {
6714 dtrace_set_thread_reentering(thread, TRUE);
6715 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
6716 dtrace_set_thread_reentering(thread, FALSE);
6717 }
6718 #if DEBUG
6719 else __dtrace_probe(dtrace_probeid_error, 0, id, 1, -1, DTRACEFLT_UNKNOWN);
6720 #endif
6721 enable_preemption();
6722 }
6723
6724 /*
6725 * DTrace Probe Hashing Functions
6726 *
6727 * The functions in this section (and indeed, the functions in remaining
6728 * sections) are not _called_ from probe context. (Any exceptions to this are
6729 * marked with a "Note:".) Rather, they are called from elsewhere in the
6730 * DTrace framework to look-up probes in, add probes to and remove probes from
6731 * the DTrace probe hashes. (Each probe is hashed by each element of the
6732 * probe tuple -- allowing for fast lookups, regardless of what was
6733 * specified.)
6734 */
6735 static uint_t
6736 dtrace_hash_str(const char *p)
6737 {
6738 unsigned int g;
6739 uint_t hval = 0;
6740
6741 while (*p) {
6742 hval = (hval << 4) + *p++;
6743 if ((g = (hval & 0xf0000000)) != 0)
6744 hval ^= g >> 24;
6745 hval &= ~g;
6746 }
6747 return (hval);
6748 }
6749
6750 static dtrace_hash_t *
6751 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6752 {
6753 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6754
6755 hash->dth_stroffs = stroffs;
6756 hash->dth_nextoffs = nextoffs;
6757 hash->dth_prevoffs = prevoffs;
6758
6759 hash->dth_size = 1;
6760 hash->dth_mask = hash->dth_size - 1;
6761
6762 hash->dth_tab = kmem_zalloc(hash->dth_size *
6763 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6764
6765 return (hash);
6766 }
6767
6768 /*
6769 * APPLE NOTE: dtrace_hash_destroy is not used.
6770 * It is called by dtrace_detach which is not
6771 * currently implemented. Revisit someday.
6772 */
6773 #if !defined(__APPLE__)
6774 static void
6775 dtrace_hash_destroy(dtrace_hash_t *hash)
6776 {
6777 #if DEBUG
6778 int i;
6779
6780 for (i = 0; i < hash->dth_size; i++)
6781 ASSERT(hash->dth_tab[i] == NULL);
6782 #endif
6783
6784 kmem_free(hash->dth_tab,
6785 hash->dth_size * sizeof (dtrace_hashbucket_t *));
6786 kmem_free(hash, sizeof (dtrace_hash_t));
6787 }
6788 #endif /* __APPLE__ */
6789
6790 static void
6791 dtrace_hash_resize(dtrace_hash_t *hash)
6792 {
6793 int size = hash->dth_size, i, ndx;
6794 int new_size = hash->dth_size << 1;
6795 int new_mask = new_size - 1;
6796 dtrace_hashbucket_t **new_tab, *bucket, *next;
6797
6798 ASSERT((new_size & new_mask) == 0);
6799
6800 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6801
6802 for (i = 0; i < size; i++) {
6803 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6804 dtrace_probe_t *probe = bucket->dthb_chain;
6805
6806 ASSERT(probe != NULL);
6807 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6808
6809 next = bucket->dthb_next;
6810 bucket->dthb_next = new_tab[ndx];
6811 new_tab[ndx] = bucket;
6812 }
6813 }
6814
6815 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6816 hash->dth_tab = new_tab;
6817 hash->dth_size = new_size;
6818 hash->dth_mask = new_mask;
6819 }
6820
6821 static void
6822 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6823 {
6824 int hashval = DTRACE_HASHSTR(hash, new);
6825 int ndx = hashval & hash->dth_mask;
6826 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6827 dtrace_probe_t **nextp, **prevp;
6828
6829 for (; bucket != NULL; bucket = bucket->dthb_next) {
6830 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6831 goto add;
6832 }
6833
6834 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6835 dtrace_hash_resize(hash);
6836 dtrace_hash_add(hash, new);
6837 return;
6838 }
6839
6840 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6841 bucket->dthb_next = hash->dth_tab[ndx];
6842 hash->dth_tab[ndx] = bucket;
6843 hash->dth_nbuckets++;
6844
6845 add:
6846 nextp = DTRACE_HASHNEXT(hash, new);
6847 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6848 *nextp = bucket->dthb_chain;
6849
6850 if (bucket->dthb_chain != NULL) {
6851 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6852 ASSERT(*prevp == NULL);
6853 *prevp = new;
6854 }
6855
6856 bucket->dthb_chain = new;
6857 bucket->dthb_len++;
6858 }
6859
6860 static dtrace_probe_t *
6861 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6862 {
6863 int hashval = DTRACE_HASHSTR(hash, template);
6864 int ndx = hashval & hash->dth_mask;
6865 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6866
6867 for (; bucket != NULL; bucket = bucket->dthb_next) {
6868 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6869 return (bucket->dthb_chain);
6870 }
6871
6872 return (NULL);
6873 }
6874
6875 static int
6876 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6877 {
6878 int hashval = DTRACE_HASHSTR(hash, template);
6879 int ndx = hashval & hash->dth_mask;
6880 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6881
6882 for (; bucket != NULL; bucket = bucket->dthb_next) {
6883 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6884 return (bucket->dthb_len);
6885 }
6886
6887 return (0);
6888 }
6889
6890 static void
6891 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6892 {
6893 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6894 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6895
6896 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6897 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6898
6899 /*
6900 * Find the bucket that we're removing this probe from.
6901 */
6902 for (; bucket != NULL; bucket = bucket->dthb_next) {
6903 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6904 break;
6905 }
6906
6907 ASSERT(bucket != NULL);
6908
6909 if (*prevp == NULL) {
6910 if (*nextp == NULL) {
6911 /*
6912 * The removed probe was the only probe on this
6913 * bucket; we need to remove the bucket.
6914 */
6915 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6916
6917 ASSERT(bucket->dthb_chain == probe);
6918 ASSERT(b != NULL);
6919
6920 if (b == bucket) {
6921 hash->dth_tab[ndx] = bucket->dthb_next;
6922 } else {
6923 while (b->dthb_next != bucket)
6924 b = b->dthb_next;
6925 b->dthb_next = bucket->dthb_next;
6926 }
6927
6928 ASSERT(hash->dth_nbuckets > 0);
6929 hash->dth_nbuckets--;
6930 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6931 return;
6932 }
6933
6934 bucket->dthb_chain = *nextp;
6935 } else {
6936 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6937 }
6938
6939 if (*nextp != NULL)
6940 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6941 }
6942
6943 /*
6944 * DTrace Utility Functions
6945 *
6946 * These are random utility functions that are _not_ called from probe context.
6947 */
6948 static int
6949 dtrace_badattr(const dtrace_attribute_t *a)
6950 {
6951 return (a->dtat_name > DTRACE_STABILITY_MAX ||
6952 a->dtat_data > DTRACE_STABILITY_MAX ||
6953 a->dtat_class > DTRACE_CLASS_MAX);
6954 }
6955
6956 /*
6957 * Return a duplicate copy of a string. If the specified string is NULL,
6958 * this function returns a zero-length string.
6959 * APPLE NOTE: Darwin employs size bounded string operation.
6960 */
6961 static char *
6962 dtrace_strdup(const char *str)
6963 {
6964 size_t bufsize = (str != NULL ? strlen(str) : 0) + 1;
6965 char *new = kmem_zalloc(bufsize, KM_SLEEP);
6966
6967 if (str != NULL)
6968 (void) strlcpy(new, str, bufsize);
6969
6970 return (new);
6971 }
6972
6973 #define DTRACE_ISALPHA(c) \
6974 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6975
6976 static int
6977 dtrace_badname(const char *s)
6978 {
6979 char c;
6980
6981 if (s == NULL || (c = *s++) == '\0')
6982 return (0);
6983
6984 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6985 return (1);
6986
6987 while ((c = *s++) != '\0') {
6988 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6989 c != '-' && c != '_' && c != '.' && c != '`')
6990 return (1);
6991 }
6992
6993 return (0);
6994 }
6995
6996 static void
6997 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6998 {
6999 uint32_t priv;
7000
7001 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7002 /*
7003 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7004 */
7005 priv = DTRACE_PRIV_ALL;
7006 } else {
7007 *uidp = crgetuid(cr);
7008 *zoneidp = crgetzoneid(cr);
7009
7010 priv = 0;
7011 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7012 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7013 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7014 priv |= DTRACE_PRIV_USER;
7015 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7016 priv |= DTRACE_PRIV_PROC;
7017 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7018 priv |= DTRACE_PRIV_OWNER;
7019 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7020 priv |= DTRACE_PRIV_ZONEOWNER;
7021 }
7022
7023 *privp = priv;
7024 }
7025
7026 #ifdef DTRACE_ERRDEBUG
7027 static void
7028 dtrace_errdebug(const char *str)
7029 {
7030 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7031 int occupied = 0;
7032
7033 lck_mtx_lock(&dtrace_errlock);
7034 dtrace_errlast = str;
7035 dtrace_errthread = (kthread_t *)current_thread();
7036
7037 while (occupied++ < DTRACE_ERRHASHSZ) {
7038 if (dtrace_errhash[hval].dter_msg == str) {
7039 dtrace_errhash[hval].dter_count++;
7040 goto out;
7041 }
7042
7043 if (dtrace_errhash[hval].dter_msg != NULL) {
7044 hval = (hval + 1) % DTRACE_ERRHASHSZ;
7045 continue;
7046 }
7047
7048 dtrace_errhash[hval].dter_msg = str;
7049 dtrace_errhash[hval].dter_count = 1;
7050 goto out;
7051 }
7052
7053 panic("dtrace: undersized error hash");
7054 out:
7055 lck_mtx_unlock(&dtrace_errlock);
7056 }
7057 #endif
7058
7059 /*
7060 * DTrace Matching Functions
7061 *
7062 * These functions are used to match groups of probes, given some elements of
7063 * a probe tuple, or some globbed expressions for elements of a probe tuple.
7064 */
7065 static int
7066 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7067 zoneid_t zoneid)
7068 {
7069 if (priv != DTRACE_PRIV_ALL) {
7070 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7071 uint32_t match = priv & ppriv;
7072
7073 /*
7074 * No PRIV_DTRACE_* privileges...
7075 */
7076 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7077 DTRACE_PRIV_KERNEL)) == 0)
7078 return (0);
7079
7080 /*
7081 * No matching bits, but there were bits to match...
7082 */
7083 if (match == 0 && ppriv != 0)
7084 return (0);
7085
7086 /*
7087 * Need to have permissions to the process, but don't...
7088 */
7089 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7090 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7091 return (0);
7092 }
7093
7094 /*
7095 * Need to be in the same zone unless we possess the
7096 * privilege to examine all zones.
7097 */
7098 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7099 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7100 return (0);
7101 }
7102 }
7103
7104 return (1);
7105 }
7106
7107 /*
7108 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7109 * consists of input pattern strings and an ops-vector to evaluate them.
7110 * This function returns >0 for match, 0 for no match, and <0 for error.
7111 */
7112 static int
7113 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7114 uint32_t priv, uid_t uid, zoneid_t zoneid)
7115 {
7116 dtrace_provider_t *pvp = prp->dtpr_provider;
7117 int rv;
7118
7119 if (pvp->dtpv_defunct)
7120 return (0);
7121
7122 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7123 return (rv);
7124
7125 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7126 return (rv);
7127
7128 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7129 return (rv);
7130
7131 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7132 return (rv);
7133
7134 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7135 return (0);
7136
7137 return (rv);
7138 }
7139
7140 /*
7141 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7142 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7143 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7144 * In addition, all of the recursion cases except for '*' matching have been
7145 * unwound. For '*', we still implement recursive evaluation, but a depth
7146 * counter is maintained and matching is aborted if we recurse too deep.
7147 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7148 */
7149 static int
7150 dtrace_match_glob(const char *s, const char *p, int depth)
7151 {
7152 const char *olds;
7153 char s1, c;
7154 int gs;
7155
7156 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7157 return (-1);
7158
7159 if (s == NULL)
7160 s = ""; /* treat NULL as empty string */
7161
7162 top:
7163 olds = s;
7164 s1 = *s++;
7165
7166 if (p == NULL)
7167 return (0);
7168
7169 if ((c = *p++) == '\0')
7170 return (s1 == '\0');
7171
7172 switch (c) {
7173 case '[': {
7174 int ok = 0, notflag = 0;
7175 char lc = '\0';
7176
7177 if (s1 == '\0')
7178 return (0);
7179
7180 if (*p == '!') {
7181 notflag = 1;
7182 p++;
7183 }
7184
7185 if ((c = *p++) == '\0')
7186 return (0);
7187
7188 do {
7189 if (c == '-' && lc != '\0' && *p != ']') {
7190 if ((c = *p++) == '\0')
7191 return (0);
7192 if (c == '\\' && (c = *p++) == '\0')
7193 return (0);
7194
7195 if (notflag) {
7196 if (s1 < lc || s1 > c)
7197 ok++;
7198 else
7199 return (0);
7200 } else if (lc <= s1 && s1 <= c)
7201 ok++;
7202
7203 } else if (c == '\\' && (c = *p++) == '\0')
7204 return (0);
7205
7206 lc = c; /* save left-hand 'c' for next iteration */
7207
7208 if (notflag) {
7209 if (s1 != c)
7210 ok++;
7211 else
7212 return (0);
7213 } else if (s1 == c)
7214 ok++;
7215
7216 if ((c = *p++) == '\0')
7217 return (0);
7218
7219 } while (c != ']');
7220
7221 if (ok)
7222 goto top;
7223
7224 return (0);
7225 }
7226
7227 case '\\':
7228 if ((c = *p++) == '\0')
7229 return (0);
7230 /*FALLTHRU*/
7231
7232 default:
7233 if (c != s1)
7234 return (0);
7235 /*FALLTHRU*/
7236
7237 case '?':
7238 if (s1 != '\0')
7239 goto top;
7240 return (0);
7241
7242 case '*':
7243 while (*p == '*')
7244 p++; /* consecutive *'s are identical to a single one */
7245
7246 if (*p == '\0')
7247 return (1);
7248
7249 for (s = olds; *s != '\0'; s++) {
7250 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7251 return (gs);
7252 }
7253
7254 return (0);
7255 }
7256 }
7257
7258 /*ARGSUSED*/
7259 static int
7260 dtrace_match_string(const char *s, const char *p, int depth)
7261 {
7262 #pragma unused(depth) /* __APPLE__ */
7263
7264 /* APPLE NOTE: Darwin employs size bounded string operation. */
7265 return (s != NULL && strncmp(s, p, strlen(s) + 1) == 0);
7266 }
7267
7268 /*ARGSUSED*/
7269 static int
7270 dtrace_match_nul(const char *s, const char *p, int depth)
7271 {
7272 #pragma unused(s, p, depth) /* __APPLE__ */
7273 return (1); /* always match the empty pattern */
7274 }
7275
7276 /*ARGSUSED*/
7277 static int
7278 dtrace_match_nonzero(const char *s, const char *p, int depth)
7279 {
7280 #pragma unused(p, depth) /* __APPLE__ */
7281 return (s != NULL && s[0] != '\0');
7282 }
7283
7284 static int
7285 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7286 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7287 {
7288 dtrace_probe_t template, *probe;
7289 dtrace_hash_t *hash = NULL;
7290 int len, rc, best = INT_MAX, nmatched = 0;
7291 dtrace_id_t i;
7292
7293 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7294
7295 /*
7296 * If the probe ID is specified in the key, just lookup by ID and
7297 * invoke the match callback once if a matching probe is found.
7298 */
7299 if (pkp->dtpk_id != DTRACE_IDNONE) {
7300 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7301 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7302 if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7303 return (DTRACE_MATCH_FAIL);
7304 nmatched++;
7305 }
7306 return (nmatched);
7307 }
7308
7309 template.dtpr_mod = (char *)(uintptr_t)pkp->dtpk_mod;
7310 template.dtpr_func = (char *)(uintptr_t)pkp->dtpk_func;
7311 template.dtpr_name = (char *)(uintptr_t)pkp->dtpk_name;
7312
7313 /*
7314 * We want to find the most distinct of the module name, function
7315 * name, and name. So for each one that is not a glob pattern or
7316 * empty string, we perform a lookup in the corresponding hash and
7317 * use the hash table with the fewest collisions to do our search.
7318 */
7319 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7320 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7321 best = len;
7322 hash = dtrace_bymod;
7323 }
7324
7325 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7326 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7327 best = len;
7328 hash = dtrace_byfunc;
7329 }
7330
7331 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7332 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7333 best = len;
7334 hash = dtrace_byname;
7335 }
7336
7337 /*
7338 * If we did not select a hash table, iterate over every probe and
7339 * invoke our callback for each one that matches our input probe key.
7340 */
7341 if (hash == NULL) {
7342 for (i = 0; i < (dtrace_id_t)dtrace_nprobes; i++) {
7343 if ((probe = dtrace_probes[i]) == NULL ||
7344 dtrace_match_probe(probe, pkp, priv, uid,
7345 zoneid) <= 0)
7346 continue;
7347
7348 nmatched++;
7349
7350 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7351 if (rc == DTRACE_MATCH_FAIL)
7352 return (DTRACE_MATCH_FAIL);
7353 break;
7354 }
7355 }
7356
7357 return (nmatched);
7358 }
7359
7360 /*
7361 * If we selected a hash table, iterate over each probe of the same key
7362 * name and invoke the callback for every probe that matches the other
7363 * attributes of our input probe key.
7364 */
7365 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7366 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7367
7368 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7369 continue;
7370
7371 nmatched++;
7372
7373 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7374 if (rc == DTRACE_MATCH_FAIL)
7375 return (DTRACE_MATCH_FAIL);
7376 break;
7377 }
7378 }
7379
7380 return (nmatched);
7381 }
7382
7383 /*
7384 * Return the function pointer dtrace_probecmp() should use to compare the
7385 * specified pattern with a string. For NULL or empty patterns, we select
7386 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7387 * For non-empty non-glob strings, we use dtrace_match_string().
7388 */
7389 static dtrace_probekey_f *
7390 dtrace_probekey_func(const char *p)
7391 {
7392 char c;
7393
7394 if (p == NULL || *p == '\0')
7395 return (&dtrace_match_nul);
7396
7397 while ((c = *p++) != '\0') {
7398 if (c == '[' || c == '?' || c == '*' || c == '\\')
7399 return (&dtrace_match_glob);
7400 }
7401
7402 return (&dtrace_match_string);
7403 }
7404
7405 /*
7406 * Build a probe comparison key for use with dtrace_match_probe() from the
7407 * given probe description. By convention, a null key only matches anchored
7408 * probes: if each field is the empty string, reset dtpk_fmatch to
7409 * dtrace_match_nonzero().
7410 */
7411 static void
7412 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7413 {
7414 pkp->dtpk_prov = pdp->dtpd_provider;
7415 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7416
7417 pkp->dtpk_mod = pdp->dtpd_mod;
7418 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7419
7420 pkp->dtpk_func = pdp->dtpd_func;
7421 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7422
7423 pkp->dtpk_name = pdp->dtpd_name;
7424 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7425
7426 pkp->dtpk_id = pdp->dtpd_id;
7427
7428 if (pkp->dtpk_id == DTRACE_IDNONE &&
7429 pkp->dtpk_pmatch == &dtrace_match_nul &&
7430 pkp->dtpk_mmatch == &dtrace_match_nul &&
7431 pkp->dtpk_fmatch == &dtrace_match_nul &&
7432 pkp->dtpk_nmatch == &dtrace_match_nul)
7433 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7434 }
7435
7436 /*
7437 * DTrace Provider-to-Framework API Functions
7438 *
7439 * These functions implement much of the Provider-to-Framework API, as
7440 * described in <sys/dtrace.h>. The parts of the API not in this section are
7441 * the functions in the API for probe management (found below), and
7442 * dtrace_probe() itself (found above).
7443 */
7444
7445 /*
7446 * Register the calling provider with the DTrace framework. This should
7447 * generally be called by DTrace providers in their attach(9E) entry point.
7448 */
7449 int
7450 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7451 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7452 {
7453 dtrace_provider_t *provider;
7454
7455 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7456 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7457 "arguments", name ? name : "<NULL>");
7458 return (EINVAL);
7459 }
7460
7461 if (name[0] == '\0' || dtrace_badname(name)) {
7462 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7463 "provider name", name);
7464 return (EINVAL);
7465 }
7466
7467 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7468 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7469 pops->dtps_destroy == NULL ||
7470 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7471 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7472 "provider ops", name);
7473 return (EINVAL);
7474 }
7475
7476 if (dtrace_badattr(&pap->dtpa_provider) ||
7477 dtrace_badattr(&pap->dtpa_mod) ||
7478 dtrace_badattr(&pap->dtpa_func) ||
7479 dtrace_badattr(&pap->dtpa_name) ||
7480 dtrace_badattr(&pap->dtpa_args)) {
7481 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7482 "provider attributes", name);
7483 return (EINVAL);
7484 }
7485
7486 if (priv & ~DTRACE_PRIV_ALL) {
7487 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7488 "privilege attributes", name);
7489 return (EINVAL);
7490 }
7491
7492 if ((priv & DTRACE_PRIV_KERNEL) &&
7493 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7494 pops->dtps_usermode == NULL) {
7495 cmn_err(CE_WARN, "failed to register provider '%s': need "
7496 "dtps_usermode() op for given privilege attributes", name);
7497 return (EINVAL);
7498 }
7499
7500 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7501
7502 /* APPLE NOTE: Darwin employs size bounded string operation. */
7503 {
7504 size_t bufsize = strlen(name) + 1;
7505 provider->dtpv_name = kmem_alloc(bufsize, KM_SLEEP);
7506 (void) strlcpy(provider->dtpv_name, name, bufsize);
7507 }
7508
7509 provider->dtpv_attr = *pap;
7510 provider->dtpv_priv.dtpp_flags = priv;
7511 if (cr != NULL) {
7512 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7513 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7514 }
7515 provider->dtpv_pops = *pops;
7516
7517 if (pops->dtps_provide == NULL) {
7518 ASSERT(pops->dtps_provide_module != NULL);
7519 provider->dtpv_pops.dtps_provide =
7520 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7521 }
7522
7523 if (pops->dtps_provide_module == NULL) {
7524 ASSERT(pops->dtps_provide != NULL);
7525 provider->dtpv_pops.dtps_provide_module =
7526 (void (*)(void *, struct modctl *))dtrace_nullop;
7527 }
7528
7529 if (pops->dtps_suspend == NULL) {
7530 ASSERT(pops->dtps_resume == NULL);
7531 provider->dtpv_pops.dtps_suspend =
7532 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7533 provider->dtpv_pops.dtps_resume =
7534 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7535 }
7536
7537 provider->dtpv_arg = arg;
7538 *idp = (dtrace_provider_id_t)provider;
7539
7540 if (pops == &dtrace_provider_ops) {
7541 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7542 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7543 ASSERT(dtrace_anon.dta_enabling == NULL);
7544
7545 /*
7546 * We make sure that the DTrace provider is at the head of
7547 * the provider chain.
7548 */
7549 provider->dtpv_next = dtrace_provider;
7550 dtrace_provider = provider;
7551 return (0);
7552 }
7553
7554 lck_mtx_lock(&dtrace_provider_lock);
7555 lck_mtx_lock(&dtrace_lock);
7556
7557 /*
7558 * If there is at least one provider registered, we'll add this
7559 * provider after the first provider.
7560 */
7561 if (dtrace_provider != NULL) {
7562 provider->dtpv_next = dtrace_provider->dtpv_next;
7563 dtrace_provider->dtpv_next = provider;
7564 } else {
7565 dtrace_provider = provider;
7566 }
7567
7568 if (dtrace_retained != NULL) {
7569 dtrace_enabling_provide(provider);
7570
7571 /*
7572 * Now we need to call dtrace_enabling_matchall() -- which
7573 * will acquire cpu_lock and dtrace_lock. We therefore need
7574 * to drop all of our locks before calling into it...
7575 */
7576 lck_mtx_unlock(&dtrace_lock);
7577 lck_mtx_unlock(&dtrace_provider_lock);
7578 dtrace_enabling_matchall();
7579
7580 return (0);
7581 }
7582
7583 lck_mtx_unlock(&dtrace_lock);
7584 lck_mtx_unlock(&dtrace_provider_lock);
7585
7586 return (0);
7587 }
7588
7589 /*
7590 * Unregister the specified provider from the DTrace framework. This should
7591 * generally be called by DTrace providers in their detach(9E) entry point.
7592 */
7593 int
7594 dtrace_unregister(dtrace_provider_id_t id)
7595 {
7596 dtrace_provider_t *old = (dtrace_provider_t *)id;
7597 dtrace_provider_t *prev = NULL;
7598 int i, self = 0;
7599 dtrace_probe_t *probe, *first = NULL;
7600
7601 if (old->dtpv_pops.dtps_enable ==
7602 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7603 /*
7604 * If DTrace itself is the provider, we're called with locks
7605 * already held.
7606 */
7607 ASSERT(old == dtrace_provider);
7608 ASSERT(dtrace_devi != NULL);
7609 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7610 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7611 self = 1;
7612
7613 if (dtrace_provider->dtpv_next != NULL) {
7614 /*
7615 * There's another provider here; return failure.
7616 */
7617 return (EBUSY);
7618 }
7619 } else {
7620 lck_mtx_lock(&dtrace_provider_lock);
7621 lck_mtx_lock(&mod_lock);
7622 lck_mtx_lock(&dtrace_lock);
7623 }
7624
7625 /*
7626 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7627 * probes, we refuse to let providers slither away, unless this
7628 * provider has already been explicitly invalidated.
7629 */
7630 if (!old->dtpv_defunct &&
7631 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7632 dtrace_anon.dta_state->dts_necbs > 0))) {
7633 if (!self) {
7634 lck_mtx_unlock(&dtrace_lock);
7635 lck_mtx_unlock(&mod_lock);
7636 lck_mtx_unlock(&dtrace_provider_lock);
7637 }
7638 return (EBUSY);
7639 }
7640
7641 /*
7642 * Attempt to destroy the probes associated with this provider.
7643 */
7644 if (old->dtpv_ecb_count!=0) {
7645 /*
7646 * We have at least one ECB; we can't remove this provider.
7647 */
7648 if (!self) {
7649 lck_mtx_unlock(&dtrace_lock);
7650 lck_mtx_unlock(&mod_lock);
7651 lck_mtx_unlock(&dtrace_provider_lock);
7652 }
7653 return (EBUSY);
7654 }
7655
7656 /*
7657 * All of the probes for this provider are disabled; we can safely
7658 * remove all of them from their hash chains and from the probe array.
7659 */
7660 for (i = 0; i < dtrace_nprobes && old->dtpv_probe_count!=0; i++) {
7661 if ((probe = dtrace_probes[i]) == NULL)
7662 continue;
7663
7664 if (probe->dtpr_provider != old)
7665 continue;
7666
7667 dtrace_probes[i] = NULL;
7668 old->dtpv_probe_count--;
7669
7670 dtrace_hash_remove(dtrace_bymod, probe);
7671 dtrace_hash_remove(dtrace_byfunc, probe);
7672 dtrace_hash_remove(dtrace_byname, probe);
7673
7674 if (first == NULL) {
7675 first = probe;
7676 probe->dtpr_nextmod = NULL;
7677 } else {
7678 probe->dtpr_nextmod = first;
7679 first = probe;
7680 }
7681 }
7682
7683 /*
7684 * The provider's probes have been removed from the hash chains and
7685 * from the probe array. Now issue a dtrace_sync() to be sure that
7686 * everyone has cleared out from any probe array processing.
7687 */
7688 dtrace_sync();
7689
7690 for (probe = first; probe != NULL; probe = first) {
7691 first = probe->dtpr_nextmod;
7692
7693 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7694 probe->dtpr_arg);
7695 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7696 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7697 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7698 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7699 zfree(dtrace_probe_t_zone, probe);
7700 }
7701
7702 if ((prev = dtrace_provider) == old) {
7703 ASSERT(self || dtrace_devi == NULL);
7704 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7705 dtrace_provider = old->dtpv_next;
7706 } else {
7707 while (prev != NULL && prev->dtpv_next != old)
7708 prev = prev->dtpv_next;
7709
7710 if (prev == NULL) {
7711 panic("attempt to unregister non-existent "
7712 "dtrace provider %p\n", (void *)id);
7713 }
7714
7715 prev->dtpv_next = old->dtpv_next;
7716 }
7717
7718 if (!self) {
7719 lck_mtx_unlock(&dtrace_lock);
7720 lck_mtx_unlock(&mod_lock);
7721 lck_mtx_unlock(&dtrace_provider_lock);
7722 }
7723
7724 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7725 kmem_free(old, sizeof (dtrace_provider_t));
7726
7727 return (0);
7728 }
7729
7730 /*
7731 * Invalidate the specified provider. All subsequent probe lookups for the
7732 * specified provider will fail, but its probes will not be removed.
7733 */
7734 void
7735 dtrace_invalidate(dtrace_provider_id_t id)
7736 {
7737 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7738
7739 ASSERT(pvp->dtpv_pops.dtps_enable !=
7740 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7741
7742 lck_mtx_lock(&dtrace_provider_lock);
7743 lck_mtx_lock(&dtrace_lock);
7744
7745 pvp->dtpv_defunct = 1;
7746
7747 lck_mtx_unlock(&dtrace_lock);
7748 lck_mtx_unlock(&dtrace_provider_lock);
7749 }
7750
7751 /*
7752 * Indicate whether or not DTrace has attached.
7753 */
7754 int
7755 dtrace_attached(void)
7756 {
7757 /*
7758 * dtrace_provider will be non-NULL iff the DTrace driver has
7759 * attached. (It's non-NULL because DTrace is always itself a
7760 * provider.)
7761 */
7762 return (dtrace_provider != NULL);
7763 }
7764
7765 /*
7766 * Remove all the unenabled probes for the given provider. This function is
7767 * not unlike dtrace_unregister(), except that it doesn't remove the provider
7768 * -- just as many of its associated probes as it can.
7769 */
7770 int
7771 dtrace_condense(dtrace_provider_id_t id)
7772 {
7773 dtrace_provider_t *prov = (dtrace_provider_t *)id;
7774 int i;
7775 dtrace_probe_t *probe;
7776
7777 /*
7778 * Make sure this isn't the dtrace provider itself.
7779 */
7780 ASSERT(prov->dtpv_pops.dtps_enable !=
7781 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7782
7783 lck_mtx_lock(&dtrace_provider_lock);
7784 lck_mtx_lock(&dtrace_lock);
7785
7786 /*
7787 * Attempt to destroy the probes associated with this provider.
7788 */
7789 for (i = 0; i < dtrace_nprobes; i++) {
7790 if ((probe = dtrace_probes[i]) == NULL)
7791 continue;
7792
7793 if (probe->dtpr_provider != prov)
7794 continue;
7795
7796 if (probe->dtpr_ecb != NULL)
7797 continue;
7798
7799 dtrace_probes[i] = NULL;
7800 prov->dtpv_probe_count--;
7801
7802 dtrace_hash_remove(dtrace_bymod, probe);
7803 dtrace_hash_remove(dtrace_byfunc, probe);
7804 dtrace_hash_remove(dtrace_byname, probe);
7805
7806 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7807 probe->dtpr_arg);
7808 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7809 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7810 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7811 zfree(dtrace_probe_t_zone, probe);
7812 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7813 }
7814
7815 lck_mtx_unlock(&dtrace_lock);
7816 lck_mtx_unlock(&dtrace_provider_lock);
7817
7818 return (0);
7819 }
7820
7821 /*
7822 * DTrace Probe Management Functions
7823 *
7824 * The functions in this section perform the DTrace probe management,
7825 * including functions to create probes, look-up probes, and call into the
7826 * providers to request that probes be provided. Some of these functions are
7827 * in the Provider-to-Framework API; these functions can be identified by the
7828 * fact that they are not declared "static".
7829 */
7830
7831 /*
7832 * Create a probe with the specified module name, function name, and name.
7833 */
7834 dtrace_id_t
7835 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7836 const char *func, const char *name, int aframes, void *arg)
7837 {
7838 dtrace_probe_t *probe, **probes;
7839 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7840 dtrace_id_t id;
7841
7842 if (provider == dtrace_provider) {
7843 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7844 } else {
7845 lck_mtx_lock(&dtrace_lock);
7846 }
7847
7848 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7849 VM_BESTFIT | VM_SLEEP);
7850
7851 probe = zalloc(dtrace_probe_t_zone);
7852 bzero(probe, sizeof (dtrace_probe_t));
7853
7854 probe->dtpr_id = id;
7855 probe->dtpr_gen = dtrace_probegen++;
7856 probe->dtpr_mod = dtrace_strdup(mod);
7857 probe->dtpr_func = dtrace_strdup(func);
7858 probe->dtpr_name = dtrace_strdup(name);
7859 probe->dtpr_arg = arg;
7860 probe->dtpr_aframes = aframes;
7861 probe->dtpr_provider = provider;
7862
7863 dtrace_hash_add(dtrace_bymod, probe);
7864 dtrace_hash_add(dtrace_byfunc, probe);
7865 dtrace_hash_add(dtrace_byname, probe);
7866
7867 if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
7868 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7869 size_t nsize = osize << 1;
7870
7871 if (nsize == 0) {
7872 ASSERT(osize == 0);
7873 ASSERT(dtrace_probes == NULL);
7874 nsize = sizeof (dtrace_probe_t *);
7875 }
7876
7877 probes = kmem_zalloc(nsize, KM_SLEEP);
7878
7879 if (dtrace_probes == NULL) {
7880 ASSERT(osize == 0);
7881 dtrace_probes = probes;
7882 dtrace_nprobes = 1;
7883 } else {
7884 dtrace_probe_t **oprobes = dtrace_probes;
7885
7886 bcopy(oprobes, probes, osize);
7887 dtrace_membar_producer();
7888 dtrace_probes = probes;
7889
7890 dtrace_sync();
7891
7892 /*
7893 * All CPUs are now seeing the new probes array; we can
7894 * safely free the old array.
7895 */
7896 kmem_free(oprobes, osize);
7897 dtrace_nprobes <<= 1;
7898 }
7899
7900 ASSERT(id - 1 < (dtrace_id_t)dtrace_nprobes);
7901 }
7902
7903 ASSERT(dtrace_probes[id - 1] == NULL);
7904 dtrace_probes[id - 1] = probe;
7905 provider->dtpv_probe_count++;
7906
7907 if (provider != dtrace_provider)
7908 lck_mtx_unlock(&dtrace_lock);
7909
7910 return (id);
7911 }
7912
7913 static dtrace_probe_t *
7914 dtrace_probe_lookup_id(dtrace_id_t id)
7915 {
7916 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7917
7918 if (id == 0 || id > (dtrace_id_t)dtrace_nprobes)
7919 return (NULL);
7920
7921 return (dtrace_probes[id - 1]);
7922 }
7923
7924 static int
7925 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7926 {
7927 *((dtrace_id_t *)arg) = probe->dtpr_id;
7928
7929 return (DTRACE_MATCH_DONE);
7930 }
7931
7932 /*
7933 * Look up a probe based on provider and one or more of module name, function
7934 * name and probe name.
7935 */
7936 dtrace_id_t
7937 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7938 const char *func, const char *name)
7939 {
7940 dtrace_probekey_t pkey;
7941 dtrace_id_t id;
7942 int match;
7943
7944 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7945 pkey.dtpk_pmatch = &dtrace_match_string;
7946 pkey.dtpk_mod = mod;
7947 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7948 pkey.dtpk_func = func;
7949 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7950 pkey.dtpk_name = name;
7951 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7952 pkey.dtpk_id = DTRACE_IDNONE;
7953
7954 lck_mtx_lock(&dtrace_lock);
7955 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7956 dtrace_probe_lookup_match, &id);
7957 lck_mtx_unlock(&dtrace_lock);
7958
7959 ASSERT(match == 1 || match == 0);
7960 return (match ? id : 0);
7961 }
7962
7963 /*
7964 * Returns the probe argument associated with the specified probe.
7965 */
7966 void *
7967 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7968 {
7969 dtrace_probe_t *probe;
7970 void *rval = NULL;
7971
7972 lck_mtx_lock(&dtrace_lock);
7973
7974 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7975 probe->dtpr_provider == (dtrace_provider_t *)id)
7976 rval = probe->dtpr_arg;
7977
7978 lck_mtx_unlock(&dtrace_lock);
7979
7980 return (rval);
7981 }
7982
7983 /*
7984 * Copy a probe into a probe description.
7985 */
7986 static void
7987 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7988 {
7989 bzero(pdp, sizeof (dtrace_probedesc_t));
7990 pdp->dtpd_id = prp->dtpr_id;
7991
7992 /* APPLE NOTE: Darwin employs size bounded string operation. */
7993 (void) strlcpy(pdp->dtpd_provider,
7994 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN);
7995
7996 (void) strlcpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN);
7997 (void) strlcpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN);
7998 (void) strlcpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN);
7999 }
8000
8001 /*
8002 * Called to indicate that a probe -- or probes -- should be provided by a
8003 * specfied provider. If the specified description is NULL, the provider will
8004 * be told to provide all of its probes. (This is done whenever a new
8005 * consumer comes along, or whenever a retained enabling is to be matched.) If
8006 * the specified description is non-NULL, the provider is given the
8007 * opportunity to dynamically provide the specified probe, allowing providers
8008 * to support the creation of probes on-the-fly. (So-called _autocreated_
8009 * probes.) If the provider is NULL, the operations will be applied to all
8010 * providers; if the provider is non-NULL the operations will only be applied
8011 * to the specified provider. The dtrace_provider_lock must be held, and the
8012 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8013 * will need to grab the dtrace_lock when it reenters the framework through
8014 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8015 */
8016 static void
8017 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8018 {
8019 struct modctl *ctl;
8020 int all = 0;
8021
8022 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8023
8024 if (prv == NULL) {
8025 all = 1;
8026 prv = dtrace_provider;
8027 }
8028
8029 do {
8030 /*
8031 * First, call the blanket provide operation.
8032 */
8033 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8034
8035 /*
8036 * Now call the per-module provide operation. We will grab
8037 * mod_lock to prevent the list from being modified. Note
8038 * that this also prevents the mod_busy bits from changing.
8039 * (mod_busy can only be changed with mod_lock held.)
8040 */
8041 lck_mtx_lock(&mod_lock);
8042
8043 ctl = dtrace_modctl_list;
8044 while (ctl) {
8045 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8046 ctl = ctl->mod_next;
8047 }
8048
8049 lck_mtx_unlock(&mod_lock);
8050 } while (all && (prv = prv->dtpv_next) != NULL);
8051 }
8052
8053 /*
8054 * Iterate over each probe, and call the Framework-to-Provider API function
8055 * denoted by offs.
8056 */
8057 static void
8058 dtrace_probe_foreach(uintptr_t offs)
8059 {
8060 dtrace_provider_t *prov;
8061 void (*func)(void *, dtrace_id_t, void *);
8062 dtrace_probe_t *probe;
8063 dtrace_icookie_t cookie;
8064 int i;
8065
8066 /*
8067 * We disable interrupts to walk through the probe array. This is
8068 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8069 * won't see stale data.
8070 */
8071 cookie = dtrace_interrupt_disable();
8072
8073 for (i = 0; i < dtrace_nprobes; i++) {
8074 if ((probe = dtrace_probes[i]) == NULL)
8075 continue;
8076
8077 if (probe->dtpr_ecb == NULL) {
8078 /*
8079 * This probe isn't enabled -- don't call the function.
8080 */
8081 continue;
8082 }
8083
8084 prov = probe->dtpr_provider;
8085 func = *((void(**)(void *, dtrace_id_t, void *))
8086 ((uintptr_t)&prov->dtpv_pops + offs));
8087
8088 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8089 }
8090
8091 dtrace_interrupt_enable(cookie);
8092 }
8093
8094 static int
8095 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8096 {
8097 dtrace_probekey_t pkey;
8098 uint32_t priv;
8099 uid_t uid;
8100 zoneid_t zoneid;
8101
8102 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8103
8104 dtrace_ecb_create_cache = NULL;
8105
8106 if (desc == NULL) {
8107 /*
8108 * If we're passed a NULL description, we're being asked to
8109 * create an ECB with a NULL probe.
8110 */
8111 (void) dtrace_ecb_create_enable(NULL, enab);
8112 return (0);
8113 }
8114
8115 dtrace_probekey(desc, &pkey);
8116 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8117 &priv, &uid, &zoneid);
8118
8119 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8120 enab));
8121 }
8122
8123 /*
8124 * DTrace Helper Provider Functions
8125 */
8126 static void
8127 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8128 {
8129 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8130 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8131 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8132 }
8133
8134 static void
8135 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8136 const dof_provider_t *dofprov, char *strtab)
8137 {
8138 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8139 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8140 dofprov->dofpv_provattr);
8141 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8142 dofprov->dofpv_modattr);
8143 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8144 dofprov->dofpv_funcattr);
8145 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8146 dofprov->dofpv_nameattr);
8147 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8148 dofprov->dofpv_argsattr);
8149 }
8150
8151 static void
8152 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8153 {
8154 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8155 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8156 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8157 dof_provider_t *provider;
8158 dof_probe_t *probe;
8159 uint32_t *off, *enoff;
8160 uint8_t *arg;
8161 char *strtab;
8162 uint_t i, nprobes;
8163 dtrace_helper_provdesc_t dhpv;
8164 dtrace_helper_probedesc_t dhpb;
8165 dtrace_meta_t *meta = dtrace_meta_pid;
8166 dtrace_mops_t *mops = &meta->dtm_mops;
8167 void *parg;
8168
8169 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8170 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8171 provider->dofpv_strtab * dof->dofh_secsize);
8172 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8173 provider->dofpv_probes * dof->dofh_secsize);
8174 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8175 provider->dofpv_prargs * dof->dofh_secsize);
8176 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8177 provider->dofpv_proffs * dof->dofh_secsize);
8178
8179 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8180 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8181 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8182 enoff = NULL;
8183
8184 /*
8185 * See dtrace_helper_provider_validate().
8186 */
8187 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8188 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8189 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8190 provider->dofpv_prenoffs * dof->dofh_secsize);
8191 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8192 }
8193
8194 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8195
8196 /*
8197 * Create the provider.
8198 */
8199 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8200
8201 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8202 return;
8203
8204 meta->dtm_count++;
8205
8206 /*
8207 * Create the probes.
8208 */
8209 for (i = 0; i < nprobes; i++) {
8210 probe = (dof_probe_t *)(uintptr_t)(daddr +
8211 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8212
8213 dhpb.dthpb_mod = dhp->dofhp_mod;
8214 dhpb.dthpb_func = strtab + probe->dofpr_func;
8215 dhpb.dthpb_name = strtab + probe->dofpr_name;
8216 #if !defined(__APPLE__)
8217 dhpb.dthpb_base = probe->dofpr_addr;
8218 #else
8219 dhpb.dthpb_base = dhp->dofhp_addr; /* FIXME: James, why? */
8220 #endif
8221 dhpb.dthpb_offs = (int32_t *)(off + probe->dofpr_offidx);
8222 dhpb.dthpb_noffs = probe->dofpr_noffs;
8223 if (enoff != NULL) {
8224 dhpb.dthpb_enoffs = (int32_t *)(enoff + probe->dofpr_enoffidx);
8225 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8226 } else {
8227 dhpb.dthpb_enoffs = NULL;
8228 dhpb.dthpb_nenoffs = 0;
8229 }
8230 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8231 dhpb.dthpb_nargc = probe->dofpr_nargc;
8232 dhpb.dthpb_xargc = probe->dofpr_xargc;
8233 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8234 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8235
8236 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8237 }
8238 }
8239
8240 static void
8241 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8242 {
8243 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8244 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8245 uint32_t i;
8246
8247 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8248
8249 for (i = 0; i < dof->dofh_secnum; i++) {
8250 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8251 dof->dofh_secoff + i * dof->dofh_secsize);
8252
8253 if (sec->dofs_type != DOF_SECT_PROVIDER)
8254 continue;
8255
8256 dtrace_helper_provide_one(dhp, sec, pid);
8257 }
8258
8259 /*
8260 * We may have just created probes, so we must now rematch against
8261 * any retained enablings. Note that this call will acquire both
8262 * cpu_lock and dtrace_lock; the fact that we are holding
8263 * dtrace_meta_lock now is what defines the ordering with respect to
8264 * these three locks.
8265 */
8266 dtrace_enabling_matchall();
8267 }
8268
8269 static void
8270 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8271 {
8272 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8273 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8274 dof_sec_t *str_sec;
8275 dof_provider_t *provider;
8276 char *strtab;
8277 dtrace_helper_provdesc_t dhpv;
8278 dtrace_meta_t *meta = dtrace_meta_pid;
8279 dtrace_mops_t *mops = &meta->dtm_mops;
8280
8281 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8282 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8283 provider->dofpv_strtab * dof->dofh_secsize);
8284
8285 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8286
8287 /*
8288 * Create the provider.
8289 */
8290 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8291
8292 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8293
8294 meta->dtm_count--;
8295 }
8296
8297 static void
8298 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8299 {
8300 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8301 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8302 uint32_t i;
8303
8304 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8305
8306 for (i = 0; i < dof->dofh_secnum; i++) {
8307 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8308 dof->dofh_secoff + i * dof->dofh_secsize);
8309
8310 if (sec->dofs_type != DOF_SECT_PROVIDER)
8311 continue;
8312
8313 dtrace_helper_provider_remove_one(dhp, sec, pid);
8314 }
8315 }
8316
8317 /*
8318 * DTrace Meta Provider-to-Framework API Functions
8319 *
8320 * These functions implement the Meta Provider-to-Framework API, as described
8321 * in <sys/dtrace.h>.
8322 */
8323 int
8324 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8325 dtrace_meta_provider_id_t *idp)
8326 {
8327 dtrace_meta_t *meta;
8328 dtrace_helpers_t *help, *next;
8329 uint_t i;
8330
8331 *idp = DTRACE_METAPROVNONE;
8332
8333 /*
8334 * We strictly don't need the name, but we hold onto it for
8335 * debuggability. All hail error queues!
8336 */
8337 if (name == NULL) {
8338 cmn_err(CE_WARN, "failed to register meta-provider: "
8339 "invalid name");
8340 return (EINVAL);
8341 }
8342
8343 if (mops == NULL ||
8344 mops->dtms_create_probe == NULL ||
8345 mops->dtms_provide_pid == NULL ||
8346 mops->dtms_remove_pid == NULL) {
8347 cmn_err(CE_WARN, "failed to register meta-register %s: "
8348 "invalid ops", name);
8349 return (EINVAL);
8350 }
8351
8352 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8353 meta->dtm_mops = *mops;
8354
8355 /* APPLE NOTE: Darwin employs size bounded string operation. */
8356 {
8357 size_t bufsize = strlen(name) + 1;
8358 meta->dtm_name = kmem_alloc(bufsize, KM_SLEEP);
8359 (void) strlcpy(meta->dtm_name, name, bufsize);
8360 }
8361
8362 meta->dtm_arg = arg;
8363
8364 lck_mtx_lock(&dtrace_meta_lock);
8365 lck_mtx_lock(&dtrace_lock);
8366
8367 if (dtrace_meta_pid != NULL) {
8368 lck_mtx_unlock(&dtrace_lock);
8369 lck_mtx_unlock(&dtrace_meta_lock);
8370 cmn_err(CE_WARN, "failed to register meta-register %s: "
8371 "user-land meta-provider exists", name);
8372 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8373 kmem_free(meta, sizeof (dtrace_meta_t));
8374 return (EINVAL);
8375 }
8376
8377 dtrace_meta_pid = meta;
8378 *idp = (dtrace_meta_provider_id_t)meta;
8379
8380 /*
8381 * If there are providers and probes ready to go, pass them
8382 * off to the new meta provider now.
8383 */
8384
8385 help = dtrace_deferred_pid;
8386 dtrace_deferred_pid = NULL;
8387
8388 lck_mtx_unlock(&dtrace_lock);
8389
8390 while (help != NULL) {
8391 for (i = 0; i < help->dthps_nprovs; i++) {
8392 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8393 help->dthps_pid);
8394 }
8395
8396 next = help->dthps_next;
8397 help->dthps_next = NULL;
8398 help->dthps_prev = NULL;
8399 help->dthps_deferred = 0;
8400 help = next;
8401 }
8402
8403 lck_mtx_unlock(&dtrace_meta_lock);
8404
8405 return (0);
8406 }
8407
8408 int
8409 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8410 {
8411 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8412
8413 lck_mtx_lock(&dtrace_meta_lock);
8414 lck_mtx_lock(&dtrace_lock);
8415
8416 if (old == dtrace_meta_pid) {
8417 pp = &dtrace_meta_pid;
8418 } else {
8419 panic("attempt to unregister non-existent "
8420 "dtrace meta-provider %p\n", (void *)old);
8421 }
8422
8423 if (old->dtm_count != 0) {
8424 lck_mtx_unlock(&dtrace_lock);
8425 lck_mtx_unlock(&dtrace_meta_lock);
8426 return (EBUSY);
8427 }
8428
8429 *pp = NULL;
8430
8431 lck_mtx_unlock(&dtrace_lock);
8432 lck_mtx_unlock(&dtrace_meta_lock);
8433
8434 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8435 kmem_free(old, sizeof (dtrace_meta_t));
8436
8437 return (0);
8438 }
8439
8440
8441 /*
8442 * DTrace DIF Object Functions
8443 */
8444 static int
8445 dtrace_difo_err(uint_t pc, const char *format, ...)
8446 {
8447 if (dtrace_err_verbose) {
8448 va_list alist;
8449
8450 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8451 va_start(alist, format);
8452 (void) vuprintf(format, alist);
8453 va_end(alist);
8454 }
8455
8456 #ifdef DTRACE_ERRDEBUG
8457 dtrace_errdebug(format);
8458 #endif
8459 return (1);
8460 }
8461
8462 /*
8463 * Validate a DTrace DIF object by checking the IR instructions. The following
8464 * rules are currently enforced by dtrace_difo_validate():
8465 *
8466 * 1. Each instruction must have a valid opcode
8467 * 2. Each register, string, variable, or subroutine reference must be valid
8468 * 3. No instruction can modify register %r0 (must be zero)
8469 * 4. All instruction reserved bits must be set to zero
8470 * 5. The last instruction must be a "ret" instruction
8471 * 6. All branch targets must reference a valid instruction _after_ the branch
8472 */
8473 static int
8474 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8475 cred_t *cr)
8476 {
8477 int err = 0;
8478 uint_t i;
8479
8480 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8481 int kcheckload;
8482 uint_t pc;
8483
8484 kcheckload = cr == NULL ||
8485 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8486
8487 dp->dtdo_destructive = 0;
8488
8489 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8490 dif_instr_t instr = dp->dtdo_buf[pc];
8491
8492 uint_t r1 = DIF_INSTR_R1(instr);
8493 uint_t r2 = DIF_INSTR_R2(instr);
8494 uint_t rd = DIF_INSTR_RD(instr);
8495 uint_t rs = DIF_INSTR_RS(instr);
8496 uint_t label = DIF_INSTR_LABEL(instr);
8497 uint_t v = DIF_INSTR_VAR(instr);
8498 uint_t subr = DIF_INSTR_SUBR(instr);
8499 uint_t type = DIF_INSTR_TYPE(instr);
8500 uint_t op = DIF_INSTR_OP(instr);
8501
8502 switch (op) {
8503 case DIF_OP_OR:
8504 case DIF_OP_XOR:
8505 case DIF_OP_AND:
8506 case DIF_OP_SLL:
8507 case DIF_OP_SRL:
8508 case DIF_OP_SRA:
8509 case DIF_OP_SUB:
8510 case DIF_OP_ADD:
8511 case DIF_OP_MUL:
8512 case DIF_OP_SDIV:
8513 case DIF_OP_UDIV:
8514 case DIF_OP_SREM:
8515 case DIF_OP_UREM:
8516 case DIF_OP_COPYS:
8517 if (r1 >= nregs)
8518 err += efunc(pc, "invalid register %u\n", r1);
8519 if (r2 >= nregs)
8520 err += efunc(pc, "invalid register %u\n", r2);
8521 if (rd >= nregs)
8522 err += efunc(pc, "invalid register %u\n", rd);
8523 if (rd == 0)
8524 err += efunc(pc, "cannot write to %r0\n");
8525 break;
8526 case DIF_OP_NOT:
8527 case DIF_OP_MOV:
8528 case DIF_OP_ALLOCS:
8529 if (r1 >= nregs)
8530 err += efunc(pc, "invalid register %u\n", r1);
8531 if (r2 != 0)
8532 err += efunc(pc, "non-zero reserved bits\n");
8533 if (rd >= nregs)
8534 err += efunc(pc, "invalid register %u\n", rd);
8535 if (rd == 0)
8536 err += efunc(pc, "cannot write to %r0\n");
8537 break;
8538 case DIF_OP_LDSB:
8539 case DIF_OP_LDSH:
8540 case DIF_OP_LDSW:
8541 case DIF_OP_LDUB:
8542 case DIF_OP_LDUH:
8543 case DIF_OP_LDUW:
8544 case DIF_OP_LDX:
8545 if (r1 >= nregs)
8546 err += efunc(pc, "invalid register %u\n", r1);
8547 if (r2 != 0)
8548 err += efunc(pc, "non-zero reserved bits\n");
8549 if (rd >= nregs)
8550 err += efunc(pc, "invalid register %u\n", rd);
8551 if (rd == 0)
8552 err += efunc(pc, "cannot write to %r0\n");
8553 if (kcheckload)
8554 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8555 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8556 break;
8557 case DIF_OP_RLDSB:
8558 case DIF_OP_RLDSH:
8559 case DIF_OP_RLDSW:
8560 case DIF_OP_RLDUB:
8561 case DIF_OP_RLDUH:
8562 case DIF_OP_RLDUW:
8563 case DIF_OP_RLDX:
8564 if (r1 >= nregs)
8565 err += efunc(pc, "invalid register %u\n", r1);
8566 if (r2 != 0)
8567 err += efunc(pc, "non-zero reserved bits\n");
8568 if (rd >= nregs)
8569 err += efunc(pc, "invalid register %u\n", rd);
8570 if (rd == 0)
8571 err += efunc(pc, "cannot write to %r0\n");
8572 break;
8573 case DIF_OP_ULDSB:
8574 case DIF_OP_ULDSH:
8575 case DIF_OP_ULDSW:
8576 case DIF_OP_ULDUB:
8577 case DIF_OP_ULDUH:
8578 case DIF_OP_ULDUW:
8579 case DIF_OP_ULDX:
8580 if (r1 >= nregs)
8581 err += efunc(pc, "invalid register %u\n", r1);
8582 if (r2 != 0)
8583 err += efunc(pc, "non-zero reserved bits\n");
8584 if (rd >= nregs)
8585 err += efunc(pc, "invalid register %u\n", rd);
8586 if (rd == 0)
8587 err += efunc(pc, "cannot write to %r0\n");
8588 break;
8589 case DIF_OP_STB:
8590 case DIF_OP_STH:
8591 case DIF_OP_STW:
8592 case DIF_OP_STX:
8593 if (r1 >= nregs)
8594 err += efunc(pc, "invalid register %u\n", r1);
8595 if (r2 != 0)
8596 err += efunc(pc, "non-zero reserved bits\n");
8597 if (rd >= nregs)
8598 err += efunc(pc, "invalid register %u\n", rd);
8599 if (rd == 0)
8600 err += efunc(pc, "cannot write to 0 address\n");
8601 break;
8602 case DIF_OP_CMP:
8603 case DIF_OP_SCMP:
8604 if (r1 >= nregs)
8605 err += efunc(pc, "invalid register %u\n", r1);
8606 if (r2 >= nregs)
8607 err += efunc(pc, "invalid register %u\n", r2);
8608 if (rd != 0)
8609 err += efunc(pc, "non-zero reserved bits\n");
8610 break;
8611 case DIF_OP_TST:
8612 if (r1 >= nregs)
8613 err += efunc(pc, "invalid register %u\n", r1);
8614 if (r2 != 0 || rd != 0)
8615 err += efunc(pc, "non-zero reserved bits\n");
8616 break;
8617 case DIF_OP_BA:
8618 case DIF_OP_BE:
8619 case DIF_OP_BNE:
8620 case DIF_OP_BG:
8621 case DIF_OP_BGU:
8622 case DIF_OP_BGE:
8623 case DIF_OP_BGEU:
8624 case DIF_OP_BL:
8625 case DIF_OP_BLU:
8626 case DIF_OP_BLE:
8627 case DIF_OP_BLEU:
8628 if (label >= dp->dtdo_len) {
8629 err += efunc(pc, "invalid branch target %u\n",
8630 label);
8631 }
8632 if (label <= pc) {
8633 err += efunc(pc, "backward branch to %u\n",
8634 label);
8635 }
8636 break;
8637 case DIF_OP_RET:
8638 if (r1 != 0 || r2 != 0)
8639 err += efunc(pc, "non-zero reserved bits\n");
8640 if (rd >= nregs)
8641 err += efunc(pc, "invalid register %u\n", rd);
8642 break;
8643 case DIF_OP_NOP:
8644 case DIF_OP_POPTS:
8645 case DIF_OP_FLUSHTS:
8646 if (r1 != 0 || r2 != 0 || rd != 0)
8647 err += efunc(pc, "non-zero reserved bits\n");
8648 break;
8649 case DIF_OP_SETX:
8650 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8651 err += efunc(pc, "invalid integer ref %u\n",
8652 DIF_INSTR_INTEGER(instr));
8653 }
8654 if (rd >= nregs)
8655 err += efunc(pc, "invalid register %u\n", rd);
8656 if (rd == 0)
8657 err += efunc(pc, "cannot write to %r0\n");
8658 break;
8659 case DIF_OP_SETS:
8660 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8661 err += efunc(pc, "invalid string ref %u\n",
8662 DIF_INSTR_STRING(instr));
8663 }
8664 if (rd >= nregs)
8665 err += efunc(pc, "invalid register %u\n", rd);
8666 if (rd == 0)
8667 err += efunc(pc, "cannot write to %r0\n");
8668 break;
8669 case DIF_OP_LDGA:
8670 case DIF_OP_LDTA:
8671 if (r1 > DIF_VAR_ARRAY_MAX)
8672 err += efunc(pc, "invalid array %u\n", r1);
8673 if (r2 >= nregs)
8674 err += efunc(pc, "invalid register %u\n", r2);
8675 if (rd >= nregs)
8676 err += efunc(pc, "invalid register %u\n", rd);
8677 if (rd == 0)
8678 err += efunc(pc, "cannot write to %r0\n");
8679 break;
8680 case DIF_OP_LDGS:
8681 case DIF_OP_LDTS:
8682 case DIF_OP_LDLS:
8683 case DIF_OP_LDGAA:
8684 case DIF_OP_LDTAA:
8685 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8686 err += efunc(pc, "invalid variable %u\n", v);
8687 if (rd >= nregs)
8688 err += efunc(pc, "invalid register %u\n", rd);
8689 if (rd == 0)
8690 err += efunc(pc, "cannot write to %r0\n");
8691 break;
8692 case DIF_OP_STGS:
8693 case DIF_OP_STTS:
8694 case DIF_OP_STLS:
8695 case DIF_OP_STGAA:
8696 case DIF_OP_STTAA:
8697 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8698 err += efunc(pc, "invalid variable %u\n", v);
8699 if (rs >= nregs)
8700 err += efunc(pc, "invalid register %u\n", rd);
8701 break;
8702 case DIF_OP_CALL:
8703 if (subr > DIF_SUBR_MAX)
8704 err += efunc(pc, "invalid subr %u\n", subr);
8705 if (rd >= nregs)
8706 err += efunc(pc, "invalid register %u\n", rd);
8707 if (rd == 0)
8708 err += efunc(pc, "cannot write to %r0\n");
8709
8710 if (subr == DIF_SUBR_COPYOUT ||
8711 subr == DIF_SUBR_COPYOUTSTR) {
8712 dp->dtdo_destructive = 1;
8713 }
8714 break;
8715 case DIF_OP_PUSHTR:
8716 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8717 err += efunc(pc, "invalid ref type %u\n", type);
8718 if (r2 >= nregs)
8719 err += efunc(pc, "invalid register %u\n", r2);
8720 if (rs >= nregs)
8721 err += efunc(pc, "invalid register %u\n", rs);
8722 break;
8723 case DIF_OP_PUSHTV:
8724 if (type != DIF_TYPE_CTF)
8725 err += efunc(pc, "invalid val type %u\n", type);
8726 if (r2 >= nregs)
8727 err += efunc(pc, "invalid register %u\n", r2);
8728 if (rs >= nregs)
8729 err += efunc(pc, "invalid register %u\n", rs);
8730 break;
8731 default:
8732 err += efunc(pc, "invalid opcode %u\n",
8733 DIF_INSTR_OP(instr));
8734 }
8735 }
8736
8737 if (dp->dtdo_len != 0 &&
8738 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8739 err += efunc(dp->dtdo_len - 1,
8740 "expected 'ret' as last DIF instruction\n");
8741 }
8742
8743 if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
8744 /*
8745 * If we're not returning by reference, the size must be either
8746 * 0 or the size of one of the base types.
8747 */
8748 switch (dp->dtdo_rtype.dtdt_size) {
8749 case 0:
8750 case sizeof (uint8_t):
8751 case sizeof (uint16_t):
8752 case sizeof (uint32_t):
8753 case sizeof (uint64_t):
8754 break;
8755
8756 default:
8757 err += efunc(dp->dtdo_len - 1, "bad return size\n");
8758 }
8759 }
8760
8761 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8762 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8763 dtrace_diftype_t *vt, *et;
8764 uint_t id;
8765 int ndx;
8766
8767 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8768 v->dtdv_scope != DIFV_SCOPE_THREAD &&
8769 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8770 err += efunc(i, "unrecognized variable scope %d\n",
8771 v->dtdv_scope);
8772 break;
8773 }
8774
8775 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8776 v->dtdv_kind != DIFV_KIND_SCALAR) {
8777 err += efunc(i, "unrecognized variable type %d\n",
8778 v->dtdv_kind);
8779 break;
8780 }
8781
8782 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8783 err += efunc(i, "%d exceeds variable id limit\n", id);
8784 break;
8785 }
8786
8787 if (id < DIF_VAR_OTHER_UBASE)
8788 continue;
8789
8790 /*
8791 * For user-defined variables, we need to check that this
8792 * definition is identical to any previous definition that we
8793 * encountered.
8794 */
8795 ndx = id - DIF_VAR_OTHER_UBASE;
8796
8797 switch (v->dtdv_scope) {
8798 case DIFV_SCOPE_GLOBAL:
8799 if (ndx < vstate->dtvs_nglobals) {
8800 dtrace_statvar_t *svar;
8801
8802 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8803 existing = &svar->dtsv_var;
8804 }
8805
8806 break;
8807
8808 case DIFV_SCOPE_THREAD:
8809 if (ndx < vstate->dtvs_ntlocals)
8810 existing = &vstate->dtvs_tlocals[ndx];
8811 break;
8812
8813 case DIFV_SCOPE_LOCAL:
8814 if (ndx < vstate->dtvs_nlocals) {
8815 dtrace_statvar_t *svar;
8816
8817 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8818 existing = &svar->dtsv_var;
8819 }
8820
8821 break;
8822 }
8823
8824 vt = &v->dtdv_type;
8825
8826 if (vt->dtdt_flags & DIF_TF_BYREF) {
8827 if (vt->dtdt_size == 0) {
8828 err += efunc(i, "zero-sized variable\n");
8829 break;
8830 }
8831
8832 if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
8833 v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
8834 vt->dtdt_size > dtrace_statvar_maxsize) {
8835 err += efunc(i, "oversized by-ref static\n");
8836 break;
8837 }
8838 }
8839
8840 if (existing == NULL || existing->dtdv_id == 0)
8841 continue;
8842
8843 ASSERT(existing->dtdv_id == v->dtdv_id);
8844 ASSERT(existing->dtdv_scope == v->dtdv_scope);
8845
8846 if (existing->dtdv_kind != v->dtdv_kind)
8847 err += efunc(i, "%d changed variable kind\n", id);
8848
8849 et = &existing->dtdv_type;
8850
8851 if (vt->dtdt_flags != et->dtdt_flags) {
8852 err += efunc(i, "%d changed variable type flags\n", id);
8853 break;
8854 }
8855
8856 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8857 err += efunc(i, "%d changed variable type size\n", id);
8858 break;
8859 }
8860 }
8861
8862 return (err);
8863 }
8864
8865 /*
8866 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
8867 * are much more constrained than normal DIFOs. Specifically, they may
8868 * not:
8869 *
8870 * 1. Make calls to subroutines other than copyin(), copyinstr() or
8871 * miscellaneous string routines
8872 * 2. Access DTrace variables other than the args[] array, and the
8873 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8874 * 3. Have thread-local variables.
8875 * 4. Have dynamic variables.
8876 */
8877 static int
8878 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8879 {
8880 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8881 int err = 0;
8882 uint_t pc;
8883
8884 for (pc = 0; pc < dp->dtdo_len; pc++) {
8885 dif_instr_t instr = dp->dtdo_buf[pc];
8886
8887 uint_t v = DIF_INSTR_VAR(instr);
8888 uint_t subr = DIF_INSTR_SUBR(instr);
8889 uint_t op = DIF_INSTR_OP(instr);
8890
8891 switch (op) {
8892 case DIF_OP_OR:
8893 case DIF_OP_XOR:
8894 case DIF_OP_AND:
8895 case DIF_OP_SLL:
8896 case DIF_OP_SRL:
8897 case DIF_OP_SRA:
8898 case DIF_OP_SUB:
8899 case DIF_OP_ADD:
8900 case DIF_OP_MUL:
8901 case DIF_OP_SDIV:
8902 case DIF_OP_UDIV:
8903 case DIF_OP_SREM:
8904 case DIF_OP_UREM:
8905 case DIF_OP_COPYS:
8906 case DIF_OP_NOT:
8907 case DIF_OP_MOV:
8908 case DIF_OP_RLDSB:
8909 case DIF_OP_RLDSH:
8910 case DIF_OP_RLDSW:
8911 case DIF_OP_RLDUB:
8912 case DIF_OP_RLDUH:
8913 case DIF_OP_RLDUW:
8914 case DIF_OP_RLDX:
8915 case DIF_OP_ULDSB:
8916 case DIF_OP_ULDSH:
8917 case DIF_OP_ULDSW:
8918 case DIF_OP_ULDUB:
8919 case DIF_OP_ULDUH:
8920 case DIF_OP_ULDUW:
8921 case DIF_OP_ULDX:
8922 case DIF_OP_STB:
8923 case DIF_OP_STH:
8924 case DIF_OP_STW:
8925 case DIF_OP_STX:
8926 case DIF_OP_ALLOCS:
8927 case DIF_OP_CMP:
8928 case DIF_OP_SCMP:
8929 case DIF_OP_TST:
8930 case DIF_OP_BA:
8931 case DIF_OP_BE:
8932 case DIF_OP_BNE:
8933 case DIF_OP_BG:
8934 case DIF_OP_BGU:
8935 case DIF_OP_BGE:
8936 case DIF_OP_BGEU:
8937 case DIF_OP_BL:
8938 case DIF_OP_BLU:
8939 case DIF_OP_BLE:
8940 case DIF_OP_BLEU:
8941 case DIF_OP_RET:
8942 case DIF_OP_NOP:
8943 case DIF_OP_POPTS:
8944 case DIF_OP_FLUSHTS:
8945 case DIF_OP_SETX:
8946 case DIF_OP_SETS:
8947 case DIF_OP_LDGA:
8948 case DIF_OP_LDLS:
8949 case DIF_OP_STGS:
8950 case DIF_OP_STLS:
8951 case DIF_OP_PUSHTR:
8952 case DIF_OP_PUSHTV:
8953 break;
8954
8955 case DIF_OP_LDGS:
8956 if (v >= DIF_VAR_OTHER_UBASE)
8957 break;
8958
8959 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8960 break;
8961
8962 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8963 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8964 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8965 v == DIF_VAR_UID || v == DIF_VAR_GID)
8966 break;
8967
8968 err += efunc(pc, "illegal variable %u\n", v);
8969 break;
8970
8971 case DIF_OP_LDTA:
8972 case DIF_OP_LDTS:
8973 case DIF_OP_LDGAA:
8974 case DIF_OP_LDTAA:
8975 err += efunc(pc, "illegal dynamic variable load\n");
8976 break;
8977
8978 case DIF_OP_STTS:
8979 case DIF_OP_STGAA:
8980 case DIF_OP_STTAA:
8981 err += efunc(pc, "illegal dynamic variable store\n");
8982 break;
8983
8984 case DIF_OP_CALL:
8985 if (subr == DIF_SUBR_ALLOCA ||
8986 subr == DIF_SUBR_BCOPY ||
8987 subr == DIF_SUBR_COPYIN ||
8988 subr == DIF_SUBR_COPYINTO ||
8989 subr == DIF_SUBR_COPYINSTR ||
8990 subr == DIF_SUBR_INDEX ||
8991 subr == DIF_SUBR_INET_NTOA ||
8992 subr == DIF_SUBR_INET_NTOA6 ||
8993 subr == DIF_SUBR_INET_NTOP ||
8994 subr == DIF_SUBR_LLTOSTR ||
8995 subr == DIF_SUBR_RINDEX ||
8996 subr == DIF_SUBR_STRCHR ||
8997 subr == DIF_SUBR_STRJOIN ||
8998 subr == DIF_SUBR_STRRCHR ||
8999 subr == DIF_SUBR_STRSTR ||
9000 subr == DIF_SUBR_COREPROFILE ||
9001 subr == DIF_SUBR_HTONS ||
9002 subr == DIF_SUBR_HTONL ||
9003 subr == DIF_SUBR_HTONLL ||
9004 subr == DIF_SUBR_NTOHS ||
9005 subr == DIF_SUBR_NTOHL ||
9006 subr == DIF_SUBR_NTOHLL)
9007 break;
9008
9009 err += efunc(pc, "invalid subr %u\n", subr);
9010 break;
9011
9012 default:
9013 err += efunc(pc, "invalid opcode %u\n",
9014 DIF_INSTR_OP(instr));
9015 }
9016 }
9017
9018 return (err);
9019 }
9020
9021 /*
9022 * Returns 1 if the expression in the DIF object can be cached on a per-thread
9023 * basis; 0 if not.
9024 */
9025 static int
9026 dtrace_difo_cacheable(dtrace_difo_t *dp)
9027 {
9028 uint_t i;
9029
9030 if (dp == NULL)
9031 return (0);
9032
9033 for (i = 0; i < dp->dtdo_varlen; i++) {
9034 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9035
9036 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9037 continue;
9038
9039 switch (v->dtdv_id) {
9040 case DIF_VAR_CURTHREAD:
9041 case DIF_VAR_PID:
9042 case DIF_VAR_TID:
9043 case DIF_VAR_EXECNAME:
9044 case DIF_VAR_ZONENAME:
9045 break;
9046
9047 default:
9048 return (0);
9049 }
9050 }
9051
9052 /*
9053 * This DIF object may be cacheable. Now we need to look for any
9054 * array loading instructions, any memory loading instructions, or
9055 * any stores to thread-local variables.
9056 */
9057 for (i = 0; i < dp->dtdo_len; i++) {
9058 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9059
9060 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9061 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9062 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9063 op == DIF_OP_LDGA || op == DIF_OP_STTS)
9064 return (0);
9065 }
9066
9067 return (1);
9068 }
9069
9070 static void
9071 dtrace_difo_hold(dtrace_difo_t *dp)
9072 {
9073 uint_t i;
9074
9075 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9076
9077 dp->dtdo_refcnt++;
9078 ASSERT(dp->dtdo_refcnt != 0);
9079
9080 /*
9081 * We need to check this DIF object for references to the variable
9082 * DIF_VAR_VTIMESTAMP.
9083 */
9084 for (i = 0; i < dp->dtdo_varlen; i++) {
9085 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9086
9087 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9088 continue;
9089
9090 if (dtrace_vtime_references++ == 0)
9091 dtrace_vtime_enable();
9092 }
9093 }
9094
9095 /*
9096 * This routine calculates the dynamic variable chunksize for a given DIF
9097 * object. The calculation is not fool-proof, and can probably be tricked by
9098 * malicious DIF -- but it works for all compiler-generated DIF. Because this
9099 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9100 * if a dynamic variable size exceeds the chunksize.
9101 */
9102 static void
9103 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9104 {
9105 uint64_t sval = 0;
9106 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9107 const dif_instr_t *text = dp->dtdo_buf;
9108 uint_t pc, srd = 0;
9109 uint_t ttop = 0;
9110 size_t size, ksize;
9111 uint_t id, i;
9112
9113 for (pc = 0; pc < dp->dtdo_len; pc++) {
9114 dif_instr_t instr = text[pc];
9115 uint_t op = DIF_INSTR_OP(instr);
9116 uint_t rd = DIF_INSTR_RD(instr);
9117 uint_t r1 = DIF_INSTR_R1(instr);
9118 uint_t nkeys = 0;
9119 uchar_t scope;
9120
9121 dtrace_key_t *key = tupregs;
9122
9123 switch (op) {
9124 case DIF_OP_SETX:
9125 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9126 srd = rd;
9127 continue;
9128
9129 case DIF_OP_STTS:
9130 key = &tupregs[DIF_DTR_NREGS];
9131 key[0].dttk_size = 0;
9132 key[1].dttk_size = 0;
9133 nkeys = 2;
9134 scope = DIFV_SCOPE_THREAD;
9135 break;
9136
9137 case DIF_OP_STGAA:
9138 case DIF_OP_STTAA:
9139 nkeys = ttop;
9140
9141 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9142 key[nkeys++].dttk_size = 0;
9143
9144 key[nkeys++].dttk_size = 0;
9145
9146 if (op == DIF_OP_STTAA) {
9147 scope = DIFV_SCOPE_THREAD;
9148 } else {
9149 scope = DIFV_SCOPE_GLOBAL;
9150 }
9151
9152 break;
9153
9154 case DIF_OP_PUSHTR:
9155 if (ttop == DIF_DTR_NREGS)
9156 return;
9157
9158 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9159 /*
9160 * If the register for the size of the "pushtr"
9161 * is %r0 (or the value is 0) and the type is
9162 * a string, we'll use the system-wide default
9163 * string size.
9164 */
9165 tupregs[ttop++].dttk_size =
9166 dtrace_strsize_default;
9167 } else {
9168 if (srd == 0)
9169 return;
9170
9171 if (sval > LONG_MAX)
9172 return;
9173
9174 tupregs[ttop++].dttk_size = sval;
9175 }
9176
9177 break;
9178
9179 case DIF_OP_PUSHTV:
9180 if (ttop == DIF_DTR_NREGS)
9181 return;
9182
9183 tupregs[ttop++].dttk_size = 0;
9184 break;
9185
9186 case DIF_OP_FLUSHTS:
9187 ttop = 0;
9188 break;
9189
9190 case DIF_OP_POPTS:
9191 if (ttop != 0)
9192 ttop--;
9193 break;
9194 }
9195
9196 sval = 0;
9197 srd = 0;
9198
9199 if (nkeys == 0)
9200 continue;
9201
9202 /*
9203 * We have a dynamic variable allocation; calculate its size.
9204 */
9205 for (ksize = 0, i = 0; i < nkeys; i++)
9206 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9207
9208 size = sizeof (dtrace_dynvar_t);
9209 size += sizeof (dtrace_key_t) * (nkeys - 1);
9210 size += ksize;
9211
9212 /*
9213 * Now we need to determine the size of the stored data.
9214 */
9215 id = DIF_INSTR_VAR(instr);
9216
9217 for (i = 0; i < dp->dtdo_varlen; i++) {
9218 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9219
9220 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9221 size += v->dtdv_type.dtdt_size;
9222 break;
9223 }
9224 }
9225
9226 if (i == dp->dtdo_varlen)
9227 return;
9228
9229 /*
9230 * We have the size. If this is larger than the chunk size
9231 * for our dynamic variable state, reset the chunk size.
9232 */
9233 size = P2ROUNDUP(size, sizeof (uint64_t));
9234
9235 /*
9236 * Before setting the chunk size, check that we're not going
9237 * to set it to a negative value...
9238 */
9239 if (size > LONG_MAX)
9240 return;
9241
9242 /*
9243 * ...and make certain that we didn't badly overflow.
9244 */
9245 if (size < ksize || size < sizeof (dtrace_dynvar_t))
9246 return;
9247
9248 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9249 vstate->dtvs_dynvars.dtds_chunksize = size;
9250 }
9251 }
9252
9253 static void
9254 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9255 {
9256 int oldsvars, osz, nsz, otlocals, ntlocals;
9257 uint_t i, id;
9258
9259 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9260 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9261
9262 for (i = 0; i < dp->dtdo_varlen; i++) {
9263 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9264 dtrace_statvar_t *svar;
9265 dtrace_statvar_t ***svarp = NULL;
9266 size_t dsize = 0;
9267 uint8_t scope = v->dtdv_scope;
9268 int *np = (int *)NULL;
9269
9270 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9271 continue;
9272
9273 id -= DIF_VAR_OTHER_UBASE;
9274
9275 switch (scope) {
9276 case DIFV_SCOPE_THREAD:
9277 while (id >= (uint_t)(otlocals = vstate->dtvs_ntlocals)) {
9278 dtrace_difv_t *tlocals;
9279
9280 if ((ntlocals = (otlocals << 1)) == 0)
9281 ntlocals = 1;
9282
9283 osz = otlocals * sizeof (dtrace_difv_t);
9284 nsz = ntlocals * sizeof (dtrace_difv_t);
9285
9286 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9287
9288 if (osz != 0) {
9289 bcopy(vstate->dtvs_tlocals,
9290 tlocals, osz);
9291 kmem_free(vstate->dtvs_tlocals, osz);
9292 }
9293
9294 vstate->dtvs_tlocals = tlocals;
9295 vstate->dtvs_ntlocals = ntlocals;
9296 }
9297
9298 vstate->dtvs_tlocals[id] = *v;
9299 continue;
9300
9301 case DIFV_SCOPE_LOCAL:
9302 np = &vstate->dtvs_nlocals;
9303 svarp = &vstate->dtvs_locals;
9304
9305 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9306 dsize = (int)NCPU * (v->dtdv_type.dtdt_size +
9307 sizeof (uint64_t));
9308 else
9309 dsize = (int)NCPU * sizeof (uint64_t);
9310
9311 break;
9312
9313 case DIFV_SCOPE_GLOBAL:
9314 np = &vstate->dtvs_nglobals;
9315 svarp = &vstate->dtvs_globals;
9316
9317 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9318 dsize = v->dtdv_type.dtdt_size +
9319 sizeof (uint64_t);
9320
9321 break;
9322
9323 default:
9324 ASSERT(0);
9325 }
9326
9327 while (id >= (uint_t)(oldsvars = *np)) {
9328 dtrace_statvar_t **statics;
9329 int newsvars, oldsize, newsize;
9330
9331 if ((newsvars = (oldsvars << 1)) == 0)
9332 newsvars = 1;
9333
9334 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9335 newsize = newsvars * sizeof (dtrace_statvar_t *);
9336
9337 statics = kmem_zalloc(newsize, KM_SLEEP);
9338
9339 if (oldsize != 0) {
9340 bcopy(*svarp, statics, oldsize);
9341 kmem_free(*svarp, oldsize);
9342 }
9343
9344 *svarp = statics;
9345 *np = newsvars;
9346 }
9347
9348 if ((svar = (*svarp)[id]) == NULL) {
9349 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9350 svar->dtsv_var = *v;
9351
9352 if ((svar->dtsv_size = dsize) != 0) {
9353 svar->dtsv_data = (uint64_t)(uintptr_t)
9354 kmem_zalloc(dsize, KM_SLEEP);
9355 }
9356
9357 (*svarp)[id] = svar;
9358 }
9359
9360 svar->dtsv_refcnt++;
9361 }
9362
9363 dtrace_difo_chunksize(dp, vstate);
9364 dtrace_difo_hold(dp);
9365 }
9366
9367 static dtrace_difo_t *
9368 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9369 {
9370 dtrace_difo_t *new;
9371 size_t sz;
9372
9373 ASSERT(dp->dtdo_buf != NULL);
9374 ASSERT(dp->dtdo_refcnt != 0);
9375
9376 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9377
9378 ASSERT(dp->dtdo_buf != NULL);
9379 sz = dp->dtdo_len * sizeof (dif_instr_t);
9380 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9381 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9382 new->dtdo_len = dp->dtdo_len;
9383
9384 if (dp->dtdo_strtab != NULL) {
9385 ASSERT(dp->dtdo_strlen != 0);
9386 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9387 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9388 new->dtdo_strlen = dp->dtdo_strlen;
9389 }
9390
9391 if (dp->dtdo_inttab != NULL) {
9392 ASSERT(dp->dtdo_intlen != 0);
9393 sz = dp->dtdo_intlen * sizeof (uint64_t);
9394 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9395 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9396 new->dtdo_intlen = dp->dtdo_intlen;
9397 }
9398
9399 if (dp->dtdo_vartab != NULL) {
9400 ASSERT(dp->dtdo_varlen != 0);
9401 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9402 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9403 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9404 new->dtdo_varlen = dp->dtdo_varlen;
9405 }
9406
9407 dtrace_difo_init(new, vstate);
9408 return (new);
9409 }
9410
9411 static void
9412 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9413 {
9414 uint_t i;
9415
9416 ASSERT(dp->dtdo_refcnt == 0);
9417
9418 for (i = 0; i < dp->dtdo_varlen; i++) {
9419 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9420 dtrace_statvar_t *svar;
9421 dtrace_statvar_t **svarp = NULL;
9422 uint_t id;
9423 uint8_t scope = v->dtdv_scope;
9424 int *np = NULL;
9425
9426 switch (scope) {
9427 case DIFV_SCOPE_THREAD:
9428 continue;
9429
9430 case DIFV_SCOPE_LOCAL:
9431 np = &vstate->dtvs_nlocals;
9432 svarp = vstate->dtvs_locals;
9433 break;
9434
9435 case DIFV_SCOPE_GLOBAL:
9436 np = &vstate->dtvs_nglobals;
9437 svarp = vstate->dtvs_globals;
9438 break;
9439
9440 default:
9441 ASSERT(0);
9442 }
9443
9444 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9445 continue;
9446
9447 id -= DIF_VAR_OTHER_UBASE;
9448
9449 ASSERT(id < (uint_t)*np);
9450
9451 svar = svarp[id];
9452 ASSERT(svar != NULL);
9453 ASSERT(svar->dtsv_refcnt > 0);
9454
9455 if (--svar->dtsv_refcnt > 0)
9456 continue;
9457
9458 if (svar->dtsv_size != 0) {
9459 ASSERT(svar->dtsv_data != 0);
9460 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9461 svar->dtsv_size);
9462 }
9463
9464 kmem_free(svar, sizeof (dtrace_statvar_t));
9465 svarp[id] = NULL;
9466 }
9467
9468 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9469 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9470 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9471 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9472
9473 kmem_free(dp, sizeof (dtrace_difo_t));
9474 }
9475
9476 static void
9477 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9478 {
9479 uint_t i;
9480
9481 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9482 ASSERT(dp->dtdo_refcnt != 0);
9483
9484 for (i = 0; i < dp->dtdo_varlen; i++) {
9485 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9486
9487 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9488 continue;
9489
9490 ASSERT(dtrace_vtime_references > 0);
9491 if (--dtrace_vtime_references == 0)
9492 dtrace_vtime_disable();
9493 }
9494
9495 if (--dp->dtdo_refcnt == 0)
9496 dtrace_difo_destroy(dp, vstate);
9497 }
9498
9499 /*
9500 * DTrace Format Functions
9501 */
9502 static uint16_t
9503 dtrace_format_add(dtrace_state_t *state, char *str)
9504 {
9505 char *fmt, **new;
9506 uint16_t ndx, len = strlen(str) + 1;
9507
9508 fmt = kmem_zalloc(len, KM_SLEEP);
9509 bcopy(str, fmt, len);
9510
9511 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9512 if (state->dts_formats[ndx] == NULL) {
9513 state->dts_formats[ndx] = fmt;
9514 return (ndx + 1);
9515 }
9516 }
9517
9518 if (state->dts_nformats == USHRT_MAX) {
9519 /*
9520 * This is only likely if a denial-of-service attack is being
9521 * attempted. As such, it's okay to fail silently here.
9522 */
9523 kmem_free(fmt, len);
9524 return (0);
9525 }
9526
9527 /*
9528 * For simplicity, we always resize the formats array to be exactly the
9529 * number of formats.
9530 */
9531 ndx = state->dts_nformats++;
9532 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9533
9534 if (state->dts_formats != NULL) {
9535 ASSERT(ndx != 0);
9536 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9537 kmem_free(state->dts_formats, ndx * sizeof (char *));
9538 }
9539
9540 state->dts_formats = new;
9541 state->dts_formats[ndx] = fmt;
9542
9543 return (ndx + 1);
9544 }
9545
9546 static void
9547 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9548 {
9549 char *fmt;
9550
9551 ASSERT(state->dts_formats != NULL);
9552 ASSERT(format <= state->dts_nformats);
9553 ASSERT(state->dts_formats[format - 1] != NULL);
9554
9555 fmt = state->dts_formats[format - 1];
9556 kmem_free(fmt, strlen(fmt) + 1);
9557 state->dts_formats[format - 1] = NULL;
9558 }
9559
9560 static void
9561 dtrace_format_destroy(dtrace_state_t *state)
9562 {
9563 int i;
9564
9565 if (state->dts_nformats == 0) {
9566 ASSERT(state->dts_formats == NULL);
9567 return;
9568 }
9569
9570 ASSERT(state->dts_formats != NULL);
9571
9572 for (i = 0; i < state->dts_nformats; i++) {
9573 char *fmt = state->dts_formats[i];
9574
9575 if (fmt == NULL)
9576 continue;
9577
9578 kmem_free(fmt, strlen(fmt) + 1);
9579 }
9580
9581 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9582 state->dts_nformats = 0;
9583 state->dts_formats = NULL;
9584 }
9585
9586 /*
9587 * DTrace Predicate Functions
9588 */
9589 static dtrace_predicate_t *
9590 dtrace_predicate_create(dtrace_difo_t *dp)
9591 {
9592 dtrace_predicate_t *pred;
9593
9594 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9595 ASSERT(dp->dtdo_refcnt != 0);
9596
9597 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9598 pred->dtp_difo = dp;
9599 pred->dtp_refcnt = 1;
9600
9601 if (!dtrace_difo_cacheable(dp))
9602 return (pred);
9603
9604 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9605 /*
9606 * This is only theoretically possible -- we have had 2^32
9607 * cacheable predicates on this machine. We cannot allow any
9608 * more predicates to become cacheable: as unlikely as it is,
9609 * there may be a thread caching a (now stale) predicate cache
9610 * ID. (N.B.: the temptation is being successfully resisted to
9611 * have this cmn_err() "Holy shit -- we executed this code!")
9612 */
9613 return (pred);
9614 }
9615
9616 pred->dtp_cacheid = dtrace_predcache_id++;
9617
9618 return (pred);
9619 }
9620
9621 static void
9622 dtrace_predicate_hold(dtrace_predicate_t *pred)
9623 {
9624 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9625 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9626 ASSERT(pred->dtp_refcnt > 0);
9627
9628 pred->dtp_refcnt++;
9629 }
9630
9631 static void
9632 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9633 {
9634 dtrace_difo_t *dp = pred->dtp_difo;
9635 #pragma unused(dp) /* __APPLE__ */
9636
9637 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9638 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9639 ASSERT(pred->dtp_refcnt > 0);
9640
9641 if (--pred->dtp_refcnt == 0) {
9642 dtrace_difo_release(pred->dtp_difo, vstate);
9643 kmem_free(pred, sizeof (dtrace_predicate_t));
9644 }
9645 }
9646
9647 /*
9648 * DTrace Action Description Functions
9649 */
9650 static dtrace_actdesc_t *
9651 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9652 uint64_t uarg, uint64_t arg)
9653 {
9654 dtrace_actdesc_t *act;
9655
9656 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
9657 arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
9658
9659 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9660 act->dtad_kind = kind;
9661 act->dtad_ntuple = ntuple;
9662 act->dtad_uarg = uarg;
9663 act->dtad_arg = arg;
9664 act->dtad_refcnt = 1;
9665
9666 return (act);
9667 }
9668
9669 static void
9670 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9671 {
9672 ASSERT(act->dtad_refcnt >= 1);
9673 act->dtad_refcnt++;
9674 }
9675
9676 static void
9677 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9678 {
9679 dtrace_actkind_t kind = act->dtad_kind;
9680 dtrace_difo_t *dp;
9681
9682 ASSERT(act->dtad_refcnt >= 1);
9683
9684 if (--act->dtad_refcnt != 0)
9685 return;
9686
9687 if ((dp = act->dtad_difo) != NULL)
9688 dtrace_difo_release(dp, vstate);
9689
9690 if (DTRACEACT_ISPRINTFLIKE(kind)) {
9691 char *str = (char *)(uintptr_t)act->dtad_arg;
9692
9693 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9694 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9695
9696 if (str != NULL)
9697 kmem_free(str, strlen(str) + 1);
9698 }
9699
9700 kmem_free(act, sizeof (dtrace_actdesc_t));
9701 }
9702
9703 /*
9704 * DTrace ECB Functions
9705 */
9706 static dtrace_ecb_t *
9707 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9708 {
9709 dtrace_ecb_t *ecb;
9710 dtrace_epid_t epid;
9711
9712 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9713
9714 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9715 ecb->dte_predicate = NULL;
9716 ecb->dte_probe = probe;
9717
9718 /*
9719 * The default size is the size of the default action: recording
9720 * the header.
9721 */
9722 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9723 ecb->dte_alignment = sizeof (dtrace_epid_t);
9724
9725 epid = state->dts_epid++;
9726
9727 if (epid - 1 >= (dtrace_epid_t)state->dts_necbs) {
9728 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9729 int necbs = state->dts_necbs << 1;
9730
9731 ASSERT(epid == (dtrace_epid_t)state->dts_necbs + 1);
9732
9733 if (necbs == 0) {
9734 ASSERT(oecbs == NULL);
9735 necbs = 1;
9736 }
9737
9738 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9739
9740 if (oecbs != NULL)
9741 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9742
9743 dtrace_membar_producer();
9744 state->dts_ecbs = ecbs;
9745
9746 if (oecbs != NULL) {
9747 /*
9748 * If this state is active, we must dtrace_sync()
9749 * before we can free the old dts_ecbs array: we're
9750 * coming in hot, and there may be active ring
9751 * buffer processing (which indexes into the dts_ecbs
9752 * array) on another CPU.
9753 */
9754 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9755 dtrace_sync();
9756
9757 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9758 }
9759
9760 dtrace_membar_producer();
9761 state->dts_necbs = necbs;
9762 }
9763
9764 ecb->dte_state = state;
9765
9766 ASSERT(state->dts_ecbs[epid - 1] == NULL);
9767 dtrace_membar_producer();
9768 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9769
9770 return (ecb);
9771 }
9772
9773 static int
9774 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9775 {
9776 dtrace_probe_t *probe = ecb->dte_probe;
9777
9778 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
9779 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9780 ASSERT(ecb->dte_next == NULL);
9781
9782 if (probe == NULL) {
9783 /*
9784 * This is the NULL probe -- there's nothing to do.
9785 */
9786 return(0);
9787 }
9788
9789 probe->dtpr_provider->dtpv_ecb_count++;
9790 if (probe->dtpr_ecb == NULL) {
9791 dtrace_provider_t *prov = probe->dtpr_provider;
9792
9793 /*
9794 * We're the first ECB on this probe.
9795 */
9796 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9797
9798 if (ecb->dte_predicate != NULL)
9799 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9800
9801 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9802 probe->dtpr_id, probe->dtpr_arg));
9803 } else {
9804 /*
9805 * This probe is already active. Swing the last pointer to
9806 * point to the new ECB, and issue a dtrace_sync() to assure
9807 * that all CPUs have seen the change.
9808 */
9809 ASSERT(probe->dtpr_ecb_last != NULL);
9810 probe->dtpr_ecb_last->dte_next = ecb;
9811 probe->dtpr_ecb_last = ecb;
9812 probe->dtpr_predcache = 0;
9813
9814 dtrace_sync();
9815 return(0);
9816 }
9817 }
9818
9819 static void
9820 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9821 {
9822 dtrace_action_t *act;
9823 uint32_t curneeded = UINT32_MAX;
9824 uint32_t aggbase = UINT32_MAX;
9825
9826 /*
9827 * If we record anything, we always record the dtrace_rechdr_t. (And
9828 * we always record it first.)
9829 */
9830 ecb->dte_size = sizeof (dtrace_rechdr_t);
9831 ecb->dte_alignment = sizeof (dtrace_epid_t);
9832
9833 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9834 dtrace_recdesc_t *rec = &act->dta_rec;
9835 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
9836
9837 ecb->dte_alignment = MAX(ecb->dte_alignment, rec->dtrd_alignment);
9838
9839 if (DTRACEACT_ISAGG(act->dta_kind)) {
9840 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9841
9842 ASSERT(rec->dtrd_size != 0);
9843 ASSERT(agg->dtag_first != NULL);
9844 ASSERT(act->dta_prev->dta_intuple);
9845 ASSERT(aggbase != UINT32_MAX);
9846 ASSERT(curneeded != UINT32_MAX);
9847
9848 agg->dtag_base = aggbase;
9849
9850 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9851 rec->dtrd_offset = curneeded;
9852 curneeded += rec->dtrd_size;
9853 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
9854
9855 aggbase = UINT32_MAX;
9856 curneeded = UINT32_MAX;
9857 } else if (act->dta_intuple) {
9858 if (curneeded == UINT32_MAX) {
9859 /*
9860 * This is the first record in a tuple. Align
9861 * curneeded to be at offset 4 in an 8-byte
9862 * aligned block.
9863 */
9864 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
9865 ASSERT(aggbase == UINT32_MAX);
9866
9867 curneeded = P2PHASEUP(ecb->dte_size,
9868 sizeof (uint64_t), sizeof (dtrace_aggid_t));
9869
9870 aggbase = curneeded - sizeof (dtrace_aggid_t);
9871 ASSERT(IS_P2ALIGNED(aggbase,
9872 sizeof (uint64_t)));
9873 }
9874
9875 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9876 rec->dtrd_offset = curneeded;
9877 curneeded += rec->dtrd_size;
9878 } else {
9879 /* tuples must be followed by an aggregation */
9880 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
9881 ecb->dte_size = P2ROUNDUP(ecb->dte_size, rec->dtrd_alignment);
9882 rec->dtrd_offset = ecb->dte_size;
9883 ecb->dte_size += rec->dtrd_size;
9884 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
9885 }
9886 }
9887
9888 if ((act = ecb->dte_action) != NULL &&
9889 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9890 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
9891 /*
9892 * If the size is still sizeof (dtrace_rechdr_t), then all
9893 * actions store no data; set the size to 0.
9894 */
9895 ecb->dte_size = 0;
9896 }
9897
9898 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
9899 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
9900 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed, ecb->dte_needed);
9901 }
9902
9903 static dtrace_action_t *
9904 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9905 {
9906 dtrace_aggregation_t *agg;
9907 size_t size = sizeof (uint64_t);
9908 int ntuple = desc->dtad_ntuple;
9909 dtrace_action_t *act;
9910 dtrace_recdesc_t *frec;
9911 dtrace_aggid_t aggid;
9912 dtrace_state_t *state = ecb->dte_state;
9913
9914 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9915 agg->dtag_ecb = ecb;
9916
9917 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9918
9919 switch (desc->dtad_kind) {
9920 case DTRACEAGG_MIN:
9921 agg->dtag_initial = INT64_MAX;
9922 agg->dtag_aggregate = dtrace_aggregate_min;
9923 break;
9924
9925 case DTRACEAGG_MAX:
9926 agg->dtag_initial = INT64_MIN;
9927 agg->dtag_aggregate = dtrace_aggregate_max;
9928 break;
9929
9930 case DTRACEAGG_COUNT:
9931 agg->dtag_aggregate = dtrace_aggregate_count;
9932 break;
9933
9934 case DTRACEAGG_QUANTIZE:
9935 agg->dtag_aggregate = dtrace_aggregate_quantize;
9936 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9937 sizeof (uint64_t);
9938 break;
9939
9940 case DTRACEAGG_LQUANTIZE: {
9941 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9942 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9943
9944 agg->dtag_initial = desc->dtad_arg;
9945 agg->dtag_aggregate = dtrace_aggregate_lquantize;
9946
9947 if (step == 0 || levels == 0)
9948 goto err;
9949
9950 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9951 break;
9952 }
9953
9954 case DTRACEAGG_LLQUANTIZE: {
9955 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
9956 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
9957 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
9958 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
9959 int64_t v;
9960
9961 agg->dtag_initial = desc->dtad_arg;
9962 agg->dtag_aggregate = dtrace_aggregate_llquantize;
9963
9964 if (factor < 2 || low >= high || nsteps < factor)
9965 goto err;
9966
9967 /*
9968 * Now check that the number of steps evenly divides a power
9969 * of the factor. (This assures both integer bucket size and
9970 * linearity within each magnitude.)
9971 */
9972 for (v = factor; v < nsteps; v *= factor)
9973 continue;
9974
9975 if ((v % nsteps) || (nsteps % factor))
9976 goto err;
9977
9978 size = (dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
9979 break;
9980 }
9981
9982 case DTRACEAGG_AVG:
9983 agg->dtag_aggregate = dtrace_aggregate_avg;
9984 size = sizeof (uint64_t) * 2;
9985 break;
9986
9987 case DTRACEAGG_STDDEV:
9988 agg->dtag_aggregate = dtrace_aggregate_stddev;
9989 size = sizeof (uint64_t) * 4;
9990 break;
9991
9992 case DTRACEAGG_SUM:
9993 agg->dtag_aggregate = dtrace_aggregate_sum;
9994 break;
9995
9996 default:
9997 goto err;
9998 }
9999
10000 agg->dtag_action.dta_rec.dtrd_size = size;
10001
10002 if (ntuple == 0)
10003 goto err;
10004
10005 /*
10006 * We must make sure that we have enough actions for the n-tuple.
10007 */
10008 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10009 if (DTRACEACT_ISAGG(act->dta_kind))
10010 break;
10011
10012 if (--ntuple == 0) {
10013 /*
10014 * This is the action with which our n-tuple begins.
10015 */
10016 agg->dtag_first = act;
10017 goto success;
10018 }
10019 }
10020
10021 /*
10022 * This n-tuple is short by ntuple elements. Return failure.
10023 */
10024 ASSERT(ntuple != 0);
10025 err:
10026 kmem_free(agg, sizeof (dtrace_aggregation_t));
10027 return (NULL);
10028
10029 success:
10030 /*
10031 * If the last action in the tuple has a size of zero, it's actually
10032 * an expression argument for the aggregating action.
10033 */
10034 ASSERT(ecb->dte_action_last != NULL);
10035 act = ecb->dte_action_last;
10036
10037 if (act->dta_kind == DTRACEACT_DIFEXPR) {
10038 ASSERT(act->dta_difo != NULL);
10039
10040 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10041 agg->dtag_hasarg = 1;
10042 }
10043
10044 /*
10045 * We need to allocate an id for this aggregation.
10046 */
10047 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10048 VM_BESTFIT | VM_SLEEP);
10049
10050 if (aggid - 1 >= (dtrace_aggid_t)state->dts_naggregations) {
10051 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10052 dtrace_aggregation_t **aggs;
10053 int naggs = state->dts_naggregations << 1;
10054 int onaggs = state->dts_naggregations;
10055
10056 ASSERT(aggid == (dtrace_aggid_t)state->dts_naggregations + 1);
10057
10058 if (naggs == 0) {
10059 ASSERT(oaggs == NULL);
10060 naggs = 1;
10061 }
10062
10063 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10064
10065 if (oaggs != NULL) {
10066 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10067 kmem_free(oaggs, onaggs * sizeof (*aggs));
10068 }
10069
10070 state->dts_aggregations = aggs;
10071 state->dts_naggregations = naggs;
10072 }
10073
10074 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10075 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10076
10077 frec = &agg->dtag_first->dta_rec;
10078 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10079 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10080
10081 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10082 ASSERT(!act->dta_intuple);
10083 act->dta_intuple = 1;
10084 }
10085
10086 return (&agg->dtag_action);
10087 }
10088
10089 static void
10090 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10091 {
10092 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10093 dtrace_state_t *state = ecb->dte_state;
10094 dtrace_aggid_t aggid = agg->dtag_id;
10095
10096 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10097 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10098
10099 ASSERT(state->dts_aggregations[aggid - 1] == agg);
10100 state->dts_aggregations[aggid - 1] = NULL;
10101
10102 kmem_free(agg, sizeof (dtrace_aggregation_t));
10103 }
10104
10105 static int
10106 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10107 {
10108 dtrace_action_t *action, *last;
10109 dtrace_difo_t *dp = desc->dtad_difo;
10110 uint32_t size = 0, align = sizeof (uint8_t), mask;
10111 uint16_t format = 0;
10112 dtrace_recdesc_t *rec;
10113 dtrace_state_t *state = ecb->dte_state;
10114 dtrace_optval_t *opt = state->dts_options;
10115 dtrace_optval_t nframes=0, strsize;
10116 uint64_t arg = desc->dtad_arg;
10117
10118 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10119 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10120
10121 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10122 /*
10123 * If this is an aggregating action, there must be neither
10124 * a speculate nor a commit on the action chain.
10125 */
10126 dtrace_action_t *act;
10127
10128 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10129 if (act->dta_kind == DTRACEACT_COMMIT)
10130 return (EINVAL);
10131
10132 if (act->dta_kind == DTRACEACT_SPECULATE)
10133 return (EINVAL);
10134 }
10135
10136 action = dtrace_ecb_aggregation_create(ecb, desc);
10137
10138 if (action == NULL)
10139 return (EINVAL);
10140 } else {
10141 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10142 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10143 dp != NULL && dp->dtdo_destructive)) {
10144 state->dts_destructive = 1;
10145 }
10146
10147 switch (desc->dtad_kind) {
10148 case DTRACEACT_PRINTF:
10149 case DTRACEACT_PRINTA:
10150 case DTRACEACT_SYSTEM:
10151 case DTRACEACT_FREOPEN:
10152 case DTRACEACT_DIFEXPR:
10153 /*
10154 * We know that our arg is a string -- turn it into a
10155 * format.
10156 */
10157 if (arg == 0) {
10158 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10159 desc->dtad_kind == DTRACEACT_DIFEXPR);
10160 format = 0;
10161 } else {
10162 ASSERT(arg != 0);
10163 ASSERT(arg > KERNELBASE);
10164 format = dtrace_format_add(state,
10165 (char *)(uintptr_t)arg);
10166 }
10167
10168 /*FALLTHROUGH*/
10169 case DTRACEACT_LIBACT:
10170 case DTRACEACT_TRACEMEM:
10171 case DTRACEACT_TRACEMEM_DYNSIZE:
10172 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
10173 if (dp == NULL)
10174 return (EINVAL);
10175
10176 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10177 break;
10178
10179 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10180 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10181 return (EINVAL);
10182
10183 size = opt[DTRACEOPT_STRSIZE];
10184 }
10185
10186 break;
10187
10188 case DTRACEACT_STACK:
10189 if ((nframes = arg) == 0) {
10190 nframes = opt[DTRACEOPT_STACKFRAMES];
10191 ASSERT(nframes > 0);
10192 arg = nframes;
10193 }
10194
10195 size = nframes * sizeof (pc_t);
10196 break;
10197
10198 case DTRACEACT_JSTACK:
10199 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10200 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10201
10202 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10203 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10204
10205 arg = DTRACE_USTACK_ARG(nframes, strsize);
10206
10207 /*FALLTHROUGH*/
10208 case DTRACEACT_USTACK:
10209 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10210 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10211 strsize = DTRACE_USTACK_STRSIZE(arg);
10212 nframes = opt[DTRACEOPT_USTACKFRAMES];
10213 ASSERT(nframes > 0);
10214 arg = DTRACE_USTACK_ARG(nframes, strsize);
10215 }
10216
10217 /*
10218 * Save a slot for the pid.
10219 */
10220 size = (nframes + 1) * sizeof (uint64_t);
10221 size += DTRACE_USTACK_STRSIZE(arg);
10222 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10223
10224 break;
10225
10226 case DTRACEACT_SYM:
10227 case DTRACEACT_MOD:
10228 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10229 sizeof (uint64_t)) ||
10230 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10231 return (EINVAL);
10232 break;
10233
10234 case DTRACEACT_USYM:
10235 case DTRACEACT_UMOD:
10236 case DTRACEACT_UADDR:
10237 if (dp == NULL ||
10238 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10239 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10240 return (EINVAL);
10241
10242 /*
10243 * We have a slot for the pid, plus a slot for the
10244 * argument. To keep things simple (aligned with
10245 * bitness-neutral sizing), we store each as a 64-bit
10246 * quantity.
10247 */
10248 size = 2 * sizeof (uint64_t);
10249 break;
10250
10251 case DTRACEACT_STOP:
10252 case DTRACEACT_BREAKPOINT:
10253 case DTRACEACT_PANIC:
10254 break;
10255
10256 case DTRACEACT_CHILL:
10257 case DTRACEACT_DISCARD:
10258 case DTRACEACT_RAISE:
10259 case DTRACEACT_PIDRESUME: /* __APPLE__ */
10260 if (dp == NULL)
10261 return (EINVAL);
10262 break;
10263
10264 case DTRACEACT_EXIT:
10265 if (dp == NULL ||
10266 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10267 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10268 return (EINVAL);
10269 break;
10270
10271 case DTRACEACT_SPECULATE:
10272 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10273 return (EINVAL);
10274
10275 if (dp == NULL)
10276 return (EINVAL);
10277
10278 state->dts_speculates = 1;
10279 break;
10280
10281 case DTRACEACT_COMMIT: {
10282 dtrace_action_t *act = ecb->dte_action;
10283
10284 for (; act != NULL; act = act->dta_next) {
10285 if (act->dta_kind == DTRACEACT_COMMIT)
10286 return (EINVAL);
10287 }
10288
10289 if (dp == NULL)
10290 return (EINVAL);
10291 break;
10292 }
10293
10294 default:
10295 return (EINVAL);
10296 }
10297
10298 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10299 /*
10300 * If this is a data-storing action or a speculate,
10301 * we must be sure that there isn't a commit on the
10302 * action chain.
10303 */
10304 dtrace_action_t *act = ecb->dte_action;
10305
10306 for (; act != NULL; act = act->dta_next) {
10307 if (act->dta_kind == DTRACEACT_COMMIT)
10308 return (EINVAL);
10309 }
10310 }
10311
10312 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10313 action->dta_rec.dtrd_size = size;
10314 }
10315
10316 action->dta_refcnt = 1;
10317 rec = &action->dta_rec;
10318 size = rec->dtrd_size;
10319
10320 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10321 if (!(size & mask)) {
10322 align = mask + 1;
10323 break;
10324 }
10325 }
10326
10327 action->dta_kind = desc->dtad_kind;
10328
10329 if ((action->dta_difo = dp) != NULL)
10330 dtrace_difo_hold(dp);
10331
10332 rec->dtrd_action = action->dta_kind;
10333 rec->dtrd_arg = arg;
10334 rec->dtrd_uarg = desc->dtad_uarg;
10335 rec->dtrd_alignment = (uint16_t)align;
10336 rec->dtrd_format = format;
10337
10338 if ((last = ecb->dte_action_last) != NULL) {
10339 ASSERT(ecb->dte_action != NULL);
10340 action->dta_prev = last;
10341 last->dta_next = action;
10342 } else {
10343 ASSERT(ecb->dte_action == NULL);
10344 ecb->dte_action = action;
10345 }
10346
10347 ecb->dte_action_last = action;
10348
10349 return (0);
10350 }
10351
10352 static void
10353 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10354 {
10355 dtrace_action_t *act = ecb->dte_action, *next;
10356 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10357 dtrace_difo_t *dp;
10358 uint16_t format;
10359
10360 if (act != NULL && act->dta_refcnt > 1) {
10361 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10362 act->dta_refcnt--;
10363 } else {
10364 for (; act != NULL; act = next) {
10365 next = act->dta_next;
10366 ASSERT(next != NULL || act == ecb->dte_action_last);
10367 ASSERT(act->dta_refcnt == 1);
10368
10369 if ((format = act->dta_rec.dtrd_format) != 0)
10370 dtrace_format_remove(ecb->dte_state, format);
10371
10372 if ((dp = act->dta_difo) != NULL)
10373 dtrace_difo_release(dp, vstate);
10374
10375 if (DTRACEACT_ISAGG(act->dta_kind)) {
10376 dtrace_ecb_aggregation_destroy(ecb, act);
10377 } else {
10378 kmem_free(act, sizeof (dtrace_action_t));
10379 }
10380 }
10381 }
10382
10383 ecb->dte_action = NULL;
10384 ecb->dte_action_last = NULL;
10385 ecb->dte_size = 0;
10386 }
10387
10388 static void
10389 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10390 {
10391 /*
10392 * We disable the ECB by removing it from its probe.
10393 */
10394 dtrace_ecb_t *pecb, *prev = NULL;
10395 dtrace_probe_t *probe = ecb->dte_probe;
10396
10397 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10398
10399 if (probe == NULL) {
10400 /*
10401 * This is the NULL probe; there is nothing to disable.
10402 */
10403 return;
10404 }
10405
10406 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10407 if (pecb == ecb)
10408 break;
10409 prev = pecb;
10410 }
10411
10412 ASSERT(pecb != NULL);
10413
10414 if (prev == NULL) {
10415 probe->dtpr_ecb = ecb->dte_next;
10416 } else {
10417 prev->dte_next = ecb->dte_next;
10418 }
10419
10420 if (ecb == probe->dtpr_ecb_last) {
10421 ASSERT(ecb->dte_next == NULL);
10422 probe->dtpr_ecb_last = prev;
10423 }
10424
10425 probe->dtpr_provider->dtpv_ecb_count--;
10426 /*
10427 * The ECB has been disconnected from the probe; now sync to assure
10428 * that all CPUs have seen the change before returning.
10429 */
10430 dtrace_sync();
10431
10432 if (probe->dtpr_ecb == NULL) {
10433 /*
10434 * That was the last ECB on the probe; clear the predicate
10435 * cache ID for the probe, disable it and sync one more time
10436 * to assure that we'll never hit it again.
10437 */
10438 dtrace_provider_t *prov = probe->dtpr_provider;
10439
10440 ASSERT(ecb->dte_next == NULL);
10441 ASSERT(probe->dtpr_ecb_last == NULL);
10442 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10443 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10444 probe->dtpr_id, probe->dtpr_arg);
10445 dtrace_sync();
10446 } else {
10447 /*
10448 * There is at least one ECB remaining on the probe. If there
10449 * is _exactly_ one, set the probe's predicate cache ID to be
10450 * the predicate cache ID of the remaining ECB.
10451 */
10452 ASSERT(probe->dtpr_ecb_last != NULL);
10453 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10454
10455 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10456 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10457
10458 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10459
10460 if (p != NULL)
10461 probe->dtpr_predcache = p->dtp_cacheid;
10462 }
10463
10464 ecb->dte_next = NULL;
10465 }
10466 }
10467
10468 static void
10469 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10470 {
10471 dtrace_state_t *state = ecb->dte_state;
10472 dtrace_vstate_t *vstate = &state->dts_vstate;
10473 dtrace_predicate_t *pred;
10474 dtrace_epid_t epid = ecb->dte_epid;
10475
10476 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10477 ASSERT(ecb->dte_next == NULL);
10478 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10479
10480 if ((pred = ecb->dte_predicate) != NULL)
10481 dtrace_predicate_release(pred, vstate);
10482
10483 dtrace_ecb_action_remove(ecb);
10484
10485 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10486 state->dts_ecbs[epid - 1] = NULL;
10487
10488 kmem_free(ecb, sizeof (dtrace_ecb_t));
10489 }
10490
10491 static dtrace_ecb_t *
10492 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10493 dtrace_enabling_t *enab)
10494 {
10495 dtrace_ecb_t *ecb;
10496 dtrace_predicate_t *pred;
10497 dtrace_actdesc_t *act;
10498 dtrace_provider_t *prov;
10499 dtrace_ecbdesc_t *desc = enab->dten_current;
10500
10501 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10502 ASSERT(state != NULL);
10503
10504 ecb = dtrace_ecb_add(state, probe);
10505 ecb->dte_uarg = desc->dted_uarg;
10506
10507 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10508 dtrace_predicate_hold(pred);
10509 ecb->dte_predicate = pred;
10510 }
10511
10512 if (probe != NULL) {
10513 /*
10514 * If the provider shows more leg than the consumer is old
10515 * enough to see, we need to enable the appropriate implicit
10516 * predicate bits to prevent the ecb from activating at
10517 * revealing times.
10518 *
10519 * Providers specifying DTRACE_PRIV_USER at register time
10520 * are stating that they need the /proc-style privilege
10521 * model to be enforced, and this is what DTRACE_COND_OWNER
10522 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10523 */
10524 prov = probe->dtpr_provider;
10525 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10526 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10527 ecb->dte_cond |= DTRACE_COND_OWNER;
10528
10529 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10530 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10531 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10532
10533 /*
10534 * If the provider shows us kernel innards and the user
10535 * is lacking sufficient privilege, enable the
10536 * DTRACE_COND_USERMODE implicit predicate.
10537 */
10538 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10539 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10540 ecb->dte_cond |= DTRACE_COND_USERMODE;
10541 }
10542
10543 if (dtrace_ecb_create_cache != NULL) {
10544 /*
10545 * If we have a cached ecb, we'll use its action list instead
10546 * of creating our own (saving both time and space).
10547 */
10548 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10549 dtrace_action_t *act_if = cached->dte_action;
10550
10551 if (act_if != NULL) {
10552 ASSERT(act_if->dta_refcnt > 0);
10553 act_if->dta_refcnt++;
10554 ecb->dte_action = act_if;
10555 ecb->dte_action_last = cached->dte_action_last;
10556 ecb->dte_needed = cached->dte_needed;
10557 ecb->dte_size = cached->dte_size;
10558 ecb->dte_alignment = cached->dte_alignment;
10559 }
10560
10561 return (ecb);
10562 }
10563
10564 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10565 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10566 dtrace_ecb_destroy(ecb);
10567 return (NULL);
10568 }
10569 }
10570
10571 dtrace_ecb_resize(ecb);
10572
10573 return (dtrace_ecb_create_cache = ecb);
10574 }
10575
10576 static int
10577 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10578 {
10579 dtrace_ecb_t *ecb;
10580 dtrace_enabling_t *enab = arg;
10581 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10582
10583 ASSERT(state != NULL);
10584
10585 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10586 /*
10587 * This probe was created in a generation for which this
10588 * enabling has previously created ECBs; we don't want to
10589 * enable it again, so just kick out.
10590 */
10591 return (DTRACE_MATCH_NEXT);
10592 }
10593
10594 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10595 return (DTRACE_MATCH_DONE);
10596
10597 if (dtrace_ecb_enable(ecb) < 0)
10598 return (DTRACE_MATCH_FAIL);
10599
10600 return (DTRACE_MATCH_NEXT);
10601 }
10602
10603 static dtrace_ecb_t *
10604 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10605 {
10606 dtrace_ecb_t *ecb;
10607 #pragma unused(ecb) /* __APPLE__ */
10608
10609 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10610
10611 if (id == 0 || id > (dtrace_epid_t)state->dts_necbs)
10612 return (NULL);
10613
10614 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10615 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10616
10617 return (state->dts_ecbs[id - 1]);
10618 }
10619
10620 static dtrace_aggregation_t *
10621 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10622 {
10623 dtrace_aggregation_t *agg;
10624 #pragma unused(agg) /* __APPLE__ */
10625
10626 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10627
10628 if (id == 0 || id > (dtrace_aggid_t)state->dts_naggregations)
10629 return (NULL);
10630
10631 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10632 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10633 agg->dtag_id == id);
10634
10635 return (state->dts_aggregations[id - 1]);
10636 }
10637
10638 /*
10639 * DTrace Buffer Functions
10640 *
10641 * The following functions manipulate DTrace buffers. Most of these functions
10642 * are called in the context of establishing or processing consumer state;
10643 * exceptions are explicitly noted.
10644 */
10645
10646 /*
10647 * Note: called from cross call context. This function switches the two
10648 * buffers on a given CPU. The atomicity of this operation is assured by
10649 * disabling interrupts while the actual switch takes place; the disabling of
10650 * interrupts serializes the execution with any execution of dtrace_probe() on
10651 * the same CPU.
10652 */
10653 static void
10654 dtrace_buffer_switch(dtrace_buffer_t *buf)
10655 {
10656 caddr_t tomax = buf->dtb_tomax;
10657 caddr_t xamot = buf->dtb_xamot;
10658 dtrace_icookie_t cookie;
10659 hrtime_t now;
10660
10661 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10662 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10663
10664 cookie = dtrace_interrupt_disable();
10665 now = dtrace_gethrtime();
10666 buf->dtb_tomax = xamot;
10667 buf->dtb_xamot = tomax;
10668 buf->dtb_xamot_drops = buf->dtb_drops;
10669 buf->dtb_xamot_offset = buf->dtb_offset;
10670 buf->dtb_xamot_errors = buf->dtb_errors;
10671 buf->dtb_xamot_flags = buf->dtb_flags;
10672 buf->dtb_offset = 0;
10673 buf->dtb_drops = 0;
10674 buf->dtb_errors = 0;
10675 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10676 buf->dtb_interval = now - buf->dtb_switched;
10677 buf->dtb_switched = now;
10678 dtrace_interrupt_enable(cookie);
10679 }
10680
10681 /*
10682 * Note: called from cross call context. This function activates a buffer
10683 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
10684 * is guaranteed by the disabling of interrupts.
10685 */
10686 static void
10687 dtrace_buffer_activate(dtrace_state_t *state)
10688 {
10689 dtrace_buffer_t *buf;
10690 dtrace_icookie_t cookie = dtrace_interrupt_disable();
10691
10692 buf = &state->dts_buffer[CPU->cpu_id];
10693
10694 if (buf->dtb_tomax != NULL) {
10695 /*
10696 * We might like to assert that the buffer is marked inactive,
10697 * but this isn't necessarily true: the buffer for the CPU
10698 * that processes the BEGIN probe has its buffer activated
10699 * manually. In this case, we take the (harmless) action
10700 * re-clearing the bit INACTIVE bit.
10701 */
10702 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10703 }
10704
10705 dtrace_interrupt_enable(cookie);
10706 }
10707
10708 static int
10709 dtrace_buffer_canalloc(size_t size)
10710 {
10711 if (size > (UINT64_MAX - dtrace_buffer_memory_inuse))
10712 return (B_FALSE);
10713 if ((size + dtrace_buffer_memory_inuse) > dtrace_buffer_memory_maxsize)
10714 return (B_FALSE);
10715
10716 return (B_TRUE);
10717 }
10718
10719 static int
10720 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10721 processorid_t cpu)
10722 {
10723 dtrace_cpu_t *cp;
10724 dtrace_buffer_t *buf;
10725 size_t size_before_alloc = dtrace_buffer_memory_inuse;
10726
10727 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
10728 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10729
10730 if (size > (size_t)dtrace_nonroot_maxsize &&
10731 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10732 return (EFBIG);
10733
10734 cp = cpu_list;
10735
10736 do {
10737 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10738 continue;
10739
10740 buf = &bufs[cp->cpu_id];
10741
10742 /*
10743 * If there is already a buffer allocated for this CPU, it
10744 * is only possible that this is a DR event. In this case,
10745 * the buffer size must match our specified size.
10746 */
10747 if (buf->dtb_tomax != NULL) {
10748 ASSERT(buf->dtb_size == size);
10749 continue;
10750 }
10751
10752 ASSERT(buf->dtb_xamot == NULL);
10753
10754 /* DTrace, please do not eat all the memory. */
10755 if (dtrace_buffer_canalloc(size) == B_FALSE)
10756 goto err;
10757 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10758 goto err;
10759 dtrace_buffer_memory_inuse += size;
10760
10761 buf->dtb_size = size;
10762 buf->dtb_flags = flags;
10763 buf->dtb_offset = 0;
10764 buf->dtb_drops = 0;
10765
10766 if (flags & DTRACEBUF_NOSWITCH)
10767 continue;
10768
10769 /* DTrace, please do not eat all the memory. */
10770 if (dtrace_buffer_canalloc(size) == B_FALSE)
10771 goto err;
10772 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10773 goto err;
10774 dtrace_buffer_memory_inuse += size;
10775 } while ((cp = cp->cpu_next) != cpu_list);
10776
10777 ASSERT(dtrace_buffer_memory_inuse <= dtrace_buffer_memory_maxsize);
10778
10779 return (0);
10780
10781 err:
10782 cp = cpu_list;
10783
10784 do {
10785 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10786 continue;
10787
10788 buf = &bufs[cp->cpu_id];
10789
10790 if (buf->dtb_xamot != NULL) {
10791 ASSERT(buf->dtb_tomax != NULL);
10792 ASSERT(buf->dtb_size == size);
10793 kmem_free(buf->dtb_xamot, size);
10794 }
10795
10796 if (buf->dtb_tomax != NULL) {
10797 ASSERT(buf->dtb_size == size);
10798 kmem_free(buf->dtb_tomax, size);
10799 }
10800
10801 buf->dtb_tomax = NULL;
10802 buf->dtb_xamot = NULL;
10803 buf->dtb_size = 0;
10804 } while ((cp = cp->cpu_next) != cpu_list);
10805
10806 /* Restore the size saved before allocating memory */
10807 dtrace_buffer_memory_inuse = size_before_alloc;
10808
10809 return (ENOMEM);
10810 }
10811
10812 /*
10813 * Note: called from probe context. This function just increments the drop
10814 * count on a buffer. It has been made a function to allow for the
10815 * possibility of understanding the source of mysterious drop counts. (A
10816 * problem for which one may be particularly disappointed that DTrace cannot
10817 * be used to understand DTrace.)
10818 */
10819 static void
10820 dtrace_buffer_drop(dtrace_buffer_t *buf)
10821 {
10822 buf->dtb_drops++;
10823 }
10824
10825 /*
10826 * Note: called from probe context. This function is called to reserve space
10827 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
10828 * mstate. Returns the new offset in the buffer, or a negative value if an
10829 * error has occurred.
10830 */
10831 static intptr_t
10832 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10833 dtrace_state_t *state, dtrace_mstate_t *mstate)
10834 {
10835 intptr_t offs = buf->dtb_offset, soffs;
10836 intptr_t woffs;
10837 caddr_t tomax;
10838 size_t total_off;
10839
10840 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10841 return (-1);
10842
10843 if ((tomax = buf->dtb_tomax) == NULL) {
10844 dtrace_buffer_drop(buf);
10845 return (-1);
10846 }
10847
10848 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10849 while (offs & (align - 1)) {
10850 /*
10851 * Assert that our alignment is off by a number which
10852 * is itself sizeof (uint32_t) aligned.
10853 */
10854 ASSERT(!((align - (offs & (align - 1))) &
10855 (sizeof (uint32_t) - 1)));
10856 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10857 offs += sizeof (uint32_t);
10858 }
10859
10860 if ((uint64_t)(soffs = offs + needed) > buf->dtb_size) {
10861 dtrace_buffer_drop(buf);
10862 return (-1);
10863 }
10864
10865 if (mstate == NULL)
10866 return (offs);
10867
10868 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10869 mstate->dtms_scratch_size = buf->dtb_size - soffs;
10870 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10871
10872 return (offs);
10873 }
10874
10875 if (buf->dtb_flags & DTRACEBUF_FILL) {
10876 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10877 (buf->dtb_flags & DTRACEBUF_FULL))
10878 return (-1);
10879 goto out;
10880 }
10881
10882 total_off = needed + (offs & (align - 1));
10883
10884 /*
10885 * For a ring buffer, life is quite a bit more complicated. Before
10886 * we can store any padding, we need to adjust our wrapping offset.
10887 * (If we've never before wrapped or we're not about to, no adjustment
10888 * is required.)
10889 */
10890 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10891 offs + total_off > buf->dtb_size) {
10892 woffs = buf->dtb_xamot_offset;
10893
10894 if (offs + total_off > buf->dtb_size) {
10895 /*
10896 * We can't fit in the end of the buffer. First, a
10897 * sanity check that we can fit in the buffer at all.
10898 */
10899 if (total_off > buf->dtb_size) {
10900 dtrace_buffer_drop(buf);
10901 return (-1);
10902 }
10903
10904 /*
10905 * We're going to be storing at the top of the buffer,
10906 * so now we need to deal with the wrapped offset. We
10907 * only reset our wrapped offset to 0 if it is
10908 * currently greater than the current offset. If it
10909 * is less than the current offset, it is because a
10910 * previous allocation induced a wrap -- but the
10911 * allocation didn't subsequently take the space due
10912 * to an error or false predicate evaluation. In this
10913 * case, we'll just leave the wrapped offset alone: if
10914 * the wrapped offset hasn't been advanced far enough
10915 * for this allocation, it will be adjusted in the
10916 * lower loop.
10917 */
10918 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10919 if (woffs >= offs)
10920 woffs = 0;
10921 } else {
10922 woffs = 0;
10923 }
10924
10925 /*
10926 * Now we know that we're going to be storing to the
10927 * top of the buffer and that there is room for us
10928 * there. We need to clear the buffer from the current
10929 * offset to the end (there may be old gunk there).
10930 */
10931 while ((uint64_t)offs < buf->dtb_size)
10932 tomax[offs++] = 0;
10933
10934 /*
10935 * We need to set our offset to zero. And because we
10936 * are wrapping, we need to set the bit indicating as
10937 * much. We can also adjust our needed space back
10938 * down to the space required by the ECB -- we know
10939 * that the top of the buffer is aligned.
10940 */
10941 offs = 0;
10942 total_off = needed;
10943 buf->dtb_flags |= DTRACEBUF_WRAPPED;
10944 } else {
10945 /*
10946 * There is room for us in the buffer, so we simply
10947 * need to check the wrapped offset.
10948 */
10949 if (woffs < offs) {
10950 /*
10951 * The wrapped offset is less than the offset.
10952 * This can happen if we allocated buffer space
10953 * that induced a wrap, but then we didn't
10954 * subsequently take the space due to an error
10955 * or false predicate evaluation. This is
10956 * okay; we know that _this_ allocation isn't
10957 * going to induce a wrap. We still can't
10958 * reset the wrapped offset to be zero,
10959 * however: the space may have been trashed in
10960 * the previous failed probe attempt. But at
10961 * least the wrapped offset doesn't need to
10962 * be adjusted at all...
10963 */
10964 goto out;
10965 }
10966 }
10967
10968 while (offs + total_off > (size_t)woffs) {
10969 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10970 size_t size;
10971
10972 if (epid == DTRACE_EPIDNONE) {
10973 size = sizeof (uint32_t);
10974 } else {
10975 ASSERT(epid <= (dtrace_epid_t)state->dts_necbs);
10976 ASSERT(state->dts_ecbs[epid - 1] != NULL);
10977
10978 size = state->dts_ecbs[epid - 1]->dte_size;
10979 }
10980
10981 ASSERT(woffs + size <= buf->dtb_size);
10982 ASSERT(size != 0);
10983
10984 if (woffs + size == buf->dtb_size) {
10985 /*
10986 * We've reached the end of the buffer; we want
10987 * to set the wrapped offset to 0 and break
10988 * out. However, if the offs is 0, then we're
10989 * in a strange edge-condition: the amount of
10990 * space that we want to reserve plus the size
10991 * of the record that we're overwriting is
10992 * greater than the size of the buffer. This
10993 * is problematic because if we reserve the
10994 * space but subsequently don't consume it (due
10995 * to a failed predicate or error) the wrapped
10996 * offset will be 0 -- yet the EPID at offset 0
10997 * will not be committed. This situation is
10998 * relatively easy to deal with: if we're in
10999 * this case, the buffer is indistinguishable
11000 * from one that hasn't wrapped; we need only
11001 * finish the job by clearing the wrapped bit,
11002 * explicitly setting the offset to be 0, and
11003 * zero'ing out the old data in the buffer.
11004 */
11005 if (offs == 0) {
11006 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11007 buf->dtb_offset = 0;
11008 woffs = total_off;
11009
11010 while ((uint64_t)woffs < buf->dtb_size)
11011 tomax[woffs++] = 0;
11012 }
11013
11014 woffs = 0;
11015 break;
11016 }
11017
11018 woffs += size;
11019 }
11020
11021 /*
11022 * We have a wrapped offset. It may be that the wrapped offset
11023 * has become zero -- that's okay.
11024 */
11025 buf->dtb_xamot_offset = woffs;
11026 }
11027
11028 out:
11029 /*
11030 * Now we can plow the buffer with any necessary padding.
11031 */
11032 while (offs & (align - 1)) {
11033 /*
11034 * Assert that our alignment is off by a number which
11035 * is itself sizeof (uint32_t) aligned.
11036 */
11037 ASSERT(!((align - (offs & (align - 1))) &
11038 (sizeof (uint32_t) - 1)));
11039 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11040 offs += sizeof (uint32_t);
11041 }
11042
11043 if (buf->dtb_flags & DTRACEBUF_FILL) {
11044 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11045 buf->dtb_flags |= DTRACEBUF_FULL;
11046 return (-1);
11047 }
11048 }
11049
11050 if (mstate == NULL)
11051 return (offs);
11052
11053 /*
11054 * For ring buffers and fill buffers, the scratch space is always
11055 * the inactive buffer.
11056 */
11057 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11058 mstate->dtms_scratch_size = buf->dtb_size;
11059 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11060
11061 return (offs);
11062 }
11063
11064 static void
11065 dtrace_buffer_polish(dtrace_buffer_t *buf)
11066 {
11067 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11068 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11069
11070 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11071 return;
11072
11073 /*
11074 * We need to polish the ring buffer. There are three cases:
11075 *
11076 * - The first (and presumably most common) is that there is no gap
11077 * between the buffer offset and the wrapped offset. In this case,
11078 * there is nothing in the buffer that isn't valid data; we can
11079 * mark the buffer as polished and return.
11080 *
11081 * - The second (less common than the first but still more common
11082 * than the third) is that there is a gap between the buffer offset
11083 * and the wrapped offset, and the wrapped offset is larger than the
11084 * buffer offset. This can happen because of an alignment issue, or
11085 * can happen because of a call to dtrace_buffer_reserve() that
11086 * didn't subsequently consume the buffer space. In this case,
11087 * we need to zero the data from the buffer offset to the wrapped
11088 * offset.
11089 *
11090 * - The third (and least common) is that there is a gap between the
11091 * buffer offset and the wrapped offset, but the wrapped offset is
11092 * _less_ than the buffer offset. This can only happen because a
11093 * call to dtrace_buffer_reserve() induced a wrap, but the space
11094 * was not subsequently consumed. In this case, we need to zero the
11095 * space from the offset to the end of the buffer _and_ from the
11096 * top of the buffer to the wrapped offset.
11097 */
11098 if (buf->dtb_offset < buf->dtb_xamot_offset) {
11099 bzero(buf->dtb_tomax + buf->dtb_offset,
11100 buf->dtb_xamot_offset - buf->dtb_offset);
11101 }
11102
11103 if (buf->dtb_offset > buf->dtb_xamot_offset) {
11104 bzero(buf->dtb_tomax + buf->dtb_offset,
11105 buf->dtb_size - buf->dtb_offset);
11106 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11107 }
11108 }
11109
11110 static void
11111 dtrace_buffer_free(dtrace_buffer_t *bufs)
11112 {
11113 int i;
11114
11115 for (i = 0; i < (int)NCPU; i++) {
11116 dtrace_buffer_t *buf = &bufs[i];
11117
11118 if (buf->dtb_tomax == NULL) {
11119 ASSERT(buf->dtb_xamot == NULL);
11120 ASSERT(buf->dtb_size == 0);
11121 continue;
11122 }
11123
11124 if (buf->dtb_xamot != NULL) {
11125 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11126 kmem_free(buf->dtb_xamot, buf->dtb_size);
11127
11128 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11129 dtrace_buffer_memory_inuse -= buf->dtb_size;
11130 }
11131
11132 kmem_free(buf->dtb_tomax, buf->dtb_size);
11133 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11134 dtrace_buffer_memory_inuse -= buf->dtb_size;
11135
11136 buf->dtb_size = 0;
11137 buf->dtb_tomax = NULL;
11138 buf->dtb_xamot = NULL;
11139 }
11140 }
11141
11142 /*
11143 * DTrace Enabling Functions
11144 */
11145 static dtrace_enabling_t *
11146 dtrace_enabling_create(dtrace_vstate_t *vstate)
11147 {
11148 dtrace_enabling_t *enab;
11149
11150 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11151 enab->dten_vstate = vstate;
11152
11153 return (enab);
11154 }
11155
11156 static void
11157 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11158 {
11159 dtrace_ecbdesc_t **ndesc;
11160 size_t osize, nsize;
11161
11162 /*
11163 * We can't add to enablings after we've enabled them, or after we've
11164 * retained them.
11165 */
11166 ASSERT(enab->dten_probegen == 0);
11167 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11168
11169 /* APPLE NOTE: this protects against gcc 4.0 botch on x86 */
11170 if (ecb == NULL) return;
11171
11172 if (enab->dten_ndesc < enab->dten_maxdesc) {
11173 enab->dten_desc[enab->dten_ndesc++] = ecb;
11174 return;
11175 }
11176
11177 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11178
11179 if (enab->dten_maxdesc == 0) {
11180 enab->dten_maxdesc = 1;
11181 } else {
11182 enab->dten_maxdesc <<= 1;
11183 }
11184
11185 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11186
11187 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11188 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11189 bcopy(enab->dten_desc, ndesc, osize);
11190 kmem_free(enab->dten_desc, osize);
11191
11192 enab->dten_desc = ndesc;
11193 enab->dten_desc[enab->dten_ndesc++] = ecb;
11194 }
11195
11196 static void
11197 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11198 dtrace_probedesc_t *pd)
11199 {
11200 dtrace_ecbdesc_t *new;
11201 dtrace_predicate_t *pred;
11202 dtrace_actdesc_t *act;
11203
11204 /*
11205 * We're going to create a new ECB description that matches the
11206 * specified ECB in every way, but has the specified probe description.
11207 */
11208 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11209
11210 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11211 dtrace_predicate_hold(pred);
11212
11213 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11214 dtrace_actdesc_hold(act);
11215
11216 new->dted_action = ecb->dted_action;
11217 new->dted_pred = ecb->dted_pred;
11218 new->dted_probe = *pd;
11219 new->dted_uarg = ecb->dted_uarg;
11220
11221 dtrace_enabling_add(enab, new);
11222 }
11223
11224 static void
11225 dtrace_enabling_dump(dtrace_enabling_t *enab)
11226 {
11227 int i;
11228
11229 for (i = 0; i < enab->dten_ndesc; i++) {
11230 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11231
11232 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11233 desc->dtpd_provider, desc->dtpd_mod,
11234 desc->dtpd_func, desc->dtpd_name);
11235 }
11236 }
11237
11238 static void
11239 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11240 {
11241 int i;
11242 dtrace_ecbdesc_t *ep;
11243 dtrace_vstate_t *vstate = enab->dten_vstate;
11244
11245 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11246
11247 for (i = 0; i < enab->dten_ndesc; i++) {
11248 dtrace_actdesc_t *act, *next;
11249 dtrace_predicate_t *pred;
11250
11251 ep = enab->dten_desc[i];
11252
11253 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11254 dtrace_predicate_release(pred, vstate);
11255
11256 for (act = ep->dted_action; act != NULL; act = next) {
11257 next = act->dtad_next;
11258 dtrace_actdesc_release(act, vstate);
11259 }
11260
11261 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11262 }
11263
11264 kmem_free(enab->dten_desc,
11265 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11266
11267 /*
11268 * If this was a retained enabling, decrement the dts_nretained count
11269 * and take it off of the dtrace_retained list.
11270 */
11271 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11272 dtrace_retained == enab) {
11273 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11274 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11275 enab->dten_vstate->dtvs_state->dts_nretained--;
11276 dtrace_retained_gen++;
11277 }
11278
11279 if (enab->dten_prev == NULL) {
11280 if (dtrace_retained == enab) {
11281 dtrace_retained = enab->dten_next;
11282
11283 if (dtrace_retained != NULL)
11284 dtrace_retained->dten_prev = NULL;
11285 }
11286 } else {
11287 ASSERT(enab != dtrace_retained);
11288 ASSERT(dtrace_retained != NULL);
11289 enab->dten_prev->dten_next = enab->dten_next;
11290 }
11291
11292 if (enab->dten_next != NULL) {
11293 ASSERT(dtrace_retained != NULL);
11294 enab->dten_next->dten_prev = enab->dten_prev;
11295 }
11296
11297 kmem_free(enab, sizeof (dtrace_enabling_t));
11298 }
11299
11300 static int
11301 dtrace_enabling_retain(dtrace_enabling_t *enab)
11302 {
11303 dtrace_state_t *state;
11304
11305 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11306 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11307 ASSERT(enab->dten_vstate != NULL);
11308
11309 state = enab->dten_vstate->dtvs_state;
11310 ASSERT(state != NULL);
11311
11312 /*
11313 * We only allow each state to retain dtrace_retain_max enablings.
11314 */
11315 if (state->dts_nretained >= dtrace_retain_max)
11316 return (ENOSPC);
11317
11318 state->dts_nretained++;
11319 dtrace_retained_gen++;
11320
11321 if (dtrace_retained == NULL) {
11322 dtrace_retained = enab;
11323 return (0);
11324 }
11325
11326 enab->dten_next = dtrace_retained;
11327 dtrace_retained->dten_prev = enab;
11328 dtrace_retained = enab;
11329
11330 return (0);
11331 }
11332
11333 static int
11334 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11335 dtrace_probedesc_t *create)
11336 {
11337 dtrace_enabling_t *new, *enab;
11338 int found = 0, err = ENOENT;
11339
11340 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11341 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11342 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11343 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11344 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11345
11346 new = dtrace_enabling_create(&state->dts_vstate);
11347
11348 /*
11349 * Iterate over all retained enablings, looking for enablings that
11350 * match the specified state.
11351 */
11352 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11353 int i;
11354
11355 /*
11356 * dtvs_state can only be NULL for helper enablings -- and
11357 * helper enablings can't be retained.
11358 */
11359 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11360
11361 if (enab->dten_vstate->dtvs_state != state)
11362 continue;
11363
11364 /*
11365 * Now iterate over each probe description; we're looking for
11366 * an exact match to the specified probe description.
11367 */
11368 for (i = 0; i < enab->dten_ndesc; i++) {
11369 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11370 dtrace_probedesc_t *pd = &ep->dted_probe;
11371
11372 /* APPLE NOTE: Darwin employs size bounded string operation. */
11373 if (strncmp(pd->dtpd_provider, match->dtpd_provider, DTRACE_PROVNAMELEN))
11374 continue;
11375
11376 if (strncmp(pd->dtpd_mod, match->dtpd_mod, DTRACE_MODNAMELEN))
11377 continue;
11378
11379 if (strncmp(pd->dtpd_func, match->dtpd_func, DTRACE_FUNCNAMELEN))
11380 continue;
11381
11382 if (strncmp(pd->dtpd_name, match->dtpd_name, DTRACE_NAMELEN))
11383 continue;
11384
11385 /*
11386 * We have a winning probe! Add it to our growing
11387 * enabling.
11388 */
11389 found = 1;
11390 dtrace_enabling_addlike(new, ep, create);
11391 }
11392 }
11393
11394 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11395 dtrace_enabling_destroy(new);
11396 return (err);
11397 }
11398
11399 return (0);
11400 }
11401
11402 static void
11403 dtrace_enabling_retract(dtrace_state_t *state)
11404 {
11405 dtrace_enabling_t *enab, *next;
11406
11407 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11408
11409 /*
11410 * Iterate over all retained enablings, destroy the enablings retained
11411 * for the specified state.
11412 */
11413 for (enab = dtrace_retained; enab != NULL; enab = next) {
11414 next = enab->dten_next;
11415
11416 /*
11417 * dtvs_state can only be NULL for helper enablings -- and
11418 * helper enablings can't be retained.
11419 */
11420 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11421
11422 if (enab->dten_vstate->dtvs_state == state) {
11423 ASSERT(state->dts_nretained > 0);
11424 dtrace_enabling_destroy(enab);
11425 }
11426 }
11427
11428 ASSERT(state->dts_nretained == 0);
11429 }
11430
11431 static int
11432 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11433 {
11434 int i = 0;
11435 int total_matched = 0, matched = 0;
11436
11437 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11438 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11439
11440 for (i = 0; i < enab->dten_ndesc; i++) {
11441 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11442
11443 enab->dten_current = ep;
11444 enab->dten_error = 0;
11445
11446 /*
11447 * If a provider failed to enable a probe then get out and
11448 * let the consumer know we failed.
11449 */
11450 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11451 return (EBUSY);
11452
11453 total_matched += matched;
11454
11455 if (enab->dten_error != 0) {
11456 /*
11457 * If we get an error half-way through enabling the
11458 * probes, we kick out -- perhaps with some number of
11459 * them enabled. Leaving enabled probes enabled may
11460 * be slightly confusing for user-level, but we expect
11461 * that no one will attempt to actually drive on in
11462 * the face of such errors. If this is an anonymous
11463 * enabling (indicated with a NULL nmatched pointer),
11464 * we cmn_err() a message. We aren't expecting to
11465 * get such an error -- such as it can exist at all,
11466 * it would be a result of corrupted DOF in the driver
11467 * properties.
11468 */
11469 if (nmatched == NULL) {
11470 cmn_err(CE_WARN, "dtrace_enabling_match() "
11471 "error on %p: %d", (void *)ep,
11472 enab->dten_error);
11473 }
11474
11475 return (enab->dten_error);
11476 }
11477 }
11478
11479 enab->dten_probegen = dtrace_probegen;
11480 if (nmatched != NULL)
11481 *nmatched = total_matched;
11482
11483 return (0);
11484 }
11485
11486 static void
11487 dtrace_enabling_matchall(void)
11488 {
11489 dtrace_enabling_t *enab;
11490
11491 lck_mtx_lock(&cpu_lock);
11492 lck_mtx_lock(&dtrace_lock);
11493
11494 /*
11495 * Iterate over all retained enablings to see if any probes match
11496 * against them. We only perform this operation on enablings for which
11497 * we have sufficient permissions by virtue of being in the global zone
11498 * or in the same zone as the DTrace client. Because we can be called
11499 * after dtrace_detach() has been called, we cannot assert that there
11500 * are retained enablings. We can safely load from dtrace_retained,
11501 * however: the taskq_destroy() at the end of dtrace_detach() will
11502 * block pending our completion.
11503 */
11504
11505 /*
11506 * Darwin doesn't do zones.
11507 * Behave as if always in "global" zone."
11508 */
11509 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11510 (void) dtrace_enabling_match(enab, NULL);
11511 }
11512
11513 lck_mtx_unlock(&dtrace_lock);
11514 lck_mtx_unlock(&cpu_lock);
11515 }
11516
11517 /*
11518 * If an enabling is to be enabled without having matched probes (that is, if
11519 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11520 * enabling must be _primed_ by creating an ECB for every ECB description.
11521 * This must be done to assure that we know the number of speculations, the
11522 * number of aggregations, the minimum buffer size needed, etc. before we
11523 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11524 * enabling any probes, we create ECBs for every ECB decription, but with a
11525 * NULL probe -- which is exactly what this function does.
11526 */
11527 static void
11528 dtrace_enabling_prime(dtrace_state_t *state)
11529 {
11530 dtrace_enabling_t *enab;
11531 int i;
11532
11533 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11534 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11535
11536 if (enab->dten_vstate->dtvs_state != state)
11537 continue;
11538
11539 /*
11540 * We don't want to prime an enabling more than once, lest
11541 * we allow a malicious user to induce resource exhaustion.
11542 * (The ECBs that result from priming an enabling aren't
11543 * leaked -- but they also aren't deallocated until the
11544 * consumer state is destroyed.)
11545 */
11546 if (enab->dten_primed)
11547 continue;
11548
11549 for (i = 0; i < enab->dten_ndesc; i++) {
11550 enab->dten_current = enab->dten_desc[i];
11551 (void) dtrace_probe_enable(NULL, enab);
11552 }
11553
11554 enab->dten_primed = 1;
11555 }
11556 }
11557
11558 /*
11559 * Called to indicate that probes should be provided due to retained
11560 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
11561 * must take an initial lap through the enabling calling the dtps_provide()
11562 * entry point explicitly to allow for autocreated probes.
11563 */
11564 static void
11565 dtrace_enabling_provide(dtrace_provider_t *prv)
11566 {
11567 int i, all = 0;
11568 dtrace_probedesc_t desc;
11569 dtrace_genid_t gen;
11570
11571 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11572 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
11573
11574 if (prv == NULL) {
11575 all = 1;
11576 prv = dtrace_provider;
11577 }
11578
11579 do {
11580 dtrace_enabling_t *enab;
11581 void *parg = prv->dtpv_arg;
11582
11583 retry:
11584 gen = dtrace_retained_gen;
11585 for (enab = dtrace_retained; enab != NULL;
11586 enab = enab->dten_next) {
11587 for (i = 0; i < enab->dten_ndesc; i++) {
11588 desc = enab->dten_desc[i]->dted_probe;
11589 lck_mtx_unlock(&dtrace_lock);
11590 prv->dtpv_pops.dtps_provide(parg, &desc);
11591 lck_mtx_lock(&dtrace_lock);
11592 /*
11593 * Process the retained enablings again if
11594 * they have changed while we weren't holding
11595 * dtrace_lock.
11596 */
11597 if (gen != dtrace_retained_gen)
11598 goto retry;
11599 }
11600 }
11601 } while (all && (prv = prv->dtpv_next) != NULL);
11602
11603 lck_mtx_unlock(&dtrace_lock);
11604 dtrace_probe_provide(NULL, all ? NULL : prv);
11605 lck_mtx_lock(&dtrace_lock);
11606 }
11607
11608 /*
11609 * DTrace DOF Functions
11610 */
11611 /*ARGSUSED*/
11612 static void
11613 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11614 {
11615 #pragma unused(dof) /* __APPLE__ */
11616 if (dtrace_err_verbose)
11617 cmn_err(CE_WARN, "failed to process DOF: %s", str);
11618
11619 #ifdef DTRACE_ERRDEBUG
11620 dtrace_errdebug(str);
11621 #endif
11622 }
11623
11624 /*
11625 * Create DOF out of a currently enabled state. Right now, we only create
11626 * DOF containing the run-time options -- but this could be expanded to create
11627 * complete DOF representing the enabled state.
11628 */
11629 static dof_hdr_t *
11630 dtrace_dof_create(dtrace_state_t *state)
11631 {
11632 dof_hdr_t *dof;
11633 dof_sec_t *sec;
11634 dof_optdesc_t *opt;
11635 int i, len = sizeof (dof_hdr_t) +
11636 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11637 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11638
11639 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11640
11641 dof = dt_kmem_zalloc_aligned(len, 8, KM_SLEEP);
11642 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11643 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11644 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11645 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11646
11647 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11648 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11649 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11650 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11651 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11652 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11653
11654 dof->dofh_flags = 0;
11655 dof->dofh_hdrsize = sizeof (dof_hdr_t);
11656 dof->dofh_secsize = sizeof (dof_sec_t);
11657 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
11658 dof->dofh_secoff = sizeof (dof_hdr_t);
11659 dof->dofh_loadsz = len;
11660 dof->dofh_filesz = len;
11661 dof->dofh_pad = 0;
11662
11663 /*
11664 * Fill in the option section header...
11665 */
11666 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11667 sec->dofs_type = DOF_SECT_OPTDESC;
11668 sec->dofs_align = sizeof (uint64_t);
11669 sec->dofs_flags = DOF_SECF_LOAD;
11670 sec->dofs_entsize = sizeof (dof_optdesc_t);
11671
11672 opt = (dof_optdesc_t *)((uintptr_t)sec +
11673 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11674
11675 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11676 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11677
11678 for (i = 0; i < DTRACEOPT_MAX; i++) {
11679 opt[i].dofo_option = i;
11680 opt[i].dofo_strtab = DOF_SECIDX_NONE;
11681 opt[i].dofo_value = state->dts_options[i];
11682 }
11683
11684 return (dof);
11685 }
11686
11687 static dof_hdr_t *
11688 dtrace_dof_copyin(user_addr_t uarg, int *errp)
11689 {
11690 dof_hdr_t hdr, *dof;
11691
11692 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
11693
11694 /*
11695 * First, we're going to copyin() the sizeof (dof_hdr_t).
11696 */
11697 if (copyin(uarg, &hdr, sizeof (hdr)) != 0) {
11698 dtrace_dof_error(NULL, "failed to copyin DOF header");
11699 *errp = EFAULT;
11700 return (NULL);
11701 }
11702
11703 /*
11704 * Now we'll allocate the entire DOF and copy it in -- provided
11705 * that the length isn't outrageous.
11706 */
11707 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
11708 dtrace_dof_error(&hdr, "load size exceeds maximum");
11709 *errp = E2BIG;
11710 return (NULL);
11711 }
11712
11713 if (hdr.dofh_loadsz < sizeof (hdr)) {
11714 dtrace_dof_error(&hdr, "invalid load size");
11715 *errp = EINVAL;
11716 return (NULL);
11717 }
11718
11719 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
11720
11721 if (copyin(uarg, dof, hdr.dofh_loadsz) != 0 ||
11722 dof->dofh_loadsz != hdr.dofh_loadsz) {
11723 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
11724 *errp = EFAULT;
11725 return (NULL);
11726 }
11727
11728 return (dof);
11729 }
11730
11731 static dof_hdr_t *
11732 dtrace_dof_copyin_from_proc(proc_t* p, user_addr_t uarg, int *errp)
11733 {
11734 dof_hdr_t hdr, *dof;
11735
11736 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
11737
11738 /*
11739 * First, we're going to copyin() the sizeof (dof_hdr_t).
11740 */
11741 if (uread(p, &hdr, sizeof(hdr), uarg) != KERN_SUCCESS) {
11742 dtrace_dof_error(NULL, "failed to copyin DOF header");
11743 *errp = EFAULT;
11744 return (NULL);
11745 }
11746
11747 /*
11748 * Now we'll allocate the entire DOF and copy it in -- provided
11749 * that the length isn't outrageous.
11750 */
11751 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
11752 dtrace_dof_error(&hdr, "load size exceeds maximum");
11753 *errp = E2BIG;
11754 return (NULL);
11755 }
11756
11757 if (hdr.dofh_loadsz < sizeof (hdr)) {
11758 dtrace_dof_error(&hdr, "invalid load size");
11759 *errp = EINVAL;
11760 return (NULL);
11761 }
11762
11763 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
11764
11765 if (uread(p, dof, hdr.dofh_loadsz, uarg) != KERN_SUCCESS) {
11766 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
11767 *errp = EFAULT;
11768 return (NULL);
11769 }
11770
11771 return (dof);
11772 }
11773
11774 static dof_hdr_t *
11775 dtrace_dof_property(const char *name)
11776 {
11777 uchar_t *buf;
11778 uint64_t loadsz;
11779 unsigned int len, i;
11780 dof_hdr_t *dof;
11781
11782 /*
11783 * Unfortunately, array of values in .conf files are always (and
11784 * only) interpreted to be integer arrays. We must read our DOF
11785 * as an integer array, and then squeeze it into a byte array.
11786 */
11787 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
11788 name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
11789 return (NULL);
11790
11791 for (i = 0; i < len; i++)
11792 buf[i] = (uchar_t)(((int *)buf)[i]);
11793
11794 if (len < sizeof (dof_hdr_t)) {
11795 ddi_prop_free(buf);
11796 dtrace_dof_error(NULL, "truncated header");
11797 return (NULL);
11798 }
11799
11800 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
11801 ddi_prop_free(buf);
11802 dtrace_dof_error(NULL, "truncated DOF");
11803 return (NULL);
11804 }
11805
11806 if (loadsz >= (uint64_t)dtrace_dof_maxsize) {
11807 ddi_prop_free(buf);
11808 dtrace_dof_error(NULL, "oversized DOF");
11809 return (NULL);
11810 }
11811
11812 dof = dt_kmem_alloc_aligned(loadsz, 8, KM_SLEEP);
11813 bcopy(buf, dof, loadsz);
11814 ddi_prop_free(buf);
11815
11816 return (dof);
11817 }
11818
11819 static void
11820 dtrace_dof_destroy(dof_hdr_t *dof)
11821 {
11822 dt_kmem_free_aligned(dof, dof->dofh_loadsz);
11823 }
11824
11825 /*
11826 * Return the dof_sec_t pointer corresponding to a given section index. If the
11827 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
11828 * a type other than DOF_SECT_NONE is specified, the header is checked against
11829 * this type and NULL is returned if the types do not match.
11830 */
11831 static dof_sec_t *
11832 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
11833 {
11834 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
11835 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
11836
11837 if (i >= dof->dofh_secnum) {
11838 dtrace_dof_error(dof, "referenced section index is invalid");
11839 return (NULL);
11840 }
11841
11842 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
11843 dtrace_dof_error(dof, "referenced section is not loadable");
11844 return (NULL);
11845 }
11846
11847 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
11848 dtrace_dof_error(dof, "referenced section is the wrong type");
11849 return (NULL);
11850 }
11851
11852 return (sec);
11853 }
11854
11855 static dtrace_probedesc_t *
11856 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
11857 {
11858 dof_probedesc_t *probe;
11859 dof_sec_t *strtab;
11860 uintptr_t daddr = (uintptr_t)dof;
11861 uintptr_t str;
11862 size_t size;
11863
11864 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
11865 dtrace_dof_error(dof, "invalid probe section");
11866 return (NULL);
11867 }
11868
11869 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11870 dtrace_dof_error(dof, "bad alignment in probe description");
11871 return (NULL);
11872 }
11873
11874 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
11875 dtrace_dof_error(dof, "truncated probe description");
11876 return (NULL);
11877 }
11878
11879 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
11880 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
11881
11882 if (strtab == NULL)
11883 return (NULL);
11884
11885 str = daddr + strtab->dofs_offset;
11886 size = strtab->dofs_size;
11887
11888 if (probe->dofp_provider >= strtab->dofs_size) {
11889 dtrace_dof_error(dof, "corrupt probe provider");
11890 return (NULL);
11891 }
11892
11893 (void) strncpy(desc->dtpd_provider,
11894 (char *)(str + probe->dofp_provider),
11895 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11896
11897 /* APPLE NOTE: Darwin employs size bounded string operation. */
11898 desc->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
11899
11900 if (probe->dofp_mod >= strtab->dofs_size) {
11901 dtrace_dof_error(dof, "corrupt probe module");
11902 return (NULL);
11903 }
11904
11905 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11906 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11907
11908 /* APPLE NOTE: Darwin employs size bounded string operation. */
11909 desc->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
11910
11911 if (probe->dofp_func >= strtab->dofs_size) {
11912 dtrace_dof_error(dof, "corrupt probe function");
11913 return (NULL);
11914 }
11915
11916 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11917 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11918
11919 /* APPLE NOTE: Darwin employs size bounded string operation. */
11920 desc->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
11921
11922 if (probe->dofp_name >= strtab->dofs_size) {
11923 dtrace_dof_error(dof, "corrupt probe name");
11924 return (NULL);
11925 }
11926
11927 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11928 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11929
11930 /* APPLE NOTE: Darwin employs size bounded string operation. */
11931 desc->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
11932
11933 return (desc);
11934 }
11935
11936 static dtrace_difo_t *
11937 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11938 cred_t *cr)
11939 {
11940 dtrace_difo_t *dp;
11941 size_t ttl = 0;
11942 dof_difohdr_t *dofd;
11943 uintptr_t daddr = (uintptr_t)dof;
11944 size_t max_size = dtrace_difo_maxsize;
11945 uint_t i;
11946 int l, n;
11947
11948
11949 static const struct {
11950 int section;
11951 int bufoffs;
11952 int lenoffs;
11953 int entsize;
11954 int align;
11955 const char *msg;
11956 } difo[] = {
11957 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11958 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11959 sizeof (dif_instr_t), "multiple DIF sections" },
11960
11961 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11962 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11963 sizeof (uint64_t), "multiple integer tables" },
11964
11965 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11966 offsetof(dtrace_difo_t, dtdo_strlen), 0,
11967 sizeof (char), "multiple string tables" },
11968
11969 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11970 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11971 sizeof (uint_t), "multiple variable tables" },
11972
11973 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
11974 };
11975
11976 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11977 dtrace_dof_error(dof, "invalid DIFO header section");
11978 return (NULL);
11979 }
11980
11981 if (sec->dofs_align != sizeof (dof_secidx_t)) {
11982 dtrace_dof_error(dof, "bad alignment in DIFO header");
11983 return (NULL);
11984 }
11985
11986 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11987 sec->dofs_size % sizeof (dof_secidx_t)) {
11988 dtrace_dof_error(dof, "bad size in DIFO header");
11989 return (NULL);
11990 }
11991
11992 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11993 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11994
11995 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11996 dp->dtdo_rtype = dofd->dofd_rtype;
11997
11998 for (l = 0; l < n; l++) {
11999 dof_sec_t *subsec;
12000 void **bufp;
12001 uint32_t *lenp;
12002
12003 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12004 dofd->dofd_links[l])) == NULL)
12005 goto err; /* invalid section link */
12006
12007 if (ttl + subsec->dofs_size > max_size) {
12008 dtrace_dof_error(dof, "exceeds maximum size");
12009 goto err;
12010 }
12011
12012 ttl += subsec->dofs_size;
12013
12014 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12015
12016 if (subsec->dofs_type != (uint32_t)difo[i].section)
12017 continue;
12018
12019 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12020 dtrace_dof_error(dof, "section not loaded");
12021 goto err;
12022 }
12023
12024 if (subsec->dofs_align != (uint32_t)difo[i].align) {
12025 dtrace_dof_error(dof, "bad alignment");
12026 goto err;
12027 }
12028
12029 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12030 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12031
12032 if (*bufp != NULL) {
12033 dtrace_dof_error(dof, difo[i].msg);
12034 goto err;
12035 }
12036
12037 if ((uint32_t)difo[i].entsize != subsec->dofs_entsize) {
12038 dtrace_dof_error(dof, "entry size mismatch");
12039 goto err;
12040 }
12041
12042 if (subsec->dofs_entsize != 0 &&
12043 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12044 dtrace_dof_error(dof, "corrupt entry size");
12045 goto err;
12046 }
12047
12048 *lenp = subsec->dofs_size;
12049 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12050 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12051 *bufp, subsec->dofs_size);
12052
12053 if (subsec->dofs_entsize != 0)
12054 *lenp /= subsec->dofs_entsize;
12055
12056 break;
12057 }
12058
12059 /*
12060 * If we encounter a loadable DIFO sub-section that is not
12061 * known to us, assume this is a broken program and fail.
12062 */
12063 if (difo[i].section == DOF_SECT_NONE &&
12064 (subsec->dofs_flags & DOF_SECF_LOAD)) {
12065 dtrace_dof_error(dof, "unrecognized DIFO subsection");
12066 goto err;
12067 }
12068 }
12069
12070 if (dp->dtdo_buf == NULL) {
12071 /*
12072 * We can't have a DIF object without DIF text.
12073 */
12074 dtrace_dof_error(dof, "missing DIF text");
12075 goto err;
12076 }
12077
12078 /*
12079 * Before we validate the DIF object, run through the variable table
12080 * looking for the strings -- if any of their size are under, we'll set
12081 * their size to be the system-wide default string size. Note that
12082 * this should _not_ happen if the "strsize" option has been set --
12083 * in this case, the compiler should have set the size to reflect the
12084 * setting of the option.
12085 */
12086 for (i = 0; i < dp->dtdo_varlen; i++) {
12087 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12088 dtrace_diftype_t *t = &v->dtdv_type;
12089
12090 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12091 continue;
12092
12093 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12094 t->dtdt_size = dtrace_strsize_default;
12095 }
12096
12097 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12098 goto err;
12099
12100 dtrace_difo_init(dp, vstate);
12101 return (dp);
12102
12103 err:
12104 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12105 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12106 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12107 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12108
12109 kmem_free(dp, sizeof (dtrace_difo_t));
12110 return (NULL);
12111 }
12112
12113 static dtrace_predicate_t *
12114 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12115 cred_t *cr)
12116 {
12117 dtrace_difo_t *dp;
12118
12119 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12120 return (NULL);
12121
12122 return (dtrace_predicate_create(dp));
12123 }
12124
12125 static dtrace_actdesc_t *
12126 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12127 cred_t *cr)
12128 {
12129 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12130 dof_actdesc_t *desc;
12131 dof_sec_t *difosec;
12132 size_t offs;
12133 uintptr_t daddr = (uintptr_t)dof;
12134 uint64_t arg;
12135 dtrace_actkind_t kind;
12136
12137 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12138 dtrace_dof_error(dof, "invalid action section");
12139 return (NULL);
12140 }
12141
12142 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12143 dtrace_dof_error(dof, "truncated action description");
12144 return (NULL);
12145 }
12146
12147 if (sec->dofs_align != sizeof (uint64_t)) {
12148 dtrace_dof_error(dof, "bad alignment in action description");
12149 return (NULL);
12150 }
12151
12152 if (sec->dofs_size < sec->dofs_entsize) {
12153 dtrace_dof_error(dof, "section entry size exceeds total size");
12154 return (NULL);
12155 }
12156
12157 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12158 dtrace_dof_error(dof, "bad entry size in action description");
12159 return (NULL);
12160 }
12161
12162 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12163 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12164 return (NULL);
12165 }
12166
12167 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12168 desc = (dof_actdesc_t *)(daddr +
12169 (uintptr_t)sec->dofs_offset + offs);
12170 kind = (dtrace_actkind_t)desc->dofa_kind;
12171
12172 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12173 (kind != DTRACEACT_PRINTA || desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12174 (kind == DTRACEACT_DIFEXPR && desc->dofa_strtab != DOF_SECIDX_NONE))
12175 {
12176 dof_sec_t *strtab;
12177 char *str, *fmt;
12178 uint64_t i;
12179
12180 /*
12181 * The argument to these actions is an index into the
12182 * DOF string table. For printf()-like actions, this
12183 * is the format string. For print(), this is the
12184 * CTF type of the expression result.
12185 */
12186 if ((strtab = dtrace_dof_sect(dof,
12187 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12188 goto err;
12189
12190 str = (char *)((uintptr_t)dof +
12191 (uintptr_t)strtab->dofs_offset);
12192
12193 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12194 if (str[i] == '\0')
12195 break;
12196 }
12197
12198 if (i >= strtab->dofs_size) {
12199 dtrace_dof_error(dof, "bogus format string");
12200 goto err;
12201 }
12202
12203 if (i == desc->dofa_arg) {
12204 dtrace_dof_error(dof, "empty format string");
12205 goto err;
12206 }
12207
12208 i -= desc->dofa_arg;
12209 fmt = kmem_alloc(i + 1, KM_SLEEP);
12210 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12211 arg = (uint64_t)(uintptr_t)fmt;
12212 } else {
12213 if (kind == DTRACEACT_PRINTA) {
12214 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12215 arg = 0;
12216 } else {
12217 arg = desc->dofa_arg;
12218 }
12219 }
12220
12221 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12222 desc->dofa_uarg, arg);
12223
12224 if (last != NULL) {
12225 last->dtad_next = act;
12226 } else {
12227 first = act;
12228 }
12229
12230 last = act;
12231
12232 if (desc->dofa_difo == DOF_SECIDX_NONE)
12233 continue;
12234
12235 if ((difosec = dtrace_dof_sect(dof,
12236 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12237 goto err;
12238
12239 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12240
12241 if (act->dtad_difo == NULL)
12242 goto err;
12243 }
12244
12245 ASSERT(first != NULL);
12246 return (first);
12247
12248 err:
12249 for (act = first; act != NULL; act = next) {
12250 next = act->dtad_next;
12251 dtrace_actdesc_release(act, vstate);
12252 }
12253
12254 return (NULL);
12255 }
12256
12257 static dtrace_ecbdesc_t *
12258 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12259 cred_t *cr)
12260 {
12261 dtrace_ecbdesc_t *ep;
12262 dof_ecbdesc_t *ecb;
12263 dtrace_probedesc_t *desc;
12264 dtrace_predicate_t *pred = NULL;
12265
12266 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12267 dtrace_dof_error(dof, "truncated ECB description");
12268 return (NULL);
12269 }
12270
12271 if (sec->dofs_align != sizeof (uint64_t)) {
12272 dtrace_dof_error(dof, "bad alignment in ECB description");
12273 return (NULL);
12274 }
12275
12276 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12277 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12278
12279 if (sec == NULL)
12280 return (NULL);
12281
12282 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12283 ep->dted_uarg = ecb->dofe_uarg;
12284 desc = &ep->dted_probe;
12285
12286 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12287 goto err;
12288
12289 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12290 if ((sec = dtrace_dof_sect(dof,
12291 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12292 goto err;
12293
12294 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12295 goto err;
12296
12297 ep->dted_pred.dtpdd_predicate = pred;
12298 }
12299
12300 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12301 if ((sec = dtrace_dof_sect(dof,
12302 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12303 goto err;
12304
12305 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12306
12307 if (ep->dted_action == NULL)
12308 goto err;
12309 }
12310
12311 return (ep);
12312
12313 err:
12314 if (pred != NULL)
12315 dtrace_predicate_release(pred, vstate);
12316 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12317 return (NULL);
12318 }
12319
12320 /*
12321 * APPLE NOTE: dyld handles dof relocation.
12322 * Darwin does not need dtrace_dof_relocate()
12323 */
12324
12325 /*
12326 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12327 * header: it should be at the front of a memory region that is at least
12328 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12329 * size. It need not be validated in any other way.
12330 */
12331 static int
12332 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12333 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12334 {
12335 #pragma unused(ubase) /* __APPLE__ */
12336 uint64_t len = dof->dofh_loadsz, seclen;
12337 uintptr_t daddr = (uintptr_t)dof;
12338 dtrace_ecbdesc_t *ep;
12339 dtrace_enabling_t *enab;
12340 uint_t i;
12341
12342 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12343 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12344
12345 /*
12346 * Check the DOF header identification bytes. In addition to checking
12347 * valid settings, we also verify that unused bits/bytes are zeroed so
12348 * we can use them later without fear of regressing existing binaries.
12349 */
12350 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12351 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12352 dtrace_dof_error(dof, "DOF magic string mismatch");
12353 return (-1);
12354 }
12355
12356 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12357 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12358 dtrace_dof_error(dof, "DOF has invalid data model");
12359 return (-1);
12360 }
12361
12362 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12363 dtrace_dof_error(dof, "DOF encoding mismatch");
12364 return (-1);
12365 }
12366
12367 /*
12368 * APPLE NOTE: Darwin only supports DOF_VERSION_3 for now.
12369 */
12370 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_3) {
12371 dtrace_dof_error(dof, "DOF version mismatch");
12372 return (-1);
12373 }
12374
12375 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12376 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12377 return (-1);
12378 }
12379
12380 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12381 dtrace_dof_error(dof, "DOF uses too many integer registers");
12382 return (-1);
12383 }
12384
12385 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12386 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12387 return (-1);
12388 }
12389
12390 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12391 if (dof->dofh_ident[i] != 0) {
12392 dtrace_dof_error(dof, "DOF has invalid ident byte set");
12393 return (-1);
12394 }
12395 }
12396
12397 if (dof->dofh_flags & ~DOF_FL_VALID) {
12398 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12399 return (-1);
12400 }
12401
12402 if (dof->dofh_secsize == 0) {
12403 dtrace_dof_error(dof, "zero section header size");
12404 return (-1);
12405 }
12406
12407 /*
12408 * Check that the section headers don't exceed the amount of DOF
12409 * data. Note that we cast the section size and number of sections
12410 * to uint64_t's to prevent possible overflow in the multiplication.
12411 */
12412 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12413
12414 if (dof->dofh_secoff > len || seclen > len ||
12415 dof->dofh_secoff + seclen > len) {
12416 dtrace_dof_error(dof, "truncated section headers");
12417 return (-1);
12418 }
12419
12420 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12421 dtrace_dof_error(dof, "misaligned section headers");
12422 return (-1);
12423 }
12424
12425 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12426 dtrace_dof_error(dof, "misaligned section size");
12427 return (-1);
12428 }
12429
12430 /*
12431 * Take an initial pass through the section headers to be sure that
12432 * the headers don't have stray offsets. If the 'noprobes' flag is
12433 * set, do not permit sections relating to providers, probes, or args.
12434 */
12435 for (i = 0; i < dof->dofh_secnum; i++) {
12436 dof_sec_t *sec = (dof_sec_t *)(daddr +
12437 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12438
12439 if (noprobes) {
12440 switch (sec->dofs_type) {
12441 case DOF_SECT_PROVIDER:
12442 case DOF_SECT_PROBES:
12443 case DOF_SECT_PRARGS:
12444 case DOF_SECT_PROFFS:
12445 dtrace_dof_error(dof, "illegal sections "
12446 "for enabling");
12447 return (-1);
12448 }
12449 }
12450
12451 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12452 continue; /* just ignore non-loadable sections */
12453
12454 if (sec->dofs_align & (sec->dofs_align - 1)) {
12455 dtrace_dof_error(dof, "bad section alignment");
12456 return (-1);
12457 }
12458
12459 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12460 dtrace_dof_error(dof, "misaligned section");
12461 return (-1);
12462 }
12463
12464 if (sec->dofs_offset > len || sec->dofs_size > len ||
12465 sec->dofs_offset + sec->dofs_size > len) {
12466 dtrace_dof_error(dof, "corrupt section header");
12467 return (-1);
12468 }
12469
12470 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12471 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12472 dtrace_dof_error(dof, "non-terminating string table");
12473 return (-1);
12474 }
12475 }
12476
12477 /*
12478 * APPLE NOTE: We have no further relocation to perform.
12479 * All dof values are relative offsets.
12480 */
12481
12482 if ((enab = *enabp) == NULL)
12483 enab = *enabp = dtrace_enabling_create(vstate);
12484
12485 for (i = 0; i < dof->dofh_secnum; i++) {
12486 dof_sec_t *sec = (dof_sec_t *)(daddr +
12487 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12488
12489 if (sec->dofs_type != DOF_SECT_ECBDESC)
12490 continue;
12491
12492 /*
12493 * APPLE NOTE: Defend against gcc 4.0 botch on x86.
12494 * not all paths out of inlined dtrace_dof_ecbdesc
12495 * are checked for the NULL return value.
12496 * Check for NULL explicitly here.
12497 */
12498 ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr);
12499 if (ep == NULL) {
12500 dtrace_enabling_destroy(enab);
12501 *enabp = NULL;
12502 return (-1);
12503 }
12504
12505 dtrace_enabling_add(enab, ep);
12506 }
12507
12508 return (0);
12509 }
12510
12511 /*
12512 * Process DOF for any options. This routine assumes that the DOF has been
12513 * at least processed by dtrace_dof_slurp().
12514 */
12515 static int
12516 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12517 {
12518 uint_t i;
12519 int rval;
12520 uint32_t entsize;
12521 size_t offs;
12522 dof_optdesc_t *desc;
12523
12524 for (i = 0; i < dof->dofh_secnum; i++) {
12525 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12526 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12527
12528 if (sec->dofs_type != DOF_SECT_OPTDESC)
12529 continue;
12530
12531 if (sec->dofs_align != sizeof (uint64_t)) {
12532 dtrace_dof_error(dof, "bad alignment in "
12533 "option description");
12534 return (EINVAL);
12535 }
12536
12537 if ((entsize = sec->dofs_entsize) == 0) {
12538 dtrace_dof_error(dof, "zeroed option entry size");
12539 return (EINVAL);
12540 }
12541
12542 if (entsize < sizeof (dof_optdesc_t)) {
12543 dtrace_dof_error(dof, "bad option entry size");
12544 return (EINVAL);
12545 }
12546
12547 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12548 desc = (dof_optdesc_t *)((uintptr_t)dof +
12549 (uintptr_t)sec->dofs_offset + offs);
12550
12551 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12552 dtrace_dof_error(dof, "non-zero option string");
12553 return (EINVAL);
12554 }
12555
12556 if (desc->dofo_value == (uint64_t)DTRACEOPT_UNSET) {
12557 dtrace_dof_error(dof, "unset option");
12558 return (EINVAL);
12559 }
12560
12561 if ((rval = dtrace_state_option(state,
12562 desc->dofo_option, desc->dofo_value)) != 0) {
12563 dtrace_dof_error(dof, "rejected option");
12564 return (rval);
12565 }
12566 }
12567 }
12568
12569 return (0);
12570 }
12571
12572 /*
12573 * DTrace Consumer State Functions
12574 */
12575 static int
12576 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12577 {
12578 size_t hashsize, maxper, min_size, chunksize = dstate->dtds_chunksize;
12579 void *base;
12580 uintptr_t limit;
12581 dtrace_dynvar_t *dvar, *next, *start;
12582 size_t i;
12583
12584 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12585 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12586
12587 bzero(dstate, sizeof (dtrace_dstate_t));
12588
12589 if ((dstate->dtds_chunksize = chunksize) == 0)
12590 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12591
12592 VERIFY(dstate->dtds_chunksize < (LONG_MAX - sizeof (dtrace_dynhash_t)));
12593
12594 if (size < (min_size = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12595 size = min_size;
12596
12597 if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12598 return (ENOMEM);
12599
12600 dstate->dtds_size = size;
12601 dstate->dtds_base = base;
12602 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12603 bzero(dstate->dtds_percpu, (int)NCPU * sizeof (dtrace_dstate_percpu_t));
12604
12605 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12606
12607 if (hashsize != 1 && (hashsize & 1))
12608 hashsize--;
12609
12610 dstate->dtds_hashsize = hashsize;
12611 dstate->dtds_hash = dstate->dtds_base;
12612
12613 /*
12614 * Set all of our hash buckets to point to the single sink, and (if
12615 * it hasn't already been set), set the sink's hash value to be the
12616 * sink sentinel value. The sink is needed for dynamic variable
12617 * lookups to know that they have iterated over an entire, valid hash
12618 * chain.
12619 */
12620 for (i = 0; i < hashsize; i++)
12621 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12622
12623 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12624 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12625
12626 /*
12627 * Determine number of active CPUs. Divide free list evenly among
12628 * active CPUs.
12629 */
12630 start = (dtrace_dynvar_t *)
12631 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12632 limit = (uintptr_t)base + size;
12633
12634 VERIFY((uintptr_t)start < limit);
12635 VERIFY((uintptr_t)start >= (uintptr_t)base);
12636
12637 maxper = (limit - (uintptr_t)start) / (int)NCPU;
12638 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12639
12640 for (i = 0; i < NCPU; i++) {
12641 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12642
12643 /*
12644 * If we don't even have enough chunks to make it once through
12645 * NCPUs, we're just going to allocate everything to the first
12646 * CPU. And if we're on the last CPU, we're going to allocate
12647 * whatever is left over. In either case, we set the limit to
12648 * be the limit of the dynamic variable space.
12649 */
12650 if (maxper == 0 || i == NCPU - 1) {
12651 limit = (uintptr_t)base + size;
12652 start = NULL;
12653 } else {
12654 limit = (uintptr_t)start + maxper;
12655 start = (dtrace_dynvar_t *)limit;
12656 }
12657
12658 VERIFY(limit <= (uintptr_t)base + size);
12659
12660 for (;;) {
12661 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12662 dstate->dtds_chunksize);
12663
12664 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12665 break;
12666
12667 VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
12668 (uintptr_t)dvar <= (uintptr_t)base + size);
12669 dvar->dtdv_next = next;
12670 dvar = next;
12671 }
12672
12673 if (maxper == 0)
12674 break;
12675 }
12676
12677 return (0);
12678 }
12679
12680 static void
12681 dtrace_dstate_fini(dtrace_dstate_t *dstate)
12682 {
12683 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12684
12685 if (dstate->dtds_base == NULL)
12686 return;
12687
12688 kmem_free(dstate->dtds_base, dstate->dtds_size);
12689 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
12690 }
12691
12692 static void
12693 dtrace_vstate_fini(dtrace_vstate_t *vstate)
12694 {
12695 /*
12696 * Logical XOR, where are you?
12697 */
12698 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12699
12700 if (vstate->dtvs_nglobals > 0) {
12701 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12702 sizeof (dtrace_statvar_t *));
12703 }
12704
12705 if (vstate->dtvs_ntlocals > 0) {
12706 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12707 sizeof (dtrace_difv_t));
12708 }
12709
12710 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
12711
12712 if (vstate->dtvs_nlocals > 0) {
12713 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
12714 sizeof (dtrace_statvar_t *));
12715 }
12716 }
12717
12718 static void
12719 dtrace_state_clean(dtrace_state_t *state)
12720 {
12721 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
12722 return;
12723
12724 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
12725 dtrace_speculation_clean(state);
12726 }
12727
12728 static void
12729 dtrace_state_deadman(dtrace_state_t *state)
12730 {
12731 hrtime_t now;
12732
12733 dtrace_sync();
12734
12735 now = dtrace_gethrtime();
12736
12737 if (state != dtrace_anon.dta_state &&
12738 now - state->dts_laststatus >= dtrace_deadman_user)
12739 return;
12740
12741 /*
12742 * We must be sure that dts_alive never appears to be less than the
12743 * value upon entry to dtrace_state_deadman(), and because we lack a
12744 * dtrace_cas64(), we cannot store to it atomically. We thus instead
12745 * store INT64_MAX to it, followed by a memory barrier, followed by
12746 * the new value. This assures that dts_alive never appears to be
12747 * less than its true value, regardless of the order in which the
12748 * stores to the underlying storage are issued.
12749 */
12750 state->dts_alive = INT64_MAX;
12751 dtrace_membar_producer();
12752 state->dts_alive = now;
12753 }
12754
12755 static int
12756 dtrace_state_create(dev_t *devp, cred_t *cr, dtrace_state_t **new_state)
12757 {
12758 minor_t minor;
12759 major_t major;
12760 char c[30];
12761 dtrace_state_t *state;
12762 dtrace_optval_t *opt;
12763 int bufsize = (int)NCPU * sizeof (dtrace_buffer_t), i;
12764
12765 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12766 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12767
12768 /* Cause restart */
12769 *new_state = NULL;
12770
12771 /*
12772 * Darwin's DEVFS layer acquired the minor number for this "device" when it called
12773 * dtrace_devfs_clone_func(). At that time, dtrace_devfs_clone_func() proposed a minor number
12774 * (next unused according to vmem_alloc()) and then immediately put the number back in play
12775 * (by calling vmem_free()). Now that minor number is being used for an open, so committing it
12776 * to use. The following vmem_alloc() must deliver that same minor number. FIXME.
12777 */
12778
12779 minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
12780 VM_BESTFIT | VM_SLEEP);
12781
12782 if (NULL != devp) {
12783 ASSERT(getminor(*devp) == minor);
12784 if (getminor(*devp) != minor) {
12785 printf("dtrace_open: couldn't re-acquire vended minor number %d. Instead got %d\n",
12786 getminor(*devp), minor);
12787 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12788 return (ERESTART); /* can't reacquire */
12789 }
12790 } else {
12791 /* NULL==devp iff "Anonymous state" (see dtrace_anon_property),
12792 * so just vend the minor device number here de novo since no "open" has occurred. */
12793 }
12794
12795 if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
12796 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12797 return (EAGAIN); /* temporary resource shortage */
12798 }
12799
12800 state = ddi_get_soft_state(dtrace_softstate, minor);
12801 state->dts_epid = DTRACE_EPIDNONE + 1;
12802
12803 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
12804 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
12805 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12806
12807 if (devp != NULL) {
12808 major = getemajor(*devp);
12809 } else {
12810 major = ddi_driver_major(dtrace_devi);
12811 }
12812
12813 state->dts_dev = makedevice(major, minor);
12814
12815 if (devp != NULL)
12816 *devp = state->dts_dev;
12817
12818 /*
12819 * We allocate NCPU buffers. On the one hand, this can be quite
12820 * a bit of memory per instance (nearly 36K on a Starcat). On the
12821 * other hand, it saves an additional memory reference in the probe
12822 * path.
12823 */
12824 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
12825 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
12826 state->dts_cleaner = CYCLIC_NONE;
12827 state->dts_deadman = CYCLIC_NONE;
12828 state->dts_vstate.dtvs_state = state;
12829
12830 for (i = 0; i < DTRACEOPT_MAX; i++)
12831 state->dts_options[i] = DTRACEOPT_UNSET;
12832
12833 /*
12834 * Set the default options.
12835 */
12836 opt = state->dts_options;
12837 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
12838 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
12839 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
12840 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
12841 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
12842 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
12843 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
12844 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
12845 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
12846 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
12847 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
12848 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
12849 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
12850 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
12851
12852 state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
12853
12854 /*
12855 * Depending on the user credentials, we set flag bits which alter probe
12856 * visibility or the amount of destructiveness allowed. In the case of
12857 * actual anonymous tracing, or the possession of all privileges, all of
12858 * the normal checks are bypassed.
12859 */
12860 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
12861 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
12862 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
12863 } else {
12864 /*
12865 * Set up the credentials for this instantiation. We take a
12866 * hold on the credential to prevent it from disappearing on
12867 * us; this in turn prevents the zone_t referenced by this
12868 * credential from disappearing. This means that we can
12869 * examine the credential and the zone from probe context.
12870 */
12871 crhold(cr);
12872 state->dts_cred.dcr_cred = cr;
12873
12874 /*
12875 * CRA_PROC means "we have *some* privilege for dtrace" and
12876 * unlocks the use of variables like pid, zonename, etc.
12877 */
12878 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12879 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12880 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12881 }
12882
12883 /*
12884 * dtrace_user allows use of syscall and profile providers.
12885 * If the user also has proc_owner and/or proc_zone, we
12886 * extend the scope to include additional visibility and
12887 * destructive power.
12888 */
12889 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12890 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12891 state->dts_cred.dcr_visible |=
12892 DTRACE_CRV_ALLPROC;
12893
12894 state->dts_cred.dcr_action |=
12895 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12896 }
12897
12898 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12899 state->dts_cred.dcr_visible |=
12900 DTRACE_CRV_ALLZONE;
12901
12902 state->dts_cred.dcr_action |=
12903 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12904 }
12905
12906 /*
12907 * If we have all privs in whatever zone this is,
12908 * we can do destructive things to processes which
12909 * have altered credentials.
12910 *
12911 * APPLE NOTE: Darwin doesn't do zones.
12912 * Behave as if zone always has destructive privs.
12913 */
12914
12915 state->dts_cred.dcr_action |=
12916 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12917 }
12918
12919 /*
12920 * Holding the dtrace_kernel privilege also implies that
12921 * the user has the dtrace_user privilege from a visibility
12922 * perspective. But without further privileges, some
12923 * destructive actions are not available.
12924 */
12925 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12926 /*
12927 * Make all probes in all zones visible. However,
12928 * this doesn't mean that all actions become available
12929 * to all zones.
12930 */
12931 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12932 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12933
12934 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12935 DTRACE_CRA_PROC;
12936 /*
12937 * Holding proc_owner means that destructive actions
12938 * for *this* zone are allowed.
12939 */
12940 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12941 state->dts_cred.dcr_action |=
12942 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12943
12944 /*
12945 * Holding proc_zone means that destructive actions
12946 * for this user/group ID in all zones is allowed.
12947 */
12948 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12949 state->dts_cred.dcr_action |=
12950 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12951
12952 /*
12953 * If we have all privs in whatever zone this is,
12954 * we can do destructive things to processes which
12955 * have altered credentials.
12956 *
12957 * APPLE NOTE: Darwin doesn't do zones.
12958 * Behave as if zone always has destructive privs.
12959 */
12960 state->dts_cred.dcr_action |=
12961 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12962 }
12963
12964 /*
12965 * Holding the dtrace_proc privilege gives control over fasttrap
12966 * and pid providers. We need to grant wider destructive
12967 * privileges in the event that the user has proc_owner and/or
12968 * proc_zone.
12969 */
12970 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12971 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12972 state->dts_cred.dcr_action |=
12973 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12974
12975 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12976 state->dts_cred.dcr_action |=
12977 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12978 }
12979 }
12980
12981 *new_state = state;
12982 return(0); /* Success */
12983 }
12984
12985 static int
12986 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12987 {
12988 dtrace_optval_t *opt = state->dts_options, size;
12989 processorid_t cpu = 0;
12990 int flags = 0, rval;
12991
12992 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12993 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12994 ASSERT(which < DTRACEOPT_MAX);
12995 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12996 (state == dtrace_anon.dta_state &&
12997 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12998
12999 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13000 return (0);
13001
13002 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13003 cpu = opt[DTRACEOPT_CPU];
13004
13005 if (which == DTRACEOPT_SPECSIZE)
13006 flags |= DTRACEBUF_NOSWITCH;
13007
13008 if (which == DTRACEOPT_BUFSIZE) {
13009 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13010 flags |= DTRACEBUF_RING;
13011
13012 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13013 flags |= DTRACEBUF_FILL;
13014
13015 if (state != dtrace_anon.dta_state ||
13016 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13017 flags |= DTRACEBUF_INACTIVE;
13018 }
13019
13020 for (size = opt[which]; (size_t)size >= sizeof (uint64_t); size >>= 1) {
13021 /*
13022 * The size must be 8-byte aligned. If the size is not 8-byte
13023 * aligned, drop it down by the difference.
13024 */
13025 if (size & (sizeof (uint64_t) - 1))
13026 size -= size & (sizeof (uint64_t) - 1);
13027
13028 if (size < state->dts_reserve) {
13029 /*
13030 * Buffers always must be large enough to accommodate
13031 * their prereserved space. We return E2BIG instead
13032 * of ENOMEM in this case to allow for user-level
13033 * software to differentiate the cases.
13034 */
13035 return (E2BIG);
13036 }
13037
13038 rval = dtrace_buffer_alloc(buf, size, flags, cpu);
13039
13040 if (rval != ENOMEM) {
13041 opt[which] = size;
13042 return (rval);
13043 }
13044
13045 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13046 return (rval);
13047 }
13048
13049 return (ENOMEM);
13050 }
13051
13052 static int
13053 dtrace_state_buffers(dtrace_state_t *state)
13054 {
13055 dtrace_speculation_t *spec = state->dts_speculations;
13056 int rval, i;
13057
13058 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13059 DTRACEOPT_BUFSIZE)) != 0)
13060 return (rval);
13061
13062 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13063 DTRACEOPT_AGGSIZE)) != 0)
13064 return (rval);
13065
13066 for (i = 0; i < state->dts_nspeculations; i++) {
13067 if ((rval = dtrace_state_buffer(state,
13068 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13069 return (rval);
13070 }
13071
13072 return (0);
13073 }
13074
13075 static void
13076 dtrace_state_prereserve(dtrace_state_t *state)
13077 {
13078 dtrace_ecb_t *ecb;
13079 dtrace_probe_t *probe;
13080
13081 state->dts_reserve = 0;
13082
13083 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13084 return;
13085
13086 /*
13087 * If our buffer policy is a "fill" buffer policy, we need to set the
13088 * prereserved space to be the space required by the END probes.
13089 */
13090 probe = dtrace_probes[dtrace_probeid_end - 1];
13091 ASSERT(probe != NULL);
13092
13093 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13094 if (ecb->dte_state != state)
13095 continue;
13096
13097 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13098 }
13099 }
13100
13101 static int
13102 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13103 {
13104 dtrace_optval_t *opt = state->dts_options, sz, nspec;
13105 dtrace_speculation_t *spec;
13106 dtrace_buffer_t *buf;
13107 cyc_handler_t hdlr;
13108 cyc_time_t when;
13109 int rval = 0, i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
13110 dtrace_icookie_t cookie;
13111
13112 lck_mtx_lock(&cpu_lock);
13113 lck_mtx_lock(&dtrace_lock);
13114
13115 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13116 rval = EBUSY;
13117 goto out;
13118 }
13119
13120 /*
13121 * Before we can perform any checks, we must prime all of the
13122 * retained enablings that correspond to this state.
13123 */
13124 dtrace_enabling_prime(state);
13125
13126 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13127 rval = EACCES;
13128 goto out;
13129 }
13130
13131 dtrace_state_prereserve(state);
13132
13133 /*
13134 * Now we want to do is try to allocate our speculations.
13135 * We do not automatically resize the number of speculations; if
13136 * this fails, we will fail the operation.
13137 */
13138 nspec = opt[DTRACEOPT_NSPEC];
13139 ASSERT(nspec != DTRACEOPT_UNSET);
13140
13141 if (nspec > INT_MAX) {
13142 rval = ENOMEM;
13143 goto out;
13144 }
13145
13146 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
13147
13148 if (spec == NULL) {
13149 rval = ENOMEM;
13150 goto out;
13151 }
13152
13153 state->dts_speculations = spec;
13154 state->dts_nspeculations = (int)nspec;
13155
13156 for (i = 0; i < nspec; i++) {
13157 if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
13158 rval = ENOMEM;
13159 goto err;
13160 }
13161
13162 spec[i].dtsp_buffer = buf;
13163 }
13164
13165 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13166 if (dtrace_anon.dta_state == NULL) {
13167 rval = ENOENT;
13168 goto out;
13169 }
13170
13171 if (state->dts_necbs != 0) {
13172 rval = EALREADY;
13173 goto out;
13174 }
13175
13176 state->dts_anon = dtrace_anon_grab();
13177 ASSERT(state->dts_anon != NULL);
13178 state = state->dts_anon;
13179
13180 /*
13181 * We want "grabanon" to be set in the grabbed state, so we'll
13182 * copy that option value from the grabbing state into the
13183 * grabbed state.
13184 */
13185 state->dts_options[DTRACEOPT_GRABANON] =
13186 opt[DTRACEOPT_GRABANON];
13187
13188 *cpu = dtrace_anon.dta_beganon;
13189
13190 /*
13191 * If the anonymous state is active (as it almost certainly
13192 * is if the anonymous enabling ultimately matched anything),
13193 * we don't allow any further option processing -- but we
13194 * don't return failure.
13195 */
13196 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13197 goto out;
13198 }
13199
13200 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13201 opt[DTRACEOPT_AGGSIZE] != 0) {
13202 if (state->dts_aggregations == NULL) {
13203 /*
13204 * We're not going to create an aggregation buffer
13205 * because we don't have any ECBs that contain
13206 * aggregations -- set this option to 0.
13207 */
13208 opt[DTRACEOPT_AGGSIZE] = 0;
13209 } else {
13210 /*
13211 * If we have an aggregation buffer, we must also have
13212 * a buffer to use as scratch.
13213 */
13214 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13215 (size_t)opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13216 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13217 }
13218 }
13219 }
13220
13221 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13222 opt[DTRACEOPT_SPECSIZE] != 0) {
13223 if (!state->dts_speculates) {
13224 /*
13225 * We're not going to create speculation buffers
13226 * because we don't have any ECBs that actually
13227 * speculate -- set the speculation size to 0.
13228 */
13229 opt[DTRACEOPT_SPECSIZE] = 0;
13230 }
13231 }
13232
13233 /*
13234 * The bare minimum size for any buffer that we're actually going to
13235 * do anything to is sizeof (uint64_t).
13236 */
13237 sz = sizeof (uint64_t);
13238
13239 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13240 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13241 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13242 /*
13243 * A buffer size has been explicitly set to 0 (or to a size
13244 * that will be adjusted to 0) and we need the space -- we
13245 * need to return failure. We return ENOSPC to differentiate
13246 * it from failing to allocate a buffer due to failure to meet
13247 * the reserve (for which we return E2BIG).
13248 */
13249 rval = ENOSPC;
13250 goto out;
13251 }
13252
13253 if ((rval = dtrace_state_buffers(state)) != 0)
13254 goto err;
13255
13256 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13257 sz = dtrace_dstate_defsize;
13258
13259 do {
13260 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13261
13262 if (rval == 0)
13263 break;
13264
13265 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13266 goto err;
13267 } while (sz >>= 1);
13268
13269 opt[DTRACEOPT_DYNVARSIZE] = sz;
13270
13271 if (rval != 0)
13272 goto err;
13273
13274 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13275 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13276
13277 if (opt[DTRACEOPT_CLEANRATE] == 0)
13278 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13279
13280 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13281 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13282
13283 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13284 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13285
13286 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13287 hdlr.cyh_arg = state;
13288 hdlr.cyh_level = CY_LOW_LEVEL;
13289
13290 when.cyt_when = 0;
13291 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13292
13293 state->dts_cleaner = cyclic_add(&hdlr, &when);
13294
13295 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13296 hdlr.cyh_arg = state;
13297 hdlr.cyh_level = CY_LOW_LEVEL;
13298
13299 when.cyt_when = 0;
13300 when.cyt_interval = dtrace_deadman_interval;
13301
13302 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13303 state->dts_deadman = cyclic_add(&hdlr, &when);
13304
13305 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13306
13307 /*
13308 * Now it's time to actually fire the BEGIN probe. We need to disable
13309 * interrupts here both to record the CPU on which we fired the BEGIN
13310 * probe (the data from this CPU will be processed first at user
13311 * level) and to manually activate the buffer for this CPU.
13312 */
13313 cookie = dtrace_interrupt_disable();
13314 *cpu = CPU->cpu_id;
13315 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13316 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13317
13318 dtrace_probe(dtrace_probeid_begin,
13319 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13320 dtrace_interrupt_enable(cookie);
13321 /*
13322 * We may have had an exit action from a BEGIN probe; only change our
13323 * state to ACTIVE if we're still in WARMUP.
13324 */
13325 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13326 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13327
13328 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13329 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13330
13331 /*
13332 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13333 * want each CPU to transition its principal buffer out of the
13334 * INACTIVE state. Doing this assures that no CPU will suddenly begin
13335 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13336 * atomically transition from processing none of a state's ECBs to
13337 * processing all of them.
13338 */
13339 dtrace_xcall(DTRACE_CPUALL,
13340 (dtrace_xcall_t)dtrace_buffer_activate, state);
13341 goto out;
13342
13343 err:
13344 dtrace_buffer_free(state->dts_buffer);
13345 dtrace_buffer_free(state->dts_aggbuffer);
13346
13347 if ((nspec = state->dts_nspeculations) == 0) {
13348 ASSERT(state->dts_speculations == NULL);
13349 goto out;
13350 }
13351
13352 spec = state->dts_speculations;
13353 ASSERT(spec != NULL);
13354
13355 for (i = 0; i < state->dts_nspeculations; i++) {
13356 if ((buf = spec[i].dtsp_buffer) == NULL)
13357 break;
13358
13359 dtrace_buffer_free(buf);
13360 kmem_free(buf, bufsize);
13361 }
13362
13363 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13364 state->dts_nspeculations = 0;
13365 state->dts_speculations = NULL;
13366
13367 out:
13368 lck_mtx_unlock(&dtrace_lock);
13369 lck_mtx_unlock(&cpu_lock);
13370
13371 return (rval);
13372 }
13373
13374 static int
13375 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13376 {
13377 dtrace_icookie_t cookie;
13378
13379 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13380
13381 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13382 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13383 return (EINVAL);
13384
13385 /*
13386 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13387 * to be sure that every CPU has seen it. See below for the details
13388 * on why this is done.
13389 */
13390 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13391 dtrace_sync();
13392
13393 /*
13394 * By this point, it is impossible for any CPU to be still processing
13395 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
13396 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13397 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
13398 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13399 * iff we're in the END probe.
13400 */
13401 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13402 dtrace_sync();
13403 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13404
13405 /*
13406 * Finally, we can release the reserve and call the END probe. We
13407 * disable interrupts across calling the END probe to allow us to
13408 * return the CPU on which we actually called the END probe. This
13409 * allows user-land to be sure that this CPU's principal buffer is
13410 * processed last.
13411 */
13412 state->dts_reserve = 0;
13413
13414 cookie = dtrace_interrupt_disable();
13415 *cpu = CPU->cpu_id;
13416 dtrace_probe(dtrace_probeid_end,
13417 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13418 dtrace_interrupt_enable(cookie);
13419
13420 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13421 dtrace_sync();
13422
13423 return (0);
13424 }
13425
13426 static int
13427 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13428 dtrace_optval_t val)
13429 {
13430 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13431
13432 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13433 return (EBUSY);
13434
13435 if (option >= DTRACEOPT_MAX)
13436 return (EINVAL);
13437
13438 if (option != DTRACEOPT_CPU && val < 0)
13439 return (EINVAL);
13440
13441 switch (option) {
13442 case DTRACEOPT_DESTRUCTIVE:
13443 /*
13444 * Prevent consumers from enabling destructive actions if DTrace
13445 * is running in a restricted environment, or if actions are
13446 * disallowed.
13447 */
13448 if (dtrace_is_restricted() || dtrace_destructive_disallow)
13449 return (EACCES);
13450
13451 state->dts_cred.dcr_destructive = 1;
13452 break;
13453
13454 case DTRACEOPT_BUFSIZE:
13455 case DTRACEOPT_DYNVARSIZE:
13456 case DTRACEOPT_AGGSIZE:
13457 case DTRACEOPT_SPECSIZE:
13458 case DTRACEOPT_STRSIZE:
13459 if (val < 0)
13460 return (EINVAL);
13461
13462 if (val >= LONG_MAX) {
13463 /*
13464 * If this is an otherwise negative value, set it to
13465 * the highest multiple of 128m less than LONG_MAX.
13466 * Technically, we're adjusting the size without
13467 * regard to the buffer resizing policy, but in fact,
13468 * this has no effect -- if we set the buffer size to
13469 * ~LONG_MAX and the buffer policy is ultimately set to
13470 * be "manual", the buffer allocation is guaranteed to
13471 * fail, if only because the allocation requires two
13472 * buffers. (We set the the size to the highest
13473 * multiple of 128m because it ensures that the size
13474 * will remain a multiple of a megabyte when
13475 * repeatedly halved -- all the way down to 15m.)
13476 */
13477 val = LONG_MAX - (1 << 27) + 1;
13478 }
13479 }
13480
13481 state->dts_options[option] = val;
13482
13483 return (0);
13484 }
13485
13486 static void
13487 dtrace_state_destroy(dtrace_state_t *state)
13488 {
13489 dtrace_ecb_t *ecb;
13490 dtrace_vstate_t *vstate = &state->dts_vstate;
13491 minor_t minor = getminor(state->dts_dev);
13492 int i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
13493 dtrace_speculation_t *spec = state->dts_speculations;
13494 int nspec = state->dts_nspeculations;
13495 uint32_t match;
13496
13497 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13498 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13499
13500 /*
13501 * First, retract any retained enablings for this state.
13502 */
13503 dtrace_enabling_retract(state);
13504 ASSERT(state->dts_nretained == 0);
13505
13506 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13507 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13508 /*
13509 * We have managed to come into dtrace_state_destroy() on a
13510 * hot enabling -- almost certainly because of a disorderly
13511 * shutdown of a consumer. (That is, a consumer that is
13512 * exiting without having called dtrace_stop().) In this case,
13513 * we're going to set our activity to be KILLED, and then
13514 * issue a sync to be sure that everyone is out of probe
13515 * context before we start blowing away ECBs.
13516 */
13517 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13518 dtrace_sync();
13519 }
13520
13521 /*
13522 * Release the credential hold we took in dtrace_state_create().
13523 */
13524 if (state->dts_cred.dcr_cred != NULL)
13525 crfree(state->dts_cred.dcr_cred);
13526
13527 /*
13528 * Now we can safely disable and destroy any enabled probes. Because
13529 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13530 * (especially if they're all enabled), we take two passes through the
13531 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13532 * in the second we disable whatever is left over.
13533 */
13534 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13535 for (i = 0; i < state->dts_necbs; i++) {
13536 if ((ecb = state->dts_ecbs[i]) == NULL)
13537 continue;
13538
13539 if (match && ecb->dte_probe != NULL) {
13540 dtrace_probe_t *probe = ecb->dte_probe;
13541 dtrace_provider_t *prov = probe->dtpr_provider;
13542
13543 if (!(prov->dtpv_priv.dtpp_flags & match))
13544 continue;
13545 }
13546
13547 dtrace_ecb_disable(ecb);
13548 dtrace_ecb_destroy(ecb);
13549 }
13550
13551 if (!match)
13552 break;
13553 }
13554
13555 /*
13556 * Before we free the buffers, perform one more sync to assure that
13557 * every CPU is out of probe context.
13558 */
13559 dtrace_sync();
13560
13561 dtrace_buffer_free(state->dts_buffer);
13562 dtrace_buffer_free(state->dts_aggbuffer);
13563
13564 for (i = 0; i < nspec; i++)
13565 dtrace_buffer_free(spec[i].dtsp_buffer);
13566
13567 if (state->dts_cleaner != CYCLIC_NONE)
13568 cyclic_remove(state->dts_cleaner);
13569
13570 if (state->dts_deadman != CYCLIC_NONE)
13571 cyclic_remove(state->dts_deadman);
13572
13573 dtrace_dstate_fini(&vstate->dtvs_dynvars);
13574 dtrace_vstate_fini(vstate);
13575 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13576
13577 if (state->dts_aggregations != NULL) {
13578 #if DEBUG
13579 for (i = 0; i < state->dts_naggregations; i++)
13580 ASSERT(state->dts_aggregations[i] == NULL);
13581 #endif
13582 ASSERT(state->dts_naggregations > 0);
13583 kmem_free(state->dts_aggregations,
13584 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13585 }
13586
13587 kmem_free(state->dts_buffer, bufsize);
13588 kmem_free(state->dts_aggbuffer, bufsize);
13589
13590 for (i = 0; i < nspec; i++)
13591 kmem_free(spec[i].dtsp_buffer, bufsize);
13592
13593 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13594
13595 dtrace_format_destroy(state);
13596
13597 vmem_destroy(state->dts_aggid_arena);
13598 ddi_soft_state_free(dtrace_softstate, minor);
13599 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13600 }
13601
13602 /*
13603 * DTrace Anonymous Enabling Functions
13604 */
13605 static dtrace_state_t *
13606 dtrace_anon_grab(void)
13607 {
13608 dtrace_state_t *state;
13609
13610 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13611
13612 if ((state = dtrace_anon.dta_state) == NULL) {
13613 ASSERT(dtrace_anon.dta_enabling == NULL);
13614 return (NULL);
13615 }
13616
13617 ASSERT(dtrace_anon.dta_enabling != NULL);
13618 ASSERT(dtrace_retained != NULL);
13619
13620 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
13621 dtrace_anon.dta_enabling = NULL;
13622 dtrace_anon.dta_state = NULL;
13623
13624 return (state);
13625 }
13626
13627 static void
13628 dtrace_anon_property(void)
13629 {
13630 int i, rv;
13631 dtrace_state_t *state;
13632 dof_hdr_t *dof;
13633 char c[32]; /* enough for "dof-data-" + digits */
13634
13635 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13636 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13637
13638 for (i = 0; ; i++) {
13639 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
13640
13641 dtrace_err_verbose = 1;
13642
13643 if ((dof = dtrace_dof_property(c)) == NULL) {
13644 dtrace_err_verbose = 0;
13645 break;
13646 }
13647
13648 /*
13649 * We want to create anonymous state, so we need to transition
13650 * the kernel debugger to indicate that DTrace is active. If
13651 * this fails (e.g. because the debugger has modified text in
13652 * some way), we won't continue with the processing.
13653 */
13654 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13655 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
13656 "enabling ignored.");
13657 dtrace_dof_destroy(dof);
13658 break;
13659 }
13660
13661 /*
13662 * If we haven't allocated an anonymous state, we'll do so now.
13663 */
13664 if ((state = dtrace_anon.dta_state) == NULL) {
13665 rv = dtrace_state_create(NULL, NULL, &state);
13666 dtrace_anon.dta_state = state;
13667 if (rv != 0 || state == NULL) {
13668 /*
13669 * This basically shouldn't happen: the only
13670 * failure mode from dtrace_state_create() is a
13671 * failure of ddi_soft_state_zalloc() that
13672 * itself should never happen. Still, the
13673 * interface allows for a failure mode, and
13674 * we want to fail as gracefully as possible:
13675 * we'll emit an error message and cease
13676 * processing anonymous state in this case.
13677 */
13678 cmn_err(CE_WARN, "failed to create "
13679 "anonymous state");
13680 dtrace_dof_destroy(dof);
13681 break;
13682 }
13683 }
13684
13685 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
13686 &dtrace_anon.dta_enabling, 0, B_TRUE);
13687
13688 if (rv == 0)
13689 rv = dtrace_dof_options(dof, state);
13690
13691 dtrace_err_verbose = 0;
13692 dtrace_dof_destroy(dof);
13693
13694 if (rv != 0) {
13695 /*
13696 * This is malformed DOF; chuck any anonymous state
13697 * that we created.
13698 */
13699 ASSERT(dtrace_anon.dta_enabling == NULL);
13700 dtrace_state_destroy(state);
13701 dtrace_anon.dta_state = NULL;
13702 break;
13703 }
13704
13705 ASSERT(dtrace_anon.dta_enabling != NULL);
13706 }
13707
13708 if (dtrace_anon.dta_enabling != NULL) {
13709 int rval;
13710
13711 /*
13712 * dtrace_enabling_retain() can only fail because we are
13713 * trying to retain more enablings than are allowed -- but
13714 * we only have one anonymous enabling, and we are guaranteed
13715 * to be allowed at least one retained enabling; we assert
13716 * that dtrace_enabling_retain() returns success.
13717 */
13718 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
13719 ASSERT(rval == 0);
13720
13721 dtrace_enabling_dump(dtrace_anon.dta_enabling);
13722 }
13723 }
13724
13725 /*
13726 * DTrace Helper Functions
13727 */
13728 static void
13729 dtrace_helper_trace(dtrace_helper_action_t *helper,
13730 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
13731 {
13732 uint32_t size, next, nnext;
13733 int i;
13734 dtrace_helptrace_t *ent;
13735 uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13736
13737 if (!dtrace_helptrace_enabled)
13738 return;
13739
13740 ASSERT((uint32_t)vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
13741
13742 /*
13743 * What would a tracing framework be without its own tracing
13744 * framework? (Well, a hell of a lot simpler, for starters...)
13745 */
13746 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
13747 sizeof (uint64_t) - sizeof (uint64_t);
13748
13749 /*
13750 * Iterate until we can allocate a slot in the trace buffer.
13751 */
13752 do {
13753 next = dtrace_helptrace_next;
13754
13755 if (next + size < dtrace_helptrace_bufsize) {
13756 nnext = next + size;
13757 } else {
13758 nnext = size;
13759 }
13760 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
13761
13762 /*
13763 * We have our slot; fill it in.
13764 */
13765 if (nnext == size)
13766 next = 0;
13767
13768 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
13769 ent->dtht_helper = helper;
13770 ent->dtht_where = where;
13771 ent->dtht_nlocals = vstate->dtvs_nlocals;
13772
13773 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
13774 mstate->dtms_fltoffs : -1;
13775 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
13776 ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
13777
13778 for (i = 0; i < vstate->dtvs_nlocals; i++) {
13779 dtrace_statvar_t *svar;
13780
13781 if ((svar = vstate->dtvs_locals[i]) == NULL)
13782 continue;
13783
13784 ASSERT(svar->dtsv_size >= (int)NCPU * sizeof (uint64_t));
13785 ent->dtht_locals[i] =
13786 ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
13787 }
13788 }
13789
13790 static uint64_t
13791 dtrace_helper(int which, dtrace_mstate_t *mstate,
13792 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
13793 {
13794 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13795 uint64_t sarg0 = mstate->dtms_arg[0];
13796 uint64_t sarg1 = mstate->dtms_arg[1];
13797 uint64_t rval = 0;
13798 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
13799 dtrace_helper_action_t *helper;
13800 dtrace_vstate_t *vstate;
13801 dtrace_difo_t *pred;
13802 int i, trace = dtrace_helptrace_enabled;
13803
13804 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
13805
13806 if (helpers == NULL)
13807 return (0);
13808
13809 if ((helper = helpers->dthps_actions[which]) == NULL)
13810 return (0);
13811
13812 vstate = &helpers->dthps_vstate;
13813 mstate->dtms_arg[0] = arg0;
13814 mstate->dtms_arg[1] = arg1;
13815
13816 /*
13817 * Now iterate over each helper. If its predicate evaluates to 'true',
13818 * we'll call the corresponding actions. Note that the below calls
13819 * to dtrace_dif_emulate() may set faults in machine state. This is
13820 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
13821 * the stored DIF offset with its own (which is the desired behavior).
13822 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
13823 * from machine state; this is okay, too.
13824 */
13825 for (; helper != NULL; helper = helper->dtha_next) {
13826 if ((pred = helper->dtha_predicate) != NULL) {
13827 if (trace)
13828 dtrace_helper_trace(helper, mstate, vstate, 0);
13829
13830 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
13831 goto next;
13832
13833 if (*flags & CPU_DTRACE_FAULT)
13834 goto err;
13835 }
13836
13837 for (i = 0; i < helper->dtha_nactions; i++) {
13838 if (trace)
13839 dtrace_helper_trace(helper,
13840 mstate, vstate, i + 1);
13841
13842 rval = dtrace_dif_emulate(helper->dtha_actions[i],
13843 mstate, vstate, state);
13844
13845 if (*flags & CPU_DTRACE_FAULT)
13846 goto err;
13847 }
13848
13849 next:
13850 if (trace)
13851 dtrace_helper_trace(helper, mstate, vstate,
13852 DTRACE_HELPTRACE_NEXT);
13853 }
13854
13855 if (trace)
13856 dtrace_helper_trace(helper, mstate, vstate,
13857 DTRACE_HELPTRACE_DONE);
13858
13859 /*
13860 * Restore the arg0 that we saved upon entry.
13861 */
13862 mstate->dtms_arg[0] = sarg0;
13863 mstate->dtms_arg[1] = sarg1;
13864
13865 return (rval);
13866
13867 err:
13868 if (trace)
13869 dtrace_helper_trace(helper, mstate, vstate,
13870 DTRACE_HELPTRACE_ERR);
13871
13872 /*
13873 * Restore the arg0 that we saved upon entry.
13874 */
13875 mstate->dtms_arg[0] = sarg0;
13876 mstate->dtms_arg[1] = sarg1;
13877
13878 return (0);
13879 }
13880
13881 static void
13882 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13883 dtrace_vstate_t *vstate)
13884 {
13885 int i;
13886
13887 if (helper->dtha_predicate != NULL)
13888 dtrace_difo_release(helper->dtha_predicate, vstate);
13889
13890 for (i = 0; i < helper->dtha_nactions; i++) {
13891 ASSERT(helper->dtha_actions[i] != NULL);
13892 dtrace_difo_release(helper->dtha_actions[i], vstate);
13893 }
13894
13895 kmem_free(helper->dtha_actions,
13896 helper->dtha_nactions * sizeof (dtrace_difo_t *));
13897 kmem_free(helper, sizeof (dtrace_helper_action_t));
13898 }
13899
13900 static int
13901 dtrace_helper_destroygen(proc_t* p, int gen)
13902 {
13903 dtrace_helpers_t *help = p->p_dtrace_helpers;
13904 dtrace_vstate_t *vstate;
13905 uint_t i;
13906
13907 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13908
13909 if (help == NULL || gen > help->dthps_generation)
13910 return (EINVAL);
13911
13912 vstate = &help->dthps_vstate;
13913
13914 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13915 dtrace_helper_action_t *last = NULL, *h, *next;
13916
13917 for (h = help->dthps_actions[i]; h != NULL; h = next) {
13918 next = h->dtha_next;
13919
13920 if (h->dtha_generation == gen) {
13921 if (last != NULL) {
13922 last->dtha_next = next;
13923 } else {
13924 help->dthps_actions[i] = next;
13925 }
13926
13927 dtrace_helper_action_destroy(h, vstate);
13928 } else {
13929 last = h;
13930 }
13931 }
13932 }
13933
13934 /*
13935 * Interate until we've cleared out all helper providers with the
13936 * given generation number.
13937 */
13938 for (;;) {
13939 dtrace_helper_provider_t *prov = NULL;
13940
13941 /*
13942 * Look for a helper provider with the right generation. We
13943 * have to start back at the beginning of the list each time
13944 * because we drop dtrace_lock. It's unlikely that we'll make
13945 * more than two passes.
13946 */
13947 for (i = 0; i < help->dthps_nprovs; i++) {
13948 prov = help->dthps_provs[i];
13949
13950 if (prov->dthp_generation == gen)
13951 break;
13952 }
13953
13954 /*
13955 * If there were no matches, we're done.
13956 */
13957 if (i == help->dthps_nprovs)
13958 break;
13959
13960 /*
13961 * Move the last helper provider into this slot.
13962 */
13963 help->dthps_nprovs--;
13964 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13965 help->dthps_provs[help->dthps_nprovs] = NULL;
13966
13967 lck_mtx_unlock(&dtrace_lock);
13968
13969 /*
13970 * If we have a meta provider, remove this helper provider.
13971 */
13972 lck_mtx_lock(&dtrace_meta_lock);
13973 if (dtrace_meta_pid != NULL) {
13974 ASSERT(dtrace_deferred_pid == NULL);
13975 dtrace_helper_provider_remove(&prov->dthp_prov,
13976 p->p_pid);
13977 }
13978 lck_mtx_unlock(&dtrace_meta_lock);
13979
13980 dtrace_helper_provider_destroy(prov);
13981
13982 lck_mtx_lock(&dtrace_lock);
13983 }
13984
13985 return (0);
13986 }
13987
13988 static int
13989 dtrace_helper_validate(dtrace_helper_action_t *helper)
13990 {
13991 int err = 0, i;
13992 dtrace_difo_t *dp;
13993
13994 if ((dp = helper->dtha_predicate) != NULL)
13995 err += dtrace_difo_validate_helper(dp);
13996
13997 for (i = 0; i < helper->dtha_nactions; i++)
13998 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13999
14000 return (err == 0);
14001 }
14002
14003 static int
14004 dtrace_helper_action_add(proc_t* p, int which, dtrace_ecbdesc_t *ep)
14005 {
14006 dtrace_helpers_t *help;
14007 dtrace_helper_action_t *helper, *last;
14008 dtrace_actdesc_t *act;
14009 dtrace_vstate_t *vstate;
14010 dtrace_predicate_t *pred;
14011 int count = 0, nactions = 0, i;
14012
14013 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14014 return (EINVAL);
14015
14016 help = p->p_dtrace_helpers;
14017 last = help->dthps_actions[which];
14018 vstate = &help->dthps_vstate;
14019
14020 for (count = 0; last != NULL; last = last->dtha_next) {
14021 count++;
14022 if (last->dtha_next == NULL)
14023 break;
14024 }
14025
14026 /*
14027 * If we already have dtrace_helper_actions_max helper actions for this
14028 * helper action type, we'll refuse to add a new one.
14029 */
14030 if (count >= dtrace_helper_actions_max)
14031 return (ENOSPC);
14032
14033 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14034 helper->dtha_generation = help->dthps_generation;
14035
14036 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14037 ASSERT(pred->dtp_difo != NULL);
14038 dtrace_difo_hold(pred->dtp_difo);
14039 helper->dtha_predicate = pred->dtp_difo;
14040 }
14041
14042 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14043 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14044 goto err;
14045
14046 if (act->dtad_difo == NULL)
14047 goto err;
14048
14049 nactions++;
14050 }
14051
14052 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14053 (helper->dtha_nactions = nactions), KM_SLEEP);
14054
14055 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14056 dtrace_difo_hold(act->dtad_difo);
14057 helper->dtha_actions[i++] = act->dtad_difo;
14058 }
14059
14060 if (!dtrace_helper_validate(helper))
14061 goto err;
14062
14063 if (last == NULL) {
14064 help->dthps_actions[which] = helper;
14065 } else {
14066 last->dtha_next = helper;
14067 }
14068
14069 if ((uint32_t)vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14070 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14071 dtrace_helptrace_next = 0;
14072 }
14073
14074 return (0);
14075 err:
14076 dtrace_helper_action_destroy(helper, vstate);
14077 return (EINVAL);
14078 }
14079
14080 static void
14081 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14082 dof_helper_t *dofhp)
14083 {
14084 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
14085
14086 lck_mtx_lock(&dtrace_meta_lock);
14087 lck_mtx_lock(&dtrace_lock);
14088
14089 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14090 /*
14091 * If the dtrace module is loaded but not attached, or if
14092 * there aren't isn't a meta provider registered to deal with
14093 * these provider descriptions, we need to postpone creating
14094 * the actual providers until later.
14095 */
14096
14097 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14098 dtrace_deferred_pid != help) {
14099 help->dthps_deferred = 1;
14100 help->dthps_pid = p->p_pid;
14101 help->dthps_next = dtrace_deferred_pid;
14102 help->dthps_prev = NULL;
14103 if (dtrace_deferred_pid != NULL)
14104 dtrace_deferred_pid->dthps_prev = help;
14105 dtrace_deferred_pid = help;
14106 }
14107
14108 lck_mtx_unlock(&dtrace_lock);
14109
14110 } else if (dofhp != NULL) {
14111 /*
14112 * If the dtrace module is loaded and we have a particular
14113 * helper provider description, pass that off to the
14114 * meta provider.
14115 */
14116
14117 lck_mtx_unlock(&dtrace_lock);
14118
14119 dtrace_helper_provide(dofhp, p->p_pid);
14120
14121 } else {
14122 /*
14123 * Otherwise, just pass all the helper provider descriptions
14124 * off to the meta provider.
14125 */
14126
14127 uint_t i;
14128 lck_mtx_unlock(&dtrace_lock);
14129
14130 for (i = 0; i < help->dthps_nprovs; i++) {
14131 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14132 p->p_pid);
14133 }
14134 }
14135
14136 lck_mtx_unlock(&dtrace_meta_lock);
14137 }
14138
14139 static int
14140 dtrace_helper_provider_add(proc_t* p, dof_helper_t *dofhp, int gen)
14141 {
14142 dtrace_helpers_t *help;
14143 dtrace_helper_provider_t *hprov, **tmp_provs;
14144 uint_t tmp_maxprovs, i;
14145
14146 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14147 help = p->p_dtrace_helpers;
14148 ASSERT(help != NULL);
14149
14150 /*
14151 * If we already have dtrace_helper_providers_max helper providers,
14152 * we're refuse to add a new one.
14153 */
14154 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14155 return (ENOSPC);
14156
14157 /*
14158 * Check to make sure this isn't a duplicate.
14159 */
14160 for (i = 0; i < help->dthps_nprovs; i++) {
14161 if (dofhp->dofhp_addr ==
14162 help->dthps_provs[i]->dthp_prov.dofhp_addr)
14163 return (EALREADY);
14164 }
14165
14166 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14167 hprov->dthp_prov = *dofhp;
14168 hprov->dthp_ref = 1;
14169 hprov->dthp_generation = gen;
14170
14171 /*
14172 * Allocate a bigger table for helper providers if it's already full.
14173 */
14174 if (help->dthps_maxprovs == help->dthps_nprovs) {
14175 tmp_maxprovs = help->dthps_maxprovs;
14176 tmp_provs = help->dthps_provs;
14177
14178 if (help->dthps_maxprovs == 0)
14179 help->dthps_maxprovs = 2;
14180 else
14181 help->dthps_maxprovs *= 2;
14182 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14183 help->dthps_maxprovs = dtrace_helper_providers_max;
14184
14185 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14186
14187 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14188 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14189
14190 if (tmp_provs != NULL) {
14191 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14192 sizeof (dtrace_helper_provider_t *));
14193 kmem_free(tmp_provs, tmp_maxprovs *
14194 sizeof (dtrace_helper_provider_t *));
14195 }
14196 }
14197
14198 help->dthps_provs[help->dthps_nprovs] = hprov;
14199 help->dthps_nprovs++;
14200
14201 return (0);
14202 }
14203
14204 static void
14205 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14206 {
14207 lck_mtx_lock(&dtrace_lock);
14208
14209 if (--hprov->dthp_ref == 0) {
14210 dof_hdr_t *dof;
14211 lck_mtx_unlock(&dtrace_lock);
14212 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14213 dtrace_dof_destroy(dof);
14214 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14215 } else {
14216 lck_mtx_unlock(&dtrace_lock);
14217 }
14218 }
14219
14220 static int
14221 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14222 {
14223 uintptr_t daddr = (uintptr_t)dof;
14224 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14225 dof_provider_t *provider;
14226 dof_probe_t *probe;
14227 uint8_t *arg;
14228 char *strtab, *typestr;
14229 dof_stridx_t typeidx;
14230 size_t typesz;
14231 uint_t nprobes, j, k;
14232
14233 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14234
14235 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14236 dtrace_dof_error(dof, "misaligned section offset");
14237 return (-1);
14238 }
14239
14240 /*
14241 * The section needs to be large enough to contain the DOF provider
14242 * structure appropriate for the given version.
14243 */
14244 if (sec->dofs_size <
14245 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14246 offsetof(dof_provider_t, dofpv_prenoffs) :
14247 sizeof (dof_provider_t))) {
14248 dtrace_dof_error(dof, "provider section too small");
14249 return (-1);
14250 }
14251
14252 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14253 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14254 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14255 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14256 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14257
14258 if (str_sec == NULL || prb_sec == NULL ||
14259 arg_sec == NULL || off_sec == NULL)
14260 return (-1);
14261
14262 enoff_sec = NULL;
14263
14264 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14265 provider->dofpv_prenoffs != DOF_SECT_NONE &&
14266 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14267 provider->dofpv_prenoffs)) == NULL)
14268 return (-1);
14269
14270 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14271
14272 if (provider->dofpv_name >= str_sec->dofs_size ||
14273 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14274 dtrace_dof_error(dof, "invalid provider name");
14275 return (-1);
14276 }
14277
14278 if (prb_sec->dofs_entsize == 0 ||
14279 prb_sec->dofs_entsize > prb_sec->dofs_size) {
14280 dtrace_dof_error(dof, "invalid entry size");
14281 return (-1);
14282 }
14283
14284 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14285 dtrace_dof_error(dof, "misaligned entry size");
14286 return (-1);
14287 }
14288
14289 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14290 dtrace_dof_error(dof, "invalid entry size");
14291 return (-1);
14292 }
14293
14294 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14295 dtrace_dof_error(dof, "misaligned section offset");
14296 return (-1);
14297 }
14298
14299 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14300 dtrace_dof_error(dof, "invalid entry size");
14301 return (-1);
14302 }
14303
14304 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14305
14306 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14307
14308 /*
14309 * Take a pass through the probes to check for errors.
14310 */
14311 for (j = 0; j < nprobes; j++) {
14312 probe = (dof_probe_t *)(uintptr_t)(daddr +
14313 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14314
14315 if (probe->dofpr_func >= str_sec->dofs_size) {
14316 dtrace_dof_error(dof, "invalid function name");
14317 return (-1);
14318 }
14319
14320 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14321 dtrace_dof_error(dof, "function name too long");
14322 return (-1);
14323 }
14324
14325 if (probe->dofpr_name >= str_sec->dofs_size ||
14326 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14327 dtrace_dof_error(dof, "invalid probe name");
14328 return (-1);
14329 }
14330
14331 /*
14332 * The offset count must not wrap the index, and the offsets
14333 * must also not overflow the section's data.
14334 */
14335 if (probe->dofpr_offidx + probe->dofpr_noffs <
14336 probe->dofpr_offidx ||
14337 (probe->dofpr_offidx + probe->dofpr_noffs) *
14338 off_sec->dofs_entsize > off_sec->dofs_size) {
14339 dtrace_dof_error(dof, "invalid probe offset");
14340 return (-1);
14341 }
14342
14343 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14344 /*
14345 * If there's no is-enabled offset section, make sure
14346 * there aren't any is-enabled offsets. Otherwise
14347 * perform the same checks as for probe offsets
14348 * (immediately above).
14349 */
14350 if (enoff_sec == NULL) {
14351 if (probe->dofpr_enoffidx != 0 ||
14352 probe->dofpr_nenoffs != 0) {
14353 dtrace_dof_error(dof, "is-enabled "
14354 "offsets with null section");
14355 return (-1);
14356 }
14357 } else if (probe->dofpr_enoffidx +
14358 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14359 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14360 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14361 dtrace_dof_error(dof, "invalid is-enabled "
14362 "offset");
14363 return (-1);
14364 }
14365
14366 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14367 dtrace_dof_error(dof, "zero probe and "
14368 "is-enabled offsets");
14369 return (-1);
14370 }
14371 } else if (probe->dofpr_noffs == 0) {
14372 dtrace_dof_error(dof, "zero probe offsets");
14373 return (-1);
14374 }
14375
14376 if (probe->dofpr_argidx + probe->dofpr_xargc <
14377 probe->dofpr_argidx ||
14378 (probe->dofpr_argidx + probe->dofpr_xargc) *
14379 arg_sec->dofs_entsize > arg_sec->dofs_size) {
14380 dtrace_dof_error(dof, "invalid args");
14381 return (-1);
14382 }
14383
14384 typeidx = probe->dofpr_nargv;
14385 typestr = strtab + probe->dofpr_nargv;
14386 for (k = 0; k < probe->dofpr_nargc; k++) {
14387 if (typeidx >= str_sec->dofs_size) {
14388 dtrace_dof_error(dof, "bad "
14389 "native argument type");
14390 return (-1);
14391 }
14392
14393 typesz = strlen(typestr) + 1;
14394 if (typesz > DTRACE_ARGTYPELEN) {
14395 dtrace_dof_error(dof, "native "
14396 "argument type too long");
14397 return (-1);
14398 }
14399 typeidx += typesz;
14400 typestr += typesz;
14401 }
14402
14403 typeidx = probe->dofpr_xargv;
14404 typestr = strtab + probe->dofpr_xargv;
14405 for (k = 0; k < probe->dofpr_xargc; k++) {
14406 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14407 dtrace_dof_error(dof, "bad "
14408 "native argument index");
14409 return (-1);
14410 }
14411
14412 if (typeidx >= str_sec->dofs_size) {
14413 dtrace_dof_error(dof, "bad "
14414 "translated argument type");
14415 return (-1);
14416 }
14417
14418 typesz = strlen(typestr) + 1;
14419 if (typesz > DTRACE_ARGTYPELEN) {
14420 dtrace_dof_error(dof, "translated argument "
14421 "type too long");
14422 return (-1);
14423 }
14424
14425 typeidx += typesz;
14426 typestr += typesz;
14427 }
14428 }
14429
14430 return (0);
14431 }
14432
14433 static int
14434 dtrace_helper_slurp(proc_t* p, dof_hdr_t *dof, dof_helper_t *dhp)
14435 {
14436 dtrace_helpers_t *help;
14437 dtrace_vstate_t *vstate;
14438 dtrace_enabling_t *enab = NULL;
14439 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14440 uintptr_t daddr = (uintptr_t)dof;
14441
14442 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14443
14444 if ((help = p->p_dtrace_helpers) == NULL)
14445 help = dtrace_helpers_create(p);
14446
14447 vstate = &help->dthps_vstate;
14448
14449 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14450 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14451 dtrace_dof_destroy(dof);
14452 return (rv);
14453 }
14454
14455 /*
14456 * Look for helper providers and validate their descriptions.
14457 */
14458 if (dhp != NULL) {
14459 for (i = 0; (uint32_t)i < dof->dofh_secnum; i++) {
14460 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14461 dof->dofh_secoff + i * dof->dofh_secsize);
14462
14463 if (sec->dofs_type != DOF_SECT_PROVIDER)
14464 continue;
14465
14466 if (dtrace_helper_provider_validate(dof, sec) != 0) {
14467 dtrace_enabling_destroy(enab);
14468 dtrace_dof_destroy(dof);
14469 return (-1);
14470 }
14471
14472 nprovs++;
14473 }
14474 }
14475
14476 /*
14477 * Now we need to walk through the ECB descriptions in the enabling.
14478 */
14479 for (i = 0; i < enab->dten_ndesc; i++) {
14480 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14481 dtrace_probedesc_t *desc = &ep->dted_probe;
14482
14483 /* APPLE NOTE: Darwin employs size bounded string operation. */
14484 if (!LIT_STRNEQL(desc->dtpd_provider, "dtrace"))
14485 continue;
14486
14487 if (!LIT_STRNEQL(desc->dtpd_mod, "helper"))
14488 continue;
14489
14490 if (!LIT_STRNEQL(desc->dtpd_func, "ustack"))
14491 continue;
14492
14493 if ((rv = dtrace_helper_action_add(p, DTRACE_HELPER_ACTION_USTACK,
14494 ep)) != 0) {
14495 /*
14496 * Adding this helper action failed -- we are now going
14497 * to rip out the entire generation and return failure.
14498 */
14499 (void) dtrace_helper_destroygen(p, help->dthps_generation);
14500 dtrace_enabling_destroy(enab);
14501 dtrace_dof_destroy(dof);
14502 return (-1);
14503 }
14504
14505 nhelpers++;
14506 }
14507
14508 if (nhelpers < enab->dten_ndesc)
14509 dtrace_dof_error(dof, "unmatched helpers");
14510
14511 gen = help->dthps_generation++;
14512 dtrace_enabling_destroy(enab);
14513
14514 if (dhp != NULL && nprovs > 0) {
14515 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14516 if (dtrace_helper_provider_add(p, dhp, gen) == 0) {
14517 lck_mtx_unlock(&dtrace_lock);
14518 dtrace_helper_provider_register(p, help, dhp);
14519 lck_mtx_lock(&dtrace_lock);
14520
14521 destroy = 0;
14522 }
14523 }
14524
14525 if (destroy)
14526 dtrace_dof_destroy(dof);
14527
14528 return (gen);
14529 }
14530
14531 /*
14532 * APPLE NOTE: DTrace lazy dof implementation
14533 *
14534 * DTrace user static probes (USDT probes) and helper actions are loaded
14535 * in a process by proccessing dof sections. The dof sections are passed
14536 * into the kernel by dyld, in a dof_ioctl_data_t block. It is rather
14537 * expensive to process dof for a process that will never use it. There
14538 * is a memory cost (allocating the providers/probes), and a cpu cost
14539 * (creating the providers/probes).
14540 *
14541 * To reduce this cost, we use "lazy dof". The normal proceedure for
14542 * dof processing is to copyin the dof(s) pointed to by the dof_ioctl_data_t
14543 * block, and invoke dof_slurp_helper() on them. When "lazy dof" is
14544 * used, each process retains the dof_ioctl_data_t block, instead of
14545 * copying in the data it points to.
14546 *
14547 * The dof_ioctl_data_t blocks are managed as if they were the actual
14548 * processed dof; on fork the block is copied to the child, on exec and
14549 * exit the block is freed.
14550 *
14551 * If the process loads library(s) containing additional dof, the
14552 * new dof_ioctl_data_t is merged with the existing block.
14553 *
14554 * There are a few catches that make this slightly more difficult.
14555 * When dyld registers dof_ioctl_data_t blocks, it expects a unique
14556 * identifier value for each dof in the block. In non-lazy dof terms,
14557 * this is the generation that dof was loaded in. If we hand back
14558 * a UID for a lazy dof, that same UID must be able to unload the
14559 * dof once it has become non-lazy. To meet this requirement, the
14560 * code that loads lazy dof requires that the UID's for dof(s) in
14561 * the lazy dof be sorted, and in ascending order. It is okay to skip
14562 * UID's, I.E., 1 -> 5 -> 6 is legal.
14563 *
14564 * Once a process has become non-lazy, it will stay non-lazy. All
14565 * future dof operations for that process will be non-lazy, even
14566 * if the dof mode transitions back to lazy.
14567 *
14568 * Always do lazy dof checks before non-lazy (I.E. In fork, exit, exec.).
14569 * That way if the lazy check fails due to transitioning to non-lazy, the
14570 * right thing is done with the newly faulted in dof.
14571 */
14572
14573 /*
14574 * This method is a bit squicky. It must handle:
14575 *
14576 * dof should not be lazy.
14577 * dof should have been handled lazily, but there was an error
14578 * dof was handled lazily, and needs to be freed.
14579 * dof was handled lazily, and must not be freed.
14580 *
14581 *
14582 * Returns EACCESS if dof should be handled non-lazily.
14583 *
14584 * KERN_SUCCESS and all other return codes indicate lazy handling of dof.
14585 *
14586 * If the dofs data is claimed by this method, dofs_claimed will be set.
14587 * Callers should not free claimed dofs.
14588 */
14589 static int
14590 dtrace_lazy_dofs_add(proc_t *p, dof_ioctl_data_t* incoming_dofs, int *dofs_claimed)
14591 {
14592 ASSERT(p);
14593 ASSERT(incoming_dofs && incoming_dofs->dofiod_count > 0);
14594
14595 int rval = 0;
14596 *dofs_claimed = 0;
14597
14598 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14599
14600 /*
14601 * If we have lazy dof, dof mode better be LAZY_ON.
14602 */
14603 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
14604 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14605 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
14606
14607 /*
14608 * Any existing helpers force non-lazy behavior.
14609 */
14610 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
14611 lck_mtx_lock(&p->p_dtrace_sprlock);
14612
14613 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
14614 unsigned int existing_dofs_count = (existing_dofs) ? existing_dofs->dofiod_count : 0;
14615 unsigned int i, merged_dofs_count = incoming_dofs->dofiod_count + existing_dofs_count;
14616
14617 /*
14618 * Range check...
14619 */
14620 if (merged_dofs_count == 0 || merged_dofs_count > 1024) {
14621 dtrace_dof_error(NULL, "lazy_dofs_add merged_dofs_count out of range");
14622 rval = EINVAL;
14623 goto unlock;
14624 }
14625
14626 /*
14627 * Each dof being added must be assigned a unique generation.
14628 */
14629 uint64_t generation = (existing_dofs) ? existing_dofs->dofiod_helpers[existing_dofs_count - 1].dofhp_dof + 1 : 1;
14630 for (i=0; i<incoming_dofs->dofiod_count; i++) {
14631 /*
14632 * We rely on these being the same so we can overwrite dofhp_dof and not lose info.
14633 */
14634 ASSERT(incoming_dofs->dofiod_helpers[i].dofhp_dof == incoming_dofs->dofiod_helpers[i].dofhp_addr);
14635 incoming_dofs->dofiod_helpers[i].dofhp_dof = generation++;
14636 }
14637
14638
14639 if (existing_dofs) {
14640 /*
14641 * Merge the existing and incoming dofs
14642 */
14643 size_t merged_dofs_size = DOF_IOCTL_DATA_T_SIZE(merged_dofs_count);
14644 dof_ioctl_data_t* merged_dofs = kmem_alloc(merged_dofs_size, KM_SLEEP);
14645
14646 bcopy(&existing_dofs->dofiod_helpers[0],
14647 &merged_dofs->dofiod_helpers[0],
14648 sizeof(dof_helper_t) * existing_dofs_count);
14649 bcopy(&incoming_dofs->dofiod_helpers[0],
14650 &merged_dofs->dofiod_helpers[existing_dofs_count],
14651 sizeof(dof_helper_t) * incoming_dofs->dofiod_count);
14652
14653 merged_dofs->dofiod_count = merged_dofs_count;
14654
14655 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
14656
14657 p->p_dtrace_lazy_dofs = merged_dofs;
14658 } else {
14659 /*
14660 * Claim the incoming dofs
14661 */
14662 *dofs_claimed = 1;
14663 p->p_dtrace_lazy_dofs = incoming_dofs;
14664 }
14665
14666 #if DEBUG
14667 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
14668 for (i=0; i<all_dofs->dofiod_count-1; i++) {
14669 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
14670 }
14671 #endif /* DEBUG */
14672
14673 unlock:
14674 lck_mtx_unlock(&p->p_dtrace_sprlock);
14675 } else {
14676 rval = EACCES;
14677 }
14678
14679 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14680
14681 return rval;
14682 }
14683
14684 /*
14685 * Returns:
14686 *
14687 * EINVAL: lazy dof is enabled, but the requested generation was not found.
14688 * EACCES: This removal needs to be handled non-lazily.
14689 */
14690 static int
14691 dtrace_lazy_dofs_remove(proc_t *p, int generation)
14692 {
14693 int rval = EINVAL;
14694
14695 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14696
14697 /*
14698 * If we have lazy dof, dof mode better be LAZY_ON.
14699 */
14700 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
14701 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14702 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
14703
14704 /*
14705 * Any existing helpers force non-lazy behavior.
14706 */
14707 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
14708 lck_mtx_lock(&p->p_dtrace_sprlock);
14709
14710 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
14711
14712 if (existing_dofs) {
14713 int index, existing_dofs_count = existing_dofs->dofiod_count;
14714 for (index=0; index<existing_dofs_count; index++) {
14715 if ((int)existing_dofs->dofiod_helpers[index].dofhp_dof == generation) {
14716 dof_ioctl_data_t* removed_dofs = NULL;
14717
14718 /*
14719 * If there is only 1 dof, we'll delete it and swap in NULL.
14720 */
14721 if (existing_dofs_count > 1) {
14722 int removed_dofs_count = existing_dofs_count - 1;
14723 size_t removed_dofs_size = DOF_IOCTL_DATA_T_SIZE(removed_dofs_count);
14724
14725 removed_dofs = kmem_alloc(removed_dofs_size, KM_SLEEP);
14726 removed_dofs->dofiod_count = removed_dofs_count;
14727
14728 /*
14729 * copy the remaining data.
14730 */
14731 if (index > 0) {
14732 bcopy(&existing_dofs->dofiod_helpers[0],
14733 &removed_dofs->dofiod_helpers[0],
14734 index * sizeof(dof_helper_t));
14735 }
14736
14737 if (index < existing_dofs_count-1) {
14738 bcopy(&existing_dofs->dofiod_helpers[index+1],
14739 &removed_dofs->dofiod_helpers[index],
14740 (existing_dofs_count - index - 1) * sizeof(dof_helper_t));
14741 }
14742 }
14743
14744 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
14745
14746 p->p_dtrace_lazy_dofs = removed_dofs;
14747
14748 rval = KERN_SUCCESS;
14749
14750 break;
14751 }
14752 }
14753
14754 #if DEBUG
14755 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
14756 if (all_dofs) {
14757 unsigned int i;
14758 for (i=0; i<all_dofs->dofiod_count-1; i++) {
14759 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
14760 }
14761 }
14762 #endif
14763
14764 }
14765
14766 lck_mtx_unlock(&p->p_dtrace_sprlock);
14767 } else {
14768 rval = EACCES;
14769 }
14770
14771 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14772
14773 return rval;
14774 }
14775
14776 void
14777 dtrace_lazy_dofs_destroy(proc_t *p)
14778 {
14779 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14780 lck_mtx_lock(&p->p_dtrace_sprlock);
14781
14782 /*
14783 * If we have lazy dof, dof mode better be LAZY_ON, or we must be exiting.
14784 * We cannot assert against DTRACE_DOF_MODE_NEVER here, because we are called from
14785 * kern_exit.c and kern_exec.c.
14786 */
14787 ASSERT(p->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON || p->p_lflag & P_LEXIT);
14788 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14789
14790 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
14791 p->p_dtrace_lazy_dofs = NULL;
14792
14793 lck_mtx_unlock(&p->p_dtrace_sprlock);
14794 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14795
14796 if (lazy_dofs) {
14797 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
14798 }
14799 }
14800
14801 void
14802 dtrace_lazy_dofs_duplicate(proc_t *parent, proc_t *child)
14803 {
14804 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
14805 lck_mtx_assert(&parent->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
14806 lck_mtx_assert(&child->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
14807
14808 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14809 lck_mtx_lock(&parent->p_dtrace_sprlock);
14810
14811 /*
14812 * If we have lazy dof, dof mode better be LAZY_ON, or we must be exiting.
14813 * We cannot assert against DTRACE_DOF_MODE_NEVER here, because we are called from
14814 * kern_fork.c
14815 */
14816 ASSERT(parent->p_dtrace_lazy_dofs == NULL || dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON);
14817 ASSERT(parent->p_dtrace_lazy_dofs == NULL || parent->p_dtrace_helpers == NULL);
14818 /*
14819 * In theory we should hold the child sprlock, but this is safe...
14820 */
14821 ASSERT(child->p_dtrace_lazy_dofs == NULL && child->p_dtrace_helpers == NULL);
14822
14823 dof_ioctl_data_t* parent_dofs = parent->p_dtrace_lazy_dofs;
14824 dof_ioctl_data_t* child_dofs = NULL;
14825 if (parent_dofs) {
14826 size_t parent_dofs_size = DOF_IOCTL_DATA_T_SIZE(parent_dofs->dofiod_count);
14827 child_dofs = kmem_alloc(parent_dofs_size, KM_SLEEP);
14828 bcopy(parent_dofs, child_dofs, parent_dofs_size);
14829 }
14830
14831 lck_mtx_unlock(&parent->p_dtrace_sprlock);
14832
14833 if (child_dofs) {
14834 lck_mtx_lock(&child->p_dtrace_sprlock);
14835 child->p_dtrace_lazy_dofs = child_dofs;
14836 lck_mtx_unlock(&child->p_dtrace_sprlock);
14837 }
14838
14839 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14840 }
14841
14842 static int
14843 dtrace_lazy_dofs_proc_iterate_filter(proc_t *p, void* ignored)
14844 {
14845 #pragma unused(ignored)
14846 /*
14847 * Okay to NULL test without taking the sprlock.
14848 */
14849 return p->p_dtrace_lazy_dofs != NULL;
14850 }
14851
14852 static int
14853 dtrace_lazy_dofs_proc_iterate_doit(proc_t *p, void* ignored)
14854 {
14855 #pragma unused(ignored)
14856 /*
14857 * It is possible this process may exit during our attempt to
14858 * fault in the dof. We could fix this by holding locks longer,
14859 * but the errors are benign.
14860 */
14861 lck_mtx_lock(&p->p_dtrace_sprlock);
14862
14863 /*
14864 * In this case only, it is okay to have lazy dof when dof mode is DTRACE_DOF_MODE_LAZY_OFF
14865 */
14866 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14867 ASSERT(dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF);
14868
14869
14870 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
14871 p->p_dtrace_lazy_dofs = NULL;
14872
14873 lck_mtx_unlock(&p->p_dtrace_sprlock);
14874
14875 /*
14876 * Process each dof_helper_t
14877 */
14878 if (lazy_dofs != NULL) {
14879 unsigned int i;
14880 int rval;
14881
14882 for (i=0; i<lazy_dofs->dofiod_count; i++) {
14883 /*
14884 * When loading lazy dof, we depend on the generations being sorted in ascending order.
14885 */
14886 ASSERT(i >= (lazy_dofs->dofiod_count - 1) || lazy_dofs->dofiod_helpers[i].dofhp_dof < lazy_dofs->dofiod_helpers[i+1].dofhp_dof);
14887
14888 dof_helper_t *dhp = &lazy_dofs->dofiod_helpers[i];
14889
14890 /*
14891 * We stored the generation in dofhp_dof. Save it, and restore the original value.
14892 */
14893 int generation = dhp->dofhp_dof;
14894 dhp->dofhp_dof = dhp->dofhp_addr;
14895
14896 dof_hdr_t *dof = dtrace_dof_copyin_from_proc(p, dhp->dofhp_dof, &rval);
14897
14898 if (dof != NULL) {
14899 dtrace_helpers_t *help;
14900
14901 lck_mtx_lock(&dtrace_lock);
14902
14903 /*
14904 * This must be done with the dtrace_lock held
14905 */
14906 if ((help = p->p_dtrace_helpers) == NULL)
14907 help = dtrace_helpers_create(p);
14908
14909 /*
14910 * If the generation value has been bumped, someone snuck in
14911 * when we released the dtrace lock. We have to dump this generation,
14912 * there is no safe way to load it.
14913 */
14914 if (help->dthps_generation <= generation) {
14915 help->dthps_generation = generation;
14916
14917 /*
14918 * dtrace_helper_slurp() takes responsibility for the dof --
14919 * it may free it now or it may save it and free it later.
14920 */
14921 if ((rval = dtrace_helper_slurp(p, dof, dhp)) != generation) {
14922 dtrace_dof_error(NULL, "returned value did not match expected generation");
14923 }
14924 }
14925
14926 lck_mtx_unlock(&dtrace_lock);
14927 }
14928 }
14929
14930 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
14931 }
14932
14933 return PROC_RETURNED;
14934 }
14935
14936 static dtrace_helpers_t *
14937 dtrace_helpers_create(proc_t *p)
14938 {
14939 dtrace_helpers_t *help;
14940
14941 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14942 ASSERT(p->p_dtrace_helpers == NULL);
14943
14944 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14945 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14946 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14947
14948 p->p_dtrace_helpers = help;
14949 dtrace_helpers++;
14950
14951 return (help);
14952 }
14953
14954 static void
14955 dtrace_helpers_destroy(proc_t* p)
14956 {
14957 dtrace_helpers_t *help;
14958 dtrace_vstate_t *vstate;
14959 uint_t i;
14960
14961 lck_mtx_lock(&dtrace_lock);
14962
14963 ASSERT(p->p_dtrace_helpers != NULL);
14964 ASSERT(dtrace_helpers > 0);
14965
14966 help = p->p_dtrace_helpers;
14967 vstate = &help->dthps_vstate;
14968
14969 /*
14970 * We're now going to lose the help from this process.
14971 */
14972 p->p_dtrace_helpers = NULL;
14973 dtrace_sync();
14974
14975 /*
14976 * Destory the helper actions.
14977 */
14978 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14979 dtrace_helper_action_t *h, *next;
14980
14981 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14982 next = h->dtha_next;
14983 dtrace_helper_action_destroy(h, vstate);
14984 h = next;
14985 }
14986 }
14987
14988 lck_mtx_unlock(&dtrace_lock);
14989
14990 /*
14991 * Destroy the helper providers.
14992 */
14993 if (help->dthps_maxprovs > 0) {
14994 lck_mtx_lock(&dtrace_meta_lock);
14995 if (dtrace_meta_pid != NULL) {
14996 ASSERT(dtrace_deferred_pid == NULL);
14997
14998 for (i = 0; i < help->dthps_nprovs; i++) {
14999 dtrace_helper_provider_remove(
15000 &help->dthps_provs[i]->dthp_prov, p->p_pid);
15001 }
15002 } else {
15003 lck_mtx_lock(&dtrace_lock);
15004 ASSERT(help->dthps_deferred == 0 ||
15005 help->dthps_next != NULL ||
15006 help->dthps_prev != NULL ||
15007 help == dtrace_deferred_pid);
15008
15009 /*
15010 * Remove the helper from the deferred list.
15011 */
15012 if (help->dthps_next != NULL)
15013 help->dthps_next->dthps_prev = help->dthps_prev;
15014 if (help->dthps_prev != NULL)
15015 help->dthps_prev->dthps_next = help->dthps_next;
15016 if (dtrace_deferred_pid == help) {
15017 dtrace_deferred_pid = help->dthps_next;
15018 ASSERT(help->dthps_prev == NULL);
15019 }
15020
15021 lck_mtx_unlock(&dtrace_lock);
15022 }
15023
15024 lck_mtx_unlock(&dtrace_meta_lock);
15025
15026 for (i = 0; i < help->dthps_nprovs; i++) {
15027 dtrace_helper_provider_destroy(help->dthps_provs[i]);
15028 }
15029
15030 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15031 sizeof (dtrace_helper_provider_t *));
15032 }
15033
15034 lck_mtx_lock(&dtrace_lock);
15035
15036 dtrace_vstate_fini(&help->dthps_vstate);
15037 kmem_free(help->dthps_actions,
15038 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15039 kmem_free(help, sizeof (dtrace_helpers_t));
15040
15041 --dtrace_helpers;
15042 lck_mtx_unlock(&dtrace_lock);
15043 }
15044
15045 static void
15046 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15047 {
15048 dtrace_helpers_t *help, *newhelp;
15049 dtrace_helper_action_t *helper, *new, *last;
15050 dtrace_difo_t *dp;
15051 dtrace_vstate_t *vstate;
15052 uint_t i;
15053 int j, sz, hasprovs = 0;
15054
15055 lck_mtx_lock(&dtrace_lock);
15056 ASSERT(from->p_dtrace_helpers != NULL);
15057 ASSERT(dtrace_helpers > 0);
15058
15059 help = from->p_dtrace_helpers;
15060 newhelp = dtrace_helpers_create(to);
15061 ASSERT(to->p_dtrace_helpers != NULL);
15062
15063 newhelp->dthps_generation = help->dthps_generation;
15064 vstate = &newhelp->dthps_vstate;
15065
15066 /*
15067 * Duplicate the helper actions.
15068 */
15069 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15070 if ((helper = help->dthps_actions[i]) == NULL)
15071 continue;
15072
15073 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15074 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15075 KM_SLEEP);
15076 new->dtha_generation = helper->dtha_generation;
15077
15078 if ((dp = helper->dtha_predicate) != NULL) {
15079 dp = dtrace_difo_duplicate(dp, vstate);
15080 new->dtha_predicate = dp;
15081 }
15082
15083 new->dtha_nactions = helper->dtha_nactions;
15084 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15085 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15086
15087 for (j = 0; j < new->dtha_nactions; j++) {
15088 dtrace_difo_t *dpj = helper->dtha_actions[j];
15089
15090 ASSERT(dpj != NULL);
15091 dpj = dtrace_difo_duplicate(dpj, vstate);
15092 new->dtha_actions[j] = dpj;
15093 }
15094
15095 if (last != NULL) {
15096 last->dtha_next = new;
15097 } else {
15098 newhelp->dthps_actions[i] = new;
15099 }
15100
15101 last = new;
15102 }
15103 }
15104
15105 /*
15106 * Duplicate the helper providers and register them with the
15107 * DTrace framework.
15108 */
15109 if (help->dthps_nprovs > 0) {
15110 newhelp->dthps_nprovs = help->dthps_nprovs;
15111 newhelp->dthps_maxprovs = help->dthps_nprovs;
15112 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15113 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15114 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15115 newhelp->dthps_provs[i] = help->dthps_provs[i];
15116 newhelp->dthps_provs[i]->dthp_ref++;
15117 }
15118
15119 hasprovs = 1;
15120 }
15121
15122 lck_mtx_unlock(&dtrace_lock);
15123
15124 if (hasprovs)
15125 dtrace_helper_provider_register(to, newhelp, NULL);
15126 }
15127
15128 /*
15129 * DTrace Hook Functions
15130 */
15131
15132 /*
15133 * APPLE NOTE: dtrace_modctl_* routines for kext support.
15134 * Used to manipulate the modctl list within dtrace xnu.
15135 */
15136
15137 modctl_t *dtrace_modctl_list;
15138
15139 static void
15140 dtrace_modctl_add(struct modctl * newctl)
15141 {
15142 struct modctl *nextp, *prevp;
15143
15144 ASSERT(newctl != NULL);
15145 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15146
15147 // Insert new module at the front of the list,
15148
15149 newctl->mod_next = dtrace_modctl_list;
15150 dtrace_modctl_list = newctl;
15151
15152 /*
15153 * If a module exists with the same name, then that module
15154 * must have been unloaded with enabled probes. We will move
15155 * the unloaded module to the new module's stale chain and
15156 * then stop traversing the list.
15157 */
15158
15159 prevp = newctl;
15160 nextp = newctl->mod_next;
15161
15162 while (nextp != NULL) {
15163 if (nextp->mod_loaded) {
15164 /* This is a loaded module. Keep traversing. */
15165 prevp = nextp;
15166 nextp = nextp->mod_next;
15167 continue;
15168 }
15169 else {
15170 /* Found an unloaded module */
15171 if (strncmp (newctl->mod_modname, nextp->mod_modname, KMOD_MAX_NAME)) {
15172 /* Names don't match. Keep traversing. */
15173 prevp = nextp;
15174 nextp = nextp->mod_next;
15175 continue;
15176 }
15177 else {
15178 /* We found a stale entry, move it. We're done. */
15179 prevp->mod_next = nextp->mod_next;
15180 newctl->mod_stale = nextp;
15181 nextp->mod_next = NULL;
15182 break;
15183 }
15184 }
15185 }
15186 }
15187
15188 static modctl_t *
15189 dtrace_modctl_lookup(struct kmod_info * kmod)
15190 {
15191 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15192
15193 struct modctl * ctl;
15194
15195 for (ctl = dtrace_modctl_list; ctl; ctl=ctl->mod_next) {
15196 if (ctl->mod_id == kmod->id)
15197 return(ctl);
15198 }
15199 return (NULL);
15200 }
15201
15202 /*
15203 * This routine is called from dtrace_module_unloaded().
15204 * It removes a modctl structure and its stale chain
15205 * from the kext shadow list.
15206 */
15207 static void
15208 dtrace_modctl_remove(struct modctl * ctl)
15209 {
15210 ASSERT(ctl != NULL);
15211 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15212 modctl_t *prevp, *nextp, *curp;
15213
15214 // Remove stale chain first
15215 for (curp=ctl->mod_stale; curp != NULL; curp=nextp) {
15216 nextp = curp->mod_stale;
15217 /* There should NEVER be user symbols allocated at this point */
15218 ASSERT(curp->mod_user_symbols == NULL);
15219 kmem_free(curp, sizeof(modctl_t));
15220 }
15221
15222 prevp = NULL;
15223 curp = dtrace_modctl_list;
15224
15225 while (curp != ctl) {
15226 prevp = curp;
15227 curp = curp->mod_next;
15228 }
15229
15230 if (prevp != NULL) {
15231 prevp->mod_next = ctl->mod_next;
15232 }
15233 else {
15234 dtrace_modctl_list = ctl->mod_next;
15235 }
15236
15237 /* There should NEVER be user symbols allocated at this point */
15238 ASSERT(ctl->mod_user_symbols == NULL);
15239
15240 kmem_free (ctl, sizeof(modctl_t));
15241 }
15242
15243 /*
15244 * APPLE NOTE: The kext loader will call dtrace_module_loaded
15245 * when the kext is loaded in memory, but before calling the
15246 * kext's start routine.
15247 *
15248 * Return 0 on success
15249 * Return -1 on failure
15250 */
15251
15252 static int
15253 dtrace_module_loaded(struct kmod_info *kmod, uint32_t flag)
15254 {
15255 dtrace_provider_t *prv;
15256
15257 /*
15258 * If kernel symbols have been disabled, return immediately
15259 * DTRACE_KERNEL_SYMBOLS_NEVER is a permanent mode, it is safe to test without holding locks
15260 */
15261 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER)
15262 return 0;
15263
15264 struct modctl *ctl = NULL;
15265 if (!kmod || kmod->address == 0 || kmod->size == 0)
15266 return(-1);
15267
15268 lck_mtx_lock(&dtrace_provider_lock);
15269 lck_mtx_lock(&mod_lock);
15270
15271 /*
15272 * Have we seen this kext before?
15273 */
15274
15275 ctl = dtrace_modctl_lookup(kmod);
15276
15277 if (ctl != NULL) {
15278 /* bail... we already have this kext in the modctl list */
15279 lck_mtx_unlock(&mod_lock);
15280 lck_mtx_unlock(&dtrace_provider_lock);
15281 if (dtrace_err_verbose)
15282 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);
15283 return(-1);
15284 }
15285 else {
15286 ctl = kmem_alloc(sizeof(struct modctl), KM_SLEEP);
15287 if (ctl == NULL) {
15288 if (dtrace_err_verbose)
15289 cmn_err(CE_WARN, "dtrace module load '%s %u' is failing ", kmod->name, (uint_t)kmod->id);
15290 lck_mtx_unlock(&mod_lock);
15291 lck_mtx_unlock(&dtrace_provider_lock);
15292 return (-1);
15293 }
15294 ctl->mod_next = NULL;
15295 ctl->mod_stale = NULL;
15296 strlcpy (ctl->mod_modname, kmod->name, sizeof(ctl->mod_modname));
15297 ctl->mod_loadcnt = kmod->id;
15298 ctl->mod_nenabled = 0;
15299 ctl->mod_address = kmod->address;
15300 ctl->mod_size = kmod->size;
15301 ctl->mod_id = kmod->id;
15302 ctl->mod_loaded = 1;
15303 ctl->mod_flags = 0;
15304 ctl->mod_user_symbols = NULL;
15305
15306 /*
15307 * Find the UUID for this module, if it has one
15308 */
15309 kernel_mach_header_t* header = (kernel_mach_header_t *)ctl->mod_address;
15310 struct load_command* load_cmd = (struct load_command *)&header[1];
15311 uint32_t i;
15312 for (i = 0; i < header->ncmds; i++) {
15313 if (load_cmd->cmd == LC_UUID) {
15314 struct uuid_command* uuid_cmd = (struct uuid_command *)load_cmd;
15315 memcpy(ctl->mod_uuid, uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
15316 ctl->mod_flags |= MODCTL_HAS_UUID;
15317 break;
15318 }
15319 load_cmd = (struct load_command *)((caddr_t)load_cmd + load_cmd->cmdsize);
15320 }
15321
15322 if (ctl->mod_address == g_kernel_kmod_info.address) {
15323 ctl->mod_flags |= MODCTL_IS_MACH_KERNEL;
15324 }
15325 }
15326 dtrace_modctl_add(ctl);
15327
15328 /*
15329 * We must hold the dtrace_lock to safely test non permanent dtrace_fbt_symbol_mode(s)
15330 */
15331 lck_mtx_lock(&dtrace_lock);
15332
15333 /*
15334 * DTrace must decide if it will instrument modules lazily via
15335 * userspace symbols (default mode), or instrument immediately via
15336 * kernel symbols (non-default mode)
15337 *
15338 * When in default/lazy mode, DTrace will only support modules
15339 * built with a valid UUID.
15340 *
15341 * Overriding the default can be done explicitly in one of
15342 * the following two ways.
15343 *
15344 * A module can force symbols from kernel space using the plist key,
15345 * OSBundleForceDTraceInit (see kmod.h). If this per kext state is set,
15346 * we fall through and instrument this module now.
15347 *
15348 * Or, the boot-arg, dtrace_kernel_symbol_mode, can be set to force symbols
15349 * from kernel space (see dtrace_impl.h). If this system state is set
15350 * to a non-userspace mode, we fall through and instrument the module now.
15351 */
15352
15353 if ((dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) &&
15354 (!(flag & KMOD_DTRACE_FORCE_INIT)))
15355 {
15356 /* We will instrument the module lazily -- this is the default */
15357 lck_mtx_unlock(&dtrace_lock);
15358 lck_mtx_unlock(&mod_lock);
15359 lck_mtx_unlock(&dtrace_provider_lock);
15360 return 0;
15361 }
15362
15363 /* We will instrument the module immediately using kernel symbols */
15364 ctl->mod_flags |= MODCTL_HAS_KERNEL_SYMBOLS;
15365
15366 lck_mtx_unlock(&dtrace_lock);
15367
15368 /*
15369 * We're going to call each providers per-module provide operation
15370 * specifying only this module.
15371 */
15372 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15373 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15374
15375 /*
15376 * APPLE NOTE: The contract with the kext loader is that once this function
15377 * has completed, it may delete kernel symbols at will.
15378 * We must set this while still holding the mod_lock.
15379 */
15380 ctl->mod_flags &= ~MODCTL_HAS_KERNEL_SYMBOLS;
15381
15382 lck_mtx_unlock(&mod_lock);
15383 lck_mtx_unlock(&dtrace_provider_lock);
15384
15385 /*
15386 * If we have any retained enablings, we need to match against them.
15387 * Enabling probes requires that cpu_lock be held, and we cannot hold
15388 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15389 * module. (In particular, this happens when loading scheduling
15390 * classes.) So if we have any retained enablings, we need to dispatch
15391 * our task queue to do the match for us.
15392 */
15393 lck_mtx_lock(&dtrace_lock);
15394
15395 if (dtrace_retained == NULL) {
15396 lck_mtx_unlock(&dtrace_lock);
15397 return 0;
15398 }
15399
15400 /* APPLE NOTE!
15401 *
15402 * The cpu_lock mentioned above is only held by dtrace code, Apple's xnu never actually
15403 * holds it for any reason. Thus the comment above is invalid, we can directly invoke
15404 * dtrace_enabling_matchall without jumping through all the hoops, and we can avoid
15405 * the delay call as well.
15406 */
15407 lck_mtx_unlock(&dtrace_lock);
15408
15409 dtrace_enabling_matchall();
15410
15411 return 0;
15412 }
15413
15414 /*
15415 * Return 0 on success
15416 * Return -1 on failure
15417 */
15418 static int
15419 dtrace_module_unloaded(struct kmod_info *kmod)
15420 {
15421 dtrace_probe_t template, *probe, *first, *next;
15422 dtrace_provider_t *prov;
15423 struct modctl *ctl = NULL;
15424 struct modctl *syncctl = NULL;
15425 struct modctl *nextsyncctl = NULL;
15426 int syncmode = 0;
15427
15428 lck_mtx_lock(&dtrace_provider_lock);
15429 lck_mtx_lock(&mod_lock);
15430 lck_mtx_lock(&dtrace_lock);
15431
15432 if (kmod == NULL) {
15433 syncmode = 1;
15434 }
15435 else {
15436 ctl = dtrace_modctl_lookup(kmod);
15437 if (ctl == NULL)
15438 {
15439 lck_mtx_unlock(&dtrace_lock);
15440 lck_mtx_unlock(&mod_lock);
15441 lck_mtx_unlock(&dtrace_provider_lock);
15442 return (-1);
15443 }
15444 ctl->mod_loaded = 0;
15445 ctl->mod_address = 0;
15446 ctl->mod_size = 0;
15447 }
15448
15449 if (dtrace_bymod == NULL) {
15450 /*
15451 * The DTrace module is loaded (obviously) but not attached;
15452 * we don't have any work to do.
15453 */
15454 if (ctl != NULL)
15455 (void)dtrace_modctl_remove(ctl);
15456 lck_mtx_unlock(&dtrace_lock);
15457 lck_mtx_unlock(&mod_lock);
15458 lck_mtx_unlock(&dtrace_provider_lock);
15459 return(0);
15460 }
15461
15462 /* Syncmode set means we target and traverse entire modctl list. */
15463 if (syncmode)
15464 nextsyncctl = dtrace_modctl_list;
15465
15466 syncloop:
15467 if (syncmode)
15468 {
15469 /* find a stale modctl struct */
15470 for (syncctl = nextsyncctl; syncctl != NULL; syncctl=syncctl->mod_next) {
15471 if (syncctl->mod_address == 0)
15472 break;
15473 }
15474 if (syncctl==NULL)
15475 {
15476 /* We have no more work to do */
15477 lck_mtx_unlock(&dtrace_lock);
15478 lck_mtx_unlock(&mod_lock);
15479 lck_mtx_unlock(&dtrace_provider_lock);
15480 return(0);
15481 }
15482 else {
15483 /* keep track of next syncctl in case this one is removed */
15484 nextsyncctl = syncctl->mod_next;
15485 ctl = syncctl;
15486 }
15487 }
15488
15489 template.dtpr_mod = ctl->mod_modname;
15490
15491 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15492 probe != NULL; probe = probe->dtpr_nextmod) {
15493 if (probe->dtpr_ecb != NULL) {
15494 /*
15495 * This shouldn't _actually_ be possible -- we're
15496 * unloading a module that has an enabled probe in it.
15497 * (It's normally up to the provider to make sure that
15498 * this can't happen.) However, because dtps_enable()
15499 * doesn't have a failure mode, there can be an
15500 * enable/unload race. Upshot: we don't want to
15501 * assert, but we're not going to disable the
15502 * probe, either.
15503 */
15504
15505
15506 if (syncmode) {
15507 /* We're syncing, let's look at next in list */
15508 goto syncloop;
15509 }
15510
15511 lck_mtx_unlock(&dtrace_lock);
15512 lck_mtx_unlock(&mod_lock);
15513 lck_mtx_unlock(&dtrace_provider_lock);
15514
15515 if (dtrace_err_verbose) {
15516 cmn_err(CE_WARN, "unloaded module '%s' had "
15517 "enabled probes", ctl->mod_modname);
15518 }
15519 return(-1);
15520 }
15521 }
15522
15523 probe = first;
15524
15525 for (first = NULL; probe != NULL; probe = next) {
15526 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15527
15528 dtrace_probes[probe->dtpr_id - 1] = NULL;
15529 probe->dtpr_provider->dtpv_probe_count--;
15530
15531 next = probe->dtpr_nextmod;
15532 dtrace_hash_remove(dtrace_bymod, probe);
15533 dtrace_hash_remove(dtrace_byfunc, probe);
15534 dtrace_hash_remove(dtrace_byname, probe);
15535
15536 if (first == NULL) {
15537 first = probe;
15538 probe->dtpr_nextmod = NULL;
15539 } else {
15540 probe->dtpr_nextmod = first;
15541 first = probe;
15542 }
15543 }
15544
15545 /*
15546 * We've removed all of the module's probes from the hash chains and
15547 * from the probe array. Now issue a dtrace_sync() to be sure that
15548 * everyone has cleared out from any probe array processing.
15549 */
15550 dtrace_sync();
15551
15552 for (probe = first; probe != NULL; probe = first) {
15553 first = probe->dtpr_nextmod;
15554 prov = probe->dtpr_provider;
15555 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15556 probe->dtpr_arg);
15557 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15558 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15559 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15560 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15561
15562 zfree(dtrace_probe_t_zone, probe);
15563 }
15564
15565 dtrace_modctl_remove(ctl);
15566
15567 if (syncmode)
15568 goto syncloop;
15569
15570 lck_mtx_unlock(&dtrace_lock);
15571 lck_mtx_unlock(&mod_lock);
15572 lck_mtx_unlock(&dtrace_provider_lock);
15573
15574 return(0);
15575 }
15576
15577 void
15578 dtrace_suspend(void)
15579 {
15580 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15581 }
15582
15583 void
15584 dtrace_resume(void)
15585 {
15586 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15587 }
15588
15589 static int
15590 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15591 {
15592 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15593 lck_mtx_lock(&dtrace_lock);
15594
15595 switch (what) {
15596 case CPU_CONFIG: {
15597 dtrace_state_t *state;
15598 dtrace_optval_t *opt, rs, c;
15599
15600 /*
15601 * For now, we only allocate a new buffer for anonymous state.
15602 */
15603 if ((state = dtrace_anon.dta_state) == NULL)
15604 break;
15605
15606 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15607 break;
15608
15609 opt = state->dts_options;
15610 c = opt[DTRACEOPT_CPU];
15611
15612 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15613 break;
15614
15615 /*
15616 * Regardless of what the actual policy is, we're going to
15617 * temporarily set our resize policy to be manual. We're
15618 * also going to temporarily set our CPU option to denote
15619 * the newly configured CPU.
15620 */
15621 rs = opt[DTRACEOPT_BUFRESIZE];
15622 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15623 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15624
15625 (void) dtrace_state_buffers(state);
15626
15627 opt[DTRACEOPT_BUFRESIZE] = rs;
15628 opt[DTRACEOPT_CPU] = c;
15629
15630 break;
15631 }
15632
15633 case CPU_UNCONFIG:
15634 /*
15635 * We don't free the buffer in the CPU_UNCONFIG case. (The
15636 * buffer will be freed when the consumer exits.)
15637 */
15638 break;
15639
15640 default:
15641 break;
15642 }
15643
15644 lck_mtx_unlock(&dtrace_lock);
15645 return (0);
15646 }
15647
15648 static void
15649 dtrace_cpu_setup_initial(processorid_t cpu)
15650 {
15651 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15652 }
15653
15654 static void
15655 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15656 {
15657 if (dtrace_toxranges >= dtrace_toxranges_max) {
15658 int osize, nsize;
15659 dtrace_toxrange_t *range;
15660
15661 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15662
15663 if (osize == 0) {
15664 ASSERT(dtrace_toxrange == NULL);
15665 ASSERT(dtrace_toxranges_max == 0);
15666 dtrace_toxranges_max = 1;
15667 } else {
15668 dtrace_toxranges_max <<= 1;
15669 }
15670
15671 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15672 range = kmem_zalloc(nsize, KM_SLEEP);
15673
15674 if (dtrace_toxrange != NULL) {
15675 ASSERT(osize != 0);
15676 bcopy(dtrace_toxrange, range, osize);
15677 kmem_free(dtrace_toxrange, osize);
15678 }
15679
15680 dtrace_toxrange = range;
15681 }
15682
15683 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15684 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15685
15686 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15687 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15688 dtrace_toxranges++;
15689 }
15690
15691 /*
15692 * DTrace Driver Cookbook Functions
15693 */
15694 /*ARGSUSED*/
15695 static int
15696 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15697 {
15698 #pragma unused(cmd) /* __APPLE__ */
15699 dtrace_provider_id_t id;
15700 dtrace_state_t *state = NULL;
15701 dtrace_enabling_t *enab;
15702
15703 lck_mtx_lock(&cpu_lock);
15704 lck_mtx_lock(&dtrace_provider_lock);
15705 lck_mtx_lock(&dtrace_lock);
15706
15707 if (ddi_soft_state_init(&dtrace_softstate,
15708 sizeof (dtrace_state_t), 0) != 0) {
15709 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15710 lck_mtx_unlock(&dtrace_lock);
15711 lck_mtx_unlock(&dtrace_provider_lock);
15712 lck_mtx_unlock(&cpu_lock);
15713 return (DDI_FAILURE);
15714 }
15715
15716 /* Darwin uses BSD cloning device driver to automagically obtain minor device number. */
15717
15718 ddi_report_dev(devi);
15719 dtrace_devi = devi;
15720
15721 dtrace_modload = dtrace_module_loaded;
15722 dtrace_modunload = dtrace_module_unloaded;
15723 dtrace_cpu_init = dtrace_cpu_setup_initial;
15724 dtrace_helpers_cleanup = dtrace_helpers_destroy;
15725 dtrace_helpers_fork = dtrace_helpers_duplicate;
15726 dtrace_cpustart_init = dtrace_suspend;
15727 dtrace_cpustart_fini = dtrace_resume;
15728 dtrace_debugger_init = dtrace_suspend;
15729 dtrace_debugger_fini = dtrace_resume;
15730
15731 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15732
15733 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15734
15735 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15736 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15737 dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15738 UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15739 VM_SLEEP | VMC_IDENTIFIER);
15740 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15741 1, INT_MAX, 0);
15742
15743 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15744 sizeof (dtrace_dstate_percpu_t) * (int)NCPU, DTRACE_STATE_ALIGN,
15745 NULL, NULL, NULL, NULL, NULL, 0);
15746
15747 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
15748 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15749 offsetof(dtrace_probe_t, dtpr_nextmod),
15750 offsetof(dtrace_probe_t, dtpr_prevmod));
15751
15752 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15753 offsetof(dtrace_probe_t, dtpr_nextfunc),
15754 offsetof(dtrace_probe_t, dtpr_prevfunc));
15755
15756 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15757 offsetof(dtrace_probe_t, dtpr_nextname),
15758 offsetof(dtrace_probe_t, dtpr_prevname));
15759
15760 if (dtrace_retain_max < 1) {
15761 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15762 "setting to 1", dtrace_retain_max);
15763 dtrace_retain_max = 1;
15764 }
15765
15766 /*
15767 * Now discover our toxic ranges.
15768 */
15769 dtrace_toxic_ranges(dtrace_toxrange_add);
15770
15771 /*
15772 * Before we register ourselves as a provider to our own framework,
15773 * we would like to assert that dtrace_provider is NULL -- but that's
15774 * not true if we were loaded as a dependency of a DTrace provider.
15775 * Once we've registered, we can assert that dtrace_provider is our
15776 * pseudo provider.
15777 */
15778 (void) dtrace_register("dtrace", &dtrace_provider_attr,
15779 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15780
15781 ASSERT(dtrace_provider != NULL);
15782 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15783
15784 #if defined (__x86_64__)
15785 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15786 dtrace_provider, NULL, NULL, "BEGIN", 1, NULL);
15787 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15788 dtrace_provider, NULL, NULL, "END", 0, NULL);
15789 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15790 dtrace_provider, NULL, NULL, "ERROR", 3, NULL);
15791 #else
15792 #error Unknown Architecture
15793 #endif
15794
15795 dtrace_anon_property();
15796 lck_mtx_unlock(&cpu_lock);
15797
15798 /*
15799 * If DTrace helper tracing is enabled, we need to allocate the
15800 * trace buffer and initialize the values.
15801 */
15802 if (dtrace_helptrace_enabled) {
15803 ASSERT(dtrace_helptrace_buffer == NULL);
15804 dtrace_helptrace_buffer =
15805 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15806 dtrace_helptrace_next = 0;
15807 }
15808
15809 /*
15810 * If there are already providers, we must ask them to provide their
15811 * probes, and then match any anonymous enabling against them. Note
15812 * that there should be no other retained enablings at this time:
15813 * the only retained enablings at this time should be the anonymous
15814 * enabling.
15815 */
15816 if (dtrace_anon.dta_enabling != NULL) {
15817 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15818
15819 /*
15820 * APPLE NOTE: if handling anonymous dof, switch symbol modes.
15821 */
15822 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
15823 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
15824 }
15825
15826 dtrace_enabling_provide(NULL);
15827 state = dtrace_anon.dta_state;
15828
15829 /*
15830 * We couldn't hold cpu_lock across the above call to
15831 * dtrace_enabling_provide(), but we must hold it to actually
15832 * enable the probes. We have to drop all of our locks, pick
15833 * up cpu_lock, and regain our locks before matching the
15834 * retained anonymous enabling.
15835 */
15836 lck_mtx_unlock(&dtrace_lock);
15837 lck_mtx_unlock(&dtrace_provider_lock);
15838
15839 lck_mtx_lock(&cpu_lock);
15840 lck_mtx_lock(&dtrace_provider_lock);
15841 lck_mtx_lock(&dtrace_lock);
15842
15843 if ((enab = dtrace_anon.dta_enabling) != NULL)
15844 (void) dtrace_enabling_match(enab, NULL);
15845
15846 lck_mtx_unlock(&cpu_lock);
15847 }
15848
15849 lck_mtx_unlock(&dtrace_lock);
15850 lck_mtx_unlock(&dtrace_provider_lock);
15851
15852 if (state != NULL) {
15853 /*
15854 * If we created any anonymous state, set it going now.
15855 */
15856 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15857 }
15858
15859 return (DDI_SUCCESS);
15860 }
15861
15862 /*ARGSUSED*/
15863 static int
15864 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15865 {
15866 #pragma unused(flag, otyp)
15867 dtrace_state_t *state;
15868 uint32_t priv;
15869 uid_t uid;
15870 zoneid_t zoneid;
15871 int rv;
15872
15873 /* APPLE: Darwin puts Helper on its own major device. */
15874
15875 /*
15876 * If no DTRACE_PRIV_* bits are set in the credential, then the
15877 * caller lacks sufficient permission to do anything with DTrace.
15878 */
15879 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15880 if (priv == DTRACE_PRIV_NONE)
15881 return (EACCES);
15882
15883 /*
15884 * APPLE NOTE: We delay the initialization of fasttrap as late as possible.
15885 * It certainly can't be later than now!
15886 */
15887 fasttrap_init();
15888
15889 /*
15890 * Ask all providers to provide all their probes.
15891 */
15892 lck_mtx_lock(&dtrace_provider_lock);
15893 dtrace_probe_provide(NULL, NULL);
15894 lck_mtx_unlock(&dtrace_provider_lock);
15895
15896 lck_mtx_lock(&cpu_lock);
15897 lck_mtx_lock(&dtrace_lock);
15898 dtrace_opens++;
15899 dtrace_membar_producer();
15900
15901 /*
15902 * If the kernel debugger is active (that is, if the kernel debugger
15903 * modified text in some way), we won't allow the open.
15904 */
15905 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15906 dtrace_opens--;
15907 lck_mtx_unlock(&dtrace_lock);
15908 lck_mtx_unlock(&cpu_lock);
15909 return (EBUSY);
15910 }
15911
15912 rv = dtrace_state_create(devp, cred_p, &state);
15913 lck_mtx_unlock(&cpu_lock);
15914
15915 if (rv != 0 || state == NULL) {
15916 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15917 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15918 lck_mtx_unlock(&dtrace_lock);
15919 /* propagate EAGAIN or ERESTART */
15920 return (rv);
15921 }
15922
15923 lck_mtx_unlock(&dtrace_lock);
15924
15925 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
15926
15927 /*
15928 * If we are currently lazy, transition states.
15929 *
15930 * Unlike dtrace_close, we do not need to check the
15931 * value of dtrace_opens, as any positive value (and
15932 * we count as 1) means we transition states.
15933 */
15934 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON) {
15935 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_OFF;
15936
15937 /*
15938 * Iterate all existing processes and load lazy dofs.
15939 */
15940 proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS,
15941 dtrace_lazy_dofs_proc_iterate_doit,
15942 NULL,
15943 dtrace_lazy_dofs_proc_iterate_filter,
15944 NULL);
15945 }
15946
15947 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
15948
15949 /*
15950 * Update kernel symbol state.
15951 *
15952 * We must own the provider and dtrace locks.
15953 *
15954 * NOTE! It may appear there is a race by setting this value so late
15955 * after dtrace_probe_provide. However, any kext loaded after the
15956 * call to probe provide and before we set LAZY_OFF will be marked as
15957 * eligible for symbols from userspace. The same dtrace that is currently
15958 * calling dtrace_open() (this call!) will get a list of kexts needing
15959 * symbols and fill them in, thus closing the race window.
15960 *
15961 * We want to set this value only after it certain it will succeed, as
15962 * this significantly reduces the complexity of error exits.
15963 */
15964 lck_mtx_lock(&dtrace_lock);
15965 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
15966 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
15967 }
15968 lck_mtx_unlock(&dtrace_lock);
15969
15970 return (0);
15971 }
15972
15973 /*ARGSUSED*/
15974 static int
15975 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15976 {
15977 #pragma unused(flag, otyp, cred_p) /* __APPLE__ */
15978 minor_t minor = getminor(dev);
15979 dtrace_state_t *state;
15980
15981 /* APPLE NOTE: Darwin puts Helper on its own major device. */
15982
15983 state = ddi_get_soft_state(dtrace_softstate, minor);
15984
15985 lck_mtx_lock(&cpu_lock);
15986 lck_mtx_lock(&dtrace_lock);
15987
15988 if (state->dts_anon) {
15989 /*
15990 * There is anonymous state. Destroy that first.
15991 */
15992 ASSERT(dtrace_anon.dta_state == NULL);
15993 dtrace_state_destroy(state->dts_anon);
15994 }
15995
15996 dtrace_state_destroy(state);
15997 ASSERT(dtrace_opens > 0);
15998
15999 /*
16000 * Only relinquish control of the kernel debugger interface when there
16001 * are no consumers and no anonymous enablings.
16002 */
16003 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16004 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16005
16006 lck_mtx_unlock(&dtrace_lock);
16007 lck_mtx_unlock(&cpu_lock);
16008
16009 /*
16010 * Lock ordering requires the dof mode lock be taken before
16011 * the dtrace_lock.
16012 */
16013 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
16014 lck_mtx_lock(&dtrace_lock);
16015
16016 if (dtrace_opens == 0) {
16017 /*
16018 * If we are currently lazy-off, and this is the last close, transition to
16019 * lazy state.
16020 */
16021 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
16022 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
16023 }
16024
16025 /*
16026 * If we are the last dtrace client, switch back to lazy (from userspace) symbols
16027 */
16028 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_KERNEL) {
16029 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
16030 }
16031 }
16032
16033 lck_mtx_unlock(&dtrace_lock);
16034 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
16035
16036 /*
16037 * Kext probes may be retained past the end of the kext's lifespan. The
16038 * probes are kept until the last reference to them has been removed.
16039 * Since closing an active dtrace context is likely to drop that last reference,
16040 * lets take a shot at cleaning out the orphaned probes now.
16041 */
16042 dtrace_module_unloaded(NULL);
16043
16044 return (0);
16045 }
16046
16047 /*ARGSUSED*/
16048 static int
16049 dtrace_ioctl_helper(u_long cmd, caddr_t arg, int *rv)
16050 {
16051 #pragma unused(rv)
16052 /*
16053 * Safe to check this outside the dof mode lock
16054 */
16055 if (dtrace_dof_mode == DTRACE_DOF_MODE_NEVER)
16056 return KERN_SUCCESS;
16057
16058 switch (cmd) {
16059 case DTRACEHIOC_ADDDOF:
16060 {
16061 dof_helper_t *dhp = NULL;
16062 size_t dof_ioctl_data_size;
16063 dof_ioctl_data_t* multi_dof;
16064 unsigned int i;
16065 int rval = 0;
16066 user_addr_t user_address = *(user_addr_t*)arg;
16067 uint64_t dof_count;
16068 int multi_dof_claimed = 0;
16069 proc_t* p = current_proc();
16070
16071 /*
16072 * Read the number of DOF sections being passed in.
16073 */
16074 if (copyin(user_address + offsetof(dof_ioctl_data_t, dofiod_count),
16075 &dof_count,
16076 sizeof(dof_count))) {
16077 dtrace_dof_error(NULL, "failed to copyin dofiod_count");
16078 return (EFAULT);
16079 }
16080
16081 /*
16082 * Range check the count.
16083 */
16084 if (dof_count == 0 || dof_count > 1024) {
16085 dtrace_dof_error(NULL, "dofiod_count is not valid");
16086 return (EINVAL);
16087 }
16088
16089 /*
16090 * Allocate a correctly sized structure and copyin the data.
16091 */
16092 dof_ioctl_data_size = DOF_IOCTL_DATA_T_SIZE(dof_count);
16093 if ((multi_dof = kmem_alloc(dof_ioctl_data_size, KM_SLEEP)) == NULL)
16094 return (ENOMEM);
16095
16096 /* NOTE! We can no longer exit this method via return */
16097 if (copyin(user_address, multi_dof, dof_ioctl_data_size) != 0) {
16098 dtrace_dof_error(NULL, "failed copyin of dof_ioctl_data_t");
16099 rval = EFAULT;
16100 goto cleanup;
16101 }
16102
16103 /*
16104 * Check that the count didn't change between the first copyin and the second.
16105 */
16106 if (multi_dof->dofiod_count != dof_count) {
16107 rval = EINVAL;
16108 goto cleanup;
16109 }
16110
16111 /*
16112 * Try to process lazily first.
16113 */
16114 rval = dtrace_lazy_dofs_add(p, multi_dof, &multi_dof_claimed);
16115
16116 /*
16117 * If rval is EACCES, we must be non-lazy.
16118 */
16119 if (rval == EACCES) {
16120 rval = 0;
16121 /*
16122 * Process each dof_helper_t
16123 */
16124 i = 0;
16125 do {
16126 dhp = &multi_dof->dofiod_helpers[i];
16127
16128 dof_hdr_t *dof = dtrace_dof_copyin(dhp->dofhp_dof, &rval);
16129
16130 if (dof != NULL) {
16131 lck_mtx_lock(&dtrace_lock);
16132
16133 /*
16134 * dtrace_helper_slurp() takes responsibility for the dof --
16135 * it may free it now or it may save it and free it later.
16136 */
16137 if ((dhp->dofhp_dof = (uint64_t)dtrace_helper_slurp(p, dof, dhp)) == -1ULL) {
16138 rval = EINVAL;
16139 }
16140
16141 lck_mtx_unlock(&dtrace_lock);
16142 }
16143 } while (++i < multi_dof->dofiod_count && rval == 0);
16144 }
16145
16146 /*
16147 * We need to copyout the multi_dof struct, because it contains
16148 * the generation (unique id) values needed to call DTRACEHIOC_REMOVE
16149 *
16150 * This could certainly be better optimized.
16151 */
16152 if (copyout(multi_dof, user_address, dof_ioctl_data_size) != 0) {
16153 dtrace_dof_error(NULL, "failed copyout of dof_ioctl_data_t");
16154 /* Don't overwrite pre-existing error code */
16155 if (rval == 0) rval = EFAULT;
16156 }
16157
16158 cleanup:
16159 /*
16160 * If we had to allocate struct memory, free it.
16161 */
16162 if (multi_dof != NULL && !multi_dof_claimed) {
16163 kmem_free(multi_dof, dof_ioctl_data_size);
16164 }
16165
16166 return rval;
16167 }
16168
16169 case DTRACEHIOC_REMOVE: {
16170 int generation = *(int*)arg;
16171 proc_t* p = current_proc();
16172
16173 /*
16174 * Try lazy first.
16175 */
16176 int rval = dtrace_lazy_dofs_remove(p, generation);
16177
16178 /*
16179 * EACCES means non-lazy
16180 */
16181 if (rval == EACCES) {
16182 lck_mtx_lock(&dtrace_lock);
16183 rval = dtrace_helper_destroygen(p, generation);
16184 lck_mtx_unlock(&dtrace_lock);
16185 }
16186
16187 return (rval);
16188 }
16189
16190 default:
16191 break;
16192 }
16193
16194 return ENOTTY;
16195 }
16196
16197 /*ARGSUSED*/
16198 static int
16199 dtrace_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
16200 {
16201 #pragma unused(md)
16202 minor_t minor = getminor(dev);
16203 dtrace_state_t *state;
16204 int rval;
16205
16206 /* Darwin puts Helper on its own major device. */
16207
16208 state = ddi_get_soft_state(dtrace_softstate, minor);
16209
16210 if (state->dts_anon) {
16211 ASSERT(dtrace_anon.dta_state == NULL);
16212 state = state->dts_anon;
16213 }
16214
16215 switch (cmd) {
16216 case DTRACEIOC_PROVIDER: {
16217 dtrace_providerdesc_t pvd;
16218 dtrace_provider_t *pvp;
16219
16220 if (copyin(arg, &pvd, sizeof (pvd)) != 0)
16221 return (EFAULT);
16222
16223 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16224 lck_mtx_lock(&dtrace_provider_lock);
16225
16226 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16227 if (strncmp(pvp->dtpv_name, pvd.dtvd_name, DTRACE_PROVNAMELEN) == 0)
16228 break;
16229 }
16230
16231 lck_mtx_unlock(&dtrace_provider_lock);
16232
16233 if (pvp == NULL)
16234 return (ESRCH);
16235
16236 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16237 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16238 if (copyout(&pvd, arg, sizeof (pvd)) != 0)
16239 return (EFAULT);
16240
16241 return (0);
16242 }
16243
16244 case DTRACEIOC_EPROBE: {
16245 dtrace_eprobedesc_t epdesc;
16246 dtrace_ecb_t *ecb;
16247 dtrace_action_t *act;
16248 void *buf;
16249 size_t size;
16250 uintptr_t dest;
16251 int nrecs;
16252
16253 if (copyin(arg, &epdesc, sizeof (epdesc)) != 0)
16254 return (EFAULT);
16255
16256 lck_mtx_lock(&dtrace_lock);
16257
16258 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16259 lck_mtx_unlock(&dtrace_lock);
16260 return (EINVAL);
16261 }
16262
16263 if (ecb->dte_probe == NULL) {
16264 lck_mtx_unlock(&dtrace_lock);
16265 return (EINVAL);
16266 }
16267
16268 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16269 epdesc.dtepd_uarg = ecb->dte_uarg;
16270 epdesc.dtepd_size = ecb->dte_size;
16271
16272 nrecs = epdesc.dtepd_nrecs;
16273 epdesc.dtepd_nrecs = 0;
16274 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16275 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16276 continue;
16277
16278 epdesc.dtepd_nrecs++;
16279 }
16280
16281 /*
16282 * Now that we have the size, we need to allocate a temporary
16283 * buffer in which to store the complete description. We need
16284 * the temporary buffer to be able to drop dtrace_lock()
16285 * across the copyout(), below.
16286 */
16287 size = sizeof (dtrace_eprobedesc_t) +
16288 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16289
16290 buf = kmem_alloc(size, KM_SLEEP);
16291 dest = (uintptr_t)buf;
16292
16293 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16294 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16295
16296 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16297 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16298 continue;
16299
16300 if (nrecs-- == 0)
16301 break;
16302
16303 bcopy(&act->dta_rec, (void *)dest,
16304 sizeof (dtrace_recdesc_t));
16305 dest += sizeof (dtrace_recdesc_t);
16306 }
16307
16308 lck_mtx_unlock(&dtrace_lock);
16309
16310 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16311 kmem_free(buf, size);
16312 return (EFAULT);
16313 }
16314
16315 kmem_free(buf, size);
16316 return (0);
16317 }
16318
16319 case DTRACEIOC_AGGDESC: {
16320 dtrace_aggdesc_t aggdesc;
16321 dtrace_action_t *act;
16322 dtrace_aggregation_t *agg;
16323 int nrecs;
16324 uint32_t offs;
16325 dtrace_recdesc_t *lrec;
16326 void *buf;
16327 size_t size;
16328 uintptr_t dest;
16329
16330 if (copyin(arg, &aggdesc, sizeof (aggdesc)) != 0)
16331 return (EFAULT);
16332
16333 lck_mtx_lock(&dtrace_lock);
16334
16335 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16336 lck_mtx_unlock(&dtrace_lock);
16337 return (EINVAL);
16338 }
16339
16340 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16341
16342 nrecs = aggdesc.dtagd_nrecs;
16343 aggdesc.dtagd_nrecs = 0;
16344
16345 offs = agg->dtag_base;
16346 lrec = &agg->dtag_action.dta_rec;
16347 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16348
16349 for (act = agg->dtag_first; ; act = act->dta_next) {
16350 ASSERT(act->dta_intuple ||
16351 DTRACEACT_ISAGG(act->dta_kind));
16352
16353 /*
16354 * If this action has a record size of zero, it
16355 * denotes an argument to the aggregating action.
16356 * Because the presence of this record doesn't (or
16357 * shouldn't) affect the way the data is interpreted,
16358 * we don't copy it out to save user-level the
16359 * confusion of dealing with a zero-length record.
16360 */
16361 if (act->dta_rec.dtrd_size == 0) {
16362 ASSERT(agg->dtag_hasarg);
16363 continue;
16364 }
16365
16366 aggdesc.dtagd_nrecs++;
16367
16368 if (act == &agg->dtag_action)
16369 break;
16370 }
16371
16372 /*
16373 * Now that we have the size, we need to allocate a temporary
16374 * buffer in which to store the complete description. We need
16375 * the temporary buffer to be able to drop dtrace_lock()
16376 * across the copyout(), below.
16377 */
16378 size = sizeof (dtrace_aggdesc_t) +
16379 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16380
16381 buf = kmem_alloc(size, KM_SLEEP);
16382 dest = (uintptr_t)buf;
16383
16384 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16385 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16386
16387 for (act = agg->dtag_first; ; act = act->dta_next) {
16388 dtrace_recdesc_t rec = act->dta_rec;
16389
16390 /*
16391 * See the comment in the above loop for why we pass
16392 * over zero-length records.
16393 */
16394 if (rec.dtrd_size == 0) {
16395 ASSERT(agg->dtag_hasarg);
16396 continue;
16397 }
16398
16399 if (nrecs-- == 0)
16400 break;
16401
16402 rec.dtrd_offset -= offs;
16403 bcopy(&rec, (void *)dest, sizeof (rec));
16404 dest += sizeof (dtrace_recdesc_t);
16405
16406 if (act == &agg->dtag_action)
16407 break;
16408 }
16409
16410 lck_mtx_unlock(&dtrace_lock);
16411
16412 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16413 kmem_free(buf, size);
16414 return (EFAULT);
16415 }
16416
16417 kmem_free(buf, size);
16418 return (0);
16419 }
16420
16421 case DTRACEIOC_ENABLE: {
16422 dof_hdr_t *dof;
16423 dtrace_enabling_t *enab = NULL;
16424 dtrace_vstate_t *vstate;
16425 int err = 0;
16426
16427 *rv = 0;
16428
16429 /*
16430 * If a NULL argument has been passed, we take this as our
16431 * cue to reevaluate our enablings.
16432 */
16433 if (arg == 0) {
16434 dtrace_enabling_matchall();
16435
16436 return (0);
16437 }
16438
16439 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16440 return (rval);
16441
16442 lck_mtx_lock(&cpu_lock);
16443 lck_mtx_lock(&dtrace_lock);
16444 vstate = &state->dts_vstate;
16445
16446 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16447 lck_mtx_unlock(&dtrace_lock);
16448 lck_mtx_unlock(&cpu_lock);
16449 dtrace_dof_destroy(dof);
16450 return (EBUSY);
16451 }
16452
16453 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16454 lck_mtx_unlock(&dtrace_lock);
16455 lck_mtx_unlock(&cpu_lock);
16456 dtrace_dof_destroy(dof);
16457 return (EINVAL);
16458 }
16459
16460 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16461 dtrace_enabling_destroy(enab);
16462 lck_mtx_unlock(&dtrace_lock);
16463 lck_mtx_unlock(&cpu_lock);
16464 dtrace_dof_destroy(dof);
16465 return (rval);
16466 }
16467
16468 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16469 err = dtrace_enabling_retain(enab);
16470 } else {
16471 dtrace_enabling_destroy(enab);
16472 }
16473
16474 lck_mtx_unlock(&dtrace_lock);
16475 lck_mtx_unlock(&cpu_lock);
16476 dtrace_dof_destroy(dof);
16477
16478 return (err);
16479 }
16480
16481 case DTRACEIOC_REPLICATE: {
16482 dtrace_repldesc_t desc;
16483 dtrace_probedesc_t *match = &desc.dtrpd_match;
16484 dtrace_probedesc_t *create = &desc.dtrpd_create;
16485 int err;
16486
16487 if (copyin(arg, &desc, sizeof (desc)) != 0)
16488 return (EFAULT);
16489
16490 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16491 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16492 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16493 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16494
16495 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16496 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16497 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16498 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16499
16500 lck_mtx_lock(&dtrace_lock);
16501 err = dtrace_enabling_replicate(state, match, create);
16502 lck_mtx_unlock(&dtrace_lock);
16503
16504 return (err);
16505 }
16506
16507 case DTRACEIOC_PROBEMATCH:
16508 case DTRACEIOC_PROBES: {
16509 dtrace_probe_t *probe = NULL;
16510 dtrace_probedesc_t desc;
16511 dtrace_probekey_t pkey;
16512 dtrace_id_t i;
16513 int m = 0;
16514 uint32_t priv;
16515 uid_t uid;
16516 zoneid_t zoneid;
16517
16518 if (copyin(arg, &desc, sizeof (desc)) != 0)
16519 return (EFAULT);
16520
16521 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16522 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16523 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16524 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16525
16526 /*
16527 * Before we attempt to match this probe, we want to give
16528 * all providers the opportunity to provide it.
16529 */
16530 if (desc.dtpd_id == DTRACE_IDNONE) {
16531 lck_mtx_lock(&dtrace_provider_lock);
16532 dtrace_probe_provide(&desc, NULL);
16533 lck_mtx_unlock(&dtrace_provider_lock);
16534 desc.dtpd_id++;
16535 }
16536
16537 if (cmd == DTRACEIOC_PROBEMATCH) {
16538 dtrace_probekey(&desc, &pkey);
16539 pkey.dtpk_id = DTRACE_IDNONE;
16540 }
16541
16542 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16543
16544 lck_mtx_lock(&dtrace_lock);
16545
16546 if (cmd == DTRACEIOC_PROBEMATCH) {
16547 /* Quiet compiler warning */
16548 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
16549 if ((probe = dtrace_probes[i - 1]) != NULL &&
16550 (m = dtrace_match_probe(probe, &pkey,
16551 priv, uid, zoneid)) != 0)
16552 break;
16553 }
16554
16555 if (m < 0) {
16556 lck_mtx_unlock(&dtrace_lock);
16557 return (EINVAL);
16558 }
16559
16560 } else {
16561 /* Quiet compiler warning */
16562 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
16563 if ((probe = dtrace_probes[i - 1]) != NULL &&
16564 dtrace_match_priv(probe, priv, uid, zoneid))
16565 break;
16566 }
16567 }
16568
16569 if (probe == NULL) {
16570 lck_mtx_unlock(&dtrace_lock);
16571 return (ESRCH);
16572 }
16573
16574 dtrace_probe_description(probe, &desc);
16575 lck_mtx_unlock(&dtrace_lock);
16576
16577 if (copyout(&desc, arg, sizeof (desc)) != 0)
16578 return (EFAULT);
16579
16580 return (0);
16581 }
16582
16583 case DTRACEIOC_PROBEARG: {
16584 dtrace_argdesc_t desc;
16585 dtrace_probe_t *probe;
16586 dtrace_provider_t *prov;
16587
16588 if (copyin(arg, &desc, sizeof (desc)) != 0)
16589 return (EFAULT);
16590
16591 if (desc.dtargd_id == DTRACE_IDNONE)
16592 return (EINVAL);
16593
16594 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16595 return (EINVAL);
16596
16597 lck_mtx_lock(&dtrace_provider_lock);
16598 lck_mtx_lock(&mod_lock);
16599 lck_mtx_lock(&dtrace_lock);
16600
16601 /* Quiet compiler warning */
16602 if (desc.dtargd_id > (dtrace_id_t)dtrace_nprobes) {
16603 lck_mtx_unlock(&dtrace_lock);
16604 lck_mtx_unlock(&mod_lock);
16605 lck_mtx_unlock(&dtrace_provider_lock);
16606 return (EINVAL);
16607 }
16608
16609 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16610 lck_mtx_unlock(&dtrace_lock);
16611 lck_mtx_unlock(&mod_lock);
16612 lck_mtx_unlock(&dtrace_provider_lock);
16613 return (EINVAL);
16614 }
16615
16616 lck_mtx_unlock(&dtrace_lock);
16617
16618 prov = probe->dtpr_provider;
16619
16620 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16621 /*
16622 * There isn't any typed information for this probe.
16623 * Set the argument number to DTRACE_ARGNONE.
16624 */
16625 desc.dtargd_ndx = DTRACE_ARGNONE;
16626 } else {
16627 desc.dtargd_native[0] = '\0';
16628 desc.dtargd_xlate[0] = '\0';
16629 desc.dtargd_mapping = desc.dtargd_ndx;
16630
16631 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16632 probe->dtpr_id, probe->dtpr_arg, &desc);
16633 }
16634
16635 lck_mtx_unlock(&mod_lock);
16636 lck_mtx_unlock(&dtrace_provider_lock);
16637
16638 if (copyout(&desc, arg, sizeof (desc)) != 0)
16639 return (EFAULT);
16640
16641 return (0);
16642 }
16643
16644 case DTRACEIOC_GO: {
16645 processorid_t cpuid;
16646 rval = dtrace_state_go(state, &cpuid);
16647
16648 if (rval != 0)
16649 return (rval);
16650
16651 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
16652 return (EFAULT);
16653
16654 return (0);
16655 }
16656
16657 case DTRACEIOC_STOP: {
16658 processorid_t cpuid;
16659
16660 lck_mtx_lock(&dtrace_lock);
16661 rval = dtrace_state_stop(state, &cpuid);
16662 lck_mtx_unlock(&dtrace_lock);
16663
16664 if (rval != 0)
16665 return (rval);
16666
16667 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
16668 return (EFAULT);
16669
16670 return (0);
16671 }
16672
16673 case DTRACEIOC_DOFGET: {
16674 dof_hdr_t hdr, *dof;
16675 uint64_t len;
16676
16677 if (copyin(arg, &hdr, sizeof (hdr)) != 0)
16678 return (EFAULT);
16679
16680 lck_mtx_lock(&dtrace_lock);
16681 dof = dtrace_dof_create(state);
16682 lck_mtx_unlock(&dtrace_lock);
16683
16684 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16685 rval = copyout(dof, arg, len);
16686 dtrace_dof_destroy(dof);
16687
16688 return (rval == 0 ? 0 : EFAULT);
16689 }
16690
16691 case DTRACEIOC_AGGSNAP:
16692 case DTRACEIOC_BUFSNAP: {
16693 dtrace_bufdesc_t desc;
16694 caddr_t cached;
16695 dtrace_buffer_t *buf;
16696
16697 if (copyin(arg, &desc, sizeof (desc)) != 0)
16698 return (EFAULT);
16699
16700 if ((int)desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16701 return (EINVAL);
16702
16703 lck_mtx_lock(&dtrace_lock);
16704
16705 if (cmd == DTRACEIOC_BUFSNAP) {
16706 buf = &state->dts_buffer[desc.dtbd_cpu];
16707 } else {
16708 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16709 }
16710
16711 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16712 size_t sz = buf->dtb_offset;
16713
16714 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16715 lck_mtx_unlock(&dtrace_lock);
16716 return (EBUSY);
16717 }
16718
16719 /*
16720 * If this buffer has already been consumed, we're
16721 * going to indicate that there's nothing left here
16722 * to consume.
16723 */
16724 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16725 lck_mtx_unlock(&dtrace_lock);
16726
16727 desc.dtbd_size = 0;
16728 desc.dtbd_drops = 0;
16729 desc.dtbd_errors = 0;
16730 desc.dtbd_oldest = 0;
16731 sz = sizeof (desc);
16732
16733 if (copyout(&desc, arg, sz) != 0)
16734 return (EFAULT);
16735
16736 return (0);
16737 }
16738
16739 /*
16740 * If this is a ring buffer that has wrapped, we want
16741 * to copy the whole thing out.
16742 */
16743 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16744 dtrace_buffer_polish(buf);
16745 sz = buf->dtb_size;
16746 }
16747
16748 if (copyout(buf->dtb_tomax, (user_addr_t)desc.dtbd_data, sz) != 0) {
16749 lck_mtx_unlock(&dtrace_lock);
16750 return (EFAULT);
16751 }
16752
16753 desc.dtbd_size = sz;
16754 desc.dtbd_drops = buf->dtb_drops;
16755 desc.dtbd_errors = buf->dtb_errors;
16756 desc.dtbd_oldest = buf->dtb_xamot_offset;
16757 desc.dtbd_timestamp = dtrace_gethrtime();
16758
16759 lck_mtx_unlock(&dtrace_lock);
16760
16761 if (copyout(&desc, arg, sizeof (desc)) != 0)
16762 return (EFAULT);
16763
16764 buf->dtb_flags |= DTRACEBUF_CONSUMED;
16765
16766 return (0);
16767 }
16768
16769 if (buf->dtb_tomax == NULL) {
16770 ASSERT(buf->dtb_xamot == NULL);
16771 lck_mtx_unlock(&dtrace_lock);
16772 return (ENOENT);
16773 }
16774
16775 cached = buf->dtb_tomax;
16776 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16777
16778 dtrace_xcall(desc.dtbd_cpu,
16779 (dtrace_xcall_t)dtrace_buffer_switch, buf);
16780
16781 state->dts_errors += buf->dtb_xamot_errors;
16782
16783 /*
16784 * If the buffers did not actually switch, then the cross call
16785 * did not take place -- presumably because the given CPU is
16786 * not in the ready set. If this is the case, we'll return
16787 * ENOENT.
16788 */
16789 if (buf->dtb_tomax == cached) {
16790 ASSERT(buf->dtb_xamot != cached);
16791 lck_mtx_unlock(&dtrace_lock);
16792 return (ENOENT);
16793 }
16794
16795 ASSERT(cached == buf->dtb_xamot);
16796
16797 /*
16798 * We have our snapshot; now copy it out.
16799 */
16800 if (copyout(buf->dtb_xamot, (user_addr_t)desc.dtbd_data,
16801 buf->dtb_xamot_offset) != 0) {
16802 lck_mtx_unlock(&dtrace_lock);
16803 return (EFAULT);
16804 }
16805
16806 desc.dtbd_size = buf->dtb_xamot_offset;
16807 desc.dtbd_drops = buf->dtb_xamot_drops;
16808 desc.dtbd_errors = buf->dtb_xamot_errors;
16809 desc.dtbd_oldest = 0;
16810 desc.dtbd_timestamp = buf->dtb_switched;
16811
16812 lck_mtx_unlock(&dtrace_lock);
16813
16814 /*
16815 * Finally, copy out the buffer description.
16816 */
16817 if (copyout(&desc, arg, sizeof (desc)) != 0)
16818 return (EFAULT);
16819
16820 return (0);
16821 }
16822
16823 case DTRACEIOC_CONF: {
16824 dtrace_conf_t conf;
16825
16826 bzero(&conf, sizeof (conf));
16827 conf.dtc_difversion = DIF_VERSION;
16828 conf.dtc_difintregs = DIF_DIR_NREGS;
16829 conf.dtc_diftupregs = DIF_DTR_NREGS;
16830 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16831
16832 if (copyout(&conf, arg, sizeof (conf)) != 0)
16833 return (EFAULT);
16834
16835 return (0);
16836 }
16837
16838 case DTRACEIOC_STATUS: {
16839 dtrace_status_t stat;
16840 dtrace_dstate_t *dstate;
16841 int i, j;
16842 uint64_t nerrs;
16843
16844 /*
16845 * See the comment in dtrace_state_deadman() for the reason
16846 * for setting dts_laststatus to INT64_MAX before setting
16847 * it to the correct value.
16848 */
16849 state->dts_laststatus = INT64_MAX;
16850 dtrace_membar_producer();
16851 state->dts_laststatus = dtrace_gethrtime();
16852
16853 bzero(&stat, sizeof (stat));
16854
16855 lck_mtx_lock(&dtrace_lock);
16856
16857 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16858 lck_mtx_unlock(&dtrace_lock);
16859 return (ENOENT);
16860 }
16861
16862 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16863 stat.dtst_exiting = 1;
16864
16865 nerrs = state->dts_errors;
16866 dstate = &state->dts_vstate.dtvs_dynvars;
16867
16868 for (i = 0; i < (int)NCPU; i++) {
16869 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16870
16871 stat.dtst_dyndrops += dcpu->dtdsc_drops;
16872 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16873 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16874
16875 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16876 stat.dtst_filled++;
16877
16878 nerrs += state->dts_buffer[i].dtb_errors;
16879
16880 for (j = 0; j < state->dts_nspeculations; j++) {
16881 dtrace_speculation_t *spec;
16882 dtrace_buffer_t *buf;
16883
16884 spec = &state->dts_speculations[j];
16885 buf = &spec->dtsp_buffer[i];
16886 stat.dtst_specdrops += buf->dtb_xamot_drops;
16887 }
16888 }
16889
16890 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16891 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16892 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16893 stat.dtst_dblerrors = state->dts_dblerrors;
16894 stat.dtst_killed =
16895 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16896 stat.dtst_errors = nerrs;
16897
16898 lck_mtx_unlock(&dtrace_lock);
16899
16900 if (copyout(&stat, arg, sizeof (stat)) != 0)
16901 return (EFAULT);
16902
16903 return (0);
16904 }
16905
16906 case DTRACEIOC_FORMAT: {
16907 dtrace_fmtdesc_t fmt;
16908 char *str;
16909 int len;
16910
16911 if (copyin(arg, &fmt, sizeof (fmt)) != 0)
16912 return (EFAULT);
16913
16914 lck_mtx_lock(&dtrace_lock);
16915
16916 if (fmt.dtfd_format == 0 ||
16917 fmt.dtfd_format > state->dts_nformats) {
16918 lck_mtx_unlock(&dtrace_lock);
16919 return (EINVAL);
16920 }
16921
16922 /*
16923 * Format strings are allocated contiguously and they are
16924 * never freed; if a format index is less than the number
16925 * of formats, we can assert that the format map is non-NULL
16926 * and that the format for the specified index is non-NULL.
16927 */
16928 ASSERT(state->dts_formats != NULL);
16929 str = state->dts_formats[fmt.dtfd_format - 1];
16930 ASSERT(str != NULL);
16931
16932 len = strlen(str) + 1;
16933
16934 if (len > fmt.dtfd_length) {
16935 fmt.dtfd_length = len;
16936
16937 if (copyout(&fmt, arg, sizeof (fmt)) != 0) {
16938 lck_mtx_unlock(&dtrace_lock);
16939 return (EINVAL);
16940 }
16941 } else {
16942 if (copyout(str, (user_addr_t)fmt.dtfd_string, len) != 0) {
16943 lck_mtx_unlock(&dtrace_lock);
16944 return (EINVAL);
16945 }
16946 }
16947
16948 lck_mtx_unlock(&dtrace_lock);
16949 return (0);
16950 }
16951
16952 case DTRACEIOC_MODUUIDSLIST: {
16953 size_t module_uuids_list_size;
16954 dtrace_module_uuids_list_t* uuids_list;
16955 uint64_t dtmul_count;
16956
16957 /*
16958 * Security restrictions make this operation illegal, if this is enabled DTrace
16959 * must refuse to provide any fbt probes.
16960 */
16961 if (dtrace_fbt_probes_restricted()) {
16962 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
16963 return (EPERM);
16964 }
16965
16966 /*
16967 * Fail if the kernel symbol mode makes this operation illegal.
16968 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
16969 * for them without holding the dtrace_lock.
16970 */
16971 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
16972 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
16973 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_MODUUIDSLIST", dtrace_kernel_symbol_mode);
16974 return (EPERM);
16975 }
16976
16977 /*
16978 * Read the number of symbolsdesc structs being passed in.
16979 */
16980 if (copyin(arg + offsetof(dtrace_module_uuids_list_t, dtmul_count),
16981 &dtmul_count,
16982 sizeof(dtmul_count))) {
16983 cmn_err(CE_WARN, "failed to copyin dtmul_count");
16984 return (EFAULT);
16985 }
16986
16987 /*
16988 * Range check the count. More than 2k kexts is probably an error.
16989 */
16990 if (dtmul_count > 2048) {
16991 cmn_err(CE_WARN, "dtmul_count is not valid");
16992 return (EINVAL);
16993 }
16994
16995 /*
16996 * For all queries, we return EINVAL when the user specified
16997 * count does not match the actual number of modules we find
16998 * available.
16999 *
17000 * If the user specified count is zero, then this serves as a
17001 * simple query to count the available modules in need of symbols.
17002 */
17003
17004 rval = 0;
17005
17006 if (dtmul_count == 0)
17007 {
17008 lck_mtx_lock(&mod_lock);
17009 struct modctl* ctl = dtrace_modctl_list;
17010 while (ctl) {
17011 /* Update the private probes bit */
17012 if (dtrace_provide_private_probes)
17013 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17014
17015 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17016 if (!MOD_SYMBOLS_DONE(ctl)) {
17017 dtmul_count++;
17018 rval = EINVAL;
17019 }
17020 ctl = ctl->mod_next;
17021 }
17022 lck_mtx_unlock(&mod_lock);
17023
17024 if (copyout(&dtmul_count, arg, sizeof (dtmul_count)) != 0)
17025 return (EFAULT);
17026 else
17027 return (rval);
17028 }
17029
17030 /*
17031 * If we reach this point, then we have a request for full list data.
17032 * Allocate a correctly sized structure and copyin the data.
17033 */
17034 module_uuids_list_size = DTRACE_MODULE_UUIDS_LIST_SIZE(dtmul_count);
17035 if ((uuids_list = kmem_alloc(module_uuids_list_size, KM_SLEEP)) == NULL)
17036 return (ENOMEM);
17037
17038 /* NOTE! We can no longer exit this method via return */
17039 if (copyin(arg, uuids_list, module_uuids_list_size) != 0) {
17040 cmn_err(CE_WARN, "failed copyin of dtrace_module_uuids_list_t");
17041 rval = EFAULT;
17042 goto moduuidslist_cleanup;
17043 }
17044
17045 /*
17046 * Check that the count didn't change between the first copyin and the second.
17047 */
17048 if (uuids_list->dtmul_count != dtmul_count) {
17049 rval = EINVAL;
17050 goto moduuidslist_cleanup;
17051 }
17052
17053 /*
17054 * Build the list of UUID's that need symbols
17055 */
17056 lck_mtx_lock(&mod_lock);
17057
17058 dtmul_count = 0;
17059
17060 struct modctl* ctl = dtrace_modctl_list;
17061 while (ctl) {
17062 /* Update the private probes bit */
17063 if (dtrace_provide_private_probes)
17064 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17065
17066 /*
17067 * We assume that userspace symbols will be "better" than kernel level symbols,
17068 * as userspace can search for dSYM(s) and symbol'd binaries. Even if kernel syms
17069 * are available, add user syms if the module might use them.
17070 */
17071 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17072 if (!MOD_SYMBOLS_DONE(ctl)) {
17073 UUID* uuid = &uuids_list->dtmul_uuid[dtmul_count];
17074 if (dtmul_count++ < uuids_list->dtmul_count) {
17075 memcpy(uuid, ctl->mod_uuid, sizeof(UUID));
17076 }
17077 }
17078 ctl = ctl->mod_next;
17079 }
17080
17081 lck_mtx_unlock(&mod_lock);
17082
17083 if (uuids_list->dtmul_count < dtmul_count)
17084 rval = EINVAL;
17085
17086 uuids_list->dtmul_count = dtmul_count;
17087
17088 /*
17089 * Copyout the symbols list (or at least the count!)
17090 */
17091 if (copyout(uuids_list, arg, module_uuids_list_size) != 0) {
17092 cmn_err(CE_WARN, "failed copyout of dtrace_symbolsdesc_list_t");
17093 rval = EFAULT;
17094 }
17095
17096 moduuidslist_cleanup:
17097 /*
17098 * If we had to allocate struct memory, free it.
17099 */
17100 if (uuids_list != NULL) {
17101 kmem_free(uuids_list, module_uuids_list_size);
17102 }
17103
17104 return rval;
17105 }
17106
17107 case DTRACEIOC_PROVMODSYMS: {
17108 size_t module_symbols_size;
17109 dtrace_module_symbols_t* module_symbols;
17110 uint64_t dtmodsyms_count;
17111
17112 /*
17113 * Security restrictions make this operation illegal, if this is enabled DTrace
17114 * must refuse to provide any fbt probes.
17115 */
17116 if (dtrace_fbt_probes_restricted()) {
17117 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
17118 return (EPERM);
17119 }
17120
17121 /*
17122 * Fail if the kernel symbol mode makes this operation illegal.
17123 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
17124 * for them without holding the dtrace_lock.
17125 */
17126 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
17127 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
17128 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_PROVMODSYMS", dtrace_kernel_symbol_mode);
17129 return (EPERM);
17130 }
17131
17132 /*
17133 * Read the number of module symbols structs being passed in.
17134 */
17135 if (copyin(arg + offsetof(dtrace_module_symbols_t, dtmodsyms_count),
17136 &dtmodsyms_count,
17137 sizeof(dtmodsyms_count))) {
17138 cmn_err(CE_WARN, "failed to copyin dtmodsyms_count");
17139 return (EFAULT);
17140 }
17141
17142 /*
17143 * Range check the count. How much data can we pass around?
17144 * FIX ME!
17145 */
17146 if (dtmodsyms_count == 0 || (dtmodsyms_count > 100 * 1024)) {
17147 cmn_err(CE_WARN, "dtmodsyms_count is not valid");
17148 return (EINVAL);
17149 }
17150
17151 /*
17152 * Allocate a correctly sized structure and copyin the data.
17153 */
17154 module_symbols_size = DTRACE_MODULE_SYMBOLS_SIZE(dtmodsyms_count);
17155 if ((module_symbols = kmem_alloc(module_symbols_size, KM_SLEEP)) == NULL)
17156 return (ENOMEM);
17157
17158 rval = 0;
17159
17160 /* NOTE! We can no longer exit this method via return */
17161 if (copyin(arg, module_symbols, module_symbols_size) != 0) {
17162 cmn_err(CE_WARN, "failed copyin of dtrace_module_symbols_t, symbol count %llu", module_symbols->dtmodsyms_count);
17163 rval = EFAULT;
17164 goto module_symbols_cleanup;
17165 }
17166
17167 /*
17168 * Check that the count didn't change between the first copyin and the second.
17169 */
17170 if (module_symbols->dtmodsyms_count != dtmodsyms_count) {
17171 rval = EINVAL;
17172 goto module_symbols_cleanup;
17173 }
17174
17175 /*
17176 * Find the modctl to add symbols to.
17177 */
17178 lck_mtx_lock(&dtrace_provider_lock);
17179 lck_mtx_lock(&mod_lock);
17180
17181 struct modctl* ctl = dtrace_modctl_list;
17182 while (ctl) {
17183 /* Update the private probes bit */
17184 if (dtrace_provide_private_probes)
17185 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17186
17187 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17188 if (MOD_HAS_UUID(ctl) && !MOD_SYMBOLS_DONE(ctl)) {
17189 if (memcmp(module_symbols->dtmodsyms_uuid, ctl->mod_uuid, sizeof(UUID)) == 0) {
17190 /* BINGO! */
17191 ctl->mod_user_symbols = module_symbols;
17192 break;
17193 }
17194 }
17195 ctl = ctl->mod_next;
17196 }
17197
17198 if (ctl) {
17199 dtrace_provider_t *prv;
17200
17201 /*
17202 * We're going to call each providers per-module provide operation
17203 * specifying only this module.
17204 */
17205 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
17206 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
17207
17208 /*
17209 * We gave every provider a chance to provide with the user syms, go ahead and clear them
17210 */
17211 ctl->mod_user_symbols = NULL; /* MUST reset this to clear HAS_USERSPACE_SYMBOLS */
17212 }
17213
17214 lck_mtx_unlock(&mod_lock);
17215 lck_mtx_unlock(&dtrace_provider_lock);
17216
17217 module_symbols_cleanup:
17218 /*
17219 * If we had to allocate struct memory, free it.
17220 */
17221 if (module_symbols != NULL) {
17222 kmem_free(module_symbols, module_symbols_size);
17223 }
17224
17225 return rval;
17226 }
17227
17228 case DTRACEIOC_PROCWAITFOR: {
17229 dtrace_procdesc_t pdesc = {
17230 .p_name = {0},
17231 .p_pid = -1
17232 };
17233
17234 if ((rval = copyin(arg, &pdesc, sizeof(pdesc))) != 0)
17235 goto proc_waitfor_error;
17236
17237 if ((rval = dtrace_proc_waitfor(&pdesc)) != 0)
17238 goto proc_waitfor_error;
17239
17240 if ((rval = copyout(&pdesc, arg, sizeof(pdesc))) != 0)
17241 goto proc_waitfor_error;
17242
17243 return 0;
17244
17245 proc_waitfor_error:
17246 /* The process was suspended, revert this since the client will not do it. */
17247 if (pdesc.p_pid != -1) {
17248 proc_t *proc = proc_find(pdesc.p_pid);
17249 if (proc != PROC_NULL) {
17250 task_pidresume(proc->task);
17251 proc_rele(proc);
17252 }
17253 }
17254
17255 return rval;
17256 }
17257
17258 default:
17259 break;
17260 }
17261
17262 return (ENOTTY);
17263 }
17264
17265 /*
17266 * APPLE NOTE: dtrace_detach not implemented
17267 */
17268 #if !defined(__APPLE__)
17269 /*ARGSUSED*/
17270 static int
17271 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17272 {
17273 dtrace_state_t *state;
17274
17275 switch (cmd) {
17276 case DDI_DETACH:
17277 break;
17278
17279 case DDI_SUSPEND:
17280 return (DDI_SUCCESS);
17281
17282 default:
17283 return (DDI_FAILURE);
17284 }
17285
17286 lck_mtx_lock(&cpu_lock);
17287 lck_mtx_lock(&dtrace_provider_lock);
17288 lck_mtx_lock(&dtrace_lock);
17289
17290 ASSERT(dtrace_opens == 0);
17291
17292 if (dtrace_helpers > 0) {
17293 lck_mtx_unlock(&dtrace_lock);
17294 lck_mtx_unlock(&dtrace_provider_lock);
17295 lck_mtx_unlock(&cpu_lock);
17296 return (DDI_FAILURE);
17297 }
17298
17299 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17300 lck_mtx_unlock(&dtrace_lock);
17301 lck_mtx_unlock(&dtrace_provider_lock);
17302 lck_mtx_unlock(&cpu_lock);
17303 return (DDI_FAILURE);
17304 }
17305
17306 dtrace_provider = NULL;
17307
17308 if ((state = dtrace_anon_grab()) != NULL) {
17309 /*
17310 * If there were ECBs on this state, the provider should
17311 * have not been allowed to detach; assert that there is
17312 * none.
17313 */
17314 ASSERT(state->dts_necbs == 0);
17315 dtrace_state_destroy(state);
17316
17317 /*
17318 * If we're being detached with anonymous state, we need to
17319 * indicate to the kernel debugger that DTrace is now inactive.
17320 */
17321 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17322 }
17323
17324 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17325 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17326 dtrace_cpu_init = NULL;
17327 dtrace_helpers_cleanup = NULL;
17328 dtrace_helpers_fork = NULL;
17329 dtrace_cpustart_init = NULL;
17330 dtrace_cpustart_fini = NULL;
17331 dtrace_debugger_init = NULL;
17332 dtrace_debugger_fini = NULL;
17333 dtrace_kreloc_init = NULL;
17334 dtrace_kreloc_fini = NULL;
17335 dtrace_modload = NULL;
17336 dtrace_modunload = NULL;
17337
17338 lck_mtx_unlock(&cpu_lock);
17339
17340 if (dtrace_helptrace_enabled) {
17341 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17342 dtrace_helptrace_buffer = NULL;
17343 }
17344
17345 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17346 dtrace_probes = NULL;
17347 dtrace_nprobes = 0;
17348
17349 dtrace_hash_destroy(dtrace_bymod);
17350 dtrace_hash_destroy(dtrace_byfunc);
17351 dtrace_hash_destroy(dtrace_byname);
17352 dtrace_bymod = NULL;
17353 dtrace_byfunc = NULL;
17354 dtrace_byname = NULL;
17355
17356 kmem_cache_destroy(dtrace_state_cache);
17357 vmem_destroy(dtrace_minor);
17358 vmem_destroy(dtrace_arena);
17359
17360 if (dtrace_toxrange != NULL) {
17361 kmem_free(dtrace_toxrange,
17362 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17363 dtrace_toxrange = NULL;
17364 dtrace_toxranges = 0;
17365 dtrace_toxranges_max = 0;
17366 }
17367
17368 ddi_remove_minor_node(dtrace_devi, NULL);
17369 dtrace_devi = NULL;
17370
17371 ddi_soft_state_fini(&dtrace_softstate);
17372
17373 ASSERT(dtrace_vtime_references == 0);
17374 ASSERT(dtrace_opens == 0);
17375 ASSERT(dtrace_retained == NULL);
17376
17377 lck_mtx_unlock(&dtrace_lock);
17378 lck_mtx_unlock(&dtrace_provider_lock);
17379
17380 /*
17381 * We don't destroy the task queue until after we have dropped our
17382 * locks (taskq_destroy() may block on running tasks). To prevent
17383 * attempting to do work after we have effectively detached but before
17384 * the task queue has been destroyed, all tasks dispatched via the
17385 * task queue must check that DTrace is still attached before
17386 * performing any operation.
17387 */
17388 taskq_destroy(dtrace_taskq);
17389 dtrace_taskq = NULL;
17390
17391 return (DDI_SUCCESS);
17392 }
17393 #endif /* __APPLE__ */
17394
17395 d_open_t _dtrace_open, helper_open;
17396 d_close_t _dtrace_close, helper_close;
17397 d_ioctl_t _dtrace_ioctl, helper_ioctl;
17398
17399 int
17400 _dtrace_open(dev_t dev, int flags, int devtype, struct proc *p)
17401 {
17402 #pragma unused(p)
17403 dev_t locdev = dev;
17404
17405 return dtrace_open( &locdev, flags, devtype, CRED());
17406 }
17407
17408 int
17409 helper_open(dev_t dev, int flags, int devtype, struct proc *p)
17410 {
17411 #pragma unused(dev,flags,devtype,p)
17412 return 0;
17413 }
17414
17415 int
17416 _dtrace_close(dev_t dev, int flags, int devtype, struct proc *p)
17417 {
17418 #pragma unused(p)
17419 return dtrace_close( dev, flags, devtype, CRED());
17420 }
17421
17422 int
17423 helper_close(dev_t dev, int flags, int devtype, struct proc *p)
17424 {
17425 #pragma unused(dev,flags,devtype,p)
17426 return 0;
17427 }
17428
17429 int
17430 _dtrace_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
17431 {
17432 #pragma unused(p)
17433 int err, rv = 0;
17434 user_addr_t uaddrp;
17435
17436 if (proc_is64bit(p))
17437 uaddrp = *(user_addr_t *)data;
17438 else
17439 uaddrp = (user_addr_t) *(uint32_t *)data;
17440
17441 err = dtrace_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
17442
17443 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
17444 if (err != 0) {
17445 ASSERT( (err & 0xfffff000) == 0 );
17446 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
17447 } else if (rv != 0) {
17448 ASSERT( (rv & 0xfff00000) == 0 );
17449 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
17450 } else
17451 return 0;
17452 }
17453
17454 int
17455 helper_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
17456 {
17457 #pragma unused(dev,fflag,p)
17458 int err, rv = 0;
17459
17460 err = dtrace_ioctl_helper(cmd, data, &rv);
17461 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
17462 if (err != 0) {
17463 ASSERT( (err & 0xfffff000) == 0 );
17464 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
17465 } else if (rv != 0) {
17466 ASSERT( (rv & 0xfff00000) == 0 );
17467 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
17468 } else
17469 return 0;
17470 }
17471
17472 #define HELPER_MAJOR -24 /* let the kernel pick the device number */
17473
17474 /*
17475 * A struct describing which functions will get invoked for certain
17476 * actions.
17477 */
17478 static struct cdevsw helper_cdevsw =
17479 {
17480 helper_open, /* open */
17481 helper_close, /* close */
17482 eno_rdwrt, /* read */
17483 eno_rdwrt, /* write */
17484 helper_ioctl, /* ioctl */
17485 (stop_fcn_t *)nulldev, /* stop */
17486 (reset_fcn_t *)nulldev, /* reset */
17487 NULL, /* tty's */
17488 eno_select, /* select */
17489 eno_mmap, /* mmap */
17490 eno_strat, /* strategy */
17491 eno_getc, /* getc */
17492 eno_putc, /* putc */
17493 0 /* type */
17494 };
17495
17496 static int helper_majdevno = 0;
17497
17498 static int gDTraceInited = 0;
17499
17500 void
17501 helper_init( void )
17502 {
17503 /*
17504 * Once the "helper" is initialized, it can take ioctl calls that use locks
17505 * and zones initialized in dtrace_init. Make certain dtrace_init was called
17506 * before us.
17507 */
17508
17509 if (!gDTraceInited) {
17510 panic("helper_init before dtrace_init\n");
17511 }
17512
17513 if (0 >= helper_majdevno)
17514 {
17515 helper_majdevno = cdevsw_add(HELPER_MAJOR, &helper_cdevsw);
17516
17517 if (helper_majdevno < 0) {
17518 printf("helper_init: failed to allocate a major number!\n");
17519 return;
17520 }
17521
17522 if (NULL == devfs_make_node( makedev(helper_majdevno, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
17523 DTRACEMNR_HELPER, 0 )) {
17524 printf("dtrace_init: failed to devfs_make_node for helper!\n");
17525 return;
17526 }
17527 } else
17528 panic("helper_init: called twice!\n");
17529 }
17530
17531 #undef HELPER_MAJOR
17532
17533 /*
17534 * Called with DEVFS_LOCK held, so vmem_alloc's underlying blist structures are protected.
17535 */
17536 static int
17537 dtrace_clone_func(dev_t dev, int action)
17538 {
17539 #pragma unused(dev)
17540
17541 if (action == DEVFS_CLONE_ALLOC) {
17542 if (NULL == dtrace_minor) /* Arena not created yet!?! */
17543 return 0;
17544 else {
17545 /*
17546 * Propose a minor number, namely the next number that vmem_alloc() will return.
17547 * Immediately put it back in play by calling vmem_free(). FIXME.
17548 */
17549 int ret = (int)(uintptr_t)vmem_alloc(dtrace_minor, 1, VM_BESTFIT | VM_SLEEP);
17550
17551 vmem_free(dtrace_minor, (void *)(uintptr_t)ret, 1);
17552
17553 return ret;
17554 }
17555 }
17556 else if (action == DEVFS_CLONE_FREE) {
17557 return 0;
17558 }
17559 else return -1;
17560 }
17561
17562 #define DTRACE_MAJOR -24 /* let the kernel pick the device number */
17563
17564 static struct cdevsw dtrace_cdevsw =
17565 {
17566 _dtrace_open, /* open */
17567 _dtrace_close, /* close */
17568 eno_rdwrt, /* read */
17569 eno_rdwrt, /* write */
17570 _dtrace_ioctl, /* ioctl */
17571 (stop_fcn_t *)nulldev, /* stop */
17572 (reset_fcn_t *)nulldev, /* reset */
17573 NULL, /* tty's */
17574 eno_select, /* select */
17575 eno_mmap, /* mmap */
17576 eno_strat, /* strategy */
17577 eno_getc, /* getc */
17578 eno_putc, /* putc */
17579 0 /* type */
17580 };
17581
17582 lck_attr_t* dtrace_lck_attr;
17583 lck_grp_attr_t* dtrace_lck_grp_attr;
17584 lck_grp_t* dtrace_lck_grp;
17585
17586 static int gMajDevNo;
17587
17588 void
17589 dtrace_init( void )
17590 {
17591 if (0 == gDTraceInited) {
17592 int i, ncpu;
17593 size_t size = sizeof(dtrace_buffer_memory_maxsize);
17594
17595 /*
17596 * DTrace allocates buffers based on the maximum number
17597 * of enabled cpus. This call avoids any race when finding
17598 * that count.
17599 */
17600 ASSERT(dtrace_max_cpus == 0);
17601 ncpu = dtrace_max_cpus = ml_get_max_cpus();
17602
17603 /*
17604 * Retrieve the size of the physical memory in order to define
17605 * the state buffer memory maximal size. If we cannot retrieve
17606 * this value, we'll consider that we have 1Gb of memory per CPU, that's
17607 * still better than raising a kernel panic.
17608 */
17609 if (0 != kernel_sysctlbyname("hw.memsize", &dtrace_buffer_memory_maxsize,
17610 &size, NULL, 0))
17611 {
17612 dtrace_buffer_memory_maxsize = ncpu * 1024 * 1024 * 1024;
17613 printf("dtrace_init: failed to retrieve the hw.memsize, defaulted to %lld bytes\n",
17614 dtrace_buffer_memory_maxsize);
17615 }
17616
17617 /*
17618 * Finally, divide by three to prevent DTrace from eating too
17619 * much memory.
17620 */
17621 dtrace_buffer_memory_maxsize /= 3;
17622 ASSERT(dtrace_buffer_memory_maxsize > 0);
17623
17624 gMajDevNo = cdevsw_add(DTRACE_MAJOR, &dtrace_cdevsw);
17625
17626 if (gMajDevNo < 0) {
17627 printf("dtrace_init: failed to allocate a major number!\n");
17628 gDTraceInited = 0;
17629 return;
17630 }
17631
17632 if (NULL == devfs_make_node_clone( makedev(gMajDevNo, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
17633 dtrace_clone_func, DTRACEMNR_DTRACE, 0 )) {
17634 printf("dtrace_init: failed to devfs_make_node_clone for dtrace!\n");
17635 gDTraceInited = 0;
17636 return;
17637 }
17638
17639 #if defined(DTRACE_MEMORY_ZONES)
17640 /*
17641 * Initialize the dtrace kalloc-emulation zones.
17642 */
17643 dtrace_alloc_init();
17644 #endif /* DTRACE_MEMORY_ZONES */
17645
17646 /*
17647 * Allocate the dtrace_probe_t zone
17648 */
17649 dtrace_probe_t_zone = zinit(sizeof(dtrace_probe_t),
17650 1024 * sizeof(dtrace_probe_t),
17651 sizeof(dtrace_probe_t),
17652 "dtrace.dtrace_probe_t");
17653
17654 /*
17655 * Create the dtrace lock group and attrs.
17656 */
17657 dtrace_lck_attr = lck_attr_alloc_init();
17658 dtrace_lck_grp_attr= lck_grp_attr_alloc_init();
17659 dtrace_lck_grp = lck_grp_alloc_init("dtrace", dtrace_lck_grp_attr);
17660
17661 /*
17662 * We have to initialize all locks explicitly
17663 */
17664 lck_mtx_init(&dtrace_lock, dtrace_lck_grp, dtrace_lck_attr);
17665 lck_mtx_init(&dtrace_provider_lock, dtrace_lck_grp, dtrace_lck_attr);
17666 lck_mtx_init(&dtrace_meta_lock, dtrace_lck_grp, dtrace_lck_attr);
17667 lck_mtx_init(&dtrace_procwaitfor_lock, dtrace_lck_grp, dtrace_lck_attr);
17668 #if DEBUG
17669 lck_mtx_init(&dtrace_errlock, dtrace_lck_grp, dtrace_lck_attr);
17670 #endif
17671 lck_rw_init(&dtrace_dof_mode_lock, dtrace_lck_grp, dtrace_lck_attr);
17672
17673 /*
17674 * The cpu_core structure consists of per-CPU state available in any context.
17675 * On some architectures, this may mean that the page(s) containing the
17676 * NCPU-sized array of cpu_core structures must be locked in the TLB -- it
17677 * is up to the platform to assure that this is performed properly. Note that
17678 * the structure is sized to avoid false sharing.
17679 */
17680 lck_mtx_init(&cpu_lock, dtrace_lck_grp, dtrace_lck_attr);
17681 lck_mtx_init(&cyc_lock, dtrace_lck_grp, dtrace_lck_attr);
17682 lck_mtx_init(&mod_lock, dtrace_lck_grp, dtrace_lck_attr);
17683
17684 /*
17685 * Initialize the CPU offline/online hooks.
17686 */
17687 dtrace_install_cpu_hooks();
17688
17689 dtrace_modctl_list = NULL;
17690
17691 cpu_core = (cpu_core_t *)kmem_zalloc( ncpu * sizeof(cpu_core_t), KM_SLEEP );
17692 for (i = 0; i < ncpu; ++i) {
17693 lck_mtx_init(&cpu_core[i].cpuc_pid_lock, dtrace_lck_grp, dtrace_lck_attr);
17694 }
17695
17696 cpu_list = (dtrace_cpu_t *)kmem_zalloc( ncpu * sizeof(dtrace_cpu_t), KM_SLEEP );
17697 for (i = 0; i < ncpu; ++i) {
17698 cpu_list[i].cpu_id = (processorid_t)i;
17699 cpu_list[i].cpu_next = &(cpu_list[(i+1) % ncpu]);
17700 LIST_INIT(&cpu_list[i].cpu_cyc_list);
17701 lck_rw_init(&cpu_list[i].cpu_ft_lock, dtrace_lck_grp, dtrace_lck_attr);
17702 }
17703
17704 lck_mtx_lock(&cpu_lock);
17705 for (i = 0; i < ncpu; ++i)
17706 /* FIXME: track CPU configuration a la CHUD Processor Pref Pane. */
17707 dtrace_cpu_setup_initial( (processorid_t)i ); /* In lieu of register_cpu_setup_func() callback */
17708 lck_mtx_unlock(&cpu_lock);
17709
17710 (void)dtrace_abs_to_nano(0LL); /* Force once only call to clock_timebase_info (which can take a lock) */
17711
17712 dtrace_isa_init();
17713 /*
17714 * See dtrace_impl.h for a description of dof modes.
17715 * The default is lazy dof.
17716 *
17717 * FIXME: Warn if state is LAZY_OFF? It won't break anything, but
17718 * makes no sense...
17719 */
17720 if (!PE_parse_boot_argn("dtrace_dof_mode", &dtrace_dof_mode, sizeof (dtrace_dof_mode))) {
17721 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
17722 }
17723
17724 /*
17725 * Sanity check of dof mode value.
17726 */
17727 switch (dtrace_dof_mode) {
17728 case DTRACE_DOF_MODE_NEVER:
17729 case DTRACE_DOF_MODE_LAZY_ON:
17730 /* valid modes, but nothing else we need to do */
17731 break;
17732
17733 case DTRACE_DOF_MODE_LAZY_OFF:
17734 case DTRACE_DOF_MODE_NON_LAZY:
17735 /* Cannot wait for a dtrace_open to init fasttrap */
17736 fasttrap_init();
17737 break;
17738
17739 default:
17740 /* Invalid, clamp to non lazy */
17741 dtrace_dof_mode = DTRACE_DOF_MODE_NON_LAZY;
17742 fasttrap_init();
17743 break;
17744 }
17745
17746 /*
17747 * See dtrace_impl.h for a description of kernel symbol modes.
17748 * The default is to wait for symbols from userspace (lazy symbols).
17749 */
17750 if (!PE_parse_boot_argn("dtrace_kernel_symbol_mode", &dtrace_kernel_symbol_mode, sizeof (dtrace_kernel_symbol_mode))) {
17751 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
17752 }
17753
17754 dtrace_restriction_policy_load();
17755
17756 gDTraceInited = 1;
17757
17758 } else
17759 panic("dtrace_init: called twice!\n");
17760 }
17761
17762 void
17763 dtrace_postinit(void)
17764 {
17765 /*
17766 * Called from bsd_init after all provider's *_init() routines have been
17767 * run. That way, anonymous DOF enabled under dtrace_attach() is safe
17768 * to go.
17769 */
17770 dtrace_attach( (dev_info_t *)(uintptr_t)makedev(gMajDevNo, 0), 0 ); /* Punning a dev_t to a dev_info_t* */
17771
17772 /*
17773 * Add the mach_kernel to the module list for lazy processing
17774 */
17775 struct kmod_info fake_kernel_kmod;
17776 memset(&fake_kernel_kmod, 0, sizeof(fake_kernel_kmod));
17777
17778 strlcpy(fake_kernel_kmod.name, "mach_kernel", sizeof(fake_kernel_kmod.name));
17779 fake_kernel_kmod.id = 1;
17780 fake_kernel_kmod.address = g_kernel_kmod_info.address;
17781 fake_kernel_kmod.size = g_kernel_kmod_info.size;
17782
17783 if (dtrace_module_loaded(&fake_kernel_kmod, 0) != 0) {
17784 printf("dtrace_postinit: Could not register mach_kernel modctl\n");
17785 }
17786
17787 (void)OSKextRegisterKextsWithDTrace();
17788 }
17789 #undef DTRACE_MAJOR
17790
17791 /*
17792 * Routines used to register interest in cpu's being added to or removed
17793 * from the system.
17794 */
17795 void
17796 register_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
17797 {
17798 #pragma unused(ignore1,ignore2)
17799 }
17800
17801 void
17802 unregister_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
17803 {
17804 #pragma unused(ignore1,ignore2)
17805 }