]> git.saurik.com Git - apple/xnu.git/blob - bsd/dev/dtrace/fasttrap.c
xnu-4570.1.46.tar.gz
[apple/xnu.git] / bsd / dev / dtrace / fasttrap.c
1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
23 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
25 */
26
27 /*
28 * #pragma ident "@(#)fasttrap.c 1.26 08/04/21 SMI"
29 */
30
31 #include <sys/types.h>
32 #include <sys/time.h>
33
34 #include <sys/codesign.h>
35 #include <sys/errno.h>
36 #include <sys/stat.h>
37 #include <sys/conf.h>
38 #include <sys/systm.h>
39 #include <sys/kauth.h>
40 #include <sys/utfconv.h>
41
42 #include <sys/fasttrap.h>
43 #include <sys/fasttrap_impl.h>
44 #include <sys/fasttrap_isa.h>
45 #include <sys/dtrace.h>
46 #include <sys/dtrace_impl.h>
47 #include <sys/proc.h>
48
49 #include <miscfs/devfs/devfs.h>
50 #include <sys/proc_internal.h>
51 #include <sys/dtrace_glue.h>
52 #include <sys/dtrace_ptss.h>
53
54 #include <kern/cs_blobs.h>
55 #include <kern/thread.h>
56 #include <kern/zalloc.h>
57
58 #include <mach/thread_act.h>
59
60 extern kern_return_t kernel_thread_start_priority(thread_continue_t continuation, void *parameter, integer_t priority, thread_t *new_thread);
61
62 /* Solaris proc_t is the struct. Darwin's proc_t is a pointer to it. */
63 #define proc_t struct proc /* Steer clear of the Darwin typedef for proc_t */
64
65 __private_extern__
66 void
67 qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *));
68
69 /*
70 * User-Land Trap-Based Tracing
71 * ----------------------------
72 *
73 * The fasttrap provider allows DTrace consumers to instrument any user-level
74 * instruction to gather data; this includes probes with semantic
75 * signifigance like entry and return as well as simple offsets into the
76 * function. While the specific techniques used are very ISA specific, the
77 * methodology is generalizable to any architecture.
78 *
79 *
80 * The General Methodology
81 * -----------------------
82 *
83 * With the primary goal of tracing every user-land instruction and the
84 * limitation that we can't trust user space so don't want to rely on much
85 * information there, we begin by replacing the instructions we want to trace
86 * with trap instructions. Each instruction we overwrite is saved into a hash
87 * table keyed by process ID and pc address. When we enter the kernel due to
88 * this trap instruction, we need the effects of the replaced instruction to
89 * appear to have occurred before we proceed with the user thread's
90 * execution.
91 *
92 * Each user level thread is represented by a ulwp_t structure which is
93 * always easily accessible through a register. The most basic way to produce
94 * the effects of the instruction we replaced is to copy that instruction out
95 * to a bit of scratch space reserved in the user thread's ulwp_t structure
96 * (a sort of kernel-private thread local storage), set the PC to that
97 * scratch space and single step. When we reenter the kernel after single
98 * stepping the instruction we must then adjust the PC to point to what would
99 * normally be the next instruction. Of course, special care must be taken
100 * for branches and jumps, but these represent such a small fraction of any
101 * instruction set that writing the code to emulate these in the kernel is
102 * not too difficult.
103 *
104 * Return probes may require several tracepoints to trace every return site,
105 * and, conversely, each tracepoint may activate several probes (the entry
106 * and offset 0 probes, for example). To solve this muliplexing problem,
107 * tracepoints contain lists of probes to activate and probes contain lists
108 * of tracepoints to enable. If a probe is activated, it adds its ID to
109 * existing tracepoints or creates new ones as necessary.
110 *
111 * Most probes are activated _before_ the instruction is executed, but return
112 * probes are activated _after_ the effects of the last instruction of the
113 * function are visible. Return probes must be fired _after_ we have
114 * single-stepped the instruction whereas all other probes are fired
115 * beforehand.
116 *
117 *
118 * Lock Ordering
119 * -------------
120 *
121 * The lock ordering below -- both internally and with respect to the DTrace
122 * framework -- is a little tricky and bears some explanation. Each provider
123 * has a lock (ftp_mtx) that protects its members including reference counts
124 * for enabled probes (ftp_rcount), consumers actively creating probes
125 * (ftp_ccount) and USDT consumers (ftp_mcount); all three prevent a provider
126 * from being freed. A provider is looked up by taking the bucket lock for the
127 * provider hash table, and is returned with its lock held. The provider lock
128 * may be taken in functions invoked by the DTrace framework, but may not be
129 * held while calling functions in the DTrace framework.
130 *
131 * To ensure consistency over multiple calls to the DTrace framework, the
132 * creation lock (ftp_cmtx) should be held. Naturally, the creation lock may
133 * not be taken when holding the provider lock as that would create a cyclic
134 * lock ordering. In situations where one would naturally take the provider
135 * lock and then the creation lock, we instead up a reference count to prevent
136 * the provider from disappearing, drop the provider lock, and acquire the
137 * creation lock.
138 *
139 * Briefly:
140 * bucket lock before provider lock
141 * DTrace before provider lock
142 * creation lock before DTrace
143 * never hold the provider lock and creation lock simultaneously
144 */
145
146 static dev_info_t *fasttrap_devi;
147 static dtrace_meta_provider_id_t fasttrap_meta_id;
148
149 static thread_t fasttrap_cleanup_thread;
150
151 static lck_mtx_t fasttrap_cleanup_mtx;
152
153
154 #define FASTTRAP_CLEANUP_PROVIDER 0x1
155 #define FASTTRAP_CLEANUP_TRACEPOINT 0x2
156
157 static uint32_t fasttrap_cleanup_work = 0;
158
159 /*
160 * Generation count on modifications to the global tracepoint lookup table.
161 */
162 static volatile uint64_t fasttrap_mod_gen;
163
164 /*
165 * APPLE NOTE: When the fasttrap provider is loaded, fasttrap_max is computed
166 * base on system memory. Each time a probe is created, fasttrap_total is
167 * incremented by the number of tracepoints that may be associated with that
168 * probe; fasttrap_total is capped at fasttrap_max.
169 */
170
171 static uint32_t fasttrap_max;
172 static uint32_t fasttrap_retired;
173 static uint32_t fasttrap_total;
174
175
176 #define FASTTRAP_TPOINTS_DEFAULT_SIZE 0x4000
177 #define FASTTRAP_PROVIDERS_DEFAULT_SIZE 0x100
178 #define FASTTRAP_PROCS_DEFAULT_SIZE 0x100
179
180 fasttrap_hash_t fasttrap_tpoints;
181 static fasttrap_hash_t fasttrap_provs;
182 static fasttrap_hash_t fasttrap_procs;
183
184 static uint64_t fasttrap_pid_count; /* pid ref count */
185 static lck_mtx_t fasttrap_count_mtx; /* lock on ref count */
186
187 #define FASTTRAP_ENABLE_FAIL 1
188 #define FASTTRAP_ENABLE_PARTIAL 2
189
190 static int fasttrap_tracepoint_enable(proc_t *, fasttrap_probe_t *, uint_t);
191 static void fasttrap_tracepoint_disable(proc_t *, fasttrap_probe_t *, uint_t);
192
193 static fasttrap_provider_t *fasttrap_provider_lookup(proc_t*, fasttrap_provider_type_t, const char *,
194 const dtrace_pattr_t *);
195 static void fasttrap_provider_retire(proc_t*, const char *, int);
196 static void fasttrap_provider_free(fasttrap_provider_t *);
197
198 static fasttrap_proc_t *fasttrap_proc_lookup(pid_t);
199 static void fasttrap_proc_release(fasttrap_proc_t *);
200
201 #define FASTTRAP_PROVS_INDEX(pid, name) \
202 ((fasttrap_hash_str(name) + (pid)) & fasttrap_provs.fth_mask)
203
204 #define FASTTRAP_PROCS_INDEX(pid) ((pid) & fasttrap_procs.fth_mask)
205
206 /*
207 * APPLE NOTE: To save memory, some common memory allocations are given
208 * a unique zone. For example, dtrace_probe_t is 72 bytes in size,
209 * which means it would fall into the kalloc.128 bucket. With
210 * 20k elements allocated, the space saved is substantial.
211 */
212
213 struct zone *fasttrap_tracepoint_t_zone;
214
215 /*
216 * APPLE NOTE: fasttrap_probe_t's are variable in size. Some quick profiling has shown
217 * that the sweet spot for reducing memory footprint is covering the first
218 * three sizes. Everything larger goes into the common pool.
219 */
220 #define FASTTRAP_PROBE_T_ZONE_MAX_TRACEPOINTS 4
221
222 struct zone *fasttrap_probe_t_zones[FASTTRAP_PROBE_T_ZONE_MAX_TRACEPOINTS];
223
224 static const char *fasttrap_probe_t_zone_names[FASTTRAP_PROBE_T_ZONE_MAX_TRACEPOINTS] = {
225 "",
226 "dtrace.fasttrap_probe_t[1]",
227 "dtrace.fasttrap_probe_t[2]",
228 "dtrace.fasttrap_probe_t[3]"
229 };
230
231 /*
232 * APPLE NOTE: We have to manage locks explicitly
233 */
234 lck_grp_t* fasttrap_lck_grp;
235 lck_grp_attr_t* fasttrap_lck_grp_attr;
236 lck_attr_t* fasttrap_lck_attr;
237
238 static int
239 fasttrap_highbit(ulong_t i)
240 {
241 int h = 1;
242
243 if (i == 0)
244 return (0);
245 #ifdef _LP64
246 if (i & 0xffffffff00000000ul) {
247 h += 32; i >>= 32;
248 }
249 #endif
250 if (i & 0xffff0000) {
251 h += 16; i >>= 16;
252 }
253 if (i & 0xff00) {
254 h += 8; i >>= 8;
255 }
256 if (i & 0xf0) {
257 h += 4; i >>= 4;
258 }
259 if (i & 0xc) {
260 h += 2; i >>= 2;
261 }
262 if (i & 0x2) {
263 h += 1;
264 }
265 return (h);
266 }
267
268 static uint_t
269 fasttrap_hash_str(const char *p)
270 {
271 unsigned int g;
272 uint_t hval = 0;
273
274 while (*p) {
275 hval = (hval << 4) + *p++;
276 if ((g = (hval & 0xf0000000)) != 0)
277 hval ^= g >> 24;
278 hval &= ~g;
279 }
280 return (hval);
281 }
282
283 /*
284 * APPLE NOTE: fasttrap_sigtrap not implemented
285 */
286 void
287 fasttrap_sigtrap(proc_t *p, uthread_t t, user_addr_t pc)
288 {
289 #pragma unused(p, t, pc)
290
291 #if !defined(__APPLE__)
292 sigqueue_t *sqp = kmem_zalloc(sizeof (sigqueue_t), KM_SLEEP);
293
294 sqp->sq_info.si_signo = SIGTRAP;
295 sqp->sq_info.si_code = TRAP_DTRACE;
296 sqp->sq_info.si_addr = (caddr_t)pc;
297
298 mutex_enter(&p->p_lock);
299 sigaddqa(p, t, sqp);
300 mutex_exit(&p->p_lock);
301
302 if (t != NULL)
303 aston(t);
304 #endif /* __APPLE__ */
305
306 printf("fasttrap_sigtrap called with no implementation.\n");
307 }
308
309 /*
310 * This function ensures that no threads are actively using the memory
311 * associated with probes that were formerly live.
312 */
313 static void
314 fasttrap_mod_barrier(uint64_t gen)
315 {
316 unsigned int i;
317
318 if (gen < fasttrap_mod_gen)
319 return;
320
321 fasttrap_mod_gen++;
322
323 for (i = 0; i < NCPU; i++) {
324 lck_mtx_lock(&cpu_core[i].cpuc_pid_lock);
325 lck_mtx_unlock(&cpu_core[i].cpuc_pid_lock);
326 }
327 }
328
329 static void fasttrap_pid_cleanup(uint32_t);
330
331 static unsigned int
332 fasttrap_pid_cleanup_providers(void)
333 {
334 fasttrap_provider_t **fpp, *fp;
335 fasttrap_bucket_t *bucket;
336 dtrace_provider_id_t provid;
337 unsigned int later = 0, i;
338
339 /*
340 * Iterate over all the providers trying to remove the marked
341 * ones. If a provider is marked but not retired, we just
342 * have to take a crack at removing it -- it's no big deal if
343 * we can't.
344 */
345 for (i = 0; i < fasttrap_provs.fth_nent; i++) {
346 bucket = &fasttrap_provs.fth_table[i];
347 lck_mtx_lock(&bucket->ftb_mtx);
348 fpp = (fasttrap_provider_t **)&bucket->ftb_data;
349
350 while ((fp = *fpp) != NULL) {
351 if (!fp->ftp_marked) {
352 fpp = &fp->ftp_next;
353 continue;
354 }
355
356 lck_mtx_lock(&fp->ftp_mtx);
357
358 /*
359 * If this provider has consumers actively
360 * creating probes (ftp_ccount) or is a USDT
361 * provider (ftp_mcount), we can't unregister
362 * or even condense.
363 */
364 if (fp->ftp_ccount != 0 ||
365 fp->ftp_mcount != 0) {
366 fp->ftp_marked = 0;
367 lck_mtx_unlock(&fp->ftp_mtx);
368 continue;
369 }
370
371 if (!fp->ftp_retired || fp->ftp_rcount != 0)
372 fp->ftp_marked = 0;
373
374 lck_mtx_unlock(&fp->ftp_mtx);
375
376 /*
377 * If we successfully unregister this
378 * provider we can remove it from the hash
379 * chain and free the memory. If our attempt
380 * to unregister fails and this is a retired
381 * provider, increment our flag to try again
382 * pretty soon. If we've consumed more than
383 * half of our total permitted number of
384 * probes call dtrace_condense() to try to
385 * clean out the unenabled probes.
386 */
387 provid = fp->ftp_provid;
388 if (dtrace_unregister(provid) != 0) {
389 if (fasttrap_total > fasttrap_max / 2)
390 (void) dtrace_condense(provid);
391 later += fp->ftp_marked;
392 fpp = &fp->ftp_next;
393 } else {
394 *fpp = fp->ftp_next;
395 fasttrap_provider_free(fp);
396 }
397 }
398 lck_mtx_unlock(&bucket->ftb_mtx);
399 }
400
401 return later;
402 }
403
404 #ifdef FASTTRAP_ASYNC_REMOVE
405 typedef struct fasttrap_tracepoint_spec {
406 pid_t fttps_pid;
407 user_addr_t fttps_pc;
408 } fasttrap_tracepoint_spec_t;
409
410 static fasttrap_tracepoint_spec_t *fasttrap_retired_spec;
411 static size_t fasttrap_cur_retired = 0, fasttrap_retired_size;
412 static lck_mtx_t fasttrap_retired_mtx;
413
414 #define DEFAULT_RETIRED_SIZE 256
415
416 static void
417 fasttrap_tracepoint_cleanup(void)
418 {
419 size_t i;
420 pid_t pid = 0;
421 user_addr_t pc;
422 proc_t *p = PROC_NULL;
423 fasttrap_tracepoint_t *tp = NULL;
424 lck_mtx_lock(&fasttrap_retired_mtx);
425 fasttrap_bucket_t *bucket;
426 for (i = 0; i < fasttrap_cur_retired; i++) {
427 pc = fasttrap_retired_spec[i].fttps_pc;
428 if (fasttrap_retired_spec[i].fttps_pid != pid) {
429 pid = fasttrap_retired_spec[i].fttps_pid;
430 if (p != PROC_NULL) {
431 sprunlock(p);
432 }
433 if ((p = sprlock(pid)) == PROC_NULL) {
434 pid = 0;
435 continue;
436 }
437 }
438 bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
439 lck_mtx_lock(&bucket->ftb_mtx);
440 for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
441 if (pid == tp->ftt_pid && pc == tp->ftt_pc &&
442 tp->ftt_proc->ftpc_acount != 0)
443 break;
444 }
445 /*
446 * Check that the tracepoint is not gone or has not been
447 * re-activated for another probe
448 */
449 if (tp == NULL || tp->ftt_retired == 0) {
450 lck_mtx_unlock(&bucket->ftb_mtx);
451 continue;
452 }
453 fasttrap_tracepoint_remove(p, tp);
454 lck_mtx_unlock(&bucket->ftb_mtx);
455 }
456 if (p != PROC_NULL) {
457 sprunlock(p);
458 }
459
460 fasttrap_cur_retired = 0;
461
462 lck_mtx_unlock(&fasttrap_retired_mtx);
463 }
464
465 void
466 fasttrap_tracepoint_retire(proc_t *p, fasttrap_tracepoint_t *tp)
467 {
468 if (tp->ftt_retired)
469 return;
470 lck_mtx_lock(&fasttrap_retired_mtx);
471 fasttrap_tracepoint_spec_t *s = &fasttrap_retired_spec[fasttrap_cur_retired++];
472 s->fttps_pid = p->p_pid;
473 s->fttps_pc = tp->ftt_pc;
474
475 if (fasttrap_cur_retired == fasttrap_retired_size) {
476 fasttrap_retired_size *= 2;
477 fasttrap_tracepoint_spec_t *new_retired = kmem_zalloc(
478 fasttrap_retired_size *
479 sizeof(fasttrap_tracepoint_t*),
480 KM_SLEEP);
481 memcpy(new_retired, fasttrap_retired_spec, sizeof(fasttrap_tracepoint_t*) * fasttrap_retired_size);
482 kmem_free(fasttrap_retired_spec, sizeof(fasttrap_tracepoint_t*) * (fasttrap_retired_size / 2));
483 fasttrap_retired_spec = new_retired;
484 }
485
486 lck_mtx_unlock(&fasttrap_retired_mtx);
487
488 tp->ftt_retired = 1;
489
490 fasttrap_pid_cleanup(FASTTRAP_CLEANUP_TRACEPOINT);
491 }
492 #else
493 void fasttrap_tracepoint_retire(proc_t *p, fasttrap_tracepoint_t *tp)
494 {
495 if (tp->ftt_retired)
496 return;
497
498 fasttrap_tracepoint_remove(p, tp);
499 }
500 #endif
501
502 static void
503 fasttrap_pid_cleanup_compute_priority(void)
504 {
505 if (fasttrap_total > (fasttrap_max / 100 * 90) || fasttrap_retired > fasttrap_max / 2) {
506 thread_precedence_policy_data_t precedence = {12 /* BASEPRI_PREEMPT_HIGH */};
507 thread_policy_set(fasttrap_cleanup_thread, THREAD_PRECEDENCE_POLICY, (thread_policy_t) &precedence, THREAD_PRECEDENCE_POLICY_COUNT);
508 }
509 else {
510 thread_precedence_policy_data_t precedence = {-39 /* BASEPRI_USER_INITIATED */};
511 thread_policy_set(fasttrap_cleanup_thread, THREAD_PRECEDENCE_POLICY, (thread_policy_t) &precedence, THREAD_PRECEDENCE_POLICY_COUNT);
512
513 }
514 }
515
516 /*
517 * This is the timeout's callback for cleaning up the providers and their
518 * probes.
519 */
520 /*ARGSUSED*/
521 __attribute__((noreturn))
522 static void
523 fasttrap_pid_cleanup_cb(void)
524 {
525 uint32_t work = 0;
526 lck_mtx_lock(&fasttrap_cleanup_mtx);
527 msleep(&fasttrap_pid_cleanup_cb, &fasttrap_cleanup_mtx, PRIBIO, "fasttrap_pid_cleanup_cb", NULL);
528 while (1) {
529 unsigned int later = 0;
530
531 work = atomic_and_32(&fasttrap_cleanup_work, 0);
532 lck_mtx_unlock(&fasttrap_cleanup_mtx);
533 if (work & FASTTRAP_CLEANUP_PROVIDER) {
534 later = fasttrap_pid_cleanup_providers();
535 }
536 #ifdef FASTTRAP_ASYNC_REMOVE
537 if (work & FASTTRAP_CLEANUP_TRACEPOINT) {
538 fasttrap_tracepoint_cleanup();
539 }
540 #endif
541 lck_mtx_lock(&fasttrap_cleanup_mtx);
542
543 fasttrap_pid_cleanup_compute_priority();
544 if (!fasttrap_cleanup_work) {
545 /*
546 * If we were unable to remove a retired provider, try again after
547 * a second. This situation can occur in certain circumstances where
548 * providers cannot be unregistered even though they have no probes
549 * enabled because of an execution of dtrace -l or something similar.
550 * If the timeout has been disabled (set to 1 because we're trying
551 * to detach), we set fasttrap_cleanup_work to ensure that we'll
552 * get a chance to do that work if and when the timeout is reenabled
553 * (if detach fails).
554 */
555 if (later > 0) {
556 struct timespec t = {1, 0};
557 msleep(&fasttrap_pid_cleanup_cb, &fasttrap_cleanup_mtx, PRIBIO, "fasttrap_pid_cleanup_cb", &t);
558 }
559 else
560 msleep(&fasttrap_pid_cleanup_cb, &fasttrap_cleanup_mtx, PRIBIO, "fasttrap_pid_cleanup_cb", NULL);
561 }
562 }
563
564 }
565
566 /*
567 * Activates the asynchronous cleanup mechanism.
568 */
569 static void
570 fasttrap_pid_cleanup(uint32_t work)
571 {
572 lck_mtx_lock(&fasttrap_cleanup_mtx);
573 atomic_or_32(&fasttrap_cleanup_work, work);
574 fasttrap_pid_cleanup_compute_priority();
575 wakeup(&fasttrap_pid_cleanup_cb);
576 lck_mtx_unlock(&fasttrap_cleanup_mtx);
577 }
578
579
580 /*
581 * This is called from cfork() via dtrace_fasttrap_fork(). The child
582 * process's address space is a (roughly) a copy of the parent process's so
583 * we have to remove all the instrumentation we had previously enabled in the
584 * parent.
585 */
586 static void
587 fasttrap_fork(proc_t *p, proc_t *cp)
588 {
589 pid_t ppid = p->p_pid;
590 unsigned int i;
591
592 ASSERT(current_proc() == p);
593 LCK_MTX_ASSERT(&p->p_dtrace_sprlock, LCK_MTX_ASSERT_OWNED);
594 ASSERT(p->p_dtrace_count > 0);
595 ASSERT(cp->p_dtrace_count == 0);
596
597 /*
598 * This would be simpler and faster if we maintained per-process
599 * hash tables of enabled tracepoints. It could, however, potentially
600 * slow down execution of a tracepoint since we'd need to go
601 * through two levels of indirection. In the future, we should
602 * consider either maintaining per-process ancillary lists of
603 * enabled tracepoints or hanging a pointer to a per-process hash
604 * table of enabled tracepoints off the proc structure.
605 */
606
607 /*
608 * We don't have to worry about the child process disappearing
609 * because we're in fork().
610 */
611 if (cp != sprlock(cp->p_pid)) {
612 printf("fasttrap_fork: sprlock(%d) returned a different proc\n", cp->p_pid);
613 return;
614 }
615 proc_unlock(cp);
616
617 /*
618 * Iterate over every tracepoint looking for ones that belong to the
619 * parent process, and remove each from the child process.
620 */
621 for (i = 0; i < fasttrap_tpoints.fth_nent; i++) {
622 fasttrap_tracepoint_t *tp;
623 fasttrap_bucket_t *bucket = &fasttrap_tpoints.fth_table[i];
624
625 lck_mtx_lock(&bucket->ftb_mtx);
626 for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
627 if (tp->ftt_pid == ppid &&
628 tp->ftt_proc->ftpc_acount != 0) {
629 fasttrap_tracepoint_remove(cp, tp);
630
631 /*
632 * The count of active providers can only be
633 * decremented (i.e. to zero) during exec,
634 * exit, and removal of a meta provider so it
635 * should be impossible to drop the count
636 * mid-fork.
637 */
638 ASSERT(tp->ftt_proc->ftpc_acount != 0);
639 }
640 }
641 lck_mtx_unlock(&bucket->ftb_mtx);
642 }
643
644 /*
645 * Free any ptss pages/entries in the child.
646 */
647 dtrace_ptss_fork(p, cp);
648
649 proc_lock(cp);
650 sprunlock(cp);
651 }
652
653 /*
654 * This is called from proc_exit() or from exec_common() if p_dtrace_probes
655 * is set on the proc structure to indicate that there is a pid provider
656 * associated with this process.
657 */
658 static void
659 fasttrap_exec_exit(proc_t *p)
660 {
661 ASSERT(p == current_proc());
662 LCK_MTX_ASSERT(&p->p_mlock, LCK_MTX_ASSERT_OWNED);
663 LCK_MTX_ASSERT(&p->p_dtrace_sprlock, LCK_MTX_ASSERT_NOTOWNED);
664
665
666 /* APPLE NOTE: Okay, the locking here is really odd and needs some
667 * explaining. This method is always called with the proc_lock held.
668 * We must drop the proc_lock before calling fasttrap_provider_retire
669 * to avoid a deadlock when it takes the bucket lock.
670 *
671 * Next, the dtrace_ptss_exec_exit function requires the sprlock
672 * be held, but not the proc_lock.
673 *
674 * Finally, we must re-acquire the proc_lock
675 */
676 proc_unlock(p);
677
678 /*
679 * We clean up the pid provider for this process here; user-land
680 * static probes are handled by the meta-provider remove entry point.
681 */
682 fasttrap_provider_retire(p, FASTTRAP_PID_NAME, 0);
683
684 /*
685 * APPLE NOTE: We also need to remove any aliased providers.
686 * XXX optimization: track which provider types are instantiated
687 * and only retire as needed.
688 */
689 fasttrap_provider_retire(p, FASTTRAP_OBJC_NAME, 0);
690 fasttrap_provider_retire(p, FASTTRAP_ONESHOT_NAME, 0);
691
692 /*
693 * This should be called after it is no longer possible for a user
694 * thread to execute (potentially dtrace instrumented) instructions.
695 */
696 lck_mtx_lock(&p->p_dtrace_sprlock);
697 dtrace_ptss_exec_exit(p);
698 lck_mtx_unlock(&p->p_dtrace_sprlock);
699
700 proc_lock(p);
701 }
702
703
704 /*ARGSUSED*/
705 static void
706 fasttrap_pid_provide(void *arg, const dtrace_probedesc_t *desc)
707 {
708 #pragma unused(arg, desc)
709 /*
710 * There are no "default" pid probes.
711 */
712 }
713
714 static int
715 fasttrap_tracepoint_enable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
716 {
717 fasttrap_tracepoint_t *tp, *new_tp = NULL;
718 fasttrap_bucket_t *bucket;
719 fasttrap_id_t *id;
720 pid_t pid;
721 user_addr_t pc;
722
723 ASSERT(index < probe->ftp_ntps);
724
725 pid = probe->ftp_pid;
726 pc = probe->ftp_tps[index].fit_tp->ftt_pc;
727 id = &probe->ftp_tps[index].fit_id;
728
729 ASSERT(probe->ftp_tps[index].fit_tp->ftt_pid == pid);
730
731 //ASSERT(!(p->p_flag & SVFORK));
732
733 /*
734 * Before we make any modifications, make sure we've imposed a barrier
735 * on the generation in which this probe was last modified.
736 */
737 fasttrap_mod_barrier(probe->ftp_gen);
738
739 bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
740
741 /*
742 * If the tracepoint has already been enabled, just add our id to the
743 * list of interested probes. This may be our second time through
744 * this path in which case we'll have constructed the tracepoint we'd
745 * like to install. If we can't find a match, and have an allocated
746 * tracepoint ready to go, enable that one now.
747 *
748 * A tracepoint whose process is defunct is also considered defunct.
749 */
750 again:
751 lck_mtx_lock(&bucket->ftb_mtx);
752 for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
753 int rc = 0;
754 /*
755 * Note that it's safe to access the active count on the
756 * associated proc structure because we know that at least one
757 * provider (this one) will still be around throughout this
758 * operation.
759 */
760 if (tp->ftt_pid != pid || tp->ftt_pc != pc ||
761 tp->ftt_proc->ftpc_acount == 0)
762 continue;
763
764 /*
765 * Now that we've found a matching tracepoint, it would be
766 * a decent idea to confirm that the tracepoint is still
767 * enabled and the trap instruction hasn't been overwritten.
768 * Since this is a little hairy, we'll punt for now.
769 */
770 if (!tp->ftt_installed) {
771 if (fasttrap_tracepoint_install(p, tp) != 0)
772 rc = FASTTRAP_ENABLE_PARTIAL;
773 }
774 /*
775 * This can't be the first interested probe. We don't have
776 * to worry about another thread being in the midst of
777 * deleting this tracepoint (which would be the only valid
778 * reason for a tracepoint to have no interested probes)
779 * since we're holding P_PR_LOCK for this process.
780 */
781 ASSERT(tp->ftt_ids != NULL || tp->ftt_retids != NULL);
782
783 switch (id->fti_ptype) {
784 case DTFTP_ENTRY:
785 case DTFTP_OFFSETS:
786 case DTFTP_IS_ENABLED:
787 id->fti_next = tp->ftt_ids;
788 dtrace_membar_producer();
789 tp->ftt_ids = id;
790 dtrace_membar_producer();
791 break;
792
793 case DTFTP_RETURN:
794 case DTFTP_POST_OFFSETS:
795 id->fti_next = tp->ftt_retids;
796 dtrace_membar_producer();
797 tp->ftt_retids = id;
798 dtrace_membar_producer();
799 break;
800
801 default:
802 ASSERT(0);
803 }
804
805 tp->ftt_retired = 0;
806
807 lck_mtx_unlock(&bucket->ftb_mtx);
808
809 if (new_tp != NULL) {
810 new_tp->ftt_ids = NULL;
811 new_tp->ftt_retids = NULL;
812 }
813
814 return rc;
815 }
816
817 /*
818 * If we have a good tracepoint ready to go, install it now while
819 * we have the lock held and no one can screw with us.
820 */
821 if (new_tp != NULL) {
822 int rc = 0;
823
824 new_tp->ftt_next = bucket->ftb_data;
825 dtrace_membar_producer();
826 bucket->ftb_data = new_tp;
827 dtrace_membar_producer();
828 lck_mtx_unlock(&bucket->ftb_mtx);
829
830 /*
831 * Activate the tracepoint in the ISA-specific manner.
832 * If this fails, we need to report the failure, but
833 * indicate that this tracepoint must still be disabled
834 * by calling fasttrap_tracepoint_disable().
835 */
836 if (fasttrap_tracepoint_install(p, new_tp) != 0)
837 rc = FASTTRAP_ENABLE_PARTIAL;
838 /*
839 * Increment the count of the number of tracepoints active in
840 * the victim process.
841 */
842 //ASSERT(p->p_proc_flag & P_PR_LOCK);
843 p->p_dtrace_count++;
844
845
846 return (rc);
847 }
848
849 lck_mtx_unlock(&bucket->ftb_mtx);
850
851 /*
852 * Initialize the tracepoint that's been preallocated with the probe.
853 */
854 new_tp = probe->ftp_tps[index].fit_tp;
855 new_tp->ftt_retired = 0;
856
857 ASSERT(new_tp->ftt_pid == pid);
858 ASSERT(new_tp->ftt_pc == pc);
859 ASSERT(new_tp->ftt_proc == probe->ftp_prov->ftp_proc);
860 ASSERT(new_tp->ftt_ids == NULL);
861 ASSERT(new_tp->ftt_retids == NULL);
862
863 switch (id->fti_ptype) {
864 case DTFTP_ENTRY:
865 case DTFTP_OFFSETS:
866 case DTFTP_IS_ENABLED:
867 id->fti_next = NULL;
868 new_tp->ftt_ids = id;
869 break;
870
871 case DTFTP_RETURN:
872 case DTFTP_POST_OFFSETS:
873 id->fti_next = NULL;
874 new_tp->ftt_retids = id;
875 break;
876
877 default:
878 ASSERT(0);
879 }
880
881 /*
882 * If the ISA-dependent initialization goes to plan, go back to the
883 * beginning and try to install this freshly made tracepoint.
884 */
885 if (fasttrap_tracepoint_init(p, new_tp, pc, id->fti_ptype) == 0)
886 goto again;
887
888 new_tp->ftt_ids = NULL;
889 new_tp->ftt_retids = NULL;
890
891 return (FASTTRAP_ENABLE_FAIL);
892 }
893
894 static void
895 fasttrap_tracepoint_disable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
896 {
897 fasttrap_bucket_t *bucket;
898 fasttrap_provider_t *provider = probe->ftp_prov;
899 fasttrap_tracepoint_t **pp, *tp;
900 fasttrap_id_t *id, **idp;
901 pid_t pid;
902 user_addr_t pc;
903
904 ASSERT(index < probe->ftp_ntps);
905
906 pid = probe->ftp_pid;
907 pc = probe->ftp_tps[index].fit_tp->ftt_pc;
908 id = &probe->ftp_tps[index].fit_id;
909
910 ASSERT(probe->ftp_tps[index].fit_tp->ftt_pid == pid);
911
912 /*
913 * Find the tracepoint and make sure that our id is one of the
914 * ones registered with it.
915 */
916 bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
917 lck_mtx_lock(&bucket->ftb_mtx);
918 for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
919 if (tp->ftt_pid == pid && tp->ftt_pc == pc &&
920 tp->ftt_proc == provider->ftp_proc)
921 break;
922 }
923
924 /*
925 * If we somehow lost this tracepoint, we're in a world of hurt.
926 */
927 ASSERT(tp != NULL);
928
929 switch (id->fti_ptype) {
930 case DTFTP_ENTRY:
931 case DTFTP_OFFSETS:
932 case DTFTP_IS_ENABLED:
933 ASSERT(tp->ftt_ids != NULL);
934 idp = &tp->ftt_ids;
935 break;
936
937 case DTFTP_RETURN:
938 case DTFTP_POST_OFFSETS:
939 ASSERT(tp->ftt_retids != NULL);
940 idp = &tp->ftt_retids;
941 break;
942
943 default:
944 /* Fix compiler warning... */
945 idp = NULL;
946 ASSERT(0);
947 }
948
949 while ((*idp)->fti_probe != probe) {
950 idp = &(*idp)->fti_next;
951 ASSERT(*idp != NULL);
952 }
953
954 id = *idp;
955 *idp = id->fti_next;
956 dtrace_membar_producer();
957
958 ASSERT(id->fti_probe == probe);
959
960 /*
961 * If there are other registered enablings of this tracepoint, we're
962 * all done, but if this was the last probe assocated with this
963 * this tracepoint, we need to remove and free it.
964 */
965 if (tp->ftt_ids != NULL || tp->ftt_retids != NULL) {
966
967 /*
968 * If the current probe's tracepoint is in use, swap it
969 * for an unused tracepoint.
970 */
971 if (tp == probe->ftp_tps[index].fit_tp) {
972 fasttrap_probe_t *tmp_probe;
973 fasttrap_tracepoint_t **tmp_tp;
974 uint_t tmp_index;
975
976 if (tp->ftt_ids != NULL) {
977 tmp_probe = tp->ftt_ids->fti_probe;
978 /* LINTED - alignment */
979 tmp_index = FASTTRAP_ID_INDEX(tp->ftt_ids);
980 tmp_tp = &tmp_probe->ftp_tps[tmp_index].fit_tp;
981 } else {
982 tmp_probe = tp->ftt_retids->fti_probe;
983 /* LINTED - alignment */
984 tmp_index = FASTTRAP_ID_INDEX(tp->ftt_retids);
985 tmp_tp = &tmp_probe->ftp_tps[tmp_index].fit_tp;
986 }
987
988 ASSERT(*tmp_tp != NULL);
989 ASSERT(*tmp_tp != probe->ftp_tps[index].fit_tp);
990 ASSERT((*tmp_tp)->ftt_ids == NULL);
991 ASSERT((*tmp_tp)->ftt_retids == NULL);
992
993 probe->ftp_tps[index].fit_tp = *tmp_tp;
994 *tmp_tp = tp;
995
996 }
997
998 lck_mtx_unlock(&bucket->ftb_mtx);
999
1000 /*
1001 * Tag the modified probe with the generation in which it was
1002 * changed.
1003 */
1004 probe->ftp_gen = fasttrap_mod_gen;
1005 return;
1006 }
1007
1008 lck_mtx_unlock(&bucket->ftb_mtx);
1009
1010 /*
1011 * We can't safely remove the tracepoint from the set of active
1012 * tracepoints until we've actually removed the fasttrap instruction
1013 * from the process's text. We can, however, operate on this
1014 * tracepoint secure in the knowledge that no other thread is going to
1015 * be looking at it since we hold P_PR_LOCK on the process if it's
1016 * live or we hold the provider lock on the process if it's dead and
1017 * gone.
1018 */
1019
1020 /*
1021 * We only need to remove the actual instruction if we're looking
1022 * at an existing process
1023 */
1024 if (p != NULL) {
1025 /*
1026 * If we fail to restore the instruction we need to kill
1027 * this process since it's in a completely unrecoverable
1028 * state.
1029 */
1030 if (fasttrap_tracepoint_remove(p, tp) != 0)
1031 fasttrap_sigtrap(p, NULL, pc);
1032
1033 /*
1034 * Decrement the count of the number of tracepoints active
1035 * in the victim process.
1036 */
1037 //ASSERT(p->p_proc_flag & P_PR_LOCK);
1038 p->p_dtrace_count--;
1039 }
1040
1041 /*
1042 * Remove the probe from the hash table of active tracepoints.
1043 */
1044 lck_mtx_lock(&bucket->ftb_mtx);
1045 pp = (fasttrap_tracepoint_t **)&bucket->ftb_data;
1046 ASSERT(*pp != NULL);
1047 while (*pp != tp) {
1048 pp = &(*pp)->ftt_next;
1049 ASSERT(*pp != NULL);
1050 }
1051
1052 *pp = tp->ftt_next;
1053 dtrace_membar_producer();
1054
1055 lck_mtx_unlock(&bucket->ftb_mtx);
1056
1057 /*
1058 * Tag the modified probe with the generation in which it was changed.
1059 */
1060 probe->ftp_gen = fasttrap_mod_gen;
1061 }
1062
1063 static void
1064 fasttrap_enable_callbacks(void)
1065 {
1066 /*
1067 * We don't have to play the rw lock game here because we're
1068 * providing something rather than taking something away --
1069 * we can be sure that no threads have tried to follow this
1070 * function pointer yet.
1071 */
1072 lck_mtx_lock(&fasttrap_count_mtx);
1073 if (fasttrap_pid_count == 0) {
1074 ASSERT(dtrace_pid_probe_ptr == NULL);
1075 ASSERT(dtrace_return_probe_ptr == NULL);
1076 dtrace_pid_probe_ptr = &fasttrap_pid_probe;
1077 dtrace_return_probe_ptr = &fasttrap_return_probe;
1078 }
1079 ASSERT(dtrace_pid_probe_ptr == &fasttrap_pid_probe);
1080 ASSERT(dtrace_return_probe_ptr == &fasttrap_return_probe);
1081 fasttrap_pid_count++;
1082 lck_mtx_unlock(&fasttrap_count_mtx);
1083 }
1084
1085 static void
1086 fasttrap_disable_callbacks(void)
1087 {
1088 //ASSERT(MUTEX_HELD(&cpu_lock));
1089
1090 lck_mtx_lock(&fasttrap_count_mtx);
1091 ASSERT(fasttrap_pid_count > 0);
1092 fasttrap_pid_count--;
1093 if (fasttrap_pid_count == 0) {
1094 dtrace_cpu_t *cur, *cpu = CPU;
1095
1096 /*
1097 * APPLE NOTE: This loop seems broken, it touches every CPU
1098 * but the one we're actually running on. Need to ask Sun folks
1099 * if that is safe. Scenario is this: We're running on CPU A,
1100 * and lock all but A. Then we get preempted, and start running
1101 * on CPU B. A probe fires on A, and is allowed to enter. BOOM!
1102 */
1103 for (cur = cpu->cpu_next; cur != cpu; cur = cur->cpu_next) {
1104 lck_rw_lock_exclusive(&cur->cpu_ft_lock);
1105 // rw_enter(&cur->cpu_ft_lock, RW_WRITER);
1106 }
1107
1108 dtrace_pid_probe_ptr = NULL;
1109 dtrace_return_probe_ptr = NULL;
1110
1111 for (cur = cpu->cpu_next; cur != cpu; cur = cur->cpu_next) {
1112 lck_rw_unlock_exclusive(&cur->cpu_ft_lock);
1113 // rw_exit(&cur->cpu_ft_lock);
1114 }
1115 }
1116 lck_mtx_unlock(&fasttrap_count_mtx);
1117 }
1118
1119 /*ARGSUSED*/
1120 static int
1121 fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
1122 {
1123 #pragma unused(arg, id)
1124 fasttrap_probe_t *probe = parg;
1125 proc_t *p;
1126 int i, rc;
1127
1128 ASSERT(probe != NULL);
1129 ASSERT(!probe->ftp_enabled);
1130 ASSERT(id == probe->ftp_id);
1131 // ASSERT(MUTEX_HELD(&cpu_lock));
1132
1133 /*
1134 * Increment the count of enabled probes on this probe's provider;
1135 * the provider can't go away while the probe still exists. We
1136 * must increment this even if we aren't able to properly enable
1137 * this probe.
1138 */
1139 lck_mtx_lock(&probe->ftp_prov->ftp_mtx);
1140 probe->ftp_prov->ftp_rcount++;
1141 lck_mtx_unlock(&probe->ftp_prov->ftp_mtx);
1142
1143 /*
1144 * If this probe's provider is retired (meaning it was valid in a
1145 * previously exec'ed incarnation of this address space), bail out. The
1146 * provider can't go away while we're in this code path.
1147 */
1148 if (probe->ftp_prov->ftp_retired)
1149 return(0);
1150
1151 /*
1152 * If we can't find the process, it may be that we're in the context of
1153 * a fork in which the traced process is being born and we're copying
1154 * USDT probes. Otherwise, the process is gone so bail.
1155 */
1156 if ((p = sprlock(probe->ftp_pid)) == PROC_NULL) {
1157 /*
1158 * APPLE NOTE: We should never end up here. The Solaris sprlock()
1159 * does not return process's with SIDL set, but we always return
1160 * the child process.
1161 */
1162 return(0);
1163 }
1164
1165 /*
1166 * APPLE NOTE: We do not have an equivalent thread structure to Solaris.
1167 * Solaris uses its ulwp_t struct for scratch space to support the pid provider.
1168 * To mimic this, we allocate on demand scratch space. If this is the first
1169 * time a probe has been enabled in this process, we need to allocate scratch
1170 * space for each already existing thread. Now is a good time to do this, as
1171 * the target process is suspended and the proc_lock is held.
1172 */
1173 if (p->p_dtrace_ptss_pages == NULL) {
1174 dtrace_ptss_enable(p);
1175 }
1176
1177 // ASSERT(!(p->p_flag & SVFORK));
1178 proc_unlock(p);
1179
1180 /*
1181 * We have to enable the trap entry point before any user threads have
1182 * the chance to execute the trap instruction we're about to place
1183 * in their process's text.
1184 */
1185 fasttrap_enable_callbacks();
1186
1187 /*
1188 * Enable all the tracepoints and add this probe's id to each
1189 * tracepoint's list of active probes.
1190 */
1191 for (i = 0; i < (int)probe->ftp_ntps; i++) {
1192 if ((rc = fasttrap_tracepoint_enable(p, probe, i)) != 0) {
1193 /*
1194 * If enabling the tracepoint failed completely,
1195 * we don't have to disable it; if the failure
1196 * was only partial we must disable it.
1197 */
1198 if (rc == FASTTRAP_ENABLE_FAIL)
1199 i--;
1200 else
1201 ASSERT(rc == FASTTRAP_ENABLE_PARTIAL);
1202
1203 /*
1204 * Back up and pull out all the tracepoints we've
1205 * created so far for this probe.
1206 */
1207 while (i >= 0) {
1208 fasttrap_tracepoint_disable(p, probe, i);
1209 i--;
1210 }
1211
1212 proc_lock(p);
1213 sprunlock(p);
1214
1215 /*
1216 * Since we're not actually enabling this probe,
1217 * drop our reference on the trap table entry.
1218 */
1219 fasttrap_disable_callbacks();
1220 return(0);
1221 }
1222 }
1223
1224 proc_lock(p);
1225 sprunlock(p);
1226
1227 probe->ftp_enabled = 1;
1228 return (0);
1229 }
1230
1231 /*ARGSUSED*/
1232 static void
1233 fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
1234 {
1235 #pragma unused(arg, id)
1236 fasttrap_probe_t *probe = parg;
1237 fasttrap_provider_t *provider = probe->ftp_prov;
1238 proc_t *p;
1239 int i, whack = 0;
1240
1241 ASSERT(id == probe->ftp_id);
1242
1243 /*
1244 * We won't be able to acquire a /proc-esque lock on the process
1245 * iff the process is dead and gone. In this case, we rely on the
1246 * provider lock as a point of mutual exclusion to prevent other
1247 * DTrace consumers from disabling this probe.
1248 */
1249 if ((p = sprlock(probe->ftp_pid)) != PROC_NULL) {
1250 // ASSERT(!(p->p_flag & SVFORK));
1251 proc_unlock(p);
1252 }
1253
1254 lck_mtx_lock(&provider->ftp_mtx);
1255
1256 /*
1257 * Disable all the associated tracepoints (for fully enabled probes).
1258 */
1259 if (probe->ftp_enabled) {
1260 for (i = 0; i < (int)probe->ftp_ntps; i++) {
1261 fasttrap_tracepoint_disable(p, probe, i);
1262 }
1263 }
1264
1265 ASSERT(provider->ftp_rcount > 0);
1266 provider->ftp_rcount--;
1267
1268 if (p != NULL) {
1269 /*
1270 * Even though we may not be able to remove it entirely, we
1271 * mark this retired provider to get a chance to remove some
1272 * of the associated probes.
1273 */
1274 if (provider->ftp_retired && !provider->ftp_marked)
1275 whack = provider->ftp_marked = 1;
1276 lck_mtx_unlock(&provider->ftp_mtx);
1277
1278 proc_lock(p);
1279 sprunlock(p);
1280 } else {
1281 /*
1282 * If the process is dead, we're just waiting for the
1283 * last probe to be disabled to be able to free it.
1284 */
1285 if (provider->ftp_rcount == 0 && !provider->ftp_marked)
1286 whack = provider->ftp_marked = 1;
1287 lck_mtx_unlock(&provider->ftp_mtx);
1288 }
1289
1290 if (whack) {
1291 fasttrap_pid_cleanup(FASTTRAP_CLEANUP_PROVIDER);
1292 }
1293
1294 if (!probe->ftp_enabled)
1295 return;
1296
1297 probe->ftp_enabled = 0;
1298
1299 // ASSERT(MUTEX_HELD(&cpu_lock));
1300 fasttrap_disable_callbacks();
1301 }
1302
1303 /*ARGSUSED*/
1304 static void
1305 fasttrap_pid_getargdesc(void *arg, dtrace_id_t id, void *parg,
1306 dtrace_argdesc_t *desc)
1307 {
1308 #pragma unused(arg, id)
1309 fasttrap_probe_t *probe = parg;
1310 char *str;
1311 int i, ndx;
1312
1313 desc->dtargd_native[0] = '\0';
1314 desc->dtargd_xlate[0] = '\0';
1315
1316 if (probe->ftp_prov->ftp_retired != 0 ||
1317 desc->dtargd_ndx >= probe->ftp_nargs) {
1318 desc->dtargd_ndx = DTRACE_ARGNONE;
1319 return;
1320 }
1321
1322 ndx = (probe->ftp_argmap != NULL) ?
1323 probe->ftp_argmap[desc->dtargd_ndx] : desc->dtargd_ndx;
1324
1325 str = probe->ftp_ntypes;
1326 for (i = 0; i < ndx; i++) {
1327 str += strlen(str) + 1;
1328 }
1329
1330 (void) strlcpy(desc->dtargd_native, str, sizeof(desc->dtargd_native));
1331
1332 if (probe->ftp_xtypes == NULL)
1333 return;
1334
1335 str = probe->ftp_xtypes;
1336 for (i = 0; i < desc->dtargd_ndx; i++) {
1337 str += strlen(str) + 1;
1338 }
1339
1340 (void) strlcpy(desc->dtargd_xlate, str, sizeof(desc->dtargd_xlate));
1341 }
1342
1343 /*ARGSUSED*/
1344 static void
1345 fasttrap_pid_destroy(void *arg, dtrace_id_t id, void *parg)
1346 {
1347 #pragma unused(arg, id)
1348 fasttrap_probe_t *probe = parg;
1349 unsigned int i;
1350
1351 ASSERT(probe != NULL);
1352 ASSERT(!probe->ftp_enabled);
1353 ASSERT(fasttrap_total >= probe->ftp_ntps);
1354
1355 atomic_add_32(&fasttrap_total, -probe->ftp_ntps);
1356 atomic_add_32(&fasttrap_retired, -probe->ftp_ntps);
1357
1358 if (probe->ftp_gen + 1 >= fasttrap_mod_gen)
1359 fasttrap_mod_barrier(probe->ftp_gen);
1360
1361 for (i = 0; i < probe->ftp_ntps; i++) {
1362 zfree(fasttrap_tracepoint_t_zone, probe->ftp_tps[i].fit_tp);
1363 }
1364
1365 if (probe->ftp_ntps < FASTTRAP_PROBE_T_ZONE_MAX_TRACEPOINTS) {
1366 zfree(fasttrap_probe_t_zones[probe->ftp_ntps], probe);
1367 } else {
1368 size_t size = offsetof(fasttrap_probe_t, ftp_tps[probe->ftp_ntps]);
1369 kmem_free(probe, size);
1370 }
1371 }
1372
1373
1374 static const dtrace_pattr_t pid_attr = {
1375 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1376 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1377 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1378 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1379 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1380 };
1381
1382 static dtrace_pops_t pid_pops = {
1383 fasttrap_pid_provide,
1384 NULL,
1385 fasttrap_pid_enable,
1386 fasttrap_pid_disable,
1387 NULL,
1388 NULL,
1389 fasttrap_pid_getargdesc,
1390 fasttrap_pid_getarg,
1391 NULL,
1392 fasttrap_pid_destroy
1393 };
1394
1395 static dtrace_pops_t usdt_pops = {
1396 fasttrap_pid_provide,
1397 NULL,
1398 fasttrap_pid_enable,
1399 fasttrap_pid_disable,
1400 NULL,
1401 NULL,
1402 fasttrap_pid_getargdesc,
1403 fasttrap_usdt_getarg,
1404 NULL,
1405 fasttrap_pid_destroy
1406 };
1407
1408 static fasttrap_proc_t *
1409 fasttrap_proc_lookup(pid_t pid)
1410 {
1411 fasttrap_bucket_t *bucket;
1412 fasttrap_proc_t *fprc, *new_fprc;
1413
1414 bucket = &fasttrap_procs.fth_table[FASTTRAP_PROCS_INDEX(pid)];
1415 lck_mtx_lock(&bucket->ftb_mtx);
1416
1417 for (fprc = bucket->ftb_data; fprc != NULL; fprc = fprc->ftpc_next) {
1418 if (fprc->ftpc_pid == pid && fprc->ftpc_acount != 0) {
1419 lck_mtx_lock(&fprc->ftpc_mtx);
1420 lck_mtx_unlock(&bucket->ftb_mtx);
1421 fprc->ftpc_rcount++;
1422 atomic_add_64(&fprc->ftpc_acount, 1);
1423 ASSERT(fprc->ftpc_acount <= fprc->ftpc_rcount);
1424 lck_mtx_unlock(&fprc->ftpc_mtx);
1425
1426 return (fprc);
1427 }
1428 }
1429
1430 /*
1431 * Drop the bucket lock so we don't try to perform a sleeping
1432 * allocation under it.
1433 */
1434 lck_mtx_unlock(&bucket->ftb_mtx);
1435
1436 new_fprc = kmem_zalloc(sizeof (fasttrap_proc_t), KM_SLEEP);
1437 ASSERT(new_fprc != NULL);
1438 new_fprc->ftpc_pid = pid;
1439 new_fprc->ftpc_rcount = 1;
1440 new_fprc->ftpc_acount = 1;
1441
1442 lck_mtx_lock(&bucket->ftb_mtx);
1443
1444 /*
1445 * Take another lap through the list to make sure a proc hasn't
1446 * been created for this pid while we weren't under the bucket lock.
1447 */
1448 for (fprc = bucket->ftb_data; fprc != NULL; fprc = fprc->ftpc_next) {
1449 if (fprc->ftpc_pid == pid && fprc->ftpc_acount != 0) {
1450 lck_mtx_lock(&fprc->ftpc_mtx);
1451 lck_mtx_unlock(&bucket->ftb_mtx);
1452 fprc->ftpc_rcount++;
1453 atomic_add_64(&fprc->ftpc_acount, 1);
1454 ASSERT(fprc->ftpc_acount <= fprc->ftpc_rcount);
1455 lck_mtx_unlock(&fprc->ftpc_mtx);
1456
1457 kmem_free(new_fprc, sizeof (fasttrap_proc_t));
1458
1459 return (fprc);
1460 }
1461 }
1462
1463 /*
1464 * APPLE NOTE: We have to initialize all locks explicitly
1465 */
1466 lck_mtx_init(&new_fprc->ftpc_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
1467
1468 new_fprc->ftpc_next = bucket->ftb_data;
1469 bucket->ftb_data = new_fprc;
1470
1471 lck_mtx_unlock(&bucket->ftb_mtx);
1472
1473 return (new_fprc);
1474 }
1475
1476 static void
1477 fasttrap_proc_release(fasttrap_proc_t *proc)
1478 {
1479 fasttrap_bucket_t *bucket;
1480 fasttrap_proc_t *fprc, **fprcp;
1481 pid_t pid = proc->ftpc_pid;
1482
1483 lck_mtx_lock(&proc->ftpc_mtx);
1484
1485 ASSERT(proc->ftpc_rcount != 0);
1486 ASSERT(proc->ftpc_acount <= proc->ftpc_rcount);
1487
1488 if (--proc->ftpc_rcount != 0) {
1489 lck_mtx_unlock(&proc->ftpc_mtx);
1490 return;
1491 }
1492
1493 lck_mtx_unlock(&proc->ftpc_mtx);
1494
1495 /*
1496 * There should definitely be no live providers associated with this
1497 * process at this point.
1498 */
1499 ASSERT(proc->ftpc_acount == 0);
1500
1501 bucket = &fasttrap_procs.fth_table[FASTTRAP_PROCS_INDEX(pid)];
1502 lck_mtx_lock(&bucket->ftb_mtx);
1503
1504 fprcp = (fasttrap_proc_t **)&bucket->ftb_data;
1505 while ((fprc = *fprcp) != NULL) {
1506 if (fprc == proc)
1507 break;
1508
1509 fprcp = &fprc->ftpc_next;
1510 }
1511
1512 /*
1513 * Something strange has happened if we can't find the proc.
1514 */
1515 ASSERT(fprc != NULL);
1516
1517 *fprcp = fprc->ftpc_next;
1518
1519 lck_mtx_unlock(&bucket->ftb_mtx);
1520
1521 /*
1522 * APPLE NOTE: explicit lock management. Not 100% certain we need this, the
1523 * memory is freed even without the destroy. Maybe accounting cleanup?
1524 */
1525 lck_mtx_destroy(&fprc->ftpc_mtx, fasttrap_lck_grp);
1526
1527 kmem_free(fprc, sizeof (fasttrap_proc_t));
1528 }
1529
1530 /*
1531 * Lookup a fasttrap-managed provider based on its name and associated proc.
1532 * A reference to the proc must be held for the duration of the call.
1533 * If the pattr argument is non-NULL, this function instantiates the provider
1534 * if it doesn't exist otherwise it returns NULL. The provider is returned
1535 * with its lock held.
1536 */
1537 static fasttrap_provider_t *
1538 fasttrap_provider_lookup(proc_t *p, fasttrap_provider_type_t provider_type, const char *name,
1539 const dtrace_pattr_t *pattr)
1540 {
1541 pid_t pid = p->p_pid;
1542 fasttrap_provider_t *fp, *new_fp = NULL;
1543 fasttrap_bucket_t *bucket;
1544 char provname[DTRACE_PROVNAMELEN];
1545 cred_t *cred;
1546
1547 ASSERT(strlen(name) < sizeof (fp->ftp_name));
1548 ASSERT(pattr != NULL);
1549
1550 bucket = &fasttrap_provs.fth_table[FASTTRAP_PROVS_INDEX(pid, name)];
1551 lck_mtx_lock(&bucket->ftb_mtx);
1552
1553 /*
1554 * Take a lap through the list and return the match if we find it.
1555 */
1556 for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1557 if (fp->ftp_pid == pid &&
1558 fp->ftp_provider_type == provider_type &&
1559 strncmp(fp->ftp_name, name, sizeof(fp->ftp_name)) == 0 &&
1560 !fp->ftp_retired) {
1561 lck_mtx_lock(&fp->ftp_mtx);
1562 lck_mtx_unlock(&bucket->ftb_mtx);
1563 return (fp);
1564 }
1565 }
1566
1567 /*
1568 * Drop the bucket lock so we don't try to perform a sleeping
1569 * allocation under it.
1570 */
1571 lck_mtx_unlock(&bucket->ftb_mtx);
1572
1573 /*
1574 * Make sure the process isn't a child created as the result
1575 * of a vfork(2), and isn't a zombie (but may be in fork).
1576 */
1577 proc_lock(p);
1578 if (p->p_lflag & (P_LINVFORK | P_LEXIT)) {
1579 proc_unlock(p);
1580 return (NULL);
1581 }
1582
1583 /*
1584 * Increment p_dtrace_probes so that the process knows to inform us
1585 * when it exits or execs. fasttrap_provider_free() decrements this
1586 * when we're done with this provider.
1587 */
1588 p->p_dtrace_probes++;
1589
1590 /*
1591 * Grab the credentials for this process so we have
1592 * something to pass to dtrace_register().
1593 * APPLE NOTE: We have no equivalent to crhold,
1594 * even though there is a cr_ref filed in ucred.
1595 */
1596 // lck_mtx_lock(&p->p_crlock;
1597 crhold(p->p_ucred);
1598 cred = p->p_ucred;
1599 // lck_mtx_unlock(&p->p_crlock);
1600 proc_unlock(p);
1601
1602 new_fp = kmem_zalloc(sizeof (fasttrap_provider_t), KM_SLEEP);
1603 ASSERT(new_fp != NULL);
1604 new_fp->ftp_pid = p->p_pid;
1605 new_fp->ftp_proc = fasttrap_proc_lookup(pid);
1606 new_fp->ftp_provider_type = provider_type;
1607
1608 /*
1609 * APPLE NOTE: locks require explicit init
1610 */
1611 lck_mtx_init(&new_fp->ftp_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
1612 lck_mtx_init(&new_fp->ftp_cmtx, fasttrap_lck_grp, fasttrap_lck_attr);
1613
1614 ASSERT(new_fp->ftp_proc != NULL);
1615
1616 lck_mtx_lock(&bucket->ftb_mtx);
1617
1618 /*
1619 * Take another lap through the list to make sure a provider hasn't
1620 * been created for this pid while we weren't under the bucket lock.
1621 */
1622 for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1623 if (fp->ftp_pid == pid && strncmp(fp->ftp_name, name, sizeof(fp->ftp_name)) == 0 &&
1624 !fp->ftp_retired) {
1625 lck_mtx_lock(&fp->ftp_mtx);
1626 lck_mtx_unlock(&bucket->ftb_mtx);
1627 fasttrap_provider_free(new_fp);
1628 crfree(cred);
1629 return (fp);
1630 }
1631 }
1632
1633 (void) strlcpy(new_fp->ftp_name, name, sizeof(new_fp->ftp_name));
1634
1635 /*
1636 * Fail and return NULL if either the provider name is too long
1637 * or we fail to register this new provider with the DTrace
1638 * framework. Note that this is the only place we ever construct
1639 * the full provider name -- we keep it in pieces in the provider
1640 * structure.
1641 */
1642 if (snprintf(provname, sizeof (provname), "%s%u", name, (uint_t)pid) >=
1643 (int)sizeof (provname) ||
1644 dtrace_register(provname, pattr,
1645 DTRACE_PRIV_PROC | DTRACE_PRIV_OWNER | DTRACE_PRIV_ZONEOWNER, cred,
1646 pattr == &pid_attr ? &pid_pops : &usdt_pops, new_fp,
1647 &new_fp->ftp_provid) != 0) {
1648 lck_mtx_unlock(&bucket->ftb_mtx);
1649 fasttrap_provider_free(new_fp);
1650 crfree(cred);
1651 return (NULL);
1652 }
1653
1654 new_fp->ftp_next = bucket->ftb_data;
1655 bucket->ftb_data = new_fp;
1656
1657 lck_mtx_lock(&new_fp->ftp_mtx);
1658 lck_mtx_unlock(&bucket->ftb_mtx);
1659
1660 crfree(cred);
1661 return (new_fp);
1662 }
1663
1664 static void
1665 fasttrap_provider_free(fasttrap_provider_t *provider)
1666 {
1667 pid_t pid = provider->ftp_pid;
1668 proc_t *p;
1669
1670 /*
1671 * There need to be no associated enabled probes, no consumers
1672 * creating probes, and no meta providers referencing this provider.
1673 */
1674 ASSERT(provider->ftp_rcount == 0);
1675 ASSERT(provider->ftp_ccount == 0);
1676 ASSERT(provider->ftp_mcount == 0);
1677
1678 /*
1679 * If this provider hasn't been retired, we need to explicitly drop the
1680 * count of active providers on the associated process structure.
1681 */
1682 if (!provider->ftp_retired) {
1683 atomic_add_64(&provider->ftp_proc->ftpc_acount, -1);
1684 ASSERT(provider->ftp_proc->ftpc_acount <
1685 provider->ftp_proc->ftpc_rcount);
1686 }
1687
1688 fasttrap_proc_release(provider->ftp_proc);
1689
1690 /*
1691 * APPLE NOTE: explicit lock management. Not 100% certain we need this, the
1692 * memory is freed even without the destroy. Maybe accounting cleanup?
1693 */
1694 lck_mtx_destroy(&provider->ftp_mtx, fasttrap_lck_grp);
1695 lck_mtx_destroy(&provider->ftp_cmtx, fasttrap_lck_grp);
1696
1697 kmem_free(provider, sizeof (fasttrap_provider_t));
1698
1699 /*
1700 * Decrement p_dtrace_probes on the process whose provider we're
1701 * freeing. We don't have to worry about clobbering somone else's
1702 * modifications to it because we have locked the bucket that
1703 * corresponds to this process's hash chain in the provider hash
1704 * table. Don't sweat it if we can't find the process.
1705 */
1706 if ((p = proc_find(pid)) == NULL) {
1707 return;
1708 }
1709
1710 proc_lock(p);
1711 p->p_dtrace_probes--;
1712 proc_unlock(p);
1713
1714 proc_rele(p);
1715 }
1716
1717 static void
1718 fasttrap_provider_retire(proc_t *p, const char *name, int mprov)
1719 {
1720 fasttrap_provider_t *fp;
1721 fasttrap_bucket_t *bucket;
1722 dtrace_provider_id_t provid;
1723 ASSERT(strlen(name) < sizeof (fp->ftp_name));
1724
1725 bucket = &fasttrap_provs.fth_table[FASTTRAP_PROVS_INDEX(p->p_pid, name)];
1726 lck_mtx_lock(&bucket->ftb_mtx);
1727
1728 for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1729 if (fp->ftp_pid == p->p_pid && strncmp(fp->ftp_name, name, sizeof(fp->ftp_name)) == 0 &&
1730 !fp->ftp_retired)
1731 break;
1732 }
1733
1734 if (fp == NULL) {
1735 lck_mtx_unlock(&bucket->ftb_mtx);
1736 return;
1737 }
1738
1739 lck_mtx_lock(&fp->ftp_mtx);
1740 ASSERT(!mprov || fp->ftp_mcount > 0);
1741 if (mprov && --fp->ftp_mcount != 0) {
1742 lck_mtx_unlock(&fp->ftp_mtx);
1743 lck_mtx_unlock(&bucket->ftb_mtx);
1744 return;
1745 }
1746
1747 /*
1748 * Mark the provider to be removed in our post-processing step, mark it
1749 * retired, and drop the active count on its proc. Marking it indicates
1750 * that we should try to remove it; setting the retired flag indicates
1751 * that we're done with this provider; dropping the active the proc
1752 * releases our hold, and when this reaches zero (as it will during
1753 * exit or exec) the proc and associated providers become defunct.
1754 *
1755 * We obviously need to take the bucket lock before the provider lock
1756 * to perform the lookup, but we need to drop the provider lock
1757 * before calling into the DTrace framework since we acquire the
1758 * provider lock in callbacks invoked from the DTrace framework. The
1759 * bucket lock therefore protects the integrity of the provider hash
1760 * table.
1761 */
1762 atomic_add_64(&fp->ftp_proc->ftpc_acount, -1);
1763 ASSERT(fp->ftp_proc->ftpc_acount < fp->ftp_proc->ftpc_rcount);
1764
1765 /*
1766 * Add this provider probes to the retired count and
1767 * make sure we don't add them twice
1768 */
1769 atomic_add_32(&fasttrap_retired, fp->ftp_pcount);
1770 fp->ftp_pcount = 0;
1771
1772 fp->ftp_retired = 1;
1773 fp->ftp_marked = 1;
1774 provid = fp->ftp_provid;
1775 lck_mtx_unlock(&fp->ftp_mtx);
1776
1777 /*
1778 * We don't have to worry about invalidating the same provider twice
1779 * since fasttrap_provider_lookup() will ignore providers that have
1780 * been marked as retired.
1781 */
1782 dtrace_invalidate(provid);
1783
1784 lck_mtx_unlock(&bucket->ftb_mtx);
1785
1786 fasttrap_pid_cleanup(FASTTRAP_CLEANUP_PROVIDER);
1787 }
1788
1789 static int
1790 fasttrap_uint32_cmp(const void *ap, const void *bp)
1791 {
1792 return (*(const uint32_t *)ap - *(const uint32_t *)bp);
1793 }
1794
1795 static int
1796 fasttrap_uint64_cmp(const void *ap, const void *bp)
1797 {
1798 return (*(const uint64_t *)ap - *(const uint64_t *)bp);
1799 }
1800
1801 static int
1802 fasttrap_add_probe(fasttrap_probe_spec_t *pdata)
1803 {
1804 proc_t *p;
1805 fasttrap_provider_t *provider;
1806 fasttrap_probe_t *pp;
1807 fasttrap_tracepoint_t *tp;
1808 const char *name;
1809 unsigned int i, aframes, whack;
1810
1811 /*
1812 * There needs to be at least one desired trace point.
1813 */
1814 if (pdata->ftps_noffs == 0)
1815 return (EINVAL);
1816
1817 switch (pdata->ftps_probe_type) {
1818 case DTFTP_ENTRY:
1819 name = "entry";
1820 aframes = FASTTRAP_ENTRY_AFRAMES;
1821 break;
1822 case DTFTP_RETURN:
1823 name = "return";
1824 aframes = FASTTRAP_RETURN_AFRAMES;
1825 break;
1826 case DTFTP_OFFSETS:
1827 aframes = 0;
1828 name = NULL;
1829 break;
1830 default:
1831 return (EINVAL);
1832 }
1833
1834 const char* provider_name;
1835 switch (pdata->ftps_provider_type) {
1836 case DTFTP_PROVIDER_PID:
1837 provider_name = FASTTRAP_PID_NAME;
1838 break;
1839 case DTFTP_PROVIDER_OBJC:
1840 provider_name = FASTTRAP_OBJC_NAME;
1841 break;
1842 case DTFTP_PROVIDER_ONESHOT:
1843 provider_name = FASTTRAP_ONESHOT_NAME;
1844 break;
1845 default:
1846 return (EINVAL);
1847 }
1848
1849 p = proc_find(pdata->ftps_pid);
1850 if (p == PROC_NULL)
1851 return (ESRCH);
1852
1853 /*
1854 * Set that the process is allowed to run modified code and
1855 * bail if it is not allowed to
1856 */
1857 #if CONFIG_EMBEDDED
1858 if ((p->p_csflags & (CS_KILL|CS_HARD)) && !cs_allow_invalid(p)) {
1859 proc_rele(p);
1860 return (EPERM);
1861 }
1862 #endif
1863 if ((provider = fasttrap_provider_lookup(p, pdata->ftps_provider_type,
1864 provider_name, &pid_attr)) == NULL) {
1865 proc_rele(p);
1866 return (ESRCH);
1867 }
1868
1869 proc_rele(p);
1870 /*
1871 * Increment this reference count to indicate that a consumer is
1872 * actively adding a new probe associated with this provider. This
1873 * prevents the provider from being deleted -- we'll need to check
1874 * for pending deletions when we drop this reference count.
1875 */
1876 provider->ftp_ccount++;
1877 lck_mtx_unlock(&provider->ftp_mtx);
1878
1879 /*
1880 * Grab the creation lock to ensure consistency between calls to
1881 * dtrace_probe_lookup() and dtrace_probe_create() in the face of
1882 * other threads creating probes. We must drop the provider lock
1883 * before taking this lock to avoid a three-way deadlock with the
1884 * DTrace framework.
1885 */
1886 lck_mtx_lock(&provider->ftp_cmtx);
1887
1888 if (name == NULL) {
1889 for (i = 0; i < pdata->ftps_noffs; i++) {
1890 char name_str[17];
1891
1892 (void) snprintf(name_str, sizeof(name_str), "%llx",
1893 (uint64_t)pdata->ftps_offs[i]);
1894
1895 if (dtrace_probe_lookup(provider->ftp_provid,
1896 pdata->ftps_mod, pdata->ftps_func, name_str) != 0)
1897 continue;
1898
1899 atomic_add_32(&fasttrap_total, 1);
1900 if (fasttrap_total > fasttrap_max) {
1901 atomic_add_32(&fasttrap_total, -1);
1902 goto no_mem;
1903 }
1904 provider->ftp_pcount++;
1905
1906 pp = zalloc(fasttrap_probe_t_zones[1]);
1907 bzero(pp, sizeof (fasttrap_probe_t));
1908
1909 pp->ftp_prov = provider;
1910 pp->ftp_faddr = pdata->ftps_pc;
1911 pp->ftp_fsize = pdata->ftps_size;
1912 pp->ftp_pid = pdata->ftps_pid;
1913 pp->ftp_ntps = 1;
1914
1915 tp = zalloc(fasttrap_tracepoint_t_zone);
1916 bzero(tp, sizeof (fasttrap_tracepoint_t));
1917
1918 tp->ftt_proc = provider->ftp_proc;
1919 tp->ftt_pc = pdata->ftps_offs[i] + pdata->ftps_pc;
1920 tp->ftt_pid = pdata->ftps_pid;
1921
1922 #if defined(__arm__) || defined(__arm64__)
1923 /*
1924 * On arm the subinfo is used to distinguish between arm
1925 * and thumb modes. On arm64 there is no thumb mode, so
1926 * this field is simply initialized to 0 on its way
1927 * into the kernel.
1928 */
1929 tp->ftt_fntype = pdata->ftps_arch_subinfo;
1930 #endif
1931
1932 pp->ftp_tps[0].fit_tp = tp;
1933 pp->ftp_tps[0].fit_id.fti_probe = pp;
1934 pp->ftp_tps[0].fit_id.fti_ptype = pdata->ftps_probe_type;
1935 pp->ftp_id = dtrace_probe_create(provider->ftp_provid,
1936 pdata->ftps_mod, pdata->ftps_func, name_str,
1937 FASTTRAP_OFFSET_AFRAMES, pp);
1938 }
1939
1940 } else if (dtrace_probe_lookup(provider->ftp_provid, pdata->ftps_mod,
1941 pdata->ftps_func, name) == 0) {
1942 atomic_add_32(&fasttrap_total, pdata->ftps_noffs);
1943
1944 if (fasttrap_total > fasttrap_max) {
1945 atomic_add_32(&fasttrap_total, -pdata->ftps_noffs);
1946 goto no_mem;
1947 }
1948
1949 /*
1950 * Make sure all tracepoint program counter values are unique.
1951 * We later assume that each probe has exactly one tracepoint
1952 * for a given pc.
1953 */
1954 qsort(pdata->ftps_offs, pdata->ftps_noffs,
1955 sizeof (uint64_t), fasttrap_uint64_cmp);
1956 for (i = 1; i < pdata->ftps_noffs; i++) {
1957 if (pdata->ftps_offs[i] > pdata->ftps_offs[i - 1])
1958 continue;
1959
1960 atomic_add_32(&fasttrap_total, -pdata->ftps_noffs);
1961 goto no_mem;
1962 }
1963 provider->ftp_pcount += pdata->ftps_noffs;
1964 ASSERT(pdata->ftps_noffs > 0);
1965 if (pdata->ftps_noffs < FASTTRAP_PROBE_T_ZONE_MAX_TRACEPOINTS) {
1966 pp = zalloc(fasttrap_probe_t_zones[pdata->ftps_noffs]);
1967 bzero(pp, offsetof(fasttrap_probe_t, ftp_tps[pdata->ftps_noffs]));
1968 } else {
1969 pp = kmem_zalloc(offsetof(fasttrap_probe_t, ftp_tps[pdata->ftps_noffs]), KM_SLEEP);
1970 }
1971
1972 pp->ftp_prov = provider;
1973 pp->ftp_faddr = pdata->ftps_pc;
1974 pp->ftp_fsize = pdata->ftps_size;
1975 pp->ftp_pid = pdata->ftps_pid;
1976 pp->ftp_ntps = pdata->ftps_noffs;
1977
1978 for (i = 0; i < pdata->ftps_noffs; i++) {
1979 tp = zalloc(fasttrap_tracepoint_t_zone);
1980 bzero(tp, sizeof (fasttrap_tracepoint_t));
1981 tp->ftt_proc = provider->ftp_proc;
1982 tp->ftt_pc = pdata->ftps_offs[i] + pdata->ftps_pc;
1983 tp->ftt_pid = pdata->ftps_pid;
1984
1985 #if defined(__arm__) || defined (__arm64__)
1986 /*
1987 * On arm the subinfo is used to distinguish between arm
1988 * and thumb modes. On arm64 there is no thumb mode, so
1989 * this field is simply initialized to 0 on its way
1990 * into the kernel.
1991 */
1992
1993 tp->ftt_fntype = pdata->ftps_arch_subinfo;
1994 #endif
1995 pp->ftp_tps[i].fit_tp = tp;
1996 pp->ftp_tps[i].fit_id.fti_probe = pp;
1997 pp->ftp_tps[i].fit_id.fti_ptype = pdata->ftps_probe_type;
1998 }
1999
2000 pp->ftp_id = dtrace_probe_create(provider->ftp_provid,
2001 pdata->ftps_mod, pdata->ftps_func, name, aframes, pp);
2002 }
2003
2004 lck_mtx_unlock(&provider->ftp_cmtx);
2005
2006 /*
2007 * We know that the provider is still valid since we incremented the
2008 * creation reference count. If someone tried to clean up this provider
2009 * while we were using it (e.g. because the process called exec(2) or
2010 * exit(2)), take note of that and try to clean it up now.
2011 */
2012 lck_mtx_lock(&provider->ftp_mtx);
2013 provider->ftp_ccount--;
2014 whack = provider->ftp_retired;
2015 lck_mtx_unlock(&provider->ftp_mtx);
2016
2017 if (whack)
2018 fasttrap_pid_cleanup(FASTTRAP_CLEANUP_PROVIDER);
2019
2020 return (0);
2021
2022 no_mem:
2023 /*
2024 * If we've exhausted the allowable resources, we'll try to remove
2025 * this provider to free some up. This is to cover the case where
2026 * the user has accidentally created many more probes than was
2027 * intended (e.g. pid123:::).
2028 */
2029 lck_mtx_unlock(&provider->ftp_cmtx);
2030 lck_mtx_lock(&provider->ftp_mtx);
2031 provider->ftp_ccount--;
2032 provider->ftp_marked = 1;
2033 lck_mtx_unlock(&provider->ftp_mtx);
2034
2035 fasttrap_pid_cleanup(FASTTRAP_CLEANUP_PROVIDER);
2036
2037 return (ENOMEM);
2038 }
2039
2040 /*ARGSUSED*/
2041 static void *
2042 fasttrap_meta_provide(void *arg, dtrace_helper_provdesc_t *dhpv, proc_t *p)
2043 {
2044 #pragma unused(arg)
2045 fasttrap_provider_t *provider;
2046
2047 /*
2048 * A 32-bit unsigned integer (like a pid for example) can be
2049 * expressed in 10 or fewer decimal digits. Make sure that we'll
2050 * have enough space for the provider name.
2051 */
2052 if (strlen(dhpv->dthpv_provname) + 10 >=
2053 sizeof (provider->ftp_name)) {
2054 cmn_err(CE_WARN, "failed to instantiate provider %s: "
2055 "name too long to accomodate pid", dhpv->dthpv_provname);
2056 return (NULL);
2057 }
2058
2059 /*
2060 * Don't let folks spoof the true pid provider.
2061 */
2062 if (strncmp(dhpv->dthpv_provname, FASTTRAP_PID_NAME, sizeof(FASTTRAP_PID_NAME)) == 0) {
2063 cmn_err(CE_WARN, "failed to instantiate provider %s: "
2064 "%s is an invalid name", dhpv->dthpv_provname,
2065 FASTTRAP_PID_NAME);
2066 return (NULL);
2067 }
2068
2069 /*
2070 * APPLE NOTE: We also need to check the objc and oneshot pid provider types
2071 */
2072 if (strncmp(dhpv->dthpv_provname, FASTTRAP_OBJC_NAME, sizeof(FASTTRAP_OBJC_NAME)) == 0) {
2073 cmn_err(CE_WARN, "failed to instantiate provider %s: "
2074 "%s is an invalid name", dhpv->dthpv_provname,
2075 FASTTRAP_OBJC_NAME);
2076 return (NULL);
2077 }
2078 if (strncmp(dhpv->dthpv_provname, FASTTRAP_ONESHOT_NAME, sizeof(FASTTRAP_ONESHOT_NAME)) == 0) {
2079 cmn_err(CE_WARN, "failed to instantiate provider %s: "
2080 "%s is an invalid name", dhpv->dthpv_provname,
2081 FASTTRAP_ONESHOT_NAME);
2082 return (NULL);
2083 }
2084
2085 /*
2086 * The highest stability class that fasttrap supports is ISA; cap
2087 * the stability of the new provider accordingly.
2088 */
2089 if (dhpv->dthpv_pattr.dtpa_provider.dtat_class > DTRACE_CLASS_ISA)
2090 dhpv->dthpv_pattr.dtpa_provider.dtat_class = DTRACE_CLASS_ISA;
2091 if (dhpv->dthpv_pattr.dtpa_mod.dtat_class > DTRACE_CLASS_ISA)
2092 dhpv->dthpv_pattr.dtpa_mod.dtat_class = DTRACE_CLASS_ISA;
2093 if (dhpv->dthpv_pattr.dtpa_func.dtat_class > DTRACE_CLASS_ISA)
2094 dhpv->dthpv_pattr.dtpa_func.dtat_class = DTRACE_CLASS_ISA;
2095 if (dhpv->dthpv_pattr.dtpa_name.dtat_class > DTRACE_CLASS_ISA)
2096 dhpv->dthpv_pattr.dtpa_name.dtat_class = DTRACE_CLASS_ISA;
2097 if (dhpv->dthpv_pattr.dtpa_args.dtat_class > DTRACE_CLASS_ISA)
2098 dhpv->dthpv_pattr.dtpa_args.dtat_class = DTRACE_CLASS_ISA;
2099
2100 if ((provider = fasttrap_provider_lookup(p, DTFTP_PROVIDER_USDT, dhpv->dthpv_provname,
2101 &dhpv->dthpv_pattr)) == NULL) {
2102 cmn_err(CE_WARN, "failed to instantiate provider %s for "
2103 "process %u", dhpv->dthpv_provname, (uint_t)p->p_pid);
2104 return (NULL);
2105 }
2106
2107 /*
2108 * APPLE NOTE!
2109 *
2110 * USDT probes (fasttrap meta probes) are very expensive to create.
2111 * Profiling has shown that the largest single cost is verifying that
2112 * dtrace hasn't already created a given meta_probe. The reason for
2113 * this is dtrace_match() often has to strcmp ~100 hashed entries for
2114 * each static probe being created. We want to get rid of that check.
2115 * The simplest way of eliminating it is to deny the ability to add
2116 * probes to an existing provider. If the provider already exists, BZZT!
2117 * This still leaves the possibility of intentionally malformed DOF
2118 * having duplicate probes. However, duplicate probes are not fatal,
2119 * and there is no way to get that by accident, so we will not check
2120 * for that case.
2121 *
2122 * UPDATE: It turns out there are several use cases that require adding
2123 * probes to existing providers. Disabling the dtrace_probe_lookup()
2124 * optimization for now. See APPLE NOTE in fasttrap_meta_create_probe.
2125 */
2126
2127 /*
2128 * Up the meta provider count so this provider isn't removed until
2129 * the meta provider has been told to remove it.
2130 */
2131 provider->ftp_mcount++;
2132
2133 lck_mtx_unlock(&provider->ftp_mtx);
2134
2135 return (provider);
2136 }
2137
2138 /*ARGSUSED*/
2139 static void
2140 fasttrap_meta_create_probe(void *arg, void *parg,
2141 dtrace_helper_probedesc_t *dhpb)
2142 {
2143 #pragma unused(arg)
2144 fasttrap_provider_t *provider = parg;
2145 fasttrap_probe_t *pp;
2146 fasttrap_tracepoint_t *tp;
2147 unsigned int i, j;
2148 uint32_t ntps;
2149
2150 /*
2151 * Since the meta provider count is non-zero we don't have to worry
2152 * about this provider disappearing.
2153 */
2154 ASSERT(provider->ftp_mcount > 0);
2155
2156 /*
2157 * The offsets must be unique.
2158 */
2159 qsort(dhpb->dthpb_offs, dhpb->dthpb_noffs, sizeof (uint32_t),
2160 fasttrap_uint32_cmp);
2161 for (i = 1; i < dhpb->dthpb_noffs; i++) {
2162 if (dhpb->dthpb_base + dhpb->dthpb_offs[i] <=
2163 dhpb->dthpb_base + dhpb->dthpb_offs[i - 1])
2164 return;
2165 }
2166
2167 qsort(dhpb->dthpb_enoffs, dhpb->dthpb_nenoffs, sizeof (uint32_t),
2168 fasttrap_uint32_cmp);
2169 for (i = 1; i < dhpb->dthpb_nenoffs; i++) {
2170 if (dhpb->dthpb_base + dhpb->dthpb_enoffs[i] <=
2171 dhpb->dthpb_base + dhpb->dthpb_enoffs[i - 1])
2172 return;
2173 }
2174
2175 /*
2176 * Grab the creation lock to ensure consistency between calls to
2177 * dtrace_probe_lookup() and dtrace_probe_create() in the face of
2178 * other threads creating probes.
2179 */
2180 lck_mtx_lock(&provider->ftp_cmtx);
2181
2182 #if 0
2183 /*
2184 * APPLE NOTE: This is hideously expensive. See note in
2185 * fasttrap_meta_provide() for why we can get away without
2186 * checking here.
2187 */
2188 if (dtrace_probe_lookup(provider->ftp_provid, dhpb->dthpb_mod,
2189 dhpb->dthpb_func, dhpb->dthpb_name) != 0) {
2190 lck_mtx_unlock(&provider->ftp_cmtx);
2191 return;
2192 }
2193 #endif
2194
2195 ntps = dhpb->dthpb_noffs + dhpb->dthpb_nenoffs;
2196 ASSERT(ntps > 0);
2197
2198 atomic_add_32(&fasttrap_total, ntps);
2199
2200 if (fasttrap_total > fasttrap_max) {
2201 atomic_add_32(&fasttrap_total, -ntps);
2202 lck_mtx_unlock(&provider->ftp_cmtx);
2203 return;
2204 }
2205
2206 provider->ftp_pcount += ntps;
2207
2208 if (ntps < FASTTRAP_PROBE_T_ZONE_MAX_TRACEPOINTS) {
2209 pp = zalloc(fasttrap_probe_t_zones[ntps]);
2210 bzero(pp, offsetof(fasttrap_probe_t, ftp_tps[ntps]));
2211 } else {
2212 pp = kmem_zalloc(offsetof(fasttrap_probe_t, ftp_tps[ntps]), KM_SLEEP);
2213 }
2214
2215 pp->ftp_prov = provider;
2216 pp->ftp_pid = provider->ftp_pid;
2217 pp->ftp_ntps = ntps;
2218 pp->ftp_nargs = dhpb->dthpb_xargc;
2219 pp->ftp_xtypes = dhpb->dthpb_xtypes;
2220 pp->ftp_ntypes = dhpb->dthpb_ntypes;
2221
2222 /*
2223 * First create a tracepoint for each actual point of interest.
2224 */
2225 for (i = 0; i < dhpb->dthpb_noffs; i++) {
2226 tp = zalloc(fasttrap_tracepoint_t_zone);
2227 bzero(tp, sizeof (fasttrap_tracepoint_t));
2228
2229 tp->ftt_proc = provider->ftp_proc;
2230
2231 /*
2232 * APPLE NOTE: We have linker support when creating DOF to handle all relocations for us.
2233 * Unfortunately, a side effect of this is that the relocations do not point at exactly
2234 * the location we want. We need to fix up the addresses here. The fixups vary by arch and type.
2235 */
2236 #if defined(__x86_64__)
2237 /*
2238 * Both 32 & 64 bit want to go back one byte, to point at the first NOP
2239 */
2240 tp->ftt_pc = dhpb->dthpb_base + (int64_t)dhpb->dthpb_offs[i] - 1;
2241 #elif defined(__arm__) || defined(__arm64__)
2242 /*
2243 * All ARM and ARM64 probes are zero offset. We need to zero out the
2244 * thumb bit because we still support 32bit user processes.
2245 * On 64bit user processes, bit zero won't be set anyway.
2246 */
2247 tp->ftt_pc = (dhpb->dthpb_base + (int64_t)dhpb->dthpb_offs[i]) & ~0x1UL;
2248 tp->ftt_fntype = FASTTRAP_FN_USDT;
2249 #else
2250 #error "Architecture not supported"
2251 #endif
2252
2253 tp->ftt_pid = provider->ftp_pid;
2254
2255 pp->ftp_tps[i].fit_tp = tp;
2256 pp->ftp_tps[i].fit_id.fti_probe = pp;
2257 pp->ftp_tps[i].fit_id.fti_ptype = DTFTP_OFFSETS;
2258 }
2259
2260 /*
2261 * Then create a tracepoint for each is-enabled point.
2262 */
2263 for (j = 0; i < ntps; i++, j++) {
2264 tp = zalloc(fasttrap_tracepoint_t_zone);
2265 bzero(tp, sizeof (fasttrap_tracepoint_t));
2266
2267 tp->ftt_proc = provider->ftp_proc;
2268
2269 /*
2270 * APPLE NOTE: We have linker support when creating DOF to handle all relocations for us.
2271 * Unfortunately, a side effect of this is that the relocations do not point at exactly
2272 * the location we want. We need to fix up the addresses here. The fixups vary by arch and type.
2273 */
2274 #if defined(__x86_64__)
2275 /*
2276 * Both 32 & 64 bit want to go forward two bytes, to point at a single byte nop.
2277 */
2278 tp->ftt_pc = dhpb->dthpb_base + (int64_t)dhpb->dthpb_enoffs[j] + 2;
2279 #elif defined(__arm__) || defined(__arm64__)
2280 /*
2281 * All ARM and ARM64 probes are zero offset. We need to zero out the
2282 * thumb bit because we still support 32bit user processes.
2283 * On 64bit user processes, bit zero won't be set anyway.
2284 */
2285 tp->ftt_pc = (dhpb->dthpb_base + (int64_t)dhpb->dthpb_enoffs[j]) & ~0x1UL;
2286 tp->ftt_fntype = FASTTRAP_FN_USDT;
2287 #else
2288 #error "Architecture not supported"
2289 #endif
2290
2291 tp->ftt_pid = provider->ftp_pid;
2292
2293 pp->ftp_tps[i].fit_tp = tp;
2294 pp->ftp_tps[i].fit_id.fti_probe = pp;
2295 pp->ftp_tps[i].fit_id.fti_ptype = DTFTP_IS_ENABLED;
2296 }
2297
2298 /*
2299 * If the arguments are shuffled around we set the argument remapping
2300 * table. Later, when the probe fires, we only remap the arguments
2301 * if the table is non-NULL.
2302 */
2303 for (i = 0; i < dhpb->dthpb_xargc; i++) {
2304 if (dhpb->dthpb_args[i] != i) {
2305 pp->ftp_argmap = dhpb->dthpb_args;
2306 break;
2307 }
2308 }
2309
2310 /*
2311 * The probe is fully constructed -- register it with DTrace.
2312 */
2313 pp->ftp_id = dtrace_probe_create(provider->ftp_provid, dhpb->dthpb_mod,
2314 dhpb->dthpb_func, dhpb->dthpb_name, FASTTRAP_OFFSET_AFRAMES, pp);
2315
2316 lck_mtx_unlock(&provider->ftp_cmtx);
2317 }
2318
2319 /*ARGSUSED*/
2320 static void
2321 fasttrap_meta_remove(void *arg, dtrace_helper_provdesc_t *dhpv, proc_t *p)
2322 {
2323 #pragma unused(arg)
2324 /*
2325 * Clean up the USDT provider. There may be active consumers of the
2326 * provider busy adding probes, no damage will actually befall the
2327 * provider until that count has dropped to zero. This just puts
2328 * the provider on death row.
2329 */
2330 fasttrap_provider_retire(p, dhpv->dthpv_provname, 1);
2331 }
2332
2333 static char*
2334 fasttrap_meta_provider_name(void *arg)
2335 {
2336 fasttrap_provider_t *fprovider = arg;
2337 dtrace_provider_t *provider = (dtrace_provider_t*)(fprovider->ftp_provid);
2338 return provider->dtpv_name;
2339 }
2340
2341 static dtrace_mops_t fasttrap_mops = {
2342 fasttrap_meta_create_probe,
2343 fasttrap_meta_provide,
2344 fasttrap_meta_remove,
2345 fasttrap_meta_provider_name
2346 };
2347
2348 /*
2349 * Validate a null-terminated string. If str is not null-terminated,
2350 * or not a UTF8 valid string, the function returns -1. Otherwise, 0 is
2351 * returned.
2352 *
2353 * str: string to validate.
2354 * maxlen: maximal length of the string, null-terminated byte included.
2355 */
2356 static int
2357 fasttrap_validatestr(char const* str, size_t maxlen) {
2358 size_t len;
2359
2360 assert(str);
2361 assert(maxlen != 0);
2362
2363 /* Check if the string is null-terminated. */
2364 len = strnlen(str, maxlen);
2365 if (len >= maxlen)
2366 return -1;
2367
2368 /* Finally, check for UTF8 validity. */
2369 return utf8_validatestr((unsigned const char*) str, len);
2370 }
2371
2372 /*ARGSUSED*/
2373 static int
2374 fasttrap_ioctl(dev_t dev, u_long cmd, user_addr_t arg, int md, cred_t *cr, int *rv)
2375 {
2376 #pragma unused(dev, md, rv)
2377 if (!dtrace_attached())
2378 return (EAGAIN);
2379
2380 if (cmd == FASTTRAPIOC_MAKEPROBE) {
2381 fasttrap_probe_spec_t *probe;
2382 uint64_t noffs;
2383 size_t size;
2384 int ret;
2385
2386 if (copyin(arg + __offsetof(fasttrap_probe_spec_t, ftps_noffs), &noffs,
2387 sizeof (probe->ftps_noffs)))
2388 return (EFAULT);
2389
2390 /*
2391 * Probes must have at least one tracepoint.
2392 */
2393 if (noffs == 0)
2394 return (EINVAL);
2395
2396 /*
2397 * We want to check the number of noffs before doing
2398 * sizing math, to prevent potential buffer overflows.
2399 */
2400 if (noffs > ((1024 * 1024) - sizeof(fasttrap_probe_spec_t)) / sizeof(probe->ftps_offs[0]))
2401 return (ENOMEM);
2402
2403 size = sizeof (fasttrap_probe_spec_t) +
2404 sizeof (probe->ftps_offs[0]) * (noffs - 1);
2405
2406 probe = kmem_alloc(size, KM_SLEEP);
2407
2408 if (copyin(arg, probe, size) != 0 ||
2409 probe->ftps_noffs != noffs) {
2410 kmem_free(probe, size);
2411 return (EFAULT);
2412 }
2413
2414 /*
2415 * Verify that the function and module strings contain no
2416 * funny characters.
2417 */
2418
2419 if (fasttrap_validatestr(probe->ftps_func, sizeof(probe->ftps_func)) != 0) {
2420 ret = EINVAL;
2421 goto err;
2422 }
2423
2424 if (fasttrap_validatestr(probe->ftps_mod, sizeof(probe->ftps_mod)) != 0) {
2425 ret = EINVAL;
2426 goto err;
2427 }
2428
2429 if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
2430 proc_t *p;
2431 pid_t pid = probe->ftps_pid;
2432
2433 /*
2434 * Report an error if the process doesn't exist
2435 * or is actively being birthed.
2436 */
2437 if ((p = proc_find(pid)) == PROC_NULL || p->p_stat == SIDL) {
2438 if (p != PROC_NULL)
2439 proc_rele(p);
2440 ret = ESRCH;
2441 goto err;
2442 }
2443 // proc_lock(p);
2444 // FIXME! How is this done on OS X?
2445 // if ((ret = priv_proc_cred_perm(cr, p, NULL,
2446 // VREAD | VWRITE)) != 0) {
2447 // mutex_exit(&p->p_lock);
2448 // return (ret);
2449 // }
2450 // proc_unlock(p);
2451 proc_rele(p);
2452 }
2453
2454 ret = fasttrap_add_probe(probe);
2455
2456 err:
2457 kmem_free(probe, size);
2458
2459 return (ret);
2460
2461 } else if (cmd == FASTTRAPIOC_GETINSTR) {
2462 fasttrap_instr_query_t instr;
2463 fasttrap_tracepoint_t *tp;
2464 uint_t index;
2465 // int ret;
2466
2467 if (copyin(arg, &instr, sizeof (instr)) != 0)
2468 return (EFAULT);
2469
2470 if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
2471 proc_t *p;
2472 pid_t pid = instr.ftiq_pid;
2473
2474 /*
2475 * Report an error if the process doesn't exist
2476 * or is actively being birthed.
2477 */
2478 if ((p = proc_find(pid)) == NULL || p->p_stat == SIDL) {
2479 if (p != PROC_NULL)
2480 proc_rele(p);
2481 return (ESRCH);
2482 }
2483 //proc_lock(p);
2484 // FIXME! How is this done on OS X?
2485 // if ((ret = priv_proc_cred_perm(cr, p, NULL,
2486 // VREAD)) != 0) {
2487 // mutex_exit(&p->p_lock);
2488 // return (ret);
2489 // }
2490 // proc_unlock(p);
2491 proc_rele(p);
2492 }
2493
2494 index = FASTTRAP_TPOINTS_INDEX(instr.ftiq_pid, instr.ftiq_pc);
2495
2496 lck_mtx_lock(&fasttrap_tpoints.fth_table[index].ftb_mtx);
2497 tp = fasttrap_tpoints.fth_table[index].ftb_data;
2498 while (tp != NULL) {
2499 if (instr.ftiq_pid == tp->ftt_pid &&
2500 instr.ftiq_pc == tp->ftt_pc &&
2501 tp->ftt_proc->ftpc_acount != 0)
2502 break;
2503
2504 tp = tp->ftt_next;
2505 }
2506
2507 if (tp == NULL) {
2508 lck_mtx_unlock(&fasttrap_tpoints.fth_table[index].ftb_mtx);
2509 return (ENOENT);
2510 }
2511
2512 bcopy(&tp->ftt_instr, &instr.ftiq_instr,
2513 sizeof (instr.ftiq_instr));
2514 lck_mtx_unlock(&fasttrap_tpoints.fth_table[index].ftb_mtx);
2515
2516 if (copyout(&instr, arg, sizeof (instr)) != 0)
2517 return (EFAULT);
2518
2519 return (0);
2520 }
2521
2522 return (EINVAL);
2523 }
2524
2525 static int
2526 fasttrap_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
2527 {
2528 ulong_t nent;
2529
2530 switch (cmd) {
2531 case DDI_ATTACH:
2532 break;
2533 case DDI_RESUME:
2534 return (DDI_SUCCESS);
2535 default:
2536 return (DDI_FAILURE);
2537 }
2538
2539 ddi_report_dev(devi);
2540 fasttrap_devi = devi;
2541
2542 /*
2543 * Install our hooks into fork(2), exec(2), and exit(2).
2544 */
2545 dtrace_fasttrap_fork_ptr = &fasttrap_fork;
2546 dtrace_fasttrap_exit_ptr = &fasttrap_exec_exit;
2547 dtrace_fasttrap_exec_ptr = &fasttrap_exec_exit;
2548
2549 /*
2550 * APPLE NOTE: We size the maximum number of fasttrap probes
2551 * based on system memory. 100k probes per 256M of system memory.
2552 * Yes, this is a WAG.
2553 */
2554 fasttrap_max = (sane_size >> 28) * 100000;
2555
2556 #if CONFIG_EMBEDDED
2557 #if defined(__LP64__)
2558 /*
2559 * On embedded, the zone map does not grow with the memory size over 1GB
2560 * (see osfmk/vm/vm_init.c)
2561 */
2562 if (fasttrap_max > 400000) {
2563 fasttrap_max = 400000;
2564 }
2565 #endif
2566 #endif
2567 if (fasttrap_max == 0)
2568 fasttrap_max = 50000;
2569
2570 fasttrap_total = 0;
2571 fasttrap_retired = 0;
2572
2573 /*
2574 * Conjure up the tracepoints hashtable...
2575 */
2576 nent = ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
2577 "fasttrap-hash-size", FASTTRAP_TPOINTS_DEFAULT_SIZE);
2578
2579 if (nent <= 0 || nent > 0x1000000)
2580 nent = FASTTRAP_TPOINTS_DEFAULT_SIZE;
2581
2582 if ((nent & (nent - 1)) == 0)
2583 fasttrap_tpoints.fth_nent = nent;
2584 else
2585 fasttrap_tpoints.fth_nent = 1 << fasttrap_highbit(nent);
2586 ASSERT(fasttrap_tpoints.fth_nent > 0);
2587 fasttrap_tpoints.fth_mask = fasttrap_tpoints.fth_nent - 1;
2588 fasttrap_tpoints.fth_table = kmem_zalloc(fasttrap_tpoints.fth_nent *
2589 sizeof (fasttrap_bucket_t), KM_SLEEP);
2590 ASSERT(fasttrap_tpoints.fth_table != NULL);
2591
2592 /*
2593 * APPLE NOTE: explicitly initialize all locks...
2594 */
2595 unsigned int i;
2596 for (i=0; i<fasttrap_tpoints.fth_nent; i++) {
2597 lck_mtx_init(&fasttrap_tpoints.fth_table[i].ftb_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
2598 }
2599
2600 /*
2601 * ... and the providers hash table...
2602 */
2603 nent = FASTTRAP_PROVIDERS_DEFAULT_SIZE;
2604 if ((nent & (nent - 1)) == 0)
2605 fasttrap_provs.fth_nent = nent;
2606 else
2607 fasttrap_provs.fth_nent = 1 << fasttrap_highbit(nent);
2608 ASSERT(fasttrap_provs.fth_nent > 0);
2609 fasttrap_provs.fth_mask = fasttrap_provs.fth_nent - 1;
2610 fasttrap_provs.fth_table = kmem_zalloc(fasttrap_provs.fth_nent *
2611 sizeof (fasttrap_bucket_t), KM_SLEEP);
2612 ASSERT(fasttrap_provs.fth_table != NULL);
2613
2614 /*
2615 * APPLE NOTE: explicitly initialize all locks...
2616 */
2617 for (i=0; i<fasttrap_provs.fth_nent; i++) {
2618 lck_mtx_init(&fasttrap_provs.fth_table[i].ftb_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
2619 }
2620
2621 /*
2622 * ... and the procs hash table.
2623 */
2624 nent = FASTTRAP_PROCS_DEFAULT_SIZE;
2625 if ((nent & (nent - 1)) == 0)
2626 fasttrap_procs.fth_nent = nent;
2627 else
2628 fasttrap_procs.fth_nent = 1 << fasttrap_highbit(nent);
2629 ASSERT(fasttrap_procs.fth_nent > 0);
2630 fasttrap_procs.fth_mask = fasttrap_procs.fth_nent - 1;
2631 fasttrap_procs.fth_table = kmem_zalloc(fasttrap_procs.fth_nent *
2632 sizeof (fasttrap_bucket_t), KM_SLEEP);
2633 ASSERT(fasttrap_procs.fth_table != NULL);
2634
2635 /*
2636 * APPLE NOTE: explicitly initialize all locks...
2637 */
2638 for (i=0; i<fasttrap_procs.fth_nent; i++) {
2639 lck_mtx_init(&fasttrap_procs.fth_table[i].ftb_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
2640 }
2641
2642 (void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
2643 &fasttrap_meta_id);
2644
2645 return (DDI_SUCCESS);
2646 }
2647
2648 static int
2649 _fasttrap_open(dev_t dev, int flags, int devtype, struct proc *p)
2650 {
2651 #pragma unused(dev, flags, devtype, p)
2652 return 0;
2653 }
2654
2655 static int
2656 _fasttrap_ioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct proc *p)
2657 {
2658 int err, rv = 0;
2659 user_addr_t uaddrp;
2660
2661 if (proc_is64bit(p))
2662 uaddrp = *(user_addr_t *)data;
2663 else
2664 uaddrp = (user_addr_t) *(uint32_t *)data;
2665
2666 err = fasttrap_ioctl(dev, cmd, uaddrp, fflag, CRED(), &rv);
2667
2668 /* XXX Darwin's BSD ioctls only return -1 or zero. Overload errno to mimic Solaris. 20 bits suffice. */
2669 if (err != 0) {
2670 ASSERT( (err & 0xfffff000) == 0 );
2671 return (err & 0xfff); /* ioctl returns -1 and errno set to an error code < 4096 */
2672 } else if (rv != 0) {
2673 ASSERT( (rv & 0xfff00000) == 0 );
2674 return (((rv & 0xfffff) << 12)); /* ioctl returns -1 and errno set to a return value >= 4096 */
2675 } else
2676 return 0;
2677 }
2678
2679 static int gFasttrapInited = 0;
2680
2681 #define FASTTRAP_MAJOR -24 /* let the kernel pick the device number */
2682
2683 /*
2684 * A struct describing which functions will get invoked for certain
2685 * actions.
2686 */
2687
2688 static struct cdevsw fasttrap_cdevsw =
2689 {
2690 _fasttrap_open, /* open */
2691 eno_opcl, /* close */
2692 eno_rdwrt, /* read */
2693 eno_rdwrt, /* write */
2694 _fasttrap_ioctl, /* ioctl */
2695 (stop_fcn_t *)nulldev, /* stop */
2696 (reset_fcn_t *)nulldev, /* reset */
2697 NULL, /* tty's */
2698 eno_select, /* select */
2699 eno_mmap, /* mmap */
2700 eno_strat, /* strategy */
2701 eno_getc, /* getc */
2702 eno_putc, /* putc */
2703 0 /* type */
2704 };
2705
2706 void fasttrap_init(void);
2707
2708 void
2709 fasttrap_init( void )
2710 {
2711 /*
2712 * This method is now invoked from multiple places. Any open of /dev/dtrace,
2713 * also dtrace_init if the dtrace_dof_mode is DTRACE_DOF_MODE_NON_LAZY.
2714 *
2715 * The reason is to delay allocating the (rather large) resources as late as possible.
2716 */
2717 if (0 == gFasttrapInited) {
2718 int majdevno = cdevsw_add(FASTTRAP_MAJOR, &fasttrap_cdevsw);
2719
2720 if (majdevno < 0) {
2721 // FIX ME! What kind of error reporting to do here?
2722 printf("fasttrap_init: failed to allocate a major number!\n");
2723 return;
2724 }
2725
2726 dev_t device = makedev( (uint32_t)majdevno, 0 );
2727 if (NULL == devfs_make_node( device, DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "fasttrap", 0 )) {
2728 return;
2729 }
2730
2731 /*
2732 * Allocate the fasttrap_tracepoint_t zone
2733 */
2734 fasttrap_tracepoint_t_zone = zinit(sizeof(fasttrap_tracepoint_t),
2735 1024 * sizeof(fasttrap_tracepoint_t),
2736 sizeof(fasttrap_tracepoint_t),
2737 "dtrace.fasttrap_tracepoint_t");
2738
2739 /*
2740 * fasttrap_probe_t's are variable in size. We use an array of zones to
2741 * cover the most common sizes.
2742 */
2743 int i;
2744 for (i=1; i<FASTTRAP_PROBE_T_ZONE_MAX_TRACEPOINTS; i++) {
2745 size_t zone_element_size = offsetof(fasttrap_probe_t, ftp_tps[i]);
2746 fasttrap_probe_t_zones[i] = zinit(zone_element_size,
2747 1024 * zone_element_size,
2748 zone_element_size,
2749 fasttrap_probe_t_zone_names[i]);
2750 }
2751
2752
2753 /*
2754 * Create the fasttrap lock group. Must be done before fasttrap_attach()!
2755 */
2756 fasttrap_lck_attr = lck_attr_alloc_init();
2757 fasttrap_lck_grp_attr= lck_grp_attr_alloc_init();
2758 fasttrap_lck_grp = lck_grp_alloc_init("fasttrap", fasttrap_lck_grp_attr);
2759
2760 /*
2761 * Initialize global locks
2762 */
2763 lck_mtx_init(&fasttrap_cleanup_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
2764 lck_mtx_init(&fasttrap_count_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
2765
2766 if (DDI_FAILURE == fasttrap_attach((dev_info_t *)(uintptr_t)device, 0 )) {
2767 // FIX ME! Do we remove the devfs node here?
2768 // What kind of error reporting?
2769 printf("fasttrap_init: Call to fasttrap_attach failed.\n");
2770 return;
2771 }
2772
2773 /*
2774 * Start the fasttrap cleanup thread
2775 */
2776 kern_return_t res = kernel_thread_start_priority((thread_continue_t)fasttrap_pid_cleanup_cb, NULL, 46 /* BASEPRI_BACKGROUND */, &fasttrap_cleanup_thread);
2777 if (res != KERN_SUCCESS) {
2778 panic("Could not create fasttrap_cleanup_thread");
2779 }
2780 thread_set_thread_name(fasttrap_cleanup_thread, "dtrace_fasttrap_cleanup_thread");
2781
2782 #ifdef FASTTRAP_ASYNC_REMOVE
2783 fasttrap_retired_size = DEFAULT_RETIRED_SIZE;
2784 fasttrap_retired_spec = kmem_zalloc(fasttrap_retired_size * sizeof(fasttrap_tracepoint_t*),
2785 KM_SLEEP);
2786 lck_mtx_init(&fasttrap_retired_mtx, fasttrap_lck_grp, fasttrap_lck_attr);
2787 #endif
2788
2789 gFasttrapInited = 1;
2790 }
2791 }
2792
2793 #undef FASTTRAP_MAJOR