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