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