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