]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
MFV illumos r266986:
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / dtrace / dtrace.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  * $FreeBSD$
22  */
23
24 /*
25  * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2012 by Delphix. All rights reserved.
28  */
29
30 #pragma ident   "%Z%%M% %I%     %E% SMI"
31
32 /*
33  * DTrace - Dynamic Tracing for Solaris
34  *
35  * This is the implementation of the Solaris Dynamic Tracing framework
36  * (DTrace).  The user-visible interface to DTrace is described at length in
37  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
38  * library, the in-kernel DTrace framework, and the DTrace providers are
39  * described in the block comments in the <sys/dtrace.h> header file.  The
40  * internal architecture of DTrace is described in the block comments in the
41  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
42  * implementation very much assume mastery of all of these sources; if one has
43  * an unanswered question about the implementation, one should consult them
44  * first.
45  *
46  * The functions here are ordered roughly as follows:
47  *
48  *   - Probe context functions
49  *   - Probe hashing functions
50  *   - Non-probe context utility functions
51  *   - Matching functions
52  *   - Provider-to-Framework API functions
53  *   - Probe management functions
54  *   - DIF object functions
55  *   - Format functions
56  *   - Predicate functions
57  *   - ECB functions
58  *   - Buffer functions
59  *   - Enabling functions
60  *   - DOF functions
61  *   - Anonymous enabling functions
62  *   - Consumer state functions
63  *   - Helper functions
64  *   - Hook functions
65  *   - Driver cookbook functions
66  *
67  * Each group of functions begins with a block comment labelled the "DTrace
68  * [Group] Functions", allowing one to find each block by searching forward
69  * on capital-f functions.
70  */
71 #include <sys/errno.h>
72 #if !defined(sun)
73 #include <sys/time.h>
74 #endif
75 #include <sys/stat.h>
76 #include <sys/modctl.h>
77 #include <sys/conf.h>
78 #include <sys/systm.h>
79 #if defined(sun)
80 #include <sys/ddi.h>
81 #include <sys/sunddi.h>
82 #endif
83 #include <sys/cpuvar.h>
84 #include <sys/kmem.h>
85 #if defined(sun)
86 #include <sys/strsubr.h>
87 #endif
88 #include <sys/sysmacros.h>
89 #include <sys/dtrace_impl.h>
90 #include <sys/atomic.h>
91 #include <sys/cmn_err.h>
92 #if defined(sun)
93 #include <sys/mutex_impl.h>
94 #include <sys/rwlock_impl.h>
95 #endif
96 #include <sys/ctf_api.h>
97 #if defined(sun)
98 #include <sys/panic.h>
99 #include <sys/priv_impl.h>
100 #endif
101 #include <sys/policy.h>
102 #if defined(sun)
103 #include <sys/cred_impl.h>
104 #include <sys/procfs_isa.h>
105 #endif
106 #include <sys/taskq.h>
107 #if defined(sun)
108 #include <sys/mkdev.h>
109 #include <sys/kdi.h>
110 #endif
111 #include <sys/zone.h>
112 #include <sys/socket.h>
113 #include <netinet/in.h>
114
115 /* FreeBSD includes: */
116 #if !defined(sun)
117 #include <sys/callout.h>
118 #include <sys/ctype.h>
119 #include <sys/eventhandler.h>
120 #include <sys/limits.h>
121 #include <sys/kdb.h>
122 #include <sys/kernel.h>
123 #include <sys/malloc.h>
124 #include <sys/sysctl.h>
125 #include <sys/lock.h>
126 #include <sys/mutex.h>
127 #include <sys/rwlock.h>
128 #include <sys/sx.h>
129 #include <sys/dtrace_bsd.h>
130 #include <netinet/in.h>
131 #include "dtrace_cddl.h"
132 #include "dtrace_debug.c"
133 #endif
134
135 /*
136  * DTrace Tunable Variables
137  *
138  * The following variables may be tuned by adding a line to /etc/system that
139  * includes both the name of the DTrace module ("dtrace") and the name of the
140  * variable.  For example:
141  *
142  *   set dtrace:dtrace_destructive_disallow = 1
143  *
144  * In general, the only variables that one should be tuning this way are those
145  * that affect system-wide DTrace behavior, and for which the default behavior
146  * is undesirable.  Most of these variables are tunable on a per-consumer
147  * basis using DTrace options, and need not be tuned on a system-wide basis.
148  * When tuning these variables, avoid pathological values; while some attempt
149  * is made to verify the integrity of these variables, they are not considered
150  * part of the supported interface to DTrace, and they are therefore not
151  * checked comprehensively.  Further, these variables should not be tuned
152  * dynamically via "mdb -kw" or other means; they should only be tuned via
153  * /etc/system.
154  */
155 int             dtrace_destructive_disallow = 0;
156 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
157 size_t          dtrace_difo_maxsize = (256 * 1024);
158 dtrace_optval_t dtrace_dof_maxsize = (8 * 1024 * 1024);
159 size_t          dtrace_global_maxsize = (16 * 1024);
160 size_t          dtrace_actions_max = (16 * 1024);
161 size_t          dtrace_retain_max = 1024;
162 dtrace_optval_t dtrace_helper_actions_max = 128;
163 dtrace_optval_t dtrace_helper_providers_max = 32;
164 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
165 size_t          dtrace_strsize_default = 256;
166 dtrace_optval_t dtrace_cleanrate_default = 9900990;             /* 101 hz */
167 dtrace_optval_t dtrace_cleanrate_min = 200000;                  /* 5000 hz */
168 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;  /* 1/minute */
169 dtrace_optval_t dtrace_aggrate_default = NANOSEC;               /* 1 hz */
170 dtrace_optval_t dtrace_statusrate_default = NANOSEC;            /* 1 hz */
171 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;  /* 6/minute */
172 dtrace_optval_t dtrace_switchrate_default = NANOSEC;            /* 1 hz */
173 dtrace_optval_t dtrace_nspec_default = 1;
174 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
175 dtrace_optval_t dtrace_stackframes_default = 20;
176 dtrace_optval_t dtrace_ustackframes_default = 20;
177 dtrace_optval_t dtrace_jstackframes_default = 50;
178 dtrace_optval_t dtrace_jstackstrsize_default = 512;
179 int             dtrace_msgdsize_max = 128;
180 hrtime_t        dtrace_chill_max = 500 * (NANOSEC / MILLISEC);  /* 500 ms */
181 hrtime_t        dtrace_chill_interval = NANOSEC;                /* 1000 ms */
182 int             dtrace_devdepth_max = 32;
183 int             dtrace_err_verbose;
184 hrtime_t        dtrace_deadman_interval = NANOSEC;
185 hrtime_t        dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
186 hrtime_t        dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
187 hrtime_t        dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
188 #if !defined(sun)
189 int             dtrace_memstr_max = 4096;
190 #endif
191
192 /*
193  * DTrace External Variables
194  *
195  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
196  * available to DTrace consumers via the backtick (`) syntax.  One of these,
197  * dtrace_zero, is made deliberately so:  it is provided as a source of
198  * well-known, zero-filled memory.  While this variable is not documented,
199  * it is used by some translators as an implementation detail.
200  */
201 const char      dtrace_zero[256] = { 0 };       /* zero-filled memory */
202
203 /*
204  * DTrace Internal Variables
205  */
206 #if defined(sun)
207 static dev_info_t       *dtrace_devi;           /* device info */
208 #endif
209 #if defined(sun)
210 static vmem_t           *dtrace_arena;          /* probe ID arena */
211 static vmem_t           *dtrace_minor;          /* minor number arena */
212 #else
213 static taskq_t          *dtrace_taskq;          /* task queue */
214 static struct unrhdr    *dtrace_arena;          /* Probe ID number.     */
215 #endif
216 static dtrace_probe_t   **dtrace_probes;        /* array of all probes */
217 static int              dtrace_nprobes;         /* number of probes */
218 static dtrace_provider_t *dtrace_provider;      /* provider list */
219 static dtrace_meta_t    *dtrace_meta_pid;       /* user-land meta provider */
220 static int              dtrace_opens;           /* number of opens */
221 static int              dtrace_helpers;         /* number of helpers */
222 static int              dtrace_getf;            /* number of unpriv getf()s */
223 #if defined(sun)
224 static void             *dtrace_softstate;      /* softstate pointer */
225 #endif
226 static dtrace_hash_t    *dtrace_bymod;          /* probes hashed by module */
227 static dtrace_hash_t    *dtrace_byfunc;         /* probes hashed by function */
228 static dtrace_hash_t    *dtrace_byname;         /* probes hashed by name */
229 static dtrace_toxrange_t *dtrace_toxrange;      /* toxic range array */
230 static int              dtrace_toxranges;       /* number of toxic ranges */
231 static int              dtrace_toxranges_max;   /* size of toxic range array */
232 static dtrace_anon_t    dtrace_anon;            /* anonymous enabling */
233 static kmem_cache_t     *dtrace_state_cache;    /* cache for dynamic state */
234 static uint64_t         dtrace_vtime_references; /* number of vtimestamp refs */
235 static kthread_t        *dtrace_panicked;       /* panicking thread */
236 static dtrace_ecb_t     *dtrace_ecb_create_cache; /* cached created ECB */
237 static dtrace_genid_t   dtrace_probegen;        /* current probe generation */
238 static dtrace_helpers_t *dtrace_deferred_pid;   /* deferred helper list */
239 static dtrace_enabling_t *dtrace_retained;      /* list of retained enablings */
240 static dtrace_dynvar_t  dtrace_dynhash_sink;    /* end of dynamic hash chains */
241 #if !defined(sun)
242 static struct mtx       dtrace_unr_mtx;
243 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
244 int             dtrace_in_probe;        /* non-zero if executing a probe */
245 #if defined(__i386__) || defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
246 uintptr_t       dtrace_in_probe_addr;   /* Address of invop when already in probe */
247 #endif
248 static eventhandler_tag dtrace_kld_load_tag;
249 static eventhandler_tag dtrace_kld_unload_try_tag;
250 #endif
251
252 /*
253  * DTrace Locking
254  * DTrace is protected by three (relatively coarse-grained) locks:
255  *
256  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
257  *     including enabling state, probes, ECBs, consumer state, helper state,
258  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
259  *     probe context is lock-free -- synchronization is handled via the
260  *     dtrace_sync() cross call mechanism.
261  *
262  * (2) dtrace_provider_lock is required when manipulating provider state, or
263  *     when provider state must be held constant.
264  *
265  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
266  *     when meta provider state must be held constant.
267  *
268  * The lock ordering between these three locks is dtrace_meta_lock before
269  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
270  * several places where dtrace_provider_lock is held by the framework as it
271  * calls into the providers -- which then call back into the framework,
272  * grabbing dtrace_lock.)
273  *
274  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
275  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
276  * role as a coarse-grained lock; it is acquired before both of these locks.
277  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
278  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
279  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
280  * acquired _between_ dtrace_provider_lock and dtrace_lock.
281  */
282 static kmutex_t         dtrace_lock;            /* probe state lock */
283 static kmutex_t         dtrace_provider_lock;   /* provider state lock */
284 static kmutex_t         dtrace_meta_lock;       /* meta-provider state lock */
285
286 #if !defined(sun)
287 /* XXX FreeBSD hacks. */
288 #define cr_suid         cr_svuid
289 #define cr_sgid         cr_svgid
290 #define ipaddr_t        in_addr_t
291 #define mod_modname     pathname
292 #define vuprintf        vprintf
293 #define ttoproc(_a)     ((_a)->td_proc)
294 #define crgetzoneid(_a) 0
295 #define NCPU            MAXCPU
296 #define SNOCD           0
297 #define CPU_ON_INTR(_a) 0
298
299 #define PRIV_EFFECTIVE          (1 << 0)
300 #define PRIV_DTRACE_KERNEL      (1 << 1)
301 #define PRIV_DTRACE_PROC        (1 << 2)
302 #define PRIV_DTRACE_USER        (1 << 3)
303 #define PRIV_PROC_OWNER         (1 << 4)
304 #define PRIV_PROC_ZONE          (1 << 5)
305 #define PRIV_ALL                ~0
306
307 SYSCTL_DECL(_debug_dtrace);
308 SYSCTL_DECL(_kern_dtrace);
309 #endif
310
311 #if defined(sun)
312 #define curcpu  CPU->cpu_id
313 #endif
314
315
316 /*
317  * DTrace Provider Variables
318  *
319  * These are the variables relating to DTrace as a provider (that is, the
320  * provider of the BEGIN, END, and ERROR probes).
321  */
322 static dtrace_pattr_t   dtrace_provider_attr = {
323 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
324 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
325 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
326 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
327 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
328 };
329
330 static void
331 dtrace_nullop(void)
332 {}
333
334 static dtrace_pops_t    dtrace_provider_ops = {
335         (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
336         (void (*)(void *, modctl_t *))dtrace_nullop,
337         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
338         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
339         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
340         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
341         NULL,
342         NULL,
343         NULL,
344         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
345 };
346
347 static dtrace_id_t      dtrace_probeid_begin;   /* special BEGIN probe */
348 static dtrace_id_t      dtrace_probeid_end;     /* special END probe */
349 dtrace_id_t             dtrace_probeid_error;   /* special ERROR probe */
350
351 /*
352  * DTrace Helper Tracing Variables
353  */
354 uint32_t dtrace_helptrace_next = 0;
355 uint32_t dtrace_helptrace_nlocals;
356 char    *dtrace_helptrace_buffer;
357 int     dtrace_helptrace_bufsize = 512 * 1024;
358
359 #ifdef DEBUG
360 int     dtrace_helptrace_enabled = 1;
361 #else
362 int     dtrace_helptrace_enabled = 0;
363 #endif
364
365 /*
366  * DTrace Error Hashing
367  *
368  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
369  * table.  This is very useful for checking coverage of tests that are
370  * expected to induce DIF or DOF processing errors, and may be useful for
371  * debugging problems in the DIF code generator or in DOF generation .  The
372  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
373  */
374 #ifdef DEBUG
375 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
376 static const char *dtrace_errlast;
377 static kthread_t *dtrace_errthread;
378 static kmutex_t dtrace_errlock;
379 #endif
380
381 /*
382  * DTrace Macros and Constants
383  *
384  * These are various macros that are useful in various spots in the
385  * implementation, along with a few random constants that have no meaning
386  * outside of the implementation.  There is no real structure to this cpp
387  * mishmash -- but is there ever?
388  */
389 #define DTRACE_HASHSTR(hash, probe)     \
390         dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
391
392 #define DTRACE_HASHNEXT(hash, probe)    \
393         (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
394
395 #define DTRACE_HASHPREV(hash, probe)    \
396         (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
397
398 #define DTRACE_HASHEQ(hash, lhs, rhs)   \
399         (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
400             *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
401
402 #define DTRACE_AGGHASHSIZE_SLEW         17
403
404 #define DTRACE_V4MAPPED_OFFSET          (sizeof (uint32_t) * 3)
405
406 /*
407  * The key for a thread-local variable consists of the lower 61 bits of the
408  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
409  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
410  * equal to a variable identifier.  This is necessary (but not sufficient) to
411  * assure that global associative arrays never collide with thread-local
412  * variables.  To guarantee that they cannot collide, we must also define the
413  * order for keying dynamic variables.  That order is:
414  *
415  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
416  *
417  * Because the variable-key and the tls-key are in orthogonal spaces, there is
418  * no way for a global variable key signature to match a thread-local key
419  * signature.
420  */
421 #if defined(sun)
422 #define DTRACE_TLS_THRKEY(where) { \
423         uint_t intr = 0; \
424         uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
425         for (; actv; actv >>= 1) \
426                 intr++; \
427         ASSERT(intr < (1 << 3)); \
428         (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
429             (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
430 }
431 #else
432 #define DTRACE_TLS_THRKEY(where) { \
433         solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
434         uint_t intr = 0; \
435         uint_t actv = _c->cpu_intr_actv; \
436         for (; actv; actv >>= 1) \
437                 intr++; \
438         ASSERT(intr < (1 << 3)); \
439         (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
440             (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
441 }
442 #endif
443
444 #define DT_BSWAP_8(x)   ((x) & 0xff)
445 #define DT_BSWAP_16(x)  ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
446 #define DT_BSWAP_32(x)  ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
447 #define DT_BSWAP_64(x)  ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
448
449 #define DT_MASK_LO 0x00000000FFFFFFFFULL
450
451 #define DTRACE_STORE(type, tomax, offset, what) \
452         *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
453
454 #ifndef __x86
455 #define DTRACE_ALIGNCHECK(addr, size, flags)                            \
456         if (addr & (size - 1)) {                                        \
457                 *flags |= CPU_DTRACE_BADALIGN;                          \
458                 cpu_core[curcpu].cpuc_dtrace_illval = addr;     \
459                 return (0);                                             \
460         }
461 #else
462 #define DTRACE_ALIGNCHECK(addr, size, flags)
463 #endif
464
465 /*
466  * Test whether a range of memory starting at testaddr of size testsz falls
467  * within the range of memory described by addr, sz.  We take care to avoid
468  * problems with overflow and underflow of the unsigned quantities, and
469  * disallow all negative sizes.  Ranges of size 0 are allowed.
470  */
471 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
472         ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
473         (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
474         (testaddr) + (testsz) >= (testaddr))
475
476 /*
477  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
478  * alloc_sz on the righthand side of the comparison in order to avoid overflow
479  * or underflow in the comparison with it.  This is simpler than the INRANGE
480  * check above, because we know that the dtms_scratch_ptr is valid in the
481  * range.  Allocations of size zero are allowed.
482  */
483 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
484         ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
485         (mstate)->dtms_scratch_ptr >= (alloc_sz))
486
487 #define DTRACE_LOADFUNC(bits)                                           \
488 /*CSTYLED*/                                                             \
489 uint##bits##_t                                                          \
490 dtrace_load##bits(uintptr_t addr)                                       \
491 {                                                                       \
492         size_t size = bits / NBBY;                                      \
493         /*CSTYLED*/                                                     \
494         uint##bits##_t rval;                                            \
495         int i;                                                          \
496         volatile uint16_t *flags = (volatile uint16_t *)                \
497             &cpu_core[curcpu].cpuc_dtrace_flags;                        \
498                                                                         \
499         DTRACE_ALIGNCHECK(addr, size, flags);                           \
500                                                                         \
501         for (i = 0; i < dtrace_toxranges; i++) {                        \
502                 if (addr >= dtrace_toxrange[i].dtt_limit)               \
503                         continue;                                       \
504                                                                         \
505                 if (addr + size <= dtrace_toxrange[i].dtt_base)         \
506                         continue;                                       \
507                                                                         \
508                 /*                                                      \
509                  * This address falls within a toxic region; return 0.  \
510                  */                                                     \
511                 *flags |= CPU_DTRACE_BADADDR;                           \
512                 cpu_core[curcpu].cpuc_dtrace_illval = addr;             \
513                 return (0);                                             \
514         }                                                               \
515                                                                         \
516         *flags |= CPU_DTRACE_NOFAULT;                                   \
517         /*CSTYLED*/                                                     \
518         rval = *((volatile uint##bits##_t *)addr);                      \
519         *flags &= ~CPU_DTRACE_NOFAULT;                                  \
520                                                                         \
521         return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);               \
522 }
523
524 #ifdef _LP64
525 #define dtrace_loadptr  dtrace_load64
526 #else
527 #define dtrace_loadptr  dtrace_load32
528 #endif
529
530 #define DTRACE_DYNHASH_FREE     0
531 #define DTRACE_DYNHASH_SINK     1
532 #define DTRACE_DYNHASH_VALID    2
533
534 #define DTRACE_MATCH_NEXT       0
535 #define DTRACE_MATCH_DONE       1
536 #define DTRACE_ANCHORED(probe)  ((probe)->dtpr_func[0] != '\0')
537 #define DTRACE_STATE_ALIGN      64
538
539 #define DTRACE_FLAGS2FLT(flags)                                         \
540         (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :           \
541         ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :                \
542         ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :            \
543         ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :                \
544         ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :                \
545         ((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :         \
546         ((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :         \
547         ((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :       \
548         ((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :         \
549         DTRACEFLT_UNKNOWN)
550
551 #define DTRACEACT_ISSTRING(act)                                         \
552         ((act)->dta_kind == DTRACEACT_DIFEXPR &&                        \
553         (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
554
555 /* Function prototype definitions: */
556 static size_t dtrace_strlen(const char *, size_t);
557 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
558 static void dtrace_enabling_provide(dtrace_provider_t *);
559 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
560 static void dtrace_enabling_matchall(void);
561 static void dtrace_enabling_reap(void);
562 static dtrace_state_t *dtrace_anon_grab(void);
563 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
564     dtrace_state_t *, uint64_t, uint64_t);
565 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
566 static void dtrace_buffer_drop(dtrace_buffer_t *);
567 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
568 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
569     dtrace_state_t *, dtrace_mstate_t *);
570 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
571     dtrace_optval_t);
572 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
573 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
574 uint16_t dtrace_load16(uintptr_t);
575 uint32_t dtrace_load32(uintptr_t);
576 uint64_t dtrace_load64(uintptr_t);
577 uint8_t dtrace_load8(uintptr_t);
578 void dtrace_dynvar_clean(dtrace_dstate_t *);
579 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
580     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
581 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
582 static int dtrace_priv_proc(dtrace_state_t *);
583 static void dtrace_getf_barrier(void);
584
585 /*
586  * DTrace Probe Context Functions
587  *
588  * These functions are called from probe context.  Because probe context is
589  * any context in which C may be called, arbitrarily locks may be held,
590  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
591  * As a result, functions called from probe context may only call other DTrace
592  * support functions -- they may not interact at all with the system at large.
593  * (Note that the ASSERT macro is made probe-context safe by redefining it in
594  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
595  * loads are to be performed from probe context, they _must_ be in terms of
596  * the safe dtrace_load*() variants.
597  *
598  * Some functions in this block are not actually called from probe context;
599  * for these functions, there will be a comment above the function reading
600  * "Note:  not called from probe context."
601  */
602 void
603 dtrace_panic(const char *format, ...)
604 {
605         va_list alist;
606
607         va_start(alist, format);
608         dtrace_vpanic(format, alist);
609         va_end(alist);
610 }
611
612 int
613 dtrace_assfail(const char *a, const char *f, int l)
614 {
615         dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
616
617         /*
618          * We just need something here that even the most clever compiler
619          * cannot optimize away.
620          */
621         return (a[(uintptr_t)f]);
622 }
623
624 /*
625  * Atomically increment a specified error counter from probe context.
626  */
627 static void
628 dtrace_error(uint32_t *counter)
629 {
630         /*
631          * Most counters stored to in probe context are per-CPU counters.
632          * However, there are some error conditions that are sufficiently
633          * arcane that they don't merit per-CPU storage.  If these counters
634          * are incremented concurrently on different CPUs, scalability will be
635          * adversely affected -- but we don't expect them to be white-hot in a
636          * correctly constructed enabling...
637          */
638         uint32_t oval, nval;
639
640         do {
641                 oval = *counter;
642
643                 if ((nval = oval + 1) == 0) {
644                         /*
645                          * If the counter would wrap, set it to 1 -- assuring
646                          * that the counter is never zero when we have seen
647                          * errors.  (The counter must be 32-bits because we
648                          * aren't guaranteed a 64-bit compare&swap operation.)
649                          * To save this code both the infamy of being fingered
650                          * by a priggish news story and the indignity of being
651                          * the target of a neo-puritan witch trial, we're
652                          * carefully avoiding any colorful description of the
653                          * likelihood of this condition -- but suffice it to
654                          * say that it is only slightly more likely than the
655                          * overflow of predicate cache IDs, as discussed in
656                          * dtrace_predicate_create().
657                          */
658                         nval = 1;
659                 }
660         } while (dtrace_cas32(counter, oval, nval) != oval);
661 }
662
663 /*
664  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
665  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
666  */
667 DTRACE_LOADFUNC(8)
668 DTRACE_LOADFUNC(16)
669 DTRACE_LOADFUNC(32)
670 DTRACE_LOADFUNC(64)
671
672 static int
673 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
674 {
675         if (dest < mstate->dtms_scratch_base)
676                 return (0);
677
678         if (dest + size < dest)
679                 return (0);
680
681         if (dest + size > mstate->dtms_scratch_ptr)
682                 return (0);
683
684         return (1);
685 }
686
687 static int
688 dtrace_canstore_statvar(uint64_t addr, size_t sz,
689     dtrace_statvar_t **svars, int nsvars)
690 {
691         int i;
692
693         for (i = 0; i < nsvars; i++) {
694                 dtrace_statvar_t *svar = svars[i];
695
696                 if (svar == NULL || svar->dtsv_size == 0)
697                         continue;
698
699                 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
700                         return (1);
701         }
702
703         return (0);
704 }
705
706 /*
707  * Check to see if the address is within a memory region to which a store may
708  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
709  * region.  The caller of dtrace_canstore() is responsible for performing any
710  * alignment checks that are needed before stores are actually executed.
711  */
712 static int
713 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
714     dtrace_vstate_t *vstate)
715 {
716         /*
717          * First, check to see if the address is in scratch space...
718          */
719         if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
720             mstate->dtms_scratch_size))
721                 return (1);
722
723         /*
724          * Now check to see if it's a dynamic variable.  This check will pick
725          * up both thread-local variables and any global dynamically-allocated
726          * variables.
727          */
728         if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
729             vstate->dtvs_dynvars.dtds_size)) {
730                 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
731                 uintptr_t base = (uintptr_t)dstate->dtds_base +
732                     (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
733                 uintptr_t chunkoffs;
734
735                 /*
736                  * Before we assume that we can store here, we need to make
737                  * sure that it isn't in our metadata -- storing to our
738                  * dynamic variable metadata would corrupt our state.  For
739                  * the range to not include any dynamic variable metadata,
740                  * it must:
741                  *
742                  *      (1) Start above the hash table that is at the base of
743                  *      the dynamic variable space
744                  *
745                  *      (2) Have a starting chunk offset that is beyond the
746                  *      dtrace_dynvar_t that is at the base of every chunk
747                  *
748                  *      (3) Not span a chunk boundary
749                  *
750                  */
751                 if (addr < base)
752                         return (0);
753
754                 chunkoffs = (addr - base) % dstate->dtds_chunksize;
755
756                 if (chunkoffs < sizeof (dtrace_dynvar_t))
757                         return (0);
758
759                 if (chunkoffs + sz > dstate->dtds_chunksize)
760                         return (0);
761
762                 return (1);
763         }
764
765         /*
766          * Finally, check the static local and global variables.  These checks
767          * take the longest, so we perform them last.
768          */
769         if (dtrace_canstore_statvar(addr, sz,
770             vstate->dtvs_locals, vstate->dtvs_nlocals))
771                 return (1);
772
773         if (dtrace_canstore_statvar(addr, sz,
774             vstate->dtvs_globals, vstate->dtvs_nglobals))
775                 return (1);
776
777         return (0);
778 }
779
780
781 /*
782  * Convenience routine to check to see if the address is within a memory
783  * region in which a load may be issued given the user's privilege level;
784  * if not, it sets the appropriate error flags and loads 'addr' into the
785  * illegal value slot.
786  *
787  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
788  * appropriate memory access protection.
789  */
790 static int
791 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
792     dtrace_vstate_t *vstate)
793 {
794         volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
795         file_t *fp;
796
797         /*
798          * If we hold the privilege to read from kernel memory, then
799          * everything is readable.
800          */
801         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
802                 return (1);
803
804         /*
805          * You can obviously read that which you can store.
806          */
807         if (dtrace_canstore(addr, sz, mstate, vstate))
808                 return (1);
809
810         /*
811          * We're allowed to read from our own string table.
812          */
813         if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
814             mstate->dtms_difo->dtdo_strlen))
815                 return (1);
816
817         if (vstate->dtvs_state != NULL &&
818             dtrace_priv_proc(vstate->dtvs_state)) {
819                 proc_t *p;
820
821                 /*
822                  * When we have privileges to the current process, there are
823                  * several context-related kernel structures that are safe to
824                  * read, even absent the privilege to read from kernel memory.
825                  * These reads are safe because these structures contain only
826                  * state that (1) we're permitted to read, (2) is harmless or
827                  * (3) contains pointers to additional kernel state that we're
828                  * not permitted to read (and as such, do not present an
829                  * opportunity for privilege escalation).  Finally (and
830                  * critically), because of the nature of their relation with
831                  * the current thread context, the memory associated with these
832                  * structures cannot change over the duration of probe context,
833                  * and it is therefore impossible for this memory to be
834                  * deallocated and reallocated as something else while it's
835                  * being operated upon.
836                  */
837                 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
838                         return (1);
839
840                 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
841                     sz, curthread->t_procp, sizeof (proc_t))) {
842                         return (1);
843                 }
844
845                 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
846                     curthread->t_cred, sizeof (cred_t))) {
847                         return (1);
848                 }
849
850 #if defined(sun)
851                 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
852                     &(p->p_pidp->pid_id), sizeof (pid_t))) {
853                         return (1);
854                 }
855
856                 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
857                     curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
858                         return (1);
859                 }
860 #endif
861         }
862
863         if ((fp = mstate->dtms_getf) != NULL) {
864                 uintptr_t psz = sizeof (void *);
865                 vnode_t *vp;
866                 vnodeops_t *op;
867
868                 /*
869                  * When getf() returns a file_t, the enabling is implicitly
870                  * granted the (transient) right to read the returned file_t
871                  * as well as the v_path and v_op->vnop_name of the underlying
872                  * vnode.  These accesses are allowed after a successful
873                  * getf() because the members that they refer to cannot change
874                  * once set -- and the barrier logic in the kernel's closef()
875                  * path assures that the file_t and its referenced vode_t
876                  * cannot themselves be stale (that is, it impossible for
877                  * either dtms_getf itself or its f_vnode member to reference
878                  * freed memory).
879                  */
880                 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
881                         return (1);
882
883                 if ((vp = fp->f_vnode) != NULL) {
884 #if defined(sun)
885                         if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
886                                 return (1);
887                         if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
888                             vp->v_path, strlen(vp->v_path) + 1)) {
889                                 return (1);
890                         }
891 #endif
892
893                         if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
894                                 return (1);
895
896 #if defined(sun)
897                         if ((op = vp->v_op) != NULL &&
898                             DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
899                                 return (1);
900                         }
901
902                         if (op != NULL && op->vnop_name != NULL &&
903                             DTRACE_INRANGE(addr, sz, op->vnop_name,
904                             strlen(op->vnop_name) + 1)) {
905                                 return (1);
906                         }
907 #endif
908                 }
909         }
910
911         DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
912         *illval = addr;
913         return (0);
914 }
915
916 /*
917  * Convenience routine to check to see if a given string is within a memory
918  * region in which a load may be issued given the user's privilege level;
919  * this exists so that we don't need to issue unnecessary dtrace_strlen()
920  * calls in the event that the user has all privileges.
921  */
922 static int
923 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
924     dtrace_vstate_t *vstate)
925 {
926         size_t strsz;
927
928         /*
929          * If we hold the privilege to read from kernel memory, then
930          * everything is readable.
931          */
932         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
933                 return (1);
934
935         strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
936         if (dtrace_canload(addr, strsz, mstate, vstate))
937                 return (1);
938
939         return (0);
940 }
941
942 /*
943  * Convenience routine to check to see if a given variable is within a memory
944  * region in which a load may be issued given the user's privilege level.
945  */
946 static int
947 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
948     dtrace_vstate_t *vstate)
949 {
950         size_t sz;
951         ASSERT(type->dtdt_flags & DIF_TF_BYREF);
952
953         /*
954          * If we hold the privilege to read from kernel memory, then
955          * everything is readable.
956          */
957         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
958                 return (1);
959
960         if (type->dtdt_kind == DIF_TYPE_STRING)
961                 sz = dtrace_strlen(src,
962                     vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
963         else
964                 sz = type->dtdt_size;
965
966         return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
967 }
968
969 /*
970  * Compare two strings using safe loads.
971  */
972 static int
973 dtrace_strncmp(char *s1, char *s2, size_t limit)
974 {
975         uint8_t c1, c2;
976         volatile uint16_t *flags;
977
978         if (s1 == s2 || limit == 0)
979                 return (0);
980
981         flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
982
983         do {
984                 if (s1 == NULL) {
985                         c1 = '\0';
986                 } else {
987                         c1 = dtrace_load8((uintptr_t)s1++);
988                 }
989
990                 if (s2 == NULL) {
991                         c2 = '\0';
992                 } else {
993                         c2 = dtrace_load8((uintptr_t)s2++);
994                 }
995
996                 if (c1 != c2)
997                         return (c1 - c2);
998         } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
999
1000         return (0);
1001 }
1002
1003 /*
1004  * Compute strlen(s) for a string using safe memory accesses.  The additional
1005  * len parameter is used to specify a maximum length to ensure completion.
1006  */
1007 static size_t
1008 dtrace_strlen(const char *s, size_t lim)
1009 {
1010         uint_t len;
1011
1012         for (len = 0; len != lim; len++) {
1013                 if (dtrace_load8((uintptr_t)s++) == '\0')
1014                         break;
1015         }
1016
1017         return (len);
1018 }
1019
1020 /*
1021  * Check if an address falls within a toxic region.
1022  */
1023 static int
1024 dtrace_istoxic(uintptr_t kaddr, size_t size)
1025 {
1026         uintptr_t taddr, tsize;
1027         int i;
1028
1029         for (i = 0; i < dtrace_toxranges; i++) {
1030                 taddr = dtrace_toxrange[i].dtt_base;
1031                 tsize = dtrace_toxrange[i].dtt_limit - taddr;
1032
1033                 if (kaddr - taddr < tsize) {
1034                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1035                         cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
1036                         return (1);
1037                 }
1038
1039                 if (taddr - kaddr < size) {
1040                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1041                         cpu_core[curcpu].cpuc_dtrace_illval = taddr;
1042                         return (1);
1043                 }
1044         }
1045
1046         return (0);
1047 }
1048
1049 /*
1050  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1051  * memory specified by the DIF program.  The dst is assumed to be safe memory
1052  * that we can store to directly because it is managed by DTrace.  As with
1053  * standard bcopy, overlapping copies are handled properly.
1054  */
1055 static void
1056 dtrace_bcopy(const void *src, void *dst, size_t len)
1057 {
1058         if (len != 0) {
1059                 uint8_t *s1 = dst;
1060                 const uint8_t *s2 = src;
1061
1062                 if (s1 <= s2) {
1063                         do {
1064                                 *s1++ = dtrace_load8((uintptr_t)s2++);
1065                         } while (--len != 0);
1066                 } else {
1067                         s2 += len;
1068                         s1 += len;
1069
1070                         do {
1071                                 *--s1 = dtrace_load8((uintptr_t)--s2);
1072                         } while (--len != 0);
1073                 }
1074         }
1075 }
1076
1077 /*
1078  * Copy src to dst using safe memory accesses, up to either the specified
1079  * length, or the point that a nul byte is encountered.  The src is assumed to
1080  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1081  * safe memory that we can store to directly because it is managed by DTrace.
1082  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1083  */
1084 static void
1085 dtrace_strcpy(const void *src, void *dst, size_t len)
1086 {
1087         if (len != 0) {
1088                 uint8_t *s1 = dst, c;
1089                 const uint8_t *s2 = src;
1090
1091                 do {
1092                         *s1++ = c = dtrace_load8((uintptr_t)s2++);
1093                 } while (--len != 0 && c != '\0');
1094         }
1095 }
1096
1097 /*
1098  * Copy src to dst, deriving the size and type from the specified (BYREF)
1099  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1100  * program.  The dst is assumed to be DTrace variable memory that is of the
1101  * specified type; we assume that we can store to directly.
1102  */
1103 static void
1104 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1105 {
1106         ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1107
1108         if (type->dtdt_kind == DIF_TYPE_STRING) {
1109                 dtrace_strcpy(src, dst, type->dtdt_size);
1110         } else {
1111                 dtrace_bcopy(src, dst, type->dtdt_size);
1112         }
1113 }
1114
1115 /*
1116  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1117  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1118  * safe memory that we can access directly because it is managed by DTrace.
1119  */
1120 static int
1121 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1122 {
1123         volatile uint16_t *flags;
1124
1125         flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1126
1127         if (s1 == s2)
1128                 return (0);
1129
1130         if (s1 == NULL || s2 == NULL)
1131                 return (1);
1132
1133         if (s1 != s2 && len != 0) {
1134                 const uint8_t *ps1 = s1;
1135                 const uint8_t *ps2 = s2;
1136
1137                 do {
1138                         if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1139                                 return (1);
1140                 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1141         }
1142         return (0);
1143 }
1144
1145 /*
1146  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1147  * is for safe DTrace-managed memory only.
1148  */
1149 static void
1150 dtrace_bzero(void *dst, size_t len)
1151 {
1152         uchar_t *cp;
1153
1154         for (cp = dst; len != 0; len--)
1155                 *cp++ = 0;
1156 }
1157
1158 static void
1159 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1160 {
1161         uint64_t result[2];
1162
1163         result[0] = addend1[0] + addend2[0];
1164         result[1] = addend1[1] + addend2[1] +
1165             (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1166
1167         sum[0] = result[0];
1168         sum[1] = result[1];
1169 }
1170
1171 /*
1172  * Shift the 128-bit value in a by b. If b is positive, shift left.
1173  * If b is negative, shift right.
1174  */
1175 static void
1176 dtrace_shift_128(uint64_t *a, int b)
1177 {
1178         uint64_t mask;
1179
1180         if (b == 0)
1181                 return;
1182
1183         if (b < 0) {
1184                 b = -b;
1185                 if (b >= 64) {
1186                         a[0] = a[1] >> (b - 64);
1187                         a[1] = 0;
1188                 } else {
1189                         a[0] >>= b;
1190                         mask = 1LL << (64 - b);
1191                         mask -= 1;
1192                         a[0] |= ((a[1] & mask) << (64 - b));
1193                         a[1] >>= b;
1194                 }
1195         } else {
1196                 if (b >= 64) {
1197                         a[1] = a[0] << (b - 64);
1198                         a[0] = 0;
1199                 } else {
1200                         a[1] <<= b;
1201                         mask = a[0] >> (64 - b);
1202                         a[1] |= mask;
1203                         a[0] <<= b;
1204                 }
1205         }
1206 }
1207
1208 /*
1209  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1210  * use native multiplication on those, and then re-combine into the
1211  * resulting 128-bit value.
1212  *
1213  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1214  *     hi1 * hi2 << 64 +
1215  *     hi1 * lo2 << 32 +
1216  *     hi2 * lo1 << 32 +
1217  *     lo1 * lo2
1218  */
1219 static void
1220 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1221 {
1222         uint64_t hi1, hi2, lo1, lo2;
1223         uint64_t tmp[2];
1224
1225         hi1 = factor1 >> 32;
1226         hi2 = factor2 >> 32;
1227
1228         lo1 = factor1 & DT_MASK_LO;
1229         lo2 = factor2 & DT_MASK_LO;
1230
1231         product[0] = lo1 * lo2;
1232         product[1] = hi1 * hi2;
1233
1234         tmp[0] = hi1 * lo2;
1235         tmp[1] = 0;
1236         dtrace_shift_128(tmp, 32);
1237         dtrace_add_128(product, tmp, product);
1238
1239         tmp[0] = hi2 * lo1;
1240         tmp[1] = 0;
1241         dtrace_shift_128(tmp, 32);
1242         dtrace_add_128(product, tmp, product);
1243 }
1244
1245 /*
1246  * This privilege check should be used by actions and subroutines to
1247  * verify that the user credentials of the process that enabled the
1248  * invoking ECB match the target credentials
1249  */
1250 static int
1251 dtrace_priv_proc_common_user(dtrace_state_t *state)
1252 {
1253         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1254
1255         /*
1256          * We should always have a non-NULL state cred here, since if cred
1257          * is null (anonymous tracing), we fast-path bypass this routine.
1258          */
1259         ASSERT(s_cr != NULL);
1260
1261         if ((cr = CRED()) != NULL &&
1262             s_cr->cr_uid == cr->cr_uid &&
1263             s_cr->cr_uid == cr->cr_ruid &&
1264             s_cr->cr_uid == cr->cr_suid &&
1265             s_cr->cr_gid == cr->cr_gid &&
1266             s_cr->cr_gid == cr->cr_rgid &&
1267             s_cr->cr_gid == cr->cr_sgid)
1268                 return (1);
1269
1270         return (0);
1271 }
1272
1273 /*
1274  * This privilege check should be used by actions and subroutines to
1275  * verify that the zone of the process that enabled the invoking ECB
1276  * matches the target credentials
1277  */
1278 static int
1279 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1280 {
1281 #if defined(sun)
1282         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1283
1284         /*
1285          * We should always have a non-NULL state cred here, since if cred
1286          * is null (anonymous tracing), we fast-path bypass this routine.
1287          */
1288         ASSERT(s_cr != NULL);
1289
1290         if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1291                 return (1);
1292
1293         return (0);
1294 #else
1295         return (1);
1296 #endif
1297 }
1298
1299 /*
1300  * This privilege check should be used by actions and subroutines to
1301  * verify that the process has not setuid or changed credentials.
1302  */
1303 static int
1304 dtrace_priv_proc_common_nocd(void)
1305 {
1306         proc_t *proc;
1307
1308         if ((proc = ttoproc(curthread)) != NULL &&
1309             !(proc->p_flag & SNOCD))
1310                 return (1);
1311
1312         return (0);
1313 }
1314
1315 static int
1316 dtrace_priv_proc_destructive(dtrace_state_t *state)
1317 {
1318         int action = state->dts_cred.dcr_action;
1319
1320         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1321             dtrace_priv_proc_common_zone(state) == 0)
1322                 goto bad;
1323
1324         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1325             dtrace_priv_proc_common_user(state) == 0)
1326                 goto bad;
1327
1328         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1329             dtrace_priv_proc_common_nocd() == 0)
1330                 goto bad;
1331
1332         return (1);
1333
1334 bad:
1335         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1336
1337         return (0);
1338 }
1339
1340 static int
1341 dtrace_priv_proc_control(dtrace_state_t *state)
1342 {
1343         if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1344                 return (1);
1345
1346         if (dtrace_priv_proc_common_zone(state) &&
1347             dtrace_priv_proc_common_user(state) &&
1348             dtrace_priv_proc_common_nocd())
1349                 return (1);
1350
1351         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1352
1353         return (0);
1354 }
1355
1356 static int
1357 dtrace_priv_proc(dtrace_state_t *state)
1358 {
1359         if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1360                 return (1);
1361
1362         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1363
1364         return (0);
1365 }
1366
1367 static int
1368 dtrace_priv_kernel(dtrace_state_t *state)
1369 {
1370         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1371                 return (1);
1372
1373         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1374
1375         return (0);
1376 }
1377
1378 static int
1379 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1380 {
1381         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1382                 return (1);
1383
1384         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1385
1386         return (0);
1387 }
1388
1389 /*
1390  * Determine if the dte_cond of the specified ECB allows for processing of
1391  * the current probe to continue.  Note that this routine may allow continued
1392  * processing, but with access(es) stripped from the mstate's dtms_access
1393  * field.
1394  */
1395 static int
1396 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1397     dtrace_ecb_t *ecb)
1398 {
1399         dtrace_probe_t *probe = ecb->dte_probe;
1400         dtrace_provider_t *prov = probe->dtpr_provider;
1401         dtrace_pops_t *pops = &prov->dtpv_pops;
1402         int mode = DTRACE_MODE_NOPRIV_DROP;
1403
1404         ASSERT(ecb->dte_cond);
1405
1406 #if defined(sun)
1407         if (pops->dtps_mode != NULL) {
1408                 mode = pops->dtps_mode(prov->dtpv_arg,
1409                     probe->dtpr_id, probe->dtpr_arg);
1410
1411                 ASSERT((mode & DTRACE_MODE_USER) ||
1412                     (mode & DTRACE_MODE_KERNEL));
1413                 ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1414                     (mode & DTRACE_MODE_NOPRIV_DROP));
1415         }
1416
1417         /*
1418          * If the dte_cond bits indicate that this consumer is only allowed to
1419          * see user-mode firings of this probe, call the provider's dtps_mode()
1420          * entry point to check that the probe was fired while in a user
1421          * context.  If that's not the case, use the policy specified by the
1422          * provider to determine if we drop the probe or merely restrict
1423          * operation.
1424          */
1425         if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1426                 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1427
1428                 if (!(mode & DTRACE_MODE_USER)) {
1429                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1430                                 return (0);
1431
1432                         mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1433                 }
1434         }
1435 #endif
1436
1437         /*
1438          * This is more subtle than it looks. We have to be absolutely certain
1439          * that CRED() isn't going to change out from under us so it's only
1440          * legit to examine that structure if we're in constrained situations.
1441          * Currently, the only times we'll this check is if a non-super-user
1442          * has enabled the profile or syscall providers -- providers that
1443          * allow visibility of all processes. For the profile case, the check
1444          * above will ensure that we're examining a user context.
1445          */
1446         if (ecb->dte_cond & DTRACE_COND_OWNER) {
1447                 cred_t *cr;
1448                 cred_t *s_cr = state->dts_cred.dcr_cred;
1449                 proc_t *proc;
1450
1451                 ASSERT(s_cr != NULL);
1452
1453                 if ((cr = CRED()) == NULL ||
1454                     s_cr->cr_uid != cr->cr_uid ||
1455                     s_cr->cr_uid != cr->cr_ruid ||
1456                     s_cr->cr_uid != cr->cr_suid ||
1457                     s_cr->cr_gid != cr->cr_gid ||
1458                     s_cr->cr_gid != cr->cr_rgid ||
1459                     s_cr->cr_gid != cr->cr_sgid ||
1460                     (proc = ttoproc(curthread)) == NULL ||
1461                     (proc->p_flag & SNOCD)) {
1462                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1463                                 return (0);
1464
1465 #if defined(sun)
1466                         mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1467 #endif
1468                 }
1469         }
1470
1471 #if defined(sun)
1472         /*
1473          * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1474          * in our zone, check to see if our mode policy is to restrict rather
1475          * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1476          * and DTRACE_ACCESS_ARGS
1477          */
1478         if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1479                 cred_t *cr;
1480                 cred_t *s_cr = state->dts_cred.dcr_cred;
1481
1482                 ASSERT(s_cr != NULL);
1483
1484                 if ((cr = CRED()) == NULL ||
1485                     s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1486                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1487                                 return (0);
1488
1489                         mstate->dtms_access &=
1490                             ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1491                 }
1492         }
1493 #endif
1494
1495         return (1);
1496 }
1497
1498 /*
1499  * Note:  not called from probe context.  This function is called
1500  * asynchronously (and at a regular interval) from outside of probe context to
1501  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1502  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1503  */
1504 void
1505 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1506 {
1507         dtrace_dynvar_t *dirty;
1508         dtrace_dstate_percpu_t *dcpu;
1509         int i, work = 0;
1510
1511         for (i = 0; i < NCPU; i++) {
1512                 dcpu = &dstate->dtds_percpu[i];
1513
1514                 ASSERT(dcpu->dtdsc_rinsing == NULL);
1515
1516                 /*
1517                  * If the dirty list is NULL, there is no dirty work to do.
1518                  */
1519                 if (dcpu->dtdsc_dirty == NULL)
1520                         continue;
1521
1522                 /*
1523                  * If the clean list is non-NULL, then we're not going to do
1524                  * any work for this CPU -- it means that there has not been
1525                  * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1526                  * since the last time we cleaned house.
1527                  */
1528                 if (dcpu->dtdsc_clean != NULL)
1529                         continue;
1530
1531                 work = 1;
1532
1533                 /*
1534                  * Atomically move the dirty list aside.
1535                  */
1536                 do {
1537                         dirty = dcpu->dtdsc_dirty;
1538
1539                         /*
1540                          * Before we zap the dirty list, set the rinsing list.
1541                          * (This allows for a potential assertion in
1542                          * dtrace_dynvar():  if a free dynamic variable appears
1543                          * on a hash chain, either the dirty list or the
1544                          * rinsing list for some CPU must be non-NULL.)
1545                          */
1546                         dcpu->dtdsc_rinsing = dirty;
1547                         dtrace_membar_producer();
1548                 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1549                     dirty, NULL) != dirty);
1550         }
1551
1552         if (!work) {
1553                 /*
1554                  * We have no work to do; we can simply return.
1555                  */
1556                 return;
1557         }
1558
1559         dtrace_sync();
1560
1561         for (i = 0; i < NCPU; i++) {
1562                 dcpu = &dstate->dtds_percpu[i];
1563
1564                 if (dcpu->dtdsc_rinsing == NULL)
1565                         continue;
1566
1567                 /*
1568                  * We are now guaranteed that no hash chain contains a pointer
1569                  * into this dirty list; we can make it clean.
1570                  */
1571                 ASSERT(dcpu->dtdsc_clean == NULL);
1572                 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1573                 dcpu->dtdsc_rinsing = NULL;
1574         }
1575
1576         /*
1577          * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1578          * sure that all CPUs have seen all of the dtdsc_clean pointers.
1579          * This prevents a race whereby a CPU incorrectly decides that
1580          * the state should be something other than DTRACE_DSTATE_CLEAN
1581          * after dtrace_dynvar_clean() has completed.
1582          */
1583         dtrace_sync();
1584
1585         dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1586 }
1587
1588 /*
1589  * Depending on the value of the op parameter, this function looks-up,
1590  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1591  * allocation is requested, this function will return a pointer to a
1592  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1593  * variable can be allocated.  If NULL is returned, the appropriate counter
1594  * will be incremented.
1595  */
1596 dtrace_dynvar_t *
1597 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1598     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1599     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1600 {
1601         uint64_t hashval = DTRACE_DYNHASH_VALID;
1602         dtrace_dynhash_t *hash = dstate->dtds_hash;
1603         dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1604         processorid_t me = curcpu, cpu = me;
1605         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1606         size_t bucket, ksize;
1607         size_t chunksize = dstate->dtds_chunksize;
1608         uintptr_t kdata, lock, nstate;
1609         uint_t i;
1610
1611         ASSERT(nkeys != 0);
1612
1613         /*
1614          * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1615          * algorithm.  For the by-value portions, we perform the algorithm in
1616          * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1617          * bit, and seems to have only a minute effect on distribution.  For
1618          * the by-reference data, we perform "One-at-a-time" iterating (safely)
1619          * over each referenced byte.  It's painful to do this, but it's much
1620          * better than pathological hash distribution.  The efficacy of the
1621          * hashing algorithm (and a comparison with other algorithms) may be
1622          * found by running the ::dtrace_dynstat MDB dcmd.
1623          */
1624         for (i = 0; i < nkeys; i++) {
1625                 if (key[i].dttk_size == 0) {
1626                         uint64_t val = key[i].dttk_value;
1627
1628                         hashval += (val >> 48) & 0xffff;
1629                         hashval += (hashval << 10);
1630                         hashval ^= (hashval >> 6);
1631
1632                         hashval += (val >> 32) & 0xffff;
1633                         hashval += (hashval << 10);
1634                         hashval ^= (hashval >> 6);
1635
1636                         hashval += (val >> 16) & 0xffff;
1637                         hashval += (hashval << 10);
1638                         hashval ^= (hashval >> 6);
1639
1640                         hashval += val & 0xffff;
1641                         hashval += (hashval << 10);
1642                         hashval ^= (hashval >> 6);
1643                 } else {
1644                         /*
1645                          * This is incredibly painful, but it beats the hell
1646                          * out of the alternative.
1647                          */
1648                         uint64_t j, size = key[i].dttk_size;
1649                         uintptr_t base = (uintptr_t)key[i].dttk_value;
1650
1651                         if (!dtrace_canload(base, size, mstate, vstate))
1652                                 break;
1653
1654                         for (j = 0; j < size; j++) {
1655                                 hashval += dtrace_load8(base + j);
1656                                 hashval += (hashval << 10);
1657                                 hashval ^= (hashval >> 6);
1658                         }
1659                 }
1660         }
1661
1662         if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1663                 return (NULL);
1664
1665         hashval += (hashval << 3);
1666         hashval ^= (hashval >> 11);
1667         hashval += (hashval << 15);
1668
1669         /*
1670          * There is a remote chance (ideally, 1 in 2^31) that our hashval
1671          * comes out to be one of our two sentinel hash values.  If this
1672          * actually happens, we set the hashval to be a value known to be a
1673          * non-sentinel value.
1674          */
1675         if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1676                 hashval = DTRACE_DYNHASH_VALID;
1677
1678         /*
1679          * Yes, it's painful to do a divide here.  If the cycle count becomes
1680          * important here, tricks can be pulled to reduce it.  (However, it's
1681          * critical that hash collisions be kept to an absolute minimum;
1682          * they're much more painful than a divide.)  It's better to have a
1683          * solution that generates few collisions and still keeps things
1684          * relatively simple.
1685          */
1686         bucket = hashval % dstate->dtds_hashsize;
1687
1688         if (op == DTRACE_DYNVAR_DEALLOC) {
1689                 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1690
1691                 for (;;) {
1692                         while ((lock = *lockp) & 1)
1693                                 continue;
1694
1695                         if (dtrace_casptr((volatile void *)lockp,
1696                             (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1697                                 break;
1698                 }
1699
1700                 dtrace_membar_producer();
1701         }
1702
1703 top:
1704         prev = NULL;
1705         lock = hash[bucket].dtdh_lock;
1706
1707         dtrace_membar_consumer();
1708
1709         start = hash[bucket].dtdh_chain;
1710         ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1711             start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1712             op != DTRACE_DYNVAR_DEALLOC));
1713
1714         for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1715                 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1716                 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1717
1718                 if (dvar->dtdv_hashval != hashval) {
1719                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1720                                 /*
1721                                  * We've reached the sink, and therefore the
1722                                  * end of the hash chain; we can kick out of
1723                                  * the loop knowing that we have seen a valid
1724                                  * snapshot of state.
1725                                  */
1726                                 ASSERT(dvar->dtdv_next == NULL);
1727                                 ASSERT(dvar == &dtrace_dynhash_sink);
1728                                 break;
1729                         }
1730
1731                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1732                                 /*
1733                                  * We've gone off the rails:  somewhere along
1734                                  * the line, one of the members of this hash
1735                                  * chain was deleted.  Note that we could also
1736                                  * detect this by simply letting this loop run
1737                                  * to completion, as we would eventually hit
1738                                  * the end of the dirty list.  However, we
1739                                  * want to avoid running the length of the
1740                                  * dirty list unnecessarily (it might be quite
1741                                  * long), so we catch this as early as
1742                                  * possible by detecting the hash marker.  In
1743                                  * this case, we simply set dvar to NULL and
1744                                  * break; the conditional after the loop will
1745                                  * send us back to top.
1746                                  */
1747                                 dvar = NULL;
1748                                 break;
1749                         }
1750
1751                         goto next;
1752                 }
1753
1754                 if (dtuple->dtt_nkeys != nkeys)
1755                         goto next;
1756
1757                 for (i = 0; i < nkeys; i++, dkey++) {
1758                         if (dkey->dttk_size != key[i].dttk_size)
1759                                 goto next; /* size or type mismatch */
1760
1761                         if (dkey->dttk_size != 0) {
1762                                 if (dtrace_bcmp(
1763                                     (void *)(uintptr_t)key[i].dttk_value,
1764                                     (void *)(uintptr_t)dkey->dttk_value,
1765                                     dkey->dttk_size))
1766                                         goto next;
1767                         } else {
1768                                 if (dkey->dttk_value != key[i].dttk_value)
1769                                         goto next;
1770                         }
1771                 }
1772
1773                 if (op != DTRACE_DYNVAR_DEALLOC)
1774                         return (dvar);
1775
1776                 ASSERT(dvar->dtdv_next == NULL ||
1777                     dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1778
1779                 if (prev != NULL) {
1780                         ASSERT(hash[bucket].dtdh_chain != dvar);
1781                         ASSERT(start != dvar);
1782                         ASSERT(prev->dtdv_next == dvar);
1783                         prev->dtdv_next = dvar->dtdv_next;
1784                 } else {
1785                         if (dtrace_casptr(&hash[bucket].dtdh_chain,
1786                             start, dvar->dtdv_next) != start) {
1787                                 /*
1788                                  * We have failed to atomically swing the
1789                                  * hash table head pointer, presumably because
1790                                  * of a conflicting allocation on another CPU.
1791                                  * We need to reread the hash chain and try
1792                                  * again.
1793                                  */
1794                                 goto top;
1795                         }
1796                 }
1797
1798                 dtrace_membar_producer();
1799
1800                 /*
1801                  * Now set the hash value to indicate that it's free.
1802                  */
1803                 ASSERT(hash[bucket].dtdh_chain != dvar);
1804                 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1805
1806                 dtrace_membar_producer();
1807
1808                 /*
1809                  * Set the next pointer to point at the dirty list, and
1810                  * atomically swing the dirty pointer to the newly freed dvar.
1811                  */
1812                 do {
1813                         next = dcpu->dtdsc_dirty;
1814                         dvar->dtdv_next = next;
1815                 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1816
1817                 /*
1818                  * Finally, unlock this hash bucket.
1819                  */
1820                 ASSERT(hash[bucket].dtdh_lock == lock);
1821                 ASSERT(lock & 1);
1822                 hash[bucket].dtdh_lock++;
1823
1824                 return (NULL);
1825 next:
1826                 prev = dvar;
1827                 continue;
1828         }
1829
1830         if (dvar == NULL) {
1831                 /*
1832                  * If dvar is NULL, it is because we went off the rails:
1833                  * one of the elements that we traversed in the hash chain
1834                  * was deleted while we were traversing it.  In this case,
1835                  * we assert that we aren't doing a dealloc (deallocs lock
1836                  * the hash bucket to prevent themselves from racing with
1837                  * one another), and retry the hash chain traversal.
1838                  */
1839                 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1840                 goto top;
1841         }
1842
1843         if (op != DTRACE_DYNVAR_ALLOC) {
1844                 /*
1845                  * If we are not to allocate a new variable, we want to
1846                  * return NULL now.  Before we return, check that the value
1847                  * of the lock word hasn't changed.  If it has, we may have
1848                  * seen an inconsistent snapshot.
1849                  */
1850                 if (op == DTRACE_DYNVAR_NOALLOC) {
1851                         if (hash[bucket].dtdh_lock != lock)
1852                                 goto top;
1853                 } else {
1854                         ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1855                         ASSERT(hash[bucket].dtdh_lock == lock);
1856                         ASSERT(lock & 1);
1857                         hash[bucket].dtdh_lock++;
1858                 }
1859
1860                 return (NULL);
1861         }
1862
1863         /*
1864          * We need to allocate a new dynamic variable.  The size we need is the
1865          * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1866          * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1867          * the size of any referred-to data (dsize).  We then round the final
1868          * size up to the chunksize for allocation.
1869          */
1870         for (ksize = 0, i = 0; i < nkeys; i++)
1871                 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1872
1873         /*
1874          * This should be pretty much impossible, but could happen if, say,
1875          * strange DIF specified the tuple.  Ideally, this should be an
1876          * assertion and not an error condition -- but that requires that the
1877          * chunksize calculation in dtrace_difo_chunksize() be absolutely
1878          * bullet-proof.  (That is, it must not be able to be fooled by
1879          * malicious DIF.)  Given the lack of backwards branches in DIF,
1880          * solving this would presumably not amount to solving the Halting
1881          * Problem -- but it still seems awfully hard.
1882          */
1883         if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1884             ksize + dsize > chunksize) {
1885                 dcpu->dtdsc_drops++;
1886                 return (NULL);
1887         }
1888
1889         nstate = DTRACE_DSTATE_EMPTY;
1890
1891         do {
1892 retry:
1893                 free = dcpu->dtdsc_free;
1894
1895                 if (free == NULL) {
1896                         dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1897                         void *rval;
1898
1899                         if (clean == NULL) {
1900                                 /*
1901                                  * We're out of dynamic variable space on
1902                                  * this CPU.  Unless we have tried all CPUs,
1903                                  * we'll try to allocate from a different
1904                                  * CPU.
1905                                  */
1906                                 switch (dstate->dtds_state) {
1907                                 case DTRACE_DSTATE_CLEAN: {
1908                                         void *sp = &dstate->dtds_state;
1909
1910                                         if (++cpu >= NCPU)
1911                                                 cpu = 0;
1912
1913                                         if (dcpu->dtdsc_dirty != NULL &&
1914                                             nstate == DTRACE_DSTATE_EMPTY)
1915                                                 nstate = DTRACE_DSTATE_DIRTY;
1916
1917                                         if (dcpu->dtdsc_rinsing != NULL)
1918                                                 nstate = DTRACE_DSTATE_RINSING;
1919
1920                                         dcpu = &dstate->dtds_percpu[cpu];
1921
1922                                         if (cpu != me)
1923                                                 goto retry;
1924
1925                                         (void) dtrace_cas32(sp,
1926                                             DTRACE_DSTATE_CLEAN, nstate);
1927
1928                                         /*
1929                                          * To increment the correct bean
1930                                          * counter, take another lap.
1931                                          */
1932                                         goto retry;
1933                                 }
1934
1935                                 case DTRACE_DSTATE_DIRTY:
1936                                         dcpu->dtdsc_dirty_drops++;
1937                                         break;
1938
1939                                 case DTRACE_DSTATE_RINSING:
1940                                         dcpu->dtdsc_rinsing_drops++;
1941                                         break;
1942
1943                                 case DTRACE_DSTATE_EMPTY:
1944                                         dcpu->dtdsc_drops++;
1945                                         break;
1946                                 }
1947
1948                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1949                                 return (NULL);
1950                         }
1951
1952                         /*
1953                          * The clean list appears to be non-empty.  We want to
1954                          * move the clean list to the free list; we start by
1955                          * moving the clean pointer aside.
1956                          */
1957                         if (dtrace_casptr(&dcpu->dtdsc_clean,
1958                             clean, NULL) != clean) {
1959                                 /*
1960                                  * We are in one of two situations:
1961                                  *
1962                                  *  (a) The clean list was switched to the
1963                                  *      free list by another CPU.
1964                                  *
1965                                  *  (b) The clean list was added to by the
1966                                  *      cleansing cyclic.
1967                                  *
1968                                  * In either of these situations, we can
1969                                  * just reattempt the free list allocation.
1970                                  */
1971                                 goto retry;
1972                         }
1973
1974                         ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1975
1976                         /*
1977                          * Now we'll move the clean list to the free list.
1978                          * It's impossible for this to fail:  the only way
1979                          * the free list can be updated is through this
1980                          * code path, and only one CPU can own the clean list.
1981                          * Thus, it would only be possible for this to fail if
1982                          * this code were racing with dtrace_dynvar_clean().
1983                          * (That is, if dtrace_dynvar_clean() updated the clean
1984                          * list, and we ended up racing to update the free
1985                          * list.)  This race is prevented by the dtrace_sync()
1986                          * in dtrace_dynvar_clean() -- which flushes the
1987                          * owners of the clean lists out before resetting
1988                          * the clean lists.
1989                          */
1990                         rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1991                         ASSERT(rval == NULL);
1992                         goto retry;
1993                 }
1994
1995                 dvar = free;
1996                 new_free = dvar->dtdv_next;
1997         } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1998
1999         /*
2000          * We have now allocated a new chunk.  We copy the tuple keys into the
2001          * tuple array and copy any referenced key data into the data space
2002          * following the tuple array.  As we do this, we relocate dttk_value
2003          * in the final tuple to point to the key data address in the chunk.
2004          */
2005         kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2006         dvar->dtdv_data = (void *)(kdata + ksize);
2007         dvar->dtdv_tuple.dtt_nkeys = nkeys;
2008
2009         for (i = 0; i < nkeys; i++) {
2010                 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2011                 size_t kesize = key[i].dttk_size;
2012
2013                 if (kesize != 0) {
2014                         dtrace_bcopy(
2015                             (const void *)(uintptr_t)key[i].dttk_value,
2016                             (void *)kdata, kesize);
2017                         dkey->dttk_value = kdata;
2018                         kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2019                 } else {
2020                         dkey->dttk_value = key[i].dttk_value;
2021                 }
2022
2023                 dkey->dttk_size = kesize;
2024         }
2025
2026         ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2027         dvar->dtdv_hashval = hashval;
2028         dvar->dtdv_next = start;
2029
2030         if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2031                 return (dvar);
2032
2033         /*
2034          * The cas has failed.  Either another CPU is adding an element to
2035          * this hash chain, or another CPU is deleting an element from this
2036          * hash chain.  The simplest way to deal with both of these cases
2037          * (though not necessarily the most efficient) is to free our
2038          * allocated block and tail-call ourselves.  Note that the free is
2039          * to the dirty list and _not_ to the free list.  This is to prevent
2040          * races with allocators, above.
2041          */
2042         dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2043
2044         dtrace_membar_producer();
2045
2046         do {
2047                 free = dcpu->dtdsc_dirty;
2048                 dvar->dtdv_next = free;
2049         } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2050
2051         return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2052 }
2053
2054 /*ARGSUSED*/
2055 static void
2056 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2057 {
2058         if ((int64_t)nval < (int64_t)*oval)
2059                 *oval = nval;
2060 }
2061
2062 /*ARGSUSED*/
2063 static void
2064 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2065 {
2066         if ((int64_t)nval > (int64_t)*oval)
2067                 *oval = nval;
2068 }
2069
2070 static void
2071 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2072 {
2073         int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2074         int64_t val = (int64_t)nval;
2075
2076         if (val < 0) {
2077                 for (i = 0; i < zero; i++) {
2078                         if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2079                                 quanta[i] += incr;
2080                                 return;
2081                         }
2082                 }
2083         } else {
2084                 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2085                         if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2086                                 quanta[i - 1] += incr;
2087                                 return;
2088                         }
2089                 }
2090
2091                 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2092                 return;
2093         }
2094
2095         ASSERT(0);
2096 }
2097
2098 static void
2099 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2100 {
2101         uint64_t arg = *lquanta++;
2102         int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2103         uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2104         uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2105         int32_t val = (int32_t)nval, level;
2106
2107         ASSERT(step != 0);
2108         ASSERT(levels != 0);
2109
2110         if (val < base) {
2111                 /*
2112                  * This is an underflow.
2113                  */
2114                 lquanta[0] += incr;
2115                 return;
2116         }
2117
2118         level = (val - base) / step;
2119
2120         if (level < levels) {
2121                 lquanta[level + 1] += incr;
2122                 return;
2123         }
2124
2125         /*
2126          * This is an overflow.
2127          */
2128         lquanta[levels + 1] += incr;
2129 }
2130
2131 static int
2132 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2133     uint16_t high, uint16_t nsteps, int64_t value)
2134 {
2135         int64_t this = 1, last, next;
2136         int base = 1, order;
2137
2138         ASSERT(factor <= nsteps);
2139         ASSERT(nsteps % factor == 0);
2140
2141         for (order = 0; order < low; order++)
2142                 this *= factor;
2143
2144         /*
2145          * If our value is less than our factor taken to the power of the
2146          * low order of magnitude, it goes into the zeroth bucket.
2147          */
2148         if (value < (last = this))
2149                 return (0);
2150
2151         for (this *= factor; order <= high; order++) {
2152                 int nbuckets = this > nsteps ? nsteps : this;
2153
2154                 if ((next = this * factor) < this) {
2155                         /*
2156                          * We should not generally get log/linear quantizations
2157                          * with a high magnitude that allows 64-bits to
2158                          * overflow, but we nonetheless protect against this
2159                          * by explicitly checking for overflow, and clamping
2160                          * our value accordingly.
2161                          */
2162                         value = this - 1;
2163                 }
2164
2165                 if (value < this) {
2166                         /*
2167                          * If our value lies within this order of magnitude,
2168                          * determine its position by taking the offset within
2169                          * the order of magnitude, dividing by the bucket
2170                          * width, and adding to our (accumulated) base.
2171                          */
2172                         return (base + (value - last) / (this / nbuckets));
2173                 }
2174
2175                 base += nbuckets - (nbuckets / factor);
2176                 last = this;
2177                 this = next;
2178         }
2179
2180         /*
2181          * Our value is greater than or equal to our factor taken to the
2182          * power of one plus the high magnitude -- return the top bucket.
2183          */
2184         return (base);
2185 }
2186
2187 static void
2188 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2189 {
2190         uint64_t arg = *llquanta++;
2191         uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2192         uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2193         uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2194         uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2195
2196         llquanta[dtrace_aggregate_llquantize_bucket(factor,
2197             low, high, nsteps, nval)] += incr;
2198 }
2199
2200 /*ARGSUSED*/
2201 static void
2202 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2203 {
2204         data[0]++;
2205         data[1] += nval;
2206 }
2207
2208 /*ARGSUSED*/
2209 static void
2210 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2211 {
2212         int64_t snval = (int64_t)nval;
2213         uint64_t tmp[2];
2214
2215         data[0]++;
2216         data[1] += nval;
2217
2218         /*
2219          * What we want to say here is:
2220          *
2221          * data[2] += nval * nval;
2222          *
2223          * But given that nval is 64-bit, we could easily overflow, so
2224          * we do this as 128-bit arithmetic.
2225          */
2226         if (snval < 0)
2227                 snval = -snval;
2228
2229         dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2230         dtrace_add_128(data + 2, tmp, data + 2);
2231 }
2232
2233 /*ARGSUSED*/
2234 static void
2235 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2236 {
2237         *oval = *oval + 1;
2238 }
2239
2240 /*ARGSUSED*/
2241 static void
2242 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2243 {
2244         *oval += nval;
2245 }
2246
2247 /*
2248  * Aggregate given the tuple in the principal data buffer, and the aggregating
2249  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2250  * buffer is specified as the buf parameter.  This routine does not return
2251  * failure; if there is no space in the aggregation buffer, the data will be
2252  * dropped, and a corresponding counter incremented.
2253  */
2254 static void
2255 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2256     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2257 {
2258         dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2259         uint32_t i, ndx, size, fsize;
2260         uint32_t align = sizeof (uint64_t) - 1;
2261         dtrace_aggbuffer_t *agb;
2262         dtrace_aggkey_t *key;
2263         uint32_t hashval = 0, limit, isstr;
2264         caddr_t tomax, data, kdata;
2265         dtrace_actkind_t action;
2266         dtrace_action_t *act;
2267         uintptr_t offs;
2268
2269         if (buf == NULL)
2270                 return;
2271
2272         if (!agg->dtag_hasarg) {
2273                 /*
2274                  * Currently, only quantize() and lquantize() take additional
2275                  * arguments, and they have the same semantics:  an increment
2276                  * value that defaults to 1 when not present.  If additional
2277                  * aggregating actions take arguments, the setting of the
2278                  * default argument value will presumably have to become more
2279                  * sophisticated...
2280                  */
2281                 arg = 1;
2282         }
2283
2284         action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2285         size = rec->dtrd_offset - agg->dtag_base;
2286         fsize = size + rec->dtrd_size;
2287
2288         ASSERT(dbuf->dtb_tomax != NULL);
2289         data = dbuf->dtb_tomax + offset + agg->dtag_base;
2290
2291         if ((tomax = buf->dtb_tomax) == NULL) {
2292                 dtrace_buffer_drop(buf);
2293                 return;
2294         }
2295
2296         /*
2297          * The metastructure is always at the bottom of the buffer.
2298          */
2299         agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2300             sizeof (dtrace_aggbuffer_t));
2301
2302         if (buf->dtb_offset == 0) {
2303                 /*
2304                  * We just kludge up approximately 1/8th of the size to be
2305                  * buckets.  If this guess ends up being routinely
2306                  * off-the-mark, we may need to dynamically readjust this
2307                  * based on past performance.
2308                  */
2309                 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2310
2311                 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2312                     (uintptr_t)tomax || hashsize == 0) {
2313                         /*
2314                          * We've been given a ludicrously small buffer;
2315                          * increment our drop count and leave.
2316                          */
2317                         dtrace_buffer_drop(buf);
2318                         return;
2319                 }
2320
2321                 /*
2322                  * And now, a pathetic attempt to try to get a an odd (or
2323                  * perchance, a prime) hash size for better hash distribution.
2324                  */
2325                 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2326                         hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2327
2328                 agb->dtagb_hashsize = hashsize;
2329                 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2330                     agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2331                 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2332
2333                 for (i = 0; i < agb->dtagb_hashsize; i++)
2334                         agb->dtagb_hash[i] = NULL;
2335         }
2336
2337         ASSERT(agg->dtag_first != NULL);
2338         ASSERT(agg->dtag_first->dta_intuple);
2339
2340         /*
2341          * Calculate the hash value based on the key.  Note that we _don't_
2342          * include the aggid in the hashing (but we will store it as part of
2343          * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2344          * algorithm: a simple, quick algorithm that has no known funnels, and
2345          * gets good distribution in practice.  The efficacy of the hashing
2346          * algorithm (and a comparison with other algorithms) may be found by
2347          * running the ::dtrace_aggstat MDB dcmd.
2348          */
2349         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2350                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2351                 limit = i + act->dta_rec.dtrd_size;
2352                 ASSERT(limit <= size);
2353                 isstr = DTRACEACT_ISSTRING(act);
2354
2355                 for (; i < limit; i++) {
2356                         hashval += data[i];
2357                         hashval += (hashval << 10);
2358                         hashval ^= (hashval >> 6);
2359
2360                         if (isstr && data[i] == '\0')
2361                                 break;
2362                 }
2363         }
2364
2365         hashval += (hashval << 3);
2366         hashval ^= (hashval >> 11);
2367         hashval += (hashval << 15);
2368
2369         /*
2370          * Yes, the divide here is expensive -- but it's generally the least
2371          * of the performance issues given the amount of data that we iterate
2372          * over to compute hash values, compare data, etc.
2373          */
2374         ndx = hashval % agb->dtagb_hashsize;
2375
2376         for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2377                 ASSERT((caddr_t)key >= tomax);
2378                 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2379
2380                 if (hashval != key->dtak_hashval || key->dtak_size != size)
2381                         continue;
2382
2383                 kdata = key->dtak_data;
2384                 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2385
2386                 for (act = agg->dtag_first; act->dta_intuple;
2387                     act = act->dta_next) {
2388                         i = act->dta_rec.dtrd_offset - agg->dtag_base;
2389                         limit = i + act->dta_rec.dtrd_size;
2390                         ASSERT(limit <= size);
2391                         isstr = DTRACEACT_ISSTRING(act);
2392
2393                         for (; i < limit; i++) {
2394                                 if (kdata[i] != data[i])
2395                                         goto next;
2396
2397                                 if (isstr && data[i] == '\0')
2398                                         break;
2399                         }
2400                 }
2401
2402                 if (action != key->dtak_action) {
2403                         /*
2404                          * We are aggregating on the same value in the same
2405                          * aggregation with two different aggregating actions.
2406                          * (This should have been picked up in the compiler,
2407                          * so we may be dealing with errant or devious DIF.)
2408                          * This is an error condition; we indicate as much,
2409                          * and return.
2410                          */
2411                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2412                         return;
2413                 }
2414
2415                 /*
2416                  * This is a hit:  we need to apply the aggregator to
2417                  * the value at this key.
2418                  */
2419                 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2420                 return;
2421 next:
2422                 continue;
2423         }
2424
2425         /*
2426          * We didn't find it.  We need to allocate some zero-filled space,
2427          * link it into the hash table appropriately, and apply the aggregator
2428          * to the (zero-filled) value.
2429          */
2430         offs = buf->dtb_offset;
2431         while (offs & (align - 1))
2432                 offs += sizeof (uint32_t);
2433
2434         /*
2435          * If we don't have enough room to both allocate a new key _and_
2436          * its associated data, increment the drop count and return.
2437          */
2438         if ((uintptr_t)tomax + offs + fsize >
2439             agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2440                 dtrace_buffer_drop(buf);
2441                 return;
2442         }
2443
2444         /*CONSTCOND*/
2445         ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2446         key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2447         agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2448
2449         key->dtak_data = kdata = tomax + offs;
2450         buf->dtb_offset = offs + fsize;
2451
2452         /*
2453          * Now copy the data across.
2454          */
2455         *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2456
2457         for (i = sizeof (dtrace_aggid_t); i < size; i++)
2458                 kdata[i] = data[i];
2459
2460         /*
2461          * Because strings are not zeroed out by default, we need to iterate
2462          * looking for actions that store strings, and we need to explicitly
2463          * pad these strings out with zeroes.
2464          */
2465         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2466                 int nul;
2467
2468                 if (!DTRACEACT_ISSTRING(act))
2469                         continue;
2470
2471                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2472                 limit = i + act->dta_rec.dtrd_size;
2473                 ASSERT(limit <= size);
2474
2475                 for (nul = 0; i < limit; i++) {
2476                         if (nul) {
2477                                 kdata[i] = '\0';
2478                                 continue;
2479                         }
2480
2481                         if (data[i] != '\0')
2482                                 continue;
2483
2484                         nul = 1;
2485                 }
2486         }
2487
2488         for (i = size; i < fsize; i++)
2489                 kdata[i] = 0;
2490
2491         key->dtak_hashval = hashval;
2492         key->dtak_size = size;
2493         key->dtak_action = action;
2494         key->dtak_next = agb->dtagb_hash[ndx];
2495         agb->dtagb_hash[ndx] = key;
2496
2497         /*
2498          * Finally, apply the aggregator.
2499          */
2500         *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2501         agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2502 }
2503
2504 /*
2505  * Given consumer state, this routine finds a speculation in the INACTIVE
2506  * state and transitions it into the ACTIVE state.  If there is no speculation
2507  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2508  * incremented -- it is up to the caller to take appropriate action.
2509  */
2510 static int
2511 dtrace_speculation(dtrace_state_t *state)
2512 {
2513         int i = 0;
2514         dtrace_speculation_state_t current;
2515         uint32_t *stat = &state->dts_speculations_unavail, count;
2516
2517         while (i < state->dts_nspeculations) {
2518                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2519
2520                 current = spec->dtsp_state;
2521
2522                 if (current != DTRACESPEC_INACTIVE) {
2523                         if (current == DTRACESPEC_COMMITTINGMANY ||
2524                             current == DTRACESPEC_COMMITTING ||
2525                             current == DTRACESPEC_DISCARDING)
2526                                 stat = &state->dts_speculations_busy;
2527                         i++;
2528                         continue;
2529                 }
2530
2531                 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2532                     current, DTRACESPEC_ACTIVE) == current)
2533                         return (i + 1);
2534         }
2535
2536         /*
2537          * We couldn't find a speculation.  If we found as much as a single
2538          * busy speculation buffer, we'll attribute this failure as "busy"
2539          * instead of "unavail".
2540          */
2541         do {
2542                 count = *stat;
2543         } while (dtrace_cas32(stat, count, count + 1) != count);
2544
2545         return (0);
2546 }
2547
2548 /*
2549  * This routine commits an active speculation.  If the specified speculation
2550  * is not in a valid state to perform a commit(), this routine will silently do
2551  * nothing.  The state of the specified speculation is transitioned according
2552  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2553  */
2554 static void
2555 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2556     dtrace_specid_t which)
2557 {
2558         dtrace_speculation_t *spec;
2559         dtrace_buffer_t *src, *dest;
2560         uintptr_t daddr, saddr, dlimit, slimit;
2561         dtrace_speculation_state_t current, new = 0;
2562         intptr_t offs;
2563         uint64_t timestamp;
2564
2565         if (which == 0)
2566                 return;
2567
2568         if (which > state->dts_nspeculations) {
2569                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2570                 return;
2571         }
2572
2573         spec = &state->dts_speculations[which - 1];
2574         src = &spec->dtsp_buffer[cpu];
2575         dest = &state->dts_buffer[cpu];
2576
2577         do {
2578                 current = spec->dtsp_state;
2579
2580                 if (current == DTRACESPEC_COMMITTINGMANY)
2581                         break;
2582
2583                 switch (current) {
2584                 case DTRACESPEC_INACTIVE:
2585                 case DTRACESPEC_DISCARDING:
2586                         return;
2587
2588                 case DTRACESPEC_COMMITTING:
2589                         /*
2590                          * This is only possible if we are (a) commit()'ing
2591                          * without having done a prior speculate() on this CPU
2592                          * and (b) racing with another commit() on a different
2593                          * CPU.  There's nothing to do -- we just assert that
2594                          * our offset is 0.
2595                          */
2596                         ASSERT(src->dtb_offset == 0);
2597                         return;
2598
2599                 case DTRACESPEC_ACTIVE:
2600                         new = DTRACESPEC_COMMITTING;
2601                         break;
2602
2603                 case DTRACESPEC_ACTIVEONE:
2604                         /*
2605                          * This speculation is active on one CPU.  If our
2606                          * buffer offset is non-zero, we know that the one CPU
2607                          * must be us.  Otherwise, we are committing on a
2608                          * different CPU from the speculate(), and we must
2609                          * rely on being asynchronously cleaned.
2610                          */
2611                         if (src->dtb_offset != 0) {
2612                                 new = DTRACESPEC_COMMITTING;
2613                                 break;
2614                         }
2615                         /*FALLTHROUGH*/
2616
2617                 case DTRACESPEC_ACTIVEMANY:
2618                         new = DTRACESPEC_COMMITTINGMANY;
2619                         break;
2620
2621                 default:
2622                         ASSERT(0);
2623                 }
2624         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2625             current, new) != current);
2626
2627         /*
2628          * We have set the state to indicate that we are committing this
2629          * speculation.  Now reserve the necessary space in the destination
2630          * buffer.
2631          */
2632         if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2633             sizeof (uint64_t), state, NULL)) < 0) {
2634                 dtrace_buffer_drop(dest);
2635                 goto out;
2636         }
2637
2638         /*
2639          * We have sufficient space to copy the speculative buffer into the
2640          * primary buffer.  First, modify the speculative buffer, filling
2641          * in the timestamp of all entries with the current time.  The data
2642          * must have the commit() time rather than the time it was traced,
2643          * so that all entries in the primary buffer are in timestamp order.
2644          */
2645         timestamp = dtrace_gethrtime();
2646         saddr = (uintptr_t)src->dtb_tomax;
2647         slimit = saddr + src->dtb_offset;
2648         while (saddr < slimit) {
2649                 size_t size;
2650                 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2651
2652                 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2653                         saddr += sizeof (dtrace_epid_t);
2654                         continue;
2655                 }
2656                 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2657                 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2658
2659                 ASSERT3U(saddr + size, <=, slimit);
2660                 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2661                 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2662
2663                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2664
2665                 saddr += size;
2666         }
2667
2668         /*
2669          * Copy the buffer across.  (Note that this is a
2670          * highly subobtimal bcopy(); in the unlikely event that this becomes
2671          * a serious performance issue, a high-performance DTrace-specific
2672          * bcopy() should obviously be invented.)
2673          */
2674         daddr = (uintptr_t)dest->dtb_tomax + offs;
2675         dlimit = daddr + src->dtb_offset;
2676         saddr = (uintptr_t)src->dtb_tomax;
2677
2678         /*
2679          * First, the aligned portion.
2680          */
2681         while (dlimit - daddr >= sizeof (uint64_t)) {
2682                 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2683
2684                 daddr += sizeof (uint64_t);
2685                 saddr += sizeof (uint64_t);
2686         }
2687
2688         /*
2689          * Now any left-over bit...
2690          */
2691         while (dlimit - daddr)
2692                 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2693
2694         /*
2695          * Finally, commit the reserved space in the destination buffer.
2696          */
2697         dest->dtb_offset = offs + src->dtb_offset;
2698
2699 out:
2700         /*
2701          * If we're lucky enough to be the only active CPU on this speculation
2702          * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2703          */
2704         if (current == DTRACESPEC_ACTIVE ||
2705             (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2706                 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2707                     DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2708
2709                 ASSERT(rval == DTRACESPEC_COMMITTING);
2710         }
2711
2712         src->dtb_offset = 0;
2713         src->dtb_xamot_drops += src->dtb_drops;
2714         src->dtb_drops = 0;
2715 }
2716
2717 /*
2718  * This routine discards an active speculation.  If the specified speculation
2719  * is not in a valid state to perform a discard(), this routine will silently
2720  * do nothing.  The state of the specified speculation is transitioned
2721  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2722  */
2723 static void
2724 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2725     dtrace_specid_t which)
2726 {
2727         dtrace_speculation_t *spec;
2728         dtrace_speculation_state_t current, new = 0;
2729         dtrace_buffer_t *buf;
2730
2731         if (which == 0)
2732                 return;
2733
2734         if (which > state->dts_nspeculations) {
2735                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2736                 return;
2737         }
2738
2739         spec = &state->dts_speculations[which - 1];
2740         buf = &spec->dtsp_buffer[cpu];
2741
2742         do {
2743                 current = spec->dtsp_state;
2744
2745                 switch (current) {
2746                 case DTRACESPEC_INACTIVE:
2747                 case DTRACESPEC_COMMITTINGMANY:
2748                 case DTRACESPEC_COMMITTING:
2749                 case DTRACESPEC_DISCARDING:
2750                         return;
2751
2752                 case DTRACESPEC_ACTIVE:
2753                 case DTRACESPEC_ACTIVEMANY:
2754                         new = DTRACESPEC_DISCARDING;
2755                         break;
2756
2757                 case DTRACESPEC_ACTIVEONE:
2758                         if (buf->dtb_offset != 0) {
2759                                 new = DTRACESPEC_INACTIVE;
2760                         } else {
2761                                 new = DTRACESPEC_DISCARDING;
2762                         }
2763                         break;
2764
2765                 default:
2766                         ASSERT(0);
2767                 }
2768         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2769             current, new) != current);
2770
2771         buf->dtb_offset = 0;
2772         buf->dtb_drops = 0;
2773 }
2774
2775 /*
2776  * Note:  not called from probe context.  This function is called
2777  * asynchronously from cross call context to clean any speculations that are
2778  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2779  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2780  * speculation.
2781  */
2782 static void
2783 dtrace_speculation_clean_here(dtrace_state_t *state)
2784 {
2785         dtrace_icookie_t cookie;
2786         processorid_t cpu = curcpu;
2787         dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2788         dtrace_specid_t i;
2789
2790         cookie = dtrace_interrupt_disable();
2791
2792         if (dest->dtb_tomax == NULL) {
2793                 dtrace_interrupt_enable(cookie);
2794                 return;
2795         }
2796
2797         for (i = 0; i < state->dts_nspeculations; i++) {
2798                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2799                 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2800
2801                 if (src->dtb_tomax == NULL)
2802                         continue;
2803
2804                 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2805                         src->dtb_offset = 0;
2806                         continue;
2807                 }
2808
2809                 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2810                         continue;
2811
2812                 if (src->dtb_offset == 0)
2813                         continue;
2814
2815                 dtrace_speculation_commit(state, cpu, i + 1);
2816         }
2817
2818         dtrace_interrupt_enable(cookie);
2819 }
2820
2821 /*
2822  * Note:  not called from probe context.  This function is called
2823  * asynchronously (and at a regular interval) to clean any speculations that
2824  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2825  * is work to be done, it cross calls all CPUs to perform that work;
2826  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2827  * INACTIVE state until they have been cleaned by all CPUs.
2828  */
2829 static void
2830 dtrace_speculation_clean(dtrace_state_t *state)
2831 {
2832         int work = 0, rv;
2833         dtrace_specid_t i;
2834
2835         for (i = 0; i < state->dts_nspeculations; i++) {
2836                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2837
2838                 ASSERT(!spec->dtsp_cleaning);
2839
2840                 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2841                     spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2842                         continue;
2843
2844                 work++;
2845                 spec->dtsp_cleaning = 1;
2846         }
2847
2848         if (!work)
2849                 return;
2850
2851         dtrace_xcall(DTRACE_CPUALL,
2852             (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2853
2854         /*
2855          * We now know that all CPUs have committed or discarded their
2856          * speculation buffers, as appropriate.  We can now set the state
2857          * to inactive.
2858          */
2859         for (i = 0; i < state->dts_nspeculations; i++) {
2860                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2861                 dtrace_speculation_state_t current, new;
2862
2863                 if (!spec->dtsp_cleaning)
2864                         continue;
2865
2866                 current = spec->dtsp_state;
2867                 ASSERT(current == DTRACESPEC_DISCARDING ||
2868                     current == DTRACESPEC_COMMITTINGMANY);
2869
2870                 new = DTRACESPEC_INACTIVE;
2871
2872                 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2873                 ASSERT(rv == current);
2874                 spec->dtsp_cleaning = 0;
2875         }
2876 }
2877
2878 /*
2879  * Called as part of a speculate() to get the speculative buffer associated
2880  * with a given speculation.  Returns NULL if the specified speculation is not
2881  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2882  * the active CPU is not the specified CPU -- the speculation will be
2883  * atomically transitioned into the ACTIVEMANY state.
2884  */
2885 static dtrace_buffer_t *
2886 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2887     dtrace_specid_t which)
2888 {
2889         dtrace_speculation_t *spec;
2890         dtrace_speculation_state_t current, new = 0;
2891         dtrace_buffer_t *buf;
2892
2893         if (which == 0)
2894                 return (NULL);
2895
2896         if (which > state->dts_nspeculations) {
2897                 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2898                 return (NULL);
2899         }
2900
2901         spec = &state->dts_speculations[which - 1];
2902         buf = &spec->dtsp_buffer[cpuid];
2903
2904         do {
2905                 current = spec->dtsp_state;
2906
2907                 switch (current) {
2908                 case DTRACESPEC_INACTIVE:
2909                 case DTRACESPEC_COMMITTINGMANY:
2910                 case DTRACESPEC_DISCARDING:
2911                         return (NULL);
2912
2913                 case DTRACESPEC_COMMITTING:
2914                         ASSERT(buf->dtb_offset == 0);
2915                         return (NULL);
2916
2917                 case DTRACESPEC_ACTIVEONE:
2918                         /*
2919                          * This speculation is currently active on one CPU.
2920                          * Check the offset in the buffer; if it's non-zero,
2921                          * that CPU must be us (and we leave the state alone).
2922                          * If it's zero, assume that we're starting on a new
2923                          * CPU -- and change the state to indicate that the
2924                          * speculation is active on more than one CPU.
2925                          */
2926                         if (buf->dtb_offset != 0)
2927                                 return (buf);
2928
2929                         new = DTRACESPEC_ACTIVEMANY;
2930                         break;
2931
2932                 case DTRACESPEC_ACTIVEMANY:
2933                         return (buf);
2934
2935                 case DTRACESPEC_ACTIVE:
2936                         new = DTRACESPEC_ACTIVEONE;
2937                         break;
2938
2939                 default:
2940                         ASSERT(0);
2941                 }
2942         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2943             current, new) != current);
2944
2945         ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2946         return (buf);
2947 }
2948
2949 /*
2950  * Return a string.  In the event that the user lacks the privilege to access
2951  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2952  * don't fail access checking.
2953  *
2954  * dtrace_dif_variable() uses this routine as a helper for various
2955  * builtin values such as 'execname' and 'probefunc.'
2956  */
2957 uintptr_t
2958 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2959     dtrace_mstate_t *mstate)
2960 {
2961         uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2962         uintptr_t ret;
2963         size_t strsz;
2964
2965         /*
2966          * The easy case: this probe is allowed to read all of memory, so
2967          * we can just return this as a vanilla pointer.
2968          */
2969         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2970                 return (addr);
2971
2972         /*
2973          * This is the tougher case: we copy the string in question from
2974          * kernel memory into scratch memory and return it that way: this
2975          * ensures that we won't trip up when access checking tests the
2976          * BYREF return value.
2977          */
2978         strsz = dtrace_strlen((char *)addr, size) + 1;
2979
2980         if (mstate->dtms_scratch_ptr + strsz >
2981             mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2982                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2983                 return (0);
2984         }
2985
2986         dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2987             strsz);
2988         ret = mstate->dtms_scratch_ptr;
2989         mstate->dtms_scratch_ptr += strsz;
2990         return (ret);
2991 }
2992
2993 /*
2994  * Return a string from a memoy address which is known to have one or
2995  * more concatenated, individually zero terminated, sub-strings.
2996  * In the event that the user lacks the privilege to access
2997  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2998  * don't fail access checking.
2999  *
3000  * dtrace_dif_variable() uses this routine as a helper for various
3001  * builtin values such as 'execargs'.
3002  */
3003 static uintptr_t
3004 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
3005     dtrace_mstate_t *mstate)
3006 {
3007         char *p;
3008         size_t i;
3009         uintptr_t ret;
3010
3011         if (mstate->dtms_scratch_ptr + strsz >
3012             mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3013                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3014                 return (0);
3015         }
3016
3017         dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3018             strsz);
3019
3020         /* Replace sub-string termination characters with a space. */
3021         for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
3022             p++, i++)
3023                 if (*p == '\0')
3024                         *p = ' ';
3025
3026         ret = mstate->dtms_scratch_ptr;
3027         mstate->dtms_scratch_ptr += strsz;
3028         return (ret);
3029 }
3030
3031 /*
3032  * This function implements the DIF emulator's variable lookups.  The emulator
3033  * passes a reserved variable identifier and optional built-in array index.
3034  */
3035 static uint64_t
3036 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3037     uint64_t ndx)
3038 {
3039         /*
3040          * If we're accessing one of the uncached arguments, we'll turn this
3041          * into a reference in the args array.
3042          */
3043         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3044                 ndx = v - DIF_VAR_ARG0;
3045                 v = DIF_VAR_ARGS;
3046         }
3047
3048         switch (v) {
3049         case DIF_VAR_ARGS:
3050                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3051                 if (ndx >= sizeof (mstate->dtms_arg) /
3052                     sizeof (mstate->dtms_arg[0])) {
3053                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3054                         dtrace_provider_t *pv;
3055                         uint64_t val;
3056
3057                         pv = mstate->dtms_probe->dtpr_provider;
3058                         if (pv->dtpv_pops.dtps_getargval != NULL)
3059                                 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3060                                     mstate->dtms_probe->dtpr_id,
3061                                     mstate->dtms_probe->dtpr_arg, ndx, aframes);
3062                         else
3063                                 val = dtrace_getarg(ndx, aframes);
3064
3065                         /*
3066                          * This is regrettably required to keep the compiler
3067                          * from tail-optimizing the call to dtrace_getarg().
3068                          * The condition always evaluates to true, but the
3069                          * compiler has no way of figuring that out a priori.
3070                          * (None of this would be necessary if the compiler
3071                          * could be relied upon to _always_ tail-optimize
3072                          * the call to dtrace_getarg() -- but it can't.)
3073                          */
3074                         if (mstate->dtms_probe != NULL)
3075                                 return (val);
3076
3077                         ASSERT(0);
3078                 }
3079
3080                 return (mstate->dtms_arg[ndx]);
3081
3082 #if defined(sun)
3083         case DIF_VAR_UREGS: {
3084                 klwp_t *lwp;
3085
3086                 if (!dtrace_priv_proc(state))
3087                         return (0);
3088
3089                 if ((lwp = curthread->t_lwp) == NULL) {
3090                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3091                         cpu_core[curcpu].cpuc_dtrace_illval = NULL;
3092                         return (0);
3093                 }
3094
3095                 return (dtrace_getreg(lwp->lwp_regs, ndx));
3096                 return (0);
3097         }
3098 #else
3099         case DIF_VAR_UREGS: {
3100                 struct trapframe *tframe;
3101
3102                 if (!dtrace_priv_proc(state))
3103                         return (0);
3104
3105                 if ((tframe = curthread->td_frame) == NULL) {
3106                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3107                         cpu_core[curcpu].cpuc_dtrace_illval = 0;
3108                         return (0);
3109                 }
3110
3111                 return (dtrace_getreg(tframe, ndx));
3112         }
3113 #endif
3114
3115         case DIF_VAR_CURTHREAD:
3116                 if (!dtrace_priv_proc(state))
3117                         return (0);
3118                 return ((uint64_t)(uintptr_t)curthread);
3119
3120         case DIF_VAR_TIMESTAMP:
3121                 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3122                         mstate->dtms_timestamp = dtrace_gethrtime();
3123                         mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3124                 }
3125                 return (mstate->dtms_timestamp);
3126
3127         case DIF_VAR_VTIMESTAMP:
3128                 ASSERT(dtrace_vtime_references != 0);
3129                 return (curthread->t_dtrace_vtime);
3130
3131         case DIF_VAR_WALLTIMESTAMP:
3132                 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3133                         mstate->dtms_walltimestamp = dtrace_gethrestime();
3134                         mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3135                 }
3136                 return (mstate->dtms_walltimestamp);
3137
3138 #if defined(sun)
3139         case DIF_VAR_IPL:
3140                 if (!dtrace_priv_kernel(state))
3141                         return (0);
3142                 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3143                         mstate->dtms_ipl = dtrace_getipl();
3144                         mstate->dtms_present |= DTRACE_MSTATE_IPL;
3145                 }
3146                 return (mstate->dtms_ipl);
3147 #endif
3148
3149         case DIF_VAR_EPID:
3150                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3151                 return (mstate->dtms_epid);
3152
3153         case DIF_VAR_ID:
3154                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3155                 return (mstate->dtms_probe->dtpr_id);
3156
3157         case DIF_VAR_STACKDEPTH:
3158                 if (!dtrace_priv_kernel(state))
3159                         return (0);
3160                 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3161                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3162
3163                         mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3164                         mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3165                 }
3166                 return (mstate->dtms_stackdepth);
3167
3168         case DIF_VAR_USTACKDEPTH:
3169                 if (!dtrace_priv_proc(state))
3170                         return (0);
3171                 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3172                         /*
3173                          * See comment in DIF_VAR_PID.
3174                          */
3175                         if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3176                             CPU_ON_INTR(CPU)) {
3177                                 mstate->dtms_ustackdepth = 0;
3178                         } else {
3179                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3180                                 mstate->dtms_ustackdepth =
3181                                     dtrace_getustackdepth();
3182                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3183                         }
3184                         mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3185                 }
3186                 return (mstate->dtms_ustackdepth);
3187
3188         case DIF_VAR_CALLER:
3189                 if (!dtrace_priv_kernel(state))
3190                         return (0);
3191                 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3192                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3193
3194                         if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3195                                 /*
3196                                  * If this is an unanchored probe, we are
3197                                  * required to go through the slow path:
3198                                  * dtrace_caller() only guarantees correct
3199                                  * results for anchored probes.
3200                                  */
3201                                 pc_t caller[2] = {0, 0};
3202
3203                                 dtrace_getpcstack(caller, 2, aframes,
3204                                     (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3205                                 mstate->dtms_caller = caller[1];
3206                         } else if ((mstate->dtms_caller =
3207                             dtrace_caller(aframes)) == -1) {
3208                                 /*
3209                                  * We have failed to do this the quick way;
3210                                  * we must resort to the slower approach of
3211                                  * calling dtrace_getpcstack().
3212                                  */
3213                                 pc_t caller = 0;
3214
3215                                 dtrace_getpcstack(&caller, 1, aframes, NULL);
3216                                 mstate->dtms_caller = caller;
3217                         }
3218
3219                         mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3220                 }
3221                 return (mstate->dtms_caller);
3222
3223         case DIF_VAR_UCALLER:
3224                 if (!dtrace_priv_proc(state))
3225                         return (0);
3226
3227                 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3228                         uint64_t ustack[3];
3229
3230                         /*
3231                          * dtrace_getupcstack() fills in the first uint64_t
3232                          * with the current PID.  The second uint64_t will
3233                          * be the program counter at user-level.  The third
3234                          * uint64_t will contain the caller, which is what
3235                          * we're after.
3236                          */
3237                         ustack[2] = 0;
3238                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3239                         dtrace_getupcstack(ustack, 3);
3240                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3241                         mstate->dtms_ucaller = ustack[2];
3242                         mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3243                 }
3244
3245                 return (mstate->dtms_ucaller);
3246
3247         case DIF_VAR_PROBEPROV:
3248                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3249                 return (dtrace_dif_varstr(
3250                     (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3251                     state, mstate));
3252
3253         case DIF_VAR_PROBEMOD:
3254                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3255                 return (dtrace_dif_varstr(
3256                     (uintptr_t)mstate->dtms_probe->dtpr_mod,
3257                     state, mstate));
3258
3259         case DIF_VAR_PROBEFUNC:
3260                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3261                 return (dtrace_dif_varstr(
3262                     (uintptr_t)mstate->dtms_probe->dtpr_func,
3263                     state, mstate));
3264
3265         case DIF_VAR_PROBENAME:
3266                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3267                 return (dtrace_dif_varstr(
3268                     (uintptr_t)mstate->dtms_probe->dtpr_name,
3269                     state, mstate));
3270
3271         case DIF_VAR_PID:
3272                 if (!dtrace_priv_proc(state))
3273                         return (0);
3274
3275 #if defined(sun)
3276                 /*
3277                  * Note that we are assuming that an unanchored probe is
3278                  * always due to a high-level interrupt.  (And we're assuming
3279                  * that there is only a single high level interrupt.)
3280                  */
3281                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3282                         return (pid0.pid_id);
3283
3284                 /*
3285                  * It is always safe to dereference one's own t_procp pointer:
3286                  * it always points to a valid, allocated proc structure.
3287                  * Further, it is always safe to dereference the p_pidp member
3288                  * of one's own proc structure.  (These are truisms becuase
3289                  * threads and processes don't clean up their own state --
3290                  * they leave that task to whomever reaps them.)
3291                  */
3292                 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3293 #else
3294                 return ((uint64_t)curproc->p_pid);
3295 #endif
3296
3297         case DIF_VAR_PPID:
3298                 if (!dtrace_priv_proc(state))
3299                         return (0);
3300
3301 #if defined(sun)
3302                 /*
3303                  * See comment in DIF_VAR_PID.
3304                  */
3305                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3306                         return (pid0.pid_id);
3307
3308                 /*
3309                  * It is always safe to dereference one's own t_procp pointer:
3310                  * it always points to a valid, allocated proc structure.
3311                  * (This is true because threads don't clean up their own
3312                  * state -- they leave that task to whomever reaps them.)
3313                  */
3314                 return ((uint64_t)curthread->t_procp->p_ppid);
3315 #else
3316                 return ((uint64_t)curproc->p_pptr->p_pid);
3317 #endif
3318
3319         case DIF_VAR_TID:
3320 #if defined(sun)
3321                 /*
3322                  * See comment in DIF_VAR_PID.
3323                  */
3324                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3325                         return (0);
3326 #endif
3327
3328                 return ((uint64_t)curthread->t_tid);
3329
3330         case DIF_VAR_EXECARGS: {
3331                 struct pargs *p_args = curthread->td_proc->p_args;
3332
3333                 if (p_args == NULL)
3334                         return(0);
3335
3336                 return (dtrace_dif_varstrz(
3337                     (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3338         }
3339
3340         case DIF_VAR_EXECNAME:
3341 #if defined(sun)
3342                 if (!dtrace_priv_proc(state))
3343                         return (0);
3344
3345                 /*
3346                  * See comment in DIF_VAR_PID.
3347                  */
3348                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3349                         return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3350
3351                 /*
3352                  * It is always safe to dereference one's own t_procp pointer:
3353                  * it always points to a valid, allocated proc structure.
3354                  * (This is true because threads don't clean up their own
3355                  * state -- they leave that task to whomever reaps them.)
3356                  */
3357                 return (dtrace_dif_varstr(
3358                     (uintptr_t)curthread->t_procp->p_user.u_comm,
3359                     state, mstate));
3360 #else
3361                 return (dtrace_dif_varstr(
3362                     (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3363 #endif
3364
3365         case DIF_VAR_ZONENAME:
3366 #if defined(sun)
3367                 if (!dtrace_priv_proc(state))
3368                         return (0);
3369
3370                 /*
3371                  * See comment in DIF_VAR_PID.
3372                  */
3373                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3374                         return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3375
3376                 /*
3377                  * It is always safe to dereference one's own t_procp pointer:
3378                  * it always points to a valid, allocated proc structure.
3379                  * (This is true because threads don't clean up their own
3380                  * state -- they leave that task to whomever reaps them.)
3381                  */
3382                 return (dtrace_dif_varstr(
3383                     (uintptr_t)curthread->t_procp->p_zone->zone_name,
3384                     state, mstate));
3385 #else
3386                 return (0);
3387 #endif
3388
3389         case DIF_VAR_UID:
3390                 if (!dtrace_priv_proc(state))
3391                         return (0);
3392
3393 #if defined(sun)
3394                 /*
3395                  * See comment in DIF_VAR_PID.
3396                  */
3397                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3398                         return ((uint64_t)p0.p_cred->cr_uid);
3399 #endif
3400
3401                 /*
3402                  * It is always safe to dereference one's own t_procp pointer:
3403                  * it always points to a valid, allocated proc structure.
3404                  * (This is true because threads don't clean up their own
3405                  * state -- they leave that task to whomever reaps them.)
3406                  *
3407                  * Additionally, it is safe to dereference one's own process
3408                  * credential, since this is never NULL after process birth.
3409                  */
3410                 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3411
3412         case DIF_VAR_GID:
3413                 if (!dtrace_priv_proc(state))
3414                         return (0);
3415
3416 #if defined(sun)
3417                 /*
3418                  * See comment in DIF_VAR_PID.
3419                  */
3420                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3421                         return ((uint64_t)p0.p_cred->cr_gid);
3422 #endif
3423
3424                 /*
3425                  * It is always safe to dereference one's own t_procp pointer:
3426                  * it always points to a valid, allocated proc structure.
3427                  * (This is true because threads don't clean up their own
3428                  * state -- they leave that task to whomever reaps them.)
3429                  *
3430                  * Additionally, it is safe to dereference one's own process
3431                  * credential, since this is never NULL after process birth.
3432                  */
3433                 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3434
3435         case DIF_VAR_ERRNO: {
3436 #if defined(sun)
3437                 klwp_t *lwp;
3438                 if (!dtrace_priv_proc(state))
3439                         return (0);
3440
3441                 /*
3442                  * See comment in DIF_VAR_PID.
3443                  */
3444                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3445                         return (0);
3446
3447                 /*
3448                  * It is always safe to dereference one's own t_lwp pointer in
3449                  * the event that this pointer is non-NULL.  (This is true
3450                  * because threads and lwps don't clean up their own state --
3451                  * they leave that task to whomever reaps them.)
3452                  */
3453                 if ((lwp = curthread->t_lwp) == NULL)
3454                         return (0);
3455
3456                 return ((uint64_t)lwp->lwp_errno);
3457 #else
3458                 return (curthread->td_errno);
3459 #endif
3460         }
3461 #if !defined(sun)
3462         case DIF_VAR_CPU: {
3463                 return curcpu;
3464         }
3465 #endif
3466         default:
3467                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3468                 return (0);
3469         }
3470 }
3471
3472 /*
3473  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3474  * Notice that we don't bother validating the proper number of arguments or
3475  * their types in the tuple stack.  This isn't needed because all argument
3476  * interpretation is safe because of our load safety -- the worst that can
3477  * happen is that a bogus program can obtain bogus results.
3478  */
3479 static void
3480 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3481     dtrace_key_t *tupregs, int nargs,
3482     dtrace_mstate_t *mstate, dtrace_state_t *state)
3483 {
3484         volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
3485         volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
3486         dtrace_vstate_t *vstate = &state->dts_vstate;
3487
3488 #if defined(sun)
3489         union {
3490                 mutex_impl_t mi;
3491                 uint64_t mx;
3492         } m;
3493
3494         union {
3495                 krwlock_t ri;
3496                 uintptr_t rw;
3497         } r;
3498 #else
3499         struct thread *lowner;
3500         union {
3501                 struct lock_object *li;
3502                 uintptr_t lx;
3503         } l;
3504 #endif
3505
3506         switch (subr) {
3507         case DIF_SUBR_RAND:
3508                 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3509                 break;
3510
3511 #if defined(sun)
3512         case DIF_SUBR_MUTEX_OWNED:
3513                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3514                     mstate, vstate)) {
3515                         regs[rd] = 0;
3516                         break;
3517                 }
3518
3519                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3520                 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3521                         regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3522                 else
3523                         regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3524                 break;
3525
3526         case DIF_SUBR_MUTEX_OWNER:
3527                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3528                     mstate, vstate)) {
3529                         regs[rd] = 0;
3530                         break;
3531                 }
3532
3533                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3534                 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3535                     MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3536                         regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3537                 else
3538                         regs[rd] = 0;
3539                 break;
3540
3541         case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3542                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3543                     mstate, vstate)) {
3544                         regs[rd] = 0;
3545                         break;
3546                 }
3547
3548                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3549                 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3550                 break;
3551
3552         case DIF_SUBR_MUTEX_TYPE_SPIN:
3553                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3554                     mstate, vstate)) {
3555                         regs[rd] = 0;
3556                         break;
3557                 }
3558
3559                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3560                 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3561                 break;
3562
3563         case DIF_SUBR_RW_READ_HELD: {
3564                 uintptr_t tmp;
3565
3566                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3567                     mstate, vstate)) {
3568                         regs[rd] = 0;
3569                         break;
3570                 }
3571
3572                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3573                 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3574                 break;
3575         }
3576
3577         case DIF_SUBR_RW_WRITE_HELD:
3578                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3579                     mstate, vstate)) {
3580                         regs[rd] = 0;
3581                         break;
3582                 }
3583
3584                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3585                 regs[rd] = _RW_WRITE_HELD(&r.ri);
3586                 break;
3587
3588         case DIF_SUBR_RW_ISWRITER:
3589                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3590                     mstate, vstate)) {
3591                         regs[rd] = 0;
3592                         break;
3593                 }
3594
3595                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3596                 regs[rd] = _RW_ISWRITER(&r.ri);
3597                 break;
3598
3599 #else
3600         case DIF_SUBR_MUTEX_OWNED:
3601                 if (!dtrace_canload(tupregs[0].dttk_value,
3602                         sizeof (struct lock_object), mstate, vstate)) {
3603                         regs[rd] = 0;
3604                         break;
3605                 }
3606                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3607                 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3608                 break;
3609
3610         case DIF_SUBR_MUTEX_OWNER:
3611                 if (!dtrace_canload(tupregs[0].dttk_value,
3612                         sizeof (struct lock_object), mstate, vstate)) {
3613                         regs[rd] = 0;
3614                         break;
3615                 }
3616                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3617                 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3618                 regs[rd] = (uintptr_t)lowner;
3619                 break;
3620
3621         case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3622                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3623                     mstate, vstate)) {
3624                         regs[rd] = 0;
3625                         break;
3626                 }
3627                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3628                 /* XXX - should be only LC_SLEEPABLE? */
3629                 regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
3630                     (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
3631                 break;
3632
3633         case DIF_SUBR_MUTEX_TYPE_SPIN:
3634                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3635                     mstate, vstate)) {
3636                         regs[rd] = 0;
3637                         break;
3638                 }
3639                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3640                 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
3641                 break;
3642
3643         case DIF_SUBR_RW_READ_HELD: 
3644         case DIF_SUBR_SX_SHARED_HELD: 
3645                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3646                     mstate, vstate)) {
3647                         regs[rd] = 0;
3648                         break;
3649                 }
3650                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3651                 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3652                     lowner == NULL;
3653                 break;
3654
3655         case DIF_SUBR_RW_WRITE_HELD:
3656         case DIF_SUBR_SX_EXCLUSIVE_HELD:
3657                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3658                     mstate, vstate)) {
3659                         regs[rd] = 0;
3660                         break;
3661                 }
3662                 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3663                 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3664                 regs[rd] = (lowner == curthread);
3665                 break;
3666
3667         case DIF_SUBR_RW_ISWRITER:
3668         case DIF_SUBR_SX_ISEXCLUSIVE:
3669                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3670                     mstate, vstate)) {
3671                         regs[rd] = 0;
3672                         break;
3673                 }
3674                 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3675                 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3676                     lowner != NULL;
3677                 break;
3678 #endif /* ! defined(sun) */
3679
3680         case DIF_SUBR_BCOPY: {
3681                 /*
3682                  * We need to be sure that the destination is in the scratch
3683                  * region -- no other region is allowed.
3684                  */
3685                 uintptr_t src = tupregs[0].dttk_value;
3686                 uintptr_t dest = tupregs[1].dttk_value;
3687                 size_t size = tupregs[2].dttk_value;
3688
3689                 if (!dtrace_inscratch(dest, size, mstate)) {
3690                         *flags |= CPU_DTRACE_BADADDR;
3691                         *illval = regs[rd];
3692                         break;
3693                 }
3694
3695                 if (!dtrace_canload(src, size, mstate, vstate)) {
3696                         regs[rd] = 0;
3697                         break;
3698                 }
3699
3700                 dtrace_bcopy((void *)src, (void *)dest, size);
3701                 break;
3702         }
3703
3704         case DIF_SUBR_ALLOCA:
3705         case DIF_SUBR_COPYIN: {
3706                 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3707                 uint64_t size =
3708                     tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3709                 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3710
3711                 /*
3712                  * This action doesn't require any credential checks since
3713                  * probes will not activate in user contexts to which the
3714                  * enabling user does not have permissions.
3715                  */
3716
3717                 /*
3718                  * Rounding up the user allocation size could have overflowed
3719                  * a large, bogus allocation (like -1ULL) to 0.
3720                  */
3721                 if (scratch_size < size ||
3722                     !DTRACE_INSCRATCH(mstate, scratch_size)) {
3723                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3724                         regs[rd] = 0;
3725                         break;
3726                 }
3727
3728                 if (subr == DIF_SUBR_COPYIN) {
3729                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3730                         dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3731                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3732                 }
3733
3734                 mstate->dtms_scratch_ptr += scratch_size;
3735                 regs[rd] = dest;
3736                 break;
3737         }
3738
3739         case DIF_SUBR_COPYINTO: {
3740                 uint64_t size = tupregs[1].dttk_value;
3741                 uintptr_t dest = tupregs[2].dttk_value;
3742
3743                 /*
3744                  * This action doesn't require any credential checks since
3745                  * probes will not activate in user contexts to which the
3746                  * enabling user does not have permissions.
3747                  */
3748                 if (!dtrace_inscratch(dest, size, mstate)) {
3749                         *flags |= CPU_DTRACE_BADADDR;
3750                         *illval = regs[rd];
3751                         break;
3752                 }
3753
3754                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3755                 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3756                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3757                 break;
3758         }
3759
3760         case DIF_SUBR_COPYINSTR: {
3761                 uintptr_t dest = mstate->dtms_scratch_ptr;
3762                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3763
3764                 if (nargs > 1 && tupregs[1].dttk_value < size)
3765                         size = tupregs[1].dttk_value + 1;
3766
3767                 /*
3768                  * This action doesn't require any credential checks since
3769                  * probes will not activate in user contexts to which the
3770                  * enabling user does not have permissions.
3771                  */
3772                 if (!DTRACE_INSCRATCH(mstate, size)) {
3773                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3774                         regs[rd] = 0;
3775                         break;
3776                 }
3777
3778                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3779                 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3780                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3781
3782                 ((char *)dest)[size - 1] = '\0';
3783                 mstate->dtms_scratch_ptr += size;
3784                 regs[rd] = dest;
3785                 break;
3786         }
3787
3788 #if defined(sun)
3789         case DIF_SUBR_MSGSIZE:
3790         case DIF_SUBR_MSGDSIZE: {
3791                 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3792                 uintptr_t wptr, rptr;
3793                 size_t count = 0;
3794                 int cont = 0;
3795
3796                 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
3797
3798                         if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3799                             vstate)) {
3800                                 regs[rd] = 0;
3801                                 break;
3802                         }
3803
3804                         wptr = dtrace_loadptr(baddr +
3805                             offsetof(mblk_t, b_wptr));
3806
3807                         rptr = dtrace_loadptr(baddr +
3808                             offsetof(mblk_t, b_rptr));
3809
3810                         if (wptr < rptr) {
3811                                 *flags |= CPU_DTRACE_BADADDR;
3812                                 *illval = tupregs[0].dttk_value;
3813                                 break;
3814                         }
3815
3816                         daddr = dtrace_loadptr(baddr +
3817                             offsetof(mblk_t, b_datap));
3818
3819                         baddr = dtrace_loadptr(baddr +
3820                             offsetof(mblk_t, b_cont));
3821
3822                         /*
3823                          * We want to prevent against denial-of-service here,
3824                          * so we're only going to search the list for
3825                          * dtrace_msgdsize_max mblks.
3826                          */
3827                         if (cont++ > dtrace_msgdsize_max) {
3828                                 *flags |= CPU_DTRACE_ILLOP;
3829                                 break;
3830                         }
3831
3832                         if (subr == DIF_SUBR_MSGDSIZE) {
3833                                 if (dtrace_load8(daddr +
3834                                     offsetof(dblk_t, db_type)) != M_DATA)
3835                                         continue;
3836                         }
3837
3838                         count += wptr - rptr;
3839                 }
3840
3841                 if (!(*flags & CPU_DTRACE_FAULT))
3842                         regs[rd] = count;
3843
3844                 break;
3845         }
3846 #endif
3847
3848         case DIF_SUBR_PROGENYOF: {
3849                 pid_t pid = tupregs[0].dttk_value;
3850                 proc_t *p;
3851                 int rval = 0;
3852
3853                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3854
3855                 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3856 #if defined(sun)
3857                         if (p->p_pidp->pid_id == pid) {
3858 #else
3859                         if (p->p_pid == pid) {
3860 #endif
3861                                 rval = 1;
3862                                 break;
3863                         }
3864                 }
3865
3866                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3867
3868                 regs[rd] = rval;
3869                 break;
3870         }
3871
3872         case DIF_SUBR_SPECULATION:
3873                 regs[rd] = dtrace_speculation(state);
3874                 break;
3875
3876         case DIF_SUBR_COPYOUT: {
3877                 uintptr_t kaddr = tupregs[0].dttk_value;
3878                 uintptr_t uaddr = tupregs[1].dttk_value;
3879                 uint64_t size = tupregs[2].dttk_value;
3880
3881                 if (!dtrace_destructive_disallow &&
3882                     dtrace_priv_proc_control(state) &&
3883                     !dtrace_istoxic(kaddr, size)) {
3884                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3885                         dtrace_copyout(kaddr, uaddr, size, flags);
3886                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3887                 }
3888                 break;
3889         }
3890
3891         case DIF_SUBR_COPYOUTSTR: {
3892                 uintptr_t kaddr = tupregs[0].dttk_value;
3893                 uintptr_t uaddr = tupregs[1].dttk_value;
3894                 uint64_t size = tupregs[2].dttk_value;
3895
3896                 if (!dtrace_destructive_disallow &&
3897                     dtrace_priv_proc_control(state) &&
3898                     !dtrace_istoxic(kaddr, size)) {
3899                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3900                         dtrace_copyoutstr(kaddr, uaddr, size, flags);
3901                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3902                 }
3903                 break;
3904         }
3905
3906         case DIF_SUBR_STRLEN: {
3907                 size_t sz;
3908                 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3909                 sz = dtrace_strlen((char *)addr,
3910                     state->dts_options[DTRACEOPT_STRSIZE]);
3911
3912                 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3913                         regs[rd] = 0;
3914                         break;
3915                 }
3916
3917                 regs[rd] = sz;
3918
3919                 break;
3920         }
3921
3922         case DIF_SUBR_STRCHR:
3923         case DIF_SUBR_STRRCHR: {
3924                 /*
3925                  * We're going to iterate over the string looking for the
3926                  * specified character.  We will iterate until we have reached
3927                  * the string length or we have found the character.  If this
3928                  * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3929                  * of the specified character instead of the first.
3930                  */
3931                 uintptr_t saddr = tupregs[0].dttk_value;
3932                 uintptr_t addr = tupregs[0].dttk_value;
3933                 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3934                 char c, target = (char)tupregs[1].dttk_value;
3935
3936                 for (regs[rd] = 0; addr < limit; addr++) {
3937                         if ((c = dtrace_load8(addr)) == target) {
3938                                 regs[rd] = addr;
3939
3940                                 if (subr == DIF_SUBR_STRCHR)
3941                                         break;
3942                         }
3943
3944                         if (c == '\0')
3945                                 break;
3946                 }
3947
3948                 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3949                         regs[rd] = 0;
3950                         break;
3951                 }
3952
3953                 break;
3954         }
3955
3956         case DIF_SUBR_STRSTR:
3957         case DIF_SUBR_INDEX:
3958         case DIF_SUBR_RINDEX: {
3959                 /*
3960                  * We're going to iterate over the string looking for the
3961                  * specified string.  We will iterate until we have reached
3962                  * the string length or we have found the string.  (Yes, this
3963                  * is done in the most naive way possible -- but considering
3964                  * that the string we're searching for is likely to be
3965                  * relatively short, the complexity of Rabin-Karp or similar
3966                  * hardly seems merited.)
3967                  */
3968                 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3969                 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3970                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3971                 size_t len = dtrace_strlen(addr, size);
3972                 size_t sublen = dtrace_strlen(substr, size);
3973                 char *limit = addr + len, *orig = addr;
3974                 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3975                 int inc = 1;
3976
3977                 regs[rd] = notfound;
3978
3979                 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3980                         regs[rd] = 0;
3981                         break;
3982                 }
3983
3984                 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3985                     vstate)) {
3986                         regs[rd] = 0;
3987                         break;
3988                 }
3989
3990                 /*
3991                  * strstr() and index()/rindex() have similar semantics if
3992                  * both strings are the empty string: strstr() returns a
3993                  * pointer to the (empty) string, and index() and rindex()
3994                  * both return index 0 (regardless of any position argument).
3995                  */
3996                 if (sublen == 0 && len == 0) {
3997                         if (subr == DIF_SUBR_STRSTR)
3998                                 regs[rd] = (uintptr_t)addr;
3999                         else
4000                                 regs[rd] = 0;
4001                         break;
4002                 }
4003
4004                 if (subr != DIF_SUBR_STRSTR) {
4005                         if (subr == DIF_SUBR_RINDEX) {
4006                                 limit = orig - 1;
4007                                 addr += len;
4008                                 inc = -1;
4009                         }
4010
4011                         /*
4012                          * Both index() and rindex() take an optional position
4013                          * argument that denotes the starting position.
4014                          */
4015                         if (nargs == 3) {
4016                                 int64_t pos = (int64_t)tupregs[2].dttk_value;
4017
4018                                 /*
4019                                  * If the position argument to index() is
4020                                  * negative, Perl implicitly clamps it at
4021                                  * zero.  This semantic is a little surprising
4022                                  * given the special meaning of negative
4023                                  * positions to similar Perl functions like
4024                                  * substr(), but it appears to reflect a
4025                                  * notion that index() can start from a
4026                                  * negative index and increment its way up to
4027                                  * the string.  Given this notion, Perl's
4028                                  * rindex() is at least self-consistent in
4029                                  * that it implicitly clamps positions greater
4030                                  * than the string length to be the string
4031                                  * length.  Where Perl completely loses
4032                                  * coherence, however, is when the specified
4033                                  * substring is the empty string ("").  In
4034                                  * this case, even if the position is
4035                                  * negative, rindex() returns 0 -- and even if
4036                                  * the position is greater than the length,
4037                                  * index() returns the string length.  These
4038                                  * semantics violate the notion that index()
4039                                  * should never return a value less than the
4040                                  * specified position and that rindex() should
4041                                  * never return a value greater than the
4042                                  * specified position.  (One assumes that
4043                                  * these semantics are artifacts of Perl's
4044                                  * implementation and not the results of
4045                                  * deliberate design -- it beggars belief that
4046                                  * even Larry Wall could desire such oddness.)
4047                                  * While in the abstract one would wish for
4048                                  * consistent position semantics across
4049                                  * substr(), index() and rindex() -- or at the
4050                                  * very least self-consistent position
4051                                  * semantics for index() and rindex() -- we
4052                                  * instead opt to keep with the extant Perl
4053                                  * semantics, in all their broken glory.  (Do
4054                                  * we have more desire to maintain Perl's
4055                                  * semantics than Perl does?  Probably.)
4056                                  */
4057                                 if (subr == DIF_SUBR_RINDEX) {
4058                                         if (pos < 0) {
4059                                                 if (sublen == 0)
4060                                                         regs[rd] = 0;
4061                                                 break;
4062                                         }
4063
4064                                         if (pos > len)
4065                                                 pos = len;
4066                                 } else {
4067                                         if (pos < 0)
4068                                                 pos = 0;
4069
4070                                         if (pos >= len) {
4071                                                 if (sublen == 0)
4072                                                         regs[rd] = len;
4073                                                 break;
4074                                         }
4075                                 }
4076
4077                                 addr = orig + pos;
4078                         }
4079                 }
4080
4081                 for (regs[rd] = notfound; addr != limit; addr += inc) {
4082                         if (dtrace_strncmp(addr, substr, sublen) == 0) {
4083                                 if (subr != DIF_SUBR_STRSTR) {
4084                                         /*
4085                                          * As D index() and rindex() are
4086                                          * modeled on Perl (and not on awk),
4087                                          * we return a zero-based (and not a
4088                                          * one-based) index.  (For you Perl
4089                                          * weenies: no, we're not going to add
4090                                          * $[ -- and shouldn't you be at a con
4091                                          * or something?)
4092                                          */
4093                                         regs[rd] = (uintptr_t)(addr - orig);
4094                                         break;
4095                                 }
4096
4097                                 ASSERT(subr == DIF_SUBR_STRSTR);
4098                                 regs[rd] = (uintptr_t)addr;
4099                                 break;
4100                         }
4101                 }
4102
4103                 break;
4104         }
4105
4106         case DIF_SUBR_STRTOK: {
4107                 uintptr_t addr = tupregs[0].dttk_value;
4108                 uintptr_t tokaddr = tupregs[1].dttk_value;
4109                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4110                 uintptr_t limit, toklimit = tokaddr + size;
4111                 uint8_t c = 0, tokmap[32];       /* 256 / 8 */
4112                 char *dest = (char *)mstate->dtms_scratch_ptr;
4113                 int i;
4114
4115                 /*
4116                  * Check both the token buffer and (later) the input buffer,
4117                  * since both could be non-scratch addresses.
4118                  */
4119                 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4120                         regs[rd] = 0;
4121                         break;
4122                 }
4123
4124                 if (!DTRACE_INSCRATCH(mstate, size)) {
4125                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4126                         regs[rd] = 0;
4127                         break;
4128                 }
4129
4130                 if (addr == 0) {
4131                         /*
4132                          * If the address specified is NULL, we use our saved
4133                          * strtok pointer from the mstate.  Note that this
4134                          * means that the saved strtok pointer is _only_
4135                          * valid within multiple enablings of the same probe --
4136                          * it behaves like an implicit clause-local variable.
4137                          */
4138                         addr = mstate->dtms_strtok;
4139                 } else {
4140                         /*
4141                          * If the user-specified address is non-NULL we must
4142                          * access check it.  This is the only time we have
4143                          * a chance to do so, since this address may reside
4144                          * in the string table of this clause-- future calls
4145                          * (when we fetch addr from mstate->dtms_strtok)
4146                          * would fail this access check.
4147                          */
4148                         if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4149                                 regs[rd] = 0;
4150                                 break;
4151                         }
4152                 }
4153
4154                 /*
4155                  * First, zero the token map, and then process the token
4156                  * string -- setting a bit in the map for every character
4157                  * found in the token string.
4158                  */
4159                 for (i = 0; i < sizeof (tokmap); i++)
4160                         tokmap[i] = 0;
4161
4162                 for (; tokaddr < toklimit; tokaddr++) {
4163                         if ((c = dtrace_load8(tokaddr)) == '\0')
4164                                 break;
4165
4166                         ASSERT((c >> 3) < sizeof (tokmap));
4167                         tokmap[c >> 3] |= (1 << (c & 0x7));
4168                 }
4169
4170                 for (limit = addr + size; addr < limit; addr++) {
4171                         /*
4172                          * We're looking for a character that is _not_ contained
4173                          * in the token string.
4174                          */
4175                         if ((c = dtrace_load8(addr)) == '\0')
4176                                 break;
4177
4178                         if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4179                                 break;
4180                 }
4181
4182                 if (c == '\0') {
4183                         /*
4184                          * We reached the end of the string without finding
4185                          * any character that was not in the token string.
4186                          * We return NULL in this case, and we set the saved
4187                          * address to NULL as well.
4188                          */
4189                         regs[rd] = 0;
4190                         mstate->dtms_strtok = 0;
4191                         break;
4192                 }
4193
4194                 /*
4195                  * From here on, we're copying into the destination string.
4196                  */
4197                 for (i = 0; addr < limit && i < size - 1; addr++) {
4198                         if ((c = dtrace_load8(addr)) == '\0')
4199                                 break;
4200
4201                         if (tokmap[c >> 3] & (1 << (c & 0x7)))
4202                                 break;
4203
4204                         ASSERT(i < size);
4205                         dest[i++] = c;
4206                 }
4207
4208                 ASSERT(i < size);
4209                 dest[i] = '\0';
4210                 regs[rd] = (uintptr_t)dest;
4211                 mstate->dtms_scratch_ptr += size;
4212                 mstate->dtms_strtok = addr;
4213                 break;
4214         }
4215
4216         case DIF_SUBR_SUBSTR: {
4217                 uintptr_t s = tupregs[0].dttk_value;
4218                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4219                 char *d = (char *)mstate->dtms_scratch_ptr;
4220                 int64_t index = (int64_t)tupregs[1].dttk_value;
4221                 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4222                 size_t len = dtrace_strlen((char *)s, size);
4223                 int64_t i = 0;
4224
4225                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4226                         regs[rd] = 0;
4227                         break;
4228                 }
4229
4230                 if (!DTRACE_INSCRATCH(mstate, size)) {
4231                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4232                         regs[rd] = 0;
4233                         break;
4234                 }
4235
4236                 if (nargs <= 2)
4237                         remaining = (int64_t)size;
4238
4239                 if (index < 0) {
4240                         index += len;
4241
4242                         if (index < 0 && index + remaining > 0) {
4243                                 remaining += index;
4244                                 index = 0;
4245                         }
4246                 }
4247
4248                 if (index >= len || index < 0) {
4249                         remaining = 0;
4250                 } else if (remaining < 0) {
4251                         remaining += len - index;
4252                 } else if (index + remaining > size) {
4253                         remaining = size - index;
4254                 }
4255
4256                 for (i = 0; i < remaining; i++) {
4257                         if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4258                                 break;
4259                 }
4260
4261                 d[i] = '\0';
4262
4263                 mstate->dtms_scratch_ptr += size;
4264                 regs[rd] = (uintptr_t)d;
4265                 break;
4266         }
4267
4268         case DIF_SUBR_TOUPPER:
4269         case DIF_SUBR_TOLOWER: {
4270                 uintptr_t s = tupregs[0].dttk_value;
4271                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4272                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4273                 size_t len = dtrace_strlen((char *)s, size);
4274                 char lower, upper, convert;
4275                 int64_t i;
4276
4277                 if (subr == DIF_SUBR_TOUPPER) {
4278                         lower = 'a';
4279                         upper = 'z';
4280                         convert = 'A';
4281                 } else {
4282                         lower = 'A';
4283                         upper = 'Z';
4284                         convert = 'a';
4285                 }
4286
4287                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4288                         regs[rd] = 0;
4289                         break;
4290                 }
4291
4292                 if (!DTRACE_INSCRATCH(mstate, size)) {
4293                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4294                         regs[rd] = 0;
4295                         break;
4296                 }
4297
4298                 for (i = 0; i < size - 1; i++) {
4299                         if ((c = dtrace_load8(s + i)) == '\0')
4300                                 break;
4301
4302                         if (c >= lower && c <= upper)
4303                                 c = convert + (c - lower);
4304
4305                         dest[i] = c;
4306                 }
4307
4308                 ASSERT(i < size);
4309                 dest[i] = '\0';
4310                 regs[rd] = (uintptr_t)dest;
4311                 mstate->dtms_scratch_ptr += size;
4312                 break;
4313         }
4314
4315 #if defined(sun)
4316         case DIF_SUBR_GETMAJOR:
4317 #ifdef _LP64
4318                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4319 #else
4320                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4321 #endif
4322                 break;
4323
4324         case DIF_SUBR_GETMINOR:
4325 #ifdef _LP64
4326                 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4327 #else
4328                 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4329 #endif
4330                 break;
4331
4332         case DIF_SUBR_DDI_PATHNAME: {
4333                 /*
4334                  * This one is a galactic mess.  We are going to roughly
4335                  * emulate ddi_pathname(), but it's made more complicated
4336                  * by the fact that we (a) want to include the minor name and
4337                  * (b) must proceed iteratively instead of recursively.
4338                  */
4339                 uintptr_t dest = mstate->dtms_scratch_ptr;
4340                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4341                 char *start = (char *)dest, *end = start + size - 1;
4342                 uintptr_t daddr = tupregs[0].dttk_value;
4343                 int64_t minor = (int64_t)tupregs[1].dttk_value;
4344                 char *s;
4345                 int i, len, depth = 0;
4346
4347                 /*
4348                  * Due to all the pointer jumping we do and context we must
4349                  * rely upon, we just mandate that the user must have kernel
4350                  * read privileges to use this routine.
4351                  */
4352                 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4353                         *flags |= CPU_DTRACE_KPRIV;
4354                         *illval = daddr;
4355                         regs[rd] = 0;
4356                 }
4357
4358                 if (!DTRACE_INSCRATCH(mstate, size)) {
4359                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4360                         regs[rd] = 0;
4361                         break;
4362                 }
4363
4364                 *end = '\0';
4365
4366                 /*
4367                  * We want to have a name for the minor.  In order to do this,
4368                  * we need to walk the minor list from the devinfo.  We want
4369                  * to be sure that we don't infinitely walk a circular list,
4370                  * so we check for circularity by sending a scout pointer
4371                  * ahead two elements for every element that we iterate over;
4372                  * if the list is circular, these will ultimately point to the
4373                  * same element.  You may recognize this little trick as the
4374                  * answer to a stupid interview question -- one that always
4375                  * seems to be asked by those who had to have it laboriously
4376                  * explained to them, and who can't even concisely describe
4377                  * the conditions under which one would be forced to resort to
4378                  * this technique.  Needless to say, those conditions are
4379                  * found here -- and probably only here.  Is this the only use
4380                  * of this infamous trick in shipping, production code?  If it
4381                  * isn't, it probably should be...
4382                  */
4383                 if (minor != -1) {
4384                         uintptr_t maddr = dtrace_loadptr(daddr +
4385                             offsetof(struct dev_info, devi_minor));
4386
4387                         uintptr_t next = offsetof(struct ddi_minor_data, next);
4388                         uintptr_t name = offsetof(struct ddi_minor_data,
4389                             d_minor) + offsetof(struct ddi_minor, name);
4390                         uintptr_t dev = offsetof(struct ddi_minor_data,
4391                             d_minor) + offsetof(struct ddi_minor, dev);
4392                         uintptr_t scout;
4393
4394                         if (maddr != NULL)
4395                                 scout = dtrace_loadptr(maddr + next);
4396
4397                         while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4398                                 uint64_t m;
4399 #ifdef _LP64
4400                                 m = dtrace_load64(maddr + dev) & MAXMIN64;
4401 #else
4402                                 m = dtrace_load32(maddr + dev) & MAXMIN;
4403 #endif
4404                                 if (m != minor) {
4405                                         maddr = dtrace_loadptr(maddr + next);
4406
4407                                         if (scout == NULL)
4408                                                 continue;
4409
4410                                         scout = dtrace_loadptr(scout + next);
4411
4412                                         if (scout == NULL)
4413                                                 continue;
4414
4415                                         scout = dtrace_loadptr(scout + next);
4416
4417                                         if (scout == NULL)
4418                                                 continue;
4419
4420                                         if (scout == maddr) {
4421                                                 *flags |= CPU_DTRACE_ILLOP;
4422                                                 break;
4423                                         }
4424
4425                                         continue;
4426                                 }
4427
4428                                 /*
4429                                  * We have the minor data.  Now we need to
4430                                  * copy the minor's name into the end of the
4431                                  * pathname.
4432                                  */
4433                                 s = (char *)dtrace_loadptr(maddr + name);
4434                                 len = dtrace_strlen(s, size);
4435
4436                                 if (*flags & CPU_DTRACE_FAULT)
4437                                         break;
4438
4439                                 if (len != 0) {
4440                                         if ((end -= (len + 1)) < start)
4441                                                 break;
4442
4443                                         *end = ':';
4444                                 }
4445
4446                                 for (i = 1; i <= len; i++)
4447                                         end[i] = dtrace_load8((uintptr_t)s++);
4448                                 break;
4449                         }
4450                 }
4451
4452                 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4453                         ddi_node_state_t devi_state;
4454
4455                         devi_state = dtrace_load32(daddr +
4456                             offsetof(struct dev_info, devi_node_state));
4457
4458                         if (*flags & CPU_DTRACE_FAULT)
4459                                 break;
4460
4461                         if (devi_state >= DS_INITIALIZED) {
4462                                 s = (char *)dtrace_loadptr(daddr +
4463                                     offsetof(struct dev_info, devi_addr));
4464                                 len = dtrace_strlen(s, size);
4465
4466                                 if (*flags & CPU_DTRACE_FAULT)
4467                                         break;
4468
4469                                 if (len != 0) {
4470                                         if ((end -= (len + 1)) < start)
4471                                                 break;
4472
4473                                         *end = '@';
4474                                 }
4475
4476                                 for (i = 1; i <= len; i++)
4477                                         end[i] = dtrace_load8((uintptr_t)s++);
4478                         }
4479
4480                         /*
4481                          * Now for the node name...
4482                          */
4483                         s = (char *)dtrace_loadptr(daddr +
4484                             offsetof(struct dev_info, devi_node_name));
4485
4486                         daddr = dtrace_loadptr(daddr +
4487                             offsetof(struct dev_info, devi_parent));
4488
4489                         /*
4490                          * If our parent is NULL (that is, if we're the root
4491                          * node), we're going to use the special path
4492                          * "devices".
4493                          */
4494                         if (daddr == 0)
4495                                 s = "devices";
4496
4497                         len = dtrace_strlen(s, size);
4498                         if (*flags & CPU_DTRACE_FAULT)
4499                                 break;
4500
4501                         if ((end -= (len + 1)) < start)
4502                                 break;
4503
4504                         for (i = 1; i <= len; i++)
4505                                 end[i] = dtrace_load8((uintptr_t)s++);
4506                         *end = '/';
4507
4508                         if (depth++ > dtrace_devdepth_max) {
4509                                 *flags |= CPU_DTRACE_ILLOP;
4510                                 break;
4511                         }
4512                 }
4513
4514                 if (end < start)
4515                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4516
4517                 if (daddr == 0) {
4518                         regs[rd] = (uintptr_t)end;
4519                         mstate->dtms_scratch_ptr += size;
4520                 }
4521
4522                 break;
4523         }
4524 #endif
4525
4526         case DIF_SUBR_STRJOIN: {
4527                 char *d = (char *)mstate->dtms_scratch_ptr;
4528                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4529                 uintptr_t s1 = tupregs[0].dttk_value;
4530                 uintptr_t s2 = tupregs[1].dttk_value;
4531                 int i = 0;
4532
4533                 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4534                     !dtrace_strcanload(s2, size, mstate, vstate)) {
4535                         regs[rd] = 0;
4536                         break;
4537                 }
4538
4539                 if (!DTRACE_INSCRATCH(mstate, size)) {
4540                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4541                         regs[rd] = 0;
4542                         break;
4543                 }
4544
4545                 for (;;) {
4546                         if (i >= size) {
4547                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4548                                 regs[rd] = 0;
4549                                 break;
4550                         }
4551
4552                         if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4553                                 i--;
4554                                 break;
4555                         }
4556                 }
4557
4558                 for (;;) {
4559                         if (i >= size) {
4560                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4561                                 regs[rd] = 0;
4562                                 break;
4563                         }
4564
4565                         if ((d[i++] = dtrace_load8(s2++)) == '\0')
4566                                 break;
4567                 }
4568
4569                 if (i < size) {
4570                         mstate->dtms_scratch_ptr += i;
4571                         regs[rd] = (uintptr_t)d;
4572                 }
4573
4574                 break;
4575         }
4576
4577         case DIF_SUBR_LLTOSTR: {
4578                 int64_t i = (int64_t)tupregs[0].dttk_value;
4579                 uint64_t val, digit;
4580                 uint64_t size = 65;     /* enough room for 2^64 in binary */
4581                 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4582                 int base = 10;
4583
4584                 if (nargs > 1) {
4585                         if ((base = tupregs[1].dttk_value) <= 1 ||
4586                             base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4587                                 *flags |= CPU_DTRACE_ILLOP;
4588                                 break;
4589                         }
4590                 }
4591
4592                 val = (base == 10 && i < 0) ? i * -1 : i;
4593
4594                 if (!DTRACE_INSCRATCH(mstate, size)) {
4595                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4596                         regs[rd] = 0;
4597                         break;
4598                 }
4599
4600                 for (*end-- = '\0'; val; val /= base) {
4601                         if ((digit = val % base) <= '9' - '0') {
4602                                 *end-- = '0' + digit;
4603                         } else {
4604                                 *end-- = 'a' + (digit - ('9' - '0') - 1);
4605                         }
4606                 }
4607
4608                 if (i == 0 && base == 16)
4609                         *end-- = '0';
4610
4611                 if (base == 16)
4612                         *end-- = 'x';
4613
4614                 if (i == 0 || base == 8 || base == 16)
4615                         *end-- = '0';
4616
4617                 if (i < 0 && base == 10)
4618                         *end-- = '-';
4619
4620                 regs[rd] = (uintptr_t)end + 1;
4621                 mstate->dtms_scratch_ptr += size;
4622                 break;
4623         }
4624
4625         case DIF_SUBR_HTONS:
4626         case DIF_SUBR_NTOHS:
4627 #if BYTE_ORDER == BIG_ENDIAN
4628                 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4629 #else
4630                 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4631 #endif
4632                 break;
4633
4634
4635         case DIF_SUBR_HTONL:
4636         case DIF_SUBR_NTOHL:
4637 #if BYTE_ORDER == BIG_ENDIAN
4638                 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4639 #else
4640                 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4641 #endif
4642                 break;
4643
4644
4645         case DIF_SUBR_HTONLL:
4646         case DIF_SUBR_NTOHLL:
4647 #if BYTE_ORDER == BIG_ENDIAN
4648                 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4649 #else
4650                 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4651 #endif
4652                 break;
4653
4654
4655         case DIF_SUBR_DIRNAME:
4656         case DIF_SUBR_BASENAME: {
4657                 char *dest = (char *)mstate->dtms_scratch_ptr;
4658                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4659                 uintptr_t src = tupregs[0].dttk_value;
4660                 int i, j, len = dtrace_strlen((char *)src, size);
4661                 int lastbase = -1, firstbase = -1, lastdir = -1;
4662                 int start, end;
4663
4664                 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4665                         regs[rd] = 0;
4666                         break;
4667                 }
4668
4669                 if (!DTRACE_INSCRATCH(mstate, size)) {
4670                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4671                         regs[rd] = 0;
4672                         break;
4673                 }
4674
4675                 /*
4676                  * The basename and dirname for a zero-length string is
4677                  * defined to be "."
4678                  */
4679                 if (len == 0) {
4680                         len = 1;
4681                         src = (uintptr_t)".";
4682                 }
4683
4684                 /*
4685                  * Start from the back of the string, moving back toward the
4686                  * front until we see a character that isn't a slash.  That
4687                  * character is the last character in the basename.
4688                  */
4689                 for (i = len - 1; i >= 0; i--) {
4690                         if (dtrace_load8(src + i) != '/')
4691                                 break;
4692                 }
4693
4694                 if (i >= 0)
4695                         lastbase = i;
4696
4697                 /*
4698                  * Starting from the last character in the basename, move
4699                  * towards the front until we find a slash.  The character
4700                  * that we processed immediately before that is the first
4701                  * character in the basename.
4702                  */
4703                 for (; i >= 0; i--) {
4704                         if (dtrace_load8(src + i) == '/')
4705                                 break;
4706                 }
4707
4708                 if (i >= 0)
4709                         firstbase = i + 1;
4710
4711                 /*
4712                  * Now keep going until we find a non-slash character.  That
4713                  * character is the last character in the dirname.
4714                  */
4715                 for (; i >= 0; i--) {
4716                         if (dtrace_load8(src + i) != '/')
4717                                 break;
4718                 }
4719
4720                 if (i >= 0)
4721                         lastdir = i;
4722
4723                 ASSERT(!(lastbase == -1 && firstbase != -1));
4724                 ASSERT(!(firstbase == -1 && lastdir != -1));
4725
4726                 if (lastbase == -1) {
4727                         /*
4728                          * We didn't find a non-slash character.  We know that
4729                          * the length is non-zero, so the whole string must be
4730                          * slashes.  In either the dirname or the basename
4731                          * case, we return '/'.
4732                          */
4733                         ASSERT(firstbase == -1);
4734                         firstbase = lastbase = lastdir = 0;
4735                 }
4736
4737                 if (firstbase == -1) {
4738                         /*
4739                          * The entire string consists only of a basename
4740                          * component.  If we're looking for dirname, we need
4741                          * to change our string to be just "."; if we're
4742                          * looking for a basename, we'll just set the first
4743                          * character of the basename to be 0.
4744                          */
4745                         if (subr == DIF_SUBR_DIRNAME) {
4746                                 ASSERT(lastdir == -1);
4747                                 src = (uintptr_t)".";
4748                                 lastdir = 0;
4749                         } else {
4750                                 firstbase = 0;
4751                         }
4752                 }
4753
4754                 if (subr == DIF_SUBR_DIRNAME) {
4755                         if (lastdir == -1) {
4756                                 /*
4757                                  * We know that we have a slash in the name --
4758                                  * or lastdir would be set to 0, above.  And
4759                                  * because lastdir is -1, we know that this
4760                                  * slash must be the first character.  (That
4761                                  * is, the full string must be of the form
4762                                  * "/basename".)  In this case, the last
4763                                  * character of the directory name is 0.
4764                                  */
4765                                 lastdir = 0;
4766                         }
4767
4768                         start = 0;
4769                         end = lastdir;
4770                 } else {
4771                         ASSERT(subr == DIF_SUBR_BASENAME);
4772                         ASSERT(firstbase != -1 && lastbase != -1);
4773                         start = firstbase;
4774                         end = lastbase;
4775                 }
4776
4777                 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4778                         dest[j] = dtrace_load8(src + i);
4779
4780                 dest[j] = '\0';
4781                 regs[rd] = (uintptr_t)dest;
4782                 mstate->dtms_scratch_ptr += size;
4783                 break;
4784         }
4785
4786         case DIF_SUBR_GETF: {
4787                 uintptr_t fd = tupregs[0].dttk_value;
4788                 struct filedesc *fdp;
4789                 file_t *fp;
4790
4791                 if (!dtrace_priv_proc(state)) {
4792                         regs[rd] = 0;
4793                         break;
4794                 }
4795                 fdp = curproc->p_fd;
4796                 FILEDESC_SLOCK(fdp);
4797                 fp = fget_locked(fdp, fd);
4798                 mstate->dtms_getf = fp;
4799                 regs[rd] = (uintptr_t)fp;
4800                 FILEDESC_SUNLOCK(fdp);
4801                 break;
4802         }
4803
4804         case DIF_SUBR_CLEANPATH: {
4805                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4806                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4807                 uintptr_t src = tupregs[0].dttk_value;
4808                 int i = 0, j = 0;
4809 #if defined(sun)
4810                 zone_t *z;
4811 #endif
4812
4813                 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4814                         regs[rd] = 0;
4815                         break;
4816                 }
4817
4818                 if (!DTRACE_INSCRATCH(mstate, size)) {
4819                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4820                         regs[rd] = 0;
4821                         break;
4822                 }
4823
4824                 /*
4825                  * Move forward, loading each character.
4826                  */
4827                 do {
4828                         c = dtrace_load8(src + i++);
4829 next:
4830                         if (j + 5 >= size)      /* 5 = strlen("/..c\0") */
4831                                 break;
4832
4833                         if (c != '/') {
4834                                 dest[j++] = c;
4835                                 continue;
4836                         }
4837
4838                         c = dtrace_load8(src + i++);
4839
4840                         if (c == '/') {
4841                                 /*
4842                                  * We have two slashes -- we can just advance
4843                                  * to the next character.
4844                                  */
4845                                 goto next;
4846                         }
4847
4848                         if (c != '.') {
4849                                 /*
4850                                  * This is not "." and it's not ".." -- we can
4851                                  * just store the "/" and this character and
4852                                  * drive on.
4853                                  */
4854                                 dest[j++] = '/';
4855                                 dest[j++] = c;
4856                                 continue;
4857                         }
4858
4859                         c = dtrace_load8(src + i++);
4860
4861                         if (c == '/') {
4862                                 /*
4863                                  * This is a "/./" component.  We're not going
4864                                  * to store anything in the destination buffer;
4865                                  * we're just going to go to the next component.
4866                                  */
4867                                 goto next;
4868                         }
4869
4870                         if (c != '.') {
4871                                 /*
4872                                  * This is not ".." -- we can just store the
4873                                  * "/." and this character and continue
4874                                  * processing.
4875                                  */
4876                                 dest[j++] = '/';
4877                                 dest[j++] = '.';
4878                                 dest[j++] = c;
4879                                 continue;
4880                         }
4881
4882                         c = dtrace_load8(src + i++);
4883
4884                         if (c != '/' && c != '\0') {
4885                                 /*
4886                                  * This is not ".." -- it's "..[mumble]".
4887                                  * We'll store the "/.." and this character
4888                                  * and continue processing.
4889                                  */
4890                                 dest[j++] = '/';
4891                                 dest[j++] = '.';
4892                                 dest[j++] = '.';
4893                                 dest[j++] = c;
4894                                 continue;
4895                         }
4896
4897                         /*
4898                          * This is "/../" or "/..\0".  We need to back up
4899                          * our destination pointer until we find a "/".
4900                          */
4901                         i--;
4902                         while (j != 0 && dest[--j] != '/')
4903                                 continue;
4904
4905                         if (c == '\0')
4906                                 dest[++j] = '/';
4907                 } while (c != '\0');
4908
4909                 dest[j] = '\0';
4910
4911 #if defined(sun)
4912                 if (mstate->dtms_getf != NULL &&
4913                     !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
4914                     (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
4915                         /*
4916                          * If we've done a getf() as a part of this ECB and we
4917                          * don't have kernel access (and we're not in the global
4918                          * zone), check if the path we cleaned up begins with
4919                          * the zone's root path, and trim it off if so.  Note
4920                          * that this is an output cleanliness issue, not a
4921                          * security issue: knowing one's zone root path does
4922                          * not enable privilege escalation.
4923                          */
4924                         if (strstr(dest, z->zone_rootpath) == dest)
4925                                 dest += strlen(z->zone_rootpath) - 1;
4926                 }
4927 #endif
4928
4929                 regs[rd] = (uintptr_t)dest;
4930                 mstate->dtms_scratch_ptr += size;
4931                 break;
4932         }
4933
4934         case DIF_SUBR_INET_NTOA:
4935         case DIF_SUBR_INET_NTOA6:
4936         case DIF_SUBR_INET_NTOP: {
4937                 size_t size;
4938                 int af, argi, i;
4939                 char *base, *end;
4940
4941                 if (subr == DIF_SUBR_INET_NTOP) {
4942                         af = (int)tupregs[0].dttk_value;
4943                         argi = 1;
4944                 } else {
4945                         af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4946                         argi = 0;
4947                 }
4948
4949                 if (af == AF_INET) {
4950                         ipaddr_t ip4;
4951                         uint8_t *ptr8, val;
4952
4953                         /*
4954                          * Safely load the IPv4 address.
4955                          */
4956                         ip4 = dtrace_load32(tupregs[argi].dttk_value);
4957
4958                         /*
4959                          * Check an IPv4 string will fit in scratch.
4960                          */
4961                         size = INET_ADDRSTRLEN;
4962                         if (!DTRACE_INSCRATCH(mstate, size)) {
4963                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4964                                 regs[rd] = 0;
4965                                 break;
4966                         }
4967                         base = (char *)mstate->dtms_scratch_ptr;
4968                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
4969
4970                         /*
4971                          * Stringify as a dotted decimal quad.
4972                          */
4973                         *end-- = '\0';
4974                         ptr8 = (uint8_t *)&ip4;
4975                         for (i = 3; i >= 0; i--) {
4976                                 val = ptr8[i];
4977
4978                                 if (val == 0) {
4979                                         *end-- = '0';
4980                                 } else {
4981                                         for (; val; val /= 10) {
4982                                                 *end-- = '0' + (val % 10);
4983                                         }
4984                                 }
4985
4986                                 if (i > 0)
4987                                         *end-- = '.';
4988                         }
4989                         ASSERT(end + 1 >= base);
4990
4991                 } else if (af == AF_INET6) {
4992                         struct in6_addr ip6;
4993                         int firstzero, tryzero, numzero, v6end;
4994                         uint16_t val;
4995                         const char digits[] = "0123456789abcdef";
4996
4997                         /*
4998                          * Stringify using RFC 1884 convention 2 - 16 bit
4999                          * hexadecimal values with a zero-run compression.
5000                          * Lower case hexadecimal digits are used.
5001                          *      eg, fe80::214:4fff:fe0b:76c8.
5002                          * The IPv4 embedded form is returned for inet_ntop,
5003                          * just the IPv4 string is returned for inet_ntoa6.
5004                          */
5005
5006                         /*
5007                          * Safely load the IPv6 address.
5008                          */
5009                         dtrace_bcopy(
5010                             (void *)(uintptr_t)tupregs[argi].dttk_value,
5011                             (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5012
5013                         /*
5014                          * Check an IPv6 string will fit in scratch.
5015                          */
5016                         size = INET6_ADDRSTRLEN;
5017                         if (!DTRACE_INSCRATCH(mstate, size)) {
5018                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5019                                 regs[rd] = 0;
5020                                 break;
5021                         }
5022                         base = (char *)mstate->dtms_scratch_ptr;
5023                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
5024                         *end-- = '\0';
5025
5026                         /*
5027                          * Find the longest run of 16 bit zero values
5028                          * for the single allowed zero compression - "::".
5029                          */
5030                         firstzero = -1;
5031                         tryzero = -1;
5032                         numzero = 1;
5033                         for (i = 0; i < sizeof (struct in6_addr); i++) {
5034 #if defined(sun)
5035                                 if (ip6._S6_un._S6_u8[i] == 0 &&
5036 #else
5037                                 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5038 #endif
5039                                     tryzero == -1 && i % 2 == 0) {
5040                                         tryzero = i;
5041                                         continue;
5042                                 }
5043
5044                                 if (tryzero != -1 &&
5045 #if defined(sun)
5046                                     (ip6._S6_un._S6_u8[i] != 0 ||
5047 #else
5048                                     (ip6.__u6_addr.__u6_addr8[i] != 0 ||
5049 #endif
5050                                     i == sizeof (struct in6_addr) - 1)) {
5051
5052                                         if (i - tryzero <= numzero) {
5053                                                 tryzero = -1;
5054                                                 continue;
5055                                         }
5056
5057                                         firstzero = tryzero;
5058                                         numzero = i - i % 2 - tryzero;
5059                                         tryzero = -1;
5060
5061 #if defined(sun)
5062                                         if (ip6._S6_un._S6_u8[i] == 0 &&
5063 #else
5064                                         if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
5065 #endif
5066                                             i == sizeof (struct in6_addr) - 1)
5067                                                 numzero += 2;
5068                                 }
5069                         }
5070                         ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5071
5072                         /*
5073                          * Check for an IPv4 embedded address.
5074                          */
5075                         v6end = sizeof (struct in6_addr) - 2;
5076                         if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5077                             IN6_IS_ADDR_V4COMPAT(&ip6)) {
5078                                 for (i = sizeof (struct in6_addr) - 1;
5079                                     i >= DTRACE_V4MAPPED_OFFSET; i--) {
5080                                         ASSERT(end >= base);
5081
5082 #if defined(sun)
5083                                         val = ip6._S6_un._S6_u8[i];
5084 #else
5085                                         val = ip6.__u6_addr.__u6_addr8[i];
5086 #endif
5087
5088                                         if (val == 0) {
5089                                                 *end-- = '0';
5090                                         } else {
5091                                                 for (; val; val /= 10) {
5092                                                         *end-- = '0' + val % 10;
5093                                                 }
5094                                         }
5095
5096                                         if (i > DTRACE_V4MAPPED_OFFSET)
5097                                                 *end-- = '.';
5098                                 }
5099
5100                                 if (subr == DIF_SUBR_INET_NTOA6)
5101                                         goto inetout;
5102
5103                                 /*
5104                                  * Set v6end to skip the IPv4 address that
5105                                  * we have already stringified.
5106                                  */
5107                                 v6end = 10;
5108                         }
5109
5110                         /*
5111                          * Build the IPv6 string by working through the
5112                          * address in reverse.
5113                          */
5114                         for (i = v6end; i >= 0; i -= 2) {
5115                                 ASSERT(end >= base);
5116
5117                                 if (i == firstzero + numzero - 2) {
5118                                         *end-- = ':';
5119                                         *end-- = ':';
5120                                         i -= numzero - 2;
5121                                         continue;
5122                                 }
5123
5124                                 if (i < 14 && i != firstzero - 2)
5125                                         *end-- = ':';
5126
5127 #if defined(sun)
5128                                 val = (ip6._S6_un._S6_u8[i] << 8) +
5129                                     ip6._S6_un._S6_u8[i + 1];
5130 #else
5131                                 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
5132                                     ip6.__u6_addr.__u6_addr8[i + 1];
5133 #endif
5134
5135                                 if (val == 0) {
5136                                         *end-- = '0';
5137                                 } else {
5138                                         for (; val; val /= 16) {
5139                                                 *end-- = digits[val % 16];
5140                                         }
5141                                 }
5142                         }
5143                         ASSERT(end + 1 >= base);
5144
5145                 } else {
5146                         /*
5147                          * The user didn't use AH_INET or AH_INET6.
5148                          */
5149                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5150                         regs[rd] = 0;
5151                         break;
5152                 }
5153
5154 inetout:        regs[rd] = (uintptr_t)end + 1;
5155                 mstate->dtms_scratch_ptr += size;
5156                 break;
5157         }
5158
5159         case DIF_SUBR_MEMREF: {
5160                 uintptr_t size = 2 * sizeof(uintptr_t);
5161                 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5162                 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
5163
5164                 /* address and length */
5165                 memref[0] = tupregs[0].dttk_value;
5166                 memref[1] = tupregs[1].dttk_value;
5167
5168                 regs[rd] = (uintptr_t) memref;
5169                 mstate->dtms_scratch_ptr += scratch_size;
5170                 break;
5171         }
5172
5173 #if !defined(sun)
5174         case DIF_SUBR_MEMSTR: {
5175                 char *str = (char *)mstate->dtms_scratch_ptr;
5176                 uintptr_t mem = tupregs[0].dttk_value;
5177                 char c = tupregs[1].dttk_value;
5178                 size_t size = tupregs[2].dttk_value;
5179                 uint8_t n;
5180                 int i;
5181
5182                 regs[rd] = 0;
5183
5184                 if (size == 0)
5185                         break;
5186
5187                 if (!dtrace_canload(mem, size - 1, mstate, vstate))
5188                         break;
5189
5190                 if (!DTRACE_INSCRATCH(mstate, size)) {
5191                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5192                         break;
5193                 }
5194
5195                 if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
5196                         *flags |= CPU_DTRACE_ILLOP;
5197                         break;
5198                 }
5199
5200                 for (i = 0; i < size - 1; i++) {
5201                         n = dtrace_load8(mem++);
5202                         str[i] = (n == 0) ? c : n;
5203                 }
5204                 str[size - 1] = 0;
5205
5206                 regs[rd] = (uintptr_t)str;
5207                 mstate->dtms_scratch_ptr += size;
5208                 break;
5209         }
5210 #endif
5211
5212         case DIF_SUBR_TYPEREF: {
5213                 uintptr_t size = 4 * sizeof(uintptr_t);
5214                 uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
5215                 size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
5216
5217                 /* address, num_elements, type_str, type_len */
5218                 typeref[0] = tupregs[0].dttk_value;
5219                 typeref[1] = tupregs[1].dttk_value;
5220                 typeref[2] = tupregs[2].dttk_value;
5221                 typeref[3] = tupregs[3].dttk_value;
5222
5223                 regs[rd] = (uintptr_t) typeref;
5224                 mstate->dtms_scratch_ptr += scratch_size;
5225                 break;
5226         }
5227         }
5228 }
5229
5230 /*
5231  * Emulate the execution of DTrace IR instructions specified by the given
5232  * DIF object.  This function is deliberately void of assertions as all of
5233  * the necessary checks are handled by a call to dtrace_difo_validate().
5234  */
5235 static uint64_t
5236 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5237     dtrace_vstate_t *vstate, dtrace_state_t *state)
5238 {
5239         const dif_instr_t *text = difo->dtdo_buf;
5240         const uint_t textlen = difo->dtdo_len;
5241         const char *strtab = difo->dtdo_strtab;
5242         const uint64_t *inttab = difo->dtdo_inttab;
5243
5244         uint64_t rval = 0;
5245         dtrace_statvar_t *svar;
5246         dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5247         dtrace_difv_t *v;
5248         volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5249         volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5250
5251         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5252         uint64_t regs[DIF_DIR_NREGS];
5253         uint64_t *tmp;
5254
5255         uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5256         int64_t cc_r;
5257         uint_t pc = 0, id, opc = 0;
5258         uint8_t ttop = 0;
5259         dif_instr_t instr;
5260         uint_t r1, r2, rd;
5261
5262         /*
5263          * We stash the current DIF object into the machine state: we need it
5264          * for subsequent access checking.
5265          */
5266         mstate->dtms_difo = difo;
5267
5268         regs[DIF_REG_R0] = 0;           /* %r0 is fixed at zero */
5269
5270         while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5271                 opc = pc;
5272
5273                 instr = text[pc++];
5274                 r1 = DIF_INSTR_R1(instr);
5275                 r2 = DIF_INSTR_R2(instr);
5276                 rd = DIF_INSTR_RD(instr);
5277
5278                 switch (DIF_INSTR_OP(instr)) {
5279                 case DIF_OP_OR:
5280                         regs[rd] = regs[r1] | regs[r2];
5281                         break;
5282                 case DIF_OP_XOR:
5283                         regs[rd] = regs[r1] ^ regs[r2];
5284                         break;
5285                 case DIF_OP_AND:
5286                         regs[rd] = regs[r1] & regs[r2];
5287                         break;
5288                 case DIF_OP_SLL:
5289                         regs[rd] = regs[r1] << regs[r2];
5290                         break;
5291                 case DIF_OP_SRL:
5292                         regs[rd] = regs[r1] >> regs[r2];
5293                         break;
5294                 case DIF_OP_SUB:
5295                         regs[rd] = regs[r1] - regs[r2];
5296                         break;
5297                 case DIF_OP_ADD:
5298                         regs[rd] = regs[r1] + regs[r2];
5299                         break;
5300                 case DIF_OP_MUL:
5301                         regs[rd] = regs[r1] * regs[r2];
5302                         break;
5303                 case DIF_OP_SDIV:
5304                         if (regs[r2] == 0) {
5305                                 regs[rd] = 0;
5306                                 *flags |= CPU_DTRACE_DIVZERO;
5307                         } else {
5308                                 regs[rd] = (int64_t)regs[r1] /
5309                                     (int64_t)regs[r2];
5310                         }
5311                         break;
5312
5313                 case DIF_OP_UDIV:
5314                         if (regs[r2] == 0) {
5315                                 regs[rd] = 0;
5316                                 *flags |= CPU_DTRACE_DIVZERO;
5317                         } else {
5318                                 regs[rd] = regs[r1] / regs[r2];
5319                         }
5320                         break;
5321
5322                 case DIF_OP_SREM:
5323                         if (regs[r2] == 0) {
5324                                 regs[rd] = 0;
5325                                 *flags |= CPU_DTRACE_DIVZERO;
5326                         } else {
5327                                 regs[rd] = (int64_t)regs[r1] %
5328                                     (int64_t)regs[r2];
5329                         }
5330                         break;
5331
5332                 case DIF_OP_UREM:
5333                         if (regs[r2] == 0) {
5334                                 regs[rd] = 0;
5335                                 *flags |= CPU_DTRACE_DIVZERO;
5336                         } else {
5337                                 regs[rd] = regs[r1] % regs[r2];
5338                         }
5339                         break;
5340
5341                 case DIF_OP_NOT:
5342                         regs[rd] = ~regs[r1];
5343                         break;
5344                 case DIF_OP_MOV:
5345                         regs[rd] = regs[r1];
5346                         break;
5347                 case DIF_OP_CMP:
5348                         cc_r = regs[r1] - regs[r2];
5349                         cc_n = cc_r < 0;
5350                         cc_z = cc_r == 0;
5351                         cc_v = 0;
5352                         cc_c = regs[r1] < regs[r2];
5353                         break;
5354                 case DIF_OP_TST:
5355                         cc_n = cc_v = cc_c = 0;
5356                         cc_z = regs[r1] == 0;
5357                         break;
5358                 case DIF_OP_BA:
5359                         pc = DIF_INSTR_LABEL(instr);
5360                         break;
5361                 case DIF_OP_BE:
5362                         if (cc_z)
5363                                 pc = DIF_INSTR_LABEL(instr);
5364                         break;
5365                 case DIF_OP_BNE:
5366                         if (cc_z == 0)
5367                                 pc = DIF_INSTR_LABEL(instr);
5368                         break;
5369                 case DIF_OP_BG:
5370                         if ((cc_z | (cc_n ^ cc_v)) == 0)
5371                                 pc = DIF_INSTR_LABEL(instr);
5372                         break;
5373                 case DIF_OP_BGU:
5374                         if ((cc_c | cc_z) == 0)
5375                                 pc = DIF_INSTR_LABEL(instr);
5376                         break;
5377                 case DIF_OP_BGE:
5378                         if ((cc_n ^ cc_v) == 0)
5379                                 pc = DIF_INSTR_LABEL(instr);
5380                         break;
5381                 case DIF_OP_BGEU:
5382                         if (cc_c == 0)
5383                                 pc = DIF_INSTR_LABEL(instr);
5384                         break;
5385                 case DIF_OP_BL:
5386                         if (cc_n ^ cc_v)
5387                                 pc = DIF_INSTR_LABEL(instr);
5388                         break;
5389                 case DIF_OP_BLU:
5390                         if (cc_c)
5391                                 pc = DIF_INSTR_LABEL(instr);
5392                         break;
5393                 case DIF_OP_BLE:
5394                         if (cc_z | (cc_n ^ cc_v))
5395                                 pc = DIF_INSTR_LABEL(instr);
5396                         break;
5397                 case DIF_OP_BLEU:
5398                         if (cc_c | cc_z)
5399                                 pc = DIF_INSTR_LABEL(instr);
5400                         break;
5401                 case DIF_OP_RLDSB:
5402                         if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5403                                 break;
5404                         /*FALLTHROUGH*/
5405                 case DIF_OP_LDSB:
5406                         regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5407                         break;
5408                 case DIF_OP_RLDSH:
5409                         if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5410                                 break;
5411                         /*FALLTHROUGH*/
5412                 case DIF_OP_LDSH:
5413                         regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5414                         break;
5415                 case DIF_OP_RLDSW:
5416                         if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5417                                 break;
5418                         /*FALLTHROUGH*/
5419                 case DIF_OP_LDSW:
5420                         regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5421                         break;
5422                 case DIF_OP_RLDUB:
5423                         if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5424                                 break;
5425                         /*FALLTHROUGH*/
5426                 case DIF_OP_LDUB:
5427                         regs[rd] = dtrace_load8(regs[r1]);
5428                         break;
5429                 case DIF_OP_RLDUH:
5430                         if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5431                                 break;
5432                         /*FALLTHROUGH*/
5433                 case DIF_OP_LDUH:
5434                         regs[rd] = dtrace_load16(regs[r1]);
5435                         break;
5436                 case DIF_OP_RLDUW:
5437                         if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5438                                 break;
5439                         /*FALLTHROUGH*/
5440                 case DIF_OP_LDUW:
5441                         regs[rd] = dtrace_load32(regs[r1]);
5442                         break;
5443                 case DIF_OP_RLDX:
5444                         if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5445                                 break;
5446                         /*FALLTHROUGH*/
5447                 case DIF_OP_LDX:
5448                         regs[rd] = dtrace_load64(regs[r1]);
5449                         break;
5450                 case DIF_OP_ULDSB:
5451                         regs[rd] = (int8_t)
5452                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5453                         break;
5454                 case DIF_OP_ULDSH:
5455                         regs[rd] = (int16_t)
5456                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5457                         break;
5458                 case DIF_OP_ULDSW:
5459                         regs[rd] = (int32_t)
5460                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5461                         break;
5462                 case DIF_OP_ULDUB:
5463                         regs[rd] =
5464                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5465                         break;
5466                 case DIF_OP_ULDUH:
5467                         regs[rd] =
5468                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5469                         break;
5470                 case DIF_OP_ULDUW:
5471                         regs[rd] =
5472                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5473                         break;
5474                 case DIF_OP_ULDX:
5475                         regs[rd] =
5476                             dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5477                         break;
5478                 case DIF_OP_RET:
5479                         rval = regs[rd];
5480                         pc = textlen;
5481                         break;
5482                 case DIF_OP_NOP:
5483                         break;
5484                 case DIF_OP_SETX:
5485                         regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5486                         break;
5487                 case DIF_OP_SETS:
5488                         regs[rd] = (uint64_t)(uintptr_t)
5489                             (strtab + DIF_INSTR_STRING(instr));
5490                         break;
5491                 case DIF_OP_SCMP: {
5492                         size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5493                         uintptr_t s1 = regs[r1];
5494                         uintptr_t s2 = regs[r2];
5495
5496                         if (s1 != 0 &&
5497                             !dtrace_strcanload(s1, sz, mstate, vstate))
5498                                 break;
5499                         if (s2 != 0 &&
5500                             !dtrace_strcanload(s2, sz, mstate, vstate))
5501                                 break;
5502
5503                         cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5504
5505                         cc_n = cc_r < 0;
5506                         cc_z = cc_r == 0;
5507                         cc_v = cc_c = 0;
5508                         break;
5509                 }
5510                 case DIF_OP_LDGA:
5511                         regs[rd] = dtrace_dif_variable(mstate, state,
5512                             r1, regs[r2]);
5513                         break;
5514                 case DIF_OP_LDGS:
5515                         id = DIF_INSTR_VAR(instr);
5516
5517                         if (id >= DIF_VAR_OTHER_UBASE) {
5518                                 uintptr_t a;
5519
5520                                 id -= DIF_VAR_OTHER_UBASE;
5521                                 svar = vstate->dtvs_globals[id];
5522                                 ASSERT(svar != NULL);
5523                                 v = &svar->dtsv_var;
5524
5525                                 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5526                                         regs[rd] = svar->dtsv_data;
5527                                         break;
5528                                 }
5529
5530                                 a = (uintptr_t)svar->dtsv_data;
5531
5532                                 if (*(uint8_t *)a == UINT8_MAX) {
5533                                         /*
5534                                          * If the 0th byte is set to UINT8_MAX
5535                                          * then this is to be treated as a
5536                                          * reference to a NULL variable.
5537                                          */
5538                                         regs[rd] = 0;
5539                                 } else {
5540                                         regs[rd] = a + sizeof (uint64_t);
5541                                 }
5542
5543                                 break;
5544                         }
5545
5546                         regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5547                         break;
5548
5549                 case DIF_OP_STGS:
5550                         id = DIF_INSTR_VAR(instr);
5551
5552                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5553                         id -= DIF_VAR_OTHER_UBASE;
5554
5555                         svar = vstate->dtvs_globals[id];
5556                         ASSERT(svar != NULL);
5557                         v = &svar->dtsv_var;
5558
5559                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5560                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5561
5562                                 ASSERT(a != 0);
5563                                 ASSERT(svar->dtsv_size != 0);
5564
5565                                 if (regs[rd] == 0) {
5566                                         *(uint8_t *)a = UINT8_MAX;
5567                                         break;
5568                                 } else {
5569                                         *(uint8_t *)a = 0;
5570                                         a += sizeof (uint64_t);
5571                                 }
5572                                 if (!dtrace_vcanload(
5573                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5574                                     mstate, vstate))
5575                                         break;
5576
5577                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5578                                     (void *)a, &v->dtdv_type);
5579                                 break;
5580                         }
5581
5582                         svar->dtsv_data = regs[rd];
5583                         break;
5584
5585                 case DIF_OP_LDTA:
5586                         /*
5587                          * There are no DTrace built-in thread-local arrays at
5588                          * present.  This opcode is saved for future work.
5589                          */
5590                         *flags |= CPU_DTRACE_ILLOP;
5591                         regs[rd] = 0;
5592                         break;
5593
5594                 case DIF_OP_LDLS:
5595                         id = DIF_INSTR_VAR(instr);
5596
5597                         if (id < DIF_VAR_OTHER_UBASE) {
5598                                 /*
5599                                  * For now, this has no meaning.
5600                                  */
5601                                 regs[rd] = 0;
5602                                 break;
5603                         }
5604
5605                         id -= DIF_VAR_OTHER_UBASE;
5606
5607                         ASSERT(id < vstate->dtvs_nlocals);
5608                         ASSERT(vstate->dtvs_locals != NULL);
5609
5610                         svar = vstate->dtvs_locals[id];
5611                         ASSERT(svar != NULL);
5612                         v = &svar->dtsv_var;
5613
5614                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5615                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5616                                 size_t sz = v->dtdv_type.dtdt_size;
5617
5618                                 sz += sizeof (uint64_t);
5619                                 ASSERT(svar->dtsv_size == NCPU * sz);
5620                                 a += curcpu * sz;
5621
5622                                 if (*(uint8_t *)a == UINT8_MAX) {
5623                                         /*
5624                                          * If the 0th byte is set to UINT8_MAX
5625                                          * then this is to be treated as a
5626                                          * reference to a NULL variable.
5627                                          */
5628                                         regs[rd] = 0;
5629                                 } else {
5630                                         regs[rd] = a + sizeof (uint64_t);
5631                                 }
5632
5633                                 break;
5634                         }
5635
5636                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5637                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5638                         regs[rd] = tmp[curcpu];
5639                         break;
5640
5641                 case DIF_OP_STLS:
5642                         id = DIF_INSTR_VAR(instr);
5643
5644                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5645                         id -= DIF_VAR_OTHER_UBASE;
5646                         ASSERT(id < vstate->dtvs_nlocals);
5647
5648                         ASSERT(vstate->dtvs_locals != NULL);
5649                         svar = vstate->dtvs_locals[id];
5650                         ASSERT(svar != NULL);
5651                         v = &svar->dtsv_var;
5652
5653                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5654                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5655                                 size_t sz = v->dtdv_type.dtdt_size;
5656
5657                                 sz += sizeof (uint64_t);
5658                                 ASSERT(svar->dtsv_size == NCPU * sz);
5659                                 a += curcpu * sz;
5660
5661                                 if (regs[rd] == 0) {
5662                                         *(uint8_t *)a = UINT8_MAX;
5663                                         break;
5664                                 } else {
5665                                         *(uint8_t *)a = 0;
5666                                         a += sizeof (uint64_t);
5667                                 }
5668
5669                                 if (!dtrace_vcanload(
5670                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5671                                     mstate, vstate))
5672                                         break;
5673
5674                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5675                                     (void *)a, &v->dtdv_type);
5676                                 break;
5677                         }
5678
5679                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5680                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5681                         tmp[curcpu] = regs[rd];
5682                         break;
5683
5684                 case DIF_OP_LDTS: {
5685                         dtrace_dynvar_t *dvar;
5686                         dtrace_key_t *key;
5687
5688                         id = DIF_INSTR_VAR(instr);
5689                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5690                         id -= DIF_VAR_OTHER_UBASE;
5691                         v = &vstate->dtvs_tlocals[id];
5692
5693                         key = &tupregs[DIF_DTR_NREGS];
5694                         key[0].dttk_value = (uint64_t)id;
5695                         key[0].dttk_size = 0;
5696                         DTRACE_TLS_THRKEY(key[1].dttk_value);
5697                         key[1].dttk_size = 0;
5698
5699                         dvar = dtrace_dynvar(dstate, 2, key,
5700                             sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5701                             mstate, vstate);
5702
5703                         if (dvar == NULL) {
5704                                 regs[rd] = 0;
5705                                 break;
5706                         }
5707
5708                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5709                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5710                         } else {
5711                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5712                         }
5713
5714                         break;
5715                 }
5716
5717                 case DIF_OP_STTS: {
5718                         dtrace_dynvar_t *dvar;
5719                         dtrace_key_t *key;
5720
5721                         id = DIF_INSTR_VAR(instr);
5722                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5723                         id -= DIF_VAR_OTHER_UBASE;
5724
5725                         key = &tupregs[DIF_DTR_NREGS];
5726                         key[0].dttk_value = (uint64_t)id;
5727                         key[0].dttk_size = 0;
5728                         DTRACE_TLS_THRKEY(key[1].dttk_value);
5729                         key[1].dttk_size = 0;
5730                         v = &vstate->dtvs_tlocals[id];
5731
5732                         dvar = dtrace_dynvar(dstate, 2, key,
5733                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5734                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
5735                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
5736                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5737
5738                         /*
5739                          * Given that we're storing to thread-local data,
5740                          * we need to flush our predicate cache.
5741                          */
5742                         curthread->t_predcache = 0;
5743
5744                         if (dvar == NULL)
5745                                 break;
5746
5747                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5748                                 if (!dtrace_vcanload(
5749                                     (void *)(uintptr_t)regs[rd],
5750                                     &v->dtdv_type, mstate, vstate))
5751                                         break;
5752
5753                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5754                                     dvar->dtdv_data, &v->dtdv_type);
5755                         } else {
5756                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5757                         }
5758
5759                         break;
5760                 }
5761
5762                 case DIF_OP_SRA:
5763                         regs[rd] = (int64_t)regs[r1] >> regs[r2];
5764                         break;
5765
5766                 case DIF_OP_CALL:
5767                         dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5768                             regs, tupregs, ttop, mstate, state);
5769                         break;
5770
5771                 case DIF_OP_PUSHTR:
5772                         if (ttop == DIF_DTR_NREGS) {
5773                                 *flags |= CPU_DTRACE_TUPOFLOW;
5774                                 break;
5775                         }
5776
5777                         if (r1 == DIF_TYPE_STRING) {
5778                                 /*
5779                                  * If this is a string type and the size is 0,
5780                                  * we'll use the system-wide default string
5781                                  * size.  Note that we are _not_ looking at
5782                                  * the value of the DTRACEOPT_STRSIZE option;
5783                                  * had this been set, we would expect to have
5784                                  * a non-zero size value in the "pushtr".
5785                                  */
5786                                 tupregs[ttop].dttk_size =
5787                                     dtrace_strlen((char *)(uintptr_t)regs[rd],
5788                                     regs[r2] ? regs[r2] :
5789                                     dtrace_strsize_default) + 1;
5790                         } else {
5791                                 tupregs[ttop].dttk_size = regs[r2];
5792                         }
5793
5794                         tupregs[ttop++].dttk_value = regs[rd];
5795                         break;
5796
5797                 case DIF_OP_PUSHTV:
5798                         if (ttop == DIF_DTR_NREGS) {
5799                                 *flags |= CPU_DTRACE_TUPOFLOW;
5800                                 break;
5801                         }
5802
5803                         tupregs[ttop].dttk_value = regs[rd];
5804                         tupregs[ttop++].dttk_size = 0;
5805                         break;
5806
5807                 case DIF_OP_POPTS:
5808                         if (ttop != 0)
5809                                 ttop--;
5810                         break;
5811
5812                 case DIF_OP_FLUSHTS:
5813                         ttop = 0;
5814                         break;
5815
5816                 case DIF_OP_LDGAA:
5817                 case DIF_OP_LDTAA: {
5818                         dtrace_dynvar_t *dvar;
5819                         dtrace_key_t *key = tupregs;
5820                         uint_t nkeys = ttop;
5821
5822                         id = DIF_INSTR_VAR(instr);
5823                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5824                         id -= DIF_VAR_OTHER_UBASE;
5825
5826                         key[nkeys].dttk_value = (uint64_t)id;
5827                         key[nkeys++].dttk_size = 0;
5828
5829                         if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5830                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5831                                 key[nkeys++].dttk_size = 0;
5832                                 v = &vstate->dtvs_tlocals[id];
5833                         } else {
5834                                 v = &vstate->dtvs_globals[id]->dtsv_var;
5835                         }
5836
5837                         dvar = dtrace_dynvar(dstate, nkeys, key,
5838                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5839                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
5840                             DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5841
5842                         if (dvar == NULL) {
5843                                 regs[rd] = 0;
5844                                 break;
5845                         }
5846
5847                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5848                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5849                         } else {
5850                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5851                         }
5852
5853                         break;
5854                 }
5855
5856                 case DIF_OP_STGAA:
5857                 case DIF_OP_STTAA: {
5858                         dtrace_dynvar_t *dvar;
5859                         dtrace_key_t *key = tupregs;
5860                         uint_t nkeys = ttop;
5861
5862                         id = DIF_INSTR_VAR(instr);
5863                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5864                         id -= DIF_VAR_OTHER_UBASE;
5865
5866                         key[nkeys].dttk_value = (uint64_t)id;
5867                         key[nkeys++].dttk_size = 0;
5868
5869                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5870                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5871                                 key[nkeys++].dttk_size = 0;
5872                                 v = &vstate->dtvs_tlocals[id];
5873                         } else {
5874                                 v = &vstate->dtvs_globals[id]->dtsv_var;
5875                         }
5876
5877                         dvar = dtrace_dynvar(dstate, nkeys, key,
5878                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5879                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
5880                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
5881                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5882
5883                         if (dvar == NULL)
5884                                 break;
5885
5886                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5887                                 if (!dtrace_vcanload(
5888                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5889                                     mstate, vstate))
5890                                         break;
5891
5892                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5893                                     dvar->dtdv_data, &v->dtdv_type);
5894                         } else {
5895                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5896                         }
5897
5898                         break;
5899                 }
5900
5901                 case DIF_OP_ALLOCS: {
5902                         uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5903                         size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5904
5905                         /*
5906                          * Rounding up the user allocation size could have
5907                          * overflowed large, bogus allocations (like -1ULL) to
5908                          * 0.
5909                          */
5910                         if (size < regs[r1] ||
5911                             !DTRACE_INSCRATCH(mstate, size)) {
5912                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5913                                 regs[rd] = 0;
5914                                 break;
5915                         }
5916
5917                         dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5918                         mstate->dtms_scratch_ptr += size;
5919                         regs[rd] = ptr;
5920                         break;
5921                 }
5922
5923                 case DIF_OP_COPYS:
5924                         if (!dtrace_canstore(regs[rd], regs[r2],
5925                             mstate, vstate)) {
5926                                 *flags |= CPU_DTRACE_BADADDR;
5927                                 *illval = regs[rd];
5928                                 break;
5929                         }
5930
5931                         if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5932                                 break;
5933
5934                         dtrace_bcopy((void *)(uintptr_t)regs[r1],
5935                             (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5936                         break;
5937
5938                 case DIF_OP_STB:
5939                         if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5940                                 *flags |= CPU_DTRACE_BADADDR;
5941                                 *illval = regs[rd];
5942                                 break;
5943                         }
5944                         *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5945                         break;
5946
5947                 case DIF_OP_STH:
5948                         if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5949                                 *flags |= CPU_DTRACE_BADADDR;
5950                                 *illval = regs[rd];
5951                                 break;
5952                         }
5953                         if (regs[rd] & 1) {
5954                                 *flags |= CPU_DTRACE_BADALIGN;
5955                                 *illval = regs[rd];
5956                                 break;
5957                         }
5958                         *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5959                         break;
5960
5961                 case DIF_OP_STW:
5962                         if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5963                                 *flags |= CPU_DTRACE_BADADDR;
5964                                 *illval = regs[rd];
5965                                 break;
5966                         }
5967                         if (regs[rd] & 3) {
5968                                 *flags |= CPU_DTRACE_BADALIGN;
5969                                 *illval = regs[rd];
5970                                 break;
5971                         }
5972                         *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5973                         break;
5974
5975                 case DIF_OP_STX:
5976                         if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5977                                 *flags |= CPU_DTRACE_BADADDR;
5978                                 *illval = regs[rd];
5979                                 break;
5980                         }
5981                         if (regs[rd] & 7) {
5982                                 *flags |= CPU_DTRACE_BADALIGN;
5983                                 *illval = regs[rd];
5984                                 break;
5985                         }
5986                         *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5987                         break;
5988                 }
5989         }
5990
5991         if (!(*flags & CPU_DTRACE_FAULT))
5992                 return (rval);
5993
5994         mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5995         mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5996
5997         return (0);
5998 }
5999
6000 static void
6001 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6002 {
6003         dtrace_probe_t *probe = ecb->dte_probe;
6004         dtrace_provider_t *prov = probe->dtpr_provider;
6005         char c[DTRACE_FULLNAMELEN + 80], *str;
6006         char *msg = "dtrace: breakpoint action at probe ";
6007         char *ecbmsg = " (ecb ";
6008         uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6009         uintptr_t val = (uintptr_t)ecb;
6010         int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6011
6012         if (dtrace_destructive_disallow)
6013                 return;
6014
6015         /*
6016          * It's impossible to be taking action on the NULL probe.
6017          */
6018         ASSERT(probe != NULL);
6019
6020         /*
6021          * This is a poor man's (destitute man's?) sprintf():  we want to
6022          * print the provider name, module name, function name and name of
6023          * the probe, along with the hex address of the ECB with the breakpoint
6024          * action -- all of which we must place in the character buffer by
6025          * hand.
6026          */
6027         while (*msg != '\0')
6028                 c[i++] = *msg++;
6029
6030         for (str = prov->dtpv_name; *str != '\0'; str++)
6031                 c[i++] = *str;
6032         c[i++] = ':';
6033
6034         for (str = probe->dtpr_mod; *str != '\0'; str++)
6035                 c[i++] = *str;
6036         c[i++] = ':';
6037
6038         for (str = probe->dtpr_func; *str != '\0'; str++)
6039                 c[i++] = *str;
6040         c[i++] = ':';
6041
6042         for (str = probe->dtpr_name; *str != '\0'; str++)
6043                 c[i++] = *str;
6044
6045         while (*ecbmsg != '\0')
6046                 c[i++] = *ecbmsg++;
6047
6048         while (shift >= 0) {
6049                 mask = (uintptr_t)0xf << shift;
6050
6051                 if (val >= ((uintptr_t)1 << shift))
6052                         c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6053                 shift -= 4;
6054         }
6055
6056         c[i++] = ')';
6057         c[i] = '\0';
6058
6059 #if defined(sun)
6060         debug_enter(c);
6061 #else
6062         kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
6063 #endif
6064 }
6065
6066 static void
6067 dtrace_action_panic(dtrace_ecb_t *ecb)
6068 {
6069         dtrace_probe_t *probe = ecb->dte_probe;
6070
6071         /*
6072          * It's impossible to be taking action on the NULL probe.
6073          */
6074         ASSERT(probe != NULL);
6075
6076         if (dtrace_destructive_disallow)
6077                 return;
6078
6079         if (dtrace_panicked != NULL)
6080                 return;
6081
6082         if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6083                 return;
6084
6085         /*
6086          * We won the right to panic.  (We want to be sure that only one
6087          * thread calls panic() from dtrace_probe(), and that panic() is
6088          * called exactly once.)
6089          */
6090         dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6091             probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6092             probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6093 }
6094
6095 static void
6096 dtrace_action_raise(uint64_t sig)
6097 {
6098         if (dtrace_destructive_disallow)
6099                 return;
6100
6101         if (sig >= NSIG) {
6102                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6103                 return;
6104         }
6105
6106 #if defined(sun)
6107         /*
6108          * raise() has a queue depth of 1 -- we ignore all subsequent
6109          * invocations of the raise() action.
6110          */
6111         if (curthread->t_dtrace_sig == 0)
6112                 curthread->t_dtrace_sig = (uint8_t)sig;
6113
6114         curthread->t_sig_check = 1;
6115         aston(curthread);
6116 #else
6117         struct proc *p = curproc;
6118         PROC_LOCK(p);
6119         kern_psignal(p, sig);
6120         PROC_UNLOCK(p);
6121 #endif
6122 }
6123
6124 static void
6125 dtrace_action_stop(void)
6126 {
6127         if (dtrace_destructive_disallow)
6128                 return;
6129
6130 #if defined(sun)
6131         if (!curthread->t_dtrace_stop) {
6132                 curthread->t_dtrace_stop = 1;
6133                 curthread->t_sig_check = 1;
6134                 aston(curthread);
6135         }
6136 #else
6137         struct proc *p = curproc;
6138         PROC_LOCK(p);
6139         kern_psignal(p, SIGSTOP);
6140         PROC_UNLOCK(p);
6141 #endif
6142 }
6143
6144 static void
6145 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6146 {
6147         hrtime_t now;
6148         volatile uint16_t *flags;
6149 #if defined(sun)
6150         cpu_t *cpu = CPU;
6151 #else
6152         cpu_t *cpu = &solaris_cpu[curcpu];
6153 #endif
6154
6155         if (dtrace_destructive_disallow)
6156                 return;
6157
6158         flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6159
6160         now = dtrace_gethrtime();
6161
6162         if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6163                 /*
6164                  * We need to advance the mark to the current time.
6165                  */
6166                 cpu->cpu_dtrace_chillmark = now;
6167                 cpu->cpu_dtrace_chilled = 0;
6168         }
6169
6170         /*
6171          * Now check to see if the requested chill time would take us over
6172          * the maximum amount of time allowed in the chill interval.  (Or
6173          * worse, if the calculation itself induces overflow.)
6174          */
6175         if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6176             cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6177                 *flags |= CPU_DTRACE_ILLOP;
6178                 return;
6179         }
6180
6181         while (dtrace_gethrtime() - now < val)
6182                 continue;
6183
6184         /*
6185          * Normally, we assure that the value of the variable "timestamp" does
6186          * not change within an ECB.  The presence of chill() represents an
6187          * exception to this rule, however.
6188          */
6189         mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6190         cpu->cpu_dtrace_chilled += val;
6191 }
6192
6193 static void
6194 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6195     uint64_t *buf, uint64_t arg)
6196 {
6197         int nframes = DTRACE_USTACK_NFRAMES(arg);
6198         int strsize = DTRACE_USTACK_STRSIZE(arg);
6199         uint64_t *pcs = &buf[1], *fps;
6200         char *str = (char *)&pcs[nframes];
6201         int size, offs = 0, i, j;
6202         uintptr_t old = mstate->dtms_scratch_ptr, saved;
6203         uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
6204         char *sym;
6205
6206         /*
6207          * Should be taking a faster path if string space has not been
6208          * allocated.
6209          */
6210         ASSERT(strsize != 0);
6211
6212         /*
6213          * We will first allocate some temporary space for the frame pointers.
6214          */
6215         fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6216         size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6217             (nframes * sizeof (uint64_t));
6218
6219         if (!DTRACE_INSCRATCH(mstate, size)) {
6220                 /*
6221                  * Not enough room for our frame pointers -- need to indicate
6222                  * that we ran out of scratch space.
6223                  */
6224                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6225                 return;
6226         }
6227
6228         mstate->dtms_scratch_ptr += size;
6229         saved = mstate->dtms_scratch_ptr;
6230
6231         /*
6232          * Now get a stack with both program counters and frame pointers.
6233          */
6234         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6235         dtrace_getufpstack(buf, fps, nframes + 1);
6236         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6237
6238         /*
6239          * If that faulted, we're cooked.
6240          */
6241         if (*flags & CPU_DTRACE_FAULT)
6242                 goto out;
6243
6244         /*
6245          * Now we want to walk up the stack, calling the USTACK helper.  For
6246          * each iteration, we restore the scratch pointer.
6247          */
6248         for (i = 0; i < nframes; i++) {
6249                 mstate->dtms_scratch_ptr = saved;
6250
6251                 if (offs >= strsize)
6252                         break;
6253
6254                 sym = (char *)(uintptr_t)dtrace_helper(
6255                     DTRACE_HELPER_ACTION_USTACK,
6256                     mstate, state, pcs[i], fps[i]);
6257
6258                 /*
6259                  * If we faulted while running the helper, we're going to
6260                  * clear the fault and null out the corresponding string.
6261                  */
6262                 if (*flags & CPU_DTRACE_FAULT) {
6263                         *flags &= ~CPU_DTRACE_FAULT;
6264                         str[offs++] = '\0';
6265                         continue;
6266                 }
6267
6268                 if (sym == NULL) {
6269                         str[offs++] = '\0';
6270                         continue;
6271                 }
6272
6273                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6274
6275                 /*
6276                  * Now copy in the string that the helper returned to us.
6277                  */
6278                 for (j = 0; offs + j < strsize; j++) {
6279                         if ((str[offs + j] = sym[j]) == '\0')
6280                                 break;
6281                 }
6282
6283                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6284
6285                 offs += j + 1;
6286         }
6287
6288         if (offs >= strsize) {
6289                 /*
6290                  * If we didn't have room for all of the strings, we don't
6291                  * abort processing -- this needn't be a fatal error -- but we
6292                  * still want to increment a counter (dts_stkstroverflows) to
6293                  * allow this condition to be warned about.  (If this is from
6294                  * a jstack() action, it is easily tuned via jstackstrsize.)
6295                  */
6296                 dtrace_error(&state->dts_stkstroverflows);
6297         }
6298
6299         while (offs < strsize)
6300                 str[offs++] = '\0';
6301
6302 out:
6303         mstate->dtms_scratch_ptr = old;
6304 }
6305
6306 /*
6307  * If you're looking for the epicenter of DTrace, you just found it.  This
6308  * is the function called by the provider to fire a probe -- from which all
6309  * subsequent probe-context DTrace activity emanates.
6310  */
6311 void
6312 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6313     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6314 {
6315         processorid_t cpuid;
6316         dtrace_icookie_t cookie;
6317         dtrace_probe_t *probe;
6318         dtrace_mstate_t mstate;
6319         dtrace_ecb_t *ecb;
6320         dtrace_action_t *act;
6321         intptr_t offs;
6322         size_t size;
6323         int vtime, onintr;
6324         volatile uint16_t *flags;
6325         hrtime_t now;
6326
6327         if (panicstr != NULL)
6328                 return;
6329
6330 #if defined(sun)
6331         /*
6332          * Kick out immediately if this CPU is still being born (in which case
6333          * curthread will be set to -1) or the current thread can't allow
6334          * probes in its current context.
6335          */
6336         if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6337                 return;
6338 #endif
6339
6340         cookie = dtrace_interrupt_disable();
6341         probe = dtrace_probes[id - 1];
6342         cpuid = curcpu;
6343         onintr = CPU_ON_INTR(CPU);
6344
6345         if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6346             probe->dtpr_predcache == curthread->t_predcache) {
6347                 /*
6348                  * We have hit in the predicate cache; we know that
6349                  * this predicate would evaluate to be false.
6350                  */
6351                 dtrace_interrupt_enable(cookie);
6352                 return;
6353         }
6354
6355 #if defined(sun)
6356         if (panic_quiesce) {
6357 #else
6358         if (panicstr != NULL) {
6359 #endif
6360                 /*
6361                  * We don't trace anything if we're panicking.
6362                  */
6363                 dtrace_interrupt_enable(cookie);
6364                 return;
6365         }
6366
6367         now = dtrace_gethrtime();
6368         vtime = dtrace_vtime_references != 0;
6369
6370         if (vtime && curthread->t_dtrace_start)
6371                 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6372
6373         mstate.dtms_difo = NULL;
6374         mstate.dtms_probe = probe;
6375         mstate.dtms_strtok = 0;
6376         mstate.dtms_arg[0] = arg0;
6377         mstate.dtms_arg[1] = arg1;
6378         mstate.dtms_arg[2] = arg2;
6379         mstate.dtms_arg[3] = arg3;
6380         mstate.dtms_arg[4] = arg4;
6381
6382         flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6383
6384         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6385                 dtrace_predicate_t *pred = ecb->dte_predicate;
6386                 dtrace_state_t *state = ecb->dte_state;
6387                 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6388                 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6389                 dtrace_vstate_t *vstate = &state->dts_vstate;
6390                 dtrace_provider_t *prov = probe->dtpr_provider;
6391                 uint64_t tracememsize = 0;
6392                 int committed = 0;
6393                 caddr_t tomax;
6394
6395                 /*
6396                  * A little subtlety with the following (seemingly innocuous)
6397                  * declaration of the automatic 'val':  by looking at the
6398                  * code, you might think that it could be declared in the
6399                  * action processing loop, below.  (That is, it's only used in
6400                  * the action processing loop.)  However, it must be declared
6401                  * out of that scope because in the case of DIF expression
6402                  * arguments to aggregating actions, one iteration of the
6403                  * action loop will use the last iteration's value.
6404                  */
6405                 uint64_t val = 0;
6406
6407                 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6408                 mstate.dtms_getf = NULL;
6409
6410                 *flags &= ~CPU_DTRACE_ERROR;
6411
6412                 if (prov == dtrace_provider) {
6413                         /*
6414                          * If dtrace itself is the provider of this probe,
6415                          * we're only going to continue processing the ECB if
6416                          * arg0 (the dtrace_state_t) is equal to the ECB's
6417                          * creating state.  (This prevents disjoint consumers
6418                          * from seeing one another's metaprobes.)
6419                          */
6420                         if (arg0 != (uint64_t)(uintptr_t)state)
6421                                 continue;
6422                 }
6423
6424                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6425                         /*
6426                          * We're not currently active.  If our provider isn't
6427                          * the dtrace pseudo provider, we're not interested.
6428                          */
6429                         if (prov != dtrace_provider)
6430                                 continue;
6431
6432                         /*
6433                          * Now we must further check if we are in the BEGIN
6434                          * probe.  If we are, we will only continue processing
6435                          * if we're still in WARMUP -- if one BEGIN enabling
6436                          * has invoked the exit() action, we don't want to
6437                          * evaluate subsequent BEGIN enablings.
6438                          */
6439                         if (probe->dtpr_id == dtrace_probeid_begin &&
6440                             state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6441                                 ASSERT(state->dts_activity ==
6442                                     DTRACE_ACTIVITY_DRAINING);
6443                                 continue;
6444                         }
6445                 }
6446
6447                 if (ecb->dte_cond) {
6448                         /*
6449                          * If the dte_cond bits indicate that this
6450                          * consumer is only allowed to see user-mode firings
6451                          * of this probe, call the provider's dtps_usermode()
6452                          * entry point to check that the probe was fired
6453                          * while in a user context. Skip this ECB if that's
6454                          * not the case.
6455                          */
6456                         if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6457                             prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6458                             probe->dtpr_id, probe->dtpr_arg) == 0)
6459                                 continue;
6460
6461 #if defined(sun)
6462                         /*
6463                          * This is more subtle than it looks. We have to be
6464                          * absolutely certain that CRED() isn't going to
6465                          * change out from under us so it's only legit to
6466                          * examine that structure if we're in constrained
6467                          * situations. Currently, the only times we'll this
6468                          * check is if a non-super-user has enabled the
6469                          * profile or syscall providers -- providers that
6470                          * allow visibility of all processes. For the
6471                          * profile case, the check above will ensure that
6472                          * we're examining a user context.
6473                          */
6474                         if (ecb->dte_cond & DTRACE_COND_OWNER) {
6475                                 cred_t *cr;
6476                                 cred_t *s_cr =
6477                                     ecb->dte_state->dts_cred.dcr_cred;
6478                                 proc_t *proc;
6479
6480                                 ASSERT(s_cr != NULL);
6481
6482                                 if ((cr = CRED()) == NULL ||
6483                                     s_cr->cr_uid != cr->cr_uid ||
6484                                     s_cr->cr_uid != cr->cr_ruid ||
6485                                     s_cr->cr_uid != cr->cr_suid ||
6486                                     s_cr->cr_gid != cr->cr_gid ||
6487                                     s_cr->cr_gid != cr->cr_rgid ||
6488                                     s_cr->cr_gid != cr->cr_sgid ||
6489                                     (proc = ttoproc(curthread)) == NULL ||
6490                                     (proc->p_flag & SNOCD))
6491                                         continue;
6492                         }
6493
6494                         if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6495                                 cred_t *cr;
6496                                 cred_t *s_cr =
6497                                     ecb->dte_state->dts_cred.dcr_cred;
6498
6499                                 ASSERT(s_cr != NULL);
6500
6501                                 if ((cr = CRED()) == NULL ||
6502                                     s_cr->cr_zone->zone_id !=
6503                                     cr->cr_zone->zone_id)
6504                                         continue;
6505                         }
6506 #endif
6507                 }
6508
6509                 if (now - state->dts_alive > dtrace_deadman_timeout) {
6510                         /*
6511                          * We seem to be dead.  Unless we (a) have kernel
6512                          * destructive permissions (b) have explicitly enabled
6513                          * destructive actions and (c) destructive actions have
6514                          * not been disabled, we're going to transition into
6515                          * the KILLED state, from which no further processing
6516                          * on this state will be performed.
6517                          */
6518                         if (!dtrace_priv_kernel_destructive(state) ||
6519                             !state->dts_cred.dcr_destructive ||
6520                             dtrace_destructive_disallow) {
6521                                 void *activity = &state->dts_activity;
6522                                 dtrace_activity_t current;
6523
6524                                 do {
6525                                         current = state->dts_activity;
6526                                 } while (dtrace_cas32(activity, current,
6527                                     DTRACE_ACTIVITY_KILLED) != current);
6528
6529                                 continue;
6530                         }
6531                 }
6532
6533                 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6534                     ecb->dte_alignment, state, &mstate)) < 0)
6535                         continue;
6536
6537                 tomax = buf->dtb_tomax;
6538                 ASSERT(tomax != NULL);
6539
6540                 if (ecb->dte_size != 0) {
6541                         dtrace_rechdr_t dtrh;
6542                         if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6543                                 mstate.dtms_timestamp = dtrace_gethrtime();
6544                                 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6545                         }
6546                         ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6547                         dtrh.dtrh_epid = ecb->dte_epid;
6548                         DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6549                             mstate.dtms_timestamp);
6550                         *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6551                 }
6552
6553                 mstate.dtms_epid = ecb->dte_epid;
6554                 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6555
6556                 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6557                         mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6558                 else
6559                         mstate.dtms_access = 0;
6560
6561                 if (pred != NULL) {
6562                         dtrace_difo_t *dp = pred->dtp_difo;
6563                         int rval;
6564
6565                         rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6566
6567                         if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6568                                 dtrace_cacheid_t cid = probe->dtpr_predcache;
6569
6570                                 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6571                                         /*
6572                                          * Update the predicate cache...
6573                                          */
6574                                         ASSERT(cid == pred->dtp_cacheid);
6575                                         curthread->t_predcache = cid;
6576                                 }
6577
6578                                 continue;
6579                         }
6580                 }
6581
6582                 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6583                     act != NULL; act = act->dta_next) {
6584                         size_t valoffs;
6585                         dtrace_difo_t *dp;
6586                         dtrace_recdesc_t *rec = &act->dta_rec;
6587
6588                         size = rec->dtrd_size;
6589                         valoffs = offs + rec->dtrd_offset;
6590
6591                         if (DTRACEACT_ISAGG(act->dta_kind)) {
6592                                 uint64_t v = 0xbad;
6593                                 dtrace_aggregation_t *agg;
6594
6595                                 agg = (dtrace_aggregation_t *)act;
6596
6597                                 if ((dp = act->dta_difo) != NULL)
6598                                         v = dtrace_dif_emulate(dp,
6599                                             &mstate, vstate, state);
6600
6601                                 if (*flags & CPU_DTRACE_ERROR)
6602                                         continue;
6603
6604                                 /*
6605                                  * Note that we always pass the expression
6606                                  * value from the previous iteration of the
6607                                  * action loop.  This value will only be used
6608                                  * if there is an expression argument to the
6609                                  * aggregating action, denoted by the
6610                                  * dtag_hasarg field.
6611                                  */
6612                                 dtrace_aggregate(agg, buf,
6613                                     offs, aggbuf, v, val);
6614                                 continue;
6615                         }
6616
6617                         switch (act->dta_kind) {
6618                         case DTRACEACT_STOP:
6619                                 if (dtrace_priv_proc_destructive(state))
6620                                         dtrace_action_stop();
6621                                 continue;
6622
6623                         case DTRACEACT_BREAKPOINT:
6624                                 if (dtrace_priv_kernel_destructive(state))
6625                                         dtrace_action_breakpoint(ecb);
6626                                 continue;
6627
6628                         case DTRACEACT_PANIC:
6629                                 if (dtrace_priv_kernel_destructive(state))
6630                                         dtrace_action_panic(ecb);
6631                                 continue;
6632
6633                         case DTRACEACT_STACK:
6634                                 if (!dtrace_priv_kernel(state))
6635                                         continue;
6636
6637                                 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6638                                     size / sizeof (pc_t), probe->dtpr_aframes,
6639                                     DTRACE_ANCHORED(probe) ? NULL :
6640                                     (uint32_t *)arg0);
6641                                 continue;
6642
6643                         case DTRACEACT_JSTACK:
6644                         case DTRACEACT_USTACK:
6645                                 if (!dtrace_priv_proc(state))
6646                                         continue;
6647
6648                                 /*
6649                                  * See comment in DIF_VAR_PID.
6650                                  */
6651                                 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6652                                     CPU_ON_INTR(CPU)) {
6653                                         int depth = DTRACE_USTACK_NFRAMES(
6654                                             rec->dtrd_arg) + 1;
6655
6656                                         dtrace_bzero((void *)(tomax + valoffs),
6657                                             DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6658                                             + depth * sizeof (uint64_t));
6659
6660                                         continue;
6661                                 }
6662
6663                                 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6664                                     curproc->p_dtrace_helpers != NULL) {
6665                                         /*
6666                                          * This is the slow path -- we have
6667                                          * allocated string space, and we're
6668                                          * getting the stack of a process that
6669                                          * has helpers.  Call into a separate
6670                                          * routine to perform this processing.
6671                                          */
6672                                         dtrace_action_ustack(&mstate, state,
6673                                             (uint64_t *)(tomax + valoffs),
6674                                             rec->dtrd_arg);
6675                                         continue;
6676                                 }
6677
6678                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6679                                 dtrace_getupcstack((uint64_t *)
6680                                     (tomax + valoffs),
6681                                     DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6682                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6683                                 continue;
6684
6685                         default:
6686                                 break;
6687                         }
6688
6689                         dp = act->dta_difo;
6690                         ASSERT(dp != NULL);
6691
6692                         val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6693
6694                         if (*flags & CPU_DTRACE_ERROR)
6695                                 continue;
6696
6697                         switch (act->dta_kind) {
6698                         case DTRACEACT_SPECULATE: {
6699                                 dtrace_rechdr_t *dtrh;
6700
6701                                 ASSERT(buf == &state->dts_buffer[cpuid]);
6702                                 buf = dtrace_speculation_buffer(state,
6703                                     cpuid, val);
6704
6705                                 if (buf == NULL) {
6706                                         *flags |= CPU_DTRACE_DROP;
6707                                         continue;
6708                                 }
6709
6710                                 offs = dtrace_buffer_reserve(buf,
6711                                     ecb->dte_needed, ecb->dte_alignment,
6712                                     state, NULL);
6713
6714                                 if (offs < 0) {
6715                                         *flags |= CPU_DTRACE_DROP;
6716                                         continue;
6717                                 }
6718
6719                                 tomax = buf->dtb_tomax;
6720                                 ASSERT(tomax != NULL);
6721
6722                                 if (ecb->dte_size == 0)
6723                                         continue;
6724
6725                                 ASSERT3U(ecb->dte_size, >=,
6726                                     sizeof (dtrace_rechdr_t));
6727                                 dtrh = ((void *)(tomax + offs));
6728                                 dtrh->dtrh_epid = ecb->dte_epid;
6729                                 /*
6730                                  * When the speculation is committed, all of
6731                                  * the records in the speculative buffer will
6732                                  * have their timestamps set to the commit
6733                                  * time.  Until then, it is set to a sentinel
6734                                  * value, for debugability.
6735                                  */
6736                                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6737                                 continue;
6738                         }
6739
6740                         case DTRACEACT_PRINTM: {
6741                                 /* The DIF returns a 'memref'. */
6742                                 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
6743
6744                                 /* Get the size from the memref. */
6745                                 size = memref[1];
6746
6747                                 /*
6748                                  * Check if the size exceeds the allocated
6749                                  * buffer size.
6750                                  */
6751                                 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6752                                         /* Flag a drop! */
6753                                         *flags |= CPU_DTRACE_DROP;
6754                                         continue;
6755                                 }
6756
6757                                 /* Store the size in the buffer first. */
6758                                 DTRACE_STORE(uintptr_t, tomax,
6759                                     valoffs, size);
6760
6761                                 /*
6762                                  * Offset the buffer address to the start
6763                                  * of the data.
6764                                  */
6765                                 valoffs += sizeof(uintptr_t);
6766
6767                                 /*
6768                                  * Reset to the memory address rather than
6769                                  * the memref array, then let the BYREF
6770                                  * code below do the work to store the 
6771                                  * memory data in the buffer.
6772                                  */
6773                                 val = memref[0];
6774                                 break;
6775                         }
6776
6777                         case DTRACEACT_PRINTT: {
6778                                 /* The DIF returns a 'typeref'. */
6779                                 uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
6780                                 char c = '\0' + 1;
6781                                 size_t s;
6782
6783                                 /*
6784                                  * Get the type string length and round it
6785                                  * up so that the data that follows is
6786                                  * aligned for easy access.
6787                                  */
6788                                 size_t typs = strlen((char *) typeref[2]) + 1;
6789                                 typs = roundup(typs,  sizeof(uintptr_t));
6790
6791                                 /*
6792                                  *Get the size from the typeref using the
6793                                  * number of elements and the type size.
6794                                  */
6795                                 size = typeref[1] * typeref[3];
6796
6797                                 /*
6798                                  * Check if the size exceeds the allocated
6799                                  * buffer size.
6800                                  */
6801                                 if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6802                                         /* Flag a drop! */
6803                                         *flags |= CPU_DTRACE_DROP;
6804                                 
6805                                 }
6806
6807                                 /* Store the size in the buffer first. */
6808                                 DTRACE_STORE(uintptr_t, tomax,
6809                                     valoffs, size);
6810                                 valoffs += sizeof(uintptr_t);
6811
6812                                 /* Store the type size in the buffer. */
6813                                 DTRACE_STORE(uintptr_t, tomax,
6814                                     valoffs, typeref[3]);
6815                                 valoffs += sizeof(uintptr_t);
6816
6817                                 val = typeref[2];
6818
6819                                 for (s = 0; s < typs; s++) {
6820                                         if (c != '\0')
6821                                                 c = dtrace_load8(val++);
6822
6823                                         DTRACE_STORE(uint8_t, tomax,
6824                                             valoffs++, c);
6825                                 }
6826
6827                                 /*
6828                                  * Reset to the memory address rather than
6829                                  * the typeref array, then let the BYREF
6830                                  * code below do the work to store the 
6831                                  * memory data in the buffer.
6832                                  */
6833                                 val = typeref[0];
6834                                 break;
6835                         }
6836
6837                         case DTRACEACT_CHILL:
6838                                 if (dtrace_priv_kernel_destructive(state))
6839                                         dtrace_action_chill(&mstate, val);
6840                                 continue;
6841
6842                         case DTRACEACT_RAISE:
6843                                 if (dtrace_priv_proc_destructive(state))
6844                                         dtrace_action_raise(val);
6845                                 continue;
6846
6847                         case DTRACEACT_COMMIT:
6848                                 ASSERT(!committed);
6849
6850                                 /*
6851                                  * We need to commit our buffer state.
6852                                  */
6853                                 if (ecb->dte_size)
6854                                         buf->dtb_offset = offs + ecb->dte_size;
6855                                 buf = &state->dts_buffer[cpuid];
6856                                 dtrace_speculation_commit(state, cpuid, val);
6857                                 committed = 1;
6858                                 continue;
6859
6860                         case DTRACEACT_DISCARD:
6861                                 dtrace_speculation_discard(state, cpuid, val);
6862                                 continue;
6863
6864                         case DTRACEACT_DIFEXPR:
6865                         case DTRACEACT_LIBACT:
6866                         case DTRACEACT_PRINTF:
6867                         case DTRACEACT_PRINTA:
6868                         case DTRACEACT_SYSTEM:
6869                         case DTRACEACT_FREOPEN:
6870                         case DTRACEACT_TRACEMEM:
6871                                 break;
6872
6873                         case DTRACEACT_TRACEMEM_DYNSIZE:
6874                                 tracememsize = val;
6875                                 break;
6876
6877                         case DTRACEACT_SYM:
6878                         case DTRACEACT_MOD:
6879                                 if (!dtrace_priv_kernel(state))
6880                                         continue;
6881                                 break;
6882
6883                         case DTRACEACT_USYM:
6884                         case DTRACEACT_UMOD:
6885                         case DTRACEACT_UADDR: {
6886 #if defined(sun)
6887                                 struct pid *pid = curthread->t_procp->p_pidp;
6888 #endif
6889
6890                                 if (!dtrace_priv_proc(state))
6891                                         continue;
6892
6893                                 DTRACE_STORE(uint64_t, tomax,
6894 #if defined(sun)
6895                                     valoffs, (uint64_t)pid->pid_id);
6896 #else
6897                                     valoffs, (uint64_t) curproc->p_pid);
6898 #endif
6899                                 DTRACE_STORE(uint64_t, tomax,
6900                                     valoffs + sizeof (uint64_t), val);
6901
6902                                 continue;
6903                         }
6904
6905                         case DTRACEACT_EXIT: {
6906                                 /*
6907                                  * For the exit action, we are going to attempt
6908                                  * to atomically set our activity to be
6909                                  * draining.  If this fails (either because
6910                                  * another CPU has beat us to the exit action,
6911                                  * or because our current activity is something
6912                                  * other than ACTIVE or WARMUP), we will
6913                                  * continue.  This assures that the exit action
6914                                  * can be successfully recorded at most once
6915                                  * when we're in the ACTIVE state.  If we're
6916                                  * encountering the exit() action while in
6917                                  * COOLDOWN, however, we want to honor the new
6918                                  * status code.  (We know that we're the only
6919                                  * thread in COOLDOWN, so there is no race.)
6920                                  */
6921                                 void *activity = &state->dts_activity;
6922                                 dtrace_activity_t current = state->dts_activity;
6923
6924                                 if (current == DTRACE_ACTIVITY_COOLDOWN)
6925                                         break;
6926
6927                                 if (current != DTRACE_ACTIVITY_WARMUP)
6928                                         current = DTRACE_ACTIVITY_ACTIVE;
6929
6930                                 if (dtrace_cas32(activity, current,
6931                                     DTRACE_ACTIVITY_DRAINING) != current) {
6932                                         *flags |= CPU_DTRACE_DROP;
6933                                         continue;
6934                                 }
6935
6936                                 break;
6937                         }
6938
6939                         default:
6940                                 ASSERT(0);
6941                         }
6942
6943                         if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6944                                 uintptr_t end = valoffs + size;
6945
6946                                 if (tracememsize != 0 &&
6947                                     valoffs + tracememsize < end) {
6948                                         end = valoffs + tracememsize;
6949                                         tracememsize = 0;
6950                                 }
6951
6952                                 if (!dtrace_vcanload((void *)(uintptr_t)val,
6953                                     &dp->dtdo_rtype, &mstate, vstate))
6954                                         continue;
6955
6956                                 /*
6957                                  * If this is a string, we're going to only
6958                                  * load until we find the zero byte -- after
6959                                  * which we'll store zero bytes.
6960                                  */
6961                                 if (dp->dtdo_rtype.dtdt_kind ==
6962                                     DIF_TYPE_STRING) {
6963                                         char c = '\0' + 1;
6964                                         int intuple = act->dta_intuple;
6965                                         size_t s;
6966
6967                                         for (s = 0; s < size; s++) {
6968                                                 if (c != '\0')
6969                                                         c = dtrace_load8(val++);
6970
6971                                                 DTRACE_STORE(uint8_t, tomax,
6972                                                     valoffs++, c);
6973
6974                                                 if (c == '\0' && intuple)
6975                                                         break;
6976                                         }
6977
6978                                         continue;
6979                                 }
6980
6981                                 while (valoffs < end) {
6982                                         DTRACE_STORE(uint8_t, tomax, valoffs++,
6983                                             dtrace_load8(val++));
6984                                 }
6985
6986                                 continue;
6987                         }
6988
6989                         switch (size) {
6990                         case 0:
6991                                 break;
6992
6993                         case sizeof (uint8_t):
6994                                 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6995                                 break;
6996                         case sizeof (uint16_t):
6997                                 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6998                                 break;
6999                         case sizeof (uint32_t):
7000                                 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7001                                 break;
7002                         case sizeof (uint64_t):
7003                                 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7004                                 break;
7005                         default:
7006                                 /*
7007                                  * Any other size should have been returned by
7008                                  * reference, not by value.
7009                                  */
7010                                 ASSERT(0);
7011                                 break;
7012                         }
7013                 }
7014
7015                 if (*flags & CPU_DTRACE_DROP)
7016                         continue;
7017
7018                 if (*flags & CPU_DTRACE_FAULT) {
7019                         int ndx;
7020                         dtrace_action_t *err;
7021
7022                         buf->dtb_errors++;
7023
7024                         if (probe->dtpr_id == dtrace_probeid_error) {
7025                                 /*
7026                                  * There's nothing we can do -- we had an
7027                                  * error on the error probe.  We bump an
7028                                  * error counter to at least indicate that
7029                                  * this condition happened.
7030                                  */
7031                                 dtrace_error(&state->dts_dblerrors);
7032                                 continue;
7033                         }
7034
7035                         if (vtime) {
7036                                 /*
7037                                  * Before recursing on dtrace_probe(), we
7038                                  * need to explicitly clear out our start
7039                                  * time to prevent it from being accumulated
7040                                  * into t_dtrace_vtime.
7041                                  */
7042                                 curthread->t_dtrace_start = 0;
7043                         }
7044
7045                         /*
7046                          * Iterate over the actions to figure out which action
7047                          * we were processing when we experienced the error.
7048                          * Note that act points _past_ the faulting action; if
7049                          * act is ecb->dte_action, the fault was in the
7050                          * predicate, if it's ecb->dte_action->dta_next it's
7051                          * in action #1, and so on.
7052                          */
7053                         for (err = ecb->dte_action, ndx = 0;
7054                             err != act; err = err->dta_next, ndx++)
7055                                 continue;
7056
7057                         dtrace_probe_error(state, ecb->dte_epid, ndx,
7058                             (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7059                             mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7060                             cpu_core[cpuid].cpuc_dtrace_illval);
7061
7062                         continue;
7063                 }
7064
7065                 if (!committed)
7066                         buf->dtb_offset = offs + ecb->dte_size;
7067         }
7068
7069         if (vtime)
7070                 curthread->t_dtrace_start = dtrace_gethrtime();
7071
7072         dtrace_interrupt_enable(cookie);
7073 }
7074
7075 /*
7076  * DTrace Probe Hashing Functions
7077  *
7078  * The functions in this section (and indeed, the functions in remaining
7079  * sections) are not _called_ from probe context.  (Any exceptions to this are
7080  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7081  * DTrace framework to look-up probes in, add probes to and remove probes from
7082  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7083  * probe tuple -- allowing for fast lookups, regardless of what was
7084  * specified.)
7085  */
7086 static uint_t
7087 dtrace_hash_str(const char *p)
7088 {
7089         unsigned int g;
7090         uint_t hval = 0;
7091
7092         while (*p) {
7093                 hval = (hval << 4) + *p++;
7094                 if ((g = (hval & 0xf0000000)) != 0)
7095                         hval ^= g >> 24;
7096                 hval &= ~g;
7097         }
7098         return (hval);
7099 }
7100
7101 static dtrace_hash_t *
7102 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7103 {
7104         dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7105
7106         hash->dth_stroffs = stroffs;
7107         hash->dth_nextoffs = nextoffs;
7108         hash->dth_prevoffs = prevoffs;
7109
7110         hash->dth_size = 1;
7111         hash->dth_mask = hash->dth_size - 1;
7112
7113         hash->dth_tab = kmem_zalloc(hash->dth_size *
7114             sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7115
7116         return (hash);
7117 }
7118
7119 static void
7120 dtrace_hash_destroy(dtrace_hash_t *hash)
7121 {
7122 #ifdef DEBUG
7123         int i;
7124
7125         for (i = 0; i < hash->dth_size; i++)
7126                 ASSERT(hash->dth_tab[i] == NULL);
7127 #endif
7128
7129         kmem_free(hash->dth_tab,
7130             hash->dth_size * sizeof (dtrace_hashbucket_t *));
7131         kmem_free(hash, sizeof (dtrace_hash_t));
7132 }
7133
7134 static void
7135 dtrace_hash_resize(dtrace_hash_t *hash)
7136 {
7137         int size = hash->dth_size, i, ndx;
7138         int new_size = hash->dth_size << 1;
7139         int new_mask = new_size - 1;
7140         dtrace_hashbucket_t **new_tab, *bucket, *next;
7141
7142         ASSERT((new_size & new_mask) == 0);
7143
7144         new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7145
7146         for (i = 0; i < size; i++) {
7147                 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7148                         dtrace_probe_t *probe = bucket->dthb_chain;
7149
7150                         ASSERT(probe != NULL);
7151                         ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7152
7153                         next = bucket->dthb_next;
7154                         bucket->dthb_next = new_tab[ndx];
7155                         new_tab[ndx] = bucket;
7156                 }
7157         }
7158
7159         kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7160         hash->dth_tab = new_tab;
7161         hash->dth_size = new_size;
7162         hash->dth_mask = new_mask;
7163 }
7164
7165 static void
7166 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7167 {
7168         int hashval = DTRACE_HASHSTR(hash, new);
7169         int ndx = hashval & hash->dth_mask;
7170         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7171         dtrace_probe_t **nextp, **prevp;
7172
7173         for (; bucket != NULL; bucket = bucket->dthb_next) {
7174                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7175                         goto add;
7176         }
7177
7178         if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7179                 dtrace_hash_resize(hash);
7180                 dtrace_hash_add(hash, new);
7181                 return;
7182         }
7183
7184         bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7185         bucket->dthb_next = hash->dth_tab[ndx];
7186         hash->dth_tab[ndx] = bucket;
7187         hash->dth_nbuckets++;
7188
7189 add:
7190         nextp = DTRACE_HASHNEXT(hash, new);
7191         ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7192         *nextp = bucket->dthb_chain;
7193
7194         if (bucket->dthb_chain != NULL) {
7195                 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7196                 ASSERT(*prevp == NULL);
7197                 *prevp = new;
7198         }
7199
7200         bucket->dthb_chain = new;
7201         bucket->dthb_len++;
7202 }
7203
7204 static dtrace_probe_t *
7205 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7206 {
7207         int hashval = DTRACE_HASHSTR(hash, template);
7208         int ndx = hashval & hash->dth_mask;
7209         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7210
7211         for (; bucket != NULL; bucket = bucket->dthb_next) {
7212                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7213                         return (bucket->dthb_chain);
7214         }
7215
7216         return (NULL);
7217 }
7218
7219 static int
7220 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7221 {
7222         int hashval = DTRACE_HASHSTR(hash, template);
7223         int ndx = hashval & hash->dth_mask;
7224         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7225
7226         for (; bucket != NULL; bucket = bucket->dthb_next) {
7227                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7228                         return (bucket->dthb_len);
7229         }
7230
7231         return (0);
7232 }
7233
7234 static void
7235 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7236 {
7237         int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7238         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7239
7240         dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7241         dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7242
7243         /*
7244          * Find the bucket that we're removing this probe from.
7245          */
7246         for (; bucket != NULL; bucket = bucket->dthb_next) {
7247                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7248                         break;
7249         }
7250
7251         ASSERT(bucket != NULL);
7252
7253         if (*prevp == NULL) {
7254                 if (*nextp == NULL) {
7255                         /*
7256                          * The removed probe was the only probe on this
7257                          * bucket; we need to remove the bucket.
7258                          */
7259                         dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7260
7261                         ASSERT(bucket->dthb_chain == probe);
7262                         ASSERT(b != NULL);
7263
7264                         if (b == bucket) {
7265                                 hash->dth_tab[ndx] = bucket->dthb_next;
7266                         } else {
7267                                 while (b->dthb_next != bucket)
7268                                         b = b->dthb_next;
7269                                 b->dthb_next = bucket->dthb_next;
7270                         }
7271
7272                         ASSERT(hash->dth_nbuckets > 0);
7273                         hash->dth_nbuckets--;
7274                         kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7275                         return;
7276                 }
7277
7278                 bucket->dthb_chain = *nextp;
7279         } else {
7280                 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7281         }
7282
7283         if (*nextp != NULL)
7284                 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7285 }
7286
7287 /*
7288  * DTrace Utility Functions
7289  *
7290  * These are random utility functions that are _not_ called from probe context.
7291  */
7292 static int
7293 dtrace_badattr(const dtrace_attribute_t *a)
7294 {
7295         return (a->dtat_name > DTRACE_STABILITY_MAX ||
7296             a->dtat_data > DTRACE_STABILITY_MAX ||
7297             a->dtat_class > DTRACE_CLASS_MAX);
7298 }
7299
7300 /*
7301  * Return a duplicate copy of a string.  If the specified string is NULL,
7302  * this function returns a zero-length string.
7303  */
7304 static char *
7305 dtrace_strdup(const char *str)
7306 {
7307         char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7308
7309         if (str != NULL)
7310                 (void) strcpy(new, str);
7311
7312         return (new);
7313 }
7314
7315 #define DTRACE_ISALPHA(c)       \
7316         (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7317
7318 static int
7319 dtrace_badname(const char *s)
7320 {
7321         char c;
7322
7323         if (s == NULL || (c = *s++) == '\0')
7324                 return (0);
7325
7326         if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7327                 return (1);
7328
7329         while ((c = *s++) != '\0') {
7330                 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7331                     c != '-' && c != '_' && c != '.' && c != '`')
7332                         return (1);
7333         }
7334
7335         return (0);
7336 }
7337
7338 static void
7339 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7340 {
7341         uint32_t priv;
7342
7343 #if defined(sun)
7344         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7345                 /*
7346                  * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7347                  */
7348                 priv = DTRACE_PRIV_ALL;
7349         } else {
7350                 *uidp = crgetuid(cr);
7351                 *zoneidp = crgetzoneid(cr);
7352
7353                 priv = 0;
7354                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7355                         priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7356                 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7357                         priv |= DTRACE_PRIV_USER;
7358                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7359                         priv |= DTRACE_PRIV_PROC;
7360                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7361                         priv |= DTRACE_PRIV_OWNER;
7362                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7363                         priv |= DTRACE_PRIV_ZONEOWNER;
7364         }
7365 #else
7366         priv = DTRACE_PRIV_ALL;
7367 #endif
7368
7369         *privp = priv;
7370 }
7371
7372 #ifdef DTRACE_ERRDEBUG
7373 static void
7374 dtrace_errdebug(const char *str)
7375 {
7376         int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7377         int occupied = 0;
7378
7379         mutex_enter(&dtrace_errlock);
7380         dtrace_errlast = str;
7381         dtrace_errthread = curthread;
7382
7383         while (occupied++ < DTRACE_ERRHASHSZ) {
7384                 if (dtrace_errhash[hval].dter_msg == str) {
7385                         dtrace_errhash[hval].dter_count++;
7386                         goto out;
7387                 }
7388
7389                 if (dtrace_errhash[hval].dter_msg != NULL) {
7390                         hval = (hval + 1) % DTRACE_ERRHASHSZ;
7391                         continue;
7392                 }
7393
7394                 dtrace_errhash[hval].dter_msg = str;
7395                 dtrace_errhash[hval].dter_count = 1;
7396                 goto out;
7397         }
7398
7399         panic("dtrace: undersized error hash");
7400 out:
7401         mutex_exit(&dtrace_errlock);
7402 }
7403 #endif
7404
7405 /*
7406  * DTrace Matching Functions
7407  *
7408  * These functions are used to match groups of probes, given some elements of
7409  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7410  */
7411 static int
7412 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7413     zoneid_t zoneid)
7414 {
7415         if (priv != DTRACE_PRIV_ALL) {
7416                 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7417                 uint32_t match = priv & ppriv;
7418
7419                 /*
7420                  * No PRIV_DTRACE_* privileges...
7421                  */
7422                 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7423                     DTRACE_PRIV_KERNEL)) == 0)
7424                         return (0);
7425
7426                 /*
7427                  * No matching bits, but there were bits to match...
7428                  */
7429                 if (match == 0 && ppriv != 0)
7430                         return (0);
7431
7432                 /*
7433                  * Need to have permissions to the process, but don't...
7434                  */
7435                 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7436                     uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7437                         return (0);
7438                 }
7439
7440                 /*
7441                  * Need to be in the same zone unless we possess the
7442                  * privilege to examine all zones.
7443                  */
7444                 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7445                     zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7446                         return (0);
7447                 }
7448         }
7449
7450         return (1);
7451 }
7452
7453 /*
7454  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7455  * consists of input pattern strings and an ops-vector to evaluate them.
7456  * This function returns >0 for match, 0 for no match, and <0 for error.
7457  */
7458 static int
7459 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7460     uint32_t priv, uid_t uid, zoneid_t zoneid)
7461 {
7462         dtrace_provider_t *pvp = prp->dtpr_provider;
7463         int rv;
7464
7465         if (pvp->dtpv_defunct)
7466                 return (0);
7467
7468         if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7469                 return (rv);
7470
7471         if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7472                 return (rv);
7473
7474         if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7475                 return (rv);
7476
7477         if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7478                 return (rv);
7479
7480         if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7481                 return (0);
7482
7483         return (rv);
7484 }
7485
7486 /*
7487  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7488  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7489  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7490  * In addition, all of the recursion cases except for '*' matching have been
7491  * unwound.  For '*', we still implement recursive evaluation, but a depth
7492  * counter is maintained and matching is aborted if we recurse too deep.
7493  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7494  */
7495 static int
7496 dtrace_match_glob(const char *s, const char *p, int depth)
7497 {
7498         const char *olds;
7499         char s1, c;
7500         int gs;
7501
7502         if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7503                 return (-1);
7504
7505         if (s == NULL)
7506                 s = ""; /* treat NULL as empty string */
7507
7508 top:
7509         olds = s;
7510         s1 = *s++;
7511
7512         if (p == NULL)
7513                 return (0);
7514
7515         if ((c = *p++) == '\0')
7516                 return (s1 == '\0');
7517
7518         switch (c) {
7519         case '[': {
7520                 int ok = 0, notflag = 0;
7521                 char lc = '\0';
7522
7523                 if (s1 == '\0')
7524                         return (0);
7525
7526                 if (*p == '!') {
7527                         notflag = 1;
7528                         p++;
7529                 }
7530
7531                 if ((c = *p++) == '\0')
7532                         return (0);
7533
7534                 do {
7535                         if (c == '-' && lc != '\0' && *p != ']') {
7536                                 if ((c = *p++) == '\0')
7537                                         return (0);
7538                                 if (c == '\\' && (c = *p++) == '\0')
7539                                         return (0);
7540
7541                                 if (notflag) {
7542                                         if (s1 < lc || s1 > c)
7543                                                 ok++;
7544                                         else
7545                                                 return (0);
7546                                 } else if (lc <= s1 && s1 <= c)
7547                                         ok++;
7548
7549                         } else if (c == '\\' && (c = *p++) == '\0')
7550                                 return (0);
7551
7552                         lc = c; /* save left-hand 'c' for next iteration */
7553
7554                         if (notflag) {
7555                                 if (s1 != c)
7556                                         ok++;
7557                                 else
7558                                         return (0);
7559                         } else if (s1 == c)
7560                                 ok++;
7561
7562                         if ((c = *p++) == '\0')
7563                                 return (0);
7564
7565                 } while (c != ']');
7566
7567                 if (ok)
7568                         goto top;
7569
7570                 return (0);
7571         }
7572
7573         case '\\':
7574                 if ((c = *p++) == '\0')
7575                         return (0);
7576                 /*FALLTHRU*/
7577
7578         default:
7579                 if (c != s1)
7580                         return (0);
7581                 /*FALLTHRU*/
7582
7583         case '?':
7584                 if (s1 != '\0')
7585                         goto top;
7586                 return (0);
7587
7588         case '*':
7589                 while (*p == '*')
7590                         p++; /* consecutive *'s are identical to a single one */
7591
7592                 if (*p == '\0')
7593                         return (1);
7594
7595                 for (s = olds; *s != '\0'; s++) {
7596                         if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7597                                 return (gs);
7598                 }
7599
7600                 return (0);
7601         }
7602 }
7603
7604 /*ARGSUSED*/
7605 static int
7606 dtrace_match_string(const char *s, const char *p, int depth)
7607 {
7608         return (s != NULL && strcmp(s, p) == 0);
7609 }
7610
7611 /*ARGSUSED*/
7612 static int
7613 dtrace_match_nul(const char *s, const char *p, int depth)
7614 {
7615         return (1); /* always match the empty pattern */
7616 }
7617
7618 /*ARGSUSED*/
7619 static int
7620 dtrace_match_nonzero(const char *s, const char *p, int depth)
7621 {
7622         return (s != NULL && s[0] != '\0');
7623 }
7624
7625 static int
7626 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7627     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7628 {
7629         dtrace_probe_t template, *probe;
7630         dtrace_hash_t *hash = NULL;
7631         int len, best = INT_MAX, nmatched = 0;
7632         dtrace_id_t i;
7633
7634         ASSERT(MUTEX_HELD(&dtrace_lock));
7635
7636         /*
7637          * If the probe ID is specified in the key, just lookup by ID and
7638          * invoke the match callback once if a matching probe is found.
7639          */
7640         if (pkp->dtpk_id != DTRACE_IDNONE) {
7641                 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7642                     dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7643                         (void) (*matched)(probe, arg);
7644                         nmatched++;
7645                 }
7646                 return (nmatched);
7647         }
7648
7649         template.dtpr_mod = (char *)pkp->dtpk_mod;
7650         template.dtpr_func = (char *)pkp->dtpk_func;
7651         template.dtpr_name = (char *)pkp->dtpk_name;
7652
7653         /*
7654          * We want to find the most distinct of the module name, function
7655          * name, and name.  So for each one that is not a glob pattern or
7656          * empty string, we perform a lookup in the corresponding hash and
7657          * use the hash table with the fewest collisions to do our search.
7658          */
7659         if (pkp->dtpk_mmatch == &dtrace_match_string &&
7660             (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7661                 best = len;
7662                 hash = dtrace_bymod;
7663         }
7664
7665         if (pkp->dtpk_fmatch == &dtrace_match_string &&
7666             (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7667                 best = len;
7668                 hash = dtrace_byfunc;
7669         }
7670
7671         if (pkp->dtpk_nmatch == &dtrace_match_string &&
7672             (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7673                 best = len;
7674                 hash = dtrace_byname;
7675         }
7676
7677         /*
7678          * If we did not select a hash table, iterate over every probe and
7679          * invoke our callback for each one that matches our input probe key.
7680          */
7681         if (hash == NULL) {
7682                 for (i = 0; i < dtrace_nprobes; i++) {
7683                         if ((probe = dtrace_probes[i]) == NULL ||
7684                             dtrace_match_probe(probe, pkp, priv, uid,
7685                             zoneid) <= 0)
7686                                 continue;
7687
7688                         nmatched++;
7689
7690                         if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7691                                 break;
7692                 }
7693
7694                 return (nmatched);
7695         }
7696
7697         /*
7698          * If we selected a hash table, iterate over each probe of the same key
7699          * name and invoke the callback for every probe that matches the other
7700          * attributes of our input probe key.
7701          */
7702         for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7703             probe = *(DTRACE_HASHNEXT(hash, probe))) {
7704
7705                 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7706                         continue;
7707
7708                 nmatched++;
7709
7710                 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7711                         break;
7712         }
7713
7714         return (nmatched);
7715 }
7716
7717 /*
7718  * Return the function pointer dtrace_probecmp() should use to compare the
7719  * specified pattern with a string.  For NULL or empty patterns, we select
7720  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7721  * For non-empty non-glob strings, we use dtrace_match_string().
7722  */
7723 static dtrace_probekey_f *
7724 dtrace_probekey_func(const char *p)
7725 {
7726         char c;
7727
7728         if (p == NULL || *p == '\0')
7729                 return (&dtrace_match_nul);
7730
7731         while ((c = *p++) != '\0') {
7732                 if (c == '[' || c == '?' || c == '*' || c == '\\')
7733                         return (&dtrace_match_glob);
7734         }
7735
7736         return (&dtrace_match_string);
7737 }
7738
7739 /*
7740  * Build a probe comparison key for use with dtrace_match_probe() from the
7741  * given probe description.  By convention, a null key only matches anchored
7742  * probes: if each field is the empty string, reset dtpk_fmatch to
7743  * dtrace_match_nonzero().
7744  */
7745 static void
7746 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7747 {
7748         pkp->dtpk_prov = pdp->dtpd_provider;
7749         pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7750
7751         pkp->dtpk_mod = pdp->dtpd_mod;
7752         pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7753
7754         pkp->dtpk_func = pdp->dtpd_func;
7755         pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7756
7757         pkp->dtpk_name = pdp->dtpd_name;
7758         pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7759
7760         pkp->dtpk_id = pdp->dtpd_id;
7761
7762         if (pkp->dtpk_id == DTRACE_IDNONE &&
7763             pkp->dtpk_pmatch == &dtrace_match_nul &&
7764             pkp->dtpk_mmatch == &dtrace_match_nul &&
7765             pkp->dtpk_fmatch == &dtrace_match_nul &&
7766             pkp->dtpk_nmatch == &dtrace_match_nul)
7767                 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7768 }
7769
7770 /*
7771  * DTrace Provider-to-Framework API Functions
7772  *
7773  * These functions implement much of the Provider-to-Framework API, as
7774  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7775  * the functions in the API for probe management (found below), and
7776  * dtrace_probe() itself (found above).
7777  */
7778
7779 /*
7780  * Register the calling provider with the DTrace framework.  This should
7781  * generally be called by DTrace providers in their attach(9E) entry point.
7782  */
7783 int
7784 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7785     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7786 {
7787         dtrace_provider_t *provider;
7788
7789         if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7790                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7791                     "arguments", name ? name : "<NULL>");
7792                 return (EINVAL);
7793         }
7794
7795         if (name[0] == '\0' || dtrace_badname(name)) {
7796                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7797                     "provider name", name);
7798                 return (EINVAL);
7799         }
7800
7801         if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7802             pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7803             pops->dtps_destroy == NULL ||
7804             ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7805                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7806                     "provider ops", name);
7807                 return (EINVAL);
7808         }
7809
7810         if (dtrace_badattr(&pap->dtpa_provider) ||
7811             dtrace_badattr(&pap->dtpa_mod) ||
7812             dtrace_badattr(&pap->dtpa_func) ||
7813             dtrace_badattr(&pap->dtpa_name) ||
7814             dtrace_badattr(&pap->dtpa_args)) {
7815                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7816                     "provider attributes", name);
7817                 return (EINVAL);
7818         }
7819
7820         if (priv & ~DTRACE_PRIV_ALL) {
7821                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7822                     "privilege attributes", name);
7823                 return (EINVAL);
7824         }
7825
7826         if ((priv & DTRACE_PRIV_KERNEL) &&
7827             (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7828             pops->dtps_usermode == NULL) {
7829                 cmn_err(CE_WARN, "failed to register provider '%s': need "
7830                     "dtps_usermode() op for given privilege attributes", name);
7831                 return (EINVAL);
7832         }
7833
7834         provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7835         provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7836         (void) strcpy(provider->dtpv_name, name);
7837
7838         provider->dtpv_attr = *pap;
7839         provider->dtpv_priv.dtpp_flags = priv;
7840         if (cr != NULL) {
7841                 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7842                 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7843         }
7844         provider->dtpv_pops = *pops;
7845
7846         if (pops->dtps_provide == NULL) {
7847                 ASSERT(pops->dtps_provide_module != NULL);
7848                 provider->dtpv_pops.dtps_provide =
7849                     (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
7850         }
7851
7852         if (pops->dtps_provide_module == NULL) {
7853                 ASSERT(pops->dtps_provide != NULL);
7854                 provider->dtpv_pops.dtps_provide_module =
7855                     (void (*)(void *, modctl_t *))dtrace_nullop;
7856         }
7857
7858         if (pops->dtps_suspend == NULL) {
7859                 ASSERT(pops->dtps_resume == NULL);
7860                 provider->dtpv_pops.dtps_suspend =
7861                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7862                 provider->dtpv_pops.dtps_resume =
7863                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7864         }
7865
7866         provider->dtpv_arg = arg;
7867         *idp = (dtrace_provider_id_t)provider;
7868
7869         if (pops == &dtrace_provider_ops) {
7870                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7871                 ASSERT(MUTEX_HELD(&dtrace_lock));
7872                 ASSERT(dtrace_anon.dta_enabling == NULL);
7873
7874                 /*
7875                  * We make sure that the DTrace provider is at the head of
7876                  * the provider chain.
7877                  */
7878                 provider->dtpv_next = dtrace_provider;
7879                 dtrace_provider = provider;
7880                 return (0);
7881         }
7882
7883         mutex_enter(&dtrace_provider_lock);
7884         mutex_enter(&dtrace_lock);
7885
7886         /*
7887          * If there is at least one provider registered, we'll add this
7888          * provider after the first provider.
7889          */
7890         if (dtrace_provider != NULL) {
7891                 provider->dtpv_next = dtrace_provider->dtpv_next;
7892                 dtrace_provider->dtpv_next = provider;
7893         } else {
7894                 dtrace_provider = provider;
7895         }
7896
7897         if (dtrace_retained != NULL) {
7898                 dtrace_enabling_provide(provider);
7899
7900                 /*
7901                  * Now we need to call dtrace_enabling_matchall() -- which
7902                  * will acquire cpu_lock and dtrace_lock.  We therefore need
7903                  * to drop all of our locks before calling into it...
7904                  */
7905                 mutex_exit(&dtrace_lock);
7906                 mutex_exit(&dtrace_provider_lock);
7907                 dtrace_enabling_matchall();
7908
7909                 return (0);
7910         }
7911
7912         mutex_exit(&dtrace_lock);
7913         mutex_exit(&dtrace_provider_lock);
7914
7915         return (0);
7916 }
7917
7918 /*
7919  * Unregister the specified provider from the DTrace framework.  This should
7920  * generally be called by DTrace providers in their detach(9E) entry point.
7921  */
7922 int
7923 dtrace_unregister(dtrace_provider_id_t id)
7924 {
7925         dtrace_provider_t *old = (dtrace_provider_t *)id;
7926         dtrace_provider_t *prev = NULL;
7927         int i, self = 0, noreap = 0;
7928         dtrace_probe_t *probe, *first = NULL;
7929
7930         if (old->dtpv_pops.dtps_enable ==
7931             (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
7932                 /*
7933                  * If DTrace itself is the provider, we're called with locks
7934                  * already held.
7935                  */
7936                 ASSERT(old == dtrace_provider);
7937 #if defined(sun)
7938                 ASSERT(dtrace_devi != NULL);
7939 #endif
7940                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7941                 ASSERT(MUTEX_HELD(&dtrace_lock));
7942                 self = 1;
7943
7944                 if (dtrace_provider->dtpv_next != NULL) {
7945                         /*
7946                          * There's another provider here; return failure.
7947                          */
7948                         return (EBUSY);
7949                 }
7950         } else {
7951                 mutex_enter(&dtrace_provider_lock);
7952 #if defined(sun)
7953                 mutex_enter(&mod_lock);
7954 #endif
7955                 mutex_enter(&dtrace_lock);
7956         }
7957
7958         /*
7959          * If anyone has /dev/dtrace open, or if there are anonymous enabled
7960          * probes, we refuse to let providers slither away, unless this
7961          * provider has already been explicitly invalidated.
7962          */
7963         if (!old->dtpv_defunct &&
7964             (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7965             dtrace_anon.dta_state->dts_necbs > 0))) {
7966                 if (!self) {
7967                         mutex_exit(&dtrace_lock);
7968 #if defined(sun)
7969                         mutex_exit(&mod_lock);
7970 #endif
7971                         mutex_exit(&dtrace_provider_lock);
7972                 }
7973                 return (EBUSY);
7974         }
7975
7976         /*
7977          * Attempt to destroy the probes associated with this provider.
7978          */
7979         for (i = 0; i < dtrace_nprobes; i++) {
7980                 if ((probe = dtrace_probes[i]) == NULL)
7981                         continue;
7982
7983                 if (probe->dtpr_provider != old)
7984                         continue;
7985
7986                 if (probe->dtpr_ecb == NULL)
7987                         continue;
7988
7989                 /*
7990                  * If we are trying to unregister a defunct provider, and the
7991                  * provider was made defunct within the interval dictated by
7992                  * dtrace_unregister_defunct_reap, we'll (asynchronously)
7993                  * attempt to reap our enablings.  To denote that the provider
7994                  * should reattempt to unregister itself at some point in the
7995                  * future, we will return a differentiable error code (EAGAIN
7996                  * instead of EBUSY) in this case.
7997                  */
7998                 if (dtrace_gethrtime() - old->dtpv_defunct >
7999                     dtrace_unregister_defunct_reap)
8000                         noreap = 1;
8001
8002                 if (!self) {
8003                         mutex_exit(&dtrace_lock);
8004 #if defined(sun)
8005                         mutex_exit(&mod_lock);
8006 #endif
8007                         mutex_exit(&dtrace_provider_lock);
8008                 }
8009
8010                 if (noreap)
8011                         return (EBUSY);
8012
8013                 (void) taskq_dispatch(dtrace_taskq,
8014                     (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8015
8016                 return (EAGAIN);
8017         }
8018
8019         /*
8020          * All of the probes for this provider are disabled; we can safely
8021          * remove all of them from their hash chains and from the probe array.
8022          */
8023         for (i = 0; i < dtrace_nprobes; i++) {
8024                 if ((probe = dtrace_probes[i]) == NULL)
8025                         continue;
8026
8027                 if (probe->dtpr_provider != old)
8028                         continue;
8029
8030                 dtrace_probes[i] = NULL;
8031
8032                 dtrace_hash_remove(dtrace_bymod, probe);
8033                 dtrace_hash_remove(dtrace_byfunc, probe);
8034                 dtrace_hash_remove(dtrace_byname, probe);
8035
8036                 if (first == NULL) {
8037                         first = probe;
8038                         probe->dtpr_nextmod = NULL;
8039                 } else {
8040                         probe->dtpr_nextmod = first;
8041                         first = probe;
8042                 }
8043         }
8044
8045         /*
8046          * The provider's probes have been removed from the hash chains and
8047          * from the probe array.  Now issue a dtrace_sync() to be sure that
8048          * everyone has cleared out from any probe array processing.
8049          */
8050         dtrace_sync();
8051
8052         for (probe = first; probe != NULL; probe = first) {
8053                 first = probe->dtpr_nextmod;
8054
8055                 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8056                     probe->dtpr_arg);
8057                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8058                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8059                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8060 #if defined(sun)
8061                 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8062 #else
8063                 free_unr(dtrace_arena, probe->dtpr_id);
8064 #endif
8065                 kmem_free(probe, sizeof (dtrace_probe_t));
8066         }
8067
8068         if ((prev = dtrace_provider) == old) {
8069 #if defined(sun)
8070                 ASSERT(self || dtrace_devi == NULL);
8071                 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8072 #endif
8073                 dtrace_provider = old->dtpv_next;
8074         } else {
8075                 while (prev != NULL && prev->dtpv_next != old)
8076                         prev = prev->dtpv_next;
8077
8078                 if (prev == NULL) {
8079                         panic("attempt to unregister non-existent "
8080                             "dtrace provider %p\n", (void *)id);
8081                 }
8082
8083                 prev->dtpv_next = old->dtpv_next;
8084         }
8085
8086         if (!self) {
8087                 mutex_exit(&dtrace_lock);
8088 #if defined(sun)
8089                 mutex_exit(&mod_lock);
8090 #endif
8091                 mutex_exit(&dtrace_provider_lock);
8092         }
8093
8094         kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8095         kmem_free(old, sizeof (dtrace_provider_t));
8096
8097         return (0);
8098 }
8099
8100 /*
8101  * Invalidate the specified provider.  All subsequent probe lookups for the
8102  * specified provider will fail, but its probes will not be removed.
8103  */
8104 void
8105 dtrace_invalidate(dtrace_provider_id_t id)
8106 {
8107         dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8108
8109         ASSERT(pvp->dtpv_pops.dtps_enable !=
8110             (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8111
8112         mutex_enter(&dtrace_provider_lock);
8113         mutex_enter(&dtrace_lock);
8114
8115         pvp->dtpv_defunct = dtrace_gethrtime();
8116
8117         mutex_exit(&dtrace_lock);
8118         mutex_exit(&dtrace_provider_lock);
8119 }
8120
8121 /*
8122  * Indicate whether or not DTrace has attached.
8123  */
8124 int
8125 dtrace_attached(void)
8126 {
8127         /*
8128          * dtrace_provider will be non-NULL iff the DTrace driver has
8129          * attached.  (It's non-NULL because DTrace is always itself a
8130          * provider.)
8131          */
8132         return (dtrace_provider != NULL);
8133 }
8134
8135 /*
8136  * Remove all the unenabled probes for the given provider.  This function is
8137  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8138  * -- just as many of its associated probes as it can.
8139  */
8140 int
8141 dtrace_condense(dtrace_provider_id_t id)
8142 {
8143         dtrace_provider_t *prov = (dtrace_provider_t *)id;
8144         int i;
8145         dtrace_probe_t *probe;
8146
8147         /*
8148          * Make sure this isn't the dtrace provider itself.
8149          */
8150         ASSERT(prov->dtpv_pops.dtps_enable !=
8151             (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
8152
8153         mutex_enter(&dtrace_provider_lock);
8154         mutex_enter(&dtrace_lock);
8155
8156         /*
8157          * Attempt to destroy the probes associated with this provider.
8158          */
8159         for (i = 0; i < dtrace_nprobes; i++) {
8160                 if ((probe = dtrace_probes[i]) == NULL)
8161                         continue;
8162
8163                 if (probe->dtpr_provider != prov)
8164                         continue;
8165
8166                 if (probe->dtpr_ecb != NULL)
8167                         continue;
8168
8169                 dtrace_probes[i] = NULL;
8170
8171                 dtrace_hash_remove(dtrace_bymod, probe);
8172                 dtrace_hash_remove(dtrace_byfunc, probe);
8173                 dtrace_hash_remove(dtrace_byname, probe);
8174
8175                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8176                     probe->dtpr_arg);
8177                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8178                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8179                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8180                 kmem_free(probe, sizeof (dtrace_probe_t));
8181 #if defined(sun)
8182                 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8183 #else
8184                 free_unr(dtrace_arena, i + 1);
8185 #endif
8186         }
8187
8188         mutex_exit(&dtrace_lock);
8189         mutex_exit(&dtrace_provider_lock);
8190
8191         return (0);
8192 }
8193
8194 /*
8195  * DTrace Probe Management Functions
8196  *
8197  * The functions in this section perform the DTrace probe management,
8198  * including functions to create probes, look-up probes, and call into the
8199  * providers to request that probes be provided.  Some of these functions are
8200  * in the Provider-to-Framework API; these functions can be identified by the
8201  * fact that they are not declared "static".
8202  */
8203
8204 /*
8205  * Create a probe with the specified module name, function name, and name.
8206  */
8207 dtrace_id_t
8208 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8209     const char *func, const char *name, int aframes, void *arg)
8210 {
8211         dtrace_probe_t *probe, **probes;
8212         dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8213         dtrace_id_t id;
8214
8215         if (provider == dtrace_provider) {
8216                 ASSERT(MUTEX_HELD(&dtrace_lock));
8217         } else {
8218                 mutex_enter(&dtrace_lock);
8219         }
8220
8221 #if defined(sun)
8222         id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8223             VM_BESTFIT | VM_SLEEP);
8224 #else
8225         id = alloc_unr(dtrace_arena);
8226 #endif
8227         probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8228
8229         probe->dtpr_id = id;
8230         probe->dtpr_gen = dtrace_probegen++;
8231         probe->dtpr_mod = dtrace_strdup(mod);
8232         probe->dtpr_func = dtrace_strdup(func);
8233         probe->dtpr_name = dtrace_strdup(name);
8234         probe->dtpr_arg = arg;
8235         probe->dtpr_aframes = aframes;
8236         probe->dtpr_provider = provider;
8237
8238         dtrace_hash_add(dtrace_bymod, probe);
8239         dtrace_hash_add(dtrace_byfunc, probe);
8240         dtrace_hash_add(dtrace_byname, probe);
8241
8242         if (id - 1 >= dtrace_nprobes) {
8243                 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8244                 size_t nsize = osize << 1;
8245
8246                 if (nsize == 0) {
8247                         ASSERT(osize == 0);
8248                         ASSERT(dtrace_probes == NULL);
8249                         nsize = sizeof (dtrace_probe_t *);
8250                 }
8251
8252                 probes = kmem_zalloc(nsize, KM_SLEEP);
8253
8254                 if (dtrace_probes == NULL) {
8255                         ASSERT(osize == 0);
8256                         dtrace_probes = probes;
8257                         dtrace_nprobes = 1;
8258                 } else {
8259                         dtrace_probe_t **oprobes = dtrace_probes;
8260
8261                         bcopy(oprobes, probes, osize);
8262                         dtrace_membar_producer();
8263                         dtrace_probes = probes;
8264
8265                         dtrace_sync();
8266
8267                         /*
8268                          * All CPUs are now seeing the new probes array; we can
8269                          * safely free the old array.
8270                          */
8271                         kmem_free(oprobes, osize);
8272                         dtrace_nprobes <<= 1;
8273                 }
8274
8275                 ASSERT(id - 1 < dtrace_nprobes);
8276         }
8277
8278         ASSERT(dtrace_probes[id - 1] == NULL);
8279         dtrace_probes[id - 1] = probe;
8280
8281         if (provider != dtrace_provider)
8282                 mutex_exit(&dtrace_lock);
8283
8284         return (id);
8285 }
8286
8287 static dtrace_probe_t *
8288 dtrace_probe_lookup_id(dtrace_id_t id)
8289 {
8290         ASSERT(MUTEX_HELD(&dtrace_lock));
8291
8292         if (id == 0 || id > dtrace_nprobes)
8293                 return (NULL);
8294
8295         return (dtrace_probes[id - 1]);
8296 }
8297
8298 static int
8299 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8300 {
8301         *((dtrace_id_t *)arg) = probe->dtpr_id;
8302
8303         return (DTRACE_MATCH_DONE);
8304 }
8305
8306 /*
8307  * Look up a probe based on provider and one or more of module name, function
8308  * name and probe name.
8309  */
8310 dtrace_id_t
8311 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
8312     char *func, char *name)
8313 {
8314         dtrace_probekey_t pkey;
8315         dtrace_id_t id;
8316         int match;
8317
8318         pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8319         pkey.dtpk_pmatch = &dtrace_match_string;
8320         pkey.dtpk_mod = mod;
8321         pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8322         pkey.dtpk_func = func;
8323         pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8324         pkey.dtpk_name = name;
8325         pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8326         pkey.dtpk_id = DTRACE_IDNONE;
8327
8328         mutex_enter(&dtrace_lock);
8329         match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8330             dtrace_probe_lookup_match, &id);
8331         mutex_exit(&dtrace_lock);
8332
8333         ASSERT(match == 1 || match == 0);
8334         return (match ? id : 0);
8335 }
8336
8337 /*
8338  * Returns the probe argument associated with the specified probe.
8339  */
8340 void *
8341 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8342 {
8343         dtrace_probe_t *probe;
8344         void *rval = NULL;
8345
8346         mutex_enter(&dtrace_lock);
8347
8348         if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8349             probe->dtpr_provider == (dtrace_provider_t *)id)
8350                 rval = probe->dtpr_arg;
8351
8352         mutex_exit(&dtrace_lock);
8353
8354         return (rval);
8355 }
8356
8357 /*
8358  * Copy a probe into a probe description.
8359  */
8360 static void
8361 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8362 {
8363         bzero(pdp, sizeof (dtrace_probedesc_t));
8364         pdp->dtpd_id = prp->dtpr_id;
8365
8366         (void) strncpy(pdp->dtpd_provider,
8367             prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8368
8369         (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8370         (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8371         (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8372 }
8373
8374 /*
8375  * Called to indicate that a probe -- or probes -- should be provided by a
8376  * specfied provider.  If the specified description is NULL, the provider will
8377  * be told to provide all of its probes.  (This is done whenever a new
8378  * consumer comes along, or whenever a retained enabling is to be matched.) If
8379  * the specified description is non-NULL, the provider is given the
8380  * opportunity to dynamically provide the specified probe, allowing providers
8381  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8382  * probes.)  If the provider is NULL, the operations will be applied to all
8383  * providers; if the provider is non-NULL the operations will only be applied
8384  * to the specified provider.  The dtrace_provider_lock must be held, and the
8385  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8386  * will need to grab the dtrace_lock when it reenters the framework through
8387  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8388  */
8389 static void
8390 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8391 {
8392 #if defined(sun)
8393         modctl_t *ctl;
8394 #endif
8395         int all = 0;
8396
8397         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8398
8399         if (prv == NULL) {
8400                 all = 1;
8401                 prv = dtrace_provider;
8402         }
8403
8404         do {
8405                 /*
8406                  * First, call the blanket provide operation.
8407                  */
8408                 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8409
8410 #if defined(sun)
8411                 /*
8412                  * Now call the per-module provide operation.  We will grab
8413                  * mod_lock to prevent the list from being modified.  Note
8414                  * that this also prevents the mod_busy bits from changing.
8415                  * (mod_busy can only be changed with mod_lock held.)
8416                  */
8417                 mutex_enter(&mod_lock);
8418
8419                 ctl = &modules;
8420                 do {
8421                         if (ctl->mod_busy || ctl->mod_mp == NULL)
8422                                 continue;
8423
8424                         prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8425
8426                 } while ((ctl = ctl->mod_next) != &modules);
8427
8428                 mutex_exit(&mod_lock);
8429 #endif
8430         } while (all && (prv = prv->dtpv_next) != NULL);
8431 }
8432
8433 #if defined(sun)
8434 /*
8435  * Iterate over each probe, and call the Framework-to-Provider API function
8436  * denoted by offs.
8437  */
8438 static void
8439 dtrace_probe_foreach(uintptr_t offs)
8440 {
8441         dtrace_provider_t *prov;
8442         void (*func)(void *, dtrace_id_t, void *);
8443         dtrace_probe_t *probe;
8444         dtrace_icookie_t cookie;
8445         int i;
8446
8447         /*
8448          * We disable interrupts to walk through the probe array.  This is
8449          * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8450          * won't see stale data.
8451          */
8452         cookie = dtrace_interrupt_disable();
8453
8454         for (i = 0; i < dtrace_nprobes; i++) {
8455                 if ((probe = dtrace_probes[i]) == NULL)
8456                         continue;
8457
8458                 if (probe->dtpr_ecb == NULL) {
8459                         /*
8460                          * This probe isn't enabled -- don't call the function.
8461                          */
8462                         continue;
8463                 }
8464
8465                 prov = probe->dtpr_provider;
8466                 func = *((void(**)(void *, dtrace_id_t, void *))
8467                     ((uintptr_t)&prov->dtpv_pops + offs));
8468
8469                 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8470         }
8471
8472         dtrace_interrupt_enable(cookie);
8473 }
8474 #endif
8475
8476 static int
8477 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8478 {
8479         dtrace_probekey_t pkey;
8480         uint32_t priv;
8481         uid_t uid;
8482         zoneid_t zoneid;
8483
8484         ASSERT(MUTEX_HELD(&dtrace_lock));
8485         dtrace_ecb_create_cache = NULL;
8486
8487         if (desc == NULL) {
8488                 /*
8489                  * If we're passed a NULL description, we're being asked to
8490                  * create an ECB with a NULL probe.
8491                  */
8492                 (void) dtrace_ecb_create_enable(NULL, enab);
8493                 return (0);
8494         }
8495
8496         dtrace_probekey(desc, &pkey);
8497         dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8498             &priv, &uid, &zoneid);
8499
8500         return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8501             enab));
8502 }
8503
8504 /*
8505  * DTrace Helper Provider Functions
8506  */
8507 static void
8508 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8509 {
8510         attr->dtat_name = DOF_ATTR_NAME(dofattr);
8511         attr->dtat_data = DOF_ATTR_DATA(dofattr);
8512         attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8513 }
8514
8515 static void
8516 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8517     const dof_provider_t *dofprov, char *strtab)
8518 {
8519         hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8520         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8521             dofprov->dofpv_provattr);
8522         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8523             dofprov->dofpv_modattr);
8524         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8525             dofprov->dofpv_funcattr);
8526         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8527             dofprov->dofpv_nameattr);
8528         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8529             dofprov->dofpv_argsattr);
8530 }
8531
8532 static void
8533 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8534 {
8535         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8536         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8537         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8538         dof_provider_t *provider;
8539         dof_probe_t *probe;
8540         uint32_t *off, *enoff;
8541         uint8_t *arg;
8542         char *strtab;
8543         uint_t i, nprobes;
8544         dtrace_helper_provdesc_t dhpv;
8545         dtrace_helper_probedesc_t dhpb;
8546         dtrace_meta_t *meta = dtrace_meta_pid;
8547         dtrace_mops_t *mops = &meta->dtm_mops;
8548         void *parg;
8549
8550         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8551         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8552             provider->dofpv_strtab * dof->dofh_secsize);
8553         prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8554             provider->dofpv_probes * dof->dofh_secsize);
8555         arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8556             provider->dofpv_prargs * dof->dofh_secsize);
8557         off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8558             provider->dofpv_proffs * dof->dofh_secsize);
8559
8560         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8561         off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8562         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8563         enoff = NULL;
8564
8565         /*
8566          * See dtrace_helper_provider_validate().
8567          */
8568         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8569             provider->dofpv_prenoffs != DOF_SECT_NONE) {
8570                 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8571                     provider->dofpv_prenoffs * dof->dofh_secsize);
8572                 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8573         }
8574
8575         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8576
8577         /*
8578          * Create the provider.
8579          */
8580         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8581
8582         if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8583                 return;
8584
8585         meta->dtm_count++;
8586
8587         /*
8588          * Create the probes.
8589          */
8590         for (i = 0; i < nprobes; i++) {
8591                 probe = (dof_probe_t *)(uintptr_t)(daddr +
8592                     prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8593
8594                 dhpb.dthpb_mod = dhp->dofhp_mod;
8595                 dhpb.dthpb_func = strtab + probe->dofpr_func;
8596                 dhpb.dthpb_name = strtab + probe->dofpr_name;
8597                 dhpb.dthpb_base = probe->dofpr_addr;
8598                 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8599                 dhpb.dthpb_noffs = probe->dofpr_noffs;
8600                 if (enoff != NULL) {
8601                         dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8602                         dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8603                 } else {
8604                         dhpb.dthpb_enoffs = NULL;
8605                         dhpb.dthpb_nenoffs = 0;
8606                 }
8607                 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8608                 dhpb.dthpb_nargc = probe->dofpr_nargc;
8609                 dhpb.dthpb_xargc = probe->dofpr_xargc;
8610                 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8611                 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8612
8613                 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8614         }
8615 }
8616
8617 static void
8618 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8619 {
8620         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8621         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8622         int i;
8623
8624         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8625
8626         for (i = 0; i < dof->dofh_secnum; i++) {
8627                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8628                     dof->dofh_secoff + i * dof->dofh_secsize);
8629
8630                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8631                         continue;
8632
8633                 dtrace_helper_provide_one(dhp, sec, pid);
8634         }
8635
8636         /*
8637          * We may have just created probes, so we must now rematch against
8638          * any retained enablings.  Note that this call will acquire both
8639          * cpu_lock and dtrace_lock; the fact that we are holding
8640          * dtrace_meta_lock now is what defines the ordering with respect to
8641          * these three locks.
8642          */
8643         dtrace_enabling_matchall();
8644 }
8645
8646 static void
8647 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8648 {
8649         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8650         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8651         dof_sec_t *str_sec;
8652         dof_provider_t *provider;
8653         char *strtab;
8654         dtrace_helper_provdesc_t dhpv;
8655         dtrace_meta_t *meta = dtrace_meta_pid;
8656         dtrace_mops_t *mops = &meta->dtm_mops;
8657
8658         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8659         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8660             provider->dofpv_strtab * dof->dofh_secsize);
8661
8662         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8663
8664         /*
8665          * Create the provider.
8666          */
8667         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8668
8669         mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8670
8671         meta->dtm_count--;
8672 }
8673
8674 static void
8675 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8676 {
8677         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8678         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8679         int i;
8680
8681         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8682
8683         for (i = 0; i < dof->dofh_secnum; i++) {
8684                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8685                     dof->dofh_secoff + i * dof->dofh_secsize);
8686
8687                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8688                         continue;
8689
8690                 dtrace_helper_provider_remove_one(dhp, sec, pid);
8691         }
8692 }
8693
8694 /*
8695  * DTrace Meta Provider-to-Framework API Functions
8696  *
8697  * These functions implement the Meta Provider-to-Framework API, as described
8698  * in <sys/dtrace.h>.
8699  */
8700 int
8701 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8702     dtrace_meta_provider_id_t *idp)
8703 {
8704         dtrace_meta_t *meta;
8705         dtrace_helpers_t *help, *next;
8706         int i;
8707
8708         *idp = DTRACE_METAPROVNONE;
8709
8710         /*
8711          * We strictly don't need the name, but we hold onto it for
8712          * debuggability. All hail error queues!
8713          */
8714         if (name == NULL) {
8715                 cmn_err(CE_WARN, "failed to register meta-provider: "
8716                     "invalid name");
8717                 return (EINVAL);
8718         }
8719
8720         if (mops == NULL ||
8721             mops->dtms_create_probe == NULL ||
8722             mops->dtms_provide_pid == NULL ||
8723             mops->dtms_remove_pid == NULL) {
8724                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8725                     "invalid ops", name);
8726                 return (EINVAL);
8727         }
8728
8729         meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8730         meta->dtm_mops = *mops;
8731         meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8732         (void) strcpy(meta->dtm_name, name);
8733         meta->dtm_arg = arg;
8734
8735         mutex_enter(&dtrace_meta_lock);
8736         mutex_enter(&dtrace_lock);
8737
8738         if (dtrace_meta_pid != NULL) {
8739                 mutex_exit(&dtrace_lock);
8740                 mutex_exit(&dtrace_meta_lock);
8741                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8742                     "user-land meta-provider exists", name);
8743                 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8744                 kmem_free(meta, sizeof (dtrace_meta_t));
8745                 return (EINVAL);
8746         }
8747
8748         dtrace_meta_pid = meta;
8749         *idp = (dtrace_meta_provider_id_t)meta;
8750
8751         /*
8752          * If there are providers and probes ready to go, pass them
8753          * off to the new meta provider now.
8754          */
8755
8756         help = dtrace_deferred_pid;
8757         dtrace_deferred_pid = NULL;
8758
8759         mutex_exit(&dtrace_lock);
8760
8761         while (help != NULL) {
8762                 for (i = 0; i < help->dthps_nprovs; i++) {
8763                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8764                             help->dthps_pid);
8765                 }
8766
8767                 next = help->dthps_next;
8768                 help->dthps_next = NULL;
8769                 help->dthps_prev = NULL;
8770                 help->dthps_deferred = 0;
8771                 help = next;
8772         }
8773
8774         mutex_exit(&dtrace_meta_lock);
8775
8776         return (0);
8777 }
8778
8779 int
8780 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8781 {
8782         dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8783
8784         mutex_enter(&dtrace_meta_lock);
8785         mutex_enter(&dtrace_lock);
8786
8787         if (old == dtrace_meta_pid) {
8788                 pp = &dtrace_meta_pid;
8789         } else {
8790                 panic("attempt to unregister non-existent "
8791                     "dtrace meta-provider %p\n", (void *)old);
8792         }
8793
8794         if (old->dtm_count != 0) {
8795                 mutex_exit(&dtrace_lock);
8796                 mutex_exit(&dtrace_meta_lock);
8797                 return (EBUSY);
8798         }
8799
8800         *pp = NULL;
8801
8802         mutex_exit(&dtrace_lock);
8803         mutex_exit(&dtrace_meta_lock);
8804
8805         kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8806         kmem_free(old, sizeof (dtrace_meta_t));
8807
8808         return (0);
8809 }
8810
8811
8812 /*
8813  * DTrace DIF Object Functions
8814  */
8815 static int
8816 dtrace_difo_err(uint_t pc, const char *format, ...)
8817 {
8818         if (dtrace_err_verbose) {
8819                 va_list alist;
8820
8821                 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8822                 va_start(alist, format);
8823                 (void) vuprintf(format, alist);
8824                 va_end(alist);
8825         }
8826
8827 #ifdef DTRACE_ERRDEBUG
8828         dtrace_errdebug(format);
8829 #endif
8830         return (1);
8831 }
8832
8833 /*
8834  * Validate a DTrace DIF object by checking the IR instructions.  The following
8835  * rules are currently enforced by dtrace_difo_validate():
8836  *
8837  * 1. Each instruction must have a valid opcode
8838  * 2. Each register, string, variable, or subroutine reference must be valid
8839  * 3. No instruction can modify register %r0 (must be zero)
8840  * 4. All instruction reserved bits must be set to zero
8841  * 5. The last instruction must be a "ret" instruction
8842  * 6. All branch targets must reference a valid instruction _after_ the branch
8843  */
8844 static int
8845 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8846     cred_t *cr)
8847 {
8848         int err = 0, i;
8849         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8850         int kcheckload;
8851         uint_t pc;
8852
8853         kcheckload = cr == NULL ||
8854             (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8855
8856         dp->dtdo_destructive = 0;
8857
8858         for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8859                 dif_instr_t instr = dp->dtdo_buf[pc];
8860
8861                 uint_t r1 = DIF_INSTR_R1(instr);
8862                 uint_t r2 = DIF_INSTR_R2(instr);
8863                 uint_t rd = DIF_INSTR_RD(instr);
8864                 uint_t rs = DIF_INSTR_RS(instr);
8865                 uint_t label = DIF_INSTR_LABEL(instr);
8866                 uint_t v = DIF_INSTR_VAR(instr);
8867                 uint_t subr = DIF_INSTR_SUBR(instr);
8868                 uint_t type = DIF_INSTR_TYPE(instr);
8869                 uint_t op = DIF_INSTR_OP(instr);
8870
8871                 switch (op) {
8872                 case DIF_OP_OR:
8873                 case DIF_OP_XOR:
8874                 case DIF_OP_AND:
8875                 case DIF_OP_SLL:
8876                 case DIF_OP_SRL:
8877                 case DIF_OP_SRA:
8878                 case DIF_OP_SUB:
8879                 case DIF_OP_ADD:
8880                 case DIF_OP_MUL:
8881                 case DIF_OP_SDIV:
8882                 case DIF_OP_UDIV:
8883                 case DIF_OP_SREM:
8884                 case DIF_OP_UREM:
8885                 case DIF_OP_COPYS:
8886                         if (r1 >= nregs)
8887                                 err += efunc(pc, "invalid register %u\n", r1);
8888                         if (r2 >= nregs)
8889                                 err += efunc(pc, "invalid register %u\n", r2);
8890                         if (rd >= nregs)
8891                                 err += efunc(pc, "invalid register %u\n", rd);
8892                         if (rd == 0)
8893                                 err += efunc(pc, "cannot write to %r0\n");
8894                         break;
8895                 case DIF_OP_NOT:
8896                 case DIF_OP_MOV:
8897                 case DIF_OP_ALLOCS:
8898                         if (r1 >= nregs)
8899                                 err += efunc(pc, "invalid register %u\n", r1);
8900                         if (r2 != 0)
8901                                 err += efunc(pc, "non-zero reserved bits\n");
8902                         if (rd >= nregs)
8903                                 err += efunc(pc, "invalid register %u\n", rd);
8904                         if (rd == 0)
8905                                 err += efunc(pc, "cannot write to %r0\n");
8906                         break;
8907                 case DIF_OP_LDSB:
8908                 case DIF_OP_LDSH:
8909                 case DIF_OP_LDSW:
8910                 case DIF_OP_LDUB:
8911                 case DIF_OP_LDUH:
8912                 case DIF_OP_LDUW:
8913                 case DIF_OP_LDX:
8914                         if (r1 >= nregs)
8915                                 err += efunc(pc, "invalid register %u\n", r1);
8916                         if (r2 != 0)
8917                                 err += efunc(pc, "non-zero reserved bits\n");
8918                         if (rd >= nregs)
8919                                 err += efunc(pc, "invalid register %u\n", rd);
8920                         if (rd == 0)
8921                                 err += efunc(pc, "cannot write to %r0\n");
8922                         if (kcheckload)
8923                                 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8924                                     DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8925                         break;
8926                 case DIF_OP_RLDSB:
8927                 case DIF_OP_RLDSH:
8928                 case DIF_OP_RLDSW:
8929                 case DIF_OP_RLDUB:
8930                 case DIF_OP_RLDUH:
8931                 case DIF_OP_RLDUW:
8932                 case DIF_OP_RLDX:
8933                         if (r1 >= nregs)
8934                                 err += efunc(pc, "invalid register %u\n", r1);
8935                         if (r2 != 0)
8936                                 err += efunc(pc, "non-zero reserved bits\n");
8937                         if (rd >= nregs)
8938                                 err += efunc(pc, "invalid register %u\n", rd);
8939                         if (rd == 0)
8940                                 err += efunc(pc, "cannot write to %r0\n");
8941                         break;
8942                 case DIF_OP_ULDSB:
8943                 case DIF_OP_ULDSH:
8944                 case DIF_OP_ULDSW:
8945                 case DIF_OP_ULDUB:
8946                 case DIF_OP_ULDUH:
8947                 case DIF_OP_ULDUW:
8948                 case DIF_OP_ULDX:
8949                         if (r1 >= nregs)
8950                                 err += efunc(pc, "invalid register %u\n", r1);
8951                         if (r2 != 0)
8952                                 err += efunc(pc, "non-zero reserved bits\n");
8953                         if (rd >= nregs)
8954                                 err += efunc(pc, "invalid register %u\n", rd);
8955                         if (rd == 0)
8956                                 err += efunc(pc, "cannot write to %r0\n");
8957                         break;
8958                 case DIF_OP_STB:
8959                 case DIF_OP_STH:
8960                 case DIF_OP_STW:
8961                 case DIF_OP_STX:
8962                         if (r1 >= nregs)
8963                                 err += efunc(pc, "invalid register %u\n", r1);
8964                         if (r2 != 0)
8965                                 err += efunc(pc, "non-zero reserved bits\n");
8966                         if (rd >= nregs)
8967                                 err += efunc(pc, "invalid register %u\n", rd);
8968                         if (rd == 0)
8969                                 err += efunc(pc, "cannot write to 0 address\n");
8970                         break;
8971                 case DIF_OP_CMP:
8972                 case DIF_OP_SCMP:
8973                         if (r1 >= nregs)
8974                                 err += efunc(pc, "invalid register %u\n", r1);
8975                         if (r2 >= nregs)
8976                                 err += efunc(pc, "invalid register %u\n", r2);
8977                         if (rd != 0)
8978                                 err += efunc(pc, "non-zero reserved bits\n");
8979                         break;
8980                 case DIF_OP_TST:
8981                         if (r1 >= nregs)
8982                                 err += efunc(pc, "invalid register %u\n", r1);
8983                         if (r2 != 0 || rd != 0)
8984                                 err += efunc(pc, "non-zero reserved bits\n");
8985                         break;
8986                 case DIF_OP_BA:
8987                 case DIF_OP_BE:
8988                 case DIF_OP_BNE:
8989                 case DIF_OP_BG:
8990                 case DIF_OP_BGU:
8991                 case DIF_OP_BGE:
8992                 case DIF_OP_BGEU:
8993                 case DIF_OP_BL:
8994                 case DIF_OP_BLU:
8995                 case DIF_OP_BLE:
8996                 case DIF_OP_BLEU:
8997                         if (label >= dp->dtdo_len) {
8998                                 err += efunc(pc, "invalid branch target %u\n",
8999                                     label);
9000                         }
9001                         if (label <= pc) {
9002                                 err += efunc(pc, "backward branch to %u\n",
9003                                     label);
9004                         }
9005                         break;
9006                 case DIF_OP_RET:
9007                         if (r1 != 0 || r2 != 0)
9008                                 err += efunc(pc, "non-zero reserved bits\n");
9009                         if (rd >= nregs)
9010                                 err += efunc(pc, "invalid register %u\n", rd);
9011                         break;
9012                 case DIF_OP_NOP:
9013                 case DIF_OP_POPTS:
9014                 case DIF_OP_FLUSHTS:
9015                         if (r1 != 0 || r2 != 0 || rd != 0)
9016                                 err += efunc(pc, "non-zero reserved bits\n");
9017                         break;
9018                 case DIF_OP_SETX:
9019                         if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9020                                 err += efunc(pc, "invalid integer ref %u\n",
9021                                     DIF_INSTR_INTEGER(instr));
9022                         }
9023                         if (rd >= nregs)
9024                                 err += efunc(pc, "invalid register %u\n", rd);
9025                         if (rd == 0)
9026                                 err += efunc(pc, "cannot write to %r0\n");
9027                         break;
9028                 case DIF_OP_SETS:
9029                         if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9030                                 err += efunc(pc, "invalid string ref %u\n",
9031                                     DIF_INSTR_STRING(instr));
9032                         }
9033                         if (rd >= nregs)
9034                                 err += efunc(pc, "invalid register %u\n", rd);
9035                         if (rd == 0)
9036                                 err += efunc(pc, "cannot write to %r0\n");
9037                         break;
9038                 case DIF_OP_LDGA:
9039                 case DIF_OP_LDTA:
9040                         if (r1 > DIF_VAR_ARRAY_MAX)
9041                                 err += efunc(pc, "invalid array %u\n", r1);
9042                         if (r2 >= nregs)
9043                                 err += efunc(pc, "invalid register %u\n", r2);
9044                         if (rd >= nregs)
9045                                 err += efunc(pc, "invalid register %u\n", rd);
9046                         if (rd == 0)
9047                                 err += efunc(pc, "cannot write to %r0\n");
9048                         break;
9049                 case DIF_OP_LDGS:
9050                 case DIF_OP_LDTS:
9051                 case DIF_OP_LDLS:
9052                 case DIF_OP_LDGAA:
9053                 case DIF_OP_LDTAA:
9054                         if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9055                                 err += efunc(pc, "invalid variable %u\n", v);
9056                         if (rd >= nregs)
9057                                 err += efunc(pc, "invalid register %u\n", rd);
9058                         if (rd == 0)
9059                                 err += efunc(pc, "cannot write to %r0\n");
9060                         break;
9061                 case DIF_OP_STGS:
9062                 case DIF_OP_STTS:
9063                 case DIF_OP_STLS:
9064                 case DIF_OP_STGAA:
9065                 case DIF_OP_STTAA:
9066                         if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9067                                 err += efunc(pc, "invalid variable %u\n", v);
9068                         if (rs >= nregs)
9069                                 err += efunc(pc, "invalid register %u\n", rd);
9070                         break;
9071                 case DIF_OP_CALL:
9072                         if (subr > DIF_SUBR_MAX)
9073                                 err += efunc(pc, "invalid subr %u\n", subr);
9074                         if (rd >= nregs)
9075                                 err += efunc(pc, "invalid register %u\n", rd);
9076                         if (rd == 0)
9077                                 err += efunc(pc, "cannot write to %r0\n");
9078
9079                         if (subr == DIF_SUBR_COPYOUT ||
9080                             subr == DIF_SUBR_COPYOUTSTR) {
9081                                 dp->dtdo_destructive = 1;
9082                         }
9083
9084                         if (subr == DIF_SUBR_GETF) {
9085                                 /*
9086                                  * If we have a getf() we need to record that
9087                                  * in our state.  Note that our state can be
9088                                  * NULL if this is a helper -- but in that
9089                                  * case, the call to getf() is itself illegal,
9090                                  * and will be caught (slightly later) when
9091                                  * the helper is validated.
9092                                  */
9093                                 if (vstate->dtvs_state != NULL)
9094                                         vstate->dtvs_state->dts_getf++;
9095                         }
9096
9097                         break;
9098                 case DIF_OP_PUSHTR:
9099                         if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9100                                 err += efunc(pc, "invalid ref type %u\n", type);
9101                         if (r2 >= nregs)
9102                                 err += efunc(pc, "invalid register %u\n", r2);
9103                         if (rs >= nregs)
9104                                 err += efunc(pc, "invalid register %u\n", rs);
9105                         break;
9106                 case DIF_OP_PUSHTV:
9107                         if (type != DIF_TYPE_CTF)
9108                                 err += efunc(pc, "invalid val type %u\n", type);
9109                         if (r2 >= nregs)
9110                                 err += efunc(pc, "invalid register %u\n", r2);
9111                         if (rs >= nregs)
9112                                 err += efunc(pc, "invalid register %u\n", rs);
9113                         break;
9114                 default:
9115                         err += efunc(pc, "invalid opcode %u\n",
9116                             DIF_INSTR_OP(instr));
9117                 }
9118         }
9119
9120         if (dp->dtdo_len != 0 &&
9121             DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9122                 err += efunc(dp->dtdo_len - 1,
9123                     "expected 'ret' as last DIF instruction\n");
9124         }
9125
9126         if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
9127                 /*
9128                  * If we're not returning by reference, the size must be either
9129                  * 0 or the size of one of the base types.
9130                  */
9131                 switch (dp->dtdo_rtype.dtdt_size) {
9132                 case 0:
9133                 case sizeof (uint8_t):
9134                 case sizeof (uint16_t):
9135                 case sizeof (uint32_t):
9136                 case sizeof (uint64_t):
9137                         break;
9138
9139                 default:
9140                         err += efunc(dp->dtdo_len - 1, "bad return size");
9141                 }
9142         }
9143
9144         for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9145                 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9146                 dtrace_diftype_t *vt, *et;
9147                 uint_t id, ndx;
9148
9149                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9150                     v->dtdv_scope != DIFV_SCOPE_THREAD &&
9151                     v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9152                         err += efunc(i, "unrecognized variable scope %d\n",
9153                             v->dtdv_scope);
9154                         break;
9155                 }
9156
9157                 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9158                     v->dtdv_kind != DIFV_KIND_SCALAR) {
9159                         err += efunc(i, "unrecognized variable type %d\n",
9160                             v->dtdv_kind);
9161                         break;
9162                 }
9163
9164                 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9165                         err += efunc(i, "%d exceeds variable id limit\n", id);
9166                         break;
9167                 }
9168
9169                 if (id < DIF_VAR_OTHER_UBASE)
9170                         continue;
9171
9172                 /*
9173                  * For user-defined variables, we need to check that this
9174                  * definition is identical to any previous definition that we
9175                  * encountered.
9176                  */
9177                 ndx = id - DIF_VAR_OTHER_UBASE;
9178
9179                 switch (v->dtdv_scope) {
9180                 case DIFV_SCOPE_GLOBAL:
9181                         if (ndx < vstate->dtvs_nglobals) {
9182                                 dtrace_statvar_t *svar;
9183
9184                                 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9185                                         existing = &svar->dtsv_var;
9186                         }
9187
9188                         break;
9189
9190                 case DIFV_SCOPE_THREAD:
9191                         if (ndx < vstate->dtvs_ntlocals)
9192                                 existing = &vstate->dtvs_tlocals[ndx];
9193                         break;
9194
9195                 case DIFV_SCOPE_LOCAL:
9196                         if (ndx < vstate->dtvs_nlocals) {
9197                                 dtrace_statvar_t *svar;
9198
9199                                 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9200                                         existing = &svar->dtsv_var;
9201                         }
9202
9203                         break;
9204                 }
9205
9206                 vt = &v->dtdv_type;
9207
9208                 if (vt->dtdt_flags & DIF_TF_BYREF) {
9209                         if (vt->dtdt_size == 0) {
9210                                 err += efunc(i, "zero-sized variable\n");
9211                                 break;
9212                         }
9213
9214                         if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
9215                             vt->dtdt_size > dtrace_global_maxsize) {
9216                                 err += efunc(i, "oversized by-ref global\n");
9217                                 break;
9218                         }
9219                 }
9220
9221                 if (existing == NULL || existing->dtdv_id == 0)
9222                         continue;
9223
9224                 ASSERT(existing->dtdv_id == v->dtdv_id);
9225                 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9226
9227                 if (existing->dtdv_kind != v->dtdv_kind)
9228                         err += efunc(i, "%d changed variable kind\n", id);
9229
9230                 et = &existing->dtdv_type;
9231
9232                 if (vt->dtdt_flags != et->dtdt_flags) {
9233                         err += efunc(i, "%d changed variable type flags\n", id);
9234                         break;
9235                 }
9236
9237                 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9238                         err += efunc(i, "%d changed variable type size\n", id);
9239                         break;
9240                 }
9241         }
9242
9243         return (err);
9244 }
9245
9246 /*
9247  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9248  * are much more constrained than normal DIFOs.  Specifically, they may
9249  * not:
9250  *
9251  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9252  *    miscellaneous string routines
9253  * 2. Access DTrace variables other than the args[] array, and the
9254  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9255  * 3. Have thread-local variables.
9256  * 4. Have dynamic variables.
9257  */
9258 static int
9259 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9260 {
9261         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9262         int err = 0;
9263         uint_t pc;
9264
9265         for (pc = 0; pc < dp->dtdo_len; pc++) {
9266                 dif_instr_t instr = dp->dtdo_buf[pc];
9267
9268                 uint_t v = DIF_INSTR_VAR(instr);
9269                 uint_t subr = DIF_INSTR_SUBR(instr);
9270                 uint_t op = DIF_INSTR_OP(instr);
9271
9272                 switch (op) {
9273                 case DIF_OP_OR:
9274                 case DIF_OP_XOR:
9275                 case DIF_OP_AND:
9276                 case DIF_OP_SLL:
9277                 case DIF_OP_SRL:
9278                 case DIF_OP_SRA:
9279                 case DIF_OP_SUB:
9280                 case DIF_OP_ADD:
9281                 case DIF_OP_MUL:
9282                 case DIF_OP_SDIV:
9283                 case DIF_OP_UDIV:
9284                 case DIF_OP_SREM:
9285                 case DIF_OP_UREM:
9286                 case DIF_OP_COPYS:
9287                 case DIF_OP_NOT:
9288                 case DIF_OP_MOV:
9289                 case DIF_OP_RLDSB:
9290                 case DIF_OP_RLDSH:
9291                 case DIF_OP_RLDSW:
9292                 case DIF_OP_RLDUB:
9293                 case DIF_OP_RLDUH:
9294                 case DIF_OP_RLDUW:
9295                 case DIF_OP_RLDX:
9296                 case DIF_OP_ULDSB:
9297                 case DIF_OP_ULDSH:
9298                 case DIF_OP_ULDSW:
9299                 case DIF_OP_ULDUB:
9300                 case DIF_OP_ULDUH:
9301                 case DIF_OP_ULDUW:
9302                 case DIF_OP_ULDX:
9303                 case DIF_OP_STB:
9304                 case DIF_OP_STH:
9305                 case DIF_OP_STW:
9306                 case DIF_OP_STX:
9307                 case DIF_OP_ALLOCS:
9308                 case DIF_OP_CMP:
9309                 case DIF_OP_SCMP:
9310                 case DIF_OP_TST:
9311                 case DIF_OP_BA:
9312                 case DIF_OP_BE:
9313                 case DIF_OP_BNE:
9314                 case DIF_OP_BG:
9315                 case DIF_OP_BGU:
9316                 case DIF_OP_BGE:
9317                 case DIF_OP_BGEU:
9318                 case DIF_OP_BL:
9319                 case DIF_OP_BLU:
9320                 case DIF_OP_BLE:
9321                 case DIF_OP_BLEU:
9322                 case DIF_OP_RET:
9323                 case DIF_OP_NOP:
9324                 case DIF_OP_POPTS:
9325                 case DIF_OP_FLUSHTS:
9326                 case DIF_OP_SETX:
9327                 case DIF_OP_SETS:
9328                 case DIF_OP_LDGA:
9329                 case DIF_OP_LDLS:
9330                 case DIF_OP_STGS:
9331                 case DIF_OP_STLS:
9332                 case DIF_OP_PUSHTR:
9333                 case DIF_OP_PUSHTV:
9334                         break;
9335
9336                 case DIF_OP_LDGS:
9337                         if (v >= DIF_VAR_OTHER_UBASE)
9338                                 break;
9339
9340                         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9341                                 break;
9342
9343                         if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9344                             v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9345                             v == DIF_VAR_EXECARGS ||
9346                             v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9347                             v == DIF_VAR_UID || v == DIF_VAR_GID)
9348                                 break;
9349
9350                         err += efunc(pc, "illegal variable %u\n", v);
9351                         break;
9352
9353                 case DIF_OP_LDTA:
9354                 case DIF_OP_LDTS:
9355                 case DIF_OP_LDGAA:
9356                 case DIF_OP_LDTAA:
9357                         err += efunc(pc, "illegal dynamic variable load\n");
9358                         break;
9359
9360                 case DIF_OP_STTS:
9361                 case DIF_OP_STGAA:
9362                 case DIF_OP_STTAA:
9363                         err += efunc(pc, "illegal dynamic variable store\n");
9364                         break;
9365
9366                 case DIF_OP_CALL:
9367                         if (subr == DIF_SUBR_ALLOCA ||
9368                             subr == DIF_SUBR_BCOPY ||
9369                             subr == DIF_SUBR_COPYIN ||
9370                             subr == DIF_SUBR_COPYINTO ||
9371                             subr == DIF_SUBR_COPYINSTR ||
9372                             subr == DIF_SUBR_INDEX ||
9373                             subr == DIF_SUBR_INET_NTOA ||
9374                             subr == DIF_SUBR_INET_NTOA6 ||
9375                             subr == DIF_SUBR_INET_NTOP ||
9376                             subr == DIF_SUBR_LLTOSTR ||
9377                             subr == DIF_SUBR_RINDEX ||
9378                             subr == DIF_SUBR_STRCHR ||
9379                             subr == DIF_SUBR_STRJOIN ||
9380                             subr == DIF_SUBR_STRRCHR ||
9381                             subr == DIF_SUBR_STRSTR ||
9382                             subr == DIF_SUBR_HTONS ||
9383                             subr == DIF_SUBR_HTONL ||
9384                             subr == DIF_SUBR_HTONLL ||
9385                             subr == DIF_SUBR_NTOHS ||
9386                             subr == DIF_SUBR_NTOHL ||
9387                             subr == DIF_SUBR_NTOHLL ||
9388                             subr == DIF_SUBR_MEMREF ||
9389 #if !defined(sun)
9390                             subr == DIF_SUBR_MEMSTR ||
9391 #endif
9392                             subr == DIF_SUBR_TYPEREF)
9393                                 break;
9394
9395                         err += efunc(pc, "invalid subr %u\n", subr);
9396                         break;
9397
9398                 default:
9399                         err += efunc(pc, "invalid opcode %u\n",
9400                             DIF_INSTR_OP(instr));
9401                 }
9402         }
9403
9404         return (err);
9405 }
9406
9407 /*
9408  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9409  * basis; 0 if not.
9410  */
9411 static int
9412 dtrace_difo_cacheable(dtrace_difo_t *dp)
9413 {
9414         int i;
9415
9416         if (dp == NULL)
9417                 return (0);
9418
9419         for (i = 0; i < dp->dtdo_varlen; i++) {
9420                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9421
9422                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9423                         continue;
9424
9425                 switch (v->dtdv_id) {
9426                 case DIF_VAR_CURTHREAD:
9427                 case DIF_VAR_PID:
9428                 case DIF_VAR_TID:
9429                 case DIF_VAR_EXECARGS:
9430                 case DIF_VAR_EXECNAME:
9431                 case DIF_VAR_ZONENAME:
9432                         break;
9433
9434                 default:
9435                         return (0);
9436                 }
9437         }
9438
9439         /*
9440          * This DIF object may be cacheable.  Now we need to look for any
9441          * array loading instructions, any memory loading instructions, or
9442          * any stores to thread-local variables.
9443          */
9444         for (i = 0; i < dp->dtdo_len; i++) {
9445                 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9446
9447                 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9448                     (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9449                     (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9450                     op == DIF_OP_LDGA || op == DIF_OP_STTS)
9451                         return (0);
9452         }
9453
9454         return (1);
9455 }
9456
9457 static void
9458 dtrace_difo_hold(dtrace_difo_t *dp)
9459 {
9460         int i;
9461
9462         ASSERT(MUTEX_HELD(&dtrace_lock));
9463
9464         dp->dtdo_refcnt++;
9465         ASSERT(dp->dtdo_refcnt != 0);
9466
9467         /*
9468          * We need to check this DIF object for references to the variable
9469          * DIF_VAR_VTIMESTAMP.
9470          */
9471         for (i = 0; i < dp->dtdo_varlen; i++) {
9472                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9473
9474                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9475                         continue;
9476
9477                 if (dtrace_vtime_references++ == 0)
9478                         dtrace_vtime_enable();
9479         }
9480 }
9481
9482 /*
9483  * This routine calculates the dynamic variable chunksize for a given DIF
9484  * object.  The calculation is not fool-proof, and can probably be tricked by
9485  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9486  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9487  * if a dynamic variable size exceeds the chunksize.
9488  */
9489 static void
9490 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9491 {
9492         uint64_t sval = 0;
9493         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9494         const dif_instr_t *text = dp->dtdo_buf;
9495         uint_t pc, srd = 0;
9496         uint_t ttop = 0;
9497         size_t size, ksize;
9498         uint_t id, i;
9499
9500         for (pc = 0; pc < dp->dtdo_len; pc++) {
9501                 dif_instr_t instr = text[pc];
9502                 uint_t op = DIF_INSTR_OP(instr);
9503                 uint_t rd = DIF_INSTR_RD(instr);
9504                 uint_t r1 = DIF_INSTR_R1(instr);
9505                 uint_t nkeys = 0;
9506                 uchar_t scope = 0;
9507
9508                 dtrace_key_t *key = tupregs;
9509
9510                 switch (op) {
9511                 case DIF_OP_SETX:
9512                         sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9513                         srd = rd;
9514                         continue;
9515
9516                 case DIF_OP_STTS:
9517                         key = &tupregs[DIF_DTR_NREGS];
9518                         key[0].dttk_size = 0;
9519                         key[1].dttk_size = 0;
9520                         nkeys = 2;
9521                         scope = DIFV_SCOPE_THREAD;
9522                         break;
9523
9524                 case DIF_OP_STGAA:
9525                 case DIF_OP_STTAA:
9526                         nkeys = ttop;
9527
9528                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9529                                 key[nkeys++].dttk_size = 0;
9530
9531                         key[nkeys++].dttk_size = 0;
9532
9533                         if (op == DIF_OP_STTAA) {
9534                                 scope = DIFV_SCOPE_THREAD;
9535                         } else {
9536                                 scope = DIFV_SCOPE_GLOBAL;
9537                         }
9538
9539                         break;
9540
9541                 case DIF_OP_PUSHTR:
9542                         if (ttop == DIF_DTR_NREGS)
9543                                 return;
9544
9545                         if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9546                                 /*
9547                                  * If the register for the size of the "pushtr"
9548                                  * is %r0 (or the value is 0) and the type is
9549                                  * a string, we'll use the system-wide default
9550                                  * string size.
9551                                  */
9552                                 tupregs[ttop++].dttk_size =
9553                                     dtrace_strsize_default;
9554                         } else {
9555                                 if (srd == 0)
9556                                         return;
9557
9558                                 tupregs[ttop++].dttk_size = sval;
9559                         }
9560
9561                         break;
9562
9563                 case DIF_OP_PUSHTV:
9564                         if (ttop == DIF_DTR_NREGS)
9565                                 return;
9566
9567                         tupregs[ttop++].dttk_size = 0;
9568                         break;
9569
9570                 case DIF_OP_FLUSHTS:
9571                         ttop = 0;
9572                         break;
9573
9574                 case DIF_OP_POPTS:
9575                         if (ttop != 0)
9576                                 ttop--;
9577                         break;
9578                 }
9579
9580                 sval = 0;
9581                 srd = 0;
9582
9583                 if (nkeys == 0)
9584                         continue;
9585
9586                 /*
9587                  * We have a dynamic variable allocation; calculate its size.
9588                  */
9589                 for (ksize = 0, i = 0; i < nkeys; i++)
9590                         ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9591
9592                 size = sizeof (dtrace_dynvar_t);
9593                 size += sizeof (dtrace_key_t) * (nkeys - 1);
9594                 size += ksize;
9595
9596                 /*
9597                  * Now we need to determine the size of the stored data.
9598                  */
9599                 id = DIF_INSTR_VAR(instr);
9600
9601                 for (i = 0; i < dp->dtdo_varlen; i++) {
9602                         dtrace_difv_t *v = &dp->dtdo_vartab[i];
9603
9604                         if (v->dtdv_id == id && v->dtdv_scope == scope) {
9605                                 size += v->dtdv_type.dtdt_size;
9606                                 break;
9607                         }
9608                 }
9609
9610                 if (i == dp->dtdo_varlen)
9611                         return;
9612
9613                 /*
9614                  * We have the size.  If this is larger than the chunk size
9615                  * for our dynamic variable state, reset the chunk size.
9616                  */
9617                 size = P2ROUNDUP(size, sizeof (uint64_t));
9618
9619                 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9620                         vstate->dtvs_dynvars.dtds_chunksize = size;
9621         }
9622 }
9623
9624 static void
9625 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9626 {
9627         int i, oldsvars, osz, nsz, otlocals, ntlocals;
9628         uint_t id;
9629
9630         ASSERT(MUTEX_HELD(&dtrace_lock));
9631         ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9632
9633         for (i = 0; i < dp->dtdo_varlen; i++) {
9634                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9635                 dtrace_statvar_t *svar, ***svarp = NULL;
9636                 size_t dsize = 0;
9637                 uint8_t scope = v->dtdv_scope;
9638                 int *np = NULL;
9639
9640                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9641                         continue;
9642
9643                 id -= DIF_VAR_OTHER_UBASE;
9644
9645                 switch (scope) {
9646                 case DIFV_SCOPE_THREAD:
9647                         while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9648                                 dtrace_difv_t *tlocals;
9649
9650                                 if ((ntlocals = (otlocals << 1)) == 0)
9651                                         ntlocals = 1;
9652
9653                                 osz = otlocals * sizeof (dtrace_difv_t);
9654                                 nsz = ntlocals * sizeof (dtrace_difv_t);
9655
9656                                 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9657
9658                                 if (osz != 0) {
9659                                         bcopy(vstate->dtvs_tlocals,
9660                                             tlocals, osz);
9661                                         kmem_free(vstate->dtvs_tlocals, osz);
9662                                 }
9663
9664                                 vstate->dtvs_tlocals = tlocals;
9665                                 vstate->dtvs_ntlocals = ntlocals;
9666                         }
9667
9668                         vstate->dtvs_tlocals[id] = *v;
9669                         continue;
9670
9671                 case DIFV_SCOPE_LOCAL:
9672                         np = &vstate->dtvs_nlocals;
9673                         svarp = &vstate->dtvs_locals;
9674
9675                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9676                                 dsize = NCPU * (v->dtdv_type.dtdt_size +
9677                                     sizeof (uint64_t));
9678                         else
9679                                 dsize = NCPU * sizeof (uint64_t);
9680
9681                         break;
9682
9683                 case DIFV_SCOPE_GLOBAL:
9684                         np = &vstate->dtvs_nglobals;
9685                         svarp = &vstate->dtvs_globals;
9686
9687                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9688                                 dsize = v->dtdv_type.dtdt_size +
9689                                     sizeof (uint64_t);
9690
9691                         break;
9692
9693                 default:
9694                         ASSERT(0);
9695                 }
9696
9697                 while (id >= (oldsvars = *np)) {
9698                         dtrace_statvar_t **statics;
9699                         int newsvars, oldsize, newsize;
9700
9701                         if ((newsvars = (oldsvars << 1)) == 0)
9702                                 newsvars = 1;
9703
9704                         oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9705                         newsize = newsvars * sizeof (dtrace_statvar_t *);
9706
9707                         statics = kmem_zalloc(newsize, KM_SLEEP);
9708
9709                         if (oldsize != 0) {
9710                                 bcopy(*svarp, statics, oldsize);
9711                                 kmem_free(*svarp, oldsize);
9712                         }
9713
9714                         *svarp = statics;
9715                         *np = newsvars;
9716                 }
9717
9718                 if ((svar = (*svarp)[id]) == NULL) {
9719                         svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9720                         svar->dtsv_var = *v;
9721
9722                         if ((svar->dtsv_size = dsize) != 0) {
9723                                 svar->dtsv_data = (uint64_t)(uintptr_t)
9724                                     kmem_zalloc(dsize, KM_SLEEP);
9725                         }
9726
9727                         (*svarp)[id] = svar;
9728                 }
9729
9730                 svar->dtsv_refcnt++;
9731         }
9732
9733         dtrace_difo_chunksize(dp, vstate);
9734         dtrace_difo_hold(dp);
9735 }
9736
9737 static dtrace_difo_t *
9738 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9739 {
9740         dtrace_difo_t *new;
9741         size_t sz;
9742
9743         ASSERT(dp->dtdo_buf != NULL);
9744         ASSERT(dp->dtdo_refcnt != 0);
9745
9746         new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9747
9748         ASSERT(dp->dtdo_buf != NULL);
9749         sz = dp->dtdo_len * sizeof (dif_instr_t);
9750         new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9751         bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9752         new->dtdo_len = dp->dtdo_len;
9753
9754         if (dp->dtdo_strtab != NULL) {
9755                 ASSERT(dp->dtdo_strlen != 0);
9756                 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9757                 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9758                 new->dtdo_strlen = dp->dtdo_strlen;
9759         }
9760
9761         if (dp->dtdo_inttab != NULL) {
9762                 ASSERT(dp->dtdo_intlen != 0);
9763                 sz = dp->dtdo_intlen * sizeof (uint64_t);
9764                 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9765                 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9766                 new->dtdo_intlen = dp->dtdo_intlen;
9767         }
9768
9769         if (dp->dtdo_vartab != NULL) {
9770                 ASSERT(dp->dtdo_varlen != 0);
9771                 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9772                 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9773                 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9774                 new->dtdo_varlen = dp->dtdo_varlen;
9775         }
9776
9777         dtrace_difo_init(new, vstate);
9778         return (new);
9779 }
9780
9781 static void
9782 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9783 {
9784         int i;
9785
9786         ASSERT(dp->dtdo_refcnt == 0);
9787
9788         for (i = 0; i < dp->dtdo_varlen; i++) {
9789                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9790                 dtrace_statvar_t *svar, **svarp = NULL;
9791                 uint_t id;
9792                 uint8_t scope = v->dtdv_scope;
9793                 int *np = NULL;
9794
9795                 switch (scope) {
9796                 case DIFV_SCOPE_THREAD:
9797                         continue;
9798
9799                 case DIFV_SCOPE_LOCAL:
9800                         np = &vstate->dtvs_nlocals;
9801                         svarp = vstate->dtvs_locals;
9802                         break;
9803
9804                 case DIFV_SCOPE_GLOBAL:
9805                         np = &vstate->dtvs_nglobals;
9806                         svarp = vstate->dtvs_globals;
9807                         break;
9808
9809                 default:
9810                         ASSERT(0);
9811                 }
9812
9813                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9814                         continue;
9815
9816                 id -= DIF_VAR_OTHER_UBASE;
9817                 ASSERT(id < *np);
9818
9819                 svar = svarp[id];
9820                 ASSERT(svar != NULL);
9821                 ASSERT(svar->dtsv_refcnt > 0);
9822
9823                 if (--svar->dtsv_refcnt > 0)
9824                         continue;
9825
9826                 if (svar->dtsv_size != 0) {
9827                         ASSERT(svar->dtsv_data != 0);
9828                         kmem_free((void *)(uintptr_t)svar->dtsv_data,
9829                             svar->dtsv_size);
9830                 }
9831
9832                 kmem_free(svar, sizeof (dtrace_statvar_t));
9833                 svarp[id] = NULL;
9834         }
9835
9836         if (dp->dtdo_buf != NULL)
9837                 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9838         if (dp->dtdo_inttab != NULL)
9839                 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9840         if (dp->dtdo_strtab != NULL)
9841                 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9842         if (dp->dtdo_vartab != NULL)
9843                 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9844
9845         kmem_free(dp, sizeof (dtrace_difo_t));
9846 }
9847
9848 static void
9849 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9850 {
9851         int i;
9852
9853         ASSERT(MUTEX_HELD(&dtrace_lock));
9854         ASSERT(dp->dtdo_refcnt != 0);
9855
9856         for (i = 0; i < dp->dtdo_varlen; i++) {
9857                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9858
9859                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9860                         continue;
9861
9862                 ASSERT(dtrace_vtime_references > 0);
9863                 if (--dtrace_vtime_references == 0)
9864                         dtrace_vtime_disable();
9865         }
9866
9867         if (--dp->dtdo_refcnt == 0)
9868                 dtrace_difo_destroy(dp, vstate);
9869 }
9870
9871 /*
9872  * DTrace Format Functions
9873  */
9874 static uint16_t
9875 dtrace_format_add(dtrace_state_t *state, char *str)
9876 {
9877         char *fmt, **new;
9878         uint16_t ndx, len = strlen(str) + 1;
9879
9880         fmt = kmem_zalloc(len, KM_SLEEP);
9881         bcopy(str, fmt, len);
9882
9883         for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9884                 if (state->dts_formats[ndx] == NULL) {
9885                         state->dts_formats[ndx] = fmt;
9886                         return (ndx + 1);
9887                 }
9888         }
9889
9890         if (state->dts_nformats == USHRT_MAX) {
9891                 /*
9892                  * This is only likely if a denial-of-service attack is being
9893                  * attempted.  As such, it's okay to fail silently here.
9894                  */
9895                 kmem_free(fmt, len);
9896                 return (0);
9897         }
9898
9899         /*
9900          * For simplicity, we always resize the formats array to be exactly the
9901          * number of formats.
9902          */
9903         ndx = state->dts_nformats++;
9904         new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9905
9906         if (state->dts_formats != NULL) {
9907                 ASSERT(ndx != 0);
9908                 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9909                 kmem_free(state->dts_formats, ndx * sizeof (char *));
9910         }
9911
9912         state->dts_formats = new;
9913         state->dts_formats[ndx] = fmt;
9914
9915         return (ndx + 1);
9916 }
9917
9918 static void
9919 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9920 {
9921         char *fmt;
9922
9923         ASSERT(state->dts_formats != NULL);
9924         ASSERT(format <= state->dts_nformats);
9925         ASSERT(state->dts_formats[format - 1] != NULL);
9926
9927         fmt = state->dts_formats[format - 1];
9928         kmem_free(fmt, strlen(fmt) + 1);
9929         state->dts_formats[format - 1] = NULL;
9930 }
9931
9932 static void
9933 dtrace_format_destroy(dtrace_state_t *state)
9934 {
9935         int i;
9936
9937         if (state->dts_nformats == 0) {
9938                 ASSERT(state->dts_formats == NULL);
9939                 return;
9940         }
9941
9942         ASSERT(state->dts_formats != NULL);
9943
9944         for (i = 0; i < state->dts_nformats; i++) {
9945                 char *fmt = state->dts_formats[i];
9946
9947                 if (fmt == NULL)
9948                         continue;
9949
9950                 kmem_free(fmt, strlen(fmt) + 1);
9951         }
9952
9953         kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9954         state->dts_nformats = 0;
9955         state->dts_formats = NULL;
9956 }
9957
9958 /*
9959  * DTrace Predicate Functions
9960  */
9961 static dtrace_predicate_t *
9962 dtrace_predicate_create(dtrace_difo_t *dp)
9963 {
9964         dtrace_predicate_t *pred;
9965
9966         ASSERT(MUTEX_HELD(&dtrace_lock));
9967         ASSERT(dp->dtdo_refcnt != 0);
9968
9969         pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9970         pred->dtp_difo = dp;
9971         pred->dtp_refcnt = 1;
9972
9973         if (!dtrace_difo_cacheable(dp))
9974                 return (pred);
9975
9976         if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9977                 /*
9978                  * This is only theoretically possible -- we have had 2^32
9979                  * cacheable predicates on this machine.  We cannot allow any
9980                  * more predicates to become cacheable:  as unlikely as it is,
9981                  * there may be a thread caching a (now stale) predicate cache
9982                  * ID. (N.B.: the temptation is being successfully resisted to
9983                  * have this cmn_err() "Holy shit -- we executed this code!")
9984                  */
9985                 return (pred);
9986         }
9987
9988         pred->dtp_cacheid = dtrace_predcache_id++;
9989
9990         return (pred);
9991 }
9992
9993 static void
9994 dtrace_predicate_hold(dtrace_predicate_t *pred)
9995 {
9996         ASSERT(MUTEX_HELD(&dtrace_lock));
9997         ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9998         ASSERT(pred->dtp_refcnt > 0);
9999
10000         pred->dtp_refcnt++;
10001 }
10002
10003 static void
10004 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10005 {
10006         dtrace_difo_t *dp = pred->dtp_difo;
10007
10008         ASSERT(MUTEX_HELD(&dtrace_lock));
10009         ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10010         ASSERT(pred->dtp_refcnt > 0);
10011
10012         if (--pred->dtp_refcnt == 0) {
10013                 dtrace_difo_release(pred->dtp_difo, vstate);
10014                 kmem_free(pred, sizeof (dtrace_predicate_t));
10015         }
10016 }
10017
10018 /*
10019  * DTrace Action Description Functions
10020  */
10021 static dtrace_actdesc_t *
10022 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10023     uint64_t uarg, uint64_t arg)
10024 {
10025         dtrace_actdesc_t *act;
10026
10027 #if defined(sun)
10028         ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10029             arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10030 #endif
10031
10032         act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10033         act->dtad_kind = kind;
10034         act->dtad_ntuple = ntuple;
10035         act->dtad_uarg = uarg;
10036         act->dtad_arg = arg;
10037         act->dtad_refcnt = 1;
10038
10039         return (act);
10040 }
10041
10042 static void
10043 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10044 {
10045         ASSERT(act->dtad_refcnt >= 1);
10046         act->dtad_refcnt++;
10047 }
10048
10049 static void
10050 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10051 {
10052         dtrace_actkind_t kind = act->dtad_kind;
10053         dtrace_difo_t *dp;
10054
10055         ASSERT(act->dtad_refcnt >= 1);
10056
10057         if (--act->dtad_refcnt != 0)
10058                 return;
10059
10060         if ((dp = act->dtad_difo) != NULL)
10061                 dtrace_difo_release(dp, vstate);
10062
10063         if (DTRACEACT_ISPRINTFLIKE(kind)) {
10064                 char *str = (char *)(uintptr_t)act->dtad_arg;
10065
10066 #if defined(sun)
10067                 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10068                     (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10069 #endif
10070
10071                 if (str != NULL)
10072                         kmem_free(str, strlen(str) + 1);
10073         }
10074
10075         kmem_free(act, sizeof (dtrace_actdesc_t));
10076 }
10077
10078 /*
10079  * DTrace ECB Functions
10080  */
10081 static dtrace_ecb_t *
10082 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10083 {
10084         dtrace_ecb_t *ecb;
10085         dtrace_epid_t epid;
10086
10087         ASSERT(MUTEX_HELD(&dtrace_lock));
10088
10089         ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10090         ecb->dte_predicate = NULL;
10091         ecb->dte_probe = probe;
10092
10093         /*
10094          * The default size is the size of the default action: recording
10095          * the header.
10096          */
10097         ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10098         ecb->dte_alignment = sizeof (dtrace_epid_t);
10099
10100         epid = state->dts_epid++;
10101
10102         if (epid - 1 >= state->dts_necbs) {
10103                 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10104                 int necbs = state->dts_necbs << 1;
10105
10106                 ASSERT(epid == state->dts_necbs + 1);
10107
10108                 if (necbs == 0) {
10109                         ASSERT(oecbs == NULL);
10110                         necbs = 1;
10111                 }
10112
10113                 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10114
10115                 if (oecbs != NULL)
10116                         bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10117
10118                 dtrace_membar_producer();
10119                 state->dts_ecbs = ecbs;
10120
10121                 if (oecbs != NULL) {
10122                         /*
10123                          * If this state is active, we must dtrace_sync()
10124                          * before we can free the old dts_ecbs array:  we're
10125                          * coming in hot, and there may be active ring
10126                          * buffer processing (which indexes into the dts_ecbs
10127                          * array) on another CPU.
10128                          */
10129                         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10130                                 dtrace_sync();
10131
10132                         kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10133                 }
10134
10135                 dtrace_membar_producer();
10136                 state->dts_necbs = necbs;
10137         }
10138
10139         ecb->dte_state = state;
10140
10141         ASSERT(state->dts_ecbs[epid - 1] == NULL);
10142         dtrace_membar_producer();
10143         state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10144
10145         return (ecb);
10146 }
10147
10148 static void
10149 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10150 {
10151         dtrace_probe_t *probe = ecb->dte_probe;
10152
10153         ASSERT(MUTEX_HELD(&cpu_lock));
10154         ASSERT(MUTEX_HELD(&dtrace_lock));
10155         ASSERT(ecb->dte_next == NULL);
10156
10157         if (probe == NULL) {
10158                 /*
10159                  * This is the NULL probe -- there's nothing to do.
10160                  */
10161                 return;
10162         }
10163
10164         if (probe->dtpr_ecb == NULL) {
10165                 dtrace_provider_t *prov = probe->dtpr_provider;
10166
10167                 /*
10168                  * We're the first ECB on this probe.
10169                  */
10170                 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10171
10172                 if (ecb->dte_predicate != NULL)
10173                         probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10174
10175                 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10176                     probe->dtpr_id, probe->dtpr_arg);
10177         } else {
10178                 /*
10179                  * This probe is already active.  Swing the last pointer to
10180                  * point to the new ECB, and issue a dtrace_sync() to assure
10181                  * that all CPUs have seen the change.
10182                  */
10183                 ASSERT(probe->dtpr_ecb_last != NULL);
10184                 probe->dtpr_ecb_last->dte_next = ecb;
10185                 probe->dtpr_ecb_last = ecb;
10186                 probe->dtpr_predcache = 0;
10187
10188                 dtrace_sync();
10189         }
10190 }
10191
10192 static void
10193 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10194 {
10195         dtrace_action_t *act;
10196         uint32_t curneeded = UINT32_MAX;
10197         uint32_t aggbase = UINT32_MAX;
10198
10199         /*
10200          * If we record anything, we always record the dtrace_rechdr_t.  (And
10201          * we always record it first.)
10202          */
10203         ecb->dte_size = sizeof (dtrace_rechdr_t);
10204         ecb->dte_alignment = sizeof (dtrace_epid_t);
10205
10206         for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10207                 dtrace_recdesc_t *rec = &act->dta_rec;
10208                 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10209
10210                 ecb->dte_alignment = MAX(ecb->dte_alignment,
10211                     rec->dtrd_alignment);
10212
10213                 if (DTRACEACT_ISAGG(act->dta_kind)) {
10214                         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10215
10216                         ASSERT(rec->dtrd_size != 0);
10217                         ASSERT(agg->dtag_first != NULL);
10218                         ASSERT(act->dta_prev->dta_intuple);
10219                         ASSERT(aggbase != UINT32_MAX);
10220                         ASSERT(curneeded != UINT32_MAX);
10221
10222                         agg->dtag_base = aggbase;
10223
10224                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10225                         rec->dtrd_offset = curneeded;
10226                         curneeded += rec->dtrd_size;
10227                         ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10228
10229                         aggbase = UINT32_MAX;
10230                         curneeded = UINT32_MAX;
10231                 } else if (act->dta_intuple) {
10232                         if (curneeded == UINT32_MAX) {
10233                                 /*
10234                                  * This is the first record in a tuple.  Align
10235                                  * curneeded to be at offset 4 in an 8-byte
10236                                  * aligned block.
10237                                  */
10238                                 ASSERT(act->dta_prev == NULL ||
10239                                     !act->dta_prev->dta_intuple);
10240                                 ASSERT3U(aggbase, ==, UINT32_MAX);
10241                                 curneeded = P2PHASEUP(ecb->dte_size,
10242                                     sizeof (uint64_t), sizeof (dtrace_aggid_t));
10243
10244                                 aggbase = curneeded - sizeof (dtrace_aggid_t);
10245                                 ASSERT(IS_P2ALIGNED(aggbase,
10246                                     sizeof (uint64_t)));
10247                         }
10248                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10249                         rec->dtrd_offset = curneeded;
10250                         curneeded += rec->dtrd_size;
10251                 } else {
10252                         /* tuples must be followed by an aggregation */
10253                         ASSERT(act->dta_prev == NULL ||
10254                             !act->dta_prev->dta_intuple);
10255
10256                         ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10257                             rec->dtrd_alignment);
10258                         rec->dtrd_offset = ecb->dte_size;
10259                         ecb->dte_size += rec->dtrd_size;
10260                         ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10261                 }
10262         }
10263
10264         if ((act = ecb->dte_action) != NULL &&
10265             !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10266             ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10267                 /*
10268                  * If the size is still sizeof (dtrace_rechdr_t), then all
10269                  * actions store no data; set the size to 0.
10270                  */
10271                 ecb->dte_size = 0;
10272         }
10273
10274         ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10275         ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10276         ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10277             ecb->dte_needed);
10278 }
10279
10280 static dtrace_action_t *
10281 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10282 {
10283         dtrace_aggregation_t *agg;
10284         size_t size = sizeof (uint64_t);
10285         int ntuple = desc->dtad_ntuple;
10286         dtrace_action_t *act;
10287         dtrace_recdesc_t *frec;
10288         dtrace_aggid_t aggid;
10289         dtrace_state_t *state = ecb->dte_state;
10290
10291         agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10292         agg->dtag_ecb = ecb;
10293
10294         ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10295
10296         switch (desc->dtad_kind) {
10297         case DTRACEAGG_MIN:
10298                 agg->dtag_initial = INT64_MAX;
10299                 agg->dtag_aggregate = dtrace_aggregate_min;
10300                 break;
10301
10302         case DTRACEAGG_MAX:
10303                 agg->dtag_initial = INT64_MIN;
10304                 agg->dtag_aggregate = dtrace_aggregate_max;
10305                 break;
10306
10307         case DTRACEAGG_COUNT:
10308                 agg->dtag_aggregate = dtrace_aggregate_count;
10309                 break;
10310
10311         case DTRACEAGG_QUANTIZE:
10312                 agg->dtag_aggregate = dtrace_aggregate_quantize;
10313                 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10314                     sizeof (uint64_t);
10315                 break;
10316
10317         case DTRACEAGG_LQUANTIZE: {
10318                 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10319                 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10320
10321                 agg->dtag_initial = desc->dtad_arg;
10322                 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10323
10324                 if (step == 0 || levels == 0)
10325                         goto err;
10326
10327                 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10328                 break;
10329         }
10330
10331         case DTRACEAGG_LLQUANTIZE: {
10332                 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10333                 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10334                 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10335                 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10336                 int64_t v;
10337
10338                 agg->dtag_initial = desc->dtad_arg;
10339                 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10340
10341                 if (factor < 2 || low >= high || nsteps < factor)
10342                         goto err;
10343
10344                 /*
10345                  * Now check that the number of steps evenly divides a power
10346                  * of the factor.  (This assures both integer bucket size and
10347                  * linearity within each magnitude.)
10348                  */
10349                 for (v = factor; v < nsteps; v *= factor)
10350                         continue;
10351
10352                 if ((v % nsteps) || (nsteps % factor))
10353                         goto err;
10354
10355                 size = (dtrace_aggregate_llquantize_bucket(factor,
10356                     low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10357                 break;
10358         }
10359
10360         case DTRACEAGG_AVG:
10361                 agg->dtag_aggregate = dtrace_aggregate_avg;
10362                 size = sizeof (uint64_t) * 2;
10363                 break;
10364
10365         case DTRACEAGG_STDDEV:
10366                 agg->dtag_aggregate = dtrace_aggregate_stddev;
10367                 size = sizeof (uint64_t) * 4;
10368                 break;
10369
10370         case DTRACEAGG_SUM:
10371                 agg->dtag_aggregate = dtrace_aggregate_sum;
10372                 break;
10373
10374         default:
10375                 goto err;
10376         }
10377
10378         agg->dtag_action.dta_rec.dtrd_size = size;
10379
10380         if (ntuple == 0)
10381                 goto err;
10382
10383         /*
10384          * We must make sure that we have enough actions for the n-tuple.
10385          */
10386         for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10387                 if (DTRACEACT_ISAGG(act->dta_kind))
10388                         break;
10389
10390                 if (--ntuple == 0) {
10391                         /*
10392                          * This is the action with which our n-tuple begins.
10393                          */
10394                         agg->dtag_first = act;
10395                         goto success;
10396                 }
10397         }
10398
10399         /*
10400          * This n-tuple is short by ntuple elements.  Return failure.
10401          */
10402         ASSERT(ntuple != 0);
10403 err:
10404         kmem_free(agg, sizeof (dtrace_aggregation_t));
10405         return (NULL);
10406
10407 success:
10408         /*
10409          * If the last action in the tuple has a size of zero, it's actually
10410          * an expression argument for the aggregating action.
10411          */
10412         ASSERT(ecb->dte_action_last != NULL);
10413         act = ecb->dte_action_last;
10414
10415         if (act->dta_kind == DTRACEACT_DIFEXPR) {
10416                 ASSERT(act->dta_difo != NULL);
10417
10418                 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10419                         agg->dtag_hasarg = 1;
10420         }
10421
10422         /*
10423          * We need to allocate an id for this aggregation.
10424          */
10425 #if defined(sun)
10426         aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10427             VM_BESTFIT | VM_SLEEP);
10428 #else
10429         aggid = alloc_unr(state->dts_aggid_arena);
10430 #endif
10431
10432         if (aggid - 1 >= state->dts_naggregations) {
10433                 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10434                 dtrace_aggregation_t **aggs;
10435                 int naggs = state->dts_naggregations << 1;
10436                 int onaggs = state->dts_naggregations;
10437
10438                 ASSERT(aggid == state->dts_naggregations + 1);
10439
10440                 if (naggs == 0) {
10441                         ASSERT(oaggs == NULL);
10442                         naggs = 1;
10443                 }
10444
10445                 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10446
10447                 if (oaggs != NULL) {
10448                         bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10449                         kmem_free(oaggs, onaggs * sizeof (*aggs));
10450                 }
10451
10452                 state->dts_aggregations = aggs;
10453                 state->dts_naggregations = naggs;
10454         }
10455
10456         ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10457         state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10458
10459         frec = &agg->dtag_first->dta_rec;
10460         if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10461                 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10462
10463         for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10464                 ASSERT(!act->dta_intuple);
10465                 act->dta_intuple = 1;
10466         }
10467
10468         return (&agg->dtag_action);
10469 }
10470
10471 static void
10472 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10473 {
10474         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10475         dtrace_state_t *state = ecb->dte_state;
10476         dtrace_aggid_t aggid = agg->dtag_id;
10477
10478         ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10479 #if defined(sun)
10480         vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10481 #else
10482         free_unr(state->dts_aggid_arena, aggid);
10483 #endif
10484
10485         ASSERT(state->dts_aggregations[aggid - 1] == agg);
10486         state->dts_aggregations[aggid - 1] = NULL;
10487
10488         kmem_free(agg, sizeof (dtrace_aggregation_t));
10489 }
10490
10491 static int
10492 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10493 {
10494         dtrace_action_t *action, *last;
10495         dtrace_difo_t *dp = desc->dtad_difo;
10496         uint32_t size = 0, align = sizeof (uint8_t), mask;
10497         uint16_t format = 0;
10498         dtrace_recdesc_t *rec;
10499         dtrace_state_t *state = ecb->dte_state;
10500         dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
10501         uint64_t arg = desc->dtad_arg;
10502
10503         ASSERT(MUTEX_HELD(&dtrace_lock));
10504         ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10505
10506         if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10507                 /*
10508                  * If this is an aggregating action, there must be neither
10509                  * a speculate nor a commit on the action chain.
10510                  */
10511                 dtrace_action_t *act;
10512
10513                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10514                         if (act->dta_kind == DTRACEACT_COMMIT)
10515                                 return (EINVAL);
10516
10517                         if (act->dta_kind == DTRACEACT_SPECULATE)
10518                                 return (EINVAL);
10519                 }
10520
10521                 action = dtrace_ecb_aggregation_create(ecb, desc);
10522
10523                 if (action == NULL)
10524                         return (EINVAL);
10525         } else {
10526                 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10527                     (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10528                     dp != NULL && dp->dtdo_destructive)) {
10529                         state->dts_destructive = 1;
10530                 }
10531
10532                 switch (desc->dtad_kind) {
10533                 case DTRACEACT_PRINTF:
10534                 case DTRACEACT_PRINTA:
10535                 case DTRACEACT_SYSTEM:
10536                 case DTRACEACT_FREOPEN:
10537                 case DTRACEACT_DIFEXPR:
10538                         /*
10539                          * We know that our arg is a string -- turn it into a
10540                          * format.
10541                          */
10542                         if (arg == 0) {
10543                                 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10544                                     desc->dtad_kind == DTRACEACT_DIFEXPR);
10545                                 format = 0;
10546                         } else {
10547                                 ASSERT(arg != 0);
10548 #if defined(sun)
10549                                 ASSERT(arg > KERNELBASE);
10550 #endif
10551                                 format = dtrace_format_add(state,
10552                                     (char *)(uintptr_t)arg);
10553                         }
10554
10555                         /*FALLTHROUGH*/
10556                 case DTRACEACT_LIBACT:
10557                 case DTRACEACT_TRACEMEM:
10558                 case DTRACEACT_TRACEMEM_DYNSIZE:
10559                         if (dp == NULL)
10560                                 return (EINVAL);
10561
10562                         if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10563                                 break;
10564
10565                         if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10566                                 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10567                                         return (EINVAL);
10568
10569                                 size = opt[DTRACEOPT_STRSIZE];
10570                         }
10571
10572                         break;
10573
10574                 case DTRACEACT_STACK:
10575                         if ((nframes = arg) == 0) {
10576                                 nframes = opt[DTRACEOPT_STACKFRAMES];
10577                                 ASSERT(nframes > 0);
10578                                 arg = nframes;
10579                         }
10580
10581                         size = nframes * sizeof (pc_t);
10582                         break;
10583
10584                 case DTRACEACT_JSTACK:
10585                         if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10586                                 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10587
10588                         if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10589                                 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10590
10591                         arg = DTRACE_USTACK_ARG(nframes, strsize);
10592
10593                         /*FALLTHROUGH*/
10594                 case DTRACEACT_USTACK:
10595                         if (desc->dtad_kind != DTRACEACT_JSTACK &&
10596                             (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10597                                 strsize = DTRACE_USTACK_STRSIZE(arg);
10598                                 nframes = opt[DTRACEOPT_USTACKFRAMES];
10599                                 ASSERT(nframes > 0);
10600                                 arg = DTRACE_USTACK_ARG(nframes, strsize);
10601                         }
10602
10603                         /*
10604                          * Save a slot for the pid.
10605                          */
10606                         size = (nframes + 1) * sizeof (uint64_t);
10607                         size += DTRACE_USTACK_STRSIZE(arg);
10608                         size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10609
10610                         break;
10611
10612                 case DTRACEACT_SYM:
10613                 case DTRACEACT_MOD:
10614                         if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10615                             sizeof (uint64_t)) ||
10616                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10617                                 return (EINVAL);
10618                         break;
10619
10620                 case DTRACEACT_USYM:
10621                 case DTRACEACT_UMOD:
10622                 case DTRACEACT_UADDR:
10623                         if (dp == NULL ||
10624                             (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10625                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10626                                 return (EINVAL);
10627
10628                         /*
10629                          * We have a slot for the pid, plus a slot for the
10630                          * argument.  To keep things simple (aligned with
10631                          * bitness-neutral sizing), we store each as a 64-bit
10632                          * quantity.
10633                          */
10634                         size = 2 * sizeof (uint64_t);
10635                         break;
10636
10637                 case DTRACEACT_STOP:
10638                 case DTRACEACT_BREAKPOINT:
10639                 case DTRACEACT_PANIC:
10640                         break;
10641
10642                 case DTRACEACT_CHILL:
10643                 case DTRACEACT_DISCARD:
10644                 case DTRACEACT_RAISE:
10645                         if (dp == NULL)
10646                                 return (EINVAL);
10647                         break;
10648
10649                 case DTRACEACT_EXIT:
10650                         if (dp == NULL ||
10651                             (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10652                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10653                                 return (EINVAL);
10654                         break;
10655
10656                 case DTRACEACT_SPECULATE:
10657                         if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10658                                 return (EINVAL);
10659
10660                         if (dp == NULL)
10661                                 return (EINVAL);
10662
10663                         state->dts_speculates = 1;
10664                         break;
10665
10666                 case DTRACEACT_PRINTM:
10667                         size = dp->dtdo_rtype.dtdt_size;
10668                         break;
10669
10670                 case DTRACEACT_PRINTT:
10671                         size = dp->dtdo_rtype.dtdt_size;
10672                         break;
10673
10674                 case DTRACEACT_COMMIT: {
10675                         dtrace_action_t *act = ecb->dte_action;
10676
10677                         for (; act != NULL; act = act->dta_next) {
10678                                 if (act->dta_kind == DTRACEACT_COMMIT)
10679                                         return (EINVAL);
10680                         }
10681
10682                         if (dp == NULL)
10683                                 return (EINVAL);
10684                         break;
10685                 }
10686
10687                 default:
10688                         return (EINVAL);
10689                 }
10690
10691                 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10692                         /*
10693                          * If this is a data-storing action or a speculate,
10694                          * we must be sure that there isn't a commit on the
10695                          * action chain.
10696                          */
10697                         dtrace_action_t *act = ecb->dte_action;
10698
10699                         for (; act != NULL; act = act->dta_next) {
10700                                 if (act->dta_kind == DTRACEACT_COMMIT)
10701                                         return (EINVAL);
10702                         }
10703                 }
10704
10705                 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10706                 action->dta_rec.dtrd_size = size;
10707         }
10708
10709         action->dta_refcnt = 1;
10710         rec = &action->dta_rec;
10711         size = rec->dtrd_size;
10712
10713         for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10714                 if (!(size & mask)) {
10715                         align = mask + 1;
10716                         break;
10717                 }
10718         }
10719
10720         action->dta_kind = desc->dtad_kind;
10721
10722         if ((action->dta_difo = dp) != NULL)
10723                 dtrace_difo_hold(dp);
10724
10725         rec->dtrd_action = action->dta_kind;
10726         rec->dtrd_arg = arg;
10727         rec->dtrd_uarg = desc->dtad_uarg;
10728         rec->dtrd_alignment = (uint16_t)align;
10729         rec->dtrd_format = format;
10730
10731         if ((last = ecb->dte_action_last) != NULL) {
10732                 ASSERT(ecb->dte_action != NULL);
10733                 action->dta_prev = last;
10734                 last->dta_next = action;
10735         } else {
10736                 ASSERT(ecb->dte_action == NULL);
10737                 ecb->dte_action = action;
10738         }
10739
10740         ecb->dte_action_last = action;
10741
10742         return (0);
10743 }
10744
10745 static void
10746 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10747 {
10748         dtrace_action_t *act = ecb->dte_action, *next;
10749         dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10750         dtrace_difo_t *dp;
10751         uint16_t format;
10752
10753         if (act != NULL && act->dta_refcnt > 1) {
10754                 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10755                 act->dta_refcnt--;
10756         } else {
10757                 for (; act != NULL; act = next) {
10758                         next = act->dta_next;
10759                         ASSERT(next != NULL || act == ecb->dte_action_last);
10760                         ASSERT(act->dta_refcnt == 1);
10761
10762                         if ((format = act->dta_rec.dtrd_format) != 0)
10763                                 dtrace_format_remove(ecb->dte_state, format);
10764
10765                         if ((dp = act->dta_difo) != NULL)
10766                                 dtrace_difo_release(dp, vstate);
10767
10768                         if (DTRACEACT_ISAGG(act->dta_kind)) {
10769                                 dtrace_ecb_aggregation_destroy(ecb, act);
10770                         } else {
10771                                 kmem_free(act, sizeof (dtrace_action_t));
10772                         }
10773                 }
10774         }
10775
10776         ecb->dte_action = NULL;
10777         ecb->dte_action_last = NULL;
10778         ecb->dte_size = 0;
10779 }
10780
10781 static void
10782 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10783 {
10784         /*
10785          * We disable the ECB by removing it from its probe.
10786          */
10787         dtrace_ecb_t *pecb, *prev = NULL;
10788         dtrace_probe_t *probe = ecb->dte_probe;
10789
10790         ASSERT(MUTEX_HELD(&dtrace_lock));
10791
10792         if (probe == NULL) {
10793                 /*
10794                  * This is the NULL probe; there is nothing to disable.
10795                  */
10796                 return;
10797         }
10798
10799         for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10800                 if (pecb == ecb)
10801                         break;
10802                 prev = pecb;
10803         }
10804
10805         ASSERT(pecb != NULL);
10806
10807         if (prev == NULL) {
10808                 probe->dtpr_ecb = ecb->dte_next;
10809         } else {
10810                 prev->dte_next = ecb->dte_next;
10811         }
10812
10813         if (ecb == probe->dtpr_ecb_last) {
10814                 ASSERT(ecb->dte_next == NULL);
10815                 probe->dtpr_ecb_last = prev;
10816         }
10817
10818         /*
10819          * The ECB has been disconnected from the probe; now sync to assure
10820          * that all CPUs have seen the change before returning.
10821          */
10822         dtrace_sync();
10823
10824         if (probe->dtpr_ecb == NULL) {
10825                 /*
10826                  * That was the last ECB on the probe; clear the predicate
10827                  * cache ID for the probe, disable it and sync one more time
10828                  * to assure that we'll never hit it again.
10829                  */
10830                 dtrace_provider_t *prov = probe->dtpr_provider;
10831
10832                 ASSERT(ecb->dte_next == NULL);
10833                 ASSERT(probe->dtpr_ecb_last == NULL);
10834                 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10835                 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10836                     probe->dtpr_id, probe->dtpr_arg);
10837                 dtrace_sync();
10838         } else {
10839                 /*
10840                  * There is at least one ECB remaining on the probe.  If there
10841                  * is _exactly_ one, set the probe's predicate cache ID to be
10842                  * the predicate cache ID of the remaining ECB.
10843                  */
10844                 ASSERT(probe->dtpr_ecb_last != NULL);
10845                 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10846
10847                 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10848                         dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10849
10850                         ASSERT(probe->dtpr_ecb->dte_next == NULL);
10851
10852                         if (p != NULL)
10853                                 probe->dtpr_predcache = p->dtp_cacheid;
10854                 }
10855
10856                 ecb->dte_next = NULL;
10857         }
10858 }
10859
10860 static void
10861 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10862 {
10863         dtrace_state_t *state = ecb->dte_state;
10864         dtrace_vstate_t *vstate = &state->dts_vstate;
10865         dtrace_predicate_t *pred;
10866         dtrace_epid_t epid = ecb->dte_epid;
10867
10868         ASSERT(MUTEX_HELD(&dtrace_lock));
10869         ASSERT(ecb->dte_next == NULL);
10870         ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10871
10872         if ((pred = ecb->dte_predicate) != NULL)
10873                 dtrace_predicate_release(pred, vstate);
10874
10875         dtrace_ecb_action_remove(ecb);
10876
10877         ASSERT(state->dts_ecbs[epid - 1] == ecb);
10878         state->dts_ecbs[epid - 1] = NULL;
10879
10880         kmem_free(ecb, sizeof (dtrace_ecb_t));
10881 }
10882
10883 static dtrace_ecb_t *
10884 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10885     dtrace_enabling_t *enab)
10886 {
10887         dtrace_ecb_t *ecb;
10888         dtrace_predicate_t *pred;
10889         dtrace_actdesc_t *act;
10890         dtrace_provider_t *prov;
10891         dtrace_ecbdesc_t *desc = enab->dten_current;
10892
10893         ASSERT(MUTEX_HELD(&dtrace_lock));
10894         ASSERT(state != NULL);
10895
10896         ecb = dtrace_ecb_add(state, probe);
10897         ecb->dte_uarg = desc->dted_uarg;
10898
10899         if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10900                 dtrace_predicate_hold(pred);
10901                 ecb->dte_predicate = pred;
10902         }
10903
10904         if (probe != NULL) {
10905                 /*
10906                  * If the provider shows more leg than the consumer is old
10907                  * enough to see, we need to enable the appropriate implicit
10908                  * predicate bits to prevent the ecb from activating at
10909                  * revealing times.
10910                  *
10911                  * Providers specifying DTRACE_PRIV_USER at register time
10912                  * are stating that they need the /proc-style privilege
10913                  * model to be enforced, and this is what DTRACE_COND_OWNER
10914                  * and DTRACE_COND_ZONEOWNER will then do at probe time.
10915                  */
10916                 prov = probe->dtpr_provider;
10917                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10918                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10919                         ecb->dte_cond |= DTRACE_COND_OWNER;
10920
10921                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10922                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10923                         ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10924
10925                 /*
10926                  * If the provider shows us kernel innards and the user
10927                  * is lacking sufficient privilege, enable the
10928                  * DTRACE_COND_USERMODE implicit predicate.
10929                  */
10930                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10931                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10932                         ecb->dte_cond |= DTRACE_COND_USERMODE;
10933         }
10934
10935         if (dtrace_ecb_create_cache != NULL) {
10936                 /*
10937                  * If we have a cached ecb, we'll use its action list instead
10938                  * of creating our own (saving both time and space).
10939                  */
10940                 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10941                 dtrace_action_t *act = cached->dte_action;
10942
10943                 if (act != NULL) {
10944                         ASSERT(act->dta_refcnt > 0);
10945                         act->dta_refcnt++;
10946                         ecb->dte_action = act;
10947                         ecb->dte_action_last = cached->dte_action_last;
10948                         ecb->dte_needed = cached->dte_needed;
10949                         ecb->dte_size = cached->dte_size;
10950                         ecb->dte_alignment = cached->dte_alignment;
10951                 }
10952
10953                 return (ecb);
10954         }
10955
10956         for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10957                 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10958                         dtrace_ecb_destroy(ecb);
10959                         return (NULL);
10960                 }
10961         }
10962
10963         dtrace_ecb_resize(ecb);
10964
10965         return (dtrace_ecb_create_cache = ecb);
10966 }
10967
10968 static int
10969 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10970 {
10971         dtrace_ecb_t *ecb;
10972         dtrace_enabling_t *enab = arg;
10973         dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10974
10975         ASSERT(state != NULL);
10976
10977         if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10978                 /*
10979                  * This probe was created in a generation for which this
10980                  * enabling has previously created ECBs; we don't want to
10981                  * enable it again, so just kick out.
10982                  */
10983                 return (DTRACE_MATCH_NEXT);
10984         }
10985
10986         if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10987                 return (DTRACE_MATCH_DONE);
10988
10989         dtrace_ecb_enable(ecb);
10990         return (DTRACE_MATCH_NEXT);
10991 }
10992
10993 static dtrace_ecb_t *
10994 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10995 {
10996         dtrace_ecb_t *ecb;
10997
10998         ASSERT(MUTEX_HELD(&dtrace_lock));
10999
11000         if (id == 0 || id > state->dts_necbs)
11001                 return (NULL);
11002
11003         ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11004         ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11005
11006         return (state->dts_ecbs[id - 1]);
11007 }
11008
11009 static dtrace_aggregation_t *
11010 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11011 {
11012         dtrace_aggregation_t *agg;
11013
11014         ASSERT(MUTEX_HELD(&dtrace_lock));
11015
11016         if (id == 0 || id > state->dts_naggregations)
11017                 return (NULL);
11018
11019         ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11020         ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11021             agg->dtag_id == id);
11022
11023         return (state->dts_aggregations[id - 1]);
11024 }
11025
11026 /*
11027  * DTrace Buffer Functions
11028  *
11029  * The following functions manipulate DTrace buffers.  Most of these functions
11030  * are called in the context of establishing or processing consumer state;
11031  * exceptions are explicitly noted.
11032  */
11033
11034 /*
11035  * Note:  called from cross call context.  This function switches the two
11036  * buffers on a given CPU.  The atomicity of this operation is assured by
11037  * disabling interrupts while the actual switch takes place; the disabling of
11038  * interrupts serializes the execution with any execution of dtrace_probe() on
11039  * the same CPU.
11040  */
11041 static void
11042 dtrace_buffer_switch(dtrace_buffer_t *buf)
11043 {
11044         caddr_t tomax = buf->dtb_tomax;
11045         caddr_t xamot = buf->dtb_xamot;
11046         dtrace_icookie_t cookie;
11047         hrtime_t now;
11048
11049         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11050         ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11051
11052         cookie = dtrace_interrupt_disable();
11053         now = dtrace_gethrtime();
11054         buf->dtb_tomax = xamot;
11055         buf->dtb_xamot = tomax;
11056         buf->dtb_xamot_drops = buf->dtb_drops;
11057         buf->dtb_xamot_offset = buf->dtb_offset;
11058         buf->dtb_xamot_errors = buf->dtb_errors;
11059         buf->dtb_xamot_flags = buf->dtb_flags;
11060         buf->dtb_offset = 0;
11061         buf->dtb_drops = 0;
11062         buf->dtb_errors = 0;
11063         buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11064         buf->dtb_interval = now - buf->dtb_switched;
11065         buf->dtb_switched = now;
11066         dtrace_interrupt_enable(cookie);
11067 }
11068
11069 /*
11070  * Note:  called from cross call context.  This function activates a buffer
11071  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11072  * is guaranteed by the disabling of interrupts.
11073  */
11074 static void
11075 dtrace_buffer_activate(dtrace_state_t *state)
11076 {
11077         dtrace_buffer_t *buf;
11078         dtrace_icookie_t cookie = dtrace_interrupt_disable();
11079
11080         buf = &state->dts_buffer[curcpu];
11081
11082         if (buf->dtb_tomax != NULL) {
11083                 /*
11084                  * We might like to assert that the buffer is marked inactive,
11085                  * but this isn't necessarily true:  the buffer for the CPU
11086                  * that processes the BEGIN probe has its buffer activated
11087                  * manually.  In this case, we take the (harmless) action
11088                  * re-clearing the bit INACTIVE bit.
11089                  */
11090                 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11091         }
11092
11093         dtrace_interrupt_enable(cookie);
11094 }
11095
11096 static int
11097 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11098     processorid_t cpu, int *factor)
11099 {
11100 #if defined(sun)
11101         cpu_t *cp;
11102 #endif
11103         dtrace_buffer_t *buf;
11104         int allocated = 0, desired = 0;
11105
11106 #if defined(sun)
11107         ASSERT(MUTEX_HELD(&cpu_lock));
11108         ASSERT(MUTEX_HELD(&dtrace_lock));
11109
11110         *factor = 1;
11111
11112         if (size > dtrace_nonroot_maxsize &&
11113             !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11114                 return (EFBIG);
11115
11116         cp = cpu_list;
11117
11118         do {
11119                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11120                         continue;
11121
11122                 buf = &bufs[cp->cpu_id];
11123
11124                 /*
11125                  * If there is already a buffer allocated for this CPU, it
11126                  * is only possible that this is a DR event.  In this case,
11127                  */
11128                 if (buf->dtb_tomax != NULL) {
11129                         ASSERT(buf->dtb_size == size);
11130                         continue;
11131                 }
11132
11133                 ASSERT(buf->dtb_xamot == NULL);
11134
11135                 if ((buf->dtb_tomax = kmem_zalloc(size,
11136                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11137                         goto err;
11138
11139                 buf->dtb_size = size;
11140                 buf->dtb_flags = flags;
11141                 buf->dtb_offset = 0;
11142                 buf->dtb_drops = 0;
11143
11144                 if (flags & DTRACEBUF_NOSWITCH)
11145                         continue;
11146
11147                 if ((buf->dtb_xamot = kmem_zalloc(size,
11148                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11149                         goto err;
11150         } while ((cp = cp->cpu_next) != cpu_list);
11151
11152         return (0);
11153
11154 err:
11155         cp = cpu_list;
11156
11157         do {
11158                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11159                         continue;
11160
11161                 buf = &bufs[cp->cpu_id];
11162                 desired += 2;
11163
11164                 if (buf->dtb_xamot != NULL) {
11165                         ASSERT(buf->dtb_tomax != NULL);
11166                         ASSERT(buf->dtb_size == size);
11167                         kmem_free(buf->dtb_xamot, size);
11168                         allocated++;
11169                 }
11170
11171                 if (buf->dtb_tomax != NULL) {
11172                         ASSERT(buf->dtb_size == size);
11173                         kmem_free(buf->dtb_tomax, size);
11174                         allocated++;
11175                 }
11176
11177                 buf->dtb_tomax = NULL;
11178                 buf->dtb_xamot = NULL;
11179                 buf->dtb_size = 0;
11180         } while ((cp = cp->cpu_next) != cpu_list);
11181 #else
11182         int i;
11183
11184         *factor = 1;
11185 #if defined(__amd64__) || defined(__mips__) || defined(__powerpc__)
11186         /*
11187          * FreeBSD isn't good at limiting the amount of memory we
11188          * ask to malloc, so let's place a limit here before trying
11189          * to do something that might well end in tears at bedtime.
11190          */
11191         if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
11192                 return (ENOMEM);
11193 #endif
11194
11195         ASSERT(MUTEX_HELD(&dtrace_lock));
11196         CPU_FOREACH(i) {
11197                 if (cpu != DTRACE_CPUALL && cpu != i)
11198                         continue;
11199
11200                 buf = &bufs[i];
11201
11202                 /*
11203                  * If there is already a buffer allocated for this CPU, it
11204                  * is only possible that this is a DR event.  In this case,
11205                  * the buffer size must match our specified size.
11206                  */
11207                 if (buf->dtb_tomax != NULL) {
11208                         ASSERT(buf->dtb_size == size);
11209                         continue;
11210                 }
11211
11212                 ASSERT(buf->dtb_xamot == NULL);
11213
11214                 if ((buf->dtb_tomax = kmem_zalloc(size,
11215                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11216                         goto err;
11217
11218                 buf->dtb_size = size;
11219                 buf->dtb_flags = flags;
11220                 buf->dtb_offset = 0;
11221                 buf->dtb_drops = 0;
11222
11223                 if (flags & DTRACEBUF_NOSWITCH)
11224                         continue;
11225
11226                 if ((buf->dtb_xamot = kmem_zalloc(size,
11227                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11228                         goto err;
11229         }
11230
11231         return (0);
11232
11233 err:
11234         /*
11235          * Error allocating memory, so free the buffers that were
11236          * allocated before the failed allocation.
11237          */
11238         CPU_FOREACH(i) {
11239                 if (cpu != DTRACE_CPUALL && cpu != i)
11240                         continue;
11241
11242                 buf = &bufs[i];
11243                 desired += 2;
11244
11245                 if (buf->dtb_xamot != NULL) {
11246                         ASSERT(buf->dtb_tomax != NULL);
11247                         ASSERT(buf->dtb_size == size);
11248                         kmem_free(buf->dtb_xamot, size);
11249                         allocated++;
11250                 }
11251
11252                 if (buf->dtb_tomax != NULL) {
11253                         ASSERT(buf->dtb_size == size);
11254                         kmem_free(buf->dtb_tomax, size);
11255                         allocated++;
11256                 }
11257
11258                 buf->dtb_tomax = NULL;
11259                 buf->dtb_xamot = NULL;
11260                 buf->dtb_size = 0;
11261
11262         }
11263 #endif
11264         *factor = desired / (allocated > 0 ? allocated : 1);
11265
11266         return (ENOMEM);
11267 }
11268
11269 /*
11270  * Note:  called from probe context.  This function just increments the drop
11271  * count on a buffer.  It has been made a function to allow for the
11272  * possibility of understanding the source of mysterious drop counts.  (A
11273  * problem for which one may be particularly disappointed that DTrace cannot
11274  * be used to understand DTrace.)
11275  */
11276 static void
11277 dtrace_buffer_drop(dtrace_buffer_t *buf)
11278 {
11279         buf->dtb_drops++;
11280 }
11281
11282 /*
11283  * Note:  called from probe context.  This function is called to reserve space
11284  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11285  * mstate.  Returns the new offset in the buffer, or a negative value if an
11286  * error has occurred.
11287  */
11288 static intptr_t
11289 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11290     dtrace_state_t *state, dtrace_mstate_t *mstate)
11291 {
11292         intptr_t offs = buf->dtb_offset, soffs;
11293         intptr_t woffs;
11294         caddr_t tomax;
11295         size_t total;
11296
11297         if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11298                 return (-1);
11299
11300         if ((tomax = buf->dtb_tomax) == NULL) {
11301                 dtrace_buffer_drop(buf);
11302                 return (-1);
11303         }
11304
11305         if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11306                 while (offs & (align - 1)) {
11307                         /*
11308                          * Assert that our alignment is off by a number which
11309                          * is itself sizeof (uint32_t) aligned.
11310                          */
11311                         ASSERT(!((align - (offs & (align - 1))) &
11312                             (sizeof (uint32_t) - 1)));
11313                         DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11314                         offs += sizeof (uint32_t);
11315                 }
11316
11317                 if ((soffs = offs + needed) > buf->dtb_size) {
11318                         dtrace_buffer_drop(buf);
11319                         return (-1);
11320                 }
11321
11322                 if (mstate == NULL)
11323                         return (offs);
11324
11325                 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11326                 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11327                 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11328
11329                 return (offs);
11330         }
11331
11332         if (buf->dtb_flags & DTRACEBUF_FILL) {
11333                 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11334                     (buf->dtb_flags & DTRACEBUF_FULL))
11335                         return (-1);
11336                 goto out;
11337         }
11338
11339         total = needed + (offs & (align - 1));
11340
11341         /*
11342          * For a ring buffer, life is quite a bit more complicated.  Before
11343          * we can store any padding, we need to adjust our wrapping offset.
11344          * (If we've never before wrapped or we're not about to, no adjustment
11345          * is required.)
11346          */
11347         if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11348             offs + total > buf->dtb_size) {
11349                 woffs = buf->dtb_xamot_offset;
11350
11351                 if (offs + total > buf->dtb_size) {
11352                         /*
11353                          * We can't fit in the end of the buffer.  First, a
11354                          * sanity check that we can fit in the buffer at all.
11355                          */
11356                         if (total > buf->dtb_size) {
11357                                 dtrace_buffer_drop(buf);
11358                                 return (-1);
11359                         }
11360
11361                         /*
11362                          * We're going to be storing at the top of the buffer,
11363                          * so now we need to deal with the wrapped offset.  We
11364                          * only reset our wrapped offset to 0 if it is
11365                          * currently greater than the current offset.  If it
11366                          * is less than the current offset, it is because a
11367                          * previous allocation induced a wrap -- but the
11368                          * allocation didn't subsequently take the space due
11369                          * to an error or false predicate evaluation.  In this
11370                          * case, we'll just leave the wrapped offset alone: if
11371                          * the wrapped offset hasn't been advanced far enough
11372                          * for this allocation, it will be adjusted in the
11373                          * lower loop.
11374                          */
11375                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11376                                 if (woffs >= offs)
11377                                         woffs = 0;
11378                         } else {
11379                                 woffs = 0;
11380                         }
11381
11382                         /*
11383                          * Now we know that we're going to be storing to the
11384                          * top of the buffer and that there is room for us
11385                          * there.  We need to clear the buffer from the current
11386                          * offset to the end (there may be old gunk there).
11387                          */
11388                         while (offs < buf->dtb_size)
11389                                 tomax[offs++] = 0;
11390
11391                         /*
11392                          * We need to set our offset to zero.  And because we
11393                          * are wrapping, we need to set the bit indicating as
11394                          * much.  We can also adjust our needed space back
11395                          * down to the space required by the ECB -- we know
11396                          * that the top of the buffer is aligned.
11397                          */
11398                         offs = 0;
11399                         total = needed;
11400                         buf->dtb_flags |= DTRACEBUF_WRAPPED;
11401                 } else {
11402                         /*
11403                          * There is room for us in the buffer, so we simply
11404                          * need to check the wrapped offset.
11405                          */
11406                         if (woffs < offs) {
11407                                 /*
11408                                  * The wrapped offset is less than the offset.
11409                                  * This can happen if we allocated buffer space
11410                                  * that induced a wrap, but then we didn't
11411                                  * subsequently take the space due to an error
11412                                  * or false predicate evaluation.  This is
11413                                  * okay; we know that _this_ allocation isn't
11414                                  * going to induce a wrap.  We still can't
11415                                  * reset the wrapped offset to be zero,
11416                                  * however: the space may have been trashed in
11417                                  * the previous failed probe attempt.  But at
11418                                  * least the wrapped offset doesn't need to
11419                                  * be adjusted at all...
11420                                  */
11421                                 goto out;
11422                         }
11423                 }
11424
11425                 while (offs + total > woffs) {
11426                         dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11427                         size_t size;
11428
11429                         if (epid == DTRACE_EPIDNONE) {
11430                                 size = sizeof (uint32_t);
11431                         } else {
11432                                 ASSERT3U(epid, <=, state->dts_necbs);
11433                                 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11434
11435                                 size = state->dts_ecbs[epid - 1]->dte_size;
11436                         }
11437
11438                         ASSERT(woffs + size <= buf->dtb_size);
11439                         ASSERT(size != 0);
11440
11441                         if (woffs + size == buf->dtb_size) {
11442                                 /*
11443                                  * We've reached the end of the buffer; we want
11444                                  * to set the wrapped offset to 0 and break
11445                                  * out.  However, if the offs is 0, then we're
11446                                  * in a strange edge-condition:  the amount of
11447                                  * space that we want to reserve plus the size
11448                                  * of the record that we're overwriting is
11449                                  * greater than the size of the buffer.  This
11450                                  * is problematic because if we reserve the
11451                                  * space but subsequently don't consume it (due
11452                                  * to a failed predicate or error) the wrapped
11453                                  * offset will be 0 -- yet the EPID at offset 0
11454                                  * will not be committed.  This situation is
11455                                  * relatively easy to deal with:  if we're in
11456                                  * this case, the buffer is indistinguishable
11457                                  * from one that hasn't wrapped; we need only
11458                                  * finish the job by clearing the wrapped bit,
11459                                  * explicitly setting the offset to be 0, and
11460                                  * zero'ing out the old data in the buffer.
11461                                  */
11462                                 if (offs == 0) {
11463                                         buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11464                                         buf->dtb_offset = 0;
11465                                         woffs = total;
11466
11467                                         while (woffs < buf->dtb_size)
11468                                                 tomax[woffs++] = 0;
11469                                 }
11470
11471                                 woffs = 0;
11472                                 break;
11473                         }
11474
11475                         woffs += size;
11476                 }
11477
11478                 /*
11479                  * We have a wrapped offset.  It may be that the wrapped offset
11480                  * has become zero -- that's okay.
11481                  */
11482                 buf->dtb_xamot_offset = woffs;
11483         }
11484
11485 out:
11486         /*
11487          * Now we can plow the buffer with any necessary padding.
11488          */
11489         while (offs & (align - 1)) {
11490                 /*
11491                  * Assert that our alignment is off by a number which
11492                  * is itself sizeof (uint32_t) aligned.
11493                  */
11494                 ASSERT(!((align - (offs & (align - 1))) &
11495                     (sizeof (uint32_t) - 1)));
11496                 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11497                 offs += sizeof (uint32_t);
11498         }
11499
11500         if (buf->dtb_flags & DTRACEBUF_FILL) {
11501                 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11502                         buf->dtb_flags |= DTRACEBUF_FULL;
11503                         return (-1);
11504                 }
11505         }
11506
11507         if (mstate == NULL)
11508                 return (offs);
11509
11510         /*
11511          * For ring buffers and fill buffers, the scratch space is always
11512          * the inactive buffer.
11513          */
11514         mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11515         mstate->dtms_scratch_size = buf->dtb_size;
11516         mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11517
11518         return (offs);
11519 }
11520
11521 static void
11522 dtrace_buffer_polish(dtrace_buffer_t *buf)
11523 {
11524         ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11525         ASSERT(MUTEX_HELD(&dtrace_lock));
11526
11527         if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11528                 return;
11529
11530         /*
11531          * We need to polish the ring buffer.  There are three cases:
11532          *
11533          * - The first (and presumably most common) is that there is no gap
11534          *   between the buffer offset and the wrapped offset.  In this case,
11535          *   there is nothing in the buffer that isn't valid data; we can
11536          *   mark the buffer as polished and return.
11537          *
11538          * - The second (less common than the first but still more common
11539          *   than the third) is that there is a gap between the buffer offset
11540          *   and the wrapped offset, and the wrapped offset is larger than the
11541          *   buffer offset.  This can happen because of an alignment issue, or
11542          *   can happen because of a call to dtrace_buffer_reserve() that
11543          *   didn't subsequently consume the buffer space.  In this case,
11544          *   we need to zero the data from the buffer offset to the wrapped
11545          *   offset.
11546          *
11547          * - The third (and least common) is that there is a gap between the
11548          *   buffer offset and the wrapped offset, but the wrapped offset is
11549          *   _less_ than the buffer offset.  This can only happen because a
11550          *   call to dtrace_buffer_reserve() induced a wrap, but the space
11551          *   was not subsequently consumed.  In this case, we need to zero the
11552          *   space from the offset to the end of the buffer _and_ from the
11553          *   top of the buffer to the wrapped offset.
11554          */
11555         if (buf->dtb_offset < buf->dtb_xamot_offset) {
11556                 bzero(buf->dtb_tomax + buf->dtb_offset,
11557                     buf->dtb_xamot_offset - buf->dtb_offset);
11558         }
11559
11560         if (buf->dtb_offset > buf->dtb_xamot_offset) {
11561                 bzero(buf->dtb_tomax + buf->dtb_offset,
11562                     buf->dtb_size - buf->dtb_offset);
11563                 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11564         }
11565 }
11566
11567 /*
11568  * This routine determines if data generated at the specified time has likely
11569  * been entirely consumed at user-level.  This routine is called to determine
11570  * if an ECB on a defunct probe (but for an active enabling) can be safely
11571  * disabled and destroyed.
11572  */
11573 static int
11574 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11575 {
11576         int i;
11577
11578         for (i = 0; i < NCPU; i++) {
11579                 dtrace_buffer_t *buf = &bufs[i];
11580
11581                 if (buf->dtb_size == 0)
11582                         continue;
11583
11584                 if (buf->dtb_flags & DTRACEBUF_RING)
11585                         return (0);
11586
11587                 if (!buf->dtb_switched && buf->dtb_offset != 0)
11588                         return (0);
11589
11590                 if (buf->dtb_switched - buf->dtb_interval < when)
11591                         return (0);
11592         }
11593
11594         return (1);
11595 }
11596
11597 static void
11598 dtrace_buffer_free(dtrace_buffer_t *bufs)
11599 {
11600         int i;
11601
11602         for (i = 0; i < NCPU; i++) {
11603                 dtrace_buffer_t *buf = &bufs[i];
11604
11605                 if (buf->dtb_tomax == NULL) {
11606                         ASSERT(buf->dtb_xamot == NULL);
11607                         ASSERT(buf->dtb_size == 0);
11608                         continue;
11609                 }
11610
11611                 if (buf->dtb_xamot != NULL) {
11612                         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11613                         kmem_free(buf->dtb_xamot, buf->dtb_size);
11614                 }
11615
11616                 kmem_free(buf->dtb_tomax, buf->dtb_size);
11617                 buf->dtb_size = 0;
11618                 buf->dtb_tomax = NULL;
11619                 buf->dtb_xamot = NULL;
11620         }
11621 }
11622
11623 /*
11624  * DTrace Enabling Functions
11625  */
11626 static dtrace_enabling_t *
11627 dtrace_enabling_create(dtrace_vstate_t *vstate)
11628 {
11629         dtrace_enabling_t *enab;
11630
11631         enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11632         enab->dten_vstate = vstate;
11633
11634         return (enab);
11635 }
11636
11637 static void
11638 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11639 {
11640         dtrace_ecbdesc_t **ndesc;
11641         size_t osize, nsize;
11642
11643         /*
11644          * We can't add to enablings after we've enabled them, or after we've
11645          * retained them.
11646          */
11647         ASSERT(enab->dten_probegen == 0);
11648         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11649
11650         if (enab->dten_ndesc < enab->dten_maxdesc) {
11651                 enab->dten_desc[enab->dten_ndesc++] = ecb;
11652                 return;
11653         }
11654
11655         osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11656
11657         if (enab->dten_maxdesc == 0) {
11658                 enab->dten_maxdesc = 1;
11659         } else {
11660                 enab->dten_maxdesc <<= 1;
11661         }
11662
11663         ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11664
11665         nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11666         ndesc = kmem_zalloc(nsize, KM_SLEEP);
11667         bcopy(enab->dten_desc, ndesc, osize);
11668         if (enab->dten_desc != NULL)
11669                 kmem_free(enab->dten_desc, osize);
11670
11671         enab->dten_desc = ndesc;
11672         enab->dten_desc[enab->dten_ndesc++] = ecb;
11673 }
11674
11675 static void
11676 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11677     dtrace_probedesc_t *pd)
11678 {
11679         dtrace_ecbdesc_t *new;
11680         dtrace_predicate_t *pred;
11681         dtrace_actdesc_t *act;
11682
11683         /*
11684          * We're going to create a new ECB description that matches the
11685          * specified ECB in every way, but has the specified probe description.
11686          */
11687         new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11688
11689         if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11690                 dtrace_predicate_hold(pred);
11691
11692         for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11693                 dtrace_actdesc_hold(act);
11694
11695         new->dted_action = ecb->dted_action;
11696         new->dted_pred = ecb->dted_pred;
11697         new->dted_probe = *pd;
11698         new->dted_uarg = ecb->dted_uarg;
11699
11700         dtrace_enabling_add(enab, new);
11701 }
11702
11703 static void
11704 dtrace_enabling_dump(dtrace_enabling_t *enab)
11705 {
11706         int i;
11707
11708         for (i = 0; i < enab->dten_ndesc; i++) {
11709                 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11710
11711                 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11712                     desc->dtpd_provider, desc->dtpd_mod,
11713                     desc->dtpd_func, desc->dtpd_name);
11714         }
11715 }
11716
11717 static void
11718 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11719 {
11720         int i;
11721         dtrace_ecbdesc_t *ep;
11722         dtrace_vstate_t *vstate = enab->dten_vstate;
11723
11724         ASSERT(MUTEX_HELD(&dtrace_lock));
11725
11726         for (i = 0; i < enab->dten_ndesc; i++) {
11727                 dtrace_actdesc_t *act, *next;
11728                 dtrace_predicate_t *pred;
11729
11730                 ep = enab->dten_desc[i];
11731
11732                 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11733                         dtrace_predicate_release(pred, vstate);
11734
11735                 for (act = ep->dted_action; act != NULL; act = next) {
11736                         next = act->dtad_next;
11737                         dtrace_actdesc_release(act, vstate);
11738                 }
11739
11740                 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11741         }
11742
11743         if (enab->dten_desc != NULL)
11744                 kmem_free(enab->dten_desc,
11745                     enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11746
11747         /*
11748          * If this was a retained enabling, decrement the dts_nretained count
11749          * and take it off of the dtrace_retained list.
11750          */
11751         if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11752             dtrace_retained == enab) {
11753                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11754                 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11755                 enab->dten_vstate->dtvs_state->dts_nretained--;
11756         }
11757
11758         if (enab->dten_prev == NULL) {
11759                 if (dtrace_retained == enab) {
11760                         dtrace_retained = enab->dten_next;
11761
11762                         if (dtrace_retained != NULL)
11763                                 dtrace_retained->dten_prev = NULL;
11764                 }
11765         } else {
11766                 ASSERT(enab != dtrace_retained);
11767                 ASSERT(dtrace_retained != NULL);
11768                 enab->dten_prev->dten_next = enab->dten_next;
11769         }
11770
11771         if (enab->dten_next != NULL) {
11772                 ASSERT(dtrace_retained != NULL);
11773                 enab->dten_next->dten_prev = enab->dten_prev;
11774         }
11775
11776         kmem_free(enab, sizeof (dtrace_enabling_t));
11777 }
11778
11779 static int
11780 dtrace_enabling_retain(dtrace_enabling_t *enab)
11781 {
11782         dtrace_state_t *state;
11783
11784         ASSERT(MUTEX_HELD(&dtrace_lock));
11785         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11786         ASSERT(enab->dten_vstate != NULL);
11787
11788         state = enab->dten_vstate->dtvs_state;
11789         ASSERT(state != NULL);
11790
11791         /*
11792          * We only allow each state to retain dtrace_retain_max enablings.
11793          */
11794         if (state->dts_nretained >= dtrace_retain_max)
11795                 return (ENOSPC);
11796
11797         state->dts_nretained++;
11798
11799         if (dtrace_retained == NULL) {
11800                 dtrace_retained = enab;
11801                 return (0);
11802         }
11803
11804         enab->dten_next = dtrace_retained;
11805         dtrace_retained->dten_prev = enab;
11806         dtrace_retained = enab;
11807
11808         return (0);
11809 }
11810
11811 static int
11812 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11813     dtrace_probedesc_t *create)
11814 {
11815         dtrace_enabling_t *new, *enab;
11816         int found = 0, err = ENOENT;
11817
11818         ASSERT(MUTEX_HELD(&dtrace_lock));
11819         ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11820         ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11821         ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11822         ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11823
11824         new = dtrace_enabling_create(&state->dts_vstate);
11825
11826         /*
11827          * Iterate over all retained enablings, looking for enablings that
11828          * match the specified state.
11829          */
11830         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11831                 int i;
11832
11833                 /*
11834                  * dtvs_state can only be NULL for helper enablings -- and
11835                  * helper enablings can't be retained.
11836                  */
11837                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11838
11839                 if (enab->dten_vstate->dtvs_state != state)
11840                         continue;
11841
11842                 /*
11843                  * Now iterate over each probe description; we're looking for
11844                  * an exact match to the specified probe description.
11845                  */
11846                 for (i = 0; i < enab->dten_ndesc; i++) {
11847                         dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11848                         dtrace_probedesc_t *pd = &ep->dted_probe;
11849
11850                         if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11851                                 continue;
11852
11853                         if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11854                                 continue;
11855
11856                         if (strcmp(pd->dtpd_func, match->dtpd_func))
11857                                 continue;
11858
11859                         if (strcmp(pd->dtpd_name, match->dtpd_name))
11860                                 continue;
11861
11862                         /*
11863                          * We have a winning probe!  Add it to our growing
11864                          * enabling.
11865                          */
11866                         found = 1;
11867                         dtrace_enabling_addlike(new, ep, create);
11868                 }
11869         }
11870
11871         if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11872                 dtrace_enabling_destroy(new);
11873                 return (err);
11874         }
11875
11876         return (0);
11877 }
11878
11879 static void
11880 dtrace_enabling_retract(dtrace_state_t *state)
11881 {
11882         dtrace_enabling_t *enab, *next;
11883
11884         ASSERT(MUTEX_HELD(&dtrace_lock));
11885
11886         /*
11887          * Iterate over all retained enablings, destroy the enablings retained
11888          * for the specified state.
11889          */
11890         for (enab = dtrace_retained; enab != NULL; enab = next) {
11891                 next = enab->dten_next;
11892
11893                 /*
11894                  * dtvs_state can only be NULL for helper enablings -- and
11895                  * helper enablings can't be retained.
11896                  */
11897                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11898
11899                 if (enab->dten_vstate->dtvs_state == state) {
11900                         ASSERT(state->dts_nretained > 0);
11901                         dtrace_enabling_destroy(enab);
11902                 }
11903         }
11904
11905         ASSERT(state->dts_nretained == 0);
11906 }
11907
11908 static int
11909 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11910 {
11911         int i = 0;
11912         int matched = 0;
11913
11914         ASSERT(MUTEX_HELD(&cpu_lock));
11915         ASSERT(MUTEX_HELD(&dtrace_lock));
11916
11917         for (i = 0; i < enab->dten_ndesc; i++) {
11918                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11919
11920                 enab->dten_current = ep;
11921                 enab->dten_error = 0;
11922
11923                 matched += dtrace_probe_enable(&ep->dted_probe, enab);
11924
11925                 if (enab->dten_error != 0) {
11926                         /*
11927                          * If we get an error half-way through enabling the
11928                          * probes, we kick out -- perhaps with some number of
11929                          * them enabled.  Leaving enabled probes enabled may
11930                          * be slightly confusing for user-level, but we expect
11931                          * that no one will attempt to actually drive on in
11932                          * the face of such errors.  If this is an anonymous
11933                          * enabling (indicated with a NULL nmatched pointer),
11934                          * we cmn_err() a message.  We aren't expecting to
11935                          * get such an error -- such as it can exist at all,
11936                          * it would be a result of corrupted DOF in the driver
11937                          * properties.
11938                          */
11939                         if (nmatched == NULL) {
11940                                 cmn_err(CE_WARN, "dtrace_enabling_match() "
11941                                     "error on %p: %d", (void *)ep,
11942                                     enab->dten_error);
11943                         }
11944
11945                         return (enab->dten_error);
11946                 }
11947         }
11948
11949         enab->dten_probegen = dtrace_probegen;
11950         if (nmatched != NULL)
11951                 *nmatched = matched;
11952
11953         return (0);
11954 }
11955
11956 static void
11957 dtrace_enabling_matchall(void)
11958 {
11959         dtrace_enabling_t *enab;
11960
11961         mutex_enter(&cpu_lock);
11962         mutex_enter(&dtrace_lock);
11963
11964         /*
11965          * Iterate over all retained enablings to see if any probes match
11966          * against them.  We only perform this operation on enablings for which
11967          * we have sufficient permissions by virtue of being in the global zone
11968          * or in the same zone as the DTrace client.  Because we can be called
11969          * after dtrace_detach() has been called, we cannot assert that there
11970          * are retained enablings.  We can safely load from dtrace_retained,
11971          * however:  the taskq_destroy() at the end of dtrace_detach() will
11972          * block pending our completion.
11973          */
11974         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11975 #if defined(sun)
11976                 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
11977
11978                 if (INGLOBALZONE(curproc) || getzoneid() == crgetzoneid(cr))
11979 #endif
11980                         (void) dtrace_enabling_match(enab, NULL);
11981         }
11982
11983         mutex_exit(&dtrace_lock);
11984         mutex_exit(&cpu_lock);
11985 }
11986
11987 /*
11988  * If an enabling is to be enabled without having matched probes (that is, if
11989  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11990  * enabling must be _primed_ by creating an ECB for every ECB description.
11991  * This must be done to assure that we know the number of speculations, the
11992  * number of aggregations, the minimum buffer size needed, etc. before we
11993  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11994  * enabling any probes, we create ECBs for every ECB decription, but with a
11995  * NULL probe -- which is exactly what this function does.
11996  */
11997 static void
11998 dtrace_enabling_prime(dtrace_state_t *state)
11999 {
12000         dtrace_enabling_t *enab;
12001         int i;
12002
12003         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12004                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12005
12006                 if (enab->dten_vstate->dtvs_state != state)
12007                         continue;
12008
12009                 /*
12010                  * We don't want to prime an enabling more than once, lest
12011                  * we allow a malicious user to induce resource exhaustion.
12012                  * (The ECBs that result from priming an enabling aren't
12013                  * leaked -- but they also aren't deallocated until the
12014                  * consumer state is destroyed.)
12015                  */
12016                 if (enab->dten_primed)
12017                         continue;
12018
12019                 for (i = 0; i < enab->dten_ndesc; i++) {
12020                         enab->dten_current = enab->dten_desc[i];
12021                         (void) dtrace_probe_enable(NULL, enab);
12022                 }
12023
12024                 enab->dten_primed = 1;
12025         }
12026 }
12027
12028 /*
12029  * Called to indicate that probes should be provided due to retained
12030  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12031  * must take an initial lap through the enabling calling the dtps_provide()
12032  * entry point explicitly to allow for autocreated probes.
12033  */
12034 static void
12035 dtrace_enabling_provide(dtrace_provider_t *prv)
12036 {
12037         int i, all = 0;
12038         dtrace_probedesc_t desc;
12039
12040         ASSERT(MUTEX_HELD(&dtrace_lock));
12041         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12042
12043         if (prv == NULL) {
12044                 all = 1;
12045                 prv = dtrace_provider;
12046         }
12047
12048         do {
12049                 dtrace_enabling_t *enab = dtrace_retained;
12050                 void *parg = prv->dtpv_arg;
12051
12052                 for (; enab != NULL; enab = enab->dten_next) {
12053                         for (i = 0; i < enab->dten_ndesc; i++) {
12054                                 desc = enab->dten_desc[i]->dted_probe;
12055                                 mutex_exit(&dtrace_lock);
12056                                 prv->dtpv_pops.dtps_provide(parg, &desc);
12057                                 mutex_enter(&dtrace_lock);
12058                         }
12059                 }
12060         } while (all && (prv = prv->dtpv_next) != NULL);
12061
12062         mutex_exit(&dtrace_lock);
12063         dtrace_probe_provide(NULL, all ? NULL : prv);
12064         mutex_enter(&dtrace_lock);
12065 }
12066
12067 /*
12068  * Called to reap ECBs that are attached to probes from defunct providers.
12069  */
12070 static void
12071 dtrace_enabling_reap(void)
12072 {
12073         dtrace_provider_t *prov;
12074         dtrace_probe_t *probe;
12075         dtrace_ecb_t *ecb;
12076         hrtime_t when;
12077         int i;
12078
12079         mutex_enter(&cpu_lock);
12080         mutex_enter(&dtrace_lock);
12081
12082         for (i = 0; i < dtrace_nprobes; i++) {
12083                 if ((probe = dtrace_probes[i]) == NULL)
12084                         continue;
12085
12086                 if (probe->dtpr_ecb == NULL)
12087                         continue;
12088
12089                 prov = probe->dtpr_provider;
12090
12091                 if ((when = prov->dtpv_defunct) == 0)
12092                         continue;
12093
12094                 /*
12095                  * We have ECBs on a defunct provider:  we want to reap these
12096                  * ECBs to allow the provider to unregister.  The destruction
12097                  * of these ECBs must be done carefully:  if we destroy the ECB
12098                  * and the consumer later wishes to consume an EPID that
12099                  * corresponds to the destroyed ECB (and if the EPID metadata
12100                  * has not been previously consumed), the consumer will abort
12101                  * processing on the unknown EPID.  To reduce (but not, sadly,
12102                  * eliminate) the possibility of this, we will only destroy an
12103                  * ECB for a defunct provider if, for the state that
12104                  * corresponds to the ECB:
12105                  *
12106                  *  (a) There is no speculative tracing (which can effectively
12107                  *      cache an EPID for an arbitrary amount of time).
12108                  *
12109                  *  (b) The principal buffers have been switched twice since the
12110                  *      provider became defunct.
12111                  *
12112                  *  (c) The aggregation buffers are of zero size or have been
12113                  *      switched twice since the provider became defunct.
12114                  *
12115                  * We use dts_speculates to determine (a) and call a function
12116                  * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12117                  * that as soon as we've been unable to destroy one of the ECBs
12118                  * associated with the probe, we quit trying -- reaping is only
12119                  * fruitful in as much as we can destroy all ECBs associated
12120                  * with the defunct provider's probes.
12121                  */
12122                 while ((ecb = probe->dtpr_ecb) != NULL) {
12123                         dtrace_state_t *state = ecb->dte_state;
12124                         dtrace_buffer_t *buf = state->dts_buffer;
12125                         dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12126
12127                         if (state->dts_speculates)
12128                                 break;
12129
12130                         if (!dtrace_buffer_consumed(buf, when))
12131                                 break;
12132
12133                         if (!dtrace_buffer_consumed(aggbuf, when))
12134                                 break;
12135
12136                         dtrace_ecb_disable(ecb);
12137                         ASSERT(probe->dtpr_ecb != ecb);
12138                         dtrace_ecb_destroy(ecb);
12139                 }
12140         }
12141
12142         mutex_exit(&dtrace_lock);
12143         mutex_exit(&cpu_lock);
12144 }
12145
12146 /*
12147  * DTrace DOF Functions
12148  */
12149 /*ARGSUSED*/
12150 static void
12151 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12152 {
12153         if (dtrace_err_verbose)
12154                 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12155
12156 #ifdef DTRACE_ERRDEBUG
12157         dtrace_errdebug(str);
12158 #endif
12159 }
12160
12161 /*
12162  * Create DOF out of a currently enabled state.  Right now, we only create
12163  * DOF containing the run-time options -- but this could be expanded to create
12164  * complete DOF representing the enabled state.
12165  */
12166 static dof_hdr_t *
12167 dtrace_dof_create(dtrace_state_t *state)
12168 {
12169         dof_hdr_t *dof;
12170         dof_sec_t *sec;
12171         dof_optdesc_t *opt;
12172         int i, len = sizeof (dof_hdr_t) +
12173             roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12174             sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12175
12176         ASSERT(MUTEX_HELD(&dtrace_lock));
12177
12178         dof = kmem_zalloc(len, KM_SLEEP);
12179         dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12180         dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12181         dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12182         dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12183
12184         dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12185         dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12186         dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12187         dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12188         dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12189         dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12190
12191         dof->dofh_flags = 0;
12192         dof->dofh_hdrsize = sizeof (dof_hdr_t);
12193         dof->dofh_secsize = sizeof (dof_sec_t);
12194         dof->dofh_secnum = 1;   /* only DOF_SECT_OPTDESC */
12195         dof->dofh_secoff = sizeof (dof_hdr_t);
12196         dof->dofh_loadsz = len;
12197         dof->dofh_filesz = len;
12198         dof->dofh_pad = 0;
12199
12200         /*
12201          * Fill in the option section header...
12202          */
12203         sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12204         sec->dofs_type = DOF_SECT_OPTDESC;
12205         sec->dofs_align = sizeof (uint64_t);
12206         sec->dofs_flags = DOF_SECF_LOAD;
12207         sec->dofs_entsize = sizeof (dof_optdesc_t);
12208
12209         opt = (dof_optdesc_t *)((uintptr_t)sec +
12210             roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12211
12212         sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12213         sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12214
12215         for (i = 0; i < DTRACEOPT_MAX; i++) {
12216                 opt[i].dofo_option = i;
12217                 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12218                 opt[i].dofo_value = state->dts_options[i];
12219         }
12220
12221         return (dof);
12222 }
12223
12224 static dof_hdr_t *
12225 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12226 {
12227         dof_hdr_t hdr, *dof;
12228
12229         ASSERT(!MUTEX_HELD(&dtrace_lock));
12230
12231         /*
12232          * First, we're going to copyin() the sizeof (dof_hdr_t).
12233          */
12234         if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12235                 dtrace_dof_error(NULL, "failed to copyin DOF header");
12236                 *errp = EFAULT;
12237                 return (NULL);
12238         }
12239
12240         /*
12241          * Now we'll allocate the entire DOF and copy it in -- provided
12242          * that the length isn't outrageous.
12243          */
12244         if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12245                 dtrace_dof_error(&hdr, "load size exceeds maximum");
12246                 *errp = E2BIG;
12247                 return (NULL);
12248         }
12249
12250         if (hdr.dofh_loadsz < sizeof (hdr)) {
12251                 dtrace_dof_error(&hdr, "invalid load size");
12252                 *errp = EINVAL;
12253                 return (NULL);
12254         }
12255
12256         dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12257
12258         if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
12259                 kmem_free(dof, hdr.dofh_loadsz);
12260                 *errp = EFAULT;
12261                 return (NULL);
12262         }
12263
12264         return (dof);
12265 }
12266
12267 #if !defined(sun)
12268 static __inline uchar_t
12269 dtrace_dof_char(char c) {
12270         switch (c) {
12271         case '0':
12272         case '1':
12273         case '2':
12274         case '3':
12275         case '4':
12276         case '5':
12277         case '6':
12278         case '7':
12279         case '8':
12280         case '9':
12281                 return (c - '0');
12282         case 'A':
12283         case 'B':
12284         case 'C':
12285         case 'D':
12286         case 'E':
12287         case 'F':
12288                 return (c - 'A' + 10);
12289         case 'a':
12290         case 'b':
12291         case 'c':
12292         case 'd':
12293         case 'e':
12294         case 'f':
12295                 return (c - 'a' + 10);
12296         }
12297         /* Should not reach here. */
12298         return (0);
12299 }
12300 #endif
12301
12302 static dof_hdr_t *
12303 dtrace_dof_property(const char *name)
12304 {
12305         uchar_t *buf;
12306         uint64_t loadsz;
12307         unsigned int len, i;
12308         dof_hdr_t *dof;
12309
12310 #if defined(sun)
12311         /*
12312          * Unfortunately, array of values in .conf files are always (and
12313          * only) interpreted to be integer arrays.  We must read our DOF
12314          * as an integer array, and then squeeze it into a byte array.
12315          */
12316         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12317             (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12318                 return (NULL);
12319
12320         for (i = 0; i < len; i++)
12321                 buf[i] = (uchar_t)(((int *)buf)[i]);
12322
12323         if (len < sizeof (dof_hdr_t)) {
12324                 ddi_prop_free(buf);
12325                 dtrace_dof_error(NULL, "truncated header");
12326                 return (NULL);
12327         }
12328
12329         if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12330                 ddi_prop_free(buf);
12331                 dtrace_dof_error(NULL, "truncated DOF");
12332                 return (NULL);
12333         }
12334
12335         if (loadsz >= dtrace_dof_maxsize) {
12336                 ddi_prop_free(buf);
12337                 dtrace_dof_error(NULL, "oversized DOF");
12338                 return (NULL);
12339         }
12340
12341         dof = kmem_alloc(loadsz, KM_SLEEP);
12342         bcopy(buf, dof, loadsz);
12343         ddi_prop_free(buf);
12344 #else
12345         char *p;
12346         char *p_env;
12347
12348         if ((p_env = getenv(name)) == NULL)
12349                 return (NULL);
12350
12351         len = strlen(p_env) / 2;
12352
12353         buf = kmem_alloc(len, KM_SLEEP);
12354
12355         dof = (dof_hdr_t *) buf;
12356
12357         p = p_env;
12358
12359         for (i = 0; i < len; i++) {
12360                 buf[i] = (dtrace_dof_char(p[0]) << 4) |
12361                      dtrace_dof_char(p[1]);
12362                 p += 2;
12363         }
12364
12365         freeenv(p_env);
12366
12367         if (len < sizeof (dof_hdr_t)) {
12368                 kmem_free(buf, 0);
12369                 dtrace_dof_error(NULL, "truncated header");
12370                 return (NULL);
12371         }
12372
12373         if (len < (loadsz = dof->dofh_loadsz)) {
12374                 kmem_free(buf, 0);
12375                 dtrace_dof_error(NULL, "truncated DOF");
12376                 return (NULL);
12377         }
12378
12379         if (loadsz >= dtrace_dof_maxsize) {
12380                 kmem_free(buf, 0);
12381                 dtrace_dof_error(NULL, "oversized DOF");
12382                 return (NULL);
12383         }
12384 #endif
12385
12386         return (dof);
12387 }
12388
12389 static void
12390 dtrace_dof_destroy(dof_hdr_t *dof)
12391 {
12392         kmem_free(dof, dof->dofh_loadsz);
12393 }
12394
12395 /*
12396  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12397  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12398  * a type other than DOF_SECT_NONE is specified, the header is checked against
12399  * this type and NULL is returned if the types do not match.
12400  */
12401 static dof_sec_t *
12402 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12403 {
12404         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12405             ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12406
12407         if (i >= dof->dofh_secnum) {
12408                 dtrace_dof_error(dof, "referenced section index is invalid");
12409                 return (NULL);
12410         }
12411
12412         if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12413                 dtrace_dof_error(dof, "referenced section is not loadable");
12414                 return (NULL);
12415         }
12416
12417         if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12418                 dtrace_dof_error(dof, "referenced section is the wrong type");
12419                 return (NULL);
12420         }
12421
12422         return (sec);
12423 }
12424
12425 static dtrace_probedesc_t *
12426 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12427 {
12428         dof_probedesc_t *probe;
12429         dof_sec_t *strtab;
12430         uintptr_t daddr = (uintptr_t)dof;
12431         uintptr_t str;
12432         size_t size;
12433
12434         if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12435                 dtrace_dof_error(dof, "invalid probe section");
12436                 return (NULL);
12437         }
12438
12439         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12440                 dtrace_dof_error(dof, "bad alignment in probe description");
12441                 return (NULL);
12442         }
12443
12444         if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12445                 dtrace_dof_error(dof, "truncated probe description");
12446                 return (NULL);
12447         }
12448
12449         probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12450         strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12451
12452         if (strtab == NULL)
12453                 return (NULL);
12454
12455         str = daddr + strtab->dofs_offset;
12456         size = strtab->dofs_size;
12457
12458         if (probe->dofp_provider >= strtab->dofs_size) {
12459                 dtrace_dof_error(dof, "corrupt probe provider");
12460                 return (NULL);
12461         }
12462
12463         (void) strncpy(desc->dtpd_provider,
12464             (char *)(str + probe->dofp_provider),
12465             MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12466
12467         if (probe->dofp_mod >= strtab->dofs_size) {
12468                 dtrace_dof_error(dof, "corrupt probe module");
12469                 return (NULL);
12470         }
12471
12472         (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12473             MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12474
12475         if (probe->dofp_func >= strtab->dofs_size) {
12476                 dtrace_dof_error(dof, "corrupt probe function");
12477                 return (NULL);
12478         }
12479
12480         (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12481             MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12482
12483         if (probe->dofp_name >= strtab->dofs_size) {
12484                 dtrace_dof_error(dof, "corrupt probe name");
12485                 return (NULL);
12486         }
12487
12488         (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12489             MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12490
12491         return (desc);
12492 }
12493
12494 static dtrace_difo_t *
12495 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12496     cred_t *cr)
12497 {
12498         dtrace_difo_t *dp;
12499         size_t ttl = 0;
12500         dof_difohdr_t *dofd;
12501         uintptr_t daddr = (uintptr_t)dof;
12502         size_t max = dtrace_difo_maxsize;
12503         int i, l, n;
12504
12505         static const struct {
12506                 int section;
12507                 int bufoffs;
12508                 int lenoffs;
12509                 int entsize;
12510                 int align;
12511                 const char *msg;
12512         } difo[] = {
12513                 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12514                 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12515                 sizeof (dif_instr_t), "multiple DIF sections" },
12516
12517                 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12518                 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12519                 sizeof (uint64_t), "multiple integer tables" },
12520
12521                 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12522                 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12523                 sizeof (char), "multiple string tables" },
12524
12525                 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12526                 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12527                 sizeof (uint_t), "multiple variable tables" },
12528
12529                 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12530         };
12531
12532         if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12533                 dtrace_dof_error(dof, "invalid DIFO header section");
12534                 return (NULL);
12535         }
12536
12537         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12538                 dtrace_dof_error(dof, "bad alignment in DIFO header");
12539                 return (NULL);
12540         }
12541
12542         if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12543             sec->dofs_size % sizeof (dof_secidx_t)) {
12544                 dtrace_dof_error(dof, "bad size in DIFO header");
12545                 return (NULL);
12546         }
12547
12548         dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12549         n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12550
12551         dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12552         dp->dtdo_rtype = dofd->dofd_rtype;
12553
12554         for (l = 0; l < n; l++) {
12555                 dof_sec_t *subsec;
12556                 void **bufp;
12557                 uint32_t *lenp;
12558
12559                 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12560                     dofd->dofd_links[l])) == NULL)
12561                         goto err; /* invalid section link */
12562
12563                 if (ttl + subsec->dofs_size > max) {
12564                         dtrace_dof_error(dof, "exceeds maximum size");
12565                         goto err;
12566                 }
12567
12568                 ttl += subsec->dofs_size;
12569
12570                 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12571                         if (subsec->dofs_type != difo[i].section)
12572                                 continue;
12573
12574                         if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12575                                 dtrace_dof_error(dof, "section not loaded");
12576                                 goto err;
12577                         }
12578
12579                         if (subsec->dofs_align != difo[i].align) {
12580                                 dtrace_dof_error(dof, "bad alignment");
12581                                 goto err;
12582                         }
12583
12584                         bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12585                         lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12586
12587                         if (*bufp != NULL) {
12588                                 dtrace_dof_error(dof, difo[i].msg);
12589                                 goto err;
12590                         }
12591
12592                         if (difo[i].entsize != subsec->dofs_entsize) {
12593                                 dtrace_dof_error(dof, "entry size mismatch");
12594                                 goto err;
12595                         }
12596
12597                         if (subsec->dofs_entsize != 0 &&
12598                             (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12599                                 dtrace_dof_error(dof, "corrupt entry size");
12600                                 goto err;
12601                         }
12602
12603                         *lenp = subsec->dofs_size;
12604                         *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12605                         bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12606                             *bufp, subsec->dofs_size);
12607
12608                         if (subsec->dofs_entsize != 0)
12609                                 *lenp /= subsec->dofs_entsize;
12610
12611                         break;
12612                 }
12613
12614                 /*
12615                  * If we encounter a loadable DIFO sub-section that is not
12616                  * known to us, assume this is a broken program and fail.
12617                  */
12618                 if (difo[i].section == DOF_SECT_NONE &&
12619                     (subsec->dofs_flags & DOF_SECF_LOAD)) {
12620                         dtrace_dof_error(dof, "unrecognized DIFO subsection");
12621                         goto err;
12622                 }
12623         }
12624
12625         if (dp->dtdo_buf == NULL) {
12626                 /*
12627                  * We can't have a DIF object without DIF text.
12628                  */
12629                 dtrace_dof_error(dof, "missing DIF text");
12630                 goto err;
12631         }
12632
12633         /*
12634          * Before we validate the DIF object, run through the variable table
12635          * looking for the strings -- if any of their size are under, we'll set
12636          * their size to be the system-wide default string size.  Note that
12637          * this should _not_ happen if the "strsize" option has been set --
12638          * in this case, the compiler should have set the size to reflect the
12639          * setting of the option.
12640          */
12641         for (i = 0; i < dp->dtdo_varlen; i++) {
12642                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12643                 dtrace_diftype_t *t = &v->dtdv_type;
12644
12645                 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12646                         continue;
12647
12648                 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12649                         t->dtdt_size = dtrace_strsize_default;
12650         }
12651
12652         if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12653                 goto err;
12654
12655         dtrace_difo_init(dp, vstate);
12656         return (dp);
12657
12658 err:
12659         kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12660         kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12661         kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12662         kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12663
12664         kmem_free(dp, sizeof (dtrace_difo_t));
12665         return (NULL);
12666 }
12667
12668 static dtrace_predicate_t *
12669 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12670     cred_t *cr)
12671 {
12672         dtrace_difo_t *dp;
12673
12674         if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12675                 return (NULL);
12676
12677         return (dtrace_predicate_create(dp));
12678 }
12679
12680 static dtrace_actdesc_t *
12681 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12682     cred_t *cr)
12683 {
12684         dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12685         dof_actdesc_t *desc;
12686         dof_sec_t *difosec;
12687         size_t offs;
12688         uintptr_t daddr = (uintptr_t)dof;
12689         uint64_t arg;
12690         dtrace_actkind_t kind;
12691
12692         if (sec->dofs_type != DOF_SECT_ACTDESC) {
12693                 dtrace_dof_error(dof, "invalid action section");
12694                 return (NULL);
12695         }
12696
12697         if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12698                 dtrace_dof_error(dof, "truncated action description");
12699                 return (NULL);
12700         }
12701
12702         if (sec->dofs_align != sizeof (uint64_t)) {
12703                 dtrace_dof_error(dof, "bad alignment in action description");
12704                 return (NULL);
12705         }
12706
12707         if (sec->dofs_size < sec->dofs_entsize) {
12708                 dtrace_dof_error(dof, "section entry size exceeds total size");
12709                 return (NULL);
12710         }
12711
12712         if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12713                 dtrace_dof_error(dof, "bad entry size in action description");
12714                 return (NULL);
12715         }
12716
12717         if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12718                 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12719                 return (NULL);
12720         }
12721
12722         for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12723                 desc = (dof_actdesc_t *)(daddr +
12724                     (uintptr_t)sec->dofs_offset + offs);
12725                 kind = (dtrace_actkind_t)desc->dofa_kind;
12726
12727                 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12728                     (kind != DTRACEACT_PRINTA ||
12729                     desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12730                     (kind == DTRACEACT_DIFEXPR &&
12731                     desc->dofa_strtab != DOF_SECIDX_NONE)) {
12732                         dof_sec_t *strtab;
12733                         char *str, *fmt;
12734                         uint64_t i;
12735
12736                         /*
12737                          * The argument to these actions is an index into the
12738                          * DOF string table.  For printf()-like actions, this
12739                          * is the format string.  For print(), this is the
12740                          * CTF type of the expression result.
12741                          */
12742                         if ((strtab = dtrace_dof_sect(dof,
12743                             DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12744                                 goto err;
12745
12746                         str = (char *)((uintptr_t)dof +
12747                             (uintptr_t)strtab->dofs_offset);
12748
12749                         for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12750                                 if (str[i] == '\0')
12751                                         break;
12752                         }
12753
12754                         if (i >= strtab->dofs_size) {
12755                                 dtrace_dof_error(dof, "bogus format string");
12756                                 goto err;
12757                         }
12758
12759                         if (i == desc->dofa_arg) {
12760                                 dtrace_dof_error(dof, "empty format string");
12761                                 goto err;
12762                         }
12763
12764                         i -= desc->dofa_arg;
12765                         fmt = kmem_alloc(i + 1, KM_SLEEP);
12766                         bcopy(&str[desc->dofa_arg], fmt, i + 1);
12767                         arg = (uint64_t)(uintptr_t)fmt;
12768                 } else {
12769                         if (kind == DTRACEACT_PRINTA) {
12770                                 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12771                                 arg = 0;
12772                         } else {
12773                                 arg = desc->dofa_arg;
12774                         }
12775                 }
12776
12777                 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12778                     desc->dofa_uarg, arg);
12779
12780                 if (last != NULL) {
12781                         last->dtad_next = act;
12782                 } else {
12783                         first = act;
12784                 }
12785
12786                 last = act;
12787
12788                 if (desc->dofa_difo == DOF_SECIDX_NONE)
12789                         continue;
12790
12791                 if ((difosec = dtrace_dof_sect(dof,
12792                     DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12793                         goto err;
12794
12795                 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12796
12797                 if (act->dtad_difo == NULL)
12798                         goto err;
12799         }
12800
12801         ASSERT(first != NULL);
12802         return (first);
12803
12804 err:
12805         for (act = first; act != NULL; act = next) {
12806                 next = act->dtad_next;
12807                 dtrace_actdesc_release(act, vstate);
12808         }
12809
12810         return (NULL);
12811 }
12812
12813 static dtrace_ecbdesc_t *
12814 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12815     cred_t *cr)
12816 {
12817         dtrace_ecbdesc_t *ep;
12818         dof_ecbdesc_t *ecb;
12819         dtrace_probedesc_t *desc;
12820         dtrace_predicate_t *pred = NULL;
12821
12822         if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12823                 dtrace_dof_error(dof, "truncated ECB description");
12824                 return (NULL);
12825         }
12826
12827         if (sec->dofs_align != sizeof (uint64_t)) {
12828                 dtrace_dof_error(dof, "bad alignment in ECB description");
12829                 return (NULL);
12830         }
12831
12832         ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12833         sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12834
12835         if (sec == NULL)
12836                 return (NULL);
12837
12838         ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12839         ep->dted_uarg = ecb->dofe_uarg;
12840         desc = &ep->dted_probe;
12841
12842         if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12843                 goto err;
12844
12845         if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12846                 if ((sec = dtrace_dof_sect(dof,
12847                     DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12848                         goto err;
12849
12850                 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12851                         goto err;
12852
12853                 ep->dted_pred.dtpdd_predicate = pred;
12854         }
12855
12856         if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12857                 if ((sec = dtrace_dof_sect(dof,
12858                     DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12859                         goto err;
12860
12861                 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12862
12863                 if (ep->dted_action == NULL)
12864                         goto err;
12865         }
12866
12867         return (ep);
12868
12869 err:
12870         if (pred != NULL)
12871                 dtrace_predicate_release(pred, vstate);
12872         kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12873         return (NULL);
12874 }
12875
12876 /*
12877  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12878  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12879  * site of any user SETX relocations to account for load object base address.
12880  * In the future, if we need other relocations, this function can be extended.
12881  */
12882 static int
12883 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12884 {
12885         uintptr_t daddr = (uintptr_t)dof;
12886         dof_relohdr_t *dofr =
12887             (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12888         dof_sec_t *ss, *rs, *ts;
12889         dof_relodesc_t *r;
12890         uint_t i, n;
12891
12892         if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12893             sec->dofs_align != sizeof (dof_secidx_t)) {
12894                 dtrace_dof_error(dof, "invalid relocation header");
12895                 return (-1);
12896         }
12897
12898         ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12899         rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12900         ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12901
12902         if (ss == NULL || rs == NULL || ts == NULL)
12903                 return (-1); /* dtrace_dof_error() has been called already */
12904
12905         if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12906             rs->dofs_align != sizeof (uint64_t)) {
12907                 dtrace_dof_error(dof, "invalid relocation section");
12908                 return (-1);
12909         }
12910
12911         r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12912         n = rs->dofs_size / rs->dofs_entsize;
12913
12914         for (i = 0; i < n; i++) {
12915                 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12916
12917                 switch (r->dofr_type) {
12918                 case DOF_RELO_NONE:
12919                         break;
12920                 case DOF_RELO_SETX:
12921                         if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12922                             sizeof (uint64_t) > ts->dofs_size) {
12923                                 dtrace_dof_error(dof, "bad relocation offset");
12924                                 return (-1);
12925                         }
12926
12927                         if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12928                                 dtrace_dof_error(dof, "misaligned setx relo");
12929                                 return (-1);
12930                         }
12931
12932                         *(uint64_t *)taddr += ubase;
12933                         break;
12934                 default:
12935                         dtrace_dof_error(dof, "invalid relocation type");
12936                         return (-1);
12937                 }
12938
12939                 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12940         }
12941
12942         return (0);
12943 }
12944
12945 /*
12946  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12947  * header:  it should be at the front of a memory region that is at least
12948  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12949  * size.  It need not be validated in any other way.
12950  */
12951 static int
12952 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12953     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12954 {
12955         uint64_t len = dof->dofh_loadsz, seclen;
12956         uintptr_t daddr = (uintptr_t)dof;
12957         dtrace_ecbdesc_t *ep;
12958         dtrace_enabling_t *enab;
12959         uint_t i;
12960
12961         ASSERT(MUTEX_HELD(&dtrace_lock));
12962         ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12963
12964         /*
12965          * Check the DOF header identification bytes.  In addition to checking
12966          * valid settings, we also verify that unused bits/bytes are zeroed so
12967          * we can use them later without fear of regressing existing binaries.
12968          */
12969         if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12970             DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12971                 dtrace_dof_error(dof, "DOF magic string mismatch");
12972                 return (-1);
12973         }
12974
12975         if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12976             dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12977                 dtrace_dof_error(dof, "DOF has invalid data model");
12978                 return (-1);
12979         }
12980
12981         if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12982                 dtrace_dof_error(dof, "DOF encoding mismatch");
12983                 return (-1);
12984         }
12985
12986         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12987             dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12988                 dtrace_dof_error(dof, "DOF version mismatch");
12989                 return (-1);
12990         }
12991
12992         if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12993                 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12994                 return (-1);
12995         }
12996
12997         if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12998                 dtrace_dof_error(dof, "DOF uses too many integer registers");
12999                 return (-1);
13000         }
13001
13002         if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13003                 dtrace_dof_error(dof, "DOF uses too many tuple registers");
13004                 return (-1);
13005         }
13006
13007         for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13008                 if (dof->dofh_ident[i] != 0) {
13009                         dtrace_dof_error(dof, "DOF has invalid ident byte set");
13010                         return (-1);
13011                 }
13012         }
13013
13014         if (dof->dofh_flags & ~DOF_FL_VALID) {
13015                 dtrace_dof_error(dof, "DOF has invalid flag bits set");
13016                 return (-1);
13017         }
13018
13019         if (dof->dofh_secsize == 0) {
13020                 dtrace_dof_error(dof, "zero section header size");
13021                 return (-1);
13022         }
13023
13024         /*
13025          * Check that the section headers don't exceed the amount of DOF
13026          * data.  Note that we cast the section size and number of sections
13027          * to uint64_t's to prevent possible overflow in the multiplication.
13028          */
13029         seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13030
13031         if (dof->dofh_secoff > len || seclen > len ||
13032             dof->dofh_secoff + seclen > len) {
13033                 dtrace_dof_error(dof, "truncated section headers");
13034                 return (-1);
13035         }
13036
13037         if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13038                 dtrace_dof_error(dof, "misaligned section headers");
13039                 return (-1);
13040         }
13041
13042         if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13043                 dtrace_dof_error(dof, "misaligned section size");
13044                 return (-1);
13045         }
13046
13047         /*
13048          * Take an initial pass through the section headers to be sure that
13049          * the headers don't have stray offsets.  If the 'noprobes' flag is
13050          * set, do not permit sections relating to providers, probes, or args.
13051          */
13052         for (i = 0; i < dof->dofh_secnum; i++) {
13053                 dof_sec_t *sec = (dof_sec_t *)(daddr +
13054                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13055
13056                 if (noprobes) {
13057                         switch (sec->dofs_type) {
13058                         case DOF_SECT_PROVIDER:
13059                         case DOF_SECT_PROBES:
13060                         case DOF_SECT_PRARGS:
13061                         case DOF_SECT_PROFFS:
13062                                 dtrace_dof_error(dof, "illegal sections "
13063                                     "for enabling");
13064                                 return (-1);
13065                         }
13066                 }
13067
13068                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13069                         continue; /* just ignore non-loadable sections */
13070
13071                 if (sec->dofs_align & (sec->dofs_align - 1)) {
13072                         dtrace_dof_error(dof, "bad section alignment");
13073                         return (-1);
13074                 }
13075
13076                 if (sec->dofs_offset & (sec->dofs_align - 1)) {
13077                         dtrace_dof_error(dof, "misaligned section");
13078                         return (-1);
13079                 }
13080
13081                 if (sec->dofs_offset > len || sec->dofs_size > len ||
13082                     sec->dofs_offset + sec->dofs_size > len) {
13083                         dtrace_dof_error(dof, "corrupt section header");
13084                         return (-1);
13085                 }
13086
13087                 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13088                     sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13089                         dtrace_dof_error(dof, "non-terminating string table");
13090                         return (-1);
13091                 }
13092         }
13093
13094         /*
13095          * Take a second pass through the sections and locate and perform any
13096          * relocations that are present.  We do this after the first pass to
13097          * be sure that all sections have had their headers validated.
13098          */
13099         for (i = 0; i < dof->dofh_secnum; i++) {
13100                 dof_sec_t *sec = (dof_sec_t *)(daddr +
13101                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13102
13103                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13104                         continue; /* skip sections that are not loadable */
13105
13106                 switch (sec->dofs_type) {
13107                 case DOF_SECT_URELHDR:
13108                         if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13109                                 return (-1);
13110                         break;
13111                 }
13112         }
13113
13114         if ((enab = *enabp) == NULL)
13115                 enab = *enabp = dtrace_enabling_create(vstate);
13116
13117         for (i = 0; i < dof->dofh_secnum; i++) {
13118                 dof_sec_t *sec = (dof_sec_t *)(daddr +
13119                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13120
13121                 if (sec->dofs_type != DOF_SECT_ECBDESC)
13122                         continue;
13123
13124                 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13125                         dtrace_enabling_destroy(enab);
13126                         *enabp = NULL;
13127                         return (-1);
13128                 }
13129
13130                 dtrace_enabling_add(enab, ep);
13131         }
13132
13133         return (0);
13134 }
13135
13136 /*
13137  * Process DOF for any options.  This routine assumes that the DOF has been
13138  * at least processed by dtrace_dof_slurp().
13139  */
13140 static int
13141 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13142 {
13143         int i, rval;
13144         uint32_t entsize;
13145         size_t offs;
13146         dof_optdesc_t *desc;
13147
13148         for (i = 0; i < dof->dofh_secnum; i++) {
13149                 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13150                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13151
13152                 if (sec->dofs_type != DOF_SECT_OPTDESC)
13153                         continue;
13154
13155                 if (sec->dofs_align != sizeof (uint64_t)) {
13156                         dtrace_dof_error(dof, "bad alignment in "
13157                             "option description");
13158                         return (EINVAL);
13159                 }
13160
13161                 if ((entsize = sec->dofs_entsize) == 0) {
13162                         dtrace_dof_error(dof, "zeroed option entry size");
13163                         return (EINVAL);
13164                 }
13165
13166                 if (entsize < sizeof (dof_optdesc_t)) {
13167                         dtrace_dof_error(dof, "bad option entry size");
13168                         return (EINVAL);
13169                 }
13170
13171                 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13172                         desc = (dof_optdesc_t *)((uintptr_t)dof +
13173                             (uintptr_t)sec->dofs_offset + offs);
13174
13175                         if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13176                                 dtrace_dof_error(dof, "non-zero option string");
13177                                 return (EINVAL);
13178                         }
13179
13180                         if (desc->dofo_value == DTRACEOPT_UNSET) {
13181                                 dtrace_dof_error(dof, "unset option");
13182                                 return (EINVAL);
13183                         }
13184
13185                         if ((rval = dtrace_state_option(state,
13186                             desc->dofo_option, desc->dofo_value)) != 0) {
13187                                 dtrace_dof_error(dof, "rejected option");
13188                                 return (rval);
13189                         }
13190                 }
13191         }
13192
13193         return (0);
13194 }
13195
13196 /*
13197  * DTrace Consumer State Functions
13198  */
13199 static int
13200 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13201 {
13202         size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13203         void *base;
13204         uintptr_t limit;
13205         dtrace_dynvar_t *dvar, *next, *start;
13206         int i;
13207
13208         ASSERT(MUTEX_HELD(&dtrace_lock));
13209         ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13210
13211         bzero(dstate, sizeof (dtrace_dstate_t));
13212
13213         if ((dstate->dtds_chunksize = chunksize) == 0)
13214                 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13215
13216         if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13217                 size = min;
13218
13219         if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13220                 return (ENOMEM);
13221
13222         dstate->dtds_size = size;
13223         dstate->dtds_base = base;
13224         dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13225         bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13226
13227         hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13228
13229         if (hashsize != 1 && (hashsize & 1))
13230                 hashsize--;
13231
13232         dstate->dtds_hashsize = hashsize;
13233         dstate->dtds_hash = dstate->dtds_base;
13234
13235         /*
13236          * Set all of our hash buckets to point to the single sink, and (if
13237          * it hasn't already been set), set the sink's hash value to be the
13238          * sink sentinel value.  The sink is needed for dynamic variable
13239          * lookups to know that they have iterated over an entire, valid hash
13240          * chain.
13241          */
13242         for (i = 0; i < hashsize; i++)
13243                 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13244
13245         if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13246                 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13247
13248         /*
13249          * Determine number of active CPUs.  Divide free list evenly among
13250          * active CPUs.
13251          */
13252         start = (dtrace_dynvar_t *)
13253             ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13254         limit = (uintptr_t)base + size;
13255
13256         maxper = (limit - (uintptr_t)start) / NCPU;
13257         maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13258
13259 #if !defined(sun)
13260         CPU_FOREACH(i) {
13261 #else
13262         for (i = 0; i < NCPU; i++) {
13263 #endif
13264                 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13265
13266                 /*
13267                  * If we don't even have enough chunks to make it once through
13268                  * NCPUs, we're just going to allocate everything to the first
13269                  * CPU.  And if we're on the last CPU, we're going to allocate
13270                  * whatever is left over.  In either case, we set the limit to
13271                  * be the limit of the dynamic variable space.
13272                  */
13273                 if (maxper == 0 || i == NCPU - 1) {
13274                         limit = (uintptr_t)base + size;
13275                         start = NULL;
13276                 } else {
13277                         limit = (uintptr_t)start + maxper;
13278                         start = (dtrace_dynvar_t *)limit;
13279                 }
13280
13281                 ASSERT(limit <= (uintptr_t)base + size);
13282
13283                 for (;;) {
13284                         next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13285                             dstate->dtds_chunksize);
13286
13287                         if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13288                                 break;
13289
13290                         dvar->dtdv_next = next;
13291                         dvar = next;
13292                 }
13293
13294                 if (maxper == 0)
13295                         break;
13296         }
13297
13298         return (0);
13299 }
13300
13301 static void
13302 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13303 {
13304         ASSERT(MUTEX_HELD(&cpu_lock));
13305
13306         if (dstate->dtds_base == NULL)
13307                 return;
13308
13309         kmem_free(dstate->dtds_base, dstate->dtds_size);
13310         kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13311 }
13312
13313 static void
13314 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13315 {
13316         /*
13317          * Logical XOR, where are you?
13318          */
13319         ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13320
13321         if (vstate->dtvs_nglobals > 0) {
13322                 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13323                     sizeof (dtrace_statvar_t *));
13324         }
13325
13326         if (vstate->dtvs_ntlocals > 0) {
13327                 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13328                     sizeof (dtrace_difv_t));
13329         }
13330
13331         ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13332
13333         if (vstate->dtvs_nlocals > 0) {
13334                 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13335                     sizeof (dtrace_statvar_t *));
13336         }
13337 }
13338
13339 #if defined(sun)
13340 static void
13341 dtrace_state_clean(dtrace_state_t *state)
13342 {
13343         if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13344                 return;
13345
13346         dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13347         dtrace_speculation_clean(state);
13348 }
13349
13350 static void
13351 dtrace_state_deadman(dtrace_state_t *state)
13352 {
13353         hrtime_t now;
13354
13355         dtrace_sync();
13356
13357         now = dtrace_gethrtime();
13358
13359         if (state != dtrace_anon.dta_state &&
13360             now - state->dts_laststatus >= dtrace_deadman_user)
13361                 return;
13362
13363         /*
13364          * We must be sure that dts_alive never appears to be less than the
13365          * value upon entry to dtrace_state_deadman(), and because we lack a
13366          * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13367          * store INT64_MAX to it, followed by a memory barrier, followed by
13368          * the new value.  This assures that dts_alive never appears to be
13369          * less than its true value, regardless of the order in which the
13370          * stores to the underlying storage are issued.
13371          */
13372         state->dts_alive = INT64_MAX;
13373         dtrace_membar_producer();
13374         state->dts_alive = now;
13375 }
13376 #else
13377 static void
13378 dtrace_state_clean(void *arg)
13379 {
13380         dtrace_state_t *state = arg;
13381         dtrace_optval_t *opt = state->dts_options;
13382
13383         if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13384                 return;
13385
13386         dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13387         dtrace_speculation_clean(state);
13388
13389         callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13390             dtrace_state_clean, state);
13391 }
13392
13393 static void
13394 dtrace_state_deadman(void *arg)
13395 {
13396         dtrace_state_t *state = arg;
13397         hrtime_t now;
13398
13399         dtrace_sync();
13400
13401         dtrace_debug_output();
13402
13403         now = dtrace_gethrtime();
13404
13405         if (state != dtrace_anon.dta_state &&
13406             now - state->dts_laststatus >= dtrace_deadman_user)
13407                 return;
13408
13409         /*
13410          * We must be sure that dts_alive never appears to be less than the
13411          * value upon entry to dtrace_state_deadman(), and because we lack a
13412          * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13413          * store INT64_MAX to it, followed by a memory barrier, followed by
13414          * the new value.  This assures that dts_alive never appears to be
13415          * less than its true value, regardless of the order in which the
13416          * stores to the underlying storage are issued.
13417          */
13418         state->dts_alive = INT64_MAX;
13419         dtrace_membar_producer();
13420         state->dts_alive = now;
13421
13422         callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13423             dtrace_state_deadman, state);
13424 }
13425 #endif
13426
13427 static dtrace_state_t *
13428 #if defined(sun)
13429 dtrace_state_create(dev_t *devp, cred_t *cr)
13430 #else
13431 dtrace_state_create(struct cdev *dev)
13432 #endif
13433 {
13434 #if defined(sun)
13435         minor_t minor;
13436         major_t major;
13437 #else
13438         cred_t *cr = NULL;
13439         int m = 0;
13440 #endif
13441         char c[30];
13442         dtrace_state_t *state;
13443         dtrace_optval_t *opt;
13444         int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13445
13446         ASSERT(MUTEX_HELD(&dtrace_lock));
13447         ASSERT(MUTEX_HELD(&cpu_lock));
13448
13449 #if defined(sun)
13450         minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13451             VM_BESTFIT | VM_SLEEP);
13452
13453         if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13454                 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13455                 return (NULL);
13456         }
13457
13458         state = ddi_get_soft_state(dtrace_softstate, minor);
13459 #else
13460         if (dev != NULL) {
13461                 cr = dev->si_cred;
13462                 m = dev2unit(dev);
13463                 }
13464
13465         /* Allocate memory for the state. */
13466         state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
13467 #endif
13468
13469         state->dts_epid = DTRACE_EPIDNONE + 1;
13470
13471         (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
13472 #if defined(sun)
13473         state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13474             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13475
13476         if (devp != NULL) {
13477                 major = getemajor(*devp);
13478         } else {
13479                 major = ddi_driver_major(dtrace_devi);
13480         }
13481
13482         state->dts_dev = makedevice(major, minor);
13483
13484         if (devp != NULL)
13485                 *devp = state->dts_dev;
13486 #else
13487         state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
13488         state->dts_dev = dev;
13489 #endif
13490
13491         /*
13492          * We allocate NCPU buffers.  On the one hand, this can be quite
13493          * a bit of memory per instance (nearly 36K on a Starcat).  On the
13494          * other hand, it saves an additional memory reference in the probe
13495          * path.
13496          */
13497         state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13498         state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13499
13500 #if defined(sun)
13501         state->dts_cleaner = CYCLIC_NONE;
13502         state->dts_deadman = CYCLIC_NONE;
13503 #else
13504         callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
13505         callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
13506 #endif
13507         state->dts_vstate.dtvs_state = state;
13508
13509         for (i = 0; i < DTRACEOPT_MAX; i++)
13510                 state->dts_options[i] = DTRACEOPT_UNSET;
13511
13512         /*
13513          * Set the default options.
13514          */
13515         opt = state->dts_options;
13516         opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13517         opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13518         opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13519         opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13520         opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13521         opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13522         opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13523         opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13524         opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13525         opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13526         opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13527         opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13528         opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13529         opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13530
13531         state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13532
13533         /*
13534          * Depending on the user credentials, we set flag bits which alter probe
13535          * visibility or the amount of destructiveness allowed.  In the case of
13536          * actual anonymous tracing, or the possession of all privileges, all of
13537          * the normal checks are bypassed.
13538          */
13539         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13540                 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13541                 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13542         } else {
13543                 /*
13544                  * Set up the credentials for this instantiation.  We take a
13545                  * hold on the credential to prevent it from disappearing on
13546                  * us; this in turn prevents the zone_t referenced by this
13547                  * credential from disappearing.  This means that we can
13548                  * examine the credential and the zone from probe context.
13549                  */
13550                 crhold(cr);
13551                 state->dts_cred.dcr_cred = cr;
13552
13553                 /*
13554                  * CRA_PROC means "we have *some* privilege for dtrace" and
13555                  * unlocks the use of variables like pid, zonename, etc.
13556                  */
13557                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13558                     PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13559                         state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13560                 }
13561
13562                 /*
13563                  * dtrace_user allows use of syscall and profile providers.
13564                  * If the user also has proc_owner and/or proc_zone, we
13565                  * extend the scope to include additional visibility and
13566                  * destructive power.
13567                  */
13568                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13569                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13570                                 state->dts_cred.dcr_visible |=
13571                                     DTRACE_CRV_ALLPROC;
13572
13573                                 state->dts_cred.dcr_action |=
13574                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13575                         }
13576
13577                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13578                                 state->dts_cred.dcr_visible |=
13579                                     DTRACE_CRV_ALLZONE;
13580
13581                                 state->dts_cred.dcr_action |=
13582                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13583                         }
13584
13585                         /*
13586                          * If we have all privs in whatever zone this is,
13587                          * we can do destructive things to processes which
13588                          * have altered credentials.
13589                          */
13590 #if defined(sun)
13591                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13592                             cr->cr_zone->zone_privset)) {
13593                                 state->dts_cred.dcr_action |=
13594                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13595                         }
13596 #endif
13597                 }
13598
13599                 /*
13600                  * Holding the dtrace_kernel privilege also implies that
13601                  * the user has the dtrace_user privilege from a visibility
13602                  * perspective.  But without further privileges, some
13603                  * destructive actions are not available.
13604                  */
13605                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13606                         /*
13607                          * Make all probes in all zones visible.  However,
13608                          * this doesn't mean that all actions become available
13609                          * to all zones.
13610                          */
13611                         state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13612                             DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13613
13614                         state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13615                             DTRACE_CRA_PROC;
13616                         /*
13617                          * Holding proc_owner means that destructive actions
13618                          * for *this* zone are allowed.
13619                          */
13620                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13621                                 state->dts_cred.dcr_action |=
13622                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13623
13624                         /*
13625                          * Holding proc_zone means that destructive actions
13626                          * for this user/group ID in all zones is allowed.
13627                          */
13628                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13629                                 state->dts_cred.dcr_action |=
13630                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13631
13632 #if defined(sun)
13633                         /*
13634                          * If we have all privs in whatever zone this is,
13635                          * we can do destructive things to processes which
13636                          * have altered credentials.
13637                          */
13638                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13639                             cr->cr_zone->zone_privset)) {
13640                                 state->dts_cred.dcr_action |=
13641                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13642                         }
13643 #endif
13644                 }
13645
13646                 /*
13647                  * Holding the dtrace_proc privilege gives control over fasttrap
13648                  * and pid providers.  We need to grant wider destructive
13649                  * privileges in the event that the user has proc_owner and/or
13650                  * proc_zone.
13651                  */
13652                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13653                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13654                                 state->dts_cred.dcr_action |=
13655                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13656
13657                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13658                                 state->dts_cred.dcr_action |=
13659                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13660                 }
13661         }
13662
13663         return (state);
13664 }
13665
13666 static int
13667 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13668 {
13669         dtrace_optval_t *opt = state->dts_options, size;
13670         processorid_t cpu = 0;;
13671         int flags = 0, rval, factor, divisor = 1;
13672
13673         ASSERT(MUTEX_HELD(&dtrace_lock));
13674         ASSERT(MUTEX_HELD(&cpu_lock));
13675         ASSERT(which < DTRACEOPT_MAX);
13676         ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13677             (state == dtrace_anon.dta_state &&
13678             state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13679
13680         if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13681                 return (0);
13682
13683         if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13684                 cpu = opt[DTRACEOPT_CPU];
13685
13686         if (which == DTRACEOPT_SPECSIZE)
13687                 flags |= DTRACEBUF_NOSWITCH;
13688
13689         if (which == DTRACEOPT_BUFSIZE) {
13690                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13691                         flags |= DTRACEBUF_RING;
13692
13693                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13694                         flags |= DTRACEBUF_FILL;
13695
13696                 if (state != dtrace_anon.dta_state ||
13697                     state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13698                         flags |= DTRACEBUF_INACTIVE;
13699         }
13700
13701         for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13702                 /*
13703                  * The size must be 8-byte aligned.  If the size is not 8-byte
13704                  * aligned, drop it down by the difference.
13705                  */
13706                 if (size & (sizeof (uint64_t) - 1))
13707                         size -= size & (sizeof (uint64_t) - 1);
13708
13709                 if (size < state->dts_reserve) {
13710                         /*
13711                          * Buffers always must be large enough to accommodate
13712                          * their prereserved space.  We return E2BIG instead
13713                          * of ENOMEM in this case to allow for user-level
13714                          * software to differentiate the cases.
13715                          */
13716                         return (E2BIG);
13717                 }
13718
13719                 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13720
13721                 if (rval != ENOMEM) {
13722                         opt[which] = size;
13723                         return (rval);
13724                 }
13725
13726                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13727                         return (rval);
13728
13729                 for (divisor = 2; divisor < factor; divisor <<= 1)
13730                         continue;
13731         }
13732
13733         return (ENOMEM);
13734 }
13735
13736 static int
13737 dtrace_state_buffers(dtrace_state_t *state)
13738 {
13739         dtrace_speculation_t *spec = state->dts_speculations;
13740         int rval, i;
13741
13742         if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13743             DTRACEOPT_BUFSIZE)) != 0)
13744                 return (rval);
13745
13746         if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13747             DTRACEOPT_AGGSIZE)) != 0)
13748                 return (rval);
13749
13750         for (i = 0; i < state->dts_nspeculations; i++) {
13751                 if ((rval = dtrace_state_buffer(state,
13752                     spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13753                         return (rval);
13754         }
13755
13756         return (0);
13757 }
13758
13759 static void
13760 dtrace_state_prereserve(dtrace_state_t *state)
13761 {
13762         dtrace_ecb_t *ecb;
13763         dtrace_probe_t *probe;
13764
13765         state->dts_reserve = 0;
13766
13767         if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13768                 return;
13769
13770         /*
13771          * If our buffer policy is a "fill" buffer policy, we need to set the
13772          * prereserved space to be the space required by the END probes.
13773          */
13774         probe = dtrace_probes[dtrace_probeid_end - 1];
13775         ASSERT(probe != NULL);
13776
13777         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13778                 if (ecb->dte_state != state)
13779                         continue;
13780
13781                 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13782         }
13783 }
13784
13785 static int
13786 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13787 {
13788         dtrace_optval_t *opt = state->dts_options, sz, nspec;
13789         dtrace_speculation_t *spec;
13790         dtrace_buffer_t *buf;
13791 #if defined(sun)
13792         cyc_handler_t hdlr;
13793         cyc_time_t when;
13794 #endif
13795         int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13796         dtrace_icookie_t cookie;
13797
13798         mutex_enter(&cpu_lock);
13799         mutex_enter(&dtrace_lock);
13800
13801         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13802                 rval = EBUSY;
13803                 goto out;
13804         }
13805
13806         /*
13807          * Before we can perform any checks, we must prime all of the
13808          * retained enablings that correspond to this state.
13809          */
13810         dtrace_enabling_prime(state);
13811
13812         if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13813                 rval = EACCES;
13814                 goto out;
13815         }
13816
13817         dtrace_state_prereserve(state);
13818
13819         /*
13820          * Now we want to do is try to allocate our speculations.
13821          * We do not automatically resize the number of speculations; if
13822          * this fails, we will fail the operation.
13823          */
13824         nspec = opt[DTRACEOPT_NSPEC];
13825         ASSERT(nspec != DTRACEOPT_UNSET);
13826
13827         if (nspec > INT_MAX) {
13828                 rval = ENOMEM;
13829                 goto out;
13830         }
13831
13832         spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13833             KM_NOSLEEP | KM_NORMALPRI);
13834
13835         if (spec == NULL) {
13836                 rval = ENOMEM;
13837                 goto out;
13838         }
13839
13840         state->dts_speculations = spec;
13841         state->dts_nspeculations = (int)nspec;
13842
13843         for (i = 0; i < nspec; i++) {
13844                 if ((buf = kmem_zalloc(bufsize,
13845                     KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13846                         rval = ENOMEM;
13847                         goto err;
13848                 }
13849
13850                 spec[i].dtsp_buffer = buf;
13851         }
13852
13853         if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13854                 if (dtrace_anon.dta_state == NULL) {
13855                         rval = ENOENT;
13856                         goto out;
13857                 }
13858
13859                 if (state->dts_necbs != 0) {
13860                         rval = EALREADY;
13861                         goto out;
13862                 }
13863
13864                 state->dts_anon = dtrace_anon_grab();
13865                 ASSERT(state->dts_anon != NULL);
13866                 state = state->dts_anon;
13867
13868                 /*
13869                  * We want "grabanon" to be set in the grabbed state, so we'll
13870                  * copy that option value from the grabbing state into the
13871                  * grabbed state.
13872                  */
13873                 state->dts_options[DTRACEOPT_GRABANON] =
13874                     opt[DTRACEOPT_GRABANON];
13875
13876                 *cpu = dtrace_anon.dta_beganon;
13877
13878                 /*
13879                  * If the anonymous state is active (as it almost certainly
13880                  * is if the anonymous enabling ultimately matched anything),
13881                  * we don't allow any further option processing -- but we
13882                  * don't return failure.
13883                  */
13884                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13885                         goto out;
13886         }
13887
13888         if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13889             opt[DTRACEOPT_AGGSIZE] != 0) {
13890                 if (state->dts_aggregations == NULL) {
13891                         /*
13892                          * We're not going to create an aggregation buffer
13893                          * because we don't have any ECBs that contain
13894                          * aggregations -- set this option to 0.
13895                          */
13896                         opt[DTRACEOPT_AGGSIZE] = 0;
13897                 } else {
13898                         /*
13899                          * If we have an aggregation buffer, we must also have
13900                          * a buffer to use as scratch.
13901                          */
13902                         if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13903                             opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13904                                 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13905                         }
13906                 }
13907         }
13908
13909         if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13910             opt[DTRACEOPT_SPECSIZE] != 0) {
13911                 if (!state->dts_speculates) {
13912                         /*
13913                          * We're not going to create speculation buffers
13914                          * because we don't have any ECBs that actually
13915                          * speculate -- set the speculation size to 0.
13916                          */
13917                         opt[DTRACEOPT_SPECSIZE] = 0;
13918                 }
13919         }
13920
13921         /*
13922          * The bare minimum size for any buffer that we're actually going to
13923          * do anything to is sizeof (uint64_t).
13924          */
13925         sz = sizeof (uint64_t);
13926
13927         if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13928             (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13929             (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13930                 /*
13931                  * A buffer size has been explicitly set to 0 (or to a size
13932                  * that will be adjusted to 0) and we need the space -- we
13933                  * need to return failure.  We return ENOSPC to differentiate
13934                  * it from failing to allocate a buffer due to failure to meet
13935                  * the reserve (for which we return E2BIG).
13936                  */
13937                 rval = ENOSPC;
13938                 goto out;
13939         }
13940
13941         if ((rval = dtrace_state_buffers(state)) != 0)
13942                 goto err;
13943
13944         if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13945                 sz = dtrace_dstate_defsize;
13946
13947         do {
13948                 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13949
13950                 if (rval == 0)
13951                         break;
13952
13953                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13954                         goto err;
13955         } while (sz >>= 1);
13956
13957         opt[DTRACEOPT_DYNVARSIZE] = sz;
13958
13959         if (rval != 0)
13960                 goto err;
13961
13962         if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13963                 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13964
13965         if (opt[DTRACEOPT_CLEANRATE] == 0)
13966                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13967
13968         if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13969                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13970
13971         if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13972                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13973
13974         state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13975 #if defined(sun)
13976         hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13977         hdlr.cyh_arg = state;
13978         hdlr.cyh_level = CY_LOW_LEVEL;
13979
13980         when.cyt_when = 0;
13981         when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13982
13983         state->dts_cleaner = cyclic_add(&hdlr, &when);
13984
13985         hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13986         hdlr.cyh_arg = state;
13987         hdlr.cyh_level = CY_LOW_LEVEL;
13988
13989         when.cyt_when = 0;
13990         when.cyt_interval = dtrace_deadman_interval;
13991
13992         state->dts_deadman = cyclic_add(&hdlr, &when);
13993 #else
13994         callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13995             dtrace_state_clean, state);
13996         callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13997             dtrace_state_deadman, state);
13998 #endif
13999
14000         state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14001
14002 #if defined(sun)
14003         if (state->dts_getf != 0 &&
14004             !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14005                 /*
14006                  * We don't have kernel privs but we have at least one call
14007                  * to getf(); we need to bump our zone's count, and (if
14008                  * this is the first enabling to have an unprivileged call
14009                  * to getf()) we need to hook into closef().
14010                  */
14011                 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14012
14013                 if (dtrace_getf++ == 0) {
14014                         ASSERT(dtrace_closef == NULL);
14015                         dtrace_closef = dtrace_getf_barrier;
14016                 }
14017         }
14018 #endif
14019
14020         /*
14021          * Now it's time to actually fire the BEGIN probe.  We need to disable
14022          * interrupts here both to record the CPU on which we fired the BEGIN
14023          * probe (the data from this CPU will be processed first at user
14024          * level) and to manually activate the buffer for this CPU.
14025          */
14026         cookie = dtrace_interrupt_disable();
14027         *cpu = curcpu;
14028         ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14029         state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14030
14031         dtrace_probe(dtrace_probeid_begin,
14032             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14033         dtrace_interrupt_enable(cookie);
14034         /*
14035          * We may have had an exit action from a BEGIN probe; only change our
14036          * state to ACTIVE if we're still in WARMUP.
14037          */
14038         ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14039             state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14040
14041         if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14042                 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14043
14044         /*
14045          * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14046          * want each CPU to transition its principal buffer out of the
14047          * INACTIVE state.  Doing this assures that no CPU will suddenly begin
14048          * processing an ECB halfway down a probe's ECB chain; all CPUs will
14049          * atomically transition from processing none of a state's ECBs to
14050          * processing all of them.
14051          */
14052         dtrace_xcall(DTRACE_CPUALL,
14053             (dtrace_xcall_t)dtrace_buffer_activate, state);
14054         goto out;
14055
14056 err:
14057         dtrace_buffer_free(state->dts_buffer);
14058         dtrace_buffer_free(state->dts_aggbuffer);
14059
14060         if ((nspec = state->dts_nspeculations) == 0) {
14061                 ASSERT(state->dts_speculations == NULL);
14062                 goto out;
14063         }
14064
14065         spec = state->dts_speculations;
14066         ASSERT(spec != NULL);
14067
14068         for (i = 0; i < state->dts_nspeculations; i++) {
14069                 if ((buf = spec[i].dtsp_buffer) == NULL)
14070                         break;
14071
14072                 dtrace_buffer_free(buf);
14073                 kmem_free(buf, bufsize);
14074         }
14075
14076         kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14077         state->dts_nspeculations = 0;
14078         state->dts_speculations = NULL;
14079
14080 out:
14081         mutex_exit(&dtrace_lock);
14082         mutex_exit(&cpu_lock);
14083
14084         return (rval);
14085 }
14086
14087 static int
14088 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14089 {
14090         dtrace_icookie_t cookie;
14091
14092         ASSERT(MUTEX_HELD(&dtrace_lock));
14093
14094         if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14095             state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14096                 return (EINVAL);
14097
14098         /*
14099          * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14100          * to be sure that every CPU has seen it.  See below for the details
14101          * on why this is done.
14102          */
14103         state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14104         dtrace_sync();
14105
14106         /*
14107          * By this point, it is impossible for any CPU to be still processing
14108          * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14109          * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14110          * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14111          * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14112          * iff we're in the END probe.
14113          */
14114         state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14115         dtrace_sync();
14116         ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14117
14118         /*
14119          * Finally, we can release the reserve and call the END probe.  We
14120          * disable interrupts across calling the END probe to allow us to
14121          * return the CPU on which we actually called the END probe.  This
14122          * allows user-land to be sure that this CPU's principal buffer is
14123          * processed last.
14124          */
14125         state->dts_reserve = 0;
14126
14127         cookie = dtrace_interrupt_disable();
14128         *cpu = curcpu;
14129         dtrace_probe(dtrace_probeid_end,
14130             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14131         dtrace_interrupt_enable(cookie);
14132
14133         state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14134         dtrace_sync();
14135
14136 #if defined(sun)
14137         if (state->dts_getf != 0 &&
14138             !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14139                 /*
14140                  * We don't have kernel privs but we have at least one call
14141                  * to getf(); we need to lower our zone's count, and (if
14142                  * this is the last enabling to have an unprivileged call
14143                  * to getf()) we need to clear the closef() hook.
14144                  */
14145                 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14146                 ASSERT(dtrace_closef == dtrace_getf_barrier);
14147                 ASSERT(dtrace_getf > 0);
14148
14149                 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14150
14151                 if (--dtrace_getf == 0)
14152                         dtrace_closef = NULL;
14153         }
14154 #endif
14155
14156         return (0);
14157 }
14158
14159 static int
14160 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14161     dtrace_optval_t val)
14162 {
14163         ASSERT(MUTEX_HELD(&dtrace_lock));
14164
14165         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14166                 return (EBUSY);
14167
14168         if (option >= DTRACEOPT_MAX)
14169                 return (EINVAL);
14170
14171         if (option != DTRACEOPT_CPU && val < 0)
14172                 return (EINVAL);
14173
14174         switch (option) {
14175         case DTRACEOPT_DESTRUCTIVE:
14176                 if (dtrace_destructive_disallow)
14177                         return (EACCES);
14178
14179                 state->dts_cred.dcr_destructive = 1;
14180                 break;
14181
14182         case DTRACEOPT_BUFSIZE:
14183         case DTRACEOPT_DYNVARSIZE:
14184         case DTRACEOPT_AGGSIZE:
14185         case DTRACEOPT_SPECSIZE:
14186         case DTRACEOPT_STRSIZE:
14187                 if (val < 0)
14188                         return (EINVAL);
14189
14190                 if (val >= LONG_MAX) {
14191                         /*
14192                          * If this is an otherwise negative value, set it to
14193                          * the highest multiple of 128m less than LONG_MAX.
14194                          * Technically, we're adjusting the size without
14195                          * regard to the buffer resizing policy, but in fact,
14196                          * this has no effect -- if we set the buffer size to
14197                          * ~LONG_MAX and the buffer policy is ultimately set to
14198                          * be "manual", the buffer allocation is guaranteed to
14199                          * fail, if only because the allocation requires two
14200                          * buffers.  (We set the the size to the highest
14201                          * multiple of 128m because it ensures that the size
14202                          * will remain a multiple of a megabyte when
14203                          * repeatedly halved -- all the way down to 15m.)
14204                          */
14205                         val = LONG_MAX - (1 << 27) + 1;
14206                 }
14207         }
14208
14209         state->dts_options[option] = val;
14210
14211         return (0);
14212 }
14213
14214 static void
14215 dtrace_state_destroy(dtrace_state_t *state)
14216 {
14217         dtrace_ecb_t *ecb;
14218         dtrace_vstate_t *vstate = &state->dts_vstate;
14219 #if defined(sun)
14220         minor_t minor = getminor(state->dts_dev);
14221 #endif
14222         int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14223         dtrace_speculation_t *spec = state->dts_speculations;
14224         int nspec = state->dts_nspeculations;
14225         uint32_t match;
14226
14227         ASSERT(MUTEX_HELD(&dtrace_lock));
14228         ASSERT(MUTEX_HELD(&cpu_lock));
14229
14230         /*
14231          * First, retract any retained enablings for this state.
14232          */
14233         dtrace_enabling_retract(state);
14234         ASSERT(state->dts_nretained == 0);
14235
14236         if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14237             state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14238                 /*
14239                  * We have managed to come into dtrace_state_destroy() on a
14240                  * hot enabling -- almost certainly because of a disorderly
14241                  * shutdown of a consumer.  (That is, a consumer that is
14242                  * exiting without having called dtrace_stop().) In this case,
14243                  * we're going to set our activity to be KILLED, and then
14244                  * issue a sync to be sure that everyone is out of probe
14245                  * context before we start blowing away ECBs.
14246                  */
14247                 state->dts_activity = DTRACE_ACTIVITY_KILLED;
14248                 dtrace_sync();
14249         }
14250
14251         /*
14252          * Release the credential hold we took in dtrace_state_create().
14253          */
14254         if (state->dts_cred.dcr_cred != NULL)
14255                 crfree(state->dts_cred.dcr_cred);
14256
14257         /*
14258          * Now we can safely disable and destroy any enabled probes.  Because
14259          * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14260          * (especially if they're all enabled), we take two passes through the
14261          * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14262          * in the second we disable whatever is left over.
14263          */
14264         for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14265                 for (i = 0; i < state->dts_necbs; i++) {
14266                         if ((ecb = state->dts_ecbs[i]) == NULL)
14267                                 continue;
14268
14269                         if (match && ecb->dte_probe != NULL) {
14270                                 dtrace_probe_t *probe = ecb->dte_probe;
14271                                 dtrace_provider_t *prov = probe->dtpr_provider;
14272
14273                                 if (!(prov->dtpv_priv.dtpp_flags & match))
14274                                         continue;
14275                         }
14276
14277                         dtrace_ecb_disable(ecb);
14278                         dtrace_ecb_destroy(ecb);
14279                 }
14280
14281                 if (!match)
14282                         break;
14283         }
14284
14285         /*
14286          * Before we free the buffers, perform one more sync to assure that
14287          * every CPU is out of probe context.
14288          */
14289         dtrace_sync();
14290
14291         dtrace_buffer_free(state->dts_buffer);
14292         dtrace_buffer_free(state->dts_aggbuffer);
14293
14294         for (i = 0; i < nspec; i++)
14295                 dtrace_buffer_free(spec[i].dtsp_buffer);
14296
14297 #if defined(sun)
14298         if (state->dts_cleaner != CYCLIC_NONE)
14299                 cyclic_remove(state->dts_cleaner);
14300
14301         if (state->dts_deadman != CYCLIC_NONE)
14302                 cyclic_remove(state->dts_deadman);
14303 #else
14304         callout_stop(&state->dts_cleaner);
14305         callout_drain(&state->dts_cleaner);
14306         callout_stop(&state->dts_deadman);
14307         callout_drain(&state->dts_deadman);
14308 #endif
14309
14310         dtrace_dstate_fini(&vstate->dtvs_dynvars);
14311         dtrace_vstate_fini(vstate);
14312         if (state->dts_ecbs != NULL)
14313                 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14314
14315         if (state->dts_aggregations != NULL) {
14316 #ifdef DEBUG
14317                 for (i = 0; i < state->dts_naggregations; i++)
14318                         ASSERT(state->dts_aggregations[i] == NULL);
14319 #endif
14320                 ASSERT(state->dts_naggregations > 0);
14321                 kmem_free(state->dts_aggregations,
14322                     state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14323         }
14324
14325         kmem_free(state->dts_buffer, bufsize);
14326         kmem_free(state->dts_aggbuffer, bufsize);
14327
14328         for (i = 0; i < nspec; i++)
14329                 kmem_free(spec[i].dtsp_buffer, bufsize);
14330
14331         if (spec != NULL)
14332                 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14333
14334         dtrace_format_destroy(state);
14335
14336         if (state->dts_aggid_arena != NULL) {
14337 #if defined(sun)
14338                 vmem_destroy(state->dts_aggid_arena);
14339 #else
14340                 delete_unrhdr(state->dts_aggid_arena);
14341 #endif
14342                 state->dts_aggid_arena = NULL;
14343         }
14344 #if defined(sun)
14345         ddi_soft_state_free(dtrace_softstate, minor);
14346         vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14347 #endif
14348 }
14349
14350 /*
14351  * DTrace Anonymous Enabling Functions
14352  */
14353 static dtrace_state_t *
14354 dtrace_anon_grab(void)
14355 {
14356         dtrace_state_t *state;
14357
14358         ASSERT(MUTEX_HELD(&dtrace_lock));
14359
14360         if ((state = dtrace_anon.dta_state) == NULL) {
14361                 ASSERT(dtrace_anon.dta_enabling == NULL);
14362                 return (NULL);
14363         }
14364
14365         ASSERT(dtrace_anon.dta_enabling != NULL);
14366         ASSERT(dtrace_retained != NULL);
14367
14368         dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14369         dtrace_anon.dta_enabling = NULL;
14370         dtrace_anon.dta_state = NULL;
14371
14372         return (state);
14373 }
14374
14375 static void
14376 dtrace_anon_property(void)
14377 {
14378         int i, rv;
14379         dtrace_state_t *state;
14380         dof_hdr_t *dof;
14381         char c[32];             /* enough for "dof-data-" + digits */
14382
14383         ASSERT(MUTEX_HELD(&dtrace_lock));
14384         ASSERT(MUTEX_HELD(&cpu_lock));
14385
14386         for (i = 0; ; i++) {
14387                 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14388
14389                 dtrace_err_verbose = 1;
14390
14391                 if ((dof = dtrace_dof_property(c)) == NULL) {
14392                         dtrace_err_verbose = 0;
14393                         break;
14394                 }
14395
14396 #if defined(sun)
14397                 /*
14398                  * We want to create anonymous state, so we need to transition
14399                  * the kernel debugger to indicate that DTrace is active.  If
14400                  * this fails (e.g. because the debugger has modified text in
14401                  * some way), we won't continue with the processing.
14402                  */
14403                 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14404                         cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14405                             "enabling ignored.");
14406                         dtrace_dof_destroy(dof);
14407                         break;
14408                 }
14409 #endif
14410
14411                 /*
14412                  * If we haven't allocated an anonymous state, we'll do so now.
14413                  */
14414                 if ((state = dtrace_anon.dta_state) == NULL) {
14415 #if defined(sun)
14416                         state = dtrace_state_create(NULL, NULL);
14417 #else
14418                         state = dtrace_state_create(NULL);
14419 #endif
14420                         dtrace_anon.dta_state = state;
14421
14422                         if (state == NULL) {
14423                                 /*
14424                                  * This basically shouldn't happen:  the only
14425                                  * failure mode from dtrace_state_create() is a
14426                                  * failure of ddi_soft_state_zalloc() that
14427                                  * itself should never happen.  Still, the
14428                                  * interface allows for a failure mode, and
14429                                  * we want to fail as gracefully as possible:
14430                                  * we'll emit an error message and cease
14431                                  * processing anonymous state in this case.
14432                                  */
14433                                 cmn_err(CE_WARN, "failed to create "
14434                                     "anonymous state");
14435                                 dtrace_dof_destroy(dof);
14436                                 break;
14437                         }
14438                 }
14439
14440                 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14441                     &dtrace_anon.dta_enabling, 0, B_TRUE);
14442
14443                 if (rv == 0)
14444                         rv = dtrace_dof_options(dof, state);
14445
14446                 dtrace_err_verbose = 0;
14447                 dtrace_dof_destroy(dof);
14448
14449                 if (rv != 0) {
14450                         /*
14451                          * This is malformed DOF; chuck any anonymous state
14452                          * that we created.
14453                          */
14454                         ASSERT(dtrace_anon.dta_enabling == NULL);
14455                         dtrace_state_destroy(state);
14456                         dtrace_anon.dta_state = NULL;
14457                         break;
14458                 }
14459
14460                 ASSERT(dtrace_anon.dta_enabling != NULL);
14461         }
14462
14463         if (dtrace_anon.dta_enabling != NULL) {
14464                 int rval;
14465
14466                 /*
14467                  * dtrace_enabling_retain() can only fail because we are
14468                  * trying to retain more enablings than are allowed -- but
14469                  * we only have one anonymous enabling, and we are guaranteed
14470                  * to be allowed at least one retained enabling; we assert
14471                  * that dtrace_enabling_retain() returns success.
14472                  */
14473                 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14474                 ASSERT(rval == 0);
14475
14476                 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14477         }
14478 }
14479
14480 /*
14481  * DTrace Helper Functions
14482  */
14483 static void
14484 dtrace_helper_trace(dtrace_helper_action_t *helper,
14485     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14486 {
14487         uint32_t size, next, nnext, i;
14488         dtrace_helptrace_t *ent;
14489         uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
14490
14491         if (!dtrace_helptrace_enabled)
14492                 return;
14493
14494         ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14495
14496         /*
14497          * What would a tracing framework be without its own tracing
14498          * framework?  (Well, a hell of a lot simpler, for starters...)
14499          */
14500         size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14501             sizeof (uint64_t) - sizeof (uint64_t);
14502
14503         /*
14504          * Iterate until we can allocate a slot in the trace buffer.
14505          */
14506         do {
14507                 next = dtrace_helptrace_next;
14508
14509                 if (next + size < dtrace_helptrace_bufsize) {
14510                         nnext = next + size;
14511                 } else {
14512                         nnext = size;
14513                 }
14514         } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14515
14516         /*
14517          * We have our slot; fill it in.
14518          */
14519         if (nnext == size)
14520                 next = 0;
14521
14522         ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14523         ent->dtht_helper = helper;
14524         ent->dtht_where = where;
14525         ent->dtht_nlocals = vstate->dtvs_nlocals;
14526
14527         ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14528             mstate->dtms_fltoffs : -1;
14529         ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14530         ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
14531
14532         for (i = 0; i < vstate->dtvs_nlocals; i++) {
14533                 dtrace_statvar_t *svar;
14534
14535                 if ((svar = vstate->dtvs_locals[i]) == NULL)
14536                         continue;
14537
14538                 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14539                 ent->dtht_locals[i] =
14540                     ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
14541         }
14542 }
14543
14544 static uint64_t
14545 dtrace_helper(int which, dtrace_mstate_t *mstate,
14546     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14547 {
14548         uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
14549         uint64_t sarg0 = mstate->dtms_arg[0];
14550         uint64_t sarg1 = mstate->dtms_arg[1];
14551         uint64_t rval = 0;
14552         dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14553         dtrace_helper_action_t *helper;
14554         dtrace_vstate_t *vstate;
14555         dtrace_difo_t *pred;
14556         int i, trace = dtrace_helptrace_enabled;
14557
14558         ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14559
14560         if (helpers == NULL)
14561                 return (0);
14562
14563         if ((helper = helpers->dthps_actions[which]) == NULL)
14564                 return (0);
14565
14566         vstate = &helpers->dthps_vstate;
14567         mstate->dtms_arg[0] = arg0;
14568         mstate->dtms_arg[1] = arg1;
14569
14570         /*
14571          * Now iterate over each helper.  If its predicate evaluates to 'true',
14572          * we'll call the corresponding actions.  Note that the below calls
14573          * to dtrace_dif_emulate() may set faults in machine state.  This is
14574          * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14575          * the stored DIF offset with its own (which is the desired behavior).
14576          * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14577          * from machine state; this is okay, too.
14578          */
14579         for (; helper != NULL; helper = helper->dtha_next) {
14580                 if ((pred = helper->dtha_predicate) != NULL) {
14581                         if (trace)
14582                                 dtrace_helper_trace(helper, mstate, vstate, 0);
14583
14584                         if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14585                                 goto next;
14586
14587                         if (*flags & CPU_DTRACE_FAULT)
14588                                 goto err;
14589                 }
14590
14591                 for (i = 0; i < helper->dtha_nactions; i++) {
14592                         if (trace)
14593                                 dtrace_helper_trace(helper,
14594                                     mstate, vstate, i + 1);
14595
14596                         rval = dtrace_dif_emulate(helper->dtha_actions[i],
14597                             mstate, vstate, state);
14598
14599                         if (*flags & CPU_DTRACE_FAULT)
14600                                 goto err;
14601                 }
14602
14603 next:
14604                 if (trace)
14605                         dtrace_helper_trace(helper, mstate, vstate,
14606                             DTRACE_HELPTRACE_NEXT);
14607         }
14608
14609         if (trace)
14610                 dtrace_helper_trace(helper, mstate, vstate,
14611                     DTRACE_HELPTRACE_DONE);
14612
14613         /*
14614          * Restore the arg0 that we saved upon entry.
14615          */
14616         mstate->dtms_arg[0] = sarg0;
14617         mstate->dtms_arg[1] = sarg1;
14618
14619         return (rval);
14620
14621 err:
14622         if (trace)
14623                 dtrace_helper_trace(helper, mstate, vstate,
14624                     DTRACE_HELPTRACE_ERR);
14625
14626         /*
14627          * Restore the arg0 that we saved upon entry.
14628          */
14629         mstate->dtms_arg[0] = sarg0;
14630         mstate->dtms_arg[1] = sarg1;
14631
14632         return (0);
14633 }
14634
14635 static void
14636 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14637     dtrace_vstate_t *vstate)
14638 {
14639         int i;
14640
14641         if (helper->dtha_predicate != NULL)
14642                 dtrace_difo_release(helper->dtha_predicate, vstate);
14643
14644         for (i = 0; i < helper->dtha_nactions; i++) {
14645                 ASSERT(helper->dtha_actions[i] != NULL);
14646                 dtrace_difo_release(helper->dtha_actions[i], vstate);
14647         }
14648
14649         kmem_free(helper->dtha_actions,
14650             helper->dtha_nactions * sizeof (dtrace_difo_t *));
14651         kmem_free(helper, sizeof (dtrace_helper_action_t));
14652 }
14653
14654 static int
14655 dtrace_helper_destroygen(int gen)
14656 {
14657         proc_t *p = curproc;
14658         dtrace_helpers_t *help = p->p_dtrace_helpers;
14659         dtrace_vstate_t *vstate;
14660         int i;
14661
14662         ASSERT(MUTEX_HELD(&dtrace_lock));
14663
14664         if (help == NULL || gen > help->dthps_generation)
14665                 return (EINVAL);
14666
14667         vstate = &help->dthps_vstate;
14668
14669         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14670                 dtrace_helper_action_t *last = NULL, *h, *next;
14671
14672                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14673                         next = h->dtha_next;
14674
14675                         if (h->dtha_generation == gen) {
14676                                 if (last != NULL) {
14677                                         last->dtha_next = next;
14678                                 } else {
14679                                         help->dthps_actions[i] = next;
14680                                 }
14681
14682                                 dtrace_helper_action_destroy(h, vstate);
14683                         } else {
14684                                 last = h;
14685                         }
14686                 }
14687         }
14688
14689         /*
14690          * Interate until we've cleared out all helper providers with the
14691          * given generation number.
14692          */
14693         for (;;) {
14694                 dtrace_helper_provider_t *prov;
14695
14696                 /*
14697                  * Look for a helper provider with the right generation. We
14698                  * have to start back at the beginning of the list each time
14699                  * because we drop dtrace_lock. It's unlikely that we'll make
14700                  * more than two passes.
14701                  */
14702                 for (i = 0; i < help->dthps_nprovs; i++) {
14703                         prov = help->dthps_provs[i];
14704
14705                         if (prov->dthp_generation == gen)
14706                                 break;
14707                 }
14708
14709                 /*
14710                  * If there were no matches, we're done.
14711                  */
14712                 if (i == help->dthps_nprovs)
14713                         break;
14714
14715                 /*
14716                  * Move the last helper provider into this slot.
14717                  */
14718                 help->dthps_nprovs--;
14719                 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14720                 help->dthps_provs[help->dthps_nprovs] = NULL;
14721
14722                 mutex_exit(&dtrace_lock);
14723
14724                 /*
14725                  * If we have a meta provider, remove this helper provider.
14726                  */
14727                 mutex_enter(&dtrace_meta_lock);
14728                 if (dtrace_meta_pid != NULL) {
14729                         ASSERT(dtrace_deferred_pid == NULL);
14730                         dtrace_helper_provider_remove(&prov->dthp_prov,
14731                             p->p_pid);
14732                 }
14733                 mutex_exit(&dtrace_meta_lock);
14734
14735                 dtrace_helper_provider_destroy(prov);
14736
14737                 mutex_enter(&dtrace_lock);
14738         }
14739
14740         return (0);
14741 }
14742
14743 static int
14744 dtrace_helper_validate(dtrace_helper_action_t *helper)
14745 {
14746         int err = 0, i;
14747         dtrace_difo_t *dp;
14748
14749         if ((dp = helper->dtha_predicate) != NULL)
14750                 err += dtrace_difo_validate_helper(dp);
14751
14752         for (i = 0; i < helper->dtha_nactions; i++)
14753                 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14754
14755         return (err == 0);
14756 }
14757
14758 static int
14759 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14760 {
14761         dtrace_helpers_t *help;
14762         dtrace_helper_action_t *helper, *last;
14763         dtrace_actdesc_t *act;
14764         dtrace_vstate_t *vstate;
14765         dtrace_predicate_t *pred;
14766         int count = 0, nactions = 0, i;
14767
14768         if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14769                 return (EINVAL);
14770
14771         help = curproc->p_dtrace_helpers;
14772         last = help->dthps_actions[which];
14773         vstate = &help->dthps_vstate;
14774
14775         for (count = 0; last != NULL; last = last->dtha_next) {
14776                 count++;
14777                 if (last->dtha_next == NULL)
14778                         break;
14779         }
14780
14781         /*
14782          * If we already have dtrace_helper_actions_max helper actions for this
14783          * helper action type, we'll refuse to add a new one.
14784          */
14785         if (count >= dtrace_helper_actions_max)
14786                 return (ENOSPC);
14787
14788         helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14789         helper->dtha_generation = help->dthps_generation;
14790
14791         if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14792                 ASSERT(pred->dtp_difo != NULL);
14793                 dtrace_difo_hold(pred->dtp_difo);
14794                 helper->dtha_predicate = pred->dtp_difo;
14795         }
14796
14797         for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14798                 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14799                         goto err;
14800
14801                 if (act->dtad_difo == NULL)
14802                         goto err;
14803
14804                 nactions++;
14805         }
14806
14807         helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14808             (helper->dtha_nactions = nactions), KM_SLEEP);
14809
14810         for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14811                 dtrace_difo_hold(act->dtad_difo);
14812                 helper->dtha_actions[i++] = act->dtad_difo;
14813         }
14814
14815         if (!dtrace_helper_validate(helper))
14816                 goto err;
14817
14818         if (last == NULL) {
14819                 help->dthps_actions[which] = helper;
14820         } else {
14821                 last->dtha_next = helper;
14822         }
14823
14824         if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14825                 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14826                 dtrace_helptrace_next = 0;
14827         }
14828
14829         return (0);
14830 err:
14831         dtrace_helper_action_destroy(helper, vstate);
14832         return (EINVAL);
14833 }
14834
14835 static void
14836 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14837     dof_helper_t *dofhp)
14838 {
14839         ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14840
14841         mutex_enter(&dtrace_meta_lock);
14842         mutex_enter(&dtrace_lock);
14843
14844         if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14845                 /*
14846                  * If the dtrace module is loaded but not attached, or if
14847                  * there aren't isn't a meta provider registered to deal with
14848                  * these provider descriptions, we need to postpone creating
14849                  * the actual providers until later.
14850                  */
14851
14852                 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14853                     dtrace_deferred_pid != help) {
14854                         help->dthps_deferred = 1;
14855                         help->dthps_pid = p->p_pid;
14856                         help->dthps_next = dtrace_deferred_pid;
14857                         help->dthps_prev = NULL;
14858                         if (dtrace_deferred_pid != NULL)
14859                                 dtrace_deferred_pid->dthps_prev = help;
14860                         dtrace_deferred_pid = help;
14861                 }
14862
14863                 mutex_exit(&dtrace_lock);
14864
14865         } else if (dofhp != NULL) {
14866                 /*
14867                  * If the dtrace module is loaded and we have a particular
14868                  * helper provider description, pass that off to the
14869                  * meta provider.
14870                  */
14871
14872                 mutex_exit(&dtrace_lock);
14873
14874                 dtrace_helper_provide(dofhp, p->p_pid);
14875
14876         } else {
14877                 /*
14878                  * Otherwise, just pass all the helper provider descriptions
14879                  * off to the meta provider.
14880                  */
14881
14882                 int i;
14883                 mutex_exit(&dtrace_lock);
14884
14885                 for (i = 0; i < help->dthps_nprovs; i++) {
14886                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14887                             p->p_pid);
14888                 }
14889         }
14890
14891         mutex_exit(&dtrace_meta_lock);
14892 }
14893
14894 static int
14895 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14896 {
14897         dtrace_helpers_t *help;
14898         dtrace_helper_provider_t *hprov, **tmp_provs;
14899         uint_t tmp_maxprovs, i;
14900
14901         ASSERT(MUTEX_HELD(&dtrace_lock));
14902
14903         help = curproc->p_dtrace_helpers;
14904         ASSERT(help != NULL);
14905
14906         /*
14907          * If we already have dtrace_helper_providers_max helper providers,
14908          * we're refuse to add a new one.
14909          */
14910         if (help->dthps_nprovs >= dtrace_helper_providers_max)
14911                 return (ENOSPC);
14912
14913         /*
14914          * Check to make sure this isn't a duplicate.
14915          */
14916         for (i = 0; i < help->dthps_nprovs; i++) {
14917                 if (dofhp->dofhp_dof ==
14918                     help->dthps_provs[i]->dthp_prov.dofhp_dof)
14919                         return (EALREADY);
14920         }
14921
14922         hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14923         hprov->dthp_prov = *dofhp;
14924         hprov->dthp_ref = 1;
14925         hprov->dthp_generation = gen;
14926
14927         /*
14928          * Allocate a bigger table for helper providers if it's already full.
14929          */
14930         if (help->dthps_maxprovs == help->dthps_nprovs) {
14931                 tmp_maxprovs = help->dthps_maxprovs;
14932                 tmp_provs = help->dthps_provs;
14933
14934                 if (help->dthps_maxprovs == 0)
14935                         help->dthps_maxprovs = 2;
14936                 else
14937                         help->dthps_maxprovs *= 2;
14938                 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14939                         help->dthps_maxprovs = dtrace_helper_providers_max;
14940
14941                 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14942
14943                 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14944                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14945
14946                 if (tmp_provs != NULL) {
14947                         bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14948                             sizeof (dtrace_helper_provider_t *));
14949                         kmem_free(tmp_provs, tmp_maxprovs *
14950                             sizeof (dtrace_helper_provider_t *));
14951                 }
14952         }
14953
14954         help->dthps_provs[help->dthps_nprovs] = hprov;
14955         help->dthps_nprovs++;
14956
14957         return (0);
14958 }
14959
14960 static void
14961 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14962 {
14963         mutex_enter(&dtrace_lock);
14964
14965         if (--hprov->dthp_ref == 0) {
14966                 dof_hdr_t *dof;
14967                 mutex_exit(&dtrace_lock);
14968                 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14969                 dtrace_dof_destroy(dof);
14970                 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14971         } else {
14972                 mutex_exit(&dtrace_lock);
14973         }
14974 }
14975
14976 static int
14977 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14978 {
14979         uintptr_t daddr = (uintptr_t)dof;
14980         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14981         dof_provider_t *provider;
14982         dof_probe_t *probe;
14983         uint8_t *arg;
14984         char *strtab, *typestr;
14985         dof_stridx_t typeidx;
14986         size_t typesz;
14987         uint_t nprobes, j, k;
14988
14989         ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14990
14991         if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14992                 dtrace_dof_error(dof, "misaligned section offset");
14993                 return (-1);
14994         }
14995
14996         /*
14997          * The section needs to be large enough to contain the DOF provider
14998          * structure appropriate for the given version.
14999          */
15000         if (sec->dofs_size <
15001             ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15002             offsetof(dof_provider_t, dofpv_prenoffs) :
15003             sizeof (dof_provider_t))) {
15004                 dtrace_dof_error(dof, "provider section too small");
15005                 return (-1);
15006         }
15007
15008         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15009         str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15010         prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15011         arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15012         off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15013
15014         if (str_sec == NULL || prb_sec == NULL ||
15015             arg_sec == NULL || off_sec == NULL)
15016                 return (-1);
15017
15018         enoff_sec = NULL;
15019
15020         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15021             provider->dofpv_prenoffs != DOF_SECT_NONE &&
15022             (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15023             provider->dofpv_prenoffs)) == NULL)
15024                 return (-1);
15025
15026         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15027
15028         if (provider->dofpv_name >= str_sec->dofs_size ||
15029             strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15030                 dtrace_dof_error(dof, "invalid provider name");
15031                 return (-1);
15032         }
15033
15034         if (prb_sec->dofs_entsize == 0 ||
15035             prb_sec->dofs_entsize > prb_sec->dofs_size) {
15036                 dtrace_dof_error(dof, "invalid entry size");
15037                 return (-1);
15038         }
15039
15040         if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15041                 dtrace_dof_error(dof, "misaligned entry size");
15042                 return (-1);
15043         }
15044
15045         if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15046                 dtrace_dof_error(dof, "invalid entry size");
15047                 return (-1);
15048         }
15049
15050         if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15051                 dtrace_dof_error(dof, "misaligned section offset");
15052                 return (-1);
15053         }
15054
15055         if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15056                 dtrace_dof_error(dof, "invalid entry size");
15057                 return (-1);
15058         }
15059
15060         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15061
15062         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15063
15064         /*
15065          * Take a pass through the probes to check for errors.
15066          */
15067         for (j = 0; j < nprobes; j++) {
15068                 probe = (dof_probe_t *)(uintptr_t)(daddr +
15069                     prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15070
15071                 if (probe->dofpr_func >= str_sec->dofs_size) {
15072                         dtrace_dof_error(dof, "invalid function name");
15073                         return (-1);
15074                 }
15075
15076                 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15077                         dtrace_dof_error(dof, "function name too long");
15078                         return (-1);
15079                 }
15080
15081                 if (probe->dofpr_name >= str_sec->dofs_size ||
15082                     strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15083                         dtrace_dof_error(dof, "invalid probe name");
15084                         return (-1);
15085                 }
15086
15087                 /*
15088                  * The offset count must not wrap the index, and the offsets
15089                  * must also not overflow the section's data.
15090                  */
15091                 if (probe->dofpr_offidx + probe->dofpr_noffs <
15092                     probe->dofpr_offidx ||
15093                     (probe->dofpr_offidx + probe->dofpr_noffs) *
15094                     off_sec->dofs_entsize > off_sec->dofs_size) {
15095                         dtrace_dof_error(dof, "invalid probe offset");
15096                         return (-1);
15097                 }
15098
15099                 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15100                         /*
15101                          * If there's no is-enabled offset section, make sure
15102                          * there aren't any is-enabled offsets. Otherwise
15103                          * perform the same checks as for probe offsets
15104                          * (immediately above).
15105                          */
15106                         if (enoff_sec == NULL) {
15107                                 if (probe->dofpr_enoffidx != 0 ||
15108                                     probe->dofpr_nenoffs != 0) {
15109                                         dtrace_dof_error(dof, "is-enabled "
15110                                             "offsets with null section");
15111                                         return (-1);
15112                                 }
15113                         } else if (probe->dofpr_enoffidx +
15114                             probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15115                             (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15116                             enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15117                                 dtrace_dof_error(dof, "invalid is-enabled "
15118                                     "offset");
15119                                 return (-1);
15120                         }
15121
15122                         if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15123                                 dtrace_dof_error(dof, "zero probe and "
15124                                     "is-enabled offsets");
15125                                 return (-1);
15126                         }
15127                 } else if (probe->dofpr_noffs == 0) {
15128                         dtrace_dof_error(dof, "zero probe offsets");
15129                         return (-1);
15130                 }
15131
15132                 if (probe->dofpr_argidx + probe->dofpr_xargc <
15133                     probe->dofpr_argidx ||
15134                     (probe->dofpr_argidx + probe->dofpr_xargc) *
15135                     arg_sec->dofs_entsize > arg_sec->dofs_size) {
15136                         dtrace_dof_error(dof, "invalid args");
15137                         return (-1);
15138                 }
15139
15140                 typeidx = probe->dofpr_nargv;
15141                 typestr = strtab + probe->dofpr_nargv;
15142                 for (k = 0; k < probe->dofpr_nargc; k++) {
15143                         if (typeidx >= str_sec->dofs_size) {
15144                                 dtrace_dof_error(dof, "bad "
15145                                     "native argument type");
15146                                 return (-1);
15147                         }
15148
15149                         typesz = strlen(typestr) + 1;
15150                         if (typesz > DTRACE_ARGTYPELEN) {
15151                                 dtrace_dof_error(dof, "native "
15152                                     "argument type too long");
15153                                 return (-1);
15154                         }
15155                         typeidx += typesz;
15156                         typestr += typesz;
15157                 }
15158
15159                 typeidx = probe->dofpr_xargv;
15160                 typestr = strtab + probe->dofpr_xargv;
15161                 for (k = 0; k < probe->dofpr_xargc; k++) {
15162                         if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15163                                 dtrace_dof_error(dof, "bad "
15164                                     "native argument index");
15165                                 return (-1);
15166                         }
15167
15168                         if (typeidx >= str_sec->dofs_size) {
15169                                 dtrace_dof_error(dof, "bad "
15170                                     "translated argument type");
15171                                 return (-1);
15172                         }
15173
15174                         typesz = strlen(typestr) + 1;
15175                         if (typesz > DTRACE_ARGTYPELEN) {
15176                                 dtrace_dof_error(dof, "translated argument "
15177                                     "type too long");
15178                                 return (-1);
15179                         }
15180
15181                         typeidx += typesz;
15182                         typestr += typesz;
15183                 }
15184         }
15185
15186         return (0);
15187 }
15188
15189 static int
15190 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15191 {
15192         dtrace_helpers_t *help;
15193         dtrace_vstate_t *vstate;
15194         dtrace_enabling_t *enab = NULL;
15195         int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15196         uintptr_t daddr = (uintptr_t)dof;
15197
15198         ASSERT(MUTEX_HELD(&dtrace_lock));
15199
15200         if ((help = curproc->p_dtrace_helpers) == NULL)
15201                 help = dtrace_helpers_create(curproc);
15202
15203         vstate = &help->dthps_vstate;
15204
15205         if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15206             dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15207                 dtrace_dof_destroy(dof);
15208                 return (rv);
15209         }
15210
15211         /*
15212          * Look for helper providers and validate their descriptions.
15213          */
15214         if (dhp != NULL) {
15215                 for (i = 0; i < dof->dofh_secnum; i++) {
15216                         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15217                             dof->dofh_secoff + i * dof->dofh_secsize);
15218
15219                         if (sec->dofs_type != DOF_SECT_PROVIDER)
15220                                 continue;
15221
15222                         if (dtrace_helper_provider_validate(dof, sec) != 0) {
15223                                 dtrace_enabling_destroy(enab);
15224                                 dtrace_dof_destroy(dof);
15225                                 return (-1);
15226                         }
15227
15228                         nprovs++;
15229                 }
15230         }
15231
15232         /*
15233          * Now we need to walk through the ECB descriptions in the enabling.
15234          */
15235         for (i = 0; i < enab->dten_ndesc; i++) {
15236                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15237                 dtrace_probedesc_t *desc = &ep->dted_probe;
15238
15239                 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15240                         continue;
15241
15242                 if (strcmp(desc->dtpd_mod, "helper") != 0)
15243                         continue;
15244
15245                 if (strcmp(desc->dtpd_func, "ustack") != 0)
15246                         continue;
15247
15248                 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15249                     ep)) != 0) {
15250                         /*
15251                          * Adding this helper action failed -- we are now going
15252                          * to rip out the entire generation and return failure.
15253                          */
15254                         (void) dtrace_helper_destroygen(help->dthps_generation);
15255                         dtrace_enabling_destroy(enab);
15256                         dtrace_dof_destroy(dof);
15257                         return (-1);
15258                 }
15259
15260                 nhelpers++;
15261         }
15262
15263         if (nhelpers < enab->dten_ndesc)
15264                 dtrace_dof_error(dof, "unmatched helpers");
15265
15266         gen = help->dthps_generation++;
15267         dtrace_enabling_destroy(enab);
15268
15269         if (dhp != NULL && nprovs > 0) {
15270                 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15271                 if (dtrace_helper_provider_add(dhp, gen) == 0) {
15272                         mutex_exit(&dtrace_lock);
15273                         dtrace_helper_provider_register(curproc, help, dhp);
15274                         mutex_enter(&dtrace_lock);
15275
15276                         destroy = 0;
15277                 }
15278         }
15279
15280         if (destroy)
15281                 dtrace_dof_destroy(dof);
15282
15283         return (gen);
15284 }
15285
15286 static dtrace_helpers_t *
15287 dtrace_helpers_create(proc_t *p)
15288 {
15289         dtrace_helpers_t *help;
15290
15291         ASSERT(MUTEX_HELD(&dtrace_lock));
15292         ASSERT(p->p_dtrace_helpers == NULL);
15293
15294         help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15295         help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15296             DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15297
15298         p->p_dtrace_helpers = help;
15299         dtrace_helpers++;
15300
15301         return (help);
15302 }
15303
15304 #if defined(sun)
15305 static
15306 #endif
15307 void
15308 dtrace_helpers_destroy(proc_t *p)
15309 {
15310         dtrace_helpers_t *help;
15311         dtrace_vstate_t *vstate;
15312 #if defined(sun)
15313         proc_t *p = curproc;
15314 #endif
15315         int i;
15316
15317         mutex_enter(&dtrace_lock);
15318
15319         ASSERT(p->p_dtrace_helpers != NULL);
15320         ASSERT(dtrace_helpers > 0);
15321
15322         help = p->p_dtrace_helpers;
15323         vstate = &help->dthps_vstate;
15324
15325         /*
15326          * We're now going to lose the help from this process.
15327          */
15328         p->p_dtrace_helpers = NULL;
15329         dtrace_sync();
15330
15331         /*
15332          * Destory the helper actions.
15333          */
15334         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15335                 dtrace_helper_action_t *h, *next;
15336
15337                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15338                         next = h->dtha_next;
15339                         dtrace_helper_action_destroy(h, vstate);
15340                         h = next;
15341                 }
15342         }
15343
15344         mutex_exit(&dtrace_lock);
15345
15346         /*
15347          * Destroy the helper providers.
15348          */
15349         if (help->dthps_maxprovs > 0) {
15350                 mutex_enter(&dtrace_meta_lock);
15351                 if (dtrace_meta_pid != NULL) {
15352                         ASSERT(dtrace_deferred_pid == NULL);
15353
15354                         for (i = 0; i < help->dthps_nprovs; i++) {
15355                                 dtrace_helper_provider_remove(
15356                                     &help->dthps_provs[i]->dthp_prov, p->p_pid);
15357                         }
15358                 } else {
15359                         mutex_enter(&dtrace_lock);
15360                         ASSERT(help->dthps_deferred == 0 ||
15361                             help->dthps_next != NULL ||
15362                             help->dthps_prev != NULL ||
15363                             help == dtrace_deferred_pid);
15364
15365                         /*
15366                          * Remove the helper from the deferred list.
15367                          */
15368                         if (help->dthps_next != NULL)
15369                                 help->dthps_next->dthps_prev = help->dthps_prev;
15370                         if (help->dthps_prev != NULL)
15371                                 help->dthps_prev->dthps_next = help->dthps_next;
15372                         if (dtrace_deferred_pid == help) {
15373                                 dtrace_deferred_pid = help->dthps_next;
15374                                 ASSERT(help->dthps_prev == NULL);
15375                         }
15376
15377                         mutex_exit(&dtrace_lock);
15378                 }
15379
15380                 mutex_exit(&dtrace_meta_lock);
15381
15382                 for (i = 0; i < help->dthps_nprovs; i++) {
15383                         dtrace_helper_provider_destroy(help->dthps_provs[i]);
15384                 }
15385
15386                 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15387                     sizeof (dtrace_helper_provider_t *));
15388         }
15389
15390         mutex_enter(&dtrace_lock);
15391
15392         dtrace_vstate_fini(&help->dthps_vstate);
15393         kmem_free(help->dthps_actions,
15394             sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15395         kmem_free(help, sizeof (dtrace_helpers_t));
15396
15397         --dtrace_helpers;
15398         mutex_exit(&dtrace_lock);
15399 }
15400
15401 #if defined(sun)
15402 static
15403 #endif
15404 void
15405 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15406 {
15407         dtrace_helpers_t *help, *newhelp;
15408         dtrace_helper_action_t *helper, *new, *last;
15409         dtrace_difo_t *dp;
15410         dtrace_vstate_t *vstate;
15411         int i, j, sz, hasprovs = 0;
15412
15413         mutex_enter(&dtrace_lock);
15414         ASSERT(from->p_dtrace_helpers != NULL);
15415         ASSERT(dtrace_helpers > 0);
15416
15417         help = from->p_dtrace_helpers;
15418         newhelp = dtrace_helpers_create(to);
15419         ASSERT(to->p_dtrace_helpers != NULL);
15420
15421         newhelp->dthps_generation = help->dthps_generation;
15422         vstate = &newhelp->dthps_vstate;
15423
15424         /*
15425          * Duplicate the helper actions.
15426          */
15427         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15428                 if ((helper = help->dthps_actions[i]) == NULL)
15429                         continue;
15430
15431                 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15432                         new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15433                             KM_SLEEP);
15434                         new->dtha_generation = helper->dtha_generation;
15435
15436                         if ((dp = helper->dtha_predicate) != NULL) {
15437                                 dp = dtrace_difo_duplicate(dp, vstate);
15438                                 new->dtha_predicate = dp;
15439                         }
15440
15441                         new->dtha_nactions = helper->dtha_nactions;
15442                         sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15443                         new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15444
15445                         for (j = 0; j < new->dtha_nactions; j++) {
15446                                 dtrace_difo_t *dp = helper->dtha_actions[j];
15447
15448                                 ASSERT(dp != NULL);
15449                                 dp = dtrace_difo_duplicate(dp, vstate);
15450                                 new->dtha_actions[j] = dp;
15451                         }
15452
15453                         if (last != NULL) {
15454                                 last->dtha_next = new;
15455                         } else {
15456                                 newhelp->dthps_actions[i] = new;
15457                         }
15458
15459                         last = new;
15460                 }
15461         }
15462
15463         /*
15464          * Duplicate the helper providers and register them with the
15465          * DTrace framework.
15466          */
15467         if (help->dthps_nprovs > 0) {
15468                 newhelp->dthps_nprovs = help->dthps_nprovs;
15469                 newhelp->dthps_maxprovs = help->dthps_nprovs;
15470                 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15471                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15472                 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15473                         newhelp->dthps_provs[i] = help->dthps_provs[i];
15474                         newhelp->dthps_provs[i]->dthp_ref++;
15475                 }
15476
15477                 hasprovs = 1;
15478         }
15479
15480         mutex_exit(&dtrace_lock);
15481
15482         if (hasprovs)
15483                 dtrace_helper_provider_register(to, newhelp, NULL);
15484 }
15485
15486 /*
15487  * DTrace Hook Functions
15488  */
15489 static void
15490 dtrace_module_loaded(modctl_t *ctl)
15491 {
15492         dtrace_provider_t *prv;
15493
15494         mutex_enter(&dtrace_provider_lock);
15495 #if defined(sun)
15496         mutex_enter(&mod_lock);
15497 #endif
15498
15499 #if defined(sun)
15500         ASSERT(ctl->mod_busy);
15501 #endif
15502
15503         /*
15504          * We're going to call each providers per-module provide operation
15505          * specifying only this module.
15506          */
15507         for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15508                 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15509
15510 #if defined(sun)
15511         mutex_exit(&mod_lock);
15512 #endif
15513         mutex_exit(&dtrace_provider_lock);
15514
15515         /*
15516          * If we have any retained enablings, we need to match against them.
15517          * Enabling probes requires that cpu_lock be held, and we cannot hold
15518          * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15519          * module.  (In particular, this happens when loading scheduling
15520          * classes.)  So if we have any retained enablings, we need to dispatch
15521          * our task queue to do the match for us.
15522          */
15523         mutex_enter(&dtrace_lock);
15524
15525         if (dtrace_retained == NULL) {
15526                 mutex_exit(&dtrace_lock);
15527                 return;
15528         }
15529
15530         (void) taskq_dispatch(dtrace_taskq,
15531             (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15532
15533         mutex_exit(&dtrace_lock);
15534
15535         /*
15536          * And now, for a little heuristic sleaze:  in general, we want to
15537          * match modules as soon as they load.  However, we cannot guarantee
15538          * this, because it would lead us to the lock ordering violation
15539          * outlined above.  The common case, of course, is that cpu_lock is
15540          * _not_ held -- so we delay here for a clock tick, hoping that that's
15541          * long enough for the task queue to do its work.  If it's not, it's
15542          * not a serious problem -- it just means that the module that we
15543          * just loaded may not be immediately instrumentable.
15544          */
15545         delay(1);
15546 }
15547
15548 static void
15549 #if defined(sun)
15550 dtrace_module_unloaded(modctl_t *ctl)
15551 #else
15552 dtrace_module_unloaded(modctl_t *ctl, int *error)
15553 #endif
15554 {
15555         dtrace_probe_t template, *probe, *first, *next;
15556         dtrace_provider_t *prov;
15557 #if !defined(sun)
15558         char modname[DTRACE_MODNAMELEN];
15559         size_t len;
15560 #endif
15561
15562 #if defined(sun)
15563         template.dtpr_mod = ctl->mod_modname;
15564 #else
15565         /* Handle the fact that ctl->filename may end in ".ko". */
15566         strlcpy(modname, ctl->filename, sizeof(modname));
15567         len = strlen(ctl->filename);
15568         if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
15569                 modname[len - 3] = '\0';
15570         template.dtpr_mod = modname;
15571 #endif
15572
15573         mutex_enter(&dtrace_provider_lock);
15574 #if defined(sun)
15575         mutex_enter(&mod_lock);
15576 #endif
15577         mutex_enter(&dtrace_lock);
15578
15579 #if !defined(sun)
15580         if (ctl->nenabled > 0) {
15581                 /* Don't allow unloads if a probe is enabled. */
15582                 mutex_exit(&dtrace_provider_lock);
15583                 mutex_exit(&dtrace_lock);
15584                 *error = -1;
15585                 printf(
15586         "kldunload: attempt to unload module that has DTrace probes enabled\n");
15587                 return;
15588         }
15589 #endif
15590
15591         if (dtrace_bymod == NULL) {
15592                 /*
15593                  * The DTrace module is loaded (obviously) but not attached;
15594                  * we don't have any work to do.
15595                  */
15596                 mutex_exit(&dtrace_provider_lock);
15597 #if defined(sun)
15598                 mutex_exit(&mod_lock);
15599 #endif
15600                 mutex_exit(&dtrace_lock);
15601                 return;
15602         }
15603
15604         for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15605             probe != NULL; probe = probe->dtpr_nextmod) {
15606                 if (probe->dtpr_ecb != NULL) {
15607                         mutex_exit(&dtrace_provider_lock);
15608 #if defined(sun)
15609                         mutex_exit(&mod_lock);
15610 #endif
15611                         mutex_exit(&dtrace_lock);
15612
15613                         /*
15614                          * This shouldn't _actually_ be possible -- we're
15615                          * unloading a module that has an enabled probe in it.
15616                          * (It's normally up to the provider to make sure that
15617                          * this can't happen.)  However, because dtps_enable()
15618                          * doesn't have a failure mode, there can be an
15619                          * enable/unload race.  Upshot:  we don't want to
15620                          * assert, but we're not going to disable the
15621                          * probe, either.
15622                          */
15623                         if (dtrace_err_verbose) {
15624 #if defined(sun)
15625                                 cmn_err(CE_WARN, "unloaded module '%s' had "
15626                                     "enabled probes", ctl->mod_modname);
15627 #else
15628                                 cmn_err(CE_WARN, "unloaded module '%s' had "
15629                                     "enabled probes", modname);
15630 #endif
15631                         }
15632
15633                         return;
15634                 }
15635         }
15636
15637         probe = first;
15638
15639         for (first = NULL; probe != NULL; probe = next) {
15640                 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15641
15642                 dtrace_probes[probe->dtpr_id - 1] = NULL;
15643
15644                 next = probe->dtpr_nextmod;
15645                 dtrace_hash_remove(dtrace_bymod, probe);
15646                 dtrace_hash_remove(dtrace_byfunc, probe);
15647                 dtrace_hash_remove(dtrace_byname, probe);
15648
15649                 if (first == NULL) {
15650                         first = probe;
15651                         probe->dtpr_nextmod = NULL;
15652                 } else {
15653                         probe->dtpr_nextmod = first;
15654                         first = probe;
15655                 }
15656         }
15657
15658         /*
15659          * We've removed all of the module's probes from the hash chains and
15660          * from the probe array.  Now issue a dtrace_sync() to be sure that
15661          * everyone has cleared out from any probe array processing.
15662          */
15663         dtrace_sync();
15664
15665         for (probe = first; probe != NULL; probe = first) {
15666                 first = probe->dtpr_nextmod;
15667                 prov = probe->dtpr_provider;
15668                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15669                     probe->dtpr_arg);
15670                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15671                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15672                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15673 #if defined(sun)
15674                 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15675 #else
15676                 free_unr(dtrace_arena, probe->dtpr_id);
15677 #endif
15678                 kmem_free(probe, sizeof (dtrace_probe_t));
15679         }
15680
15681         mutex_exit(&dtrace_lock);
15682 #if defined(sun)
15683         mutex_exit(&mod_lock);
15684 #endif
15685         mutex_exit(&dtrace_provider_lock);
15686 }
15687
15688 #if !defined(sun)
15689 static void
15690 dtrace_kld_load(void *arg __unused, linker_file_t lf)
15691 {
15692
15693         dtrace_module_loaded(lf);
15694 }
15695
15696 static void
15697 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
15698 {
15699
15700         if (*error != 0)
15701                 /* We already have an error, so don't do anything. */
15702                 return;
15703         dtrace_module_unloaded(lf, error);
15704 }
15705 #endif
15706
15707 #if defined(sun)
15708 static void
15709 dtrace_suspend(void)
15710 {
15711         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15712 }
15713
15714 static void
15715 dtrace_resume(void)
15716 {
15717         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15718 }
15719 #endif
15720
15721 static int
15722 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15723 {
15724         ASSERT(MUTEX_HELD(&cpu_lock));
15725         mutex_enter(&dtrace_lock);
15726
15727         switch (what) {
15728         case CPU_CONFIG: {
15729                 dtrace_state_t *state;
15730                 dtrace_optval_t *opt, rs, c;
15731
15732                 /*
15733                  * For now, we only allocate a new buffer for anonymous state.
15734                  */
15735                 if ((state = dtrace_anon.dta_state) == NULL)
15736                         break;
15737
15738                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15739                         break;
15740
15741                 opt = state->dts_options;
15742                 c = opt[DTRACEOPT_CPU];
15743
15744                 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15745                         break;
15746
15747                 /*
15748                  * Regardless of what the actual policy is, we're going to
15749                  * temporarily set our resize policy to be manual.  We're
15750                  * also going to temporarily set our CPU option to denote
15751                  * the newly configured CPU.
15752                  */
15753                 rs = opt[DTRACEOPT_BUFRESIZE];
15754                 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15755                 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15756
15757                 (void) dtrace_state_buffers(state);
15758
15759                 opt[DTRACEOPT_BUFRESIZE] = rs;
15760                 opt[DTRACEOPT_CPU] = c;
15761
15762                 break;
15763         }
15764
15765         case CPU_UNCONFIG:
15766                 /*
15767                  * We don't free the buffer in the CPU_UNCONFIG case.  (The
15768                  * buffer will be freed when the consumer exits.)
15769                  */
15770                 break;
15771
15772         default:
15773                 break;
15774         }
15775
15776         mutex_exit(&dtrace_lock);
15777         return (0);
15778 }
15779
15780 #if defined(sun)
15781 static void
15782 dtrace_cpu_setup_initial(processorid_t cpu)
15783 {
15784         (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15785 }
15786 #endif
15787
15788 static void
15789 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15790 {
15791         if (dtrace_toxranges >= dtrace_toxranges_max) {
15792                 int osize, nsize;
15793                 dtrace_toxrange_t *range;
15794
15795                 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15796
15797                 if (osize == 0) {
15798                         ASSERT(dtrace_toxrange == NULL);
15799                         ASSERT(dtrace_toxranges_max == 0);
15800                         dtrace_toxranges_max = 1;
15801                 } else {
15802                         dtrace_toxranges_max <<= 1;
15803                 }
15804
15805                 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15806                 range = kmem_zalloc(nsize, KM_SLEEP);
15807
15808                 if (dtrace_toxrange != NULL) {
15809                         ASSERT(osize != 0);
15810                         bcopy(dtrace_toxrange, range, osize);
15811                         kmem_free(dtrace_toxrange, osize);
15812                 }
15813
15814                 dtrace_toxrange = range;
15815         }
15816
15817         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15818         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15819
15820         dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15821         dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15822         dtrace_toxranges++;
15823 }
15824
15825 static void
15826 dtrace_getf_barrier()
15827 {
15828 #if defined(sun)
15829         /*
15830          * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
15831          * that contain calls to getf(), this routine will be called on every
15832          * closef() before either the underlying vnode is released or the
15833          * file_t itself is freed.  By the time we are here, it is essential
15834          * that the file_t can no longer be accessed from a call to getf()
15835          * in probe context -- that assures that a dtrace_sync() can be used
15836          * to clear out any enablings referring to the old structures.
15837          */
15838         if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
15839             kcred->cr_zone->zone_dtrace_getf != 0)
15840                 dtrace_sync();
15841 #endif
15842 }
15843
15844 /*
15845  * DTrace Driver Cookbook Functions
15846  */
15847 #if defined(sun)
15848 /*ARGSUSED*/
15849 static int
15850 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15851 {
15852         dtrace_provider_id_t id;
15853         dtrace_state_t *state = NULL;
15854         dtrace_enabling_t *enab;
15855
15856         mutex_enter(&cpu_lock);
15857         mutex_enter(&dtrace_provider_lock);
15858         mutex_enter(&dtrace_lock);
15859
15860         if (ddi_soft_state_init(&dtrace_softstate,
15861             sizeof (dtrace_state_t), 0) != 0) {
15862                 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15863                 mutex_exit(&cpu_lock);
15864                 mutex_exit(&dtrace_provider_lock);
15865                 mutex_exit(&dtrace_lock);
15866                 return (DDI_FAILURE);
15867         }
15868
15869         if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15870             DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15871             ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15872             DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15873                 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15874                 ddi_remove_minor_node(devi, NULL);
15875                 ddi_soft_state_fini(&dtrace_softstate);
15876                 mutex_exit(&cpu_lock);
15877                 mutex_exit(&dtrace_provider_lock);
15878                 mutex_exit(&dtrace_lock);
15879                 return (DDI_FAILURE);
15880         }
15881
15882         ddi_report_dev(devi);
15883         dtrace_devi = devi;
15884
15885         dtrace_modload = dtrace_module_loaded;
15886         dtrace_modunload = dtrace_module_unloaded;
15887         dtrace_cpu_init = dtrace_cpu_setup_initial;
15888         dtrace_helpers_cleanup = dtrace_helpers_destroy;
15889         dtrace_helpers_fork = dtrace_helpers_duplicate;
15890         dtrace_cpustart_init = dtrace_suspend;
15891         dtrace_cpustart_fini = dtrace_resume;
15892         dtrace_debugger_init = dtrace_suspend;
15893         dtrace_debugger_fini = dtrace_resume;
15894
15895         register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15896
15897         ASSERT(MUTEX_HELD(&cpu_lock));
15898
15899         dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15900             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15901         dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15902             UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15903             VM_SLEEP | VMC_IDENTIFIER);
15904         dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15905             1, INT_MAX, 0);
15906
15907         dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15908             sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15909             NULL, NULL, NULL, NULL, NULL, 0);
15910
15911         ASSERT(MUTEX_HELD(&cpu_lock));
15912         dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15913             offsetof(dtrace_probe_t, dtpr_nextmod),
15914             offsetof(dtrace_probe_t, dtpr_prevmod));
15915
15916         dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15917             offsetof(dtrace_probe_t, dtpr_nextfunc),
15918             offsetof(dtrace_probe_t, dtpr_prevfunc));
15919
15920         dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15921             offsetof(dtrace_probe_t, dtpr_nextname),
15922             offsetof(dtrace_probe_t, dtpr_prevname));
15923
15924         if (dtrace_retain_max < 1) {
15925                 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15926                     "setting to 1", dtrace_retain_max);
15927                 dtrace_retain_max = 1;
15928         }
15929
15930         /*
15931          * Now discover our toxic ranges.
15932          */
15933         dtrace_toxic_ranges(dtrace_toxrange_add);
15934
15935         /*
15936          * Before we register ourselves as a provider to our own framework,
15937          * we would like to assert that dtrace_provider is NULL -- but that's
15938          * not true if we were loaded as a dependency of a DTrace provider.
15939          * Once we've registered, we can assert that dtrace_provider is our
15940          * pseudo provider.
15941          */
15942         (void) dtrace_register("dtrace", &dtrace_provider_attr,
15943             DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15944
15945         ASSERT(dtrace_provider != NULL);
15946         ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15947
15948         dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15949             dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15950         dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15951             dtrace_provider, NULL, NULL, "END", 0, NULL);
15952         dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15953             dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15954
15955         dtrace_anon_property();
15956         mutex_exit(&cpu_lock);
15957
15958         /*
15959          * If DTrace helper tracing is enabled, we need to allocate the
15960          * trace buffer and initialize the values.
15961          */
15962         if (dtrace_helptrace_enabled) {
15963                 ASSERT(dtrace_helptrace_buffer == NULL);
15964                 dtrace_helptrace_buffer =
15965                     kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15966                 dtrace_helptrace_next = 0;
15967         }
15968
15969         /*
15970          * If there are already providers, we must ask them to provide their
15971          * probes, and then match any anonymous enabling against them.  Note
15972          * that there should be no other retained enablings at this time:
15973          * the only retained enablings at this time should be the anonymous
15974          * enabling.
15975          */
15976         if (dtrace_anon.dta_enabling != NULL) {
15977                 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15978
15979                 dtrace_enabling_provide(NULL);
15980                 state = dtrace_anon.dta_state;
15981
15982                 /*
15983                  * We couldn't hold cpu_lock across the above call to
15984                  * dtrace_enabling_provide(), but we must hold it to actually
15985                  * enable the probes.  We have to drop all of our locks, pick
15986                  * up cpu_lock, and regain our locks before matching the
15987                  * retained anonymous enabling.
15988                  */
15989                 mutex_exit(&dtrace_lock);
15990                 mutex_exit(&dtrace_provider_lock);
15991
15992                 mutex_enter(&cpu_lock);
15993                 mutex_enter(&dtrace_provider_lock);
15994                 mutex_enter(&dtrace_lock);
15995
15996                 if ((enab = dtrace_anon.dta_enabling) != NULL)
15997                         (void) dtrace_enabling_match(enab, NULL);
15998
15999                 mutex_exit(&cpu_lock);
16000         }
16001
16002         mutex_exit(&dtrace_lock);
16003         mutex_exit(&dtrace_provider_lock);
16004
16005         if (state != NULL) {
16006                 /*
16007                  * If we created any anonymous state, set it going now.
16008                  */
16009                 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16010         }
16011
16012         return (DDI_SUCCESS);
16013 }
16014 #endif
16015
16016 #if !defined(sun)
16017 static void dtrace_dtr(void *);
16018 #endif
16019
16020 /*ARGSUSED*/
16021 static int
16022 #if defined(sun)
16023 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16024 #else
16025 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
16026 #endif
16027 {
16028         dtrace_state_t *state;
16029         uint32_t priv;
16030         uid_t uid;
16031         zoneid_t zoneid;
16032
16033 #if defined(sun)
16034         if (getminor(*devp) == DTRACEMNRN_HELPER)
16035                 return (0);
16036
16037         /*
16038          * If this wasn't an open with the "helper" minor, then it must be
16039          * the "dtrace" minor.
16040          */
16041         ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
16042 #else
16043         cred_t *cred_p = NULL;
16044         cred_p = dev->si_cred;
16045
16046         /*
16047          * If no DTRACE_PRIV_* bits are set in the credential, then the
16048          * caller lacks sufficient permission to do anything with DTrace.
16049          */
16050         dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16051         if (priv == DTRACE_PRIV_NONE) {
16052 #endif
16053
16054                 return (EACCES);
16055         }
16056
16057         /*
16058          * Ask all providers to provide all their probes.
16059          */
16060         mutex_enter(&dtrace_provider_lock);
16061         dtrace_probe_provide(NULL, NULL);
16062         mutex_exit(&dtrace_provider_lock);
16063
16064         mutex_enter(&cpu_lock);
16065         mutex_enter(&dtrace_lock);
16066         dtrace_opens++;
16067         dtrace_membar_producer();
16068
16069 #if defined(sun)
16070         /*
16071          * If the kernel debugger is active (that is, if the kernel debugger
16072          * modified text in some way), we won't allow the open.
16073          */
16074         if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16075                 dtrace_opens--;
16076                 mutex_exit(&cpu_lock);
16077                 mutex_exit(&dtrace_lock);
16078                 return (EBUSY);
16079         }
16080
16081         state = dtrace_state_create(devp, cred_p);
16082 #else
16083         state = dtrace_state_create(dev);
16084         devfs_set_cdevpriv(state, dtrace_dtr);
16085 #endif
16086
16087         mutex_exit(&cpu_lock);
16088
16089         if (state == NULL) {
16090 #if defined(sun)
16091                 if (--dtrace_opens == 0)
16092                         (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16093 #else
16094                 --dtrace_opens;
16095 #endif
16096                 mutex_exit(&dtrace_lock);
16097                 return (EAGAIN);
16098         }
16099
16100         mutex_exit(&dtrace_lock);
16101
16102         return (0);
16103 }
16104
16105 /*ARGSUSED*/
16106 #if defined(sun)
16107 static int
16108 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16109 #else
16110 static void
16111 dtrace_dtr(void *data)
16112 #endif
16113 {
16114 #if defined(sun)
16115         minor_t minor = getminor(dev);
16116         dtrace_state_t *state;
16117
16118         if (minor == DTRACEMNRN_HELPER)
16119                 return (0);
16120
16121         state = ddi_get_soft_state(dtrace_softstate, minor);
16122 #else
16123         dtrace_state_t *state = data;
16124 #endif
16125
16126         mutex_enter(&cpu_lock);
16127         mutex_enter(&dtrace_lock);
16128
16129         if (state != NULL) {
16130                 if (state->dts_anon) {
16131                         /*
16132                          * There is anonymous state. Destroy that first.
16133                          */
16134                         ASSERT(dtrace_anon.dta_state == NULL);
16135                         dtrace_state_destroy(state->dts_anon);
16136                 }
16137
16138                 dtrace_state_destroy(state);
16139
16140 #if !defined(sun)
16141                 kmem_free(state, 0);
16142 #endif
16143         }
16144
16145         ASSERT(dtrace_opens > 0);
16146 #if defined(sun)
16147         if (--dtrace_opens == 0)
16148                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16149 #else
16150         --dtrace_opens;
16151 #endif
16152
16153         mutex_exit(&dtrace_lock);
16154         mutex_exit(&cpu_lock);
16155
16156 #if defined(sun)
16157         return (0);
16158 #endif
16159 }
16160
16161 #if defined(sun)
16162 /*ARGSUSED*/
16163 static int
16164 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16165 {
16166         int rval;
16167         dof_helper_t help, *dhp = NULL;
16168
16169         switch (cmd) {
16170         case DTRACEHIOC_ADDDOF:
16171                 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16172                         dtrace_dof_error(NULL, "failed to copyin DOF helper");
16173                         return (EFAULT);
16174                 }
16175
16176                 dhp = &help;
16177                 arg = (intptr_t)help.dofhp_dof;
16178                 /*FALLTHROUGH*/
16179
16180         case DTRACEHIOC_ADD: {
16181                 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
16182
16183                 if (dof == NULL)
16184                         return (rval);
16185
16186                 mutex_enter(&dtrace_lock);
16187
16188                 /*
16189                  * dtrace_helper_slurp() takes responsibility for the dof --
16190                  * it may free it now or it may save it and free it later.
16191                  */
16192                 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
16193                         *rv = rval;
16194                         rval = 0;
16195                 } else {
16196                         rval = EINVAL;
16197                 }
16198
16199                 mutex_exit(&dtrace_lock);
16200                 return (rval);
16201         }
16202
16203         case DTRACEHIOC_REMOVE: {
16204                 mutex_enter(&dtrace_lock);
16205                 rval = dtrace_helper_destroygen(arg);
16206                 mutex_exit(&dtrace_lock);
16207
16208                 return (rval);
16209         }
16210
16211         default:
16212                 break;
16213         }
16214
16215         return (ENOTTY);
16216 }
16217
16218 /*ARGSUSED*/
16219 static int
16220 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16221 {
16222         minor_t minor = getminor(dev);
16223         dtrace_state_t *state;
16224         int rval;
16225
16226         if (minor == DTRACEMNRN_HELPER)
16227                 return (dtrace_ioctl_helper(cmd, arg, rv));
16228
16229         state = ddi_get_soft_state(dtrace_softstate, minor);
16230
16231         if (state->dts_anon) {
16232                 ASSERT(dtrace_anon.dta_state == NULL);
16233                 state = state->dts_anon;
16234         }
16235
16236         switch (cmd) {
16237         case DTRACEIOC_PROVIDER: {
16238                 dtrace_providerdesc_t pvd;
16239                 dtrace_provider_t *pvp;
16240
16241                 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16242                         return (EFAULT);
16243
16244                 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16245                 mutex_enter(&dtrace_provider_lock);
16246
16247                 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16248                         if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16249                                 break;
16250                 }
16251
16252                 mutex_exit(&dtrace_provider_lock);
16253
16254                 if (pvp == NULL)
16255                         return (ESRCH);
16256
16257                 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16258                 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16259
16260                 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16261                         return (EFAULT);
16262
16263                 return (0);
16264         }
16265
16266         case DTRACEIOC_EPROBE: {
16267                 dtrace_eprobedesc_t epdesc;
16268                 dtrace_ecb_t *ecb;
16269                 dtrace_action_t *act;
16270                 void *buf;
16271                 size_t size;
16272                 uintptr_t dest;
16273                 int nrecs;
16274
16275                 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16276                         return (EFAULT);
16277
16278                 mutex_enter(&dtrace_lock);
16279
16280                 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16281                         mutex_exit(&dtrace_lock);
16282                         return (EINVAL);
16283                 }
16284
16285                 if (ecb->dte_probe == NULL) {
16286                         mutex_exit(&dtrace_lock);
16287                         return (EINVAL);
16288                 }
16289
16290                 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16291                 epdesc.dtepd_uarg = ecb->dte_uarg;
16292                 epdesc.dtepd_size = ecb->dte_size;
16293
16294                 nrecs = epdesc.dtepd_nrecs;
16295                 epdesc.dtepd_nrecs = 0;
16296                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16297                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16298                                 continue;
16299
16300                         epdesc.dtepd_nrecs++;
16301                 }
16302
16303                 /*
16304                  * Now that we have the size, we need to allocate a temporary
16305                  * buffer in which to store the complete description.  We need
16306                  * the temporary buffer to be able to drop dtrace_lock()
16307                  * across the copyout(), below.
16308                  */
16309                 size = sizeof (dtrace_eprobedesc_t) +
16310                     (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16311
16312                 buf = kmem_alloc(size, KM_SLEEP);
16313                 dest = (uintptr_t)buf;
16314
16315                 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16316                 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16317
16318                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16319                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16320                                 continue;
16321
16322                         if (nrecs-- == 0)
16323                                 break;
16324
16325                         bcopy(&act->dta_rec, (void *)dest,
16326                             sizeof (dtrace_recdesc_t));
16327                         dest += sizeof (dtrace_recdesc_t);
16328                 }
16329
16330                 mutex_exit(&dtrace_lock);
16331
16332                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16333                         kmem_free(buf, size);
16334                         return (EFAULT);
16335                 }
16336
16337                 kmem_free(buf, size);
16338                 return (0);
16339         }
16340
16341         case DTRACEIOC_AGGDESC: {
16342                 dtrace_aggdesc_t aggdesc;
16343                 dtrace_action_t *act;
16344                 dtrace_aggregation_t *agg;
16345                 int nrecs;
16346                 uint32_t offs;
16347                 dtrace_recdesc_t *lrec;
16348                 void *buf;
16349                 size_t size;
16350                 uintptr_t dest;
16351
16352                 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16353                         return (EFAULT);
16354
16355                 mutex_enter(&dtrace_lock);
16356
16357                 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16358                         mutex_exit(&dtrace_lock);
16359                         return (EINVAL);
16360                 }
16361
16362                 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16363
16364                 nrecs = aggdesc.dtagd_nrecs;
16365                 aggdesc.dtagd_nrecs = 0;
16366
16367                 offs = agg->dtag_base;
16368                 lrec = &agg->dtag_action.dta_rec;
16369                 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16370
16371                 for (act = agg->dtag_first; ; act = act->dta_next) {
16372                         ASSERT(act->dta_intuple ||
16373                             DTRACEACT_ISAGG(act->dta_kind));
16374
16375                         /*
16376                          * If this action has a record size of zero, it
16377                          * denotes an argument to the aggregating action.
16378                          * Because the presence of this record doesn't (or
16379                          * shouldn't) affect the way the data is interpreted,
16380                          * we don't copy it out to save user-level the
16381                          * confusion of dealing with a zero-length record.
16382                          */
16383                         if (act->dta_rec.dtrd_size == 0) {
16384                                 ASSERT(agg->dtag_hasarg);
16385                                 continue;
16386                         }
16387
16388                         aggdesc.dtagd_nrecs++;
16389
16390                         if (act == &agg->dtag_action)
16391                                 break;
16392                 }
16393
16394                 /*
16395                  * Now that we have the size, we need to allocate a temporary
16396                  * buffer in which to store the complete description.  We need
16397                  * the temporary buffer to be able to drop dtrace_lock()
16398                  * across the copyout(), below.
16399                  */
16400                 size = sizeof (dtrace_aggdesc_t) +
16401                     (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16402
16403                 buf = kmem_alloc(size, KM_SLEEP);
16404                 dest = (uintptr_t)buf;
16405
16406                 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16407                 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16408
16409                 for (act = agg->dtag_first; ; act = act->dta_next) {
16410                         dtrace_recdesc_t rec = act->dta_rec;
16411
16412                         /*
16413                          * See the comment in the above loop for why we pass
16414                          * over zero-length records.
16415                          */
16416                         if (rec.dtrd_size == 0) {
16417                                 ASSERT(agg->dtag_hasarg);
16418                                 continue;
16419                         }
16420
16421                         if (nrecs-- == 0)
16422                                 break;
16423
16424                         rec.dtrd_offset -= offs;
16425                         bcopy(&rec, (void *)dest, sizeof (rec));
16426                         dest += sizeof (dtrace_recdesc_t);
16427
16428                         if (act == &agg->dtag_action)
16429                                 break;
16430                 }
16431
16432                 mutex_exit(&dtrace_lock);
16433
16434                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16435                         kmem_free(buf, size);
16436                         return (EFAULT);
16437                 }
16438
16439                 kmem_free(buf, size);
16440                 return (0);
16441         }
16442
16443         case DTRACEIOC_ENABLE: {
16444                 dof_hdr_t *dof;
16445                 dtrace_enabling_t *enab = NULL;
16446                 dtrace_vstate_t *vstate;
16447                 int err = 0;
16448
16449                 *rv = 0;
16450
16451                 /*
16452                  * If a NULL argument has been passed, we take this as our
16453                  * cue to reevaluate our enablings.
16454                  */
16455                 if (arg == NULL) {
16456                         dtrace_enabling_matchall();
16457
16458                         return (0);
16459                 }
16460
16461                 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16462                         return (rval);
16463
16464                 mutex_enter(&cpu_lock);
16465                 mutex_enter(&dtrace_lock);
16466                 vstate = &state->dts_vstate;
16467
16468                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16469                         mutex_exit(&dtrace_lock);
16470                         mutex_exit(&cpu_lock);
16471                         dtrace_dof_destroy(dof);
16472                         return (EBUSY);
16473                 }
16474
16475                 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16476                         mutex_exit(&dtrace_lock);
16477                         mutex_exit(&cpu_lock);
16478                         dtrace_dof_destroy(dof);
16479                         return (EINVAL);
16480                 }
16481
16482                 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16483                         dtrace_enabling_destroy(enab);
16484                         mutex_exit(&dtrace_lock);
16485                         mutex_exit(&cpu_lock);
16486                         dtrace_dof_destroy(dof);
16487                         return (rval);
16488                 }
16489
16490                 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16491                         err = dtrace_enabling_retain(enab);
16492                 } else {
16493                         dtrace_enabling_destroy(enab);
16494                 }
16495
16496                 mutex_exit(&cpu_lock);
16497                 mutex_exit(&dtrace_lock);
16498                 dtrace_dof_destroy(dof);
16499
16500                 return (err);
16501         }
16502
16503         case DTRACEIOC_REPLICATE: {
16504                 dtrace_repldesc_t desc;
16505                 dtrace_probedesc_t *match = &desc.dtrpd_match;
16506                 dtrace_probedesc_t *create = &desc.dtrpd_create;
16507                 int err;
16508
16509                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16510                         return (EFAULT);
16511
16512                 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16513                 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16514                 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16515                 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16516
16517                 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16518                 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16519                 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16520                 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16521
16522                 mutex_enter(&dtrace_lock);
16523                 err = dtrace_enabling_replicate(state, match, create);
16524                 mutex_exit(&dtrace_lock);
16525
16526                 return (err);
16527         }
16528
16529         case DTRACEIOC_PROBEMATCH:
16530         case DTRACEIOC_PROBES: {
16531                 dtrace_probe_t *probe = NULL;
16532                 dtrace_probedesc_t desc;
16533                 dtrace_probekey_t pkey;
16534                 dtrace_id_t i;
16535                 int m = 0;
16536                 uint32_t priv;
16537                 uid_t uid;
16538                 zoneid_t zoneid;
16539
16540                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16541                         return (EFAULT);
16542
16543                 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16544                 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16545                 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16546                 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16547
16548                 /*
16549                  * Before we attempt to match this probe, we want to give
16550                  * all providers the opportunity to provide it.
16551                  */
16552                 if (desc.dtpd_id == DTRACE_IDNONE) {
16553                         mutex_enter(&dtrace_provider_lock);
16554                         dtrace_probe_provide(&desc, NULL);
16555                         mutex_exit(&dtrace_provider_lock);
16556                         desc.dtpd_id++;
16557                 }
16558
16559                 if (cmd == DTRACEIOC_PROBEMATCH)  {
16560                         dtrace_probekey(&desc, &pkey);
16561                         pkey.dtpk_id = DTRACE_IDNONE;
16562                 }
16563
16564                 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16565
16566                 mutex_enter(&dtrace_lock);
16567
16568                 if (cmd == DTRACEIOC_PROBEMATCH) {
16569                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16570                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16571                                     (m = dtrace_match_probe(probe, &pkey,
16572                                     priv, uid, zoneid)) != 0)
16573                                         break;
16574                         }
16575
16576                         if (m < 0) {
16577                                 mutex_exit(&dtrace_lock);
16578                                 return (EINVAL);
16579                         }
16580
16581                 } else {
16582                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16583                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16584                                     dtrace_match_priv(probe, priv, uid, zoneid))
16585                                         break;
16586                         }
16587                 }
16588
16589                 if (probe == NULL) {
16590                         mutex_exit(&dtrace_lock);
16591                         return (ESRCH);
16592                 }
16593
16594                 dtrace_probe_description(probe, &desc);
16595                 mutex_exit(&dtrace_lock);
16596
16597                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16598                         return (EFAULT);
16599
16600                 return (0);
16601         }
16602
16603         case DTRACEIOC_PROBEARG: {
16604                 dtrace_argdesc_t desc;
16605                 dtrace_probe_t *probe;
16606                 dtrace_provider_t *prov;
16607
16608                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16609                         return (EFAULT);
16610
16611                 if (desc.dtargd_id == DTRACE_IDNONE)
16612                         return (EINVAL);
16613
16614                 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16615                         return (EINVAL);
16616
16617                 mutex_enter(&dtrace_provider_lock);
16618                 mutex_enter(&mod_lock);
16619                 mutex_enter(&dtrace_lock);
16620
16621                 if (desc.dtargd_id > dtrace_nprobes) {
16622                         mutex_exit(&dtrace_lock);
16623                         mutex_exit(&mod_lock);
16624                         mutex_exit(&dtrace_provider_lock);
16625                         return (EINVAL);
16626                 }
16627
16628                 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16629                         mutex_exit(&dtrace_lock);
16630                         mutex_exit(&mod_lock);
16631                         mutex_exit(&dtrace_provider_lock);
16632                         return (EINVAL);
16633                 }
16634
16635                 mutex_exit(&dtrace_lock);
16636
16637                 prov = probe->dtpr_provider;
16638
16639                 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16640                         /*
16641                          * There isn't any typed information for this probe.
16642                          * Set the argument number to DTRACE_ARGNONE.
16643                          */
16644                         desc.dtargd_ndx = DTRACE_ARGNONE;
16645                 } else {
16646                         desc.dtargd_native[0] = '\0';
16647                         desc.dtargd_xlate[0] = '\0';
16648                         desc.dtargd_mapping = desc.dtargd_ndx;
16649
16650                         prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16651                             probe->dtpr_id, probe->dtpr_arg, &desc);
16652                 }
16653
16654                 mutex_exit(&mod_lock);
16655                 mutex_exit(&dtrace_provider_lock);
16656
16657                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16658                         return (EFAULT);
16659
16660                 return (0);
16661         }
16662
16663         case DTRACEIOC_GO: {
16664                 processorid_t cpuid;
16665                 rval = dtrace_state_go(state, &cpuid);
16666
16667                 if (rval != 0)
16668                         return (rval);
16669
16670                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16671                         return (EFAULT);
16672
16673                 return (0);
16674         }
16675
16676         case DTRACEIOC_STOP: {
16677                 processorid_t cpuid;
16678
16679                 mutex_enter(&dtrace_lock);
16680                 rval = dtrace_state_stop(state, &cpuid);
16681                 mutex_exit(&dtrace_lock);
16682
16683                 if (rval != 0)
16684                         return (rval);
16685
16686                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16687                         return (EFAULT);
16688
16689                 return (0);
16690         }
16691
16692         case DTRACEIOC_DOFGET: {
16693                 dof_hdr_t hdr, *dof;
16694                 uint64_t len;
16695
16696                 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16697                         return (EFAULT);
16698
16699                 mutex_enter(&dtrace_lock);
16700                 dof = dtrace_dof_create(state);
16701                 mutex_exit(&dtrace_lock);
16702
16703                 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16704                 rval = copyout(dof, (void *)arg, len);
16705                 dtrace_dof_destroy(dof);
16706
16707                 return (rval == 0 ? 0 : EFAULT);
16708         }
16709
16710         case DTRACEIOC_AGGSNAP:
16711         case DTRACEIOC_BUFSNAP: {
16712                 dtrace_bufdesc_t desc;
16713                 caddr_t cached;
16714                 dtrace_buffer_t *buf;
16715
16716                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16717                         return (EFAULT);
16718
16719                 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16720                         return (EINVAL);
16721
16722                 mutex_enter(&dtrace_lock);
16723
16724                 if (cmd == DTRACEIOC_BUFSNAP) {
16725                         buf = &state->dts_buffer[desc.dtbd_cpu];
16726                 } else {
16727                         buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16728                 }
16729
16730                 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16731                         size_t sz = buf->dtb_offset;
16732
16733                         if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16734                                 mutex_exit(&dtrace_lock);
16735                                 return (EBUSY);
16736                         }
16737
16738                         /*
16739                          * If this buffer has already been consumed, we're
16740                          * going to indicate that there's nothing left here
16741                          * to consume.
16742                          */
16743                         if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16744                                 mutex_exit(&dtrace_lock);
16745
16746                                 desc.dtbd_size = 0;
16747                                 desc.dtbd_drops = 0;
16748                                 desc.dtbd_errors = 0;
16749                                 desc.dtbd_oldest = 0;
16750                                 sz = sizeof (desc);
16751
16752                                 if (copyout(&desc, (void *)arg, sz) != 0)
16753                                         return (EFAULT);
16754
16755                                 return (0);
16756                         }
16757
16758                         /*
16759                          * If this is a ring buffer that has wrapped, we want
16760                          * to copy the whole thing out.
16761                          */
16762                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16763                                 dtrace_buffer_polish(buf);
16764                                 sz = buf->dtb_size;
16765                         }
16766
16767                         if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16768                                 mutex_exit(&dtrace_lock);
16769                                 return (EFAULT);
16770                         }
16771
16772                         desc.dtbd_size = sz;
16773                         desc.dtbd_drops = buf->dtb_drops;
16774                         desc.dtbd_errors = buf->dtb_errors;
16775                         desc.dtbd_oldest = buf->dtb_xamot_offset;
16776                         desc.dtbd_timestamp = dtrace_gethrtime();
16777
16778                         mutex_exit(&dtrace_lock);
16779
16780                         if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16781                                 return (EFAULT);
16782
16783                         buf->dtb_flags |= DTRACEBUF_CONSUMED;
16784
16785                         return (0);
16786                 }
16787
16788                 if (buf->dtb_tomax == NULL) {
16789                         ASSERT(buf->dtb_xamot == NULL);
16790                         mutex_exit(&dtrace_lock);
16791                         return (ENOENT);
16792                 }
16793
16794                 cached = buf->dtb_tomax;
16795                 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16796
16797                 dtrace_xcall(desc.dtbd_cpu,
16798                     (dtrace_xcall_t)dtrace_buffer_switch, buf);
16799
16800                 state->dts_errors += buf->dtb_xamot_errors;
16801
16802                 /*
16803                  * If the buffers did not actually switch, then the cross call
16804                  * did not take place -- presumably because the given CPU is
16805                  * not in the ready set.  If this is the case, we'll return
16806                  * ENOENT.
16807                  */
16808                 if (buf->dtb_tomax == cached) {
16809                         ASSERT(buf->dtb_xamot != cached);
16810                         mutex_exit(&dtrace_lock);
16811                         return (ENOENT);
16812                 }
16813
16814                 ASSERT(cached == buf->dtb_xamot);
16815
16816                 /*
16817                  * We have our snapshot; now copy it out.
16818                  */
16819                 if (copyout(buf->dtb_xamot, desc.dtbd_data,
16820                     buf->dtb_xamot_offset) != 0) {
16821                         mutex_exit(&dtrace_lock);
16822                         return (EFAULT);
16823                 }
16824
16825                 desc.dtbd_size = buf->dtb_xamot_offset;
16826                 desc.dtbd_drops = buf->dtb_xamot_drops;
16827                 desc.dtbd_errors = buf->dtb_xamot_errors;
16828                 desc.dtbd_oldest = 0;
16829                 desc.dtbd_timestamp = buf->dtb_switched;
16830
16831                 mutex_exit(&dtrace_lock);
16832
16833                 /*
16834                  * Finally, copy out the buffer description.
16835                  */
16836                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16837                         return (EFAULT);
16838
16839                 return (0);
16840         }
16841
16842         case DTRACEIOC_CONF: {
16843                 dtrace_conf_t conf;
16844
16845                 bzero(&conf, sizeof (conf));
16846                 conf.dtc_difversion = DIF_VERSION;
16847                 conf.dtc_difintregs = DIF_DIR_NREGS;
16848                 conf.dtc_diftupregs = DIF_DTR_NREGS;
16849                 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16850
16851                 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16852                         return (EFAULT);
16853
16854                 return (0);
16855         }
16856
16857         case DTRACEIOC_STATUS: {
16858                 dtrace_status_t stat;
16859                 dtrace_dstate_t *dstate;
16860                 int i, j;
16861                 uint64_t nerrs;
16862
16863                 /*
16864                  * See the comment in dtrace_state_deadman() for the reason
16865                  * for setting dts_laststatus to INT64_MAX before setting
16866                  * it to the correct value.
16867                  */
16868                 state->dts_laststatus = INT64_MAX;
16869                 dtrace_membar_producer();
16870                 state->dts_laststatus = dtrace_gethrtime();
16871
16872                 bzero(&stat, sizeof (stat));
16873
16874                 mutex_enter(&dtrace_lock);
16875
16876                 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16877                         mutex_exit(&dtrace_lock);
16878                         return (ENOENT);
16879                 }
16880
16881                 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16882                         stat.dtst_exiting = 1;
16883
16884                 nerrs = state->dts_errors;
16885                 dstate = &state->dts_vstate.dtvs_dynvars;
16886
16887                 for (i = 0; i < NCPU; i++) {
16888                         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16889
16890                         stat.dtst_dyndrops += dcpu->dtdsc_drops;
16891                         stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16892                         stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16893
16894                         if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16895                                 stat.dtst_filled++;
16896
16897                         nerrs += state->dts_buffer[i].dtb_errors;
16898
16899                         for (j = 0; j < state->dts_nspeculations; j++) {
16900                                 dtrace_speculation_t *spec;
16901                                 dtrace_buffer_t *buf;
16902
16903                                 spec = &state->dts_speculations[j];
16904                                 buf = &spec->dtsp_buffer[i];
16905                                 stat.dtst_specdrops += buf->dtb_xamot_drops;
16906                         }
16907                 }
16908
16909                 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16910                 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16911                 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16912                 stat.dtst_dblerrors = state->dts_dblerrors;
16913                 stat.dtst_killed =
16914                     (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16915                 stat.dtst_errors = nerrs;
16916
16917                 mutex_exit(&dtrace_lock);
16918
16919                 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16920                         return (EFAULT);
16921
16922                 return (0);
16923         }
16924
16925         case DTRACEIOC_FORMAT: {
16926                 dtrace_fmtdesc_t fmt;
16927                 char *str;
16928                 int len;
16929
16930                 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16931                         return (EFAULT);
16932
16933                 mutex_enter(&dtrace_lock);
16934
16935                 if (fmt.dtfd_format == 0 ||
16936                     fmt.dtfd_format > state->dts_nformats) {
16937                         mutex_exit(&dtrace_lock);
16938                         return (EINVAL);
16939                 }
16940
16941                 /*
16942                  * Format strings are allocated contiguously and they are
16943                  * never freed; if a format index is less than the number
16944                  * of formats, we can assert that the format map is non-NULL
16945                  * and that the format for the specified index is non-NULL.
16946                  */
16947                 ASSERT(state->dts_formats != NULL);
16948                 str = state->dts_formats[fmt.dtfd_format - 1];
16949                 ASSERT(str != NULL);
16950
16951                 len = strlen(str) + 1;
16952
16953                 if (len > fmt.dtfd_length) {
16954                         fmt.dtfd_length = len;
16955
16956                         if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16957                                 mutex_exit(&dtrace_lock);
16958                                 return (EINVAL);
16959                         }
16960                 } else {
16961                         if (copyout(str, fmt.dtfd_string, len) != 0) {
16962                                 mutex_exit(&dtrace_lock);
16963                                 return (EINVAL);
16964                         }
16965                 }
16966
16967                 mutex_exit(&dtrace_lock);
16968                 return (0);
16969         }
16970
16971         default:
16972                 break;
16973         }
16974
16975         return (ENOTTY);
16976 }
16977
16978 /*ARGSUSED*/
16979 static int
16980 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16981 {
16982         dtrace_state_t *state;
16983
16984         switch (cmd) {
16985         case DDI_DETACH:
16986                 break;
16987
16988         case DDI_SUSPEND:
16989                 return (DDI_SUCCESS);
16990
16991         default:
16992                 return (DDI_FAILURE);
16993         }
16994
16995         mutex_enter(&cpu_lock);
16996         mutex_enter(&dtrace_provider_lock);
16997         mutex_enter(&dtrace_lock);
16998
16999         ASSERT(dtrace_opens == 0);
17000
17001         if (dtrace_helpers > 0) {
17002                 mutex_exit(&dtrace_provider_lock);
17003                 mutex_exit(&dtrace_lock);
17004                 mutex_exit(&cpu_lock);
17005                 return (DDI_FAILURE);
17006         }
17007
17008         if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17009                 mutex_exit(&dtrace_provider_lock);
17010                 mutex_exit(&dtrace_lock);
17011                 mutex_exit(&cpu_lock);
17012                 return (DDI_FAILURE);
17013         }
17014
17015         dtrace_provider = NULL;
17016
17017         if ((state = dtrace_anon_grab()) != NULL) {
17018                 /*
17019                  * If there were ECBs on this state, the provider should
17020                  * have not been allowed to detach; assert that there is
17021                  * none.
17022                  */
17023                 ASSERT(state->dts_necbs == 0);
17024                 dtrace_state_destroy(state);
17025
17026                 /*
17027                  * If we're being detached with anonymous state, we need to
17028                  * indicate to the kernel debugger that DTrace is now inactive.
17029                  */
17030                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17031         }
17032
17033         bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17034         unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17035         dtrace_cpu_init = NULL;
17036         dtrace_helpers_cleanup = NULL;
17037         dtrace_helpers_fork = NULL;
17038         dtrace_cpustart_init = NULL;
17039         dtrace_cpustart_fini = NULL;
17040         dtrace_debugger_init = NULL;
17041         dtrace_debugger_fini = NULL;
17042         dtrace_modload = NULL;
17043         dtrace_modunload = NULL;
17044
17045         ASSERT(dtrace_getf == 0);
17046         ASSERT(dtrace_closef == NULL);
17047
17048         mutex_exit(&cpu_lock);
17049
17050         if (dtrace_helptrace_enabled) {
17051                 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
17052                 dtrace_helptrace_buffer = NULL;
17053         }
17054
17055         kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17056         dtrace_probes = NULL;
17057         dtrace_nprobes = 0;
17058
17059         dtrace_hash_destroy(dtrace_bymod);
17060         dtrace_hash_destroy(dtrace_byfunc);
17061         dtrace_hash_destroy(dtrace_byname);
17062         dtrace_bymod = NULL;
17063         dtrace_byfunc = NULL;
17064         dtrace_byname = NULL;
17065
17066         kmem_cache_destroy(dtrace_state_cache);
17067         vmem_destroy(dtrace_minor);
17068         vmem_destroy(dtrace_arena);
17069
17070         if (dtrace_toxrange != NULL) {
17071                 kmem_free(dtrace_toxrange,
17072                     dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17073                 dtrace_toxrange = NULL;
17074                 dtrace_toxranges = 0;
17075                 dtrace_toxranges_max = 0;
17076         }
17077
17078         ddi_remove_minor_node(dtrace_devi, NULL);
17079         dtrace_devi = NULL;
17080
17081         ddi_soft_state_fini(&dtrace_softstate);
17082
17083         ASSERT(dtrace_vtime_references == 0);
17084         ASSERT(dtrace_opens == 0);
17085         ASSERT(dtrace_retained == NULL);
17086
17087         mutex_exit(&dtrace_lock);
17088         mutex_exit(&dtrace_provider_lock);
17089
17090         /*
17091          * We don't destroy the task queue until after we have dropped our
17092          * locks (taskq_destroy() may block on running tasks).  To prevent
17093          * attempting to do work after we have effectively detached but before
17094          * the task queue has been destroyed, all tasks dispatched via the
17095          * task queue must check that DTrace is still attached before
17096          * performing any operation.
17097          */
17098         taskq_destroy(dtrace_taskq);
17099         dtrace_taskq = NULL;
17100
17101         return (DDI_SUCCESS);
17102 }
17103 #endif
17104
17105 #if defined(sun)
17106 /*ARGSUSED*/
17107 static int
17108 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
17109 {
17110         int error;
17111
17112         switch (infocmd) {
17113         case DDI_INFO_DEVT2DEVINFO:
17114                 *result = (void *)dtrace_devi;
17115                 error = DDI_SUCCESS;
17116                 break;
17117         case DDI_INFO_DEVT2INSTANCE:
17118                 *result = (void *)0;
17119                 error = DDI_SUCCESS;
17120                 break;
17121         default:
17122                 error = DDI_FAILURE;
17123         }
17124         return (error);
17125 }
17126 #endif
17127
17128 #if defined(sun)
17129 static struct cb_ops dtrace_cb_ops = {
17130         dtrace_open,            /* open */
17131         dtrace_close,           /* close */
17132         nulldev,                /* strategy */
17133         nulldev,                /* print */
17134         nodev,                  /* dump */
17135         nodev,                  /* read */
17136         nodev,                  /* write */
17137         dtrace_ioctl,           /* ioctl */
17138         nodev,                  /* devmap */
17139         nodev,                  /* mmap */
17140         nodev,                  /* segmap */
17141         nochpoll,               /* poll */
17142         ddi_prop_op,            /* cb_prop_op */
17143         0,                      /* streamtab  */
17144         D_NEW | D_MP            /* Driver compatibility flag */
17145 };
17146
17147 static struct dev_ops dtrace_ops = {
17148         DEVO_REV,               /* devo_rev */
17149         0,                      /* refcnt */
17150         dtrace_info,            /* get_dev_info */
17151         nulldev,                /* identify */
17152         nulldev,                /* probe */
17153         dtrace_attach,          /* attach */
17154         dtrace_detach,          /* detach */
17155         nodev,                  /* reset */
17156         &dtrace_cb_ops,         /* driver operations */
17157         NULL,                   /* bus operations */
17158         nodev                   /* dev power */
17159 };
17160
17161 static struct modldrv modldrv = {
17162         &mod_driverops,         /* module type (this is a pseudo driver) */
17163         "Dynamic Tracing",      /* name of module */
17164         &dtrace_ops,            /* driver ops */
17165 };
17166
17167 static struct modlinkage modlinkage = {
17168         MODREV_1,
17169         (void *)&modldrv,
17170         NULL
17171 };
17172
17173 int
17174 _init(void)
17175 {
17176         return (mod_install(&modlinkage));
17177 }
17178
17179 int
17180 _info(struct modinfo *modinfop)
17181 {
17182         return (mod_info(&modlinkage, modinfop));
17183 }
17184
17185 int
17186 _fini(void)
17187 {
17188         return (mod_remove(&modlinkage));
17189 }
17190 #else
17191
17192 static d_ioctl_t        dtrace_ioctl;
17193 static d_ioctl_t        dtrace_ioctl_helper;
17194 static void             dtrace_load(void *);
17195 static int              dtrace_unload(void);
17196 static struct cdev      *dtrace_dev;
17197 static struct cdev      *helper_dev;
17198
17199 void dtrace_invop_init(void);
17200 void dtrace_invop_uninit(void);
17201
17202 static struct cdevsw dtrace_cdevsw = {
17203         .d_version      = D_VERSION,
17204         .d_ioctl        = dtrace_ioctl,
17205         .d_open         = dtrace_open,
17206         .d_name         = "dtrace",
17207 };
17208
17209 static struct cdevsw helper_cdevsw = {
17210         .d_version      = D_VERSION,
17211         .d_ioctl        = dtrace_ioctl_helper,
17212         .d_name         = "helper",
17213 };
17214
17215 #include <dtrace_anon.c>
17216 #include <dtrace_ioctl.c>
17217 #include <dtrace_load.c>
17218 #include <dtrace_modevent.c>
17219 #include <dtrace_sysctl.c>
17220 #include <dtrace_unload.c>
17221 #include <dtrace_vtime.c>
17222 #include <dtrace_hacks.c>
17223 #include <dtrace_isa.c>
17224
17225 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
17226 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
17227 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
17228
17229 DEV_MODULE(dtrace, dtrace_modevent, NULL);
17230 MODULE_VERSION(dtrace, 1);
17231 MODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
17232 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
17233 #endif