xref: /titanic_41/usr/src/uts/common/dtrace/fasttrap.c (revision 8ad60789b9913d5b2118fe76d8cd7a661d8ae8b6)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/atomic.h>
31 #include <sys/errno.h>
32 #include <sys/stat.h>
33 #include <sys/modctl.h>
34 #include <sys/conf.h>
35 #include <sys/systm.h>
36 #include <sys/ddi.h>
37 #include <sys/sunddi.h>
38 #include <sys/cpuvar.h>
39 #include <sys/kmem.h>
40 #include <sys/strsubr.h>
41 #include <sys/fasttrap.h>
42 #include <sys/fasttrap_impl.h>
43 #include <sys/fasttrap_isa.h>
44 #include <sys/dtrace.h>
45 #include <sys/dtrace_impl.h>
46 #include <sys/sysmacros.h>
47 #include <sys/frame.h>
48 #include <sys/stack.h>
49 #include <sys/proc.h>
50 #include <sys/priv.h>
51 #include <sys/policy.h>
52 #include <sys/ontrap.h>
53 #include <sys/vmsystm.h>
54 #include <sys/prsystm.h>
55 
56 
57 #include <vm/as.h>
58 #include <vm/seg.h>
59 #include <vm/seg_dev.h>
60 #include <vm/seg_vn.h>
61 #include <vm/seg_spt.h>
62 #include <vm/seg_kmem.h>
63 
64 /*
65  * User-Land Trap-Based Tracing
66  * ----------------------------
67  *
68  * The fasttrap provider allows DTrace consumers to instrument any user-level
69  * instruction to gather data; this includes probes with semantic
70  * signifigance like entry and return as well as simple offsets into the
71  * function. While the specific techniques used are very ISA specific, the
72  * methodology is generalizable to any architecture.
73  *
74  *
75  * The General Methodology
76  * -----------------------
77  *
78  * With the primary goal of tracing every user-land instruction and the
79  * limitation that we can't trust user space so don't want to rely on much
80  * information there, we begin by replacing the instructions we want to trace
81  * with trap instructions. Each instruction we overwrite is saved into a hash
82  * table keyed by process ID and pc address. When we enter the kernel due to
83  * this trap instruction, we need the effects of the replaced instruction to
84  * appear to have occurred before we proceed with the user thread's
85  * execution.
86  *
87  * Each user level thread is represented by a ulwp_t structure which is
88  * always easily accessible through a register. The most basic way to produce
89  * the effects of the instruction we replaced is to copy that instruction out
90  * to a bit of scratch space reserved in the user thread's ulwp_t structure
91  * (a sort of kernel-private thread local storage), set the PC to that
92  * scratch space and single step. When we reenter the kernel after single
93  * stepping the instruction we must then adjust the PC to point to what would
94  * normally be the next instruction. Of course, special care must be taken
95  * for branches and jumps, but these represent such a small fraction of any
96  * instruction set that writing the code to emulate these in the kernel is
97  * not too difficult.
98  *
99  * Return probes may require several tracepoints to trace every return site,
100  * and, conversely, each tracepoint may activate several probes (the entry
101  * and offset 0 probes, for example). To solve this muliplexing problem,
102  * tracepoints contain lists of probes to activate and probes contain lists
103  * of tracepoints to enable. If a probe is activated, it adds its ID to
104  * existing tracepoints or creates new ones as necessary.
105  *
106  * Most probes are activated _before_ the instruction is executed, but return
107  * probes are activated _after_ the effects of the last instruction of the
108  * function are visible. Return probes must be fired _after_ we have
109  * single-stepped the instruction whereas all other probes are fired
110  * beforehand.
111  */
112 
113 static dev_info_t *fasttrap_devi;
114 static dtrace_provider_id_t fasttrap_id;
115 static dtrace_meta_provider_id_t fasttrap_meta_id;
116 
117 static timeout_id_t fasttrap_timeout;
118 static kmutex_t fasttrap_cleanup_mtx;
119 static uint_t fasttrap_cleanup_work;
120 
121 /*
122  * Generation count on modifications to the global tracepoint lookup table.
123  */
124 static volatile uint64_t fasttrap_mod_gen;
125 
126 /*
127  * When the fasttrap provider is loaded, fasttrap_max is set to either
128  * FASTTRAP_MAX_DEFAULT or the value for fasttrap-max-probes in the
129  * fasttrap.conf file. Each time a probe is created, fasttrap_total is
130  * incremented by the number of tracepoints that may be associated with that
131  * probe; fasttrap_total is capped at fasttrap_max.
132  */
133 #define	FASTTRAP_MAX_DEFAULT		250000
134 static uint32_t fasttrap_max;
135 static uint32_t fasttrap_total;
136 
137 
138 #define	FASTTRAP_TPOINTS_DEFAULT_SIZE	0x4000
139 #define	FASTTRAP_PROVIDERS_DEFAULT_SIZE	0x100
140 
141 #define	FASTTRAP_PID_NAME		"pid"
142 
143 fasttrap_hash_t			fasttrap_tpoints;
144 static fasttrap_hash_t		fasttrap_provs;
145 
146 dtrace_id_t			fasttrap_probe_id;
147 static int			fasttrap_count;		/* ref count */
148 static int			fasttrap_pid_count;	/* pid ref count */
149 static kmutex_t			fasttrap_count_mtx;	/* lock on ref count */
150 
151 #define	FASTTRAP_ENABLE_FAIL	1
152 #define	FASTTRAP_ENABLE_PARTIAL	2
153 
154 static int fasttrap_tracepoint_enable(proc_t *, fasttrap_probe_t *, uint_t);
155 static void fasttrap_tracepoint_disable(proc_t *, fasttrap_probe_t *, uint_t);
156 
157 static fasttrap_provider_t *fasttrap_provider_lookup(pid_t, const char *,
158     const dtrace_pattr_t *);
159 static void fasttrap_provider_free(fasttrap_provider_t *);
160 static void fasttrap_provider_retire(fasttrap_provider_t *);
161 
162 #define	FASTTRAP_PROVS_INDEX(pid, name) \
163 	((fasttrap_hash_str(name) + (pid)) & fasttrap_provs.fth_mask)
164 
165 static int
166 fasttrap_highbit(ulong_t i)
167 {
168 	int h = 1;
169 
170 	if (i == 0)
171 		return (0);
172 #ifdef _LP64
173 	if (i & 0xffffffff00000000ul) {
174 		h += 32; i >>= 32;
175 	}
176 #endif
177 	if (i & 0xffff0000) {
178 		h += 16; i >>= 16;
179 	}
180 	if (i & 0xff00) {
181 		h += 8; i >>= 8;
182 	}
183 	if (i & 0xf0) {
184 		h += 4; i >>= 4;
185 	}
186 	if (i & 0xc) {
187 		h += 2; i >>= 2;
188 	}
189 	if (i & 0x2) {
190 		h += 1;
191 	}
192 	return (h);
193 }
194 
195 static uint_t
196 fasttrap_hash_str(const char *p)
197 {
198 	unsigned int g;
199 	uint_t hval = 0;
200 
201 	while (*p) {
202 		hval = (hval << 4) + *p++;
203 		if ((g = (hval & 0xf0000000)) != 0)
204 			hval ^= g >> 24;
205 		hval &= ~g;
206 	}
207 	return (hval);
208 }
209 
210 void
211 fasttrap_sigtrap(proc_t *p, kthread_t *t, uintptr_t pc)
212 {
213 	sigqueue_t *sqp = kmem_zalloc(sizeof (sigqueue_t), KM_SLEEP);
214 
215 	sqp->sq_info.si_signo = SIGTRAP;
216 	sqp->sq_info.si_code = TRAP_DTRACE;
217 	sqp->sq_info.si_addr = (caddr_t)pc;
218 
219 	mutex_enter(&p->p_lock);
220 	sigaddqa(p, t, sqp);
221 	mutex_exit(&p->p_lock);
222 
223 	if (t != NULL)
224 		aston(t);
225 }
226 
227 /*
228  * This function ensures that no threads are actively using the memory
229  * associated with probes that were formerly live.
230  */
231 static void
232 fasttrap_mod_barrier(uint64_t gen)
233 {
234 	int i;
235 
236 	if (gen < fasttrap_mod_gen)
237 		return;
238 
239 	fasttrap_mod_gen++;
240 
241 	for (i = 0; i < NCPU; i++) {
242 		mutex_enter(&cpu_core[i].cpuc_pid_lock);
243 		mutex_exit(&cpu_core[i].cpuc_pid_lock);
244 	}
245 }
246 
247 /*
248  * This is the timeout's callback for cleaning up the providers and their
249  * probes.
250  */
251 /*ARGSUSED*/
252 static void
253 fasttrap_pid_cleanup_cb(void *data)
254 {
255 	fasttrap_provider_t **fpp, *fp;
256 	fasttrap_bucket_t *bucket;
257 	dtrace_provider_id_t provid;
258 	int i, later;
259 
260 	static volatile int in = 0;
261 	ASSERT(in == 0);
262 	in = 1;
263 
264 	mutex_enter(&fasttrap_cleanup_mtx);
265 	while (fasttrap_cleanup_work) {
266 		fasttrap_cleanup_work = 0;
267 		mutex_exit(&fasttrap_cleanup_mtx);
268 
269 		later = 0;
270 
271 		/*
272 		 * Iterate over all the providers trying to remove the marked
273 		 * ones.  If a provider is marked, but not defunct, we just
274 		 * have to take a crack at removing it -- it's no big deal if
275 		 * we can't.
276 		 */
277 		for (i = 0; i < fasttrap_provs.fth_nent; i++) {
278 			bucket = &fasttrap_provs.fth_table[i];
279 			mutex_enter(&bucket->ftb_mtx);
280 			fpp = (fasttrap_provider_t **)&bucket->ftb_data;
281 
282 			while ((fp = *fpp) != NULL) {
283 				if (!fp->ftp_marked) {
284 					fpp = &fp->ftp_next;
285 					continue;
286 				}
287 
288 				mutex_enter(&fp->ftp_mtx);
289 
290 				/*
291 				 * If this provider is referenced either
292 				 * because it is a USDT provider or is being
293 				 * modified, we can't unregister or even
294 				 * condense.
295 				 */
296 				if (fp->ftp_ccount != 0) {
297 					mutex_exit(&fp->ftp_mtx);
298 					fp->ftp_marked = 0;
299 					continue;
300 				}
301 
302 				if (!fp->ftp_defunct || fp->ftp_rcount != 0)
303 					fp->ftp_marked = 0;
304 
305 				mutex_exit(&fp->ftp_mtx);
306 
307 				/*
308 				 * If we successfully unregister this
309 				 * provider we can remove it from the hash
310 				 * chain and free the memory. If our attempt
311 				 * to unregister fails and this is a defunct
312 				 * provider, increment our flag to try again
313 				 * pretty soon. If we've consumed more than
314 				 * half of our total permitted number of
315 				 * probes call dtrace_condense() to try to
316 				 * clean out the unenabled probes.
317 				 */
318 				provid = fp->ftp_provid;
319 				if (dtrace_unregister(provid) != 0) {
320 					if (fasttrap_total > fasttrap_max / 2)
321 						(void) dtrace_condense(provid);
322 					later += fp->ftp_marked;
323 					fpp = &fp->ftp_next;
324 				} else {
325 					*fpp = fp->ftp_next;
326 					fasttrap_provider_free(fp);
327 				}
328 			}
329 			mutex_exit(&bucket->ftb_mtx);
330 		}
331 
332 		mutex_enter(&fasttrap_cleanup_mtx);
333 	}
334 
335 	ASSERT(fasttrap_timeout != 0);
336 
337 	/*
338 	 * If we were unable to remove a defunct provider, try again after
339 	 * a second. This situation can occur in certain circumstances where
340 	 * providers cannot be unregistered even though they have no probes
341 	 * enabled because of an execution of dtrace -l or something similar.
342 	 * If the timeout has been disabled (set to 1 because we're trying
343 	 * to detach), we set fasttrap_cleanup_work to ensure that we'll
344 	 * get a chance to do that work if and when the timeout is reenabled
345 	 * (if detach fails).
346 	 */
347 	if (later > 0 && fasttrap_timeout != (timeout_id_t)1)
348 		fasttrap_timeout = timeout(&fasttrap_pid_cleanup_cb, NULL, hz);
349 	else if (later > 0)
350 		fasttrap_cleanup_work = 1;
351 	else
352 		fasttrap_timeout = 0;
353 
354 	mutex_exit(&fasttrap_cleanup_mtx);
355 	in = 0;
356 }
357 
358 /*
359  * Activates the asynchronous cleanup mechanism.
360  */
361 static void
362 fasttrap_pid_cleanup(void)
363 {
364 	mutex_enter(&fasttrap_cleanup_mtx);
365 	fasttrap_cleanup_work = 1;
366 	if (fasttrap_timeout == 0)
367 		fasttrap_timeout = timeout(&fasttrap_pid_cleanup_cb, NULL, 1);
368 	mutex_exit(&fasttrap_cleanup_mtx);
369 }
370 
371 /*
372  * This is called from cfork() via dtrace_fasttrap_fork(). The child
373  * process's address space is a (roughly) a copy of the parent process's so
374  * we have to remove all the instrumentation we had previously enabled in the
375  * parent.
376  */
377 static void
378 fasttrap_fork(proc_t *p, proc_t *cp)
379 {
380 	pid_t ppid = p->p_pid;
381 	int i;
382 
383 	ASSERT(curproc == p);
384 	ASSERT(p->p_proc_flag & P_PR_LOCK);
385 	ASSERT(p->p_dtrace_count > 0);
386 	ASSERT(cp->p_dtrace_count == 0);
387 
388 	/*
389 	 * This would be simpler and faster if we maintained per-process
390 	 * hash tables of enabled tracepoints. It could, however, potentially
391 	 * slow down execution of a tracepoint since we'd need to go
392 	 * through two levels of indirection. In the future, we should
393 	 * consider either maintaining per-process ancillary lists of
394 	 * enabled tracepoints or hanging a pointer to a per-process hash
395 	 * table of enabled tracepoints off the proc structure.
396 	 */
397 
398 	/*
399 	 * We don't have to worry about the child process disappearing
400 	 * because we're in fork().
401 	 */
402 	mutex_enter(&cp->p_lock);
403 	sprlock_proc(cp);
404 	mutex_exit(&cp->p_lock);
405 
406 	/*
407 	 * Iterate over every tracepoint looking for ones that belong to the
408 	 * parent process, and remove each from the child process.
409 	 */
410 	for (i = 0; i < fasttrap_tpoints.fth_nent; i++) {
411 		fasttrap_tracepoint_t *tp;
412 		fasttrap_bucket_t *bucket = &fasttrap_tpoints.fth_table[i];
413 
414 		mutex_enter(&bucket->ftb_mtx);
415 		for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
416 			if (tp->ftt_pid == ppid && !tp->ftt_prov->ftp_defunct) {
417 				int ret = fasttrap_tracepoint_remove(cp, tp);
418 				ASSERT(ret == 0);
419 			}
420 		}
421 		mutex_exit(&bucket->ftb_mtx);
422 	}
423 
424 	mutex_enter(&cp->p_lock);
425 	sprunlock(cp);
426 }
427 
428 /*
429  * This is called from proc_exit() or from exec_common() if p_dtrace_probes
430  * is set on the proc structure to indicate that there is a pid provider
431  * associated with this process.
432  */
433 static void
434 fasttrap_exec_exit(proc_t *p)
435 {
436 	fasttrap_provider_t *provider;
437 
438 	ASSERT(p == curproc);
439 	ASSERT(MUTEX_HELD(&p->p_lock));
440 
441 	mutex_exit(&p->p_lock);
442 
443 	/*
444 	 * We clean up the pid provider for this process here; user-land
445 	 * static probes are handled by the meta-provider remove entry point.
446 	 */
447 	if ((provider = fasttrap_provider_lookup(p->p_pid,
448 	    FASTTRAP_PID_NAME, NULL)) != NULL)
449 		fasttrap_provider_retire(provider);
450 
451 	mutex_enter(&p->p_lock);
452 }
453 
454 
455 /*ARGSUSED*/
456 static void
457 fasttrap_pid_provide(void *arg, const dtrace_probedesc_t *desc)
458 {
459 	/*
460 	 * There are no "default" pid probes.
461 	 */
462 }
463 
464 /*ARGSUSED*/
465 static void
466 fasttrap_provide(void *arg, const dtrace_probedesc_t *desc)
467 {
468 	if (dtrace_probe_lookup(fasttrap_id, NULL, "fasttrap", "fasttrap") == 0)
469 		fasttrap_probe_id = dtrace_probe_create(fasttrap_id, NULL,
470 		    "fasttrap", "fasttrap", FASTTRAP_AFRAMES, NULL);
471 }
472 
473 static int
474 fasttrap_tracepoint_enable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
475 {
476 	fasttrap_tracepoint_t *tp, *new_tp = NULL;
477 	fasttrap_bucket_t *bucket;
478 	fasttrap_id_t *id;
479 	pid_t pid;
480 	uintptr_t pc;
481 
482 	ASSERT(index < probe->ftp_ntps);
483 
484 	pid = probe->ftp_pid;
485 	pc = probe->ftp_tps[index].fit_tp->ftt_pc;
486 	id = &probe->ftp_tps[index].fit_id;
487 
488 	ASSERT(probe->ftp_tps[index].fit_tp->ftt_pid == pid);
489 
490 	ASSERT(!(p->p_flag & SVFORK));
491 
492 	/*
493 	 * Before we make any modifications, make sure we've imposed a barrier
494 	 * on the generation in which this probe was last modified.
495 	 */
496 	fasttrap_mod_barrier(probe->ftp_gen);
497 
498 	bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
499 
500 	/*
501 	 * If the tracepoint has already been enabled, just add our id to the
502 	 * list of interested probes. This may be our second time through
503 	 * this path in which case we'll have constructed the tracepoint we'd
504 	 * like to install. If we can't find a match, and have an allocated
505 	 * tracepoint ready to go, enable that one now.
506 	 *
507 	 * Tracepoints whose provider is now defunct are also considered
508 	 * defunct.
509 	 */
510 again:
511 	mutex_enter(&bucket->ftb_mtx);
512 	for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
513 		if (tp->ftt_pid != pid || tp->ftt_pc != pc ||
514 		    tp->ftt_prov->ftp_defunct)
515 			continue;
516 
517 		/*
518 		 * Now that we've found a matching tracepoint, it would be
519 		 * a decent idea to confirm that the tracepoint is still
520 		 * enabled and the trap instruction hasn't been overwritten.
521 		 * Since this is a little hairy, we'll punt for now.
522 		 */
523 
524 		/*
525 		 * This can't be the first interested probe. We don't have
526 		 * to worry about another thread being in the midst of
527 		 * deleting this tracepoint (which would be the only valid
528 		 * reason for a tracepoint to have no interested probes)
529 		 * since we're holding P_PR_LOCK for this process.
530 		 */
531 		ASSERT(tp->ftt_ids != NULL || tp->ftt_retids != NULL);
532 
533 		if (probe->ftp_type == DTFTP_RETURN ||
534 		    probe->ftp_type == DTFTP_POST_OFFSETS) {
535 			id->fti_next = tp->ftt_retids;
536 			membar_producer();
537 			tp->ftt_retids = id;
538 			membar_producer();
539 		} else {
540 			id->fti_next = tp->ftt_ids;
541 			membar_producer();
542 			tp->ftt_ids = id;
543 			membar_producer();
544 		}
545 
546 		mutex_exit(&bucket->ftb_mtx);
547 
548 		if (new_tp != NULL) {
549 			new_tp->ftt_ids = NULL;
550 			new_tp->ftt_retids = NULL;
551 		}
552 
553 		return (0);
554 	}
555 
556 	/*
557 	 * If we have a good tracepoint ready to go, install it now while
558 	 * we have the lock held and no one can screw with us.
559 	 */
560 	if (new_tp != NULL) {
561 		int rc = 0;
562 
563 		new_tp->ftt_next = bucket->ftb_data;
564 		membar_producer();
565 		bucket->ftb_data = new_tp;
566 		membar_producer();
567 		mutex_exit(&bucket->ftb_mtx);
568 
569 		/*
570 		 * Activate the tracepoint in the ISA-specific manner.
571 		 * If this fails, we need to report the failure, but
572 		 * indicate that this tracepoint must still be disabled
573 		 * by calling fasttrap_tracepoint_disable().
574 		 */
575 		if (fasttrap_tracepoint_install(p, new_tp) != 0)
576 			rc = FASTTRAP_ENABLE_PARTIAL;
577 
578 		/*
579 		 * Increment the count of the number of tracepoints active in
580 		 * the victim process.
581 		 */
582 		ASSERT(p->p_proc_flag & P_PR_LOCK);
583 		p->p_dtrace_count++;
584 
585 		return (rc);
586 	}
587 
588 	mutex_exit(&bucket->ftb_mtx);
589 
590 	/*
591 	 * Initialize the tracepoint that's been preallocated with the probe.
592 	 */
593 	new_tp = probe->ftp_tps[index].fit_tp;
594 
595 	ASSERT(new_tp->ftt_pid == pid);
596 	ASSERT(new_tp->ftt_pc == pc);
597 	ASSERT(new_tp->ftt_prov == probe->ftp_prov);
598 	ASSERT(new_tp->ftt_ids == NULL);
599 	ASSERT(new_tp->ftt_retids == NULL);
600 
601 	if (probe->ftp_type == DTFTP_RETURN ||
602 	    probe->ftp_type == DTFTP_POST_OFFSETS) {
603 		id->fti_next = NULL;
604 		new_tp->ftt_retids = id;
605 	} else {
606 		id->fti_next = NULL;
607 		new_tp->ftt_ids = id;
608 	}
609 
610 	/*
611 	 * If the ISA-dependent initialization goes to plan, go back to the
612 	 * beginning and try to install this freshly made tracepoint.
613 	 */
614 	if (fasttrap_tracepoint_init(p, probe, new_tp, pc) == 0)
615 		goto again;
616 
617 	new_tp->ftt_ids = NULL;
618 	new_tp->ftt_retids = NULL;
619 
620 	return (FASTTRAP_ENABLE_FAIL);
621 }
622 
623 static void
624 fasttrap_tracepoint_disable(proc_t *p, fasttrap_probe_t *probe, uint_t index)
625 {
626 	fasttrap_bucket_t *bucket;
627 	fasttrap_provider_t *provider = probe->ftp_prov;
628 	fasttrap_tracepoint_t **pp, *tp;
629 	fasttrap_id_t *id, **idp;
630 	pid_t pid;
631 	uintptr_t pc;
632 
633 	ASSERT(index < probe->ftp_ntps);
634 
635 	pid = probe->ftp_pid;
636 	pc = probe->ftp_tps[index].fit_tp->ftt_pc;
637 
638 	ASSERT(probe->ftp_tps[index].fit_tp->ftt_pid == pid);
639 
640 	/*
641 	 * Find the tracepoint and make sure that our id is one of the
642 	 * ones registered with it.
643 	 */
644 	bucket = &fasttrap_tpoints.fth_table[FASTTRAP_TPOINTS_INDEX(pid, pc)];
645 	mutex_enter(&bucket->ftb_mtx);
646 	for (tp = bucket->ftb_data; tp != NULL; tp = tp->ftt_next) {
647 		if (tp->ftt_pid == pid && tp->ftt_pc == pc &&
648 		    tp->ftt_prov == provider)
649 			break;
650 	}
651 
652 	/*
653 	 * If we somehow lost this tracepoint, we're in a world of hurt.
654 	 */
655 	ASSERT(tp != NULL);
656 
657 	if (probe->ftp_type == DTFTP_RETURN ||
658 	    probe->ftp_type == DTFTP_POST_OFFSETS) {
659 		ASSERT(tp->ftt_retids != NULL);
660 		idp = &tp->ftt_retids;
661 	} else {
662 		ASSERT(tp->ftt_ids != NULL);
663 		idp = &tp->ftt_ids;
664 	}
665 
666 	while ((*idp)->fti_probe != probe) {
667 		idp = &(*idp)->fti_next;
668 		ASSERT(*idp != NULL);
669 	}
670 
671 	id = *idp;
672 	*idp = id->fti_next;
673 	membar_producer();
674 
675 	ASSERT(id->fti_probe == probe);
676 
677 	/*
678 	 * If there are other registered enablings of this tracepoint, we're
679 	 * all done, but if this was the last probe assocated with this
680 	 * this tracepoint, we need to remove and free it.
681 	 */
682 	if (tp->ftt_ids != NULL || tp->ftt_retids != NULL) {
683 
684 		/*
685 		 * If the current probe's tracepoint is in use, swap it
686 		 * for an unused tracepoint.
687 		 */
688 		if (tp == probe->ftp_tps[index].fit_tp) {
689 			fasttrap_probe_t *tmp_probe;
690 			fasttrap_tracepoint_t **tmp_tp;
691 			uint_t tmp_index;
692 
693 			if (tp->ftt_ids != NULL) {
694 				tmp_probe = tp->ftt_ids->fti_probe;
695 				tmp_index = FASTTRAP_ID_INDEX(tp->ftt_ids);
696 				tmp_tp = &tmp_probe->ftp_tps[tmp_index].fit_tp;
697 			} else {
698 				tmp_probe = tp->ftt_retids->fti_probe;
699 				tmp_index = FASTTRAP_ID_INDEX(tp->ftt_retids);
700 				tmp_tp = &tmp_probe->ftp_tps[tmp_index].fit_tp;
701 			}
702 
703 			ASSERT(*tmp_tp != NULL);
704 			ASSERT(*tmp_tp != probe->ftp_tps[index].fit_tp);
705 			ASSERT((*tmp_tp)->ftt_ids == NULL);
706 			ASSERT((*tmp_tp)->ftt_retids == NULL);
707 
708 			probe->ftp_tps[index].fit_tp = *tmp_tp;
709 			*tmp_tp = tp;
710 
711 		}
712 
713 		mutex_exit(&bucket->ftb_mtx);
714 
715 		/*
716 		 * Tag the modified probe with the generation in which it was
717 		 * changed.
718 		 */
719 		probe->ftp_gen = fasttrap_mod_gen;
720 		return;
721 	}
722 
723 	mutex_exit(&bucket->ftb_mtx);
724 
725 	/*
726 	 * We can't safely remove the tracepoint from the set of active
727 	 * tracepoints until we've actually removed the fasttrap instruction
728 	 * from the process's text. We can, however, operate on this
729 	 * tracepoint secure in the knowledge that no other thread is going to
730 	 * be looking at it since we hold P_PR_LOCK on the process if it's
731 	 * live or we hold the provider lock on the process if it's dead and
732 	 * gone.
733 	 */
734 
735 	/*
736 	 * We only need to remove the actual instruction if we're looking
737 	 * at an existing process
738 	 */
739 	if (p != NULL) {
740 		/*
741 		 * If we fail to restore the instruction we need to kill
742 		 * this process since it's in a completely unrecoverable
743 		 * state.
744 		 */
745 		if (fasttrap_tracepoint_remove(p, tp) != 0)
746 			fasttrap_sigtrap(p, NULL, pc);
747 
748 		/*
749 		 * Decrement the count of the number of tracepoints active
750 		 * in the victim process.
751 		 */
752 		ASSERT(p->p_proc_flag & P_PR_LOCK);
753 		p->p_dtrace_count--;
754 	}
755 
756 	/*
757 	 * Remove the probe from the hash table of active tracepoints.
758 	 */
759 	mutex_enter(&bucket->ftb_mtx);
760 	pp = (fasttrap_tracepoint_t **)&bucket->ftb_data;
761 	ASSERT(*pp != NULL);
762 	while (*pp != tp) {
763 		pp = &(*pp)->ftt_next;
764 		ASSERT(*pp != NULL);
765 	}
766 
767 	*pp = tp->ftt_next;
768 	membar_producer();
769 
770 	mutex_exit(&bucket->ftb_mtx);
771 
772 	/*
773 	 * Tag the modified probe with the generation in which it was changed.
774 	 */
775 	probe->ftp_gen = fasttrap_mod_gen;
776 }
777 
778 typedef int fasttrap_probe_f(struct regs *);
779 
780 static void
781 fasttrap_enable_common(int *count, fasttrap_probe_f **fptr, fasttrap_probe_f *f,
782     fasttrap_probe_f **fptr2, fasttrap_probe_f *f2)
783 {
784 	/*
785 	 * We don't have to play the rw lock game here because we're
786 	 * providing something rather than taking something away --
787 	 * we can be sure that no threads have tried to follow this
788 	 * function pointer yet.
789 	 */
790 	mutex_enter(&fasttrap_count_mtx);
791 	if (*count == 0) {
792 		ASSERT(*fptr == NULL);
793 		*fptr = f;
794 		if (fptr2 != NULL)
795 			*fptr2 = f2;
796 	}
797 	ASSERT(*fptr == f);
798 	ASSERT(fptr2 == NULL || *fptr2 == f2);
799 	(*count)++;
800 	mutex_exit(&fasttrap_count_mtx);
801 }
802 
803 static void
804 fasttrap_disable_common(int *count, fasttrap_probe_f **fptr,
805     fasttrap_probe_f **fptr2)
806 {
807 	ASSERT(MUTEX_HELD(&cpu_lock));
808 
809 	mutex_enter(&fasttrap_count_mtx);
810 	(*count)--;
811 	ASSERT(*count >= 0);
812 	if (*count == 0) {
813 		cpu_t *cur, *cpu = CPU;
814 
815 		for (cur = cpu->cpu_next_onln; cur != cpu;
816 			cur = cur->cpu_next_onln) {
817 			rw_enter(&cur->cpu_ft_lock, RW_WRITER);
818 		}
819 
820 		*fptr = NULL;
821 		if (fptr2 != NULL)
822 			*fptr2 = NULL;
823 
824 		for (cur = cpu->cpu_next_onln; cur != cpu;
825 			cur = cur->cpu_next_onln) {
826 			rw_exit(&cur->cpu_ft_lock);
827 		}
828 	}
829 	mutex_exit(&fasttrap_count_mtx);
830 }
831 
832 /*ARGSUSED*/
833 static void
834 fasttrap_enable(void *arg, dtrace_id_t id, void *parg)
835 {
836 	/*
837 	 * Enable the probe that corresponds to statically placed trace
838 	 * points which have not explicitly been placed in the process's text
839 	 * by the fasttrap provider.
840 	 */
841 	ASSERT(arg == NULL);
842 	ASSERT(id == fasttrap_probe_id);
843 
844 	fasttrap_enable_common(&fasttrap_count,
845 	    &dtrace_fasttrap_probe_ptr, fasttrap_probe, NULL, NULL);
846 }
847 
848 
849 /*ARGSUSED*/
850 static void
851 fasttrap_pid_enable(void *arg, dtrace_id_t id, void *parg)
852 {
853 	fasttrap_probe_t *probe = parg;
854 	proc_t *p;
855 	int i, rc;
856 
857 	ASSERT(probe != NULL);
858 	ASSERT(!probe->ftp_enabled);
859 	ASSERT(id == probe->ftp_id);
860 	ASSERT(MUTEX_HELD(&cpu_lock));
861 
862 	/*
863 	 * Increment the count of enabled probes on this probe's provider;
864 	 * the provider can't go away while the probe still exists. We
865 	 * must increment this even if we aren't able to properly enable
866 	 * this probe.
867 	 */
868 	mutex_enter(&probe->ftp_prov->ftp_mtx);
869 	probe->ftp_prov->ftp_rcount++;
870 	mutex_exit(&probe->ftp_prov->ftp_mtx);
871 
872 	/*
873 	 * Bail out if we can't find the process for this probe or its
874 	 * provider is defunct (meaning it was valid in a previously exec'ed
875 	 * incarnation of this address space). The provider can't go away
876 	 * while we're in this code path.
877 	 */
878 	if (probe->ftp_prov->ftp_defunct ||
879 	    (p = sprlock(probe->ftp_pid)) == NULL)
880 		return;
881 
882 	ASSERT(!(p->p_flag & SVFORK));
883 	mutex_exit(&p->p_lock);
884 
885 	/*
886 	 * We have to enable the trap entry before any user threads have
887 	 * the chance to execute the trap instruction we're about to place
888 	 * in their process's text.
889 	 */
890 	fasttrap_enable_common(&fasttrap_pid_count,
891 	    &dtrace_pid_probe_ptr, fasttrap_pid_probe,
892 	    &dtrace_return_probe_ptr, fasttrap_return_probe);
893 
894 	/*
895 	 * Enable all the tracepoints and add this probe's id to each
896 	 * tracepoint's list of active probes.
897 	 */
898 	for (i = 0; i < probe->ftp_ntps; i++) {
899 		if ((rc = fasttrap_tracepoint_enable(p, probe, i)) != 0) {
900 			/*
901 			 * If enabling the tracepoint failed completely,
902 			 * we don't have to disable it; if the failure
903 			 * was only partial we must disable it.
904 			 */
905 			if (rc == FASTTRAP_ENABLE_FAIL)
906 				i--;
907 			else
908 				ASSERT(rc == FASTTRAP_ENABLE_PARTIAL);
909 
910 			/*
911 			 * Back up and pull out all the tracepoints we've
912 			 * created so far for this probe.
913 			 */
914 			while (i-- >= 0) {
915 				fasttrap_tracepoint_disable(p, probe, i);
916 			}
917 
918 			mutex_enter(&p->p_lock);
919 			sprunlock(p);
920 
921 			/*
922 			 * Since we're not actually enabling this probe,
923 			 * drop our reference on the trap table entry.
924 			 */
925 			fasttrap_disable_common(&fasttrap_pid_count,
926 			    &dtrace_pid_probe_ptr, &dtrace_return_probe_ptr);
927 			return;
928 		}
929 	}
930 
931 	mutex_enter(&p->p_lock);
932 	sprunlock(p);
933 
934 	probe->ftp_enabled = 1;
935 }
936 
937 
938 /*ARGSUSED*/
939 static void
940 fasttrap_disable(void *arg, dtrace_id_t id, void *parg)
941 {
942 	/*
943 	 * Disable the probe the corresponds to statically placed trace
944 	 * points.
945 	 */
946 	ASSERT(arg == NULL);
947 	ASSERT(id == fasttrap_probe_id);
948 	ASSERT(MUTEX_HELD(&cpu_lock));
949 	fasttrap_disable_common(&fasttrap_count, &dtrace_fasttrap_probe_ptr,
950 	    NULL);
951 }
952 
953 /*ARGSUSED*/
954 static void
955 fasttrap_pid_disable(void *arg, dtrace_id_t id, void *parg)
956 {
957 	fasttrap_probe_t *probe = parg;
958 	fasttrap_provider_t *provider = probe->ftp_prov;
959 	proc_t *p;
960 	int i, whack = 0;
961 
962 	if (!probe->ftp_enabled) {
963 		mutex_enter(&provider->ftp_mtx);
964 		provider->ftp_rcount--;
965 		ASSERT(provider->ftp_rcount >= 0);
966 		mutex_exit(&provider->ftp_mtx);
967 		return;
968 	}
969 
970 	ASSERT(id == probe->ftp_id);
971 
972 	/*
973 	 * We won't be able to acquire a /proc-esque lock on the process
974 	 * iff the process is dead and gone. In this case, we rely on the
975 	 * provider lock as a point of mutual exclusion to prevent other
976 	 * DTrace consumers from disabling this probe.
977 	 */
978 	if ((p = sprlock(probe->ftp_pid)) != NULL) {
979 		ASSERT(!(p->p_flag & SVFORK));
980 		mutex_exit(&p->p_lock);
981 	}
982 
983 	mutex_enter(&provider->ftp_mtx);
984 
985 	/*
986 	 * Disable all the associated tracepoints.
987 	 */
988 	for (i = 0; i < probe->ftp_ntps; i++) {
989 		fasttrap_tracepoint_disable(p, probe, i);
990 	}
991 
992 	ASSERT(provider->ftp_rcount > 0);
993 	provider->ftp_rcount--;
994 
995 	if (p != NULL) {
996 		/*
997 		 * Even though we may not be able to remove it entirely, we
998 		 * mark this defunct provider to get a chance to remove some
999 		 * of the associated probes.
1000 		 */
1001 		if (provider->ftp_defunct && !provider->ftp_marked)
1002 			whack = provider->ftp_marked = 1;
1003 		mutex_exit(&provider->ftp_mtx);
1004 
1005 		mutex_enter(&p->p_lock);
1006 		sprunlock(p);
1007 	} else {
1008 		/*
1009 		 * If the process is dead, we're just waiting for the
1010 		 * last probe to be disabled to be able to free it.
1011 		 */
1012 		if (provider->ftp_rcount == 0 && !provider->ftp_marked)
1013 			whack = provider->ftp_marked = 1;
1014 		mutex_exit(&provider->ftp_mtx);
1015 	}
1016 
1017 	if (whack)
1018 		fasttrap_pid_cleanup();
1019 
1020 	probe->ftp_enabled = 0;
1021 
1022 	ASSERT(MUTEX_HELD(&cpu_lock));
1023 	fasttrap_disable_common(&fasttrap_pid_count, &dtrace_pid_probe_ptr,
1024 	    &dtrace_return_probe_ptr);
1025 }
1026 
1027 /*ARGSUSED*/
1028 static void
1029 fasttrap_pid_getargdesc(void *arg, dtrace_id_t id, void *parg,
1030     dtrace_argdesc_t *desc)
1031 {
1032 	fasttrap_probe_t *probe = parg;
1033 	char *str;
1034 	int i;
1035 
1036 	desc->dtargd_native[0] = '\0';
1037 	desc->dtargd_xlate[0] = '\0';
1038 
1039 	if (probe->ftp_prov->ftp_defunct != 0 ||
1040 	    desc->dtargd_ndx >= probe->ftp_nargs) {
1041 		desc->dtargd_ndx = DTRACE_ARGNONE;
1042 		return;
1043 	}
1044 
1045 	/*
1046 	 * We only need to set this member if the argument is remapped.
1047 	 */
1048 	if (probe->ftp_argmap != NULL)
1049 		desc->dtargd_mapping = probe->ftp_argmap[desc->dtargd_ndx];
1050 
1051 	str = probe->ftp_ntypes;
1052 	for (i = 0; i < desc->dtargd_mapping; i++) {
1053 		str += strlen(str) + 1;
1054 	}
1055 
1056 	ASSERT(strlen(str + 1) < sizeof (desc->dtargd_native));
1057 	(void) strcpy(desc->dtargd_native, str);
1058 
1059 	if (probe->ftp_xtypes == NULL)
1060 		return;
1061 
1062 	str = probe->ftp_xtypes;
1063 	for (i = 0; i < desc->dtargd_ndx; i++) {
1064 		str += strlen(str) + 1;
1065 	}
1066 
1067 	ASSERT(strlen(str + 1) < sizeof (desc->dtargd_xlate));
1068 	(void) strcpy(desc->dtargd_xlate, str);
1069 }
1070 
1071 /*ARGSUSED*/
1072 static void
1073 fasttrap_destroy(void *arg, dtrace_id_t id, void *parg)
1074 {
1075 	ASSERT(arg == NULL);
1076 	ASSERT(id == fasttrap_probe_id);
1077 }
1078 
1079 /*ARGSUSED*/
1080 static void
1081 fasttrap_pid_destroy(void *arg, dtrace_id_t id, void *parg)
1082 {
1083 	fasttrap_probe_t *probe = parg;
1084 	int i;
1085 	size_t size;
1086 
1087 	ASSERT(probe != NULL);
1088 	ASSERT(!probe->ftp_enabled);
1089 	ASSERT(fasttrap_total >= probe->ftp_ntps);
1090 
1091 	atomic_add_32(&fasttrap_total, -probe->ftp_ntps);
1092 	size = sizeof (fasttrap_probe_t) +
1093 	    sizeof (probe->ftp_tps[0]) * (probe->ftp_ntps - 1);
1094 
1095 	if (probe->ftp_gen + 1 >= fasttrap_mod_gen)
1096 		fasttrap_mod_barrier(probe->ftp_gen);
1097 
1098 	for (i = 0; i < probe->ftp_ntps; i++) {
1099 		kmem_free(probe->ftp_tps[i].fit_tp,
1100 		    sizeof (fasttrap_tracepoint_t));
1101 	}
1102 
1103 	kmem_free(probe, size);
1104 }
1105 
1106 
1107 static const dtrace_pattr_t fasttrap_attr = {
1108 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1109 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1110 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1111 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1112 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1113 };
1114 
1115 static dtrace_pops_t fasttrap_pops = {
1116 	fasttrap_provide,
1117 	NULL,
1118 	fasttrap_enable,
1119 	fasttrap_disable,
1120 	NULL,
1121 	NULL,
1122 	NULL,
1123 	fasttrap_getarg,
1124 	NULL,
1125 	fasttrap_destroy
1126 };
1127 
1128 static const dtrace_pattr_t pid_attr = {
1129 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1130 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1131 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1132 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1133 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1134 };
1135 
1136 static dtrace_pops_t pid_pops = {
1137 	fasttrap_pid_provide,
1138 	NULL,
1139 	fasttrap_pid_enable,
1140 	fasttrap_pid_disable,
1141 	NULL,
1142 	NULL,
1143 	fasttrap_pid_getargdesc,
1144 	fasttrap_getarg,
1145 	NULL,
1146 	fasttrap_pid_destroy
1147 };
1148 
1149 static dtrace_pops_t usdt_pops = {
1150 	fasttrap_pid_provide,
1151 	NULL,
1152 	fasttrap_pid_enable,
1153 	fasttrap_pid_disable,
1154 	NULL,
1155 	NULL,
1156 	fasttrap_pid_getargdesc,
1157 	fasttrap_usdt_getarg,
1158 	NULL,
1159 	fasttrap_pid_destroy
1160 };
1161 
1162 /*
1163  * Lookup a fasttrap-managed provider based on its name and associated pid.
1164  * If the pattr argument is non-NULL, this function instantiates the provider
1165  * if it doesn't exist otherwise it returns NULL. The provider is returned
1166  * with its lock held.
1167  */
1168 static fasttrap_provider_t *
1169 fasttrap_provider_lookup(pid_t pid, const char *name,
1170     const dtrace_pattr_t *pattr)
1171 {
1172 	fasttrap_provider_t *fp, *new_fp = NULL;
1173 	fasttrap_bucket_t *bucket;
1174 	char provname[DTRACE_PROVNAMELEN];
1175 	proc_t *p;
1176 	uid_t uid = (uid_t)-1;
1177 
1178 	ASSERT(strlen(name) < sizeof (fp->ftp_name));
1179 
1180 	bucket = &fasttrap_provs.fth_table[FASTTRAP_PROVS_INDEX(pid, name)];
1181 	mutex_enter(&bucket->ftb_mtx);
1182 
1183 	/*
1184 	 * Take a lap through the list and return the match if we find it.
1185 	 */
1186 	for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1187 		if (fp->ftp_pid == pid && strcmp(fp->ftp_name, name) == 0 &&
1188 		    !fp->ftp_defunct) {
1189 			mutex_enter(&fp->ftp_mtx);
1190 			mutex_exit(&bucket->ftb_mtx);
1191 			return (fp);
1192 		}
1193 	}
1194 
1195 	/*
1196 	 * Drop the bucket lock so we don't try to perform a sleeping
1197 	 * allocation under it.
1198 	 */
1199 	mutex_exit(&bucket->ftb_mtx);
1200 
1201 	if (pattr == NULL)
1202 		return (NULL);
1203 
1204 	/*
1205 	 * Make sure the process exists, isn't a child created as the result
1206 	 * of a vfork(2), and isn't a zombie (but may be in fork). Record the
1207 	 * process's uid to pass to dtrace_register().
1208 	 */
1209 	mutex_enter(&pidlock);
1210 	if ((p = prfind(pid)) == NULL) {
1211 		mutex_exit(&pidlock);
1212 		return (NULL);
1213 	}
1214 	mutex_enter(&p->p_lock);
1215 	mutex_exit(&pidlock);
1216 	if (p->p_flag & (SVFORK | SEXITING)) {
1217 		mutex_exit(&p->p_lock);
1218 		return (NULL);
1219 	}
1220 
1221 	/*
1222 	 * Increment p_dtrace_probes so that the process knows to inform us
1223 	 * when it exits or execs. fasttrap_provider_free() decrements this
1224 	 * when we're done with this provider.
1225 	 */
1226 	p->p_dtrace_probes++;
1227 
1228 	mutex_enter(&p->p_crlock);
1229 	uid = crgetruid(p->p_cred);
1230 	mutex_exit(&p->p_crlock);
1231 	mutex_exit(&p->p_lock);
1232 
1233 	new_fp = kmem_zalloc(sizeof (fasttrap_provider_t), KM_SLEEP);
1234 
1235 	mutex_enter(&bucket->ftb_mtx);
1236 
1237 	/*
1238 	 * Take another lap through the list to make sure a provider hasn't
1239 	 * been created for this pid while we weren't under the bucket lock.
1240 	 */
1241 	for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1242 		if (fp->ftp_pid == pid && strcmp(fp->ftp_name, name) == 0 &&
1243 		    !fp->ftp_defunct) {
1244 			mutex_enter(&fp->ftp_mtx);
1245 			mutex_exit(&bucket->ftb_mtx);
1246 			fasttrap_provider_free(new_fp);
1247 			return (fp);
1248 		}
1249 	}
1250 
1251 	new_fp->ftp_pid = pid;
1252 	(void) strcpy(new_fp->ftp_name, name);
1253 
1254 	/*
1255 	 * Fail and return NULL if either the provider name is too long
1256 	 * or we fail to register this new provider with the DTrace
1257 	 * framework. Note that this is the only place we ever construct
1258 	 * the full provider name -- we keep it in pieces in the provider
1259 	 * structure.
1260 	 */
1261 	if (snprintf(provname, sizeof (provname), "%s%u", name, (uint_t)pid) >=
1262 	    sizeof (provname) ||
1263 	    dtrace_register(provname, pattr,
1264 	    DTRACE_PRIV_PROC | DTRACE_PRIV_OWNER, uid,
1265 	    pattr == &pid_attr ? &pid_pops : &usdt_pops, new_fp,
1266 	    &new_fp->ftp_provid) != 0) {
1267 		mutex_exit(&bucket->ftb_mtx);
1268 		fasttrap_provider_free(new_fp);
1269 		return (NULL);
1270 	}
1271 
1272 	new_fp->ftp_next = bucket->ftb_data;
1273 	bucket->ftb_data = new_fp;
1274 
1275 	mutex_enter(&new_fp->ftp_mtx);
1276 	mutex_exit(&bucket->ftb_mtx);
1277 
1278 	return (new_fp);
1279 }
1280 
1281 static void
1282 fasttrap_provider_free(fasttrap_provider_t *provider)
1283 {
1284 	pid_t pid = provider->ftp_pid;
1285 	proc_t *p;
1286 
1287 	/*
1288 	 * There need to be no consumers using this provider and no
1289 	 * associated enabled probes.
1290 	 */
1291 	ASSERT(provider->ftp_ccount == 0);
1292 	ASSERT(provider->ftp_rcount == 0);
1293 
1294 	kmem_free(provider, sizeof (fasttrap_provider_t));
1295 
1296 	/*
1297 	 * Decrement p_dtrace_probes on the process whose provider we're
1298 	 * freeing. We don't have to worry about clobbering somone else's
1299 	 * modifications to it because we have locked the bucket that
1300 	 * corresponds to this process's hash chain in the provider hash
1301 	 * table. Don't sweat it if we can't find the process.
1302 	 */
1303 	mutex_enter(&pidlock);
1304 	if ((p = prfind(pid)) == NULL) {
1305 		mutex_exit(&pidlock);
1306 		return;
1307 	}
1308 
1309 	mutex_enter(&p->p_lock);
1310 	mutex_exit(&pidlock);
1311 
1312 	p->p_dtrace_probes--;
1313 	mutex_exit(&p->p_lock);
1314 }
1315 
1316 static void
1317 fasttrap_provider_retire(fasttrap_provider_t *provider)
1318 {
1319 	dtrace_provider_id_t provid = provider->ftp_provid;
1320 
1321 	/*
1322 	 * Mark the provider to be removed in our post-processing step
1323 	 * and mark it as defunct. The former indicates that we should try
1324 	 * to remove it, the latter indicates that even if we were unable
1325 	 * to remove it, this provider shouldn't be used to create probes
1326 	 * in the future.
1327 	 */
1328 	provider->ftp_defunct = 1;
1329 	provider->ftp_marked = 1;
1330 	mutex_exit(&provider->ftp_mtx);
1331 
1332 	/*
1333 	 * We don't have to worry about invalidating the same provider twice
1334 	 * since fasttrap_provider_lookup() will ignore provider that have
1335 	 * been marked as defunct.
1336 	 */
1337 	dtrace_invalidate(provid);
1338 
1339 	fasttrap_pid_cleanup();
1340 }
1341 
1342 static int
1343 fasttrap_add_probe(fasttrap_probe_spec_t *pdata)
1344 {
1345 	fasttrap_provider_t *provider;
1346 	fasttrap_probe_t *pp;
1347 	fasttrap_tracepoint_t *tp;
1348 	char *name;
1349 	size_t size;
1350 	int i, aframes, whack;
1351 
1352 	switch (pdata->ftps_type) {
1353 	case DTFTP_ENTRY:
1354 		name = "entry";
1355 		aframes = FASTTRAP_ENTRY_AFRAMES;
1356 		break;
1357 	case DTFTP_RETURN:
1358 		name = "return";
1359 		aframes = FASTTRAP_RETURN_AFRAMES;
1360 		break;
1361 	case DTFTP_OFFSETS:
1362 		name = NULL;
1363 		break;
1364 	default:
1365 		return (EINVAL);
1366 	}
1367 
1368 	if ((provider = fasttrap_provider_lookup(pdata->ftps_pid,
1369 	    FASTTRAP_PID_NAME, &pid_attr)) == NULL)
1370 		return (ESRCH);
1371 
1372 	/*
1373 	 * Increment this reference count to indicate that a consumer is
1374 	 * actively adding a new probe associated with this provider.
1375 	 */
1376 	provider->ftp_ccount++;
1377 	mutex_exit(&provider->ftp_mtx);
1378 
1379 	if (name != NULL) {
1380 		if (dtrace_probe_lookup(provider->ftp_provid,
1381 		    pdata->ftps_mod, pdata->ftps_func, name) != 0)
1382 			goto done;
1383 
1384 		atomic_add_32(&fasttrap_total, pdata->ftps_noffs);
1385 
1386 		if (fasttrap_total > fasttrap_max) {
1387 			atomic_add_32(&fasttrap_total, -pdata->ftps_noffs);
1388 			goto no_mem;
1389 		}
1390 
1391 		ASSERT(pdata->ftps_noffs > 0);
1392 		size = sizeof (fasttrap_probe_t) +
1393 		    sizeof (pp->ftp_tps[0]) * (pdata->ftps_noffs - 1);
1394 
1395 		pp = kmem_zalloc(size, KM_SLEEP);
1396 
1397 		pp->ftp_prov = provider;
1398 		pp->ftp_faddr = pdata->ftps_pc;
1399 		pp->ftp_fsize = pdata->ftps_size;
1400 		pp->ftp_pid = pdata->ftps_pid;
1401 		pp->ftp_ntps = pdata->ftps_noffs;
1402 		pp->ftp_type = pdata->ftps_type;
1403 
1404 		for (i = 0; i < pdata->ftps_noffs; i++) {
1405 			tp = kmem_zalloc(sizeof (fasttrap_tracepoint_t),
1406 			    KM_SLEEP);
1407 
1408 			tp->ftt_prov = provider;
1409 			tp->ftt_pc = pdata->ftps_offs[i] + pdata->ftps_pc;
1410 			tp->ftt_pid = pdata->ftps_pid;
1411 
1412 			pp->ftp_tps[i].fit_tp = tp;
1413 			pp->ftp_tps[i].fit_id.fti_probe = pp;
1414 		}
1415 
1416 		pp->ftp_id = dtrace_probe_create(provider->ftp_provid,
1417 		    pdata->ftps_mod, pdata->ftps_func, name, aframes, pp);
1418 	} else {
1419 		for (i = 0; i < pdata->ftps_noffs; i++) {
1420 			char name_str[17];
1421 
1422 			(void) sprintf(name_str, "%llx",
1423 			    (unsigned long long)pdata->ftps_offs[i]);
1424 
1425 			if (dtrace_probe_lookup(provider->ftp_provid,
1426 			    pdata->ftps_mod, pdata->ftps_func, name_str) != 0)
1427 				continue;
1428 
1429 			atomic_add_32(&fasttrap_total, 1);
1430 
1431 			if (fasttrap_total > fasttrap_max) {
1432 				atomic_add_32(&fasttrap_total, -1);
1433 				goto no_mem;
1434 			}
1435 
1436 			pp = kmem_zalloc(sizeof (fasttrap_probe_t), KM_SLEEP);
1437 
1438 			pp->ftp_prov = provider;
1439 			pp->ftp_faddr = pdata->ftps_pc;
1440 			pp->ftp_fsize = pdata->ftps_size;
1441 			pp->ftp_pid = pdata->ftps_pid;
1442 			pp->ftp_ntps = 1;
1443 			pp->ftp_type = pdata->ftps_type;
1444 
1445 			tp = kmem_zalloc(sizeof (fasttrap_tracepoint_t),
1446 			    KM_SLEEP);
1447 
1448 			tp->ftt_prov = provider;
1449 			tp->ftt_pc = pdata->ftps_offs[i] + pdata->ftps_pc;
1450 			tp->ftt_pid = pdata->ftps_pid;
1451 
1452 			pp->ftp_tps[0].fit_tp = tp;
1453 			pp->ftp_tps[0].fit_id.fti_probe = pp;
1454 
1455 			pp->ftp_id = dtrace_probe_create(provider->ftp_provid,
1456 			    pdata->ftps_mod, pdata->ftps_func, name_str,
1457 			    FASTTRAP_OFFSET_AFRAMES, pp);
1458 		}
1459 	}
1460 
1461 done:
1462 	/*
1463 	 * We know that the provider is still valid since we incremented the
1464 	 * reference count. If someone tried to free this provider while we
1465 	 * were using it (e.g. because the process called exec(2) or exit(2)),
1466 	 * take note of that and try to free it now.
1467 	 */
1468 	mutex_enter(&provider->ftp_mtx);
1469 	provider->ftp_ccount--;
1470 	whack = provider->ftp_defunct;
1471 	mutex_exit(&provider->ftp_mtx);
1472 
1473 	if (whack)
1474 		fasttrap_pid_cleanup();
1475 
1476 	return (0);
1477 
1478 no_mem:
1479 	/*
1480 	 * If we've exhausted the allowable resources, we'll try to remove
1481 	 * this provider to free some up. This is to cover the case where
1482 	 * the user has accidentally created many more probes than was
1483 	 * intended (e.g. pid123:::).
1484 	 */
1485 	mutex_enter(&provider->ftp_mtx);
1486 	provider->ftp_ccount--;
1487 	provider->ftp_marked = 1;
1488 	mutex_exit(&provider->ftp_mtx);
1489 
1490 	fasttrap_pid_cleanup();
1491 
1492 	return (ENOMEM);
1493 }
1494 
1495 /*ARGSUSED*/
1496 static void *
1497 fasttrap_meta_provide(void *arg, dtrace_helper_provdesc_t *dhpv, pid_t pid)
1498 {
1499 	fasttrap_provider_t *provider;
1500 
1501 	/*
1502 	 * A 32-bit unsigned integer (like a pid for example) can be
1503 	 * expressed in 10 or fewer decimal digits. Make sure that we'll
1504 	 * have enough space for the provider name.
1505 	 */
1506 	if (strlen(dhpv->dthpv_provname) + 10 >=
1507 	    sizeof (provider->ftp_name)) {
1508 		cmn_err(CE_WARN, "failed to instantiate provider %s: "
1509 		    "name too long to accomodate pid", dhpv->dthpv_provname);
1510 		return (NULL);
1511 	}
1512 
1513 	/*
1514 	 * Don't let folks spoof the true pid provider.
1515 	 */
1516 	if (strcmp(dhpv->dthpv_provname, FASTTRAP_PID_NAME) == 0) {
1517 		cmn_err(CE_WARN, "failed to instantiate provider %s: "
1518 		    "%s is an invalid name", dhpv->dthpv_provname,
1519 		    FASTTRAP_PID_NAME);
1520 		return (NULL);
1521 	}
1522 
1523 	/*
1524 	 * The highest stability class that fasttrap supports is ISA; cap
1525 	 * the stability of the new provider accordingly.
1526 	 */
1527 	if (dhpv->dthpv_pattr.dtpa_provider.dtat_class >= DTRACE_CLASS_COMMON)
1528 		dhpv->dthpv_pattr.dtpa_provider.dtat_class = DTRACE_CLASS_ISA;
1529 	if (dhpv->dthpv_pattr.dtpa_mod.dtat_class >= DTRACE_CLASS_COMMON)
1530 		dhpv->dthpv_pattr.dtpa_mod.dtat_class = DTRACE_CLASS_ISA;
1531 	if (dhpv->dthpv_pattr.dtpa_func.dtat_class >= DTRACE_CLASS_COMMON)
1532 		dhpv->dthpv_pattr.dtpa_func.dtat_class = DTRACE_CLASS_ISA;
1533 	if (dhpv->dthpv_pattr.dtpa_name.dtat_class >= DTRACE_CLASS_COMMON)
1534 		dhpv->dthpv_pattr.dtpa_name.dtat_class = DTRACE_CLASS_ISA;
1535 	if (dhpv->dthpv_pattr.dtpa_args.dtat_class >= DTRACE_CLASS_COMMON)
1536 		dhpv->dthpv_pattr.dtpa_args.dtat_class = DTRACE_CLASS_ISA;
1537 
1538 	if ((provider = fasttrap_provider_lookup(pid, dhpv->dthpv_provname,
1539 	    &dhpv->dthpv_pattr)) == NULL) {
1540 		cmn_err(CE_WARN, "failed to instantiate provider %s for "
1541 		    "process %u",  dhpv->dthpv_provname, (uint_t)pid);
1542 		return (NULL);
1543 	}
1544 
1545 	/*
1546 	 * We elevate the consumer count here to ensure that this provider
1547 	 * isn't removed until after the meta provider has been told to
1548 	 * remove it.
1549 	 */
1550 	provider->ftp_ccount++;
1551 
1552 	mutex_exit(&provider->ftp_mtx);
1553 
1554 	return (provider);
1555 }
1556 
1557 /*ARGSUSED*/
1558 static void
1559 fasttrap_meta_create_probe(void *arg, void *parg,
1560     dtrace_helper_probedesc_t *dhpb)
1561 {
1562 	fasttrap_provider_t *provider = parg;
1563 	fasttrap_probe_t *pp;
1564 	fasttrap_tracepoint_t *tp;
1565 	size_t size;
1566 	int i;
1567 
1568 	mutex_enter(&provider->ftp_mtx);
1569 
1570 	if (dtrace_probe_lookup(provider->ftp_provid, dhpb->dthpb_mod,
1571 	    dhpb->dthpb_func, dhpb->dthpb_name) != 0) {
1572 		mutex_exit(&provider->ftp_mtx);
1573 		return;
1574 	}
1575 
1576 	atomic_add_32(&fasttrap_total, dhpb->dthpb_noffs);
1577 
1578 	if (fasttrap_total > fasttrap_max) {
1579 		atomic_add_32(&fasttrap_total, -dhpb->dthpb_noffs);
1580 		mutex_exit(&provider->ftp_mtx);
1581 		return;
1582 	}
1583 
1584 	size = sizeof (fasttrap_probe_t) +
1585 	    sizeof (pp->ftp_tps[0]) * (dhpb->dthpb_noffs - 1);
1586 	pp = kmem_zalloc(size, KM_SLEEP);
1587 
1588 	pp->ftp_prov = provider;
1589 	pp->ftp_pid = provider->ftp_pid;
1590 	pp->ftp_ntps = dhpb->dthpb_noffs;
1591 #ifdef __sparc
1592 	pp->ftp_type = DTFTP_POST_OFFSETS;
1593 #else
1594 	pp->ftp_type = DTFTP_OFFSETS;
1595 #endif
1596 	pp->ftp_nargs = dhpb->dthpb_xargc;
1597 	pp->ftp_xtypes = dhpb->dthpb_xtypes;
1598 	pp->ftp_ntypes = dhpb->dthpb_ntypes;
1599 
1600 	for (i = 0; i < pp->ftp_ntps; i++) {
1601 		tp = kmem_zalloc(sizeof (fasttrap_tracepoint_t), KM_SLEEP);
1602 
1603 		tp->ftt_prov = provider;
1604 		tp->ftt_pc = dhpb->dthpb_base + dhpb->dthpb_offs[i];
1605 		tp->ftt_pid = provider->ftp_pid;
1606 
1607 		pp->ftp_tps[i].fit_tp = tp;
1608 		pp->ftp_tps[i].fit_id.fti_probe = pp;
1609 	}
1610 
1611 	/*
1612 	 * If the arguments are shuffled around we set the argument remapping
1613 	 * table. Later, when the probe fires, we only remap the arguments
1614 	 * if the table is non-NULL.
1615 	 */
1616 	for (i = 0; i < dhpb->dthpb_xargc; i++) {
1617 		if (dhpb->dthpb_args[i] != i) {
1618 			pp->ftp_argmap = dhpb->dthpb_args;
1619 			break;
1620 		}
1621 	}
1622 
1623 	/*
1624 	 * The probe is fully constructed -- register it with DTrace.
1625 	 */
1626 	pp->ftp_id = dtrace_probe_create(provider->ftp_provid, dhpb->dthpb_mod,
1627 	    dhpb->dthpb_func, dhpb->dthpb_name, FASTTRAP_OFFSET_AFRAMES, pp);
1628 
1629 	mutex_exit(&provider->ftp_mtx);
1630 }
1631 
1632 /*ARGSUSED*/
1633 static void
1634 fasttrap_meta_remove(void *arg, dtrace_helper_provdesc_t *dhpv, pid_t pid)
1635 {
1636 	fasttrap_provider_t *provider;
1637 
1638 	if ((provider = fasttrap_provider_lookup(pid,
1639 	    dhpv->dthpv_provname, NULL)) != NULL) {
1640 		/*
1641 		 * Drop the consumer count now that we're done with this
1642 		 * provider. If there are no other consumers retire it now.
1643 		 */
1644 		if (--provider->ftp_ccount == 0)
1645 			fasttrap_provider_retire(provider);
1646 		else
1647 			mutex_exit(&provider->ftp_mtx);
1648 	}
1649 }
1650 
1651 static dtrace_mops_t fasttrap_mops = {
1652 	fasttrap_meta_create_probe,
1653 	fasttrap_meta_provide,
1654 	fasttrap_meta_remove
1655 };
1656 
1657 /*ARGSUSED*/
1658 static int
1659 fasttrap_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
1660 {
1661 	return (0);
1662 }
1663 
1664 /*ARGSUSED*/
1665 static int
1666 fasttrap_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
1667 {
1668 	if (!dtrace_attached())
1669 		return (EAGAIN);
1670 
1671 	if (cmd == FASTTRAPIOC_MAKEPROBE) {
1672 		fasttrap_probe_spec_t *uprobe = (void *)arg;
1673 		fasttrap_probe_spec_t *probe;
1674 		uint64_t noffs;
1675 		size_t size;
1676 		int ret;
1677 		char *c;
1678 
1679 		if (copyin(&uprobe->ftps_noffs, &noffs,
1680 		    sizeof (uprobe->ftps_noffs)))
1681 			return (EFAULT);
1682 
1683 		/*
1684 		 * Probes must have at least one tracepoint.
1685 		 */
1686 		if (noffs == 0)
1687 			return (EINVAL);
1688 
1689 		size = sizeof (fasttrap_probe_spec_t) +
1690 		    sizeof (probe->ftps_offs[0]) * (noffs - 1);
1691 
1692 		if (size > 1024 * 1024)
1693 			return (ENOMEM);
1694 
1695 		probe = kmem_alloc(size, KM_SLEEP);
1696 
1697 		if (copyin(uprobe, probe, size) != 0) {
1698 			kmem_free(probe, size);
1699 			return (EFAULT);
1700 		}
1701 
1702 		/*
1703 		 * Verify that the function and module strings contain no
1704 		 * funny characters.
1705 		 */
1706 		for (c = &probe->ftps_func[0]; *c != '\0'; c++) {
1707 			if (*c < 0x20 || 0x7f <= *c) {
1708 				ret = EINVAL;
1709 				goto err;
1710 			}
1711 		}
1712 
1713 		for (c = &probe->ftps_mod[0]; *c != '\0'; c++) {
1714 			if (*c < 0x20 || 0x7f <= *c) {
1715 				ret = EINVAL;
1716 				goto err;
1717 			}
1718 		}
1719 
1720 		if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
1721 			proc_t *p;
1722 			pid_t pid = probe->ftps_pid;
1723 
1724 			mutex_enter(&pidlock);
1725 			/*
1726 			 * Report an error if the process doesn't exist
1727 			 * or is actively being birthed.
1728 			 */
1729 			if ((p = prfind(pid)) == NULL || p->p_stat == SIDL) {
1730 				mutex_exit(&pidlock);
1731 				return (ESRCH);
1732 			}
1733 			mutex_enter(&p->p_lock);
1734 			mutex_exit(&pidlock);
1735 
1736 			if ((ret = priv_proc_cred_perm(cr, p, NULL,
1737 			    VREAD | VWRITE)) != 0) {
1738 				mutex_exit(&p->p_lock);
1739 				return (ret);
1740 			}
1741 
1742 			mutex_exit(&p->p_lock);
1743 		}
1744 
1745 		ret = fasttrap_add_probe(probe);
1746 err:
1747 		kmem_free(probe, size);
1748 
1749 		return (ret);
1750 
1751 	} else if (cmd == FASTTRAPIOC_GETINSTR) {
1752 		fasttrap_instr_query_t instr;
1753 		fasttrap_tracepoint_t *tp;
1754 		uint_t index;
1755 		int ret;
1756 
1757 		if (copyin((void *)arg, &instr, sizeof (instr)) != 0)
1758 			return (EFAULT);
1759 
1760 		if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
1761 			proc_t *p;
1762 			pid_t pid = instr.ftiq_pid;
1763 
1764 			mutex_enter(&pidlock);
1765 			/*
1766 			 * Report an error if the process doesn't exist
1767 			 * or is actively being birthed.
1768 			 */
1769 			if ((p = prfind(pid)) == NULL || p->p_stat == SIDL) {
1770 				mutex_exit(&pidlock);
1771 				return (ESRCH);
1772 			}
1773 			mutex_enter(&p->p_lock);
1774 			mutex_exit(&pidlock);
1775 
1776 			if ((ret = priv_proc_cred_perm(cr, p, NULL,
1777 			    VREAD)) != 0) {
1778 				mutex_exit(&p->p_lock);
1779 				return (ret);
1780 			}
1781 
1782 			mutex_exit(&p->p_lock);
1783 		}
1784 
1785 		index = FASTTRAP_TPOINTS_INDEX(instr.ftiq_pid, instr.ftiq_pc);
1786 
1787 		mutex_enter(&fasttrap_tpoints.fth_table[index].ftb_mtx);
1788 		tp = fasttrap_tpoints.fth_table[index].ftb_data;
1789 		while (tp != NULL) {
1790 			if (instr.ftiq_pid == tp->ftt_pid &&
1791 			    instr.ftiq_pc == tp->ftt_pc &&
1792 			    !tp->ftt_prov->ftp_defunct)
1793 				break;
1794 
1795 			tp = tp->ftt_next;
1796 		}
1797 
1798 		if (tp == NULL) {
1799 			mutex_exit(&fasttrap_tpoints.fth_table[index].ftb_mtx);
1800 			return (ENOENT);
1801 		}
1802 
1803 		bcopy(&tp->ftt_instr, &instr.ftiq_instr,
1804 		    sizeof (instr.ftiq_instr));
1805 		mutex_exit(&fasttrap_tpoints.fth_table[index].ftb_mtx);
1806 
1807 		if (copyout(&instr, (void *)arg, sizeof (instr)) != 0)
1808 			return (EFAULT);
1809 
1810 		return (0);
1811 	}
1812 
1813 	return (EINVAL);
1814 }
1815 
1816 static struct cb_ops fasttrap_cb_ops = {
1817 	fasttrap_open,		/* open */
1818 	nodev,			/* close */
1819 	nulldev,		/* strategy */
1820 	nulldev,		/* print */
1821 	nodev,			/* dump */
1822 	nodev,			/* read */
1823 	nodev,			/* write */
1824 	fasttrap_ioctl,		/* ioctl */
1825 	nodev,			/* devmap */
1826 	nodev,			/* mmap */
1827 	nodev,			/* segmap */
1828 	nochpoll,		/* poll */
1829 	ddi_prop_op,		/* cb_prop_op */
1830 	0,			/* streamtab  */
1831 	D_NEW | D_MP		/* Driver compatibility flag */
1832 };
1833 
1834 /*ARGSUSED*/
1835 static int
1836 fasttrap_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1837 {
1838 	int error;
1839 
1840 	switch (infocmd) {
1841 	case DDI_INFO_DEVT2DEVINFO:
1842 		*result = (void *)fasttrap_devi;
1843 		error = DDI_SUCCESS;
1844 		break;
1845 	case DDI_INFO_DEVT2INSTANCE:
1846 		*result = (void *)0;
1847 		error = DDI_SUCCESS;
1848 		break;
1849 	default:
1850 		error = DDI_FAILURE;
1851 	}
1852 	return (error);
1853 }
1854 
1855 static int
1856 fasttrap_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
1857 {
1858 	ulong_t nent;
1859 
1860 	switch (cmd) {
1861 	case DDI_ATTACH:
1862 		break;
1863 	case DDI_RESUME:
1864 		return (DDI_SUCCESS);
1865 	default:
1866 		return (DDI_FAILURE);
1867 	}
1868 
1869 	if (ddi_create_minor_node(devi, "fasttrap", S_IFCHR, 0,
1870 	    DDI_PSEUDO, NULL) == DDI_FAILURE ||
1871 	    dtrace_register("fasttrap", &fasttrap_attr, DTRACE_PRIV_USER, 0,
1872 	    &fasttrap_pops, NULL, &fasttrap_id) != 0) {
1873 		ddi_remove_minor_node(devi, NULL);
1874 		return (DDI_FAILURE);
1875 	}
1876 
1877 	ddi_report_dev(devi);
1878 	fasttrap_devi = devi;
1879 
1880 	/*
1881 	 * Install our hooks into fork(2), exec(2), and exit(2).
1882 	 */
1883 	dtrace_fasttrap_fork_ptr = &fasttrap_fork;
1884 	dtrace_fasttrap_exit_ptr = &fasttrap_exec_exit;
1885 	dtrace_fasttrap_exec_ptr = &fasttrap_exec_exit;
1886 
1887 	fasttrap_max = ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1888 	    "fasttrap-max-probes", FASTTRAP_MAX_DEFAULT);
1889 	fasttrap_total = 0;
1890 
1891 	/*
1892 	 * Conjure up the tracepoints hashtable...
1893 	 */
1894 	nent = ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1895 	    "fasttrap-hash-size", FASTTRAP_TPOINTS_DEFAULT_SIZE);
1896 
1897 	if (nent <= 0 || nent > 0x1000000)
1898 		nent = FASTTRAP_TPOINTS_DEFAULT_SIZE;
1899 
1900 	if ((nent & (nent - 1)) == 0)
1901 		fasttrap_tpoints.fth_nent = nent;
1902 	else
1903 		fasttrap_tpoints.fth_nent = 1 << fasttrap_highbit(nent);
1904 	ASSERT(fasttrap_tpoints.fth_nent > 0);
1905 	fasttrap_tpoints.fth_mask = fasttrap_tpoints.fth_nent - 1;
1906 	fasttrap_tpoints.fth_table = kmem_zalloc(fasttrap_tpoints.fth_nent *
1907 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
1908 
1909 	/*
1910 	 * ... and the providers hash table.
1911 	 */
1912 	nent = FASTTRAP_PROVIDERS_DEFAULT_SIZE;
1913 	if ((nent & (nent - 1)) == 0)
1914 		fasttrap_provs.fth_nent = nent;
1915 	else
1916 		fasttrap_provs.fth_nent = 1 << fasttrap_highbit(nent);
1917 	ASSERT(fasttrap_provs.fth_nent > 0);
1918 	fasttrap_provs.fth_mask = fasttrap_provs.fth_nent - 1;
1919 
1920 	fasttrap_provs.fth_table = kmem_zalloc(fasttrap_provs.fth_nent *
1921 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
1922 
1923 	(void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
1924 	    &fasttrap_meta_id);
1925 
1926 	return (DDI_SUCCESS);
1927 }
1928 
1929 static int
1930 fasttrap_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1931 {
1932 	int i, fail = 0;
1933 	timeout_id_t tmp;
1934 
1935 	switch (cmd) {
1936 	case DDI_DETACH:
1937 		break;
1938 	case DDI_SUSPEND:
1939 		return (DDI_SUCCESS);
1940 	default:
1941 		return (DDI_FAILURE);
1942 	}
1943 
1944 	/*
1945 	 * Unregister the meta-provider to make sure no new fasttrap-
1946 	 * managed providers come along while we're trying to close up
1947 	 * shop. If we fail to detach, we'll need to re-register as a
1948 	 * meta-provider. We can fail to unregister as a meta-provider
1949 	 * if providers we manage still exist.
1950 	 */
1951 	if (fasttrap_meta_id != DTRACE_METAPROVNONE &&
1952 	    dtrace_meta_unregister(fasttrap_meta_id) != 0)
1953 		return (DDI_FAILURE);
1954 
1955 	/*
1956 	 * Prevent any new timeouts from running by setting fasttrap_timeout
1957 	 * to a non-zero value, and wait for the current timeout to complete.
1958 	 */
1959 	mutex_enter(&fasttrap_cleanup_mtx);
1960 	fasttrap_cleanup_work = 0;
1961 
1962 	while (fasttrap_timeout != (timeout_id_t)1) {
1963 		tmp = fasttrap_timeout;
1964 		fasttrap_timeout = (timeout_id_t)1;
1965 
1966 		if (tmp != 0) {
1967 			mutex_exit(&fasttrap_cleanup_mtx);
1968 			(void) untimeout(tmp);
1969 			mutex_enter(&fasttrap_cleanup_mtx);
1970 		}
1971 	}
1972 
1973 	fasttrap_cleanup_work = 0;
1974 	mutex_exit(&fasttrap_cleanup_mtx);
1975 
1976 	/*
1977 	 * Iterate over all of our providers. If there's still a process
1978 	 * that corresponds to that pid, fail to detach.
1979 	 */
1980 	for (i = 0; i < fasttrap_provs.fth_nent; i++) {
1981 		fasttrap_provider_t **fpp, *fp;
1982 		fasttrap_bucket_t *bucket = &fasttrap_provs.fth_table[i];
1983 
1984 		mutex_enter(&bucket->ftb_mtx);
1985 		fpp = (fasttrap_provider_t **)&bucket->ftb_data;
1986 		while ((fp = *fpp) != NULL) {
1987 			/*
1988 			 * Acquire and release the lock as a simple way of
1989 			 * waiting for any other consumer to finish with
1990 			 * this provider. A thread must first acquire the
1991 			 * bucket lock so there's no chance of another thread
1992 			 * blocking on the providers lock.
1993 			 */
1994 			mutex_enter(&fp->ftp_mtx);
1995 			mutex_exit(&fp->ftp_mtx);
1996 
1997 			if (dtrace_unregister(fp->ftp_provid) != 0) {
1998 				fail = 1;
1999 				fpp = &fp->ftp_next;
2000 			} else {
2001 				*fpp = fp->ftp_next;
2002 				fasttrap_provider_free(fp);
2003 			}
2004 		}
2005 
2006 		mutex_exit(&bucket->ftb_mtx);
2007 	}
2008 
2009 	if (fail || dtrace_unregister(fasttrap_id) != 0) {
2010 		uint_t work;
2011 		/*
2012 		 * If we're failing to detach, we need to unblock timeouts
2013 		 * and start a new timeout if any work has accumulated while
2014 		 * we've been unsuccessfully trying to detach.
2015 		 */
2016 		mutex_enter(&fasttrap_cleanup_mtx);
2017 		fasttrap_timeout = 0;
2018 		work = fasttrap_cleanup_work;
2019 		mutex_exit(&fasttrap_cleanup_mtx);
2020 
2021 		if (work)
2022 			fasttrap_pid_cleanup();
2023 
2024 		(void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
2025 		    &fasttrap_meta_id);
2026 
2027 		return (DDI_FAILURE);
2028 	}
2029 
2030 #ifdef DEBUG
2031 	mutex_enter(&fasttrap_count_mtx);
2032 	ASSERT(fasttrap_count == 0);
2033 	mutex_exit(&fasttrap_count_mtx);
2034 #endif
2035 
2036 	kmem_free(fasttrap_tpoints.fth_table,
2037 	    fasttrap_tpoints.fth_nent * sizeof (fasttrap_bucket_t));
2038 	fasttrap_tpoints.fth_nent = 0;
2039 
2040 	kmem_free(fasttrap_provs.fth_table,
2041 	    fasttrap_provs.fth_nent * sizeof (fasttrap_bucket_t));
2042 	fasttrap_provs.fth_nent = 0;
2043 
2044 	/*
2045 	 * We know there are no tracepoints in any process anywhere in
2046 	 * the system so there is no process which has its p_dtrace_count
2047 	 * greater than zero, therefore we know that no thread can actively
2048 	 * be executing code in fasttrap_fork(). Similarly for p_dtrace_probes
2049 	 * and fasttrap_exec() and fasttrap_exit().
2050 	 */
2051 	ASSERT(dtrace_fasttrap_fork_ptr == &fasttrap_fork);
2052 	dtrace_fasttrap_fork_ptr = NULL;
2053 
2054 	ASSERT(dtrace_fasttrap_exec_ptr == &fasttrap_exec_exit);
2055 	dtrace_fasttrap_exec_ptr = NULL;
2056 
2057 	ASSERT(dtrace_fasttrap_exit_ptr == &fasttrap_exec_exit);
2058 	dtrace_fasttrap_exit_ptr = NULL;
2059 
2060 	ddi_remove_minor_node(devi, NULL);
2061 
2062 	return (DDI_SUCCESS);
2063 }
2064 
2065 static struct dev_ops fasttrap_ops = {
2066 	DEVO_REV,		/* devo_rev */
2067 	0,			/* refcnt */
2068 	fasttrap_info,		/* get_dev_info */
2069 	nulldev,		/* identify */
2070 	nulldev,		/* probe */
2071 	fasttrap_attach,	/* attach */
2072 	fasttrap_detach,	/* detach */
2073 	nodev,			/* reset */
2074 	&fasttrap_cb_ops,	/* driver operations */
2075 	NULL,			/* bus operations */
2076 	nodev			/* dev power */
2077 };
2078 
2079 /*
2080  * Module linkage information for the kernel.
2081  */
2082 static struct modldrv modldrv = {
2083 	&mod_driverops,		/* module type (this is a pseudo driver) */
2084 	"Fasttrap Tracing",	/* name of module */
2085 	&fasttrap_ops,		/* driver ops */
2086 };
2087 
2088 static struct modlinkage modlinkage = {
2089 	MODREV_1,
2090 	(void *)&modldrv,
2091 	NULL
2092 };
2093 
2094 int
2095 _init(void)
2096 {
2097 	return (mod_install(&modlinkage));
2098 }
2099 
2100 int
2101 _info(struct modinfo *modinfop)
2102 {
2103 	return (mod_info(&modlinkage, modinfop));
2104 }
2105 
2106 int
2107 _fini(void)
2108 {
2109 	return (mod_remove(&modlinkage));
2110 }
2111