]> git.saurik.com Git - apple/xnu.git/blob - bsd/dev/dtrace/dtrace.c
c90a465a95c90a1bc15d4d592a5be5e4392234d2
[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, 2016, 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 * - Process functions
65 * - Consumer state functions
66 * - Helper functions
67 * - Hook functions
68 * - Driver cookbook functions
69 *
70 * Each group of functions begins with a block comment labelled the "DTrace
71 * [Group] Functions", allowing one to find each block by searching forward
72 * on capital-f functions.
73 */
74 #include <sys/errno.h>
75 #include <sys/types.h>
76 #include <sys/stat.h>
77 #include <sys/conf.h>
78 #include <sys/systm.h>
79 #include <sys/dtrace_impl.h>
80 #include <sys/param.h>
81 #include <sys/proc_internal.h>
82 #include <sys/ioctl.h>
83 #include <sys/fcntl.h>
84 #include <miscfs/devfs/devfs.h>
85 #include <sys/malloc.h>
86 #include <sys/kernel_types.h>
87 #include <sys/proc_internal.h>
88 #include <sys/uio_internal.h>
89 #include <sys/kauth.h>
90 #include <vm/pmap.h>
91 #include <sys/user.h>
92 #include <mach/exception_types.h>
93 #include <sys/signalvar.h>
94 #include <mach/task.h>
95 #include <kern/zalloc.h>
96 #include <kern/ast.h>
97 #include <kern/sched_prim.h>
98 #include <kern/task.h>
99 #include <netinet/in.h>
100 #include <libkern/sysctl.h>
101 #include <sys/kdebug.h>
102
103 #include <kern/cpu_data.h>
104 extern uint32_t pmap_find_phys(void *, uint64_t);
105 extern boolean_t pmap_valid_page(uint32_t);
106 extern void OSKextRegisterKextsWithDTrace(void);
107 extern kmod_info_t g_kernel_kmod_info;
108
109 /* Solaris proc_t is the struct. Darwin's proc_t is a pointer to it. */
110 #define proc_t struct proc /* Steer clear of the Darwin typedef for proc_t */
111
112 #define t_predcache t_dtrace_predcache /* Cosmetic. Helps readability of thread.h */
113
114 extern void dtrace_suspend(void);
115 extern void dtrace_resume(void);
116 extern void dtrace_init(void);
117 extern void helper_init(void);
118 extern void fasttrap_init(void);
119
120 static int dtrace_lazy_dofs_duplicate(proc_t *, proc_t *);
121 extern void dtrace_lazy_dofs_destroy(proc_t *);
122 extern void dtrace_postinit(void);
123
124 extern void dtrace_proc_fork(proc_t*, proc_t*, int);
125 extern void dtrace_proc_exec(proc_t*);
126 extern void dtrace_proc_exit(proc_t*);
127 /*
128 * DTrace Tunable Variables
129 *
130 * The following variables may be dynamically tuned by using sysctl(8), the
131 * variables being stored in the kern.dtrace namespace. For example:
132 * sysctl kern.dtrace.dof_maxsize = 1048575 # 1M
133 *
134 * In general, the only variables that one should be tuning this way are those
135 * that affect system-wide DTrace behavior, and for which the default behavior
136 * is undesirable. Most of these variables are tunable on a per-consumer
137 * basis using DTrace options, and need not be tuned on a system-wide basis.
138 * When tuning these variables, avoid pathological values; while some attempt
139 * is made to verify the integrity of these variables, they are not considered
140 * part of the supported interface to DTrace, and they are therefore not
141 * checked comprehensively.
142 */
143 uint64_t dtrace_buffer_memory_maxsize = 0; /* initialized in dtrace_init */
144 uint64_t dtrace_buffer_memory_inuse = 0;
145 int dtrace_destructive_disallow = 0;
146 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
147 size_t dtrace_difo_maxsize = (256 * 1024);
148 dtrace_optval_t dtrace_dof_maxsize = (384 * 1024);
149 dtrace_optval_t dtrace_statvar_maxsize = (16 * 1024);
150 dtrace_optval_t dtrace_statvar_maxsize_max = (16 * 10 * 1024);
151 size_t dtrace_actions_max = (16 * 1024);
152 size_t dtrace_retain_max = 1024;
153 dtrace_optval_t dtrace_helper_actions_max = 32;
154 dtrace_optval_t dtrace_helper_providers_max = 64;
155 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
156 size_t dtrace_strsize_default = 256;
157 dtrace_optval_t dtrace_strsize_min = 8;
158 dtrace_optval_t dtrace_strsize_max = 65536;
159 dtrace_optval_t dtrace_cleanrate_default = 990099000; /* 1.1 hz */
160 dtrace_optval_t dtrace_cleanrate_min = 20000000; /* 50 hz */
161 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC; /* 1/minute */
162 dtrace_optval_t dtrace_aggrate_default = NANOSEC; /* 1 hz */
163 dtrace_optval_t dtrace_statusrate_default = NANOSEC; /* 1 hz */
164 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC; /* 6/minute */
165 dtrace_optval_t dtrace_switchrate_default = NANOSEC; /* 1 hz */
166 dtrace_optval_t dtrace_nspec_default = 1;
167 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
168 dtrace_optval_t dtrace_stackframes_default = 20;
169 dtrace_optval_t dtrace_ustackframes_default = 20;
170 dtrace_optval_t dtrace_jstackframes_default = 50;
171 dtrace_optval_t dtrace_jstackstrsize_default = 512;
172 dtrace_optval_t dtrace_buflimit_default = 75;
173 dtrace_optval_t dtrace_buflimit_min = 1;
174 dtrace_optval_t dtrace_buflimit_max = 99;
175 int dtrace_msgdsize_max = 128;
176 hrtime_t dtrace_chill_max = 500 * (NANOSEC / MILLISEC); /* 500 ms */
177 hrtime_t dtrace_chill_interval = NANOSEC; /* 1000 ms */
178 int dtrace_devdepth_max = 32;
179 int dtrace_err_verbose;
180 int dtrace_provide_private_probes = 0;
181 hrtime_t dtrace_deadman_interval = NANOSEC;
182 hrtime_t dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
183 hrtime_t dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
184
185 /*
186 * DTrace External Variables
187 *
188 * As dtrace(7D) is a kernel module, any DTrace variables are obviously
189 * available to DTrace consumers via the backtick (`) syntax. One of these,
190 * dtrace_zero, is made deliberately so: it is provided as a source of
191 * well-known, zero-filled memory. While this variable is not documented,
192 * it is used by some translators as an implementation detail.
193 */
194 const char dtrace_zero[256] = { 0 }; /* zero-filled memory */
195 unsigned int dtrace_max_cpus = 0; /* number of enabled cpus */
196 /*
197 * DTrace Internal Variables
198 */
199 static dev_info_t *dtrace_devi; /* device info */
200 static vmem_t *dtrace_arena; /* probe ID arena */
201 static taskq_t *dtrace_taskq; /* task queue */
202 static dtrace_probe_t **dtrace_probes; /* array of all probes */
203 static int dtrace_nprobes; /* number of probes */
204 static dtrace_provider_t *dtrace_provider; /* provider list */
205 static dtrace_meta_t *dtrace_meta_pid; /* user-land meta provider */
206 static int dtrace_opens; /* number of opens */
207 static int dtrace_helpers; /* number of helpers */
208 static dtrace_hash_t *dtrace_bymod; /* probes hashed by module */
209 static dtrace_hash_t *dtrace_byfunc; /* probes hashed by function */
210 static dtrace_hash_t *dtrace_byname; /* probes hashed by name */
211 static dtrace_toxrange_t *dtrace_toxrange; /* toxic range array */
212 static int dtrace_toxranges; /* number of toxic ranges */
213 static int dtrace_toxranges_max; /* size of toxic range array */
214 static dtrace_anon_t dtrace_anon; /* anonymous enabling */
215 static kmem_cache_t *dtrace_state_cache; /* cache for dynamic state */
216 static uint64_t dtrace_vtime_references; /* number of vtimestamp refs */
217 static kthread_t *dtrace_panicked; /* panicking thread */
218 static dtrace_ecb_t *dtrace_ecb_create_cache; /* cached created ECB */
219 static dtrace_genid_t dtrace_probegen; /* current probe generation */
220 static dtrace_helpers_t *dtrace_deferred_pid; /* deferred helper list */
221 static dtrace_enabling_t *dtrace_retained; /* list of retained enablings */
222 static dtrace_genid_t dtrace_retained_gen; /* current retained enab gen */
223 static dtrace_dynvar_t dtrace_dynhash_sink; /* end of dynamic hash chains */
224
225 static int dtrace_dof_mode; /* See dtrace_impl.h for a description of Darwin's dof modes. */
226
227 /*
228 * This does't quite fit as an internal variable, as it must be accessed in
229 * fbt_provide and sdt_provide. Its clearly not a dtrace tunable variable either...
230 */
231 int dtrace_kernel_symbol_mode; /* See dtrace_impl.h for a description of Darwin's kernel symbol modes. */
232 static uint32_t dtrace_wake_clients;
233
234
235 /*
236 * To save memory, some common memory allocations are given a
237 * unique zone. For example, dtrace_probe_t is 72 bytes in size,
238 * which means it would fall into the kalloc.128 bucket. With
239 * 20k elements allocated, the space saved is substantial.
240 */
241
242 struct zone *dtrace_probe_t_zone;
243
244 static int dtrace_module_unloaded(struct kmod_info *kmod);
245
246 /*
247 * DTrace Locking
248 * DTrace is protected by three (relatively coarse-grained) locks:
249 *
250 * (1) dtrace_lock is required to manipulate essentially any DTrace state,
251 * including enabling state, probes, ECBs, consumer state, helper state,
252 * etc. Importantly, dtrace_lock is _not_ required when in probe context;
253 * probe context is lock-free -- synchronization is handled via the
254 * dtrace_sync() cross call mechanism.
255 *
256 * (2) dtrace_provider_lock is required when manipulating provider state, or
257 * when provider state must be held constant.
258 *
259 * (3) dtrace_meta_lock is required when manipulating meta provider state, or
260 * when meta provider state must be held constant.
261 *
262 * The lock ordering between these three locks is dtrace_meta_lock before
263 * dtrace_provider_lock before dtrace_lock. (In particular, there are
264 * several places where dtrace_provider_lock is held by the framework as it
265 * calls into the providers -- which then call back into the framework,
266 * grabbing dtrace_lock.)
267 *
268 * There are two other locks in the mix: mod_lock and cpu_lock. With respect
269 * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
270 * role as a coarse-grained lock; it is acquired before both of these locks.
271 * With respect to dtrace_meta_lock, its behavior is stranger: cpu_lock must
272 * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
273 * mod_lock is similar with respect to dtrace_provider_lock in that it must be
274 * acquired _between_ dtrace_provider_lock and dtrace_lock.
275 */
276
277
278 /*
279 * APPLE NOTE:
280 *
281 * For porting purposes, all kmutex_t vars have been changed
282 * to lck_mtx_t, which require explicit initialization.
283 *
284 * kmutex_t becomes lck_mtx_t
285 * mutex_enter() becomes lck_mtx_lock()
286 * mutex_exit() becomes lck_mtx_unlock()
287 *
288 * Lock asserts are changed like this:
289 *
290 * ASSERT(MUTEX_HELD(&cpu_lock));
291 * becomes:
292 * lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
293 *
294 */
295 static lck_mtx_t dtrace_lock; /* probe state lock */
296 static lck_mtx_t dtrace_provider_lock; /* provider state lock */
297 static lck_mtx_t dtrace_meta_lock; /* meta-provider state lock */
298 static lck_rw_t dtrace_dof_mode_lock; /* dof mode lock */
299
300 /*
301 * DTrace Provider Variables
302 *
303 * These are the variables relating to DTrace as a provider (that is, the
304 * provider of the BEGIN, END, and ERROR probes).
305 */
306 static dtrace_pattr_t dtrace_provider_attr = {
307 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
308 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
309 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
310 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
311 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
312 };
313
314 static void
315 dtrace_nullop(void)
316 {}
317
318 static int
319 dtrace_enable_nullop(void)
320 {
321 return (0);
322 }
323
324 static dtrace_pops_t dtrace_provider_ops = {
325 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
326 (void (*)(void *, struct modctl *))dtrace_nullop,
327 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
328 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
329 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
330 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
331 NULL,
332 NULL,
333 NULL,
334 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
335 };
336
337 static dtrace_id_t dtrace_probeid_begin; /* special BEGIN probe */
338 static dtrace_id_t dtrace_probeid_end; /* special END probe */
339 dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
340
341 /*
342 * DTrace Helper Tracing Variables
343 */
344 uint32_t dtrace_helptrace_next = 0;
345 uint32_t dtrace_helptrace_nlocals;
346 char *dtrace_helptrace_buffer;
347 size_t dtrace_helptrace_bufsize = 512 * 1024;
348
349 #if DEBUG
350 int dtrace_helptrace_enabled = 1;
351 #else
352 int dtrace_helptrace_enabled = 0;
353 #endif
354
355
356 /*
357 * DTrace Error Hashing
358 *
359 * On DEBUG kernels, DTrace will track the errors that has seen in a hash
360 * table. This is very useful for checking coverage of tests that are
361 * expected to induce DIF or DOF processing errors, and may be useful for
362 * debugging problems in the DIF code generator or in DOF generation . The
363 * error hash may be examined with the ::dtrace_errhash MDB dcmd.
364 */
365 #if DEBUG
366 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
367 static const char *dtrace_errlast;
368 static kthread_t *dtrace_errthread;
369 static lck_mtx_t dtrace_errlock;
370 #endif
371
372 /*
373 * DTrace Macros and Constants
374 *
375 * These are various macros that are useful in various spots in the
376 * implementation, along with a few random constants that have no meaning
377 * outside of the implementation. There is no real structure to this cpp
378 * mishmash -- but is there ever?
379 */
380 #define DTRACE_HASHSTR(hash, probe) \
381 dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
382
383 #define DTRACE_HASHNEXT(hash, probe) \
384 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
385
386 #define DTRACE_HASHPREV(hash, probe) \
387 (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
388
389 #define DTRACE_HASHEQ(hash, lhs, rhs) \
390 (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
391 *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
392
393 #define DTRACE_AGGHASHSIZE_SLEW 17
394
395 #define DTRACE_V4MAPPED_OFFSET (sizeof (uint32_t) * 3)
396
397 /*
398 * The key for a thread-local variable consists of the lower 61 bits of the
399 * current_thread(), plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
400 * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
401 * equal to a variable identifier. This is necessary (but not sufficient) to
402 * assure that global associative arrays never collide with thread-local
403 * variables. To guarantee that they cannot collide, we must also define the
404 * order for keying dynamic variables. That order is:
405 *
406 * [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
407 *
408 * Because the variable-key and the tls-key are in orthogonal spaces, there is
409 * no way for a global variable key signature to match a thread-local key
410 * signature.
411 */
412 #if defined (__x86_64__)
413 /* FIXME: two function calls!! */
414 #define DTRACE_TLS_THRKEY(where) { \
415 uint_t intr = ml_at_interrupt_context(); /* Note: just one measly bit */ \
416 uint64_t thr = (uintptr_t)current_thread(); \
417 ASSERT(intr < (1 << 3)); \
418 (where) = ((thr + DIF_VARIABLE_MAX) & \
419 (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
420 }
421 #else
422 #error Unknown architecture
423 #endif
424
425 #define DT_BSWAP_8(x) ((x) & 0xff)
426 #define DT_BSWAP_16(x) ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
427 #define DT_BSWAP_32(x) ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
428 #define DT_BSWAP_64(x) ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
429
430 #define DT_MASK_LO 0x00000000FFFFFFFFULL
431
432 #define DTRACE_STORE(type, tomax, offset, what) \
433 *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
434
435
436 #define DTRACE_ALIGNCHECK(addr, size, flags) \
437 if (addr & (MIN(size,4) - 1)) { \
438 *flags |= CPU_DTRACE_BADALIGN; \
439 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
440 return (0); \
441 }
442
443 #define DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz) \
444 do { \
445 if ((remp) != NULL) { \
446 *(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr); \
447 } \
448 } while (0)
449
450
451 /*
452 * Test whether a range of memory starting at testaddr of size testsz falls
453 * within the range of memory described by addr, sz. We take care to avoid
454 * problems with overflow and underflow of the unsigned quantities, and
455 * disallow all negative sizes. Ranges of size 0 are allowed.
456 */
457 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
458 ((testaddr) - (baseaddr) < (basesz) && \
459 (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
460 (testaddr) + (testsz) >= (testaddr))
461
462 /*
463 * Test whether alloc_sz bytes will fit in the scratch region. We isolate
464 * alloc_sz on the righthand side of the comparison in order to avoid overflow
465 * or underflow in the comparison with it. This is simpler than the INRANGE
466 * check above, because we know that the dtms_scratch_ptr is valid in the
467 * range. Allocations of size zero are allowed.
468 */
469 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
470 ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
471 (mstate)->dtms_scratch_ptr >= (alloc_sz))
472
473 #define RECOVER_LABEL(bits) dtraceLoadRecover##bits:
474
475 #if defined (__x86_64__) || (defined (__arm__) || defined (__arm64__))
476 #define DTRACE_LOADFUNC(bits) \
477 /*CSTYLED*/ \
478 uint##bits##_t dtrace_load##bits(uintptr_t addr); \
479 \
480 uint##bits##_t \
481 dtrace_load##bits(uintptr_t addr) \
482 { \
483 size_t size = bits / NBBY; \
484 /*CSTYLED*/ \
485 uint##bits##_t rval = 0; \
486 int i; \
487 volatile uint16_t *flags = (volatile uint16_t *) \
488 &cpu_core[CPU->cpu_id].cpuc_dtrace_flags; \
489 \
490 DTRACE_ALIGNCHECK(addr, size, flags); \
491 \
492 for (i = 0; i < dtrace_toxranges; i++) { \
493 if (addr >= dtrace_toxrange[i].dtt_limit) \
494 continue; \
495 \
496 if (addr + size <= dtrace_toxrange[i].dtt_base) \
497 continue; \
498 \
499 /* \
500 * This address falls within a toxic region; return 0. \
501 */ \
502 *flags |= CPU_DTRACE_BADADDR; \
503 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
504 return (0); \
505 } \
506 \
507 { \
508 volatile vm_offset_t recover = (vm_offset_t)&&dtraceLoadRecover##bits; \
509 *flags |= CPU_DTRACE_NOFAULT; \
510 recover = dtrace_set_thread_recover(current_thread(), recover); \
511 /*CSTYLED*/ \
512 /* \
513 * PR6394061 - avoid device memory that is unpredictably \
514 * mapped and unmapped \
515 */ \
516 if (pmap_valid_page(pmap_find_phys(kernel_pmap, addr))) \
517 rval = *((volatile uint##bits##_t *)addr); \
518 else { \
519 *flags |= CPU_DTRACE_BADADDR; \
520 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr; \
521 return (0); \
522 } \
523 \
524 RECOVER_LABEL(bits); \
525 (void)dtrace_set_thread_recover(current_thread(), recover); \
526 *flags &= ~CPU_DTRACE_NOFAULT; \
527 } \
528 \
529 return (rval); \
530 }
531 #else /* all other architectures */
532 #error Unknown Architecture
533 #endif
534
535 #ifdef __LP64__
536 #define dtrace_loadptr dtrace_load64
537 #else
538 #define dtrace_loadptr dtrace_load32
539 #endif
540
541 #define DTRACE_DYNHASH_FREE 0
542 #define DTRACE_DYNHASH_SINK 1
543 #define DTRACE_DYNHASH_VALID 2
544
545 #define DTRACE_MATCH_FAIL -1
546 #define DTRACE_MATCH_NEXT 0
547 #define DTRACE_MATCH_DONE 1
548 #define DTRACE_ANCHORED(probe) ((probe)->dtpr_func[0] != '\0')
549 #define DTRACE_STATE_ALIGN 64
550
551 #define DTRACE_FLAGS2FLT(flags) \
552 (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR : \
553 ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP : \
554 ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO : \
555 ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV : \
556 ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV : \
557 ((flags) & CPU_DTRACE_TUPOFLOW) ? DTRACEFLT_TUPOFLOW : \
558 ((flags) & CPU_DTRACE_BADALIGN) ? DTRACEFLT_BADALIGN : \
559 ((flags) & CPU_DTRACE_NOSCRATCH) ? DTRACEFLT_NOSCRATCH : \
560 ((flags) & CPU_DTRACE_BADSTACK) ? DTRACEFLT_BADSTACK : \
561 DTRACEFLT_UNKNOWN)
562
563 #define DTRACEACT_ISSTRING(act) \
564 ((act)->dta_kind == DTRACEACT_DIFEXPR && \
565 (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
566
567
568 static size_t dtrace_strlen(const char *, size_t);
569 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
570 static void dtrace_enabling_provide(dtrace_provider_t *);
571 static int dtrace_enabling_match(dtrace_enabling_t *, int *, dtrace_match_cond_t *cond);
572 static void dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond);
573 static void dtrace_enabling_matchall(void);
574 static dtrace_state_t *dtrace_anon_grab(void);
575 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
576 dtrace_state_t *, uint64_t, uint64_t);
577 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
578 static void dtrace_buffer_drop(dtrace_buffer_t *);
579 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
580 dtrace_state_t *, dtrace_mstate_t *);
581 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
582 dtrace_optval_t);
583 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
584 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
585 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
586 dtrace_mstate_t *, dtrace_vstate_t *);
587 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
588 dtrace_mstate_t *, dtrace_vstate_t *);
589
590
591 /*
592 * DTrace sysctl handlers
593 *
594 * These declarations and functions are used for a deeper DTrace configuration.
595 * Most of them are not per-consumer basis and may impact the other DTrace
596 * consumers. Correctness may not be supported for all the variables, so you
597 * should be careful about what values you are using.
598 */
599
600 SYSCTL_DECL(_kern_dtrace);
601 SYSCTL_NODE(_kern, OID_AUTO, dtrace, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "dtrace");
602
603 static int
604 sysctl_dtrace_err_verbose SYSCTL_HANDLER_ARGS
605 {
606 #pragma unused(oidp, arg2)
607 int changed, error;
608 int value = *(int *) arg1;
609
610 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
611 if (error || !changed)
612 return (error);
613
614 if (value != 0 && value != 1)
615 return (ERANGE);
616
617 lck_mtx_lock(&dtrace_lock);
618 dtrace_err_verbose = value;
619 lck_mtx_unlock(&dtrace_lock);
620
621 return (0);
622 }
623
624 /*
625 * kern.dtrace.err_verbose
626 *
627 * Set DTrace verbosity when an error occured (0 = disabled, 1 = enabld).
628 * Errors are reported when a DIFO or a DOF has been rejected by the kernel.
629 */
630 SYSCTL_PROC(_kern_dtrace, OID_AUTO, err_verbose,
631 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
632 &dtrace_err_verbose, 0,
633 sysctl_dtrace_err_verbose, "I", "dtrace error verbose");
634
635 static int
636 sysctl_dtrace_buffer_memory_maxsize SYSCTL_HANDLER_ARGS
637 {
638 #pragma unused(oidp, arg2, req)
639 int changed, error;
640 uint64_t value = *(uint64_t *) arg1;
641
642 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
643 if (error || !changed)
644 return (error);
645
646 if (value <= dtrace_buffer_memory_inuse)
647 return (ERANGE);
648
649 lck_mtx_lock(&dtrace_lock);
650 dtrace_buffer_memory_maxsize = value;
651 lck_mtx_unlock(&dtrace_lock);
652
653 return (0);
654 }
655
656 /*
657 * kern.dtrace.buffer_memory_maxsize
658 *
659 * Set DTrace maximal size in bytes used by all the consumers' state buffers. By default
660 * the limit is PHYS_MEM / 3 for *all* consumers. Attempting to set a null, a negative value
661 * or a value <= to dtrace_buffer_memory_inuse will result in a failure.
662 */
663 SYSCTL_PROC(_kern_dtrace, OID_AUTO, buffer_memory_maxsize,
664 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
665 &dtrace_buffer_memory_maxsize, 0,
666 sysctl_dtrace_buffer_memory_maxsize, "Q", "dtrace state buffer memory maxsize");
667
668 /*
669 * kern.dtrace.buffer_memory_inuse
670 *
671 * Current state buffer memory used, in bytes, by all the DTrace consumers.
672 * This value is read-only.
673 */
674 SYSCTL_QUAD(_kern_dtrace, OID_AUTO, buffer_memory_inuse, CTLFLAG_RD | CTLFLAG_LOCKED,
675 &dtrace_buffer_memory_inuse, "dtrace state buffer memory in-use");
676
677 static int
678 sysctl_dtrace_difo_maxsize SYSCTL_HANDLER_ARGS
679 {
680 #pragma unused(oidp, arg2, req)
681 int changed, error;
682 size_t value = *(size_t*) arg1;
683
684 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
685 if (error || !changed)
686 return (error);
687
688 if (value <= 0)
689 return (ERANGE);
690
691 lck_mtx_lock(&dtrace_lock);
692 dtrace_difo_maxsize = value;
693 lck_mtx_unlock(&dtrace_lock);
694
695 return (0);
696 }
697
698 /*
699 * kern.dtrace.difo_maxsize
700 *
701 * Set the DIFO max size in bytes, check the definition of dtrace_difo_maxsize
702 * to get the default value. Attempting to set a null or negative size will
703 * result in a failure.
704 */
705 SYSCTL_PROC(_kern_dtrace, OID_AUTO, difo_maxsize,
706 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
707 &dtrace_difo_maxsize, 0,
708 sysctl_dtrace_difo_maxsize, "Q", "dtrace difo maxsize");
709
710 static int
711 sysctl_dtrace_dof_maxsize SYSCTL_HANDLER_ARGS
712 {
713 #pragma unused(oidp, arg2, req)
714 int changed, error;
715 dtrace_optval_t value = *(dtrace_optval_t *) arg1;
716
717 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
718 if (error || !changed)
719 return (error);
720
721 if (value <= 0)
722 return (ERANGE);
723
724 lck_mtx_lock(&dtrace_lock);
725 dtrace_dof_maxsize = value;
726 lck_mtx_unlock(&dtrace_lock);
727
728 return (0);
729 }
730
731 /*
732 * kern.dtrace.dof_maxsize
733 *
734 * Set the DOF max size in bytes, check the definition of dtrace_dof_maxsize to
735 * get the default value. Attempting to set a null or negative size will result
736 * in a failure.
737 */
738 SYSCTL_PROC(_kern_dtrace, OID_AUTO, dof_maxsize,
739 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
740 &dtrace_dof_maxsize, 0,
741 sysctl_dtrace_dof_maxsize, "Q", "dtrace dof maxsize");
742
743 static int
744 sysctl_dtrace_statvar_maxsize SYSCTL_HANDLER_ARGS
745 {
746 #pragma unused(oidp, arg2, req)
747 int changed, error;
748 dtrace_optval_t value = *(dtrace_optval_t*) arg1;
749
750 error = sysctl_io_number(req, value, sizeof(value), &value, &changed);
751 if (error || !changed)
752 return (error);
753
754 if (value <= 0)
755 return (ERANGE);
756 if (value > dtrace_statvar_maxsize_max)
757 return (ERANGE);
758
759 lck_mtx_lock(&dtrace_lock);
760 dtrace_statvar_maxsize = value;
761 lck_mtx_unlock(&dtrace_lock);
762
763 return (0);
764 }
765
766 /*
767 * kern.dtrace.global_maxsize
768 *
769 * Set the variable max size in bytes, check the definition of
770 * dtrace_statvar_maxsize to get the default value. Attempting to set a null,
771 * too high or negative size will result in a failure.
772 */
773 SYSCTL_PROC(_kern_dtrace, OID_AUTO, global_maxsize,
774 CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED,
775 &dtrace_statvar_maxsize, 0,
776 sysctl_dtrace_statvar_maxsize, "Q", "dtrace statvar maxsize");
777
778 static int
779 sysctl_dtrace_provide_private_probes SYSCTL_HANDLER_ARGS
780 {
781 #pragma unused(oidp, arg2)
782 int error;
783 int value = *(int *) arg1;
784
785 error = sysctl_io_number(req, value, sizeof(value), &value, NULL);
786 if (error)
787 return (error);
788
789 if (value != 0 && value != 1)
790 return (ERANGE);
791
792 lck_mtx_lock(&dtrace_lock);
793 dtrace_provide_private_probes = value;
794 lck_mtx_unlock(&dtrace_lock);
795
796 return (0);
797 }
798
799 /*
800 * kern.dtrace.provide_private_probes
801 *
802 * Set whether the providers must provide the private probes. This is
803 * mainly used by the FBT provider to request probes for the private/static
804 * symbols.
805 */
806 SYSCTL_PROC(_kern_dtrace, OID_AUTO, provide_private_probes,
807 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
808 &dtrace_provide_private_probes, 0,
809 sysctl_dtrace_provide_private_probes, "I", "provider must provide the private probes");
810
811 /*
812 * DTrace Probe Context Functions
813 *
814 * These functions are called from probe context. Because probe context is
815 * any context in which C may be called, arbitrarily locks may be held,
816 * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
817 * As a result, functions called from probe context may only call other DTrace
818 * support functions -- they may not interact at all with the system at large.
819 * (Note that the ASSERT macro is made probe-context safe by redefining it in
820 * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
821 * loads are to be performed from probe context, they _must_ be in terms of
822 * the safe dtrace_load*() variants.
823 *
824 * Some functions in this block are not actually called from probe context;
825 * for these functions, there will be a comment above the function reading
826 * "Note: not called from probe context."
827 */
828
829 int
830 dtrace_assfail(const char *a, const char *f, int l)
831 {
832 panic("dtrace: assertion failed: %s, file: %s, line: %d", a, f, l);
833
834 /*
835 * We just need something here that even the most clever compiler
836 * cannot optimize away.
837 */
838 return (a[(uintptr_t)f]);
839 }
840
841 /*
842 * Atomically increment a specified error counter from probe context.
843 */
844 static void
845 dtrace_error(uint32_t *counter)
846 {
847 /*
848 * Most counters stored to in probe context are per-CPU counters.
849 * However, there are some error conditions that are sufficiently
850 * arcane that they don't merit per-CPU storage. If these counters
851 * are incremented concurrently on different CPUs, scalability will be
852 * adversely affected -- but we don't expect them to be white-hot in a
853 * correctly constructed enabling...
854 */
855 uint32_t oval, nval;
856
857 do {
858 oval = *counter;
859
860 if ((nval = oval + 1) == 0) {
861 /*
862 * If the counter would wrap, set it to 1 -- assuring
863 * that the counter is never zero when we have seen
864 * errors. (The counter must be 32-bits because we
865 * aren't guaranteed a 64-bit compare&swap operation.)
866 * To save this code both the infamy of being fingered
867 * by a priggish news story and the indignity of being
868 * the target of a neo-puritan witch trial, we're
869 * carefully avoiding any colorful description of the
870 * likelihood of this condition -- but suffice it to
871 * say that it is only slightly more likely than the
872 * overflow of predicate cache IDs, as discussed in
873 * dtrace_predicate_create().
874 */
875 nval = 1;
876 }
877 } while (dtrace_cas32(counter, oval, nval) != oval);
878 }
879
880 /*
881 * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
882 * uint8_t, a uint16_t, a uint32_t and a uint64_t.
883 */
884 DTRACE_LOADFUNC(8)
885 DTRACE_LOADFUNC(16)
886 DTRACE_LOADFUNC(32)
887 DTRACE_LOADFUNC(64)
888
889 static int
890 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
891 {
892 if (dest < mstate->dtms_scratch_base)
893 return (0);
894
895 if (dest + size < dest)
896 return (0);
897
898 if (dest + size > mstate->dtms_scratch_ptr)
899 return (0);
900
901 return (1);
902 }
903
904 static int
905 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
906 dtrace_statvar_t **svars, int nsvars)
907 {
908 int i;
909
910 size_t maxglobalsize, maxlocalsize;
911
912 maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
913 maxlocalsize = (maxglobalsize) * NCPU;
914
915 if (nsvars == 0)
916 return (0);
917
918 for (i = 0; i < nsvars; i++) {
919 dtrace_statvar_t *svar = svars[i];
920 uint8_t scope;
921 size_t size;
922
923 if (svar == NULL || (size = svar->dtsv_size) == 0)
924 continue;
925
926 scope = svar->dtsv_var.dtdv_scope;
927
928 /**
929 * We verify that our size is valid in the spirit of providing
930 * defense in depth: we want to prevent attackers from using
931 * DTrace to escalate an orthogonal kernel heap corruption bug
932 * into the ability to store to arbitrary locations in memory.
933 */
934 VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
935 (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
936
937 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size)) {
938 DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
939 svar->dtsv_size);
940 return (1);
941 }
942 }
943
944 return (0);
945 }
946
947 /*
948 * Check to see if the address is within a memory region to which a store may
949 * be issued. This includes the DTrace scratch areas, and any DTrace variable
950 * region. The caller of dtrace_canstore() is responsible for performing any
951 * alignment checks that are needed before stores are actually executed.
952 */
953 static int
954 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
955 dtrace_vstate_t *vstate)
956 {
957 return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
958 }
959 /*
960 * Implementation of dtrace_canstore which communicates the upper bound of the
961 * allowed memory region.
962 */
963 static int
964 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
965 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
966 {
967 /*
968 * First, check to see if the address is in scratch space...
969 */
970 if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
971 mstate->dtms_scratch_size)) {
972 DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
973 mstate->dtms_scratch_size);
974 return (1);
975 }
976 /*
977 * Now check to see if it's a dynamic variable. This check will pick
978 * up both thread-local variables and any global dynamically-allocated
979 * variables.
980 */
981 if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
982 vstate->dtvs_dynvars.dtds_size)) {
983 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
984 uintptr_t base = (uintptr_t)dstate->dtds_base +
985 (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
986 uintptr_t chunkoffs;
987 dtrace_dynvar_t *dvar;
988
989 /*
990 * Before we assume that we can store here, we need to make
991 * sure that it isn't in our metadata -- storing to our
992 * dynamic variable metadata would corrupt our state. For
993 * the range to not include any dynamic variable metadata,
994 * it must:
995 *
996 * (1) Start above the hash table that is at the base of
997 * the dynamic variable space
998 *
999 * (2) Have a starting chunk offset that is beyond the
1000 * dtrace_dynvar_t that is at the base of every chunk
1001 *
1002 * (3) Not span a chunk boundary
1003 *
1004 * (4) Not be in the tuple space of a dynamic variable
1005 *
1006 */
1007 if (addr < base)
1008 return (0);
1009
1010 chunkoffs = (addr - base) % dstate->dtds_chunksize;
1011
1012 if (chunkoffs < sizeof (dtrace_dynvar_t))
1013 return (0);
1014
1015 if (chunkoffs + sz > dstate->dtds_chunksize)
1016 return (0);
1017
1018 dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
1019
1020 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
1021 return (0);
1022
1023 if (chunkoffs < sizeof (dtrace_dynvar_t) +
1024 ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
1025 return (0);
1026
1027 return (1);
1028 }
1029
1030 /*
1031 * Finally, check the static local and global variables. These checks
1032 * take the longest, so we perform them last.
1033 */
1034 if (dtrace_canstore_statvar(addr, sz, remain,
1035 vstate->dtvs_locals, vstate->dtvs_nlocals))
1036 return (1);
1037
1038 if (dtrace_canstore_statvar(addr, sz, remain,
1039 vstate->dtvs_globals, vstate->dtvs_nglobals))
1040 return (1);
1041
1042 return (0);
1043 }
1044
1045
1046 /*
1047 * Convenience routine to check to see if the address is within a memory
1048 * region in which a load may be issued given the user's privilege level;
1049 * if not, it sets the appropriate error flags and loads 'addr' into the
1050 * illegal value slot.
1051 *
1052 * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
1053 * appropriate memory access protection.
1054 */
1055 static int
1056 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
1057 dtrace_vstate_t *vstate)
1058 {
1059 return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
1060 }
1061
1062 /*
1063 * Implementation of dtrace_canload which communicates the upper bound of the
1064 * allowed memory region.
1065 */
1066 static int
1067 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
1068 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1069 {
1070 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
1071
1072 /*
1073 * If we hold the privilege to read from kernel memory, then
1074 * everything is readable.
1075 */
1076 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1077 DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1078 return (1);
1079 }
1080
1081 /*
1082 * You can obviously read that which you can store.
1083 */
1084 if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
1085 return (1);
1086
1087 /*
1088 * We're allowed to read from our own string table.
1089 */
1090 if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
1091 mstate->dtms_difo->dtdo_strlen)) {
1092 DTRACE_RANGE_REMAIN(remain, addr,
1093 mstate->dtms_difo->dtdo_strtab,
1094 mstate->dtms_difo->dtdo_strlen);
1095 return (1);
1096 }
1097
1098 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
1099 *illval = addr;
1100 return (0);
1101 }
1102
1103 /*
1104 * Convenience routine to check to see if a given string is within a memory
1105 * region in which a load may be issued given the user's privilege level;
1106 * this exists so that we don't need to issue unnecessary dtrace_strlen()
1107 * calls in the event that the user has all privileges.
1108 */
1109 static int
1110 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
1111 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1112 {
1113 size_t rsize;
1114
1115 /*
1116 * If we hold the privilege to read from kernel memory, then
1117 * everything is readable.
1118 */
1119 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1120 DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
1121 return (1);
1122 }
1123
1124 /*
1125 * Even if the caller is uninterested in querying the remaining valid
1126 * range, it is required to ensure that the access is allowed.
1127 */
1128 if (remain == NULL) {
1129 remain = &rsize;
1130 }
1131 if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
1132 size_t strsz;
1133 /*
1134 * Perform the strlen after determining the length of the
1135 * memory region which is accessible. This prevents timing
1136 * information from being used to find NULs in memory which is
1137 * not accessible to the caller.
1138 */
1139 strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
1140 MIN(sz, *remain));
1141 if (strsz <= *remain) {
1142 return (1);
1143 }
1144 }
1145
1146 return (0);
1147 }
1148
1149 /*
1150 * Convenience routine to check to see if a given variable is within a memory
1151 * region in which a load may be issued given the user's privilege level.
1152 */
1153 static int
1154 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
1155 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1156 {
1157 size_t sz;
1158 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1159
1160 /*
1161 * Calculate the max size before performing any checks since even
1162 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
1163 * return the max length via 'remain'.
1164 */
1165 if (type->dtdt_kind == DIF_TYPE_STRING) {
1166 dtrace_state_t *state = vstate->dtvs_state;
1167
1168 if (state != NULL) {
1169 sz = state->dts_options[DTRACEOPT_STRSIZE];
1170 } else {
1171 /*
1172 * In helper context, we have a NULL state; fall back
1173 * to using the system-wide default for the string size
1174 * in this case.
1175 */
1176 sz = dtrace_strsize_default;
1177 }
1178 } else {
1179 sz = type->dtdt_size;
1180 }
1181
1182 /*
1183 * If we hold the privilege to read from kernel memory, then
1184 * everything is readable.
1185 */
1186 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1187 DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1188 return (1);
1189 }
1190
1191 if (type->dtdt_kind == DIF_TYPE_STRING) {
1192 return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1193 vstate));
1194 }
1195 return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1196 vstate));
1197 }
1198
1199 /*
1200 * Compare two strings using safe loads.
1201 */
1202 static int
1203 dtrace_strncmp(char *s1, char *s2, size_t limit)
1204 {
1205 uint8_t c1, c2;
1206 volatile uint16_t *flags;
1207
1208 if (s1 == s2 || limit == 0)
1209 return (0);
1210
1211 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1212
1213 do {
1214 if (s1 == NULL) {
1215 c1 = '\0';
1216 } else {
1217 c1 = dtrace_load8((uintptr_t)s1++);
1218 }
1219
1220 if (s2 == NULL) {
1221 c2 = '\0';
1222 } else {
1223 c2 = dtrace_load8((uintptr_t)s2++);
1224 }
1225
1226 if (c1 != c2)
1227 return (c1 - c2);
1228 } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1229
1230 return (0);
1231 }
1232
1233 /*
1234 * Compute strlen(s) for a string using safe memory accesses. The additional
1235 * len parameter is used to specify a maximum length to ensure completion.
1236 */
1237 static size_t
1238 dtrace_strlen(const char *s, size_t lim)
1239 {
1240 uint_t len;
1241
1242 for (len = 0; len != lim; len++) {
1243 if (dtrace_load8((uintptr_t)s++) == '\0')
1244 break;
1245 }
1246
1247 return (len);
1248 }
1249
1250 /*
1251 * Check if an address falls within a toxic region.
1252 */
1253 static int
1254 dtrace_istoxic(uintptr_t kaddr, size_t size)
1255 {
1256 uintptr_t taddr, tsize;
1257 int i;
1258
1259 for (i = 0; i < dtrace_toxranges; i++) {
1260 taddr = dtrace_toxrange[i].dtt_base;
1261 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1262
1263 if (kaddr - taddr < tsize) {
1264 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1265 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1266 return (1);
1267 }
1268
1269 if (taddr - kaddr < size) {
1270 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1271 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1272 return (1);
1273 }
1274 }
1275
1276 return (0);
1277 }
1278
1279 /*
1280 * Copy src to dst using safe memory accesses. The src is assumed to be unsafe
1281 * memory specified by the DIF program. The dst is assumed to be safe memory
1282 * that we can store to directly because it is managed by DTrace. As with
1283 * standard bcopy, overlapping copies are handled properly.
1284 */
1285 static void
1286 dtrace_bcopy(const void *src, void *dst, size_t len)
1287 {
1288 if (len != 0) {
1289 uint8_t *s1 = dst;
1290 const uint8_t *s2 = src;
1291
1292 if (s1 <= s2) {
1293 do {
1294 *s1++ = dtrace_load8((uintptr_t)s2++);
1295 } while (--len != 0);
1296 } else {
1297 s2 += len;
1298 s1 += len;
1299
1300 do {
1301 *--s1 = dtrace_load8((uintptr_t)--s2);
1302 } while (--len != 0);
1303 }
1304 }
1305 }
1306
1307 /*
1308 * Copy src to dst using safe memory accesses, up to either the specified
1309 * length, or the point that a nul byte is encountered. The src is assumed to
1310 * be unsafe memory specified by the DIF program. The dst is assumed to be
1311 * safe memory that we can store to directly because it is managed by DTrace.
1312 * Unlike dtrace_bcopy(), overlapping regions are not handled.
1313 */
1314 static void
1315 dtrace_strcpy(const void *src, void *dst, size_t len)
1316 {
1317 if (len != 0) {
1318 uint8_t *s1 = dst, c;
1319 const uint8_t *s2 = src;
1320
1321 do {
1322 *s1++ = c = dtrace_load8((uintptr_t)s2++);
1323 } while (--len != 0 && c != '\0');
1324 }
1325 }
1326
1327 /*
1328 * Copy src to dst, deriving the size and type from the specified (BYREF)
1329 * variable type. The src is assumed to be unsafe memory specified by the DIF
1330 * program. The dst is assumed to be DTrace variable memory that is of the
1331 * specified type; we assume that we can store to directly.
1332 */
1333 static void
1334 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1335 {
1336 ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1337
1338 if (type->dtdt_kind == DIF_TYPE_STRING) {
1339 dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1340 } else {
1341 dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1342 }
1343 }
1344
1345 /*
1346 * Compare s1 to s2 using safe memory accesses. The s1 data is assumed to be
1347 * unsafe memory specified by the DIF program. The s2 data is assumed to be
1348 * safe memory that we can access directly because it is managed by DTrace.
1349 */
1350 static int
1351 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1352 {
1353 volatile uint16_t *flags;
1354
1355 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1356
1357 if (s1 == s2)
1358 return (0);
1359
1360 if (s1 == NULL || s2 == NULL)
1361 return (1);
1362
1363 if (s1 != s2 && len != 0) {
1364 const uint8_t *ps1 = s1;
1365 const uint8_t *ps2 = s2;
1366
1367 do {
1368 if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1369 return (1);
1370 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1371 }
1372 return (0);
1373 }
1374
1375 /*
1376 * Zero the specified region using a simple byte-by-byte loop. Note that this
1377 * is for safe DTrace-managed memory only.
1378 */
1379 static void
1380 dtrace_bzero(void *dst, size_t len)
1381 {
1382 uchar_t *cp;
1383
1384 for (cp = dst; len != 0; len--)
1385 *cp++ = 0;
1386 }
1387
1388 static void
1389 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1390 {
1391 uint64_t result[2];
1392
1393 result[0] = addend1[0] + addend2[0];
1394 result[1] = addend1[1] + addend2[1] +
1395 (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1396
1397 sum[0] = result[0];
1398 sum[1] = result[1];
1399 }
1400
1401 /*
1402 * Shift the 128-bit value in a by b. If b is positive, shift left.
1403 * If b is negative, shift right.
1404 */
1405 static void
1406 dtrace_shift_128(uint64_t *a, int b)
1407 {
1408 uint64_t mask;
1409
1410 if (b == 0)
1411 return;
1412
1413 if (b < 0) {
1414 b = -b;
1415 if (b >= 64) {
1416 a[0] = a[1] >> (b - 64);
1417 a[1] = 0;
1418 } else {
1419 a[0] >>= b;
1420 mask = 1LL << (64 - b);
1421 mask -= 1;
1422 a[0] |= ((a[1] & mask) << (64 - b));
1423 a[1] >>= b;
1424 }
1425 } else {
1426 if (b >= 64) {
1427 a[1] = a[0] << (b - 64);
1428 a[0] = 0;
1429 } else {
1430 a[1] <<= b;
1431 mask = a[0] >> (64 - b);
1432 a[1] |= mask;
1433 a[0] <<= b;
1434 }
1435 }
1436 }
1437
1438 /*
1439 * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1440 * use native multiplication on those, and then re-combine into the
1441 * resulting 128-bit value.
1442 *
1443 * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1444 * hi1 * hi2 << 64 +
1445 * hi1 * lo2 << 32 +
1446 * hi2 * lo1 << 32 +
1447 * lo1 * lo2
1448 */
1449 static void
1450 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1451 {
1452 uint64_t hi1, hi2, lo1, lo2;
1453 uint64_t tmp[2];
1454
1455 hi1 = factor1 >> 32;
1456 hi2 = factor2 >> 32;
1457
1458 lo1 = factor1 & DT_MASK_LO;
1459 lo2 = factor2 & DT_MASK_LO;
1460
1461 product[0] = lo1 * lo2;
1462 product[1] = hi1 * hi2;
1463
1464 tmp[0] = hi1 * lo2;
1465 tmp[1] = 0;
1466 dtrace_shift_128(tmp, 32);
1467 dtrace_add_128(product, tmp, product);
1468
1469 tmp[0] = hi2 * lo1;
1470 tmp[1] = 0;
1471 dtrace_shift_128(tmp, 32);
1472 dtrace_add_128(product, tmp, product);
1473 }
1474
1475 /*
1476 * This privilege check should be used by actions and subroutines to
1477 * verify that the user credentials of the process that enabled the
1478 * invoking ECB match the target credentials
1479 */
1480 static int
1481 dtrace_priv_proc_common_user(dtrace_state_t *state)
1482 {
1483 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1484
1485 /*
1486 * We should always have a non-NULL state cred here, since if cred
1487 * is null (anonymous tracing), we fast-path bypass this routine.
1488 */
1489 ASSERT(s_cr != NULL);
1490
1491 if ((cr = dtrace_CRED()) != NULL &&
1492 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_uid &&
1493 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_ruid &&
1494 posix_cred_get(s_cr)->cr_uid == posix_cred_get(cr)->cr_suid &&
1495 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_gid &&
1496 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_rgid &&
1497 posix_cred_get(s_cr)->cr_gid == posix_cred_get(cr)->cr_sgid)
1498 return (1);
1499
1500 return (0);
1501 }
1502
1503 /*
1504 * This privilege check should be used by actions and subroutines to
1505 * verify that the zone of the process that enabled the invoking ECB
1506 * matches the target credentials
1507 */
1508 static int
1509 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1510 {
1511 cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1512 #pragma unused(cr, s_cr, state) /* __APPLE__ */
1513
1514 /*
1515 * We should always have a non-NULL state cred here, since if cred
1516 * is null (anonymous tracing), we fast-path bypass this routine.
1517 */
1518 ASSERT(s_cr != NULL);
1519
1520 return 1; /* APPLE NOTE: Darwin doesn't do zones. */
1521 }
1522
1523 /*
1524 * This privilege check should be used by actions and subroutines to
1525 * verify that the process has not setuid or changed credentials.
1526 */
1527 static int
1528 dtrace_priv_proc_common_nocd(void)
1529 {
1530 return 1; /* Darwin omits "No Core Dump" flag. */
1531 }
1532
1533 static int
1534 dtrace_priv_proc_destructive(dtrace_state_t *state)
1535 {
1536 int action = state->dts_cred.dcr_action;
1537
1538 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1539 goto bad;
1540
1541 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1542 goto bad;
1543
1544 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1545 dtrace_priv_proc_common_zone(state) == 0)
1546 goto bad;
1547
1548 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1549 dtrace_priv_proc_common_user(state) == 0)
1550 goto bad;
1551
1552 if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1553 dtrace_priv_proc_common_nocd() == 0)
1554 goto bad;
1555
1556 return (1);
1557
1558 bad:
1559 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1560
1561 return (0);
1562 }
1563
1564 static int
1565 dtrace_priv_proc_control(dtrace_state_t *state)
1566 {
1567 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1568 goto bad;
1569
1570 if (dtrace_is_restricted() && !dtrace_can_attach_to_proc(current_proc()))
1571 goto bad;
1572
1573 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1574 return (1);
1575
1576 if (dtrace_priv_proc_common_zone(state) &&
1577 dtrace_priv_proc_common_user(state) &&
1578 dtrace_priv_proc_common_nocd())
1579 return (1);
1580
1581 bad:
1582 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1583
1584 return (0);
1585 }
1586
1587 static int
1588 dtrace_priv_proc(dtrace_state_t *state)
1589 {
1590 if (ISSET(current_proc()->p_lflag, P_LNOATTACH))
1591 goto bad;
1592
1593 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed() && !dtrace_can_attach_to_proc(current_proc()))
1594 goto bad;
1595
1596 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1597 return (1);
1598
1599 bad:
1600 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1601
1602 return (0);
1603 }
1604
1605 /*
1606 * The P_LNOATTACH check is an Apple specific check.
1607 * We need a version of dtrace_priv_proc() that omits
1608 * that check for PID and EXECNAME accesses
1609 */
1610 static int
1611 dtrace_priv_proc_relaxed(dtrace_state_t *state)
1612 {
1613
1614 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1615 return (1);
1616
1617 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1618
1619 return (0);
1620 }
1621
1622 static int
1623 dtrace_priv_kernel(dtrace_state_t *state)
1624 {
1625 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed())
1626 goto bad;
1627
1628 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1629 return (1);
1630
1631 bad:
1632 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1633
1634 return (0);
1635 }
1636
1637 static int
1638 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1639 {
1640 if (dtrace_is_restricted())
1641 goto bad;
1642
1643 if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1644 return (1);
1645
1646 bad:
1647 cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1648
1649 return (0);
1650 }
1651
1652 /*
1653 * Note: not called from probe context. This function is called
1654 * asynchronously (and at a regular interval) from outside of probe context to
1655 * clean the dirty dynamic variable lists on all CPUs. Dynamic variable
1656 * cleaning is explained in detail in <sys/dtrace_impl.h>.
1657 */
1658 static void
1659 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1660 {
1661 dtrace_dynvar_t *dirty;
1662 dtrace_dstate_percpu_t *dcpu;
1663 int i, work = 0;
1664
1665 for (i = 0; i < (int)NCPU; i++) {
1666 dcpu = &dstate->dtds_percpu[i];
1667
1668 ASSERT(dcpu->dtdsc_rinsing == NULL);
1669
1670 /*
1671 * If the dirty list is NULL, there is no dirty work to do.
1672 */
1673 if (dcpu->dtdsc_dirty == NULL)
1674 continue;
1675
1676 /*
1677 * If the clean list is non-NULL, then we're not going to do
1678 * any work for this CPU -- it means that there has not been
1679 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1680 * since the last time we cleaned house.
1681 */
1682 if (dcpu->dtdsc_clean != NULL)
1683 continue;
1684
1685 work = 1;
1686
1687 /*
1688 * Atomically move the dirty list aside.
1689 */
1690 do {
1691 dirty = dcpu->dtdsc_dirty;
1692
1693 /*
1694 * Before we zap the dirty list, set the rinsing list.
1695 * (This allows for a potential assertion in
1696 * dtrace_dynvar(): if a free dynamic variable appears
1697 * on a hash chain, either the dirty list or the
1698 * rinsing list for some CPU must be non-NULL.)
1699 */
1700 dcpu->dtdsc_rinsing = dirty;
1701 dtrace_membar_producer();
1702 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1703 dirty, NULL) != dirty);
1704 }
1705
1706 if (!work) {
1707 /*
1708 * We have no work to do; we can simply return.
1709 */
1710 return;
1711 }
1712
1713 dtrace_sync();
1714
1715 for (i = 0; i < (int)NCPU; i++) {
1716 dcpu = &dstate->dtds_percpu[i];
1717
1718 if (dcpu->dtdsc_rinsing == NULL)
1719 continue;
1720
1721 /*
1722 * We are now guaranteed that no hash chain contains a pointer
1723 * into this dirty list; we can make it clean.
1724 */
1725 ASSERT(dcpu->dtdsc_clean == NULL);
1726 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1727 dcpu->dtdsc_rinsing = NULL;
1728 }
1729
1730 /*
1731 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1732 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1733 * This prevents a race whereby a CPU incorrectly decides that
1734 * the state should be something other than DTRACE_DSTATE_CLEAN
1735 * after dtrace_dynvar_clean() has completed.
1736 */
1737 dtrace_sync();
1738
1739 dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1740 }
1741
1742 /*
1743 * Depending on the value of the op parameter, this function looks-up,
1744 * allocates or deallocates an arbitrarily-keyed dynamic variable. If an
1745 * allocation is requested, this function will return a pointer to a
1746 * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1747 * variable can be allocated. If NULL is returned, the appropriate counter
1748 * will be incremented.
1749 */
1750 static dtrace_dynvar_t *
1751 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1752 dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1753 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1754 {
1755 uint64_t hashval = DTRACE_DYNHASH_VALID;
1756 dtrace_dynhash_t *hash = dstate->dtds_hash;
1757 dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1758 processorid_t me = CPU->cpu_id, cpu = me;
1759 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1760 size_t bucket, ksize;
1761 size_t chunksize = dstate->dtds_chunksize;
1762 uintptr_t kdata, lock, nstate;
1763 uint_t i;
1764
1765 ASSERT(nkeys != 0);
1766
1767 /*
1768 * Hash the key. As with aggregations, we use Jenkins' "One-at-a-time"
1769 * algorithm. For the by-value portions, we perform the algorithm in
1770 * 16-bit chunks (as opposed to 8-bit chunks). This speeds things up a
1771 * bit, and seems to have only a minute effect on distribution. For
1772 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1773 * over each referenced byte. It's painful to do this, but it's much
1774 * better than pathological hash distribution. The efficacy of the
1775 * hashing algorithm (and a comparison with other algorithms) may be
1776 * found by running the ::dtrace_dynstat MDB dcmd.
1777 */
1778 for (i = 0; i < nkeys; i++) {
1779 if (key[i].dttk_size == 0) {
1780 uint64_t val = key[i].dttk_value;
1781
1782 hashval += (val >> 48) & 0xffff;
1783 hashval += (hashval << 10);
1784 hashval ^= (hashval >> 6);
1785
1786 hashval += (val >> 32) & 0xffff;
1787 hashval += (hashval << 10);
1788 hashval ^= (hashval >> 6);
1789
1790 hashval += (val >> 16) & 0xffff;
1791 hashval += (hashval << 10);
1792 hashval ^= (hashval >> 6);
1793
1794 hashval += val & 0xffff;
1795 hashval += (hashval << 10);
1796 hashval ^= (hashval >> 6);
1797 } else {
1798 /*
1799 * This is incredibly painful, but it beats the hell
1800 * out of the alternative.
1801 */
1802 uint64_t j, size = key[i].dttk_size;
1803 uintptr_t base = (uintptr_t)key[i].dttk_value;
1804
1805 if (!dtrace_canload(base, size, mstate, vstate))
1806 break;
1807
1808 for (j = 0; j < size; j++) {
1809 hashval += dtrace_load8(base + j);
1810 hashval += (hashval << 10);
1811 hashval ^= (hashval >> 6);
1812 }
1813 }
1814 }
1815
1816 if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1817 return (NULL);
1818
1819 hashval += (hashval << 3);
1820 hashval ^= (hashval >> 11);
1821 hashval += (hashval << 15);
1822
1823 /*
1824 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1825 * comes out to be one of our two sentinel hash values. If this
1826 * actually happens, we set the hashval to be a value known to be a
1827 * non-sentinel value.
1828 */
1829 if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1830 hashval = DTRACE_DYNHASH_VALID;
1831
1832 /*
1833 * Yes, it's painful to do a divide here. If the cycle count becomes
1834 * important here, tricks can be pulled to reduce it. (However, it's
1835 * critical that hash collisions be kept to an absolute minimum;
1836 * they're much more painful than a divide.) It's better to have a
1837 * solution that generates few collisions and still keeps things
1838 * relatively simple.
1839 */
1840 bucket = hashval % dstate->dtds_hashsize;
1841
1842 if (op == DTRACE_DYNVAR_DEALLOC) {
1843 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1844
1845 for (;;) {
1846 while ((lock = *lockp) & 1)
1847 continue;
1848
1849 if (dtrace_casptr((void *)(uintptr_t)lockp,
1850 (void *)lock, (void *)(lock + 1)) == (void *)lock)
1851 break;
1852 }
1853
1854 dtrace_membar_producer();
1855 }
1856
1857 top:
1858 prev = NULL;
1859 lock = hash[bucket].dtdh_lock;
1860
1861 dtrace_membar_consumer();
1862
1863 start = hash[bucket].dtdh_chain;
1864 ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1865 start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1866 op != DTRACE_DYNVAR_DEALLOC));
1867
1868 for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1869 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1870 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1871
1872 if (dvar->dtdv_hashval != hashval) {
1873 if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1874 /*
1875 * We've reached the sink, and therefore the
1876 * end of the hash chain; we can kick out of
1877 * the loop knowing that we have seen a valid
1878 * snapshot of state.
1879 */
1880 ASSERT(dvar->dtdv_next == NULL);
1881 ASSERT(dvar == &dtrace_dynhash_sink);
1882 break;
1883 }
1884
1885 if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1886 /*
1887 * We've gone off the rails: somewhere along
1888 * the line, one of the members of this hash
1889 * chain was deleted. Note that we could also
1890 * detect this by simply letting this loop run
1891 * to completion, as we would eventually hit
1892 * the end of the dirty list. However, we
1893 * want to avoid running the length of the
1894 * dirty list unnecessarily (it might be quite
1895 * long), so we catch this as early as
1896 * possible by detecting the hash marker. In
1897 * this case, we simply set dvar to NULL and
1898 * break; the conditional after the loop will
1899 * send us back to top.
1900 */
1901 dvar = NULL;
1902 break;
1903 }
1904
1905 goto next;
1906 }
1907
1908 if (dtuple->dtt_nkeys != nkeys)
1909 goto next;
1910
1911 for (i = 0; i < nkeys; i++, dkey++) {
1912 if (dkey->dttk_size != key[i].dttk_size)
1913 goto next; /* size or type mismatch */
1914
1915 if (dkey->dttk_size != 0) {
1916 if (dtrace_bcmp(
1917 (void *)(uintptr_t)key[i].dttk_value,
1918 (void *)(uintptr_t)dkey->dttk_value,
1919 dkey->dttk_size))
1920 goto next;
1921 } else {
1922 if (dkey->dttk_value != key[i].dttk_value)
1923 goto next;
1924 }
1925 }
1926
1927 if (op != DTRACE_DYNVAR_DEALLOC)
1928 return (dvar);
1929
1930 ASSERT(dvar->dtdv_next == NULL ||
1931 dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1932
1933 if (prev != NULL) {
1934 ASSERT(hash[bucket].dtdh_chain != dvar);
1935 ASSERT(start != dvar);
1936 ASSERT(prev->dtdv_next == dvar);
1937 prev->dtdv_next = dvar->dtdv_next;
1938 } else {
1939 if (dtrace_casptr(&hash[bucket].dtdh_chain,
1940 start, dvar->dtdv_next) != start) {
1941 /*
1942 * We have failed to atomically swing the
1943 * hash table head pointer, presumably because
1944 * of a conflicting allocation on another CPU.
1945 * We need to reread the hash chain and try
1946 * again.
1947 */
1948 goto top;
1949 }
1950 }
1951
1952 dtrace_membar_producer();
1953
1954 /*
1955 * Now set the hash value to indicate that it's free.
1956 */
1957 ASSERT(hash[bucket].dtdh_chain != dvar);
1958 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1959
1960 dtrace_membar_producer();
1961
1962 /*
1963 * Set the next pointer to point at the dirty list, and
1964 * atomically swing the dirty pointer to the newly freed dvar.
1965 */
1966 do {
1967 next = dcpu->dtdsc_dirty;
1968 dvar->dtdv_next = next;
1969 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1970
1971 /*
1972 * Finally, unlock this hash bucket.
1973 */
1974 ASSERT(hash[bucket].dtdh_lock == lock);
1975 ASSERT(lock & 1);
1976 hash[bucket].dtdh_lock++;
1977
1978 return (NULL);
1979 next:
1980 prev = dvar;
1981 continue;
1982 }
1983
1984 if (dvar == NULL) {
1985 /*
1986 * If dvar is NULL, it is because we went off the rails:
1987 * one of the elements that we traversed in the hash chain
1988 * was deleted while we were traversing it. In this case,
1989 * we assert that we aren't doing a dealloc (deallocs lock
1990 * the hash bucket to prevent themselves from racing with
1991 * one another), and retry the hash chain traversal.
1992 */
1993 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1994 goto top;
1995 }
1996
1997 if (op != DTRACE_DYNVAR_ALLOC) {
1998 /*
1999 * If we are not to allocate a new variable, we want to
2000 * return NULL now. Before we return, check that the value
2001 * of the lock word hasn't changed. If it has, we may have
2002 * seen an inconsistent snapshot.
2003 */
2004 if (op == DTRACE_DYNVAR_NOALLOC) {
2005 if (hash[bucket].dtdh_lock != lock)
2006 goto top;
2007 } else {
2008 ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2009 ASSERT(hash[bucket].dtdh_lock == lock);
2010 ASSERT(lock & 1);
2011 hash[bucket].dtdh_lock++;
2012 }
2013
2014 return (NULL);
2015 }
2016
2017 /*
2018 * We need to allocate a new dynamic variable. The size we need is the
2019 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2020 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2021 * the size of any referred-to data (dsize). We then round the final
2022 * size up to the chunksize for allocation.
2023 */
2024 for (ksize = 0, i = 0; i < nkeys; i++)
2025 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2026
2027 /*
2028 * This should be pretty much impossible, but could happen if, say,
2029 * strange DIF specified the tuple. Ideally, this should be an
2030 * assertion and not an error condition -- but that requires that the
2031 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2032 * bullet-proof. (That is, it must not be able to be fooled by
2033 * malicious DIF.) Given the lack of backwards branches in DIF,
2034 * solving this would presumably not amount to solving the Halting
2035 * Problem -- but it still seems awfully hard.
2036 */
2037 if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2038 ksize + dsize > chunksize) {
2039 dcpu->dtdsc_drops++;
2040 return (NULL);
2041 }
2042
2043 nstate = DTRACE_DSTATE_EMPTY;
2044
2045 do {
2046 retry:
2047 free = dcpu->dtdsc_free;
2048
2049 if (free == NULL) {
2050 dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2051 void *rval;
2052
2053 if (clean == NULL) {
2054 /*
2055 * We're out of dynamic variable space on
2056 * this CPU. Unless we have tried all CPUs,
2057 * we'll try to allocate from a different
2058 * CPU.
2059 */
2060 switch (dstate->dtds_state) {
2061 case DTRACE_DSTATE_CLEAN: {
2062 void *sp = &dstate->dtds_state;
2063
2064 if (++cpu >= (int)NCPU)
2065 cpu = 0;
2066
2067 if (dcpu->dtdsc_dirty != NULL &&
2068 nstate == DTRACE_DSTATE_EMPTY)
2069 nstate = DTRACE_DSTATE_DIRTY;
2070
2071 if (dcpu->dtdsc_rinsing != NULL)
2072 nstate = DTRACE_DSTATE_RINSING;
2073
2074 dcpu = &dstate->dtds_percpu[cpu];
2075
2076 if (cpu != me)
2077 goto retry;
2078
2079 (void) dtrace_cas32(sp,
2080 DTRACE_DSTATE_CLEAN, nstate);
2081
2082 /*
2083 * To increment the correct bean
2084 * counter, take another lap.
2085 */
2086 goto retry;
2087 }
2088
2089 case DTRACE_DSTATE_DIRTY:
2090 dcpu->dtdsc_dirty_drops++;
2091 break;
2092
2093 case DTRACE_DSTATE_RINSING:
2094 dcpu->dtdsc_rinsing_drops++;
2095 break;
2096
2097 case DTRACE_DSTATE_EMPTY:
2098 dcpu->dtdsc_drops++;
2099 break;
2100 }
2101
2102 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2103 return (NULL);
2104 }
2105
2106 /*
2107 * The clean list appears to be non-empty. We want to
2108 * move the clean list to the free list; we start by
2109 * moving the clean pointer aside.
2110 */
2111 if (dtrace_casptr(&dcpu->dtdsc_clean,
2112 clean, NULL) != clean) {
2113 /*
2114 * We are in one of two situations:
2115 *
2116 * (a) The clean list was switched to the
2117 * free list by another CPU.
2118 *
2119 * (b) The clean list was added to by the
2120 * cleansing cyclic.
2121 *
2122 * In either of these situations, we can
2123 * just reattempt the free list allocation.
2124 */
2125 goto retry;
2126 }
2127
2128 ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2129
2130 /*
2131 * Now we'll move the clean list to the free list.
2132 * It's impossible for this to fail: the only way
2133 * the free list can be updated is through this
2134 * code path, and only one CPU can own the clean list.
2135 * Thus, it would only be possible for this to fail if
2136 * this code were racing with dtrace_dynvar_clean().
2137 * (That is, if dtrace_dynvar_clean() updated the clean
2138 * list, and we ended up racing to update the free
2139 * list.) This race is prevented by the dtrace_sync()
2140 * in dtrace_dynvar_clean() -- which flushes the
2141 * owners of the clean lists out before resetting
2142 * the clean lists.
2143 */
2144 rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2145 ASSERT(rval == NULL);
2146 goto retry;
2147 }
2148
2149 dvar = free;
2150 new_free = dvar->dtdv_next;
2151 } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2152
2153 /*
2154 * We have now allocated a new chunk. We copy the tuple keys into the
2155 * tuple array and copy any referenced key data into the data space
2156 * following the tuple array. As we do this, we relocate dttk_value
2157 * in the final tuple to point to the key data address in the chunk.
2158 */
2159 kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2160 dvar->dtdv_data = (void *)(kdata + ksize);
2161 dvar->dtdv_tuple.dtt_nkeys = nkeys;
2162
2163 for (i = 0; i < nkeys; i++) {
2164 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2165 size_t kesize = key[i].dttk_size;
2166
2167 if (kesize != 0) {
2168 dtrace_bcopy(
2169 (const void *)(uintptr_t)key[i].dttk_value,
2170 (void *)kdata, kesize);
2171 dkey->dttk_value = kdata;
2172 kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2173 } else {
2174 dkey->dttk_value = key[i].dttk_value;
2175 }
2176
2177 dkey->dttk_size = kesize;
2178 }
2179
2180 ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2181 dvar->dtdv_hashval = hashval;
2182 dvar->dtdv_next = start;
2183
2184 if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2185 return (dvar);
2186
2187 /*
2188 * The cas has failed. Either another CPU is adding an element to
2189 * this hash chain, or another CPU is deleting an element from this
2190 * hash chain. The simplest way to deal with both of these cases
2191 * (though not necessarily the most efficient) is to free our
2192 * allocated block and tail-call ourselves. Note that the free is
2193 * to the dirty list and _not_ to the free list. This is to prevent
2194 * races with allocators, above.
2195 */
2196 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2197
2198 dtrace_membar_producer();
2199
2200 do {
2201 free = dcpu->dtdsc_dirty;
2202 dvar->dtdv_next = free;
2203 } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2204
2205 return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2206 }
2207
2208 /*ARGSUSED*/
2209 static void
2210 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2211 {
2212 #pragma unused(arg) /* __APPLE__ */
2213 if ((int64_t)nval < (int64_t)*oval)
2214 *oval = nval;
2215 }
2216
2217 /*ARGSUSED*/
2218 static void
2219 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2220 {
2221 #pragma unused(arg) /* __APPLE__ */
2222 if ((int64_t)nval > (int64_t)*oval)
2223 *oval = nval;
2224 }
2225
2226 static void
2227 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2228 {
2229 int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2230 int64_t val = (int64_t)nval;
2231
2232 if (val < 0) {
2233 for (i = 0; i < zero; i++) {
2234 if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2235 quanta[i] += incr;
2236 return;
2237 }
2238 }
2239 } else {
2240 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2241 if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2242 quanta[i - 1] += incr;
2243 return;
2244 }
2245 }
2246
2247 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2248 return;
2249 }
2250
2251 ASSERT(0);
2252 }
2253
2254 static void
2255 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2256 {
2257 uint64_t arg = *lquanta++;
2258 int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2259 uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2260 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2261 int32_t val = (int32_t)nval, level;
2262
2263 ASSERT(step != 0);
2264 ASSERT(levels != 0);
2265
2266 if (val < base) {
2267 /*
2268 * This is an underflow.
2269 */
2270 lquanta[0] += incr;
2271 return;
2272 }
2273
2274 level = (val - base) / step;
2275
2276 if (level < levels) {
2277 lquanta[level + 1] += incr;
2278 return;
2279 }
2280
2281 /*
2282 * This is an overflow.
2283 */
2284 lquanta[levels + 1] += incr;
2285 }
2286
2287 static int
2288 dtrace_aggregate_llquantize_bucket(int16_t factor, int16_t low, int16_t high,
2289 int16_t nsteps, int64_t value)
2290 {
2291 int64_t this = 1, last, next;
2292 int base = 1, order;
2293
2294 for (order = 0; order < low; ++order)
2295 this *= factor;
2296
2297 /*
2298 * If our value is less than our factor taken to the power of the
2299 * low order of magnitude, it goes into the zeroth bucket.
2300 */
2301 if (value < this)
2302 return 0;
2303 else
2304 last = this;
2305
2306 for (this *= factor; order <= high; ++order) {
2307 int nbuckets = this > nsteps ? nsteps : this;
2308
2309 /*
2310 * We should not generally get log/linear quantizations
2311 * with a high magnitude that allows 64-bits to
2312 * overflow, but we nonetheless protect against this
2313 * by explicitly checking for overflow, and clamping
2314 * our value accordingly.
2315 */
2316 next = this * factor;
2317 if (next < this) {
2318 value = this - 1;
2319 }
2320
2321 /*
2322 * If our value lies within this order of magnitude,
2323 * determine its position by taking the offset within
2324 * the order of magnitude, dividing by the bucket
2325 * width, and adding to our (accumulated) base.
2326 */
2327 if (value < this) {
2328 return (base + (value - last) / (this / nbuckets));
2329 }
2330
2331 base += nbuckets - (nbuckets / factor);
2332 last = this;
2333 this = next;
2334 }
2335
2336 /*
2337 * Our value is greater than or equal to our factor taken to the
2338 * power of one plus the high magnitude -- return the top bucket.
2339 */
2340 return base;
2341 }
2342
2343 static void
2344 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2345 {
2346 uint64_t arg = *llquanta++;
2347 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2348 uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2349 uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2350 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2351
2352 llquanta[dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, nval)] += incr;
2353 }
2354
2355 /*ARGSUSED*/
2356 static void
2357 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2358 {
2359 #pragma unused(arg) /* __APPLE__ */
2360 data[0]++;
2361 data[1] += nval;
2362 }
2363
2364 /*ARGSUSED*/
2365 static void
2366 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2367 {
2368 #pragma unused(arg) /* __APPLE__ */
2369 int64_t snval = (int64_t)nval;
2370 uint64_t tmp[2];
2371
2372 data[0]++;
2373 data[1] += nval;
2374
2375 /*
2376 * What we want to say here is:
2377 *
2378 * data[2] += nval * nval;
2379 *
2380 * But given that nval is 64-bit, we could easily overflow, so
2381 * we do this as 128-bit arithmetic.
2382 */
2383 if (snval < 0)
2384 snval = -snval;
2385
2386 dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2387 dtrace_add_128(data + 2, tmp, data + 2);
2388 }
2389
2390 /*ARGSUSED*/
2391 static void
2392 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2393 {
2394 #pragma unused(nval, arg) /* __APPLE__ */
2395 *oval = *oval + 1;
2396 }
2397
2398 /*ARGSUSED*/
2399 static void
2400 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2401 {
2402 #pragma unused(arg) /* __APPLE__ */
2403 *oval += nval;
2404 }
2405
2406 /*
2407 * Aggregate given the tuple in the principal data buffer, and the aggregating
2408 * action denoted by the specified dtrace_aggregation_t. The aggregation
2409 * buffer is specified as the buf parameter. This routine does not return
2410 * failure; if there is no space in the aggregation buffer, the data will be
2411 * dropped, and a corresponding counter incremented.
2412 */
2413 static void
2414 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2415 intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2416 {
2417 #pragma unused(arg)
2418 dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2419 uint32_t i, ndx, size, fsize;
2420 uint32_t align = sizeof (uint64_t) - 1;
2421 dtrace_aggbuffer_t *agb;
2422 dtrace_aggkey_t *key;
2423 uint32_t hashval = 0, limit, isstr;
2424 caddr_t tomax, data, kdata;
2425 dtrace_actkind_t action;
2426 dtrace_action_t *act;
2427 uintptr_t offs;
2428
2429 if (buf == NULL)
2430 return;
2431
2432 if (!agg->dtag_hasarg) {
2433 /*
2434 * Currently, only quantize() and lquantize() take additional
2435 * arguments, and they have the same semantics: an increment
2436 * value that defaults to 1 when not present. If additional
2437 * aggregating actions take arguments, the setting of the
2438 * default argument value will presumably have to become more
2439 * sophisticated...
2440 */
2441 arg = 1;
2442 }
2443
2444 action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2445 size = rec->dtrd_offset - agg->dtag_base;
2446 fsize = size + rec->dtrd_size;
2447
2448 ASSERT(dbuf->dtb_tomax != NULL);
2449 data = dbuf->dtb_tomax + offset + agg->dtag_base;
2450
2451 if ((tomax = buf->dtb_tomax) == NULL) {
2452 dtrace_buffer_drop(buf);
2453 return;
2454 }
2455
2456 /*
2457 * The metastructure is always at the bottom of the buffer.
2458 */
2459 agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2460 sizeof (dtrace_aggbuffer_t));
2461
2462 if (buf->dtb_offset == 0) {
2463 /*
2464 * We just kludge up approximately 1/8th of the size to be
2465 * buckets. If this guess ends up being routinely
2466 * off-the-mark, we may need to dynamically readjust this
2467 * based on past performance.
2468 */
2469 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2470
2471 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2472 (uintptr_t)tomax || hashsize == 0) {
2473 /*
2474 * We've been given a ludicrously small buffer;
2475 * increment our drop count and leave.
2476 */
2477 dtrace_buffer_drop(buf);
2478 return;
2479 }
2480
2481 /*
2482 * And now, a pathetic attempt to try to get a an odd (or
2483 * perchance, a prime) hash size for better hash distribution.
2484 */
2485 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2486 hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2487
2488 agb->dtagb_hashsize = hashsize;
2489 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2490 agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2491 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2492
2493 for (i = 0; i < agb->dtagb_hashsize; i++)
2494 agb->dtagb_hash[i] = NULL;
2495 }
2496
2497 ASSERT(agg->dtag_first != NULL);
2498 ASSERT(agg->dtag_first->dta_intuple);
2499
2500 /*
2501 * Calculate the hash value based on the key. Note that we _don't_
2502 * include the aggid in the hashing (but we will store it as part of
2503 * the key). The hashing algorithm is Bob Jenkins' "One-at-a-time"
2504 * algorithm: a simple, quick algorithm that has no known funnels, and
2505 * gets good distribution in practice. The efficacy of the hashing
2506 * algorithm (and a comparison with other algorithms) may be found by
2507 * running the ::dtrace_aggstat MDB dcmd.
2508 */
2509 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2510 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2511 limit = i + act->dta_rec.dtrd_size;
2512 ASSERT(limit <= size);
2513 isstr = DTRACEACT_ISSTRING(act);
2514
2515 for (; i < limit; i++) {
2516 hashval += data[i];
2517 hashval += (hashval << 10);
2518 hashval ^= (hashval >> 6);
2519
2520 if (isstr && data[i] == '\0')
2521 break;
2522 }
2523 }
2524
2525 hashval += (hashval << 3);
2526 hashval ^= (hashval >> 11);
2527 hashval += (hashval << 15);
2528
2529 /*
2530 * Yes, the divide here is expensive -- but it's generally the least
2531 * of the performance issues given the amount of data that we iterate
2532 * over to compute hash values, compare data, etc.
2533 */
2534 ndx = hashval % agb->dtagb_hashsize;
2535
2536 for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2537 ASSERT((caddr_t)key >= tomax);
2538 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2539
2540 if (hashval != key->dtak_hashval || key->dtak_size != size)
2541 continue;
2542
2543 kdata = key->dtak_data;
2544 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2545
2546 for (act = agg->dtag_first; act->dta_intuple;
2547 act = act->dta_next) {
2548 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2549 limit = i + act->dta_rec.dtrd_size;
2550 ASSERT(limit <= size);
2551 isstr = DTRACEACT_ISSTRING(act);
2552
2553 for (; i < limit; i++) {
2554 if (kdata[i] != data[i])
2555 goto next;
2556
2557 if (isstr && data[i] == '\0')
2558 break;
2559 }
2560 }
2561
2562 if (action != key->dtak_action) {
2563 /*
2564 * We are aggregating on the same value in the same
2565 * aggregation with two different aggregating actions.
2566 * (This should have been picked up in the compiler,
2567 * so we may be dealing with errant or devious DIF.)
2568 * This is an error condition; we indicate as much,
2569 * and return.
2570 */
2571 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2572 return;
2573 }
2574
2575 /*
2576 * This is a hit: we need to apply the aggregator to
2577 * the value at this key.
2578 */
2579 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2580 return;
2581 next:
2582 continue;
2583 }
2584
2585 /*
2586 * We didn't find it. We need to allocate some zero-filled space,
2587 * link it into the hash table appropriately, and apply the aggregator
2588 * to the (zero-filled) value.
2589 */
2590 offs = buf->dtb_offset;
2591 while (offs & (align - 1))
2592 offs += sizeof (uint32_t);
2593
2594 /*
2595 * If we don't have enough room to both allocate a new key _and_
2596 * its associated data, increment the drop count and return.
2597 */
2598 if ((uintptr_t)tomax + offs + fsize >
2599 agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2600 dtrace_buffer_drop(buf);
2601 return;
2602 }
2603
2604 /*CONSTCOND*/
2605 ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2606 key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2607 agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2608
2609 key->dtak_data = kdata = tomax + offs;
2610 buf->dtb_offset = offs + fsize;
2611
2612 /*
2613 * Now copy the data across.
2614 */
2615 *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2616
2617 for (i = sizeof (dtrace_aggid_t); i < size; i++)
2618 kdata[i] = data[i];
2619
2620 /*
2621 * Because strings are not zeroed out by default, we need to iterate
2622 * looking for actions that store strings, and we need to explicitly
2623 * pad these strings out with zeroes.
2624 */
2625 for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2626 int nul;
2627
2628 if (!DTRACEACT_ISSTRING(act))
2629 continue;
2630
2631 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2632 limit = i + act->dta_rec.dtrd_size;
2633 ASSERT(limit <= size);
2634
2635 for (nul = 0; i < limit; i++) {
2636 if (nul) {
2637 kdata[i] = '\0';
2638 continue;
2639 }
2640
2641 if (data[i] != '\0')
2642 continue;
2643
2644 nul = 1;
2645 }
2646 }
2647
2648 for (i = size; i < fsize; i++)
2649 kdata[i] = 0;
2650
2651 key->dtak_hashval = hashval;
2652 key->dtak_size = size;
2653 key->dtak_action = action;
2654 key->dtak_next = agb->dtagb_hash[ndx];
2655 agb->dtagb_hash[ndx] = key;
2656
2657 /*
2658 * Finally, apply the aggregator.
2659 */
2660 *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2661 agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2662 }
2663
2664 /*
2665 * Given consumer state, this routine finds a speculation in the INACTIVE
2666 * state and transitions it into the ACTIVE state. If there is no speculation
2667 * in the INACTIVE state, 0 is returned. In this case, no error counter is
2668 * incremented -- it is up to the caller to take appropriate action.
2669 */
2670 static int
2671 dtrace_speculation(dtrace_state_t *state)
2672 {
2673 int i = 0;
2674 dtrace_speculation_state_t current;
2675 uint32_t *stat = &state->dts_speculations_unavail, count;
2676
2677 while (i < state->dts_nspeculations) {
2678 dtrace_speculation_t *spec = &state->dts_speculations[i];
2679
2680 current = spec->dtsp_state;
2681
2682 if (current != DTRACESPEC_INACTIVE) {
2683 if (current == DTRACESPEC_COMMITTINGMANY ||
2684 current == DTRACESPEC_COMMITTING ||
2685 current == DTRACESPEC_DISCARDING)
2686 stat = &state->dts_speculations_busy;
2687 i++;
2688 continue;
2689 }
2690
2691 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2692 current, DTRACESPEC_ACTIVE) == current)
2693 return (i + 1);
2694 }
2695
2696 /*
2697 * We couldn't find a speculation. If we found as much as a single
2698 * busy speculation buffer, we'll attribute this failure as "busy"
2699 * instead of "unavail".
2700 */
2701 do {
2702 count = *stat;
2703 } while (dtrace_cas32(stat, count, count + 1) != count);
2704
2705 return (0);
2706 }
2707
2708 /*
2709 * This routine commits an active speculation. If the specified speculation
2710 * is not in a valid state to perform a commit(), this routine will silently do
2711 * nothing. The state of the specified speculation is transitioned according
2712 * to the state transition diagram outlined in <sys/dtrace_impl.h>
2713 */
2714 static void
2715 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2716 dtrace_specid_t which)
2717 {
2718 dtrace_speculation_t *spec;
2719 dtrace_buffer_t *src, *dest;
2720 uintptr_t daddr, saddr, dlimit, slimit;
2721 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2722 intptr_t offs;
2723 uint64_t timestamp;
2724
2725 if (which == 0)
2726 return;
2727
2728 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2729 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2730 return;
2731 }
2732
2733 spec = &state->dts_speculations[which - 1];
2734 src = &spec->dtsp_buffer[cpu];
2735 dest = &state->dts_buffer[cpu];
2736
2737 do {
2738 current = spec->dtsp_state;
2739
2740 if (current == DTRACESPEC_COMMITTINGMANY)
2741 break;
2742
2743 switch (current) {
2744 case DTRACESPEC_INACTIVE:
2745 case DTRACESPEC_DISCARDING:
2746 return;
2747
2748 case DTRACESPEC_COMMITTING:
2749 /*
2750 * This is only possible if we are (a) commit()'ing
2751 * without having done a prior speculate() on this CPU
2752 * and (b) racing with another commit() on a different
2753 * CPU. There's nothing to do -- we just assert that
2754 * our offset is 0.
2755 */
2756 ASSERT(src->dtb_offset == 0);
2757 return;
2758
2759 case DTRACESPEC_ACTIVE:
2760 new = DTRACESPEC_COMMITTING;
2761 break;
2762
2763 case DTRACESPEC_ACTIVEONE:
2764 /*
2765 * This speculation is active on one CPU. If our
2766 * buffer offset is non-zero, we know that the one CPU
2767 * must be us. Otherwise, we are committing on a
2768 * different CPU from the speculate(), and we must
2769 * rely on being asynchronously cleaned.
2770 */
2771 if (src->dtb_offset != 0) {
2772 new = DTRACESPEC_COMMITTING;
2773 break;
2774 }
2775 /*FALLTHROUGH*/
2776
2777 case DTRACESPEC_ACTIVEMANY:
2778 new = DTRACESPEC_COMMITTINGMANY;
2779 break;
2780
2781 default:
2782 ASSERT(0);
2783 }
2784 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2785 current, new) != current);
2786
2787 /*
2788 * We have set the state to indicate that we are committing this
2789 * speculation. Now reserve the necessary space in the destination
2790 * buffer.
2791 */
2792 if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2793 sizeof (uint64_t), state, NULL)) < 0) {
2794 dtrace_buffer_drop(dest);
2795 goto out;
2796 }
2797
2798 /*
2799 * We have sufficient space to copy the speculative buffer into the
2800 * primary buffer. First, modify the speculative buffer, filling
2801 * in the timestamp of all entries with the current time. The data
2802 * must have the commit() time rather than the time it was traced,
2803 * so that all entries in the primary buffer are in timestamp order.
2804 */
2805 timestamp = dtrace_gethrtime();
2806 saddr = (uintptr_t)src->dtb_tomax;
2807 slimit = saddr + src->dtb_offset;
2808 while (saddr < slimit) {
2809 size_t size;
2810 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2811
2812 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2813 saddr += sizeof (dtrace_epid_t);
2814 continue;
2815 }
2816
2817 ASSERT(dtrh->dtrh_epid <= ((dtrace_epid_t) state->dts_necbs));
2818 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2819
2820 ASSERT(saddr + size <= slimit);
2821 ASSERT(size >= sizeof(dtrace_rechdr_t));
2822 ASSERT(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh) == UINT64_MAX);
2823
2824 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2825
2826 saddr += size;
2827 }
2828
2829 /*
2830 * Copy the buffer across. (Note that this is a
2831 * highly subobtimal bcopy(); in the unlikely event that this becomes
2832 * a serious performance issue, a high-performance DTrace-specific
2833 * bcopy() should obviously be invented.)
2834 */
2835 daddr = (uintptr_t)dest->dtb_tomax + offs;
2836 dlimit = daddr + src->dtb_offset;
2837 saddr = (uintptr_t)src->dtb_tomax;
2838
2839 /*
2840 * First, the aligned portion.
2841 */
2842 while (dlimit - daddr >= sizeof (uint64_t)) {
2843 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2844
2845 daddr += sizeof (uint64_t);
2846 saddr += sizeof (uint64_t);
2847 }
2848
2849 /*
2850 * Now any left-over bit...
2851 */
2852 while (dlimit - daddr)
2853 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2854
2855 /*
2856 * Finally, commit the reserved space in the destination buffer.
2857 */
2858 dest->dtb_offset = offs + src->dtb_offset;
2859
2860 out:
2861 /*
2862 * If we're lucky enough to be the only active CPU on this speculation
2863 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2864 */
2865 if (current == DTRACESPEC_ACTIVE ||
2866 (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2867 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2868 DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2869 #pragma unused(rval) /* __APPLE__ */
2870
2871 ASSERT(rval == DTRACESPEC_COMMITTING);
2872 }
2873
2874 src->dtb_offset = 0;
2875 src->dtb_xamot_drops += src->dtb_drops;
2876 src->dtb_drops = 0;
2877 }
2878
2879 /*
2880 * This routine discards an active speculation. If the specified speculation
2881 * is not in a valid state to perform a discard(), this routine will silently
2882 * do nothing. The state of the specified speculation is transitioned
2883 * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2884 */
2885 static void
2886 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2887 dtrace_specid_t which)
2888 {
2889 dtrace_speculation_t *spec;
2890 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
2891 dtrace_buffer_t *buf;
2892
2893 if (which == 0)
2894 return;
2895
2896 if (which > (dtrace_specid_t)state->dts_nspeculations) {
2897 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2898 return;
2899 }
2900
2901 spec = &state->dts_speculations[which - 1];
2902 buf = &spec->dtsp_buffer[cpu];
2903
2904 do {
2905 current = spec->dtsp_state;
2906
2907 switch (current) {
2908 case DTRACESPEC_INACTIVE:
2909 case DTRACESPEC_COMMITTINGMANY:
2910 case DTRACESPEC_COMMITTING:
2911 case DTRACESPEC_DISCARDING:
2912 return;
2913
2914 case DTRACESPEC_ACTIVE:
2915 case DTRACESPEC_ACTIVEMANY:
2916 new = DTRACESPEC_DISCARDING;
2917 break;
2918
2919 case DTRACESPEC_ACTIVEONE:
2920 if (buf->dtb_offset != 0) {
2921 new = DTRACESPEC_INACTIVE;
2922 } else {
2923 new = DTRACESPEC_DISCARDING;
2924 }
2925 break;
2926
2927 default:
2928 ASSERT(0);
2929 }
2930 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2931 current, new) != current);
2932
2933 buf->dtb_offset = 0;
2934 buf->dtb_drops = 0;
2935 }
2936
2937 /*
2938 * Note: not called from probe context. This function is called
2939 * asynchronously from cross call context to clean any speculations that are
2940 * in the COMMITTINGMANY or DISCARDING states. These speculations may not be
2941 * transitioned back to the INACTIVE state until all CPUs have cleaned the
2942 * speculation.
2943 */
2944 static void
2945 dtrace_speculation_clean_here(dtrace_state_t *state)
2946 {
2947 dtrace_icookie_t cookie;
2948 processorid_t cpu = CPU->cpu_id;
2949 dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2950 dtrace_specid_t i;
2951
2952 cookie = dtrace_interrupt_disable();
2953
2954 if (dest->dtb_tomax == NULL) {
2955 dtrace_interrupt_enable(cookie);
2956 return;
2957 }
2958
2959 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2960 dtrace_speculation_t *spec = &state->dts_speculations[i];
2961 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2962
2963 if (src->dtb_tomax == NULL)
2964 continue;
2965
2966 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2967 src->dtb_offset = 0;
2968 continue;
2969 }
2970
2971 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2972 continue;
2973
2974 if (src->dtb_offset == 0)
2975 continue;
2976
2977 dtrace_speculation_commit(state, cpu, i + 1);
2978 }
2979
2980 dtrace_interrupt_enable(cookie);
2981 }
2982
2983 /*
2984 * Note: not called from probe context. This function is called
2985 * asynchronously (and at a regular interval) to clean any speculations that
2986 * are in the COMMITTINGMANY or DISCARDING states. If it discovers that there
2987 * is work to be done, it cross calls all CPUs to perform that work;
2988 * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2989 * INACTIVE state until they have been cleaned by all CPUs.
2990 */
2991 static void
2992 dtrace_speculation_clean(dtrace_state_t *state)
2993 {
2994 int work = 0;
2995 uint32_t rv;
2996 dtrace_specid_t i;
2997
2998 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
2999 dtrace_speculation_t *spec = &state->dts_speculations[i];
3000
3001 ASSERT(!spec->dtsp_cleaning);
3002
3003 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
3004 spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
3005 continue;
3006
3007 work++;
3008 spec->dtsp_cleaning = 1;
3009 }
3010
3011 if (!work)
3012 return;
3013
3014 dtrace_xcall(DTRACE_CPUALL,
3015 (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3016
3017 /*
3018 * We now know that all CPUs have committed or discarded their
3019 * speculation buffers, as appropriate. We can now set the state
3020 * to inactive.
3021 */
3022 for (i = 0; i < (dtrace_specid_t)state->dts_nspeculations; i++) {
3023 dtrace_speculation_t *spec = &state->dts_speculations[i];
3024 dtrace_speculation_state_t current, new;
3025
3026 if (!spec->dtsp_cleaning)
3027 continue;
3028
3029 current = spec->dtsp_state;
3030 ASSERT(current == DTRACESPEC_DISCARDING ||
3031 current == DTRACESPEC_COMMITTINGMANY);
3032
3033 new = DTRACESPEC_INACTIVE;
3034
3035 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3036 ASSERT(rv == current);
3037 spec->dtsp_cleaning = 0;
3038 }
3039 }
3040
3041 /*
3042 * Called as part of a speculate() to get the speculative buffer associated
3043 * with a given speculation. Returns NULL if the specified speculation is not
3044 * in an ACTIVE state. If the speculation is in the ACTIVEONE state -- and
3045 * the active CPU is not the specified CPU -- the speculation will be
3046 * atomically transitioned into the ACTIVEMANY state.
3047 */
3048 static dtrace_buffer_t *
3049 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3050 dtrace_specid_t which)
3051 {
3052 dtrace_speculation_t *spec;
3053 dtrace_speculation_state_t current, new = DTRACESPEC_INACTIVE;
3054 dtrace_buffer_t *buf;
3055
3056 if (which == 0)
3057 return (NULL);
3058
3059 if (which > (dtrace_specid_t)state->dts_nspeculations) {
3060 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3061 return (NULL);
3062 }
3063
3064 spec = &state->dts_speculations[which - 1];
3065 buf = &spec->dtsp_buffer[cpuid];
3066
3067 do {
3068 current = spec->dtsp_state;
3069
3070 switch (current) {
3071 case DTRACESPEC_INACTIVE:
3072 case DTRACESPEC_COMMITTINGMANY:
3073 case DTRACESPEC_DISCARDING:
3074 return (NULL);
3075
3076 case DTRACESPEC_COMMITTING:
3077 ASSERT(buf->dtb_offset == 0);
3078 return (NULL);
3079
3080 case DTRACESPEC_ACTIVEONE:
3081 /*
3082 * This speculation is currently active on one CPU.
3083 * Check the offset in the buffer; if it's non-zero,
3084 * that CPU must be us (and we leave the state alone).
3085 * If it's zero, assume that we're starting on a new
3086 * CPU -- and change the state to indicate that the
3087 * speculation is active on more than one CPU.
3088 */
3089 if (buf->dtb_offset != 0)
3090 return (buf);
3091
3092 new = DTRACESPEC_ACTIVEMANY;
3093 break;
3094
3095 case DTRACESPEC_ACTIVEMANY:
3096 return (buf);
3097
3098 case DTRACESPEC_ACTIVE:
3099 new = DTRACESPEC_ACTIVEONE;
3100 break;
3101
3102 default:
3103 ASSERT(0);
3104 }
3105 } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3106 current, new) != current);
3107
3108 ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3109 return (buf);
3110 }
3111
3112 /*
3113 * Return a string. In the event that the user lacks the privilege to access
3114 * arbitrary kernel memory, we copy the string out to scratch memory so that we
3115 * don't fail access checking.
3116 *
3117 * dtrace_dif_variable() uses this routine as a helper for various
3118 * builtin values such as 'execname' and 'probefunc.'
3119 */
3120 static
3121 uintptr_t
3122 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3123 dtrace_mstate_t *mstate)
3124 {
3125 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3126 uintptr_t ret;
3127 size_t strsz;
3128
3129 /*
3130 * The easy case: this probe is allowed to read all of memory, so
3131 * we can just return this as a vanilla pointer.
3132 */
3133 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3134 return (addr);
3135
3136 /*
3137 * This is the tougher case: we copy the string in question from
3138 * kernel memory into scratch memory and return it that way: this
3139 * ensures that we won't trip up when access checking tests the
3140 * BYREF return value.
3141 */
3142 strsz = dtrace_strlen((char *)addr, size) + 1;
3143
3144 if (mstate->dtms_scratch_ptr + strsz >
3145 mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3146 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3147 return (0);
3148 }
3149
3150 dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3151 strsz);
3152 ret = mstate->dtms_scratch_ptr;
3153 mstate->dtms_scratch_ptr += strsz;
3154 return (ret);
3155 }
3156
3157 /*
3158 * This function implements the DIF emulator's variable lookups. The emulator
3159 * passes a reserved variable identifier and optional built-in array index.
3160 */
3161 static uint64_t
3162 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3163 uint64_t ndx)
3164 {
3165 /*
3166 * If we're accessing one of the uncached arguments, we'll turn this
3167 * into a reference in the args array.
3168 */
3169 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3170 ndx = v - DIF_VAR_ARG0;
3171 v = DIF_VAR_ARGS;
3172 }
3173
3174 switch (v) {
3175 case DIF_VAR_ARGS:
3176 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3177 if (ndx >= sizeof (mstate->dtms_arg) /
3178 sizeof (mstate->dtms_arg[0])) {
3179 /*
3180 * APPLE NOTE: Account for introduction of __dtrace_probe()
3181 */
3182 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3183 dtrace_provider_t *pv;
3184 uint64_t val;
3185
3186 pv = mstate->dtms_probe->dtpr_provider;
3187 if (pv->dtpv_pops.dtps_getargval != NULL)
3188 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3189 mstate->dtms_probe->dtpr_id,
3190 mstate->dtms_probe->dtpr_arg, ndx, aframes);
3191 /* Special case access of arg5 as passed to dtrace_probe_error() (which see.) */
3192 else if (mstate->dtms_probe->dtpr_id == dtrace_probeid_error && ndx == 5) {
3193 return ((dtrace_state_t *)(uintptr_t)(mstate->dtms_arg[0]))->dts_arg_error_illval;
3194 }
3195
3196 else
3197 val = dtrace_getarg(ndx, aframes);
3198
3199 /*
3200 * This is regrettably required to keep the compiler
3201 * from tail-optimizing the call to dtrace_getarg().
3202 * The condition always evaluates to true, but the
3203 * compiler has no way of figuring that out a priori.
3204 * (None of this would be necessary if the compiler
3205 * could be relied upon to _always_ tail-optimize
3206 * the call to dtrace_getarg() -- but it can't.)
3207 */
3208 if (mstate->dtms_probe != NULL)
3209 return (val);
3210
3211 ASSERT(0);
3212 }
3213
3214 return (mstate->dtms_arg[ndx]);
3215
3216 case DIF_VAR_UREGS: {
3217 thread_t thread;
3218
3219 if (!dtrace_priv_proc(state))
3220 return (0);
3221
3222 if ((thread = current_thread()) == NULL) {
3223 DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3224 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3225 return (0);
3226 }
3227
3228 return (dtrace_getreg(find_user_regs(thread), ndx));
3229 }
3230
3231
3232 case DIF_VAR_CURTHREAD:
3233 if (!dtrace_priv_kernel(state))
3234 return (0);
3235
3236 return ((uint64_t)(uintptr_t)current_thread());
3237
3238 case DIF_VAR_TIMESTAMP:
3239 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3240 mstate->dtms_timestamp = dtrace_gethrtime();
3241 mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3242 }
3243 return (mstate->dtms_timestamp);
3244
3245 case DIF_VAR_VTIMESTAMP:
3246 ASSERT(dtrace_vtime_references != 0);
3247 return (dtrace_get_thread_vtime(current_thread()));
3248
3249 case DIF_VAR_WALLTIMESTAMP:
3250 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3251 mstate->dtms_walltimestamp = dtrace_gethrestime();
3252 mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3253 }
3254 return (mstate->dtms_walltimestamp);
3255
3256 case DIF_VAR_MACHTIMESTAMP:
3257 if (!(mstate->dtms_present & DTRACE_MSTATE_MACHTIMESTAMP)) {
3258 mstate->dtms_machtimestamp = mach_absolute_time();
3259 mstate->dtms_present |= DTRACE_MSTATE_MACHTIMESTAMP;
3260 }
3261 return (mstate->dtms_machtimestamp);
3262
3263 case DIF_VAR_CPU:
3264 return ((uint64_t) dtrace_get_thread_last_cpu_id(current_thread()));
3265
3266 case DIF_VAR_IPL:
3267 if (!dtrace_priv_kernel(state))
3268 return (0);
3269 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3270 mstate->dtms_ipl = dtrace_getipl();
3271 mstate->dtms_present |= DTRACE_MSTATE_IPL;
3272 }
3273 return (mstate->dtms_ipl);
3274
3275 case DIF_VAR_EPID:
3276 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3277 return (mstate->dtms_epid);
3278
3279 case DIF_VAR_ID:
3280 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3281 return (mstate->dtms_probe->dtpr_id);
3282
3283 case DIF_VAR_STACKDEPTH:
3284 if (!dtrace_priv_kernel(state))
3285 return (0);
3286 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3287 /*
3288 * APPLE NOTE: Account for introduction of __dtrace_probe()
3289 */
3290 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3291
3292 mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3293 mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3294 }
3295 return (mstate->dtms_stackdepth);
3296
3297 case DIF_VAR_USTACKDEPTH:
3298 if (!dtrace_priv_proc(state))
3299 return (0);
3300 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3301 /*
3302 * See comment in DIF_VAR_PID.
3303 */
3304 if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3305 CPU_ON_INTR(CPU)) {
3306 mstate->dtms_ustackdepth = 0;
3307 } else {
3308 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3309 mstate->dtms_ustackdepth =
3310 dtrace_getustackdepth();
3311 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3312 }
3313 mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3314 }
3315 return (mstate->dtms_ustackdepth);
3316
3317 case DIF_VAR_CALLER:
3318 if (!dtrace_priv_kernel(state))
3319 return (0);
3320 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3321 /*
3322 * APPLE NOTE: Account for introduction of __dtrace_probe()
3323 */
3324 int aframes = mstate->dtms_probe->dtpr_aframes + 3;
3325
3326 if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3327 /*
3328 * If this is an unanchored probe, we are
3329 * required to go through the slow path:
3330 * dtrace_caller() only guarantees correct
3331 * results for anchored probes.
3332 */
3333 pc_t caller[2];
3334
3335 dtrace_getpcstack(caller, 2, aframes,
3336 (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3337 mstate->dtms_caller = caller[1];
3338 } else if ((mstate->dtms_caller =
3339 dtrace_caller(aframes)) == (uintptr_t)-1) {
3340 /*
3341 * We have failed to do this the quick way;
3342 * we must resort to the slower approach of
3343 * calling dtrace_getpcstack().
3344 */
3345 pc_t caller;
3346
3347 dtrace_getpcstack(&caller, 1, aframes, NULL);
3348 mstate->dtms_caller = caller;
3349 }
3350
3351 mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3352 }
3353 return (mstate->dtms_caller);
3354
3355 case DIF_VAR_UCALLER:
3356 if (!dtrace_priv_proc(state))
3357 return (0);
3358
3359 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3360 uint64_t ustack[3];
3361
3362 /*
3363 * dtrace_getupcstack() fills in the first uint64_t
3364 * with the current PID. The second uint64_t will
3365 * be the program counter at user-level. The third
3366 * uint64_t will contain the caller, which is what
3367 * we're after.
3368 */
3369 ustack[2] = 0;
3370 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3371 dtrace_getupcstack(ustack, 3);
3372 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3373 mstate->dtms_ucaller = ustack[2];
3374 mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3375 }
3376
3377 return (mstate->dtms_ucaller);
3378
3379 case DIF_VAR_PROBEPROV:
3380 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3381 return (dtrace_dif_varstr(
3382 (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3383 state, mstate));
3384
3385 case DIF_VAR_PROBEMOD:
3386 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3387 return (dtrace_dif_varstr(
3388 (uintptr_t)mstate->dtms_probe->dtpr_mod,
3389 state, mstate));
3390
3391 case DIF_VAR_PROBEFUNC:
3392 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3393 return (dtrace_dif_varstr(
3394 (uintptr_t)mstate->dtms_probe->dtpr_func,
3395 state, mstate));
3396
3397 case DIF_VAR_PROBENAME:
3398 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3399 return (dtrace_dif_varstr(
3400 (uintptr_t)mstate->dtms_probe->dtpr_name,
3401 state, mstate));
3402
3403 case DIF_VAR_PID:
3404 if (!dtrace_priv_proc_relaxed(state))
3405 return (0);
3406
3407 /*
3408 * Note that we are assuming that an unanchored probe is
3409 * always due to a high-level interrupt. (And we're assuming
3410 * that there is only a single high level interrupt.)
3411 */
3412 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3413 /* Anchored probe that fires while on an interrupt accrues to process 0 */
3414 return 0;
3415
3416 return ((uint64_t)dtrace_proc_selfpid());
3417
3418 case DIF_VAR_PPID:
3419 if (!dtrace_priv_proc_relaxed(state))
3420 return (0);
3421
3422 /*
3423 * See comment in DIF_VAR_PID.
3424 */
3425 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3426 return (0);
3427
3428 return ((uint64_t)dtrace_proc_selfppid());
3429
3430 case DIF_VAR_TID:
3431 /* We do not need to check for null current_thread() */
3432 return thread_tid(current_thread()); /* globally unique */
3433
3434 case DIF_VAR_PTHREAD_SELF:
3435 if (!dtrace_priv_proc(state))
3436 return (0);
3437
3438 /* Not currently supported, but we should be able to delta the dispatchqaddr and dispatchqoffset to get pthread_self */
3439 return 0;
3440
3441 case DIF_VAR_DISPATCHQADDR:
3442 if (!dtrace_priv_proc(state))
3443 return (0);
3444
3445 /* We do not need to check for null current_thread() */
3446 return thread_dispatchqaddr(current_thread());
3447
3448 case DIF_VAR_EXECNAME:
3449 {
3450 char *xname = (char *)mstate->dtms_scratch_ptr;
3451 size_t scratch_size = MAXCOMLEN+1;
3452
3453 /* The scratch allocation's lifetime is that of the clause. */
3454 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3455 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3456 return 0;
3457 }
3458
3459 if (!dtrace_priv_proc_relaxed(state))
3460 return (0);
3461
3462 mstate->dtms_scratch_ptr += scratch_size;
3463 proc_selfname( xname, scratch_size );
3464
3465 return ((uint64_t)(uintptr_t)xname);
3466 }
3467
3468
3469 case DIF_VAR_ZONENAME:
3470 {
3471 /* scratch_size is equal to length('global') + 1 for the null-terminator. */
3472 char *zname = (char *)mstate->dtms_scratch_ptr;
3473 size_t scratch_size = 6 + 1;
3474
3475 if (!dtrace_priv_proc(state))
3476 return (0);
3477
3478 /* The scratch allocation's lifetime is that of the clause. */
3479 if (!DTRACE_INSCRATCH(mstate, scratch_size)) {
3480 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3481 return 0;
3482 }
3483
3484 mstate->dtms_scratch_ptr += scratch_size;
3485
3486 /* The kernel does not provide zonename, it will always return 'global'. */
3487 strlcpy(zname, "global", scratch_size);
3488
3489 return ((uint64_t)(uintptr_t)zname);
3490 }
3491
3492 case DIF_VAR_UID:
3493 if (!dtrace_priv_proc_relaxed(state))
3494 return (0);
3495
3496 /*
3497 * See comment in DIF_VAR_PID.
3498 */
3499 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3500 return (0);
3501
3502 return ((uint64_t) dtrace_proc_selfruid());
3503
3504 case DIF_VAR_GID:
3505 if (!dtrace_priv_proc(state))
3506 return (0);
3507
3508 /*
3509 * See comment in DIF_VAR_PID.
3510 */
3511 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3512 return (0);
3513
3514 if (dtrace_CRED() != NULL)
3515 /* Credential does not require lazy initialization. */
3516 return ((uint64_t)kauth_getgid());
3517 else {
3518 /* proc_lock would be taken under kauth_cred_proc_ref() in kauth_cred_get(). */
3519 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3520 return -1ULL;
3521 }
3522
3523 case DIF_VAR_ERRNO: {
3524 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
3525 if (!dtrace_priv_proc(state))
3526 return (0);
3527
3528 /*
3529 * See comment in DIF_VAR_PID.
3530 */
3531 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3532 return (0);
3533
3534 if (uthread)
3535 return (uint64_t)uthread->t_dtrace_errno;
3536 else {
3537 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3538 return -1ULL;
3539 }
3540 }
3541
3542 default:
3543 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3544 return (0);
3545 }
3546 }
3547
3548 /*
3549 * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3550 * Notice that we don't bother validating the proper number of arguments or
3551 * their types in the tuple stack. This isn't needed because all argument
3552 * interpretation is safe because of our load safety -- the worst that can
3553 * happen is that a bogus program can obtain bogus results.
3554 */
3555 static void
3556 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3557 dtrace_key_t *tupregs, int nargs,
3558 dtrace_mstate_t *mstate, dtrace_state_t *state)
3559 {
3560 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3561 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3562 dtrace_vstate_t *vstate = &state->dts_vstate;
3563
3564 #if !defined(__APPLE__)
3565 union {
3566 mutex_impl_t mi;
3567 uint64_t mx;
3568 } m;
3569
3570 union {
3571 krwlock_t ri;
3572 uintptr_t rw;
3573 } r;
3574 #else
3575 /* FIXME: awaits lock/mutex work */
3576 #endif /* __APPLE__ */
3577
3578 switch (subr) {
3579 case DIF_SUBR_RAND:
3580 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3581 break;
3582
3583 #if !defined(__APPLE__)
3584 case DIF_SUBR_MUTEX_OWNED:
3585 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3586 mstate, vstate)) {
3587 regs[rd] = 0;
3588 break;
3589 }
3590
3591 m.mx = dtrace_load64(tupregs[0].dttk_value);
3592 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3593 regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3594 else
3595 regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3596 break;
3597
3598 case DIF_SUBR_MUTEX_OWNER:
3599 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3600 mstate, vstate)) {
3601 regs[rd] = 0;
3602 break;
3603 }
3604
3605 m.mx = dtrace_load64(tupregs[0].dttk_value);
3606 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3607 MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3608 regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3609 else
3610 regs[rd] = 0;
3611 break;
3612
3613 case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3614 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3615 mstate, vstate)) {
3616 regs[rd] = 0;
3617 break;
3618 }
3619
3620 m.mx = dtrace_load64(tupregs[0].dttk_value);
3621 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3622 break;
3623
3624 case DIF_SUBR_MUTEX_TYPE_SPIN:
3625 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3626 mstate, vstate)) {
3627 regs[rd] = 0;
3628 break;
3629 }
3630
3631 m.mx = dtrace_load64(tupregs[0].dttk_value);
3632 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3633 break;
3634
3635 case DIF_SUBR_RW_READ_HELD: {
3636 uintptr_t tmp;
3637
3638 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3639 mstate, vstate)) {
3640 regs[rd] = 0;
3641 break;
3642 }
3643
3644 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3645 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3646 break;
3647 }
3648
3649 case DIF_SUBR_RW_WRITE_HELD:
3650 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3651 mstate, vstate)) {
3652 regs[rd] = 0;
3653 break;
3654 }
3655
3656 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3657 regs[rd] = _RW_WRITE_HELD(&r.ri);
3658 break;
3659
3660 case DIF_SUBR_RW_ISWRITER:
3661 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3662 mstate, vstate)) {
3663 regs[rd] = 0;
3664 break;
3665 }
3666
3667 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3668 regs[rd] = _RW_ISWRITER(&r.ri);
3669 break;
3670 #else
3671 /* FIXME: awaits lock/mutex work */
3672 #endif /* __APPLE__ */
3673
3674 case DIF_SUBR_BCOPY: {
3675 /*
3676 * We need to be sure that the destination is in the scratch
3677 * region -- no other region is allowed.
3678 */
3679 uintptr_t src = tupregs[0].dttk_value;
3680 uintptr_t dest = tupregs[1].dttk_value;
3681 size_t size = tupregs[2].dttk_value;
3682
3683 if (!dtrace_inscratch(dest, size, mstate)) {
3684 *flags |= CPU_DTRACE_BADADDR;
3685 *illval = regs[rd];
3686 break;
3687 }
3688
3689 if (!dtrace_canload(src, size, mstate, vstate)) {
3690 regs[rd] = 0;
3691 break;
3692 }
3693
3694 dtrace_bcopy((void *)src, (void *)dest, size);
3695 break;
3696 }
3697
3698 case DIF_SUBR_ALLOCA:
3699 case DIF_SUBR_COPYIN: {
3700 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3701 uint64_t size =
3702 tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3703 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3704
3705 /*
3706 * Check whether the user can access kernel memory
3707 */
3708 if (dtrace_priv_kernel(state) == 0) {
3709 DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
3710 regs[rd] = 0;
3711 break;
3712 }
3713 /*
3714 * This action doesn't require any credential checks since
3715 * probes will not activate in user contexts to which the
3716 * enabling user does not have permissions.
3717 */
3718
3719 /*
3720 * Rounding up the user allocation size could have overflowed
3721 * a large, bogus allocation (like -1ULL) to 0.
3722 */
3723 if (scratch_size < size ||
3724 !DTRACE_INSCRATCH(mstate, scratch_size)) {
3725 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3726 regs[rd] = 0;
3727 break;
3728 }
3729
3730 if (subr == DIF_SUBR_COPYIN) {
3731 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3732 if (dtrace_priv_proc(state))
3733 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3734 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3735 }
3736
3737 mstate->dtms_scratch_ptr += scratch_size;
3738 regs[rd] = dest;
3739 break;
3740 }
3741
3742 case DIF_SUBR_COPYINTO: {
3743 uint64_t size = tupregs[1].dttk_value;
3744 uintptr_t dest = tupregs[2].dttk_value;
3745
3746 /*
3747 * This action doesn't require any credential checks since
3748 * probes will not activate in user contexts to which the
3749 * enabling user does not have permissions.
3750 */
3751 if (!dtrace_inscratch(dest, size, mstate)) {
3752 *flags |= CPU_DTRACE_BADADDR;
3753 *illval = regs[rd];
3754 break;
3755 }
3756
3757 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3758 if (dtrace_priv_proc(state))
3759 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3760 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3761 break;
3762 }
3763
3764 case DIF_SUBR_COPYINSTR: {
3765 uintptr_t dest = mstate->dtms_scratch_ptr;
3766 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3767
3768 if (nargs > 1 && tupregs[1].dttk_value < size)
3769 size = tupregs[1].dttk_value + 1;
3770
3771 /*
3772 * This action doesn't require any credential checks since
3773 * probes will not activate in user contexts to which the
3774 * enabling user does not have permissions.
3775 */
3776 if (!DTRACE_INSCRATCH(mstate, size)) {
3777 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3778 regs[rd] = 0;
3779 break;
3780 }
3781
3782 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3783 if (dtrace_priv_proc(state))
3784 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3785 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3786
3787 ((char *)dest)[size - 1] = '\0';
3788 mstate->dtms_scratch_ptr += size;
3789 regs[rd] = dest;
3790 break;
3791 }
3792
3793 case DIF_SUBR_MSGSIZE:
3794 case DIF_SUBR_MSGDSIZE: {
3795 /* Darwin does not implement SysV streams messages */
3796 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3797 regs[rd] = 0;
3798 break;
3799 }
3800
3801 case DIF_SUBR_PROGENYOF: {
3802 pid_t pid = tupregs[0].dttk_value;
3803 struct proc *p = current_proc();
3804 int rval = 0, lim = nprocs;
3805
3806 while(p && (lim-- > 0)) {
3807 pid_t ppid;
3808
3809 ppid = (pid_t)dtrace_load32((uintptr_t)&(p->p_pid));
3810 if (*flags & CPU_DTRACE_FAULT)
3811 break;
3812
3813 if (ppid == pid) {
3814 rval = 1;
3815 break;
3816 }
3817
3818 if (ppid == 0)
3819 break; /* Can't climb process tree any further. */
3820
3821 p = (struct proc *)dtrace_loadptr((uintptr_t)&(p->p_pptr));
3822 if (*flags & CPU_DTRACE_FAULT)
3823 break;
3824 }
3825
3826 regs[rd] = rval;
3827 break;
3828 }
3829
3830 case DIF_SUBR_SPECULATION:
3831 regs[rd] = dtrace_speculation(state);
3832 break;
3833
3834
3835 case DIF_SUBR_COPYOUT: {
3836 uintptr_t kaddr = tupregs[0].dttk_value;
3837 user_addr_t uaddr = tupregs[1].dttk_value;
3838 uint64_t size = tupregs[2].dttk_value;
3839
3840 if (!dtrace_destructive_disallow &&
3841 dtrace_priv_proc_control(state) &&
3842 !dtrace_istoxic(kaddr, size) &&
3843 dtrace_canload(kaddr, size, mstate, vstate)) {
3844 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3845 dtrace_copyout(kaddr, uaddr, size, flags);
3846 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3847 }
3848 break;
3849 }
3850
3851 case DIF_SUBR_COPYOUTSTR: {
3852 uintptr_t kaddr = tupregs[0].dttk_value;
3853 user_addr_t uaddr = tupregs[1].dttk_value;
3854 uint64_t size = tupregs[2].dttk_value;
3855 size_t lim;
3856
3857 if (!dtrace_destructive_disallow &&
3858 dtrace_priv_proc_control(state) &&
3859 !dtrace_istoxic(kaddr, size) &&
3860 dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
3861 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3862 dtrace_copyoutstr(kaddr, uaddr, lim, flags);
3863 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3864 }
3865 break;
3866 }
3867
3868 case DIF_SUBR_STRLEN: {
3869 size_t size = state->dts_options[DTRACEOPT_STRSIZE];
3870 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3871 size_t lim;
3872
3873 if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
3874 regs[rd] = 0;
3875 break;
3876 }
3877
3878 regs[rd] = dtrace_strlen((char *)addr, lim);
3879
3880 break;
3881 }
3882
3883 case DIF_SUBR_STRCHR:
3884 case DIF_SUBR_STRRCHR: {
3885 /*
3886 * We're going to iterate over the string looking for the
3887 * specified character. We will iterate until we have reached
3888 * the string length or we have found the character. If this
3889 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3890 * of the specified character instead of the first.
3891 */
3892 uintptr_t addr = tupregs[0].dttk_value;
3893 uintptr_t addr_limit;
3894 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3895 size_t lim;
3896 char c, target = (char)tupregs[1].dttk_value;
3897
3898 if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
3899 regs[rd] = NULL;
3900 break;
3901 }
3902 addr_limit = addr + lim;
3903
3904 for (regs[rd] = 0; addr < addr_limit; addr++) {
3905 if ((c = dtrace_load8(addr)) == target) {
3906 regs[rd] = addr;
3907
3908 if (subr == DIF_SUBR_STRCHR)
3909 break;
3910 }
3911
3912 if (c == '\0')
3913 break;
3914 }
3915
3916 break;
3917 }
3918
3919 case DIF_SUBR_STRSTR:
3920 case DIF_SUBR_INDEX:
3921 case DIF_SUBR_RINDEX: {
3922 /*
3923 * We're going to iterate over the string looking for the
3924 * specified string. We will iterate until we have reached
3925 * the string length or we have found the string. (Yes, this
3926 * is done in the most naive way possible -- but considering
3927 * that the string we're searching for is likely to be
3928 * relatively short, the complexity of Rabin-Karp or similar
3929 * hardly seems merited.)
3930 */
3931 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3932 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3933 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3934 size_t len = dtrace_strlen(addr, size);
3935 size_t sublen = dtrace_strlen(substr, size);
3936 char *limit = addr + len, *orig = addr;
3937 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3938 int inc = 1;
3939
3940 regs[rd] = notfound;
3941
3942 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3943 regs[rd] = 0;
3944 break;
3945 }
3946
3947 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3948 vstate)) {
3949 regs[rd] = 0;
3950 break;
3951 }
3952
3953 /*
3954 * strstr() and index()/rindex() have similar semantics if
3955 * both strings are the empty string: strstr() returns a
3956 * pointer to the (empty) string, and index() and rindex()
3957 * both return index 0 (regardless of any position argument).
3958 */
3959 if (sublen == 0 && len == 0) {
3960 if (subr == DIF_SUBR_STRSTR)
3961 regs[rd] = (uintptr_t)addr;
3962 else
3963 regs[rd] = 0;
3964 break;
3965 }
3966
3967 if (subr != DIF_SUBR_STRSTR) {
3968 if (subr == DIF_SUBR_RINDEX) {
3969 limit = orig - 1;
3970 addr += len;
3971 inc = -1;
3972 }
3973
3974 /*
3975 * Both index() and rindex() take an optional position
3976 * argument that denotes the starting position.
3977 */
3978 if (nargs == 3) {
3979 int64_t pos = (int64_t)tupregs[2].dttk_value;
3980
3981 /*
3982 * If the position argument to index() is
3983 * negative, Perl implicitly clamps it at
3984 * zero. This semantic is a little surprising
3985 * given the special meaning of negative
3986 * positions to similar Perl functions like
3987 * substr(), but it appears to reflect a
3988 * notion that index() can start from a
3989 * negative index and increment its way up to
3990 * the string. Given this notion, Perl's
3991 * rindex() is at least self-consistent in
3992 * that it implicitly clamps positions greater
3993 * than the string length to be the string
3994 * length. Where Perl completely loses
3995 * coherence, however, is when the specified
3996 * substring is the empty string (""). In
3997 * this case, even if the position is
3998 * negative, rindex() returns 0 -- and even if
3999 * the position is greater than the length,
4000 * index() returns the string length. These
4001 * semantics violate the notion that index()
4002 * should never return a value less than the
4003 * specified position and that rindex() should
4004 * never return a value greater than the
4005 * specified position. (One assumes that
4006 * these semantics are artifacts of Perl's
4007 * implementation and not the results of
4008 * deliberate design -- it beggars belief that
4009 * even Larry Wall could desire such oddness.)
4010 * While in the abstract one would wish for
4011 * consistent position semantics across
4012 * substr(), index() and rindex() -- or at the
4013 * very least self-consistent position
4014 * semantics for index() and rindex() -- we
4015 * instead opt to keep with the extant Perl
4016 * semantics, in all their broken glory. (Do
4017 * we have more desire to maintain Perl's
4018 * semantics than Perl does? Probably.)
4019 */
4020 if (subr == DIF_SUBR_RINDEX) {
4021 if (pos < 0) {
4022 if (sublen == 0)
4023 regs[rd] = 0;
4024 break;
4025 }
4026
4027 if ((size_t)pos > len)
4028 pos = len;
4029 } else {
4030 if (pos < 0)
4031 pos = 0;
4032
4033 if ((size_t)pos >= len) {
4034 if (sublen == 0)
4035 regs[rd] = len;
4036 break;
4037 }
4038 }
4039
4040 addr = orig + pos;
4041 }
4042 }
4043
4044 for (regs[rd] = notfound; addr != limit; addr += inc) {
4045 if (dtrace_strncmp(addr, substr, sublen) == 0) {
4046 if (subr != DIF_SUBR_STRSTR) {
4047 /*
4048 * As D index() and rindex() are
4049 * modeled on Perl (and not on awk),
4050 * we return a zero-based (and not a
4051 * one-based) index. (For you Perl
4052 * weenies: no, we're not going to add
4053 * $[ -- and shouldn't you be at a con
4054 * or something?)
4055 */
4056 regs[rd] = (uintptr_t)(addr - orig);
4057 break;
4058 }
4059
4060 ASSERT(subr == DIF_SUBR_STRSTR);
4061 regs[rd] = (uintptr_t)addr;
4062 break;
4063 }
4064 }
4065
4066 break;
4067 }
4068
4069 case DIF_SUBR_STRTOK: {
4070 uintptr_t addr = tupregs[0].dttk_value;
4071 uintptr_t tokaddr = tupregs[1].dttk_value;
4072 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4073 uintptr_t limit, toklimit;
4074 size_t clim;
4075 char *dest = (char *)mstate->dtms_scratch_ptr;
4076 uint8_t c='\0', tokmap[32]; /* 256 / 8 */
4077 uint64_t i = 0;
4078
4079 /*
4080 * Check both the token buffer and (later) the input buffer,
4081 * since both could be non-scratch addresses.
4082 */
4083 if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4084 regs[rd] = 0;
4085 break;
4086 }
4087 toklimit = tokaddr + clim;
4088
4089 if (!DTRACE_INSCRATCH(mstate, size)) {
4090 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4091 regs[rd] = 0;
4092 break;
4093 }
4094
4095 if (addr == 0) {
4096 /*
4097 * If the address specified is NULL, we use our saved
4098 * strtok pointer from the mstate. Note that this
4099 * means that the saved strtok pointer is _only_
4100 * valid within multiple enablings of the same probe --
4101 * it behaves like an implicit clause-local variable.
4102 */
4103 addr = mstate->dtms_strtok;
4104 limit = mstate->dtms_strtok_limit;
4105 } else {
4106 /*
4107 * If the user-specified address is non-NULL we must
4108 * access check it. This is the only time we have
4109 * a chance to do so, since this address may reside
4110 * in the string table of this clause-- future calls
4111 * (when we fetch addr from mstate->dtms_strtok)
4112 * would fail this access check.
4113 */
4114 if (!dtrace_strcanload(addr, size, &clim, mstate,
4115 vstate)) {
4116 regs[rd] = 0;
4117 break;
4118 }
4119 limit = addr + clim;
4120 }
4121
4122 /*
4123 * First, zero the token map, and then process the token
4124 * string -- setting a bit in the map for every character
4125 * found in the token string.
4126 */
4127 for (i = 0; i < (int)sizeof (tokmap); i++)
4128 tokmap[i] = 0;
4129
4130 for (; tokaddr < toklimit; tokaddr++) {
4131 if ((c = dtrace_load8(tokaddr)) == '\0')
4132 break;
4133
4134 ASSERT((c >> 3) < sizeof (tokmap));
4135 tokmap[c >> 3] |= (1 << (c & 0x7));
4136 }
4137
4138 for (; addr < limit; addr++) {
4139 /*
4140 * We're looking for a character that is _not_
4141 * contained in the token string.
4142 */
4143 if ((c = dtrace_load8(addr)) == '\0')
4144 break;
4145
4146 if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4147 break;
4148 }
4149
4150 if (c == '\0') {
4151 /*
4152 * We reached the end of the string without finding
4153 * any character that was not in the token string.
4154 * We return NULL in this case, and we set the saved
4155 * address to NULL as well.
4156 */
4157 regs[rd] = 0;
4158 mstate->dtms_strtok = 0;
4159 mstate->dtms_strtok_limit = NULL;
4160 break;
4161 }
4162
4163 /*
4164 * From here on, we're copying into the destination string.
4165 */
4166 for (i = 0; addr < limit && i < size - 1; addr++) {
4167 if ((c = dtrace_load8(addr)) == '\0')
4168 break;
4169
4170 if (tokmap[c >> 3] & (1 << (c & 0x7)))
4171 break;
4172
4173 ASSERT(i < size);
4174 dest[i++] = c;
4175 }
4176
4177 ASSERT(i < size);
4178 dest[i] = '\0';
4179 regs[rd] = (uintptr_t)dest;
4180 mstate->dtms_scratch_ptr += size;
4181 mstate->dtms_strtok = addr;
4182 mstate->dtms_strtok_limit = limit;
4183 break;
4184 }
4185
4186 case DIF_SUBR_SUBSTR: {
4187 uintptr_t s = tupregs[0].dttk_value;
4188 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4189 char *d = (char *)mstate->dtms_scratch_ptr;
4190 int64_t index = (int64_t)tupregs[1].dttk_value;
4191 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4192 size_t len = dtrace_strlen((char *)s, size);
4193 int64_t i = 0;
4194
4195 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4196 regs[rd] = 0;
4197 break;
4198 }
4199
4200 if (!DTRACE_INSCRATCH(mstate, size)) {
4201 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4202 regs[rd] = 0;
4203 break;
4204 }
4205
4206 if (nargs <= 2)
4207 remaining = (int64_t)size;
4208
4209 if (index < 0) {
4210 index += len;
4211
4212 if (index < 0 && index + remaining > 0) {
4213 remaining += index;
4214 index = 0;
4215 }
4216 }
4217
4218 if ((size_t)index >= len || index < 0) {
4219 remaining = 0;
4220 } else if (remaining < 0) {
4221 remaining += len - index;
4222 } else if ((uint64_t)index + (uint64_t)remaining > size) {
4223 remaining = size - index;
4224 }
4225
4226 for (i = 0; i < remaining; i++) {
4227 if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4228 break;
4229 }
4230
4231 d[i] = '\0';
4232
4233 mstate->dtms_scratch_ptr += size;
4234 regs[rd] = (uintptr_t)d;
4235 break;
4236 }
4237
4238 case DIF_SUBR_GETMAJOR:
4239 regs[rd] = (uintptr_t)major( (dev_t)tupregs[0].dttk_value );
4240 break;
4241
4242 case DIF_SUBR_GETMINOR:
4243 regs[rd] = (uintptr_t)minor( (dev_t)tupregs[0].dttk_value );
4244 break;
4245
4246 case DIF_SUBR_DDI_PATHNAME: {
4247 /* APPLE NOTE: currently unsupported on Darwin */
4248 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4249 regs[rd] = 0;
4250 break;
4251 }
4252
4253 case DIF_SUBR_STRJOIN: {
4254 char *d = (char *)mstate->dtms_scratch_ptr;
4255 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4256 uintptr_t s1 = tupregs[0].dttk_value;
4257 uintptr_t s2 = tupregs[1].dttk_value;
4258 uint64_t i = 0, j = 0;
4259 size_t lim1, lim2;
4260 char c;
4261
4262 if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
4263 !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
4264 regs[rd] = 0;
4265 break;
4266 }
4267
4268 if (!DTRACE_INSCRATCH(mstate, size)) {
4269 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4270 regs[rd] = 0;
4271 break;
4272 }
4273
4274 for (;;) {
4275 if (i >= size) {
4276 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4277 regs[rd] = 0;
4278 break;
4279 }
4280 c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
4281 if ((d[i++] = c) == '\0') {
4282 i--;
4283 break;
4284 }
4285 }
4286
4287 for (;;) {
4288 if (i >= size) {
4289 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4290 regs[rd] = 0;
4291 break;
4292 }
4293 c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
4294 if ((d[i++] = c) == '\0')
4295 break;
4296 }
4297
4298 if (i < size) {
4299 mstate->dtms_scratch_ptr += i;
4300 regs[rd] = (uintptr_t)d;
4301 }
4302
4303 break;
4304 }
4305
4306 case DIF_SUBR_LLTOSTR: {
4307 int64_t i = (int64_t)tupregs[0].dttk_value;
4308 int64_t val = i < 0 ? i * -1 : i;
4309 uint64_t size = 22; /* enough room for 2^64 in decimal */
4310 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4311
4312 if (!DTRACE_INSCRATCH(mstate, size)) {
4313 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4314 regs[rd] = 0;
4315 break;
4316 }
4317
4318 for (*end-- = '\0'; val; val /= 10)
4319 *end-- = '0' + (val % 10);
4320
4321 if (i == 0)
4322 *end-- = '0';
4323
4324 if (i < 0)
4325 *end-- = '-';
4326
4327 regs[rd] = (uintptr_t)end + 1;
4328 mstate->dtms_scratch_ptr += size;
4329 break;
4330 }
4331
4332 case DIF_SUBR_HTONS:
4333 case DIF_SUBR_NTOHS:
4334 #ifdef _BIG_ENDIAN
4335 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4336 #else
4337 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4338 #endif
4339 break;
4340
4341
4342 case DIF_SUBR_HTONL:
4343 case DIF_SUBR_NTOHL:
4344 #ifdef _BIG_ENDIAN
4345 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4346 #else
4347 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4348 #endif
4349 break;
4350
4351
4352 case DIF_SUBR_HTONLL:
4353 case DIF_SUBR_NTOHLL:
4354 #ifdef _BIG_ENDIAN
4355 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4356 #else
4357 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4358 #endif
4359 break;
4360
4361
4362 case DIF_SUBR_DIRNAME:
4363 case DIF_SUBR_BASENAME: {
4364 char *dest = (char *)mstate->dtms_scratch_ptr;
4365 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4366 uintptr_t src = tupregs[0].dttk_value;
4367 int i, j, len = dtrace_strlen((char *)src, size);
4368 int lastbase = -1, firstbase = -1, lastdir = -1;
4369 int start, end;
4370
4371 if (!dtrace_canload(src, len + 1, 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 * The basename and dirname for a zero-length string is
4384 * defined to be "."
4385 */
4386 if (len == 0) {
4387 len = 1;
4388 src = (uintptr_t)".";
4389 }
4390
4391 /*
4392 * Start from the back of the string, moving back toward the
4393 * front until we see a character that isn't a slash. That
4394 * character is the last character in the basename.
4395 */
4396 for (i = len - 1; i >= 0; i--) {
4397 if (dtrace_load8(src + i) != '/')
4398 break;
4399 }
4400
4401 if (i >= 0)
4402 lastbase = i;
4403
4404 /*
4405 * Starting from the last character in the basename, move
4406 * towards the front until we find a slash. The character
4407 * that we processed immediately before that is the first
4408 * character in the basename.
4409 */
4410 for (; i >= 0; i--) {
4411 if (dtrace_load8(src + i) == '/')
4412 break;
4413 }
4414
4415 if (i >= 0)
4416 firstbase = i + 1;
4417
4418 /*
4419 * Now keep going until we find a non-slash character. That
4420 * character is the last character in the dirname.
4421 */
4422 for (; i >= 0; i--) {
4423 if (dtrace_load8(src + i) != '/')
4424 break;
4425 }
4426
4427 if (i >= 0)
4428 lastdir = i;
4429
4430 ASSERT(!(lastbase == -1 && firstbase != -1));
4431 ASSERT(!(firstbase == -1 && lastdir != -1));
4432
4433 if (lastbase == -1) {
4434 /*
4435 * We didn't find a non-slash character. We know that
4436 * the length is non-zero, so the whole string must be
4437 * slashes. In either the dirname or the basename
4438 * case, we return '/'.
4439 */
4440 ASSERT(firstbase == -1);
4441 firstbase = lastbase = lastdir = 0;
4442 }
4443
4444 if (firstbase == -1) {
4445 /*
4446 * The entire string consists only of a basename
4447 * component. If we're looking for dirname, we need
4448 * to change our string to be just "."; if we're
4449 * looking for a basename, we'll just set the first
4450 * character of the basename to be 0.
4451 */
4452 if (subr == DIF_SUBR_DIRNAME) {
4453 ASSERT(lastdir == -1);
4454 src = (uintptr_t)".";
4455 lastdir = 0;
4456 } else {
4457 firstbase = 0;
4458 }
4459 }
4460
4461 if (subr == DIF_SUBR_DIRNAME) {
4462 if (lastdir == -1) {
4463 /*
4464 * We know that we have a slash in the name --
4465 * or lastdir would be set to 0, above. And
4466 * because lastdir is -1, we know that this
4467 * slash must be the first character. (That
4468 * is, the full string must be of the form
4469 * "/basename".) In this case, the last
4470 * character of the directory name is 0.
4471 */
4472 lastdir = 0;
4473 }
4474
4475 start = 0;
4476 end = lastdir;
4477 } else {
4478 ASSERT(subr == DIF_SUBR_BASENAME);
4479 ASSERT(firstbase != -1 && lastbase != -1);
4480 start = firstbase;
4481 end = lastbase;
4482 }
4483
4484 for (i = start, j = 0; i <= end && (uint64_t)j < size - 1; i++, j++)
4485 dest[j] = dtrace_load8(src + i);
4486
4487 dest[j] = '\0';
4488 regs[rd] = (uintptr_t)dest;
4489 mstate->dtms_scratch_ptr += size;
4490 break;
4491 }
4492
4493 case DIF_SUBR_CLEANPATH: {
4494 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4495 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4496 uintptr_t src = tupregs[0].dttk_value;
4497 size_t lim;
4498 size_t i = 0, j = 0;
4499
4500 if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
4501 regs[rd] = 0;
4502 break;
4503 }
4504
4505 if (!DTRACE_INSCRATCH(mstate, size)) {
4506 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4507 regs[rd] = 0;
4508 break;
4509 }
4510
4511 /*
4512 * Move forward, loading each character.
4513 */
4514 do {
4515 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
4516 next:
4517 if ((uint64_t)(j + 5) >= size) /* 5 = strlen("/..c\0") */
4518 break;
4519
4520 if (c != '/') {
4521 dest[j++] = c;
4522 continue;
4523 }
4524
4525 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
4526
4527 if (c == '/') {
4528 /*
4529 * We have two slashes -- we can just advance
4530 * to the next character.
4531 */
4532 goto next;
4533 }
4534
4535 if (c != '.') {
4536 /*
4537 * This is not "." and it's not ".." -- we can
4538 * just store the "/" and this character and
4539 * drive on.
4540 */
4541 dest[j++] = '/';
4542 dest[j++] = c;
4543 continue;
4544 }
4545
4546 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
4547
4548 if (c == '/') {
4549 /*
4550 * This is a "/./" component. We're not going
4551 * to store anything in the destination buffer;
4552 * we're just going to go to the next component.
4553 */
4554 goto next;
4555 }
4556
4557 if (c != '.') {
4558 /*
4559 * This is not ".." -- we can just store the
4560 * "/." and this character and continue
4561 * processing.
4562 */
4563 dest[j++] = '/';
4564 dest[j++] = '.';
4565 dest[j++] = c;
4566 continue;
4567 }
4568
4569 c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
4570
4571 if (c != '/' && c != '\0') {
4572 /*
4573 * This is not ".." -- it's "..[mumble]".
4574 * We'll store the "/.." and this character
4575 * and continue processing.
4576 */
4577 dest[j++] = '/';
4578 dest[j++] = '.';
4579 dest[j++] = '.';
4580 dest[j++] = c;
4581 continue;
4582 }
4583
4584 /*
4585 * This is "/../" or "/..\0". We need to back up
4586 * our destination pointer until we find a "/".
4587 */
4588 i--;
4589 while (j != 0 && dest[--j] != '/')
4590 continue;
4591
4592 if (c == '\0')
4593 dest[++j] = '/';
4594 } while (c != '\0');
4595
4596 dest[j] = '\0';
4597 regs[rd] = (uintptr_t)dest;
4598 mstate->dtms_scratch_ptr += size;
4599 break;
4600 }
4601
4602 case DIF_SUBR_INET_NTOA:
4603 case DIF_SUBR_INET_NTOA6:
4604 case DIF_SUBR_INET_NTOP: {
4605 size_t size;
4606 int af, argi, i;
4607 char *base, *end;
4608
4609 if (subr == DIF_SUBR_INET_NTOP) {
4610 af = (int)tupregs[0].dttk_value;
4611 argi = 1;
4612 } else {
4613 af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4614 argi = 0;
4615 }
4616
4617 if (af == AF_INET) {
4618 #if !defined(__APPLE__)
4619 ipaddr_t ip4;
4620 #else
4621 uint32_t ip4;
4622 #endif /* __APPLE__ */
4623 uint8_t *ptr8, val;
4624
4625 /*
4626 * Safely load the IPv4 address.
4627 */
4628 #if !defined(__APPLE__)
4629 ip4 = dtrace_load32(tupregs[argi].dttk_value);
4630 #else
4631 if (!dtrace_canload(tupregs[argi].dttk_value, sizeof(ip4),
4632 mstate, vstate)) {
4633 regs[rd] = 0;
4634 break;
4635 }
4636
4637 dtrace_bcopy(
4638 (void *)(uintptr_t)tupregs[argi].dttk_value,
4639 (void *)(uintptr_t)&ip4, sizeof (ip4));
4640 #endif /* __APPLE__ */
4641 /*
4642 * Check an IPv4 string will fit in scratch.
4643 */
4644 #if !defined(__APPLE__)
4645 size = INET_ADDRSTRLEN;
4646 #else
4647 size = MAX_IPv4_STR_LEN;
4648 #endif /* __APPLE__ */
4649 if (!DTRACE_INSCRATCH(mstate, size)) {
4650 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4651 regs[rd] = 0;
4652 break;
4653 }
4654 base = (char *)mstate->dtms_scratch_ptr;
4655 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4656
4657 /*
4658 * Stringify as a dotted decimal quad.
4659 */
4660 *end-- = '\0';
4661 ptr8 = (uint8_t *)&ip4;
4662 for (i = 3; i >= 0; i--) {
4663 val = ptr8[i];
4664
4665 if (val == 0) {
4666 *end-- = '0';
4667 } else {
4668 for (; val; val /= 10) {
4669 *end-- = '0' + (val % 10);
4670 }
4671 }
4672
4673 if (i > 0)
4674 *end-- = '.';
4675 }
4676 ASSERT(end + 1 >= base);
4677
4678 } else if (af == AF_INET6) {
4679 #if defined(__APPLE__)
4680 #define _S6_un __u6_addr
4681 #define _S6_u8 __u6_addr8
4682 #endif /* __APPLE__ */
4683 struct in6_addr ip6;
4684 int firstzero, tryzero, numzero, v6end;
4685 uint16_t val;
4686 const char digits[] = "0123456789abcdef";
4687
4688 /*
4689 * Stringify using RFC 1884 convention 2 - 16 bit
4690 * hexadecimal values with a zero-run compression.
4691 * Lower case hexadecimal digits are used.
4692 * eg, fe80::214:4fff:fe0b:76c8.
4693 * The IPv4 embedded form is returned for inet_ntop,
4694 * just the IPv4 string is returned for inet_ntoa6.
4695 */
4696
4697 if (!dtrace_canload(tupregs[argi].dttk_value,
4698 sizeof(struct in6_addr), mstate, vstate)) {
4699 regs[rd] = 0;
4700 break;
4701 }
4702
4703 /*
4704 * Safely load the IPv6 address.
4705 */
4706 dtrace_bcopy(
4707 (void *)(uintptr_t)tupregs[argi].dttk_value,
4708 (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4709
4710 /*
4711 * Check an IPv6 string will fit in scratch.
4712 */
4713 size = INET6_ADDRSTRLEN;
4714 if (!DTRACE_INSCRATCH(mstate, size)) {
4715 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4716 regs[rd] = 0;
4717 break;
4718 }
4719 base = (char *)mstate->dtms_scratch_ptr;
4720 end = (char *)mstate->dtms_scratch_ptr + size - 1;
4721 *end-- = '\0';
4722
4723 /*
4724 * Find the longest run of 16 bit zero values
4725 * for the single allowed zero compression - "::".
4726 */
4727 firstzero = -1;
4728 tryzero = -1;
4729 numzero = 1;
4730 for (i = 0; i < (int)sizeof (struct in6_addr); i++) {
4731 if (ip6._S6_un._S6_u8[i] == 0 &&
4732 tryzero == -1 && i % 2 == 0) {
4733 tryzero = i;
4734 continue;
4735 }
4736
4737 if (tryzero != -1 &&
4738 (ip6._S6_un._S6_u8[i] != 0 ||
4739 i == sizeof (struct in6_addr) - 1)) {
4740
4741 if (i - tryzero <= numzero) {
4742 tryzero = -1;
4743 continue;
4744 }
4745
4746 firstzero = tryzero;
4747 numzero = i - i % 2 - tryzero;
4748 tryzero = -1;
4749
4750 if (ip6._S6_un._S6_u8[i] == 0 &&
4751 i == sizeof (struct in6_addr) - 1)
4752 numzero += 2;
4753 }
4754 }
4755 ASSERT(firstzero + numzero <= (int)sizeof (struct in6_addr));
4756
4757 /*
4758 * Check for an IPv4 embedded address.
4759 */
4760 v6end = sizeof (struct in6_addr) - 2;
4761 if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4762 IN6_IS_ADDR_V4COMPAT(&ip6)) {
4763 for (i = sizeof (struct in6_addr) - 1;
4764 i >= (int)DTRACE_V4MAPPED_OFFSET; i--) {
4765 ASSERT(end >= base);
4766
4767 val = ip6._S6_un._S6_u8[i];
4768
4769 if (val == 0) {
4770 *end-- = '0';
4771 } else {
4772 for (; val; val /= 10) {
4773 *end-- = '0' + val % 10;
4774 }
4775 }
4776
4777 if (i > (int)DTRACE_V4MAPPED_OFFSET)
4778 *end-- = '.';
4779 }
4780
4781 if (subr == DIF_SUBR_INET_NTOA6)
4782 goto inetout;
4783
4784 /*
4785 * Set v6end to skip the IPv4 address that
4786 * we have already stringified.
4787 */
4788 v6end = 10;
4789 }
4790
4791 /*
4792 * Build the IPv6 string by working through the
4793 * address in reverse.
4794 */
4795 for (i = v6end; i >= 0; i -= 2) {
4796 ASSERT(end >= base);
4797
4798 if (i == firstzero + numzero - 2) {
4799 *end-- = ':';
4800 *end-- = ':';
4801 i -= numzero - 2;
4802 continue;
4803 }
4804
4805 if (i < 14 && i != firstzero - 2)
4806 *end-- = ':';
4807
4808 val = (ip6._S6_un._S6_u8[i] << 8) +
4809 ip6._S6_un._S6_u8[i + 1];
4810
4811 if (val == 0) {
4812 *end-- = '0';
4813 } else {
4814 for (; val; val /= 16) {
4815 *end-- = digits[val % 16];
4816 }
4817 }
4818 }
4819 ASSERT(end + 1 >= base);
4820
4821 #if defined(__APPLE__)
4822 #undef _S6_un
4823 #undef _S6_u8
4824 #endif /* __APPLE__ */
4825 } else {
4826 /*
4827 * The user didn't use AH_INET or AH_INET6.
4828 */
4829 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4830 regs[rd] = 0;
4831 break;
4832 }
4833
4834 inetout: regs[rd] = (uintptr_t)end + 1;
4835 mstate->dtms_scratch_ptr += size;
4836 break;
4837 }
4838
4839 case DIF_SUBR_TOUPPER:
4840 case DIF_SUBR_TOLOWER: {
4841 uintptr_t src = tupregs[0].dttk_value;
4842 char *dest = (char *)mstate->dtms_scratch_ptr;
4843 char lower, upper, base, c;
4844 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4845 size_t len = dtrace_strlen((char*) src, size);
4846 size_t i = 0;
4847
4848 lower = (subr == DIF_SUBR_TOUPPER) ? 'a' : 'A';
4849 upper = (subr == DIF_SUBR_TOUPPER) ? 'z' : 'Z';
4850 base = (subr == DIF_SUBR_TOUPPER) ? 'A' : 'a';
4851
4852 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4853 regs[rd] = 0;
4854 break;
4855 }
4856
4857 if (!DTRACE_INSCRATCH(mstate, size)) {
4858 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4859 regs[rd] = 0;
4860 break;
4861 }
4862
4863 for (i = 0; i < size - 1; ++i) {
4864 if ((c = dtrace_load8(src + i)) == '\0')
4865 break;
4866 if (c >= lower && c <= upper)
4867 c = base + (c - lower);
4868 dest[i] = c;
4869 }
4870
4871 ASSERT(i < size);
4872
4873 dest[i] = '\0';
4874 regs[rd] = (uintptr_t) dest;
4875 mstate->dtms_scratch_ptr += size;
4876
4877 break;
4878 }
4879
4880 #if defined(__APPLE__)
4881 case DIF_SUBR_VM_KERNEL_ADDRPERM: {
4882 if (!dtrace_priv_kernel(state)) {
4883 regs[rd] = 0;
4884 } else {
4885 regs[rd] = VM_KERNEL_ADDRPERM((vm_offset_t) tupregs[0].dttk_value);
4886 }
4887
4888 break;
4889 }
4890
4891 case DIF_SUBR_KDEBUG_TRACE: {
4892 uint32_t debugid;
4893 uintptr_t args[4] = {0};
4894 int i;
4895
4896 if (nargs < 2 || nargs > 5) {
4897 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4898 break;
4899 }
4900
4901 if (dtrace_destructive_disallow)
4902 return;
4903
4904 debugid = tupregs[0].dttk_value;
4905 for (i = 0; i < nargs - 1; i++)
4906 args[i] = tupregs[i + 1].dttk_value;
4907
4908 kernel_debug(debugid, args[0], args[1], args[2], args[3], 0);
4909
4910 break;
4911 }
4912
4913 case DIF_SUBR_KDEBUG_TRACE_STRING: {
4914 if (nargs != 3) {
4915 break;
4916 }
4917
4918 if (dtrace_destructive_disallow)
4919 return;
4920
4921 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4922 uint32_t debugid = tupregs[0].dttk_value;
4923 uint64_t str_id = tupregs[1].dttk_value;
4924 uintptr_t src = tupregs[2].dttk_value;
4925 size_t lim;
4926 char buf[size];
4927 char* str = NULL;
4928
4929 if (src != (uintptr_t)0) {
4930 str = buf;
4931 if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
4932 break;
4933 }
4934 dtrace_strcpy((void*)src, buf, size);
4935 }
4936
4937 (void)kernel_debug_string(debugid, &str_id, str);
4938 regs[rd] = str_id;
4939
4940 break;
4941 }
4942 #endif
4943
4944 }
4945 }
4946
4947 /*
4948 * Emulate the execution of DTrace IR instructions specified by the given
4949 * DIF object. This function is deliberately void of assertions as all of
4950 * the necessary checks are handled by a call to dtrace_difo_validate().
4951 */
4952 static uint64_t
4953 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4954 dtrace_vstate_t *vstate, dtrace_state_t *state)
4955 {
4956 const dif_instr_t *text = difo->dtdo_buf;
4957 const uint_t textlen = difo->dtdo_len;
4958 const char *strtab = difo->dtdo_strtab;
4959 const uint64_t *inttab = difo->dtdo_inttab;
4960
4961 uint64_t rval = 0;
4962 dtrace_statvar_t *svar;
4963 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4964 dtrace_difv_t *v;
4965 volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4966 volatile uint64_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4967
4968 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4969 uint64_t regs[DIF_DIR_NREGS];
4970 uint64_t *tmp;
4971
4972 uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4973 int64_t cc_r;
4974 uint_t pc = 0, id, opc = 0;
4975 uint8_t ttop = 0;
4976 dif_instr_t instr;
4977 uint_t r1, r2, rd;
4978
4979 /*
4980 * We stash the current DIF object into the machine state: we need it
4981 * for subsequent access checking.
4982 */
4983 mstate->dtms_difo = difo;
4984
4985 regs[DIF_REG_R0] = 0; /* %r0 is fixed at zero */
4986
4987 while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4988 opc = pc;
4989
4990 instr = text[pc++];
4991 r1 = DIF_INSTR_R1(instr);
4992 r2 = DIF_INSTR_R2(instr);
4993 rd = DIF_INSTR_RD(instr);
4994
4995 switch (DIF_INSTR_OP(instr)) {
4996 case DIF_OP_OR:
4997 regs[rd] = regs[r1] | regs[r2];
4998 break;
4999 case DIF_OP_XOR:
5000 regs[rd] = regs[r1] ^ regs[r2];
5001 break;
5002 case DIF_OP_AND:
5003 regs[rd] = regs[r1] & regs[r2];
5004 break;
5005 case DIF_OP_SLL:
5006 regs[rd] = regs[r1] << regs[r2];
5007 break;
5008 case DIF_OP_SRL:
5009 regs[rd] = regs[r1] >> regs[r2];
5010 break;
5011 case DIF_OP_SUB:
5012 regs[rd] = regs[r1] - regs[r2];
5013 break;
5014 case DIF_OP_ADD:
5015 regs[rd] = regs[r1] + regs[r2];
5016 break;
5017 case DIF_OP_MUL:
5018 regs[rd] = regs[r1] * regs[r2];
5019 break;
5020 case DIF_OP_SDIV:
5021 if (regs[r2] == 0) {
5022 regs[rd] = 0;
5023 *flags |= CPU_DTRACE_DIVZERO;
5024 } else {
5025 regs[rd] = (int64_t)regs[r1] /
5026 (int64_t)regs[r2];
5027 }
5028 break;
5029
5030 case DIF_OP_UDIV:
5031 if (regs[r2] == 0) {
5032 regs[rd] = 0;
5033 *flags |= CPU_DTRACE_DIVZERO;
5034 } else {
5035 regs[rd] = regs[r1] / regs[r2];
5036 }
5037 break;
5038
5039 case DIF_OP_SREM:
5040 if (regs[r2] == 0) {
5041 regs[rd] = 0;
5042 *flags |= CPU_DTRACE_DIVZERO;
5043 } else {
5044 regs[rd] = (int64_t)regs[r1] %
5045 (int64_t)regs[r2];
5046 }
5047 break;
5048
5049 case DIF_OP_UREM:
5050 if (regs[r2] == 0) {
5051 regs[rd] = 0;
5052 *flags |= CPU_DTRACE_DIVZERO;
5053 } else {
5054 regs[rd] = regs[r1] % regs[r2];
5055 }
5056 break;
5057
5058 case DIF_OP_NOT:
5059 regs[rd] = ~regs[r1];
5060 break;
5061 case DIF_OP_MOV:
5062 regs[rd] = regs[r1];
5063 break;
5064 case DIF_OP_CMP:
5065 cc_r = regs[r1] - regs[r2];
5066 cc_n = cc_r < 0;
5067 cc_z = cc_r == 0;
5068 cc_v = 0;
5069 cc_c = regs[r1] < regs[r2];
5070 break;
5071 case DIF_OP_TST:
5072 cc_n = cc_v = cc_c = 0;
5073 cc_z = regs[r1] == 0;
5074 break;
5075 case DIF_OP_BA:
5076 pc = DIF_INSTR_LABEL(instr);
5077 break;
5078 case DIF_OP_BE:
5079 if (cc_z)
5080 pc = DIF_INSTR_LABEL(instr);
5081 break;
5082 case DIF_OP_BNE:
5083 if (cc_z == 0)
5084 pc = DIF_INSTR_LABEL(instr);
5085 break;
5086 case DIF_OP_BG:
5087 if ((cc_z | (cc_n ^ cc_v)) == 0)
5088 pc = DIF_INSTR_LABEL(instr);
5089 break;
5090 case DIF_OP_BGU:
5091 if ((cc_c | cc_z) == 0)
5092 pc = DIF_INSTR_LABEL(instr);
5093 break;
5094 case DIF_OP_BGE:
5095 if ((cc_n ^ cc_v) == 0)
5096 pc = DIF_INSTR_LABEL(instr);
5097 break;
5098 case DIF_OP_BGEU:
5099 if (cc_c == 0)
5100 pc = DIF_INSTR_LABEL(instr);
5101 break;
5102 case DIF_OP_BL:
5103 if (cc_n ^ cc_v)
5104 pc = DIF_INSTR_LABEL(instr);
5105 break;
5106 case DIF_OP_BLU:
5107 if (cc_c)
5108 pc = DIF_INSTR_LABEL(instr);
5109 break;
5110 case DIF_OP_BLE:
5111 if (cc_z | (cc_n ^ cc_v))
5112 pc = DIF_INSTR_LABEL(instr);
5113 break;
5114 case DIF_OP_BLEU:
5115 if (cc_c | cc_z)
5116 pc = DIF_INSTR_LABEL(instr);
5117 break;
5118 case DIF_OP_RLDSB:
5119 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5120 *flags |= CPU_DTRACE_KPRIV;
5121 *illval = regs[r1];
5122 break;
5123 }
5124 /*FALLTHROUGH*/
5125 case DIF_OP_LDSB:
5126 regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5127 break;
5128 case DIF_OP_RLDSH:
5129 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5130 *flags |= CPU_DTRACE_KPRIV;
5131 *illval = regs[r1];
5132 break;
5133 }
5134 /*FALLTHROUGH*/
5135 case DIF_OP_LDSH:
5136 regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5137 break;
5138 case DIF_OP_RLDSW:
5139 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5140 *flags |= CPU_DTRACE_KPRIV;
5141 *illval = regs[r1];
5142 break;
5143 }
5144 /*FALLTHROUGH*/
5145 case DIF_OP_LDSW:
5146 regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5147 break;
5148 case DIF_OP_RLDUB:
5149 if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5150 *flags |= CPU_DTRACE_KPRIV;
5151 *illval = regs[r1];
5152 break;
5153 }
5154 /*FALLTHROUGH*/
5155 case DIF_OP_LDUB:
5156 regs[rd] = dtrace_load8(regs[r1]);
5157 break;
5158 case DIF_OP_RLDUH:
5159 if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5160 *flags |= CPU_DTRACE_KPRIV;
5161 *illval = regs[r1];
5162 break;
5163 }
5164 /*FALLTHROUGH*/
5165 case DIF_OP_LDUH:
5166 regs[rd] = dtrace_load16(regs[r1]);
5167 break;
5168 case DIF_OP_RLDUW:
5169 if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5170 *flags |= CPU_DTRACE_KPRIV;
5171 *illval = regs[r1];
5172 break;
5173 }
5174 /*FALLTHROUGH*/
5175 case DIF_OP_LDUW:
5176 regs[rd] = dtrace_load32(regs[r1]);
5177 break;
5178 case DIF_OP_RLDX:
5179 if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5180 *flags |= CPU_DTRACE_KPRIV;
5181 *illval = regs[r1];
5182 break;
5183 }
5184 /*FALLTHROUGH*/
5185 case DIF_OP_LDX:
5186 regs[rd] = dtrace_load64(regs[r1]);
5187 break;
5188 /*
5189 * Darwin 32-bit kernel may fetch from 64-bit user.
5190 * Do not cast regs to uintptr_t
5191 * DIF_OP_ULDSB,DIF_OP_ULDSH, DIF_OP_ULDSW, DIF_OP_ULDUB
5192 * DIF_OP_ULDUH, DIF_OP_ULDUW, DIF_OP_ULDX
5193 */
5194 case DIF_OP_ULDSB:
5195 regs[rd] = (int8_t)
5196 dtrace_fuword8(regs[r1]);
5197 break;
5198 case DIF_OP_ULDSH:
5199 regs[rd] = (int16_t)
5200 dtrace_fuword16(regs[r1]);
5201 break;
5202 case DIF_OP_ULDSW:
5203 regs[rd] = (int32_t)
5204 dtrace_fuword32(regs[r1]);
5205 break;
5206 case DIF_OP_ULDUB:
5207 regs[rd] =
5208 dtrace_fuword8(regs[r1]);
5209 break;
5210 case DIF_OP_ULDUH:
5211 regs[rd] =
5212 dtrace_fuword16(regs[r1]);
5213 break;
5214 case DIF_OP_ULDUW:
5215 regs[rd] =
5216 dtrace_fuword32(regs[r1]);
5217 break;
5218 case DIF_OP_ULDX:
5219 regs[rd] =
5220 dtrace_fuword64(regs[r1]);
5221 break;
5222 case DIF_OP_RET:
5223 rval = regs[rd];
5224 pc = textlen;
5225 break;
5226 case DIF_OP_NOP:
5227 break;
5228 case DIF_OP_SETX:
5229 regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5230 break;
5231 case DIF_OP_SETS:
5232 regs[rd] = (uint64_t)(uintptr_t)
5233 (strtab + DIF_INSTR_STRING(instr));
5234 break;
5235 case DIF_OP_SCMP: {
5236 size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5237 uintptr_t s1 = regs[r1];
5238 uintptr_t s2 = regs[r2];
5239 size_t lim1 = sz, lim2 = sz;
5240
5241 if (s1 != 0 &&
5242 !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
5243 break;
5244 if (s2 != 0 &&
5245 !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
5246 break;
5247
5248 cc_r = dtrace_strncmp((char *)s1, (char *)s2,
5249 MIN(lim1, lim2));
5250
5251 cc_n = cc_r < 0;
5252 cc_z = cc_r == 0;
5253 cc_v = cc_c = 0;
5254 break;
5255 }
5256 case DIF_OP_LDGA:
5257 regs[rd] = dtrace_dif_variable(mstate, state,
5258 r1, regs[r2]);
5259 break;
5260 case DIF_OP_LDGS:
5261 id = DIF_INSTR_VAR(instr);
5262
5263 if (id >= DIF_VAR_OTHER_UBASE) {
5264 uintptr_t a;
5265
5266 id -= DIF_VAR_OTHER_UBASE;
5267 svar = vstate->dtvs_globals[id];
5268 ASSERT(svar != NULL);
5269 v = &svar->dtsv_var;
5270
5271 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5272 regs[rd] = svar->dtsv_data;
5273 break;
5274 }
5275
5276 a = (uintptr_t)svar->dtsv_data;
5277
5278 if (*(uint8_t *)a == UINT8_MAX) {
5279 /*
5280 * If the 0th byte is set to UINT8_MAX
5281 * then this is to be treated as a
5282 * reference to a NULL variable.
5283 */
5284 regs[rd] = 0;
5285 } else {
5286 regs[rd] = a + sizeof (uint64_t);
5287 }
5288
5289 break;
5290 }
5291
5292 regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5293 break;
5294
5295 case DIF_OP_STGS:
5296 id = DIF_INSTR_VAR(instr);
5297
5298 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5299 id -= DIF_VAR_OTHER_UBASE;
5300
5301 VERIFY(id < (uint_t)vstate->dtvs_nglobals);
5302 svar = vstate->dtvs_globals[id];
5303 ASSERT(svar != NULL);
5304 v = &svar->dtsv_var;
5305
5306 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5307 uintptr_t a = (uintptr_t)svar->dtsv_data;
5308 size_t lim;
5309
5310 ASSERT(a != 0);
5311 ASSERT(svar->dtsv_size != 0);
5312
5313 if (regs[rd] == 0) {
5314 *(uint8_t *)a = UINT8_MAX;
5315 break;
5316 } else {
5317 *(uint8_t *)a = 0;
5318 a += sizeof (uint64_t);
5319 }
5320 if (!dtrace_vcanload(
5321 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5322 &lim, mstate, vstate))
5323 break;
5324
5325 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5326 (void *)a, &v->dtdv_type, lim);
5327 break;
5328 }
5329
5330 svar->dtsv_data = regs[rd];
5331 break;
5332
5333 case DIF_OP_LDTA:
5334 /*
5335 * There are no DTrace built-in thread-local arrays at
5336 * present. This opcode is saved for future work.
5337 */
5338 *flags |= CPU_DTRACE_ILLOP;
5339 regs[rd] = 0;
5340 break;
5341
5342 case DIF_OP_LDLS:
5343 id = DIF_INSTR_VAR(instr);
5344
5345 if (id < DIF_VAR_OTHER_UBASE) {
5346 /*
5347 * For now, this has no meaning.
5348 */
5349 regs[rd] = 0;
5350 break;
5351 }
5352
5353 id -= DIF_VAR_OTHER_UBASE;
5354
5355 ASSERT(id < (uint_t)vstate->dtvs_nlocals);
5356 ASSERT(vstate->dtvs_locals != NULL);
5357 svar = vstate->dtvs_locals[id];
5358 ASSERT(svar != NULL);
5359 v = &svar->dtsv_var;
5360
5361 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5362 uintptr_t a = (uintptr_t)svar->dtsv_data;
5363 size_t sz = v->dtdv_type.dtdt_size;
5364
5365 sz += sizeof (uint64_t);
5366 ASSERT(svar->dtsv_size == (int)NCPU * sz);
5367 a += CPU->cpu_id * sz;
5368
5369 if (*(uint8_t *)a == UINT8_MAX) {
5370 /*
5371 * If the 0th byte is set to UINT8_MAX
5372 * then this is to be treated as a
5373 * reference to a NULL variable.
5374 */
5375 regs[rd] = 0;
5376 } else {
5377 regs[rd] = a + sizeof (uint64_t);
5378 }
5379
5380 break;
5381 }
5382
5383 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5384 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5385 regs[rd] = tmp[CPU->cpu_id];
5386 break;
5387
5388 case DIF_OP_STLS:
5389 id = DIF_INSTR_VAR(instr);
5390
5391 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5392 id -= DIF_VAR_OTHER_UBASE;
5393 VERIFY(id < (uint_t)vstate->dtvs_nlocals);
5394 ASSERT(vstate->dtvs_locals != NULL);
5395 svar = vstate->dtvs_locals[id];
5396 ASSERT(svar != NULL);
5397 v = &svar->dtsv_var;
5398
5399 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5400 uintptr_t a = (uintptr_t)svar->dtsv_data;
5401 size_t sz = v->dtdv_type.dtdt_size;
5402 size_t lim;
5403
5404 sz += sizeof (uint64_t);
5405 ASSERT(svar->dtsv_size == (int)NCPU * sz);
5406 a += CPU->cpu_id * sz;
5407
5408 if (regs[rd] == 0) {
5409 *(uint8_t *)a = UINT8_MAX;
5410 break;
5411 } else {
5412 *(uint8_t *)a = 0;
5413 a += sizeof (uint64_t);
5414 }
5415
5416 if (!dtrace_vcanload(
5417 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5418 &lim, mstate, vstate))
5419 break;
5420
5421 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5422 (void *)a, &v->dtdv_type, lim);
5423 break;
5424 }
5425
5426 ASSERT(svar->dtsv_size == (int)NCPU * sizeof (uint64_t));
5427 tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5428 tmp[CPU->cpu_id] = regs[rd];
5429 break;
5430
5431 case DIF_OP_LDTS: {
5432 dtrace_dynvar_t *dvar;
5433 dtrace_key_t *key;
5434
5435 id = DIF_INSTR_VAR(instr);
5436 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5437 id -= DIF_VAR_OTHER_UBASE;
5438 v = &vstate->dtvs_tlocals[id];
5439
5440 key = &tupregs[DIF_DTR_NREGS];
5441 key[0].dttk_value = (uint64_t)id;
5442 key[0].dttk_size = 0;
5443 DTRACE_TLS_THRKEY(key[1].dttk_value);
5444 key[1].dttk_size = 0;
5445
5446 dvar = dtrace_dynvar(dstate, 2, key,
5447 sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5448 mstate, vstate);
5449
5450 if (dvar == NULL) {
5451 regs[rd] = 0;
5452 break;
5453 }
5454
5455 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5456 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5457 } else {
5458 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5459 }
5460
5461 break;
5462 }
5463
5464 case DIF_OP_STTS: {
5465 dtrace_dynvar_t *dvar;
5466 dtrace_key_t *key;
5467
5468 id = DIF_INSTR_VAR(instr);
5469 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5470 id -= DIF_VAR_OTHER_UBASE;
5471 VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
5472
5473 key = &tupregs[DIF_DTR_NREGS];
5474 key[0].dttk_value = (uint64_t)id;
5475 key[0].dttk_size = 0;
5476 DTRACE_TLS_THRKEY(key[1].dttk_value);
5477 key[1].dttk_size = 0;
5478 v = &vstate->dtvs_tlocals[id];
5479
5480 dvar = dtrace_dynvar(dstate, 2, key,
5481 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5482 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5483 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5484 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5485
5486 /*
5487 * Given that we're storing to thread-local data,
5488 * we need to flush our predicate cache.
5489 */
5490 dtrace_set_thread_predcache(current_thread(), 0);
5491
5492 if (dvar == NULL)
5493 break;
5494
5495 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5496 size_t lim;
5497
5498 if (!dtrace_vcanload(
5499 (void *)(uintptr_t)regs[rd],
5500 &v->dtdv_type, &lim, mstate, vstate))
5501 break;
5502
5503 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5504 dvar->dtdv_data, &v->dtdv_type, lim);
5505 } else {
5506 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5507 }
5508
5509 break;
5510 }
5511
5512 case DIF_OP_SRA:
5513 regs[rd] = (int64_t)regs[r1] >> regs[r2];
5514 break;
5515
5516 case DIF_OP_CALL:
5517 dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5518 regs, tupregs, ttop, mstate, state);
5519 break;
5520
5521 case DIF_OP_PUSHTR:
5522 if (ttop == DIF_DTR_NREGS) {
5523 *flags |= CPU_DTRACE_TUPOFLOW;
5524 break;
5525 }
5526
5527 if (r1 == DIF_TYPE_STRING) {
5528 /*
5529 * If this is a string type and the size is 0,
5530 * we'll use the system-wide default string
5531 * size. Note that we are _not_ looking at
5532 * the value of the DTRACEOPT_STRSIZE option;
5533 * had this been set, we would expect to have
5534 * a non-zero size value in the "pushtr".
5535 */
5536 tupregs[ttop].dttk_size =
5537 dtrace_strlen((char *)(uintptr_t)regs[rd],
5538 regs[r2] ? regs[r2] :
5539 dtrace_strsize_default) + 1;
5540 } else {
5541 if (regs[r2] > LONG_MAX) {
5542 *flags |= CPU_DTRACE_ILLOP;
5543 break;
5544 }
5545 tupregs[ttop].dttk_size = regs[r2];
5546 }
5547
5548 tupregs[ttop++].dttk_value = regs[rd];
5549 break;
5550
5551 case DIF_OP_PUSHTV:
5552 if (ttop == DIF_DTR_NREGS) {
5553 *flags |= CPU_DTRACE_TUPOFLOW;
5554 break;
5555 }
5556
5557 tupregs[ttop].dttk_value = regs[rd];
5558 tupregs[ttop++].dttk_size = 0;
5559 break;
5560
5561 case DIF_OP_POPTS:
5562 if (ttop != 0)
5563 ttop--;
5564 break;
5565
5566 case DIF_OP_FLUSHTS:
5567 ttop = 0;
5568 break;
5569
5570 case DIF_OP_LDGAA:
5571 case DIF_OP_LDTAA: {
5572 dtrace_dynvar_t *dvar;
5573 dtrace_key_t *key = tupregs;
5574 uint_t nkeys = ttop;
5575
5576 id = DIF_INSTR_VAR(instr);
5577 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5578 id -= DIF_VAR_OTHER_UBASE;
5579
5580 key[nkeys].dttk_value = (uint64_t)id;
5581 key[nkeys++].dttk_size = 0;
5582
5583 if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5584 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5585 key[nkeys++].dttk_size = 0;
5586 VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
5587 v = &vstate->dtvs_tlocals[id];
5588 } else {
5589 VERIFY(id < (uint_t)vstate->dtvs_nglobals);
5590 v = &vstate->dtvs_globals[id]->dtsv_var;
5591 }
5592
5593 dvar = dtrace_dynvar(dstate, nkeys, key,
5594 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5595 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5596 DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5597
5598 if (dvar == NULL) {
5599 regs[rd] = 0;
5600 break;
5601 }
5602
5603 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5604 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5605 } else {
5606 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5607 }
5608
5609 break;
5610 }
5611
5612 case DIF_OP_STGAA:
5613 case DIF_OP_STTAA: {
5614 dtrace_dynvar_t *dvar;
5615 dtrace_key_t *key = tupregs;
5616 uint_t nkeys = ttop;
5617
5618 id = DIF_INSTR_VAR(instr);
5619 ASSERT(id >= DIF_VAR_OTHER_UBASE);
5620 id -= DIF_VAR_OTHER_UBASE;
5621
5622 key[nkeys].dttk_value = (uint64_t)id;
5623 key[nkeys++].dttk_size = 0;
5624
5625 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5626 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5627 key[nkeys++].dttk_size = 0;
5628 VERIFY(id < (uint_t)vstate->dtvs_ntlocals);
5629 v = &vstate->dtvs_tlocals[id];
5630 } else {
5631 VERIFY(id < (uint_t)vstate->dtvs_nglobals);
5632 v = &vstate->dtvs_globals[id]->dtsv_var;
5633 }
5634
5635 dvar = dtrace_dynvar(dstate, nkeys, key,
5636 v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5637 v->dtdv_type.dtdt_size : sizeof (uint64_t),
5638 regs[rd] ? DTRACE_DYNVAR_ALLOC :
5639 DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5640
5641 if (dvar == NULL)
5642 break;
5643
5644 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5645 size_t lim;
5646
5647 if (!dtrace_vcanload(
5648 (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5649 &lim, mstate, vstate))
5650 break;
5651
5652 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5653 dvar->dtdv_data, &v->dtdv_type, lim);
5654 } else {
5655 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5656 }
5657
5658 break;
5659 }
5660
5661 case DIF_OP_ALLOCS: {
5662 uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5663 size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5664
5665 /*
5666 * Rounding up the user allocation size could have
5667 * overflowed large, bogus allocations (like -1ULL) to
5668 * 0.
5669 */
5670 if (size < regs[r1] ||
5671 !DTRACE_INSCRATCH(mstate, size)) {
5672 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5673 regs[rd] = 0;
5674 break;
5675 }
5676
5677 dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5678 mstate->dtms_scratch_ptr += size;
5679 regs[rd] = ptr;
5680 break;
5681 }
5682
5683 case DIF_OP_COPYS:
5684 if (!dtrace_canstore(regs[rd], regs[r2],
5685 mstate, vstate)) {
5686 *flags |= CPU_DTRACE_BADADDR;
5687 *illval = regs[rd];
5688 break;
5689 }
5690
5691 if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5692 break;
5693
5694 dtrace_bcopy((void *)(uintptr_t)regs[r1],
5695 (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5696 break;
5697
5698 case DIF_OP_STB:
5699 if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5700 *flags |= CPU_DTRACE_BADADDR;
5701 *illval = regs[rd];
5702 break;
5703 }
5704 *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5705 break;
5706
5707 case DIF_OP_STH:
5708 if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5709 *flags |= CPU_DTRACE_BADADDR;
5710 *illval = regs[rd];
5711 break;
5712 }
5713 if (regs[rd] & 1) {
5714 *flags |= CPU_DTRACE_BADALIGN;
5715 *illval = regs[rd];
5716 break;
5717 }
5718 *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5719 break;
5720
5721 case DIF_OP_STW:
5722 if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5723 *flags |= CPU_DTRACE_BADADDR;
5724 *illval = regs[rd];
5725 break;
5726 }
5727 if (regs[rd] & 3) {
5728 *flags |= CPU_DTRACE_BADALIGN;
5729 *illval = regs[rd];
5730 break;
5731 }
5732 *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5733 break;
5734
5735 case DIF_OP_STX:
5736 if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5737 *flags |= CPU_DTRACE_BADADDR;
5738 *illval = regs[rd];
5739 break;
5740 }
5741
5742 /*
5743 * Darwin kmem_zalloc() called from
5744 * dtrace_difo_init() is 4-byte aligned.
5745 */
5746 if (regs[rd] & 3) {
5747 *flags |= CPU_DTRACE_BADALIGN;
5748 *illval = regs[rd];
5749 break;
5750 }
5751 *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5752 break;
5753 }
5754 }
5755
5756 if (!(*flags & CPU_DTRACE_FAULT))
5757 return (rval);
5758
5759 mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5760 mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5761
5762 return (0);
5763 }
5764
5765 static void
5766 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5767 {
5768 dtrace_probe_t *probe = ecb->dte_probe;
5769 dtrace_provider_t *prov = probe->dtpr_provider;
5770 char c[DTRACE_FULLNAMELEN + 80], *str;
5771 const char *msg = "dtrace: breakpoint action at probe ";
5772 const char *ecbmsg = " (ecb ";
5773 uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5774 uintptr_t val = (uintptr_t)ecb;
5775 int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5776
5777 if (dtrace_destructive_disallow)
5778 return;
5779
5780 /*
5781 * It's impossible to be taking action on the NULL probe.
5782 */
5783 ASSERT(probe != NULL);
5784
5785 /*
5786 * This is a poor man's (destitute man's?) sprintf(): we want to
5787 * print the provider name, module name, function name and name of
5788 * the probe, along with the hex address of the ECB with the breakpoint
5789 * action -- all of which we must place in the character buffer by
5790 * hand.
5791 */
5792 while (*msg != '\0')
5793 c[i++] = *msg++;
5794
5795 for (str = prov->dtpv_name; *str != '\0'; str++)
5796 c[i++] = *str;
5797 c[i++] = ':';
5798
5799 for (str = probe->dtpr_mod; *str != '\0'; str++)
5800 c[i++] = *str;
5801 c[i++] = ':';
5802
5803 for (str = probe->dtpr_func; *str != '\0'; str++)
5804 c[i++] = *str;
5805 c[i++] = ':';
5806
5807 for (str = probe->dtpr_name; *str != '\0'; str++)
5808 c[i++] = *str;
5809
5810 while (*ecbmsg != '\0')
5811 c[i++] = *ecbmsg++;
5812
5813 while (shift >= 0) {
5814 mask = (uintptr_t)0xf << shift;
5815
5816 if (val >= ((uintptr_t)1 << shift))
5817 c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5818 shift -= 4;
5819 }
5820
5821 c[i++] = ')';
5822 c[i] = '\0';
5823
5824 debug_enter(c);
5825 }
5826
5827 static void
5828 dtrace_action_panic(dtrace_ecb_t *ecb)
5829 {
5830 dtrace_probe_t *probe = ecb->dte_probe;
5831
5832 /*
5833 * It's impossible to be taking action on the NULL probe.
5834 */
5835 ASSERT(probe != NULL);
5836
5837 if (dtrace_destructive_disallow)
5838 return;
5839
5840 if (dtrace_panicked != NULL)
5841 return;
5842
5843 if (dtrace_casptr(&dtrace_panicked, NULL, current_thread()) != NULL)
5844 return;
5845
5846 /*
5847 * We won the right to panic. (We want to be sure that only one
5848 * thread calls panic() from dtrace_probe(), and that panic() is
5849 * called exactly once.)
5850 */
5851 panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5852 probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5853 probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5854
5855 /*
5856 * APPLE NOTE: this was for an old Mac OS X debug feature
5857 * allowing a return from panic(). Revisit someday.
5858 */
5859 dtrace_panicked = NULL;
5860 }
5861
5862 static void
5863 dtrace_action_raise(uint64_t sig)
5864 {
5865 if (dtrace_destructive_disallow)
5866 return;
5867
5868 if (sig >= NSIG) {
5869 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5870 return;
5871 }
5872
5873 /*
5874 * raise() has a queue depth of 1 -- we ignore all subsequent
5875 * invocations of the raise() action.
5876 */
5877
5878 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5879
5880 if (uthread && uthread->t_dtrace_sig == 0) {
5881 uthread->t_dtrace_sig = sig;
5882 act_set_astbsd(current_thread());
5883 }
5884 }
5885
5886 static void
5887 dtrace_action_stop(void)
5888 {
5889 if (dtrace_destructive_disallow)
5890 return;
5891
5892 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5893 if (uthread) {
5894 /*
5895 * The currently running process will be set to task_suspend
5896 * when it next leaves the kernel.
5897 */
5898 uthread->t_dtrace_stop = 1;
5899 act_set_astbsd(current_thread());
5900 }
5901 }
5902
5903
5904 /*
5905 * APPLE NOTE: pidresume works in conjunction with the dtrace stop action.
5906 * Both activate only when the currently running process next leaves the
5907 * kernel.
5908 */
5909 static void
5910 dtrace_action_pidresume(uint64_t pid)
5911 {
5912 if (dtrace_destructive_disallow)
5913 return;
5914
5915 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
5916 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5917 return;
5918 }
5919 uthread_t uthread = (uthread_t)get_bsdthread_info(current_thread());
5920
5921 /*
5922 * When the currently running process leaves the kernel, it attempts to
5923 * task_resume the process (denoted by pid), if that pid appears to have
5924 * been stopped by dtrace_action_stop().
5925 * The currently running process has a pidresume() queue depth of 1 --
5926 * subsequent invocations of the pidresume() action are ignored.
5927 */
5928
5929 if (pid != 0 && uthread && uthread->t_dtrace_resumepid == 0) {
5930 uthread->t_dtrace_resumepid = pid;
5931 act_set_astbsd(current_thread());
5932 }
5933 }
5934
5935 static void
5936 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5937 {
5938 hrtime_t now;
5939 volatile uint16_t *flags;
5940 dtrace_cpu_t *cpu = CPU;
5941
5942 if (dtrace_destructive_disallow)
5943 return;
5944
5945 flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5946
5947 now = dtrace_gethrtime();
5948
5949 if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5950 /*
5951 * We need to advance the mark to the current time.
5952 */
5953 cpu->cpu_dtrace_chillmark = now;
5954 cpu->cpu_dtrace_chilled = 0;
5955 }
5956
5957 /*
5958 * Now check to see if the requested chill time would take us over
5959 * the maximum amount of time allowed in the chill interval. (Or
5960 * worse, if the calculation itself induces overflow.)
5961 */
5962 if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5963 cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5964 *flags |= CPU_DTRACE_ILLOP;
5965 return;
5966 }
5967
5968 while (dtrace_gethrtime() - now < val)
5969 continue;
5970
5971 /*
5972 * Normally, we assure that the value of the variable "timestamp" does
5973 * not change within an ECB. The presence of chill() represents an
5974 * exception to this rule, however.
5975 */
5976 mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5977 cpu->cpu_dtrace_chilled += val;
5978 }
5979
5980 static void
5981 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5982 uint64_t *buf, uint64_t arg)
5983 {
5984 int nframes = DTRACE_USTACK_NFRAMES(arg);
5985 int strsize = DTRACE_USTACK_STRSIZE(arg);
5986 uint64_t *pcs = &buf[1], *fps;
5987 char *str = (char *)&pcs[nframes];
5988 int size, offs = 0, i, j;
5989 uintptr_t old = mstate->dtms_scratch_ptr, saved;
5990 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5991 char *sym;
5992
5993 /*
5994 * Should be taking a faster path if string space has not been
5995 * allocated.
5996 */
5997 ASSERT(strsize != 0);
5998
5999 /*
6000 * We will first allocate some temporary space for the frame pointers.
6001 */
6002 fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6003 size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6004 (nframes * sizeof (uint64_t));
6005
6006 if (!DTRACE_INSCRATCH(mstate, (uintptr_t)size)) {
6007 /*
6008 * Not enough room for our frame pointers -- need to indicate
6009 * that we ran out of scratch space.
6010 */
6011 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6012 return;
6013 }
6014
6015 mstate->dtms_scratch_ptr += size;
6016 saved = mstate->dtms_scratch_ptr;
6017
6018 /*
6019 * Now get a stack with both program counters and frame pointers.
6020 */
6021 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6022 dtrace_getufpstack(buf, fps, nframes + 1);
6023 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6024
6025 /*
6026 * If that faulted, we're cooked.
6027 */
6028 if (*flags & CPU_DTRACE_FAULT)
6029 goto out;
6030
6031 /*
6032 * Now we want to walk up the stack, calling the USTACK helper. For
6033 * each iteration, we restore the scratch pointer.
6034 */
6035 for (i = 0; i < nframes; i++) {
6036 mstate->dtms_scratch_ptr = saved;
6037
6038 if (offs >= strsize)
6039 break;
6040
6041 sym = (char *)(uintptr_t)dtrace_helper(
6042 DTRACE_HELPER_ACTION_USTACK,
6043 mstate, state, pcs[i], fps[i]);
6044
6045 /*
6046 * If we faulted while running the helper, we're going to
6047 * clear the fault and null out the corresponding string.
6048 */
6049 if (*flags & CPU_DTRACE_FAULT) {
6050 *flags &= ~CPU_DTRACE_FAULT;
6051 str[offs++] = '\0';
6052 continue;
6053 }
6054
6055 if (sym == NULL) {
6056 str[offs++] = '\0';
6057 continue;
6058 }
6059
6060 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6061
6062 /*
6063 * Now copy in the string that the helper returned to us.
6064 */
6065 for (j = 0; offs + j < strsize; j++) {
6066 if ((str[offs + j] = sym[j]) == '\0')
6067 break;
6068 }
6069
6070 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6071
6072 offs += j + 1;
6073 }
6074
6075 if (offs >= strsize) {
6076 /*
6077 * If we didn't have room for all of the strings, we don't
6078 * abort processing -- this needn't be a fatal error -- but we
6079 * still want to increment a counter (dts_stkstroverflows) to
6080 * allow this condition to be warned about. (If this is from
6081 * a jstack() action, it is easily tuned via jstackstrsize.)
6082 */
6083 dtrace_error(&state->dts_stkstroverflows);
6084 }
6085
6086 while (offs < strsize)
6087 str[offs++] = '\0';
6088
6089 out:
6090 mstate->dtms_scratch_ptr = old;
6091 }
6092
6093 static void
6094 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6095 size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6096 {
6097 volatile uint16_t *flags;
6098 uint64_t val = *valp;
6099 size_t valoffs = *valoffsp;
6100
6101 flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6102 ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6103
6104 /*
6105 * If this is a string, we're going to only load until we find the zero
6106 * byte -- after which we'll store zero bytes.
6107 */
6108 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6109 char c = '\0' + 1;
6110 size_t s;
6111
6112 for (s = 0; s < size; s++) {
6113 if (c != '\0' && dtkind == DIF_TF_BYREF) {
6114 c = dtrace_load8(val++);
6115 } else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6116 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6117 c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6118 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6119 if (*flags & CPU_DTRACE_FAULT)
6120 break;
6121 }
6122
6123 DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6124
6125 if (c == '\0' && intuple)
6126 break;
6127 }
6128 } else {
6129 uint8_t c;
6130 while (valoffs < end) {
6131 if (dtkind == DIF_TF_BYREF) {
6132 c = dtrace_load8(val++);
6133 } else if (dtkind == DIF_TF_BYUREF) {
6134 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6135 c = dtrace_fuword8((user_addr_t)(uintptr_t)val++);
6136 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6137 if (*flags & CPU_DTRACE_FAULT)
6138 break;
6139 }
6140
6141 DTRACE_STORE(uint8_t, tomax,
6142 valoffs++, c);
6143 }
6144 }
6145
6146 *valp = val;
6147 *valoffsp = valoffs;
6148 }
6149
6150 /*
6151 * If you're looking for the epicenter of DTrace, you just found it. This
6152 * is the function called by the provider to fire a probe -- from which all
6153 * subsequent probe-context DTrace activity emanates.
6154 */
6155 static void
6156 __dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
6157 uint64_t arg2, uint64_t arg3, uint64_t arg4)
6158 {
6159 processorid_t cpuid;
6160 dtrace_icookie_t cookie;
6161 dtrace_probe_t *probe;
6162 dtrace_mstate_t mstate;
6163 dtrace_ecb_t *ecb;
6164 dtrace_action_t *act;
6165 intptr_t offs;
6166 size_t size;
6167 int vtime, onintr;
6168 volatile uint16_t *flags;
6169 hrtime_t now;
6170
6171 cookie = dtrace_interrupt_disable();
6172 probe = dtrace_probes[id - 1];
6173 cpuid = CPU->cpu_id;
6174 onintr = CPU_ON_INTR(CPU);
6175
6176 if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6177 probe->dtpr_predcache == dtrace_get_thread_predcache(current_thread())) {
6178 /*
6179 * We have hit in the predicate cache; we know that
6180 * this predicate would evaluate to be false.
6181 */
6182 dtrace_interrupt_enable(cookie);
6183 return;
6184 }
6185
6186 if (panic_quiesce) {
6187 /*
6188 * We don't trace anything if we're panicking.
6189 */
6190 dtrace_interrupt_enable(cookie);
6191 return;
6192 }
6193
6194 #if !defined(__APPLE__)
6195 now = dtrace_gethrtime();
6196 vtime = dtrace_vtime_references != 0;
6197
6198 if (vtime && curthread->t_dtrace_start)
6199 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6200 #else
6201 /*
6202 * APPLE NOTE: The time spent entering DTrace and arriving
6203 * to this point, is attributed to the current thread.
6204 * Instead it should accrue to DTrace. FIXME
6205 */
6206 vtime = dtrace_vtime_references != 0;
6207
6208 if (vtime)
6209 {
6210 int64_t dtrace_accum_time, recent_vtime;
6211 thread_t thread = current_thread();
6212
6213 dtrace_accum_time = dtrace_get_thread_tracing(thread); /* Time spent inside DTrace so far (nanoseconds) */
6214
6215 if (dtrace_accum_time >= 0) {
6216 recent_vtime = dtrace_abs_to_nano(dtrace_calc_thread_recent_vtime(thread)); /* up to the moment thread vtime */
6217
6218 recent_vtime = recent_vtime - dtrace_accum_time; /* Time without DTrace contribution */
6219
6220 dtrace_set_thread_vtime(thread, recent_vtime);
6221 }
6222 }
6223
6224 now = dtrace_gethrtime(); /* must not precede dtrace_calc_thread_recent_vtime() call! */
6225 #endif /* __APPLE__ */
6226
6227 /*
6228 * APPLE NOTE: A provider may call dtrace_probe_error() in lieu of
6229 * dtrace_probe() in some circumstances. See, e.g. fasttrap_isa.c.
6230 * However the provider has no access to ECB context, so passes
6231 * 0 through "arg0" and the probe_id of the overridden probe as arg1.
6232 * Detect that here and cons up a viable state (from the probe_id).
6233 */
6234 if (dtrace_probeid_error == id && 0 == arg0) {
6235 dtrace_id_t ftp_id = (dtrace_id_t)arg1;
6236 dtrace_probe_t *ftp_probe = dtrace_probes[ftp_id - 1];
6237 dtrace_ecb_t *ftp_ecb = ftp_probe->dtpr_ecb;
6238
6239 if (NULL != ftp_ecb) {
6240 dtrace_state_t *ftp_state = ftp_ecb->dte_state;
6241
6242 arg0 = (uint64_t)(uintptr_t)ftp_state;
6243 arg1 = ftp_ecb->dte_epid;
6244 /*
6245 * args[2-4] established by caller.
6246 */
6247 ftp_state->dts_arg_error_illval = -1; /* arg5 */
6248 }
6249 }
6250
6251 mstate.dtms_difo = NULL;
6252 mstate.dtms_probe = probe;
6253 mstate.dtms_strtok = 0;
6254 mstate.dtms_arg[0] = arg0;
6255 mstate.dtms_arg[1] = arg1;
6256 mstate.dtms_arg[2] = arg2;
6257 mstate.dtms_arg[3] = arg3;
6258 mstate.dtms_arg[4] = arg4;
6259
6260 flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6261
6262 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6263 dtrace_predicate_t *pred = ecb->dte_predicate;
6264 dtrace_state_t *state = ecb->dte_state;
6265 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6266 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6267 dtrace_vstate_t *vstate = &state->dts_vstate;
6268 dtrace_provider_t *prov = probe->dtpr_provider;
6269 uint64_t tracememsize = 0;
6270 int committed = 0;
6271 caddr_t tomax;
6272
6273 /*
6274 * A little subtlety with the following (seemingly innocuous)
6275 * declaration of the automatic 'val': by looking at the
6276 * code, you might think that it could be declared in the
6277 * action processing loop, below. (That is, it's only used in
6278 * the action processing loop.) However, it must be declared
6279 * out of that scope because in the case of DIF expression
6280 * arguments to aggregating actions, one iteration of the
6281 * action loop will use the last iteration's value.
6282 */
6283 #ifdef lint
6284 uint64_t val = 0;
6285 #else
6286 uint64_t val = 0;
6287 #endif
6288
6289 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6290 *flags &= ~CPU_DTRACE_ERROR;
6291
6292 if (prov == dtrace_provider) {
6293 /*
6294 * If dtrace itself is the provider of this probe,
6295 * we're only going to continue processing the ECB if
6296 * arg0 (the dtrace_state_t) is equal to the ECB's
6297 * creating state. (This prevents disjoint consumers
6298 * from seeing one another's metaprobes.)
6299 */
6300 if (arg0 != (uint64_t)(uintptr_t)state)
6301 continue;
6302 }
6303
6304 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6305 /*
6306 * We're not currently active. If our provider isn't
6307 * the dtrace pseudo provider, we're not interested.
6308 */
6309 if (prov != dtrace_provider)
6310 continue;
6311
6312 /*
6313 * Now we must further check if we are in the BEGIN
6314 * probe. If we are, we will only continue processing
6315 * if we're still in WARMUP -- if one BEGIN enabling
6316 * has invoked the exit() action, we don't want to
6317 * evaluate subsequent BEGIN enablings.
6318 */
6319 if (probe->dtpr_id == dtrace_probeid_begin &&
6320 state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6321 ASSERT(state->dts_activity ==
6322 DTRACE_ACTIVITY_DRAINING);
6323 continue;
6324 }
6325 }
6326
6327 if (ecb->dte_cond) {
6328 /*
6329 * If the dte_cond bits indicate that this
6330 * consumer is only allowed to see user-mode firings
6331 * of this probe, call the provider's dtps_usermode()
6332 * entry point to check that the probe was fired
6333 * while in a user context. Skip this ECB if that's
6334 * not the case.
6335 */
6336 if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6337 prov->dtpv_pops.dtps_usermode &&
6338 prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6339 probe->dtpr_id, probe->dtpr_arg) == 0)
6340 continue;
6341
6342 /*
6343 * This is more subtle than it looks. We have to be
6344 * absolutely certain that CRED() isn't going to
6345 * change out from under us so it's only legit to
6346 * examine that structure if we're in constrained
6347 * situations. Currently, the only times we'll this
6348 * check is if a non-super-user has enabled the
6349 * profile or syscall providers -- providers that
6350 * allow visibility of all processes. For the
6351 * profile case, the check above will ensure that
6352 * we're examining a user context.
6353 */
6354 if (ecb->dte_cond & DTRACE_COND_OWNER) {
6355 cred_t *cr;
6356 cred_t *s_cr =
6357 ecb->dte_state->dts_cred.dcr_cred;
6358 proc_t *proc;
6359 #pragma unused(proc) /* __APPLE__ */
6360
6361 ASSERT(s_cr != NULL);
6362
6363 /*
6364 * XXX this is hackish, but so is setting a variable
6365 * XXX in a McCarthy OR...
6366 */
6367 if ((cr = dtrace_CRED()) == NULL ||
6368 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_uid ||
6369 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_ruid ||
6370 posix_cred_get(s_cr)->cr_uid != posix_cred_get(cr)->cr_suid ||
6371 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_gid ||
6372 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_rgid ||
6373 posix_cred_get(s_cr)->cr_gid != posix_cred_get(cr)->cr_sgid ||
6374 #if !defined(__APPLE__)
6375 (proc = ttoproc(curthread)) == NULL ||
6376 (proc->p_flag & SNOCD))
6377 #else
6378 1) /* APPLE NOTE: Darwin omits "No Core Dump" flag */
6379 #endif /* __APPLE__ */
6380 continue;
6381 }
6382
6383 if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6384 cred_t *cr;
6385 cred_t *s_cr =
6386 ecb->dte_state->dts_cred.dcr_cred;
6387 #pragma unused(cr, s_cr) /* __APPLE__ */
6388
6389 ASSERT(s_cr != NULL);
6390
6391 #if !defined(__APPLE__)
6392 if ((cr = CRED()) == NULL ||
6393 s_cr->cr_zone->zone_id !=
6394 cr->cr_zone->zone_id)
6395 continue;
6396 #else
6397 /* APPLE NOTE: Darwin doesn't do zones. */
6398 #endif /* __APPLE__ */
6399 }
6400 }
6401
6402 if (now - state->dts_alive > dtrace_deadman_timeout) {
6403 /*
6404 * We seem to be dead. Unless we (a) have kernel
6405 * destructive permissions (b) have expicitly enabled
6406 * destructive actions and (c) destructive actions have
6407 * not been disabled, we're going to transition into
6408 * the KILLED state, from which no further processing
6409 * on this state will be performed.
6410 */
6411 if (!dtrace_priv_kernel_destructive(state) ||
6412 !state->dts_cred.dcr_destructive ||
6413 dtrace_destructive_disallow) {
6414 void *activity = &state->dts_activity;
6415 dtrace_activity_t current;
6416
6417 do {
6418 current = state->dts_activity;
6419 } while (dtrace_cas32(activity, current,
6420 DTRACE_ACTIVITY_KILLED) != current);
6421
6422 continue;
6423 }
6424 }
6425
6426 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6427 ecb->dte_alignment, state, &mstate)) < 0)
6428 continue;
6429
6430 tomax = buf->dtb_tomax;
6431 ASSERT(tomax != NULL);
6432
6433 /*
6434 * Build and store the record header corresponding to the ECB.
6435 */
6436 if (ecb->dte_size != 0) {
6437 dtrace_rechdr_t dtrh;
6438
6439 if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6440 mstate.dtms_timestamp = dtrace_gethrtime();
6441 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6442 }
6443
6444 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6445
6446 dtrh.dtrh_epid = ecb->dte_epid;
6447 DTRACE_RECORD_STORE_TIMESTAMP(&dtrh, mstate.dtms_timestamp);
6448 DTRACE_STORE(dtrace_rechdr_t, tomax, offs, dtrh);
6449 }
6450
6451 mstate.dtms_epid = ecb->dte_epid;
6452 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6453
6454 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6455 mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6456 else
6457 mstate.dtms_access = 0;
6458
6459 if (pred != NULL) {
6460 dtrace_difo_t *dp = pred->dtp_difo;
6461 int rval;
6462
6463 rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6464
6465 if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6466 dtrace_cacheid_t cid = probe->dtpr_predcache;
6467
6468 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6469 /*
6470 * Update the predicate cache...
6471 */
6472 ASSERT(cid == pred->dtp_cacheid);
6473
6474 dtrace_set_thread_predcache(current_thread(), cid);
6475 }
6476
6477 continue;
6478 }
6479 }
6480
6481 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6482 act != NULL; act = act->dta_next) {
6483 size_t valoffs;
6484 dtrace_difo_t *dp;
6485 dtrace_recdesc_t *rec = &act->dta_rec;
6486
6487 size = rec->dtrd_size;
6488 valoffs = offs + rec->dtrd_offset;
6489
6490 if (DTRACEACT_ISAGG(act->dta_kind)) {
6491 uint64_t v = 0xbad;
6492 dtrace_aggregation_t *agg;
6493
6494 agg = (dtrace_aggregation_t *)act;
6495
6496 if ((dp = act->dta_difo) != NULL)
6497 v = dtrace_dif_emulate(dp,
6498 &mstate, vstate, state);
6499
6500 if (*flags & CPU_DTRACE_ERROR)
6501 continue;
6502
6503 /*
6504 * Note that we always pass the expression
6505 * value from the previous iteration of the
6506 * action loop. This value will only be used
6507 * if there is an expression argument to the
6508 * aggregating action, denoted by the
6509 * dtag_hasarg field.
6510 */
6511 dtrace_aggregate(agg, buf,
6512 offs, aggbuf, v, val);
6513 continue;
6514 }
6515
6516 switch (act->dta_kind) {
6517 case DTRACEACT_STOP:
6518 if (dtrace_priv_proc_destructive(state))
6519 dtrace_action_stop();
6520 continue;
6521
6522 case DTRACEACT_BREAKPOINT:
6523 if (dtrace_priv_kernel_destructive(state))
6524 dtrace_action_breakpoint(ecb);
6525 continue;
6526
6527 case DTRACEACT_PANIC:
6528 if (dtrace_priv_kernel_destructive(state))
6529 dtrace_action_panic(ecb);
6530 continue;
6531
6532 case DTRACEACT_STACK:
6533 if (!dtrace_priv_kernel(state))
6534 continue;
6535
6536 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6537 size / sizeof (pc_t), probe->dtpr_aframes,
6538 DTRACE_ANCHORED(probe) ? NULL :
6539 (uint32_t *)(uintptr_t)arg0);
6540 continue;
6541
6542 case DTRACEACT_JSTACK:
6543 case DTRACEACT_USTACK:
6544 if (!dtrace_priv_proc(state))
6545 continue;
6546
6547 /*
6548 * See comment in DIF_VAR_PID.
6549 */
6550 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6551 CPU_ON_INTR(CPU)) {
6552 int depth = DTRACE_USTACK_NFRAMES(
6553 rec->dtrd_arg) + 1;
6554
6555 dtrace_bzero((void *)(tomax + valoffs),
6556 DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6557 + depth * sizeof (uint64_t));
6558
6559 continue;
6560 }
6561
6562 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6563 curproc->p_dtrace_helpers != NULL) {
6564 /*
6565 * This is the slow path -- we have
6566 * allocated string space, and we're
6567 * getting the stack of a process that
6568 * has helpers. Call into a separate
6569 * routine to perform this processing.
6570 */
6571 dtrace_action_ustack(&mstate, state,
6572 (uint64_t *)(tomax + valoffs),
6573 rec->dtrd_arg);
6574 continue;
6575 }
6576
6577 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6578 dtrace_getupcstack((uint64_t *)
6579 (tomax + valoffs),
6580 DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6581 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6582 continue;
6583
6584 default:
6585 break;
6586 }
6587
6588 dp = act->dta_difo;
6589 ASSERT(dp != NULL);
6590
6591 val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6592
6593 if (*flags & CPU_DTRACE_ERROR)
6594 continue;
6595
6596 switch (act->dta_kind) {
6597 case DTRACEACT_SPECULATE: {
6598 dtrace_rechdr_t *dtrh = NULL;
6599
6600 ASSERT(buf == &state->dts_buffer[cpuid]);
6601 buf = dtrace_speculation_buffer(state,
6602 cpuid, val);
6603
6604 if (buf == NULL) {
6605 *flags |= CPU_DTRACE_DROP;
6606 continue;
6607 }
6608
6609 offs = dtrace_buffer_reserve(buf,
6610 ecb->dte_needed, ecb->dte_alignment,
6611 state, NULL);
6612
6613 if (offs < 0) {
6614 *flags |= CPU_DTRACE_DROP;
6615 continue;
6616 }
6617
6618 tomax = buf->dtb_tomax;
6619 ASSERT(tomax != NULL);
6620
6621 if (ecb->dte_size == 0)
6622 continue;
6623
6624 ASSERT(ecb->dte_size >= sizeof(dtrace_rechdr_t));
6625 dtrh = ((void *)(tomax + offs));
6626 dtrh->dtrh_epid = ecb->dte_epid;
6627
6628 /*
6629 * When the speculation is committed, all of
6630 * the records in the speculative buffer will
6631 * have their timestamps set to the commit
6632 * time. Until then, it is set to a sentinel
6633 * value, for debugability.
6634 */
6635 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6636
6637 continue;
6638 }
6639
6640 case DTRACEACT_CHILL:
6641 if (dtrace_priv_kernel_destructive(state))
6642 dtrace_action_chill(&mstate, val);
6643 continue;
6644
6645 case DTRACEACT_RAISE:
6646 if (dtrace_priv_proc_destructive(state))
6647 dtrace_action_raise(val);
6648 continue;
6649
6650 case DTRACEACT_PIDRESUME: /* __APPLE__ */
6651 if (dtrace_priv_proc_destructive(state))
6652 dtrace_action_pidresume(val);
6653 continue;
6654
6655 case DTRACEACT_COMMIT:
6656 ASSERT(!committed);
6657
6658 /*
6659 * We need to commit our buffer state.
6660 */
6661 if (ecb->dte_size)
6662 buf->dtb_offset = offs + ecb->dte_size;
6663 buf = &state->dts_buffer[cpuid];
6664 dtrace_speculation_commit(state, cpuid, val);
6665 committed = 1;
6666 continue;
6667
6668 case DTRACEACT_DISCARD:
6669 dtrace_speculation_discard(state, cpuid, val);
6670 continue;
6671
6672 case DTRACEACT_DIFEXPR:
6673 case DTRACEACT_LIBACT:
6674 case DTRACEACT_PRINTF:
6675 case DTRACEACT_PRINTA:
6676 case DTRACEACT_SYSTEM:
6677 case DTRACEACT_FREOPEN:
6678 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
6679 case DTRACEACT_TRACEMEM:
6680 break;
6681
6682 case DTRACEACT_TRACEMEM_DYNSIZE:
6683 tracememsize = val;
6684 break;
6685
6686 case DTRACEACT_SYM:
6687 case DTRACEACT_MOD:
6688 if (!dtrace_priv_kernel(state))
6689 continue;
6690 break;
6691
6692 case DTRACEACT_USYM:
6693 case DTRACEACT_UMOD:
6694 case DTRACEACT_UADDR: {
6695 if (!dtrace_priv_proc(state))
6696 continue;
6697
6698 DTRACE_STORE(uint64_t, tomax,
6699 valoffs, (uint64_t)dtrace_proc_selfpid());
6700 DTRACE_STORE(uint64_t, tomax,
6701 valoffs + sizeof (uint64_t), val);
6702
6703 continue;
6704 }
6705
6706 case DTRACEACT_EXIT: {
6707 /*
6708 * For the exit action, we are going to attempt
6709 * to atomically set our activity to be
6710 * draining. If this fails (either because
6711 * another CPU has beat us to the exit action,
6712 * or because our current activity is something
6713 * other than ACTIVE or WARMUP), we will
6714 * continue. This assures that the exit action
6715 * can be successfully recorded at most once
6716 * when we're in the ACTIVE state. If we're
6717 * encountering the exit() action while in
6718 * COOLDOWN, however, we want to honor the new
6719 * status code. (We know that we're the only
6720 * thread in COOLDOWN, so there is no race.)
6721 */
6722 void *activity = &state->dts_activity;
6723 dtrace_activity_t current = state->dts_activity;
6724
6725 if (current == DTRACE_ACTIVITY_COOLDOWN)
6726 break;
6727
6728 if (current != DTRACE_ACTIVITY_WARMUP)
6729 current = DTRACE_ACTIVITY_ACTIVE;
6730
6731 if (dtrace_cas32(activity, current,
6732 DTRACE_ACTIVITY_DRAINING) != current) {
6733 *flags |= CPU_DTRACE_DROP;
6734 continue;
6735 }
6736
6737 break;
6738 }
6739
6740 default:
6741 ASSERT(0);
6742 }
6743
6744 if (dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF)) {
6745 uintptr_t end = valoffs + size;
6746
6747 if (tracememsize != 0 &&
6748 valoffs + tracememsize < end)
6749 {
6750 end = valoffs + tracememsize;
6751 tracememsize = 0;
6752 }
6753
6754 if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
6755 !dtrace_vcanload((void *)(uintptr_t)val,
6756 &dp->dtdo_rtype, NULL, &mstate, vstate))
6757 {
6758 continue;
6759 }
6760
6761 dtrace_store_by_ref(dp, tomax, size, &valoffs,
6762 &val, end, act->dta_intuple,
6763 dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
6764 DIF_TF_BYREF: DIF_TF_BYUREF);
6765
6766 continue;
6767 }
6768
6769 switch (size) {
6770 case 0:
6771 break;
6772
6773 case sizeof (uint8_t):
6774 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6775 break;
6776 case sizeof (uint16_t):
6777 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6778 break;
6779 case sizeof (uint32_t):
6780 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6781 break;
6782 case sizeof (uint64_t):
6783 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6784 break;
6785 default:
6786 /*
6787 * Any other size should have been returned by
6788 * reference, not by value.
6789 */
6790 ASSERT(0);
6791 break;
6792 }
6793 }
6794
6795 if (*flags & CPU_DTRACE_DROP)
6796 continue;
6797
6798 if (*flags & CPU_DTRACE_FAULT) {
6799 int ndx;
6800 dtrace_action_t *err;
6801
6802 buf->dtb_errors++;
6803
6804 if (probe->dtpr_id == dtrace_probeid_error) {
6805 /*
6806 * There's nothing we can do -- we had an
6807 * error on the error probe. We bump an
6808 * error counter to at least indicate that
6809 * this condition happened.
6810 */
6811 dtrace_error(&state->dts_dblerrors);
6812 continue;
6813 }
6814
6815 if (vtime) {
6816 /*
6817 * Before recursing on dtrace_probe(), we
6818 * need to explicitly clear out our start
6819 * time to prevent it from being accumulated
6820 * into t_dtrace_vtime.
6821 */
6822
6823 /*
6824 * Darwin sets the sign bit on t_dtrace_tracing
6825 * to suspend accumulation to it.
6826 */
6827 dtrace_set_thread_tracing(current_thread(),
6828 (1ULL<<63) | dtrace_get_thread_tracing(current_thread()));
6829
6830 }
6831
6832 /*
6833 * Iterate over the actions to figure out which action
6834 * we were processing when we experienced the error.
6835 * Note that act points _past_ the faulting action; if
6836 * act is ecb->dte_action, the fault was in the
6837 * predicate, if it's ecb->dte_action->dta_next it's
6838 * in action #1, and so on.
6839 */
6840 for (err = ecb->dte_action, ndx = 0;
6841 err != act; err = err->dta_next, ndx++)
6842 continue;
6843
6844 dtrace_probe_error(state, ecb->dte_epid, ndx,
6845 (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6846 mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6847 cpu_core[cpuid].cpuc_dtrace_illval);
6848
6849 continue;
6850 }
6851
6852 if (!committed)
6853 buf->dtb_offset = offs + ecb->dte_size;
6854 }
6855
6856 /* FIXME: On Darwin the time spent leaving DTrace from this point to the rti is attributed
6857 to the current thread. Instead it should accrue to DTrace. */
6858 if (vtime) {
6859 thread_t thread = current_thread();
6860 int64_t t = dtrace_get_thread_tracing(thread);
6861
6862 if (t >= 0) {
6863 /* Usual case, accumulate time spent here into t_dtrace_tracing */
6864 dtrace_set_thread_tracing(thread, t + (dtrace_gethrtime() - now));
6865 } else {
6866 /* Return from error recursion. No accumulation, just clear the sign bit on t_dtrace_tracing. */
6867 dtrace_set_thread_tracing(thread, (~(1ULL<<63)) & t);
6868 }
6869 }
6870
6871 dtrace_interrupt_enable(cookie);
6872 }
6873
6874 /*
6875 * APPLE NOTE: Don't allow a thread to re-enter dtrace_probe().
6876 * This could occur if a probe is encountered on some function in the
6877 * transitive closure of the call to dtrace_probe().
6878 * Solaris has some strong guarantees that this won't happen.
6879 * The Darwin implementation is not so mature as to make those guarantees.
6880 * Hence, the introduction of __dtrace_probe() on xnu.
6881 */
6882
6883 void
6884 dtrace_probe(dtrace_id_t id, uint64_t arg0, uint64_t arg1,
6885 uint64_t arg2, uint64_t arg3, uint64_t arg4)
6886 {
6887 thread_t thread = current_thread();
6888 disable_preemption();
6889 if (id == dtrace_probeid_error) {
6890 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
6891 dtrace_getipl(); /* Defeat tail-call optimization of __dtrace_probe() */
6892 } else if (!dtrace_get_thread_reentering(thread)) {
6893 dtrace_set_thread_reentering(thread, TRUE);
6894 __dtrace_probe(id, arg0, arg1, arg2, arg3, arg4);
6895 dtrace_set_thread_reentering(thread, FALSE);
6896 }
6897 #if DEBUG
6898 else __dtrace_probe(dtrace_probeid_error, 0, id, 1, -1, DTRACEFLT_UNKNOWN);
6899 #endif
6900 enable_preemption();
6901 }
6902
6903 /*
6904 * DTrace Probe Hashing Functions
6905 *
6906 * The functions in this section (and indeed, the functions in remaining
6907 * sections) are not _called_ from probe context. (Any exceptions to this are
6908 * marked with a "Note:".) Rather, they are called from elsewhere in the
6909 * DTrace framework to look-up probes in, add probes to and remove probes from
6910 * the DTrace probe hashes. (Each probe is hashed by each element of the
6911 * probe tuple -- allowing for fast lookups, regardless of what was
6912 * specified.)
6913 */
6914 static uint_t
6915 dtrace_hash_str(const char *p)
6916 {
6917 unsigned int g;
6918 uint_t hval = 0;
6919
6920 while (*p) {
6921 hval = (hval << 4) + *p++;
6922 if ((g = (hval & 0xf0000000)) != 0)
6923 hval ^= g >> 24;
6924 hval &= ~g;
6925 }
6926 return (hval);
6927 }
6928
6929 static dtrace_hash_t *
6930 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6931 {
6932 dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6933
6934 hash->dth_stroffs = stroffs;
6935 hash->dth_nextoffs = nextoffs;
6936 hash->dth_prevoffs = prevoffs;
6937
6938 hash->dth_size = 1;
6939 hash->dth_mask = hash->dth_size - 1;
6940
6941 hash->dth_tab = kmem_zalloc(hash->dth_size *
6942 sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6943
6944 return (hash);
6945 }
6946
6947 /*
6948 * APPLE NOTE: dtrace_hash_destroy is not used.
6949 * It is called by dtrace_detach which is not
6950 * currently implemented. Revisit someday.
6951 */
6952 #if !defined(__APPLE__)
6953 static void
6954 dtrace_hash_destroy(dtrace_hash_t *hash)
6955 {
6956 #if DEBUG
6957 int i;
6958
6959 for (i = 0; i < hash->dth_size; i++)
6960 ASSERT(hash->dth_tab[i] == NULL);
6961 #endif
6962
6963 kmem_free(hash->dth_tab,
6964 hash->dth_size * sizeof (dtrace_hashbucket_t *));
6965 kmem_free(hash, sizeof (dtrace_hash_t));
6966 }
6967 #endif /* __APPLE__ */
6968
6969 static void
6970 dtrace_hash_resize(dtrace_hash_t *hash)
6971 {
6972 int size = hash->dth_size, i, ndx;
6973 int new_size = hash->dth_size << 1;
6974 int new_mask = new_size - 1;
6975 dtrace_hashbucket_t **new_tab, *bucket, *next;
6976
6977 ASSERT((new_size & new_mask) == 0);
6978
6979 new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6980
6981 for (i = 0; i < size; i++) {
6982 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6983 dtrace_probe_t *probe = bucket->dthb_chain;
6984
6985 ASSERT(probe != NULL);
6986 ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6987
6988 next = bucket->dthb_next;
6989 bucket->dthb_next = new_tab[ndx];
6990 new_tab[ndx] = bucket;
6991 }
6992 }
6993
6994 kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6995 hash->dth_tab = new_tab;
6996 hash->dth_size = new_size;
6997 hash->dth_mask = new_mask;
6998 }
6999
7000 static void
7001 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7002 {
7003 int hashval = DTRACE_HASHSTR(hash, new);
7004 int ndx = hashval & hash->dth_mask;
7005 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7006 dtrace_probe_t **nextp, **prevp;
7007
7008 for (; bucket != NULL; bucket = bucket->dthb_next) {
7009 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7010 goto add;
7011 }
7012
7013 if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7014 dtrace_hash_resize(hash);
7015 dtrace_hash_add(hash, new);
7016 return;
7017 }
7018
7019 bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7020 bucket->dthb_next = hash->dth_tab[ndx];
7021 hash->dth_tab[ndx] = bucket;
7022 hash->dth_nbuckets++;
7023
7024 add:
7025 nextp = DTRACE_HASHNEXT(hash, new);
7026 ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7027 *nextp = bucket->dthb_chain;
7028
7029 if (bucket->dthb_chain != NULL) {
7030 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7031 ASSERT(*prevp == NULL);
7032 *prevp = new;
7033 }
7034
7035 bucket->dthb_chain = new;
7036 bucket->dthb_len++;
7037 }
7038
7039 static dtrace_probe_t *
7040 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7041 {
7042 int hashval = DTRACE_HASHSTR(hash, template);
7043 int ndx = hashval & hash->dth_mask;
7044 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7045
7046 for (; bucket != NULL; bucket = bucket->dthb_next) {
7047 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7048 return (bucket->dthb_chain);
7049 }
7050
7051 return (NULL);
7052 }
7053
7054 static int
7055 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7056 {
7057 int hashval = DTRACE_HASHSTR(hash, template);
7058 int ndx = hashval & hash->dth_mask;
7059 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7060
7061 for (; bucket != NULL; bucket = bucket->dthb_next) {
7062 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7063 return (bucket->dthb_len);
7064 }
7065
7066 return (0);
7067 }
7068
7069 static void
7070 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7071 {
7072 int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7073 dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7074
7075 dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7076 dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7077
7078 /*
7079 * Find the bucket that we're removing this probe from.
7080 */
7081 for (; bucket != NULL; bucket = bucket->dthb_next) {
7082 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7083 break;
7084 }
7085
7086 ASSERT(bucket != NULL);
7087
7088 if (*prevp == NULL) {
7089 if (*nextp == NULL) {
7090 /*
7091 * The removed probe was the only probe on this
7092 * bucket; we need to remove the bucket.
7093 */
7094 dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7095
7096 ASSERT(bucket->dthb_chain == probe);
7097 ASSERT(b != NULL);
7098
7099 if (b == bucket) {
7100 hash->dth_tab[ndx] = bucket->dthb_next;
7101 } else {
7102 while (b->dthb_next != bucket)
7103 b = b->dthb_next;
7104 b->dthb_next = bucket->dthb_next;
7105 }
7106
7107 ASSERT(hash->dth_nbuckets > 0);
7108 hash->dth_nbuckets--;
7109 kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7110 return;
7111 }
7112
7113 bucket->dthb_chain = *nextp;
7114 } else {
7115 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7116 }
7117
7118 if (*nextp != NULL)
7119 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7120 }
7121
7122 /*
7123 * DTrace Utility Functions
7124 *
7125 * These are random utility functions that are _not_ called from probe context.
7126 */
7127 static int
7128 dtrace_badattr(const dtrace_attribute_t *a)
7129 {
7130 return (a->dtat_name > DTRACE_STABILITY_MAX ||
7131 a->dtat_data > DTRACE_STABILITY_MAX ||
7132 a->dtat_class > DTRACE_CLASS_MAX);
7133 }
7134
7135 /*
7136 * Return a duplicate copy of a string. If the specified string is NULL,
7137 * this function returns a zero-length string.
7138 * APPLE NOTE: Darwin employs size bounded string operation.
7139 */
7140 static char *
7141 dtrace_strdup(const char *str)
7142 {
7143 size_t bufsize = (str != NULL ? strlen(str) : 0) + 1;
7144 char *new = kmem_zalloc(bufsize, KM_SLEEP);
7145
7146 if (str != NULL)
7147 (void) strlcpy(new, str, bufsize);
7148
7149 return (new);
7150 }
7151
7152 #define DTRACE_ISALPHA(c) \
7153 (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7154
7155 static int
7156 dtrace_badname(const char *s)
7157 {
7158 char c;
7159
7160 if (s == NULL || (c = *s++) == '\0')
7161 return (0);
7162
7163 if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7164 return (1);
7165
7166 while ((c = *s++) != '\0') {
7167 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7168 c != '-' && c != '_' && c != '.' && c != '`')
7169 return (1);
7170 }
7171
7172 return (0);
7173 }
7174
7175 static void
7176 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7177 {
7178 uint32_t priv;
7179
7180 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7181 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
7182 priv = DTRACE_PRIV_USER | DTRACE_PRIV_PROC;
7183 }
7184 else {
7185 priv = DTRACE_PRIV_ALL;
7186 }
7187 } else {
7188 *uidp = crgetuid(cr);
7189 *zoneidp = crgetzoneid(cr);
7190
7191 priv = 0;
7192 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7193 priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7194 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7195 priv |= DTRACE_PRIV_USER;
7196 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7197 priv |= DTRACE_PRIV_PROC;
7198 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7199 priv |= DTRACE_PRIV_OWNER;
7200 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7201 priv |= DTRACE_PRIV_ZONEOWNER;
7202 }
7203
7204 *privp = priv;
7205 }
7206
7207 #ifdef DTRACE_ERRDEBUG
7208 static void
7209 dtrace_errdebug(const char *str)
7210 {
7211 int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7212 int occupied = 0;
7213
7214 lck_mtx_lock(&dtrace_errlock);
7215 dtrace_errlast = str;
7216 dtrace_errthread = (kthread_t *)current_thread();
7217
7218 while (occupied++ < DTRACE_ERRHASHSZ) {
7219 if (dtrace_errhash[hval].dter_msg == str) {
7220 dtrace_errhash[hval].dter_count++;
7221 goto out;
7222 }
7223
7224 if (dtrace_errhash[hval].dter_msg != NULL) {
7225 hval = (hval + 1) % DTRACE_ERRHASHSZ;
7226 continue;
7227 }
7228
7229 dtrace_errhash[hval].dter_msg = str;
7230 dtrace_errhash[hval].dter_count = 1;
7231 goto out;
7232 }
7233
7234 panic("dtrace: undersized error hash");
7235 out:
7236 lck_mtx_unlock(&dtrace_errlock);
7237 }
7238 #endif
7239
7240 /*
7241 * DTrace Matching Functions
7242 *
7243 * These functions are used to match groups of probes, given some elements of
7244 * a probe tuple, or some globbed expressions for elements of a probe tuple.
7245 */
7246 static int
7247 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7248 zoneid_t zoneid)
7249 {
7250 if (priv != DTRACE_PRIV_ALL) {
7251 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7252 uint32_t match = priv & ppriv;
7253
7254 /*
7255 * No PRIV_DTRACE_* privileges...
7256 */
7257 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7258 DTRACE_PRIV_KERNEL)) == 0)
7259 return (0);
7260
7261 /*
7262 * No matching bits, but there were bits to match...
7263 */
7264 if (match == 0 && ppriv != 0)
7265 return (0);
7266
7267 /*
7268 * Need to have permissions to the process, but don't...
7269 */
7270 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7271 uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7272 return (0);
7273 }
7274
7275 /*
7276 * Need to be in the same zone unless we possess the
7277 * privilege to examine all zones.
7278 */
7279 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7280 zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7281 return (0);
7282 }
7283 }
7284
7285 return (1);
7286 }
7287
7288 /*
7289 * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7290 * consists of input pattern strings and an ops-vector to evaluate them.
7291 * This function returns >0 for match, 0 for no match, and <0 for error.
7292 */
7293 static int
7294 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7295 uint32_t priv, uid_t uid, zoneid_t zoneid)
7296 {
7297 dtrace_provider_t *pvp = prp->dtpr_provider;
7298 int rv;
7299
7300 if (pvp->dtpv_defunct)
7301 return (0);
7302
7303 if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7304 return (rv);
7305
7306 if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7307 return (rv);
7308
7309 if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7310 return (rv);
7311
7312 if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7313 return (rv);
7314
7315 if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7316 return (0);
7317
7318 return (rv);
7319 }
7320
7321 /*
7322 * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7323 * interface for matching a glob pattern 'p' to an input string 's'. Unlike
7324 * libc's version, the kernel version only applies to 8-bit ASCII strings.
7325 * In addition, all of the recursion cases except for '*' matching have been
7326 * unwound. For '*', we still implement recursive evaluation, but a depth
7327 * counter is maintained and matching is aborted if we recurse too deep.
7328 * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7329 */
7330 static int
7331 dtrace_match_glob(const char *s, const char *p, int depth)
7332 {
7333 const char *olds;
7334 char s1, c;
7335 int gs;
7336
7337 if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7338 return (-1);
7339
7340 if (s == NULL)
7341 s = ""; /* treat NULL as empty string */
7342
7343 top:
7344 olds = s;
7345 s1 = *s++;
7346
7347 if (p == NULL)
7348 return (0);
7349
7350 if ((c = *p++) == '\0')
7351 return (s1 == '\0');
7352
7353 switch (c) {
7354 case '[': {
7355 int ok = 0, notflag = 0;
7356 char lc = '\0';
7357
7358 if (s1 == '\0')
7359 return (0);
7360
7361 if (*p == '!') {
7362 notflag = 1;
7363 p++;
7364 }
7365
7366 if ((c = *p++) == '\0')
7367 return (0);
7368
7369 do {
7370 if (c == '-' && lc != '\0' && *p != ']') {
7371 if ((c = *p++) == '\0')
7372 return (0);
7373 if (c == '\\' && (c = *p++) == '\0')
7374 return (0);
7375
7376 if (notflag) {
7377 if (s1 < lc || s1 > c)
7378 ok++;
7379 else
7380 return (0);
7381 } else if (lc <= s1 && s1 <= c)
7382 ok++;
7383
7384 } else if (c == '\\' && (c = *p++) == '\0')
7385 return (0);
7386
7387 lc = c; /* save left-hand 'c' for next iteration */
7388
7389 if (notflag) {
7390 if (s1 != c)
7391 ok++;
7392 else
7393 return (0);
7394 } else if (s1 == c)
7395 ok++;
7396
7397 if ((c = *p++) == '\0')
7398 return (0);
7399
7400 } while (c != ']');
7401
7402 if (ok)
7403 goto top;
7404
7405 return (0);
7406 }
7407
7408 case '\\':
7409 if ((c = *p++) == '\0')
7410 return (0);
7411 /*FALLTHRU*/
7412
7413 default:
7414 if (c != s1)
7415 return (0);
7416 /*FALLTHRU*/
7417
7418 case '?':
7419 if (s1 != '\0')
7420 goto top;
7421 return (0);
7422
7423 case '*':
7424 while (*p == '*')
7425 p++; /* consecutive *'s are identical to a single one */
7426
7427 if (*p == '\0')
7428 return (1);
7429
7430 for (s = olds; *s != '\0'; s++) {
7431 if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7432 return (gs);
7433 }
7434
7435 return (0);
7436 }
7437 }
7438
7439 /*ARGSUSED*/
7440 static int
7441 dtrace_match_string(const char *s, const char *p, int depth)
7442 {
7443 #pragma unused(depth) /* __APPLE__ */
7444
7445 /* APPLE NOTE: Darwin employs size bounded string operation. */
7446 return (s != NULL && strncmp(s, p, strlen(s) + 1) == 0);
7447 }
7448
7449 /*ARGSUSED*/
7450 static int
7451 dtrace_match_nul(const char *s, const char *p, int depth)
7452 {
7453 #pragma unused(s, p, depth) /* __APPLE__ */
7454 return (1); /* always match the empty pattern */
7455 }
7456
7457 /*ARGSUSED*/
7458 static int
7459 dtrace_match_nonzero(const char *s, const char *p, int depth)
7460 {
7461 #pragma unused(p, depth) /* __APPLE__ */
7462 return (s != NULL && s[0] != '\0');
7463 }
7464
7465 static int
7466 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7467 zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7468 {
7469 dtrace_probe_t template, *probe;
7470 dtrace_hash_t *hash = NULL;
7471 int len, rc, best = INT_MAX, nmatched = 0;
7472 dtrace_id_t i;
7473
7474 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7475
7476 /*
7477 * If the probe ID is specified in the key, just lookup by ID and
7478 * invoke the match callback once if a matching probe is found.
7479 */
7480 if (pkp->dtpk_id != DTRACE_IDNONE) {
7481 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7482 dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7483 if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7484 return (DTRACE_MATCH_FAIL);
7485 nmatched++;
7486 }
7487 return (nmatched);
7488 }
7489
7490 template.dtpr_mod = (char *)(uintptr_t)pkp->dtpk_mod;
7491 template.dtpr_func = (char *)(uintptr_t)pkp->dtpk_func;
7492 template.dtpr_name = (char *)(uintptr_t)pkp->dtpk_name;
7493
7494 /*
7495 * We want to find the most distinct of the module name, function
7496 * name, and name. So for each one that is not a glob pattern or
7497 * empty string, we perform a lookup in the corresponding hash and
7498 * use the hash table with the fewest collisions to do our search.
7499 */
7500 if (pkp->dtpk_mmatch == &dtrace_match_string &&
7501 (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7502 best = len;
7503 hash = dtrace_bymod;
7504 }
7505
7506 if (pkp->dtpk_fmatch == &dtrace_match_string &&
7507 (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7508 best = len;
7509 hash = dtrace_byfunc;
7510 }
7511
7512 if (pkp->dtpk_nmatch == &dtrace_match_string &&
7513 (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7514 best = len;
7515 hash = dtrace_byname;
7516 }
7517
7518 /*
7519 * If we did not select a hash table, iterate over every probe and
7520 * invoke our callback for each one that matches our input probe key.
7521 */
7522 if (hash == NULL) {
7523 for (i = 0; i < (dtrace_id_t)dtrace_nprobes; i++) {
7524 if ((probe = dtrace_probes[i]) == NULL ||
7525 dtrace_match_probe(probe, pkp, priv, uid,
7526 zoneid) <= 0)
7527 continue;
7528
7529 nmatched++;
7530
7531 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7532 if (rc == DTRACE_MATCH_FAIL)
7533 return (DTRACE_MATCH_FAIL);
7534 break;
7535 }
7536 }
7537
7538 return (nmatched);
7539 }
7540
7541 /*
7542 * If we selected a hash table, iterate over each probe of the same key
7543 * name and invoke the callback for every probe that matches the other
7544 * attributes of our input probe key.
7545 */
7546 for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7547 probe = *(DTRACE_HASHNEXT(hash, probe))) {
7548
7549 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7550 continue;
7551
7552 nmatched++;
7553
7554 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7555 if (rc == DTRACE_MATCH_FAIL)
7556 return (DTRACE_MATCH_FAIL);
7557 break;
7558 }
7559 }
7560
7561 return (nmatched);
7562 }
7563
7564 /*
7565 * Return the function pointer dtrace_probecmp() should use to compare the
7566 * specified pattern with a string. For NULL or empty patterns, we select
7567 * dtrace_match_nul(). For glob pattern strings, we use dtrace_match_glob().
7568 * For non-empty non-glob strings, we use dtrace_match_string().
7569 */
7570 static dtrace_probekey_f *
7571 dtrace_probekey_func(const char *p)
7572 {
7573 char c;
7574
7575 if (p == NULL || *p == '\0')
7576 return (&dtrace_match_nul);
7577
7578 while ((c = *p++) != '\0') {
7579 if (c == '[' || c == '?' || c == '*' || c == '\\')
7580 return (&dtrace_match_glob);
7581 }
7582
7583 return (&dtrace_match_string);
7584 }
7585
7586 /*
7587 * Build a probe comparison key for use with dtrace_match_probe() from the
7588 * given probe description. By convention, a null key only matches anchored
7589 * probes: if each field is the empty string, reset dtpk_fmatch to
7590 * dtrace_match_nonzero().
7591 */
7592 static void
7593 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7594 {
7595 pkp->dtpk_prov = pdp->dtpd_provider;
7596 pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7597
7598 pkp->dtpk_mod = pdp->dtpd_mod;
7599 pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7600
7601 pkp->dtpk_func = pdp->dtpd_func;
7602 pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7603
7604 pkp->dtpk_name = pdp->dtpd_name;
7605 pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7606
7607 pkp->dtpk_id = pdp->dtpd_id;
7608
7609 if (pkp->dtpk_id == DTRACE_IDNONE &&
7610 pkp->dtpk_pmatch == &dtrace_match_nul &&
7611 pkp->dtpk_mmatch == &dtrace_match_nul &&
7612 pkp->dtpk_fmatch == &dtrace_match_nul &&
7613 pkp->dtpk_nmatch == &dtrace_match_nul)
7614 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7615 }
7616
7617 static int
7618 dtrace_cond_provider_match(dtrace_probedesc_t *desc, void *data)
7619 {
7620 if (desc == NULL)
7621 return 1;
7622
7623 dtrace_probekey_f *func = dtrace_probekey_func(desc->dtpd_provider);
7624
7625 return func(desc->dtpd_provider, (char*)data, 0);
7626 }
7627
7628 /*
7629 * DTrace Provider-to-Framework API Functions
7630 *
7631 * These functions implement much of the Provider-to-Framework API, as
7632 * described in <sys/dtrace.h>. The parts of the API not in this section are
7633 * the functions in the API for probe management (found below), and
7634 * dtrace_probe() itself (found above).
7635 */
7636
7637 /*
7638 * Register the calling provider with the DTrace framework. This should
7639 * generally be called by DTrace providers in their attach(9E) entry point.
7640 */
7641 int
7642 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7643 cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7644 {
7645 dtrace_provider_t *provider;
7646
7647 if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7648 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7649 "arguments", name ? name : "<NULL>");
7650 return (EINVAL);
7651 }
7652
7653 if (name[0] == '\0' || dtrace_badname(name)) {
7654 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7655 "provider name", name);
7656 return (EINVAL);
7657 }
7658
7659 if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7660 pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7661 pops->dtps_destroy == NULL ||
7662 ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7663 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7664 "provider ops", name);
7665 return (EINVAL);
7666 }
7667
7668 if (dtrace_badattr(&pap->dtpa_provider) ||
7669 dtrace_badattr(&pap->dtpa_mod) ||
7670 dtrace_badattr(&pap->dtpa_func) ||
7671 dtrace_badattr(&pap->dtpa_name) ||
7672 dtrace_badattr(&pap->dtpa_args)) {
7673 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7674 "provider attributes", name);
7675 return (EINVAL);
7676 }
7677
7678 if (priv & ~DTRACE_PRIV_ALL) {
7679 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7680 "privilege attributes", name);
7681 return (EINVAL);
7682 }
7683
7684 if ((priv & DTRACE_PRIV_KERNEL) &&
7685 (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7686 pops->dtps_usermode == NULL) {
7687 cmn_err(CE_WARN, "failed to register provider '%s': need "
7688 "dtps_usermode() op for given privilege attributes", name);
7689 return (EINVAL);
7690 }
7691
7692 provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7693
7694 /* APPLE NOTE: Darwin employs size bounded string operation. */
7695 {
7696 size_t bufsize = strlen(name) + 1;
7697 provider->dtpv_name = kmem_alloc(bufsize, KM_SLEEP);
7698 (void) strlcpy(provider->dtpv_name, name, bufsize);
7699 }
7700
7701 provider->dtpv_attr = *pap;
7702 provider->dtpv_priv.dtpp_flags = priv;
7703 if (cr != NULL) {
7704 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7705 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7706 }
7707 provider->dtpv_pops = *pops;
7708
7709 if (pops->dtps_provide == NULL) {
7710 ASSERT(pops->dtps_provide_module != NULL);
7711 provider->dtpv_pops.dtps_provide =
7712 (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7713 }
7714
7715 if (pops->dtps_provide_module == NULL) {
7716 ASSERT(pops->dtps_provide != NULL);
7717 provider->dtpv_pops.dtps_provide_module =
7718 (void (*)(void *, struct modctl *))dtrace_nullop;
7719 }
7720
7721 if (pops->dtps_suspend == NULL) {
7722 ASSERT(pops->dtps_resume == NULL);
7723 provider->dtpv_pops.dtps_suspend =
7724 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7725 provider->dtpv_pops.dtps_resume =
7726 (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7727 }
7728
7729 provider->dtpv_arg = arg;
7730 *idp = (dtrace_provider_id_t)provider;
7731
7732 if (pops == &dtrace_provider_ops) {
7733 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7734 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7735 ASSERT(dtrace_anon.dta_enabling == NULL);
7736
7737 /*
7738 * We make sure that the DTrace provider is at the head of
7739 * the provider chain.
7740 */
7741 provider->dtpv_next = dtrace_provider;
7742 dtrace_provider = provider;
7743 return (0);
7744 }
7745
7746 lck_mtx_lock(&dtrace_provider_lock);
7747 lck_mtx_lock(&dtrace_lock);
7748
7749 /*
7750 * If there is at least one provider registered, we'll add this
7751 * provider after the first provider.
7752 */
7753 if (dtrace_provider != NULL) {
7754 provider->dtpv_next = dtrace_provider->dtpv_next;
7755 dtrace_provider->dtpv_next = provider;
7756 } else {
7757 dtrace_provider = provider;
7758 }
7759
7760 if (dtrace_retained != NULL) {
7761 dtrace_enabling_provide(provider);
7762
7763 /*
7764 * Now we need to call dtrace_enabling_matchall_with_cond() --
7765 * with a condition matching the provider name we just added,
7766 * which will acquire cpu_lock and dtrace_lock. We therefore need
7767 * to drop all of our locks before calling into it...
7768 */
7769 lck_mtx_unlock(&dtrace_lock);
7770 lck_mtx_unlock(&dtrace_provider_lock);
7771
7772 dtrace_match_cond_t cond = {dtrace_cond_provider_match, provider->dtpv_name};
7773 dtrace_enabling_matchall_with_cond(&cond);
7774
7775 return (0);
7776 }
7777
7778 lck_mtx_unlock(&dtrace_lock);
7779 lck_mtx_unlock(&dtrace_provider_lock);
7780
7781 return (0);
7782 }
7783
7784 /*
7785 * Unregister the specified provider from the DTrace framework. This should
7786 * generally be called by DTrace providers in their detach(9E) entry point.
7787 */
7788 int
7789 dtrace_unregister(dtrace_provider_id_t id)
7790 {
7791 dtrace_provider_t *old = (dtrace_provider_t *)id;
7792 dtrace_provider_t *prev = NULL;
7793 int i, self = 0;
7794 dtrace_probe_t *probe, *first = NULL;
7795
7796 if (old->dtpv_pops.dtps_enable ==
7797 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7798 /*
7799 * If DTrace itself is the provider, we're called with locks
7800 * already held.
7801 */
7802 ASSERT(old == dtrace_provider);
7803 ASSERT(dtrace_devi != NULL);
7804 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
7805 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
7806 self = 1;
7807
7808 if (dtrace_provider->dtpv_next != NULL) {
7809 /*
7810 * There's another provider here; return failure.
7811 */
7812 return (EBUSY);
7813 }
7814 } else {
7815 lck_mtx_lock(&dtrace_provider_lock);
7816 lck_mtx_lock(&mod_lock);
7817 lck_mtx_lock(&dtrace_lock);
7818 }
7819
7820 /*
7821 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7822 * probes, we refuse to let providers slither away, unless this
7823 * provider has already been explicitly invalidated.
7824 */
7825 if (!old->dtpv_defunct &&
7826 (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7827 dtrace_anon.dta_state->dts_necbs > 0))) {
7828 if (!self) {
7829 lck_mtx_unlock(&dtrace_lock);
7830 lck_mtx_unlock(&mod_lock);
7831 lck_mtx_unlock(&dtrace_provider_lock);
7832 }
7833 return (EBUSY);
7834 }
7835
7836 /*
7837 * Attempt to destroy the probes associated with this provider.
7838 */
7839 if (old->dtpv_ecb_count!=0) {
7840 /*
7841 * We have at least one ECB; we can't remove this provider.
7842 */
7843 if (!self) {
7844 lck_mtx_unlock(&dtrace_lock);
7845 lck_mtx_unlock(&mod_lock);
7846 lck_mtx_unlock(&dtrace_provider_lock);
7847 }
7848 return (EBUSY);
7849 }
7850
7851 /*
7852 * All of the probes for this provider are disabled; we can safely
7853 * remove all of them from their hash chains and from the probe array.
7854 */
7855 for (i = 0; i < dtrace_nprobes && old->dtpv_probe_count!=0; i++) {
7856 if ((probe = dtrace_probes[i]) == NULL)
7857 continue;
7858
7859 if (probe->dtpr_provider != old)
7860 continue;
7861
7862 dtrace_probes[i] = NULL;
7863 old->dtpv_probe_count--;
7864
7865 dtrace_hash_remove(dtrace_bymod, probe);
7866 dtrace_hash_remove(dtrace_byfunc, probe);
7867 dtrace_hash_remove(dtrace_byname, probe);
7868
7869 if (first == NULL) {
7870 first = probe;
7871 probe->dtpr_nextmod = NULL;
7872 } else {
7873 probe->dtpr_nextmod = first;
7874 first = probe;
7875 }
7876 }
7877
7878 /*
7879 * The provider's probes have been removed from the hash chains and
7880 * from the probe array. Now issue a dtrace_sync() to be sure that
7881 * everyone has cleared out from any probe array processing.
7882 */
7883 dtrace_sync();
7884
7885 for (probe = first; probe != NULL; probe = first) {
7886 first = probe->dtpr_nextmod;
7887
7888 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7889 probe->dtpr_arg);
7890 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7891 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7892 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7893 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7894 zfree(dtrace_probe_t_zone, probe);
7895 }
7896
7897 if ((prev = dtrace_provider) == old) {
7898 ASSERT(self || dtrace_devi == NULL);
7899 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7900 dtrace_provider = old->dtpv_next;
7901 } else {
7902 while (prev != NULL && prev->dtpv_next != old)
7903 prev = prev->dtpv_next;
7904
7905 if (prev == NULL) {
7906 panic("attempt to unregister non-existent "
7907 "dtrace provider %p\n", (void *)id);
7908 }
7909
7910 prev->dtpv_next = old->dtpv_next;
7911 }
7912
7913 if (!self) {
7914 lck_mtx_unlock(&dtrace_lock);
7915 lck_mtx_unlock(&mod_lock);
7916 lck_mtx_unlock(&dtrace_provider_lock);
7917 }
7918
7919 kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7920 kmem_free(old, sizeof (dtrace_provider_t));
7921
7922 return (0);
7923 }
7924
7925 /*
7926 * Invalidate the specified provider. All subsequent probe lookups for the
7927 * specified provider will fail, but its probes will not be removed.
7928 */
7929 void
7930 dtrace_invalidate(dtrace_provider_id_t id)
7931 {
7932 dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7933
7934 ASSERT(pvp->dtpv_pops.dtps_enable !=
7935 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7936
7937 lck_mtx_lock(&dtrace_provider_lock);
7938 lck_mtx_lock(&dtrace_lock);
7939
7940 pvp->dtpv_defunct = 1;
7941
7942 lck_mtx_unlock(&dtrace_lock);
7943 lck_mtx_unlock(&dtrace_provider_lock);
7944 }
7945
7946 /*
7947 * Indicate whether or not DTrace has attached.
7948 */
7949 int
7950 dtrace_attached(void)
7951 {
7952 /*
7953 * dtrace_provider will be non-NULL iff the DTrace driver has
7954 * attached. (It's non-NULL because DTrace is always itself a
7955 * provider.)
7956 */
7957 return (dtrace_provider != NULL);
7958 }
7959
7960 /*
7961 * Remove all the unenabled probes for the given provider. This function is
7962 * not unlike dtrace_unregister(), except that it doesn't remove the provider
7963 * -- just as many of its associated probes as it can.
7964 */
7965 int
7966 dtrace_condense(dtrace_provider_id_t id)
7967 {
7968 dtrace_provider_t *prov = (dtrace_provider_t *)id;
7969 int i;
7970 dtrace_probe_t *probe;
7971
7972 /*
7973 * Make sure this isn't the dtrace provider itself.
7974 */
7975 ASSERT(prov->dtpv_pops.dtps_enable !=
7976 (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7977
7978 lck_mtx_lock(&dtrace_provider_lock);
7979 lck_mtx_lock(&dtrace_lock);
7980
7981 /*
7982 * Attempt to destroy the probes associated with this provider.
7983 */
7984 for (i = 0; i < dtrace_nprobes; i++) {
7985 if ((probe = dtrace_probes[i]) == NULL)
7986 continue;
7987
7988 if (probe->dtpr_provider != prov)
7989 continue;
7990
7991 if (probe->dtpr_ecb != NULL)
7992 continue;
7993
7994 dtrace_probes[i] = NULL;
7995 prov->dtpv_probe_count--;
7996
7997 dtrace_hash_remove(dtrace_bymod, probe);
7998 dtrace_hash_remove(dtrace_byfunc, probe);
7999 dtrace_hash_remove(dtrace_byname, probe);
8000
8001 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8002 probe->dtpr_arg);
8003 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8004 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8005 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8006 zfree(dtrace_probe_t_zone, probe);
8007 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8008 }
8009
8010 lck_mtx_unlock(&dtrace_lock);
8011 lck_mtx_unlock(&dtrace_provider_lock);
8012
8013 return (0);
8014 }
8015
8016 /*
8017 * DTrace Probe Management Functions
8018 *
8019 * The functions in this section perform the DTrace probe management,
8020 * including functions to create probes, look-up probes, and call into the
8021 * providers to request that probes be provided. Some of these functions are
8022 * in the Provider-to-Framework API; these functions can be identified by the
8023 * fact that they are not declared "static".
8024 */
8025
8026 /*
8027 * Create a probe with the specified module name, function name, and name.
8028 */
8029 dtrace_id_t
8030 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8031 const char *func, const char *name, int aframes, void *arg)
8032 {
8033 dtrace_probe_t *probe, **probes;
8034 dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8035 dtrace_id_t id;
8036
8037 if (provider == dtrace_provider) {
8038 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8039 } else {
8040 lck_mtx_lock(&dtrace_lock);
8041 }
8042
8043 id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8044 VM_BESTFIT | VM_SLEEP);
8045
8046 probe = zalloc(dtrace_probe_t_zone);
8047 bzero(probe, sizeof (dtrace_probe_t));
8048
8049 probe->dtpr_id = id;
8050 probe->dtpr_gen = dtrace_probegen++;
8051 probe->dtpr_mod = dtrace_strdup(mod);
8052 probe->dtpr_func = dtrace_strdup(func);
8053 probe->dtpr_name = dtrace_strdup(name);
8054 probe->dtpr_arg = arg;
8055 probe->dtpr_aframes = aframes;
8056 probe->dtpr_provider = provider;
8057
8058 dtrace_hash_add(dtrace_bymod, probe);
8059 dtrace_hash_add(dtrace_byfunc, probe);
8060 dtrace_hash_add(dtrace_byname, probe);
8061
8062 if (id - 1 >= (dtrace_id_t)dtrace_nprobes) {
8063 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8064 size_t nsize = osize << 1;
8065
8066 if (nsize == 0) {
8067 ASSERT(osize == 0);
8068 ASSERT(dtrace_probes == NULL);
8069 nsize = sizeof (dtrace_probe_t *);
8070 }
8071
8072 probes = kmem_zalloc(nsize, KM_SLEEP);
8073
8074 if (dtrace_probes == NULL) {
8075 ASSERT(osize == 0);
8076 dtrace_probes = probes;
8077 dtrace_nprobes = 1;
8078 } else {
8079 dtrace_probe_t **oprobes = dtrace_probes;
8080
8081 bcopy(oprobes, probes, osize);
8082 dtrace_membar_producer();
8083 dtrace_probes = probes;
8084
8085 dtrace_sync();
8086
8087 /*
8088 * All CPUs are now seeing the new probes array; we can
8089 * safely free the old array.
8090 */
8091 kmem_free(oprobes, osize);
8092 dtrace_nprobes <<= 1;
8093 }
8094
8095 ASSERT(id - 1 < (dtrace_id_t)dtrace_nprobes);
8096 }
8097
8098 ASSERT(dtrace_probes[id - 1] == NULL);
8099 dtrace_probes[id - 1] = probe;
8100 provider->dtpv_probe_count++;
8101
8102 if (provider != dtrace_provider)
8103 lck_mtx_unlock(&dtrace_lock);
8104
8105 return (id);
8106 }
8107
8108 static dtrace_probe_t *
8109 dtrace_probe_lookup_id(dtrace_id_t id)
8110 {
8111 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8112
8113 if (id == 0 || id > (dtrace_id_t)dtrace_nprobes)
8114 return (NULL);
8115
8116 return (dtrace_probes[id - 1]);
8117 }
8118
8119 static int
8120 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8121 {
8122 *((dtrace_id_t *)arg) = probe->dtpr_id;
8123
8124 return (DTRACE_MATCH_DONE);
8125 }
8126
8127 /*
8128 * Look up a probe based on provider and one or more of module name, function
8129 * name and probe name.
8130 */
8131 dtrace_id_t
8132 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8133 const char *func, const char *name)
8134 {
8135 dtrace_probekey_t pkey;
8136 dtrace_id_t id;
8137 int match;
8138
8139 pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8140 pkey.dtpk_pmatch = &dtrace_match_string;
8141 pkey.dtpk_mod = mod;
8142 pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8143 pkey.dtpk_func = func;
8144 pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8145 pkey.dtpk_name = name;
8146 pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8147 pkey.dtpk_id = DTRACE_IDNONE;
8148
8149 lck_mtx_lock(&dtrace_lock);
8150 match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8151 dtrace_probe_lookup_match, &id);
8152 lck_mtx_unlock(&dtrace_lock);
8153
8154 ASSERT(match == 1 || match == 0);
8155 return (match ? id : 0);
8156 }
8157
8158 /*
8159 * Returns the probe argument associated with the specified probe.
8160 */
8161 void *
8162 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8163 {
8164 dtrace_probe_t *probe;
8165 void *rval = NULL;
8166
8167 lck_mtx_lock(&dtrace_lock);
8168
8169 if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8170 probe->dtpr_provider == (dtrace_provider_t *)id)
8171 rval = probe->dtpr_arg;
8172
8173 lck_mtx_unlock(&dtrace_lock);
8174
8175 return (rval);
8176 }
8177
8178 /*
8179 * Copy a probe into a probe description.
8180 */
8181 static void
8182 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8183 {
8184 bzero(pdp, sizeof (dtrace_probedesc_t));
8185 pdp->dtpd_id = prp->dtpr_id;
8186
8187 /* APPLE NOTE: Darwin employs size bounded string operation. */
8188 (void) strlcpy(pdp->dtpd_provider,
8189 prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN);
8190
8191 (void) strlcpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN);
8192 (void) strlcpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN);
8193 (void) strlcpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN);
8194 }
8195
8196 /*
8197 * Called to indicate that a probe -- or probes -- should be provided by a
8198 * specfied provider. If the specified description is NULL, the provider will
8199 * be told to provide all of its probes. (This is done whenever a new
8200 * consumer comes along, or whenever a retained enabling is to be matched.) If
8201 * the specified description is non-NULL, the provider is given the
8202 * opportunity to dynamically provide the specified probe, allowing providers
8203 * to support the creation of probes on-the-fly. (So-called _autocreated_
8204 * probes.) If the provider is NULL, the operations will be applied to all
8205 * providers; if the provider is non-NULL the operations will only be applied
8206 * to the specified provider. The dtrace_provider_lock must be held, and the
8207 * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8208 * will need to grab the dtrace_lock when it reenters the framework through
8209 * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8210 */
8211 static void
8212 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8213 {
8214 struct modctl *ctl;
8215 int all = 0;
8216
8217 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
8218
8219 if (prv == NULL) {
8220 all = 1;
8221 prv = dtrace_provider;
8222 }
8223
8224 do {
8225 /*
8226 * First, call the blanket provide operation.
8227 */
8228 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8229
8230 /*
8231 * Now call the per-module provide operation. We will grab
8232 * mod_lock to prevent the list from being modified. Note
8233 * that this also prevents the mod_busy bits from changing.
8234 * (mod_busy can only be changed with mod_lock held.)
8235 */
8236 lck_mtx_lock(&mod_lock);
8237
8238 ctl = dtrace_modctl_list;
8239 while (ctl) {
8240 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8241 ctl = ctl->mod_next;
8242 }
8243
8244 lck_mtx_unlock(&mod_lock);
8245 } while (all && (prv = prv->dtpv_next) != NULL);
8246 }
8247
8248 /*
8249 * Iterate over each probe, and call the Framework-to-Provider API function
8250 * denoted by offs.
8251 */
8252 static void
8253 dtrace_probe_foreach(uintptr_t offs)
8254 {
8255 dtrace_provider_t *prov;
8256 void (*func)(void *, dtrace_id_t, void *);
8257 dtrace_probe_t *probe;
8258 dtrace_icookie_t cookie;
8259 int i;
8260
8261 /*
8262 * We disable interrupts to walk through the probe array. This is
8263 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8264 * won't see stale data.
8265 */
8266 cookie = dtrace_interrupt_disable();
8267
8268 for (i = 0; i < dtrace_nprobes; i++) {
8269 if ((probe = dtrace_probes[i]) == NULL)
8270 continue;
8271
8272 if (probe->dtpr_ecb == NULL) {
8273 /*
8274 * This probe isn't enabled -- don't call the function.
8275 */
8276 continue;
8277 }
8278
8279 prov = probe->dtpr_provider;
8280 func = *((void(**)(void *, dtrace_id_t, void *))
8281 ((uintptr_t)&prov->dtpv_pops + offs));
8282
8283 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8284 }
8285
8286 dtrace_interrupt_enable(cookie);
8287 }
8288
8289 static int
8290 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8291 {
8292 dtrace_probekey_t pkey;
8293 uint32_t priv;
8294 uid_t uid;
8295 zoneid_t zoneid;
8296
8297 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
8298
8299 dtrace_ecb_create_cache = NULL;
8300
8301 if (desc == NULL) {
8302 /*
8303 * If we're passed a NULL description, we're being asked to
8304 * create an ECB with a NULL probe.
8305 */
8306 (void) dtrace_ecb_create_enable(NULL, enab);
8307 return (0);
8308 }
8309
8310 dtrace_probekey(desc, &pkey);
8311 dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8312 &priv, &uid, &zoneid);
8313
8314 return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8315 enab));
8316 }
8317
8318 /*
8319 * DTrace Helper Provider Functions
8320 */
8321 static void
8322 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8323 {
8324 attr->dtat_name = DOF_ATTR_NAME(dofattr);
8325 attr->dtat_data = DOF_ATTR_DATA(dofattr);
8326 attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8327 }
8328
8329 static void
8330 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8331 const dof_provider_t *dofprov, char *strtab)
8332 {
8333 hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8334 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8335 dofprov->dofpv_provattr);
8336 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8337 dofprov->dofpv_modattr);
8338 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8339 dofprov->dofpv_funcattr);
8340 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8341 dofprov->dofpv_nameattr);
8342 dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8343 dofprov->dofpv_argsattr);
8344 }
8345
8346 static void
8347 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8348 {
8349 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8350 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8351 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8352 dof_provider_t *provider;
8353 dof_probe_t *probe;
8354 uint32_t *off, *enoff;
8355 uint8_t *arg;
8356 char *strtab;
8357 uint_t i, nprobes;
8358 dtrace_helper_provdesc_t dhpv;
8359 dtrace_helper_probedesc_t dhpb;
8360 dtrace_meta_t *meta = dtrace_meta_pid;
8361 dtrace_mops_t *mops = &meta->dtm_mops;
8362 void *parg;
8363
8364 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8365 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8366 provider->dofpv_strtab * dof->dofh_secsize);
8367 prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8368 provider->dofpv_probes * dof->dofh_secsize);
8369 arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8370 provider->dofpv_prargs * dof->dofh_secsize);
8371 off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8372 provider->dofpv_proffs * dof->dofh_secsize);
8373
8374 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8375 off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8376 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8377 enoff = NULL;
8378
8379 /*
8380 * See dtrace_helper_provider_validate().
8381 */
8382 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8383 provider->dofpv_prenoffs != DOF_SECT_NONE) {
8384 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8385 provider->dofpv_prenoffs * dof->dofh_secsize);
8386 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8387 }
8388
8389 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8390
8391 /*
8392 * Create the provider.
8393 */
8394 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8395
8396 if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8397 return;
8398
8399 meta->dtm_count++;
8400
8401 /*
8402 * Create the probes.
8403 */
8404 for (i = 0; i < nprobes; i++) {
8405 probe = (dof_probe_t *)(uintptr_t)(daddr +
8406 prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8407
8408 dhpb.dthpb_mod = dhp->dofhp_mod;
8409 dhpb.dthpb_func = strtab + probe->dofpr_func;
8410 dhpb.dthpb_name = strtab + probe->dofpr_name;
8411 #if !defined(__APPLE__)
8412 dhpb.dthpb_base = probe->dofpr_addr;
8413 #else
8414 dhpb.dthpb_base = dhp->dofhp_addr; /* FIXME: James, why? */
8415 #endif
8416 dhpb.dthpb_offs = (int32_t *)(off + probe->dofpr_offidx);
8417 dhpb.dthpb_noffs = probe->dofpr_noffs;
8418 if (enoff != NULL) {
8419 dhpb.dthpb_enoffs = (int32_t *)(enoff + probe->dofpr_enoffidx);
8420 dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8421 } else {
8422 dhpb.dthpb_enoffs = NULL;
8423 dhpb.dthpb_nenoffs = 0;
8424 }
8425 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8426 dhpb.dthpb_nargc = probe->dofpr_nargc;
8427 dhpb.dthpb_xargc = probe->dofpr_xargc;
8428 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8429 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8430
8431 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8432 }
8433
8434 /*
8435 * Since we just created probes, we need to match our enablings
8436 * against those, with a precondition knowing that we have only
8437 * added probes from this provider
8438 */
8439 char *prov_name = mops->dtms_provider_name(parg);
8440 ASSERT(prov_name != NULL);
8441 dtrace_match_cond_t cond = {dtrace_cond_provider_match, (void*)prov_name};
8442
8443 dtrace_enabling_matchall_with_cond(&cond);
8444 }
8445
8446 static void
8447 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8448 {
8449 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8450 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8451 uint32_t i;
8452
8453 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8454
8455 for (i = 0; i < dof->dofh_secnum; i++) {
8456 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8457 dof->dofh_secoff + i * dof->dofh_secsize);
8458
8459 if (sec->dofs_type != DOF_SECT_PROVIDER)
8460 continue;
8461
8462 dtrace_helper_provide_one(dhp, sec, pid);
8463 }
8464 }
8465
8466 static void
8467 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8468 {
8469 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8470 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8471 dof_sec_t *str_sec;
8472 dof_provider_t *provider;
8473 char *strtab;
8474 dtrace_helper_provdesc_t dhpv;
8475 dtrace_meta_t *meta = dtrace_meta_pid;
8476 dtrace_mops_t *mops = &meta->dtm_mops;
8477
8478 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8479 str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8480 provider->dofpv_strtab * dof->dofh_secsize);
8481
8482 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8483
8484 /*
8485 * Create the provider.
8486 */
8487 dtrace_dofprov2hprov(&dhpv, provider, strtab);
8488
8489 mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8490
8491 meta->dtm_count--;
8492 }
8493
8494 static void
8495 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8496 {
8497 uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8498 dof_hdr_t *dof = (dof_hdr_t *)daddr;
8499 uint32_t i;
8500
8501 lck_mtx_assert(&dtrace_meta_lock, LCK_MTX_ASSERT_OWNED);
8502
8503 for (i = 0; i < dof->dofh_secnum; i++) {
8504 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8505 dof->dofh_secoff + i * dof->dofh_secsize);
8506
8507 if (sec->dofs_type != DOF_SECT_PROVIDER)
8508 continue;
8509
8510 dtrace_helper_provider_remove_one(dhp, sec, pid);
8511 }
8512 }
8513
8514 /*
8515 * DTrace Meta Provider-to-Framework API Functions
8516 *
8517 * These functions implement the Meta Provider-to-Framework API, as described
8518 * in <sys/dtrace.h>.
8519 */
8520 int
8521 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8522 dtrace_meta_provider_id_t *idp)
8523 {
8524 dtrace_meta_t *meta;
8525 dtrace_helpers_t *help, *next;
8526 uint_t i;
8527
8528 *idp = DTRACE_METAPROVNONE;
8529
8530 /*
8531 * We strictly don't need the name, but we hold onto it for
8532 * debuggability. All hail error queues!
8533 */
8534 if (name == NULL) {
8535 cmn_err(CE_WARN, "failed to register meta-provider: "
8536 "invalid name");
8537 return (EINVAL);
8538 }
8539
8540 if (mops == NULL ||
8541 mops->dtms_create_probe == NULL ||
8542 mops->dtms_provide_pid == NULL ||
8543 mops->dtms_remove_pid == NULL) {
8544 cmn_err(CE_WARN, "failed to register meta-register %s: "
8545 "invalid ops", name);
8546 return (EINVAL);
8547 }
8548
8549 meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8550 meta->dtm_mops = *mops;
8551
8552 /* APPLE NOTE: Darwin employs size bounded string operation. */
8553 {
8554 size_t bufsize = strlen(name) + 1;
8555 meta->dtm_name = kmem_alloc(bufsize, KM_SLEEP);
8556 (void) strlcpy(meta->dtm_name, name, bufsize);
8557 }
8558
8559 meta->dtm_arg = arg;
8560
8561 lck_mtx_lock(&dtrace_meta_lock);
8562 lck_mtx_lock(&dtrace_lock);
8563
8564 if (dtrace_meta_pid != NULL) {
8565 lck_mtx_unlock(&dtrace_lock);
8566 lck_mtx_unlock(&dtrace_meta_lock);
8567 cmn_err(CE_WARN, "failed to register meta-register %s: "
8568 "user-land meta-provider exists", name);
8569 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8570 kmem_free(meta, sizeof (dtrace_meta_t));
8571 return (EINVAL);
8572 }
8573
8574 dtrace_meta_pid = meta;
8575 *idp = (dtrace_meta_provider_id_t)meta;
8576
8577 /*
8578 * If there are providers and probes ready to go, pass them
8579 * off to the new meta provider now.
8580 */
8581
8582 help = dtrace_deferred_pid;
8583 dtrace_deferred_pid = NULL;
8584
8585 lck_mtx_unlock(&dtrace_lock);
8586
8587 while (help != NULL) {
8588 for (i = 0; i < help->dthps_nprovs; i++) {
8589 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8590 help->dthps_pid);
8591 }
8592
8593 next = help->dthps_next;
8594 help->dthps_next = NULL;
8595 help->dthps_prev = NULL;
8596 help->dthps_deferred = 0;
8597 help = next;
8598 }
8599
8600 lck_mtx_unlock(&dtrace_meta_lock);
8601
8602 return (0);
8603 }
8604
8605 int
8606 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8607 {
8608 dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8609
8610 lck_mtx_lock(&dtrace_meta_lock);
8611 lck_mtx_lock(&dtrace_lock);
8612
8613 if (old == dtrace_meta_pid) {
8614 pp = &dtrace_meta_pid;
8615 } else {
8616 panic("attempt to unregister non-existent "
8617 "dtrace meta-provider %p\n", (void *)old);
8618 }
8619
8620 if (old->dtm_count != 0) {
8621 lck_mtx_unlock(&dtrace_lock);
8622 lck_mtx_unlock(&dtrace_meta_lock);
8623 return (EBUSY);
8624 }
8625
8626 *pp = NULL;
8627
8628 lck_mtx_unlock(&dtrace_lock);
8629 lck_mtx_unlock(&dtrace_meta_lock);
8630
8631 kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8632 kmem_free(old, sizeof (dtrace_meta_t));
8633
8634 return (0);
8635 }
8636
8637
8638 /*
8639 * DTrace DIF Object Functions
8640 */
8641 static int
8642 dtrace_difo_err(uint_t pc, const char *format, ...)
8643 {
8644 if (dtrace_err_verbose) {
8645 va_list alist;
8646
8647 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8648 va_start(alist, format);
8649 (void) vuprintf(format, alist);
8650 va_end(alist);
8651 }
8652
8653 #ifdef DTRACE_ERRDEBUG
8654 dtrace_errdebug(format);
8655 #endif
8656 return (1);
8657 }
8658
8659 /*
8660 * Validate a DTrace DIF object by checking the IR instructions. The following
8661 * rules are currently enforced by dtrace_difo_validate():
8662 *
8663 * 1. Each instruction must have a valid opcode
8664 * 2. Each register, string, variable, or subroutine reference must be valid
8665 * 3. No instruction can modify register %r0 (must be zero)
8666 * 4. All instruction reserved bits must be set to zero
8667 * 5. The last instruction must be a "ret" instruction
8668 * 6. All branch targets must reference a valid instruction _after_ the branch
8669 */
8670 static int
8671 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8672 cred_t *cr)
8673 {
8674 int err = 0;
8675 uint_t i;
8676
8677 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8678 int kcheckload;
8679 uint_t pc;
8680 int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
8681
8682 kcheckload = cr == NULL ||
8683 (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8684
8685 dp->dtdo_destructive = 0;
8686
8687 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8688 dif_instr_t instr = dp->dtdo_buf[pc];
8689
8690 uint_t r1 = DIF_INSTR_R1(instr);
8691 uint_t r2 = DIF_INSTR_R2(instr);
8692 uint_t rd = DIF_INSTR_RD(instr);
8693 uint_t rs = DIF_INSTR_RS(instr);
8694 uint_t label = DIF_INSTR_LABEL(instr);
8695 uint_t v = DIF_INSTR_VAR(instr);
8696 uint_t subr = DIF_INSTR_SUBR(instr);
8697 uint_t type = DIF_INSTR_TYPE(instr);
8698 uint_t op = DIF_INSTR_OP(instr);
8699
8700 switch (op) {
8701 case DIF_OP_OR:
8702 case DIF_OP_XOR:
8703 case DIF_OP_AND:
8704 case DIF_OP_SLL:
8705 case DIF_OP_SRL:
8706 case DIF_OP_SRA:
8707 case DIF_OP_SUB:
8708 case DIF_OP_ADD:
8709 case DIF_OP_MUL:
8710 case DIF_OP_SDIV:
8711 case DIF_OP_UDIV:
8712 case DIF_OP_SREM:
8713 case DIF_OP_UREM:
8714 case DIF_OP_COPYS:
8715 if (r1 >= nregs)
8716 err += efunc(pc, "invalid register %u\n", r1);
8717 if (r2 >= nregs)
8718 err += efunc(pc, "invalid register %u\n", r2);
8719 if (rd >= nregs)
8720 err += efunc(pc, "invalid register %u\n", rd);
8721 if (rd == 0)
8722 err += efunc(pc, "cannot write to %r0\n");
8723 break;
8724 case DIF_OP_NOT:
8725 case DIF_OP_MOV:
8726 case DIF_OP_ALLOCS:
8727 if (r1 >= nregs)
8728 err += efunc(pc, "invalid register %u\n", r1);
8729 if (r2 != 0)
8730 err += efunc(pc, "non-zero reserved bits\n");
8731 if (rd >= nregs)
8732 err += efunc(pc, "invalid register %u\n", rd);
8733 if (rd == 0)
8734 err += efunc(pc, "cannot write to %r0\n");
8735 break;
8736 case DIF_OP_LDSB:
8737 case DIF_OP_LDSH:
8738 case DIF_OP_LDSW:
8739 case DIF_OP_LDUB:
8740 case DIF_OP_LDUH:
8741 case DIF_OP_LDUW:
8742 case DIF_OP_LDX:
8743 if (r1 >= nregs)
8744 err += efunc(pc, "invalid register %u\n", r1);
8745 if (r2 != 0)
8746 err += efunc(pc, "non-zero reserved bits\n");
8747 if (rd >= nregs)
8748 err += efunc(pc, "invalid register %u\n", rd);
8749 if (rd == 0)
8750 err += efunc(pc, "cannot write to %r0\n");
8751 if (kcheckload)
8752 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8753 DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8754 break;
8755 case DIF_OP_RLDSB:
8756 case DIF_OP_RLDSH:
8757 case DIF_OP_RLDSW:
8758 case DIF_OP_RLDUB:
8759 case DIF_OP_RLDUH:
8760 case DIF_OP_RLDUW:
8761 case DIF_OP_RLDX:
8762 if (r1 >= nregs)
8763 err += efunc(pc, "invalid register %u\n", r1);
8764 if (r2 != 0)
8765 err += efunc(pc, "non-zero reserved bits\n");
8766 if (rd >= nregs)
8767 err += efunc(pc, "invalid register %u\n", rd);
8768 if (rd == 0)
8769 err += efunc(pc, "cannot write to %r0\n");
8770 break;
8771 case DIF_OP_ULDSB:
8772 case DIF_OP_ULDSH:
8773 case DIF_OP_ULDSW:
8774 case DIF_OP_ULDUB:
8775 case DIF_OP_ULDUH:
8776 case DIF_OP_ULDUW:
8777 case DIF_OP_ULDX:
8778 if (r1 >= nregs)
8779 err += efunc(pc, "invalid register %u\n", r1);
8780 if (r2 != 0)
8781 err += efunc(pc, "non-zero reserved bits\n");
8782 if (rd >= nregs)
8783 err += efunc(pc, "invalid register %u\n", rd);
8784 if (rd == 0)
8785 err += efunc(pc, "cannot write to %r0\n");
8786 break;
8787 case DIF_OP_STB:
8788 case DIF_OP_STH:
8789 case DIF_OP_STW:
8790 case DIF_OP_STX:
8791 if (r1 >= nregs)
8792 err += efunc(pc, "invalid register %u\n", r1);
8793 if (r2 != 0)
8794 err += efunc(pc, "non-zero reserved bits\n");
8795 if (rd >= nregs)
8796 err += efunc(pc, "invalid register %u\n", rd);
8797 if (rd == 0)
8798 err += efunc(pc, "cannot write to 0 address\n");
8799 break;
8800 case DIF_OP_CMP:
8801 case DIF_OP_SCMP:
8802 if (r1 >= nregs)
8803 err += efunc(pc, "invalid register %u\n", r1);
8804 if (r2 >= nregs)
8805 err += efunc(pc, "invalid register %u\n", r2);
8806 if (rd != 0)
8807 err += efunc(pc, "non-zero reserved bits\n");
8808 break;
8809 case DIF_OP_TST:
8810 if (r1 >= nregs)
8811 err += efunc(pc, "invalid register %u\n", r1);
8812 if (r2 != 0 || rd != 0)
8813 err += efunc(pc, "non-zero reserved bits\n");
8814 break;
8815 case DIF_OP_BA:
8816 case DIF_OP_BE:
8817 case DIF_OP_BNE:
8818 case DIF_OP_BG:
8819 case DIF_OP_BGU:
8820 case DIF_OP_BGE:
8821 case DIF_OP_BGEU:
8822 case DIF_OP_BL:
8823 case DIF_OP_BLU:
8824 case DIF_OP_BLE:
8825 case DIF_OP_BLEU:
8826 if (label >= dp->dtdo_len) {
8827 err += efunc(pc, "invalid branch target %u\n",
8828 label);
8829 }
8830 if (label <= pc) {
8831 err += efunc(pc, "backward branch to %u\n",
8832 label);
8833 }
8834 break;
8835 case DIF_OP_RET:
8836 if (r1 != 0 || r2 != 0)
8837 err += efunc(pc, "non-zero reserved bits\n");
8838 if (rd >= nregs)
8839 err += efunc(pc, "invalid register %u\n", rd);
8840 break;
8841 case DIF_OP_NOP:
8842 case DIF_OP_POPTS:
8843 case DIF_OP_FLUSHTS:
8844 if (r1 != 0 || r2 != 0 || rd != 0)
8845 err += efunc(pc, "non-zero reserved bits\n");
8846 break;
8847 case DIF_OP_SETX:
8848 if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8849 err += efunc(pc, "invalid integer ref %u\n",
8850 DIF_INSTR_INTEGER(instr));
8851 }
8852 if (rd >= nregs)
8853 err += efunc(pc, "invalid register %u\n", rd);
8854 if (rd == 0)
8855 err += efunc(pc, "cannot write to %r0\n");
8856 break;
8857 case DIF_OP_SETS:
8858 if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8859 err += efunc(pc, "invalid string ref %u\n",
8860 DIF_INSTR_STRING(instr));
8861 }
8862 if (rd >= nregs)
8863 err += efunc(pc, "invalid register %u\n", rd);
8864 if (rd == 0)
8865 err += efunc(pc, "cannot write to %r0\n");
8866 break;
8867 case DIF_OP_LDGA:
8868 case DIF_OP_LDTA:
8869 if (r1 > DIF_VAR_ARRAY_MAX)
8870 err += efunc(pc, "invalid array %u\n", r1);
8871 if (r2 >= nregs)
8872 err += efunc(pc, "invalid register %u\n", r2);
8873 if (rd >= nregs)
8874 err += efunc(pc, "invalid register %u\n", rd);
8875 if (rd == 0)
8876 err += efunc(pc, "cannot write to %r0\n");
8877 break;
8878 case DIF_OP_LDGS:
8879 case DIF_OP_LDTS:
8880 case DIF_OP_LDLS:
8881 case DIF_OP_LDGAA:
8882 case DIF_OP_LDTAA:
8883 if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8884 err += efunc(pc, "invalid variable %u\n", v);
8885 if (rd >= nregs)
8886 err += efunc(pc, "invalid register %u\n", rd);
8887 if (rd == 0)
8888 err += efunc(pc, "cannot write to %r0\n");
8889 break;
8890 case DIF_OP_STGS:
8891 case DIF_OP_STTS:
8892 case DIF_OP_STLS:
8893 case DIF_OP_STGAA:
8894 case DIF_OP_STTAA:
8895 if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8896 err += efunc(pc, "invalid variable %u\n", v);
8897 if (rs >= nregs)
8898 err += efunc(pc, "invalid register %u\n", rd);
8899 break;
8900 case DIF_OP_CALL:
8901 if (subr > DIF_SUBR_MAX &&
8902 !(subr >= DIF_SUBR_APPLE_MIN && subr <= DIF_SUBR_APPLE_MAX))
8903 err += efunc(pc, "invalid subr %u\n", subr);
8904 if (rd >= nregs)
8905 err += efunc(pc, "invalid register %u\n", rd);
8906 if (rd == 0)
8907 err += efunc(pc, "cannot write to %r0\n");
8908
8909 if (subr == DIF_SUBR_COPYOUT ||
8910 subr == DIF_SUBR_COPYOUTSTR ||
8911 subr == DIF_SUBR_KDEBUG_TRACE ||
8912 subr == DIF_SUBR_KDEBUG_TRACE_STRING) {
8913 dp->dtdo_destructive = 1;
8914 }
8915 break;
8916 case DIF_OP_PUSHTR:
8917 if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8918 err += efunc(pc, "invalid ref type %u\n", type);
8919 if (r2 >= nregs)
8920 err += efunc(pc, "invalid register %u\n", r2);
8921 if (rs >= nregs)
8922 err += efunc(pc, "invalid register %u\n", rs);
8923 break;
8924 case DIF_OP_PUSHTV:
8925 if (type != DIF_TYPE_CTF)
8926 err += efunc(pc, "invalid val type %u\n", type);
8927 if (r2 >= nregs)
8928 err += efunc(pc, "invalid register %u\n", r2);
8929 if (rs >= nregs)
8930 err += efunc(pc, "invalid register %u\n", rs);
8931 break;
8932 default:
8933 err += efunc(pc, "invalid opcode %u\n",
8934 DIF_INSTR_OP(instr));
8935 }
8936 }
8937
8938 if (dp->dtdo_len != 0 &&
8939 DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8940 err += efunc(dp->dtdo_len - 1,
8941 "expected 'ret' as last DIF instruction\n");
8942 }
8943
8944 if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
8945 /*
8946 * If we're not returning by reference, the size must be either
8947 * 0 or the size of one of the base types.
8948 */
8949 switch (dp->dtdo_rtype.dtdt_size) {
8950 case 0:
8951 case sizeof (uint8_t):
8952 case sizeof (uint16_t):
8953 case sizeof (uint32_t):
8954 case sizeof (uint64_t):
8955 break;
8956
8957 default:
8958 err += efunc(dp->dtdo_len - 1, "bad return size\n");
8959 }
8960 }
8961
8962 for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8963 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8964 dtrace_diftype_t *vt, *et;
8965 uint_t id;
8966 int ndx;
8967
8968 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8969 v->dtdv_scope != DIFV_SCOPE_THREAD &&
8970 v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8971 err += efunc(i, "unrecognized variable scope %d\n",
8972 v->dtdv_scope);
8973 break;
8974 }
8975
8976 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8977 v->dtdv_kind != DIFV_KIND_SCALAR) {
8978 err += efunc(i, "unrecognized variable type %d\n",
8979 v->dtdv_kind);
8980 break;
8981 }
8982
8983 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8984 err += efunc(i, "%d exceeds variable id limit\n", id);
8985 break;
8986 }
8987
8988 if (id < DIF_VAR_OTHER_UBASE)
8989 continue;
8990
8991 /*
8992 * For user-defined variables, we need to check that this
8993 * definition is identical to any previous definition that we
8994 * encountered.
8995 */
8996 ndx = id - DIF_VAR_OTHER_UBASE;
8997
8998 switch (v->dtdv_scope) {
8999 case DIFV_SCOPE_GLOBAL:
9000 if (maxglobal == -1 || ndx > maxglobal)
9001 maxglobal = ndx;
9002
9003 if (ndx < vstate->dtvs_nglobals) {
9004 dtrace_statvar_t *svar;
9005
9006 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9007 existing = &svar->dtsv_var;
9008 }
9009
9010 break;
9011
9012 case DIFV_SCOPE_THREAD:
9013 if (maxtlocal == -1 || ndx > maxtlocal)
9014 maxtlocal = ndx;
9015
9016 if (ndx < vstate->dtvs_ntlocals)
9017 existing = &vstate->dtvs_tlocals[ndx];
9018 break;
9019
9020 case DIFV_SCOPE_LOCAL:
9021 if (maxlocal == -1 || ndx > maxlocal)
9022 maxlocal = ndx;
9023 if (ndx < vstate->dtvs_nlocals) {
9024 dtrace_statvar_t *svar;
9025
9026 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9027 existing = &svar->dtsv_var;
9028 }
9029
9030 break;
9031 }
9032
9033 vt = &v->dtdv_type;
9034
9035 if (vt->dtdt_flags & DIF_TF_BYREF) {
9036 if (vt->dtdt_size == 0) {
9037 err += efunc(i, "zero-sized variable\n");
9038 break;
9039 }
9040
9041 if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9042 v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9043 vt->dtdt_size > dtrace_statvar_maxsize) {
9044 err += efunc(i, "oversized by-ref static\n");
9045 break;
9046 }
9047 }
9048
9049 if (existing == NULL || existing->dtdv_id == 0)
9050 continue;
9051
9052 ASSERT(existing->dtdv_id == v->dtdv_id);
9053 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9054
9055 if (existing->dtdv_kind != v->dtdv_kind)
9056 err += efunc(i, "%d changed variable kind\n", id);
9057
9058 et = &existing->dtdv_type;
9059
9060 if (vt->dtdt_flags != et->dtdt_flags) {
9061 err += efunc(i, "%d changed variable type flags\n", id);
9062 break;
9063 }
9064
9065 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9066 err += efunc(i, "%d changed variable type size\n", id);
9067 break;
9068 }
9069 }
9070
9071 for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9072 dif_instr_t instr = dp->dtdo_buf[pc];
9073
9074 uint_t v = DIF_INSTR_VAR(instr);
9075 uint_t op = DIF_INSTR_OP(instr);
9076
9077 switch (op) {
9078 case DIF_OP_LDGS:
9079 case DIF_OP_LDGAA:
9080 case DIF_OP_STGS:
9081 case DIF_OP_STGAA:
9082 if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxglobal))
9083 err += efunc(pc, "invalid variable %u\n", v);
9084 break;
9085 case DIF_OP_LDTS:
9086 case DIF_OP_LDTAA:
9087 case DIF_OP_STTS:
9088 case DIF_OP_STTAA:
9089 if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxtlocal))
9090 err += efunc(pc, "invalid variable %u\n", v);
9091 break;
9092 case DIF_OP_LDLS:
9093 case DIF_OP_STLS:
9094 if (v > (uint_t)(DIF_VAR_OTHER_UBASE + maxlocal))
9095 err += efunc(pc, "invalid variable %u\n", v);
9096 break;
9097 default:
9098 break;
9099 }
9100 }
9101
9102 return (err);
9103 }
9104
9105 /*
9106 * Validate a DTrace DIF object that it is to be used as a helper. Helpers
9107 * are much more constrained than normal DIFOs. Specifically, they may
9108 * not:
9109 *
9110 * 1. Make calls to subroutines other than copyin(), copyinstr() or
9111 * miscellaneous string routines
9112 * 2. Access DTrace variables other than the args[] array, and the
9113 * curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9114 * 3. Have thread-local variables.
9115 * 4. Have dynamic variables.
9116 */
9117 static int
9118 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9119 {
9120 int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9121 int err = 0;
9122 uint_t pc;
9123
9124 for (pc = 0; pc < dp->dtdo_len; pc++) {
9125 dif_instr_t instr = dp->dtdo_buf[pc];
9126
9127 uint_t v = DIF_INSTR_VAR(instr);
9128 uint_t subr = DIF_INSTR_SUBR(instr);
9129 uint_t op = DIF_INSTR_OP(instr);
9130
9131 switch (op) {
9132 case DIF_OP_OR:
9133 case DIF_OP_XOR:
9134 case DIF_OP_AND:
9135 case DIF_OP_SLL:
9136 case DIF_OP_SRL:
9137 case DIF_OP_SRA:
9138 case DIF_OP_SUB:
9139 case DIF_OP_ADD:
9140 case DIF_OP_MUL:
9141 case DIF_OP_SDIV:
9142 case DIF_OP_UDIV:
9143 case DIF_OP_SREM:
9144 case DIF_OP_UREM:
9145 case DIF_OP_COPYS:
9146 case DIF_OP_NOT:
9147 case DIF_OP_MOV:
9148 case DIF_OP_RLDSB:
9149 case DIF_OP_RLDSH:
9150 case DIF_OP_RLDSW:
9151 case DIF_OP_RLDUB:
9152 case DIF_OP_RLDUH:
9153 case DIF_OP_RLDUW:
9154 case DIF_OP_RLDX:
9155 case DIF_OP_ULDSB:
9156 case DIF_OP_ULDSH:
9157 case DIF_OP_ULDSW:
9158 case DIF_OP_ULDUB:
9159 case DIF_OP_ULDUH:
9160 case DIF_OP_ULDUW:
9161 case DIF_OP_ULDX:
9162 case DIF_OP_STB:
9163 case DIF_OP_STH:
9164 case DIF_OP_STW:
9165 case DIF_OP_STX:
9166 case DIF_OP_ALLOCS:
9167 case DIF_OP_CMP:
9168 case DIF_OP_SCMP:
9169 case DIF_OP_TST:
9170 case DIF_OP_BA:
9171 case DIF_OP_BE:
9172 case DIF_OP_BNE:
9173 case DIF_OP_BG:
9174 case DIF_OP_BGU:
9175 case DIF_OP_BGE:
9176 case DIF_OP_BGEU:
9177 case DIF_OP_BL:
9178 case DIF_OP_BLU:
9179 case DIF_OP_BLE:
9180 case DIF_OP_BLEU:
9181 case DIF_OP_RET:
9182 case DIF_OP_NOP:
9183 case DIF_OP_POPTS:
9184 case DIF_OP_FLUSHTS:
9185 case DIF_OP_SETX:
9186 case DIF_OP_SETS:
9187 case DIF_OP_LDGA:
9188 case DIF_OP_LDLS:
9189 case DIF_OP_STGS:
9190 case DIF_OP_STLS:
9191 case DIF_OP_PUSHTR:
9192 case DIF_OP_PUSHTV:
9193 break;
9194
9195 case DIF_OP_LDGS:
9196 if (v >= DIF_VAR_OTHER_UBASE)
9197 break;
9198
9199 if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9200 break;
9201
9202 if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9203 v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9204 v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9205 v == DIF_VAR_UID || v == DIF_VAR_GID)
9206 break;
9207
9208 err += efunc(pc, "illegal variable %u\n", v);
9209 break;
9210
9211 case DIF_OP_LDTA:
9212 case DIF_OP_LDTS:
9213 case DIF_OP_LDGAA:
9214 case DIF_OP_LDTAA:
9215 err += efunc(pc, "illegal dynamic variable load\n");
9216 break;
9217
9218 case DIF_OP_STTS:
9219 case DIF_OP_STGAA:
9220 case DIF_OP_STTAA:
9221 err += efunc(pc, "illegal dynamic variable store\n");
9222 break;
9223
9224 case DIF_OP_CALL:
9225 if (subr == DIF_SUBR_ALLOCA ||
9226 subr == DIF_SUBR_BCOPY ||
9227 subr == DIF_SUBR_COPYIN ||
9228 subr == DIF_SUBR_COPYINTO ||
9229 subr == DIF_SUBR_COPYINSTR ||
9230 subr == DIF_SUBR_INDEX ||
9231 subr == DIF_SUBR_INET_NTOA ||
9232 subr == DIF_SUBR_INET_NTOA6 ||
9233 subr == DIF_SUBR_INET_NTOP ||
9234 subr == DIF_SUBR_LLTOSTR ||
9235 subr == DIF_SUBR_RINDEX ||
9236 subr == DIF_SUBR_STRCHR ||
9237 subr == DIF_SUBR_STRJOIN ||
9238 subr == DIF_SUBR_STRRCHR ||
9239 subr == DIF_SUBR_STRSTR ||
9240 subr == DIF_SUBR_KDEBUG_TRACE ||
9241 subr == DIF_SUBR_KDEBUG_TRACE_STRING ||
9242 subr == DIF_SUBR_HTONS ||
9243 subr == DIF_SUBR_HTONL ||
9244 subr == DIF_SUBR_HTONLL ||
9245 subr == DIF_SUBR_NTOHS ||
9246 subr == DIF_SUBR_NTOHL ||
9247 subr == DIF_SUBR_NTOHLL)
9248 break;
9249
9250 err += efunc(pc, "invalid subr %u\n", subr);
9251 break;
9252
9253 default:
9254 err += efunc(pc, "invalid opcode %u\n",
9255 DIF_INSTR_OP(instr));
9256 }
9257 }
9258
9259 return (err);
9260 }
9261
9262 /*
9263 * Returns 1 if the expression in the DIF object can be cached on a per-thread
9264 * basis; 0 if not.
9265 */
9266 static int
9267 dtrace_difo_cacheable(dtrace_difo_t *dp)
9268 {
9269 uint_t i;
9270
9271 if (dp == NULL)
9272 return (0);
9273
9274 for (i = 0; i < dp->dtdo_varlen; i++) {
9275 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9276
9277 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9278 continue;
9279
9280 switch (v->dtdv_id) {
9281 case DIF_VAR_CURTHREAD:
9282 case DIF_VAR_PID:
9283 case DIF_VAR_TID:
9284 case DIF_VAR_EXECNAME:
9285 case DIF_VAR_ZONENAME:
9286 break;
9287
9288 default:
9289 return (0);
9290 }
9291 }
9292
9293 /*
9294 * This DIF object may be cacheable. Now we need to look for any
9295 * array loading instructions, any memory loading instructions, or
9296 * any stores to thread-local variables.
9297 */
9298 for (i = 0; i < dp->dtdo_len; i++) {
9299 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9300
9301 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9302 (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9303 (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9304 op == DIF_OP_LDGA || op == DIF_OP_STTS)
9305 return (0);
9306 }
9307
9308 return (1);
9309 }
9310
9311 static void
9312 dtrace_difo_hold(dtrace_difo_t *dp)
9313 {
9314 uint_t i;
9315
9316 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9317
9318 dp->dtdo_refcnt++;
9319 ASSERT(dp->dtdo_refcnt != 0);
9320
9321 /*
9322 * We need to check this DIF object for references to the variable
9323 * DIF_VAR_VTIMESTAMP.
9324 */
9325 for (i = 0; i < dp->dtdo_varlen; i++) {
9326 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9327
9328 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9329 continue;
9330
9331 if (dtrace_vtime_references++ == 0)
9332 dtrace_vtime_enable();
9333 }
9334 }
9335
9336 /*
9337 * This routine calculates the dynamic variable chunksize for a given DIF
9338 * object. The calculation is not fool-proof, and can probably be tricked by
9339 * malicious DIF -- but it works for all compiler-generated DIF. Because this
9340 * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9341 * if a dynamic variable size exceeds the chunksize.
9342 */
9343 static void
9344 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9345 {
9346 uint64_t sval = 0;
9347 dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9348 const dif_instr_t *text = dp->dtdo_buf;
9349 uint_t pc, srd = 0;
9350 uint_t ttop = 0;
9351 size_t size, ksize;
9352 uint_t id, i;
9353
9354 for (pc = 0; pc < dp->dtdo_len; pc++) {
9355 dif_instr_t instr = text[pc];
9356 uint_t op = DIF_INSTR_OP(instr);
9357 uint_t rd = DIF_INSTR_RD(instr);
9358 uint_t r1 = DIF_INSTR_R1(instr);
9359 uint_t nkeys = 0;
9360 uchar_t scope;
9361
9362 dtrace_key_t *key = tupregs;
9363
9364 switch (op) {
9365 case DIF_OP_SETX:
9366 sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9367 srd = rd;
9368 continue;
9369
9370 case DIF_OP_STTS:
9371 key = &tupregs[DIF_DTR_NREGS];
9372 key[0].dttk_size = 0;
9373 key[1].dttk_size = 0;
9374 nkeys = 2;
9375 scope = DIFV_SCOPE_THREAD;
9376 break;
9377
9378 case DIF_OP_STGAA:
9379 case DIF_OP_STTAA:
9380 nkeys = ttop;
9381
9382 if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9383 key[nkeys++].dttk_size = 0;
9384
9385 key[nkeys++].dttk_size = 0;
9386
9387 if (op == DIF_OP_STTAA) {
9388 scope = DIFV_SCOPE_THREAD;
9389 } else {
9390 scope = DIFV_SCOPE_GLOBAL;
9391 }
9392
9393 break;
9394
9395 case DIF_OP_PUSHTR:
9396 if (ttop == DIF_DTR_NREGS)
9397 return;
9398
9399 if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9400 /*
9401 * If the register for the size of the "pushtr"
9402 * is %r0 (or the value is 0) and the type is
9403 * a string, we'll use the system-wide default
9404 * string size.
9405 */
9406 tupregs[ttop++].dttk_size =
9407 dtrace_strsize_default;
9408 } else {
9409 if (srd == 0)
9410 return;
9411
9412 if (sval > LONG_MAX)
9413 return;
9414
9415 tupregs[ttop++].dttk_size = sval;
9416 }
9417
9418 break;
9419
9420 case DIF_OP_PUSHTV:
9421 if (ttop == DIF_DTR_NREGS)
9422 return;
9423
9424 tupregs[ttop++].dttk_size = 0;
9425 break;
9426
9427 case DIF_OP_FLUSHTS:
9428 ttop = 0;
9429 break;
9430
9431 case DIF_OP_POPTS:
9432 if (ttop != 0)
9433 ttop--;
9434 break;
9435 }
9436
9437 sval = 0;
9438 srd = 0;
9439
9440 if (nkeys == 0)
9441 continue;
9442
9443 /*
9444 * We have a dynamic variable allocation; calculate its size.
9445 */
9446 for (ksize = 0, i = 0; i < nkeys; i++)
9447 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9448
9449 size = sizeof (dtrace_dynvar_t);
9450 size += sizeof (dtrace_key_t) * (nkeys - 1);
9451 size += ksize;
9452
9453 /*
9454 * Now we need to determine the size of the stored data.
9455 */
9456 id = DIF_INSTR_VAR(instr);
9457
9458 for (i = 0; i < dp->dtdo_varlen; i++) {
9459 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9460
9461 if (v->dtdv_id == id && v->dtdv_scope == scope) {
9462 size += v->dtdv_type.dtdt_size;
9463 break;
9464 }
9465 }
9466
9467 if (i == dp->dtdo_varlen)
9468 return;
9469
9470 /*
9471 * We have the size. If this is larger than the chunk size
9472 * for our dynamic variable state, reset the chunk size.
9473 */
9474 size = P2ROUNDUP(size, sizeof (uint64_t));
9475
9476 /*
9477 * Before setting the chunk size, check that we're not going
9478 * to set it to a negative value...
9479 */
9480 if (size > LONG_MAX)
9481 return;
9482
9483 /*
9484 * ...and make certain that we didn't badly overflow.
9485 */
9486 if (size < ksize || size < sizeof (dtrace_dynvar_t))
9487 return;
9488
9489 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9490 vstate->dtvs_dynvars.dtds_chunksize = size;
9491 }
9492 }
9493
9494 static void
9495 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9496 {
9497 int oldsvars, osz, nsz, otlocals, ntlocals;
9498 uint_t i, id;
9499
9500 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9501 ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9502
9503 for (i = 0; i < dp->dtdo_varlen; i++) {
9504 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9505 dtrace_statvar_t *svar;
9506 dtrace_statvar_t ***svarp = NULL;
9507 size_t dsize = 0;
9508 uint8_t scope = v->dtdv_scope;
9509 int *np = (int *)NULL;
9510
9511 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9512 continue;
9513
9514 id -= DIF_VAR_OTHER_UBASE;
9515
9516 switch (scope) {
9517 case DIFV_SCOPE_THREAD:
9518 while (id >= (uint_t)(otlocals = vstate->dtvs_ntlocals)) {
9519 dtrace_difv_t *tlocals;
9520
9521 if ((ntlocals = (otlocals << 1)) == 0)
9522 ntlocals = 1;
9523
9524 osz = otlocals * sizeof (dtrace_difv_t);
9525 nsz = ntlocals * sizeof (dtrace_difv_t);
9526
9527 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9528
9529 if (osz != 0) {
9530 bcopy(vstate->dtvs_tlocals,
9531 tlocals, osz);
9532 kmem_free(vstate->dtvs_tlocals, osz);
9533 }
9534
9535 vstate->dtvs_tlocals = tlocals;
9536 vstate->dtvs_ntlocals = ntlocals;
9537 }
9538
9539 vstate->dtvs_tlocals[id] = *v;
9540 continue;
9541
9542 case DIFV_SCOPE_LOCAL:
9543 np = &vstate->dtvs_nlocals;
9544 svarp = &vstate->dtvs_locals;
9545
9546 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9547 dsize = (int)NCPU * (v->dtdv_type.dtdt_size +
9548 sizeof (uint64_t));
9549 else
9550 dsize = (int)NCPU * sizeof (uint64_t);
9551
9552 break;
9553
9554 case DIFV_SCOPE_GLOBAL:
9555 np = &vstate->dtvs_nglobals;
9556 svarp = &vstate->dtvs_globals;
9557
9558 if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9559 dsize = v->dtdv_type.dtdt_size +
9560 sizeof (uint64_t);
9561
9562 break;
9563
9564 default:
9565 ASSERT(0);
9566 }
9567
9568 while (id >= (uint_t)(oldsvars = *np)) {
9569 dtrace_statvar_t **statics;
9570 int newsvars, oldsize, newsize;
9571
9572 if ((newsvars = (oldsvars << 1)) == 0)
9573 newsvars = 1;
9574
9575 oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9576 newsize = newsvars * sizeof (dtrace_statvar_t *);
9577
9578 statics = kmem_zalloc(newsize, KM_SLEEP);
9579
9580 if (oldsize != 0) {
9581 bcopy(*svarp, statics, oldsize);
9582 kmem_free(*svarp, oldsize);
9583 }
9584
9585 *svarp = statics;
9586 *np = newsvars;
9587 }
9588
9589 if ((svar = (*svarp)[id]) == NULL) {
9590 svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9591 svar->dtsv_var = *v;
9592
9593 if ((svar->dtsv_size = dsize) != 0) {
9594 svar->dtsv_data = (uint64_t)(uintptr_t)
9595 kmem_zalloc(dsize, KM_SLEEP);
9596 }
9597
9598 (*svarp)[id] = svar;
9599 }
9600
9601 svar->dtsv_refcnt++;
9602 }
9603
9604 dtrace_difo_chunksize(dp, vstate);
9605 dtrace_difo_hold(dp);
9606 }
9607
9608 static dtrace_difo_t *
9609 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9610 {
9611 dtrace_difo_t *new;
9612 size_t sz;
9613
9614 ASSERT(dp->dtdo_buf != NULL);
9615 ASSERT(dp->dtdo_refcnt != 0);
9616
9617 new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9618
9619 ASSERT(dp->dtdo_buf != NULL);
9620 sz = dp->dtdo_len * sizeof (dif_instr_t);
9621 new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9622 bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9623 new->dtdo_len = dp->dtdo_len;
9624
9625 if (dp->dtdo_strtab != NULL) {
9626 ASSERT(dp->dtdo_strlen != 0);
9627 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9628 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9629 new->dtdo_strlen = dp->dtdo_strlen;
9630 }
9631
9632 if (dp->dtdo_inttab != NULL) {
9633 ASSERT(dp->dtdo_intlen != 0);
9634 sz = dp->dtdo_intlen * sizeof (uint64_t);
9635 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9636 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9637 new->dtdo_intlen = dp->dtdo_intlen;
9638 }
9639
9640 if (dp->dtdo_vartab != NULL) {
9641 ASSERT(dp->dtdo_varlen != 0);
9642 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9643 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9644 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9645 new->dtdo_varlen = dp->dtdo_varlen;
9646 }
9647
9648 dtrace_difo_init(new, vstate);
9649 return (new);
9650 }
9651
9652 static void
9653 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9654 {
9655 uint_t i;
9656
9657 ASSERT(dp->dtdo_refcnt == 0);
9658
9659 for (i = 0; i < dp->dtdo_varlen; i++) {
9660 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9661 dtrace_statvar_t *svar;
9662 dtrace_statvar_t **svarp = NULL;
9663 uint_t id;
9664 uint8_t scope = v->dtdv_scope;
9665 int *np = NULL;
9666
9667 switch (scope) {
9668 case DIFV_SCOPE_THREAD:
9669 continue;
9670
9671 case DIFV_SCOPE_LOCAL:
9672 np = &vstate->dtvs_nlocals;
9673 svarp = vstate->dtvs_locals;
9674 break;
9675
9676 case DIFV_SCOPE_GLOBAL:
9677 np = &vstate->dtvs_nglobals;
9678 svarp = vstate->dtvs_globals;
9679 break;
9680
9681 default:
9682 ASSERT(0);
9683 }
9684
9685 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9686 continue;
9687
9688 id -= DIF_VAR_OTHER_UBASE;
9689
9690 ASSERT(id < (uint_t)*np);
9691
9692 svar = svarp[id];
9693 ASSERT(svar != NULL);
9694 ASSERT(svar->dtsv_refcnt > 0);
9695
9696 if (--svar->dtsv_refcnt > 0)
9697 continue;
9698
9699 if (svar->dtsv_size != 0) {
9700 ASSERT(svar->dtsv_data != 0);
9701 kmem_free((void *)(uintptr_t)svar->dtsv_data,
9702 svar->dtsv_size);
9703 }
9704
9705 kmem_free(svar, sizeof (dtrace_statvar_t));
9706 svarp[id] = NULL;
9707 }
9708
9709 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9710 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9711 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9712 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9713
9714 kmem_free(dp, sizeof (dtrace_difo_t));
9715 }
9716
9717 static void
9718 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9719 {
9720 uint_t i;
9721
9722 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9723 ASSERT(dp->dtdo_refcnt != 0);
9724
9725 for (i = 0; i < dp->dtdo_varlen; i++) {
9726 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9727
9728 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9729 continue;
9730
9731 ASSERT(dtrace_vtime_references > 0);
9732 if (--dtrace_vtime_references == 0)
9733 dtrace_vtime_disable();
9734 }
9735
9736 if (--dp->dtdo_refcnt == 0)
9737 dtrace_difo_destroy(dp, vstate);
9738 }
9739
9740 /*
9741 * DTrace Format Functions
9742 */
9743 static uint16_t
9744 dtrace_format_add(dtrace_state_t *state, char *str)
9745 {
9746 char *fmt, **new;
9747 uint16_t ndx, len = strlen(str) + 1;
9748
9749 fmt = kmem_zalloc(len, KM_SLEEP);
9750 bcopy(str, fmt, len);
9751
9752 for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9753 if (state->dts_formats[ndx] == NULL) {
9754 state->dts_formats[ndx] = fmt;
9755 return (ndx + 1);
9756 }
9757 }
9758
9759 if (state->dts_nformats == USHRT_MAX) {
9760 /*
9761 * This is only likely if a denial-of-service attack is being
9762 * attempted. As such, it's okay to fail silently here.
9763 */
9764 kmem_free(fmt, len);
9765 return (0);
9766 }
9767
9768 /*
9769 * For simplicity, we always resize the formats array to be exactly the
9770 * number of formats.
9771 */
9772 ndx = state->dts_nformats++;
9773 new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9774
9775 if (state->dts_formats != NULL) {
9776 ASSERT(ndx != 0);
9777 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9778 kmem_free(state->dts_formats, ndx * sizeof (char *));
9779 }
9780
9781 state->dts_formats = new;
9782 state->dts_formats[ndx] = fmt;
9783
9784 return (ndx + 1);
9785 }
9786
9787 static void
9788 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9789 {
9790 char *fmt;
9791
9792 ASSERT(state->dts_formats != NULL);
9793 ASSERT(format <= state->dts_nformats);
9794 ASSERT(state->dts_formats[format - 1] != NULL);
9795
9796 fmt = state->dts_formats[format - 1];
9797 kmem_free(fmt, strlen(fmt) + 1);
9798 state->dts_formats[format - 1] = NULL;
9799 }
9800
9801 static void
9802 dtrace_format_destroy(dtrace_state_t *state)
9803 {
9804 int i;
9805
9806 if (state->dts_nformats == 0) {
9807 ASSERT(state->dts_formats == NULL);
9808 return;
9809 }
9810
9811 ASSERT(state->dts_formats != NULL);
9812
9813 for (i = 0; i < state->dts_nformats; i++) {
9814 char *fmt = state->dts_formats[i];
9815
9816 if (fmt == NULL)
9817 continue;
9818
9819 kmem_free(fmt, strlen(fmt) + 1);
9820 }
9821
9822 kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9823 state->dts_nformats = 0;
9824 state->dts_formats = NULL;
9825 }
9826
9827 /*
9828 * DTrace Predicate Functions
9829 */
9830 static dtrace_predicate_t *
9831 dtrace_predicate_create(dtrace_difo_t *dp)
9832 {
9833 dtrace_predicate_t *pred;
9834
9835 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9836 ASSERT(dp->dtdo_refcnt != 0);
9837
9838 pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9839 pred->dtp_difo = dp;
9840 pred->dtp_refcnt = 1;
9841
9842 if (!dtrace_difo_cacheable(dp))
9843 return (pred);
9844
9845 if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9846 /*
9847 * This is only theoretically possible -- we have had 2^32
9848 * cacheable predicates on this machine. We cannot allow any
9849 * more predicates to become cacheable: as unlikely as it is,
9850 * there may be a thread caching a (now stale) predicate cache
9851 * ID. (N.B.: the temptation is being successfully resisted to
9852 * have this cmn_err() "Holy shit -- we executed this code!")
9853 */
9854 return (pred);
9855 }
9856
9857 pred->dtp_cacheid = dtrace_predcache_id++;
9858
9859 return (pred);
9860 }
9861
9862 static void
9863 dtrace_predicate_hold(dtrace_predicate_t *pred)
9864 {
9865 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9866 ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9867 ASSERT(pred->dtp_refcnt > 0);
9868
9869 pred->dtp_refcnt++;
9870 }
9871
9872 static void
9873 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9874 {
9875 dtrace_difo_t *dp = pred->dtp_difo;
9876 #pragma unused(dp) /* __APPLE__ */
9877
9878 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9879 ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9880 ASSERT(pred->dtp_refcnt > 0);
9881
9882 if (--pred->dtp_refcnt == 0) {
9883 dtrace_difo_release(pred->dtp_difo, vstate);
9884 kmem_free(pred, sizeof (dtrace_predicate_t));
9885 }
9886 }
9887
9888 /*
9889 * DTrace Action Description Functions
9890 */
9891 static dtrace_actdesc_t *
9892 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9893 uint64_t uarg, uint64_t arg)
9894 {
9895 dtrace_actdesc_t *act;
9896
9897 ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
9898 arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
9899
9900 act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9901 act->dtad_kind = kind;
9902 act->dtad_ntuple = ntuple;
9903 act->dtad_uarg = uarg;
9904 act->dtad_arg = arg;
9905 act->dtad_refcnt = 1;
9906
9907 return (act);
9908 }
9909
9910 static void
9911 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9912 {
9913 ASSERT(act->dtad_refcnt >= 1);
9914 act->dtad_refcnt++;
9915 }
9916
9917 static void
9918 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9919 {
9920 dtrace_actkind_t kind = act->dtad_kind;
9921 dtrace_difo_t *dp;
9922
9923 ASSERT(act->dtad_refcnt >= 1);
9924
9925 if (--act->dtad_refcnt != 0)
9926 return;
9927
9928 if ((dp = act->dtad_difo) != NULL)
9929 dtrace_difo_release(dp, vstate);
9930
9931 if (DTRACEACT_ISPRINTFLIKE(kind)) {
9932 char *str = (char *)(uintptr_t)act->dtad_arg;
9933
9934 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9935 (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9936
9937 if (str != NULL)
9938 kmem_free(str, strlen(str) + 1);
9939 }
9940
9941 kmem_free(act, sizeof (dtrace_actdesc_t));
9942 }
9943
9944 /*
9945 * DTrace ECB Functions
9946 */
9947 static dtrace_ecb_t *
9948 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9949 {
9950 dtrace_ecb_t *ecb;
9951 dtrace_epid_t epid;
9952
9953 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
9954
9955 ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9956 ecb->dte_predicate = NULL;
9957 ecb->dte_probe = probe;
9958
9959 /*
9960 * The default size is the size of the default action: recording
9961 * the header.
9962 */
9963 ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9964 ecb->dte_alignment = sizeof (dtrace_epid_t);
9965
9966 epid = state->dts_epid++;
9967
9968 if (epid - 1 >= (dtrace_epid_t)state->dts_necbs) {
9969 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9970 int necbs = state->dts_necbs << 1;
9971
9972 ASSERT(epid == (dtrace_epid_t)state->dts_necbs + 1);
9973
9974 if (necbs == 0) {
9975 ASSERT(oecbs == NULL);
9976 necbs = 1;
9977 }
9978
9979 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9980
9981 if (oecbs != NULL)
9982 bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9983
9984 dtrace_membar_producer();
9985 state->dts_ecbs = ecbs;
9986
9987 if (oecbs != NULL) {
9988 /*
9989 * If this state is active, we must dtrace_sync()
9990 * before we can free the old dts_ecbs array: we're
9991 * coming in hot, and there may be active ring
9992 * buffer processing (which indexes into the dts_ecbs
9993 * array) on another CPU.
9994 */
9995 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9996 dtrace_sync();
9997
9998 kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9999 }
10000
10001 dtrace_membar_producer();
10002 state->dts_necbs = necbs;
10003 }
10004
10005 ecb->dte_state = state;
10006
10007 ASSERT(state->dts_ecbs[epid - 1] == NULL);
10008 dtrace_membar_producer();
10009 state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10010
10011 return (ecb);
10012 }
10013
10014 static int
10015 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10016 {
10017 dtrace_probe_t *probe = ecb->dte_probe;
10018
10019 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
10020 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10021 ASSERT(ecb->dte_next == NULL);
10022
10023 if (probe == NULL) {
10024 /*
10025 * This is the NULL probe -- there's nothing to do.
10026 */
10027 return(0);
10028 }
10029
10030 probe->dtpr_provider->dtpv_ecb_count++;
10031 if (probe->dtpr_ecb == NULL) {
10032 dtrace_provider_t *prov = probe->dtpr_provider;
10033
10034 /*
10035 * We're the first ECB on this probe.
10036 */
10037 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10038
10039 if (ecb->dte_predicate != NULL)
10040 probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10041
10042 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10043 probe->dtpr_id, probe->dtpr_arg));
10044 } else {
10045 /*
10046 * This probe is already active. Swing the last pointer to
10047 * point to the new ECB, and issue a dtrace_sync() to assure
10048 * that all CPUs have seen the change.
10049 */
10050 ASSERT(probe->dtpr_ecb_last != NULL);
10051 probe->dtpr_ecb_last->dte_next = ecb;
10052 probe->dtpr_ecb_last = ecb;
10053 probe->dtpr_predcache = 0;
10054
10055 dtrace_sync();
10056 return(0);
10057 }
10058 }
10059
10060 static int
10061 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10062 {
10063 dtrace_action_t *act;
10064 uint32_t curneeded = UINT32_MAX;
10065 uint32_t aggbase = UINT32_MAX;
10066
10067 /*
10068 * If we record anything, we always record the dtrace_rechdr_t. (And
10069 * we always record it first.)
10070 */
10071 ecb->dte_size = sizeof (dtrace_rechdr_t);
10072 ecb->dte_alignment = sizeof (dtrace_epid_t);
10073
10074 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10075 dtrace_recdesc_t *rec = &act->dta_rec;
10076 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10077
10078 ecb->dte_alignment = MAX(ecb->dte_alignment, rec->dtrd_alignment);
10079
10080 if (DTRACEACT_ISAGG(act->dta_kind)) {
10081 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10082
10083 ASSERT(rec->dtrd_size != 0);
10084 ASSERT(agg->dtag_first != NULL);
10085 ASSERT(act->dta_prev->dta_intuple);
10086 ASSERT(aggbase != UINT32_MAX);
10087 ASSERT(curneeded != UINT32_MAX);
10088
10089 agg->dtag_base = aggbase;
10090 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10091 rec->dtrd_offset = curneeded;
10092 if (curneeded + rec->dtrd_size < curneeded)
10093 return (EINVAL);
10094 curneeded += rec->dtrd_size;
10095 ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10096
10097 aggbase = UINT32_MAX;
10098 curneeded = UINT32_MAX;
10099 } else if (act->dta_intuple) {
10100 if (curneeded == UINT32_MAX) {
10101 /*
10102 * This is the first record in a tuple. Align
10103 * curneeded to be at offset 4 in an 8-byte
10104 * aligned block.
10105 */
10106 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
10107 ASSERT(aggbase == UINT32_MAX);
10108
10109 curneeded = P2PHASEUP(ecb->dte_size,
10110 sizeof (uint64_t), sizeof (dtrace_aggid_t));
10111
10112 aggbase = curneeded - sizeof (dtrace_aggid_t);
10113 ASSERT(IS_P2ALIGNED(aggbase,
10114 sizeof (uint64_t)));
10115 }
10116
10117 curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10118 rec->dtrd_offset = curneeded;
10119 curneeded += rec->dtrd_size;
10120 if (curneeded + rec->dtrd_size < curneeded)
10121 return (EINVAL);
10122 } else {
10123 /* tuples must be followed by an aggregation */
10124 ASSERT(act->dta_prev == NULL || !act->dta_prev->dta_intuple);
10125 ecb->dte_size = P2ROUNDUP(ecb->dte_size, rec->dtrd_alignment);
10126 rec->dtrd_offset = ecb->dte_size;
10127 if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
10128 return (EINVAL);
10129 ecb->dte_size += rec->dtrd_size;
10130 ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10131 }
10132 }
10133
10134 if ((act = ecb->dte_action) != NULL &&
10135 !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10136 ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10137 /*
10138 * If the size is still sizeof (dtrace_rechdr_t), then all
10139 * actions store no data; set the size to 0.
10140 */
10141 ecb->dte_size = 0;
10142 }
10143
10144 ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10145 ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10146 ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed, ecb->dte_needed);
10147 return (0);
10148 }
10149
10150 static dtrace_action_t *
10151 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10152 {
10153 dtrace_aggregation_t *agg;
10154 size_t size = sizeof (uint64_t);
10155 int ntuple = desc->dtad_ntuple;
10156 dtrace_action_t *act;
10157 dtrace_recdesc_t *frec;
10158 dtrace_aggid_t aggid;
10159 dtrace_state_t *state = ecb->dte_state;
10160
10161 agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10162 agg->dtag_ecb = ecb;
10163
10164 ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10165
10166 switch (desc->dtad_kind) {
10167 case DTRACEAGG_MIN:
10168 agg->dtag_initial = INT64_MAX;
10169 agg->dtag_aggregate = dtrace_aggregate_min;
10170 break;
10171
10172 case DTRACEAGG_MAX:
10173 agg->dtag_initial = INT64_MIN;
10174 agg->dtag_aggregate = dtrace_aggregate_max;
10175 break;
10176
10177 case DTRACEAGG_COUNT:
10178 agg->dtag_aggregate = dtrace_aggregate_count;
10179 break;
10180
10181 case DTRACEAGG_QUANTIZE:
10182 agg->dtag_aggregate = dtrace_aggregate_quantize;
10183 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10184 sizeof (uint64_t);
10185 break;
10186
10187 case DTRACEAGG_LQUANTIZE: {
10188 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10189 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10190
10191 agg->dtag_initial = desc->dtad_arg;
10192 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10193
10194 if (step == 0 || levels == 0)
10195 goto err;
10196
10197 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10198 break;
10199 }
10200
10201 case DTRACEAGG_LLQUANTIZE: {
10202 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10203 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10204 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10205 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10206 int64_t v;
10207
10208 agg->dtag_initial = desc->dtad_arg;
10209 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10210
10211 if (factor < 2 || low >= high || nsteps < factor)
10212 goto err;
10213
10214 /*
10215 * Now check that the number of steps evenly divides a power
10216 * of the factor. (This assures both integer bucket size and
10217 * linearity within each magnitude.)
10218 */
10219 for (v = factor; v < nsteps; v *= factor)
10220 continue;
10221
10222 if ((v % nsteps) || (nsteps % factor))
10223 goto err;
10224
10225 size = (dtrace_aggregate_llquantize_bucket(factor, low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10226 break;
10227 }
10228
10229 case DTRACEAGG_AVG:
10230 agg->dtag_aggregate = dtrace_aggregate_avg;
10231 size = sizeof (uint64_t) * 2;
10232 break;
10233
10234 case DTRACEAGG_STDDEV:
10235 agg->dtag_aggregate = dtrace_aggregate_stddev;
10236 size = sizeof (uint64_t) * 4;
10237 break;
10238
10239 case DTRACEAGG_SUM:
10240 agg->dtag_aggregate = dtrace_aggregate_sum;
10241 break;
10242
10243 default:
10244 goto err;
10245 }
10246
10247 agg->dtag_action.dta_rec.dtrd_size = size;
10248
10249 if (ntuple == 0)
10250 goto err;
10251
10252 /*
10253 * We must make sure that we have enough actions for the n-tuple.
10254 */
10255 for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10256 if (DTRACEACT_ISAGG(act->dta_kind))
10257 break;
10258
10259 if (--ntuple == 0) {
10260 /*
10261 * This is the action with which our n-tuple begins.
10262 */
10263 agg->dtag_first = act;
10264 goto success;
10265 }
10266 }
10267
10268 /*
10269 * This n-tuple is short by ntuple elements. Return failure.
10270 */
10271 ASSERT(ntuple != 0);
10272 err:
10273 kmem_free(agg, sizeof (dtrace_aggregation_t));
10274 return (NULL);
10275
10276 success:
10277 /*
10278 * If the last action in the tuple has a size of zero, it's actually
10279 * an expression argument for the aggregating action.
10280 */
10281 ASSERT(ecb->dte_action_last != NULL);
10282 act = ecb->dte_action_last;
10283
10284 if (act->dta_kind == DTRACEACT_DIFEXPR) {
10285 ASSERT(act->dta_difo != NULL);
10286
10287 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10288 agg->dtag_hasarg = 1;
10289 }
10290
10291 /*
10292 * We need to allocate an id for this aggregation.
10293 */
10294 aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10295 VM_BESTFIT | VM_SLEEP);
10296
10297 if (aggid - 1 >= (dtrace_aggid_t)state->dts_naggregations) {
10298 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10299 dtrace_aggregation_t **aggs;
10300 int naggs = state->dts_naggregations << 1;
10301 int onaggs = state->dts_naggregations;
10302
10303 ASSERT(aggid == (dtrace_aggid_t)state->dts_naggregations + 1);
10304
10305 if (naggs == 0) {
10306 ASSERT(oaggs == NULL);
10307 naggs = 1;
10308 }
10309
10310 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10311
10312 if (oaggs != NULL) {
10313 bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10314 kmem_free(oaggs, onaggs * sizeof (*aggs));
10315 }
10316
10317 state->dts_aggregations = aggs;
10318 state->dts_naggregations = naggs;
10319 }
10320
10321 ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10322 state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10323
10324 frec = &agg->dtag_first->dta_rec;
10325 if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10326 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10327
10328 for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10329 ASSERT(!act->dta_intuple);
10330 act->dta_intuple = 1;
10331 }
10332
10333 return (&agg->dtag_action);
10334 }
10335
10336 static void
10337 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10338 {
10339 dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10340 dtrace_state_t *state = ecb->dte_state;
10341 dtrace_aggid_t aggid = agg->dtag_id;
10342
10343 ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10344 vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10345
10346 ASSERT(state->dts_aggregations[aggid - 1] == agg);
10347 state->dts_aggregations[aggid - 1] = NULL;
10348
10349 kmem_free(agg, sizeof (dtrace_aggregation_t));
10350 }
10351
10352 static int
10353 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10354 {
10355 dtrace_action_t *action, *last;
10356 dtrace_difo_t *dp = desc->dtad_difo;
10357 uint32_t size = 0, align = sizeof (uint8_t), mask;
10358 uint16_t format = 0;
10359 dtrace_recdesc_t *rec;
10360 dtrace_state_t *state = ecb->dte_state;
10361 dtrace_optval_t *opt = state->dts_options;
10362 dtrace_optval_t nframes=0, strsize;
10363 uint64_t arg = desc->dtad_arg;
10364
10365 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10366 ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10367
10368 if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10369 /*
10370 * If this is an aggregating action, there must be neither
10371 * a speculate nor a commit on the action chain.
10372 */
10373 dtrace_action_t *act;
10374
10375 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10376 if (act->dta_kind == DTRACEACT_COMMIT)
10377 return (EINVAL);
10378
10379 if (act->dta_kind == DTRACEACT_SPECULATE)
10380 return (EINVAL);
10381 }
10382
10383 action = dtrace_ecb_aggregation_create(ecb, desc);
10384
10385 if (action == NULL)
10386 return (EINVAL);
10387 } else {
10388 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10389 (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10390 dp != NULL && dp->dtdo_destructive)) {
10391 state->dts_destructive = 1;
10392 }
10393
10394 switch (desc->dtad_kind) {
10395 case DTRACEACT_PRINTF:
10396 case DTRACEACT_PRINTA:
10397 case DTRACEACT_SYSTEM:
10398 case DTRACEACT_FREOPEN:
10399 case DTRACEACT_DIFEXPR:
10400 /*
10401 * We know that our arg is a string -- turn it into a
10402 * format.
10403 */
10404 if (arg == 0) {
10405 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10406 desc->dtad_kind == DTRACEACT_DIFEXPR);
10407 format = 0;
10408 } else {
10409 ASSERT(arg != 0);
10410 ASSERT(arg > KERNELBASE);
10411 format = dtrace_format_add(state,
10412 (char *)(uintptr_t)arg);
10413 }
10414
10415 /*FALLTHROUGH*/
10416 case DTRACEACT_LIBACT:
10417 case DTRACEACT_TRACEMEM:
10418 case DTRACEACT_TRACEMEM_DYNSIZE:
10419 case DTRACEACT_APPLEBINARY: /* __APPLE__ */
10420 if (dp == NULL)
10421 return (EINVAL);
10422
10423 if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10424 break;
10425
10426 if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10427 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10428 return (EINVAL);
10429
10430 size = opt[DTRACEOPT_STRSIZE];
10431 }
10432
10433 break;
10434
10435 case DTRACEACT_STACK:
10436 if ((nframes = arg) == 0) {
10437 nframes = opt[DTRACEOPT_STACKFRAMES];
10438 ASSERT(nframes > 0);
10439 arg = nframes;
10440 }
10441
10442 size = nframes * sizeof (pc_t);
10443 break;
10444
10445 case DTRACEACT_JSTACK:
10446 if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10447 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10448
10449 if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10450 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10451
10452 arg = DTRACE_USTACK_ARG(nframes, strsize);
10453
10454 /*FALLTHROUGH*/
10455 case DTRACEACT_USTACK:
10456 if (desc->dtad_kind != DTRACEACT_JSTACK &&
10457 (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10458 strsize = DTRACE_USTACK_STRSIZE(arg);
10459 nframes = opt[DTRACEOPT_USTACKFRAMES];
10460 ASSERT(nframes > 0);
10461 arg = DTRACE_USTACK_ARG(nframes, strsize);
10462 }
10463
10464 /*
10465 * Save a slot for the pid.
10466 */
10467 size = (nframes + 1) * sizeof (uint64_t);
10468 size += DTRACE_USTACK_STRSIZE(arg);
10469 size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10470
10471 break;
10472
10473 case DTRACEACT_SYM:
10474 case DTRACEACT_MOD:
10475 if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10476 sizeof (uint64_t)) ||
10477 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10478 return (EINVAL);
10479 break;
10480
10481 case DTRACEACT_USYM:
10482 case DTRACEACT_UMOD:
10483 case DTRACEACT_UADDR:
10484 if (dp == NULL ||
10485 (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10486 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10487 return (EINVAL);
10488
10489 /*
10490 * We have a slot for the pid, plus a slot for the
10491 * argument. To keep things simple (aligned with
10492 * bitness-neutral sizing), we store each as a 64-bit
10493 * quantity.
10494 */
10495 size = 2 * sizeof (uint64_t);
10496 break;
10497
10498 case DTRACEACT_STOP:
10499 case DTRACEACT_BREAKPOINT:
10500 case DTRACEACT_PANIC:
10501 break;
10502
10503 case DTRACEACT_CHILL:
10504 case DTRACEACT_DISCARD:
10505 case DTRACEACT_RAISE:
10506 case DTRACEACT_PIDRESUME: /* __APPLE__ */
10507 if (dp == NULL)
10508 return (EINVAL);
10509 break;
10510
10511 case DTRACEACT_EXIT:
10512 if (dp == NULL ||
10513 (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10514 (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10515 return (EINVAL);
10516 break;
10517
10518 case DTRACEACT_SPECULATE:
10519 if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10520 return (EINVAL);
10521
10522 if (dp == NULL)
10523 return (EINVAL);
10524
10525 state->dts_speculates = 1;
10526 break;
10527
10528 case DTRACEACT_COMMIT: {
10529 dtrace_action_t *act = ecb->dte_action;
10530
10531 for (; act != NULL; act = act->dta_next) {
10532 if (act->dta_kind == DTRACEACT_COMMIT)
10533 return (EINVAL);
10534 }
10535
10536 if (dp == NULL)
10537 return (EINVAL);
10538 break;
10539 }
10540
10541 default:
10542 return (EINVAL);
10543 }
10544
10545 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10546 /*
10547 * If this is a data-storing action or a speculate,
10548 * we must be sure that there isn't a commit on the
10549 * action chain.
10550 */
10551 dtrace_action_t *act = ecb->dte_action;
10552
10553 for (; act != NULL; act = act->dta_next) {
10554 if (act->dta_kind == DTRACEACT_COMMIT)
10555 return (EINVAL);
10556 }
10557 }
10558
10559 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10560 action->dta_rec.dtrd_size = size;
10561 }
10562
10563 action->dta_refcnt = 1;
10564 rec = &action->dta_rec;
10565 size = rec->dtrd_size;
10566
10567 for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10568 if (!(size & mask)) {
10569 align = mask + 1;
10570 break;
10571 }
10572 }
10573
10574 action->dta_kind = desc->dtad_kind;
10575
10576 if ((action->dta_difo = dp) != NULL)
10577 dtrace_difo_hold(dp);
10578
10579 rec->dtrd_action = action->dta_kind;
10580 rec->dtrd_arg = arg;
10581 rec->dtrd_uarg = desc->dtad_uarg;
10582 rec->dtrd_alignment = (uint16_t)align;
10583 rec->dtrd_format = format;
10584
10585 if ((last = ecb->dte_action_last) != NULL) {
10586 ASSERT(ecb->dte_action != NULL);
10587 action->dta_prev = last;
10588 last->dta_next = action;
10589 } else {
10590 ASSERT(ecb->dte_action == NULL);
10591 ecb->dte_action = action;
10592 }
10593
10594 ecb->dte_action_last = action;
10595
10596 return (0);
10597 }
10598
10599 static void
10600 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10601 {
10602 dtrace_action_t *act = ecb->dte_action, *next;
10603 dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10604 dtrace_difo_t *dp;
10605 uint16_t format;
10606
10607 if (act != NULL && act->dta_refcnt > 1) {
10608 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10609 act->dta_refcnt--;
10610 } else {
10611 for (; act != NULL; act = next) {
10612 next = act->dta_next;
10613 ASSERT(next != NULL || act == ecb->dte_action_last);
10614 ASSERT(act->dta_refcnt == 1);
10615
10616 if ((format = act->dta_rec.dtrd_format) != 0)
10617 dtrace_format_remove(ecb->dte_state, format);
10618
10619 if ((dp = act->dta_difo) != NULL)
10620 dtrace_difo_release(dp, vstate);
10621
10622 if (DTRACEACT_ISAGG(act->dta_kind)) {
10623 dtrace_ecb_aggregation_destroy(ecb, act);
10624 } else {
10625 kmem_free(act, sizeof (dtrace_action_t));
10626 }
10627 }
10628 }
10629
10630 ecb->dte_action = NULL;
10631 ecb->dte_action_last = NULL;
10632 ecb->dte_size = 0;
10633 }
10634
10635 static void
10636 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10637 {
10638 /*
10639 * We disable the ECB by removing it from its probe.
10640 */
10641 dtrace_ecb_t *pecb, *prev = NULL;
10642 dtrace_probe_t *probe = ecb->dte_probe;
10643
10644 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10645
10646 if (probe == NULL) {
10647 /*
10648 * This is the NULL probe; there is nothing to disable.
10649 */
10650 return;
10651 }
10652
10653 for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10654 if (pecb == ecb)
10655 break;
10656 prev = pecb;
10657 }
10658
10659 ASSERT(pecb != NULL);
10660
10661 if (prev == NULL) {
10662 probe->dtpr_ecb = ecb->dte_next;
10663 } else {
10664 prev->dte_next = ecb->dte_next;
10665 }
10666
10667 if (ecb == probe->dtpr_ecb_last) {
10668 ASSERT(ecb->dte_next == NULL);
10669 probe->dtpr_ecb_last = prev;
10670 }
10671
10672 probe->dtpr_provider->dtpv_ecb_count--;
10673 /*
10674 * The ECB has been disconnected from the probe; now sync to assure
10675 * that all CPUs have seen the change before returning.
10676 */
10677 dtrace_sync();
10678
10679 if (probe->dtpr_ecb == NULL) {
10680 /*
10681 * That was the last ECB on the probe; clear the predicate
10682 * cache ID for the probe, disable it and sync one more time
10683 * to assure that we'll never hit it again.
10684 */
10685 dtrace_provider_t *prov = probe->dtpr_provider;
10686
10687 ASSERT(ecb->dte_next == NULL);
10688 ASSERT(probe->dtpr_ecb_last == NULL);
10689 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10690 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10691 probe->dtpr_id, probe->dtpr_arg);
10692 dtrace_sync();
10693 } else {
10694 /*
10695 * There is at least one ECB remaining on the probe. If there
10696 * is _exactly_ one, set the probe's predicate cache ID to be
10697 * the predicate cache ID of the remaining ECB.
10698 */
10699 ASSERT(probe->dtpr_ecb_last != NULL);
10700 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10701
10702 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10703 dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10704
10705 ASSERT(probe->dtpr_ecb->dte_next == NULL);
10706
10707 if (p != NULL)
10708 probe->dtpr_predcache = p->dtp_cacheid;
10709 }
10710
10711 ecb->dte_next = NULL;
10712 }
10713 }
10714
10715 static void
10716 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10717 {
10718 dtrace_state_t *state = ecb->dte_state;
10719 dtrace_vstate_t *vstate = &state->dts_vstate;
10720 dtrace_predicate_t *pred;
10721 dtrace_epid_t epid = ecb->dte_epid;
10722
10723 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10724 ASSERT(ecb->dte_next == NULL);
10725 ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10726
10727 if ((pred = ecb->dte_predicate) != NULL)
10728 dtrace_predicate_release(pred, vstate);
10729
10730 dtrace_ecb_action_remove(ecb);
10731
10732 ASSERT(state->dts_ecbs[epid - 1] == ecb);
10733 state->dts_ecbs[epid - 1] = NULL;
10734
10735 kmem_free(ecb, sizeof (dtrace_ecb_t));
10736 }
10737
10738 static dtrace_ecb_t *
10739 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10740 dtrace_enabling_t *enab)
10741 {
10742 dtrace_ecb_t *ecb;
10743 dtrace_predicate_t *pred;
10744 dtrace_actdesc_t *act;
10745 dtrace_provider_t *prov;
10746 dtrace_ecbdesc_t *desc = enab->dten_current;
10747
10748 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10749 ASSERT(state != NULL);
10750
10751 ecb = dtrace_ecb_add(state, probe);
10752 ecb->dte_uarg = desc->dted_uarg;
10753
10754 if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10755 dtrace_predicate_hold(pred);
10756 ecb->dte_predicate = pred;
10757 }
10758
10759 if (probe != NULL) {
10760 /*
10761 * If the provider shows more leg than the consumer is old
10762 * enough to see, we need to enable the appropriate implicit
10763 * predicate bits to prevent the ecb from activating at
10764 * revealing times.
10765 *
10766 * Providers specifying DTRACE_PRIV_USER at register time
10767 * are stating that they need the /proc-style privilege
10768 * model to be enforced, and this is what DTRACE_COND_OWNER
10769 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10770 */
10771 prov = probe->dtpr_provider;
10772 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10773 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10774 ecb->dte_cond |= DTRACE_COND_OWNER;
10775
10776 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10777 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10778 ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10779
10780 /*
10781 * If the provider shows us kernel innards and the user
10782 * is lacking sufficient privilege, enable the
10783 * DTRACE_COND_USERMODE implicit predicate.
10784 */
10785 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10786 (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10787 ecb->dte_cond |= DTRACE_COND_USERMODE;
10788 }
10789
10790 if (dtrace_ecb_create_cache != NULL) {
10791 /*
10792 * If we have a cached ecb, we'll use its action list instead
10793 * of creating our own (saving both time and space).
10794 */
10795 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10796 dtrace_action_t *act_if = cached->dte_action;
10797
10798 if (act_if != NULL) {
10799 ASSERT(act_if->dta_refcnt > 0);
10800 act_if->dta_refcnt++;
10801 ecb->dte_action = act_if;
10802 ecb->dte_action_last = cached->dte_action_last;
10803 ecb->dte_needed = cached->dte_needed;
10804 ecb->dte_size = cached->dte_size;
10805 ecb->dte_alignment = cached->dte_alignment;
10806 }
10807
10808 return (ecb);
10809 }
10810
10811 for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10812 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10813 dtrace_ecb_destroy(ecb);
10814 return (NULL);
10815 }
10816 }
10817
10818 if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
10819 dtrace_ecb_destroy(ecb);
10820 return (NULL);
10821 }
10822
10823 return (dtrace_ecb_create_cache = ecb);
10824 }
10825
10826 static int
10827 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10828 {
10829 dtrace_ecb_t *ecb;
10830 dtrace_enabling_t *enab = arg;
10831 dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10832
10833 ASSERT(state != NULL);
10834
10835 if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10836 /*
10837 * This probe was created in a generation for which this
10838 * enabling has previously created ECBs; we don't want to
10839 * enable it again, so just kick out.
10840 */
10841 return (DTRACE_MATCH_NEXT);
10842 }
10843
10844 if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10845 return (DTRACE_MATCH_DONE);
10846
10847 if (dtrace_ecb_enable(ecb) < 0)
10848 return (DTRACE_MATCH_FAIL);
10849
10850 return (DTRACE_MATCH_NEXT);
10851 }
10852
10853 static dtrace_ecb_t *
10854 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10855 {
10856 dtrace_ecb_t *ecb;
10857 #pragma unused(ecb) /* __APPLE__ */
10858
10859 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10860
10861 if (id == 0 || id > (dtrace_epid_t)state->dts_necbs)
10862 return (NULL);
10863
10864 ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10865 ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10866
10867 return (state->dts_ecbs[id - 1]);
10868 }
10869
10870 static dtrace_aggregation_t *
10871 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10872 {
10873 dtrace_aggregation_t *agg;
10874 #pragma unused(agg) /* __APPLE__ */
10875
10876 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10877
10878 if (id == 0 || id > (dtrace_aggid_t)state->dts_naggregations)
10879 return (NULL);
10880
10881 ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10882 ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10883 agg->dtag_id == id);
10884
10885 return (state->dts_aggregations[id - 1]);
10886 }
10887
10888 /*
10889 * DTrace Buffer Functions
10890 *
10891 * The following functions manipulate DTrace buffers. Most of these functions
10892 * are called in the context of establishing or processing consumer state;
10893 * exceptions are explicitly noted.
10894 */
10895
10896 /*
10897 * Note: called from cross call context. This function switches the two
10898 * buffers on a given CPU. The atomicity of this operation is assured by
10899 * disabling interrupts while the actual switch takes place; the disabling of
10900 * interrupts serializes the execution with any execution of dtrace_probe() on
10901 * the same CPU.
10902 */
10903 static void
10904 dtrace_buffer_switch(dtrace_buffer_t *buf)
10905 {
10906 caddr_t tomax = buf->dtb_tomax;
10907 caddr_t xamot = buf->dtb_xamot;
10908 dtrace_icookie_t cookie;
10909 hrtime_t now;
10910
10911 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10912 ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10913
10914 cookie = dtrace_interrupt_disable();
10915 now = dtrace_gethrtime();
10916 buf->dtb_tomax = xamot;
10917 buf->dtb_xamot = tomax;
10918 buf->dtb_xamot_drops = buf->dtb_drops;
10919 buf->dtb_xamot_offset = buf->dtb_offset;
10920 buf->dtb_xamot_errors = buf->dtb_errors;
10921 buf->dtb_xamot_flags = buf->dtb_flags;
10922 buf->dtb_offset = 0;
10923 buf->dtb_drops = 0;
10924 buf->dtb_errors = 0;
10925 buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10926 buf->dtb_interval = now - buf->dtb_switched;
10927 buf->dtb_switched = now;
10928 buf->dtb_cur_limit = buf->dtb_limit;
10929
10930 dtrace_interrupt_enable(cookie);
10931 }
10932
10933 /*
10934 * Note: called from cross call context. This function activates a buffer
10935 * on a CPU. As with dtrace_buffer_switch(), the atomicity of the operation
10936 * is guaranteed by the disabling of interrupts.
10937 */
10938 static void
10939 dtrace_buffer_activate(dtrace_state_t *state)
10940 {
10941 dtrace_buffer_t *buf;
10942 dtrace_icookie_t cookie = dtrace_interrupt_disable();
10943
10944 buf = &state->dts_buffer[CPU->cpu_id];
10945
10946 if (buf->dtb_tomax != NULL) {
10947 /*
10948 * We might like to assert that the buffer is marked inactive,
10949 * but this isn't necessarily true: the buffer for the CPU
10950 * that processes the BEGIN probe has its buffer activated
10951 * manually. In this case, we take the (harmless) action
10952 * re-clearing the bit INACTIVE bit.
10953 */
10954 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10955 }
10956
10957 dtrace_interrupt_enable(cookie);
10958 }
10959
10960 static int
10961 dtrace_buffer_canalloc(size_t size)
10962 {
10963 if (size > (UINT64_MAX - dtrace_buffer_memory_inuse))
10964 return (B_FALSE);
10965 if ((size + dtrace_buffer_memory_inuse) > dtrace_buffer_memory_maxsize)
10966 return (B_FALSE);
10967
10968 return (B_TRUE);
10969 }
10970
10971 static int
10972 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t limit, size_t size, int flags,
10973 processorid_t cpu)
10974 {
10975 dtrace_cpu_t *cp;
10976 dtrace_buffer_t *buf;
10977 size_t size_before_alloc = dtrace_buffer_memory_inuse;
10978
10979 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
10980 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
10981
10982 if (size > (size_t)dtrace_nonroot_maxsize &&
10983 !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10984 return (EFBIG);
10985
10986 cp = cpu_list;
10987
10988 do {
10989 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10990 continue;
10991
10992 buf = &bufs[cp->cpu_id];
10993
10994 /*
10995 * If there is already a buffer allocated for this CPU, it
10996 * is only possible that this is a DR event. In this case,
10997 * the buffer size must match our specified size.
10998 */
10999 if (buf->dtb_tomax != NULL) {
11000 ASSERT(buf->dtb_size == size);
11001 continue;
11002 }
11003
11004 ASSERT(buf->dtb_xamot == NULL);
11005
11006
11007 /* DTrace, please do not eat all the memory. */
11008 if (dtrace_buffer_canalloc(size) == B_FALSE)
11009 goto err;
11010 if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11011 goto err;
11012 dtrace_buffer_memory_inuse += size;
11013
11014 /* Unsure that limit is always lower than size */
11015 limit = limit == size ? limit - 1 : limit;
11016 buf->dtb_cur_limit = limit;
11017 buf->dtb_limit = limit;
11018 buf->dtb_size = size;
11019 buf->dtb_flags = flags;
11020 buf->dtb_offset = 0;
11021 buf->dtb_drops = 0;
11022
11023 if (flags & DTRACEBUF_NOSWITCH)
11024 continue;
11025
11026 /* DTrace, please do not eat all the memory. */
11027 if (dtrace_buffer_canalloc(size) == B_FALSE)
11028 goto err;
11029 if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11030 goto err;
11031 dtrace_buffer_memory_inuse += size;
11032 } while ((cp = cp->cpu_next) != cpu_list);
11033
11034 ASSERT(dtrace_buffer_memory_inuse <= dtrace_buffer_memory_maxsize);
11035
11036 return (0);
11037
11038 err:
11039 cp = cpu_list;
11040
11041 do {
11042 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11043 continue;
11044
11045 buf = &bufs[cp->cpu_id];
11046
11047 if (buf->dtb_xamot != NULL) {
11048 ASSERT(buf->dtb_tomax != NULL);
11049 ASSERT(buf->dtb_size == size);
11050 kmem_free(buf->dtb_xamot, size);
11051 }
11052
11053 if (buf->dtb_tomax != NULL) {
11054 ASSERT(buf->dtb_size == size);
11055 kmem_free(buf->dtb_tomax, size);
11056 }
11057
11058 buf->dtb_tomax = NULL;
11059 buf->dtb_xamot = NULL;
11060 buf->dtb_size = 0;
11061 } while ((cp = cp->cpu_next) != cpu_list);
11062
11063 /* Restore the size saved before allocating memory */
11064 dtrace_buffer_memory_inuse = size_before_alloc;
11065
11066 return (ENOMEM);
11067 }
11068
11069 /*
11070 * Note: called from probe context. This function just increments the drop
11071 * count on a buffer. It has been made a function to allow for the
11072 * possibility of understanding the source of mysterious drop counts. (A
11073 * problem for which one may be particularly disappointed that DTrace cannot
11074 * be used to understand DTrace.)
11075 */
11076 static void
11077 dtrace_buffer_drop(dtrace_buffer_t *buf)
11078 {
11079 buf->dtb_drops++;
11080 }
11081
11082 /*
11083 * Note: called from probe context. This function is called to reserve space
11084 * in a buffer. If mstate is non-NULL, sets the scratch base and size in the
11085 * mstate. Returns the new offset in the buffer, or a negative value if an
11086 * error has occurred.
11087 */
11088 static intptr_t
11089 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11090 dtrace_state_t *state, dtrace_mstate_t *mstate)
11091 {
11092 intptr_t offs = buf->dtb_offset, soffs;
11093 intptr_t woffs;
11094 caddr_t tomax;
11095 size_t total_off;
11096
11097 if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11098 return (-1);
11099
11100 if ((tomax = buf->dtb_tomax) == NULL) {
11101 dtrace_buffer_drop(buf);
11102 return (-1);
11103 }
11104
11105 if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11106 while (offs & (align - 1)) {
11107 /*
11108 * Assert that our alignment is off by a number which
11109 * is itself sizeof (uint32_t) aligned.
11110 */
11111 ASSERT(!((align - (offs & (align - 1))) &
11112 (sizeof (uint32_t) - 1)));
11113 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11114 offs += sizeof (uint32_t);
11115 }
11116
11117 if ((uint64_t)(soffs = offs + needed) > buf->dtb_cur_limit) {
11118 if (buf->dtb_cur_limit == buf->dtb_limit) {
11119 buf->dtb_cur_limit = buf->dtb_size;
11120
11121 atomic_add_32(&state->dts_buf_over_limit, 1);
11122 /**
11123 * Set an AST on the current processor
11124 * so that we can wake up the process
11125 * outside of probe context, when we know
11126 * it is safe to do so
11127 */
11128 minor_t minor = getminor(state->dts_dev);
11129 ASSERT(minor < 32);
11130
11131 atomic_or_32(&dtrace_wake_clients, 1 << minor);
11132 ast_dtrace_on();
11133 }
11134 if ((uint64_t)soffs > buf->dtb_size) {
11135 dtrace_buffer_drop(buf);
11136 return (-1);
11137 }
11138 }
11139
11140 if (mstate == NULL)
11141 return (offs);
11142
11143 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11144 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11145 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11146
11147 return (offs);
11148 }
11149
11150 if (buf->dtb_flags & DTRACEBUF_FILL) {
11151 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11152 (buf->dtb_flags & DTRACEBUF_FULL))
11153 return (-1);
11154 goto out;
11155 }
11156
11157 total_off = needed + (offs & (align - 1));
11158
11159 /*
11160 * For a ring buffer, life is quite a bit more complicated. Before
11161 * we can store any padding, we need to adjust our wrapping offset.
11162 * (If we've never before wrapped or we're not about to, no adjustment
11163 * is required.)
11164 */
11165 if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11166 offs + total_off > buf->dtb_size) {
11167 woffs = buf->dtb_xamot_offset;
11168
11169 if (offs + total_off > buf->dtb_size) {
11170 /*
11171 * We can't fit in the end of the buffer. First, a
11172 * sanity check that we can fit in the buffer at all.
11173 */
11174 if (total_off > buf->dtb_size) {
11175 dtrace_buffer_drop(buf);
11176 return (-1);
11177 }
11178
11179 /*
11180 * We're going to be storing at the top of the buffer,
11181 * so now we need to deal with the wrapped offset. We
11182 * only reset our wrapped offset to 0 if it is
11183 * currently greater than the current offset. If it
11184 * is less than the current offset, it is because a
11185 * previous allocation induced a wrap -- but the
11186 * allocation didn't subsequently take the space due
11187 * to an error or false predicate evaluation. In this
11188 * case, we'll just leave the wrapped offset alone: if
11189 * the wrapped offset hasn't been advanced far enough
11190 * for this allocation, it will be adjusted in the
11191 * lower loop.
11192 */
11193 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11194 if (woffs >= offs)
11195 woffs = 0;
11196 } else {
11197 woffs = 0;
11198 }
11199
11200 /*
11201 * Now we know that we're going to be storing to the
11202 * top of the buffer and that there is room for us
11203 * there. We need to clear the buffer from the current
11204 * offset to the end (there may be old gunk there).
11205 */
11206 while ((uint64_t)offs < buf->dtb_size)
11207 tomax[offs++] = 0;
11208
11209 /*
11210 * We need to set our offset to zero. And because we
11211 * are wrapping, we need to set the bit indicating as
11212 * much. We can also adjust our needed space back
11213 * down to the space required by the ECB -- we know
11214 * that the top of the buffer is aligned.
11215 */
11216 offs = 0;
11217 total_off = needed;
11218 buf->dtb_flags |= DTRACEBUF_WRAPPED;
11219 } else {
11220 /*
11221 * There is room for us in the buffer, so we simply
11222 * need to check the wrapped offset.
11223 */
11224 if (woffs < offs) {
11225 /*
11226 * The wrapped offset is less than the offset.
11227 * This can happen if we allocated buffer space
11228 * that induced a wrap, but then we didn't
11229 * subsequently take the space due to an error
11230 * or false predicate evaluation. This is
11231 * okay; we know that _this_ allocation isn't
11232 * going to induce a wrap. We still can't
11233 * reset the wrapped offset to be zero,
11234 * however: the space may have been trashed in
11235 * the previous failed probe attempt. But at
11236 * least the wrapped offset doesn't need to
11237 * be adjusted at all...
11238 */
11239 goto out;
11240 }
11241 }
11242
11243 while (offs + total_off > (size_t)woffs) {
11244 dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11245 size_t size;
11246
11247 if (epid == DTRACE_EPIDNONE) {
11248 size = sizeof (uint32_t);
11249 } else {
11250 ASSERT(epid <= (dtrace_epid_t)state->dts_necbs);
11251 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11252
11253 size = state->dts_ecbs[epid - 1]->dte_size;
11254 }
11255
11256 ASSERT(woffs + size <= buf->dtb_size);
11257 ASSERT(size != 0);
11258
11259 if (woffs + size == buf->dtb_size) {
11260 /*
11261 * We've reached the end of the buffer; we want
11262 * to set the wrapped offset to 0 and break
11263 * out. However, if the offs is 0, then we're
11264 * in a strange edge-condition: the amount of
11265 * space that we want to reserve plus the size
11266 * of the record that we're overwriting is
11267 * greater than the size of the buffer. This
11268 * is problematic because if we reserve the
11269 * space but subsequently don't consume it (due
11270 * to a failed predicate or error) the wrapped
11271 * offset will be 0 -- yet the EPID at offset 0
11272 * will not be committed. This situation is
11273 * relatively easy to deal with: if we're in
11274 * this case, the buffer is indistinguishable
11275 * from one that hasn't wrapped; we need only
11276 * finish the job by clearing the wrapped bit,
11277 * explicitly setting the offset to be 0, and
11278 * zero'ing out the old data in the buffer.
11279 */
11280 if (offs == 0) {
11281 buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11282 buf->dtb_offset = 0;
11283 woffs = total_off;
11284
11285 while ((uint64_t)woffs < buf->dtb_size)
11286 tomax[woffs++] = 0;
11287 }
11288
11289 woffs = 0;
11290 break;
11291 }
11292
11293 woffs += size;
11294 }
11295
11296 /*
11297 * We have a wrapped offset. It may be that the wrapped offset
11298 * has become zero -- that's okay.
11299 */
11300 buf->dtb_xamot_offset = woffs;
11301 }
11302
11303 out:
11304 /*
11305 * Now we can plow the buffer with any necessary padding.
11306 */
11307 while (offs & (align - 1)) {
11308 /*
11309 * Assert that our alignment is off by a number which
11310 * is itself sizeof (uint32_t) aligned.
11311 */
11312 ASSERT(!((align - (offs & (align - 1))) &
11313 (sizeof (uint32_t) - 1)));
11314 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11315 offs += sizeof (uint32_t);
11316 }
11317
11318 if (buf->dtb_flags & DTRACEBUF_FILL) {
11319 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11320 buf->dtb_flags |= DTRACEBUF_FULL;
11321 return (-1);
11322 }
11323 }
11324
11325 if (mstate == NULL)
11326 return (offs);
11327
11328 /*
11329 * For ring buffers and fill buffers, the scratch space is always
11330 * the inactive buffer.
11331 */
11332 mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11333 mstate->dtms_scratch_size = buf->dtb_size;
11334 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11335
11336 return (offs);
11337 }
11338
11339 static void
11340 dtrace_buffer_polish(dtrace_buffer_t *buf)
11341 {
11342 ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11343 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11344
11345 if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11346 return;
11347
11348 /*
11349 * We need to polish the ring buffer. There are three cases:
11350 *
11351 * - The first (and presumably most common) is that there is no gap
11352 * between the buffer offset and the wrapped offset. In this case,
11353 * there is nothing in the buffer that isn't valid data; we can
11354 * mark the buffer as polished and return.
11355 *
11356 * - The second (less common than the first but still more common
11357 * than the third) is that there is a gap between the buffer offset
11358 * and the wrapped offset, and the wrapped offset is larger than the
11359 * buffer offset. This can happen because of an alignment issue, or
11360 * can happen because of a call to dtrace_buffer_reserve() that
11361 * didn't subsequently consume the buffer space. In this case,
11362 * we need to zero the data from the buffer offset to the wrapped
11363 * offset.
11364 *
11365 * - The third (and least common) is that there is a gap between the
11366 * buffer offset and the wrapped offset, but the wrapped offset is
11367 * _less_ than the buffer offset. This can only happen because a
11368 * call to dtrace_buffer_reserve() induced a wrap, but the space
11369 * was not subsequently consumed. In this case, we need to zero the
11370 * space from the offset to the end of the buffer _and_ from the
11371 * top of the buffer to the wrapped offset.
11372 */
11373 if (buf->dtb_offset < buf->dtb_xamot_offset) {
11374 bzero(buf->dtb_tomax + buf->dtb_offset,
11375 buf->dtb_xamot_offset - buf->dtb_offset);
11376 }
11377
11378 if (buf->dtb_offset > buf->dtb_xamot_offset) {
11379 bzero(buf->dtb_tomax + buf->dtb_offset,
11380 buf->dtb_size - buf->dtb_offset);
11381 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11382 }
11383 }
11384
11385 static void
11386 dtrace_buffer_free(dtrace_buffer_t *bufs)
11387 {
11388 int i;
11389
11390 for (i = 0; i < (int)NCPU; i++) {
11391 dtrace_buffer_t *buf = &bufs[i];
11392
11393 if (buf->dtb_tomax == NULL) {
11394 ASSERT(buf->dtb_xamot == NULL);
11395 ASSERT(buf->dtb_size == 0);
11396 continue;
11397 }
11398
11399 if (buf->dtb_xamot != NULL) {
11400 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11401 kmem_free(buf->dtb_xamot, buf->dtb_size);
11402
11403 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11404 dtrace_buffer_memory_inuse -= buf->dtb_size;
11405 }
11406
11407 kmem_free(buf->dtb_tomax, buf->dtb_size);
11408 ASSERT(dtrace_buffer_memory_inuse >= buf->dtb_size);
11409 dtrace_buffer_memory_inuse -= buf->dtb_size;
11410
11411 buf->dtb_size = 0;
11412 buf->dtb_tomax = NULL;
11413 buf->dtb_xamot = NULL;
11414 }
11415 }
11416
11417 /*
11418 * DTrace Enabling Functions
11419 */
11420 static dtrace_enabling_t *
11421 dtrace_enabling_create(dtrace_vstate_t *vstate)
11422 {
11423 dtrace_enabling_t *enab;
11424
11425 enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11426 enab->dten_vstate = vstate;
11427
11428 return (enab);
11429 }
11430
11431 static void
11432 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11433 {
11434 dtrace_ecbdesc_t **ndesc;
11435 size_t osize, nsize;
11436
11437 /*
11438 * We can't add to enablings after we've enabled them, or after we've
11439 * retained them.
11440 */
11441 ASSERT(enab->dten_probegen == 0);
11442 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11443
11444 /* APPLE NOTE: this protects against gcc 4.0 botch on x86 */
11445 if (ecb == NULL) return;
11446
11447 if (enab->dten_ndesc < enab->dten_maxdesc) {
11448 enab->dten_desc[enab->dten_ndesc++] = ecb;
11449 return;
11450 }
11451
11452 osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11453
11454 if (enab->dten_maxdesc == 0) {
11455 enab->dten_maxdesc = 1;
11456 } else {
11457 enab->dten_maxdesc <<= 1;
11458 }
11459
11460 ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11461
11462 nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11463 ndesc = kmem_zalloc(nsize, KM_SLEEP);
11464 bcopy(enab->dten_desc, ndesc, osize);
11465 kmem_free(enab->dten_desc, osize);
11466
11467 enab->dten_desc = ndesc;
11468 enab->dten_desc[enab->dten_ndesc++] = ecb;
11469 }
11470
11471 static void
11472 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11473 dtrace_probedesc_t *pd)
11474 {
11475 dtrace_ecbdesc_t *new;
11476 dtrace_predicate_t *pred;
11477 dtrace_actdesc_t *act;
11478
11479 /*
11480 * We're going to create a new ECB description that matches the
11481 * specified ECB in every way, but has the specified probe description.
11482 */
11483 new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11484
11485 if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11486 dtrace_predicate_hold(pred);
11487
11488 for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11489 dtrace_actdesc_hold(act);
11490
11491 new->dted_action = ecb->dted_action;
11492 new->dted_pred = ecb->dted_pred;
11493 new->dted_probe = *pd;
11494 new->dted_uarg = ecb->dted_uarg;
11495
11496 dtrace_enabling_add(enab, new);
11497 }
11498
11499 static void
11500 dtrace_enabling_dump(dtrace_enabling_t *enab)
11501 {
11502 int i;
11503
11504 for (i = 0; i < enab->dten_ndesc; i++) {
11505 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11506
11507 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11508 desc->dtpd_provider, desc->dtpd_mod,
11509 desc->dtpd_func, desc->dtpd_name);
11510 }
11511 }
11512
11513 static void
11514 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11515 {
11516 int i;
11517 dtrace_ecbdesc_t *ep;
11518 dtrace_vstate_t *vstate = enab->dten_vstate;
11519
11520 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11521
11522 for (i = 0; i < enab->dten_ndesc; i++) {
11523 dtrace_actdesc_t *act, *next;
11524 dtrace_predicate_t *pred;
11525
11526 ep = enab->dten_desc[i];
11527
11528 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11529 dtrace_predicate_release(pred, vstate);
11530
11531 for (act = ep->dted_action; act != NULL; act = next) {
11532 next = act->dtad_next;
11533 dtrace_actdesc_release(act, vstate);
11534 }
11535
11536 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11537 }
11538
11539 kmem_free(enab->dten_desc,
11540 enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11541
11542 /*
11543 * If this was a retained enabling, decrement the dts_nretained count
11544 * and take it off of the dtrace_retained list.
11545 */
11546 if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11547 dtrace_retained == enab) {
11548 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11549 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11550 enab->dten_vstate->dtvs_state->dts_nretained--;
11551 dtrace_retained_gen++;
11552 }
11553
11554 if (enab->dten_prev == NULL) {
11555 if (dtrace_retained == enab) {
11556 dtrace_retained = enab->dten_next;
11557
11558 if (dtrace_retained != NULL)
11559 dtrace_retained->dten_prev = NULL;
11560 }
11561 } else {
11562 ASSERT(enab != dtrace_retained);
11563 ASSERT(dtrace_retained != NULL);
11564 enab->dten_prev->dten_next = enab->dten_next;
11565 }
11566
11567 if (enab->dten_next != NULL) {
11568 ASSERT(dtrace_retained != NULL);
11569 enab->dten_next->dten_prev = enab->dten_prev;
11570 }
11571
11572 kmem_free(enab, sizeof (dtrace_enabling_t));
11573 }
11574
11575 static int
11576 dtrace_enabling_retain(dtrace_enabling_t *enab)
11577 {
11578 dtrace_state_t *state;
11579
11580 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11581 ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11582 ASSERT(enab->dten_vstate != NULL);
11583
11584 state = enab->dten_vstate->dtvs_state;
11585 ASSERT(state != NULL);
11586
11587 /*
11588 * We only allow each state to retain dtrace_retain_max enablings.
11589 */
11590 if (state->dts_nretained >= dtrace_retain_max)
11591 return (ENOSPC);
11592
11593 state->dts_nretained++;
11594 dtrace_retained_gen++;
11595
11596 if (dtrace_retained == NULL) {
11597 dtrace_retained = enab;
11598 return (0);
11599 }
11600
11601 enab->dten_next = dtrace_retained;
11602 dtrace_retained->dten_prev = enab;
11603 dtrace_retained = enab;
11604
11605 return (0);
11606 }
11607
11608 static int
11609 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11610 dtrace_probedesc_t *create)
11611 {
11612 dtrace_enabling_t *new, *enab;
11613 int found = 0, err = ENOENT;
11614
11615 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11616 ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11617 ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11618 ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11619 ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11620
11621 new = dtrace_enabling_create(&state->dts_vstate);
11622
11623 /*
11624 * Iterate over all retained enablings, looking for enablings that
11625 * match the specified state.
11626 */
11627 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11628 int i;
11629
11630 /*
11631 * dtvs_state can only be NULL for helper enablings -- and
11632 * helper enablings can't be retained.
11633 */
11634 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11635
11636 if (enab->dten_vstate->dtvs_state != state)
11637 continue;
11638
11639 /*
11640 * Now iterate over each probe description; we're looking for
11641 * an exact match to the specified probe description.
11642 */
11643 for (i = 0; i < enab->dten_ndesc; i++) {
11644 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11645 dtrace_probedesc_t *pd = &ep->dted_probe;
11646
11647 /* APPLE NOTE: Darwin employs size bounded string operation. */
11648 if (strncmp(pd->dtpd_provider, match->dtpd_provider, DTRACE_PROVNAMELEN))
11649 continue;
11650
11651 if (strncmp(pd->dtpd_mod, match->dtpd_mod, DTRACE_MODNAMELEN))
11652 continue;
11653
11654 if (strncmp(pd->dtpd_func, match->dtpd_func, DTRACE_FUNCNAMELEN))
11655 continue;
11656
11657 if (strncmp(pd->dtpd_name, match->dtpd_name, DTRACE_NAMELEN))
11658 continue;
11659
11660 /*
11661 * We have a winning probe! Add it to our growing
11662 * enabling.
11663 */
11664 found = 1;
11665 dtrace_enabling_addlike(new, ep, create);
11666 }
11667 }
11668
11669 if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11670 dtrace_enabling_destroy(new);
11671 return (err);
11672 }
11673
11674 return (0);
11675 }
11676
11677 static void
11678 dtrace_enabling_retract(dtrace_state_t *state)
11679 {
11680 dtrace_enabling_t *enab, *next;
11681
11682 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11683
11684 /*
11685 * Iterate over all retained enablings, destroy the enablings retained
11686 * for the specified state.
11687 */
11688 for (enab = dtrace_retained; enab != NULL; enab = next) {
11689 next = enab->dten_next;
11690
11691 /*
11692 * dtvs_state can only be NULL for helper enablings -- and
11693 * helper enablings can't be retained.
11694 */
11695 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11696
11697 if (enab->dten_vstate->dtvs_state == state) {
11698 ASSERT(state->dts_nretained > 0);
11699 dtrace_enabling_destroy(enab);
11700 }
11701 }
11702
11703 ASSERT(state->dts_nretained == 0);
11704 }
11705
11706 static int
11707 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched, dtrace_match_cond_t *cond)
11708 {
11709 int i = 0;
11710 int total_matched = 0, matched = 0;
11711
11712 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
11713 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11714
11715 for (i = 0; i < enab->dten_ndesc; i++) {
11716 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11717
11718 enab->dten_current = ep;
11719 enab->dten_error = 0;
11720
11721 /**
11722 * Before doing a dtrace_probe_enable, which is really
11723 * expensive, check that this enabling matches the matching precondition
11724 * if we have one
11725 */
11726 if (cond && (cond->dmc_func(&ep->dted_probe, cond->dmc_data) == 0)) {
11727 continue;
11728 }
11729 /*
11730 * If a provider failed to enable a probe then get out and
11731 * let the consumer know we failed.
11732 */
11733 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11734 return (EBUSY);
11735
11736 total_matched += matched;
11737
11738 if (enab->dten_error != 0) {
11739 /*
11740 * If we get an error half-way through enabling the
11741 * probes, we kick out -- perhaps with some number of
11742 * them enabled. Leaving enabled probes enabled may
11743 * be slightly confusing for user-level, but we expect
11744 * that no one will attempt to actually drive on in
11745 * the face of such errors. If this is an anonymous
11746 * enabling (indicated with a NULL nmatched pointer),
11747 * we cmn_err() a message. We aren't expecting to
11748 * get such an error -- such as it can exist at all,
11749 * it would be a result of corrupted DOF in the driver
11750 * properties.
11751 */
11752 if (nmatched == NULL) {
11753 cmn_err(CE_WARN, "dtrace_enabling_match() "
11754 "error on %p: %d", (void *)ep,
11755 enab->dten_error);
11756 }
11757
11758 return (enab->dten_error);
11759 }
11760 }
11761
11762 enab->dten_probegen = dtrace_probegen;
11763 if (nmatched != NULL)
11764 *nmatched = total_matched;
11765
11766 return (0);
11767 }
11768
11769 static void
11770 dtrace_enabling_matchall_with_cond(dtrace_match_cond_t *cond)
11771 {
11772 dtrace_enabling_t *enab;
11773
11774 lck_mtx_lock(&cpu_lock);
11775 lck_mtx_lock(&dtrace_lock);
11776
11777 /*
11778 * Iterate over all retained enablings to see if any probes match
11779 * against them. We only perform this operation on enablings for which
11780 * we have sufficient permissions by virtue of being in the global zone
11781 * or in the same zone as the DTrace client. Because we can be called
11782 * after dtrace_detach() has been called, we cannot assert that there
11783 * are retained enablings. We can safely load from dtrace_retained,
11784 * however: the taskq_destroy() at the end of dtrace_detach() will
11785 * block pending our completion.
11786 */
11787
11788 /*
11789 * Darwin doesn't do zones.
11790 * Behave as if always in "global" zone."
11791 */
11792 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11793 (void) dtrace_enabling_match(enab, NULL, cond);
11794 }
11795
11796 lck_mtx_unlock(&dtrace_lock);
11797 lck_mtx_unlock(&cpu_lock);
11798
11799 }
11800
11801 static void
11802 dtrace_enabling_matchall(void)
11803 {
11804 dtrace_enabling_matchall_with_cond(NULL);
11805 }
11806
11807
11808
11809 /*
11810 * If an enabling is to be enabled without having matched probes (that is, if
11811 * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11812 * enabling must be _primed_ by creating an ECB for every ECB description.
11813 * This must be done to assure that we know the number of speculations, the
11814 * number of aggregations, the minimum buffer size needed, etc. before we
11815 * transition out of DTRACE_ACTIVITY_INACTIVE. To do this without actually
11816 * enabling any probes, we create ECBs for every ECB decription, but with a
11817 * NULL probe -- which is exactly what this function does.
11818 */
11819 static void
11820 dtrace_enabling_prime(dtrace_state_t *state)
11821 {
11822 dtrace_enabling_t *enab;
11823 int i;
11824
11825 for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11826 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11827
11828 if (enab->dten_vstate->dtvs_state != state)
11829 continue;
11830
11831 /*
11832 * We don't want to prime an enabling more than once, lest
11833 * we allow a malicious user to induce resource exhaustion.
11834 * (The ECBs that result from priming an enabling aren't
11835 * leaked -- but they also aren't deallocated until the
11836 * consumer state is destroyed.)
11837 */
11838 if (enab->dten_primed)
11839 continue;
11840
11841 for (i = 0; i < enab->dten_ndesc; i++) {
11842 enab->dten_current = enab->dten_desc[i];
11843 (void) dtrace_probe_enable(NULL, enab);
11844 }
11845
11846 enab->dten_primed = 1;
11847 }
11848 }
11849
11850 /*
11851 * Called to indicate that probes should be provided due to retained
11852 * enablings. This is implemented in terms of dtrace_probe_provide(), but it
11853 * must take an initial lap through the enabling calling the dtps_provide()
11854 * entry point explicitly to allow for autocreated probes.
11855 */
11856 static void
11857 dtrace_enabling_provide(dtrace_provider_t *prv)
11858 {
11859 int i, all = 0;
11860 dtrace_probedesc_t desc;
11861 dtrace_genid_t gen;
11862
11863 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11864 lck_mtx_assert(&dtrace_provider_lock, LCK_MTX_ASSERT_OWNED);
11865
11866 if (prv == NULL) {
11867 all = 1;
11868 prv = dtrace_provider;
11869 }
11870
11871 do {
11872 dtrace_enabling_t *enab;
11873 void *parg = prv->dtpv_arg;
11874
11875 retry:
11876 gen = dtrace_retained_gen;
11877 for (enab = dtrace_retained; enab != NULL;
11878 enab = enab->dten_next) {
11879 for (i = 0; i < enab->dten_ndesc; i++) {
11880 desc = enab->dten_desc[i]->dted_probe;
11881 lck_mtx_unlock(&dtrace_lock);
11882 prv->dtpv_pops.dtps_provide(parg, &desc);
11883 lck_mtx_lock(&dtrace_lock);
11884 /*
11885 * Process the retained enablings again if
11886 * they have changed while we weren't holding
11887 * dtrace_lock.
11888 */
11889 if (gen != dtrace_retained_gen)
11890 goto retry;
11891 }
11892 }
11893 } while (all && (prv = prv->dtpv_next) != NULL);
11894
11895 lck_mtx_unlock(&dtrace_lock);
11896 dtrace_probe_provide(NULL, all ? NULL : prv);
11897 lck_mtx_lock(&dtrace_lock);
11898 }
11899
11900 /*
11901 * DTrace DOF Functions
11902 */
11903 /*ARGSUSED*/
11904 static void
11905 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11906 {
11907 #pragma unused(dof) /* __APPLE__ */
11908 if (dtrace_err_verbose)
11909 cmn_err(CE_WARN, "failed to process DOF: %s", str);
11910
11911 #ifdef DTRACE_ERRDEBUG
11912 dtrace_errdebug(str);
11913 #endif
11914 }
11915
11916 /*
11917 * Create DOF out of a currently enabled state. Right now, we only create
11918 * DOF containing the run-time options -- but this could be expanded to create
11919 * complete DOF representing the enabled state.
11920 */
11921 static dof_hdr_t *
11922 dtrace_dof_create(dtrace_state_t *state)
11923 {
11924 dof_hdr_t *dof;
11925 dof_sec_t *sec;
11926 dof_optdesc_t *opt;
11927 int i, len = sizeof (dof_hdr_t) +
11928 roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11929 sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11930
11931 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
11932
11933 dof = dt_kmem_zalloc_aligned(len, 8, KM_SLEEP);
11934 dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11935 dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11936 dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11937 dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11938
11939 dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11940 dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11941 dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11942 dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11943 dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11944 dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11945
11946 dof->dofh_flags = 0;
11947 dof->dofh_hdrsize = sizeof (dof_hdr_t);
11948 dof->dofh_secsize = sizeof (dof_sec_t);
11949 dof->dofh_secnum = 1; /* only DOF_SECT_OPTDESC */
11950 dof->dofh_secoff = sizeof (dof_hdr_t);
11951 dof->dofh_loadsz = len;
11952 dof->dofh_filesz = len;
11953 dof->dofh_pad = 0;
11954
11955 /*
11956 * Fill in the option section header...
11957 */
11958 sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11959 sec->dofs_type = DOF_SECT_OPTDESC;
11960 sec->dofs_align = sizeof (uint64_t);
11961 sec->dofs_flags = DOF_SECF_LOAD;
11962 sec->dofs_entsize = sizeof (dof_optdesc_t);
11963
11964 opt = (dof_optdesc_t *)((uintptr_t)sec +
11965 roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11966
11967 sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11968 sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11969
11970 for (i = 0; i < DTRACEOPT_MAX; i++) {
11971 opt[i].dofo_option = i;
11972 opt[i].dofo_strtab = DOF_SECIDX_NONE;
11973 opt[i].dofo_value = state->dts_options[i];
11974 }
11975
11976 return (dof);
11977 }
11978
11979 static dof_hdr_t *
11980 dtrace_dof_copyin(user_addr_t uarg, int *errp)
11981 {
11982 dof_hdr_t hdr, *dof;
11983
11984 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
11985
11986 /*
11987 * First, we're going to copyin() the sizeof (dof_hdr_t).
11988 */
11989 if (copyin(uarg, &hdr, sizeof (hdr)) != 0) {
11990 dtrace_dof_error(NULL, "failed to copyin DOF header");
11991 *errp = EFAULT;
11992 return (NULL);
11993 }
11994
11995 /*
11996 * Now we'll allocate the entire DOF and copy it in -- provided
11997 * that the length isn't outrageous.
11998 */
11999 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
12000 dtrace_dof_error(&hdr, "load size exceeds maximum");
12001 *errp = E2BIG;
12002 return (NULL);
12003 }
12004
12005 if (hdr.dofh_loadsz < sizeof (hdr)) {
12006 dtrace_dof_error(&hdr, "invalid load size");
12007 *errp = EINVAL;
12008 return (NULL);
12009 }
12010
12011 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
12012
12013 if (copyin(uarg, dof, hdr.dofh_loadsz) != 0 ||
12014 dof->dofh_loadsz != hdr.dofh_loadsz) {
12015 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
12016 *errp = EFAULT;
12017 return (NULL);
12018 }
12019
12020 return (dof);
12021 }
12022
12023 static dof_hdr_t *
12024 dtrace_dof_copyin_from_proc(proc_t* p, user_addr_t uarg, int *errp)
12025 {
12026 dof_hdr_t hdr, *dof;
12027
12028 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
12029
12030 /*
12031 * First, we're going to copyin() the sizeof (dof_hdr_t).
12032 */
12033 if (uread(p, &hdr, sizeof(hdr), uarg) != KERN_SUCCESS) {
12034 dtrace_dof_error(NULL, "failed to copyin DOF header");
12035 *errp = EFAULT;
12036 return (NULL);
12037 }
12038
12039 /*
12040 * Now we'll allocate the entire DOF and copy it in -- provided
12041 * that the length isn't outrageous.
12042 */
12043 if (hdr.dofh_loadsz >= (uint64_t)dtrace_dof_maxsize) {
12044 dtrace_dof_error(&hdr, "load size exceeds maximum");
12045 *errp = E2BIG;
12046 return (NULL);
12047 }
12048
12049 if (hdr.dofh_loadsz < sizeof (hdr)) {
12050 dtrace_dof_error(&hdr, "invalid load size");
12051 *errp = EINVAL;
12052 return (NULL);
12053 }
12054
12055 dof = dt_kmem_alloc_aligned(hdr.dofh_loadsz, 8, KM_SLEEP);
12056
12057 if (uread(p, dof, hdr.dofh_loadsz, uarg) != KERN_SUCCESS) {
12058 dt_kmem_free_aligned(dof, hdr.dofh_loadsz);
12059 *errp = EFAULT;
12060 return (NULL);
12061 }
12062
12063 return (dof);
12064 }
12065
12066 static dof_hdr_t *
12067 dtrace_dof_property(const char *name)
12068 {
12069 uchar_t *buf;
12070 uint64_t loadsz;
12071 unsigned int len, i;
12072 dof_hdr_t *dof;
12073
12074 /*
12075 * Unfortunately, array of values in .conf files are always (and
12076 * only) interpreted to be integer arrays. We must read our DOF
12077 * as an integer array, and then squeeze it into a byte array.
12078 */
12079 if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12080 name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12081 return (NULL);
12082
12083 for (i = 0; i < len; i++)
12084 buf[i] = (uchar_t)(((int *)buf)[i]);
12085
12086 if (len < sizeof (dof_hdr_t)) {
12087 ddi_prop_free(buf);
12088 dtrace_dof_error(NULL, "truncated header");
12089 return (NULL);
12090 }
12091
12092 if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12093 ddi_prop_free(buf);
12094 dtrace_dof_error(NULL, "truncated DOF");
12095 return (NULL);
12096 }
12097
12098 if (loadsz >= (uint64_t)dtrace_dof_maxsize) {
12099 ddi_prop_free(buf);
12100 dtrace_dof_error(NULL, "oversized DOF");
12101 return (NULL);
12102 }
12103
12104 dof = dt_kmem_alloc_aligned(loadsz, 8, KM_SLEEP);
12105 bcopy(buf, dof, loadsz);
12106 ddi_prop_free(buf);
12107
12108 return (dof);
12109 }
12110
12111 static void
12112 dtrace_dof_destroy(dof_hdr_t *dof)
12113 {
12114 dt_kmem_free_aligned(dof, dof->dofh_loadsz);
12115 }
12116
12117 /*
12118 * Return the dof_sec_t pointer corresponding to a given section index. If the
12119 * index is not valid, dtrace_dof_error() is called and NULL is returned. If
12120 * a type other than DOF_SECT_NONE is specified, the header is checked against
12121 * this type and NULL is returned if the types do not match.
12122 */
12123 static dof_sec_t *
12124 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12125 {
12126 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12127 ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12128
12129 if (i >= dof->dofh_secnum) {
12130 dtrace_dof_error(dof, "referenced section index is invalid");
12131 return (NULL);
12132 }
12133
12134 if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12135 dtrace_dof_error(dof, "referenced section is not loadable");
12136 return (NULL);
12137 }
12138
12139 if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12140 dtrace_dof_error(dof, "referenced section is the wrong type");
12141 return (NULL);
12142 }
12143
12144 return (sec);
12145 }
12146
12147 static dtrace_probedesc_t *
12148 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12149 {
12150 dof_probedesc_t *probe;
12151 dof_sec_t *strtab;
12152 uintptr_t daddr = (uintptr_t)dof;
12153 uintptr_t str;
12154 size_t size;
12155
12156 if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12157 dtrace_dof_error(dof, "invalid probe section");
12158 return (NULL);
12159 }
12160
12161 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12162 dtrace_dof_error(dof, "bad alignment in probe description");
12163 return (NULL);
12164 }
12165
12166 if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12167 dtrace_dof_error(dof, "truncated probe description");
12168 return (NULL);
12169 }
12170
12171 probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12172 strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12173
12174 if (strtab == NULL)
12175 return (NULL);
12176
12177 str = daddr + strtab->dofs_offset;
12178 size = strtab->dofs_size;
12179
12180 if (probe->dofp_provider >= strtab->dofs_size) {
12181 dtrace_dof_error(dof, "corrupt probe provider");
12182 return (NULL);
12183 }
12184
12185 (void) strncpy(desc->dtpd_provider,
12186 (char *)(str + probe->dofp_provider),
12187 MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12188
12189 /* APPLE NOTE: Darwin employs size bounded string operation. */
12190 desc->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
12191
12192 if (probe->dofp_mod >= strtab->dofs_size) {
12193 dtrace_dof_error(dof, "corrupt probe module");
12194 return (NULL);
12195 }
12196
12197 (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12198 MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12199
12200 /* APPLE NOTE: Darwin employs size bounded string operation. */
12201 desc->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
12202
12203 if (probe->dofp_func >= strtab->dofs_size) {
12204 dtrace_dof_error(dof, "corrupt probe function");
12205 return (NULL);
12206 }
12207
12208 (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12209 MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12210
12211 /* APPLE NOTE: Darwin employs size bounded string operation. */
12212 desc->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
12213
12214 if (probe->dofp_name >= strtab->dofs_size) {
12215 dtrace_dof_error(dof, "corrupt probe name");
12216 return (NULL);
12217 }
12218
12219 (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12220 MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12221
12222 /* APPLE NOTE: Darwin employs size bounded string operation. */
12223 desc->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
12224
12225 return (desc);
12226 }
12227
12228 static dtrace_difo_t *
12229 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12230 cred_t *cr)
12231 {
12232 dtrace_difo_t *dp;
12233 size_t ttl = 0;
12234 dof_difohdr_t *dofd;
12235 uintptr_t daddr = (uintptr_t)dof;
12236 size_t max_size = dtrace_difo_maxsize;
12237 uint_t i;
12238 int l, n;
12239
12240
12241 static const struct {
12242 int section;
12243 int bufoffs;
12244 int lenoffs;
12245 int entsize;
12246 int align;
12247 const char *msg;
12248 } difo[] = {
12249 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12250 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12251 sizeof (dif_instr_t), "multiple DIF sections" },
12252
12253 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12254 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12255 sizeof (uint64_t), "multiple integer tables" },
12256
12257 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12258 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12259 sizeof (char), "multiple string tables" },
12260
12261 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12262 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12263 sizeof (uint_t), "multiple variable tables" },
12264
12265 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12266 };
12267
12268 if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12269 dtrace_dof_error(dof, "invalid DIFO header section");
12270 return (NULL);
12271 }
12272
12273 if (sec->dofs_align != sizeof (dof_secidx_t)) {
12274 dtrace_dof_error(dof, "bad alignment in DIFO header");
12275 return (NULL);
12276 }
12277
12278 if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12279 sec->dofs_size % sizeof (dof_secidx_t)) {
12280 dtrace_dof_error(dof, "bad size in DIFO header");
12281 return (NULL);
12282 }
12283
12284 dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12285 n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12286
12287 dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12288 dp->dtdo_rtype = dofd->dofd_rtype;
12289
12290 for (l = 0; l < n; l++) {
12291 dof_sec_t *subsec;
12292 void **bufp;
12293 uint32_t *lenp;
12294
12295 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12296 dofd->dofd_links[l])) == NULL)
12297 goto err; /* invalid section link */
12298
12299 if (ttl + subsec->dofs_size > max_size) {
12300 dtrace_dof_error(dof, "exceeds maximum size");
12301 goto err;
12302 }
12303
12304 ttl += subsec->dofs_size;
12305
12306 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12307
12308 if (subsec->dofs_type != (uint32_t)difo[i].section)
12309 continue;
12310
12311 if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12312 dtrace_dof_error(dof, "section not loaded");
12313 goto err;
12314 }
12315
12316 if (subsec->dofs_align != (uint32_t)difo[i].align) {
12317 dtrace_dof_error(dof, "bad alignment");
12318 goto err;
12319 }
12320
12321 bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12322 lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12323
12324 if (*bufp != NULL) {
12325 dtrace_dof_error(dof, difo[i].msg);
12326 goto err;
12327 }
12328
12329 if ((uint32_t)difo[i].entsize != subsec->dofs_entsize) {
12330 dtrace_dof_error(dof, "entry size mismatch");
12331 goto err;
12332 }
12333
12334 if (subsec->dofs_entsize != 0 &&
12335 (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12336 dtrace_dof_error(dof, "corrupt entry size");
12337 goto err;
12338 }
12339
12340 *lenp = subsec->dofs_size;
12341 *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12342 bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12343 *bufp, subsec->dofs_size);
12344
12345 if (subsec->dofs_entsize != 0)
12346 *lenp /= subsec->dofs_entsize;
12347
12348 break;
12349 }
12350
12351 /*
12352 * If we encounter a loadable DIFO sub-section that is not
12353 * known to us, assume this is a broken program and fail.
12354 */
12355 if (difo[i].section == DOF_SECT_NONE &&
12356 (subsec->dofs_flags & DOF_SECF_LOAD)) {
12357 dtrace_dof_error(dof, "unrecognized DIFO subsection");
12358 goto err;
12359 }
12360 }
12361
12362 if (dp->dtdo_buf == NULL) {
12363 /*
12364 * We can't have a DIF object without DIF text.
12365 */
12366 dtrace_dof_error(dof, "missing DIF text");
12367 goto err;
12368 }
12369
12370 /*
12371 * Before we validate the DIF object, run through the variable table
12372 * looking for the strings -- if any of their size are under, we'll set
12373 * their size to be the system-wide default string size. Note that
12374 * this should _not_ happen if the "strsize" option has been set --
12375 * in this case, the compiler should have set the size to reflect the
12376 * setting of the option.
12377 */
12378 for (i = 0; i < dp->dtdo_varlen; i++) {
12379 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12380 dtrace_diftype_t *t = &v->dtdv_type;
12381
12382 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12383 continue;
12384
12385 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12386 t->dtdt_size = dtrace_strsize_default;
12387 }
12388
12389 if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12390 goto err;
12391
12392 dtrace_difo_init(dp, vstate);
12393 return (dp);
12394
12395 err:
12396 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12397 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12398 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12399 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12400
12401 kmem_free(dp, sizeof (dtrace_difo_t));
12402 return (NULL);
12403 }
12404
12405 static dtrace_predicate_t *
12406 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12407 cred_t *cr)
12408 {
12409 dtrace_difo_t *dp;
12410
12411 if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12412 return (NULL);
12413
12414 return (dtrace_predicate_create(dp));
12415 }
12416
12417 static dtrace_actdesc_t *
12418 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12419 cred_t *cr)
12420 {
12421 dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12422 dof_actdesc_t *desc;
12423 dof_sec_t *difosec;
12424 size_t offs;
12425 uintptr_t daddr = (uintptr_t)dof;
12426 uint64_t arg;
12427 dtrace_actkind_t kind;
12428
12429 if (sec->dofs_type != DOF_SECT_ACTDESC) {
12430 dtrace_dof_error(dof, "invalid action section");
12431 return (NULL);
12432 }
12433
12434 if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12435 dtrace_dof_error(dof, "truncated action description");
12436 return (NULL);
12437 }
12438
12439 if (sec->dofs_align != sizeof (uint64_t)) {
12440 dtrace_dof_error(dof, "bad alignment in action description");
12441 return (NULL);
12442 }
12443
12444 if (sec->dofs_size < sec->dofs_entsize) {
12445 dtrace_dof_error(dof, "section entry size exceeds total size");
12446 return (NULL);
12447 }
12448
12449 if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12450 dtrace_dof_error(dof, "bad entry size in action description");
12451 return (NULL);
12452 }
12453
12454 if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12455 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12456 return (NULL);
12457 }
12458
12459 for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12460 desc = (dof_actdesc_t *)(daddr +
12461 (uintptr_t)sec->dofs_offset + offs);
12462 kind = (dtrace_actkind_t)desc->dofa_kind;
12463
12464 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12465 (kind != DTRACEACT_PRINTA || desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12466 (kind == DTRACEACT_DIFEXPR && desc->dofa_strtab != DOF_SECIDX_NONE))
12467 {
12468 dof_sec_t *strtab;
12469 char *str, *fmt;
12470 uint64_t i;
12471
12472 /*
12473 * The argument to these actions is an index into the
12474 * DOF string table. For printf()-like actions, this
12475 * is the format string. For print(), this is the
12476 * CTF type of the expression result.
12477 */
12478 if ((strtab = dtrace_dof_sect(dof,
12479 DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12480 goto err;
12481
12482 str = (char *)((uintptr_t)dof +
12483 (uintptr_t)strtab->dofs_offset);
12484
12485 for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12486 if (str[i] == '\0')
12487 break;
12488 }
12489
12490 if (i >= strtab->dofs_size) {
12491 dtrace_dof_error(dof, "bogus format string");
12492 goto err;
12493 }
12494
12495 if (i == desc->dofa_arg) {
12496 dtrace_dof_error(dof, "empty format string");
12497 goto err;
12498 }
12499
12500 i -= desc->dofa_arg;
12501 fmt = kmem_alloc(i + 1, KM_SLEEP);
12502 bcopy(&str[desc->dofa_arg], fmt, i + 1);
12503 arg = (uint64_t)(uintptr_t)fmt;
12504 } else {
12505 if (kind == DTRACEACT_PRINTA) {
12506 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12507 arg = 0;
12508 } else {
12509 arg = desc->dofa_arg;
12510 }
12511 }
12512
12513 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12514 desc->dofa_uarg, arg);
12515
12516 if (last != NULL) {
12517 last->dtad_next = act;
12518 } else {
12519 first = act;
12520 }
12521
12522 last = act;
12523
12524 if (desc->dofa_difo == DOF_SECIDX_NONE)
12525 continue;
12526
12527 if ((difosec = dtrace_dof_sect(dof,
12528 DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12529 goto err;
12530
12531 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12532
12533 if (act->dtad_difo == NULL)
12534 goto err;
12535 }
12536
12537 ASSERT(first != NULL);
12538 return (first);
12539
12540 err:
12541 for (act = first; act != NULL; act = next) {
12542 next = act->dtad_next;
12543 dtrace_actdesc_release(act, vstate);
12544 }
12545
12546 return (NULL);
12547 }
12548
12549 static dtrace_ecbdesc_t *
12550 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12551 cred_t *cr)
12552 {
12553 dtrace_ecbdesc_t *ep;
12554 dof_ecbdesc_t *ecb;
12555 dtrace_probedesc_t *desc;
12556 dtrace_predicate_t *pred = NULL;
12557
12558 if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12559 dtrace_dof_error(dof, "truncated ECB description");
12560 return (NULL);
12561 }
12562
12563 if (sec->dofs_align != sizeof (uint64_t)) {
12564 dtrace_dof_error(dof, "bad alignment in ECB description");
12565 return (NULL);
12566 }
12567
12568 ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12569 sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12570
12571 if (sec == NULL)
12572 return (NULL);
12573
12574 ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12575 ep->dted_uarg = ecb->dofe_uarg;
12576 desc = &ep->dted_probe;
12577
12578 if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12579 goto err;
12580
12581 if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12582 if ((sec = dtrace_dof_sect(dof,
12583 DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12584 goto err;
12585
12586 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12587 goto err;
12588
12589 ep->dted_pred.dtpdd_predicate = pred;
12590 }
12591
12592 if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12593 if ((sec = dtrace_dof_sect(dof,
12594 DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12595 goto err;
12596
12597 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12598
12599 if (ep->dted_action == NULL)
12600 goto err;
12601 }
12602
12603 return (ep);
12604
12605 err:
12606 if (pred != NULL)
12607 dtrace_predicate_release(pred, vstate);
12608 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12609 return (NULL);
12610 }
12611
12612 /*
12613 * APPLE NOTE: dyld handles dof relocation.
12614 * Darwin does not need dtrace_dof_relocate()
12615 */
12616
12617 /*
12618 * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12619 * header: it should be at the front of a memory region that is at least
12620 * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12621 * size. It need not be validated in any other way.
12622 */
12623 static int
12624 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12625 dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12626 {
12627 #pragma unused(ubase) /* __APPLE__ */
12628 uint64_t len = dof->dofh_loadsz, seclen;
12629 uintptr_t daddr = (uintptr_t)dof;
12630 dtrace_ecbdesc_t *ep;
12631 dtrace_enabling_t *enab;
12632 uint_t i;
12633
12634 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12635 ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12636
12637 /*
12638 * Check the DOF header identification bytes. In addition to checking
12639 * valid settings, we also verify that unused bits/bytes are zeroed so
12640 * we can use them later without fear of regressing existing binaries.
12641 */
12642 if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12643 DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12644 dtrace_dof_error(dof, "DOF magic string mismatch");
12645 return (-1);
12646 }
12647
12648 if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12649 dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12650 dtrace_dof_error(dof, "DOF has invalid data model");
12651 return (-1);
12652 }
12653
12654 if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12655 dtrace_dof_error(dof, "DOF encoding mismatch");
12656 return (-1);
12657 }
12658
12659 /*
12660 * APPLE NOTE: Darwin only supports DOF_VERSION_3 for now.
12661 */
12662 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_3) {
12663 dtrace_dof_error(dof, "DOF version mismatch");
12664 return (-1);
12665 }
12666
12667 if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12668 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12669 return (-1);
12670 }
12671
12672 if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12673 dtrace_dof_error(dof, "DOF uses too many integer registers");
12674 return (-1);
12675 }
12676
12677 if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12678 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12679 return (-1);
12680 }
12681
12682 for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12683 if (dof->dofh_ident[i] != 0) {
12684 dtrace_dof_error(dof, "DOF has invalid ident byte set");
12685 return (-1);
12686 }
12687 }
12688
12689 if (dof->dofh_flags & ~DOF_FL_VALID) {
12690 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12691 return (-1);
12692 }
12693
12694 if (dof->dofh_secsize == 0) {
12695 dtrace_dof_error(dof, "zero section header size");
12696 return (-1);
12697 }
12698
12699 /*
12700 * Check that the section headers don't exceed the amount of DOF
12701 * data. Note that we cast the section size and number of sections
12702 * to uint64_t's to prevent possible overflow in the multiplication.
12703 */
12704 seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12705
12706 if (dof->dofh_secoff > len || seclen > len ||
12707 dof->dofh_secoff + seclen > len) {
12708 dtrace_dof_error(dof, "truncated section headers");
12709 return (-1);
12710 }
12711
12712 if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12713 dtrace_dof_error(dof, "misaligned section headers");
12714 return (-1);
12715 }
12716
12717 if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12718 dtrace_dof_error(dof, "misaligned section size");
12719 return (-1);
12720 }
12721
12722 /*
12723 * Take an initial pass through the section headers to be sure that
12724 * the headers don't have stray offsets. If the 'noprobes' flag is
12725 * set, do not permit sections relating to providers, probes, or args.
12726 */
12727 for (i = 0; i < dof->dofh_secnum; i++) {
12728 dof_sec_t *sec = (dof_sec_t *)(daddr +
12729 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12730
12731 if (noprobes) {
12732 switch (sec->dofs_type) {
12733 case DOF_SECT_PROVIDER:
12734 case DOF_SECT_PROBES:
12735 case DOF_SECT_PRARGS:
12736 case DOF_SECT_PROFFS:
12737 dtrace_dof_error(dof, "illegal sections "
12738 "for enabling");
12739 return (-1);
12740 }
12741 }
12742
12743 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12744 continue; /* just ignore non-loadable sections */
12745
12746 if (sec->dofs_align & (sec->dofs_align - 1)) {
12747 dtrace_dof_error(dof, "bad section alignment");
12748 return (-1);
12749 }
12750
12751 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12752 dtrace_dof_error(dof, "misaligned section");
12753 return (-1);
12754 }
12755
12756 if (sec->dofs_offset > len || sec->dofs_size > len ||
12757 sec->dofs_offset + sec->dofs_size > len) {
12758 dtrace_dof_error(dof, "corrupt section header");
12759 return (-1);
12760 }
12761
12762 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12763 sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12764 dtrace_dof_error(dof, "non-terminating string table");
12765 return (-1);
12766 }
12767 }
12768
12769 /*
12770 * APPLE NOTE: We have no further relocation to perform.
12771 * All dof values are relative offsets.
12772 */
12773
12774 if ((enab = *enabp) == NULL)
12775 enab = *enabp = dtrace_enabling_create(vstate);
12776
12777 for (i = 0; i < dof->dofh_secnum; i++) {
12778 dof_sec_t *sec = (dof_sec_t *)(daddr +
12779 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12780
12781 if (sec->dofs_type != DOF_SECT_ECBDESC)
12782 continue;
12783
12784 /*
12785 * APPLE NOTE: Defend against gcc 4.0 botch on x86.
12786 * not all paths out of inlined dtrace_dof_ecbdesc
12787 * are checked for the NULL return value.
12788 * Check for NULL explicitly here.
12789 */
12790 ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr);
12791 if (ep == NULL) {
12792 dtrace_enabling_destroy(enab);
12793 *enabp = NULL;
12794 return (-1);
12795 }
12796
12797 dtrace_enabling_add(enab, ep);
12798 }
12799
12800 return (0);
12801 }
12802
12803 /*
12804 * Process DOF for any options. This routine assumes that the DOF has been
12805 * at least processed by dtrace_dof_slurp().
12806 */
12807 static int
12808 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12809 {
12810 uint_t i;
12811 int rval;
12812 uint32_t entsize;
12813 size_t offs;
12814 dof_optdesc_t *desc;
12815
12816 for (i = 0; i < dof->dofh_secnum; i++) {
12817 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12818 (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12819
12820 if (sec->dofs_type != DOF_SECT_OPTDESC)
12821 continue;
12822
12823 if (sec->dofs_align != sizeof (uint64_t)) {
12824 dtrace_dof_error(dof, "bad alignment in "
12825 "option description");
12826 return (EINVAL);
12827 }
12828
12829 if ((entsize = sec->dofs_entsize) == 0) {
12830 dtrace_dof_error(dof, "zeroed option entry size");
12831 return (EINVAL);
12832 }
12833
12834 if (entsize < sizeof (dof_optdesc_t)) {
12835 dtrace_dof_error(dof, "bad option entry size");
12836 return (EINVAL);
12837 }
12838
12839 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12840 desc = (dof_optdesc_t *)((uintptr_t)dof +
12841 (uintptr_t)sec->dofs_offset + offs);
12842
12843 if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12844 dtrace_dof_error(dof, "non-zero option string");
12845 return (EINVAL);
12846 }
12847
12848 if (desc->dofo_value == (uint64_t)DTRACEOPT_UNSET) {
12849 dtrace_dof_error(dof, "unset option");
12850 return (EINVAL);
12851 }
12852
12853 if ((rval = dtrace_state_option(state,
12854 desc->dofo_option, desc->dofo_value)) != 0) {
12855 dtrace_dof_error(dof, "rejected option");
12856 return (rval);
12857 }
12858 }
12859 }
12860
12861 return (0);
12862 }
12863
12864 /*
12865 * DTrace Consumer State Functions
12866 */
12867 static int
12868 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12869 {
12870 size_t hashsize, maxper, min_size, chunksize = dstate->dtds_chunksize;
12871 void *base;
12872 uintptr_t limit;
12873 dtrace_dynvar_t *dvar, *next, *start;
12874 size_t i;
12875
12876 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
12877 ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12878
12879 bzero(dstate, sizeof (dtrace_dstate_t));
12880
12881 if ((dstate->dtds_chunksize = chunksize) == 0)
12882 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12883
12884 VERIFY(dstate->dtds_chunksize < (LONG_MAX - sizeof (dtrace_dynhash_t)));
12885
12886 if (size < (min_size = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12887 size = min_size;
12888
12889 if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12890 return (ENOMEM);
12891
12892 dstate->dtds_size = size;
12893 dstate->dtds_base = base;
12894 dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12895 bzero(dstate->dtds_percpu, (int)NCPU * sizeof (dtrace_dstate_percpu_t));
12896
12897 hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12898
12899 if (hashsize != 1 && (hashsize & 1))
12900 hashsize--;
12901
12902 dstate->dtds_hashsize = hashsize;
12903 dstate->dtds_hash = dstate->dtds_base;
12904
12905 /*
12906 * Set all of our hash buckets to point to the single sink, and (if
12907 * it hasn't already been set), set the sink's hash value to be the
12908 * sink sentinel value. The sink is needed for dynamic variable
12909 * lookups to know that they have iterated over an entire, valid hash
12910 * chain.
12911 */
12912 for (i = 0; i < hashsize; i++)
12913 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12914
12915 if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12916 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12917
12918 /*
12919 * Determine number of active CPUs. Divide free list evenly among
12920 * active CPUs.
12921 */
12922 start = (dtrace_dynvar_t *)
12923 ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12924 limit = (uintptr_t)base + size;
12925
12926 VERIFY((uintptr_t)start < limit);
12927 VERIFY((uintptr_t)start >= (uintptr_t)base);
12928
12929 maxper = (limit - (uintptr_t)start) / (int)NCPU;
12930 maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12931
12932 for (i = 0; i < NCPU; i++) {
12933 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12934
12935 /*
12936 * If we don't even have enough chunks to make it once through
12937 * NCPUs, we're just going to allocate everything to the first
12938 * CPU. And if we're on the last CPU, we're going to allocate
12939 * whatever is left over. In either case, we set the limit to
12940 * be the limit of the dynamic variable space.
12941 */
12942 if (maxper == 0 || i == NCPU - 1) {
12943 limit = (uintptr_t)base + size;
12944 start = NULL;
12945 } else {
12946 limit = (uintptr_t)start + maxper;
12947 start = (dtrace_dynvar_t *)limit;
12948 }
12949
12950 VERIFY(limit <= (uintptr_t)base + size);
12951
12952 for (;;) {
12953 next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12954 dstate->dtds_chunksize);
12955
12956 if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12957 break;
12958
12959 VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
12960 (uintptr_t)dvar <= (uintptr_t)base + size);
12961 dvar->dtdv_next = next;
12962 dvar = next;
12963 }
12964
12965 if (maxper == 0)
12966 break;
12967 }
12968
12969 return (0);
12970 }
12971
12972 static void
12973 dtrace_dstate_fini(dtrace_dstate_t *dstate)
12974 {
12975 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
12976
12977 if (dstate->dtds_base == NULL)
12978 return;
12979
12980 kmem_free(dstate->dtds_base, dstate->dtds_size);
12981 kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
12982 }
12983
12984 static void
12985 dtrace_vstate_fini(dtrace_vstate_t *vstate)
12986 {
12987 /*
12988 * Logical XOR, where are you?
12989 */
12990 ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12991
12992 if (vstate->dtvs_nglobals > 0) {
12993 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12994 sizeof (dtrace_statvar_t *));
12995 }
12996
12997 if (vstate->dtvs_ntlocals > 0) {
12998 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12999 sizeof (dtrace_difv_t));
13000 }
13001
13002 ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13003
13004 if (vstate->dtvs_nlocals > 0) {
13005 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13006 sizeof (dtrace_statvar_t *));
13007 }
13008 }
13009
13010 static void
13011 dtrace_state_clean(dtrace_state_t *state)
13012 {
13013 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13014 return;
13015
13016 dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13017 dtrace_speculation_clean(state);
13018 }
13019
13020 static void
13021 dtrace_state_deadman(dtrace_state_t *state)
13022 {
13023 hrtime_t now;
13024
13025 dtrace_sync();
13026
13027 now = dtrace_gethrtime();
13028
13029 if (state != dtrace_anon.dta_state &&
13030 now - state->dts_laststatus >= dtrace_deadman_user)
13031 return;
13032
13033 /*
13034 * We must be sure that dts_alive never appears to be less than the
13035 * value upon entry to dtrace_state_deadman(), and because we lack a
13036 * dtrace_cas64(), we cannot store to it atomically. We thus instead
13037 * store INT64_MAX to it, followed by a memory barrier, followed by
13038 * the new value. This assures that dts_alive never appears to be
13039 * less than its true value, regardless of the order in which the
13040 * stores to the underlying storage are issued.
13041 */
13042 state->dts_alive = INT64_MAX;
13043 dtrace_membar_producer();
13044 state->dts_alive = now;
13045 }
13046
13047 static int
13048 dtrace_state_create(dev_t *devp, cred_t *cr, dtrace_state_t **new_state)
13049 {
13050 minor_t minor;
13051 major_t major;
13052 char c[30];
13053 dtrace_state_t *state;
13054 dtrace_optval_t *opt;
13055 int bufsize = (int)NCPU * sizeof (dtrace_buffer_t), i;
13056
13057 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13058 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13059
13060 /* Cause restart */
13061 *new_state = NULL;
13062
13063 minor = getminor(*devp);
13064
13065 state = dtrace_state_allocate(minor);
13066 if (NULL == state) {
13067 printf("dtrace_open: couldn't acquire minor number %d. This usually means that too many DTrace clients are in use at the moment", minor);
13068 return (ERESTART); /* can't reacquire */
13069 }
13070
13071 state->dts_epid = DTRACE_EPIDNONE + 1;
13072
13073 (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13074 state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13075 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13076
13077 if (devp != NULL) {
13078 major = getemajor(*devp);
13079 } else {
13080 major = ddi_driver_major(dtrace_devi);
13081 }
13082
13083 state->dts_dev = makedevice(major, minor);
13084
13085 if (devp != NULL)
13086 *devp = state->dts_dev;
13087
13088 /*
13089 * We allocate NCPU buffers. On the one hand, this can be quite
13090 * a bit of memory per instance (nearly 36K on a Starcat). On the
13091 * other hand, it saves an additional memory reference in the probe
13092 * path.
13093 */
13094 state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13095 state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13096 state->dts_buf_over_limit = 0;
13097 state->dts_cleaner = CYCLIC_NONE;
13098 state->dts_deadman = CYCLIC_NONE;
13099 state->dts_vstate.dtvs_state = state;
13100
13101 for (i = 0; i < DTRACEOPT_MAX; i++)
13102 state->dts_options[i] = DTRACEOPT_UNSET;
13103
13104 /*
13105 * Set the default options.
13106 */
13107 opt = state->dts_options;
13108 opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13109 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13110 opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13111 opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13112 opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13113 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13114 opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13115 opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13116 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13117 opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13118 opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13119 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13120 opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13121 opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13122 opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_default;
13123
13124 /*
13125 * Depending on the user credentials, we set flag bits which alter probe
13126 * visibility or the amount of destructiveness allowed. In the case of
13127 * actual anonymous tracing, or the possession of all privileges, all of
13128 * the normal checks are bypassed.
13129 */
13130 #if defined(__APPLE__)
13131 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13132 if (dtrace_is_restricted() && !dtrace_are_restrictions_relaxed()) {
13133 /*
13134 * Allow only proc credentials when DTrace is
13135 * restricted by the current security policy
13136 */
13137 state->dts_cred.dcr_visible = DTRACE_CRV_ALLPROC;
13138 state->dts_cred.dcr_action = DTRACE_CRA_PROC | DTRACE_CRA_PROC_CONTROL | DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13139 }
13140 else {
13141 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13142 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13143 }
13144 }
13145
13146 #else
13147 if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13148 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13149 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13150 }
13151 else {
13152 /*
13153 * Set up the credentials for this instantiation. We take a
13154 * hold on the credential to prevent it from disappearing on
13155 * us; this in turn prevents the zone_t referenced by this
13156 * credential from disappearing. This means that we can
13157 * examine the credential and the zone from probe context.
13158 */
13159 crhold(cr);
13160 state->dts_cred.dcr_cred = cr;
13161
13162 /*
13163 * CRA_PROC means "we have *some* privilege for dtrace" and
13164 * unlocks the use of variables like pid, zonename, etc.
13165 */
13166 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13167 PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13168 state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13169 }
13170
13171 /*
13172 * dtrace_user allows use of syscall and profile providers.
13173 * If the user also has proc_owner and/or proc_zone, we
13174 * extend the scope to include additional visibility and
13175 * destructive power.
13176 */
13177 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13178 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13179 state->dts_cred.dcr_visible |=
13180 DTRACE_CRV_ALLPROC;
13181
13182 state->dts_cred.dcr_action |=
13183 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13184 }
13185
13186 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13187 state->dts_cred.dcr_visible |=
13188 DTRACE_CRV_ALLZONE;
13189
13190 state->dts_cred.dcr_action |=
13191 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13192 }
13193
13194 /*
13195 * If we have all privs in whatever zone this is,
13196 * we can do destructive things to processes which
13197 * have altered credentials.
13198 *
13199 * APPLE NOTE: Darwin doesn't do zones.
13200 * Behave as if zone always has destructive privs.
13201 */
13202
13203 state->dts_cred.dcr_action |=
13204 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13205 }
13206
13207 /*
13208 * Holding the dtrace_kernel privilege also implies that
13209 * the user has the dtrace_user privilege from a visibility
13210 * perspective. But without further privileges, some
13211 * destructive actions are not available.
13212 */
13213 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13214 /*
13215 * Make all probes in all zones visible. However,
13216 * this doesn't mean that all actions become available
13217 * to all zones.
13218 */
13219 state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13220 DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13221
13222 state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13223 DTRACE_CRA_PROC;
13224 /*
13225 * Holding proc_owner means that destructive actions
13226 * for *this* zone are allowed.
13227 */
13228 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13229 state->dts_cred.dcr_action |=
13230 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13231
13232 /*
13233 * Holding proc_zone means that destructive actions
13234 * for this user/group ID in all zones is allowed.
13235 */
13236 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13237 state->dts_cred.dcr_action |=
13238 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13239
13240 /*
13241 * If we have all privs in whatever zone this is,
13242 * we can do destructive things to processes which
13243 * have altered credentials.
13244 *
13245 * APPLE NOTE: Darwin doesn't do zones.
13246 * Behave as if zone always has destructive privs.
13247 */
13248 state->dts_cred.dcr_action |=
13249 DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13250 }
13251
13252 /*
13253 * Holding the dtrace_proc privilege gives control over fasttrap
13254 * and pid providers. We need to grant wider destructive
13255 * privileges in the event that the user has proc_owner and/or
13256 * proc_zone.
13257 */
13258 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13259 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13260 state->dts_cred.dcr_action |=
13261 DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13262
13263 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13264 state->dts_cred.dcr_action |=
13265 DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13266 }
13267 }
13268 #endif
13269
13270 *new_state = state;
13271 return(0); /* Success */
13272 }
13273
13274 static int
13275 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13276 {
13277 dtrace_optval_t *opt = state->dts_options, size;
13278 processorid_t cpu = 0;
13279 size_t limit = buf->dtb_size;
13280 int flags = 0, rval;
13281
13282 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13283 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13284 ASSERT(which < DTRACEOPT_MAX);
13285 ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13286 (state == dtrace_anon.dta_state &&
13287 state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13288
13289 if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13290 return (0);
13291
13292 if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13293 cpu = opt[DTRACEOPT_CPU];
13294
13295 if (which == DTRACEOPT_SPECSIZE)
13296 flags |= DTRACEBUF_NOSWITCH;
13297
13298 if (which == DTRACEOPT_BUFSIZE) {
13299 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13300 flags |= DTRACEBUF_RING;
13301
13302 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13303 flags |= DTRACEBUF_FILL;
13304
13305 if (state != dtrace_anon.dta_state ||
13306 state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13307 flags |= DTRACEBUF_INACTIVE;
13308 }
13309
13310 for (size = opt[which]; (size_t)size >= sizeof (uint64_t); size >>= 1) {
13311 /*
13312 * The size must be 8-byte aligned. If the size is not 8-byte
13313 * aligned, drop it down by the difference.
13314 */
13315 if (size & (sizeof (uint64_t) - 1))
13316 size -= size & (sizeof (uint64_t) - 1);
13317
13318 if (size < state->dts_reserve) {
13319 /*
13320 * Buffers always must be large enough to accommodate
13321 * their prereserved space. We return E2BIG instead
13322 * of ENOMEM in this case to allow for user-level
13323 * software to differentiate the cases.
13324 */
13325 return (E2BIG);
13326 }
13327 limit = opt[DTRACEOPT_BUFLIMIT] * size / 100;
13328 rval = dtrace_buffer_alloc(buf, limit, size, flags, cpu);
13329
13330 if (rval != ENOMEM) {
13331 opt[which] = size;
13332 return (rval);
13333 }
13334
13335 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13336 return (rval);
13337 }
13338
13339 return (ENOMEM);
13340 }
13341
13342 static int
13343 dtrace_state_buffers(dtrace_state_t *state)
13344 {
13345 dtrace_speculation_t *spec = state->dts_speculations;
13346 int rval, i;
13347
13348 if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13349 DTRACEOPT_BUFSIZE)) != 0)
13350 return (rval);
13351
13352 if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13353 DTRACEOPT_AGGSIZE)) != 0)
13354 return (rval);
13355
13356 for (i = 0; i < state->dts_nspeculations; i++) {
13357 if ((rval = dtrace_state_buffer(state,
13358 spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13359 return (rval);
13360 }
13361
13362 return (0);
13363 }
13364
13365 static void
13366 dtrace_state_prereserve(dtrace_state_t *state)
13367 {
13368 dtrace_ecb_t *ecb;
13369 dtrace_probe_t *probe;
13370
13371 state->dts_reserve = 0;
13372
13373 if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13374 return;
13375
13376 /*
13377 * If our buffer policy is a "fill" buffer policy, we need to set the
13378 * prereserved space to be the space required by the END probes.
13379 */
13380 probe = dtrace_probes[dtrace_probeid_end - 1];
13381 ASSERT(probe != NULL);
13382
13383 for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13384 if (ecb->dte_state != state)
13385 continue;
13386
13387 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13388 }
13389 }
13390
13391 static int
13392 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13393 {
13394 dtrace_optval_t *opt = state->dts_options, sz, nspec;
13395 dtrace_speculation_t *spec;
13396 dtrace_buffer_t *buf;
13397 cyc_handler_t hdlr;
13398 cyc_time_t when;
13399 int rval = 0, i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
13400 dtrace_icookie_t cookie;
13401
13402 lck_mtx_lock(&cpu_lock);
13403 lck_mtx_lock(&dtrace_lock);
13404
13405 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13406 rval = EBUSY;
13407 goto out;
13408 }
13409
13410 /*
13411 * Before we can perform any checks, we must prime all of the
13412 * retained enablings that correspond to this state.
13413 */
13414 dtrace_enabling_prime(state);
13415
13416 if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13417 rval = EACCES;
13418 goto out;
13419 }
13420
13421 dtrace_state_prereserve(state);
13422
13423 /*
13424 * Now we want to do is try to allocate our speculations.
13425 * We do not automatically resize the number of speculations; if
13426 * this fails, we will fail the operation.
13427 */
13428 nspec = opt[DTRACEOPT_NSPEC];
13429 ASSERT(nspec != DTRACEOPT_UNSET);
13430
13431 if (nspec > INT_MAX) {
13432 rval = ENOMEM;
13433 goto out;
13434 }
13435
13436 spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
13437
13438 if (spec == NULL) {
13439 rval = ENOMEM;
13440 goto out;
13441 }
13442
13443 state->dts_speculations = spec;
13444 state->dts_nspeculations = (int)nspec;
13445
13446 for (i = 0; i < nspec; i++) {
13447 if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
13448 rval = ENOMEM;
13449 goto err;
13450 }
13451
13452 spec[i].dtsp_buffer = buf;
13453 }
13454
13455 if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13456 if (dtrace_anon.dta_state == NULL) {
13457 rval = ENOENT;
13458 goto out;
13459 }
13460
13461 if (state->dts_necbs != 0) {
13462 rval = EALREADY;
13463 goto out;
13464 }
13465
13466 state->dts_anon = dtrace_anon_grab();
13467 ASSERT(state->dts_anon != NULL);
13468 state = state->dts_anon;
13469
13470 /*
13471 * We want "grabanon" to be set in the grabbed state, so we'll
13472 * copy that option value from the grabbing state into the
13473 * grabbed state.
13474 */
13475 state->dts_options[DTRACEOPT_GRABANON] =
13476 opt[DTRACEOPT_GRABANON];
13477
13478 *cpu = dtrace_anon.dta_beganon;
13479
13480 /*
13481 * If the anonymous state is active (as it almost certainly
13482 * is if the anonymous enabling ultimately matched anything),
13483 * we don't allow any further option processing -- but we
13484 * don't return failure.
13485 */
13486 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13487 goto out;
13488 }
13489
13490 if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13491 opt[DTRACEOPT_AGGSIZE] != 0) {
13492 if (state->dts_aggregations == NULL) {
13493 /*
13494 * We're not going to create an aggregation buffer
13495 * because we don't have any ECBs that contain
13496 * aggregations -- set this option to 0.
13497 */
13498 opt[DTRACEOPT_AGGSIZE] = 0;
13499 } else {
13500 /*
13501 * If we have an aggregation buffer, we must also have
13502 * a buffer to use as scratch.
13503 */
13504 if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13505 (size_t)opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13506 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13507 }
13508 }
13509 }
13510
13511 if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13512 opt[DTRACEOPT_SPECSIZE] != 0) {
13513 if (!state->dts_speculates) {
13514 /*
13515 * We're not going to create speculation buffers
13516 * because we don't have any ECBs that actually
13517 * speculate -- set the speculation size to 0.
13518 */
13519 opt[DTRACEOPT_SPECSIZE] = 0;
13520 }
13521 }
13522
13523 /*
13524 * The bare minimum size for any buffer that we're actually going to
13525 * do anything to is sizeof (uint64_t).
13526 */
13527 sz = sizeof (uint64_t);
13528
13529 if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13530 (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13531 (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13532 /*
13533 * A buffer size has been explicitly set to 0 (or to a size
13534 * that will be adjusted to 0) and we need the space -- we
13535 * need to return failure. We return ENOSPC to differentiate
13536 * it from failing to allocate a buffer due to failure to meet
13537 * the reserve (for which we return E2BIG).
13538 */
13539 rval = ENOSPC;
13540 goto out;
13541 }
13542
13543 if ((rval = dtrace_state_buffers(state)) != 0)
13544 goto err;
13545
13546 if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13547 sz = dtrace_dstate_defsize;
13548
13549 do {
13550 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13551
13552 if (rval == 0)
13553 break;
13554
13555 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13556 goto err;
13557 } while (sz >>= 1);
13558
13559 opt[DTRACEOPT_DYNVARSIZE] = sz;
13560
13561 if (rval != 0)
13562 goto err;
13563
13564 if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13565 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13566
13567 if (opt[DTRACEOPT_CLEANRATE] == 0)
13568 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13569
13570 if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13571 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13572
13573 if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13574 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13575
13576 if (opt[DTRACEOPT_STRSIZE] > dtrace_strsize_max)
13577 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_max;
13578
13579 if (opt[DTRACEOPT_STRSIZE] < dtrace_strsize_min)
13580 opt[DTRACEOPT_STRSIZE] = dtrace_strsize_min;
13581
13582 if (opt[DTRACEOPT_BUFLIMIT] > dtrace_buflimit_max)
13583 opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_max;
13584
13585 if (opt[DTRACEOPT_BUFLIMIT] < dtrace_buflimit_min)
13586 opt[DTRACEOPT_BUFLIMIT] = dtrace_buflimit_min;
13587
13588 hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13589 hdlr.cyh_arg = state;
13590 hdlr.cyh_level = CY_LOW_LEVEL;
13591
13592 when.cyt_when = 0;
13593 when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13594
13595 state->dts_cleaner = cyclic_add(&hdlr, &when);
13596
13597 hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13598 hdlr.cyh_arg = state;
13599 hdlr.cyh_level = CY_LOW_LEVEL;
13600
13601 when.cyt_when = 0;
13602 when.cyt_interval = dtrace_deadman_interval;
13603
13604 state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13605 state->dts_deadman = cyclic_add(&hdlr, &when);
13606
13607 state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13608
13609 /*
13610 * Now it's time to actually fire the BEGIN probe. We need to disable
13611 * interrupts here both to record the CPU on which we fired the BEGIN
13612 * probe (the data from this CPU will be processed first at user
13613 * level) and to manually activate the buffer for this CPU.
13614 */
13615 cookie = dtrace_interrupt_disable();
13616 *cpu = CPU->cpu_id;
13617 ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13618 state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13619
13620 dtrace_probe(dtrace_probeid_begin,
13621 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13622 dtrace_interrupt_enable(cookie);
13623 /*
13624 * We may have had an exit action from a BEGIN probe; only change our
13625 * state to ACTIVE if we're still in WARMUP.
13626 */
13627 ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13628 state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13629
13630 if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13631 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13632
13633 /*
13634 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13635 * want each CPU to transition its principal buffer out of the
13636 * INACTIVE state. Doing this assures that no CPU will suddenly begin
13637 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13638 * atomically transition from processing none of a state's ECBs to
13639 * processing all of them.
13640 */
13641 dtrace_xcall(DTRACE_CPUALL,
13642 (dtrace_xcall_t)dtrace_buffer_activate, state);
13643 goto out;
13644
13645 err:
13646 dtrace_buffer_free(state->dts_buffer);
13647 dtrace_buffer_free(state->dts_aggbuffer);
13648
13649 if ((nspec = state->dts_nspeculations) == 0) {
13650 ASSERT(state->dts_speculations == NULL);
13651 goto out;
13652 }
13653
13654 spec = state->dts_speculations;
13655 ASSERT(spec != NULL);
13656
13657 for (i = 0; i < state->dts_nspeculations; i++) {
13658 if ((buf = spec[i].dtsp_buffer) == NULL)
13659 break;
13660
13661 dtrace_buffer_free(buf);
13662 kmem_free(buf, bufsize);
13663 }
13664
13665 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13666 state->dts_nspeculations = 0;
13667 state->dts_speculations = NULL;
13668
13669 out:
13670 lck_mtx_unlock(&dtrace_lock);
13671 lck_mtx_unlock(&cpu_lock);
13672
13673 return (rval);
13674 }
13675
13676 static int
13677 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13678 {
13679 dtrace_icookie_t cookie;
13680
13681 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13682
13683 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13684 state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13685 return (EINVAL);
13686
13687 /*
13688 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13689 * to be sure that every CPU has seen it. See below for the details
13690 * on why this is done.
13691 */
13692 state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13693 dtrace_sync();
13694
13695 /*
13696 * By this point, it is impossible for any CPU to be still processing
13697 * with DTRACE_ACTIVITY_ACTIVE. We can thus set our activity to
13698 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13699 * other CPU in dtrace_buffer_reserve(). This allows dtrace_probe()
13700 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13701 * iff we're in the END probe.
13702 */
13703 state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13704 dtrace_sync();
13705 ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13706
13707 /*
13708 * Finally, we can release the reserve and call the END probe. We
13709 * disable interrupts across calling the END probe to allow us to
13710 * return the CPU on which we actually called the END probe. This
13711 * allows user-land to be sure that this CPU's principal buffer is
13712 * processed last.
13713 */
13714 state->dts_reserve = 0;
13715
13716 cookie = dtrace_interrupt_disable();
13717 *cpu = CPU->cpu_id;
13718 dtrace_probe(dtrace_probeid_end,
13719 (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13720 dtrace_interrupt_enable(cookie);
13721
13722 state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13723 dtrace_sync();
13724
13725 return (0);
13726 }
13727
13728 static int
13729 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13730 dtrace_optval_t val)
13731 {
13732 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13733
13734 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13735 return (EBUSY);
13736
13737 if (option >= DTRACEOPT_MAX)
13738 return (EINVAL);
13739
13740 if (option != DTRACEOPT_CPU && val < 0)
13741 return (EINVAL);
13742
13743 switch (option) {
13744 case DTRACEOPT_DESTRUCTIVE:
13745 /*
13746 * Prevent consumers from enabling destructive actions if DTrace
13747 * is running in a restricted environment, or if actions are
13748 * disallowed.
13749 */
13750 if (dtrace_is_restricted() || dtrace_destructive_disallow)
13751 return (EACCES);
13752
13753 state->dts_cred.dcr_destructive = 1;
13754 break;
13755
13756 case DTRACEOPT_BUFSIZE:
13757 case DTRACEOPT_DYNVARSIZE:
13758 case DTRACEOPT_AGGSIZE:
13759 case DTRACEOPT_SPECSIZE:
13760 case DTRACEOPT_STRSIZE:
13761 if (val < 0)
13762 return (EINVAL);
13763
13764 if (val >= LONG_MAX) {
13765 /*
13766 * If this is an otherwise negative value, set it to
13767 * the highest multiple of 128m less than LONG_MAX.
13768 * Technically, we're adjusting the size without
13769 * regard to the buffer resizing policy, but in fact,
13770 * this has no effect -- if we set the buffer size to
13771 * ~LONG_MAX and the buffer policy is ultimately set to
13772 * be "manual", the buffer allocation is guaranteed to
13773 * fail, if only because the allocation requires two
13774 * buffers. (We set the the size to the highest
13775 * multiple of 128m because it ensures that the size
13776 * will remain a multiple of a megabyte when
13777 * repeatedly halved -- all the way down to 15m.)
13778 */
13779 val = LONG_MAX - (1 << 27) + 1;
13780 }
13781 }
13782
13783 state->dts_options[option] = val;
13784
13785 return (0);
13786 }
13787
13788 static void
13789 dtrace_state_destroy(dtrace_state_t *state)
13790 {
13791 dtrace_ecb_t *ecb;
13792 dtrace_vstate_t *vstate = &state->dts_vstate;
13793 minor_t minor = getminor(state->dts_dev);
13794 int i, bufsize = (int)NCPU * sizeof (dtrace_buffer_t);
13795 dtrace_speculation_t *spec = state->dts_speculations;
13796 int nspec = state->dts_nspeculations;
13797 uint32_t match;
13798
13799 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13800 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13801
13802 /*
13803 * First, retract any retained enablings for this state.
13804 */
13805 dtrace_enabling_retract(state);
13806 ASSERT(state->dts_nretained == 0);
13807
13808 if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13809 state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13810 /*
13811 * We have managed to come into dtrace_state_destroy() on a
13812 * hot enabling -- almost certainly because of a disorderly
13813 * shutdown of a consumer. (That is, a consumer that is
13814 * exiting without having called dtrace_stop().) In this case,
13815 * we're going to set our activity to be KILLED, and then
13816 * issue a sync to be sure that everyone is out of probe
13817 * context before we start blowing away ECBs.
13818 */
13819 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13820 dtrace_sync();
13821 }
13822
13823 /*
13824 * Release the credential hold we took in dtrace_state_create().
13825 */
13826 if (state->dts_cred.dcr_cred != NULL)
13827 crfree(state->dts_cred.dcr_cred);
13828
13829 /*
13830 * Now we can safely disable and destroy any enabled probes. Because
13831 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13832 * (especially if they're all enabled), we take two passes through the
13833 * ECBs: in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13834 * in the second we disable whatever is left over.
13835 */
13836 for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13837 for (i = 0; i < state->dts_necbs; i++) {
13838 if ((ecb = state->dts_ecbs[i]) == NULL)
13839 continue;
13840
13841 if (match && ecb->dte_probe != NULL) {
13842 dtrace_probe_t *probe = ecb->dte_probe;
13843 dtrace_provider_t *prov = probe->dtpr_provider;
13844
13845 if (!(prov->dtpv_priv.dtpp_flags & match))
13846 continue;
13847 }
13848
13849 dtrace_ecb_disable(ecb);
13850 dtrace_ecb_destroy(ecb);
13851 }
13852
13853 if (!match)
13854 break;
13855 }
13856
13857 /*
13858 * Before we free the buffers, perform one more sync to assure that
13859 * every CPU is out of probe context.
13860 */
13861 dtrace_sync();
13862
13863 dtrace_buffer_free(state->dts_buffer);
13864 dtrace_buffer_free(state->dts_aggbuffer);
13865
13866 for (i = 0; i < nspec; i++)
13867 dtrace_buffer_free(spec[i].dtsp_buffer);
13868
13869 if (state->dts_cleaner != CYCLIC_NONE)
13870 cyclic_remove(state->dts_cleaner);
13871
13872 if (state->dts_deadman != CYCLIC_NONE)
13873 cyclic_remove(state->dts_deadman);
13874
13875 dtrace_dstate_fini(&vstate->dtvs_dynvars);
13876 dtrace_vstate_fini(vstate);
13877 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13878
13879 if (state->dts_aggregations != NULL) {
13880 #if DEBUG
13881 for (i = 0; i < state->dts_naggregations; i++)
13882 ASSERT(state->dts_aggregations[i] == NULL);
13883 #endif
13884 ASSERT(state->dts_naggregations > 0);
13885 kmem_free(state->dts_aggregations,
13886 state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13887 }
13888
13889 kmem_free(state->dts_buffer, bufsize);
13890 kmem_free(state->dts_aggbuffer, bufsize);
13891
13892 for (i = 0; i < nspec; i++)
13893 kmem_free(spec[i].dtsp_buffer, bufsize);
13894
13895 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13896
13897 dtrace_format_destroy(state);
13898
13899 vmem_destroy(state->dts_aggid_arena);
13900 dtrace_state_free(minor);
13901 }
13902
13903 /*
13904 * DTrace Anonymous Enabling Functions
13905 */
13906 static dtrace_state_t *
13907 dtrace_anon_grab(void)
13908 {
13909 dtrace_state_t *state;
13910
13911 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13912
13913 if ((state = dtrace_anon.dta_state) == NULL) {
13914 ASSERT(dtrace_anon.dta_enabling == NULL);
13915 return (NULL);
13916 }
13917
13918 ASSERT(dtrace_anon.dta_enabling != NULL);
13919 ASSERT(dtrace_retained != NULL);
13920
13921 dtrace_enabling_destroy(dtrace_anon.dta_enabling);
13922 dtrace_anon.dta_enabling = NULL;
13923 dtrace_anon.dta_state = NULL;
13924
13925 return (state);
13926 }
13927
13928 static void
13929 dtrace_anon_property(void)
13930 {
13931 int i, rv;
13932 dtrace_state_t *state;
13933 dof_hdr_t *dof;
13934 char c[32]; /* enough for "dof-data-" + digits */
13935
13936 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
13937 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
13938
13939 for (i = 0; ; i++) {
13940 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
13941
13942 dtrace_err_verbose = 1;
13943
13944 if ((dof = dtrace_dof_property(c)) == NULL) {
13945 dtrace_err_verbose = 0;
13946 break;
13947 }
13948
13949 /*
13950 * We want to create anonymous state, so we need to transition
13951 * the kernel debugger to indicate that DTrace is active. If
13952 * this fails (e.g. because the debugger has modified text in
13953 * some way), we won't continue with the processing.
13954 */
13955 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13956 cmn_err(CE_NOTE, "kernel debugger active; anonymous "
13957 "enabling ignored.");
13958 dtrace_dof_destroy(dof);
13959 break;
13960 }
13961
13962 /*
13963 * If we haven't allocated an anonymous state, we'll do so now.
13964 */
13965 if ((state = dtrace_anon.dta_state) == NULL) {
13966 rv = dtrace_state_create(NULL, NULL, &state);
13967 dtrace_anon.dta_state = state;
13968 if (rv != 0 || state == NULL) {
13969 /*
13970 * This basically shouldn't happen: the only
13971 * failure mode from dtrace_state_create() is a
13972 * failure of ddi_soft_state_zalloc() that
13973 * itself should never happen. Still, the
13974 * interface allows for a failure mode, and
13975 * we want to fail as gracefully as possible:
13976 * we'll emit an error message and cease
13977 * processing anonymous state in this case.
13978 */
13979 cmn_err(CE_WARN, "failed to create "
13980 "anonymous state");
13981 dtrace_dof_destroy(dof);
13982 break;
13983 }
13984 }
13985
13986 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
13987 &dtrace_anon.dta_enabling, 0, B_TRUE);
13988
13989 if (rv == 0)
13990 rv = dtrace_dof_options(dof, state);
13991
13992 dtrace_err_verbose = 0;
13993 dtrace_dof_destroy(dof);
13994
13995 if (rv != 0) {
13996 /*
13997 * This is malformed DOF; chuck any anonymous state
13998 * that we created.
13999 */
14000 ASSERT(dtrace_anon.dta_enabling == NULL);
14001 dtrace_state_destroy(state);
14002 dtrace_anon.dta_state = NULL;
14003 break;
14004 }
14005
14006 ASSERT(dtrace_anon.dta_enabling != NULL);
14007 }
14008
14009 if (dtrace_anon.dta_enabling != NULL) {
14010 int rval;
14011
14012 /*
14013 * dtrace_enabling_retain() can only fail because we are
14014 * trying to retain more enablings than are allowed -- but
14015 * we only have one anonymous enabling, and we are guaranteed
14016 * to be allowed at least one retained enabling; we assert
14017 * that dtrace_enabling_retain() returns success.
14018 */
14019 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14020 ASSERT(rval == 0);
14021
14022 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14023 }
14024 }
14025
14026 /*
14027 * DTrace Helper Functions
14028 */
14029 static void
14030 dtrace_helper_trace(dtrace_helper_action_t *helper,
14031 dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14032 {
14033 uint32_t size, next, nnext;
14034 int i;
14035 dtrace_helptrace_t *ent;
14036 uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14037
14038 if (!dtrace_helptrace_enabled)
14039 return;
14040
14041 ASSERT((uint32_t)vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14042
14043 /*
14044 * What would a tracing framework be without its own tracing
14045 * framework? (Well, a hell of a lot simpler, for starters...)
14046 */
14047 size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14048 sizeof (uint64_t) - sizeof (uint64_t);
14049
14050 /*
14051 * Iterate until we can allocate a slot in the trace buffer.
14052 */
14053 do {
14054 next = dtrace_helptrace_next;
14055
14056 if (next + size < dtrace_helptrace_bufsize) {
14057 nnext = next + size;
14058 } else {
14059 nnext = size;
14060 }
14061 } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14062
14063 /*
14064 * We have our slot; fill it in.
14065 */
14066 if (nnext == size)
14067 next = 0;
14068
14069 ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14070 ent->dtht_helper = helper;
14071 ent->dtht_where = where;
14072 ent->dtht_nlocals = vstate->dtvs_nlocals;
14073
14074 ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14075 mstate->dtms_fltoffs : -1;
14076 ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14077 ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14078
14079 for (i = 0; i < vstate->dtvs_nlocals; i++) {
14080 dtrace_statvar_t *svar;
14081
14082 if ((svar = vstate->dtvs_locals[i]) == NULL)
14083 continue;
14084
14085 ASSERT(svar->dtsv_size >= (int)NCPU * sizeof (uint64_t));
14086 ent->dtht_locals[i] =
14087 ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14088 }
14089 }
14090
14091 static uint64_t
14092 dtrace_helper(int which, dtrace_mstate_t *mstate,
14093 dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14094 {
14095 uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14096 uint64_t sarg0 = mstate->dtms_arg[0];
14097 uint64_t sarg1 = mstate->dtms_arg[1];
14098 uint64_t rval = 0;
14099 dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14100 dtrace_helper_action_t *helper;
14101 dtrace_vstate_t *vstate;
14102 dtrace_difo_t *pred;
14103 int i, trace = dtrace_helptrace_enabled;
14104
14105 ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14106
14107 if (helpers == NULL)
14108 return (0);
14109
14110 if ((helper = helpers->dthps_actions[which]) == NULL)
14111 return (0);
14112
14113 vstate = &helpers->dthps_vstate;
14114 mstate->dtms_arg[0] = arg0;
14115 mstate->dtms_arg[1] = arg1;
14116
14117 /*
14118 * Now iterate over each helper. If its predicate evaluates to 'true',
14119 * we'll call the corresponding actions. Note that the below calls
14120 * to dtrace_dif_emulate() may set faults in machine state. This is
14121 * okay: our caller (the outer dtrace_dif_emulate()) will simply plow
14122 * the stored DIF offset with its own (which is the desired behavior).
14123 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14124 * from machine state; this is okay, too.
14125 */
14126 for (; helper != NULL; helper = helper->dtha_next) {
14127 if ((pred = helper->dtha_predicate) != NULL) {
14128 if (trace)
14129 dtrace_helper_trace(helper, mstate, vstate, 0);
14130
14131 if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14132 goto next;
14133
14134 if (*flags & CPU_DTRACE_FAULT)
14135 goto err;
14136 }
14137
14138 for (i = 0; i < helper->dtha_nactions; i++) {
14139 if (trace)
14140 dtrace_helper_trace(helper,
14141 mstate, vstate, i + 1);
14142
14143 rval = dtrace_dif_emulate(helper->dtha_actions[i],
14144 mstate, vstate, state);
14145
14146 if (*flags & CPU_DTRACE_FAULT)
14147 goto err;
14148 }
14149
14150 next:
14151 if (trace)
14152 dtrace_helper_trace(helper, mstate, vstate,
14153 DTRACE_HELPTRACE_NEXT);
14154 }
14155
14156 if (trace)
14157 dtrace_helper_trace(helper, mstate, vstate,
14158 DTRACE_HELPTRACE_DONE);
14159
14160 /*
14161 * Restore the arg0 that we saved upon entry.
14162 */
14163 mstate->dtms_arg[0] = sarg0;
14164 mstate->dtms_arg[1] = sarg1;
14165
14166 return (rval);
14167
14168 err:
14169 if (trace)
14170 dtrace_helper_trace(helper, mstate, vstate,
14171 DTRACE_HELPTRACE_ERR);
14172
14173 /*
14174 * Restore the arg0 that we saved upon entry.
14175 */
14176 mstate->dtms_arg[0] = sarg0;
14177 mstate->dtms_arg[1] = sarg1;
14178
14179 return (0);
14180 }
14181
14182 static void
14183 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14184 dtrace_vstate_t *vstate)
14185 {
14186 int i;
14187
14188 if (helper->dtha_predicate != NULL)
14189 dtrace_difo_release(helper->dtha_predicate, vstate);
14190
14191 for (i = 0; i < helper->dtha_nactions; i++) {
14192 ASSERT(helper->dtha_actions[i] != NULL);
14193 dtrace_difo_release(helper->dtha_actions[i], vstate);
14194 }
14195
14196 kmem_free(helper->dtha_actions,
14197 helper->dtha_nactions * sizeof (dtrace_difo_t *));
14198 kmem_free(helper, sizeof (dtrace_helper_action_t));
14199 }
14200
14201 static int
14202 dtrace_helper_destroygen(proc_t* p, int gen)
14203 {
14204 dtrace_helpers_t *help = p->p_dtrace_helpers;
14205 dtrace_vstate_t *vstate;
14206 uint_t i;
14207
14208 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14209
14210 if (help == NULL || gen > help->dthps_generation)
14211 return (EINVAL);
14212
14213 vstate = &help->dthps_vstate;
14214
14215 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14216 dtrace_helper_action_t *last = NULL, *h, *next;
14217
14218 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14219 next = h->dtha_next;
14220
14221 if (h->dtha_generation == gen) {
14222 if (last != NULL) {
14223 last->dtha_next = next;
14224 } else {
14225 help->dthps_actions[i] = next;
14226 }
14227
14228 dtrace_helper_action_destroy(h, vstate);
14229 } else {
14230 last = h;
14231 }
14232 }
14233 }
14234
14235 /*
14236 * Interate until we've cleared out all helper providers with the
14237 * given generation number.
14238 */
14239 for (;;) {
14240 dtrace_helper_provider_t *prov = NULL;
14241
14242 /*
14243 * Look for a helper provider with the right generation. We
14244 * have to start back at the beginning of the list each time
14245 * because we drop dtrace_lock. It's unlikely that we'll make
14246 * more than two passes.
14247 */
14248 for (i = 0; i < help->dthps_nprovs; i++) {
14249 prov = help->dthps_provs[i];
14250
14251 if (prov->dthp_generation == gen)
14252 break;
14253 }
14254
14255 /*
14256 * If there were no matches, we're done.
14257 */
14258 if (i == help->dthps_nprovs)
14259 break;
14260
14261 /*
14262 * Move the last helper provider into this slot.
14263 */
14264 help->dthps_nprovs--;
14265 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14266 help->dthps_provs[help->dthps_nprovs] = NULL;
14267
14268 lck_mtx_unlock(&dtrace_lock);
14269
14270 /*
14271 * If we have a meta provider, remove this helper provider.
14272 */
14273 lck_mtx_lock(&dtrace_meta_lock);
14274 if (dtrace_meta_pid != NULL) {
14275 ASSERT(dtrace_deferred_pid == NULL);
14276 dtrace_helper_provider_remove(&prov->dthp_prov,
14277 p->p_pid);
14278 }
14279 lck_mtx_unlock(&dtrace_meta_lock);
14280
14281 dtrace_helper_provider_destroy(prov);
14282
14283 lck_mtx_lock(&dtrace_lock);
14284 }
14285
14286 return (0);
14287 }
14288
14289 static int
14290 dtrace_helper_validate(dtrace_helper_action_t *helper)
14291 {
14292 int err = 0, i;
14293 dtrace_difo_t *dp;
14294
14295 if ((dp = helper->dtha_predicate) != NULL)
14296 err += dtrace_difo_validate_helper(dp);
14297
14298 for (i = 0; i < helper->dtha_nactions; i++)
14299 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14300
14301 return (err == 0);
14302 }
14303
14304 static int
14305 dtrace_helper_action_add(proc_t* p, int which, dtrace_ecbdesc_t *ep)
14306 {
14307 dtrace_helpers_t *help;
14308 dtrace_helper_action_t *helper, *last;
14309 dtrace_actdesc_t *act;
14310 dtrace_vstate_t *vstate;
14311 dtrace_predicate_t *pred;
14312 int count = 0, nactions = 0, i;
14313
14314 if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14315 return (EINVAL);
14316
14317 help = p->p_dtrace_helpers;
14318 last = help->dthps_actions[which];
14319 vstate = &help->dthps_vstate;
14320
14321 for (count = 0; last != NULL; last = last->dtha_next) {
14322 count++;
14323 if (last->dtha_next == NULL)
14324 break;
14325 }
14326
14327 /*
14328 * If we already have dtrace_helper_actions_max helper actions for this
14329 * helper action type, we'll refuse to add a new one.
14330 */
14331 if (count >= dtrace_helper_actions_max)
14332 return (ENOSPC);
14333
14334 helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14335 helper->dtha_generation = help->dthps_generation;
14336
14337 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14338 ASSERT(pred->dtp_difo != NULL);
14339 dtrace_difo_hold(pred->dtp_difo);
14340 helper->dtha_predicate = pred->dtp_difo;
14341 }
14342
14343 for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14344 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14345 goto err;
14346
14347 if (act->dtad_difo == NULL)
14348 goto err;
14349
14350 nactions++;
14351 }
14352
14353 helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14354 (helper->dtha_nactions = nactions), KM_SLEEP);
14355
14356 for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14357 dtrace_difo_hold(act->dtad_difo);
14358 helper->dtha_actions[i++] = act->dtad_difo;
14359 }
14360
14361 if (!dtrace_helper_validate(helper))
14362 goto err;
14363
14364 if (last == NULL) {
14365 help->dthps_actions[which] = helper;
14366 } else {
14367 last->dtha_next = helper;
14368 }
14369
14370 if ((uint32_t)vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14371 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14372 dtrace_helptrace_next = 0;
14373 }
14374
14375 return (0);
14376 err:
14377 dtrace_helper_action_destroy(helper, vstate);
14378 return (EINVAL);
14379 }
14380
14381 static void
14382 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14383 dof_helper_t *dofhp)
14384 {
14385 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
14386
14387 lck_mtx_lock(&dtrace_meta_lock);
14388 lck_mtx_lock(&dtrace_lock);
14389
14390 if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14391 /*
14392 * If the dtrace module is loaded but not attached, or if
14393 * there aren't isn't a meta provider registered to deal with
14394 * these provider descriptions, we need to postpone creating
14395 * the actual providers until later.
14396 */
14397
14398 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14399 dtrace_deferred_pid != help) {
14400 help->dthps_deferred = 1;
14401 help->dthps_pid = p->p_pid;
14402 help->dthps_next = dtrace_deferred_pid;
14403 help->dthps_prev = NULL;
14404 if (dtrace_deferred_pid != NULL)
14405 dtrace_deferred_pid->dthps_prev = help;
14406 dtrace_deferred_pid = help;
14407 }
14408
14409 lck_mtx_unlock(&dtrace_lock);
14410
14411 } else if (dofhp != NULL) {
14412 /*
14413 * If the dtrace module is loaded and we have a particular
14414 * helper provider description, pass that off to the
14415 * meta provider.
14416 */
14417
14418 lck_mtx_unlock(&dtrace_lock);
14419
14420 dtrace_helper_provide(dofhp, p->p_pid);
14421
14422 } else {
14423 /*
14424 * Otherwise, just pass all the helper provider descriptions
14425 * off to the meta provider.
14426 */
14427
14428 uint_t i;
14429 lck_mtx_unlock(&dtrace_lock);
14430
14431 for (i = 0; i < help->dthps_nprovs; i++) {
14432 dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14433 p->p_pid);
14434 }
14435 }
14436
14437 lck_mtx_unlock(&dtrace_meta_lock);
14438 }
14439
14440 static int
14441 dtrace_helper_provider_add(proc_t* p, dof_helper_t *dofhp, int gen)
14442 {
14443 dtrace_helpers_t *help;
14444 dtrace_helper_provider_t *hprov, **tmp_provs;
14445 uint_t tmp_maxprovs, i;
14446
14447 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14448 help = p->p_dtrace_helpers;
14449 ASSERT(help != NULL);
14450
14451 /*
14452 * If we already have dtrace_helper_providers_max helper providers,
14453 * we're refuse to add a new one.
14454 */
14455 if (help->dthps_nprovs >= dtrace_helper_providers_max)
14456 return (ENOSPC);
14457
14458 /*
14459 * Check to make sure this isn't a duplicate.
14460 */
14461 for (i = 0; i < help->dthps_nprovs; i++) {
14462 if (dofhp->dofhp_addr ==
14463 help->dthps_provs[i]->dthp_prov.dofhp_addr)
14464 return (EALREADY);
14465 }
14466
14467 hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14468 hprov->dthp_prov = *dofhp;
14469 hprov->dthp_ref = 1;
14470 hprov->dthp_generation = gen;
14471
14472 /*
14473 * Allocate a bigger table for helper providers if it's already full.
14474 */
14475 if (help->dthps_maxprovs == help->dthps_nprovs) {
14476 tmp_maxprovs = help->dthps_maxprovs;
14477 tmp_provs = help->dthps_provs;
14478
14479 if (help->dthps_maxprovs == 0)
14480 help->dthps_maxprovs = 2;
14481 else
14482 help->dthps_maxprovs *= 2;
14483 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14484 help->dthps_maxprovs = dtrace_helper_providers_max;
14485
14486 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14487
14488 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14489 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14490
14491 if (tmp_provs != NULL) {
14492 bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14493 sizeof (dtrace_helper_provider_t *));
14494 kmem_free(tmp_provs, tmp_maxprovs *
14495 sizeof (dtrace_helper_provider_t *));
14496 }
14497 }
14498
14499 help->dthps_provs[help->dthps_nprovs] = hprov;
14500 help->dthps_nprovs++;
14501
14502 return (0);
14503 }
14504
14505 static void
14506 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14507 {
14508 lck_mtx_lock(&dtrace_lock);
14509
14510 if (--hprov->dthp_ref == 0) {
14511 dof_hdr_t *dof;
14512 lck_mtx_unlock(&dtrace_lock);
14513 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14514 dtrace_dof_destroy(dof);
14515 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14516 } else {
14517 lck_mtx_unlock(&dtrace_lock);
14518 }
14519 }
14520
14521 static int
14522 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14523 {
14524 uintptr_t daddr = (uintptr_t)dof;
14525 dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14526 dof_provider_t *provider;
14527 dof_probe_t *probe;
14528 uint8_t *arg;
14529 char *strtab, *typestr;
14530 dof_stridx_t typeidx;
14531 size_t typesz;
14532 uint_t nprobes, j, k;
14533
14534 ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14535
14536 if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14537 dtrace_dof_error(dof, "misaligned section offset");
14538 return (-1);
14539 }
14540
14541 /*
14542 * The section needs to be large enough to contain the DOF provider
14543 * structure appropriate for the given version.
14544 */
14545 if (sec->dofs_size <
14546 ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14547 offsetof(dof_provider_t, dofpv_prenoffs) :
14548 sizeof (dof_provider_t))) {
14549 dtrace_dof_error(dof, "provider section too small");
14550 return (-1);
14551 }
14552
14553 provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14554 str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14555 prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14556 arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14557 off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14558
14559 if (str_sec == NULL || prb_sec == NULL ||
14560 arg_sec == NULL || off_sec == NULL)
14561 return (-1);
14562
14563 enoff_sec = NULL;
14564
14565 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14566 provider->dofpv_prenoffs != DOF_SECT_NONE &&
14567 (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14568 provider->dofpv_prenoffs)) == NULL)
14569 return (-1);
14570
14571 strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14572
14573 if (provider->dofpv_name >= str_sec->dofs_size ||
14574 strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14575 dtrace_dof_error(dof, "invalid provider name");
14576 return (-1);
14577 }
14578
14579 if (prb_sec->dofs_entsize == 0 ||
14580 prb_sec->dofs_entsize > prb_sec->dofs_size) {
14581 dtrace_dof_error(dof, "invalid entry size");
14582 return (-1);
14583 }
14584
14585 if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14586 dtrace_dof_error(dof, "misaligned entry size");
14587 return (-1);
14588 }
14589
14590 if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14591 dtrace_dof_error(dof, "invalid entry size");
14592 return (-1);
14593 }
14594
14595 if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14596 dtrace_dof_error(dof, "misaligned section offset");
14597 return (-1);
14598 }
14599
14600 if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14601 dtrace_dof_error(dof, "invalid entry size");
14602 return (-1);
14603 }
14604
14605 arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14606
14607 nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14608
14609 /*
14610 * Take a pass through the probes to check for errors.
14611 */
14612 for (j = 0; j < nprobes; j++) {
14613 probe = (dof_probe_t *)(uintptr_t)(daddr +
14614 prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14615
14616 if (probe->dofpr_func >= str_sec->dofs_size) {
14617 dtrace_dof_error(dof, "invalid function name");
14618 return (-1);
14619 }
14620
14621 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14622 dtrace_dof_error(dof, "function name too long");
14623 return (-1);
14624 }
14625
14626 if (probe->dofpr_name >= str_sec->dofs_size ||
14627 strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14628 dtrace_dof_error(dof, "invalid probe name");
14629 return (-1);
14630 }
14631
14632 /*
14633 * The offset count must not wrap the index, and the offsets
14634 * must also not overflow the section's data.
14635 */
14636 if (probe->dofpr_offidx + probe->dofpr_noffs <
14637 probe->dofpr_offidx ||
14638 (probe->dofpr_offidx + probe->dofpr_noffs) *
14639 off_sec->dofs_entsize > off_sec->dofs_size) {
14640 dtrace_dof_error(dof, "invalid probe offset");
14641 return (-1);
14642 }
14643
14644 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14645 /*
14646 * If there's no is-enabled offset section, make sure
14647 * there aren't any is-enabled offsets. Otherwise
14648 * perform the same checks as for probe offsets
14649 * (immediately above).
14650 */
14651 if (enoff_sec == NULL) {
14652 if (probe->dofpr_enoffidx != 0 ||
14653 probe->dofpr_nenoffs != 0) {
14654 dtrace_dof_error(dof, "is-enabled "
14655 "offsets with null section");
14656 return (-1);
14657 }
14658 } else if (probe->dofpr_enoffidx +
14659 probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14660 (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14661 enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14662 dtrace_dof_error(dof, "invalid is-enabled "
14663 "offset");
14664 return (-1);
14665 }
14666
14667 if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14668 dtrace_dof_error(dof, "zero probe and "
14669 "is-enabled offsets");
14670 return (-1);
14671 }
14672 } else if (probe->dofpr_noffs == 0) {
14673 dtrace_dof_error(dof, "zero probe offsets");
14674 return (-1);
14675 }
14676
14677 if (probe->dofpr_argidx + probe->dofpr_xargc <
14678 probe->dofpr_argidx ||
14679 (probe->dofpr_argidx + probe->dofpr_xargc) *
14680 arg_sec->dofs_entsize > arg_sec->dofs_size) {
14681 dtrace_dof_error(dof, "invalid args");
14682 return (-1);
14683 }
14684
14685 typeidx = probe->dofpr_nargv;
14686 typestr = strtab + probe->dofpr_nargv;
14687 for (k = 0; k < probe->dofpr_nargc; k++) {
14688 if (typeidx >= str_sec->dofs_size) {
14689 dtrace_dof_error(dof, "bad "
14690 "native argument type");
14691 return (-1);
14692 }
14693
14694 typesz = strlen(typestr) + 1;
14695 if (typesz > DTRACE_ARGTYPELEN) {
14696 dtrace_dof_error(dof, "native "
14697 "argument type too long");
14698 return (-1);
14699 }
14700 typeidx += typesz;
14701 typestr += typesz;
14702 }
14703
14704 typeidx = probe->dofpr_xargv;
14705 typestr = strtab + probe->dofpr_xargv;
14706 for (k = 0; k < probe->dofpr_xargc; k++) {
14707 if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14708 dtrace_dof_error(dof, "bad "
14709 "native argument index");
14710 return (-1);
14711 }
14712
14713 if (typeidx >= str_sec->dofs_size) {
14714 dtrace_dof_error(dof, "bad "
14715 "translated argument type");
14716 return (-1);
14717 }
14718
14719 typesz = strlen(typestr) + 1;
14720 if (typesz > DTRACE_ARGTYPELEN) {
14721 dtrace_dof_error(dof, "translated argument "
14722 "type too long");
14723 return (-1);
14724 }
14725
14726 typeidx += typesz;
14727 typestr += typesz;
14728 }
14729 }
14730
14731 return (0);
14732 }
14733
14734 static int
14735 dtrace_helper_slurp(proc_t* p, dof_hdr_t *dof, dof_helper_t *dhp)
14736 {
14737 dtrace_helpers_t *help;
14738 dtrace_vstate_t *vstate;
14739 dtrace_enabling_t *enab = NULL;
14740 int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14741 uintptr_t daddr = (uintptr_t)dof;
14742
14743 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
14744
14745 if ((help = p->p_dtrace_helpers) == NULL)
14746 help = dtrace_helpers_create(p);
14747
14748 vstate = &help->dthps_vstate;
14749
14750 if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14751 dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14752 dtrace_dof_destroy(dof);
14753 return (rv);
14754 }
14755
14756 /*
14757 * Look for helper providers and validate their descriptions.
14758 */
14759 if (dhp != NULL) {
14760 for (i = 0; (uint32_t)i < dof->dofh_secnum; i++) {
14761 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14762 dof->dofh_secoff + i * dof->dofh_secsize);
14763
14764 if (sec->dofs_type != DOF_SECT_PROVIDER)
14765 continue;
14766
14767 if (dtrace_helper_provider_validate(dof, sec) != 0) {
14768 dtrace_enabling_destroy(enab);
14769 dtrace_dof_destroy(dof);
14770 return (-1);
14771 }
14772
14773 nprovs++;
14774 }
14775 }
14776
14777 /*
14778 * Now we need to walk through the ECB descriptions in the enabling.
14779 */
14780 for (i = 0; i < enab->dten_ndesc; i++) {
14781 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14782 dtrace_probedesc_t *desc = &ep->dted_probe;
14783
14784 /* APPLE NOTE: Darwin employs size bounded string operation. */
14785 if (!LIT_STRNEQL(desc->dtpd_provider, "dtrace"))
14786 continue;
14787
14788 if (!LIT_STRNEQL(desc->dtpd_mod, "helper"))
14789 continue;
14790
14791 if (!LIT_STRNEQL(desc->dtpd_func, "ustack"))
14792 continue;
14793
14794 if ((rv = dtrace_helper_action_add(p, DTRACE_HELPER_ACTION_USTACK,
14795 ep)) != 0) {
14796 /*
14797 * Adding this helper action failed -- we are now going
14798 * to rip out the entire generation and return failure.
14799 */
14800 (void) dtrace_helper_destroygen(p, help->dthps_generation);
14801 dtrace_enabling_destroy(enab);
14802 dtrace_dof_destroy(dof);
14803 return (-1);
14804 }
14805
14806 nhelpers++;
14807 }
14808
14809 if (nhelpers < enab->dten_ndesc)
14810 dtrace_dof_error(dof, "unmatched helpers");
14811
14812 gen = help->dthps_generation++;
14813 dtrace_enabling_destroy(enab);
14814
14815 if (dhp != NULL && nprovs > 0) {
14816 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14817 if (dtrace_helper_provider_add(p, dhp, gen) == 0) {
14818 lck_mtx_unlock(&dtrace_lock);
14819 dtrace_helper_provider_register(p, help, dhp);
14820 lck_mtx_lock(&dtrace_lock);
14821
14822 destroy = 0;
14823 }
14824 }
14825
14826 if (destroy)
14827 dtrace_dof_destroy(dof);
14828
14829 return (gen);
14830 }
14831
14832 /*
14833 * APPLE NOTE: DTrace lazy dof implementation
14834 *
14835 * DTrace user static probes (USDT probes) and helper actions are loaded
14836 * in a process by proccessing dof sections. The dof sections are passed
14837 * into the kernel by dyld, in a dof_ioctl_data_t block. It is rather
14838 * expensive to process dof for a process that will never use it. There
14839 * is a memory cost (allocating the providers/probes), and a cpu cost
14840 * (creating the providers/probes).
14841 *
14842 * To reduce this cost, we use "lazy dof". The normal proceedure for
14843 * dof processing is to copyin the dof(s) pointed to by the dof_ioctl_data_t
14844 * block, and invoke dof_slurp_helper() on them. When "lazy dof" is
14845 * used, each process retains the dof_ioctl_data_t block, instead of
14846 * copying in the data it points to.
14847 *
14848 * The dof_ioctl_data_t blocks are managed as if they were the actual
14849 * processed dof; on fork the block is copied to the child, on exec and
14850 * exit the block is freed.
14851 *
14852 * If the process loads library(s) containing additional dof, the
14853 * new dof_ioctl_data_t is merged with the existing block.
14854 *
14855 * There are a few catches that make this slightly more difficult.
14856 * When dyld registers dof_ioctl_data_t blocks, it expects a unique
14857 * identifier value for each dof in the block. In non-lazy dof terms,
14858 * this is the generation that dof was loaded in. If we hand back
14859 * a UID for a lazy dof, that same UID must be able to unload the
14860 * dof once it has become non-lazy. To meet this requirement, the
14861 * code that loads lazy dof requires that the UID's for dof(s) in
14862 * the lazy dof be sorted, and in ascending order. It is okay to skip
14863 * UID's, I.E., 1 -> 5 -> 6 is legal.
14864 *
14865 * Once a process has become non-lazy, it will stay non-lazy. All
14866 * future dof operations for that process will be non-lazy, even
14867 * if the dof mode transitions back to lazy.
14868 *
14869 * Always do lazy dof checks before non-lazy (I.E. In fork, exit, exec.).
14870 * That way if the lazy check fails due to transitioning to non-lazy, the
14871 * right thing is done with the newly faulted in dof.
14872 */
14873
14874 /*
14875 * This method is a bit squicky. It must handle:
14876 *
14877 * dof should not be lazy.
14878 * dof should have been handled lazily, but there was an error
14879 * dof was handled lazily, and needs to be freed.
14880 * dof was handled lazily, and must not be freed.
14881 *
14882 *
14883 * Returns EACCESS if dof should be handled non-lazily.
14884 *
14885 * KERN_SUCCESS and all other return codes indicate lazy handling of dof.
14886 *
14887 * If the dofs data is claimed by this method, dofs_claimed will be set.
14888 * Callers should not free claimed dofs.
14889 */
14890 static int
14891 dtrace_lazy_dofs_add(proc_t *p, dof_ioctl_data_t* incoming_dofs, int *dofs_claimed)
14892 {
14893 ASSERT(p);
14894 ASSERT(incoming_dofs && incoming_dofs->dofiod_count > 0);
14895
14896 int rval = 0;
14897 *dofs_claimed = 0;
14898
14899 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14900
14901 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14902 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
14903
14904 /*
14905 * Any existing helpers force non-lazy behavior.
14906 */
14907 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
14908 lck_mtx_lock(&p->p_dtrace_sprlock);
14909
14910 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
14911 unsigned int existing_dofs_count = (existing_dofs) ? existing_dofs->dofiod_count : 0;
14912 unsigned int i, merged_dofs_count = incoming_dofs->dofiod_count + existing_dofs_count;
14913
14914 /*
14915 * Range check...
14916 */
14917 if (merged_dofs_count == 0 || merged_dofs_count > 1024) {
14918 dtrace_dof_error(NULL, "lazy_dofs_add merged_dofs_count out of range");
14919 rval = EINVAL;
14920 goto unlock;
14921 }
14922
14923 /*
14924 * Each dof being added must be assigned a unique generation.
14925 */
14926 uint64_t generation = (existing_dofs) ? existing_dofs->dofiod_helpers[existing_dofs_count - 1].dofhp_dof + 1 : 1;
14927 for (i=0; i<incoming_dofs->dofiod_count; i++) {
14928 /*
14929 * We rely on these being the same so we can overwrite dofhp_dof and not lose info.
14930 */
14931 ASSERT(incoming_dofs->dofiod_helpers[i].dofhp_dof == incoming_dofs->dofiod_helpers[i].dofhp_addr);
14932 incoming_dofs->dofiod_helpers[i].dofhp_dof = generation++;
14933 }
14934
14935
14936 if (existing_dofs) {
14937 /*
14938 * Merge the existing and incoming dofs
14939 */
14940 size_t merged_dofs_size = DOF_IOCTL_DATA_T_SIZE(merged_dofs_count);
14941 dof_ioctl_data_t* merged_dofs = kmem_alloc(merged_dofs_size, KM_SLEEP);
14942
14943 bcopy(&existing_dofs->dofiod_helpers[0],
14944 &merged_dofs->dofiod_helpers[0],
14945 sizeof(dof_helper_t) * existing_dofs_count);
14946 bcopy(&incoming_dofs->dofiod_helpers[0],
14947 &merged_dofs->dofiod_helpers[existing_dofs_count],
14948 sizeof(dof_helper_t) * incoming_dofs->dofiod_count);
14949
14950 merged_dofs->dofiod_count = merged_dofs_count;
14951
14952 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
14953
14954 p->p_dtrace_lazy_dofs = merged_dofs;
14955 } else {
14956 /*
14957 * Claim the incoming dofs
14958 */
14959 *dofs_claimed = 1;
14960 p->p_dtrace_lazy_dofs = incoming_dofs;
14961 }
14962
14963 #if DEBUG
14964 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
14965 for (i=0; i<all_dofs->dofiod_count-1; i++) {
14966 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
14967 }
14968 #endif /* DEBUG */
14969
14970 unlock:
14971 lck_mtx_unlock(&p->p_dtrace_sprlock);
14972 } else {
14973 rval = EACCES;
14974 }
14975
14976 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
14977
14978 return rval;
14979 }
14980
14981 /*
14982 * Returns:
14983 *
14984 * EINVAL: lazy dof is enabled, but the requested generation was not found.
14985 * EACCES: This removal needs to be handled non-lazily.
14986 */
14987 static int
14988 dtrace_lazy_dofs_remove(proc_t *p, int generation)
14989 {
14990 int rval = EINVAL;
14991
14992 lck_rw_lock_shared(&dtrace_dof_mode_lock);
14993
14994 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
14995 ASSERT(dtrace_dof_mode != DTRACE_DOF_MODE_NEVER);
14996
14997 /*
14998 * Any existing helpers force non-lazy behavior.
14999 */
15000 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON && (p->p_dtrace_helpers == NULL)) {
15001 lck_mtx_lock(&p->p_dtrace_sprlock);
15002
15003 dof_ioctl_data_t* existing_dofs = p->p_dtrace_lazy_dofs;
15004
15005 if (existing_dofs) {
15006 int index, existing_dofs_count = existing_dofs->dofiod_count;
15007 for (index=0; index<existing_dofs_count; index++) {
15008 if ((int)existing_dofs->dofiod_helpers[index].dofhp_dof == generation) {
15009 dof_ioctl_data_t* removed_dofs = NULL;
15010
15011 /*
15012 * If there is only 1 dof, we'll delete it and swap in NULL.
15013 */
15014 if (existing_dofs_count > 1) {
15015 int removed_dofs_count = existing_dofs_count - 1;
15016 size_t removed_dofs_size = DOF_IOCTL_DATA_T_SIZE(removed_dofs_count);
15017
15018 removed_dofs = kmem_alloc(removed_dofs_size, KM_SLEEP);
15019 removed_dofs->dofiod_count = removed_dofs_count;
15020
15021 /*
15022 * copy the remaining data.
15023 */
15024 if (index > 0) {
15025 bcopy(&existing_dofs->dofiod_helpers[0],
15026 &removed_dofs->dofiod_helpers[0],
15027 index * sizeof(dof_helper_t));
15028 }
15029
15030 if (index < existing_dofs_count-1) {
15031 bcopy(&existing_dofs->dofiod_helpers[index+1],
15032 &removed_dofs->dofiod_helpers[index],
15033 (existing_dofs_count - index - 1) * sizeof(dof_helper_t));
15034 }
15035 }
15036
15037 kmem_free(existing_dofs, DOF_IOCTL_DATA_T_SIZE(existing_dofs_count));
15038
15039 p->p_dtrace_lazy_dofs = removed_dofs;
15040
15041 rval = KERN_SUCCESS;
15042
15043 break;
15044 }
15045 }
15046
15047 #if DEBUG
15048 dof_ioctl_data_t* all_dofs = p->p_dtrace_lazy_dofs;
15049 if (all_dofs) {
15050 unsigned int i;
15051 for (i=0; i<all_dofs->dofiod_count-1; i++) {
15052 ASSERT(all_dofs->dofiod_helpers[i].dofhp_dof < all_dofs->dofiod_helpers[i+1].dofhp_dof);
15053 }
15054 }
15055 #endif
15056
15057 }
15058
15059 lck_mtx_unlock(&p->p_dtrace_sprlock);
15060 } else {
15061 rval = EACCES;
15062 }
15063
15064 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15065
15066 return rval;
15067 }
15068
15069 void
15070 dtrace_lazy_dofs_destroy(proc_t *p)
15071 {
15072 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15073 lck_mtx_lock(&p->p_dtrace_sprlock);
15074
15075 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15076
15077 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
15078 p->p_dtrace_lazy_dofs = NULL;
15079
15080 lck_mtx_unlock(&p->p_dtrace_sprlock);
15081 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15082
15083 if (lazy_dofs) {
15084 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
15085 }
15086 }
15087
15088 static int
15089 dtrace_lazy_dofs_proc_iterate_filter(proc_t *p, void* ignored)
15090 {
15091 #pragma unused(ignored)
15092 /*
15093 * Okay to NULL test without taking the sprlock.
15094 */
15095 return p->p_dtrace_lazy_dofs != NULL;
15096 }
15097
15098 static void
15099 dtrace_lazy_dofs_process(proc_t *p) {
15100 /*
15101 * It is possible this process may exit during our attempt to
15102 * fault in the dof. We could fix this by holding locks longer,
15103 * but the errors are benign.
15104 */
15105 lck_mtx_lock(&p->p_dtrace_sprlock);
15106
15107
15108 ASSERT(p->p_dtrace_lazy_dofs == NULL || p->p_dtrace_helpers == NULL);
15109 ASSERT(dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF);
15110
15111 dof_ioctl_data_t* lazy_dofs = p->p_dtrace_lazy_dofs;
15112 p->p_dtrace_lazy_dofs = NULL;
15113
15114 lck_mtx_unlock(&p->p_dtrace_sprlock);
15115
15116 /*
15117 * Process each dof_helper_t
15118 */
15119 if (lazy_dofs != NULL) {
15120 unsigned int i;
15121 int rval;
15122
15123 for (i=0; i<lazy_dofs->dofiod_count; i++) {
15124 /*
15125 * When loading lazy dof, we depend on the generations being sorted in ascending order.
15126 */
15127 ASSERT(i >= (lazy_dofs->dofiod_count - 1) || lazy_dofs->dofiod_helpers[i].dofhp_dof < lazy_dofs->dofiod_helpers[i+1].dofhp_dof);
15128
15129 dof_helper_t *dhp = &lazy_dofs->dofiod_helpers[i];
15130
15131 /*
15132 * We stored the generation in dofhp_dof. Save it, and restore the original value.
15133 */
15134 int generation = dhp->dofhp_dof;
15135 dhp->dofhp_dof = dhp->dofhp_addr;
15136
15137 dof_hdr_t *dof = dtrace_dof_copyin_from_proc(p, dhp->dofhp_dof, &rval);
15138
15139 if (dof != NULL) {
15140 dtrace_helpers_t *help;
15141
15142 lck_mtx_lock(&dtrace_lock);
15143
15144 /*
15145 * This must be done with the dtrace_lock held
15146 */
15147 if ((help = p->p_dtrace_helpers) == NULL)
15148 help = dtrace_helpers_create(p);
15149
15150 /*
15151 * If the generation value has been bumped, someone snuck in
15152 * when we released the dtrace lock. We have to dump this generation,
15153 * there is no safe way to load it.
15154 */
15155 if (help->dthps_generation <= generation) {
15156 help->dthps_generation = generation;
15157
15158 /*
15159 * dtrace_helper_slurp() takes responsibility for the dof --
15160 * it may free it now or it may save it and free it later.
15161 */
15162 if ((rval = dtrace_helper_slurp(p, dof, dhp)) != generation) {
15163 dtrace_dof_error(NULL, "returned value did not match expected generation");
15164 }
15165 }
15166
15167 lck_mtx_unlock(&dtrace_lock);
15168 }
15169 }
15170
15171 kmem_free(lazy_dofs, DOF_IOCTL_DATA_T_SIZE(lazy_dofs->dofiod_count));
15172 }
15173 }
15174
15175 static int
15176 dtrace_lazy_dofs_proc_iterate_doit(proc_t *p, void* ignored)
15177 {
15178 #pragma unused(ignored)
15179
15180 dtrace_lazy_dofs_process(p);
15181
15182 return PROC_RETURNED;
15183 }
15184
15185 #define DTRACE_LAZY_DOFS_DUPLICATED 1
15186
15187 static int
15188 dtrace_lazy_dofs_duplicate(proc_t *parent, proc_t *child)
15189 {
15190 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_NOTOWNED);
15191 lck_mtx_assert(&parent->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
15192 lck_mtx_assert(&child->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
15193
15194 lck_rw_lock_shared(&dtrace_dof_mode_lock);
15195 lck_mtx_lock(&parent->p_dtrace_sprlock);
15196
15197 /*
15198 * We need to make sure that the transition to lazy dofs -> helpers
15199 * was atomic for our parent
15200 */
15201 ASSERT(parent->p_dtrace_lazy_dofs == NULL || parent->p_dtrace_helpers == NULL);
15202 /*
15203 * In theory we should hold the child sprlock, but this is safe...
15204 */
15205 ASSERT(child->p_dtrace_lazy_dofs == NULL && child->p_dtrace_helpers == NULL);
15206
15207 dof_ioctl_data_t* parent_dofs = parent->p_dtrace_lazy_dofs;
15208 dof_ioctl_data_t* child_dofs = NULL;
15209 if (parent_dofs) {
15210 size_t parent_dofs_size = DOF_IOCTL_DATA_T_SIZE(parent_dofs->dofiod_count);
15211 child_dofs = kmem_alloc(parent_dofs_size, KM_SLEEP);
15212 bcopy(parent_dofs, child_dofs, parent_dofs_size);
15213 }
15214
15215 lck_mtx_unlock(&parent->p_dtrace_sprlock);
15216
15217 if (child_dofs) {
15218 lck_mtx_lock(&child->p_dtrace_sprlock);
15219 child->p_dtrace_lazy_dofs = child_dofs;
15220 lck_mtx_unlock(&child->p_dtrace_sprlock);
15221 /**
15222 * We process the DOF at this point if the mode is set to
15223 * LAZY_OFF. This can happen if DTrace is still processing the
15224 * DOF of other process (which can happen because the
15225 * protected pager can have a huge latency)
15226 * but has not processed our parent yet
15227 */
15228 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
15229 dtrace_lazy_dofs_process(child);
15230 }
15231 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15232
15233 return DTRACE_LAZY_DOFS_DUPLICATED;
15234 }
15235 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
15236
15237 return 0;
15238 }
15239
15240 static dtrace_helpers_t *
15241 dtrace_helpers_create(proc_t *p)
15242 {
15243 dtrace_helpers_t *help;
15244
15245 lck_mtx_assert(&dtrace_lock, LCK_MTX_ASSERT_OWNED);
15246 ASSERT(p->p_dtrace_helpers == NULL);
15247
15248 help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15249 help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15250 DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15251
15252 p->p_dtrace_helpers = help;
15253 dtrace_helpers++;
15254
15255 return (help);
15256 }
15257
15258 static void
15259 dtrace_helpers_destroy(proc_t* p)
15260 {
15261 dtrace_helpers_t *help;
15262 dtrace_vstate_t *vstate;
15263 uint_t i;
15264
15265 lck_mtx_lock(&dtrace_lock);
15266
15267 ASSERT(p->p_dtrace_helpers != NULL);
15268 ASSERT(dtrace_helpers > 0);
15269
15270 help = p->p_dtrace_helpers;
15271 vstate = &help->dthps_vstate;
15272
15273 /*
15274 * We're now going to lose the help from this process.
15275 */
15276 p->p_dtrace_helpers = NULL;
15277 dtrace_sync();
15278
15279 /*
15280 * Destory the helper actions.
15281 */
15282 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15283 dtrace_helper_action_t *h, *next;
15284
15285 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15286 next = h->dtha_next;
15287 dtrace_helper_action_destroy(h, vstate);
15288 h = next;
15289 }
15290 }
15291
15292 lck_mtx_unlock(&dtrace_lock);
15293
15294 /*
15295 * Destroy the helper providers.
15296 */
15297 if (help->dthps_maxprovs > 0) {
15298 lck_mtx_lock(&dtrace_meta_lock);
15299 if (dtrace_meta_pid != NULL) {
15300 ASSERT(dtrace_deferred_pid == NULL);
15301
15302 for (i = 0; i < help->dthps_nprovs; i++) {
15303 dtrace_helper_provider_remove(
15304 &help->dthps_provs[i]->dthp_prov, p->p_pid);
15305 }
15306 } else {
15307 lck_mtx_lock(&dtrace_lock);
15308 ASSERT(help->dthps_deferred == 0 ||
15309 help->dthps_next != NULL ||
15310 help->dthps_prev != NULL ||
15311 help == dtrace_deferred_pid);
15312
15313 /*
15314 * Remove the helper from the deferred list.
15315 */
15316 if (help->dthps_next != NULL)
15317 help->dthps_next->dthps_prev = help->dthps_prev;
15318 if (help->dthps_prev != NULL)
15319 help->dthps_prev->dthps_next = help->dthps_next;
15320 if (dtrace_deferred_pid == help) {
15321 dtrace_deferred_pid = help->dthps_next;
15322 ASSERT(help->dthps_prev == NULL);
15323 }
15324
15325 lck_mtx_unlock(&dtrace_lock);
15326 }
15327
15328 lck_mtx_unlock(&dtrace_meta_lock);
15329
15330 for (i = 0; i < help->dthps_nprovs; i++) {
15331 dtrace_helper_provider_destroy(help->dthps_provs[i]);
15332 }
15333
15334 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15335 sizeof (dtrace_helper_provider_t *));
15336 }
15337
15338 lck_mtx_lock(&dtrace_lock);
15339
15340 dtrace_vstate_fini(&help->dthps_vstate);
15341 kmem_free(help->dthps_actions,
15342 sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15343 kmem_free(help, sizeof (dtrace_helpers_t));
15344
15345 --dtrace_helpers;
15346 lck_mtx_unlock(&dtrace_lock);
15347 }
15348
15349 static void
15350 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15351 {
15352 dtrace_helpers_t *help, *newhelp;
15353 dtrace_helper_action_t *helper, *new, *last;
15354 dtrace_difo_t *dp;
15355 dtrace_vstate_t *vstate;
15356 uint_t i;
15357 int j, sz, hasprovs = 0;
15358
15359 lck_mtx_lock(&dtrace_lock);
15360 ASSERT(from->p_dtrace_helpers != NULL);
15361 ASSERT(dtrace_helpers > 0);
15362
15363 help = from->p_dtrace_helpers;
15364 newhelp = dtrace_helpers_create(to);
15365 ASSERT(to->p_dtrace_helpers != NULL);
15366
15367 newhelp->dthps_generation = help->dthps_generation;
15368 vstate = &newhelp->dthps_vstate;
15369
15370 /*
15371 * Duplicate the helper actions.
15372 */
15373 for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15374 if ((helper = help->dthps_actions[i]) == NULL)
15375 continue;
15376
15377 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15378 new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15379 KM_SLEEP);
15380 new->dtha_generation = helper->dtha_generation;
15381
15382 if ((dp = helper->dtha_predicate) != NULL) {
15383 dp = dtrace_difo_duplicate(dp, vstate);
15384 new->dtha_predicate = dp;
15385 }
15386
15387 new->dtha_nactions = helper->dtha_nactions;
15388 sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15389 new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15390
15391 for (j = 0; j < new->dtha_nactions; j++) {
15392 dtrace_difo_t *dpj = helper->dtha_actions[j];
15393
15394 ASSERT(dpj != NULL);
15395 dpj = dtrace_difo_duplicate(dpj, vstate);
15396 new->dtha_actions[j] = dpj;
15397 }
15398
15399 if (last != NULL) {
15400 last->dtha_next = new;
15401 } else {
15402 newhelp->dthps_actions[i] = new;
15403 }
15404
15405 last = new;
15406 }
15407 }
15408
15409 /*
15410 * Duplicate the helper providers and register them with the
15411 * DTrace framework.
15412 */
15413 if (help->dthps_nprovs > 0) {
15414 newhelp->dthps_nprovs = help->dthps_nprovs;
15415 newhelp->dthps_maxprovs = help->dthps_nprovs;
15416 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15417 sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15418 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15419 newhelp->dthps_provs[i] = help->dthps_provs[i];
15420 newhelp->dthps_provs[i]->dthp_ref++;
15421 }
15422
15423 hasprovs = 1;
15424 }
15425
15426 lck_mtx_unlock(&dtrace_lock);
15427
15428 if (hasprovs)
15429 dtrace_helper_provider_register(to, newhelp, NULL);
15430 }
15431
15432 /**
15433 * DTrace Process functions
15434 */
15435
15436 void
15437 dtrace_proc_fork(proc_t *parent_proc, proc_t *child_proc, int spawn)
15438 {
15439 /*
15440 * This code applies to new processes who are copying the task
15441 * and thread state and address spaces of their parent process.
15442 */
15443 if (!spawn) {
15444 /*
15445 * APPLE NOTE: Solaris does a sprlock() and drops the
15446 * proc_lock here. We're cheating a bit and only taking
15447 * the p_dtrace_sprlock lock. A full sprlock would
15448 * task_suspend the parent.
15449 */
15450 lck_mtx_lock(&parent_proc->p_dtrace_sprlock);
15451
15452 /*
15453 * Remove all DTrace tracepoints from the child process. We
15454 * need to do this _before_ duplicating USDT providers since
15455 * any associated probes may be immediately enabled.
15456 */
15457 if (parent_proc->p_dtrace_count > 0) {
15458 dtrace_fasttrap_fork(parent_proc, child_proc);
15459 }
15460
15461 lck_mtx_unlock(&parent_proc->p_dtrace_sprlock);
15462
15463 /*
15464 * Duplicate any lazy dof(s). This must be done while NOT
15465 * holding the parent sprlock! Lock ordering is
15466 * dtrace_dof_mode_lock, then sprlock. It is imperative we
15467 * always call dtrace_lazy_dofs_duplicate, rather than null
15468 * check and call if !NULL. If we NULL test, during lazy dof
15469 * faulting we can race with the faulting code and proceed
15470 * from here to beyond the helpers copy. The lazy dof
15471 * faulting will then fail to copy the helpers to the child
15472 * process. We return if we duplicated lazy dofs as a process
15473 * can only have one at the same time to avoid a race between
15474 * a dtrace client and dtrace_proc_fork where a process would
15475 * end up with both lazy dofs and helpers.
15476 */
15477 if (dtrace_lazy_dofs_duplicate(parent_proc, child_proc) == DTRACE_LAZY_DOFS_DUPLICATED) {
15478 return;
15479 }
15480
15481 /*
15482 * Duplicate any helper actions and providers if they haven't
15483 * already.
15484 */
15485 #if !defined(__APPLE__)
15486 /*
15487 * The SFORKING
15488 * we set above informs the code to enable USDT probes that
15489 * sprlock() may fail because the child is being forked.
15490 */
15491 #endif
15492 /*
15493 * APPLE NOTE: As best I can tell, Apple's sprlock() equivalent
15494 * never fails to find the child. We do not set SFORKING.
15495 */
15496 if (parent_proc->p_dtrace_helpers != NULL && dtrace_helpers_fork) {
15497 (*dtrace_helpers_fork)(parent_proc, child_proc);
15498 }
15499 }
15500 }
15501
15502 void
15503 dtrace_proc_exec(proc_t *p)
15504 {
15505 /*
15506 * Invalidate any predicate evaluation already cached for this thread by DTrace.
15507 * That's because we've just stored to p_comm and DTrace refers to that when it
15508 * evaluates the "execname" special variable. uid and gid may have changed as well.
15509 */
15510 dtrace_set_thread_predcache(current_thread(), 0);
15511
15512 /*
15513 * Free any outstanding lazy dof entries. It is imperative we
15514 * always call dtrace_lazy_dofs_destroy, rather than null check
15515 * and call if !NULL. If we NULL test, during lazy dof faulting
15516 * we can race with the faulting code and proceed from here to
15517 * beyond the helpers cleanup. The lazy dof faulting will then
15518 * install new helpers which no longer belong to this process!
15519 */
15520 dtrace_lazy_dofs_destroy(p);
15521
15522
15523 /*
15524 * Clean up any DTrace helpers for the process.
15525 */
15526 if (p->p_dtrace_helpers != NULL && dtrace_helpers_cleanup) {
15527 (*dtrace_helpers_cleanup)(p);
15528 }
15529
15530 /*
15531 * Cleanup the DTrace provider associated with this process.
15532 */
15533 proc_lock(p);
15534 if (p->p_dtrace_probes && dtrace_fasttrap_exec_ptr) {
15535 (*dtrace_fasttrap_exec_ptr)(p);
15536 }
15537 proc_unlock(p);
15538 }
15539
15540 void
15541 dtrace_proc_exit(proc_t *p)
15542 {
15543 /*
15544 * Free any outstanding lazy dof entries. It is imperative we
15545 * always call dtrace_lazy_dofs_destroy, rather than null check
15546 * and call if !NULL. If we NULL test, during lazy dof faulting
15547 * we can race with the faulting code and proceed from here to
15548 * beyond the helpers cleanup. The lazy dof faulting will then
15549 * install new helpers which will never be cleaned up, and leak.
15550 */
15551 dtrace_lazy_dofs_destroy(p);
15552
15553 /*
15554 * Clean up any DTrace helper actions or probes for the process.
15555 */
15556 if (p->p_dtrace_helpers != NULL) {
15557 (*dtrace_helpers_cleanup)(p);
15558 }
15559
15560 /*
15561 * Clean up any DTrace probes associated with this process.
15562 */
15563 /*
15564 * APPLE NOTE: We release ptss pages/entries in dtrace_fasttrap_exit_ptr(),
15565 * call this after dtrace_helpers_cleanup()
15566 */
15567 proc_lock(p);
15568 if (p->p_dtrace_probes && dtrace_fasttrap_exit_ptr) {
15569 (*dtrace_fasttrap_exit_ptr)(p);
15570 }
15571 proc_unlock(p);
15572 }
15573
15574 /*
15575 * DTrace Hook Functions
15576 */
15577
15578 /*
15579 * APPLE NOTE: dtrace_modctl_* routines for kext support.
15580 * Used to manipulate the modctl list within dtrace xnu.
15581 */
15582
15583 modctl_t *dtrace_modctl_list;
15584
15585 static void
15586 dtrace_modctl_add(struct modctl * newctl)
15587 {
15588 struct modctl *nextp, *prevp;
15589
15590 ASSERT(newctl != NULL);
15591 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15592
15593 // Insert new module at the front of the list,
15594
15595 newctl->mod_next = dtrace_modctl_list;
15596 dtrace_modctl_list = newctl;
15597
15598 /*
15599 * If a module exists with the same name, then that module
15600 * must have been unloaded with enabled probes. We will move
15601 * the unloaded module to the new module's stale chain and
15602 * then stop traversing the list.
15603 */
15604
15605 prevp = newctl;
15606 nextp = newctl->mod_next;
15607
15608 while (nextp != NULL) {
15609 if (nextp->mod_loaded) {
15610 /* This is a loaded module. Keep traversing. */
15611 prevp = nextp;
15612 nextp = nextp->mod_next;
15613 continue;
15614 }
15615 else {
15616 /* Found an unloaded module */
15617 if (strncmp (newctl->mod_modname, nextp->mod_modname, KMOD_MAX_NAME)) {
15618 /* Names don't match. Keep traversing. */
15619 prevp = nextp;
15620 nextp = nextp->mod_next;
15621 continue;
15622 }
15623 else {
15624 /* We found a stale entry, move it. We're done. */
15625 prevp->mod_next = nextp->mod_next;
15626 newctl->mod_stale = nextp;
15627 nextp->mod_next = NULL;
15628 break;
15629 }
15630 }
15631 }
15632 }
15633
15634 static modctl_t *
15635 dtrace_modctl_lookup(struct kmod_info * kmod)
15636 {
15637 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15638
15639 struct modctl * ctl;
15640
15641 for (ctl = dtrace_modctl_list; ctl; ctl=ctl->mod_next) {
15642 if (ctl->mod_id == kmod->id)
15643 return(ctl);
15644 }
15645 return (NULL);
15646 }
15647
15648 /*
15649 * This routine is called from dtrace_module_unloaded().
15650 * It removes a modctl structure and its stale chain
15651 * from the kext shadow list.
15652 */
15653 static void
15654 dtrace_modctl_remove(struct modctl * ctl)
15655 {
15656 ASSERT(ctl != NULL);
15657 lck_mtx_assert(&mod_lock, LCK_MTX_ASSERT_OWNED);
15658 modctl_t *prevp, *nextp, *curp;
15659
15660 // Remove stale chain first
15661 for (curp=ctl->mod_stale; curp != NULL; curp=nextp) {
15662 nextp = curp->mod_stale;
15663 /* There should NEVER be user symbols allocated at this point */
15664 ASSERT(curp->mod_user_symbols == NULL);
15665 kmem_free(curp, sizeof(modctl_t));
15666 }
15667
15668 prevp = NULL;
15669 curp = dtrace_modctl_list;
15670
15671 while (curp != ctl) {
15672 prevp = curp;
15673 curp = curp->mod_next;
15674 }
15675
15676 if (prevp != NULL) {
15677 prevp->mod_next = ctl->mod_next;
15678 }
15679 else {
15680 dtrace_modctl_list = ctl->mod_next;
15681 }
15682
15683 /* There should NEVER be user symbols allocated at this point */
15684 ASSERT(ctl->mod_user_symbols == NULL);
15685
15686 kmem_free (ctl, sizeof(modctl_t));
15687 }
15688
15689 /*
15690 * APPLE NOTE: The kext loader will call dtrace_module_loaded
15691 * when the kext is loaded in memory, but before calling the
15692 * kext's start routine.
15693 *
15694 * Return 0 on success
15695 * Return -1 on failure
15696 */
15697
15698 static int
15699 dtrace_module_loaded(struct kmod_info *kmod, uint32_t flag)
15700 {
15701 dtrace_provider_t *prv;
15702
15703 /*
15704 * If kernel symbols have been disabled, return immediately
15705 * DTRACE_KERNEL_SYMBOLS_NEVER is a permanent mode, it is safe to test without holding locks
15706 */
15707 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER)
15708 return 0;
15709
15710 struct modctl *ctl = NULL;
15711 if (!kmod || kmod->address == 0 || kmod->size == 0)
15712 return(-1);
15713
15714 lck_mtx_lock(&dtrace_provider_lock);
15715 lck_mtx_lock(&mod_lock);
15716
15717 /*
15718 * Have we seen this kext before?
15719 */
15720
15721 ctl = dtrace_modctl_lookup(kmod);
15722
15723 if (ctl != NULL) {
15724 /* bail... we already have this kext in the modctl list */
15725 lck_mtx_unlock(&mod_lock);
15726 lck_mtx_unlock(&dtrace_provider_lock);
15727 if (dtrace_err_verbose)
15728 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);
15729 return(-1);
15730 }
15731 else {
15732 ctl = kmem_alloc(sizeof(struct modctl), KM_SLEEP);
15733 if (ctl == NULL) {
15734 if (dtrace_err_verbose)
15735 cmn_err(CE_WARN, "dtrace module load '%s %u' is failing ", kmod->name, (uint_t)kmod->id);
15736 lck_mtx_unlock(&mod_lock);
15737 lck_mtx_unlock(&dtrace_provider_lock);
15738 return (-1);
15739 }
15740 ctl->mod_next = NULL;
15741 ctl->mod_stale = NULL;
15742 strlcpy (ctl->mod_modname, kmod->name, sizeof(ctl->mod_modname));
15743 ctl->mod_loadcnt = kmod->id;
15744 ctl->mod_nenabled = 0;
15745 ctl->mod_address = kmod->address;
15746 ctl->mod_size = kmod->size;
15747 ctl->mod_id = kmod->id;
15748 ctl->mod_loaded = 1;
15749 ctl->mod_flags = 0;
15750 ctl->mod_user_symbols = NULL;
15751
15752 /*
15753 * Find the UUID for this module, if it has one
15754 */
15755 kernel_mach_header_t* header = (kernel_mach_header_t *)ctl->mod_address;
15756 struct load_command* load_cmd = (struct load_command *)&header[1];
15757 uint32_t i;
15758 for (i = 0; i < header->ncmds; i++) {
15759 if (load_cmd->cmd == LC_UUID) {
15760 struct uuid_command* uuid_cmd = (struct uuid_command *)load_cmd;
15761 memcpy(ctl->mod_uuid, uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
15762 ctl->mod_flags |= MODCTL_HAS_UUID;
15763 break;
15764 }
15765 load_cmd = (struct load_command *)((caddr_t)load_cmd + load_cmd->cmdsize);
15766 }
15767
15768 if (ctl->mod_address == g_kernel_kmod_info.address) {
15769 ctl->mod_flags |= MODCTL_IS_MACH_KERNEL;
15770 }
15771 }
15772 dtrace_modctl_add(ctl);
15773
15774 /*
15775 * We must hold the dtrace_lock to safely test non permanent dtrace_fbt_symbol_mode(s)
15776 */
15777 lck_mtx_lock(&dtrace_lock);
15778
15779 /*
15780 * DTrace must decide if it will instrument modules lazily via
15781 * userspace symbols (default mode), or instrument immediately via
15782 * kernel symbols (non-default mode)
15783 *
15784 * When in default/lazy mode, DTrace will only support modules
15785 * built with a valid UUID.
15786 *
15787 * Overriding the default can be done explicitly in one of
15788 * the following two ways.
15789 *
15790 * A module can force symbols from kernel space using the plist key,
15791 * OSBundleForceDTraceInit (see kmod.h). If this per kext state is set,
15792 * we fall through and instrument this module now.
15793 *
15794 * Or, the boot-arg, dtrace_kernel_symbol_mode, can be set to force symbols
15795 * from kernel space (see dtrace_impl.h). If this system state is set
15796 * to a non-userspace mode, we fall through and instrument the module now.
15797 */
15798
15799 if ((dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) &&
15800 (!(flag & KMOD_DTRACE_FORCE_INIT)))
15801 {
15802 /* We will instrument the module lazily -- this is the default */
15803 lck_mtx_unlock(&dtrace_lock);
15804 lck_mtx_unlock(&mod_lock);
15805 lck_mtx_unlock(&dtrace_provider_lock);
15806 return 0;
15807 }
15808
15809 /* We will instrument the module immediately using kernel symbols */
15810 ctl->mod_flags |= MODCTL_HAS_KERNEL_SYMBOLS;
15811
15812 lck_mtx_unlock(&dtrace_lock);
15813
15814 /*
15815 * We're going to call each providers per-module provide operation
15816 * specifying only this module.
15817 */
15818 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15819 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15820
15821 /*
15822 * APPLE NOTE: The contract with the kext loader is that once this function
15823 * has completed, it may delete kernel symbols at will.
15824 * We must set this while still holding the mod_lock.
15825 */
15826 ctl->mod_flags &= ~MODCTL_HAS_KERNEL_SYMBOLS;
15827
15828 lck_mtx_unlock(&mod_lock);
15829 lck_mtx_unlock(&dtrace_provider_lock);
15830
15831 /*
15832 * If we have any retained enablings, we need to match against them.
15833 * Enabling probes requires that cpu_lock be held, and we cannot hold
15834 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15835 * module. (In particular, this happens when loading scheduling
15836 * classes.) So if we have any retained enablings, we need to dispatch
15837 * our task queue to do the match for us.
15838 */
15839 lck_mtx_lock(&dtrace_lock);
15840
15841 if (dtrace_retained == NULL) {
15842 lck_mtx_unlock(&dtrace_lock);
15843 return 0;
15844 }
15845
15846 /* APPLE NOTE!
15847 *
15848 * The cpu_lock mentioned above is only held by dtrace code, Apple's xnu never actually
15849 * holds it for any reason. Thus the comment above is invalid, we can directly invoke
15850 * dtrace_enabling_matchall without jumping through all the hoops, and we can avoid
15851 * the delay call as well.
15852 */
15853 lck_mtx_unlock(&dtrace_lock);
15854
15855 dtrace_enabling_matchall();
15856
15857 return 0;
15858 }
15859
15860 /*
15861 * Return 0 on success
15862 * Return -1 on failure
15863 */
15864 static int
15865 dtrace_module_unloaded(struct kmod_info *kmod)
15866 {
15867 dtrace_probe_t template, *probe, *first, *next;
15868 dtrace_provider_t *prov;
15869 struct modctl *ctl = NULL;
15870 struct modctl *syncctl = NULL;
15871 struct modctl *nextsyncctl = NULL;
15872 int syncmode = 0;
15873
15874 lck_mtx_lock(&dtrace_provider_lock);
15875 lck_mtx_lock(&mod_lock);
15876 lck_mtx_lock(&dtrace_lock);
15877
15878 if (kmod == NULL) {
15879 syncmode = 1;
15880 }
15881 else {
15882 ctl = dtrace_modctl_lookup(kmod);
15883 if (ctl == NULL)
15884 {
15885 lck_mtx_unlock(&dtrace_lock);
15886 lck_mtx_unlock(&mod_lock);
15887 lck_mtx_unlock(&dtrace_provider_lock);
15888 return (-1);
15889 }
15890 ctl->mod_loaded = 0;
15891 ctl->mod_address = 0;
15892 ctl->mod_size = 0;
15893 }
15894
15895 if (dtrace_bymod == NULL) {
15896 /*
15897 * The DTrace module is loaded (obviously) but not attached;
15898 * we don't have any work to do.
15899 */
15900 if (ctl != NULL)
15901 (void)dtrace_modctl_remove(ctl);
15902 lck_mtx_unlock(&dtrace_lock);
15903 lck_mtx_unlock(&mod_lock);
15904 lck_mtx_unlock(&dtrace_provider_lock);
15905 return(0);
15906 }
15907
15908 /* Syncmode set means we target and traverse entire modctl list. */
15909 if (syncmode)
15910 nextsyncctl = dtrace_modctl_list;
15911
15912 syncloop:
15913 if (syncmode)
15914 {
15915 /* find a stale modctl struct */
15916 for (syncctl = nextsyncctl; syncctl != NULL; syncctl=syncctl->mod_next) {
15917 if (syncctl->mod_address == 0)
15918 break;
15919 }
15920 if (syncctl==NULL)
15921 {
15922 /* We have no more work to do */
15923 lck_mtx_unlock(&dtrace_lock);
15924 lck_mtx_unlock(&mod_lock);
15925 lck_mtx_unlock(&dtrace_provider_lock);
15926 return(0);
15927 }
15928 else {
15929 /* keep track of next syncctl in case this one is removed */
15930 nextsyncctl = syncctl->mod_next;
15931 ctl = syncctl;
15932 }
15933 }
15934
15935 template.dtpr_mod = ctl->mod_modname;
15936
15937 for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15938 probe != NULL; probe = probe->dtpr_nextmod) {
15939 if (probe->dtpr_ecb != NULL) {
15940 /*
15941 * This shouldn't _actually_ be possible -- we're
15942 * unloading a module that has an enabled probe in it.
15943 * (It's normally up to the provider to make sure that
15944 * this can't happen.) However, because dtps_enable()
15945 * doesn't have a failure mode, there can be an
15946 * enable/unload race. Upshot: we don't want to
15947 * assert, but we're not going to disable the
15948 * probe, either.
15949 */
15950
15951
15952 if (syncmode) {
15953 /* We're syncing, let's look at next in list */
15954 goto syncloop;
15955 }
15956
15957 lck_mtx_unlock(&dtrace_lock);
15958 lck_mtx_unlock(&mod_lock);
15959 lck_mtx_unlock(&dtrace_provider_lock);
15960
15961 if (dtrace_err_verbose) {
15962 cmn_err(CE_WARN, "unloaded module '%s' had "
15963 "enabled probes", ctl->mod_modname);
15964 }
15965 return(-1);
15966 }
15967 }
15968
15969 probe = first;
15970
15971 for (first = NULL; probe != NULL; probe = next) {
15972 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15973
15974 dtrace_probes[probe->dtpr_id - 1] = NULL;
15975 probe->dtpr_provider->dtpv_probe_count--;
15976
15977 next = probe->dtpr_nextmod;
15978 dtrace_hash_remove(dtrace_bymod, probe);
15979 dtrace_hash_remove(dtrace_byfunc, probe);
15980 dtrace_hash_remove(dtrace_byname, probe);
15981
15982 if (first == NULL) {
15983 first = probe;
15984 probe->dtpr_nextmod = NULL;
15985 } else {
15986 probe->dtpr_nextmod = first;
15987 first = probe;
15988 }
15989 }
15990
15991 /*
15992 * We've removed all of the module's probes from the hash chains and
15993 * from the probe array. Now issue a dtrace_sync() to be sure that
15994 * everyone has cleared out from any probe array processing.
15995 */
15996 dtrace_sync();
15997
15998 for (probe = first; probe != NULL; probe = first) {
15999 first = probe->dtpr_nextmod;
16000 prov = probe->dtpr_provider;
16001 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
16002 probe->dtpr_arg);
16003 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
16004 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
16005 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
16006 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
16007
16008 zfree(dtrace_probe_t_zone, probe);
16009 }
16010
16011 dtrace_modctl_remove(ctl);
16012
16013 if (syncmode)
16014 goto syncloop;
16015
16016 lck_mtx_unlock(&dtrace_lock);
16017 lck_mtx_unlock(&mod_lock);
16018 lck_mtx_unlock(&dtrace_provider_lock);
16019
16020 return(0);
16021 }
16022
16023 void
16024 dtrace_suspend(void)
16025 {
16026 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
16027 }
16028
16029 void
16030 dtrace_resume(void)
16031 {
16032 dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
16033 }
16034
16035 static int
16036 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
16037 {
16038 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
16039 lck_mtx_lock(&dtrace_lock);
16040
16041 switch (what) {
16042 case CPU_CONFIG: {
16043 dtrace_state_t *state;
16044 dtrace_optval_t *opt, rs, c;
16045
16046 /*
16047 * For now, we only allocate a new buffer for anonymous state.
16048 */
16049 if ((state = dtrace_anon.dta_state) == NULL)
16050 break;
16051
16052 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
16053 break;
16054
16055 opt = state->dts_options;
16056 c = opt[DTRACEOPT_CPU];
16057
16058 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
16059 break;
16060
16061 /*
16062 * Regardless of what the actual policy is, we're going to
16063 * temporarily set our resize policy to be manual. We're
16064 * also going to temporarily set our CPU option to denote
16065 * the newly configured CPU.
16066 */
16067 rs = opt[DTRACEOPT_BUFRESIZE];
16068 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
16069 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
16070
16071 (void) dtrace_state_buffers(state);
16072
16073 opt[DTRACEOPT_BUFRESIZE] = rs;
16074 opt[DTRACEOPT_CPU] = c;
16075
16076 break;
16077 }
16078
16079 case CPU_UNCONFIG:
16080 /*
16081 * We don't free the buffer in the CPU_UNCONFIG case. (The
16082 * buffer will be freed when the consumer exits.)
16083 */
16084 break;
16085
16086 default:
16087 break;
16088 }
16089
16090 lck_mtx_unlock(&dtrace_lock);
16091 return (0);
16092 }
16093
16094 static void
16095 dtrace_cpu_setup_initial(processorid_t cpu)
16096 {
16097 (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
16098 }
16099
16100 static void
16101 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
16102 {
16103 if (dtrace_toxranges >= dtrace_toxranges_max) {
16104 int osize, nsize;
16105 dtrace_toxrange_t *range;
16106
16107 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16108
16109 if (osize == 0) {
16110 ASSERT(dtrace_toxrange == NULL);
16111 ASSERT(dtrace_toxranges_max == 0);
16112 dtrace_toxranges_max = 1;
16113 } else {
16114 dtrace_toxranges_max <<= 1;
16115 }
16116
16117 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
16118 range = kmem_zalloc(nsize, KM_SLEEP);
16119
16120 if (dtrace_toxrange != NULL) {
16121 ASSERT(osize != 0);
16122 bcopy(dtrace_toxrange, range, osize);
16123 kmem_free(dtrace_toxrange, osize);
16124 }
16125
16126 dtrace_toxrange = range;
16127 }
16128
16129 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
16130 ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
16131
16132 dtrace_toxrange[dtrace_toxranges].dtt_base = base;
16133 dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
16134 dtrace_toxranges++;
16135 }
16136
16137 /*
16138 * DTrace Driver Cookbook Functions
16139 */
16140 /*ARGSUSED*/
16141 static int
16142 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16143 {
16144 #pragma unused(cmd) /* __APPLE__ */
16145 dtrace_provider_id_t id;
16146 dtrace_state_t *state = NULL;
16147 dtrace_enabling_t *enab;
16148
16149 lck_mtx_lock(&cpu_lock);
16150 lck_mtx_lock(&dtrace_provider_lock);
16151 lck_mtx_lock(&dtrace_lock);
16152
16153 /* Darwin uses BSD cloning device driver to automagically obtain minor device number. */
16154
16155 ddi_report_dev(devi);
16156 dtrace_devi = devi;
16157
16158 dtrace_modload = dtrace_module_loaded;
16159 dtrace_modunload = dtrace_module_unloaded;
16160 dtrace_cpu_init = dtrace_cpu_setup_initial;
16161 dtrace_helpers_cleanup = dtrace_helpers_destroy;
16162 dtrace_helpers_fork = dtrace_helpers_duplicate;
16163 dtrace_cpustart_init = dtrace_suspend;
16164 dtrace_cpustart_fini = dtrace_resume;
16165 dtrace_debugger_init = dtrace_suspend;
16166 dtrace_debugger_fini = dtrace_resume;
16167
16168 register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16169
16170 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
16171
16172 dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16173 NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16174 dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16175 1, INT_MAX, 0);
16176
16177 dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16178 sizeof (dtrace_dstate_percpu_t) * (int)NCPU, DTRACE_STATE_ALIGN,
16179 NULL, NULL, NULL, NULL, NULL, 0);
16180
16181 lck_mtx_assert(&cpu_lock, LCK_MTX_ASSERT_OWNED);
16182
16183 dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16184 offsetof(dtrace_probe_t, dtpr_nextmod),
16185 offsetof(dtrace_probe_t, dtpr_prevmod));
16186
16187 dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16188 offsetof(dtrace_probe_t, dtpr_nextfunc),
16189 offsetof(dtrace_probe_t, dtpr_prevfunc));
16190
16191 dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16192 offsetof(dtrace_probe_t, dtpr_nextname),
16193 offsetof(dtrace_probe_t, dtpr_prevname));
16194
16195 if (dtrace_retain_max < 1) {
16196 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16197 "setting to 1", dtrace_retain_max);
16198 dtrace_retain_max = 1;
16199 }
16200
16201 /*
16202 * Now discover our toxic ranges.
16203 */
16204 dtrace_toxic_ranges(dtrace_toxrange_add);
16205
16206 /*
16207 * Before we register ourselves as a provider to our own framework,
16208 * we would like to assert that dtrace_provider is NULL -- but that's
16209 * not true if we were loaded as a dependency of a DTrace provider.
16210 * Once we've registered, we can assert that dtrace_provider is our
16211 * pseudo provider.
16212 */
16213 (void) dtrace_register("dtrace", &dtrace_provider_attr,
16214 DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16215
16216 ASSERT(dtrace_provider != NULL);
16217 ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16218
16219 #if defined (__x86_64__)
16220 dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16221 dtrace_provider, NULL, NULL, "BEGIN", 1, NULL);
16222 dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16223 dtrace_provider, NULL, NULL, "END", 0, NULL);
16224 dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16225 dtrace_provider, NULL, NULL, "ERROR", 3, NULL);
16226 #else
16227 #error Unknown Architecture
16228 #endif
16229
16230 dtrace_anon_property();
16231 lck_mtx_unlock(&cpu_lock);
16232
16233 /*
16234 * If DTrace helper tracing is enabled, we need to allocate the
16235 * trace buffer and initialize the values.
16236 */
16237 if (dtrace_helptrace_enabled) {
16238 ASSERT(dtrace_helptrace_buffer == NULL);
16239 dtrace_helptrace_buffer =
16240 kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16241 dtrace_helptrace_next = 0;
16242 }
16243
16244 /*
16245 * If there are already providers, we must ask them to provide their
16246 * probes, and then match any anonymous enabling against them. Note
16247 * that there should be no other retained enablings at this time:
16248 * the only retained enablings at this time should be the anonymous
16249 * enabling.
16250 */
16251 if (dtrace_anon.dta_enabling != NULL) {
16252 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16253
16254 /*
16255 * APPLE NOTE: if handling anonymous dof, switch symbol modes.
16256 */
16257 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
16258 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
16259 }
16260
16261 dtrace_enabling_provide(NULL);
16262 state = dtrace_anon.dta_state;
16263
16264 /*
16265 * We couldn't hold cpu_lock across the above call to
16266 * dtrace_enabling_provide(), but we must hold it to actually
16267 * enable the probes. We have to drop all of our locks, pick
16268 * up cpu_lock, and regain our locks before matching the
16269 * retained anonymous enabling.
16270 */
16271 lck_mtx_unlock(&dtrace_lock);
16272 lck_mtx_unlock(&dtrace_provider_lock);
16273
16274 lck_mtx_lock(&cpu_lock);
16275 lck_mtx_lock(&dtrace_provider_lock);
16276 lck_mtx_lock(&dtrace_lock);
16277
16278 if ((enab = dtrace_anon.dta_enabling) != NULL)
16279 (void) dtrace_enabling_match(enab, NULL, NULL);
16280
16281 lck_mtx_unlock(&cpu_lock);
16282 }
16283
16284 lck_mtx_unlock(&dtrace_lock);
16285 lck_mtx_unlock(&dtrace_provider_lock);
16286
16287 if (state != NULL) {
16288 /*
16289 * If we created any anonymous state, set it going now.
16290 */
16291 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16292 }
16293
16294 return (DDI_SUCCESS);
16295 }
16296
16297 /*ARGSUSED*/
16298 static int
16299 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16300 {
16301 #pragma unused(flag, otyp)
16302 dtrace_state_t *state;
16303 uint32_t priv;
16304 uid_t uid;
16305 zoneid_t zoneid;
16306 int rv;
16307
16308 /* APPLE: Darwin puts Helper on its own major device. */
16309
16310 /*
16311 * If no DTRACE_PRIV_* bits are set in the credential, then the
16312 * caller lacks sufficient permission to do anything with DTrace.
16313 */
16314 dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16315 if (priv == DTRACE_PRIV_NONE)
16316 return (EACCES);
16317
16318 /*
16319 * APPLE NOTE: We delay the initialization of fasttrap as late as possible.
16320 * It certainly can't be later than now!
16321 */
16322 fasttrap_init();
16323
16324 /*
16325 * Ask all providers to provide all their probes.
16326 */
16327 lck_mtx_lock(&dtrace_provider_lock);
16328 dtrace_probe_provide(NULL, NULL);
16329 lck_mtx_unlock(&dtrace_provider_lock);
16330
16331 lck_mtx_lock(&cpu_lock);
16332 lck_mtx_lock(&dtrace_lock);
16333 dtrace_opens++;
16334 dtrace_membar_producer();
16335
16336 /*
16337 * If the kernel debugger is active (that is, if the kernel debugger
16338 * modified text in some way), we won't allow the open.
16339 */
16340 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16341 dtrace_opens--;
16342 lck_mtx_unlock(&dtrace_lock);
16343 lck_mtx_unlock(&cpu_lock);
16344 return (EBUSY);
16345 }
16346
16347 rv = dtrace_state_create(devp, cred_p, &state);
16348 lck_mtx_unlock(&cpu_lock);
16349
16350 if (rv != 0 || state == NULL) {
16351 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16352 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16353 lck_mtx_unlock(&dtrace_lock);
16354 /* propagate EAGAIN or ERESTART */
16355 return (rv);
16356 }
16357
16358 lck_mtx_unlock(&dtrace_lock);
16359
16360 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
16361
16362 /*
16363 * If we are currently lazy, transition states.
16364 *
16365 * Unlike dtrace_close, we do not need to check the
16366 * value of dtrace_opens, as any positive value (and
16367 * we count as 1) means we transition states.
16368 */
16369 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_ON) {
16370 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_OFF;
16371 /*
16372 * We do not need to hold the exclusive lock while processing
16373 * DOF on processes. We do need to make sure the mode does not get
16374 * changed to DTRACE_DOF_MODE_LAZY_ON during that stage though
16375 * (which should not happen anyway since it only happens in
16376 * dtrace_close). There is no way imcomplete USDT probes can be
16377 * activate by any DTrace clients here since they all have to
16378 * call dtrace_open and be blocked on dtrace_dof_mode_lock
16379 */
16380 lck_rw_lock_exclusive_to_shared(&dtrace_dof_mode_lock);
16381 /*
16382 * Iterate all existing processes and load lazy dofs.
16383 */
16384 proc_iterate(PROC_ALLPROCLIST | PROC_NOWAITTRANS,
16385 dtrace_lazy_dofs_proc_iterate_doit,
16386 NULL,
16387 dtrace_lazy_dofs_proc_iterate_filter,
16388 NULL);
16389
16390 lck_rw_unlock_shared(&dtrace_dof_mode_lock);
16391 }
16392 else {
16393 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
16394 }
16395
16396
16397 /*
16398 * Update kernel symbol state.
16399 *
16400 * We must own the provider and dtrace locks.
16401 *
16402 * NOTE! It may appear there is a race by setting this value so late
16403 * after dtrace_probe_provide. However, any kext loaded after the
16404 * call to probe provide and before we set LAZY_OFF will be marked as
16405 * eligible for symbols from userspace. The same dtrace that is currently
16406 * calling dtrace_open() (this call!) will get a list of kexts needing
16407 * symbols and fill them in, thus closing the race window.
16408 *
16409 * We want to set this value only after it certain it will succeed, as
16410 * this significantly reduces the complexity of error exits.
16411 */
16412 lck_mtx_lock(&dtrace_lock);
16413 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE) {
16414 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_KERNEL;
16415 }
16416 lck_mtx_unlock(&dtrace_lock);
16417
16418 return (0);
16419 }
16420
16421 /*ARGSUSED*/
16422 static int
16423 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16424 {
16425 #pragma unused(flag, otyp, cred_p) /* __APPLE__ */
16426 minor_t minor = getminor(dev);
16427 dtrace_state_t *state;
16428
16429 /* APPLE NOTE: Darwin puts Helper on its own major device. */
16430 state = dtrace_state_get(minor);
16431
16432 lck_mtx_lock(&cpu_lock);
16433 lck_mtx_lock(&dtrace_lock);
16434
16435 if (state->dts_anon) {
16436 /*
16437 * There is anonymous state. Destroy that first.
16438 */
16439 ASSERT(dtrace_anon.dta_state == NULL);
16440 dtrace_state_destroy(state->dts_anon);
16441 }
16442
16443 dtrace_state_destroy(state);
16444 ASSERT(dtrace_opens > 0);
16445
16446 /*
16447 * Only relinquish control of the kernel debugger interface when there
16448 * are no consumers and no anonymous enablings.
16449 */
16450 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16451 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16452
16453 lck_mtx_unlock(&dtrace_lock);
16454 lck_mtx_unlock(&cpu_lock);
16455
16456 /*
16457 * Lock ordering requires the dof mode lock be taken before
16458 * the dtrace_lock.
16459 */
16460 lck_rw_lock_exclusive(&dtrace_dof_mode_lock);
16461 lck_mtx_lock(&dtrace_lock);
16462
16463 if (dtrace_opens == 0) {
16464 /*
16465 * If we are currently lazy-off, and this is the last close, transition to
16466 * lazy state.
16467 */
16468 if (dtrace_dof_mode == DTRACE_DOF_MODE_LAZY_OFF) {
16469 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
16470 }
16471
16472 /*
16473 * If we are the last dtrace client, switch back to lazy (from userspace) symbols
16474 */
16475 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_FROM_KERNEL) {
16476 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
16477 }
16478 }
16479
16480 lck_mtx_unlock(&dtrace_lock);
16481 lck_rw_unlock_exclusive(&dtrace_dof_mode_lock);
16482
16483 /*
16484 * Kext probes may be retained past the end of the kext's lifespan. The
16485 * probes are kept until the last reference to them has been removed.
16486 * Since closing an active dtrace context is likely to drop that last reference,
16487 * lets take a shot at cleaning out the orphaned probes now.
16488 */
16489 dtrace_module_unloaded(NULL);
16490
16491 return (0);
16492 }
16493
16494 /*ARGSUSED*/
16495 static int
16496 dtrace_ioctl_helper(u_long cmd, caddr_t arg, int *rv)
16497 {
16498 #pragma unused(rv)
16499 /*
16500 * Safe to check this outside the dof mode lock
16501 */
16502 if (dtrace_dof_mode == DTRACE_DOF_MODE_NEVER)
16503 return KERN_SUCCESS;
16504
16505 switch (cmd) {
16506 case DTRACEHIOC_ADDDOF:
16507 {
16508 dof_helper_t *dhp = NULL;
16509 size_t dof_ioctl_data_size;
16510 dof_ioctl_data_t* multi_dof;
16511 unsigned int i;
16512 int rval = 0;
16513 user_addr_t user_address = *(user_addr_t*)arg;
16514 uint64_t dof_count;
16515 int multi_dof_claimed = 0;
16516 proc_t* p = current_proc();
16517
16518 /*
16519 * Read the number of DOF sections being passed in.
16520 */
16521 if (copyin(user_address + offsetof(dof_ioctl_data_t, dofiod_count),
16522 &dof_count,
16523 sizeof(dof_count))) {
16524 dtrace_dof_error(NULL, "failed to copyin dofiod_count");
16525 return (EFAULT);
16526 }
16527
16528 /*
16529 * Range check the count.
16530 */
16531 if (dof_count == 0 || dof_count > 1024) {
16532 dtrace_dof_error(NULL, "dofiod_count is not valid");
16533 return (EINVAL);
16534 }
16535
16536 /*
16537 * Allocate a correctly sized structure and copyin the data.
16538 */
16539 dof_ioctl_data_size = DOF_IOCTL_DATA_T_SIZE(dof_count);
16540 if ((multi_dof = kmem_alloc(dof_ioctl_data_size, KM_SLEEP)) == NULL)
16541 return (ENOMEM);
16542
16543 /* NOTE! We can no longer exit this method via return */
16544 if (copyin(user_address, multi_dof, dof_ioctl_data_size) != 0) {
16545 dtrace_dof_error(NULL, "failed copyin of dof_ioctl_data_t");
16546 rval = EFAULT;
16547 goto cleanup;
16548 }
16549
16550 /*
16551 * Check that the count didn't change between the first copyin and the second.
16552 */
16553 if (multi_dof->dofiod_count != dof_count) {
16554 rval = EINVAL;
16555 goto cleanup;
16556 }
16557
16558 /*
16559 * Try to process lazily first.
16560 */
16561 rval = dtrace_lazy_dofs_add(p, multi_dof, &multi_dof_claimed);
16562
16563 /*
16564 * If rval is EACCES, we must be non-lazy.
16565 */
16566 if (rval == EACCES) {
16567 rval = 0;
16568 /*
16569 * Process each dof_helper_t
16570 */
16571 i = 0;
16572 do {
16573 dhp = &multi_dof->dofiod_helpers[i];
16574
16575 dof_hdr_t *dof = dtrace_dof_copyin(dhp->dofhp_dof, &rval);
16576
16577 if (dof != NULL) {
16578 lck_mtx_lock(&dtrace_lock);
16579
16580 /*
16581 * dtrace_helper_slurp() takes responsibility for the dof --
16582 * it may free it now or it may save it and free it later.
16583 */
16584 if ((dhp->dofhp_dof = (uint64_t)dtrace_helper_slurp(p, dof, dhp)) == -1ULL) {
16585 rval = EINVAL;
16586 }
16587
16588 lck_mtx_unlock(&dtrace_lock);
16589 }
16590 } while (++i < multi_dof->dofiod_count && rval == 0);
16591 }
16592
16593 /*
16594 * We need to copyout the multi_dof struct, because it contains
16595 * the generation (unique id) values needed to call DTRACEHIOC_REMOVE
16596 *
16597 * This could certainly be better optimized.
16598 */
16599 if (copyout(multi_dof, user_address, dof_ioctl_data_size) != 0) {
16600 dtrace_dof_error(NULL, "failed copyout of dof_ioctl_data_t");
16601 /* Don't overwrite pre-existing error code */
16602 if (rval == 0) rval = EFAULT;
16603 }
16604
16605 cleanup:
16606 /*
16607 * If we had to allocate struct memory, free it.
16608 */
16609 if (multi_dof != NULL && !multi_dof_claimed) {
16610 kmem_free(multi_dof, dof_ioctl_data_size);
16611 }
16612
16613 return rval;
16614 }
16615
16616 case DTRACEHIOC_REMOVE: {
16617 int generation = *(int*)arg;
16618 proc_t* p = current_proc();
16619
16620 /*
16621 * Try lazy first.
16622 */
16623 int rval = dtrace_lazy_dofs_remove(p, generation);
16624
16625 /*
16626 * EACCES means non-lazy
16627 */
16628 if (rval == EACCES) {
16629 lck_mtx_lock(&dtrace_lock);
16630 rval = dtrace_helper_destroygen(p, generation);
16631 lck_mtx_unlock(&dtrace_lock);
16632 }
16633
16634 return (rval);
16635 }
16636
16637 default:
16638 break;
16639 }
16640
16641 return ENOTTY;
16642 }
16643
16644 /*ARGSUSED*/
16645 static int
16646 dtrace_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
16647 {
16648 #pragma unused(md)
16649 minor_t minor = getminor(dev);
16650 dtrace_state_t *state;
16651 int rval;
16652
16653 /* Darwin puts Helper on its own major device. */
16654
16655 state = dtrace_state_get(minor);
16656
16657 if (state->dts_anon) {
16658 ASSERT(dtrace_anon.dta_state == NULL);
16659 state = state->dts_anon;
16660 }
16661
16662 switch (cmd) {
16663 case DTRACEIOC_PROVIDER: {
16664 dtrace_providerdesc_t pvd;
16665 dtrace_provider_t *pvp;
16666
16667 if (copyin(arg, &pvd, sizeof (pvd)) != 0)
16668 return (EFAULT);
16669
16670 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16671 lck_mtx_lock(&dtrace_provider_lock);
16672
16673 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16674 if (strncmp(pvp->dtpv_name, pvd.dtvd_name, DTRACE_PROVNAMELEN) == 0)
16675 break;
16676 }
16677
16678 lck_mtx_unlock(&dtrace_provider_lock);
16679
16680 if (pvp == NULL)
16681 return (ESRCH);
16682
16683 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16684 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16685 if (copyout(&pvd, arg, sizeof (pvd)) != 0)
16686 return (EFAULT);
16687
16688 return (0);
16689 }
16690
16691 case DTRACEIOC_EPROBE: {
16692 dtrace_eprobedesc_t epdesc;
16693 dtrace_ecb_t *ecb;
16694 dtrace_action_t *act;
16695 void *buf;
16696 size_t size;
16697 uintptr_t dest;
16698 int nrecs;
16699
16700 if (copyin(arg, &epdesc, sizeof (epdesc)) != 0)
16701 return (EFAULT);
16702
16703 lck_mtx_lock(&dtrace_lock);
16704
16705 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16706 lck_mtx_unlock(&dtrace_lock);
16707 return (EINVAL);
16708 }
16709
16710 if (ecb->dte_probe == NULL) {
16711 lck_mtx_unlock(&dtrace_lock);
16712 return (EINVAL);
16713 }
16714
16715 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16716 epdesc.dtepd_uarg = ecb->dte_uarg;
16717 epdesc.dtepd_size = ecb->dte_size;
16718
16719 nrecs = epdesc.dtepd_nrecs;
16720 epdesc.dtepd_nrecs = 0;
16721 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16722 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16723 continue;
16724
16725 epdesc.dtepd_nrecs++;
16726 }
16727
16728 /*
16729 * Now that we have the size, we need to allocate a temporary
16730 * buffer in which to store the complete description. We need
16731 * the temporary buffer to be able to drop dtrace_lock()
16732 * across the copyout(), below.
16733 */
16734 size = sizeof (dtrace_eprobedesc_t) +
16735 (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16736
16737 buf = kmem_alloc(size, KM_SLEEP);
16738 dest = (uintptr_t)buf;
16739
16740 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16741 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16742
16743 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16744 if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16745 continue;
16746
16747 if (nrecs-- == 0)
16748 break;
16749
16750 bcopy(&act->dta_rec, (void *)dest,
16751 sizeof (dtrace_recdesc_t));
16752 dest += sizeof (dtrace_recdesc_t);
16753 }
16754
16755 lck_mtx_unlock(&dtrace_lock);
16756
16757 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16758 kmem_free(buf, size);
16759 return (EFAULT);
16760 }
16761
16762 kmem_free(buf, size);
16763 return (0);
16764 }
16765
16766 case DTRACEIOC_AGGDESC: {
16767 dtrace_aggdesc_t aggdesc;
16768 dtrace_action_t *act;
16769 dtrace_aggregation_t *agg;
16770 int nrecs;
16771 uint32_t offs;
16772 dtrace_recdesc_t *lrec;
16773 void *buf;
16774 size_t size;
16775 uintptr_t dest;
16776
16777 if (copyin(arg, &aggdesc, sizeof (aggdesc)) != 0)
16778 return (EFAULT);
16779
16780 lck_mtx_lock(&dtrace_lock);
16781
16782 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16783 lck_mtx_unlock(&dtrace_lock);
16784 return (EINVAL);
16785 }
16786
16787 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16788
16789 nrecs = aggdesc.dtagd_nrecs;
16790 aggdesc.dtagd_nrecs = 0;
16791
16792 offs = agg->dtag_base;
16793 lrec = &agg->dtag_action.dta_rec;
16794 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16795
16796 for (act = agg->dtag_first; ; act = act->dta_next) {
16797 ASSERT(act->dta_intuple ||
16798 DTRACEACT_ISAGG(act->dta_kind));
16799
16800 /*
16801 * If this action has a record size of zero, it
16802 * denotes an argument to the aggregating action.
16803 * Because the presence of this record doesn't (or
16804 * shouldn't) affect the way the data is interpreted,
16805 * we don't copy it out to save user-level the
16806 * confusion of dealing with a zero-length record.
16807 */
16808 if (act->dta_rec.dtrd_size == 0) {
16809 ASSERT(agg->dtag_hasarg);
16810 continue;
16811 }
16812
16813 aggdesc.dtagd_nrecs++;
16814
16815 if (act == &agg->dtag_action)
16816 break;
16817 }
16818
16819 /*
16820 * Now that we have the size, we need to allocate a temporary
16821 * buffer in which to store the complete description. We need
16822 * the temporary buffer to be able to drop dtrace_lock()
16823 * across the copyout(), below.
16824 */
16825 size = sizeof (dtrace_aggdesc_t) +
16826 (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16827
16828 buf = kmem_alloc(size, KM_SLEEP);
16829 dest = (uintptr_t)buf;
16830
16831 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16832 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16833
16834 for (act = agg->dtag_first; ; act = act->dta_next) {
16835 dtrace_recdesc_t rec = act->dta_rec;
16836
16837 /*
16838 * See the comment in the above loop for why we pass
16839 * over zero-length records.
16840 */
16841 if (rec.dtrd_size == 0) {
16842 ASSERT(agg->dtag_hasarg);
16843 continue;
16844 }
16845
16846 if (nrecs-- == 0)
16847 break;
16848
16849 rec.dtrd_offset -= offs;
16850 bcopy(&rec, (void *)dest, sizeof (rec));
16851 dest += sizeof (dtrace_recdesc_t);
16852
16853 if (act == &agg->dtag_action)
16854 break;
16855 }
16856
16857 lck_mtx_unlock(&dtrace_lock);
16858
16859 if (copyout(buf, arg, dest - (uintptr_t)buf) != 0) {
16860 kmem_free(buf, size);
16861 return (EFAULT);
16862 }
16863
16864 kmem_free(buf, size);
16865 return (0);
16866 }
16867
16868 case DTRACEIOC_ENABLE: {
16869 dof_hdr_t *dof;
16870 dtrace_enabling_t *enab = NULL;
16871 dtrace_vstate_t *vstate;
16872 int err = 0;
16873
16874 *rv = 0;
16875
16876 /*
16877 * If a NULL argument has been passed, we take this as our
16878 * cue to reevaluate our enablings.
16879 */
16880 if (arg == 0) {
16881 dtrace_enabling_matchall();
16882
16883 return (0);
16884 }
16885
16886 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16887 return (rval);
16888
16889 lck_mtx_lock(&cpu_lock);
16890 lck_mtx_lock(&dtrace_lock);
16891 vstate = &state->dts_vstate;
16892
16893 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16894 lck_mtx_unlock(&dtrace_lock);
16895 lck_mtx_unlock(&cpu_lock);
16896 dtrace_dof_destroy(dof);
16897 return (EBUSY);
16898 }
16899
16900 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16901 lck_mtx_unlock(&dtrace_lock);
16902 lck_mtx_unlock(&cpu_lock);
16903 dtrace_dof_destroy(dof);
16904 return (EINVAL);
16905 }
16906
16907 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16908 dtrace_enabling_destroy(enab);
16909 lck_mtx_unlock(&dtrace_lock);
16910 lck_mtx_unlock(&cpu_lock);
16911 dtrace_dof_destroy(dof);
16912 return (rval);
16913 }
16914
16915 if ((err = dtrace_enabling_match(enab, rv, NULL)) == 0) {
16916 err = dtrace_enabling_retain(enab);
16917 } else {
16918 dtrace_enabling_destroy(enab);
16919 }
16920
16921 lck_mtx_unlock(&dtrace_lock);
16922 lck_mtx_unlock(&cpu_lock);
16923 dtrace_dof_destroy(dof);
16924
16925 return (err);
16926 }
16927
16928 case DTRACEIOC_REPLICATE: {
16929 dtrace_repldesc_t desc;
16930 dtrace_probedesc_t *match = &desc.dtrpd_match;
16931 dtrace_probedesc_t *create = &desc.dtrpd_create;
16932 int err;
16933
16934 if (copyin(arg, &desc, sizeof (desc)) != 0)
16935 return (EFAULT);
16936
16937 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16938 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16939 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16940 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16941
16942 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16943 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16944 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16945 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16946
16947 lck_mtx_lock(&dtrace_lock);
16948 err = dtrace_enabling_replicate(state, match, create);
16949 lck_mtx_unlock(&dtrace_lock);
16950
16951 return (err);
16952 }
16953
16954 case DTRACEIOC_PROBEMATCH:
16955 case DTRACEIOC_PROBES: {
16956 dtrace_probe_t *probe = NULL;
16957 dtrace_probedesc_t desc;
16958 dtrace_probekey_t pkey;
16959 dtrace_id_t i;
16960 int m = 0;
16961 uint32_t priv;
16962 uid_t uid;
16963 zoneid_t zoneid;
16964
16965 if (copyin(arg, &desc, sizeof (desc)) != 0)
16966 return (EFAULT);
16967
16968 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16969 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16970 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16971 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16972
16973 /*
16974 * Before we attempt to match this probe, we want to give
16975 * all providers the opportunity to provide it.
16976 */
16977 if (desc.dtpd_id == DTRACE_IDNONE) {
16978 lck_mtx_lock(&dtrace_provider_lock);
16979 dtrace_probe_provide(&desc, NULL);
16980 lck_mtx_unlock(&dtrace_provider_lock);
16981 desc.dtpd_id++;
16982 }
16983
16984 if (cmd == DTRACEIOC_PROBEMATCH) {
16985 dtrace_probekey(&desc, &pkey);
16986 pkey.dtpk_id = DTRACE_IDNONE;
16987 }
16988
16989 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16990
16991 lck_mtx_lock(&dtrace_lock);
16992
16993 if (cmd == DTRACEIOC_PROBEMATCH) {
16994 /* Quiet compiler warning */
16995 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
16996 if ((probe = dtrace_probes[i - 1]) != NULL &&
16997 (m = dtrace_match_probe(probe, &pkey,
16998 priv, uid, zoneid)) != 0)
16999 break;
17000 }
17001
17002 if (m < 0) {
17003 lck_mtx_unlock(&dtrace_lock);
17004 return (EINVAL);
17005 }
17006
17007 } else {
17008 /* Quiet compiler warning */
17009 for (i = desc.dtpd_id; i <= (dtrace_id_t)dtrace_nprobes; i++) {
17010 if ((probe = dtrace_probes[i - 1]) != NULL &&
17011 dtrace_match_priv(probe, priv, uid, zoneid))
17012 break;
17013 }
17014 }
17015
17016 if (probe == NULL) {
17017 lck_mtx_unlock(&dtrace_lock);
17018 return (ESRCH);
17019 }
17020
17021 dtrace_probe_description(probe, &desc);
17022 lck_mtx_unlock(&dtrace_lock);
17023
17024 if (copyout(&desc, arg, sizeof (desc)) != 0)
17025 return (EFAULT);
17026
17027 return (0);
17028 }
17029
17030 case DTRACEIOC_PROBEARG: {
17031 dtrace_argdesc_t desc;
17032 dtrace_probe_t *probe;
17033 dtrace_provider_t *prov;
17034
17035 if (copyin(arg, &desc, sizeof (desc)) != 0)
17036 return (EFAULT);
17037
17038 if (desc.dtargd_id == DTRACE_IDNONE)
17039 return (EINVAL);
17040
17041 if (desc.dtargd_ndx == DTRACE_ARGNONE)
17042 return (EINVAL);
17043
17044 lck_mtx_lock(&dtrace_provider_lock);
17045 lck_mtx_lock(&mod_lock);
17046 lck_mtx_lock(&dtrace_lock);
17047
17048 /* Quiet compiler warning */
17049 if (desc.dtargd_id > (dtrace_id_t)dtrace_nprobes) {
17050 lck_mtx_unlock(&dtrace_lock);
17051 lck_mtx_unlock(&mod_lock);
17052 lck_mtx_unlock(&dtrace_provider_lock);
17053 return (EINVAL);
17054 }
17055
17056 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
17057 lck_mtx_unlock(&dtrace_lock);
17058 lck_mtx_unlock(&mod_lock);
17059 lck_mtx_unlock(&dtrace_provider_lock);
17060 return (EINVAL);
17061 }
17062
17063 lck_mtx_unlock(&dtrace_lock);
17064
17065 prov = probe->dtpr_provider;
17066
17067 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
17068 /*
17069 * There isn't any typed information for this probe.
17070 * Set the argument number to DTRACE_ARGNONE.
17071 */
17072 desc.dtargd_ndx = DTRACE_ARGNONE;
17073 } else {
17074 desc.dtargd_native[0] = '\0';
17075 desc.dtargd_xlate[0] = '\0';
17076 desc.dtargd_mapping = desc.dtargd_ndx;
17077
17078 prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
17079 probe->dtpr_id, probe->dtpr_arg, &desc);
17080 }
17081
17082 lck_mtx_unlock(&mod_lock);
17083 lck_mtx_unlock(&dtrace_provider_lock);
17084
17085 if (copyout(&desc, arg, sizeof (desc)) != 0)
17086 return (EFAULT);
17087
17088 return (0);
17089 }
17090
17091 case DTRACEIOC_GO: {
17092 processorid_t cpuid;
17093 rval = dtrace_state_go(state, &cpuid);
17094
17095 if (rval != 0)
17096 return (rval);
17097
17098 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
17099 return (EFAULT);
17100
17101 return (0);
17102 }
17103
17104 case DTRACEIOC_STOP: {
17105 processorid_t cpuid;
17106
17107 lck_mtx_lock(&dtrace_lock);
17108 rval = dtrace_state_stop(state, &cpuid);
17109 lck_mtx_unlock(&dtrace_lock);
17110
17111 if (rval != 0)
17112 return (rval);
17113
17114 if (copyout(&cpuid, arg, sizeof (cpuid)) != 0)
17115 return (EFAULT);
17116
17117 return (0);
17118 }
17119
17120 case DTRACEIOC_DOFGET: {
17121 dof_hdr_t hdr, *dof;
17122 uint64_t len;
17123
17124 if (copyin(arg, &hdr, sizeof (hdr)) != 0)
17125 return (EFAULT);
17126
17127 lck_mtx_lock(&dtrace_lock);
17128 dof = dtrace_dof_create(state);
17129 lck_mtx_unlock(&dtrace_lock);
17130
17131 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
17132 rval = copyout(dof, arg, len);
17133 dtrace_dof_destroy(dof);
17134
17135 return (rval == 0 ? 0 : EFAULT);
17136 }
17137
17138 case DTRACEIOC_SLEEP: {
17139 int64_t time;
17140 uint64_t abstime;
17141 uint64_t rvalue = DTRACE_WAKE_TIMEOUT;
17142
17143 if (copyin(arg, &time, sizeof(time)) != 0)
17144 return (EFAULT);
17145
17146 nanoseconds_to_absolutetime((uint64_t)time, &abstime);
17147 clock_absolutetime_interval_to_deadline(abstime, &abstime);
17148
17149 if (assert_wait_deadline(state, THREAD_ABORTSAFE, abstime) == THREAD_WAITING) {
17150 if (state->dts_buf_over_limit > 0) {
17151 clear_wait(current_thread(), THREAD_INTERRUPTED);
17152 rvalue = DTRACE_WAKE_BUF_LIMIT;
17153 } else {
17154 thread_block(THREAD_CONTINUE_NULL);
17155 if (state->dts_buf_over_limit > 0) {
17156 rvalue = DTRACE_WAKE_BUF_LIMIT;
17157 }
17158 }
17159 }
17160
17161 if (copyout(&rvalue, arg, sizeof(rvalue)) != 0)
17162 return (EFAULT);
17163
17164 return (0);
17165 }
17166
17167 case DTRACEIOC_SIGNAL: {
17168 wakeup(state);
17169 return (0);
17170 }
17171
17172 case DTRACEIOC_AGGSNAP:
17173 case DTRACEIOC_BUFSNAP: {
17174 dtrace_bufdesc_t desc;
17175 caddr_t cached;
17176 boolean_t over_limit;
17177 dtrace_buffer_t *buf;
17178
17179 if (copyin(arg, &desc, sizeof (desc)) != 0)
17180 return (EFAULT);
17181
17182 if ((int)desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
17183 return (EINVAL);
17184
17185 lck_mtx_lock(&dtrace_lock);
17186
17187 if (cmd == DTRACEIOC_BUFSNAP) {
17188 buf = &state->dts_buffer[desc.dtbd_cpu];
17189 } else {
17190 buf = &state->dts_aggbuffer[desc.dtbd_cpu];
17191 }
17192
17193 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
17194 size_t sz = buf->dtb_offset;
17195
17196 if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
17197 lck_mtx_unlock(&dtrace_lock);
17198 return (EBUSY);
17199 }
17200
17201 /*
17202 * If this buffer has already been consumed, we're
17203 * going to indicate that there's nothing left here
17204 * to consume.
17205 */
17206 if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
17207 lck_mtx_unlock(&dtrace_lock);
17208
17209 desc.dtbd_size = 0;
17210 desc.dtbd_drops = 0;
17211 desc.dtbd_errors = 0;
17212 desc.dtbd_oldest = 0;
17213 sz = sizeof (desc);
17214
17215 if (copyout(&desc, arg, sz) != 0)
17216 return (EFAULT);
17217
17218 return (0);
17219 }
17220
17221 /*
17222 * If this is a ring buffer that has wrapped, we want
17223 * to copy the whole thing out.
17224 */
17225 if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
17226 dtrace_buffer_polish(buf);
17227 sz = buf->dtb_size;
17228 }
17229
17230 if (copyout(buf->dtb_tomax, (user_addr_t)desc.dtbd_data, sz) != 0) {
17231 lck_mtx_unlock(&dtrace_lock);
17232 return (EFAULT);
17233 }
17234
17235 desc.dtbd_size = sz;
17236 desc.dtbd_drops = buf->dtb_drops;
17237 desc.dtbd_errors = buf->dtb_errors;
17238 desc.dtbd_oldest = buf->dtb_xamot_offset;
17239 desc.dtbd_timestamp = dtrace_gethrtime();
17240
17241 lck_mtx_unlock(&dtrace_lock);
17242
17243 if (copyout(&desc, arg, sizeof (desc)) != 0)
17244 return (EFAULT);
17245
17246 buf->dtb_flags |= DTRACEBUF_CONSUMED;
17247
17248 return (0);
17249 }
17250
17251 if (buf->dtb_tomax == NULL) {
17252 ASSERT(buf->dtb_xamot == NULL);
17253 lck_mtx_unlock(&dtrace_lock);
17254 return (ENOENT);
17255 }
17256
17257 cached = buf->dtb_tomax;
17258 over_limit = buf->dtb_cur_limit == buf->dtb_size;
17259
17260 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
17261
17262 dtrace_xcall(desc.dtbd_cpu,
17263 (dtrace_xcall_t)dtrace_buffer_switch, buf);
17264
17265 state->dts_errors += buf->dtb_xamot_errors;
17266
17267 /*
17268 * If the buffers did not actually switch, then the cross call
17269 * did not take place -- presumably because the given CPU is
17270 * not in the ready set. If this is the case, we'll return
17271 * ENOENT.
17272 */
17273 if (buf->dtb_tomax == cached) {
17274 ASSERT(buf->dtb_xamot != cached);
17275 lck_mtx_unlock(&dtrace_lock);
17276 return (ENOENT);
17277 }
17278
17279 ASSERT(cached == buf->dtb_xamot);
17280 /*
17281 * At this point we know the buffer have switched, so we
17282 * can decrement the over limit count if the buffer was over
17283 * its limit. The new buffer might already be over its limit
17284 * yet, but we don't care since we're guaranteed not to be
17285 * checking the buffer over limit count at this point.
17286 */
17287 if (over_limit) {
17288 uint32_t old = atomic_add_32(&state->dts_buf_over_limit, -1);
17289 #pragma unused(old)
17290
17291 /*
17292 * Verify that we didn't underflow the value
17293 */
17294 ASSERT(old != 0);
17295 }
17296
17297 /*
17298 * We have our snapshot; now copy it out.
17299 */
17300 if (copyout(buf->dtb_xamot, (user_addr_t)desc.dtbd_data,
17301 buf->dtb_xamot_offset) != 0) {
17302 lck_mtx_unlock(&dtrace_lock);
17303 return (EFAULT);
17304 }
17305
17306 desc.dtbd_size = buf->dtb_xamot_offset;
17307 desc.dtbd_drops = buf->dtb_xamot_drops;
17308 desc.dtbd_errors = buf->dtb_xamot_errors;
17309 desc.dtbd_oldest = 0;
17310 desc.dtbd_timestamp = buf->dtb_switched;
17311
17312 lck_mtx_unlock(&dtrace_lock);
17313
17314 /*
17315 * Finally, copy out the buffer description.
17316 */
17317 if (copyout(&desc, arg, sizeof (desc)) != 0)
17318 return (EFAULT);
17319
17320 return (0);
17321 }
17322
17323 case DTRACEIOC_CONF: {
17324 dtrace_conf_t conf;
17325
17326 bzero(&conf, sizeof (conf));
17327 conf.dtc_difversion = DIF_VERSION;
17328 conf.dtc_difintregs = DIF_DIR_NREGS;
17329 conf.dtc_diftupregs = DIF_DTR_NREGS;
17330 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
17331
17332 if (copyout(&conf, arg, sizeof (conf)) != 0)
17333 return (EFAULT);
17334
17335 return (0);
17336 }
17337
17338 case DTRACEIOC_STATUS: {
17339 dtrace_status_t stat;
17340 dtrace_dstate_t *dstate;
17341 int i, j;
17342 uint64_t nerrs;
17343
17344 /*
17345 * See the comment in dtrace_state_deadman() for the reason
17346 * for setting dts_laststatus to INT64_MAX before setting
17347 * it to the correct value.
17348 */
17349 state->dts_laststatus = INT64_MAX;
17350 dtrace_membar_producer();
17351 state->dts_laststatus = dtrace_gethrtime();
17352
17353 bzero(&stat, sizeof (stat));
17354
17355 lck_mtx_lock(&dtrace_lock);
17356
17357 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17358 lck_mtx_unlock(&dtrace_lock);
17359 return (ENOENT);
17360 }
17361
17362 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17363 stat.dtst_exiting = 1;
17364
17365 nerrs = state->dts_errors;
17366 dstate = &state->dts_vstate.dtvs_dynvars;
17367
17368 for (i = 0; i < (int)NCPU; i++) {
17369 dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17370
17371 stat.dtst_dyndrops += dcpu->dtdsc_drops;
17372 stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17373 stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17374
17375 if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17376 stat.dtst_filled++;
17377
17378 nerrs += state->dts_buffer[i].dtb_errors;
17379
17380 for (j = 0; j < state->dts_nspeculations; j++) {
17381 dtrace_speculation_t *spec;
17382 dtrace_buffer_t *buf;
17383
17384 spec = &state->dts_speculations[j];
17385 buf = &spec->dtsp_buffer[i];
17386 stat.dtst_specdrops += buf->dtb_xamot_drops;
17387 }
17388 }
17389
17390 stat.dtst_specdrops_busy = state->dts_speculations_busy;
17391 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17392 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17393 stat.dtst_dblerrors = state->dts_dblerrors;
17394 stat.dtst_killed =
17395 (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17396 stat.dtst_errors = nerrs;
17397
17398 lck_mtx_unlock(&dtrace_lock);
17399
17400 if (copyout(&stat, arg, sizeof (stat)) != 0)
17401 return (EFAULT);
17402
17403 return (0);
17404 }
17405
17406 case DTRACEIOC_FORMAT: {
17407 dtrace_fmtdesc_t fmt;
17408 char *str;
17409 int len;
17410
17411 if (copyin(arg, &fmt, sizeof (fmt)) != 0)
17412 return (EFAULT);
17413
17414 lck_mtx_lock(&dtrace_lock);
17415
17416 if (fmt.dtfd_format == 0 ||
17417 fmt.dtfd_format > state->dts_nformats) {
17418 lck_mtx_unlock(&dtrace_lock);
17419 return (EINVAL);
17420 }
17421
17422 /*
17423 * Format strings are allocated contiguously and they are
17424 * never freed; if a format index is less than the number
17425 * of formats, we can assert that the format map is non-NULL
17426 * and that the format for the specified index is non-NULL.
17427 */
17428 ASSERT(state->dts_formats != NULL);
17429 str = state->dts_formats[fmt.dtfd_format - 1];
17430 ASSERT(str != NULL);
17431
17432 len = strlen(str) + 1;
17433
17434 if (len > fmt.dtfd_length) {
17435 fmt.dtfd_length = len;
17436
17437 if (copyout(&fmt, arg, sizeof (fmt)) != 0) {
17438 lck_mtx_unlock(&dtrace_lock);
17439 return (EINVAL);
17440 }
17441 } else {
17442 if (copyout(str, (user_addr_t)fmt.dtfd_string, len) != 0) {
17443 lck_mtx_unlock(&dtrace_lock);
17444 return (EINVAL);
17445 }
17446 }
17447
17448 lck_mtx_unlock(&dtrace_lock);
17449 return (0);
17450 }
17451
17452 case DTRACEIOC_MODUUIDSLIST: {
17453 size_t module_uuids_list_size;
17454 dtrace_module_uuids_list_t* uuids_list;
17455 uint64_t dtmul_count;
17456
17457 /*
17458 * Security restrictions make this operation illegal, if this is enabled DTrace
17459 * must refuse to provide any fbt probes.
17460 */
17461 if (dtrace_fbt_probes_restricted()) {
17462 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
17463 return (EPERM);
17464 }
17465
17466 /*
17467 * Fail if the kernel symbol mode makes this operation illegal.
17468 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
17469 * for them without holding the dtrace_lock.
17470 */
17471 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
17472 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
17473 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_MODUUIDSLIST", dtrace_kernel_symbol_mode);
17474 return (EPERM);
17475 }
17476
17477 /*
17478 * Read the number of symbolsdesc structs being passed in.
17479 */
17480 if (copyin(arg + offsetof(dtrace_module_uuids_list_t, dtmul_count),
17481 &dtmul_count,
17482 sizeof(dtmul_count))) {
17483 cmn_err(CE_WARN, "failed to copyin dtmul_count");
17484 return (EFAULT);
17485 }
17486
17487 /*
17488 * Range check the count. More than 2k kexts is probably an error.
17489 */
17490 if (dtmul_count > 2048) {
17491 cmn_err(CE_WARN, "dtmul_count is not valid");
17492 return (EINVAL);
17493 }
17494
17495 /*
17496 * For all queries, we return EINVAL when the user specified
17497 * count does not match the actual number of modules we find
17498 * available.
17499 *
17500 * If the user specified count is zero, then this serves as a
17501 * simple query to count the available modules in need of symbols.
17502 */
17503
17504 rval = 0;
17505
17506 if (dtmul_count == 0)
17507 {
17508 lck_mtx_lock(&mod_lock);
17509 struct modctl* ctl = dtrace_modctl_list;
17510 while (ctl) {
17511 /* Update the private probes bit */
17512 if (dtrace_provide_private_probes)
17513 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17514
17515 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17516 if (!MOD_SYMBOLS_DONE(ctl)) {
17517 dtmul_count++;
17518 rval = EINVAL;
17519 }
17520 ctl = ctl->mod_next;
17521 }
17522 lck_mtx_unlock(&mod_lock);
17523
17524 if (copyout(&dtmul_count, arg, sizeof (dtmul_count)) != 0)
17525 return (EFAULT);
17526 else
17527 return (rval);
17528 }
17529
17530 /*
17531 * If we reach this point, then we have a request for full list data.
17532 * Allocate a correctly sized structure and copyin the data.
17533 */
17534 module_uuids_list_size = DTRACE_MODULE_UUIDS_LIST_SIZE(dtmul_count);
17535 if ((uuids_list = kmem_alloc(module_uuids_list_size, KM_SLEEP)) == NULL)
17536 return (ENOMEM);
17537
17538 /* NOTE! We can no longer exit this method via return */
17539 if (copyin(arg, uuids_list, module_uuids_list_size) != 0) {
17540 cmn_err(CE_WARN, "failed copyin of dtrace_module_uuids_list_t");
17541 rval = EFAULT;
17542 goto moduuidslist_cleanup;
17543 }
17544
17545 /*
17546 * Check that the count didn't change between the first copyin and the second.
17547 */
17548 if (uuids_list->dtmul_count != dtmul_count) {
17549 rval = EINVAL;
17550 goto moduuidslist_cleanup;
17551 }
17552
17553 /*
17554 * Build the list of UUID's that need symbols
17555 */
17556 lck_mtx_lock(&mod_lock);
17557
17558 dtmul_count = 0;
17559
17560 struct modctl* ctl = dtrace_modctl_list;
17561 while (ctl) {
17562 /* Update the private probes bit */
17563 if (dtrace_provide_private_probes)
17564 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17565
17566 /*
17567 * We assume that userspace symbols will be "better" than kernel level symbols,
17568 * as userspace can search for dSYM(s) and symbol'd binaries. Even if kernel syms
17569 * are available, add user syms if the module might use them.
17570 */
17571 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17572 if (!MOD_SYMBOLS_DONE(ctl)) {
17573 UUID* uuid = &uuids_list->dtmul_uuid[dtmul_count];
17574 if (dtmul_count++ < uuids_list->dtmul_count) {
17575 memcpy(uuid, ctl->mod_uuid, sizeof(UUID));
17576 }
17577 }
17578 ctl = ctl->mod_next;
17579 }
17580
17581 lck_mtx_unlock(&mod_lock);
17582
17583 if (uuids_list->dtmul_count < dtmul_count)
17584 rval = EINVAL;
17585
17586 uuids_list->dtmul_count = dtmul_count;
17587
17588 /*
17589 * Copyout the symbols list (or at least the count!)
17590 */
17591 if (copyout(uuids_list, arg, module_uuids_list_size) != 0) {
17592 cmn_err(CE_WARN, "failed copyout of dtrace_symbolsdesc_list_t");
17593 rval = EFAULT;
17594 }
17595
17596 moduuidslist_cleanup:
17597 /*
17598 * If we had to allocate struct memory, free it.
17599 */
17600 if (uuids_list != NULL) {
17601 kmem_free(uuids_list, module_uuids_list_size);
17602 }
17603
17604 return rval;
17605 }
17606
17607 case DTRACEIOC_PROVMODSYMS: {
17608 size_t module_symbols_size;
17609 dtrace_module_symbols_t* module_symbols;
17610 uint64_t dtmodsyms_count;
17611
17612 /*
17613 * Security restrictions make this operation illegal, if this is enabled DTrace
17614 * must refuse to provide any fbt probes.
17615 */
17616 if (dtrace_fbt_probes_restricted()) {
17617 cmn_err(CE_WARN, "security restrictions disallow DTRACEIOC_MODUUIDSLIST");
17618 return (EPERM);
17619 }
17620
17621 /*
17622 * Fail if the kernel symbol mode makes this operation illegal.
17623 * Both NEVER & ALWAYS_FROM_KERNEL are permanent states, it is legal to check
17624 * for them without holding the dtrace_lock.
17625 */
17626 if (dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_NEVER ||
17627 dtrace_kernel_symbol_mode == DTRACE_KERNEL_SYMBOLS_ALWAYS_FROM_KERNEL) {
17628 cmn_err(CE_WARN, "dtrace_kernel_symbol_mode of %u disallows DTRACEIOC_PROVMODSYMS", dtrace_kernel_symbol_mode);
17629 return (EPERM);
17630 }
17631
17632 /*
17633 * Read the number of module symbols structs being passed in.
17634 */
17635 if (copyin(arg + offsetof(dtrace_module_symbols_t, dtmodsyms_count),
17636 &dtmodsyms_count,
17637 sizeof(dtmodsyms_count))) {
17638 cmn_err(CE_WARN, "failed to copyin dtmodsyms_count");
17639 return (EFAULT);
17640 }
17641
17642 /*
17643 * Range check the count. How much data can we pass around?
17644 * FIX ME!
17645 */
17646 if (dtmodsyms_count == 0 || (dtmodsyms_count > 100 * 1024)) {
17647 cmn_err(CE_WARN, "dtmodsyms_count is not valid");
17648 return (EINVAL);
17649 }
17650
17651 /*
17652 * Allocate a correctly sized structure and copyin the data.
17653 */
17654 module_symbols_size = DTRACE_MODULE_SYMBOLS_SIZE(dtmodsyms_count);
17655 if ((module_symbols = kmem_alloc(module_symbols_size, KM_SLEEP)) == NULL)
17656 return (ENOMEM);
17657
17658 rval = 0;
17659
17660 /* NOTE! We can no longer exit this method via return */
17661 if (copyin(arg, module_symbols, module_symbols_size) != 0) {
17662 cmn_err(CE_WARN, "failed copyin of dtrace_module_symbols_t");
17663 rval = EFAULT;
17664 goto module_symbols_cleanup;
17665 }
17666
17667 /*
17668 * Check that the count didn't change between the first copyin and the second.
17669 */
17670 if (module_symbols->dtmodsyms_count != dtmodsyms_count) {
17671 rval = EINVAL;
17672 goto module_symbols_cleanup;
17673 }
17674
17675 /*
17676 * Find the modctl to add symbols to.
17677 */
17678 lck_mtx_lock(&dtrace_provider_lock);
17679 lck_mtx_lock(&mod_lock);
17680
17681 struct modctl* ctl = dtrace_modctl_list;
17682 while (ctl) {
17683 /* Update the private probes bit */
17684 if (dtrace_provide_private_probes)
17685 ctl->mod_flags |= MODCTL_FBT_PROVIDE_PRIVATE_PROBES;
17686
17687 ASSERT(!MOD_HAS_USERSPACE_SYMBOLS(ctl));
17688 if (MOD_HAS_UUID(ctl) && !MOD_SYMBOLS_DONE(ctl)) {
17689 if (memcmp(module_symbols->dtmodsyms_uuid, ctl->mod_uuid, sizeof(UUID)) == 0) {
17690 /* BINGO! */
17691 ctl->mod_user_symbols = module_symbols;
17692 break;
17693 }
17694 }
17695 ctl = ctl->mod_next;
17696 }
17697
17698 if (ctl) {
17699 dtrace_provider_t *prv;
17700
17701 /*
17702 * We're going to call each providers per-module provide operation
17703 * specifying only this module.
17704 */
17705 for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
17706 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
17707
17708 /*
17709 * We gave every provider a chance to provide with the user syms, go ahead and clear them
17710 */
17711 ctl->mod_user_symbols = NULL; /* MUST reset this to clear HAS_USERSPACE_SYMBOLS */
17712 }
17713
17714 lck_mtx_unlock(&mod_lock);
17715 lck_mtx_unlock(&dtrace_provider_lock);
17716
17717 module_symbols_cleanup:
17718 /*
17719 * If we had to allocate struct memory, free it.
17720 */
17721 if (module_symbols != NULL) {
17722 kmem_free(module_symbols, module_symbols_size);
17723 }
17724
17725 return rval;
17726 }
17727
17728 case DTRACEIOC_PROCWAITFOR: {
17729 dtrace_procdesc_t pdesc = {
17730 .p_name = {0},
17731 .p_pid = -1
17732 };
17733
17734 if ((rval = copyin(arg, &pdesc, sizeof(pdesc))) != 0)
17735 goto proc_waitfor_error;
17736
17737 if ((rval = dtrace_proc_waitfor(&pdesc)) != 0)
17738 goto proc_waitfor_error;
17739
17740 if ((rval = copyout(&pdesc, arg, sizeof(pdesc))) != 0)
17741 goto proc_waitfor_error;
17742
17743 return 0;
17744
17745 proc_waitfor_error:
17746 /* The process was suspended, revert this since the client will not do it. */
17747 if (pdesc.p_pid != -1) {
17748 proc_t *proc = proc_find(pdesc.p_pid);
17749 if (proc != PROC_NULL) {
17750 task_pidresume(proc->task);
17751 proc_rele(proc);
17752 }
17753 }
17754
17755 return rval;
17756 }
17757
17758 default:
17759 break;
17760 }
17761
17762 return (ENOTTY);
17763 }
17764
17765 /*
17766 * APPLE NOTE: dtrace_detach not implemented
17767 */
17768 #if !defined(__APPLE__)
17769 /*ARGSUSED*/
17770 static int
17771 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17772 {
17773 dtrace_state_t *state;
17774
17775 switch (cmd) {
17776 case DDI_DETACH:
17777 break;
17778
17779 case DDI_SUSPEND:
17780 return (DDI_SUCCESS);
17781
17782 default:
17783 return (DDI_FAILURE);
17784 }
17785
17786 lck_mtx_lock(&cpu_lock);
17787 lck_mtx_lock(&dtrace_provider_lock);
17788 lck_mtx_lock(&dtrace_lock);
17789
17790 ASSERT(dtrace_opens == 0);
17791
17792 if (dtrace_helpers > 0) {
17793 lck_mtx_unlock(&dtrace_lock);
17794 lck_mtx_unlock(&dtrace_provider_lock);
17795 lck_mtx_unlock(&cpu_lock);
17796 return (DDI_FAILURE);
17797 }
17798
17799 if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17800 lck_mtx_unlock(&dtrace_lock);
17801 lck_mtx_unlock(&dtrace_provider_lock);
17802 lck_mtx_unlock(&cpu_lock);
17803 return (DDI_FAILURE);
17804 }
17805
17806 dtrace_provider = NULL;
17807
17808 if ((state = dtrace_anon_grab()) != NULL) {
17809 /*
17810 * If there were ECBs on this state, the provider should
17811 * have not been allowed to detach; assert that there is
17812 * none.
17813 */
17814 ASSERT(state->dts_necbs == 0);
17815 dtrace_state_destroy(state);
17816
17817 /*
17818 * If we're being detached with anonymous state, we need to
17819 * indicate to the kernel debugger that DTrace is now inactive.
17820 */
17821 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17822 }
17823
17824 bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17825 unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17826 dtrace_cpu_init = NULL;
17827 dtrace_helpers_cleanup = NULL;
17828 dtrace_helpers_fork = NULL;
17829 dtrace_cpustart_init = NULL;
17830 dtrace_cpustart_fini = NULL;
17831 dtrace_debugger_init = NULL;
17832 dtrace_debugger_fini = NULL;
17833 dtrace_kreloc_init = NULL;
17834 dtrace_kreloc_fini = NULL;
17835 dtrace_modload = NULL;
17836 dtrace_modunload = NULL;
17837
17838 lck_mtx_unlock(&cpu_lock);
17839
17840 if (dtrace_helptrace_enabled) {
17841 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17842 dtrace_helptrace_buffer = NULL;
17843 }
17844
17845 kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17846 dtrace_probes = NULL;
17847 dtrace_nprobes = 0;
17848
17849 dtrace_hash_destroy(dtrace_bymod);
17850 dtrace_hash_destroy(dtrace_byfunc);
17851 dtrace_hash_destroy(dtrace_byname);
17852 dtrace_bymod = NULL;
17853 dtrace_byfunc = NULL;
17854 dtrace_byname = NULL;
17855
17856 kmem_cache_destroy(dtrace_state_cache);
17857 vmem_destroy(dtrace_arena);
17858
17859 if (dtrace_toxrange != NULL) {
17860 kmem_free(dtrace_toxrange,
17861 dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17862 dtrace_toxrange = NULL;
17863 dtrace_toxranges = 0;
17864 dtrace_toxranges_max = 0;
17865 }
17866
17867 ddi_remove_minor_node(dtrace_devi, NULL);
17868 dtrace_devi = NULL;
17869
17870 ddi_soft_state_fini(&dtrace_softstate);
17871
17872 ASSERT(dtrace_vtime_references == 0);
17873 ASSERT(dtrace_opens == 0);
17874 ASSERT(dtrace_retained == NULL);
17875
17876 lck_mtx_unlock(&dtrace_lock);
17877 lck_mtx_unlock(&dtrace_provider_lock);
17878
17879 /*
17880 * We don't destroy the task queue until after we have dropped our
17881 * locks (taskq_destroy() may block on running tasks). To prevent
17882 * attempting to do work after we have effectively detached but before
17883 * the task queue has been destroyed, all tasks dispatched via the
17884 * task queue must check that DTrace is still attached before
17885 * performing any operation.
17886 */
17887 taskq_destroy(dtrace_taskq);
17888 dtrace_taskq = NULL;
17889
17890 return (DDI_SUCCESS);
17891 }
17892 #endif /* __APPLE__ */
17893
17894 d_open_t _dtrace_open, helper_open;
17895 d_close_t _dtrace_close, helper_close;
17896 d_ioctl_t _dtrace_ioctl, helper_ioctl;
17897
17898 int
17899 _dtrace_open(dev_t dev, int flags, int devtype, struct proc *p)
17900 {
17901 #pragma unused(p)
17902 dev_t locdev = dev;
17903
17904 return dtrace_open( &locdev, flags, devtype, CRED());
17905 }
17906
17907 int
17908 helper_open(dev_t dev, int flags, int devtype, struct proc *p)
17909 {
17910 #pragma unused(dev,flags,devtype,p)
17911 return 0;
17912 }
17913
17914 int
17915 _dtrace_close(dev_t dev, int flags, int devtype, struct proc *p)
17916 {
17917 #pragma unused(p)
17918 return dtrace_close( dev, flags, devtype, CRED());
17919 }
17920
17921 int
17922 helper_close(dev_t dev, int flags, int devtype, struct proc *p)
17923 {
17924 #pragma unused(dev,flags,devtype,p)
17925 return 0;
17926 }
17927
17928 int
17929 _dtrace_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
17930 {
17931 #pragma unused(p)
17932 int err, rv = 0;
17933 user_addr_t uaddrp;
17934
17935 if (proc_is64bit(p))
17936 uaddrp = *(user_addr_t *)data;
17937 else
17938 uaddrp = (user_addr_t) *(uint32_t *)data;
17939
17940 err = dtrace_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
17941
17942 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
17943 if (err != 0) {
17944 ASSERT( (err & 0xfffff000) == 0 );
17945 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
17946 } else if (rv != 0) {
17947 ASSERT( (rv & 0xfff00000) == 0 );
17948 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
17949 } else
17950 return 0;
17951 }
17952
17953 int
17954 helper_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
17955 {
17956 #pragma unused(dev,fflag,p)
17957 int err, rv = 0;
17958
17959 err = dtrace_ioctl_helper(cmd, data, &rv);
17960 /* Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
17961 if (err != 0) {
17962 ASSERT( (err & 0xfffff000) == 0 );
17963 return (err & 0xfff); /* ioctl will return -1 and will set errno to an error code < 4096 */
17964 } else if (rv != 0) {
17965 ASSERT( (rv & 0xfff00000) == 0 );
17966 return (((rv & 0xfffff) << 12)); /* ioctl will return -1 and will set errno to a value >= 4096 */
17967 } else
17968 return 0;
17969 }
17970
17971 #define HELPER_MAJOR -24 /* let the kernel pick the device number */
17972
17973 /*
17974 * A struct describing which functions will get invoked for certain
17975 * actions.
17976 */
17977 static struct cdevsw helper_cdevsw =
17978 {
17979 helper_open, /* open */
17980 helper_close, /* close */
17981 eno_rdwrt, /* read */
17982 eno_rdwrt, /* write */
17983 helper_ioctl, /* ioctl */
17984 (stop_fcn_t *)nulldev, /* stop */
17985 (reset_fcn_t *)nulldev, /* reset */
17986 NULL, /* tty's */
17987 eno_select, /* select */
17988 eno_mmap, /* mmap */
17989 eno_strat, /* strategy */
17990 eno_getc, /* getc */
17991 eno_putc, /* putc */
17992 0 /* type */
17993 };
17994
17995 static int helper_majdevno = 0;
17996
17997 static int gDTraceInited = 0;
17998
17999 void
18000 helper_init( void )
18001 {
18002 /*
18003 * Once the "helper" is initialized, it can take ioctl calls that use locks
18004 * and zones initialized in dtrace_init. Make certain dtrace_init was called
18005 * before us.
18006 */
18007
18008 if (!gDTraceInited) {
18009 panic("helper_init before dtrace_init\n");
18010 }
18011
18012 if (0 >= helper_majdevno)
18013 {
18014 helper_majdevno = cdevsw_add(HELPER_MAJOR, &helper_cdevsw);
18015
18016 if (helper_majdevno < 0) {
18017 printf("helper_init: failed to allocate a major number!\n");
18018 return;
18019 }
18020
18021 if (NULL == devfs_make_node( makedev(helper_majdevno, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
18022 DTRACEMNR_HELPER, 0 )) {
18023 printf("dtrace_init: failed to devfs_make_node for helper!\n");
18024 return;
18025 }
18026 } else
18027 panic("helper_init: called twice!\n");
18028 }
18029
18030 #undef HELPER_MAJOR
18031
18032 static int
18033 dtrace_clone_func(dev_t dev, int action)
18034 {
18035 #pragma unused(dev)
18036
18037 if (action == DEVFS_CLONE_ALLOC) {
18038 return dtrace_state_reserve();
18039 }
18040 else if (action == DEVFS_CLONE_FREE) {
18041 return 0;
18042 }
18043 else return -1;
18044 }
18045
18046 void dtrace_ast(void);
18047
18048 void
18049 dtrace_ast(void)
18050 {
18051 int i;
18052 uint32_t clients = atomic_and_32(&dtrace_wake_clients, 0);
18053 if (clients == 0)
18054 return;
18055 /**
18056 * We disable preemption here to be sure that we won't get
18057 * interrupted by a wakeup to a thread that is higher
18058 * priority than us, so that we do issue all wakeups
18059 */
18060 disable_preemption();
18061 for (i = 0; i < DTRACE_NCLIENTS; i++) {
18062 if (clients & (1 << i)) {
18063 dtrace_state_t *state = dtrace_state_get(i);
18064 if (state) {
18065 wakeup(state);
18066 }
18067
18068 }
18069 }
18070 enable_preemption();
18071 }
18072
18073
18074 #define DTRACE_MAJOR -24 /* let the kernel pick the device number */
18075
18076 static struct cdevsw dtrace_cdevsw =
18077 {
18078 _dtrace_open, /* open */
18079 _dtrace_close, /* close */
18080 eno_rdwrt, /* read */
18081 eno_rdwrt, /* write */
18082 _dtrace_ioctl, /* ioctl */
18083 (stop_fcn_t *)nulldev, /* stop */
18084 (reset_fcn_t *)nulldev, /* reset */
18085 NULL, /* tty's */
18086 eno_select, /* select */
18087 eno_mmap, /* mmap */
18088 eno_strat, /* strategy */
18089 eno_getc, /* getc */
18090 eno_putc, /* putc */
18091 0 /* type */
18092 };
18093
18094 lck_attr_t* dtrace_lck_attr;
18095 lck_grp_attr_t* dtrace_lck_grp_attr;
18096 lck_grp_t* dtrace_lck_grp;
18097
18098 static int gMajDevNo;
18099
18100 void
18101 dtrace_init( void )
18102 {
18103 if (0 == gDTraceInited) {
18104 int i, ncpu;
18105 size_t size = sizeof(dtrace_buffer_memory_maxsize);
18106
18107 /*
18108 * DTrace allocates buffers based on the maximum number
18109 * of enabled cpus. This call avoids any race when finding
18110 * that count.
18111 */
18112 ASSERT(dtrace_max_cpus == 0);
18113 ncpu = dtrace_max_cpus = ml_get_max_cpus();
18114
18115 /*
18116 * Retrieve the size of the physical memory in order to define
18117 * the state buffer memory maximal size. If we cannot retrieve
18118 * this value, we'll consider that we have 1Gb of memory per CPU, that's
18119 * still better than raising a kernel panic.
18120 */
18121 if (0 != kernel_sysctlbyname("hw.memsize", &dtrace_buffer_memory_maxsize,
18122 &size, NULL, 0))
18123 {
18124 dtrace_buffer_memory_maxsize = ncpu * 1024 * 1024 * 1024;
18125 printf("dtrace_init: failed to retrieve the hw.memsize, defaulted to %lld bytes\n",
18126 dtrace_buffer_memory_maxsize);
18127 }
18128
18129 /*
18130 * Finally, divide by three to prevent DTrace from eating too
18131 * much memory.
18132 */
18133 dtrace_buffer_memory_maxsize /= 3;
18134 ASSERT(dtrace_buffer_memory_maxsize > 0);
18135
18136 gMajDevNo = cdevsw_add(DTRACE_MAJOR, &dtrace_cdevsw);
18137
18138 if (gMajDevNo < 0) {
18139 printf("dtrace_init: failed to allocate a major number!\n");
18140 gDTraceInited = 0;
18141 return;
18142 }
18143
18144 if (NULL == devfs_make_node_clone( makedev(gMajDevNo, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666,
18145 dtrace_clone_func, DTRACEMNR_DTRACE, 0 )) {
18146 printf("dtrace_init: failed to devfs_make_node_clone for dtrace!\n");
18147 gDTraceInited = 0;
18148 return;
18149 }
18150
18151 #if defined(DTRACE_MEMORY_ZONES)
18152 /*
18153 * Initialize the dtrace kalloc-emulation zones.
18154 */
18155 dtrace_alloc_init();
18156 #endif /* DTRACE_MEMORY_ZONES */
18157
18158 /*
18159 * Allocate the dtrace_probe_t zone
18160 */
18161 dtrace_probe_t_zone = zinit(sizeof(dtrace_probe_t),
18162 1024 * sizeof(dtrace_probe_t),
18163 sizeof(dtrace_probe_t),
18164 "dtrace.dtrace_probe_t");
18165
18166 /*
18167 * Create the dtrace lock group and attrs.
18168 */
18169 dtrace_lck_attr = lck_attr_alloc_init();
18170 dtrace_lck_grp_attr= lck_grp_attr_alloc_init();
18171 dtrace_lck_grp = lck_grp_alloc_init("dtrace", dtrace_lck_grp_attr);
18172
18173 /*
18174 * We have to initialize all locks explicitly
18175 */
18176 lck_mtx_init(&dtrace_lock, dtrace_lck_grp, dtrace_lck_attr);
18177 lck_mtx_init(&dtrace_provider_lock, dtrace_lck_grp, dtrace_lck_attr);
18178 lck_mtx_init(&dtrace_meta_lock, dtrace_lck_grp, dtrace_lck_attr);
18179 lck_mtx_init(&dtrace_procwaitfor_lock, dtrace_lck_grp, dtrace_lck_attr);
18180 #if DEBUG
18181 lck_mtx_init(&dtrace_errlock, dtrace_lck_grp, dtrace_lck_attr);
18182 #endif
18183 lck_rw_init(&dtrace_dof_mode_lock, dtrace_lck_grp, dtrace_lck_attr);
18184
18185 /*
18186 * The cpu_core structure consists of per-CPU state available in any context.
18187 * On some architectures, this may mean that the page(s) containing the
18188 * NCPU-sized array of cpu_core structures must be locked in the TLB -- it
18189 * is up to the platform to assure that this is performed properly. Note that
18190 * the structure is sized to avoid false sharing.
18191 */
18192 lck_mtx_init(&cpu_lock, dtrace_lck_grp, dtrace_lck_attr);
18193 lck_mtx_init(&cyc_lock, dtrace_lck_grp, dtrace_lck_attr);
18194 lck_mtx_init(&mod_lock, dtrace_lck_grp, dtrace_lck_attr);
18195
18196 /*
18197 * Initialize the CPU offline/online hooks.
18198 */
18199 dtrace_install_cpu_hooks();
18200
18201 dtrace_modctl_list = NULL;
18202
18203 cpu_core = (cpu_core_t *)kmem_zalloc( ncpu * sizeof(cpu_core_t), KM_SLEEP );
18204 for (i = 0; i < ncpu; ++i) {
18205 lck_mtx_init(&cpu_core[i].cpuc_pid_lock, dtrace_lck_grp, dtrace_lck_attr);
18206 }
18207
18208 cpu_list = (dtrace_cpu_t *)kmem_zalloc( ncpu * sizeof(dtrace_cpu_t), KM_SLEEP );
18209 for (i = 0; i < ncpu; ++i) {
18210 cpu_list[i].cpu_id = (processorid_t)i;
18211 cpu_list[i].cpu_next = &(cpu_list[(i+1) % ncpu]);
18212 LIST_INIT(&cpu_list[i].cpu_cyc_list);
18213 lck_rw_init(&cpu_list[i].cpu_ft_lock, dtrace_lck_grp, dtrace_lck_attr);
18214 }
18215
18216 lck_mtx_lock(&cpu_lock);
18217 for (i = 0; i < ncpu; ++i)
18218 /* FIXME: track CPU configuration */
18219 dtrace_cpu_setup_initial( (processorid_t)i ); /* In lieu of register_cpu_setup_func() callback */
18220 lck_mtx_unlock(&cpu_lock);
18221
18222 (void)dtrace_abs_to_nano(0LL); /* Force once only call to clock_timebase_info (which can take a lock) */
18223
18224 dtrace_isa_init();
18225 /*
18226 * See dtrace_impl.h for a description of dof modes.
18227 * The default is lazy dof.
18228 *
18229 * FIXME: Warn if state is LAZY_OFF? It won't break anything, but
18230 * makes no sense...
18231 */
18232 if (!PE_parse_boot_argn("dtrace_dof_mode", &dtrace_dof_mode, sizeof (dtrace_dof_mode))) {
18233 dtrace_dof_mode = DTRACE_DOF_MODE_LAZY_ON;
18234 }
18235
18236 /*
18237 * Sanity check of dof mode value.
18238 */
18239 switch (dtrace_dof_mode) {
18240 case DTRACE_DOF_MODE_NEVER:
18241 case DTRACE_DOF_MODE_LAZY_ON:
18242 /* valid modes, but nothing else we need to do */
18243 break;
18244
18245 case DTRACE_DOF_MODE_LAZY_OFF:
18246 case DTRACE_DOF_MODE_NON_LAZY:
18247 /* Cannot wait for a dtrace_open to init fasttrap */
18248 fasttrap_init();
18249 break;
18250
18251 default:
18252 /* Invalid, clamp to non lazy */
18253 dtrace_dof_mode = DTRACE_DOF_MODE_NON_LAZY;
18254 fasttrap_init();
18255 break;
18256 }
18257
18258 /*
18259 * See dtrace_impl.h for a description of kernel symbol modes.
18260 * The default is to wait for symbols from userspace (lazy symbols).
18261 */
18262 if (!PE_parse_boot_argn("dtrace_kernel_symbol_mode", &dtrace_kernel_symbol_mode, sizeof (dtrace_kernel_symbol_mode))) {
18263 dtrace_kernel_symbol_mode = DTRACE_KERNEL_SYMBOLS_FROM_USERSPACE;
18264 }
18265
18266 dtrace_restriction_policy_load();
18267
18268 gDTraceInited = 1;
18269
18270 } else
18271 panic("dtrace_init: called twice!\n");
18272 }
18273
18274 void
18275 dtrace_postinit(void)
18276 {
18277 /*
18278 * Called from bsd_init after all provider's *_init() routines have been
18279 * run. That way, anonymous DOF enabled under dtrace_attach() is safe
18280 * to go.
18281 */
18282 dtrace_attach( (dev_info_t *)(uintptr_t)makedev(gMajDevNo, 0), 0 ); /* Punning a dev_t to a dev_info_t* */
18283
18284 /*
18285 * Add the mach_kernel to the module list for lazy processing
18286 */
18287 struct kmod_info fake_kernel_kmod;
18288 memset(&fake_kernel_kmod, 0, sizeof(fake_kernel_kmod));
18289
18290 strlcpy(fake_kernel_kmod.name, "mach_kernel", sizeof(fake_kernel_kmod.name));
18291 fake_kernel_kmod.id = 1;
18292 fake_kernel_kmod.address = g_kernel_kmod_info.address;
18293 fake_kernel_kmod.size = g_kernel_kmod_info.size;
18294
18295 if (dtrace_module_loaded(&fake_kernel_kmod, 0) != 0) {
18296 printf("dtrace_postinit: Could not register mach_kernel modctl\n");
18297 }
18298
18299 (void)OSKextRegisterKextsWithDTrace();
18300 }
18301 #undef DTRACE_MAJOR
18302
18303 /*
18304 * Routines used to register interest in cpu's being added to or removed
18305 * from the system.
18306 */
18307 void
18308 register_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
18309 {
18310 #pragma unused(ignore1,ignore2)
18311 }
18312
18313 void
18314 unregister_cpu_setup_func(cpu_setup_func_t *ignore1, void *ignore2)
18315 {
18316 #pragma unused(ignore1,ignore2)
18317 }