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