xref: /titanic_44/usr/src/uts/common/dtrace/fasttrap.c (revision a399b7655a1d835aa8606c2b29e4e777baac8635)
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;
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 	/*
1062 	 * We only need to set this member if the argument is remapped.
1063 	 */
1064 	if (probe->ftp_argmap != NULL)
1065 		desc->dtargd_mapping = probe->ftp_argmap[desc->dtargd_ndx];
1066 
1067 	str = probe->ftp_ntypes;
1068 	for (i = 0; i < desc->dtargd_mapping; i++) {
1069 		str += strlen(str) + 1;
1070 	}
1071 
1072 	ASSERT(strlen(str + 1) < sizeof (desc->dtargd_native));
1073 	(void) strcpy(desc->dtargd_native, str);
1074 
1075 	if (probe->ftp_xtypes == NULL)
1076 		return;
1077 
1078 	str = probe->ftp_xtypes;
1079 	for (i = 0; i < desc->dtargd_ndx; i++) {
1080 		str += strlen(str) + 1;
1081 	}
1082 
1083 	ASSERT(strlen(str + 1) < sizeof (desc->dtargd_xlate));
1084 	(void) strcpy(desc->dtargd_xlate, str);
1085 }
1086 
1087 /*ARGSUSED*/
1088 static void
1089 fasttrap_pid_destroy(void *arg, dtrace_id_t id, void *parg)
1090 {
1091 	fasttrap_probe_t *probe = parg;
1092 	int i;
1093 	size_t size;
1094 
1095 	ASSERT(probe != NULL);
1096 	ASSERT(!probe->ftp_enabled);
1097 	ASSERT(fasttrap_total >= probe->ftp_ntps);
1098 
1099 	atomic_add_32(&fasttrap_total, -probe->ftp_ntps);
1100 	size = offsetof(fasttrap_probe_t, ftp_tps[probe->ftp_ntps]);
1101 
1102 	if (probe->ftp_gen + 1 >= fasttrap_mod_gen)
1103 		fasttrap_mod_barrier(probe->ftp_gen);
1104 
1105 	for (i = 0; i < probe->ftp_ntps; i++) {
1106 		kmem_free(probe->ftp_tps[i].fit_tp,
1107 		    sizeof (fasttrap_tracepoint_t));
1108 	}
1109 
1110 	kmem_free(probe, size);
1111 }
1112 
1113 
1114 static const dtrace_pattr_t pid_attr = {
1115 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1116 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1117 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1118 { DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_ISA },
1119 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
1120 };
1121 
1122 static dtrace_pops_t pid_pops = {
1123 	fasttrap_pid_provide,
1124 	NULL,
1125 	fasttrap_pid_enable,
1126 	fasttrap_pid_disable,
1127 	NULL,
1128 	NULL,
1129 	fasttrap_pid_getargdesc,
1130 	fasttrap_pid_getarg,
1131 	NULL,
1132 	fasttrap_pid_destroy
1133 };
1134 
1135 static dtrace_pops_t usdt_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_usdt_getarg,
1144 	NULL,
1145 	fasttrap_pid_destroy
1146 };
1147 
1148 static fasttrap_proc_t *
1149 fasttrap_proc_lookup(pid_t pid)
1150 {
1151 	fasttrap_bucket_t *bucket;
1152 	fasttrap_proc_t *fprc, *new_fprc;
1153 
1154 	bucket = &fasttrap_procs.fth_table[FASTTRAP_PROCS_INDEX(pid)];
1155 	mutex_enter(&bucket->ftb_mtx);
1156 
1157 	for (fprc = bucket->ftb_data; fprc != NULL; fprc = fprc->ftpc_next) {
1158 		if (fprc->ftpc_pid == pid && !fprc->ftpc_defunct) {
1159 			mutex_enter(&fprc->ftpc_mtx);
1160 			mutex_exit(&bucket->ftb_mtx);
1161 			fprc->ftpc_count++;
1162 			mutex_exit(&fprc->ftpc_mtx);
1163 
1164 			return (fprc);
1165 		}
1166 	}
1167 
1168 	/*
1169 	 * Drop the bucket lock so we don't try to perform a sleeping
1170 	 * allocation under it.
1171 	 */
1172 	mutex_exit(&bucket->ftb_mtx);
1173 
1174 	new_fprc = kmem_zalloc(sizeof (fasttrap_proc_t), KM_SLEEP);
1175 	new_fprc->ftpc_pid = pid;
1176 	new_fprc->ftpc_count = 1;
1177 
1178 	mutex_enter(&bucket->ftb_mtx);
1179 
1180 	/*
1181 	 * Take another lap through the list to make sure a proc hasn't
1182 	 * been created for this pid while we weren't under the bucket lock.
1183 	 */
1184 	for (fprc = bucket->ftb_data; fprc != NULL; fprc = fprc->ftpc_next) {
1185 		if (fprc->ftpc_pid == pid && !fprc->ftpc_defunct) {
1186 			mutex_enter(&fprc->ftpc_mtx);
1187 			mutex_exit(&bucket->ftb_mtx);
1188 			fprc->ftpc_count++;
1189 			mutex_exit(&fprc->ftpc_mtx);
1190 
1191 			kmem_free(new_fprc, sizeof (fasttrap_proc_t));
1192 
1193 			return (fprc);
1194 		}
1195 	}
1196 
1197 	new_fprc->ftpc_next = bucket->ftb_data;
1198 	bucket->ftb_data = new_fprc;
1199 
1200 	mutex_exit(&bucket->ftb_mtx);
1201 
1202 	return (new_fprc);
1203 }
1204 
1205 static void
1206 fasttrap_proc_release(fasttrap_proc_t *proc)
1207 {
1208 	fasttrap_bucket_t *bucket;
1209 	fasttrap_proc_t *fprc, **fprcp;
1210 	pid_t pid = proc->ftpc_pid;
1211 
1212 	mutex_enter(&proc->ftpc_mtx);
1213 
1214 	ASSERT(proc->ftpc_count != 0);
1215 
1216 	if (--proc->ftpc_count != 0) {
1217 		mutex_exit(&proc->ftpc_mtx);
1218 		return;
1219 	}
1220 
1221 	mutex_exit(&proc->ftpc_mtx);
1222 
1223 	bucket = &fasttrap_procs.fth_table[FASTTRAP_PROCS_INDEX(pid)];
1224 	mutex_enter(&bucket->ftb_mtx);
1225 
1226 	fprcp = (fasttrap_proc_t **)&bucket->ftb_data;
1227 	while ((fprc = *fprcp) != NULL) {
1228 		if (fprc == proc)
1229 			break;
1230 
1231 		fprcp = &fprc->ftpc_next;
1232 	}
1233 
1234 	/*
1235 	 * Something strange has happened if we can't find the proc.
1236 	 */
1237 	ASSERT(fprc != NULL);
1238 
1239 	*fprcp = fprc->ftpc_next;
1240 
1241 	mutex_exit(&bucket->ftb_mtx);
1242 
1243 	kmem_free(fprc, sizeof (fasttrap_proc_t));
1244 }
1245 
1246 /*
1247  * Lookup a fasttrap-managed provider based on its name and associated pid.
1248  * If the pattr argument is non-NULL, this function instantiates the provider
1249  * if it doesn't exist otherwise it returns NULL. The provider is returned
1250  * with its lock held.
1251  */
1252 static fasttrap_provider_t *
1253 fasttrap_provider_lookup(pid_t pid, const char *name,
1254     const dtrace_pattr_t *pattr)
1255 {
1256 	fasttrap_provider_t *fp, *new_fp = NULL;
1257 	fasttrap_bucket_t *bucket;
1258 	char provname[DTRACE_PROVNAMELEN];
1259 	proc_t *p;
1260 	cred_t *cred;
1261 
1262 	ASSERT(strlen(name) < sizeof (fp->ftp_name));
1263 	ASSERT(pattr != NULL);
1264 
1265 	bucket = &fasttrap_provs.fth_table[FASTTRAP_PROVS_INDEX(pid, name)];
1266 	mutex_enter(&bucket->ftb_mtx);
1267 
1268 	/*
1269 	 * Take a lap through the list and return the match if we find it.
1270 	 */
1271 	for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1272 		if (fp->ftp_pid == pid && strcmp(fp->ftp_name, name) == 0 &&
1273 		    !fp->ftp_retired) {
1274 			mutex_enter(&fp->ftp_mtx);
1275 			mutex_exit(&bucket->ftb_mtx);
1276 			return (fp);
1277 		}
1278 	}
1279 
1280 	/*
1281 	 * Drop the bucket lock so we don't try to perform a sleeping
1282 	 * allocation under it.
1283 	 */
1284 	mutex_exit(&bucket->ftb_mtx);
1285 
1286 	/*
1287 	 * Make sure the process exists, isn't a child created as the result
1288 	 * of a vfork(2), and isn't a zombie (but may be in fork).
1289 	 */
1290 	mutex_enter(&pidlock);
1291 	if ((p = prfind(pid)) == NULL) {
1292 		mutex_exit(&pidlock);
1293 		return (NULL);
1294 	}
1295 	mutex_enter(&p->p_lock);
1296 	mutex_exit(&pidlock);
1297 	if (p->p_flag & (SVFORK | SEXITING)) {
1298 		mutex_exit(&p->p_lock);
1299 		return (NULL);
1300 	}
1301 
1302 	/*
1303 	 * Increment p_dtrace_probes so that the process knows to inform us
1304 	 * when it exits or execs. fasttrap_provider_free() decrements this
1305 	 * when we're done with this provider.
1306 	 */
1307 	p->p_dtrace_probes++;
1308 
1309 	/*
1310 	 * Grab the credentials for this process so we have
1311 	 * something to pass to dtrace_register().
1312 	 */
1313 	mutex_enter(&p->p_crlock);
1314 	crhold(p->p_cred);
1315 	cred = p->p_cred;
1316 	mutex_exit(&p->p_crlock);
1317 	mutex_exit(&p->p_lock);
1318 
1319 	new_fp = kmem_zalloc(sizeof (fasttrap_provider_t), KM_SLEEP);
1320 	new_fp->ftp_pid = pid;
1321 	new_fp->ftp_proc = fasttrap_proc_lookup(pid);
1322 
1323 	ASSERT(new_fp->ftp_proc != NULL);
1324 
1325 	mutex_enter(&bucket->ftb_mtx);
1326 
1327 	/*
1328 	 * Take another lap through the list to make sure a provider hasn't
1329 	 * been created for this pid while we weren't under the bucket lock.
1330 	 */
1331 	for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1332 		if (fp->ftp_pid == pid && strcmp(fp->ftp_name, name) == 0 &&
1333 		    !fp->ftp_retired) {
1334 			mutex_enter(&fp->ftp_mtx);
1335 			mutex_exit(&bucket->ftb_mtx);
1336 			fasttrap_provider_free(new_fp);
1337 			crfree(cred);
1338 			return (fp);
1339 		}
1340 	}
1341 
1342 	(void) strcpy(new_fp->ftp_name, name);
1343 
1344 	/*
1345 	 * Fail and return NULL if either the provider name is too long
1346 	 * or we fail to register this new provider with the DTrace
1347 	 * framework. Note that this is the only place we ever construct
1348 	 * the full provider name -- we keep it in pieces in the provider
1349 	 * structure.
1350 	 */
1351 	if (snprintf(provname, sizeof (provname), "%s%u", name, (uint_t)pid) >=
1352 	    sizeof (provname) ||
1353 	    dtrace_register(provname, pattr,
1354 	    DTRACE_PRIV_PROC | DTRACE_PRIV_OWNER | DTRACE_PRIV_ZONEOWNER, cred,
1355 	    pattr == &pid_attr ? &pid_pops : &usdt_pops, new_fp,
1356 	    &new_fp->ftp_provid) != 0) {
1357 		mutex_exit(&bucket->ftb_mtx);
1358 		fasttrap_provider_free(new_fp);
1359 		crfree(cred);
1360 		return (NULL);
1361 	}
1362 
1363 	new_fp->ftp_next = bucket->ftb_data;
1364 	bucket->ftb_data = new_fp;
1365 
1366 	mutex_enter(&new_fp->ftp_mtx);
1367 	mutex_exit(&bucket->ftb_mtx);
1368 
1369 	crfree(cred);
1370 	return (new_fp);
1371 }
1372 
1373 static void
1374 fasttrap_provider_free(fasttrap_provider_t *provider)
1375 {
1376 	pid_t pid = provider->ftp_pid;
1377 	proc_t *p;
1378 
1379 	/*
1380 	 * There need to be no associated enabled probes, no consumers
1381 	 * creating probes, and no meta providers referencing this provider.
1382 	 */
1383 	ASSERT(provider->ftp_rcount == 0);
1384 	ASSERT(provider->ftp_ccount == 0);
1385 	ASSERT(provider->ftp_mcount == 0);
1386 
1387 	fasttrap_proc_release(provider->ftp_proc);
1388 
1389 	kmem_free(provider, sizeof (fasttrap_provider_t));
1390 
1391 	/*
1392 	 * Decrement p_dtrace_probes on the process whose provider we're
1393 	 * freeing. We don't have to worry about clobbering somone else's
1394 	 * modifications to it because we have locked the bucket that
1395 	 * corresponds to this process's hash chain in the provider hash
1396 	 * table. Don't sweat it if we can't find the process.
1397 	 */
1398 	mutex_enter(&pidlock);
1399 	if ((p = prfind(pid)) == NULL) {
1400 		mutex_exit(&pidlock);
1401 		return;
1402 	}
1403 
1404 	mutex_enter(&p->p_lock);
1405 	mutex_exit(&pidlock);
1406 
1407 	p->p_dtrace_probes--;
1408 	mutex_exit(&p->p_lock);
1409 }
1410 
1411 static void
1412 fasttrap_provider_retire(pid_t pid, const char *name, int mprov)
1413 {
1414 	fasttrap_provider_t *fp;
1415 	fasttrap_bucket_t *bucket;
1416 	dtrace_provider_id_t provid;
1417 
1418 	ASSERT(strlen(name) < sizeof (fp->ftp_name));
1419 
1420 	bucket = &fasttrap_provs.fth_table[FASTTRAP_PROVS_INDEX(pid, name)];
1421 	mutex_enter(&bucket->ftb_mtx);
1422 
1423 	for (fp = bucket->ftb_data; fp != NULL; fp = fp->ftp_next) {
1424 		if (fp->ftp_pid == pid && strcmp(fp->ftp_name, name) == 0 &&
1425 		    !fp->ftp_retired)
1426 			break;
1427 	}
1428 
1429 	if (fp == NULL) {
1430 		mutex_exit(&bucket->ftb_mtx);
1431 		return;
1432 	}
1433 
1434 	mutex_enter(&fp->ftp_mtx);
1435 	ASSERT(!mprov || fp->ftp_mcount > 0);
1436 	if (mprov && --fp->ftp_mcount != 0)  {
1437 		mutex_exit(&fp->ftp_mtx);
1438 		mutex_exit(&bucket->ftb_mtx);
1439 		return;
1440 	}
1441 
1442 	/*
1443 	 * Mark the provider to be removed in our post-processing step,
1444 	 * mark it retired, and mark its proc as defunct (though it may
1445 	 * already be marked defunct by another provider that shares the
1446 	 * same proc). Marking it indicates that we should try to remove it;
1447 	 * setting the retired flag indicates that we're done with this
1448 	 * provider; setting the proc to be defunct indicates that all
1449 	 * tracepoints associated with the traced process should be ignored.
1450 	 *
1451 	 * We obviously need to take the bucket lock before the provider lock
1452 	 * to perform the lookup, but we need to drop the provider lock
1453 	 * before calling into the DTrace framework since we acquire the
1454 	 * provider lock in callbacks invoked from the DTrace framework. The
1455 	 * bucket lock therefore protects the integrity of the provider hash
1456 	 * table.
1457 	 */
1458 	fp->ftp_proc->ftpc_defunct = 1;
1459 	fp->ftp_retired = 1;
1460 	fp->ftp_marked = 1;
1461 	provid = fp->ftp_provid;
1462 	mutex_exit(&fp->ftp_mtx);
1463 
1464 	/*
1465 	 * We don't have to worry about invalidating the same provider twice
1466 	 * since fasttrap_provider_lookup() will ignore provider that have
1467 	 * been marked as retired.
1468 	 */
1469 	dtrace_invalidate(provid);
1470 
1471 	mutex_exit(&bucket->ftb_mtx);
1472 
1473 	fasttrap_pid_cleanup();
1474 }
1475 
1476 static int
1477 fasttrap_uint32_cmp(const void *ap, const void *bp)
1478 {
1479 	return (*(const uint32_t *)ap - *(const uint32_t *)bp);
1480 }
1481 
1482 static int
1483 fasttrap_uint64_cmp(const void *ap, const void *bp)
1484 {
1485 	return (*(const uint64_t *)ap - *(const uint64_t *)bp);
1486 }
1487 
1488 static int
1489 fasttrap_add_probe(fasttrap_probe_spec_t *pdata)
1490 {
1491 	fasttrap_provider_t *provider;
1492 	fasttrap_probe_t *pp;
1493 	fasttrap_tracepoint_t *tp;
1494 	char *name;
1495 	int i, aframes, whack;
1496 
1497 	/*
1498 	 * There needs to be at least one desired trace point.
1499 	 */
1500 	if (pdata->ftps_noffs == 0)
1501 		return (EINVAL);
1502 
1503 	switch (pdata->ftps_type) {
1504 	case DTFTP_ENTRY:
1505 		name = "entry";
1506 		aframes = FASTTRAP_ENTRY_AFRAMES;
1507 		break;
1508 	case DTFTP_RETURN:
1509 		name = "return";
1510 		aframes = FASTTRAP_RETURN_AFRAMES;
1511 		break;
1512 	case DTFTP_OFFSETS:
1513 		name = NULL;
1514 		break;
1515 	default:
1516 		return (EINVAL);
1517 	}
1518 
1519 	if ((provider = fasttrap_provider_lookup(pdata->ftps_pid,
1520 	    FASTTRAP_PID_NAME, &pid_attr)) == NULL)
1521 		return (ESRCH);
1522 
1523 	/*
1524 	 * Increment this reference count to indicate that a consumer is
1525 	 * actively adding a new probe associated with this provider. This
1526 	 * prevents the provider from being deleted -- we'll need to check
1527 	 * for pending deletions when we drop this reference count.
1528 	 */
1529 	provider->ftp_ccount++;
1530 	mutex_exit(&provider->ftp_mtx);
1531 
1532 	/*
1533 	 * Grab the creation lock to ensure consistency between calls to
1534 	 * dtrace_probe_lookup() and dtrace_probe_create() in the face of
1535 	 * other threads creating probes. We must drop the provider lock
1536 	 * before taking this lock to avoid a three-way deadlock with the
1537 	 * DTrace framework.
1538 	 */
1539 	mutex_enter(&provider->ftp_cmtx);
1540 
1541 	if (name == NULL) {
1542 		for (i = 0; i < pdata->ftps_noffs; i++) {
1543 			char name_str[17];
1544 
1545 			(void) sprintf(name_str, "%llx",
1546 			    (unsigned long long)pdata->ftps_offs[i]);
1547 
1548 			if (dtrace_probe_lookup(provider->ftp_provid,
1549 			    pdata->ftps_mod, pdata->ftps_func, name_str) != 0)
1550 				continue;
1551 
1552 			atomic_add_32(&fasttrap_total, 1);
1553 
1554 			if (fasttrap_total > fasttrap_max) {
1555 				atomic_add_32(&fasttrap_total, -1);
1556 				goto no_mem;
1557 			}
1558 
1559 			pp = kmem_zalloc(sizeof (fasttrap_probe_t), KM_SLEEP);
1560 
1561 			pp->ftp_prov = provider;
1562 			pp->ftp_faddr = pdata->ftps_pc;
1563 			pp->ftp_fsize = pdata->ftps_size;
1564 			pp->ftp_pid = pdata->ftps_pid;
1565 			pp->ftp_ntps = 1;
1566 
1567 			tp = kmem_zalloc(sizeof (fasttrap_tracepoint_t),
1568 			    KM_SLEEP);
1569 
1570 			tp->ftt_proc = provider->ftp_proc;
1571 			tp->ftt_pc = pdata->ftps_offs[i] + pdata->ftps_pc;
1572 			tp->ftt_pid = pdata->ftps_pid;
1573 
1574 			pp->ftp_tps[0].fit_tp = tp;
1575 			pp->ftp_tps[0].fit_id.fti_probe = pp;
1576 			pp->ftp_tps[0].fit_id.fti_ptype = pdata->ftps_type;
1577 
1578 			pp->ftp_id = dtrace_probe_create(provider->ftp_provid,
1579 			    pdata->ftps_mod, pdata->ftps_func, name_str,
1580 			    FASTTRAP_OFFSET_AFRAMES, pp);
1581 		}
1582 
1583 	} else if (dtrace_probe_lookup(provider->ftp_provid, pdata->ftps_mod,
1584 	    pdata->ftps_func, name) == 0) {
1585 		atomic_add_32(&fasttrap_total, pdata->ftps_noffs);
1586 
1587 		if (fasttrap_total > fasttrap_max) {
1588 			atomic_add_32(&fasttrap_total, -pdata->ftps_noffs);
1589 			goto no_mem;
1590 		}
1591 
1592 		/*
1593 		 * Make sure all tracepoint program counter values are unique.
1594 		 * We later assume that each probe has exactly one tracepoint
1595 		 * for a given pc.
1596 		 */
1597 		qsort(pdata->ftps_offs, pdata->ftps_noffs,
1598 		    sizeof (uint64_t), fasttrap_uint64_cmp);
1599 		for (i = 1; i < pdata->ftps_noffs; i++) {
1600 			if (pdata->ftps_offs[i] > pdata->ftps_offs[i - 1])
1601 				continue;
1602 
1603 			atomic_add_32(&fasttrap_total, -pdata->ftps_noffs);
1604 			goto no_mem;
1605 		}
1606 
1607 		ASSERT(pdata->ftps_noffs > 0);
1608 		pp = kmem_zalloc(offsetof(fasttrap_probe_t,
1609 		    ftp_tps[pdata->ftps_noffs]), KM_SLEEP);
1610 
1611 		pp->ftp_prov = provider;
1612 		pp->ftp_faddr = pdata->ftps_pc;
1613 		pp->ftp_fsize = pdata->ftps_size;
1614 		pp->ftp_pid = pdata->ftps_pid;
1615 		pp->ftp_ntps = pdata->ftps_noffs;
1616 
1617 		for (i = 0; i < pdata->ftps_noffs; i++) {
1618 			tp = kmem_zalloc(sizeof (fasttrap_tracepoint_t),
1619 			    KM_SLEEP);
1620 
1621 			tp->ftt_proc = provider->ftp_proc;
1622 			tp->ftt_pc = pdata->ftps_offs[i] + pdata->ftps_pc;
1623 			tp->ftt_pid = pdata->ftps_pid;
1624 
1625 			pp->ftp_tps[i].fit_tp = tp;
1626 			pp->ftp_tps[i].fit_id.fti_probe = pp;
1627 			pp->ftp_tps[i].fit_id.fti_ptype = pdata->ftps_type;
1628 		}
1629 
1630 		pp->ftp_id = dtrace_probe_create(provider->ftp_provid,
1631 		    pdata->ftps_mod, pdata->ftps_func, name, aframes, pp);
1632 	}
1633 
1634 	mutex_exit(&provider->ftp_cmtx);
1635 
1636 	/*
1637 	 * We know that the provider is still valid since we incremented the
1638 	 * creation reference count. If someone tried to clean up this provider
1639 	 * while we were using it (e.g. because the process called exec(2) or
1640 	 * exit(2)), take note of that and try to clean it up now.
1641 	 */
1642 	mutex_enter(&provider->ftp_mtx);
1643 	provider->ftp_ccount--;
1644 	whack = provider->ftp_retired;
1645 	mutex_exit(&provider->ftp_mtx);
1646 
1647 	if (whack)
1648 		fasttrap_pid_cleanup();
1649 
1650 	return (0);
1651 
1652 no_mem:
1653 	/*
1654 	 * If we've exhausted the allowable resources, we'll try to remove
1655 	 * this provider to free some up. This is to cover the case where
1656 	 * the user has accidentally created many more probes than was
1657 	 * intended (e.g. pid123:::).
1658 	 */
1659 	mutex_exit(&provider->ftp_cmtx);
1660 	mutex_enter(&provider->ftp_mtx);
1661 	provider->ftp_ccount--;
1662 	provider->ftp_marked = 1;
1663 	mutex_exit(&provider->ftp_mtx);
1664 
1665 	fasttrap_pid_cleanup();
1666 
1667 	return (ENOMEM);
1668 }
1669 
1670 /*ARGSUSED*/
1671 static void *
1672 fasttrap_meta_provide(void *arg, dtrace_helper_provdesc_t *dhpv, pid_t pid)
1673 {
1674 	fasttrap_provider_t *provider;
1675 
1676 	/*
1677 	 * A 32-bit unsigned integer (like a pid for example) can be
1678 	 * expressed in 10 or fewer decimal digits. Make sure that we'll
1679 	 * have enough space for the provider name.
1680 	 */
1681 	if (strlen(dhpv->dthpv_provname) + 10 >=
1682 	    sizeof (provider->ftp_name)) {
1683 		cmn_err(CE_WARN, "failed to instantiate provider %s: "
1684 		    "name too long to accomodate pid", dhpv->dthpv_provname);
1685 		return (NULL);
1686 	}
1687 
1688 	/*
1689 	 * Don't let folks spoof the true pid provider.
1690 	 */
1691 	if (strcmp(dhpv->dthpv_provname, FASTTRAP_PID_NAME) == 0) {
1692 		cmn_err(CE_WARN, "failed to instantiate provider %s: "
1693 		    "%s is an invalid name", dhpv->dthpv_provname,
1694 		    FASTTRAP_PID_NAME);
1695 		return (NULL);
1696 	}
1697 
1698 	/*
1699 	 * The highest stability class that fasttrap supports is ISA; cap
1700 	 * the stability of the new provider accordingly.
1701 	 */
1702 	if (dhpv->dthpv_pattr.dtpa_provider.dtat_class >= DTRACE_CLASS_COMMON)
1703 		dhpv->dthpv_pattr.dtpa_provider.dtat_class = DTRACE_CLASS_ISA;
1704 	if (dhpv->dthpv_pattr.dtpa_mod.dtat_class >= DTRACE_CLASS_COMMON)
1705 		dhpv->dthpv_pattr.dtpa_mod.dtat_class = DTRACE_CLASS_ISA;
1706 	if (dhpv->dthpv_pattr.dtpa_func.dtat_class >= DTRACE_CLASS_COMMON)
1707 		dhpv->dthpv_pattr.dtpa_func.dtat_class = DTRACE_CLASS_ISA;
1708 	if (dhpv->dthpv_pattr.dtpa_name.dtat_class >= DTRACE_CLASS_COMMON)
1709 		dhpv->dthpv_pattr.dtpa_name.dtat_class = DTRACE_CLASS_ISA;
1710 	if (dhpv->dthpv_pattr.dtpa_args.dtat_class >= DTRACE_CLASS_COMMON)
1711 		dhpv->dthpv_pattr.dtpa_args.dtat_class = DTRACE_CLASS_ISA;
1712 
1713 	if ((provider = fasttrap_provider_lookup(pid, dhpv->dthpv_provname,
1714 	    &dhpv->dthpv_pattr)) == NULL) {
1715 		cmn_err(CE_WARN, "failed to instantiate provider %s for "
1716 		    "process %u",  dhpv->dthpv_provname, (uint_t)pid);
1717 		return (NULL);
1718 	}
1719 
1720 	/*
1721 	 * Up the meta provider count so this provider isn't removed until
1722 	 * the meta provider has been told to remove it.
1723 	 */
1724 	provider->ftp_mcount++;
1725 
1726 	mutex_exit(&provider->ftp_mtx);
1727 
1728 	return (provider);
1729 }
1730 
1731 /*ARGSUSED*/
1732 static void
1733 fasttrap_meta_create_probe(void *arg, void *parg,
1734     dtrace_helper_probedesc_t *dhpb)
1735 {
1736 	fasttrap_provider_t *provider = parg;
1737 	fasttrap_probe_t *pp;
1738 	fasttrap_tracepoint_t *tp;
1739 	int i, j;
1740 	uint32_t ntps;
1741 
1742 	/*
1743 	 * Since the meta provider count is non-zero we don't have to worry
1744 	 * about this provider disappearing.
1745 	 */
1746 	ASSERT(provider->ftp_mcount > 0);
1747 
1748 	/*
1749 	 * The offsets must be unique.
1750 	 */
1751 	qsort(dhpb->dthpb_offs, dhpb->dthpb_noffs, sizeof (uint32_t),
1752 	    fasttrap_uint32_cmp);
1753 	for (i = 1; i < dhpb->dthpb_noffs; i++) {
1754 		if (dhpb->dthpb_base + dhpb->dthpb_offs[i] <=
1755 		    dhpb->dthpb_base + dhpb->dthpb_offs[i - 1])
1756 			return;
1757 	}
1758 
1759 	qsort(dhpb->dthpb_enoffs, dhpb->dthpb_nenoffs, sizeof (uint32_t),
1760 	    fasttrap_uint32_cmp);
1761 	for (i = 1; i < dhpb->dthpb_nenoffs; i++) {
1762 		if (dhpb->dthpb_base + dhpb->dthpb_enoffs[i] <=
1763 		    dhpb->dthpb_base + dhpb->dthpb_enoffs[i - 1])
1764 			return;
1765 	}
1766 
1767 	/*
1768 	 * Grab the creation lock to ensure consistency between calls to
1769 	 * dtrace_probe_lookup() and dtrace_probe_create() in the face of
1770 	 * other threads creating probes.
1771 	 */
1772 	mutex_enter(&provider->ftp_cmtx);
1773 
1774 	if (dtrace_probe_lookup(provider->ftp_provid, dhpb->dthpb_mod,
1775 	    dhpb->dthpb_func, dhpb->dthpb_name) != 0) {
1776 		mutex_exit(&provider->ftp_cmtx);
1777 		return;
1778 	}
1779 
1780 	ntps = dhpb->dthpb_noffs + dhpb->dthpb_nenoffs;
1781 	ASSERT(ntps > 0);
1782 
1783 	atomic_add_32(&fasttrap_total, ntps);
1784 
1785 	if (fasttrap_total > fasttrap_max) {
1786 		atomic_add_32(&fasttrap_total, -ntps);
1787 		mutex_exit(&provider->ftp_cmtx);
1788 		return;
1789 	}
1790 
1791 	pp = kmem_zalloc(offsetof(fasttrap_probe_t, ftp_tps[ntps]), KM_SLEEP);
1792 
1793 	pp->ftp_prov = provider;
1794 	pp->ftp_pid = provider->ftp_pid;
1795 	pp->ftp_ntps = ntps;
1796 	pp->ftp_nargs = dhpb->dthpb_xargc;
1797 	pp->ftp_xtypes = dhpb->dthpb_xtypes;
1798 	pp->ftp_ntypes = dhpb->dthpb_ntypes;
1799 
1800 	/*
1801 	 * First create a tracepoint for each actual point of interest.
1802 	 */
1803 	for (i = 0; i < dhpb->dthpb_noffs; i++) {
1804 		tp = kmem_zalloc(sizeof (fasttrap_tracepoint_t), KM_SLEEP);
1805 
1806 		tp->ftt_proc = provider->ftp_proc;
1807 		tp->ftt_pc = dhpb->dthpb_base + dhpb->dthpb_offs[i];
1808 		tp->ftt_pid = provider->ftp_pid;
1809 
1810 		pp->ftp_tps[i].fit_tp = tp;
1811 		pp->ftp_tps[i].fit_id.fti_probe = pp;
1812 #ifdef __sparc
1813 		pp->ftp_tps[i].fit_id.fti_ptype = DTFTP_POST_OFFSETS;
1814 #else
1815 		pp->ftp_tps[i].fit_id.fti_ptype = DTFTP_OFFSETS;
1816 #endif
1817 	}
1818 
1819 	/*
1820 	 * Then create a tracepoint for each is-enabled point.
1821 	 */
1822 	for (j = 0; i < ntps; i++, j++) {
1823 		tp = kmem_zalloc(sizeof (fasttrap_tracepoint_t), KM_SLEEP);
1824 
1825 		tp->ftt_proc = provider->ftp_proc;
1826 		tp->ftt_pc = dhpb->dthpb_base + dhpb->dthpb_enoffs[j];
1827 		tp->ftt_pid = provider->ftp_pid;
1828 
1829 		pp->ftp_tps[i].fit_tp = tp;
1830 		pp->ftp_tps[i].fit_id.fti_probe = pp;
1831 		pp->ftp_tps[i].fit_id.fti_ptype = DTFTP_IS_ENABLED;
1832 	}
1833 
1834 	/*
1835 	 * If the arguments are shuffled around we set the argument remapping
1836 	 * table. Later, when the probe fires, we only remap the arguments
1837 	 * if the table is non-NULL.
1838 	 */
1839 	for (i = 0; i < dhpb->dthpb_xargc; i++) {
1840 		if (dhpb->dthpb_args[i] != i) {
1841 			pp->ftp_argmap = dhpb->dthpb_args;
1842 			break;
1843 		}
1844 	}
1845 
1846 	/*
1847 	 * The probe is fully constructed -- register it with DTrace.
1848 	 */
1849 	pp->ftp_id = dtrace_probe_create(provider->ftp_provid, dhpb->dthpb_mod,
1850 	    dhpb->dthpb_func, dhpb->dthpb_name, FASTTRAP_OFFSET_AFRAMES, pp);
1851 
1852 	mutex_exit(&provider->ftp_cmtx);
1853 }
1854 
1855 /*ARGSUSED*/
1856 static void
1857 fasttrap_meta_remove(void *arg, dtrace_helper_provdesc_t *dhpv, pid_t pid)
1858 {
1859 	/*
1860 	 * Clean up the USDT provider. There may be active consumers of the
1861 	 * provider busy adding probes, no damage will actually befall the
1862 	 * provider until that count has dropped to zero. This just puts
1863 	 * the provider on death row.
1864 	 */
1865 	fasttrap_provider_retire(pid, dhpv->dthpv_provname, 1);
1866 }
1867 
1868 static dtrace_mops_t fasttrap_mops = {
1869 	fasttrap_meta_create_probe,
1870 	fasttrap_meta_provide,
1871 	fasttrap_meta_remove
1872 };
1873 
1874 /*ARGSUSED*/
1875 static int
1876 fasttrap_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
1877 {
1878 	return (0);
1879 }
1880 
1881 /*ARGSUSED*/
1882 static int
1883 fasttrap_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
1884 {
1885 	if (!dtrace_attached())
1886 		return (EAGAIN);
1887 
1888 	if (cmd == FASTTRAPIOC_MAKEPROBE) {
1889 		fasttrap_probe_spec_t *uprobe = (void *)arg;
1890 		fasttrap_probe_spec_t *probe;
1891 		uint64_t noffs;
1892 		size_t size;
1893 		int ret;
1894 		char *c;
1895 
1896 		if (copyin(&uprobe->ftps_noffs, &noffs,
1897 		    sizeof (uprobe->ftps_noffs)))
1898 			return (EFAULT);
1899 
1900 		/*
1901 		 * Probes must have at least one tracepoint.
1902 		 */
1903 		if (noffs == 0)
1904 			return (EINVAL);
1905 
1906 		size = sizeof (fasttrap_probe_spec_t) +
1907 		    sizeof (probe->ftps_offs[0]) * (noffs - 1);
1908 
1909 		if (size > 1024 * 1024)
1910 			return (ENOMEM);
1911 
1912 		probe = kmem_alloc(size, KM_SLEEP);
1913 
1914 		if (copyin(uprobe, probe, size) != 0) {
1915 			kmem_free(probe, size);
1916 			return (EFAULT);
1917 		}
1918 
1919 		/*
1920 		 * Verify that the function and module strings contain no
1921 		 * funny characters.
1922 		 */
1923 		for (c = &probe->ftps_func[0]; *c != '\0'; c++) {
1924 			if (*c < 0x20 || 0x7f <= *c) {
1925 				ret = EINVAL;
1926 				goto err;
1927 			}
1928 		}
1929 
1930 		for (c = &probe->ftps_mod[0]; *c != '\0'; c++) {
1931 			if (*c < 0x20 || 0x7f <= *c) {
1932 				ret = EINVAL;
1933 				goto err;
1934 			}
1935 		}
1936 
1937 		if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
1938 			proc_t *p;
1939 			pid_t pid = probe->ftps_pid;
1940 
1941 			mutex_enter(&pidlock);
1942 			/*
1943 			 * Report an error if the process doesn't exist
1944 			 * or is actively being birthed.
1945 			 */
1946 			if ((p = prfind(pid)) == NULL || p->p_stat == SIDL) {
1947 				mutex_exit(&pidlock);
1948 				return (ESRCH);
1949 			}
1950 			mutex_enter(&p->p_lock);
1951 			mutex_exit(&pidlock);
1952 
1953 			if ((ret = priv_proc_cred_perm(cr, p, NULL,
1954 			    VREAD | VWRITE)) != 0) {
1955 				mutex_exit(&p->p_lock);
1956 				return (ret);
1957 			}
1958 
1959 			mutex_exit(&p->p_lock);
1960 		}
1961 
1962 		ret = fasttrap_add_probe(probe);
1963 err:
1964 		kmem_free(probe, size);
1965 
1966 		return (ret);
1967 
1968 	} else if (cmd == FASTTRAPIOC_GETINSTR) {
1969 		fasttrap_instr_query_t instr;
1970 		fasttrap_tracepoint_t *tp;
1971 		uint_t index;
1972 		int ret;
1973 
1974 		if (copyin((void *)arg, &instr, sizeof (instr)) != 0)
1975 			return (EFAULT);
1976 
1977 		if (!PRIV_POLICY_CHOICE(cr, PRIV_ALL, B_FALSE)) {
1978 			proc_t *p;
1979 			pid_t pid = instr.ftiq_pid;
1980 
1981 			mutex_enter(&pidlock);
1982 			/*
1983 			 * Report an error if the process doesn't exist
1984 			 * or is actively being birthed.
1985 			 */
1986 			if ((p = prfind(pid)) == NULL || p->p_stat == SIDL) {
1987 				mutex_exit(&pidlock);
1988 				return (ESRCH);
1989 			}
1990 			mutex_enter(&p->p_lock);
1991 			mutex_exit(&pidlock);
1992 
1993 			if ((ret = priv_proc_cred_perm(cr, p, NULL,
1994 			    VREAD)) != 0) {
1995 				mutex_exit(&p->p_lock);
1996 				return (ret);
1997 			}
1998 
1999 			mutex_exit(&p->p_lock);
2000 		}
2001 
2002 		index = FASTTRAP_TPOINTS_INDEX(instr.ftiq_pid, instr.ftiq_pc);
2003 
2004 		mutex_enter(&fasttrap_tpoints.fth_table[index].ftb_mtx);
2005 		tp = fasttrap_tpoints.fth_table[index].ftb_data;
2006 		while (tp != NULL) {
2007 			if (instr.ftiq_pid == tp->ftt_pid &&
2008 			    instr.ftiq_pc == tp->ftt_pc &&
2009 			    !tp->ftt_proc->ftpc_defunct)
2010 				break;
2011 
2012 			tp = tp->ftt_next;
2013 		}
2014 
2015 		if (tp == NULL) {
2016 			mutex_exit(&fasttrap_tpoints.fth_table[index].ftb_mtx);
2017 			return (ENOENT);
2018 		}
2019 
2020 		bcopy(&tp->ftt_instr, &instr.ftiq_instr,
2021 		    sizeof (instr.ftiq_instr));
2022 		mutex_exit(&fasttrap_tpoints.fth_table[index].ftb_mtx);
2023 
2024 		if (copyout(&instr, (void *)arg, sizeof (instr)) != 0)
2025 			return (EFAULT);
2026 
2027 		return (0);
2028 	}
2029 
2030 	return (EINVAL);
2031 }
2032 
2033 static struct cb_ops fasttrap_cb_ops = {
2034 	fasttrap_open,		/* open */
2035 	nodev,			/* close */
2036 	nulldev,		/* strategy */
2037 	nulldev,		/* print */
2038 	nodev,			/* dump */
2039 	nodev,			/* read */
2040 	nodev,			/* write */
2041 	fasttrap_ioctl,		/* ioctl */
2042 	nodev,			/* devmap */
2043 	nodev,			/* mmap */
2044 	nodev,			/* segmap */
2045 	nochpoll,		/* poll */
2046 	ddi_prop_op,		/* cb_prop_op */
2047 	0,			/* streamtab  */
2048 	D_NEW | D_MP		/* Driver compatibility flag */
2049 };
2050 
2051 /*ARGSUSED*/
2052 static int
2053 fasttrap_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2054 {
2055 	int error;
2056 
2057 	switch (infocmd) {
2058 	case DDI_INFO_DEVT2DEVINFO:
2059 		*result = (void *)fasttrap_devi;
2060 		error = DDI_SUCCESS;
2061 		break;
2062 	case DDI_INFO_DEVT2INSTANCE:
2063 		*result = (void *)0;
2064 		error = DDI_SUCCESS;
2065 		break;
2066 	default:
2067 		error = DDI_FAILURE;
2068 	}
2069 	return (error);
2070 }
2071 
2072 static int
2073 fasttrap_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
2074 {
2075 	ulong_t nent;
2076 
2077 	switch (cmd) {
2078 	case DDI_ATTACH:
2079 		break;
2080 	case DDI_RESUME:
2081 		return (DDI_SUCCESS);
2082 	default:
2083 		return (DDI_FAILURE);
2084 	}
2085 
2086 	if (ddi_create_minor_node(devi, "fasttrap", S_IFCHR, 0,
2087 	    DDI_PSEUDO, NULL) == DDI_FAILURE) {
2088 		ddi_remove_minor_node(devi, NULL);
2089 		return (DDI_FAILURE);
2090 	}
2091 
2092 	ddi_report_dev(devi);
2093 	fasttrap_devi = devi;
2094 
2095 	/*
2096 	 * Install our hooks into fork(2), exec(2), and exit(2).
2097 	 */
2098 	dtrace_fasttrap_fork_ptr = &fasttrap_fork;
2099 	dtrace_fasttrap_exit_ptr = &fasttrap_exec_exit;
2100 	dtrace_fasttrap_exec_ptr = &fasttrap_exec_exit;
2101 
2102 	fasttrap_max = ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
2103 	    "fasttrap-max-probes", FASTTRAP_MAX_DEFAULT);
2104 	fasttrap_total = 0;
2105 
2106 	/*
2107 	 * Conjure up the tracepoints hashtable...
2108 	 */
2109 	nent = ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
2110 	    "fasttrap-hash-size", FASTTRAP_TPOINTS_DEFAULT_SIZE);
2111 
2112 	if (nent == 0 || nent > 0x1000000)
2113 		nent = FASTTRAP_TPOINTS_DEFAULT_SIZE;
2114 
2115 	if ((nent & (nent - 1)) == 0)
2116 		fasttrap_tpoints.fth_nent = nent;
2117 	else
2118 		fasttrap_tpoints.fth_nent = 1 << fasttrap_highbit(nent);
2119 	ASSERT(fasttrap_tpoints.fth_nent > 0);
2120 	fasttrap_tpoints.fth_mask = fasttrap_tpoints.fth_nent - 1;
2121 	fasttrap_tpoints.fth_table = kmem_zalloc(fasttrap_tpoints.fth_nent *
2122 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
2123 
2124 	/*
2125 	 * ... and the providers hash table...
2126 	 */
2127 	nent = FASTTRAP_PROVIDERS_DEFAULT_SIZE;
2128 	if ((nent & (nent - 1)) == 0)
2129 		fasttrap_provs.fth_nent = nent;
2130 	else
2131 		fasttrap_provs.fth_nent = 1 << fasttrap_highbit(nent);
2132 	ASSERT(fasttrap_provs.fth_nent > 0);
2133 	fasttrap_provs.fth_mask = fasttrap_provs.fth_nent - 1;
2134 	fasttrap_provs.fth_table = kmem_zalloc(fasttrap_provs.fth_nent *
2135 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
2136 
2137 	/*
2138 	 * ... and the procs hash table.
2139 	 */
2140 	nent = FASTTRAP_PROCS_DEFAULT_SIZE;
2141 	if ((nent & (nent - 1)) == 0)
2142 		fasttrap_procs.fth_nent = nent;
2143 	else
2144 		fasttrap_procs.fth_nent = 1 << fasttrap_highbit(nent);
2145 	ASSERT(fasttrap_procs.fth_nent > 0);
2146 	fasttrap_procs.fth_mask = fasttrap_procs.fth_nent - 1;
2147 	fasttrap_procs.fth_table = kmem_zalloc(fasttrap_procs.fth_nent *
2148 	    sizeof (fasttrap_bucket_t), KM_SLEEP);
2149 
2150 	(void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
2151 	    &fasttrap_meta_id);
2152 
2153 	return (DDI_SUCCESS);
2154 }
2155 
2156 static int
2157 fasttrap_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
2158 {
2159 	int i, fail = 0;
2160 	timeout_id_t tmp;
2161 
2162 	switch (cmd) {
2163 	case DDI_DETACH:
2164 		break;
2165 	case DDI_SUSPEND:
2166 		return (DDI_SUCCESS);
2167 	default:
2168 		return (DDI_FAILURE);
2169 	}
2170 
2171 	/*
2172 	 * Unregister the meta-provider to make sure no new fasttrap-
2173 	 * managed providers come along while we're trying to close up
2174 	 * shop. If we fail to detach, we'll need to re-register as a
2175 	 * meta-provider. We can fail to unregister as a meta-provider
2176 	 * if providers we manage still exist.
2177 	 */
2178 	if (fasttrap_meta_id != DTRACE_METAPROVNONE &&
2179 	    dtrace_meta_unregister(fasttrap_meta_id) != 0)
2180 		return (DDI_FAILURE);
2181 
2182 	/*
2183 	 * Prevent any new timeouts from running by setting fasttrap_timeout
2184 	 * to a non-zero value, and wait for the current timeout to complete.
2185 	 */
2186 	mutex_enter(&fasttrap_cleanup_mtx);
2187 	fasttrap_cleanup_work = 0;
2188 
2189 	while (fasttrap_timeout != (timeout_id_t)1) {
2190 		tmp = fasttrap_timeout;
2191 		fasttrap_timeout = (timeout_id_t)1;
2192 
2193 		if (tmp != 0) {
2194 			mutex_exit(&fasttrap_cleanup_mtx);
2195 			(void) untimeout(tmp);
2196 			mutex_enter(&fasttrap_cleanup_mtx);
2197 		}
2198 	}
2199 
2200 	fasttrap_cleanup_work = 0;
2201 	mutex_exit(&fasttrap_cleanup_mtx);
2202 
2203 	/*
2204 	 * Iterate over all of our providers. If there's still a process
2205 	 * that corresponds to that pid, fail to detach.
2206 	 */
2207 	for (i = 0; i < fasttrap_provs.fth_nent; i++) {
2208 		fasttrap_provider_t **fpp, *fp;
2209 		fasttrap_bucket_t *bucket = &fasttrap_provs.fth_table[i];
2210 
2211 		mutex_enter(&bucket->ftb_mtx);
2212 		fpp = (fasttrap_provider_t **)&bucket->ftb_data;
2213 		while ((fp = *fpp) != NULL) {
2214 			/*
2215 			 * Acquire and release the lock as a simple way of
2216 			 * waiting for any other consumer to finish with
2217 			 * this provider. A thread must first acquire the
2218 			 * bucket lock so there's no chance of another thread
2219 			 * blocking on the provider's lock.
2220 			 */
2221 			mutex_enter(&fp->ftp_mtx);
2222 			mutex_exit(&fp->ftp_mtx);
2223 
2224 			if (dtrace_unregister(fp->ftp_provid) != 0) {
2225 				fail = 1;
2226 				fpp = &fp->ftp_next;
2227 			} else {
2228 				*fpp = fp->ftp_next;
2229 				fasttrap_provider_free(fp);
2230 			}
2231 		}
2232 
2233 		mutex_exit(&bucket->ftb_mtx);
2234 	}
2235 
2236 	if (fail) {
2237 		uint_t work;
2238 		/*
2239 		 * If we're failing to detach, we need to unblock timeouts
2240 		 * and start a new timeout if any work has accumulated while
2241 		 * we've been unsuccessfully trying to detach.
2242 		 */
2243 		mutex_enter(&fasttrap_cleanup_mtx);
2244 		fasttrap_timeout = 0;
2245 		work = fasttrap_cleanup_work;
2246 		mutex_exit(&fasttrap_cleanup_mtx);
2247 
2248 		if (work)
2249 			fasttrap_pid_cleanup();
2250 
2251 		(void) dtrace_meta_register("fasttrap", &fasttrap_mops, NULL,
2252 		    &fasttrap_meta_id);
2253 
2254 		return (DDI_FAILURE);
2255 	}
2256 
2257 #ifdef DEBUG
2258 	mutex_enter(&fasttrap_count_mtx);
2259 	ASSERT(fasttrap_pid_count == 0);
2260 	mutex_exit(&fasttrap_count_mtx);
2261 #endif
2262 
2263 	kmem_free(fasttrap_tpoints.fth_table,
2264 	    fasttrap_tpoints.fth_nent * sizeof (fasttrap_bucket_t));
2265 	fasttrap_tpoints.fth_nent = 0;
2266 
2267 	kmem_free(fasttrap_provs.fth_table,
2268 	    fasttrap_provs.fth_nent * sizeof (fasttrap_bucket_t));
2269 	fasttrap_provs.fth_nent = 0;
2270 
2271 	kmem_free(fasttrap_procs.fth_table,
2272 	    fasttrap_procs.fth_nent * sizeof (fasttrap_bucket_t));
2273 	fasttrap_procs.fth_nent = 0;
2274 
2275 	/*
2276 	 * We know there are no tracepoints in any process anywhere in
2277 	 * the system so there is no process which has its p_dtrace_count
2278 	 * greater than zero, therefore we know that no thread can actively
2279 	 * be executing code in fasttrap_fork(). Similarly for p_dtrace_probes
2280 	 * and fasttrap_exec() and fasttrap_exit().
2281 	 */
2282 	ASSERT(dtrace_fasttrap_fork_ptr == &fasttrap_fork);
2283 	dtrace_fasttrap_fork_ptr = NULL;
2284 
2285 	ASSERT(dtrace_fasttrap_exec_ptr == &fasttrap_exec_exit);
2286 	dtrace_fasttrap_exec_ptr = NULL;
2287 
2288 	ASSERT(dtrace_fasttrap_exit_ptr == &fasttrap_exec_exit);
2289 	dtrace_fasttrap_exit_ptr = NULL;
2290 
2291 	ddi_remove_minor_node(devi, NULL);
2292 
2293 	return (DDI_SUCCESS);
2294 }
2295 
2296 static struct dev_ops fasttrap_ops = {
2297 	DEVO_REV,		/* devo_rev */
2298 	0,			/* refcnt */
2299 	fasttrap_info,		/* get_dev_info */
2300 	nulldev,		/* identify */
2301 	nulldev,		/* probe */
2302 	fasttrap_attach,	/* attach */
2303 	fasttrap_detach,	/* detach */
2304 	nodev,			/* reset */
2305 	&fasttrap_cb_ops,	/* driver operations */
2306 	NULL,			/* bus operations */
2307 	nodev			/* dev power */
2308 };
2309 
2310 /*
2311  * Module linkage information for the kernel.
2312  */
2313 static struct modldrv modldrv = {
2314 	&mod_driverops,		/* module type (this is a pseudo driver) */
2315 	"Fasttrap Tracing",	/* name of module */
2316 	&fasttrap_ops,		/* driver ops */
2317 };
2318 
2319 static struct modlinkage modlinkage = {
2320 	MODREV_1,
2321 	(void *)&modldrv,
2322 	NULL
2323 };
2324 
2325 int
2326 _init(void)
2327 {
2328 	return (mod_install(&modlinkage));
2329 }
2330 
2331 int
2332 _info(struct modinfo *modinfop)
2333 {
2334 	return (mod_info(&modlinkage, modinfop));
2335 }
2336 
2337 int
2338 _fini(void)
2339 {
2340 	return (mod_remove(&modlinkage));
2341 }
2342