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