]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c
MFC r256571:
[FreeBSD/stable/9.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 #if defined(sun)
223 static void             *dtrace_softstate;      /* softstate pointer */
224 #endif
225 static dtrace_hash_t    *dtrace_bymod;          /* probes hashed by module */
226 static dtrace_hash_t    *dtrace_byfunc;         /* probes hashed by function */
227 static dtrace_hash_t    *dtrace_byname;         /* probes hashed by name */
228 static dtrace_toxrange_t *dtrace_toxrange;      /* toxic range array */
229 static int              dtrace_toxranges;       /* number of toxic ranges */
230 static int              dtrace_toxranges_max;   /* size of toxic range array */
231 static dtrace_anon_t    dtrace_anon;            /* anonymous enabling */
232 static kmem_cache_t     *dtrace_state_cache;    /* cache for dynamic state */
233 static uint64_t         dtrace_vtime_references; /* number of vtimestamp refs */
234 static kthread_t        *dtrace_panicked;       /* panicking thread */
235 static dtrace_ecb_t     *dtrace_ecb_create_cache; /* cached created ECB */
236 static dtrace_genid_t   dtrace_probegen;        /* current probe generation */
237 static dtrace_helpers_t *dtrace_deferred_pid;   /* deferred helper list */
238 static dtrace_enabling_t *dtrace_retained;      /* list of retained enablings */
239 static dtrace_dynvar_t  dtrace_dynhash_sink;    /* end of dynamic hash chains */
240 #if !defined(sun)
241 static struct mtx       dtrace_unr_mtx;
242 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
243 int             dtrace_in_probe;        /* non-zero if executing a probe */
244 #if defined(__i386__) || defined(__amd64__)
245 uintptr_t       dtrace_in_probe_addr;   /* Address of invop when already in probe */
246 #endif
247 static eventhandler_tag dtrace_kld_load_tag;
248 static eventhandler_tag dtrace_kld_unload_try_tag;
249 #endif
250
251 /*
252  * DTrace Locking
253  * DTrace is protected by three (relatively coarse-grained) locks:
254  *
255  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
256  *     including enabling state, probes, ECBs, consumer state, helper state,
257  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
258  *     probe context is lock-free -- synchronization is handled via the
259  *     dtrace_sync() cross call mechanism.
260  *
261  * (2) dtrace_provider_lock is required when manipulating provider state, or
262  *     when provider state must be held constant.
263  *
264  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
265  *     when meta provider state must be held constant.
266  *
267  * The lock ordering between these three locks is dtrace_meta_lock before
268  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
269  * several places where dtrace_provider_lock is held by the framework as it
270  * calls into the providers -- which then call back into the framework,
271  * grabbing dtrace_lock.)
272  *
273  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
274  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
275  * role as a coarse-grained lock; it is acquired before both of these locks.
276  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
277  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
278  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
279  * acquired _between_ dtrace_provider_lock and dtrace_lock.
280  */
281 static kmutex_t         dtrace_lock;            /* probe state lock */
282 static kmutex_t         dtrace_provider_lock;   /* provider state lock */
283 static kmutex_t         dtrace_meta_lock;       /* meta-provider state lock */
284
285 #if !defined(sun)
286 /* XXX FreeBSD hacks. */
287 #define cr_suid         cr_svuid
288 #define cr_sgid         cr_svgid
289 #define ipaddr_t        in_addr_t
290 #define mod_modname     pathname
291 #define vuprintf        vprintf
292 #define ttoproc(_a)     ((_a)->td_proc)
293 #define crgetzoneid(_a) 0
294 #define NCPU            MAXCPU
295 #define SNOCD           0
296 #define CPU_ON_INTR(_a) 0
297
298 #define PRIV_EFFECTIVE          (1 << 0)
299 #define PRIV_DTRACE_KERNEL      (1 << 1)
300 #define PRIV_DTRACE_PROC        (1 << 2)
301 #define PRIV_DTRACE_USER        (1 << 3)
302 #define PRIV_PROC_OWNER         (1 << 4)
303 #define PRIV_PROC_ZONE          (1 << 5)
304 #define PRIV_ALL                ~0
305
306 SYSCTL_DECL(_debug_dtrace);
307 SYSCTL_DECL(_kern_dtrace);
308 #endif
309
310 #if defined(sun)
311 #define curcpu  CPU->cpu_id
312 #endif
313
314
315 /*
316  * DTrace Provider Variables
317  *
318  * These are the variables relating to DTrace as a provider (that is, the
319  * provider of the BEGIN, END, and ERROR probes).
320  */
321 static dtrace_pattr_t   dtrace_provider_attr = {
322 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
323 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
324 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
325 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
326 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
327 };
328
329 static void
330 dtrace_nullop(void)
331 {}
332
333 static dtrace_pops_t    dtrace_provider_ops = {
334         (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
335         (void (*)(void *, modctl_t *))dtrace_nullop,
336         (void (*)(void *, dtrace_id_t, void *))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         NULL,
341         NULL,
342         NULL,
343         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
344 };
345
346 static dtrace_id_t      dtrace_probeid_begin;   /* special BEGIN probe */
347 static dtrace_id_t      dtrace_probeid_end;     /* special END probe */
348 dtrace_id_t             dtrace_probeid_error;   /* special ERROR probe */
349
350 /*
351  * DTrace Helper Tracing Variables
352  */
353 uint32_t dtrace_helptrace_next = 0;
354 uint32_t dtrace_helptrace_nlocals;
355 char    *dtrace_helptrace_buffer;
356 int     dtrace_helptrace_bufsize = 512 * 1024;
357
358 #ifdef DEBUG
359 int     dtrace_helptrace_enabled = 1;
360 #else
361 int     dtrace_helptrace_enabled = 0;
362 #endif
363
364 /*
365  * DTrace Error Hashing
366  *
367  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
368  * table.  This is very useful for checking coverage of tests that are
369  * expected to induce DIF or DOF processing errors, and may be useful for
370  * debugging problems in the DIF code generator or in DOF generation .  The
371  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
372  */
373 #ifdef DEBUG
374 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
375 static const char *dtrace_errlast;
376 static kthread_t *dtrace_errthread;
377 static kmutex_t dtrace_errlock;
378 #endif
379
380 /*
381  * DTrace Macros and Constants
382  *
383  * These are various macros that are useful in various spots in the
384  * implementation, along with a few random constants that have no meaning
385  * outside of the implementation.  There is no real structure to this cpp
386  * mishmash -- but is there ever?
387  */
388 #define DTRACE_HASHSTR(hash, probe)     \
389         dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
390
391 #define DTRACE_HASHNEXT(hash, probe)    \
392         (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
393
394 #define DTRACE_HASHPREV(hash, probe)    \
395         (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
396
397 #define DTRACE_HASHEQ(hash, lhs, rhs)   \
398         (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
399             *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
400
401 #define DTRACE_AGGHASHSIZE_SLEW         17
402
403 #define DTRACE_V4MAPPED_OFFSET          (sizeof (uint32_t) * 3)
404
405 /*
406  * The key for a thread-local variable consists of the lower 61 bits of the
407  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
408  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
409  * equal to a variable identifier.  This is necessary (but not sufficient) to
410  * assure that global associative arrays never collide with thread-local
411  * variables.  To guarantee that they cannot collide, we must also define the
412  * order for keying dynamic variables.  That order is:
413  *
414  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
415  *
416  * Because the variable-key and the tls-key are in orthogonal spaces, there is
417  * no way for a global variable key signature to match a thread-local key
418  * signature.
419  */
420 #if defined(sun)
421 #define DTRACE_TLS_THRKEY(where) { \
422         uint_t intr = 0; \
423         uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
424         for (; actv; actv >>= 1) \
425                 intr++; \
426         ASSERT(intr < (1 << 3)); \
427         (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
428             (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
429 }
430 #else
431 #define DTRACE_TLS_THRKEY(where) { \
432         solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
433         uint_t intr = 0; \
434         uint_t actv = _c->cpu_intr_actv; \
435         for (; actv; actv >>= 1) \
436                 intr++; \
437         ASSERT(intr < (1 << 3)); \
438         (where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
439             (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
440 }
441 #endif
442
443 #define DT_BSWAP_8(x)   ((x) & 0xff)
444 #define DT_BSWAP_16(x)  ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
445 #define DT_BSWAP_32(x)  ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
446 #define DT_BSWAP_64(x)  ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
447
448 #define DT_MASK_LO 0x00000000FFFFFFFFULL
449
450 #define DTRACE_STORE(type, tomax, offset, what) \
451         *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
452
453 #ifndef __x86
454 #define DTRACE_ALIGNCHECK(addr, size, flags)                            \
455         if (addr & (size - 1)) {                                        \
456                 *flags |= CPU_DTRACE_BADALIGN;                          \
457                 cpu_core[curcpu].cpuc_dtrace_illval = addr;     \
458                 return (0);                                             \
459         }
460 #else
461 #define DTRACE_ALIGNCHECK(addr, size, flags)
462 #endif
463
464 /*
465  * Test whether a range of memory starting at testaddr of size testsz falls
466  * within the range of memory described by addr, sz.  We take care to avoid
467  * problems with overflow and underflow of the unsigned quantities, and
468  * disallow all negative sizes.  Ranges of size 0 are allowed.
469  */
470 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
471         ((testaddr) - (baseaddr) < (basesz) && \
472         (testaddr) + (testsz) - (baseaddr) <= (basesz) && \
473         (testaddr) + (testsz) >= (testaddr))
474
475 /*
476  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
477  * alloc_sz on the righthand side of the comparison in order to avoid overflow
478  * or underflow in the comparison with it.  This is simpler than the INRANGE
479  * check above, because we know that the dtms_scratch_ptr is valid in the
480  * range.  Allocations of size zero are allowed.
481  */
482 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
483         ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
484         (mstate)->dtms_scratch_ptr >= (alloc_sz))
485
486 #define DTRACE_LOADFUNC(bits)                                           \
487 /*CSTYLED*/                                                             \
488 uint##bits##_t                                                          \
489 dtrace_load##bits(uintptr_t addr)                                       \
490 {                                                                       \
491         size_t size = bits / NBBY;                                      \
492         /*CSTYLED*/                                                     \
493         uint##bits##_t rval;                                            \
494         int i;                                                          \
495         volatile uint16_t *flags = (volatile uint16_t *)                \
496             &cpu_core[curcpu].cpuc_dtrace_flags;                        \
497                                                                         \
498         DTRACE_ALIGNCHECK(addr, size, flags);                           \
499                                                                         \
500         for (i = 0; i < dtrace_toxranges; i++) {                        \
501                 if (addr >= dtrace_toxrange[i].dtt_limit)               \
502                         continue;                                       \
503                                                                         \
504                 if (addr + size <= dtrace_toxrange[i].dtt_base)         \
505                         continue;                                       \
506                                                                         \
507                 /*                                                      \
508                  * This address falls within a toxic region; return 0.  \
509                  */                                                     \
510                 *flags |= CPU_DTRACE_BADADDR;                           \
511                 cpu_core[curcpu].cpuc_dtrace_illval = addr;             \
512                 return (0);                                             \
513         }                                                               \
514                                                                         \
515         *flags |= CPU_DTRACE_NOFAULT;                                   \
516         /*CSTYLED*/                                                     \
517         rval = *((volatile uint##bits##_t *)addr);                      \
518         *flags &= ~CPU_DTRACE_NOFAULT;                                  \
519                                                                         \
520         return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);               \
521 }
522
523 #ifdef _LP64
524 #define dtrace_loadptr  dtrace_load64
525 #else
526 #define dtrace_loadptr  dtrace_load32
527 #endif
528
529 #define DTRACE_DYNHASH_FREE     0
530 #define DTRACE_DYNHASH_SINK     1
531 #define DTRACE_DYNHASH_VALID    2
532
533 #define DTRACE_MATCH_NEXT       0
534 #define DTRACE_MATCH_DONE       1
535 #define DTRACE_ANCHORED(probe)  ((probe)->dtpr_func[0] != '\0')
536 #define DTRACE_STATE_ALIGN      64
537
538 #define DTRACE_FLAGS2FLT(flags)                                         \
539         (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :           \
540         ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :                \
541         ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :            \
542         ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :                \
543         ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :                \
544         ((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :         \
545         ((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :         \
546         ((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :       \
547         ((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :         \
548         DTRACEFLT_UNKNOWN)
549
550 #define DTRACEACT_ISSTRING(act)                                         \
551         ((act)->dta_kind == DTRACEACT_DIFEXPR &&                        \
552         (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
553
554 /* Function prototype definitions: */
555 static size_t dtrace_strlen(const char *, size_t);
556 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
557 static void dtrace_enabling_provide(dtrace_provider_t *);
558 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
559 static void dtrace_enabling_matchall(void);
560 static void dtrace_enabling_reap(void);
561 static dtrace_state_t *dtrace_anon_grab(void);
562 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
563     dtrace_state_t *, uint64_t, uint64_t);
564 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
565 static void dtrace_buffer_drop(dtrace_buffer_t *);
566 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
567 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
568     dtrace_state_t *, dtrace_mstate_t *);
569 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
570     dtrace_optval_t);
571 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
572 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
573 uint16_t dtrace_load16(uintptr_t);
574 uint32_t dtrace_load32(uintptr_t);
575 uint64_t dtrace_load64(uintptr_t);
576 uint8_t dtrace_load8(uintptr_t);
577 void dtrace_dynvar_clean(dtrace_dstate_t *);
578 dtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
579     size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
580 uintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
581
582 /*
583  * DTrace Probe Context Functions
584  *
585  * These functions are called from probe context.  Because probe context is
586  * any context in which C may be called, arbitrarily locks may be held,
587  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
588  * As a result, functions called from probe context may only call other DTrace
589  * support functions -- they may not interact at all with the system at large.
590  * (Note that the ASSERT macro is made probe-context safe by redefining it in
591  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
592  * loads are to be performed from probe context, they _must_ be in terms of
593  * the safe dtrace_load*() variants.
594  *
595  * Some functions in this block are not actually called from probe context;
596  * for these functions, there will be a comment above the function reading
597  * "Note:  not called from probe context."
598  */
599 void
600 dtrace_panic(const char *format, ...)
601 {
602         va_list alist;
603
604         va_start(alist, format);
605         dtrace_vpanic(format, alist);
606         va_end(alist);
607 }
608
609 int
610 dtrace_assfail(const char *a, const char *f, int l)
611 {
612         dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
613
614         /*
615          * We just need something here that even the most clever compiler
616          * cannot optimize away.
617          */
618         return (a[(uintptr_t)f]);
619 }
620
621 /*
622  * Atomically increment a specified error counter from probe context.
623  */
624 static void
625 dtrace_error(uint32_t *counter)
626 {
627         /*
628          * Most counters stored to in probe context are per-CPU counters.
629          * However, there are some error conditions that are sufficiently
630          * arcane that they don't merit per-CPU storage.  If these counters
631          * are incremented concurrently on different CPUs, scalability will be
632          * adversely affected -- but we don't expect them to be white-hot in a
633          * correctly constructed enabling...
634          */
635         uint32_t oval, nval;
636
637         do {
638                 oval = *counter;
639
640                 if ((nval = oval + 1) == 0) {
641                         /*
642                          * If the counter would wrap, set it to 1 -- assuring
643                          * that the counter is never zero when we have seen
644                          * errors.  (The counter must be 32-bits because we
645                          * aren't guaranteed a 64-bit compare&swap operation.)
646                          * To save this code both the infamy of being fingered
647                          * by a priggish news story and the indignity of being
648                          * the target of a neo-puritan witch trial, we're
649                          * carefully avoiding any colorful description of the
650                          * likelihood of this condition -- but suffice it to
651                          * say that it is only slightly more likely than the
652                          * overflow of predicate cache IDs, as discussed in
653                          * dtrace_predicate_create().
654                          */
655                         nval = 1;
656                 }
657         } while (dtrace_cas32(counter, oval, nval) != oval);
658 }
659
660 /*
661  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
662  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
663  */
664 DTRACE_LOADFUNC(8)
665 DTRACE_LOADFUNC(16)
666 DTRACE_LOADFUNC(32)
667 DTRACE_LOADFUNC(64)
668
669 static int
670 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
671 {
672         if (dest < mstate->dtms_scratch_base)
673                 return (0);
674
675         if (dest + size < dest)
676                 return (0);
677
678         if (dest + size > mstate->dtms_scratch_ptr)
679                 return (0);
680
681         return (1);
682 }
683
684 static int
685 dtrace_canstore_statvar(uint64_t addr, size_t sz,
686     dtrace_statvar_t **svars, int nsvars)
687 {
688         int i;
689
690         for (i = 0; i < nsvars; i++) {
691                 dtrace_statvar_t *svar = svars[i];
692
693                 if (svar == NULL || svar->dtsv_size == 0)
694                         continue;
695
696                 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
697                         return (1);
698         }
699
700         return (0);
701 }
702
703 /*
704  * Check to see if the address is within a memory region to which a store may
705  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
706  * region.  The caller of dtrace_canstore() is responsible for performing any
707  * alignment checks that are needed before stores are actually executed.
708  */
709 static int
710 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
711     dtrace_vstate_t *vstate)
712 {
713         /*
714          * First, check to see if the address is in scratch space...
715          */
716         if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
717             mstate->dtms_scratch_size))
718                 return (1);
719
720         /*
721          * Now check to see if it's a dynamic variable.  This check will pick
722          * up both thread-local variables and any global dynamically-allocated
723          * variables.
724          */
725         if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
726             vstate->dtvs_dynvars.dtds_size)) {
727                 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
728                 uintptr_t base = (uintptr_t)dstate->dtds_base +
729                     (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
730                 uintptr_t chunkoffs;
731
732                 /*
733                  * Before we assume that we can store here, we need to make
734                  * sure that it isn't in our metadata -- storing to our
735                  * dynamic variable metadata would corrupt our state.  For
736                  * the range to not include any dynamic variable metadata,
737                  * it must:
738                  *
739                  *      (1) Start above the hash table that is at the base of
740                  *      the dynamic variable space
741                  *
742                  *      (2) Have a starting chunk offset that is beyond the
743                  *      dtrace_dynvar_t that is at the base of every chunk
744                  *
745                  *      (3) Not span a chunk boundary
746                  *
747                  */
748                 if (addr < base)
749                         return (0);
750
751                 chunkoffs = (addr - base) % dstate->dtds_chunksize;
752
753                 if (chunkoffs < sizeof (dtrace_dynvar_t))
754                         return (0);
755
756                 if (chunkoffs + sz > dstate->dtds_chunksize)
757                         return (0);
758
759                 return (1);
760         }
761
762         /*
763          * Finally, check the static local and global variables.  These checks
764          * take the longest, so we perform them last.
765          */
766         if (dtrace_canstore_statvar(addr, sz,
767             vstate->dtvs_locals, vstate->dtvs_nlocals))
768                 return (1);
769
770         if (dtrace_canstore_statvar(addr, sz,
771             vstate->dtvs_globals, vstate->dtvs_nglobals))
772                 return (1);
773
774         return (0);
775 }
776
777
778 /*
779  * Convenience routine to check to see if the address is within a memory
780  * region in which a load may be issued given the user's privilege level;
781  * if not, it sets the appropriate error flags and loads 'addr' into the
782  * illegal value slot.
783  *
784  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
785  * appropriate memory access protection.
786  */
787 static int
788 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
789     dtrace_vstate_t *vstate)
790 {
791         volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
792
793         /*
794          * If we hold the privilege to read from kernel memory, then
795          * everything is readable.
796          */
797         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
798                 return (1);
799
800         /*
801          * You can obviously read that which you can store.
802          */
803         if (dtrace_canstore(addr, sz, mstate, vstate))
804                 return (1);
805
806         /*
807          * We're allowed to read from our own string table.
808          */
809         if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
810             mstate->dtms_difo->dtdo_strlen))
811                 return (1);
812
813         DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
814         *illval = addr;
815         return (0);
816 }
817
818 /*
819  * Convenience routine to check to see if a given string is within a memory
820  * region in which a load may be issued given the user's privilege level;
821  * this exists so that we don't need to issue unnecessary dtrace_strlen()
822  * calls in the event that the user has all privileges.
823  */
824 static int
825 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
826     dtrace_vstate_t *vstate)
827 {
828         size_t strsz;
829
830         /*
831          * If we hold the privilege to read from kernel memory, then
832          * everything is readable.
833          */
834         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
835                 return (1);
836
837         strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
838         if (dtrace_canload(addr, strsz, mstate, vstate))
839                 return (1);
840
841         return (0);
842 }
843
844 /*
845  * Convenience routine to check to see if a given variable is within a memory
846  * region in which a load may be issued given the user's privilege level.
847  */
848 static int
849 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
850     dtrace_vstate_t *vstate)
851 {
852         size_t sz;
853         ASSERT(type->dtdt_flags & DIF_TF_BYREF);
854
855         /*
856          * If we hold the privilege to read from kernel memory, then
857          * everything is readable.
858          */
859         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
860                 return (1);
861
862         if (type->dtdt_kind == DIF_TYPE_STRING)
863                 sz = dtrace_strlen(src,
864                     vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
865         else
866                 sz = type->dtdt_size;
867
868         return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
869 }
870
871 /*
872  * Compare two strings using safe loads.
873  */
874 static int
875 dtrace_strncmp(char *s1, char *s2, size_t limit)
876 {
877         uint8_t c1, c2;
878         volatile uint16_t *flags;
879
880         if (s1 == s2 || limit == 0)
881                 return (0);
882
883         flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
884
885         do {
886                 if (s1 == NULL) {
887                         c1 = '\0';
888                 } else {
889                         c1 = dtrace_load8((uintptr_t)s1++);
890                 }
891
892                 if (s2 == NULL) {
893                         c2 = '\0';
894                 } else {
895                         c2 = dtrace_load8((uintptr_t)s2++);
896                 }
897
898                 if (c1 != c2)
899                         return (c1 - c2);
900         } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
901
902         return (0);
903 }
904
905 /*
906  * Compute strlen(s) for a string using safe memory accesses.  The additional
907  * len parameter is used to specify a maximum length to ensure completion.
908  */
909 static size_t
910 dtrace_strlen(const char *s, size_t lim)
911 {
912         uint_t len;
913
914         for (len = 0; len != lim; len++) {
915                 if (dtrace_load8((uintptr_t)s++) == '\0')
916                         break;
917         }
918
919         return (len);
920 }
921
922 /*
923  * Check if an address falls within a toxic region.
924  */
925 static int
926 dtrace_istoxic(uintptr_t kaddr, size_t size)
927 {
928         uintptr_t taddr, tsize;
929         int i;
930
931         for (i = 0; i < dtrace_toxranges; i++) {
932                 taddr = dtrace_toxrange[i].dtt_base;
933                 tsize = dtrace_toxrange[i].dtt_limit - taddr;
934
935                 if (kaddr - taddr < tsize) {
936                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
937                         cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
938                         return (1);
939                 }
940
941                 if (taddr - kaddr < size) {
942                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
943                         cpu_core[curcpu].cpuc_dtrace_illval = taddr;
944                         return (1);
945                 }
946         }
947
948         return (0);
949 }
950
951 /*
952  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
953  * memory specified by the DIF program.  The dst is assumed to be safe memory
954  * that we can store to directly because it is managed by DTrace.  As with
955  * standard bcopy, overlapping copies are handled properly.
956  */
957 static void
958 dtrace_bcopy(const void *src, void *dst, size_t len)
959 {
960         if (len != 0) {
961                 uint8_t *s1 = dst;
962                 const uint8_t *s2 = src;
963
964                 if (s1 <= s2) {
965                         do {
966                                 *s1++ = dtrace_load8((uintptr_t)s2++);
967                         } while (--len != 0);
968                 } else {
969                         s2 += len;
970                         s1 += len;
971
972                         do {
973                                 *--s1 = dtrace_load8((uintptr_t)--s2);
974                         } while (--len != 0);
975                 }
976         }
977 }
978
979 /*
980  * Copy src to dst using safe memory accesses, up to either the specified
981  * length, or the point that a nul byte is encountered.  The src is assumed to
982  * be unsafe memory specified by the DIF program.  The dst is assumed to be
983  * safe memory that we can store to directly because it is managed by DTrace.
984  * Unlike dtrace_bcopy(), overlapping regions are not handled.
985  */
986 static void
987 dtrace_strcpy(const void *src, void *dst, size_t len)
988 {
989         if (len != 0) {
990                 uint8_t *s1 = dst, c;
991                 const uint8_t *s2 = src;
992
993                 do {
994                         *s1++ = c = dtrace_load8((uintptr_t)s2++);
995                 } while (--len != 0 && c != '\0');
996         }
997 }
998
999 /*
1000  * Copy src to dst, deriving the size and type from the specified (BYREF)
1001  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1002  * program.  The dst is assumed to be DTrace variable memory that is of the
1003  * specified type; we assume that we can store to directly.
1004  */
1005 static void
1006 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1007 {
1008         ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1009
1010         if (type->dtdt_kind == DIF_TYPE_STRING) {
1011                 dtrace_strcpy(src, dst, type->dtdt_size);
1012         } else {
1013                 dtrace_bcopy(src, dst, type->dtdt_size);
1014         }
1015 }
1016
1017 /*
1018  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1019  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1020  * safe memory that we can access directly because it is managed by DTrace.
1021  */
1022 static int
1023 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1024 {
1025         volatile uint16_t *flags;
1026
1027         flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1028
1029         if (s1 == s2)
1030                 return (0);
1031
1032         if (s1 == NULL || s2 == NULL)
1033                 return (1);
1034
1035         if (s1 != s2 && len != 0) {
1036                 const uint8_t *ps1 = s1;
1037                 const uint8_t *ps2 = s2;
1038
1039                 do {
1040                         if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1041                                 return (1);
1042                 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1043         }
1044         return (0);
1045 }
1046
1047 /*
1048  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1049  * is for safe DTrace-managed memory only.
1050  */
1051 static void
1052 dtrace_bzero(void *dst, size_t len)
1053 {
1054         uchar_t *cp;
1055
1056         for (cp = dst; len != 0; len--)
1057                 *cp++ = 0;
1058 }
1059
1060 static void
1061 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1062 {
1063         uint64_t result[2];
1064
1065         result[0] = addend1[0] + addend2[0];
1066         result[1] = addend1[1] + addend2[1] +
1067             (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1068
1069         sum[0] = result[0];
1070         sum[1] = result[1];
1071 }
1072
1073 /*
1074  * Shift the 128-bit value in a by b. If b is positive, shift left.
1075  * If b is negative, shift right.
1076  */
1077 static void
1078 dtrace_shift_128(uint64_t *a, int b)
1079 {
1080         uint64_t mask;
1081
1082         if (b == 0)
1083                 return;
1084
1085         if (b < 0) {
1086                 b = -b;
1087                 if (b >= 64) {
1088                         a[0] = a[1] >> (b - 64);
1089                         a[1] = 0;
1090                 } else {
1091                         a[0] >>= b;
1092                         mask = 1LL << (64 - b);
1093                         mask -= 1;
1094                         a[0] |= ((a[1] & mask) << (64 - b));
1095                         a[1] >>= b;
1096                 }
1097         } else {
1098                 if (b >= 64) {
1099                         a[1] = a[0] << (b - 64);
1100                         a[0] = 0;
1101                 } else {
1102                         a[1] <<= b;
1103                         mask = a[0] >> (64 - b);
1104                         a[1] |= mask;
1105                         a[0] <<= b;
1106                 }
1107         }
1108 }
1109
1110 /*
1111  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1112  * use native multiplication on those, and then re-combine into the
1113  * resulting 128-bit value.
1114  *
1115  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1116  *     hi1 * hi2 << 64 +
1117  *     hi1 * lo2 << 32 +
1118  *     hi2 * lo1 << 32 +
1119  *     lo1 * lo2
1120  */
1121 static void
1122 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1123 {
1124         uint64_t hi1, hi2, lo1, lo2;
1125         uint64_t tmp[2];
1126
1127         hi1 = factor1 >> 32;
1128         hi2 = factor2 >> 32;
1129
1130         lo1 = factor1 & DT_MASK_LO;
1131         lo2 = factor2 & DT_MASK_LO;
1132
1133         product[0] = lo1 * lo2;
1134         product[1] = hi1 * hi2;
1135
1136         tmp[0] = hi1 * lo2;
1137         tmp[1] = 0;
1138         dtrace_shift_128(tmp, 32);
1139         dtrace_add_128(product, tmp, product);
1140
1141         tmp[0] = hi2 * lo1;
1142         tmp[1] = 0;
1143         dtrace_shift_128(tmp, 32);
1144         dtrace_add_128(product, tmp, product);
1145 }
1146
1147 /*
1148  * This privilege check should be used by actions and subroutines to
1149  * verify that the user credentials of the process that enabled the
1150  * invoking ECB match the target credentials
1151  */
1152 static int
1153 dtrace_priv_proc_common_user(dtrace_state_t *state)
1154 {
1155         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1156
1157         /*
1158          * We should always have a non-NULL state cred here, since if cred
1159          * is null (anonymous tracing), we fast-path bypass this routine.
1160          */
1161         ASSERT(s_cr != NULL);
1162
1163         if ((cr = CRED()) != NULL &&
1164             s_cr->cr_uid == cr->cr_uid &&
1165             s_cr->cr_uid == cr->cr_ruid &&
1166             s_cr->cr_uid == cr->cr_suid &&
1167             s_cr->cr_gid == cr->cr_gid &&
1168             s_cr->cr_gid == cr->cr_rgid &&
1169             s_cr->cr_gid == cr->cr_sgid)
1170                 return (1);
1171
1172         return (0);
1173 }
1174
1175 /*
1176  * This privilege check should be used by actions and subroutines to
1177  * verify that the zone of the process that enabled the invoking ECB
1178  * matches the target credentials
1179  */
1180 static int
1181 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1182 {
1183 #if defined(sun)
1184         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1185
1186         /*
1187          * We should always have a non-NULL state cred here, since if cred
1188          * is null (anonymous tracing), we fast-path bypass this routine.
1189          */
1190         ASSERT(s_cr != NULL);
1191
1192         if ((cr = CRED()) != NULL &&
1193             s_cr->cr_zone == cr->cr_zone)
1194                 return (1);
1195
1196         return (0);
1197 #else
1198         return (1);
1199 #endif
1200 }
1201
1202 /*
1203  * This privilege check should be used by actions and subroutines to
1204  * verify that the process has not setuid or changed credentials.
1205  */
1206 static int
1207 dtrace_priv_proc_common_nocd(void)
1208 {
1209         proc_t *proc;
1210
1211         if ((proc = ttoproc(curthread)) != NULL &&
1212             !(proc->p_flag & SNOCD))
1213                 return (1);
1214
1215         return (0);
1216 }
1217
1218 static int
1219 dtrace_priv_proc_destructive(dtrace_state_t *state)
1220 {
1221         int action = state->dts_cred.dcr_action;
1222
1223         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1224             dtrace_priv_proc_common_zone(state) == 0)
1225                 goto bad;
1226
1227         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1228             dtrace_priv_proc_common_user(state) == 0)
1229                 goto bad;
1230
1231         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1232             dtrace_priv_proc_common_nocd() == 0)
1233                 goto bad;
1234
1235         return (1);
1236
1237 bad:
1238         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1239
1240         return (0);
1241 }
1242
1243 static int
1244 dtrace_priv_proc_control(dtrace_state_t *state)
1245 {
1246         if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1247                 return (1);
1248
1249         if (dtrace_priv_proc_common_zone(state) &&
1250             dtrace_priv_proc_common_user(state) &&
1251             dtrace_priv_proc_common_nocd())
1252                 return (1);
1253
1254         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1255
1256         return (0);
1257 }
1258
1259 static int
1260 dtrace_priv_proc(dtrace_state_t *state)
1261 {
1262         if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1263                 return (1);
1264
1265         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1266
1267         return (0);
1268 }
1269
1270 static int
1271 dtrace_priv_kernel(dtrace_state_t *state)
1272 {
1273         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1274                 return (1);
1275
1276         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1277
1278         return (0);
1279 }
1280
1281 static int
1282 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1283 {
1284         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1285                 return (1);
1286
1287         cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1288
1289         return (0);
1290 }
1291
1292 /*
1293  * Note:  not called from probe context.  This function is called
1294  * asynchronously (and at a regular interval) from outside of probe context to
1295  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1296  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1297  */
1298 void
1299 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1300 {
1301         dtrace_dynvar_t *dirty;
1302         dtrace_dstate_percpu_t *dcpu;
1303         int i, work = 0;
1304
1305         for (i = 0; i < NCPU; i++) {
1306                 dcpu = &dstate->dtds_percpu[i];
1307
1308                 ASSERT(dcpu->dtdsc_rinsing == NULL);
1309
1310                 /*
1311                  * If the dirty list is NULL, there is no dirty work to do.
1312                  */
1313                 if (dcpu->dtdsc_dirty == NULL)
1314                         continue;
1315
1316                 /*
1317                  * If the clean list is non-NULL, then we're not going to do
1318                  * any work for this CPU -- it means that there has not been
1319                  * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1320                  * since the last time we cleaned house.
1321                  */
1322                 if (dcpu->dtdsc_clean != NULL)
1323                         continue;
1324
1325                 work = 1;
1326
1327                 /*
1328                  * Atomically move the dirty list aside.
1329                  */
1330                 do {
1331                         dirty = dcpu->dtdsc_dirty;
1332
1333                         /*
1334                          * Before we zap the dirty list, set the rinsing list.
1335                          * (This allows for a potential assertion in
1336                          * dtrace_dynvar():  if a free dynamic variable appears
1337                          * on a hash chain, either the dirty list or the
1338                          * rinsing list for some CPU must be non-NULL.)
1339                          */
1340                         dcpu->dtdsc_rinsing = dirty;
1341                         dtrace_membar_producer();
1342                 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1343                     dirty, NULL) != dirty);
1344         }
1345
1346         if (!work) {
1347                 /*
1348                  * We have no work to do; we can simply return.
1349                  */
1350                 return;
1351         }
1352
1353         dtrace_sync();
1354
1355         for (i = 0; i < NCPU; i++) {
1356                 dcpu = &dstate->dtds_percpu[i];
1357
1358                 if (dcpu->dtdsc_rinsing == NULL)
1359                         continue;
1360
1361                 /*
1362                  * We are now guaranteed that no hash chain contains a pointer
1363                  * into this dirty list; we can make it clean.
1364                  */
1365                 ASSERT(dcpu->dtdsc_clean == NULL);
1366                 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1367                 dcpu->dtdsc_rinsing = NULL;
1368         }
1369
1370         /*
1371          * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1372          * sure that all CPUs have seen all of the dtdsc_clean pointers.
1373          * This prevents a race whereby a CPU incorrectly decides that
1374          * the state should be something other than DTRACE_DSTATE_CLEAN
1375          * after dtrace_dynvar_clean() has completed.
1376          */
1377         dtrace_sync();
1378
1379         dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1380 }
1381
1382 /*
1383  * Depending on the value of the op parameter, this function looks-up,
1384  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1385  * allocation is requested, this function will return a pointer to a
1386  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1387  * variable can be allocated.  If NULL is returned, the appropriate counter
1388  * will be incremented.
1389  */
1390 dtrace_dynvar_t *
1391 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1392     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1393     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1394 {
1395         uint64_t hashval = DTRACE_DYNHASH_VALID;
1396         dtrace_dynhash_t *hash = dstate->dtds_hash;
1397         dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1398         processorid_t me = curcpu, cpu = me;
1399         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1400         size_t bucket, ksize;
1401         size_t chunksize = dstate->dtds_chunksize;
1402         uintptr_t kdata, lock, nstate;
1403         uint_t i;
1404
1405         ASSERT(nkeys != 0);
1406
1407         /*
1408          * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1409          * algorithm.  For the by-value portions, we perform the algorithm in
1410          * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1411          * bit, and seems to have only a minute effect on distribution.  For
1412          * the by-reference data, we perform "One-at-a-time" iterating (safely)
1413          * over each referenced byte.  It's painful to do this, but it's much
1414          * better than pathological hash distribution.  The efficacy of the
1415          * hashing algorithm (and a comparison with other algorithms) may be
1416          * found by running the ::dtrace_dynstat MDB dcmd.
1417          */
1418         for (i = 0; i < nkeys; i++) {
1419                 if (key[i].dttk_size == 0) {
1420                         uint64_t val = key[i].dttk_value;
1421
1422                         hashval += (val >> 48) & 0xffff;
1423                         hashval += (hashval << 10);
1424                         hashval ^= (hashval >> 6);
1425
1426                         hashval += (val >> 32) & 0xffff;
1427                         hashval += (hashval << 10);
1428                         hashval ^= (hashval >> 6);
1429
1430                         hashval += (val >> 16) & 0xffff;
1431                         hashval += (hashval << 10);
1432                         hashval ^= (hashval >> 6);
1433
1434                         hashval += val & 0xffff;
1435                         hashval += (hashval << 10);
1436                         hashval ^= (hashval >> 6);
1437                 } else {
1438                         /*
1439                          * This is incredibly painful, but it beats the hell
1440                          * out of the alternative.
1441                          */
1442                         uint64_t j, size = key[i].dttk_size;
1443                         uintptr_t base = (uintptr_t)key[i].dttk_value;
1444
1445                         if (!dtrace_canload(base, size, mstate, vstate))
1446                                 break;
1447
1448                         for (j = 0; j < size; j++) {
1449                                 hashval += dtrace_load8(base + j);
1450                                 hashval += (hashval << 10);
1451                                 hashval ^= (hashval >> 6);
1452                         }
1453                 }
1454         }
1455
1456         if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1457                 return (NULL);
1458
1459         hashval += (hashval << 3);
1460         hashval ^= (hashval >> 11);
1461         hashval += (hashval << 15);
1462
1463         /*
1464          * There is a remote chance (ideally, 1 in 2^31) that our hashval
1465          * comes out to be one of our two sentinel hash values.  If this
1466          * actually happens, we set the hashval to be a value known to be a
1467          * non-sentinel value.
1468          */
1469         if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1470                 hashval = DTRACE_DYNHASH_VALID;
1471
1472         /*
1473          * Yes, it's painful to do a divide here.  If the cycle count becomes
1474          * important here, tricks can be pulled to reduce it.  (However, it's
1475          * critical that hash collisions be kept to an absolute minimum;
1476          * they're much more painful than a divide.)  It's better to have a
1477          * solution that generates few collisions and still keeps things
1478          * relatively simple.
1479          */
1480         bucket = hashval % dstate->dtds_hashsize;
1481
1482         if (op == DTRACE_DYNVAR_DEALLOC) {
1483                 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1484
1485                 for (;;) {
1486                         while ((lock = *lockp) & 1)
1487                                 continue;
1488
1489                         if (dtrace_casptr((volatile void *)lockp,
1490                             (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1491                                 break;
1492                 }
1493
1494                 dtrace_membar_producer();
1495         }
1496
1497 top:
1498         prev = NULL;
1499         lock = hash[bucket].dtdh_lock;
1500
1501         dtrace_membar_consumer();
1502
1503         start = hash[bucket].dtdh_chain;
1504         ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1505             start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1506             op != DTRACE_DYNVAR_DEALLOC));
1507
1508         for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1509                 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1510                 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1511
1512                 if (dvar->dtdv_hashval != hashval) {
1513                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1514                                 /*
1515                                  * We've reached the sink, and therefore the
1516                                  * end of the hash chain; we can kick out of
1517                                  * the loop knowing that we have seen a valid
1518                                  * snapshot of state.
1519                                  */
1520                                 ASSERT(dvar->dtdv_next == NULL);
1521                                 ASSERT(dvar == &dtrace_dynhash_sink);
1522                                 break;
1523                         }
1524
1525                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1526                                 /*
1527                                  * We've gone off the rails:  somewhere along
1528                                  * the line, one of the members of this hash
1529                                  * chain was deleted.  Note that we could also
1530                                  * detect this by simply letting this loop run
1531                                  * to completion, as we would eventually hit
1532                                  * the end of the dirty list.  However, we
1533                                  * want to avoid running the length of the
1534                                  * dirty list unnecessarily (it might be quite
1535                                  * long), so we catch this as early as
1536                                  * possible by detecting the hash marker.  In
1537                                  * this case, we simply set dvar to NULL and
1538                                  * break; the conditional after the loop will
1539                                  * send us back to top.
1540                                  */
1541                                 dvar = NULL;
1542                                 break;
1543                         }
1544
1545                         goto next;
1546                 }
1547
1548                 if (dtuple->dtt_nkeys != nkeys)
1549                         goto next;
1550
1551                 for (i = 0; i < nkeys; i++, dkey++) {
1552                         if (dkey->dttk_size != key[i].dttk_size)
1553                                 goto next; /* size or type mismatch */
1554
1555                         if (dkey->dttk_size != 0) {
1556                                 if (dtrace_bcmp(
1557                                     (void *)(uintptr_t)key[i].dttk_value,
1558                                     (void *)(uintptr_t)dkey->dttk_value,
1559                                     dkey->dttk_size))
1560                                         goto next;
1561                         } else {
1562                                 if (dkey->dttk_value != key[i].dttk_value)
1563                                         goto next;
1564                         }
1565                 }
1566
1567                 if (op != DTRACE_DYNVAR_DEALLOC)
1568                         return (dvar);
1569
1570                 ASSERT(dvar->dtdv_next == NULL ||
1571                     dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1572
1573                 if (prev != NULL) {
1574                         ASSERT(hash[bucket].dtdh_chain != dvar);
1575                         ASSERT(start != dvar);
1576                         ASSERT(prev->dtdv_next == dvar);
1577                         prev->dtdv_next = dvar->dtdv_next;
1578                 } else {
1579                         if (dtrace_casptr(&hash[bucket].dtdh_chain,
1580                             start, dvar->dtdv_next) != start) {
1581                                 /*
1582                                  * We have failed to atomically swing the
1583                                  * hash table head pointer, presumably because
1584                                  * of a conflicting allocation on another CPU.
1585                                  * We need to reread the hash chain and try
1586                                  * again.
1587                                  */
1588                                 goto top;
1589                         }
1590                 }
1591
1592                 dtrace_membar_producer();
1593
1594                 /*
1595                  * Now set the hash value to indicate that it's free.
1596                  */
1597                 ASSERT(hash[bucket].dtdh_chain != dvar);
1598                 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1599
1600                 dtrace_membar_producer();
1601
1602                 /*
1603                  * Set the next pointer to point at the dirty list, and
1604                  * atomically swing the dirty pointer to the newly freed dvar.
1605                  */
1606                 do {
1607                         next = dcpu->dtdsc_dirty;
1608                         dvar->dtdv_next = next;
1609                 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1610
1611                 /*
1612                  * Finally, unlock this hash bucket.
1613                  */
1614                 ASSERT(hash[bucket].dtdh_lock == lock);
1615                 ASSERT(lock & 1);
1616                 hash[bucket].dtdh_lock++;
1617
1618                 return (NULL);
1619 next:
1620                 prev = dvar;
1621                 continue;
1622         }
1623
1624         if (dvar == NULL) {
1625                 /*
1626                  * If dvar is NULL, it is because we went off the rails:
1627                  * one of the elements that we traversed in the hash chain
1628                  * was deleted while we were traversing it.  In this case,
1629                  * we assert that we aren't doing a dealloc (deallocs lock
1630                  * the hash bucket to prevent themselves from racing with
1631                  * one another), and retry the hash chain traversal.
1632                  */
1633                 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1634                 goto top;
1635         }
1636
1637         if (op != DTRACE_DYNVAR_ALLOC) {
1638                 /*
1639                  * If we are not to allocate a new variable, we want to
1640                  * return NULL now.  Before we return, check that the value
1641                  * of the lock word hasn't changed.  If it has, we may have
1642                  * seen an inconsistent snapshot.
1643                  */
1644                 if (op == DTRACE_DYNVAR_NOALLOC) {
1645                         if (hash[bucket].dtdh_lock != lock)
1646                                 goto top;
1647                 } else {
1648                         ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1649                         ASSERT(hash[bucket].dtdh_lock == lock);
1650                         ASSERT(lock & 1);
1651                         hash[bucket].dtdh_lock++;
1652                 }
1653
1654                 return (NULL);
1655         }
1656
1657         /*
1658          * We need to allocate a new dynamic variable.  The size we need is the
1659          * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1660          * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1661          * the size of any referred-to data (dsize).  We then round the final
1662          * size up to the chunksize for allocation.
1663          */
1664         for (ksize = 0, i = 0; i < nkeys; i++)
1665                 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1666
1667         /*
1668          * This should be pretty much impossible, but could happen if, say,
1669          * strange DIF specified the tuple.  Ideally, this should be an
1670          * assertion and not an error condition -- but that requires that the
1671          * chunksize calculation in dtrace_difo_chunksize() be absolutely
1672          * bullet-proof.  (That is, it must not be able to be fooled by
1673          * malicious DIF.)  Given the lack of backwards branches in DIF,
1674          * solving this would presumably not amount to solving the Halting
1675          * Problem -- but it still seems awfully hard.
1676          */
1677         if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1678             ksize + dsize > chunksize) {
1679                 dcpu->dtdsc_drops++;
1680                 return (NULL);
1681         }
1682
1683         nstate = DTRACE_DSTATE_EMPTY;
1684
1685         do {
1686 retry:
1687                 free = dcpu->dtdsc_free;
1688
1689                 if (free == NULL) {
1690                         dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1691                         void *rval;
1692
1693                         if (clean == NULL) {
1694                                 /*
1695                                  * We're out of dynamic variable space on
1696                                  * this CPU.  Unless we have tried all CPUs,
1697                                  * we'll try to allocate from a different
1698                                  * CPU.
1699                                  */
1700                                 switch (dstate->dtds_state) {
1701                                 case DTRACE_DSTATE_CLEAN: {
1702                                         void *sp = &dstate->dtds_state;
1703
1704                                         if (++cpu >= NCPU)
1705                                                 cpu = 0;
1706
1707                                         if (dcpu->dtdsc_dirty != NULL &&
1708                                             nstate == DTRACE_DSTATE_EMPTY)
1709                                                 nstate = DTRACE_DSTATE_DIRTY;
1710
1711                                         if (dcpu->dtdsc_rinsing != NULL)
1712                                                 nstate = DTRACE_DSTATE_RINSING;
1713
1714                                         dcpu = &dstate->dtds_percpu[cpu];
1715
1716                                         if (cpu != me)
1717                                                 goto retry;
1718
1719                                         (void) dtrace_cas32(sp,
1720                                             DTRACE_DSTATE_CLEAN, nstate);
1721
1722                                         /*
1723                                          * To increment the correct bean
1724                                          * counter, take another lap.
1725                                          */
1726                                         goto retry;
1727                                 }
1728
1729                                 case DTRACE_DSTATE_DIRTY:
1730                                         dcpu->dtdsc_dirty_drops++;
1731                                         break;
1732
1733                                 case DTRACE_DSTATE_RINSING:
1734                                         dcpu->dtdsc_rinsing_drops++;
1735                                         break;
1736
1737                                 case DTRACE_DSTATE_EMPTY:
1738                                         dcpu->dtdsc_drops++;
1739                                         break;
1740                                 }
1741
1742                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1743                                 return (NULL);
1744                         }
1745
1746                         /*
1747                          * The clean list appears to be non-empty.  We want to
1748                          * move the clean list to the free list; we start by
1749                          * moving the clean pointer aside.
1750                          */
1751                         if (dtrace_casptr(&dcpu->dtdsc_clean,
1752                             clean, NULL) != clean) {
1753                                 /*
1754                                  * We are in one of two situations:
1755                                  *
1756                                  *  (a) The clean list was switched to the
1757                                  *      free list by another CPU.
1758                                  *
1759                                  *  (b) The clean list was added to by the
1760                                  *      cleansing cyclic.
1761                                  *
1762                                  * In either of these situations, we can
1763                                  * just reattempt the free list allocation.
1764                                  */
1765                                 goto retry;
1766                         }
1767
1768                         ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1769
1770                         /*
1771                          * Now we'll move the clean list to the free list.
1772                          * It's impossible for this to fail:  the only way
1773                          * the free list can be updated is through this
1774                          * code path, and only one CPU can own the clean list.
1775                          * Thus, it would only be possible for this to fail if
1776                          * this code were racing with dtrace_dynvar_clean().
1777                          * (That is, if dtrace_dynvar_clean() updated the clean
1778                          * list, and we ended up racing to update the free
1779                          * list.)  This race is prevented by the dtrace_sync()
1780                          * in dtrace_dynvar_clean() -- which flushes the
1781                          * owners of the clean lists out before resetting
1782                          * the clean lists.
1783                          */
1784                         rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1785                         ASSERT(rval == NULL);
1786                         goto retry;
1787                 }
1788
1789                 dvar = free;
1790                 new_free = dvar->dtdv_next;
1791         } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1792
1793         /*
1794          * We have now allocated a new chunk.  We copy the tuple keys into the
1795          * tuple array and copy any referenced key data into the data space
1796          * following the tuple array.  As we do this, we relocate dttk_value
1797          * in the final tuple to point to the key data address in the chunk.
1798          */
1799         kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1800         dvar->dtdv_data = (void *)(kdata + ksize);
1801         dvar->dtdv_tuple.dtt_nkeys = nkeys;
1802
1803         for (i = 0; i < nkeys; i++) {
1804                 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1805                 size_t kesize = key[i].dttk_size;
1806
1807                 if (kesize != 0) {
1808                         dtrace_bcopy(
1809                             (const void *)(uintptr_t)key[i].dttk_value,
1810                             (void *)kdata, kesize);
1811                         dkey->dttk_value = kdata;
1812                         kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1813                 } else {
1814                         dkey->dttk_value = key[i].dttk_value;
1815                 }
1816
1817                 dkey->dttk_size = kesize;
1818         }
1819
1820         ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1821         dvar->dtdv_hashval = hashval;
1822         dvar->dtdv_next = start;
1823
1824         if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1825                 return (dvar);
1826
1827         /*
1828          * The cas has failed.  Either another CPU is adding an element to
1829          * this hash chain, or another CPU is deleting an element from this
1830          * hash chain.  The simplest way to deal with both of these cases
1831          * (though not necessarily the most efficient) is to free our
1832          * allocated block and tail-call ourselves.  Note that the free is
1833          * to the dirty list and _not_ to the free list.  This is to prevent
1834          * races with allocators, above.
1835          */
1836         dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1837
1838         dtrace_membar_producer();
1839
1840         do {
1841                 free = dcpu->dtdsc_dirty;
1842                 dvar->dtdv_next = free;
1843         } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1844
1845         return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1846 }
1847
1848 /*ARGSUSED*/
1849 static void
1850 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1851 {
1852         if ((int64_t)nval < (int64_t)*oval)
1853                 *oval = nval;
1854 }
1855
1856 /*ARGSUSED*/
1857 static void
1858 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1859 {
1860         if ((int64_t)nval > (int64_t)*oval)
1861                 *oval = nval;
1862 }
1863
1864 static void
1865 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1866 {
1867         int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1868         int64_t val = (int64_t)nval;
1869
1870         if (val < 0) {
1871                 for (i = 0; i < zero; i++) {
1872                         if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1873                                 quanta[i] += incr;
1874                                 return;
1875                         }
1876                 }
1877         } else {
1878                 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1879                         if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1880                                 quanta[i - 1] += incr;
1881                                 return;
1882                         }
1883                 }
1884
1885                 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1886                 return;
1887         }
1888
1889         ASSERT(0);
1890 }
1891
1892 static void
1893 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1894 {
1895         uint64_t arg = *lquanta++;
1896         int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1897         uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1898         uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1899         int32_t val = (int32_t)nval, level;
1900
1901         ASSERT(step != 0);
1902         ASSERT(levels != 0);
1903
1904         if (val < base) {
1905                 /*
1906                  * This is an underflow.
1907                  */
1908                 lquanta[0] += incr;
1909                 return;
1910         }
1911
1912         level = (val - base) / step;
1913
1914         if (level < levels) {
1915                 lquanta[level + 1] += incr;
1916                 return;
1917         }
1918
1919         /*
1920          * This is an overflow.
1921          */
1922         lquanta[levels + 1] += incr;
1923 }
1924
1925 static int
1926 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
1927     uint16_t high, uint16_t nsteps, int64_t value)
1928 {
1929         int64_t this = 1, last, next;
1930         int base = 1, order;
1931
1932         ASSERT(factor <= nsteps);
1933         ASSERT(nsteps % factor == 0);
1934
1935         for (order = 0; order < low; order++)
1936                 this *= factor;
1937
1938         /*
1939          * If our value is less than our factor taken to the power of the
1940          * low order of magnitude, it goes into the zeroth bucket.
1941          */
1942         if (value < (last = this))
1943                 return (0);
1944
1945         for (this *= factor; order <= high; order++) {
1946                 int nbuckets = this > nsteps ? nsteps : this;
1947
1948                 if ((next = this * factor) < this) {
1949                         /*
1950                          * We should not generally get log/linear quantizations
1951                          * with a high magnitude that allows 64-bits to
1952                          * overflow, but we nonetheless protect against this
1953                          * by explicitly checking for overflow, and clamping
1954                          * our value accordingly.
1955                          */
1956                         value = this - 1;
1957                 }
1958
1959                 if (value < this) {
1960                         /*
1961                          * If our value lies within this order of magnitude,
1962                          * determine its position by taking the offset within
1963                          * the order of magnitude, dividing by the bucket
1964                          * width, and adding to our (accumulated) base.
1965                          */
1966                         return (base + (value - last) / (this / nbuckets));
1967                 }
1968
1969                 base += nbuckets - (nbuckets / factor);
1970                 last = this;
1971                 this = next;
1972         }
1973
1974         /*
1975          * Our value is greater than or equal to our factor taken to the
1976          * power of one plus the high magnitude -- return the top bucket.
1977          */
1978         return (base);
1979 }
1980
1981 static void
1982 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
1983 {
1984         uint64_t arg = *llquanta++;
1985         uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
1986         uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
1987         uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
1988         uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
1989
1990         llquanta[dtrace_aggregate_llquantize_bucket(factor,
1991             low, high, nsteps, nval)] += incr;
1992 }
1993
1994 /*ARGSUSED*/
1995 static void
1996 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1997 {
1998         data[0]++;
1999         data[1] += nval;
2000 }
2001
2002 /*ARGSUSED*/
2003 static void
2004 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2005 {
2006         int64_t snval = (int64_t)nval;
2007         uint64_t tmp[2];
2008
2009         data[0]++;
2010         data[1] += nval;
2011
2012         /*
2013          * What we want to say here is:
2014          *
2015          * data[2] += nval * nval;
2016          *
2017          * But given that nval is 64-bit, we could easily overflow, so
2018          * we do this as 128-bit arithmetic.
2019          */
2020         if (snval < 0)
2021                 snval = -snval;
2022
2023         dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2024         dtrace_add_128(data + 2, tmp, data + 2);
2025 }
2026
2027 /*ARGSUSED*/
2028 static void
2029 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2030 {
2031         *oval = *oval + 1;
2032 }
2033
2034 /*ARGSUSED*/
2035 static void
2036 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2037 {
2038         *oval += nval;
2039 }
2040
2041 /*
2042  * Aggregate given the tuple in the principal data buffer, and the aggregating
2043  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2044  * buffer is specified as the buf parameter.  This routine does not return
2045  * failure; if there is no space in the aggregation buffer, the data will be
2046  * dropped, and a corresponding counter incremented.
2047  */
2048 static void
2049 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2050     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2051 {
2052         dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2053         uint32_t i, ndx, size, fsize;
2054         uint32_t align = sizeof (uint64_t) - 1;
2055         dtrace_aggbuffer_t *agb;
2056         dtrace_aggkey_t *key;
2057         uint32_t hashval = 0, limit, isstr;
2058         caddr_t tomax, data, kdata;
2059         dtrace_actkind_t action;
2060         dtrace_action_t *act;
2061         uintptr_t offs;
2062
2063         if (buf == NULL)
2064                 return;
2065
2066         if (!agg->dtag_hasarg) {
2067                 /*
2068                  * Currently, only quantize() and lquantize() take additional
2069                  * arguments, and they have the same semantics:  an increment
2070                  * value that defaults to 1 when not present.  If additional
2071                  * aggregating actions take arguments, the setting of the
2072                  * default argument value will presumably have to become more
2073                  * sophisticated...
2074                  */
2075                 arg = 1;
2076         }
2077
2078         action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2079         size = rec->dtrd_offset - agg->dtag_base;
2080         fsize = size + rec->dtrd_size;
2081
2082         ASSERT(dbuf->dtb_tomax != NULL);
2083         data = dbuf->dtb_tomax + offset + agg->dtag_base;
2084
2085         if ((tomax = buf->dtb_tomax) == NULL) {
2086                 dtrace_buffer_drop(buf);
2087                 return;
2088         }
2089
2090         /*
2091          * The metastructure is always at the bottom of the buffer.
2092          */
2093         agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2094             sizeof (dtrace_aggbuffer_t));
2095
2096         if (buf->dtb_offset == 0) {
2097                 /*
2098                  * We just kludge up approximately 1/8th of the size to be
2099                  * buckets.  If this guess ends up being routinely
2100                  * off-the-mark, we may need to dynamically readjust this
2101                  * based on past performance.
2102                  */
2103                 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2104
2105                 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2106                     (uintptr_t)tomax || hashsize == 0) {
2107                         /*
2108                          * We've been given a ludicrously small buffer;
2109                          * increment our drop count and leave.
2110                          */
2111                         dtrace_buffer_drop(buf);
2112                         return;
2113                 }
2114
2115                 /*
2116                  * And now, a pathetic attempt to try to get a an odd (or
2117                  * perchance, a prime) hash size for better hash distribution.
2118                  */
2119                 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2120                         hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2121
2122                 agb->dtagb_hashsize = hashsize;
2123                 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2124                     agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2125                 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2126
2127                 for (i = 0; i < agb->dtagb_hashsize; i++)
2128                         agb->dtagb_hash[i] = NULL;
2129         }
2130
2131         ASSERT(agg->dtag_first != NULL);
2132         ASSERT(agg->dtag_first->dta_intuple);
2133
2134         /*
2135          * Calculate the hash value based on the key.  Note that we _don't_
2136          * include the aggid in the hashing (but we will store it as part of
2137          * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2138          * algorithm: a simple, quick algorithm that has no known funnels, and
2139          * gets good distribution in practice.  The efficacy of the hashing
2140          * algorithm (and a comparison with other algorithms) may be found by
2141          * running the ::dtrace_aggstat MDB dcmd.
2142          */
2143         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2144                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2145                 limit = i + act->dta_rec.dtrd_size;
2146                 ASSERT(limit <= size);
2147                 isstr = DTRACEACT_ISSTRING(act);
2148
2149                 for (; i < limit; i++) {
2150                         hashval += data[i];
2151                         hashval += (hashval << 10);
2152                         hashval ^= (hashval >> 6);
2153
2154                         if (isstr && data[i] == '\0')
2155                                 break;
2156                 }
2157         }
2158
2159         hashval += (hashval << 3);
2160         hashval ^= (hashval >> 11);
2161         hashval += (hashval << 15);
2162
2163         /*
2164          * Yes, the divide here is expensive -- but it's generally the least
2165          * of the performance issues given the amount of data that we iterate
2166          * over to compute hash values, compare data, etc.
2167          */
2168         ndx = hashval % agb->dtagb_hashsize;
2169
2170         for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2171                 ASSERT((caddr_t)key >= tomax);
2172                 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2173
2174                 if (hashval != key->dtak_hashval || key->dtak_size != size)
2175                         continue;
2176
2177                 kdata = key->dtak_data;
2178                 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2179
2180                 for (act = agg->dtag_first; act->dta_intuple;
2181                     act = act->dta_next) {
2182                         i = act->dta_rec.dtrd_offset - agg->dtag_base;
2183                         limit = i + act->dta_rec.dtrd_size;
2184                         ASSERT(limit <= size);
2185                         isstr = DTRACEACT_ISSTRING(act);
2186
2187                         for (; i < limit; i++) {
2188                                 if (kdata[i] != data[i])
2189                                         goto next;
2190
2191                                 if (isstr && data[i] == '\0')
2192                                         break;
2193                         }
2194                 }
2195
2196                 if (action != key->dtak_action) {
2197                         /*
2198                          * We are aggregating on the same value in the same
2199                          * aggregation with two different aggregating actions.
2200                          * (This should have been picked up in the compiler,
2201                          * so we may be dealing with errant or devious DIF.)
2202                          * This is an error condition; we indicate as much,
2203                          * and return.
2204                          */
2205                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2206                         return;
2207                 }
2208
2209                 /*
2210                  * This is a hit:  we need to apply the aggregator to
2211                  * the value at this key.
2212                  */
2213                 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2214                 return;
2215 next:
2216                 continue;
2217         }
2218
2219         /*
2220          * We didn't find it.  We need to allocate some zero-filled space,
2221          * link it into the hash table appropriately, and apply the aggregator
2222          * to the (zero-filled) value.
2223          */
2224         offs = buf->dtb_offset;
2225         while (offs & (align - 1))
2226                 offs += sizeof (uint32_t);
2227
2228         /*
2229          * If we don't have enough room to both allocate a new key _and_
2230          * its associated data, increment the drop count and return.
2231          */
2232         if ((uintptr_t)tomax + offs + fsize >
2233             agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2234                 dtrace_buffer_drop(buf);
2235                 return;
2236         }
2237
2238         /*CONSTCOND*/
2239         ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2240         key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2241         agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2242
2243         key->dtak_data = kdata = tomax + offs;
2244         buf->dtb_offset = offs + fsize;
2245
2246         /*
2247          * Now copy the data across.
2248          */
2249         *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2250
2251         for (i = sizeof (dtrace_aggid_t); i < size; i++)
2252                 kdata[i] = data[i];
2253
2254         /*
2255          * Because strings are not zeroed out by default, we need to iterate
2256          * looking for actions that store strings, and we need to explicitly
2257          * pad these strings out with zeroes.
2258          */
2259         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2260                 int nul;
2261
2262                 if (!DTRACEACT_ISSTRING(act))
2263                         continue;
2264
2265                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2266                 limit = i + act->dta_rec.dtrd_size;
2267                 ASSERT(limit <= size);
2268
2269                 for (nul = 0; i < limit; i++) {
2270                         if (nul) {
2271                                 kdata[i] = '\0';
2272                                 continue;
2273                         }
2274
2275                         if (data[i] != '\0')
2276                                 continue;
2277
2278                         nul = 1;
2279                 }
2280         }
2281
2282         for (i = size; i < fsize; i++)
2283                 kdata[i] = 0;
2284
2285         key->dtak_hashval = hashval;
2286         key->dtak_size = size;
2287         key->dtak_action = action;
2288         key->dtak_next = agb->dtagb_hash[ndx];
2289         agb->dtagb_hash[ndx] = key;
2290
2291         /*
2292          * Finally, apply the aggregator.
2293          */
2294         *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2295         agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2296 }
2297
2298 /*
2299  * Given consumer state, this routine finds a speculation in the INACTIVE
2300  * state and transitions it into the ACTIVE state.  If there is no speculation
2301  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2302  * incremented -- it is up to the caller to take appropriate action.
2303  */
2304 static int
2305 dtrace_speculation(dtrace_state_t *state)
2306 {
2307         int i = 0;
2308         dtrace_speculation_state_t current;
2309         uint32_t *stat = &state->dts_speculations_unavail, count;
2310
2311         while (i < state->dts_nspeculations) {
2312                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2313
2314                 current = spec->dtsp_state;
2315
2316                 if (current != DTRACESPEC_INACTIVE) {
2317                         if (current == DTRACESPEC_COMMITTINGMANY ||
2318                             current == DTRACESPEC_COMMITTING ||
2319                             current == DTRACESPEC_DISCARDING)
2320                                 stat = &state->dts_speculations_busy;
2321                         i++;
2322                         continue;
2323                 }
2324
2325                 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2326                     current, DTRACESPEC_ACTIVE) == current)
2327                         return (i + 1);
2328         }
2329
2330         /*
2331          * We couldn't find a speculation.  If we found as much as a single
2332          * busy speculation buffer, we'll attribute this failure as "busy"
2333          * instead of "unavail".
2334          */
2335         do {
2336                 count = *stat;
2337         } while (dtrace_cas32(stat, count, count + 1) != count);
2338
2339         return (0);
2340 }
2341
2342 /*
2343  * This routine commits an active speculation.  If the specified speculation
2344  * is not in a valid state to perform a commit(), this routine will silently do
2345  * nothing.  The state of the specified speculation is transitioned according
2346  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2347  */
2348 static void
2349 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2350     dtrace_specid_t which)
2351 {
2352         dtrace_speculation_t *spec;
2353         dtrace_buffer_t *src, *dest;
2354         uintptr_t daddr, saddr, dlimit, slimit;
2355         dtrace_speculation_state_t current, new = 0;
2356         intptr_t offs;
2357         uint64_t timestamp;
2358
2359         if (which == 0)
2360                 return;
2361
2362         if (which > state->dts_nspeculations) {
2363                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2364                 return;
2365         }
2366
2367         spec = &state->dts_speculations[which - 1];
2368         src = &spec->dtsp_buffer[cpu];
2369         dest = &state->dts_buffer[cpu];
2370
2371         do {
2372                 current = spec->dtsp_state;
2373
2374                 if (current == DTRACESPEC_COMMITTINGMANY)
2375                         break;
2376
2377                 switch (current) {
2378                 case DTRACESPEC_INACTIVE:
2379                 case DTRACESPEC_DISCARDING:
2380                         return;
2381
2382                 case DTRACESPEC_COMMITTING:
2383                         /*
2384                          * This is only possible if we are (a) commit()'ing
2385                          * without having done a prior speculate() on this CPU
2386                          * and (b) racing with another commit() on a different
2387                          * CPU.  There's nothing to do -- we just assert that
2388                          * our offset is 0.
2389                          */
2390                         ASSERT(src->dtb_offset == 0);
2391                         return;
2392
2393                 case DTRACESPEC_ACTIVE:
2394                         new = DTRACESPEC_COMMITTING;
2395                         break;
2396
2397                 case DTRACESPEC_ACTIVEONE:
2398                         /*
2399                          * This speculation is active on one CPU.  If our
2400                          * buffer offset is non-zero, we know that the one CPU
2401                          * must be us.  Otherwise, we are committing on a
2402                          * different CPU from the speculate(), and we must
2403                          * rely on being asynchronously cleaned.
2404                          */
2405                         if (src->dtb_offset != 0) {
2406                                 new = DTRACESPEC_COMMITTING;
2407                                 break;
2408                         }
2409                         /*FALLTHROUGH*/
2410
2411                 case DTRACESPEC_ACTIVEMANY:
2412                         new = DTRACESPEC_COMMITTINGMANY;
2413                         break;
2414
2415                 default:
2416                         ASSERT(0);
2417                 }
2418         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2419             current, new) != current);
2420
2421         /*
2422          * We have set the state to indicate that we are committing this
2423          * speculation.  Now reserve the necessary space in the destination
2424          * buffer.
2425          */
2426         if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2427             sizeof (uint64_t), state, NULL)) < 0) {
2428                 dtrace_buffer_drop(dest);
2429                 goto out;
2430         }
2431
2432         /*
2433          * We have sufficient space to copy the speculative buffer into the
2434          * primary buffer.  First, modify the speculative buffer, filling
2435          * in the timestamp of all entries with the current time.  The data
2436          * must have the commit() time rather than the time it was traced,
2437          * so that all entries in the primary buffer are in timestamp order.
2438          */
2439         timestamp = dtrace_gethrtime();
2440         saddr = (uintptr_t)src->dtb_tomax;
2441         slimit = saddr + src->dtb_offset;
2442         while (saddr < slimit) {
2443                 size_t size;
2444                 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2445
2446                 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2447                         saddr += sizeof (dtrace_epid_t);
2448                         continue;
2449                 }
2450                 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2451                 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2452
2453                 ASSERT3U(saddr + size, <=, slimit);
2454                 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2455                 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2456
2457                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2458
2459                 saddr += size;
2460         }
2461
2462         /*
2463          * Copy the buffer across.  (Note that this is a
2464          * highly subobtimal bcopy(); in the unlikely event that this becomes
2465          * a serious performance issue, a high-performance DTrace-specific
2466          * bcopy() should obviously be invented.)
2467          */
2468         daddr = (uintptr_t)dest->dtb_tomax + offs;
2469         dlimit = daddr + src->dtb_offset;
2470         saddr = (uintptr_t)src->dtb_tomax;
2471
2472         /*
2473          * First, the aligned portion.
2474          */
2475         while (dlimit - daddr >= sizeof (uint64_t)) {
2476                 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2477
2478                 daddr += sizeof (uint64_t);
2479                 saddr += sizeof (uint64_t);
2480         }
2481
2482         /*
2483          * Now any left-over bit...
2484          */
2485         while (dlimit - daddr)
2486                 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2487
2488         /*
2489          * Finally, commit the reserved space in the destination buffer.
2490          */
2491         dest->dtb_offset = offs + src->dtb_offset;
2492
2493 out:
2494         /*
2495          * If we're lucky enough to be the only active CPU on this speculation
2496          * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2497          */
2498         if (current == DTRACESPEC_ACTIVE ||
2499             (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2500                 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2501                     DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2502
2503                 ASSERT(rval == DTRACESPEC_COMMITTING);
2504         }
2505
2506         src->dtb_offset = 0;
2507         src->dtb_xamot_drops += src->dtb_drops;
2508         src->dtb_drops = 0;
2509 }
2510
2511 /*
2512  * This routine discards an active speculation.  If the specified speculation
2513  * is not in a valid state to perform a discard(), this routine will silently
2514  * do nothing.  The state of the specified speculation is transitioned
2515  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2516  */
2517 static void
2518 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2519     dtrace_specid_t which)
2520 {
2521         dtrace_speculation_t *spec;
2522         dtrace_speculation_state_t current, new = 0;
2523         dtrace_buffer_t *buf;
2524
2525         if (which == 0)
2526                 return;
2527
2528         if (which > state->dts_nspeculations) {
2529                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2530                 return;
2531         }
2532
2533         spec = &state->dts_speculations[which - 1];
2534         buf = &spec->dtsp_buffer[cpu];
2535
2536         do {
2537                 current = spec->dtsp_state;
2538
2539                 switch (current) {
2540                 case DTRACESPEC_INACTIVE:
2541                 case DTRACESPEC_COMMITTINGMANY:
2542                 case DTRACESPEC_COMMITTING:
2543                 case DTRACESPEC_DISCARDING:
2544                         return;
2545
2546                 case DTRACESPEC_ACTIVE:
2547                 case DTRACESPEC_ACTIVEMANY:
2548                         new = DTRACESPEC_DISCARDING;
2549                         break;
2550
2551                 case DTRACESPEC_ACTIVEONE:
2552                         if (buf->dtb_offset != 0) {
2553                                 new = DTRACESPEC_INACTIVE;
2554                         } else {
2555                                 new = DTRACESPEC_DISCARDING;
2556                         }
2557                         break;
2558
2559                 default:
2560                         ASSERT(0);
2561                 }
2562         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2563             current, new) != current);
2564
2565         buf->dtb_offset = 0;
2566         buf->dtb_drops = 0;
2567 }
2568
2569 /*
2570  * Note:  not called from probe context.  This function is called
2571  * asynchronously from cross call context to clean any speculations that are
2572  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2573  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2574  * speculation.
2575  */
2576 static void
2577 dtrace_speculation_clean_here(dtrace_state_t *state)
2578 {
2579         dtrace_icookie_t cookie;
2580         processorid_t cpu = curcpu;
2581         dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2582         dtrace_specid_t i;
2583
2584         cookie = dtrace_interrupt_disable();
2585
2586         if (dest->dtb_tomax == NULL) {
2587                 dtrace_interrupt_enable(cookie);
2588                 return;
2589         }
2590
2591         for (i = 0; i < state->dts_nspeculations; i++) {
2592                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2593                 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2594
2595                 if (src->dtb_tomax == NULL)
2596                         continue;
2597
2598                 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2599                         src->dtb_offset = 0;
2600                         continue;
2601                 }
2602
2603                 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2604                         continue;
2605
2606                 if (src->dtb_offset == 0)
2607                         continue;
2608
2609                 dtrace_speculation_commit(state, cpu, i + 1);
2610         }
2611
2612         dtrace_interrupt_enable(cookie);
2613 }
2614
2615 /*
2616  * Note:  not called from probe context.  This function is called
2617  * asynchronously (and at a regular interval) to clean any speculations that
2618  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2619  * is work to be done, it cross calls all CPUs to perform that work;
2620  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2621  * INACTIVE state until they have been cleaned by all CPUs.
2622  */
2623 static void
2624 dtrace_speculation_clean(dtrace_state_t *state)
2625 {
2626         int work = 0, rv;
2627         dtrace_specid_t i;
2628
2629         for (i = 0; i < state->dts_nspeculations; i++) {
2630                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2631
2632                 ASSERT(!spec->dtsp_cleaning);
2633
2634                 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2635                     spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2636                         continue;
2637
2638                 work++;
2639                 spec->dtsp_cleaning = 1;
2640         }
2641
2642         if (!work)
2643                 return;
2644
2645         dtrace_xcall(DTRACE_CPUALL,
2646             (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2647
2648         /*
2649          * We now know that all CPUs have committed or discarded their
2650          * speculation buffers, as appropriate.  We can now set the state
2651          * to inactive.
2652          */
2653         for (i = 0; i < state->dts_nspeculations; i++) {
2654                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2655                 dtrace_speculation_state_t current, new;
2656
2657                 if (!spec->dtsp_cleaning)
2658                         continue;
2659
2660                 current = spec->dtsp_state;
2661                 ASSERT(current == DTRACESPEC_DISCARDING ||
2662                     current == DTRACESPEC_COMMITTINGMANY);
2663
2664                 new = DTRACESPEC_INACTIVE;
2665
2666                 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2667                 ASSERT(rv == current);
2668                 spec->dtsp_cleaning = 0;
2669         }
2670 }
2671
2672 /*
2673  * Called as part of a speculate() to get the speculative buffer associated
2674  * with a given speculation.  Returns NULL if the specified speculation is not
2675  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2676  * the active CPU is not the specified CPU -- the speculation will be
2677  * atomically transitioned into the ACTIVEMANY state.
2678  */
2679 static dtrace_buffer_t *
2680 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2681     dtrace_specid_t which)
2682 {
2683         dtrace_speculation_t *spec;
2684         dtrace_speculation_state_t current, new = 0;
2685         dtrace_buffer_t *buf;
2686
2687         if (which == 0)
2688                 return (NULL);
2689
2690         if (which > state->dts_nspeculations) {
2691                 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2692                 return (NULL);
2693         }
2694
2695         spec = &state->dts_speculations[which - 1];
2696         buf = &spec->dtsp_buffer[cpuid];
2697
2698         do {
2699                 current = spec->dtsp_state;
2700
2701                 switch (current) {
2702                 case DTRACESPEC_INACTIVE:
2703                 case DTRACESPEC_COMMITTINGMANY:
2704                 case DTRACESPEC_DISCARDING:
2705                         return (NULL);
2706
2707                 case DTRACESPEC_COMMITTING:
2708                         ASSERT(buf->dtb_offset == 0);
2709                         return (NULL);
2710
2711                 case DTRACESPEC_ACTIVEONE:
2712                         /*
2713                          * This speculation is currently active on one CPU.
2714                          * Check the offset in the buffer; if it's non-zero,
2715                          * that CPU must be us (and we leave the state alone).
2716                          * If it's zero, assume that we're starting on a new
2717                          * CPU -- and change the state to indicate that the
2718                          * speculation is active on more than one CPU.
2719                          */
2720                         if (buf->dtb_offset != 0)
2721                                 return (buf);
2722
2723                         new = DTRACESPEC_ACTIVEMANY;
2724                         break;
2725
2726                 case DTRACESPEC_ACTIVEMANY:
2727                         return (buf);
2728
2729                 case DTRACESPEC_ACTIVE:
2730                         new = DTRACESPEC_ACTIVEONE;
2731                         break;
2732
2733                 default:
2734                         ASSERT(0);
2735                 }
2736         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2737             current, new) != current);
2738
2739         ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2740         return (buf);
2741 }
2742
2743 /*
2744  * Return a string.  In the event that the user lacks the privilege to access
2745  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2746  * don't fail access checking.
2747  *
2748  * dtrace_dif_variable() uses this routine as a helper for various
2749  * builtin values such as 'execname' and 'probefunc.'
2750  */
2751 uintptr_t
2752 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2753     dtrace_mstate_t *mstate)
2754 {
2755         uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2756         uintptr_t ret;
2757         size_t strsz;
2758
2759         /*
2760          * The easy case: this probe is allowed to read all of memory, so
2761          * we can just return this as a vanilla pointer.
2762          */
2763         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2764                 return (addr);
2765
2766         /*
2767          * This is the tougher case: we copy the string in question from
2768          * kernel memory into scratch memory and return it that way: this
2769          * ensures that we won't trip up when access checking tests the
2770          * BYREF return value.
2771          */
2772         strsz = dtrace_strlen((char *)addr, size) + 1;
2773
2774         if (mstate->dtms_scratch_ptr + strsz >
2775             mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2776                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2777                 return (0);
2778         }
2779
2780         dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2781             strsz);
2782         ret = mstate->dtms_scratch_ptr;
2783         mstate->dtms_scratch_ptr += strsz;
2784         return (ret);
2785 }
2786
2787 /*
2788  * Return a string from a memoy address which is known to have one or
2789  * more concatenated, individually zero terminated, sub-strings.
2790  * In the event that the user lacks the privilege to access
2791  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2792  * don't fail access checking.
2793  *
2794  * dtrace_dif_variable() uses this routine as a helper for various
2795  * builtin values such as 'execargs'.
2796  */
2797 static uintptr_t
2798 dtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
2799     dtrace_mstate_t *mstate)
2800 {
2801         char *p;
2802         size_t i;
2803         uintptr_t ret;
2804
2805         if (mstate->dtms_scratch_ptr + strsz >
2806             mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2807                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2808                 return (0);
2809         }
2810
2811         dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2812             strsz);
2813
2814         /* Replace sub-string termination characters with a space. */
2815         for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
2816             p++, i++)
2817                 if (*p == '\0')
2818                         *p = ' ';
2819
2820         ret = mstate->dtms_scratch_ptr;
2821         mstate->dtms_scratch_ptr += strsz;
2822         return (ret);
2823 }
2824
2825 /*
2826  * This function implements the DIF emulator's variable lookups.  The emulator
2827  * passes a reserved variable identifier and optional built-in array index.
2828  */
2829 static uint64_t
2830 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2831     uint64_t ndx)
2832 {
2833         /*
2834          * If we're accessing one of the uncached arguments, we'll turn this
2835          * into a reference in the args array.
2836          */
2837         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2838                 ndx = v - DIF_VAR_ARG0;
2839                 v = DIF_VAR_ARGS;
2840         }
2841
2842         switch (v) {
2843         case DIF_VAR_ARGS:
2844                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2845                 if (ndx >= sizeof (mstate->dtms_arg) /
2846                     sizeof (mstate->dtms_arg[0])) {
2847                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2848                         dtrace_provider_t *pv;
2849                         uint64_t val;
2850
2851                         pv = mstate->dtms_probe->dtpr_provider;
2852                         if (pv->dtpv_pops.dtps_getargval != NULL)
2853                                 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2854                                     mstate->dtms_probe->dtpr_id,
2855                                     mstate->dtms_probe->dtpr_arg, ndx, aframes);
2856                         else
2857                                 val = dtrace_getarg(ndx, aframes);
2858
2859                         /*
2860                          * This is regrettably required to keep the compiler
2861                          * from tail-optimizing the call to dtrace_getarg().
2862                          * The condition always evaluates to true, but the
2863                          * compiler has no way of figuring that out a priori.
2864                          * (None of this would be necessary if the compiler
2865                          * could be relied upon to _always_ tail-optimize
2866                          * the call to dtrace_getarg() -- but it can't.)
2867                          */
2868                         if (mstate->dtms_probe != NULL)
2869                                 return (val);
2870
2871                         ASSERT(0);
2872                 }
2873
2874                 return (mstate->dtms_arg[ndx]);
2875
2876 #if defined(sun)
2877         case DIF_VAR_UREGS: {
2878                 klwp_t *lwp;
2879
2880                 if (!dtrace_priv_proc(state))
2881                         return (0);
2882
2883                 if ((lwp = curthread->t_lwp) == NULL) {
2884                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2885                         cpu_core[curcpu].cpuc_dtrace_illval = NULL;
2886                         return (0);
2887                 }
2888
2889                 return (dtrace_getreg(lwp->lwp_regs, ndx));
2890                 return (0);
2891         }
2892 #else
2893         case DIF_VAR_UREGS: {
2894                 struct trapframe *tframe;
2895
2896                 if (!dtrace_priv_proc(state))
2897                         return (0);
2898
2899                 if ((tframe = curthread->td_frame) == NULL) {
2900                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2901                         cpu_core[curcpu].cpuc_dtrace_illval = 0;
2902                         return (0);
2903                 }
2904
2905                 return (dtrace_getreg(tframe, ndx));
2906         }
2907 #endif
2908
2909         case DIF_VAR_CURTHREAD:
2910                 if (!dtrace_priv_kernel(state))
2911                         return (0);
2912                 return ((uint64_t)(uintptr_t)curthread);
2913
2914         case DIF_VAR_TIMESTAMP:
2915                 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2916                         mstate->dtms_timestamp = dtrace_gethrtime();
2917                         mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2918                 }
2919                 return (mstate->dtms_timestamp);
2920
2921         case DIF_VAR_VTIMESTAMP:
2922                 ASSERT(dtrace_vtime_references != 0);
2923                 return (curthread->t_dtrace_vtime);
2924
2925         case DIF_VAR_WALLTIMESTAMP:
2926                 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2927                         mstate->dtms_walltimestamp = dtrace_gethrestime();
2928                         mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2929                 }
2930                 return (mstate->dtms_walltimestamp);
2931
2932 #if defined(sun)
2933         case DIF_VAR_IPL:
2934                 if (!dtrace_priv_kernel(state))
2935                         return (0);
2936                 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2937                         mstate->dtms_ipl = dtrace_getipl();
2938                         mstate->dtms_present |= DTRACE_MSTATE_IPL;
2939                 }
2940                 return (mstate->dtms_ipl);
2941 #endif
2942
2943         case DIF_VAR_EPID:
2944                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2945                 return (mstate->dtms_epid);
2946
2947         case DIF_VAR_ID:
2948                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2949                 return (mstate->dtms_probe->dtpr_id);
2950
2951         case DIF_VAR_STACKDEPTH:
2952                 if (!dtrace_priv_kernel(state))
2953                         return (0);
2954                 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2955                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2956
2957                         mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2958                         mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2959                 }
2960                 return (mstate->dtms_stackdepth);
2961
2962         case DIF_VAR_USTACKDEPTH:
2963                 if (!dtrace_priv_proc(state))
2964                         return (0);
2965                 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2966                         /*
2967                          * See comment in DIF_VAR_PID.
2968                          */
2969                         if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2970                             CPU_ON_INTR(CPU)) {
2971                                 mstate->dtms_ustackdepth = 0;
2972                         } else {
2973                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2974                                 mstate->dtms_ustackdepth =
2975                                     dtrace_getustackdepth();
2976                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2977                         }
2978                         mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2979                 }
2980                 return (mstate->dtms_ustackdepth);
2981
2982         case DIF_VAR_CALLER:
2983                 if (!dtrace_priv_kernel(state))
2984                         return (0);
2985                 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2986                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2987
2988                         if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2989                                 /*
2990                                  * If this is an unanchored probe, we are
2991                                  * required to go through the slow path:
2992                                  * dtrace_caller() only guarantees correct
2993                                  * results for anchored probes.
2994                                  */
2995                                 pc_t caller[2] = {0, 0};
2996
2997                                 dtrace_getpcstack(caller, 2, aframes,
2998                                     (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2999                                 mstate->dtms_caller = caller[1];
3000                         } else if ((mstate->dtms_caller =
3001                             dtrace_caller(aframes)) == -1) {
3002                                 /*
3003                                  * We have failed to do this the quick way;
3004                                  * we must resort to the slower approach of
3005                                  * calling dtrace_getpcstack().
3006                                  */
3007                                 pc_t caller = 0;
3008
3009                                 dtrace_getpcstack(&caller, 1, aframes, NULL);
3010                                 mstate->dtms_caller = caller;
3011                         }
3012
3013                         mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3014                 }
3015                 return (mstate->dtms_caller);
3016
3017         case DIF_VAR_UCALLER:
3018                 if (!dtrace_priv_proc(state))
3019                         return (0);
3020
3021                 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3022                         uint64_t ustack[3];
3023
3024                         /*
3025                          * dtrace_getupcstack() fills in the first uint64_t
3026                          * with the current PID.  The second uint64_t will
3027                          * be the program counter at user-level.  The third
3028                          * uint64_t will contain the caller, which is what
3029                          * we're after.
3030                          */
3031                         ustack[2] = 0;
3032                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3033                         dtrace_getupcstack(ustack, 3);
3034                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3035                         mstate->dtms_ucaller = ustack[2];
3036                         mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3037                 }
3038
3039                 return (mstate->dtms_ucaller);
3040
3041         case DIF_VAR_PROBEPROV:
3042                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3043                 return (dtrace_dif_varstr(
3044                     (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3045                     state, mstate));
3046
3047         case DIF_VAR_PROBEMOD:
3048                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3049                 return (dtrace_dif_varstr(
3050                     (uintptr_t)mstate->dtms_probe->dtpr_mod,
3051                     state, mstate));
3052
3053         case DIF_VAR_PROBEFUNC:
3054                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3055                 return (dtrace_dif_varstr(
3056                     (uintptr_t)mstate->dtms_probe->dtpr_func,
3057                     state, mstate));
3058
3059         case DIF_VAR_PROBENAME:
3060                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3061                 return (dtrace_dif_varstr(
3062                     (uintptr_t)mstate->dtms_probe->dtpr_name,
3063                     state, mstate));
3064
3065         case DIF_VAR_PID:
3066                 if (!dtrace_priv_proc(state))
3067                         return (0);
3068
3069 #if defined(sun)
3070                 /*
3071                  * Note that we are assuming that an unanchored probe is
3072                  * always due to a high-level interrupt.  (And we're assuming
3073                  * that there is only a single high level interrupt.)
3074                  */
3075                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3076                         return (pid0.pid_id);
3077
3078                 /*
3079                  * It is always safe to dereference one's own t_procp pointer:
3080                  * it always points to a valid, allocated proc structure.
3081                  * Further, it is always safe to dereference the p_pidp member
3082                  * of one's own proc structure.  (These are truisms becuase
3083                  * threads and processes don't clean up their own state --
3084                  * they leave that task to whomever reaps them.)
3085                  */
3086                 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3087 #else
3088                 return ((uint64_t)curproc->p_pid);
3089 #endif
3090
3091         case DIF_VAR_PPID:
3092                 if (!dtrace_priv_proc(state))
3093                         return (0);
3094
3095 #if defined(sun)
3096                 /*
3097                  * See comment in DIF_VAR_PID.
3098                  */
3099                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3100                         return (pid0.pid_id);
3101
3102                 /*
3103                  * It is always safe to dereference one's own t_procp pointer:
3104                  * it always points to a valid, allocated proc structure.
3105                  * (This is true because threads don't clean up their own
3106                  * state -- they leave that task to whomever reaps them.)
3107                  */
3108                 return ((uint64_t)curthread->t_procp->p_ppid);
3109 #else
3110                 return ((uint64_t)curproc->p_pptr->p_pid);
3111 #endif
3112
3113         case DIF_VAR_TID:
3114 #if defined(sun)
3115                 /*
3116                  * See comment in DIF_VAR_PID.
3117                  */
3118                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3119                         return (0);
3120 #endif
3121
3122                 return ((uint64_t)curthread->t_tid);
3123
3124         case DIF_VAR_EXECARGS: {
3125                 struct pargs *p_args = curthread->td_proc->p_args;
3126
3127                 if (p_args == NULL)
3128                         return(0);
3129
3130                 return (dtrace_dif_varstrz(
3131                     (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3132         }
3133
3134         case DIF_VAR_EXECNAME:
3135 #if defined(sun)
3136                 if (!dtrace_priv_proc(state))
3137                         return (0);
3138
3139                 /*
3140                  * See comment in DIF_VAR_PID.
3141                  */
3142                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3143                         return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3144
3145                 /*
3146                  * It is always safe to dereference one's own t_procp pointer:
3147                  * it always points to a valid, allocated proc structure.
3148                  * (This is true because threads don't clean up their own
3149                  * state -- they leave that task to whomever reaps them.)
3150                  */
3151                 return (dtrace_dif_varstr(
3152                     (uintptr_t)curthread->t_procp->p_user.u_comm,
3153                     state, mstate));
3154 #else
3155                 return (dtrace_dif_varstr(
3156                     (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3157 #endif
3158
3159         case DIF_VAR_ZONENAME:
3160 #if defined(sun)
3161                 if (!dtrace_priv_proc(state))
3162                         return (0);
3163
3164                 /*
3165                  * See comment in DIF_VAR_PID.
3166                  */
3167                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3168                         return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3169
3170                 /*
3171                  * It is always safe to dereference one's own t_procp pointer:
3172                  * it always points to a valid, allocated proc structure.
3173                  * (This is true because threads don't clean up their own
3174                  * state -- they leave that task to whomever reaps them.)
3175                  */
3176                 return (dtrace_dif_varstr(
3177                     (uintptr_t)curthread->t_procp->p_zone->zone_name,
3178                     state, mstate));
3179 #else
3180                 return (0);
3181 #endif
3182
3183         case DIF_VAR_UID:
3184                 if (!dtrace_priv_proc(state))
3185                         return (0);
3186
3187 #if defined(sun)
3188                 /*
3189                  * See comment in DIF_VAR_PID.
3190                  */
3191                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3192                         return ((uint64_t)p0.p_cred->cr_uid);
3193 #endif
3194
3195                 /*
3196                  * It is always safe to dereference one's own t_procp pointer:
3197                  * it always points to a valid, allocated proc structure.
3198                  * (This is true because threads don't clean up their own
3199                  * state -- they leave that task to whomever reaps them.)
3200                  *
3201                  * Additionally, it is safe to dereference one's own process
3202                  * credential, since this is never NULL after process birth.
3203                  */
3204                 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3205
3206         case DIF_VAR_GID:
3207                 if (!dtrace_priv_proc(state))
3208                         return (0);
3209
3210 #if defined(sun)
3211                 /*
3212                  * See comment in DIF_VAR_PID.
3213                  */
3214                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3215                         return ((uint64_t)p0.p_cred->cr_gid);
3216 #endif
3217
3218                 /*
3219                  * It is always safe to dereference one's own t_procp pointer:
3220                  * it always points to a valid, allocated proc structure.
3221                  * (This is true because threads don't clean up their own
3222                  * state -- they leave that task to whomever reaps them.)
3223                  *
3224                  * Additionally, it is safe to dereference one's own process
3225                  * credential, since this is never NULL after process birth.
3226                  */
3227                 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3228
3229         case DIF_VAR_ERRNO: {
3230 #if defined(sun)
3231                 klwp_t *lwp;
3232                 if (!dtrace_priv_proc(state))
3233                         return (0);
3234
3235                 /*
3236                  * See comment in DIF_VAR_PID.
3237                  */
3238                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3239                         return (0);
3240
3241                 /*
3242                  * It is always safe to dereference one's own t_lwp pointer in
3243                  * the event that this pointer is non-NULL.  (This is true
3244                  * because threads and lwps don't clean up their own state --
3245                  * they leave that task to whomever reaps them.)
3246                  */
3247                 if ((lwp = curthread->t_lwp) == NULL)
3248                         return (0);
3249
3250                 return ((uint64_t)lwp->lwp_errno);
3251 #else
3252                 return (curthread->td_errno);
3253 #endif
3254         }
3255 #if !defined(sun)
3256         case DIF_VAR_CPU: {
3257                 return curcpu;
3258         }
3259 #endif
3260         default:
3261                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3262                 return (0);
3263         }
3264 }
3265
3266 /*
3267  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3268  * Notice that we don't bother validating the proper number of arguments or
3269  * their types in the tuple stack.  This isn't needed because all argument
3270  * interpretation is safe because of our load safety -- the worst that can
3271  * happen is that a bogus program can obtain bogus results.
3272  */
3273 static void
3274 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3275     dtrace_key_t *tupregs, int nargs,
3276     dtrace_mstate_t *mstate, dtrace_state_t *state)
3277 {
3278         volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
3279         volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
3280         dtrace_vstate_t *vstate = &state->dts_vstate;
3281
3282 #if defined(sun)
3283         union {
3284                 mutex_impl_t mi;
3285                 uint64_t mx;
3286         } m;
3287
3288         union {
3289                 krwlock_t ri;
3290                 uintptr_t rw;
3291         } r;
3292 #else
3293         struct thread *lowner;
3294         union {
3295                 struct lock_object *li;
3296                 uintptr_t lx;
3297         } l;
3298 #endif
3299
3300         switch (subr) {
3301         case DIF_SUBR_RAND:
3302                 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3303                 break;
3304
3305 #if defined(sun)
3306         case DIF_SUBR_MUTEX_OWNED:
3307                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3308                     mstate, vstate)) {
3309                         regs[rd] = 0;
3310                         break;
3311                 }
3312
3313                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3314                 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3315                         regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3316                 else
3317                         regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3318                 break;
3319
3320         case DIF_SUBR_MUTEX_OWNER:
3321                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3322                     mstate, vstate)) {
3323                         regs[rd] = 0;
3324                         break;
3325                 }
3326
3327                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3328                 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3329                     MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3330                         regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3331                 else
3332                         regs[rd] = 0;
3333                 break;
3334
3335         case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3336                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3337                     mstate, vstate)) {
3338                         regs[rd] = 0;
3339                         break;
3340                 }
3341
3342                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3343                 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3344                 break;
3345
3346         case DIF_SUBR_MUTEX_TYPE_SPIN:
3347                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3348                     mstate, vstate)) {
3349                         regs[rd] = 0;
3350                         break;
3351                 }
3352
3353                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3354                 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3355                 break;
3356
3357         case DIF_SUBR_RW_READ_HELD: {
3358                 uintptr_t tmp;
3359
3360                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3361                     mstate, vstate)) {
3362                         regs[rd] = 0;
3363                         break;
3364                 }
3365
3366                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3367                 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3368                 break;
3369         }
3370
3371         case DIF_SUBR_RW_WRITE_HELD:
3372                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3373                     mstate, vstate)) {
3374                         regs[rd] = 0;
3375                         break;
3376                 }
3377
3378                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3379                 regs[rd] = _RW_WRITE_HELD(&r.ri);
3380                 break;
3381
3382         case DIF_SUBR_RW_ISWRITER:
3383                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3384                     mstate, vstate)) {
3385                         regs[rd] = 0;
3386                         break;
3387                 }
3388
3389                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3390                 regs[rd] = _RW_ISWRITER(&r.ri);
3391                 break;
3392
3393 #else
3394         case DIF_SUBR_MUTEX_OWNED:
3395                 if (!dtrace_canload(tupregs[0].dttk_value,
3396                         sizeof (struct lock_object), mstate, vstate)) {
3397                         regs[rd] = 0;
3398                         break;
3399                 }
3400                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3401                 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3402                 break;
3403
3404         case DIF_SUBR_MUTEX_OWNER:
3405                 if (!dtrace_canload(tupregs[0].dttk_value,
3406                         sizeof (struct lock_object), mstate, vstate)) {
3407                         regs[rd] = 0;
3408                         break;
3409                 }
3410                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3411                 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3412                 regs[rd] = (uintptr_t)lowner;
3413                 break;
3414
3415         case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3416                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3417                     mstate, vstate)) {
3418                         regs[rd] = 0;
3419                         break;
3420                 }
3421                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3422                 /* XXX - should be only LC_SLEEPABLE? */
3423                 regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
3424                     (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
3425                 break;
3426
3427         case DIF_SUBR_MUTEX_TYPE_SPIN:
3428                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3429                     mstate, vstate)) {
3430                         regs[rd] = 0;
3431                         break;
3432                 }
3433                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3434                 regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
3435                 break;
3436
3437         case DIF_SUBR_RW_READ_HELD: 
3438         case DIF_SUBR_SX_SHARED_HELD: 
3439                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3440                     mstate, vstate)) {
3441                         regs[rd] = 0;
3442                         break;
3443                 }
3444                 l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3445                 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3446                     lowner == NULL;
3447                 break;
3448
3449         case DIF_SUBR_RW_WRITE_HELD:
3450         case DIF_SUBR_SX_EXCLUSIVE_HELD:
3451                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3452                     mstate, vstate)) {
3453                         regs[rd] = 0;
3454                         break;
3455                 }
3456                 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3457                 LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3458                 regs[rd] = (lowner == curthread);
3459                 break;
3460
3461         case DIF_SUBR_RW_ISWRITER:
3462         case DIF_SUBR_SX_ISEXCLUSIVE:
3463                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3464                     mstate, vstate)) {
3465                         regs[rd] = 0;
3466                         break;
3467                 }
3468                 l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3469                 regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3470                     lowner != NULL;
3471                 break;
3472 #endif /* ! defined(sun) */
3473
3474         case DIF_SUBR_BCOPY: {
3475                 /*
3476                  * We need to be sure that the destination is in the scratch
3477                  * region -- no other region is allowed.
3478                  */
3479                 uintptr_t src = tupregs[0].dttk_value;
3480                 uintptr_t dest = tupregs[1].dttk_value;
3481                 size_t size = tupregs[2].dttk_value;
3482
3483                 if (!dtrace_inscratch(dest, size, mstate)) {
3484                         *flags |= CPU_DTRACE_BADADDR;
3485                         *illval = regs[rd];
3486                         break;
3487                 }
3488
3489                 if (!dtrace_canload(src, size, mstate, vstate)) {
3490                         regs[rd] = 0;
3491                         break;
3492                 }
3493
3494                 dtrace_bcopy((void *)src, (void *)dest, size);
3495                 break;
3496         }
3497
3498         case DIF_SUBR_ALLOCA:
3499         case DIF_SUBR_COPYIN: {
3500                 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3501                 uint64_t size =
3502                     tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3503                 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3504
3505                 /*
3506                  * This action doesn't require any credential checks since
3507                  * probes will not activate in user contexts to which the
3508                  * enabling user does not have permissions.
3509                  */
3510
3511                 /*
3512                  * Rounding up the user allocation size could have overflowed
3513                  * a large, bogus allocation (like -1ULL) to 0.
3514                  */
3515                 if (scratch_size < size ||
3516                     !DTRACE_INSCRATCH(mstate, scratch_size)) {
3517                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3518                         regs[rd] = 0;
3519                         break;
3520                 }
3521
3522                 if (subr == DIF_SUBR_COPYIN) {
3523                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3524                         dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3525                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3526                 }
3527
3528                 mstate->dtms_scratch_ptr += scratch_size;
3529                 regs[rd] = dest;
3530                 break;
3531         }
3532
3533         case DIF_SUBR_COPYINTO: {
3534                 uint64_t size = tupregs[1].dttk_value;
3535                 uintptr_t dest = tupregs[2].dttk_value;
3536
3537                 /*
3538                  * This action doesn't require any credential checks since
3539                  * probes will not activate in user contexts to which the
3540                  * enabling user does not have permissions.
3541                  */
3542                 if (!dtrace_inscratch(dest, size, mstate)) {
3543                         *flags |= CPU_DTRACE_BADADDR;
3544                         *illval = regs[rd];
3545                         break;
3546                 }
3547
3548                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3549                 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3550                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3551                 break;
3552         }
3553
3554         case DIF_SUBR_COPYINSTR: {
3555                 uintptr_t dest = mstate->dtms_scratch_ptr;
3556                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3557
3558                 if (nargs > 1 && tupregs[1].dttk_value < size)
3559                         size = tupregs[1].dttk_value + 1;
3560
3561                 /*
3562                  * This action doesn't require any credential checks since
3563                  * probes will not activate in user contexts to which the
3564                  * enabling user does not have permissions.
3565                  */
3566                 if (!DTRACE_INSCRATCH(mstate, size)) {
3567                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3568                         regs[rd] = 0;
3569                         break;
3570                 }
3571
3572                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3573                 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3574                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3575
3576                 ((char *)dest)[size - 1] = '\0';
3577                 mstate->dtms_scratch_ptr += size;
3578                 regs[rd] = dest;
3579                 break;
3580         }
3581
3582 #if defined(sun)
3583         case DIF_SUBR_MSGSIZE:
3584         case DIF_SUBR_MSGDSIZE: {
3585                 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3586                 uintptr_t wptr, rptr;
3587                 size_t count = 0;
3588                 int cont = 0;
3589
3590                 while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
3591
3592                         if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3593                             vstate)) {
3594                                 regs[rd] = 0;
3595                                 break;
3596                         }
3597
3598                         wptr = dtrace_loadptr(baddr +
3599                             offsetof(mblk_t, b_wptr));
3600
3601                         rptr = dtrace_loadptr(baddr +
3602                             offsetof(mblk_t, b_rptr));
3603
3604                         if (wptr < rptr) {
3605                                 *flags |= CPU_DTRACE_BADADDR;
3606                                 *illval = tupregs[0].dttk_value;
3607                                 break;
3608                         }
3609
3610                         daddr = dtrace_loadptr(baddr +
3611                             offsetof(mblk_t, b_datap));
3612
3613                         baddr = dtrace_loadptr(baddr +
3614                             offsetof(mblk_t, b_cont));
3615
3616                         /*
3617                          * We want to prevent against denial-of-service here,
3618                          * so we're only going to search the list for
3619                          * dtrace_msgdsize_max mblks.
3620                          */
3621                         if (cont++ > dtrace_msgdsize_max) {
3622                                 *flags |= CPU_DTRACE_ILLOP;
3623                                 break;
3624                         }
3625
3626                         if (subr == DIF_SUBR_MSGDSIZE) {
3627                                 if (dtrace_load8(daddr +
3628                                     offsetof(dblk_t, db_type)) != M_DATA)
3629                                         continue;
3630                         }
3631
3632                         count += wptr - rptr;
3633                 }
3634
3635                 if (!(*flags & CPU_DTRACE_FAULT))
3636                         regs[rd] = count;
3637
3638                 break;
3639         }
3640 #endif
3641
3642         case DIF_SUBR_PROGENYOF: {
3643                 pid_t pid = tupregs[0].dttk_value;
3644                 proc_t *p;
3645                 int rval = 0;
3646
3647                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3648
3649                 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3650 #if defined(sun)
3651                         if (p->p_pidp->pid_id == pid) {
3652 #else
3653                         if (p->p_pid == pid) {
3654 #endif
3655                                 rval = 1;
3656                                 break;
3657                         }
3658                 }
3659
3660                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3661
3662                 regs[rd] = rval;
3663                 break;
3664         }
3665
3666         case DIF_SUBR_SPECULATION:
3667                 regs[rd] = dtrace_speculation(state);
3668                 break;
3669
3670         case DIF_SUBR_COPYOUT: {
3671                 uintptr_t kaddr = tupregs[0].dttk_value;
3672                 uintptr_t uaddr = tupregs[1].dttk_value;
3673                 uint64_t size = tupregs[2].dttk_value;
3674
3675                 if (!dtrace_destructive_disallow &&
3676                     dtrace_priv_proc_control(state) &&
3677                     !dtrace_istoxic(kaddr, size)) {
3678                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3679                         dtrace_copyout(kaddr, uaddr, size, flags);
3680                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3681                 }
3682                 break;
3683         }
3684
3685         case DIF_SUBR_COPYOUTSTR: {
3686                 uintptr_t kaddr = tupregs[0].dttk_value;
3687                 uintptr_t uaddr = tupregs[1].dttk_value;
3688                 uint64_t size = tupregs[2].dttk_value;
3689
3690                 if (!dtrace_destructive_disallow &&
3691                     dtrace_priv_proc_control(state) &&
3692                     !dtrace_istoxic(kaddr, size)) {
3693                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3694                         dtrace_copyoutstr(kaddr, uaddr, size, flags);
3695                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3696                 }
3697                 break;
3698         }
3699
3700         case DIF_SUBR_STRLEN: {
3701                 size_t sz;
3702                 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3703                 sz = dtrace_strlen((char *)addr,
3704                     state->dts_options[DTRACEOPT_STRSIZE]);
3705
3706                 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3707                         regs[rd] = 0;
3708                         break;
3709                 }
3710
3711                 regs[rd] = sz;
3712
3713                 break;
3714         }
3715
3716         case DIF_SUBR_STRCHR:
3717         case DIF_SUBR_STRRCHR: {
3718                 /*
3719                  * We're going to iterate over the string looking for the
3720                  * specified character.  We will iterate until we have reached
3721                  * the string length or we have found the character.  If this
3722                  * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3723                  * of the specified character instead of the first.
3724                  */
3725                 uintptr_t saddr = tupregs[0].dttk_value;
3726                 uintptr_t addr = tupregs[0].dttk_value;
3727                 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3728                 char c, target = (char)tupregs[1].dttk_value;
3729
3730                 for (regs[rd] = 0; addr < limit; addr++) {
3731                         if ((c = dtrace_load8(addr)) == target) {
3732                                 regs[rd] = addr;
3733
3734                                 if (subr == DIF_SUBR_STRCHR)
3735                                         break;
3736                         }
3737
3738                         if (c == '\0')
3739                                 break;
3740                 }
3741
3742                 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3743                         regs[rd] = 0;
3744                         break;
3745                 }
3746
3747                 break;
3748         }
3749
3750         case DIF_SUBR_STRSTR:
3751         case DIF_SUBR_INDEX:
3752         case DIF_SUBR_RINDEX: {
3753                 /*
3754                  * We're going to iterate over the string looking for the
3755                  * specified string.  We will iterate until we have reached
3756                  * the string length or we have found the string.  (Yes, this
3757                  * is done in the most naive way possible -- but considering
3758                  * that the string we're searching for is likely to be
3759                  * relatively short, the complexity of Rabin-Karp or similar
3760                  * hardly seems merited.)
3761                  */
3762                 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3763                 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3764                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3765                 size_t len = dtrace_strlen(addr, size);
3766                 size_t sublen = dtrace_strlen(substr, size);
3767                 char *limit = addr + len, *orig = addr;
3768                 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3769                 int inc = 1;
3770
3771                 regs[rd] = notfound;
3772
3773                 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3774                         regs[rd] = 0;
3775                         break;
3776                 }
3777
3778                 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3779                     vstate)) {
3780                         regs[rd] = 0;
3781                         break;
3782                 }
3783
3784                 /*
3785                  * strstr() and index()/rindex() have similar semantics if
3786                  * both strings are the empty string: strstr() returns a
3787                  * pointer to the (empty) string, and index() and rindex()
3788                  * both return index 0 (regardless of any position argument).
3789                  */
3790                 if (sublen == 0 && len == 0) {
3791                         if (subr == DIF_SUBR_STRSTR)
3792                                 regs[rd] = (uintptr_t)addr;
3793                         else
3794                                 regs[rd] = 0;
3795                         break;
3796                 }
3797
3798                 if (subr != DIF_SUBR_STRSTR) {
3799                         if (subr == DIF_SUBR_RINDEX) {
3800                                 limit = orig - 1;
3801                                 addr += len;
3802                                 inc = -1;
3803                         }
3804
3805                         /*
3806                          * Both index() and rindex() take an optional position
3807                          * argument that denotes the starting position.
3808                          */
3809                         if (nargs == 3) {
3810                                 int64_t pos = (int64_t)tupregs[2].dttk_value;
3811
3812                                 /*
3813                                  * If the position argument to index() is
3814                                  * negative, Perl implicitly clamps it at
3815                                  * zero.  This semantic is a little surprising
3816                                  * given the special meaning of negative
3817                                  * positions to similar Perl functions like
3818                                  * substr(), but it appears to reflect a
3819                                  * notion that index() can start from a
3820                                  * negative index and increment its way up to
3821                                  * the string.  Given this notion, Perl's
3822                                  * rindex() is at least self-consistent in
3823                                  * that it implicitly clamps positions greater
3824                                  * than the string length to be the string
3825                                  * length.  Where Perl completely loses
3826                                  * coherence, however, is when the specified
3827                                  * substring is the empty string ("").  In
3828                                  * this case, even if the position is
3829                                  * negative, rindex() returns 0 -- and even if
3830                                  * the position is greater than the length,
3831                                  * index() returns the string length.  These
3832                                  * semantics violate the notion that index()
3833                                  * should never return a value less than the
3834                                  * specified position and that rindex() should
3835                                  * never return a value greater than the
3836                                  * specified position.  (One assumes that
3837                                  * these semantics are artifacts of Perl's
3838                                  * implementation and not the results of
3839                                  * deliberate design -- it beggars belief that
3840                                  * even Larry Wall could desire such oddness.)
3841                                  * While in the abstract one would wish for
3842                                  * consistent position semantics across
3843                                  * substr(), index() and rindex() -- or at the
3844                                  * very least self-consistent position
3845                                  * semantics for index() and rindex() -- we
3846                                  * instead opt to keep with the extant Perl
3847                                  * semantics, in all their broken glory.  (Do
3848                                  * we have more desire to maintain Perl's
3849                                  * semantics than Perl does?  Probably.)
3850                                  */
3851                                 if (subr == DIF_SUBR_RINDEX) {
3852                                         if (pos < 0) {
3853                                                 if (sublen == 0)
3854                                                         regs[rd] = 0;
3855                                                 break;
3856                                         }
3857
3858                                         if (pos > len)
3859                                                 pos = len;
3860                                 } else {
3861                                         if (pos < 0)
3862                                                 pos = 0;
3863
3864                                         if (pos >= len) {
3865                                                 if (sublen == 0)
3866                                                         regs[rd] = len;
3867                                                 break;
3868                                         }
3869                                 }
3870
3871                                 addr = orig + pos;
3872                         }
3873                 }
3874
3875                 for (regs[rd] = notfound; addr != limit; addr += inc) {
3876                         if (dtrace_strncmp(addr, substr, sublen) == 0) {
3877                                 if (subr != DIF_SUBR_STRSTR) {
3878                                         /*
3879                                          * As D index() and rindex() are
3880                                          * modeled on Perl (and not on awk),
3881                                          * we return a zero-based (and not a
3882                                          * one-based) index.  (For you Perl
3883                                          * weenies: no, we're not going to add
3884                                          * $[ -- and shouldn't you be at a con
3885                                          * or something?)
3886                                          */
3887                                         regs[rd] = (uintptr_t)(addr - orig);
3888                                         break;
3889                                 }
3890
3891                                 ASSERT(subr == DIF_SUBR_STRSTR);
3892                                 regs[rd] = (uintptr_t)addr;
3893                                 break;
3894                         }
3895                 }
3896
3897                 break;
3898         }
3899
3900         case DIF_SUBR_STRTOK: {
3901                 uintptr_t addr = tupregs[0].dttk_value;
3902                 uintptr_t tokaddr = tupregs[1].dttk_value;
3903                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3904                 uintptr_t limit, toklimit = tokaddr + size;
3905                 uint8_t c = 0, tokmap[32];       /* 256 / 8 */
3906                 char *dest = (char *)mstate->dtms_scratch_ptr;
3907                 int i;
3908
3909                 /*
3910                  * Check both the token buffer and (later) the input buffer,
3911                  * since both could be non-scratch addresses.
3912                  */
3913                 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3914                         regs[rd] = 0;
3915                         break;
3916                 }
3917
3918                 if (!DTRACE_INSCRATCH(mstate, size)) {
3919                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3920                         regs[rd] = 0;
3921                         break;
3922                 }
3923
3924                 if (addr == 0) {
3925                         /*
3926                          * If the address specified is NULL, we use our saved
3927                          * strtok pointer from the mstate.  Note that this
3928                          * means that the saved strtok pointer is _only_
3929                          * valid within multiple enablings of the same probe --
3930                          * it behaves like an implicit clause-local variable.
3931                          */
3932                         addr = mstate->dtms_strtok;
3933                 } else {
3934                         /*
3935                          * If the user-specified address is non-NULL we must
3936                          * access check it.  This is the only time we have
3937                          * a chance to do so, since this address may reside
3938                          * in the string table of this clause-- future calls
3939                          * (when we fetch addr from mstate->dtms_strtok)
3940                          * would fail this access check.
3941                          */
3942                         if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3943                                 regs[rd] = 0;
3944                                 break;
3945                         }
3946                 }
3947
3948                 /*
3949                  * First, zero the token map, and then process the token
3950                  * string -- setting a bit in the map for every character
3951                  * found in the token string.
3952                  */
3953                 for (i = 0; i < sizeof (tokmap); i++)
3954                         tokmap[i] = 0;
3955
3956                 for (; tokaddr < toklimit; tokaddr++) {
3957                         if ((c = dtrace_load8(tokaddr)) == '\0')
3958                                 break;
3959
3960                         ASSERT((c >> 3) < sizeof (tokmap));
3961                         tokmap[c >> 3] |= (1 << (c & 0x7));
3962                 }
3963
3964                 for (limit = addr + size; addr < limit; addr++) {
3965                         /*
3966                          * We're looking for a character that is _not_ contained
3967                          * in the token string.
3968                          */
3969                         if ((c = dtrace_load8(addr)) == '\0')
3970                                 break;
3971
3972                         if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3973                                 break;
3974                 }
3975
3976                 if (c == '\0') {
3977                         /*
3978                          * We reached the end of the string without finding
3979                          * any character that was not in the token string.
3980                          * We return NULL in this case, and we set the saved
3981                          * address to NULL as well.
3982                          */
3983                         regs[rd] = 0;
3984                         mstate->dtms_strtok = 0;
3985                         break;
3986                 }
3987
3988                 /*
3989                  * From here on, we're copying into the destination string.
3990                  */
3991                 for (i = 0; addr < limit && i < size - 1; addr++) {
3992                         if ((c = dtrace_load8(addr)) == '\0')
3993                                 break;
3994
3995                         if (tokmap[c >> 3] & (1 << (c & 0x7)))
3996                                 break;
3997
3998                         ASSERT(i < size);
3999                         dest[i++] = c;
4000                 }
4001
4002                 ASSERT(i < size);
4003                 dest[i] = '\0';
4004                 regs[rd] = (uintptr_t)dest;
4005                 mstate->dtms_scratch_ptr += size;
4006                 mstate->dtms_strtok = addr;
4007                 break;
4008         }
4009
4010         case DIF_SUBR_SUBSTR: {
4011                 uintptr_t s = tupregs[0].dttk_value;
4012                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4013                 char *d = (char *)mstate->dtms_scratch_ptr;
4014                 int64_t index = (int64_t)tupregs[1].dttk_value;
4015                 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4016                 size_t len = dtrace_strlen((char *)s, size);
4017                 int64_t i = 0;
4018
4019                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4020                         regs[rd] = 0;
4021                         break;
4022                 }
4023
4024                 if (!DTRACE_INSCRATCH(mstate, size)) {
4025                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4026                         regs[rd] = 0;
4027                         break;
4028                 }
4029
4030                 if (nargs <= 2)
4031                         remaining = (int64_t)size;
4032
4033                 if (index < 0) {
4034                         index += len;
4035
4036                         if (index < 0 && index + remaining > 0) {
4037                                 remaining += index;
4038                                 index = 0;
4039                         }
4040                 }
4041
4042                 if (index >= len || index < 0) {
4043                         remaining = 0;
4044                 } else if (remaining < 0) {
4045                         remaining += len - index;
4046                 } else if (index + remaining > size) {
4047                         remaining = size - index;
4048                 }
4049
4050                 for (i = 0; i < remaining; i++) {
4051                         if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4052                                 break;
4053                 }
4054
4055                 d[i] = '\0';
4056
4057                 mstate->dtms_scratch_ptr += size;
4058                 regs[rd] = (uintptr_t)d;
4059                 break;
4060         }
4061
4062         case DIF_SUBR_TOUPPER:
4063         case DIF_SUBR_TOLOWER: {
4064                 uintptr_t s = tupregs[0].dttk_value;
4065                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4066                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4067                 size_t len = dtrace_strlen((char *)s, size);
4068                 char lower, upper, convert;
4069                 int64_t i;
4070
4071                 if (subr == DIF_SUBR_TOUPPER) {
4072                         lower = 'a';
4073                         upper = 'z';
4074                         convert = 'A';
4075                 } else {
4076                         lower = 'A';
4077                         upper = 'Z';
4078                         convert = 'a';
4079                 }
4080
4081                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4082                         regs[rd] = 0;
4083                         break;
4084                 }
4085
4086                 if (!DTRACE_INSCRATCH(mstate, size)) {
4087                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4088                         regs[rd] = 0;
4089                         break;
4090                 }
4091
4092                 for (i = 0; i < size - 1; i++) {
4093                         if ((c = dtrace_load8(s + i)) == '\0')
4094                                 break;
4095
4096                         if (c >= lower && c <= upper)
4097                                 c = convert + (c - lower);
4098
4099                         dest[i] = c;
4100                 }
4101
4102                 ASSERT(i < size);
4103                 dest[i] = '\0';
4104                 regs[rd] = (uintptr_t)dest;
4105                 mstate->dtms_scratch_ptr += size;
4106                 break;
4107         }
4108
4109 #if defined(sun)
4110         case DIF_SUBR_GETMAJOR:
4111 #ifdef _LP64
4112                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4113 #else
4114                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4115 #endif
4116                 break;
4117
4118         case DIF_SUBR_GETMINOR:
4119 #ifdef _LP64
4120                 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4121 #else
4122                 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4123 #endif
4124                 break;
4125
4126         case DIF_SUBR_DDI_PATHNAME: {
4127                 /*
4128                  * This one is a galactic mess.  We are going to roughly
4129                  * emulate ddi_pathname(), but it's made more complicated
4130                  * by the fact that we (a) want to include the minor name and
4131                  * (b) must proceed iteratively instead of recursively.
4132                  */
4133                 uintptr_t dest = mstate->dtms_scratch_ptr;
4134                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4135                 char *start = (char *)dest, *end = start + size - 1;
4136                 uintptr_t daddr = tupregs[0].dttk_value;
4137                 int64_t minor = (int64_t)tupregs[1].dttk_value;
4138                 char *s;
4139                 int i, len, depth = 0;
4140
4141                 /*
4142                  * Due to all the pointer jumping we do and context we must
4143                  * rely upon, we just mandate that the user must have kernel
4144                  * read privileges to use this routine.
4145                  */
4146                 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4147                         *flags |= CPU_DTRACE_KPRIV;
4148                         *illval = daddr;
4149                         regs[rd] = 0;
4150                 }
4151
4152                 if (!DTRACE_INSCRATCH(mstate, size)) {
4153                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4154                         regs[rd] = 0;
4155                         break;
4156                 }
4157
4158                 *end = '\0';
4159
4160                 /*
4161                  * We want to have a name for the minor.  In order to do this,
4162                  * we need to walk the minor list from the devinfo.  We want
4163                  * to be sure that we don't infinitely walk a circular list,
4164                  * so we check for circularity by sending a scout pointer
4165                  * ahead two elements for every element that we iterate over;
4166                  * if the list is circular, these will ultimately point to the
4167                  * same element.  You may recognize this little trick as the
4168                  * answer to a stupid interview question -- one that always
4169                  * seems to be asked by those who had to have it laboriously
4170                  * explained to them, and who can't even concisely describe
4171                  * the conditions under which one would be forced to resort to
4172                  * this technique.  Needless to say, those conditions are
4173                  * found here -- and probably only here.  Is this the only use
4174                  * of this infamous trick in shipping, production code?  If it
4175                  * isn't, it probably should be...
4176                  */
4177                 if (minor != -1) {
4178                         uintptr_t maddr = dtrace_loadptr(daddr +
4179                             offsetof(struct dev_info, devi_minor));
4180
4181                         uintptr_t next = offsetof(struct ddi_minor_data, next);
4182                         uintptr_t name = offsetof(struct ddi_minor_data,
4183                             d_minor) + offsetof(struct ddi_minor, name);
4184                         uintptr_t dev = offsetof(struct ddi_minor_data,
4185                             d_minor) + offsetof(struct ddi_minor, dev);
4186                         uintptr_t scout;
4187
4188                         if (maddr != NULL)
4189                                 scout = dtrace_loadptr(maddr + next);
4190
4191                         while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4192                                 uint64_t m;
4193 #ifdef _LP64
4194                                 m = dtrace_load64(maddr + dev) & MAXMIN64;
4195 #else
4196                                 m = dtrace_load32(maddr + dev) & MAXMIN;
4197 #endif
4198                                 if (m != minor) {
4199                                         maddr = dtrace_loadptr(maddr + next);
4200
4201                                         if (scout == NULL)
4202                                                 continue;
4203
4204                                         scout = dtrace_loadptr(scout + next);
4205
4206                                         if (scout == NULL)
4207                                                 continue;
4208
4209                                         scout = dtrace_loadptr(scout + next);
4210
4211                                         if (scout == NULL)
4212                                                 continue;
4213
4214                                         if (scout == maddr) {
4215                                                 *flags |= CPU_DTRACE_ILLOP;
4216                                                 break;
4217                                         }
4218
4219                                         continue;
4220                                 }
4221
4222                                 /*
4223                                  * We have the minor data.  Now we need to
4224                                  * copy the minor's name into the end of the
4225                                  * pathname.
4226                                  */
4227                                 s = (char *)dtrace_loadptr(maddr + name);
4228                                 len = dtrace_strlen(s, size);
4229
4230                                 if (*flags & CPU_DTRACE_FAULT)
4231                                         break;
4232
4233                                 if (len != 0) {
4234                                         if ((end -= (len + 1)) < start)
4235                                                 break;
4236
4237                                         *end = ':';
4238                                 }
4239
4240                                 for (i = 1; i <= len; i++)
4241                                         end[i] = dtrace_load8((uintptr_t)s++);
4242                                 break;
4243                         }
4244                 }
4245
4246                 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4247                         ddi_node_state_t devi_state;
4248
4249                         devi_state = dtrace_load32(daddr +
4250                             offsetof(struct dev_info, devi_node_state));
4251
4252                         if (*flags & CPU_DTRACE_FAULT)
4253                                 break;
4254
4255                         if (devi_state >= DS_INITIALIZED) {
4256                                 s = (char *)dtrace_loadptr(daddr +
4257                                     offsetof(struct dev_info, devi_addr));
4258                                 len = dtrace_strlen(s, size);
4259
4260                                 if (*flags & CPU_DTRACE_FAULT)
4261                                         break;
4262
4263                                 if (len != 0) {
4264                                         if ((end -= (len + 1)) < start)
4265                                                 break;
4266
4267                                         *end = '@';
4268                                 }
4269
4270                                 for (i = 1; i <= len; i++)
4271                                         end[i] = dtrace_load8((uintptr_t)s++);
4272                         }
4273
4274                         /*
4275                          * Now for the node name...
4276                          */
4277                         s = (char *)dtrace_loadptr(daddr +
4278                             offsetof(struct dev_info, devi_node_name));
4279
4280                         daddr = dtrace_loadptr(daddr +
4281                             offsetof(struct dev_info, devi_parent));
4282
4283                         /*
4284                          * If our parent is NULL (that is, if we're the root
4285                          * node), we're going to use the special path
4286                          * "devices".
4287                          */
4288                         if (daddr == 0)
4289                                 s = "devices";
4290
4291                         len = dtrace_strlen(s, size);
4292                         if (*flags & CPU_DTRACE_FAULT)
4293                                 break;
4294
4295                         if ((end -= (len + 1)) < start)
4296                                 break;
4297
4298                         for (i = 1; i <= len; i++)
4299                                 end[i] = dtrace_load8((uintptr_t)s++);
4300                         *end = '/';
4301
4302                         if (depth++ > dtrace_devdepth_max) {
4303                                 *flags |= CPU_DTRACE_ILLOP;
4304                                 break;
4305                         }
4306                 }
4307
4308                 if (end < start)
4309                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4310
4311                 if (daddr == 0) {
4312                         regs[rd] = (uintptr_t)end;
4313                         mstate->dtms_scratch_ptr += size;
4314                 }
4315
4316                 break;
4317         }
4318 #endif
4319
4320         case DIF_SUBR_STRJOIN: {
4321                 char *d = (char *)mstate->dtms_scratch_ptr;
4322                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4323                 uintptr_t s1 = tupregs[0].dttk_value;
4324                 uintptr_t s2 = tupregs[1].dttk_value;
4325                 int i = 0;
4326
4327                 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4328                     !dtrace_strcanload(s2, size, mstate, vstate)) {
4329                         regs[rd] = 0;
4330                         break;
4331                 }
4332
4333                 if (!DTRACE_INSCRATCH(mstate, size)) {
4334                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4335                         regs[rd] = 0;
4336                         break;
4337                 }
4338
4339                 for (;;) {
4340                         if (i >= size) {
4341                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4342                                 regs[rd] = 0;
4343                                 break;
4344                         }
4345
4346                         if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4347                                 i--;
4348                                 break;
4349                         }
4350                 }
4351
4352                 for (;;) {
4353                         if (i >= size) {
4354                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4355                                 regs[rd] = 0;
4356                                 break;
4357                         }
4358
4359                         if ((d[i++] = dtrace_load8(s2++)) == '\0')
4360                                 break;
4361                 }
4362
4363                 if (i < size) {
4364                         mstate->dtms_scratch_ptr += i;
4365                         regs[rd] = (uintptr_t)d;
4366                 }
4367
4368                 break;
4369         }
4370
4371         case DIF_SUBR_LLTOSTR: {
4372                 int64_t i = (int64_t)tupregs[0].dttk_value;
4373                 uint64_t val, digit;
4374                 uint64_t size = 65;     /* enough room for 2^64 in binary */
4375                 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4376                 int base = 10;
4377
4378                 if (nargs > 1) {
4379                         if ((base = tupregs[1].dttk_value) <= 1 ||
4380                             base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4381                                 *flags |= CPU_DTRACE_ILLOP;
4382                                 break;
4383                         }
4384                 }
4385
4386                 val = (base == 10 && i < 0) ? i * -1 : i;
4387
4388                 if (!DTRACE_INSCRATCH(mstate, size)) {
4389                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4390                         regs[rd] = 0;
4391                         break;
4392                 }
4393
4394                 for (*end-- = '\0'; val; val /= base) {
4395                         if ((digit = val % base) <= '9' - '0') {
4396                                 *end-- = '0' + digit;
4397                         } else {
4398                                 *end-- = 'a' + (digit - ('9' - '0') - 1);
4399                         }
4400                 }
4401
4402                 if (i == 0 && base == 16)
4403                         *end-- = '0';
4404
4405                 if (base == 16)
4406                         *end-- = 'x';
4407
4408                 if (i == 0 || base == 8 || base == 16)
4409                         *end-- = '0';
4410
4411                 if (i < 0 && base == 10)
4412                         *end-- = '-';
4413
4414                 regs[rd] = (uintptr_t)end + 1;
4415                 mstate->dtms_scratch_ptr += size;
4416                 break;
4417         }
4418
4419         case DIF_SUBR_HTONS:
4420         case DIF_SUBR_NTOHS:
4421 #if BYTE_ORDER == BIG_ENDIAN
4422                 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4423 #else
4424                 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4425 #endif
4426                 break;
4427
4428
4429         case DIF_SUBR_HTONL:
4430         case DIF_SUBR_NTOHL:
4431 #if BYTE_ORDER == BIG_ENDIAN
4432                 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4433 #else
4434                 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4435 #endif
4436                 break;
4437
4438
4439         case DIF_SUBR_HTONLL:
4440         case DIF_SUBR_NTOHLL:
4441 #if BYTE_ORDER == BIG_ENDIAN
4442                 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4443 #else
4444                 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4445 #endif
4446                 break;
4447
4448
4449         case DIF_SUBR_DIRNAME:
4450         case DIF_SUBR_BASENAME: {
4451                 char *dest = (char *)mstate->dtms_scratch_ptr;
4452                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4453                 uintptr_t src = tupregs[0].dttk_value;
4454                 int i, j, len = dtrace_strlen((char *)src, size);
4455                 int lastbase = -1, firstbase = -1, lastdir = -1;
4456                 int start, end;
4457
4458                 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4459                         regs[rd] = 0;
4460                         break;
4461                 }
4462
4463                 if (!DTRACE_INSCRATCH(mstate, size)) {
4464                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4465                         regs[rd] = 0;
4466                         break;
4467                 }
4468
4469                 /*
4470                  * The basename and dirname for a zero-length string is
4471                  * defined to be "."
4472                  */
4473                 if (len == 0) {
4474                         len = 1;
4475                         src = (uintptr_t)".";
4476                 }
4477
4478                 /*
4479                  * Start from the back of the string, moving back toward the
4480                  * front until we see a character that isn't a slash.  That
4481                  * character is the last character in the basename.
4482                  */
4483                 for (i = len - 1; i >= 0; i--) {
4484                         if (dtrace_load8(src + i) != '/')
4485                                 break;
4486                 }
4487
4488                 if (i >= 0)
4489                         lastbase = i;
4490
4491                 /*
4492                  * Starting from the last character in the basename, move
4493                  * towards the front until we find a slash.  The character
4494                  * that we processed immediately before that is the first
4495                  * character in the basename.
4496                  */
4497                 for (; i >= 0; i--) {
4498                         if (dtrace_load8(src + i) == '/')
4499                                 break;
4500                 }
4501
4502                 if (i >= 0)
4503                         firstbase = i + 1;
4504
4505                 /*
4506                  * Now keep going until we find a non-slash character.  That
4507                  * character is the last character in the dirname.
4508                  */
4509                 for (; i >= 0; i--) {
4510                         if (dtrace_load8(src + i) != '/')
4511                                 break;
4512                 }
4513
4514                 if (i >= 0)
4515                         lastdir = i;
4516
4517                 ASSERT(!(lastbase == -1 && firstbase != -1));
4518                 ASSERT(!(firstbase == -1 && lastdir != -1));
4519
4520                 if (lastbase == -1) {
4521                         /*
4522                          * We didn't find a non-slash character.  We know that
4523                          * the length is non-zero, so the whole string must be
4524                          * slashes.  In either the dirname or the basename
4525                          * case, we return '/'.
4526                          */
4527                         ASSERT(firstbase == -1);
4528                         firstbase = lastbase = lastdir = 0;
4529                 }
4530
4531                 if (firstbase == -1) {
4532                         /*
4533                          * The entire string consists only of a basename
4534                          * component.  If we're looking for dirname, we need
4535                          * to change our string to be just "."; if we're
4536                          * looking for a basename, we'll just set the first
4537                          * character of the basename to be 0.
4538                          */
4539                         if (subr == DIF_SUBR_DIRNAME) {
4540                                 ASSERT(lastdir == -1);
4541                                 src = (uintptr_t)".";
4542                                 lastdir = 0;
4543                         } else {
4544                                 firstbase = 0;
4545                         }
4546                 }
4547
4548                 if (subr == DIF_SUBR_DIRNAME) {
4549                         if (lastdir == -1) {
4550                                 /*
4551                                  * We know that we have a slash in the name --
4552                                  * or lastdir would be set to 0, above.  And
4553                                  * because lastdir is -1, we know that this
4554                                  * slash must be the first character.  (That
4555                                  * is, the full string must be of the form
4556                                  * "/basename".)  In this case, the last
4557                                  * character of the directory name is 0.
4558                                  */
4559                                 lastdir = 0;
4560                         }
4561
4562                         start = 0;
4563                         end = lastdir;
4564                 } else {
4565                         ASSERT(subr == DIF_SUBR_BASENAME);
4566                         ASSERT(firstbase != -1 && lastbase != -1);
4567                         start = firstbase;
4568                         end = lastbase;
4569                 }
4570
4571                 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4572                         dest[j] = dtrace_load8(src + i);
4573
4574                 dest[j] = '\0';
4575                 regs[rd] = (uintptr_t)dest;
4576                 mstate->dtms_scratch_ptr += size;
4577                 break;
4578         }
4579
4580         case DIF_SUBR_CLEANPATH: {
4581                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4582                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4583                 uintptr_t src = tupregs[0].dttk_value;
4584                 int i = 0, j = 0;
4585
4586                 if (!dtrace_strcanload(src, size, mstate, vstate)) {
4587                         regs[rd] = 0;
4588                         break;
4589                 }
4590
4591                 if (!DTRACE_INSCRATCH(mstate, size)) {
4592                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4593                         regs[rd] = 0;
4594                         break;
4595                 }
4596
4597                 /*
4598                  * Move forward, loading each character.
4599                  */
4600                 do {
4601                         c = dtrace_load8(src + i++);
4602 next:
4603                         if (j + 5 >= size)      /* 5 = strlen("/..c\0") */
4604                                 break;
4605
4606                         if (c != '/') {
4607                                 dest[j++] = c;
4608                                 continue;
4609                         }
4610
4611                         c = dtrace_load8(src + i++);
4612
4613                         if (c == '/') {
4614                                 /*
4615                                  * We have two slashes -- we can just advance
4616                                  * to the next character.
4617                                  */
4618                                 goto next;
4619                         }
4620
4621                         if (c != '.') {
4622                                 /*
4623                                  * This is not "." and it's not ".." -- we can
4624                                  * just store the "/" and this character and
4625                                  * drive on.
4626                                  */
4627                                 dest[j++] = '/';
4628                                 dest[j++] = c;
4629                                 continue;
4630                         }
4631
4632                         c = dtrace_load8(src + i++);
4633
4634                         if (c == '/') {
4635                                 /*
4636                                  * This is a "/./" component.  We're not going
4637                                  * to store anything in the destination buffer;
4638                                  * we're just going to go to the next component.
4639                                  */
4640                                 goto next;
4641                         }
4642
4643                         if (c != '.') {
4644                                 /*
4645                                  * This is not ".." -- we can just store the
4646                                  * "/." and this character and continue
4647                                  * processing.
4648                                  */
4649                                 dest[j++] = '/';
4650                                 dest[j++] = '.';
4651                                 dest[j++] = c;
4652                                 continue;
4653                         }
4654
4655                         c = dtrace_load8(src + i++);
4656
4657                         if (c != '/' && c != '\0') {
4658                                 /*
4659                                  * This is not ".." -- it's "..[mumble]".
4660                                  * We'll store the "/.." and this character
4661                                  * and continue processing.
4662                                  */
4663                                 dest[j++] = '/';
4664                                 dest[j++] = '.';
4665                                 dest[j++] = '.';
4666                                 dest[j++] = c;
4667                                 continue;
4668                         }
4669
4670                         /*
4671                          * This is "/../" or "/..\0".  We need to back up
4672                          * our destination pointer until we find a "/".
4673                          */
4674                         i--;
4675                         while (j != 0 && dest[--j] != '/')
4676                                 continue;
4677
4678                         if (c == '\0')
4679                                 dest[++j] = '/';
4680                 } while (c != '\0');
4681
4682                 dest[j] = '\0';
4683                 regs[rd] = (uintptr_t)dest;
4684                 mstate->dtms_scratch_ptr += size;
4685                 break;
4686         }
4687
4688         case DIF_SUBR_INET_NTOA:
4689         case DIF_SUBR_INET_NTOA6:
4690         case DIF_SUBR_INET_NTOP: {
4691                 size_t size;
4692                 int af, argi, i;
4693                 char *base, *end;
4694
4695                 if (subr == DIF_SUBR_INET_NTOP) {
4696                         af = (int)tupregs[0].dttk_value;
4697                         argi = 1;
4698                 } else {
4699                         af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4700                         argi = 0;
4701                 }
4702
4703                 if (af == AF_INET) {
4704                         ipaddr_t ip4;
4705                         uint8_t *ptr8, val;
4706
4707                         /*
4708                          * Safely load the IPv4 address.
4709                          */
4710                         ip4 = dtrace_load32(tupregs[argi].dttk_value);
4711
4712                         /*
4713                          * Check an IPv4 string will fit in scratch.
4714                          */
4715                         size = INET_ADDRSTRLEN;
4716                         if (!DTRACE_INSCRATCH(mstate, size)) {
4717                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4718                                 regs[rd] = 0;
4719                                 break;
4720                         }
4721                         base = (char *)mstate->dtms_scratch_ptr;
4722                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
4723
4724                         /*
4725                          * Stringify as a dotted decimal quad.
4726                          */
4727                         *end-- = '\0';
4728                         ptr8 = (uint8_t *)&ip4;
4729                         for (i = 3; i >= 0; i--) {
4730                                 val = ptr8[i];
4731
4732                                 if (val == 0) {
4733                                         *end-- = '0';
4734                                 } else {
4735                                         for (; val; val /= 10) {
4736                                                 *end-- = '0' + (val % 10);
4737                                         }
4738                                 }
4739
4740                                 if (i > 0)
4741                                         *end-- = '.';
4742                         }
4743                         ASSERT(end + 1 >= base);
4744
4745                 } else if (af == AF_INET6) {
4746                         struct in6_addr ip6;
4747                         int firstzero, tryzero, numzero, v6end;
4748                         uint16_t val;
4749                         const char digits[] = "0123456789abcdef";
4750
4751                         /*
4752                          * Stringify using RFC 1884 convention 2 - 16 bit
4753                          * hexadecimal values with a zero-run compression.
4754                          * Lower case hexadecimal digits are used.
4755                          *      eg, fe80::214:4fff:fe0b:76c8.
4756                          * The IPv4 embedded form is returned for inet_ntop,
4757                          * just the IPv4 string is returned for inet_ntoa6.
4758                          */
4759
4760                         /*
4761                          * Safely load the IPv6 address.
4762                          */
4763                         dtrace_bcopy(
4764                             (void *)(uintptr_t)tupregs[argi].dttk_value,
4765                             (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4766
4767                         /*
4768                          * Check an IPv6 string will fit in scratch.
4769                          */
4770                         size = INET6_ADDRSTRLEN;
4771                         if (!DTRACE_INSCRATCH(mstate, size)) {
4772                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4773                                 regs[rd] = 0;
4774                                 break;
4775                         }
4776                         base = (char *)mstate->dtms_scratch_ptr;
4777                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
4778                         *end-- = '\0';
4779
4780                         /*
4781                          * Find the longest run of 16 bit zero values
4782                          * for the single allowed zero compression - "::".
4783                          */
4784                         firstzero = -1;
4785                         tryzero = -1;
4786                         numzero = 1;
4787                         for (i = 0; i < sizeof (struct in6_addr); i++) {
4788 #if defined(sun)
4789                                 if (ip6._S6_un._S6_u8[i] == 0 &&
4790 #else
4791                                 if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4792 #endif
4793                                     tryzero == -1 && i % 2 == 0) {
4794                                         tryzero = i;
4795                                         continue;
4796                                 }
4797
4798                                 if (tryzero != -1 &&
4799 #if defined(sun)
4800                                     (ip6._S6_un._S6_u8[i] != 0 ||
4801 #else
4802                                     (ip6.__u6_addr.__u6_addr8[i] != 0 ||
4803 #endif
4804                                     i == sizeof (struct in6_addr) - 1)) {
4805
4806                                         if (i - tryzero <= numzero) {
4807                                                 tryzero = -1;
4808                                                 continue;
4809                                         }
4810
4811                                         firstzero = tryzero;
4812                                         numzero = i - i % 2 - tryzero;
4813                                         tryzero = -1;
4814
4815 #if defined(sun)
4816                                         if (ip6._S6_un._S6_u8[i] == 0 &&
4817 #else
4818                                         if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4819 #endif
4820                                             i == sizeof (struct in6_addr) - 1)
4821                                                 numzero += 2;
4822                                 }
4823                         }
4824                         ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4825
4826                         /*
4827                          * Check for an IPv4 embedded address.
4828                          */
4829                         v6end = sizeof (struct in6_addr) - 2;
4830                         if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4831                             IN6_IS_ADDR_V4COMPAT(&ip6)) {
4832                                 for (i = sizeof (struct in6_addr) - 1;
4833                                     i >= DTRACE_V4MAPPED_OFFSET; i--) {
4834                                         ASSERT(end >= base);
4835
4836 #if defined(sun)
4837                                         val = ip6._S6_un._S6_u8[i];
4838 #else
4839                                         val = ip6.__u6_addr.__u6_addr8[i];
4840 #endif
4841
4842                                         if (val == 0) {
4843                                                 *end-- = '0';
4844                                         } else {
4845                                                 for (; val; val /= 10) {
4846                                                         *end-- = '0' + val % 10;
4847                                                 }
4848                                         }
4849
4850                                         if (i > DTRACE_V4MAPPED_OFFSET)
4851                                                 *end-- = '.';
4852                                 }
4853
4854                                 if (subr == DIF_SUBR_INET_NTOA6)
4855                                         goto inetout;
4856
4857                                 /*
4858                                  * Set v6end to skip the IPv4 address that
4859                                  * we have already stringified.
4860                                  */
4861                                 v6end = 10;
4862                         }
4863
4864                         /*
4865                          * Build the IPv6 string by working through the
4866                          * address in reverse.
4867                          */
4868                         for (i = v6end; i >= 0; i -= 2) {
4869                                 ASSERT(end >= base);
4870
4871                                 if (i == firstzero + numzero - 2) {
4872                                         *end-- = ':';
4873                                         *end-- = ':';
4874                                         i -= numzero - 2;
4875                                         continue;
4876                                 }
4877
4878                                 if (i < 14 && i != firstzero - 2)
4879                                         *end-- = ':';
4880
4881 #if defined(sun)
4882                                 val = (ip6._S6_un._S6_u8[i] << 8) +
4883                                     ip6._S6_un._S6_u8[i + 1];
4884 #else
4885                                 val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
4886                                     ip6.__u6_addr.__u6_addr8[i + 1];
4887 #endif
4888
4889                                 if (val == 0) {
4890                                         *end-- = '0';
4891                                 } else {
4892                                         for (; val; val /= 16) {
4893                                                 *end-- = digits[val % 16];
4894                                         }
4895                                 }
4896                         }
4897                         ASSERT(end + 1 >= base);
4898
4899                 } else {
4900                         /*
4901                          * The user didn't use AH_INET or AH_INET6.
4902                          */
4903                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4904                         regs[rd] = 0;
4905                         break;
4906                 }
4907
4908 inetout:        regs[rd] = (uintptr_t)end + 1;
4909                 mstate->dtms_scratch_ptr += size;
4910                 break;
4911         }
4912
4913         case DIF_SUBR_MEMREF: {
4914                 uintptr_t size = 2 * sizeof(uintptr_t);
4915                 uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4916                 size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
4917
4918                 /* address and length */
4919                 memref[0] = tupregs[0].dttk_value;
4920                 memref[1] = tupregs[1].dttk_value;
4921
4922                 regs[rd] = (uintptr_t) memref;
4923                 mstate->dtms_scratch_ptr += scratch_size;
4924                 break;
4925         }
4926
4927 #if !defined(sun)
4928         case DIF_SUBR_MEMSTR: {
4929                 char *str = (char *)mstate->dtms_scratch_ptr;
4930                 uintptr_t mem = tupregs[0].dttk_value;
4931                 char c = tupregs[1].dttk_value;
4932                 size_t size = tupregs[2].dttk_value;
4933                 uint8_t n;
4934                 int i;
4935
4936                 regs[rd] = 0;
4937
4938                 if (size == 0)
4939                         break;
4940
4941                 if (!dtrace_canload(mem, size - 1, mstate, vstate))
4942                         break;
4943
4944                 if (!DTRACE_INSCRATCH(mstate, size)) {
4945                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4946                         break;
4947                 }
4948
4949                 if (dtrace_memstr_max != 0 && size > dtrace_memstr_max) {
4950                         *flags |= CPU_DTRACE_ILLOP;
4951                         break;
4952                 }
4953
4954                 for (i = 0; i < size - 1; i++) {
4955                         n = dtrace_load8(mem++);
4956                         str[i] = (n == 0) ? c : n;
4957                 }
4958                 str[size - 1] = 0;
4959
4960                 regs[rd] = (uintptr_t)str;
4961                 mstate->dtms_scratch_ptr += size;
4962                 break;
4963         }
4964 #endif
4965
4966         case DIF_SUBR_TYPEREF: {
4967                 uintptr_t size = 4 * sizeof(uintptr_t);
4968                 uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4969                 size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
4970
4971                 /* address, num_elements, type_str, type_len */
4972                 typeref[0] = tupregs[0].dttk_value;
4973                 typeref[1] = tupregs[1].dttk_value;
4974                 typeref[2] = tupregs[2].dttk_value;
4975                 typeref[3] = tupregs[3].dttk_value;
4976
4977                 regs[rd] = (uintptr_t) typeref;
4978                 mstate->dtms_scratch_ptr += scratch_size;
4979                 break;
4980         }
4981         }
4982 }
4983
4984 /*
4985  * Emulate the execution of DTrace IR instructions specified by the given
4986  * DIF object.  This function is deliberately void of assertions as all of
4987  * the necessary checks are handled by a call to dtrace_difo_validate().
4988  */
4989 static uint64_t
4990 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4991     dtrace_vstate_t *vstate, dtrace_state_t *state)
4992 {
4993         const dif_instr_t *text = difo->dtdo_buf;
4994         const uint_t textlen = difo->dtdo_len;
4995         const char *strtab = difo->dtdo_strtab;
4996         const uint64_t *inttab = difo->dtdo_inttab;
4997
4998         uint64_t rval = 0;
4999         dtrace_statvar_t *svar;
5000         dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5001         dtrace_difv_t *v;
5002         volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5003         volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
5004
5005         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5006         uint64_t regs[DIF_DIR_NREGS];
5007         uint64_t *tmp;
5008
5009         uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5010         int64_t cc_r;
5011         uint_t pc = 0, id, opc = 0;
5012         uint8_t ttop = 0;
5013         dif_instr_t instr;
5014         uint_t r1, r2, rd;
5015
5016         /*
5017          * We stash the current DIF object into the machine state: we need it
5018          * for subsequent access checking.
5019          */
5020         mstate->dtms_difo = difo;
5021
5022         regs[DIF_REG_R0] = 0;           /* %r0 is fixed at zero */
5023
5024         while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5025                 opc = pc;
5026
5027                 instr = text[pc++];
5028                 r1 = DIF_INSTR_R1(instr);
5029                 r2 = DIF_INSTR_R2(instr);
5030                 rd = DIF_INSTR_RD(instr);
5031
5032                 switch (DIF_INSTR_OP(instr)) {
5033                 case DIF_OP_OR:
5034                         regs[rd] = regs[r1] | regs[r2];
5035                         break;
5036                 case DIF_OP_XOR:
5037                         regs[rd] = regs[r1] ^ regs[r2];
5038                         break;
5039                 case DIF_OP_AND:
5040                         regs[rd] = regs[r1] & regs[r2];
5041                         break;
5042                 case DIF_OP_SLL:
5043                         regs[rd] = regs[r1] << regs[r2];
5044                         break;
5045                 case DIF_OP_SRL:
5046                         regs[rd] = regs[r1] >> regs[r2];
5047                         break;
5048                 case DIF_OP_SUB:
5049                         regs[rd] = regs[r1] - regs[r2];
5050                         break;
5051                 case DIF_OP_ADD:
5052                         regs[rd] = regs[r1] + regs[r2];
5053                         break;
5054                 case DIF_OP_MUL:
5055                         regs[rd] = regs[r1] * regs[r2];
5056                         break;
5057                 case DIF_OP_SDIV:
5058                         if (regs[r2] == 0) {
5059                                 regs[rd] = 0;
5060                                 *flags |= CPU_DTRACE_DIVZERO;
5061                         } else {
5062                                 regs[rd] = (int64_t)regs[r1] /
5063                                     (int64_t)regs[r2];
5064                         }
5065                         break;
5066
5067                 case DIF_OP_UDIV:
5068                         if (regs[r2] == 0) {
5069                                 regs[rd] = 0;
5070                                 *flags |= CPU_DTRACE_DIVZERO;
5071                         } else {
5072                                 regs[rd] = regs[r1] / regs[r2];
5073                         }
5074                         break;
5075
5076                 case DIF_OP_SREM:
5077                         if (regs[r2] == 0) {
5078                                 regs[rd] = 0;
5079                                 *flags |= CPU_DTRACE_DIVZERO;
5080                         } else {
5081                                 regs[rd] = (int64_t)regs[r1] %
5082                                     (int64_t)regs[r2];
5083                         }
5084                         break;
5085
5086                 case DIF_OP_UREM:
5087                         if (regs[r2] == 0) {
5088                                 regs[rd] = 0;
5089                                 *flags |= CPU_DTRACE_DIVZERO;
5090                         } else {
5091                                 regs[rd] = regs[r1] % regs[r2];
5092                         }
5093                         break;
5094
5095                 case DIF_OP_NOT:
5096                         regs[rd] = ~regs[r1];
5097                         break;
5098                 case DIF_OP_MOV:
5099                         regs[rd] = regs[r1];
5100                         break;
5101                 case DIF_OP_CMP:
5102                         cc_r = regs[r1] - regs[r2];
5103                         cc_n = cc_r < 0;
5104                         cc_z = cc_r == 0;
5105                         cc_v = 0;
5106                         cc_c = regs[r1] < regs[r2];
5107                         break;
5108                 case DIF_OP_TST:
5109                         cc_n = cc_v = cc_c = 0;
5110                         cc_z = regs[r1] == 0;
5111                         break;
5112                 case DIF_OP_BA:
5113                         pc = DIF_INSTR_LABEL(instr);
5114                         break;
5115                 case DIF_OP_BE:
5116                         if (cc_z)
5117                                 pc = DIF_INSTR_LABEL(instr);
5118                         break;
5119                 case DIF_OP_BNE:
5120                         if (cc_z == 0)
5121                                 pc = DIF_INSTR_LABEL(instr);
5122                         break;
5123                 case DIF_OP_BG:
5124                         if ((cc_z | (cc_n ^ cc_v)) == 0)
5125                                 pc = DIF_INSTR_LABEL(instr);
5126                         break;
5127                 case DIF_OP_BGU:
5128                         if ((cc_c | cc_z) == 0)
5129                                 pc = DIF_INSTR_LABEL(instr);
5130                         break;
5131                 case DIF_OP_BGE:
5132                         if ((cc_n ^ cc_v) == 0)
5133                                 pc = DIF_INSTR_LABEL(instr);
5134                         break;
5135                 case DIF_OP_BGEU:
5136                         if (cc_c == 0)
5137                                 pc = DIF_INSTR_LABEL(instr);
5138                         break;
5139                 case DIF_OP_BL:
5140                         if (cc_n ^ cc_v)
5141                                 pc = DIF_INSTR_LABEL(instr);
5142                         break;
5143                 case DIF_OP_BLU:
5144                         if (cc_c)
5145                                 pc = DIF_INSTR_LABEL(instr);
5146                         break;
5147                 case DIF_OP_BLE:
5148                         if (cc_z | (cc_n ^ cc_v))
5149                                 pc = DIF_INSTR_LABEL(instr);
5150                         break;
5151                 case DIF_OP_BLEU:
5152                         if (cc_c | cc_z)
5153                                 pc = DIF_INSTR_LABEL(instr);
5154                         break;
5155                 case DIF_OP_RLDSB:
5156                         if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5157                                 *flags |= CPU_DTRACE_KPRIV;
5158                                 *illval = regs[r1];
5159                                 break;
5160                         }
5161                         /*FALLTHROUGH*/
5162                 case DIF_OP_LDSB:
5163                         regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5164                         break;
5165                 case DIF_OP_RLDSH:
5166                         if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5167                                 *flags |= CPU_DTRACE_KPRIV;
5168                                 *illval = regs[r1];
5169                                 break;
5170                         }
5171                         /*FALLTHROUGH*/
5172                 case DIF_OP_LDSH:
5173                         regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5174                         break;
5175                 case DIF_OP_RLDSW:
5176                         if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5177                                 *flags |= CPU_DTRACE_KPRIV;
5178                                 *illval = regs[r1];
5179                                 break;
5180                         }
5181                         /*FALLTHROUGH*/
5182                 case DIF_OP_LDSW:
5183                         regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5184                         break;
5185                 case DIF_OP_RLDUB:
5186                         if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5187                                 *flags |= CPU_DTRACE_KPRIV;
5188                                 *illval = regs[r1];
5189                                 break;
5190                         }
5191                         /*FALLTHROUGH*/
5192                 case DIF_OP_LDUB:
5193                         regs[rd] = dtrace_load8(regs[r1]);
5194                         break;
5195                 case DIF_OP_RLDUH:
5196                         if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5197                                 *flags |= CPU_DTRACE_KPRIV;
5198                                 *illval = regs[r1];
5199                                 break;
5200                         }
5201                         /*FALLTHROUGH*/
5202                 case DIF_OP_LDUH:
5203                         regs[rd] = dtrace_load16(regs[r1]);
5204                         break;
5205                 case DIF_OP_RLDUW:
5206                         if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5207                                 *flags |= CPU_DTRACE_KPRIV;
5208                                 *illval = regs[r1];
5209                                 break;
5210                         }
5211                         /*FALLTHROUGH*/
5212                 case DIF_OP_LDUW:
5213                         regs[rd] = dtrace_load32(regs[r1]);
5214                         break;
5215                 case DIF_OP_RLDX:
5216                         if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5217                                 *flags |= CPU_DTRACE_KPRIV;
5218                                 *illval = regs[r1];
5219                                 break;
5220                         }
5221                         /*FALLTHROUGH*/
5222                 case DIF_OP_LDX:
5223                         regs[rd] = dtrace_load64(regs[r1]);
5224                         break;
5225                 case DIF_OP_ULDSB:
5226                         regs[rd] = (int8_t)
5227                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5228                         break;
5229                 case DIF_OP_ULDSH:
5230                         regs[rd] = (int16_t)
5231                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5232                         break;
5233                 case DIF_OP_ULDSW:
5234                         regs[rd] = (int32_t)
5235                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5236                         break;
5237                 case DIF_OP_ULDUB:
5238                         regs[rd] =
5239                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5240                         break;
5241                 case DIF_OP_ULDUH:
5242                         regs[rd] =
5243                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5244                         break;
5245                 case DIF_OP_ULDUW:
5246                         regs[rd] =
5247                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5248                         break;
5249                 case DIF_OP_ULDX:
5250                         regs[rd] =
5251                             dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5252                         break;
5253                 case DIF_OP_RET:
5254                         rval = regs[rd];
5255                         pc = textlen;
5256                         break;
5257                 case DIF_OP_NOP:
5258                         break;
5259                 case DIF_OP_SETX:
5260                         regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5261                         break;
5262                 case DIF_OP_SETS:
5263                         regs[rd] = (uint64_t)(uintptr_t)
5264                             (strtab + DIF_INSTR_STRING(instr));
5265                         break;
5266                 case DIF_OP_SCMP: {
5267                         size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5268                         uintptr_t s1 = regs[r1];
5269                         uintptr_t s2 = regs[r2];
5270
5271                         if (s1 != 0 &&
5272                             !dtrace_strcanload(s1, sz, mstate, vstate))
5273                                 break;
5274                         if (s2 != 0 &&
5275                             !dtrace_strcanload(s2, sz, mstate, vstate))
5276                                 break;
5277
5278                         cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5279
5280                         cc_n = cc_r < 0;
5281                         cc_z = cc_r == 0;
5282                         cc_v = cc_c = 0;
5283                         break;
5284                 }
5285                 case DIF_OP_LDGA:
5286                         regs[rd] = dtrace_dif_variable(mstate, state,
5287                             r1, regs[r2]);
5288                         break;
5289                 case DIF_OP_LDGS:
5290                         id = DIF_INSTR_VAR(instr);
5291
5292                         if (id >= DIF_VAR_OTHER_UBASE) {
5293                                 uintptr_t a;
5294
5295                                 id -= DIF_VAR_OTHER_UBASE;
5296                                 svar = vstate->dtvs_globals[id];
5297                                 ASSERT(svar != NULL);
5298                                 v = &svar->dtsv_var;
5299
5300                                 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5301                                         regs[rd] = svar->dtsv_data;
5302                                         break;
5303                                 }
5304
5305                                 a = (uintptr_t)svar->dtsv_data;
5306
5307                                 if (*(uint8_t *)a == UINT8_MAX) {
5308                                         /*
5309                                          * If the 0th byte is set to UINT8_MAX
5310                                          * then this is to be treated as a
5311                                          * reference to a NULL variable.
5312                                          */
5313                                         regs[rd] = 0;
5314                                 } else {
5315                                         regs[rd] = a + sizeof (uint64_t);
5316                                 }
5317
5318                                 break;
5319                         }
5320
5321                         regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5322                         break;
5323
5324                 case DIF_OP_STGS:
5325                         id = DIF_INSTR_VAR(instr);
5326
5327                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5328                         id -= DIF_VAR_OTHER_UBASE;
5329
5330                         svar = vstate->dtvs_globals[id];
5331                         ASSERT(svar != NULL);
5332                         v = &svar->dtsv_var;
5333
5334                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5335                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5336
5337                                 ASSERT(a != 0);
5338                                 ASSERT(svar->dtsv_size != 0);
5339
5340                                 if (regs[rd] == 0) {
5341                                         *(uint8_t *)a = UINT8_MAX;
5342                                         break;
5343                                 } else {
5344                                         *(uint8_t *)a = 0;
5345                                         a += sizeof (uint64_t);
5346                                 }
5347                                 if (!dtrace_vcanload(
5348                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5349                                     mstate, vstate))
5350                                         break;
5351
5352                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5353                                     (void *)a, &v->dtdv_type);
5354                                 break;
5355                         }
5356
5357                         svar->dtsv_data = regs[rd];
5358                         break;
5359
5360                 case DIF_OP_LDTA:
5361                         /*
5362                          * There are no DTrace built-in thread-local arrays at
5363                          * present.  This opcode is saved for future work.
5364                          */
5365                         *flags |= CPU_DTRACE_ILLOP;
5366                         regs[rd] = 0;
5367                         break;
5368
5369                 case DIF_OP_LDLS:
5370                         id = DIF_INSTR_VAR(instr);
5371
5372                         if (id < DIF_VAR_OTHER_UBASE) {
5373                                 /*
5374                                  * For now, this has no meaning.
5375                                  */
5376                                 regs[rd] = 0;
5377                                 break;
5378                         }
5379
5380                         id -= DIF_VAR_OTHER_UBASE;
5381
5382                         ASSERT(id < vstate->dtvs_nlocals);
5383                         ASSERT(vstate->dtvs_locals != NULL);
5384
5385                         svar = vstate->dtvs_locals[id];
5386                         ASSERT(svar != NULL);
5387                         v = &svar->dtsv_var;
5388
5389                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5390                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5391                                 size_t sz = v->dtdv_type.dtdt_size;
5392
5393                                 sz += sizeof (uint64_t);
5394                                 ASSERT(svar->dtsv_size == NCPU * sz);
5395                                 a += curcpu * sz;
5396
5397                                 if (*(uint8_t *)a == UINT8_MAX) {
5398                                         /*
5399                                          * If the 0th byte is set to UINT8_MAX
5400                                          * then this is to be treated as a
5401                                          * reference to a NULL variable.
5402                                          */
5403                                         regs[rd] = 0;
5404                                 } else {
5405                                         regs[rd] = a + sizeof (uint64_t);
5406                                 }
5407
5408                                 break;
5409                         }
5410
5411                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5412                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5413                         regs[rd] = tmp[curcpu];
5414                         break;
5415
5416                 case DIF_OP_STLS:
5417                         id = DIF_INSTR_VAR(instr);
5418
5419                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5420                         id -= DIF_VAR_OTHER_UBASE;
5421                         ASSERT(id < vstate->dtvs_nlocals);
5422
5423                         ASSERT(vstate->dtvs_locals != NULL);
5424                         svar = vstate->dtvs_locals[id];
5425                         ASSERT(svar != NULL);
5426                         v = &svar->dtsv_var;
5427
5428                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5429                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5430                                 size_t sz = v->dtdv_type.dtdt_size;
5431
5432                                 sz += sizeof (uint64_t);
5433                                 ASSERT(svar->dtsv_size == NCPU * sz);
5434                                 a += curcpu * sz;
5435
5436                                 if (regs[rd] == 0) {
5437                                         *(uint8_t *)a = UINT8_MAX;
5438                                         break;
5439                                 } else {
5440                                         *(uint8_t *)a = 0;
5441                                         a += sizeof (uint64_t);
5442                                 }
5443
5444                                 if (!dtrace_vcanload(
5445                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5446                                     mstate, vstate))
5447                                         break;
5448
5449                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5450                                     (void *)a, &v->dtdv_type);
5451                                 break;
5452                         }
5453
5454                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5455                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5456                         tmp[curcpu] = regs[rd];
5457                         break;
5458
5459                 case DIF_OP_LDTS: {
5460                         dtrace_dynvar_t *dvar;
5461                         dtrace_key_t *key;
5462
5463                         id = DIF_INSTR_VAR(instr);
5464                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5465                         id -= DIF_VAR_OTHER_UBASE;
5466                         v = &vstate->dtvs_tlocals[id];
5467
5468                         key = &tupregs[DIF_DTR_NREGS];
5469                         key[0].dttk_value = (uint64_t)id;
5470                         key[0].dttk_size = 0;
5471                         DTRACE_TLS_THRKEY(key[1].dttk_value);
5472                         key[1].dttk_size = 0;
5473
5474                         dvar = dtrace_dynvar(dstate, 2, key,
5475                             sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5476                             mstate, vstate);
5477
5478                         if (dvar == NULL) {
5479                                 regs[rd] = 0;
5480                                 break;
5481                         }
5482
5483                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5484                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5485                         } else {
5486                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5487                         }
5488
5489                         break;
5490                 }
5491
5492                 case DIF_OP_STTS: {
5493                         dtrace_dynvar_t *dvar;
5494                         dtrace_key_t *key;
5495
5496                         id = DIF_INSTR_VAR(instr);
5497                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5498                         id -= DIF_VAR_OTHER_UBASE;
5499
5500                         key = &tupregs[DIF_DTR_NREGS];
5501                         key[0].dttk_value = (uint64_t)id;
5502                         key[0].dttk_size = 0;
5503                         DTRACE_TLS_THRKEY(key[1].dttk_value);
5504                         key[1].dttk_size = 0;
5505                         v = &vstate->dtvs_tlocals[id];
5506
5507                         dvar = dtrace_dynvar(dstate, 2, key,
5508                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5509                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
5510                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
5511                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5512
5513                         /*
5514                          * Given that we're storing to thread-local data,
5515                          * we need to flush our predicate cache.
5516                          */
5517                         curthread->t_predcache = 0;
5518
5519                         if (dvar == NULL)
5520                                 break;
5521
5522                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5523                                 if (!dtrace_vcanload(
5524                                     (void *)(uintptr_t)regs[rd],
5525                                     &v->dtdv_type, mstate, vstate))
5526                                         break;
5527
5528                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5529                                     dvar->dtdv_data, &v->dtdv_type);
5530                         } else {
5531                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5532                         }
5533
5534                         break;
5535                 }
5536
5537                 case DIF_OP_SRA:
5538                         regs[rd] = (int64_t)regs[r1] >> regs[r2];
5539                         break;
5540
5541                 case DIF_OP_CALL:
5542                         dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5543                             regs, tupregs, ttop, mstate, state);
5544                         break;
5545
5546                 case DIF_OP_PUSHTR:
5547                         if (ttop == DIF_DTR_NREGS) {
5548                                 *flags |= CPU_DTRACE_TUPOFLOW;
5549                                 break;
5550                         }
5551
5552                         if (r1 == DIF_TYPE_STRING) {
5553                                 /*
5554                                  * If this is a string type and the size is 0,
5555                                  * we'll use the system-wide default string
5556                                  * size.  Note that we are _not_ looking at
5557                                  * the value of the DTRACEOPT_STRSIZE option;
5558                                  * had this been set, we would expect to have
5559                                  * a non-zero size value in the "pushtr".
5560                                  */
5561                                 tupregs[ttop].dttk_size =
5562                                     dtrace_strlen((char *)(uintptr_t)regs[rd],
5563                                     regs[r2] ? regs[r2] :
5564                                     dtrace_strsize_default) + 1;
5565                         } else {
5566                                 tupregs[ttop].dttk_size = regs[r2];
5567                         }
5568
5569                         tupregs[ttop++].dttk_value = regs[rd];
5570                         break;
5571
5572                 case DIF_OP_PUSHTV:
5573                         if (ttop == DIF_DTR_NREGS) {
5574                                 *flags |= CPU_DTRACE_TUPOFLOW;
5575                                 break;
5576                         }
5577
5578                         tupregs[ttop].dttk_value = regs[rd];
5579                         tupregs[ttop++].dttk_size = 0;
5580                         break;
5581
5582                 case DIF_OP_POPTS:
5583                         if (ttop != 0)
5584                                 ttop--;
5585                         break;
5586
5587                 case DIF_OP_FLUSHTS:
5588                         ttop = 0;
5589                         break;
5590
5591                 case DIF_OP_LDGAA:
5592                 case DIF_OP_LDTAA: {
5593                         dtrace_dynvar_t *dvar;
5594                         dtrace_key_t *key = tupregs;
5595                         uint_t nkeys = ttop;
5596
5597                         id = DIF_INSTR_VAR(instr);
5598                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5599                         id -= DIF_VAR_OTHER_UBASE;
5600
5601                         key[nkeys].dttk_value = (uint64_t)id;
5602                         key[nkeys++].dttk_size = 0;
5603
5604                         if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5605                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5606                                 key[nkeys++].dttk_size = 0;
5607                                 v = &vstate->dtvs_tlocals[id];
5608                         } else {
5609                                 v = &vstate->dtvs_globals[id]->dtsv_var;
5610                         }
5611
5612                         dvar = dtrace_dynvar(dstate, nkeys, key,
5613                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5614                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
5615                             DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5616
5617                         if (dvar == NULL) {
5618                                 regs[rd] = 0;
5619                                 break;
5620                         }
5621
5622                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5623                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5624                         } else {
5625                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5626                         }
5627
5628                         break;
5629                 }
5630
5631                 case DIF_OP_STGAA:
5632                 case DIF_OP_STTAA: {
5633                         dtrace_dynvar_t *dvar;
5634                         dtrace_key_t *key = tupregs;
5635                         uint_t nkeys = ttop;
5636
5637                         id = DIF_INSTR_VAR(instr);
5638                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5639                         id -= DIF_VAR_OTHER_UBASE;
5640
5641                         key[nkeys].dttk_value = (uint64_t)id;
5642                         key[nkeys++].dttk_size = 0;
5643
5644                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5645                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5646                                 key[nkeys++].dttk_size = 0;
5647                                 v = &vstate->dtvs_tlocals[id];
5648                         } else {
5649                                 v = &vstate->dtvs_globals[id]->dtsv_var;
5650                         }
5651
5652                         dvar = dtrace_dynvar(dstate, nkeys, key,
5653                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5654                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
5655                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
5656                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5657
5658                         if (dvar == NULL)
5659                                 break;
5660
5661                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5662                                 if (!dtrace_vcanload(
5663                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5664                                     mstate, vstate))
5665                                         break;
5666
5667                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5668                                     dvar->dtdv_data, &v->dtdv_type);
5669                         } else {
5670                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5671                         }
5672
5673                         break;
5674                 }
5675
5676                 case DIF_OP_ALLOCS: {
5677                         uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5678                         size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5679
5680                         /*
5681                          * Rounding up the user allocation size could have
5682                          * overflowed large, bogus allocations (like -1ULL) to
5683                          * 0.
5684                          */
5685                         if (size < regs[r1] ||
5686                             !DTRACE_INSCRATCH(mstate, size)) {
5687                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5688                                 regs[rd] = 0;
5689                                 break;
5690                         }
5691
5692                         dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5693                         mstate->dtms_scratch_ptr += size;
5694                         regs[rd] = ptr;
5695                         break;
5696                 }
5697
5698                 case DIF_OP_COPYS:
5699                         if (!dtrace_canstore(regs[rd], regs[r2],
5700                             mstate, vstate)) {
5701                                 *flags |= CPU_DTRACE_BADADDR;
5702                                 *illval = regs[rd];
5703                                 break;
5704                         }
5705
5706                         if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5707                                 break;
5708
5709                         dtrace_bcopy((void *)(uintptr_t)regs[r1],
5710                             (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5711                         break;
5712
5713                 case DIF_OP_STB:
5714                         if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5715                                 *flags |= CPU_DTRACE_BADADDR;
5716                                 *illval = regs[rd];
5717                                 break;
5718                         }
5719                         *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5720                         break;
5721
5722                 case DIF_OP_STH:
5723                         if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5724                                 *flags |= CPU_DTRACE_BADADDR;
5725                                 *illval = regs[rd];
5726                                 break;
5727                         }
5728                         if (regs[rd] & 1) {
5729                                 *flags |= CPU_DTRACE_BADALIGN;
5730                                 *illval = regs[rd];
5731                                 break;
5732                         }
5733                         *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5734                         break;
5735
5736                 case DIF_OP_STW:
5737                         if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5738                                 *flags |= CPU_DTRACE_BADADDR;
5739                                 *illval = regs[rd];
5740                                 break;
5741                         }
5742                         if (regs[rd] & 3) {
5743                                 *flags |= CPU_DTRACE_BADALIGN;
5744                                 *illval = regs[rd];
5745                                 break;
5746                         }
5747                         *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5748                         break;
5749
5750                 case DIF_OP_STX:
5751                         if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5752                                 *flags |= CPU_DTRACE_BADADDR;
5753                                 *illval = regs[rd];
5754                                 break;
5755                         }
5756                         if (regs[rd] & 7) {
5757                                 *flags |= CPU_DTRACE_BADALIGN;
5758                                 *illval = regs[rd];
5759                                 break;
5760                         }
5761                         *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5762                         break;
5763                 }
5764         }
5765
5766         if (!(*flags & CPU_DTRACE_FAULT))
5767                 return (rval);
5768
5769         mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5770         mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5771
5772         return (0);
5773 }
5774
5775 static void
5776 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5777 {
5778         dtrace_probe_t *probe = ecb->dte_probe;
5779         dtrace_provider_t *prov = probe->dtpr_provider;
5780         char c[DTRACE_FULLNAMELEN + 80], *str;
5781         char *msg = "dtrace: breakpoint action at probe ";
5782         char *ecbmsg = " (ecb ";
5783         uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5784         uintptr_t val = (uintptr_t)ecb;
5785         int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5786
5787         if (dtrace_destructive_disallow)
5788                 return;
5789
5790         /*
5791          * It's impossible to be taking action on the NULL probe.
5792          */
5793         ASSERT(probe != NULL);
5794
5795         /*
5796          * This is a poor man's (destitute man's?) sprintf():  we want to
5797          * print the provider name, module name, function name and name of
5798          * the probe, along with the hex address of the ECB with the breakpoint
5799          * action -- all of which we must place in the character buffer by
5800          * hand.
5801          */
5802         while (*msg != '\0')
5803                 c[i++] = *msg++;
5804
5805         for (str = prov->dtpv_name; *str != '\0'; str++)
5806                 c[i++] = *str;
5807         c[i++] = ':';
5808
5809         for (str = probe->dtpr_mod; *str != '\0'; str++)
5810                 c[i++] = *str;
5811         c[i++] = ':';
5812
5813         for (str = probe->dtpr_func; *str != '\0'; str++)
5814                 c[i++] = *str;
5815         c[i++] = ':';
5816
5817         for (str = probe->dtpr_name; *str != '\0'; str++)
5818                 c[i++] = *str;
5819
5820         while (*ecbmsg != '\0')
5821                 c[i++] = *ecbmsg++;
5822
5823         while (shift >= 0) {
5824                 mask = (uintptr_t)0xf << shift;
5825
5826                 if (val >= ((uintptr_t)1 << shift))
5827                         c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5828                 shift -= 4;
5829         }
5830
5831         c[i++] = ')';
5832         c[i] = '\0';
5833
5834 #if defined(sun)
5835         debug_enter(c);
5836 #else
5837         kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
5838 #endif
5839 }
5840
5841 static void
5842 dtrace_action_panic(dtrace_ecb_t *ecb)
5843 {
5844         dtrace_probe_t *probe = ecb->dte_probe;
5845
5846         /*
5847          * It's impossible to be taking action on the NULL probe.
5848          */
5849         ASSERT(probe != NULL);
5850
5851         if (dtrace_destructive_disallow)
5852                 return;
5853
5854         if (dtrace_panicked != NULL)
5855                 return;
5856
5857         if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5858                 return;
5859
5860         /*
5861          * We won the right to panic.  (We want to be sure that only one
5862          * thread calls panic() from dtrace_probe(), and that panic() is
5863          * called exactly once.)
5864          */
5865         dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5866             probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5867             probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5868 }
5869
5870 static void
5871 dtrace_action_raise(uint64_t sig)
5872 {
5873         if (dtrace_destructive_disallow)
5874                 return;
5875
5876         if (sig >= NSIG) {
5877                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5878                 return;
5879         }
5880
5881 #if defined(sun)
5882         /*
5883          * raise() has a queue depth of 1 -- we ignore all subsequent
5884          * invocations of the raise() action.
5885          */
5886         if (curthread->t_dtrace_sig == 0)
5887                 curthread->t_dtrace_sig = (uint8_t)sig;
5888
5889         curthread->t_sig_check = 1;
5890         aston(curthread);
5891 #else
5892         struct proc *p = curproc;
5893         PROC_LOCK(p);
5894         kern_psignal(p, sig);
5895         PROC_UNLOCK(p);
5896 #endif
5897 }
5898
5899 static void
5900 dtrace_action_stop(void)
5901 {
5902         if (dtrace_destructive_disallow)
5903                 return;
5904
5905 #if defined(sun)
5906         if (!curthread->t_dtrace_stop) {
5907                 curthread->t_dtrace_stop = 1;
5908                 curthread->t_sig_check = 1;
5909                 aston(curthread);
5910         }
5911 #else
5912         struct proc *p = curproc;
5913         PROC_LOCK(p);
5914         kern_psignal(p, SIGSTOP);
5915         PROC_UNLOCK(p);
5916 #endif
5917 }
5918
5919 static void
5920 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5921 {
5922         hrtime_t now;
5923         volatile uint16_t *flags;
5924 #if defined(sun)
5925         cpu_t *cpu = CPU;
5926 #else
5927         cpu_t *cpu = &solaris_cpu[curcpu];
5928 #endif
5929
5930         if (dtrace_destructive_disallow)
5931                 return;
5932
5933         flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5934
5935         now = dtrace_gethrtime();
5936
5937         if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5938                 /*
5939                  * We need to advance the mark to the current time.
5940                  */
5941                 cpu->cpu_dtrace_chillmark = now;
5942                 cpu->cpu_dtrace_chilled = 0;
5943         }
5944
5945         /*
5946          * Now check to see if the requested chill time would take us over
5947          * the maximum amount of time allowed in the chill interval.  (Or
5948          * worse, if the calculation itself induces overflow.)
5949          */
5950         if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5951             cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5952                 *flags |= CPU_DTRACE_ILLOP;
5953                 return;
5954         }
5955
5956         while (dtrace_gethrtime() - now < val)
5957                 continue;
5958
5959         /*
5960          * Normally, we assure that the value of the variable "timestamp" does
5961          * not change within an ECB.  The presence of chill() represents an
5962          * exception to this rule, however.
5963          */
5964         mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5965         cpu->cpu_dtrace_chilled += val;
5966 }
5967
5968 static void
5969 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5970     uint64_t *buf, uint64_t arg)
5971 {
5972         int nframes = DTRACE_USTACK_NFRAMES(arg);
5973         int strsize = DTRACE_USTACK_STRSIZE(arg);
5974         uint64_t *pcs = &buf[1], *fps;
5975         char *str = (char *)&pcs[nframes];
5976         int size, offs = 0, i, j;
5977         uintptr_t old = mstate->dtms_scratch_ptr, saved;
5978         uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5979         char *sym;
5980
5981         /*
5982          * Should be taking a faster path if string space has not been
5983          * allocated.
5984          */
5985         ASSERT(strsize != 0);
5986
5987         /*
5988          * We will first allocate some temporary space for the frame pointers.
5989          */
5990         fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5991         size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5992             (nframes * sizeof (uint64_t));
5993
5994         if (!DTRACE_INSCRATCH(mstate, size)) {
5995                 /*
5996                  * Not enough room for our frame pointers -- need to indicate
5997                  * that we ran out of scratch space.
5998                  */
5999                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6000                 return;
6001         }
6002
6003         mstate->dtms_scratch_ptr += size;
6004         saved = mstate->dtms_scratch_ptr;
6005
6006         /*
6007          * Now get a stack with both program counters and frame pointers.
6008          */
6009         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6010         dtrace_getufpstack(buf, fps, nframes + 1);
6011         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6012
6013         /*
6014          * If that faulted, we're cooked.
6015          */
6016         if (*flags & CPU_DTRACE_FAULT)
6017                 goto out;
6018
6019         /*
6020          * Now we want to walk up the stack, calling the USTACK helper.  For
6021          * each iteration, we restore the scratch pointer.
6022          */
6023         for (i = 0; i < nframes; i++) {
6024                 mstate->dtms_scratch_ptr = saved;
6025
6026                 if (offs >= strsize)
6027                         break;
6028
6029                 sym = (char *)(uintptr_t)dtrace_helper(
6030                     DTRACE_HELPER_ACTION_USTACK,
6031                     mstate, state, pcs[i], fps[i]);
6032
6033                 /*
6034                  * If we faulted while running the helper, we're going to
6035                  * clear the fault and null out the corresponding string.
6036                  */
6037                 if (*flags & CPU_DTRACE_FAULT) {
6038                         *flags &= ~CPU_DTRACE_FAULT;
6039                         str[offs++] = '\0';
6040                         continue;
6041                 }
6042
6043                 if (sym == NULL) {
6044                         str[offs++] = '\0';
6045                         continue;
6046                 }
6047
6048                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6049
6050                 /*
6051                  * Now copy in the string that the helper returned to us.
6052                  */
6053                 for (j = 0; offs + j < strsize; j++) {
6054                         if ((str[offs + j] = sym[j]) == '\0')
6055                                 break;
6056                 }
6057
6058                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6059
6060                 offs += j + 1;
6061         }
6062
6063         if (offs >= strsize) {
6064                 /*
6065                  * If we didn't have room for all of the strings, we don't
6066                  * abort processing -- this needn't be a fatal error -- but we
6067                  * still want to increment a counter (dts_stkstroverflows) to
6068                  * allow this condition to be warned about.  (If this is from
6069                  * a jstack() action, it is easily tuned via jstackstrsize.)
6070                  */
6071                 dtrace_error(&state->dts_stkstroverflows);
6072         }
6073
6074         while (offs < strsize)
6075                 str[offs++] = '\0';
6076
6077 out:
6078         mstate->dtms_scratch_ptr = old;
6079 }
6080
6081 /*
6082  * If you're looking for the epicenter of DTrace, you just found it.  This
6083  * is the function called by the provider to fire a probe -- from which all
6084  * subsequent probe-context DTrace activity emanates.
6085  */
6086 void
6087 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6088     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6089 {
6090         processorid_t cpuid;
6091         dtrace_icookie_t cookie;
6092         dtrace_probe_t *probe;
6093         dtrace_mstate_t mstate;
6094         dtrace_ecb_t *ecb;
6095         dtrace_action_t *act;
6096         intptr_t offs;
6097         size_t size;
6098         int vtime, onintr;
6099         volatile uint16_t *flags;
6100         hrtime_t now;
6101
6102         if (panicstr != NULL)
6103                 return;
6104
6105 #if defined(sun)
6106         /*
6107          * Kick out immediately if this CPU is still being born (in which case
6108          * curthread will be set to -1) or the current thread can't allow
6109          * probes in its current context.
6110          */
6111         if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6112                 return;
6113 #endif
6114
6115         cookie = dtrace_interrupt_disable();
6116         probe = dtrace_probes[id - 1];
6117         cpuid = curcpu;
6118         onintr = CPU_ON_INTR(CPU);
6119
6120         if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6121             probe->dtpr_predcache == curthread->t_predcache) {
6122                 /*
6123                  * We have hit in the predicate cache; we know that
6124                  * this predicate would evaluate to be false.
6125                  */
6126                 dtrace_interrupt_enable(cookie);
6127                 return;
6128         }
6129
6130 #if defined(sun)
6131         if (panic_quiesce) {
6132 #else
6133         if (panicstr != NULL) {
6134 #endif
6135                 /*
6136                  * We don't trace anything if we're panicking.
6137                  */
6138                 dtrace_interrupt_enable(cookie);
6139                 return;
6140         }
6141
6142         now = dtrace_gethrtime();
6143         vtime = dtrace_vtime_references != 0;
6144
6145         if (vtime && curthread->t_dtrace_start)
6146                 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6147
6148         mstate.dtms_difo = NULL;
6149         mstate.dtms_probe = probe;
6150         mstate.dtms_strtok = 0;
6151         mstate.dtms_arg[0] = arg0;
6152         mstate.dtms_arg[1] = arg1;
6153         mstate.dtms_arg[2] = arg2;
6154         mstate.dtms_arg[3] = arg3;
6155         mstate.dtms_arg[4] = arg4;
6156
6157         flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6158
6159         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6160                 dtrace_predicate_t *pred = ecb->dte_predicate;
6161                 dtrace_state_t *state = ecb->dte_state;
6162                 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6163                 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6164                 dtrace_vstate_t *vstate = &state->dts_vstate;
6165                 dtrace_provider_t *prov = probe->dtpr_provider;
6166                 uint64_t tracememsize = 0;
6167                 int committed = 0;
6168                 caddr_t tomax;
6169
6170                 /*
6171                  * A little subtlety with the following (seemingly innocuous)
6172                  * declaration of the automatic 'val':  by looking at the
6173                  * code, you might think that it could be declared in the
6174                  * action processing loop, below.  (That is, it's only used in
6175                  * the action processing loop.)  However, it must be declared
6176                  * out of that scope because in the case of DIF expression
6177                  * arguments to aggregating actions, one iteration of the
6178                  * action loop will use the last iteration's value.
6179                  */
6180                 uint64_t val = 0;
6181
6182                 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6183                 *flags &= ~CPU_DTRACE_ERROR;
6184
6185                 if (prov == dtrace_provider) {
6186                         /*
6187                          * If dtrace itself is the provider of this probe,
6188                          * we're only going to continue processing the ECB if
6189                          * arg0 (the dtrace_state_t) is equal to the ECB's
6190                          * creating state.  (This prevents disjoint consumers
6191                          * from seeing one another's metaprobes.)
6192                          */
6193                         if (arg0 != (uint64_t)(uintptr_t)state)
6194                                 continue;
6195                 }
6196
6197                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6198                         /*
6199                          * We're not currently active.  If our provider isn't
6200                          * the dtrace pseudo provider, we're not interested.
6201                          */
6202                         if (prov != dtrace_provider)
6203                                 continue;
6204
6205                         /*
6206                          * Now we must further check if we are in the BEGIN
6207                          * probe.  If we are, we will only continue processing
6208                          * if we're still in WARMUP -- if one BEGIN enabling
6209                          * has invoked the exit() action, we don't want to
6210                          * evaluate subsequent BEGIN enablings.
6211                          */
6212                         if (probe->dtpr_id == dtrace_probeid_begin &&
6213                             state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6214                                 ASSERT(state->dts_activity ==
6215                                     DTRACE_ACTIVITY_DRAINING);
6216                                 continue;
6217                         }
6218                 }
6219
6220                 if (ecb->dte_cond) {
6221                         /*
6222                          * If the dte_cond bits indicate that this
6223                          * consumer is only allowed to see user-mode firings
6224                          * of this probe, call the provider's dtps_usermode()
6225                          * entry point to check that the probe was fired
6226                          * while in a user context. Skip this ECB if that's
6227                          * not the case.
6228                          */
6229                         if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6230                             prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6231                             probe->dtpr_id, probe->dtpr_arg) == 0)
6232                                 continue;
6233
6234 #if defined(sun)
6235                         /*
6236                          * This is more subtle than it looks. We have to be
6237                          * absolutely certain that CRED() isn't going to
6238                          * change out from under us so it's only legit to
6239                          * examine that structure if we're in constrained
6240                          * situations. Currently, the only times we'll this
6241                          * check is if a non-super-user has enabled the
6242                          * profile or syscall providers -- providers that
6243                          * allow visibility of all processes. For the
6244                          * profile case, the check above will ensure that
6245                          * we're examining a user context.
6246                          */
6247                         if (ecb->dte_cond & DTRACE_COND_OWNER) {
6248                                 cred_t *cr;
6249                                 cred_t *s_cr =
6250                                     ecb->dte_state->dts_cred.dcr_cred;
6251                                 proc_t *proc;
6252
6253                                 ASSERT(s_cr != NULL);
6254
6255                                 if ((cr = CRED()) == NULL ||
6256                                     s_cr->cr_uid != cr->cr_uid ||
6257                                     s_cr->cr_uid != cr->cr_ruid ||
6258                                     s_cr->cr_uid != cr->cr_suid ||
6259                                     s_cr->cr_gid != cr->cr_gid ||
6260                                     s_cr->cr_gid != cr->cr_rgid ||
6261                                     s_cr->cr_gid != cr->cr_sgid ||
6262                                     (proc = ttoproc(curthread)) == NULL ||
6263                                     (proc->p_flag & SNOCD))
6264                                         continue;
6265                         }
6266
6267                         if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6268                                 cred_t *cr;
6269                                 cred_t *s_cr =
6270                                     ecb->dte_state->dts_cred.dcr_cred;
6271
6272                                 ASSERT(s_cr != NULL);
6273
6274                                 if ((cr = CRED()) == NULL ||
6275                                     s_cr->cr_zone->zone_id !=
6276                                     cr->cr_zone->zone_id)
6277                                         continue;
6278                         }
6279 #endif
6280                 }
6281
6282                 if (now - state->dts_alive > dtrace_deadman_timeout) {
6283                         /*
6284                          * We seem to be dead.  Unless we (a) have kernel
6285                          * destructive permissions (b) have explicitly enabled
6286                          * destructive actions and (c) destructive actions have
6287                          * not been disabled, we're going to transition into
6288                          * the KILLED state, from which no further processing
6289                          * on this state will be performed.
6290                          */
6291                         if (!dtrace_priv_kernel_destructive(state) ||
6292                             !state->dts_cred.dcr_destructive ||
6293                             dtrace_destructive_disallow) {
6294                                 void *activity = &state->dts_activity;
6295                                 dtrace_activity_t current;
6296
6297                                 do {
6298                                         current = state->dts_activity;
6299                                 } while (dtrace_cas32(activity, current,
6300                                     DTRACE_ACTIVITY_KILLED) != current);
6301
6302                                 continue;
6303                         }
6304                 }
6305
6306                 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6307                     ecb->dte_alignment, state, &mstate)) < 0)
6308                         continue;
6309
6310                 tomax = buf->dtb_tomax;
6311                 ASSERT(tomax != NULL);
6312
6313                 if (ecb->dte_size != 0) {
6314                         dtrace_rechdr_t dtrh;
6315                         if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6316                                 mstate.dtms_timestamp = dtrace_gethrtime();
6317                                 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6318                         }
6319                         ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6320                         dtrh.dtrh_epid = ecb->dte_epid;
6321                         DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6322                             mstate.dtms_timestamp);
6323                         *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6324                 }
6325
6326                 mstate.dtms_epid = ecb->dte_epid;
6327                 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6328
6329                 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6330                         mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6331                 else
6332                         mstate.dtms_access = 0;
6333
6334                 if (pred != NULL) {
6335                         dtrace_difo_t *dp = pred->dtp_difo;
6336                         int rval;
6337
6338                         rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6339
6340                         if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6341                                 dtrace_cacheid_t cid = probe->dtpr_predcache;
6342
6343                                 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6344                                         /*
6345                                          * Update the predicate cache...
6346                                          */
6347                                         ASSERT(cid == pred->dtp_cacheid);
6348                                         curthread->t_predcache = cid;
6349                                 }
6350
6351                                 continue;
6352                         }
6353                 }
6354
6355                 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6356                     act != NULL; act = act->dta_next) {
6357                         size_t valoffs;
6358                         dtrace_difo_t *dp;
6359                         dtrace_recdesc_t *rec = &act->dta_rec;
6360
6361                         size = rec->dtrd_size;
6362                         valoffs = offs + rec->dtrd_offset;
6363
6364                         if (DTRACEACT_ISAGG(act->dta_kind)) {
6365                                 uint64_t v = 0xbad;
6366                                 dtrace_aggregation_t *agg;
6367
6368                                 agg = (dtrace_aggregation_t *)act;
6369
6370                                 if ((dp = act->dta_difo) != NULL)
6371                                         v = dtrace_dif_emulate(dp,
6372                                             &mstate, vstate, state);
6373
6374                                 if (*flags & CPU_DTRACE_ERROR)
6375                                         continue;
6376
6377                                 /*
6378                                  * Note that we always pass the expression
6379                                  * value from the previous iteration of the
6380                                  * action loop.  This value will only be used
6381                                  * if there is an expression argument to the
6382                                  * aggregating action, denoted by the
6383                                  * dtag_hasarg field.
6384                                  */
6385                                 dtrace_aggregate(agg, buf,
6386                                     offs, aggbuf, v, val);
6387                                 continue;
6388                         }
6389
6390                         switch (act->dta_kind) {
6391                         case DTRACEACT_STOP:
6392                                 if (dtrace_priv_proc_destructive(state))
6393                                         dtrace_action_stop();
6394                                 continue;
6395
6396                         case DTRACEACT_BREAKPOINT:
6397                                 if (dtrace_priv_kernel_destructive(state))
6398                                         dtrace_action_breakpoint(ecb);
6399                                 continue;
6400
6401                         case DTRACEACT_PANIC:
6402                                 if (dtrace_priv_kernel_destructive(state))
6403                                         dtrace_action_panic(ecb);
6404                                 continue;
6405
6406                         case DTRACEACT_STACK:
6407                                 if (!dtrace_priv_kernel(state))
6408                                         continue;
6409
6410                                 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6411                                     size / sizeof (pc_t), probe->dtpr_aframes,
6412                                     DTRACE_ANCHORED(probe) ? NULL :
6413                                     (uint32_t *)arg0);
6414                                 continue;
6415
6416                         case DTRACEACT_JSTACK:
6417                         case DTRACEACT_USTACK:
6418                                 if (!dtrace_priv_proc(state))
6419                                         continue;
6420
6421                                 /*
6422                                  * See comment in DIF_VAR_PID.
6423                                  */
6424                                 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6425                                     CPU_ON_INTR(CPU)) {
6426                                         int depth = DTRACE_USTACK_NFRAMES(
6427                                             rec->dtrd_arg) + 1;
6428
6429                                         dtrace_bzero((void *)(tomax + valoffs),
6430                                             DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6431                                             + depth * sizeof (uint64_t));
6432
6433                                         continue;
6434                                 }
6435
6436                                 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6437                                     curproc->p_dtrace_helpers != NULL) {
6438                                         /*
6439                                          * This is the slow path -- we have
6440                                          * allocated string space, and we're
6441                                          * getting the stack of a process that
6442                                          * has helpers.  Call into a separate
6443                                          * routine to perform this processing.
6444                                          */
6445                                         dtrace_action_ustack(&mstate, state,
6446                                             (uint64_t *)(tomax + valoffs),
6447                                             rec->dtrd_arg);
6448                                         continue;
6449                                 }
6450
6451                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6452                                 dtrace_getupcstack((uint64_t *)
6453                                     (tomax + valoffs),
6454                                     DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6455                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6456                                 continue;
6457
6458                         default:
6459                                 break;
6460                         }
6461
6462                         dp = act->dta_difo;
6463                         ASSERT(dp != NULL);
6464
6465                         val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6466
6467                         if (*flags & CPU_DTRACE_ERROR)
6468                                 continue;
6469
6470                         switch (act->dta_kind) {
6471                         case DTRACEACT_SPECULATE: {
6472                                 dtrace_rechdr_t *dtrh;
6473
6474                                 ASSERT(buf == &state->dts_buffer[cpuid]);
6475                                 buf = dtrace_speculation_buffer(state,
6476                                     cpuid, val);
6477
6478                                 if (buf == NULL) {
6479                                         *flags |= CPU_DTRACE_DROP;
6480                                         continue;
6481                                 }
6482
6483                                 offs = dtrace_buffer_reserve(buf,
6484                                     ecb->dte_needed, ecb->dte_alignment,
6485                                     state, NULL);
6486
6487                                 if (offs < 0) {
6488                                         *flags |= CPU_DTRACE_DROP;
6489                                         continue;
6490                                 }
6491
6492                                 tomax = buf->dtb_tomax;
6493                                 ASSERT(tomax != NULL);
6494
6495                                 if (ecb->dte_size == 0)
6496                                         continue;
6497
6498                                 ASSERT3U(ecb->dte_size, >=,
6499                                     sizeof (dtrace_rechdr_t));
6500                                 dtrh = ((void *)(tomax + offs));
6501                                 dtrh->dtrh_epid = ecb->dte_epid;
6502                                 /*
6503                                  * When the speculation is committed, all of
6504                                  * the records in the speculative buffer will
6505                                  * have their timestamps set to the commit
6506                                  * time.  Until then, it is set to a sentinel
6507                                  * value, for debugability.
6508                                  */
6509                                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6510                                 continue;
6511                         }
6512
6513                         case DTRACEACT_PRINTM: {
6514                                 /* The DIF returns a 'memref'. */
6515                                 uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
6516
6517                                 /* Get the size from the memref. */
6518                                 size = memref[1];
6519
6520                                 /*
6521                                  * Check if the size exceeds the allocated
6522                                  * buffer size.
6523                                  */
6524                                 if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6525                                         /* Flag a drop! */
6526                                         *flags |= CPU_DTRACE_DROP;
6527                                         continue;
6528                                 }
6529
6530                                 /* Store the size in the buffer first. */
6531                                 DTRACE_STORE(uintptr_t, tomax,
6532                                     valoffs, size);
6533
6534                                 /*
6535                                  * Offset the buffer address to the start
6536                                  * of the data.
6537                                  */
6538                                 valoffs += sizeof(uintptr_t);
6539
6540                                 /*
6541                                  * Reset to the memory address rather than
6542                                  * the memref array, then let the BYREF
6543                                  * code below do the work to store the 
6544                                  * memory data in the buffer.
6545                                  */
6546                                 val = memref[0];
6547                                 break;
6548                         }
6549
6550                         case DTRACEACT_PRINTT: {
6551                                 /* The DIF returns a 'typeref'. */
6552                                 uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
6553                                 char c = '\0' + 1;
6554                                 size_t s;
6555
6556                                 /*
6557                                  * Get the type string length and round it
6558                                  * up so that the data that follows is
6559                                  * aligned for easy access.
6560                                  */
6561                                 size_t typs = strlen((char *) typeref[2]) + 1;
6562                                 typs = roundup(typs,  sizeof(uintptr_t));
6563
6564                                 /*
6565                                  *Get the size from the typeref using the
6566                                  * number of elements and the type size.
6567                                  */
6568                                 size = typeref[1] * typeref[3];
6569
6570                                 /*
6571                                  * Check if the size exceeds the allocated
6572                                  * buffer size.
6573                                  */
6574                                 if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6575                                         /* Flag a drop! */
6576                                         *flags |= CPU_DTRACE_DROP;
6577                                 
6578                                 }
6579
6580                                 /* Store the size in the buffer first. */
6581                                 DTRACE_STORE(uintptr_t, tomax,
6582                                     valoffs, size);
6583                                 valoffs += sizeof(uintptr_t);
6584
6585                                 /* Store the type size in the buffer. */
6586                                 DTRACE_STORE(uintptr_t, tomax,
6587                                     valoffs, typeref[3]);
6588                                 valoffs += sizeof(uintptr_t);
6589
6590                                 val = typeref[2];
6591
6592                                 for (s = 0; s < typs; s++) {
6593                                         if (c != '\0')
6594                                                 c = dtrace_load8(val++);
6595
6596                                         DTRACE_STORE(uint8_t, tomax,
6597                                             valoffs++, c);
6598                                 }
6599
6600                                 /*
6601                                  * Reset to the memory address rather than
6602                                  * the typeref array, then let the BYREF
6603                                  * code below do the work to store the 
6604                                  * memory data in the buffer.
6605                                  */
6606                                 val = typeref[0];
6607                                 break;
6608                         }
6609
6610                         case DTRACEACT_CHILL:
6611                                 if (dtrace_priv_kernel_destructive(state))
6612                                         dtrace_action_chill(&mstate, val);
6613                                 continue;
6614
6615                         case DTRACEACT_RAISE:
6616                                 if (dtrace_priv_proc_destructive(state))
6617                                         dtrace_action_raise(val);
6618                                 continue;
6619
6620                         case DTRACEACT_COMMIT:
6621                                 ASSERT(!committed);
6622
6623                                 /*
6624                                  * We need to commit our buffer state.
6625                                  */
6626                                 if (ecb->dte_size)
6627                                         buf->dtb_offset = offs + ecb->dte_size;
6628                                 buf = &state->dts_buffer[cpuid];
6629                                 dtrace_speculation_commit(state, cpuid, val);
6630                                 committed = 1;
6631                                 continue;
6632
6633                         case DTRACEACT_DISCARD:
6634                                 dtrace_speculation_discard(state, cpuid, val);
6635                                 continue;
6636
6637                         case DTRACEACT_DIFEXPR:
6638                         case DTRACEACT_LIBACT:
6639                         case DTRACEACT_PRINTF:
6640                         case DTRACEACT_PRINTA:
6641                         case DTRACEACT_SYSTEM:
6642                         case DTRACEACT_FREOPEN:
6643                         case DTRACEACT_TRACEMEM:
6644                                 break;
6645
6646                         case DTRACEACT_TRACEMEM_DYNSIZE:
6647                                 tracememsize = val;
6648                                 break;
6649
6650                         case DTRACEACT_SYM:
6651                         case DTRACEACT_MOD:
6652                                 if (!dtrace_priv_kernel(state))
6653                                         continue;
6654                                 break;
6655
6656                         case DTRACEACT_USYM:
6657                         case DTRACEACT_UMOD:
6658                         case DTRACEACT_UADDR: {
6659 #if defined(sun)
6660                                 struct pid *pid = curthread->t_procp->p_pidp;
6661 #endif
6662
6663                                 if (!dtrace_priv_proc(state))
6664                                         continue;
6665
6666                                 DTRACE_STORE(uint64_t, tomax,
6667 #if defined(sun)
6668                                     valoffs, (uint64_t)pid->pid_id);
6669 #else
6670                                     valoffs, (uint64_t) curproc->p_pid);
6671 #endif
6672                                 DTRACE_STORE(uint64_t, tomax,
6673                                     valoffs + sizeof (uint64_t), val);
6674
6675                                 continue;
6676                         }
6677
6678                         case DTRACEACT_EXIT: {
6679                                 /*
6680                                  * For the exit action, we are going to attempt
6681                                  * to atomically set our activity to be
6682                                  * draining.  If this fails (either because
6683                                  * another CPU has beat us to the exit action,
6684                                  * or because our current activity is something
6685                                  * other than ACTIVE or WARMUP), we will
6686                                  * continue.  This assures that the exit action
6687                                  * can be successfully recorded at most once
6688                                  * when we're in the ACTIVE state.  If we're
6689                                  * encountering the exit() action while in
6690                                  * COOLDOWN, however, we want to honor the new
6691                                  * status code.  (We know that we're the only
6692                                  * thread in COOLDOWN, so there is no race.)
6693                                  */
6694                                 void *activity = &state->dts_activity;
6695                                 dtrace_activity_t current = state->dts_activity;
6696
6697                                 if (current == DTRACE_ACTIVITY_COOLDOWN)
6698                                         break;
6699
6700                                 if (current != DTRACE_ACTIVITY_WARMUP)
6701                                         current = DTRACE_ACTIVITY_ACTIVE;
6702
6703                                 if (dtrace_cas32(activity, current,
6704                                     DTRACE_ACTIVITY_DRAINING) != current) {
6705                                         *flags |= CPU_DTRACE_DROP;
6706                                         continue;
6707                                 }
6708
6709                                 break;
6710                         }
6711
6712                         default:
6713                                 ASSERT(0);
6714                         }
6715
6716                         if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6717                                 uintptr_t end = valoffs + size;
6718
6719                                 if (tracememsize != 0 &&
6720                                     valoffs + tracememsize < end) {
6721                                         end = valoffs + tracememsize;
6722                                         tracememsize = 0;
6723                                 }
6724
6725                                 if (!dtrace_vcanload((void *)(uintptr_t)val,
6726                                     &dp->dtdo_rtype, &mstate, vstate))
6727                                         continue;
6728
6729                                 /*
6730                                  * If this is a string, we're going to only
6731                                  * load until we find the zero byte -- after
6732                                  * which we'll store zero bytes.
6733                                  */
6734                                 if (dp->dtdo_rtype.dtdt_kind ==
6735                                     DIF_TYPE_STRING) {
6736                                         char c = '\0' + 1;
6737                                         int intuple = act->dta_intuple;
6738                                         size_t s;
6739
6740                                         for (s = 0; s < size; s++) {
6741                                                 if (c != '\0')
6742                                                         c = dtrace_load8(val++);
6743
6744                                                 DTRACE_STORE(uint8_t, tomax,
6745                                                     valoffs++, c);
6746
6747                                                 if (c == '\0' && intuple)
6748                                                         break;
6749                                         }
6750
6751                                         continue;
6752                                 }
6753
6754                                 while (valoffs < end) {
6755                                         DTRACE_STORE(uint8_t, tomax, valoffs++,
6756                                             dtrace_load8(val++));
6757                                 }
6758
6759                                 continue;
6760                         }
6761
6762                         switch (size) {
6763                         case 0:
6764                                 break;
6765
6766                         case sizeof (uint8_t):
6767                                 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6768                                 break;
6769                         case sizeof (uint16_t):
6770                                 DTRACE_STORE(uint16_t, tomax, valoffs, val);
6771                                 break;
6772                         case sizeof (uint32_t):
6773                                 DTRACE_STORE(uint32_t, tomax, valoffs, val);
6774                                 break;
6775                         case sizeof (uint64_t):
6776                                 DTRACE_STORE(uint64_t, tomax, valoffs, val);
6777                                 break;
6778                         default:
6779                                 /*
6780                                  * Any other size should have been returned by
6781                                  * reference, not by value.
6782                                  */
6783                                 ASSERT(0);
6784                                 break;
6785                         }
6786                 }
6787
6788                 if (*flags & CPU_DTRACE_DROP)
6789                         continue;
6790
6791                 if (*flags & CPU_DTRACE_FAULT) {
6792                         int ndx;
6793                         dtrace_action_t *err;
6794
6795                         buf->dtb_errors++;
6796
6797                         if (probe->dtpr_id == dtrace_probeid_error) {
6798                                 /*
6799                                  * There's nothing we can do -- we had an
6800                                  * error on the error probe.  We bump an
6801                                  * error counter to at least indicate that
6802                                  * this condition happened.
6803                                  */
6804                                 dtrace_error(&state->dts_dblerrors);
6805                                 continue;
6806                         }
6807
6808                         if (vtime) {
6809                                 /*
6810                                  * Before recursing on dtrace_probe(), we
6811                                  * need to explicitly clear out our start
6812                                  * time to prevent it from being accumulated
6813                                  * into t_dtrace_vtime.
6814                                  */
6815                                 curthread->t_dtrace_start = 0;
6816                         }
6817
6818                         /*
6819                          * Iterate over the actions to figure out which action
6820                          * we were processing when we experienced the error.
6821                          * Note that act points _past_ the faulting action; if
6822                          * act is ecb->dte_action, the fault was in the
6823                          * predicate, if it's ecb->dte_action->dta_next it's
6824                          * in action #1, and so on.
6825                          */
6826                         for (err = ecb->dte_action, ndx = 0;
6827                             err != act; err = err->dta_next, ndx++)
6828                                 continue;
6829
6830                         dtrace_probe_error(state, ecb->dte_epid, ndx,
6831                             (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6832                             mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6833                             cpu_core[cpuid].cpuc_dtrace_illval);
6834
6835                         continue;
6836                 }
6837
6838                 if (!committed)
6839                         buf->dtb_offset = offs + ecb->dte_size;
6840         }
6841
6842         if (vtime)
6843                 curthread->t_dtrace_start = dtrace_gethrtime();
6844
6845         dtrace_interrupt_enable(cookie);
6846 }
6847
6848 /*
6849  * DTrace Probe Hashing Functions
6850  *
6851  * The functions in this section (and indeed, the functions in remaining
6852  * sections) are not _called_ from probe context.  (Any exceptions to this are
6853  * marked with a "Note:".)  Rather, they are called from elsewhere in the
6854  * DTrace framework to look-up probes in, add probes to and remove probes from
6855  * the DTrace probe hashes.  (Each probe is hashed by each element of the
6856  * probe tuple -- allowing for fast lookups, regardless of what was
6857  * specified.)
6858  */
6859 static uint_t
6860 dtrace_hash_str(const char *p)
6861 {
6862         unsigned int g;
6863         uint_t hval = 0;
6864
6865         while (*p) {
6866                 hval = (hval << 4) + *p++;
6867                 if ((g = (hval & 0xf0000000)) != 0)
6868                         hval ^= g >> 24;
6869                 hval &= ~g;
6870         }
6871         return (hval);
6872 }
6873
6874 static dtrace_hash_t *
6875 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6876 {
6877         dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6878
6879         hash->dth_stroffs = stroffs;
6880         hash->dth_nextoffs = nextoffs;
6881         hash->dth_prevoffs = prevoffs;
6882
6883         hash->dth_size = 1;
6884         hash->dth_mask = hash->dth_size - 1;
6885
6886         hash->dth_tab = kmem_zalloc(hash->dth_size *
6887             sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6888
6889         return (hash);
6890 }
6891
6892 static void
6893 dtrace_hash_destroy(dtrace_hash_t *hash)
6894 {
6895 #ifdef DEBUG
6896         int i;
6897
6898         for (i = 0; i < hash->dth_size; i++)
6899                 ASSERT(hash->dth_tab[i] == NULL);
6900 #endif
6901
6902         kmem_free(hash->dth_tab,
6903             hash->dth_size * sizeof (dtrace_hashbucket_t *));
6904         kmem_free(hash, sizeof (dtrace_hash_t));
6905 }
6906
6907 static void
6908 dtrace_hash_resize(dtrace_hash_t *hash)
6909 {
6910         int size = hash->dth_size, i, ndx;
6911         int new_size = hash->dth_size << 1;
6912         int new_mask = new_size - 1;
6913         dtrace_hashbucket_t **new_tab, *bucket, *next;
6914
6915         ASSERT((new_size & new_mask) == 0);
6916
6917         new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6918
6919         for (i = 0; i < size; i++) {
6920                 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6921                         dtrace_probe_t *probe = bucket->dthb_chain;
6922
6923                         ASSERT(probe != NULL);
6924                         ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6925
6926                         next = bucket->dthb_next;
6927                         bucket->dthb_next = new_tab[ndx];
6928                         new_tab[ndx] = bucket;
6929                 }
6930         }
6931
6932         kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6933         hash->dth_tab = new_tab;
6934         hash->dth_size = new_size;
6935         hash->dth_mask = new_mask;
6936 }
6937
6938 static void
6939 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6940 {
6941         int hashval = DTRACE_HASHSTR(hash, new);
6942         int ndx = hashval & hash->dth_mask;
6943         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6944         dtrace_probe_t **nextp, **prevp;
6945
6946         for (; bucket != NULL; bucket = bucket->dthb_next) {
6947                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6948                         goto add;
6949         }
6950
6951         if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6952                 dtrace_hash_resize(hash);
6953                 dtrace_hash_add(hash, new);
6954                 return;
6955         }
6956
6957         bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6958         bucket->dthb_next = hash->dth_tab[ndx];
6959         hash->dth_tab[ndx] = bucket;
6960         hash->dth_nbuckets++;
6961
6962 add:
6963         nextp = DTRACE_HASHNEXT(hash, new);
6964         ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6965         *nextp = bucket->dthb_chain;
6966
6967         if (bucket->dthb_chain != NULL) {
6968                 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6969                 ASSERT(*prevp == NULL);
6970                 *prevp = new;
6971         }
6972
6973         bucket->dthb_chain = new;
6974         bucket->dthb_len++;
6975 }
6976
6977 static dtrace_probe_t *
6978 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6979 {
6980         int hashval = DTRACE_HASHSTR(hash, template);
6981         int ndx = hashval & hash->dth_mask;
6982         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6983
6984         for (; bucket != NULL; bucket = bucket->dthb_next) {
6985                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6986                         return (bucket->dthb_chain);
6987         }
6988
6989         return (NULL);
6990 }
6991
6992 static int
6993 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6994 {
6995         int hashval = DTRACE_HASHSTR(hash, template);
6996         int ndx = hashval & hash->dth_mask;
6997         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6998
6999         for (; bucket != NULL; bucket = bucket->dthb_next) {
7000                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7001                         return (bucket->dthb_len);
7002         }
7003
7004         return (0);
7005 }
7006
7007 static void
7008 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7009 {
7010         int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7011         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7012
7013         dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7014         dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7015
7016         /*
7017          * Find the bucket that we're removing this probe from.
7018          */
7019         for (; bucket != NULL; bucket = bucket->dthb_next) {
7020                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7021                         break;
7022         }
7023
7024         ASSERT(bucket != NULL);
7025
7026         if (*prevp == NULL) {
7027                 if (*nextp == NULL) {
7028                         /*
7029                          * The removed probe was the only probe on this
7030                          * bucket; we need to remove the bucket.
7031                          */
7032                         dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7033
7034                         ASSERT(bucket->dthb_chain == probe);
7035                         ASSERT(b != NULL);
7036
7037                         if (b == bucket) {
7038                                 hash->dth_tab[ndx] = bucket->dthb_next;
7039                         } else {
7040                                 while (b->dthb_next != bucket)
7041                                         b = b->dthb_next;
7042                                 b->dthb_next = bucket->dthb_next;
7043                         }
7044
7045                         ASSERT(hash->dth_nbuckets > 0);
7046                         hash->dth_nbuckets--;
7047                         kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7048                         return;
7049                 }
7050
7051                 bucket->dthb_chain = *nextp;
7052         } else {
7053                 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7054         }
7055
7056         if (*nextp != NULL)
7057                 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7058 }
7059
7060 /*
7061  * DTrace Utility Functions
7062  *
7063  * These are random utility functions that are _not_ called from probe context.
7064  */
7065 static int
7066 dtrace_badattr(const dtrace_attribute_t *a)
7067 {
7068         return (a->dtat_name > DTRACE_STABILITY_MAX ||
7069             a->dtat_data > DTRACE_STABILITY_MAX ||
7070             a->dtat_class > DTRACE_CLASS_MAX);
7071 }
7072
7073 /*
7074  * Return a duplicate copy of a string.  If the specified string is NULL,
7075  * this function returns a zero-length string.
7076  */
7077 static char *
7078 dtrace_strdup(const char *str)
7079 {
7080         char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7081
7082         if (str != NULL)
7083                 (void) strcpy(new, str);
7084
7085         return (new);
7086 }
7087
7088 #define DTRACE_ISALPHA(c)       \
7089         (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7090
7091 static int
7092 dtrace_badname(const char *s)
7093 {
7094         char c;
7095
7096         if (s == NULL || (c = *s++) == '\0')
7097                 return (0);
7098
7099         if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7100                 return (1);
7101
7102         while ((c = *s++) != '\0') {
7103                 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7104                     c != '-' && c != '_' && c != '.' && c != '`')
7105                         return (1);
7106         }
7107
7108         return (0);
7109 }
7110
7111 static void
7112 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7113 {
7114         uint32_t priv;
7115
7116 #if defined(sun)
7117         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7118                 /*
7119                  * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7120                  */
7121                 priv = DTRACE_PRIV_ALL;
7122         } else {
7123                 *uidp = crgetuid(cr);
7124                 *zoneidp = crgetzoneid(cr);
7125
7126                 priv = 0;
7127                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7128                         priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7129                 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7130                         priv |= DTRACE_PRIV_USER;
7131                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7132                         priv |= DTRACE_PRIV_PROC;
7133                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7134                         priv |= DTRACE_PRIV_OWNER;
7135                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7136                         priv |= DTRACE_PRIV_ZONEOWNER;
7137         }
7138 #else
7139         priv = DTRACE_PRIV_ALL;
7140 #endif
7141
7142         *privp = priv;
7143 }
7144
7145 #ifdef DTRACE_ERRDEBUG
7146 static void
7147 dtrace_errdebug(const char *str)
7148 {
7149         int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7150         int occupied = 0;
7151
7152         mutex_enter(&dtrace_errlock);
7153         dtrace_errlast = str;
7154         dtrace_errthread = curthread;
7155
7156         while (occupied++ < DTRACE_ERRHASHSZ) {
7157                 if (dtrace_errhash[hval].dter_msg == str) {
7158                         dtrace_errhash[hval].dter_count++;
7159                         goto out;
7160                 }
7161
7162                 if (dtrace_errhash[hval].dter_msg != NULL) {
7163                         hval = (hval + 1) % DTRACE_ERRHASHSZ;
7164                         continue;
7165                 }
7166
7167                 dtrace_errhash[hval].dter_msg = str;
7168                 dtrace_errhash[hval].dter_count = 1;
7169                 goto out;
7170         }
7171
7172         panic("dtrace: undersized error hash");
7173 out:
7174         mutex_exit(&dtrace_errlock);
7175 }
7176 #endif
7177
7178 /*
7179  * DTrace Matching Functions
7180  *
7181  * These functions are used to match groups of probes, given some elements of
7182  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7183  */
7184 static int
7185 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7186     zoneid_t zoneid)
7187 {
7188         if (priv != DTRACE_PRIV_ALL) {
7189                 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7190                 uint32_t match = priv & ppriv;
7191
7192                 /*
7193                  * No PRIV_DTRACE_* privileges...
7194                  */
7195                 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7196                     DTRACE_PRIV_KERNEL)) == 0)
7197                         return (0);
7198
7199                 /*
7200                  * No matching bits, but there were bits to match...
7201                  */
7202                 if (match == 0 && ppriv != 0)
7203                         return (0);
7204
7205                 /*
7206                  * Need to have permissions to the process, but don't...
7207                  */
7208                 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7209                     uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7210                         return (0);
7211                 }
7212
7213                 /*
7214                  * Need to be in the same zone unless we possess the
7215                  * privilege to examine all zones.
7216                  */
7217                 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7218                     zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7219                         return (0);
7220                 }
7221         }
7222
7223         return (1);
7224 }
7225
7226 /*
7227  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7228  * consists of input pattern strings and an ops-vector to evaluate them.
7229  * This function returns >0 for match, 0 for no match, and <0 for error.
7230  */
7231 static int
7232 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7233     uint32_t priv, uid_t uid, zoneid_t zoneid)
7234 {
7235         dtrace_provider_t *pvp = prp->dtpr_provider;
7236         int rv;
7237
7238         if (pvp->dtpv_defunct)
7239                 return (0);
7240
7241         if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7242                 return (rv);
7243
7244         if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7245                 return (rv);
7246
7247         if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7248                 return (rv);
7249
7250         if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7251                 return (rv);
7252
7253         if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7254                 return (0);
7255
7256         return (rv);
7257 }
7258
7259 /*
7260  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7261  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7262  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7263  * In addition, all of the recursion cases except for '*' matching have been
7264  * unwound.  For '*', we still implement recursive evaluation, but a depth
7265  * counter is maintained and matching is aborted if we recurse too deep.
7266  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7267  */
7268 static int
7269 dtrace_match_glob(const char *s, const char *p, int depth)
7270 {
7271         const char *olds;
7272         char s1, c;
7273         int gs;
7274
7275         if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7276                 return (-1);
7277
7278         if (s == NULL)
7279                 s = ""; /* treat NULL as empty string */
7280
7281 top:
7282         olds = s;
7283         s1 = *s++;
7284
7285         if (p == NULL)
7286                 return (0);
7287
7288         if ((c = *p++) == '\0')
7289                 return (s1 == '\0');
7290
7291         switch (c) {
7292         case '[': {
7293                 int ok = 0, notflag = 0;
7294                 char lc = '\0';
7295
7296                 if (s1 == '\0')
7297                         return (0);
7298
7299                 if (*p == '!') {
7300                         notflag = 1;
7301                         p++;
7302                 }
7303
7304                 if ((c = *p++) == '\0')
7305                         return (0);
7306
7307                 do {
7308                         if (c == '-' && lc != '\0' && *p != ']') {
7309                                 if ((c = *p++) == '\0')
7310                                         return (0);
7311                                 if (c == '\\' && (c = *p++) == '\0')
7312                                         return (0);
7313
7314                                 if (notflag) {
7315                                         if (s1 < lc || s1 > c)
7316                                                 ok++;
7317                                         else
7318                                                 return (0);
7319                                 } else if (lc <= s1 && s1 <= c)
7320                                         ok++;
7321
7322                         } else if (c == '\\' && (c = *p++) == '\0')
7323                                 return (0);
7324
7325                         lc = c; /* save left-hand 'c' for next iteration */
7326
7327                         if (notflag) {
7328                                 if (s1 != c)
7329                                         ok++;
7330                                 else
7331                                         return (0);
7332                         } else if (s1 == c)
7333                                 ok++;
7334
7335                         if ((c = *p++) == '\0')
7336                                 return (0);
7337
7338                 } while (c != ']');
7339
7340                 if (ok)
7341                         goto top;
7342
7343                 return (0);
7344         }
7345
7346         case '\\':
7347                 if ((c = *p++) == '\0')
7348                         return (0);
7349                 /*FALLTHRU*/
7350
7351         default:
7352                 if (c != s1)
7353                         return (0);
7354                 /*FALLTHRU*/
7355
7356         case '?':
7357                 if (s1 != '\0')
7358                         goto top;
7359                 return (0);
7360
7361         case '*':
7362                 while (*p == '*')
7363                         p++; /* consecutive *'s are identical to a single one */
7364
7365                 if (*p == '\0')
7366                         return (1);
7367
7368                 for (s = olds; *s != '\0'; s++) {
7369                         if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7370                                 return (gs);
7371                 }
7372
7373                 return (0);
7374         }
7375 }
7376
7377 /*ARGSUSED*/
7378 static int
7379 dtrace_match_string(const char *s, const char *p, int depth)
7380 {
7381         return (s != NULL && strcmp(s, p) == 0);
7382 }
7383
7384 /*ARGSUSED*/
7385 static int
7386 dtrace_match_nul(const char *s, const char *p, int depth)
7387 {
7388         return (1); /* always match the empty pattern */
7389 }
7390
7391 /*ARGSUSED*/
7392 static int
7393 dtrace_match_nonzero(const char *s, const char *p, int depth)
7394 {
7395         return (s != NULL && s[0] != '\0');
7396 }
7397
7398 static int
7399 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7400     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7401 {
7402         dtrace_probe_t template, *probe;
7403         dtrace_hash_t *hash = NULL;
7404         int len, best = INT_MAX, nmatched = 0;
7405         dtrace_id_t i;
7406
7407         ASSERT(MUTEX_HELD(&dtrace_lock));
7408
7409         /*
7410          * If the probe ID is specified in the key, just lookup by ID and
7411          * invoke the match callback once if a matching probe is found.
7412          */
7413         if (pkp->dtpk_id != DTRACE_IDNONE) {
7414                 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7415                     dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7416                         (void) (*matched)(probe, arg);
7417                         nmatched++;
7418                 }
7419                 return (nmatched);
7420         }
7421
7422         template.dtpr_mod = (char *)pkp->dtpk_mod;
7423         template.dtpr_func = (char *)pkp->dtpk_func;
7424         template.dtpr_name = (char *)pkp->dtpk_name;
7425
7426         /*
7427          * We want to find the most distinct of the module name, function
7428          * name, and name.  So for each one that is not a glob pattern or
7429          * empty string, we perform a lookup in the corresponding hash and
7430          * use the hash table with the fewest collisions to do our search.
7431          */
7432         if (pkp->dtpk_mmatch == &dtrace_match_string &&
7433             (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7434                 best = len;
7435                 hash = dtrace_bymod;
7436         }
7437
7438         if (pkp->dtpk_fmatch == &dtrace_match_string &&
7439             (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7440                 best = len;
7441                 hash = dtrace_byfunc;
7442         }
7443
7444         if (pkp->dtpk_nmatch == &dtrace_match_string &&
7445             (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7446                 best = len;
7447                 hash = dtrace_byname;
7448         }
7449
7450         /*
7451          * If we did not select a hash table, iterate over every probe and
7452          * invoke our callback for each one that matches our input probe key.
7453          */
7454         if (hash == NULL) {
7455                 for (i = 0; i < dtrace_nprobes; i++) {
7456                         if ((probe = dtrace_probes[i]) == NULL ||
7457                             dtrace_match_probe(probe, pkp, priv, uid,
7458                             zoneid) <= 0)
7459                                 continue;
7460
7461                         nmatched++;
7462
7463                         if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7464                                 break;
7465                 }
7466
7467                 return (nmatched);
7468         }
7469
7470         /*
7471          * If we selected a hash table, iterate over each probe of the same key
7472          * name and invoke the callback for every probe that matches the other
7473          * attributes of our input probe key.
7474          */
7475         for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7476             probe = *(DTRACE_HASHNEXT(hash, probe))) {
7477
7478                 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7479                         continue;
7480
7481                 nmatched++;
7482
7483                 if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7484                         break;
7485         }
7486
7487         return (nmatched);
7488 }
7489
7490 /*
7491  * Return the function pointer dtrace_probecmp() should use to compare the
7492  * specified pattern with a string.  For NULL or empty patterns, we select
7493  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7494  * For non-empty non-glob strings, we use dtrace_match_string().
7495  */
7496 static dtrace_probekey_f *
7497 dtrace_probekey_func(const char *p)
7498 {
7499         char c;
7500
7501         if (p == NULL || *p == '\0')
7502                 return (&dtrace_match_nul);
7503
7504         while ((c = *p++) != '\0') {
7505                 if (c == '[' || c == '?' || c == '*' || c == '\\')
7506                         return (&dtrace_match_glob);
7507         }
7508
7509         return (&dtrace_match_string);
7510 }
7511
7512 /*
7513  * Build a probe comparison key for use with dtrace_match_probe() from the
7514  * given probe description.  By convention, a null key only matches anchored
7515  * probes: if each field is the empty string, reset dtpk_fmatch to
7516  * dtrace_match_nonzero().
7517  */
7518 static void
7519 dtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7520 {
7521         pkp->dtpk_prov = pdp->dtpd_provider;
7522         pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7523
7524         pkp->dtpk_mod = pdp->dtpd_mod;
7525         pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7526
7527         pkp->dtpk_func = pdp->dtpd_func;
7528         pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7529
7530         pkp->dtpk_name = pdp->dtpd_name;
7531         pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7532
7533         pkp->dtpk_id = pdp->dtpd_id;
7534
7535         if (pkp->dtpk_id == DTRACE_IDNONE &&
7536             pkp->dtpk_pmatch == &dtrace_match_nul &&
7537             pkp->dtpk_mmatch == &dtrace_match_nul &&
7538             pkp->dtpk_fmatch == &dtrace_match_nul &&
7539             pkp->dtpk_nmatch == &dtrace_match_nul)
7540                 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7541 }
7542
7543 /*
7544  * DTrace Provider-to-Framework API Functions
7545  *
7546  * These functions implement much of the Provider-to-Framework API, as
7547  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7548  * the functions in the API for probe management (found below), and
7549  * dtrace_probe() itself (found above).
7550  */
7551
7552 /*
7553  * Register the calling provider with the DTrace framework.  This should
7554  * generally be called by DTrace providers in their attach(9E) entry point.
7555  */
7556 int
7557 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7558     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7559 {
7560         dtrace_provider_t *provider;
7561
7562         if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7563                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7564                     "arguments", name ? name : "<NULL>");
7565                 return (EINVAL);
7566         }
7567
7568         if (name[0] == '\0' || dtrace_badname(name)) {
7569                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7570                     "provider name", name);
7571                 return (EINVAL);
7572         }
7573
7574         if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7575             pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7576             pops->dtps_destroy == NULL ||
7577             ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7578                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7579                     "provider ops", name);
7580                 return (EINVAL);
7581         }
7582
7583         if (dtrace_badattr(&pap->dtpa_provider) ||
7584             dtrace_badattr(&pap->dtpa_mod) ||
7585             dtrace_badattr(&pap->dtpa_func) ||
7586             dtrace_badattr(&pap->dtpa_name) ||
7587             dtrace_badattr(&pap->dtpa_args)) {
7588                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7589                     "provider attributes", name);
7590                 return (EINVAL);
7591         }
7592
7593         if (priv & ~DTRACE_PRIV_ALL) {
7594                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7595                     "privilege attributes", name);
7596                 return (EINVAL);
7597         }
7598
7599         if ((priv & DTRACE_PRIV_KERNEL) &&
7600             (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7601             pops->dtps_usermode == NULL) {
7602                 cmn_err(CE_WARN, "failed to register provider '%s': need "
7603                     "dtps_usermode() op for given privilege attributes", name);
7604                 return (EINVAL);
7605         }
7606
7607         provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7608         provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7609         (void) strcpy(provider->dtpv_name, name);
7610
7611         provider->dtpv_attr = *pap;
7612         provider->dtpv_priv.dtpp_flags = priv;
7613         if (cr != NULL) {
7614                 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7615                 provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7616         }
7617         provider->dtpv_pops = *pops;
7618
7619         if (pops->dtps_provide == NULL) {
7620                 ASSERT(pops->dtps_provide_module != NULL);
7621                 provider->dtpv_pops.dtps_provide =
7622                     (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
7623         }
7624
7625         if (pops->dtps_provide_module == NULL) {
7626                 ASSERT(pops->dtps_provide != NULL);
7627                 provider->dtpv_pops.dtps_provide_module =
7628                     (void (*)(void *, modctl_t *))dtrace_nullop;
7629         }
7630
7631         if (pops->dtps_suspend == NULL) {
7632                 ASSERT(pops->dtps_resume == NULL);
7633                 provider->dtpv_pops.dtps_suspend =
7634                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7635                 provider->dtpv_pops.dtps_resume =
7636                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7637         }
7638
7639         provider->dtpv_arg = arg;
7640         *idp = (dtrace_provider_id_t)provider;
7641
7642         if (pops == &dtrace_provider_ops) {
7643                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7644                 ASSERT(MUTEX_HELD(&dtrace_lock));
7645                 ASSERT(dtrace_anon.dta_enabling == NULL);
7646
7647                 /*
7648                  * We make sure that the DTrace provider is at the head of
7649                  * the provider chain.
7650                  */
7651                 provider->dtpv_next = dtrace_provider;
7652                 dtrace_provider = provider;
7653                 return (0);
7654         }
7655
7656         mutex_enter(&dtrace_provider_lock);
7657         mutex_enter(&dtrace_lock);
7658
7659         /*
7660          * If there is at least one provider registered, we'll add this
7661          * provider after the first provider.
7662          */
7663         if (dtrace_provider != NULL) {
7664                 provider->dtpv_next = dtrace_provider->dtpv_next;
7665                 dtrace_provider->dtpv_next = provider;
7666         } else {
7667                 dtrace_provider = provider;
7668         }
7669
7670         if (dtrace_retained != NULL) {
7671                 dtrace_enabling_provide(provider);
7672
7673                 /*
7674                  * Now we need to call dtrace_enabling_matchall() -- which
7675                  * will acquire cpu_lock and dtrace_lock.  We therefore need
7676                  * to drop all of our locks before calling into it...
7677                  */
7678                 mutex_exit(&dtrace_lock);
7679                 mutex_exit(&dtrace_provider_lock);
7680                 dtrace_enabling_matchall();
7681
7682                 return (0);
7683         }
7684
7685         mutex_exit(&dtrace_lock);
7686         mutex_exit(&dtrace_provider_lock);
7687
7688         return (0);
7689 }
7690
7691 /*
7692  * Unregister the specified provider from the DTrace framework.  This should
7693  * generally be called by DTrace providers in their detach(9E) entry point.
7694  */
7695 int
7696 dtrace_unregister(dtrace_provider_id_t id)
7697 {
7698         dtrace_provider_t *old = (dtrace_provider_t *)id;
7699         dtrace_provider_t *prev = NULL;
7700         int i, self = 0, noreap = 0;
7701         dtrace_probe_t *probe, *first = NULL;
7702
7703         if (old->dtpv_pops.dtps_enable ==
7704             (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
7705                 /*
7706                  * If DTrace itself is the provider, we're called with locks
7707                  * already held.
7708                  */
7709                 ASSERT(old == dtrace_provider);
7710 #if defined(sun)
7711                 ASSERT(dtrace_devi != NULL);
7712 #endif
7713                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7714                 ASSERT(MUTEX_HELD(&dtrace_lock));
7715                 self = 1;
7716
7717                 if (dtrace_provider->dtpv_next != NULL) {
7718                         /*
7719                          * There's another provider here; return failure.
7720                          */
7721                         return (EBUSY);
7722                 }
7723         } else {
7724                 mutex_enter(&dtrace_provider_lock);
7725 #if defined(sun)
7726                 mutex_enter(&mod_lock);
7727 #endif
7728                 mutex_enter(&dtrace_lock);
7729         }
7730
7731         /*
7732          * If anyone has /dev/dtrace open, or if there are anonymous enabled
7733          * probes, we refuse to let providers slither away, unless this
7734          * provider has already been explicitly invalidated.
7735          */
7736         if (!old->dtpv_defunct &&
7737             (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7738             dtrace_anon.dta_state->dts_necbs > 0))) {
7739                 if (!self) {
7740                         mutex_exit(&dtrace_lock);
7741 #if defined(sun)
7742                         mutex_exit(&mod_lock);
7743 #endif
7744                         mutex_exit(&dtrace_provider_lock);
7745                 }
7746                 return (EBUSY);
7747         }
7748
7749         /*
7750          * Attempt to destroy the probes associated with this provider.
7751          */
7752         for (i = 0; i < dtrace_nprobes; i++) {
7753                 if ((probe = dtrace_probes[i]) == NULL)
7754                         continue;
7755
7756                 if (probe->dtpr_provider != old)
7757                         continue;
7758
7759                 if (probe->dtpr_ecb == NULL)
7760                         continue;
7761
7762                 /*
7763                  * If we are trying to unregister a defunct provider, and the
7764                  * provider was made defunct within the interval dictated by
7765                  * dtrace_unregister_defunct_reap, we'll (asynchronously)
7766                  * attempt to reap our enablings.  To denote that the provider
7767                  * should reattempt to unregister itself at some point in the
7768                  * future, we will return a differentiable error code (EAGAIN
7769                  * instead of EBUSY) in this case.
7770                  */
7771                 if (dtrace_gethrtime() - old->dtpv_defunct >
7772                     dtrace_unregister_defunct_reap)
7773                         noreap = 1;
7774
7775                 if (!self) {
7776                         mutex_exit(&dtrace_lock);
7777 #if defined(sun)
7778                         mutex_exit(&mod_lock);
7779 #endif
7780                         mutex_exit(&dtrace_provider_lock);
7781                 }
7782
7783                 if (noreap)
7784                         return (EBUSY);
7785
7786                 (void) taskq_dispatch(dtrace_taskq,
7787                     (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
7788
7789                 return (EAGAIN);
7790         }
7791
7792         /*
7793          * All of the probes for this provider are disabled; we can safely
7794          * remove all of them from their hash chains and from the probe array.
7795          */
7796         for (i = 0; i < dtrace_nprobes; i++) {
7797                 if ((probe = dtrace_probes[i]) == NULL)
7798                         continue;
7799
7800                 if (probe->dtpr_provider != old)
7801                         continue;
7802
7803                 dtrace_probes[i] = NULL;
7804
7805                 dtrace_hash_remove(dtrace_bymod, probe);
7806                 dtrace_hash_remove(dtrace_byfunc, probe);
7807                 dtrace_hash_remove(dtrace_byname, probe);
7808
7809                 if (first == NULL) {
7810                         first = probe;
7811                         probe->dtpr_nextmod = NULL;
7812                 } else {
7813                         probe->dtpr_nextmod = first;
7814                         first = probe;
7815                 }
7816         }
7817
7818         /*
7819          * The provider's probes have been removed from the hash chains and
7820          * from the probe array.  Now issue a dtrace_sync() to be sure that
7821          * everyone has cleared out from any probe array processing.
7822          */
7823         dtrace_sync();
7824
7825         for (probe = first; probe != NULL; probe = first) {
7826                 first = probe->dtpr_nextmod;
7827
7828                 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7829                     probe->dtpr_arg);
7830                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7831                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7832                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7833 #if defined(sun)
7834                 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7835 #else
7836                 free_unr(dtrace_arena, probe->dtpr_id);
7837 #endif
7838                 kmem_free(probe, sizeof (dtrace_probe_t));
7839         }
7840
7841         if ((prev = dtrace_provider) == old) {
7842 #if defined(sun)
7843                 ASSERT(self || dtrace_devi == NULL);
7844                 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7845 #endif
7846                 dtrace_provider = old->dtpv_next;
7847         } else {
7848                 while (prev != NULL && prev->dtpv_next != old)
7849                         prev = prev->dtpv_next;
7850
7851                 if (prev == NULL) {
7852                         panic("attempt to unregister non-existent "
7853                             "dtrace provider %p\n", (void *)id);
7854                 }
7855
7856                 prev->dtpv_next = old->dtpv_next;
7857         }
7858
7859         if (!self) {
7860                 mutex_exit(&dtrace_lock);
7861 #if defined(sun)
7862                 mutex_exit(&mod_lock);
7863 #endif
7864                 mutex_exit(&dtrace_provider_lock);
7865         }
7866
7867         kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7868         kmem_free(old, sizeof (dtrace_provider_t));
7869
7870         return (0);
7871 }
7872
7873 /*
7874  * Invalidate the specified provider.  All subsequent probe lookups for the
7875  * specified provider will fail, but its probes will not be removed.
7876  */
7877 void
7878 dtrace_invalidate(dtrace_provider_id_t id)
7879 {
7880         dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7881
7882         ASSERT(pvp->dtpv_pops.dtps_enable !=
7883             (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7884
7885         mutex_enter(&dtrace_provider_lock);
7886         mutex_enter(&dtrace_lock);
7887
7888         pvp->dtpv_defunct = dtrace_gethrtime();
7889
7890         mutex_exit(&dtrace_lock);
7891         mutex_exit(&dtrace_provider_lock);
7892 }
7893
7894 /*
7895  * Indicate whether or not DTrace has attached.
7896  */
7897 int
7898 dtrace_attached(void)
7899 {
7900         /*
7901          * dtrace_provider will be non-NULL iff the DTrace driver has
7902          * attached.  (It's non-NULL because DTrace is always itself a
7903          * provider.)
7904          */
7905         return (dtrace_provider != NULL);
7906 }
7907
7908 /*
7909  * Remove all the unenabled probes for the given provider.  This function is
7910  * not unlike dtrace_unregister(), except that it doesn't remove the provider
7911  * -- just as many of its associated probes as it can.
7912  */
7913 int
7914 dtrace_condense(dtrace_provider_id_t id)
7915 {
7916         dtrace_provider_t *prov = (dtrace_provider_t *)id;
7917         int i;
7918         dtrace_probe_t *probe;
7919
7920         /*
7921          * Make sure this isn't the dtrace provider itself.
7922          */
7923         ASSERT(prov->dtpv_pops.dtps_enable !=
7924             (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7925
7926         mutex_enter(&dtrace_provider_lock);
7927         mutex_enter(&dtrace_lock);
7928
7929         /*
7930          * Attempt to destroy the probes associated with this provider.
7931          */
7932         for (i = 0; i < dtrace_nprobes; i++) {
7933                 if ((probe = dtrace_probes[i]) == NULL)
7934                         continue;
7935
7936                 if (probe->dtpr_provider != prov)
7937                         continue;
7938
7939                 if (probe->dtpr_ecb != NULL)
7940                         continue;
7941
7942                 dtrace_probes[i] = NULL;
7943
7944                 dtrace_hash_remove(dtrace_bymod, probe);
7945                 dtrace_hash_remove(dtrace_byfunc, probe);
7946                 dtrace_hash_remove(dtrace_byname, probe);
7947
7948                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7949                     probe->dtpr_arg);
7950                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7951                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7952                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7953                 kmem_free(probe, sizeof (dtrace_probe_t));
7954 #if defined(sun)
7955                 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7956 #else
7957                 free_unr(dtrace_arena, i + 1);
7958 #endif
7959         }
7960
7961         mutex_exit(&dtrace_lock);
7962         mutex_exit(&dtrace_provider_lock);
7963
7964         return (0);
7965 }
7966
7967 /*
7968  * DTrace Probe Management Functions
7969  *
7970  * The functions in this section perform the DTrace probe management,
7971  * including functions to create probes, look-up probes, and call into the
7972  * providers to request that probes be provided.  Some of these functions are
7973  * in the Provider-to-Framework API; these functions can be identified by the
7974  * fact that they are not declared "static".
7975  */
7976
7977 /*
7978  * Create a probe with the specified module name, function name, and name.
7979  */
7980 dtrace_id_t
7981 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7982     const char *func, const char *name, int aframes, void *arg)
7983 {
7984         dtrace_probe_t *probe, **probes;
7985         dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7986         dtrace_id_t id;
7987
7988         if (provider == dtrace_provider) {
7989                 ASSERT(MUTEX_HELD(&dtrace_lock));
7990         } else {
7991                 mutex_enter(&dtrace_lock);
7992         }
7993
7994 #if defined(sun)
7995         id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7996             VM_BESTFIT | VM_SLEEP);
7997 #else
7998         id = alloc_unr(dtrace_arena);
7999 #endif
8000         probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8001
8002         probe->dtpr_id = id;
8003         probe->dtpr_gen = dtrace_probegen++;
8004         probe->dtpr_mod = dtrace_strdup(mod);
8005         probe->dtpr_func = dtrace_strdup(func);
8006         probe->dtpr_name = dtrace_strdup(name);
8007         probe->dtpr_arg = arg;
8008         probe->dtpr_aframes = aframes;
8009         probe->dtpr_provider = provider;
8010
8011         dtrace_hash_add(dtrace_bymod, probe);
8012         dtrace_hash_add(dtrace_byfunc, probe);
8013         dtrace_hash_add(dtrace_byname, probe);
8014
8015         if (id - 1 >= dtrace_nprobes) {
8016                 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8017                 size_t nsize = osize << 1;
8018
8019                 if (nsize == 0) {
8020                         ASSERT(osize == 0);
8021                         ASSERT(dtrace_probes == NULL);
8022                         nsize = sizeof (dtrace_probe_t *);
8023                 }
8024
8025                 probes = kmem_zalloc(nsize, KM_SLEEP);
8026
8027                 if (dtrace_probes == NULL) {
8028                         ASSERT(osize == 0);
8029                         dtrace_probes = probes;
8030                         dtrace_nprobes = 1;
8031                 } else {
8032                         dtrace_probe_t **oprobes = dtrace_probes;
8033
8034                         bcopy(oprobes, probes, osize);
8035                         dtrace_membar_producer();
8036                         dtrace_probes = probes;
8037
8038                         dtrace_sync();
8039
8040                         /*
8041                          * All CPUs are now seeing the new probes array; we can
8042                          * safely free the old array.
8043                          */
8044                         kmem_free(oprobes, osize);
8045                         dtrace_nprobes <<= 1;
8046                 }
8047
8048                 ASSERT(id - 1 < dtrace_nprobes);
8049         }
8050
8051         ASSERT(dtrace_probes[id - 1] == NULL);
8052         dtrace_probes[id - 1] = probe;
8053
8054         if (provider != dtrace_provider)
8055                 mutex_exit(&dtrace_lock);
8056
8057         return (id);
8058 }
8059
8060 static dtrace_probe_t *
8061 dtrace_probe_lookup_id(dtrace_id_t id)
8062 {
8063         ASSERT(MUTEX_HELD(&dtrace_lock));
8064
8065         if (id == 0 || id > dtrace_nprobes)
8066                 return (NULL);
8067
8068         return (dtrace_probes[id - 1]);
8069 }
8070
8071 static int
8072 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8073 {
8074         *((dtrace_id_t *)arg) = probe->dtpr_id;
8075
8076         return (DTRACE_MATCH_DONE);
8077 }
8078
8079 /*
8080  * Look up a probe based on provider and one or more of module name, function
8081  * name and probe name.
8082  */
8083 dtrace_id_t
8084 dtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
8085     char *func, char *name)
8086 {
8087         dtrace_probekey_t pkey;
8088         dtrace_id_t id;
8089         int match;
8090
8091         pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8092         pkey.dtpk_pmatch = &dtrace_match_string;
8093         pkey.dtpk_mod = mod;
8094         pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8095         pkey.dtpk_func = func;
8096         pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8097         pkey.dtpk_name = name;
8098         pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8099         pkey.dtpk_id = DTRACE_IDNONE;
8100
8101         mutex_enter(&dtrace_lock);
8102         match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8103             dtrace_probe_lookup_match, &id);
8104         mutex_exit(&dtrace_lock);
8105
8106         ASSERT(match == 1 || match == 0);
8107         return (match ? id : 0);
8108 }
8109
8110 /*
8111  * Returns the probe argument associated with the specified probe.
8112  */
8113 void *
8114 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8115 {
8116         dtrace_probe_t *probe;
8117         void *rval = NULL;
8118
8119         mutex_enter(&dtrace_lock);
8120
8121         if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8122             probe->dtpr_provider == (dtrace_provider_t *)id)
8123                 rval = probe->dtpr_arg;
8124
8125         mutex_exit(&dtrace_lock);
8126
8127         return (rval);
8128 }
8129
8130 /*
8131  * Copy a probe into a probe description.
8132  */
8133 static void
8134 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8135 {
8136         bzero(pdp, sizeof (dtrace_probedesc_t));
8137         pdp->dtpd_id = prp->dtpr_id;
8138
8139         (void) strncpy(pdp->dtpd_provider,
8140             prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8141
8142         (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8143         (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8144         (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8145 }
8146
8147 /*
8148  * Called to indicate that a probe -- or probes -- should be provided by a
8149  * specfied provider.  If the specified description is NULL, the provider will
8150  * be told to provide all of its probes.  (This is done whenever a new
8151  * consumer comes along, or whenever a retained enabling is to be matched.) If
8152  * the specified description is non-NULL, the provider is given the
8153  * opportunity to dynamically provide the specified probe, allowing providers
8154  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8155  * probes.)  If the provider is NULL, the operations will be applied to all
8156  * providers; if the provider is non-NULL the operations will only be applied
8157  * to the specified provider.  The dtrace_provider_lock must be held, and the
8158  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8159  * will need to grab the dtrace_lock when it reenters the framework through
8160  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8161  */
8162 static void
8163 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8164 {
8165 #if defined(sun)
8166         modctl_t *ctl;
8167 #endif
8168         int all = 0;
8169
8170         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8171
8172         if (prv == NULL) {
8173                 all = 1;
8174                 prv = dtrace_provider;
8175         }
8176
8177         do {
8178                 /*
8179                  * First, call the blanket provide operation.
8180                  */
8181                 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8182
8183 #if defined(sun)
8184                 /*
8185                  * Now call the per-module provide operation.  We will grab
8186                  * mod_lock to prevent the list from being modified.  Note
8187                  * that this also prevents the mod_busy bits from changing.
8188                  * (mod_busy can only be changed with mod_lock held.)
8189                  */
8190                 mutex_enter(&mod_lock);
8191
8192                 ctl = &modules;
8193                 do {
8194                         if (ctl->mod_busy || ctl->mod_mp == NULL)
8195                                 continue;
8196
8197                         prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8198
8199                 } while ((ctl = ctl->mod_next) != &modules);
8200
8201                 mutex_exit(&mod_lock);
8202 #endif
8203         } while (all && (prv = prv->dtpv_next) != NULL);
8204 }
8205
8206 #if defined(sun)
8207 /*
8208  * Iterate over each probe, and call the Framework-to-Provider API function
8209  * denoted by offs.
8210  */
8211 static void
8212 dtrace_probe_foreach(uintptr_t offs)
8213 {
8214         dtrace_provider_t *prov;
8215         void (*func)(void *, dtrace_id_t, void *);
8216         dtrace_probe_t *probe;
8217         dtrace_icookie_t cookie;
8218         int i;
8219
8220         /*
8221          * We disable interrupts to walk through the probe array.  This is
8222          * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8223          * won't see stale data.
8224          */
8225         cookie = dtrace_interrupt_disable();
8226
8227         for (i = 0; i < dtrace_nprobes; i++) {
8228                 if ((probe = dtrace_probes[i]) == NULL)
8229                         continue;
8230
8231                 if (probe->dtpr_ecb == NULL) {
8232                         /*
8233                          * This probe isn't enabled -- don't call the function.
8234                          */
8235                         continue;
8236                 }
8237
8238                 prov = probe->dtpr_provider;
8239                 func = *((void(**)(void *, dtrace_id_t, void *))
8240                     ((uintptr_t)&prov->dtpv_pops + offs));
8241
8242                 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8243         }
8244
8245         dtrace_interrupt_enable(cookie);
8246 }
8247 #endif
8248
8249 static int
8250 dtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8251 {
8252         dtrace_probekey_t pkey;
8253         uint32_t priv;
8254         uid_t uid;
8255         zoneid_t zoneid;
8256
8257         ASSERT(MUTEX_HELD(&dtrace_lock));
8258         dtrace_ecb_create_cache = NULL;
8259
8260         if (desc == NULL) {
8261                 /*
8262                  * If we're passed a NULL description, we're being asked to
8263                  * create an ECB with a NULL probe.
8264                  */
8265                 (void) dtrace_ecb_create_enable(NULL, enab);
8266                 return (0);
8267         }
8268
8269         dtrace_probekey(desc, &pkey);
8270         dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8271             &priv, &uid, &zoneid);
8272
8273         return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8274             enab));
8275 }
8276
8277 /*
8278  * DTrace Helper Provider Functions
8279  */
8280 static void
8281 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8282 {
8283         attr->dtat_name = DOF_ATTR_NAME(dofattr);
8284         attr->dtat_data = DOF_ATTR_DATA(dofattr);
8285         attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8286 }
8287
8288 static void
8289 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8290     const dof_provider_t *dofprov, char *strtab)
8291 {
8292         hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8293         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8294             dofprov->dofpv_provattr);
8295         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8296             dofprov->dofpv_modattr);
8297         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8298             dofprov->dofpv_funcattr);
8299         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8300             dofprov->dofpv_nameattr);
8301         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8302             dofprov->dofpv_argsattr);
8303 }
8304
8305 static void
8306 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8307 {
8308         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8309         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8310         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8311         dof_provider_t *provider;
8312         dof_probe_t *probe;
8313         uint32_t *off, *enoff;
8314         uint8_t *arg;
8315         char *strtab;
8316         uint_t i, nprobes;
8317         dtrace_helper_provdesc_t dhpv;
8318         dtrace_helper_probedesc_t dhpb;
8319         dtrace_meta_t *meta = dtrace_meta_pid;
8320         dtrace_mops_t *mops = &meta->dtm_mops;
8321         void *parg;
8322
8323         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8324         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8325             provider->dofpv_strtab * dof->dofh_secsize);
8326         prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8327             provider->dofpv_probes * dof->dofh_secsize);
8328         arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8329             provider->dofpv_prargs * dof->dofh_secsize);
8330         off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8331             provider->dofpv_proffs * dof->dofh_secsize);
8332
8333         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8334         off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8335         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8336         enoff = NULL;
8337
8338         /*
8339          * See dtrace_helper_provider_validate().
8340          */
8341         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8342             provider->dofpv_prenoffs != DOF_SECT_NONE) {
8343                 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8344                     provider->dofpv_prenoffs * dof->dofh_secsize);
8345                 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8346         }
8347
8348         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8349
8350         /*
8351          * Create the provider.
8352          */
8353         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8354
8355         if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8356                 return;
8357
8358         meta->dtm_count++;
8359
8360         /*
8361          * Create the probes.
8362          */
8363         for (i = 0; i < nprobes; i++) {
8364                 probe = (dof_probe_t *)(uintptr_t)(daddr +
8365                     prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8366
8367                 dhpb.dthpb_mod = dhp->dofhp_mod;
8368                 dhpb.dthpb_func = strtab + probe->dofpr_func;
8369                 dhpb.dthpb_name = strtab + probe->dofpr_name;
8370                 dhpb.dthpb_base = probe->dofpr_addr;
8371                 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8372                 dhpb.dthpb_noffs = probe->dofpr_noffs;
8373                 if (enoff != NULL) {
8374                         dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8375                         dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8376                 } else {
8377                         dhpb.dthpb_enoffs = NULL;
8378                         dhpb.dthpb_nenoffs = 0;
8379                 }
8380                 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8381                 dhpb.dthpb_nargc = probe->dofpr_nargc;
8382                 dhpb.dthpb_xargc = probe->dofpr_xargc;
8383                 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8384                 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8385
8386                 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8387         }
8388 }
8389
8390 static void
8391 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8392 {
8393         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8394         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8395         int i;
8396
8397         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8398
8399         for (i = 0; i < dof->dofh_secnum; i++) {
8400                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8401                     dof->dofh_secoff + i * dof->dofh_secsize);
8402
8403                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8404                         continue;
8405
8406                 dtrace_helper_provide_one(dhp, sec, pid);
8407         }
8408
8409         /*
8410          * We may have just created probes, so we must now rematch against
8411          * any retained enablings.  Note that this call will acquire both
8412          * cpu_lock and dtrace_lock; the fact that we are holding
8413          * dtrace_meta_lock now is what defines the ordering with respect to
8414          * these three locks.
8415          */
8416         dtrace_enabling_matchall();
8417 }
8418
8419 static void
8420 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8421 {
8422         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8423         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8424         dof_sec_t *str_sec;
8425         dof_provider_t *provider;
8426         char *strtab;
8427         dtrace_helper_provdesc_t dhpv;
8428         dtrace_meta_t *meta = dtrace_meta_pid;
8429         dtrace_mops_t *mops = &meta->dtm_mops;
8430
8431         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8432         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8433             provider->dofpv_strtab * dof->dofh_secsize);
8434
8435         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8436
8437         /*
8438          * Create the provider.
8439          */
8440         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8441
8442         mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8443
8444         meta->dtm_count--;
8445 }
8446
8447 static void
8448 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8449 {
8450         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8451         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8452         int i;
8453
8454         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8455
8456         for (i = 0; i < dof->dofh_secnum; i++) {
8457                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8458                     dof->dofh_secoff + i * dof->dofh_secsize);
8459
8460                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8461                         continue;
8462
8463                 dtrace_helper_provider_remove_one(dhp, sec, pid);
8464         }
8465 }
8466
8467 /*
8468  * DTrace Meta Provider-to-Framework API Functions
8469  *
8470  * These functions implement the Meta Provider-to-Framework API, as described
8471  * in <sys/dtrace.h>.
8472  */
8473 int
8474 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8475     dtrace_meta_provider_id_t *idp)
8476 {
8477         dtrace_meta_t *meta;
8478         dtrace_helpers_t *help, *next;
8479         int i;
8480
8481         *idp = DTRACE_METAPROVNONE;
8482
8483         /*
8484          * We strictly don't need the name, but we hold onto it for
8485          * debuggability. All hail error queues!
8486          */
8487         if (name == NULL) {
8488                 cmn_err(CE_WARN, "failed to register meta-provider: "
8489                     "invalid name");
8490                 return (EINVAL);
8491         }
8492
8493         if (mops == NULL ||
8494             mops->dtms_create_probe == NULL ||
8495             mops->dtms_provide_pid == NULL ||
8496             mops->dtms_remove_pid == NULL) {
8497                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8498                     "invalid ops", name);
8499                 return (EINVAL);
8500         }
8501
8502         meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8503         meta->dtm_mops = *mops;
8504         meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8505         (void) strcpy(meta->dtm_name, name);
8506         meta->dtm_arg = arg;
8507
8508         mutex_enter(&dtrace_meta_lock);
8509         mutex_enter(&dtrace_lock);
8510
8511         if (dtrace_meta_pid != NULL) {
8512                 mutex_exit(&dtrace_lock);
8513                 mutex_exit(&dtrace_meta_lock);
8514                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8515                     "user-land meta-provider exists", name);
8516                 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8517                 kmem_free(meta, sizeof (dtrace_meta_t));
8518                 return (EINVAL);
8519         }
8520
8521         dtrace_meta_pid = meta;
8522         *idp = (dtrace_meta_provider_id_t)meta;
8523
8524         /*
8525          * If there are providers and probes ready to go, pass them
8526          * off to the new meta provider now.
8527          */
8528
8529         help = dtrace_deferred_pid;
8530         dtrace_deferred_pid = NULL;
8531
8532         mutex_exit(&dtrace_lock);
8533
8534         while (help != NULL) {
8535                 for (i = 0; i < help->dthps_nprovs; i++) {
8536                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8537                             help->dthps_pid);
8538                 }
8539
8540                 next = help->dthps_next;
8541                 help->dthps_next = NULL;
8542                 help->dthps_prev = NULL;
8543                 help->dthps_deferred = 0;
8544                 help = next;
8545         }
8546
8547         mutex_exit(&dtrace_meta_lock);
8548
8549         return (0);
8550 }
8551
8552 int
8553 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8554 {
8555         dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8556
8557         mutex_enter(&dtrace_meta_lock);
8558         mutex_enter(&dtrace_lock);
8559
8560         if (old == dtrace_meta_pid) {
8561                 pp = &dtrace_meta_pid;
8562         } else {
8563                 panic("attempt to unregister non-existent "
8564                     "dtrace meta-provider %p\n", (void *)old);
8565         }
8566
8567         if (old->dtm_count != 0) {
8568                 mutex_exit(&dtrace_lock);
8569                 mutex_exit(&dtrace_meta_lock);
8570                 return (EBUSY);
8571         }
8572
8573         *pp = NULL;
8574
8575         mutex_exit(&dtrace_lock);
8576         mutex_exit(&dtrace_meta_lock);
8577
8578         kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8579         kmem_free(old, sizeof (dtrace_meta_t));
8580
8581         return (0);
8582 }
8583
8584
8585 /*
8586  * DTrace DIF Object Functions
8587  */
8588 static int
8589 dtrace_difo_err(uint_t pc, const char *format, ...)
8590 {
8591         if (dtrace_err_verbose) {
8592                 va_list alist;
8593
8594                 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8595                 va_start(alist, format);
8596                 (void) vuprintf(format, alist);
8597                 va_end(alist);
8598         }
8599
8600 #ifdef DTRACE_ERRDEBUG
8601         dtrace_errdebug(format);
8602 #endif
8603         return (1);
8604 }
8605
8606 /*
8607  * Validate a DTrace DIF object by checking the IR instructions.  The following
8608  * rules are currently enforced by dtrace_difo_validate():
8609  *
8610  * 1. Each instruction must have a valid opcode
8611  * 2. Each register, string, variable, or subroutine reference must be valid
8612  * 3. No instruction can modify register %r0 (must be zero)
8613  * 4. All instruction reserved bits must be set to zero
8614  * 5. The last instruction must be a "ret" instruction
8615  * 6. All branch targets must reference a valid instruction _after_ the branch
8616  */
8617 static int
8618 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8619     cred_t *cr)
8620 {
8621         int err = 0, i;
8622         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8623         int kcheckload;
8624         uint_t pc;
8625
8626         kcheckload = cr == NULL ||
8627             (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8628
8629         dp->dtdo_destructive = 0;
8630
8631         for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8632                 dif_instr_t instr = dp->dtdo_buf[pc];
8633
8634                 uint_t r1 = DIF_INSTR_R1(instr);
8635                 uint_t r2 = DIF_INSTR_R2(instr);
8636                 uint_t rd = DIF_INSTR_RD(instr);
8637                 uint_t rs = DIF_INSTR_RS(instr);
8638                 uint_t label = DIF_INSTR_LABEL(instr);
8639                 uint_t v = DIF_INSTR_VAR(instr);
8640                 uint_t subr = DIF_INSTR_SUBR(instr);
8641                 uint_t type = DIF_INSTR_TYPE(instr);
8642                 uint_t op = DIF_INSTR_OP(instr);
8643
8644                 switch (op) {
8645                 case DIF_OP_OR:
8646                 case DIF_OP_XOR:
8647                 case DIF_OP_AND:
8648                 case DIF_OP_SLL:
8649                 case DIF_OP_SRL:
8650                 case DIF_OP_SRA:
8651                 case DIF_OP_SUB:
8652                 case DIF_OP_ADD:
8653                 case DIF_OP_MUL:
8654                 case DIF_OP_SDIV:
8655                 case DIF_OP_UDIV:
8656                 case DIF_OP_SREM:
8657                 case DIF_OP_UREM:
8658                 case DIF_OP_COPYS:
8659                         if (r1 >= nregs)
8660                                 err += efunc(pc, "invalid register %u\n", r1);
8661                         if (r2 >= nregs)
8662                                 err += efunc(pc, "invalid register %u\n", r2);
8663                         if (rd >= nregs)
8664                                 err += efunc(pc, "invalid register %u\n", rd);
8665                         if (rd == 0)
8666                                 err += efunc(pc, "cannot write to %r0\n");
8667                         break;
8668                 case DIF_OP_NOT:
8669                 case DIF_OP_MOV:
8670                 case DIF_OP_ALLOCS:
8671                         if (r1 >= nregs)
8672                                 err += efunc(pc, "invalid register %u\n", r1);
8673                         if (r2 != 0)
8674                                 err += efunc(pc, "non-zero reserved bits\n");
8675                         if (rd >= nregs)
8676                                 err += efunc(pc, "invalid register %u\n", rd);
8677                         if (rd == 0)
8678                                 err += efunc(pc, "cannot write to %r0\n");
8679                         break;
8680                 case DIF_OP_LDSB:
8681                 case DIF_OP_LDSH:
8682                 case DIF_OP_LDSW:
8683                 case DIF_OP_LDUB:
8684                 case DIF_OP_LDUH:
8685                 case DIF_OP_LDUW:
8686                 case DIF_OP_LDX:
8687                         if (r1 >= nregs)
8688                                 err += efunc(pc, "invalid register %u\n", r1);
8689                         if (r2 != 0)
8690                                 err += efunc(pc, "non-zero reserved bits\n");
8691                         if (rd >= nregs)
8692                                 err += efunc(pc, "invalid register %u\n", rd);
8693                         if (rd == 0)
8694                                 err += efunc(pc, "cannot write to %r0\n");
8695                         if (kcheckload)
8696                                 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8697                                     DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8698                         break;
8699                 case DIF_OP_RLDSB:
8700                 case DIF_OP_RLDSH:
8701                 case DIF_OP_RLDSW:
8702                 case DIF_OP_RLDUB:
8703                 case DIF_OP_RLDUH:
8704                 case DIF_OP_RLDUW:
8705                 case DIF_OP_RLDX:
8706                         if (r1 >= nregs)
8707                                 err += efunc(pc, "invalid register %u\n", r1);
8708                         if (r2 != 0)
8709                                 err += efunc(pc, "non-zero reserved bits\n");
8710                         if (rd >= nregs)
8711                                 err += efunc(pc, "invalid register %u\n", rd);
8712                         if (rd == 0)
8713                                 err += efunc(pc, "cannot write to %r0\n");
8714                         break;
8715                 case DIF_OP_ULDSB:
8716                 case DIF_OP_ULDSH:
8717                 case DIF_OP_ULDSW:
8718                 case DIF_OP_ULDUB:
8719                 case DIF_OP_ULDUH:
8720                 case DIF_OP_ULDUW:
8721                 case DIF_OP_ULDX:
8722                         if (r1 >= nregs)
8723                                 err += efunc(pc, "invalid register %u\n", r1);
8724                         if (r2 != 0)
8725                                 err += efunc(pc, "non-zero reserved bits\n");
8726                         if (rd >= nregs)
8727                                 err += efunc(pc, "invalid register %u\n", rd);
8728                         if (rd == 0)
8729                                 err += efunc(pc, "cannot write to %r0\n");
8730                         break;
8731                 case DIF_OP_STB:
8732                 case DIF_OP_STH:
8733                 case DIF_OP_STW:
8734                 case DIF_OP_STX:
8735                         if (r1 >= nregs)
8736                                 err += efunc(pc, "invalid register %u\n", r1);
8737                         if (r2 != 0)
8738                                 err += efunc(pc, "non-zero reserved bits\n");
8739                         if (rd >= nregs)
8740                                 err += efunc(pc, "invalid register %u\n", rd);
8741                         if (rd == 0)
8742                                 err += efunc(pc, "cannot write to 0 address\n");
8743                         break;
8744                 case DIF_OP_CMP:
8745                 case DIF_OP_SCMP:
8746                         if (r1 >= nregs)
8747                                 err += efunc(pc, "invalid register %u\n", r1);
8748                         if (r2 >= nregs)
8749                                 err += efunc(pc, "invalid register %u\n", r2);
8750                         if (rd != 0)
8751                                 err += efunc(pc, "non-zero reserved bits\n");
8752                         break;
8753                 case DIF_OP_TST:
8754                         if (r1 >= nregs)
8755                                 err += efunc(pc, "invalid register %u\n", r1);
8756                         if (r2 != 0 || rd != 0)
8757                                 err += efunc(pc, "non-zero reserved bits\n");
8758                         break;
8759                 case DIF_OP_BA:
8760                 case DIF_OP_BE:
8761                 case DIF_OP_BNE:
8762                 case DIF_OP_BG:
8763                 case DIF_OP_BGU:
8764                 case DIF_OP_BGE:
8765                 case DIF_OP_BGEU:
8766                 case DIF_OP_BL:
8767                 case DIF_OP_BLU:
8768                 case DIF_OP_BLE:
8769                 case DIF_OP_BLEU:
8770                         if (label >= dp->dtdo_len) {
8771                                 err += efunc(pc, "invalid branch target %u\n",
8772                                     label);
8773                         }
8774                         if (label <= pc) {
8775                                 err += efunc(pc, "backward branch to %u\n",
8776                                     label);
8777                         }
8778                         break;
8779                 case DIF_OP_RET:
8780                         if (r1 != 0 || r2 != 0)
8781                                 err += efunc(pc, "non-zero reserved bits\n");
8782                         if (rd >= nregs)
8783                                 err += efunc(pc, "invalid register %u\n", rd);
8784                         break;
8785                 case DIF_OP_NOP:
8786                 case DIF_OP_POPTS:
8787                 case DIF_OP_FLUSHTS:
8788                         if (r1 != 0 || r2 != 0 || rd != 0)
8789                                 err += efunc(pc, "non-zero reserved bits\n");
8790                         break;
8791                 case DIF_OP_SETX:
8792                         if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8793                                 err += efunc(pc, "invalid integer ref %u\n",
8794                                     DIF_INSTR_INTEGER(instr));
8795                         }
8796                         if (rd >= nregs)
8797                                 err += efunc(pc, "invalid register %u\n", rd);
8798                         if (rd == 0)
8799                                 err += efunc(pc, "cannot write to %r0\n");
8800                         break;
8801                 case DIF_OP_SETS:
8802                         if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8803                                 err += efunc(pc, "invalid string ref %u\n",
8804                                     DIF_INSTR_STRING(instr));
8805                         }
8806                         if (rd >= nregs)
8807                                 err += efunc(pc, "invalid register %u\n", rd);
8808                         if (rd == 0)
8809                                 err += efunc(pc, "cannot write to %r0\n");
8810                         break;
8811                 case DIF_OP_LDGA:
8812                 case DIF_OP_LDTA:
8813                         if (r1 > DIF_VAR_ARRAY_MAX)
8814                                 err += efunc(pc, "invalid array %u\n", r1);
8815                         if (r2 >= nregs)
8816                                 err += efunc(pc, "invalid register %u\n", r2);
8817                         if (rd >= nregs)
8818                                 err += efunc(pc, "invalid register %u\n", rd);
8819                         if (rd == 0)
8820                                 err += efunc(pc, "cannot write to %r0\n");
8821                         break;
8822                 case DIF_OP_LDGS:
8823                 case DIF_OP_LDTS:
8824                 case DIF_OP_LDLS:
8825                 case DIF_OP_LDGAA:
8826                 case DIF_OP_LDTAA:
8827                         if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8828                                 err += efunc(pc, "invalid variable %u\n", v);
8829                         if (rd >= nregs)
8830                                 err += efunc(pc, "invalid register %u\n", rd);
8831                         if (rd == 0)
8832                                 err += efunc(pc, "cannot write to %r0\n");
8833                         break;
8834                 case DIF_OP_STGS:
8835                 case DIF_OP_STTS:
8836                 case DIF_OP_STLS:
8837                 case DIF_OP_STGAA:
8838                 case DIF_OP_STTAA:
8839                         if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8840                                 err += efunc(pc, "invalid variable %u\n", v);
8841                         if (rs >= nregs)
8842                                 err += efunc(pc, "invalid register %u\n", rd);
8843                         break;
8844                 case DIF_OP_CALL:
8845                         if (subr > DIF_SUBR_MAX)
8846                                 err += efunc(pc, "invalid subr %u\n", subr);
8847                         if (rd >= nregs)
8848                                 err += efunc(pc, "invalid register %u\n", rd);
8849                         if (rd == 0)
8850                                 err += efunc(pc, "cannot write to %r0\n");
8851
8852                         if (subr == DIF_SUBR_COPYOUT ||
8853                             subr == DIF_SUBR_COPYOUTSTR) {
8854                                 dp->dtdo_destructive = 1;
8855                         }
8856                         break;
8857                 case DIF_OP_PUSHTR:
8858                         if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8859                                 err += efunc(pc, "invalid ref type %u\n", type);
8860                         if (r2 >= nregs)
8861                                 err += efunc(pc, "invalid register %u\n", r2);
8862                         if (rs >= nregs)
8863                                 err += efunc(pc, "invalid register %u\n", rs);
8864                         break;
8865                 case DIF_OP_PUSHTV:
8866                         if (type != DIF_TYPE_CTF)
8867                                 err += efunc(pc, "invalid val type %u\n", type);
8868                         if (r2 >= nregs)
8869                                 err += efunc(pc, "invalid register %u\n", r2);
8870                         if (rs >= nregs)
8871                                 err += efunc(pc, "invalid register %u\n", rs);
8872                         break;
8873                 default:
8874                         err += efunc(pc, "invalid opcode %u\n",
8875                             DIF_INSTR_OP(instr));
8876                 }
8877         }
8878
8879         if (dp->dtdo_len != 0 &&
8880             DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8881                 err += efunc(dp->dtdo_len - 1,
8882                     "expected 'ret' as last DIF instruction\n");
8883         }
8884
8885         if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8886                 /*
8887                  * If we're not returning by reference, the size must be either
8888                  * 0 or the size of one of the base types.
8889                  */
8890                 switch (dp->dtdo_rtype.dtdt_size) {
8891                 case 0:
8892                 case sizeof (uint8_t):
8893                 case sizeof (uint16_t):
8894                 case sizeof (uint32_t):
8895                 case sizeof (uint64_t):
8896                         break;
8897
8898                 default:
8899                         err += efunc(dp->dtdo_len - 1, "bad return size");
8900                 }
8901         }
8902
8903         for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8904                 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8905                 dtrace_diftype_t *vt, *et;
8906                 uint_t id, ndx;
8907
8908                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8909                     v->dtdv_scope != DIFV_SCOPE_THREAD &&
8910                     v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8911                         err += efunc(i, "unrecognized variable scope %d\n",
8912                             v->dtdv_scope);
8913                         break;
8914                 }
8915
8916                 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8917                     v->dtdv_kind != DIFV_KIND_SCALAR) {
8918                         err += efunc(i, "unrecognized variable type %d\n",
8919                             v->dtdv_kind);
8920                         break;
8921                 }
8922
8923                 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8924                         err += efunc(i, "%d exceeds variable id limit\n", id);
8925                         break;
8926                 }
8927
8928                 if (id < DIF_VAR_OTHER_UBASE)
8929                         continue;
8930
8931                 /*
8932                  * For user-defined variables, we need to check that this
8933                  * definition is identical to any previous definition that we
8934                  * encountered.
8935                  */
8936                 ndx = id - DIF_VAR_OTHER_UBASE;
8937
8938                 switch (v->dtdv_scope) {
8939                 case DIFV_SCOPE_GLOBAL:
8940                         if (ndx < vstate->dtvs_nglobals) {
8941                                 dtrace_statvar_t *svar;
8942
8943                                 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8944                                         existing = &svar->dtsv_var;
8945                         }
8946
8947                         break;
8948
8949                 case DIFV_SCOPE_THREAD:
8950                         if (ndx < vstate->dtvs_ntlocals)
8951                                 existing = &vstate->dtvs_tlocals[ndx];
8952                         break;
8953
8954                 case DIFV_SCOPE_LOCAL:
8955                         if (ndx < vstate->dtvs_nlocals) {
8956                                 dtrace_statvar_t *svar;
8957
8958                                 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8959                                         existing = &svar->dtsv_var;
8960                         }
8961
8962                         break;
8963                 }
8964
8965                 vt = &v->dtdv_type;
8966
8967                 if (vt->dtdt_flags & DIF_TF_BYREF) {
8968                         if (vt->dtdt_size == 0) {
8969                                 err += efunc(i, "zero-sized variable\n");
8970                                 break;
8971                         }
8972
8973                         if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8974                             vt->dtdt_size > dtrace_global_maxsize) {
8975                                 err += efunc(i, "oversized by-ref global\n");
8976                                 break;
8977                         }
8978                 }
8979
8980                 if (existing == NULL || existing->dtdv_id == 0)
8981                         continue;
8982
8983                 ASSERT(existing->dtdv_id == v->dtdv_id);
8984                 ASSERT(existing->dtdv_scope == v->dtdv_scope);
8985
8986                 if (existing->dtdv_kind != v->dtdv_kind)
8987                         err += efunc(i, "%d changed variable kind\n", id);
8988
8989                 et = &existing->dtdv_type;
8990
8991                 if (vt->dtdt_flags != et->dtdt_flags) {
8992                         err += efunc(i, "%d changed variable type flags\n", id);
8993                         break;
8994                 }
8995
8996                 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8997                         err += efunc(i, "%d changed variable type size\n", id);
8998                         break;
8999                 }
9000         }
9001
9002         return (err);
9003 }
9004
9005 /*
9006  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9007  * are much more constrained than normal DIFOs.  Specifically, they may
9008  * not:
9009  *
9010  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9011  *    miscellaneous string routines
9012  * 2. Access DTrace variables other than the args[] array, and the
9013  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9014  * 3. Have thread-local variables.
9015  * 4. Have dynamic variables.
9016  */
9017 static int
9018 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9019 {
9020         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9021         int err = 0;
9022         uint_t pc;
9023
9024         for (pc = 0; pc < dp->dtdo_len; pc++) {
9025                 dif_instr_t instr = dp->dtdo_buf[pc];
9026
9027                 uint_t v = DIF_INSTR_VAR(instr);
9028                 uint_t subr = DIF_INSTR_SUBR(instr);
9029                 uint_t op = DIF_INSTR_OP(instr);
9030
9031                 switch (op) {
9032                 case DIF_OP_OR:
9033                 case DIF_OP_XOR:
9034                 case DIF_OP_AND:
9035                 case DIF_OP_SLL:
9036                 case DIF_OP_SRL:
9037                 case DIF_OP_SRA:
9038                 case DIF_OP_SUB:
9039                 case DIF_OP_ADD:
9040                 case DIF_OP_MUL:
9041                 case DIF_OP_SDIV:
9042                 case DIF_OP_UDIV:
9043                 case DIF_OP_SREM:
9044                 case DIF_OP_UREM:
9045                 case DIF_OP_COPYS:
9046                 case DIF_OP_NOT:
9047                 case DIF_OP_MOV:
9048                 case DIF_OP_RLDSB:
9049                 case DIF_OP_RLDSH:
9050                 case DIF_OP_RLDSW:
9051                 case DIF_OP_RLDUB:
9052                 case DIF_OP_RLDUH:
9053                 case DIF_OP_RLDUW:
9054                 case DIF_OP_RLDX:
9055                 case DIF_OP_ULDSB:
9056                 case DIF_OP_ULDSH:
9057                 case DIF_OP_ULDSW:
9058                 case DIF_OP_ULDUB:
9059                 case DIF_OP_ULDUH:
9060                 case DIF_OP_ULDUW:
9061                 case DIF_OP_ULDX:
9062                 case DIF_OP_STB:
9063                 case DIF_OP_STH:
9064                 case DIF_OP_STW:
9065                 case DIF_OP_STX:
9066                 case DIF_OP_ALLOCS:
9067                 case DIF_OP_CMP:
9068                 case DIF_OP_SCMP:
9069                 case DIF_OP_TST:
9070                 case DIF_OP_BA:
9071                 case DIF_OP_BE:
9072                 case DIF_OP_BNE:
9073                 case DIF_OP_BG:
9074                 case DIF_OP_BGU:
9075                 case DIF_OP_BGE:
9076                 case DIF_OP_BGEU:
9077                 case DIF_OP_BL:
9078                 case DIF_OP_BLU:
9079                 case DIF_OP_BLE:
9080                 case DIF_OP_BLEU:
9081                 case DIF_OP_RET:
9082                 case DIF_OP_NOP:
9083                 case DIF_OP_POPTS:
9084                 case DIF_OP_FLUSHTS:
9085                 case DIF_OP_SETX:
9086                 case DIF_OP_SETS:
9087                 case DIF_OP_LDGA:
9088                 case DIF_OP_LDLS:
9089                 case DIF_OP_STGS:
9090                 case DIF_OP_STLS:
9091                 case DIF_OP_PUSHTR:
9092                 case DIF_OP_PUSHTV:
9093                         break;
9094
9095                 case DIF_OP_LDGS:
9096                         if (v >= DIF_VAR_OTHER_UBASE)
9097                                 break;
9098
9099                         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9100                                 break;
9101
9102                         if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9103                             v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9104                             v == DIF_VAR_EXECARGS ||
9105                             v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9106                             v == DIF_VAR_UID || v == DIF_VAR_GID)
9107                                 break;
9108
9109                         err += efunc(pc, "illegal variable %u\n", v);
9110                         break;
9111
9112                 case DIF_OP_LDTA:
9113                 case DIF_OP_LDTS:
9114                 case DIF_OP_LDGAA:
9115                 case DIF_OP_LDTAA:
9116                         err += efunc(pc, "illegal dynamic variable load\n");
9117                         break;
9118
9119                 case DIF_OP_STTS:
9120                 case DIF_OP_STGAA:
9121                 case DIF_OP_STTAA:
9122                         err += efunc(pc, "illegal dynamic variable store\n");
9123                         break;
9124
9125                 case DIF_OP_CALL:
9126                         if (subr == DIF_SUBR_ALLOCA ||
9127                             subr == DIF_SUBR_BCOPY ||
9128                             subr == DIF_SUBR_COPYIN ||
9129                             subr == DIF_SUBR_COPYINTO ||
9130                             subr == DIF_SUBR_COPYINSTR ||
9131                             subr == DIF_SUBR_INDEX ||
9132                             subr == DIF_SUBR_INET_NTOA ||
9133                             subr == DIF_SUBR_INET_NTOA6 ||
9134                             subr == DIF_SUBR_INET_NTOP ||
9135                             subr == DIF_SUBR_LLTOSTR ||
9136                             subr == DIF_SUBR_RINDEX ||
9137                             subr == DIF_SUBR_STRCHR ||
9138                             subr == DIF_SUBR_STRJOIN ||
9139                             subr == DIF_SUBR_STRRCHR ||
9140                             subr == DIF_SUBR_STRSTR ||
9141                             subr == DIF_SUBR_HTONS ||
9142                             subr == DIF_SUBR_HTONL ||
9143                             subr == DIF_SUBR_HTONLL ||
9144                             subr == DIF_SUBR_NTOHS ||
9145                             subr == DIF_SUBR_NTOHL ||
9146                             subr == DIF_SUBR_NTOHLL ||
9147                             subr == DIF_SUBR_MEMREF ||
9148 #if !defined(sun)
9149                             subr == DIF_SUBR_MEMSTR ||
9150 #endif
9151                             subr == DIF_SUBR_TYPEREF)
9152                                 break;
9153
9154                         err += efunc(pc, "invalid subr %u\n", subr);
9155                         break;
9156
9157                 default:
9158                         err += efunc(pc, "invalid opcode %u\n",
9159                             DIF_INSTR_OP(instr));
9160                 }
9161         }
9162
9163         return (err);
9164 }
9165
9166 /*
9167  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9168  * basis; 0 if not.
9169  */
9170 static int
9171 dtrace_difo_cacheable(dtrace_difo_t *dp)
9172 {
9173         int i;
9174
9175         if (dp == NULL)
9176                 return (0);
9177
9178         for (i = 0; i < dp->dtdo_varlen; i++) {
9179                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9180
9181                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9182                         continue;
9183
9184                 switch (v->dtdv_id) {
9185                 case DIF_VAR_CURTHREAD:
9186                 case DIF_VAR_PID:
9187                 case DIF_VAR_TID:
9188                 case DIF_VAR_EXECARGS:
9189                 case DIF_VAR_EXECNAME:
9190                 case DIF_VAR_ZONENAME:
9191                         break;
9192
9193                 default:
9194                         return (0);
9195                 }
9196         }
9197
9198         /*
9199          * This DIF object may be cacheable.  Now we need to look for any
9200          * array loading instructions, any memory loading instructions, or
9201          * any stores to thread-local variables.
9202          */
9203         for (i = 0; i < dp->dtdo_len; i++) {
9204                 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9205
9206                 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9207                     (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9208                     (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9209                     op == DIF_OP_LDGA || op == DIF_OP_STTS)
9210                         return (0);
9211         }
9212
9213         return (1);
9214 }
9215
9216 static void
9217 dtrace_difo_hold(dtrace_difo_t *dp)
9218 {
9219         int i;
9220
9221         ASSERT(MUTEX_HELD(&dtrace_lock));
9222
9223         dp->dtdo_refcnt++;
9224         ASSERT(dp->dtdo_refcnt != 0);
9225
9226         /*
9227          * We need to check this DIF object for references to the variable
9228          * DIF_VAR_VTIMESTAMP.
9229          */
9230         for (i = 0; i < dp->dtdo_varlen; i++) {
9231                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9232
9233                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9234                         continue;
9235
9236                 if (dtrace_vtime_references++ == 0)
9237                         dtrace_vtime_enable();
9238         }
9239 }
9240
9241 /*
9242  * This routine calculates the dynamic variable chunksize for a given DIF
9243  * object.  The calculation is not fool-proof, and can probably be tricked by
9244  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9245  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9246  * if a dynamic variable size exceeds the chunksize.
9247  */
9248 static void
9249 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9250 {
9251         uint64_t sval = 0;
9252         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9253         const dif_instr_t *text = dp->dtdo_buf;
9254         uint_t pc, srd = 0;
9255         uint_t ttop = 0;
9256         size_t size, ksize;
9257         uint_t id, i;
9258
9259         for (pc = 0; pc < dp->dtdo_len; pc++) {
9260                 dif_instr_t instr = text[pc];
9261                 uint_t op = DIF_INSTR_OP(instr);
9262                 uint_t rd = DIF_INSTR_RD(instr);
9263                 uint_t r1 = DIF_INSTR_R1(instr);
9264                 uint_t nkeys = 0;
9265                 uchar_t scope = 0;
9266
9267                 dtrace_key_t *key = tupregs;
9268
9269                 switch (op) {
9270                 case DIF_OP_SETX:
9271                         sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9272                         srd = rd;
9273                         continue;
9274
9275                 case DIF_OP_STTS:
9276                         key = &tupregs[DIF_DTR_NREGS];
9277                         key[0].dttk_size = 0;
9278                         key[1].dttk_size = 0;
9279                         nkeys = 2;
9280                         scope = DIFV_SCOPE_THREAD;
9281                         break;
9282
9283                 case DIF_OP_STGAA:
9284                 case DIF_OP_STTAA:
9285                         nkeys = ttop;
9286
9287                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9288                                 key[nkeys++].dttk_size = 0;
9289
9290                         key[nkeys++].dttk_size = 0;
9291
9292                         if (op == DIF_OP_STTAA) {
9293                                 scope = DIFV_SCOPE_THREAD;
9294                         } else {
9295                                 scope = DIFV_SCOPE_GLOBAL;
9296                         }
9297
9298                         break;
9299
9300                 case DIF_OP_PUSHTR:
9301                         if (ttop == DIF_DTR_NREGS)
9302                                 return;
9303
9304                         if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9305                                 /*
9306                                  * If the register for the size of the "pushtr"
9307                                  * is %r0 (or the value is 0) and the type is
9308                                  * a string, we'll use the system-wide default
9309                                  * string size.
9310                                  */
9311                                 tupregs[ttop++].dttk_size =
9312                                     dtrace_strsize_default;
9313                         } else {
9314                                 if (srd == 0)
9315                                         return;
9316
9317                                 tupregs[ttop++].dttk_size = sval;
9318                         }
9319
9320                         break;
9321
9322                 case DIF_OP_PUSHTV:
9323                         if (ttop == DIF_DTR_NREGS)
9324                                 return;
9325
9326                         tupregs[ttop++].dttk_size = 0;
9327                         break;
9328
9329                 case DIF_OP_FLUSHTS:
9330                         ttop = 0;
9331                         break;
9332
9333                 case DIF_OP_POPTS:
9334                         if (ttop != 0)
9335                                 ttop--;
9336                         break;
9337                 }
9338
9339                 sval = 0;
9340                 srd = 0;
9341
9342                 if (nkeys == 0)
9343                         continue;
9344
9345                 /*
9346                  * We have a dynamic variable allocation; calculate its size.
9347                  */
9348                 for (ksize = 0, i = 0; i < nkeys; i++)
9349                         ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9350
9351                 size = sizeof (dtrace_dynvar_t);
9352                 size += sizeof (dtrace_key_t) * (nkeys - 1);
9353                 size += ksize;
9354
9355                 /*
9356                  * Now we need to determine the size of the stored data.
9357                  */
9358                 id = DIF_INSTR_VAR(instr);
9359
9360                 for (i = 0; i < dp->dtdo_varlen; i++) {
9361                         dtrace_difv_t *v = &dp->dtdo_vartab[i];
9362
9363                         if (v->dtdv_id == id && v->dtdv_scope == scope) {
9364                                 size += v->dtdv_type.dtdt_size;
9365                                 break;
9366                         }
9367                 }
9368
9369                 if (i == dp->dtdo_varlen)
9370                         return;
9371
9372                 /*
9373                  * We have the size.  If this is larger than the chunk size
9374                  * for our dynamic variable state, reset the chunk size.
9375                  */
9376                 size = P2ROUNDUP(size, sizeof (uint64_t));
9377
9378                 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9379                         vstate->dtvs_dynvars.dtds_chunksize = size;
9380         }
9381 }
9382
9383 static void
9384 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9385 {
9386         int i, oldsvars, osz, nsz, otlocals, ntlocals;
9387         uint_t id;
9388
9389         ASSERT(MUTEX_HELD(&dtrace_lock));
9390         ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9391
9392         for (i = 0; i < dp->dtdo_varlen; i++) {
9393                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9394                 dtrace_statvar_t *svar, ***svarp = NULL;
9395                 size_t dsize = 0;
9396                 uint8_t scope = v->dtdv_scope;
9397                 int *np = NULL;
9398
9399                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9400                         continue;
9401
9402                 id -= DIF_VAR_OTHER_UBASE;
9403
9404                 switch (scope) {
9405                 case DIFV_SCOPE_THREAD:
9406                         while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9407                                 dtrace_difv_t *tlocals;
9408
9409                                 if ((ntlocals = (otlocals << 1)) == 0)
9410                                         ntlocals = 1;
9411
9412                                 osz = otlocals * sizeof (dtrace_difv_t);
9413                                 nsz = ntlocals * sizeof (dtrace_difv_t);
9414
9415                                 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9416
9417                                 if (osz != 0) {
9418                                         bcopy(vstate->dtvs_tlocals,
9419                                             tlocals, osz);
9420                                         kmem_free(vstate->dtvs_tlocals, osz);
9421                                 }
9422
9423                                 vstate->dtvs_tlocals = tlocals;
9424                                 vstate->dtvs_ntlocals = ntlocals;
9425                         }
9426
9427                         vstate->dtvs_tlocals[id] = *v;
9428                         continue;
9429
9430                 case DIFV_SCOPE_LOCAL:
9431                         np = &vstate->dtvs_nlocals;
9432                         svarp = &vstate->dtvs_locals;
9433
9434                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9435                                 dsize = NCPU * (v->dtdv_type.dtdt_size +
9436                                     sizeof (uint64_t));
9437                         else
9438                                 dsize = NCPU * sizeof (uint64_t);
9439
9440                         break;
9441
9442                 case DIFV_SCOPE_GLOBAL:
9443                         np = &vstate->dtvs_nglobals;
9444                         svarp = &vstate->dtvs_globals;
9445
9446                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9447                                 dsize = v->dtdv_type.dtdt_size +
9448                                     sizeof (uint64_t);
9449
9450                         break;
9451
9452                 default:
9453                         ASSERT(0);
9454                 }
9455
9456                 while (id >= (oldsvars = *np)) {
9457                         dtrace_statvar_t **statics;
9458                         int newsvars, oldsize, newsize;
9459
9460                         if ((newsvars = (oldsvars << 1)) == 0)
9461                                 newsvars = 1;
9462
9463                         oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9464                         newsize = newsvars * sizeof (dtrace_statvar_t *);
9465
9466                         statics = kmem_zalloc(newsize, KM_SLEEP);
9467
9468                         if (oldsize != 0) {
9469                                 bcopy(*svarp, statics, oldsize);
9470                                 kmem_free(*svarp, oldsize);
9471                         }
9472
9473                         *svarp = statics;
9474                         *np = newsvars;
9475                 }
9476
9477                 if ((svar = (*svarp)[id]) == NULL) {
9478                         svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9479                         svar->dtsv_var = *v;
9480
9481                         if ((svar->dtsv_size = dsize) != 0) {
9482                                 svar->dtsv_data = (uint64_t)(uintptr_t)
9483                                     kmem_zalloc(dsize, KM_SLEEP);
9484                         }
9485
9486                         (*svarp)[id] = svar;
9487                 }
9488
9489                 svar->dtsv_refcnt++;
9490         }
9491
9492         dtrace_difo_chunksize(dp, vstate);
9493         dtrace_difo_hold(dp);
9494 }
9495
9496 static dtrace_difo_t *
9497 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9498 {
9499         dtrace_difo_t *new;
9500         size_t sz;
9501
9502         ASSERT(dp->dtdo_buf != NULL);
9503         ASSERT(dp->dtdo_refcnt != 0);
9504
9505         new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9506
9507         ASSERT(dp->dtdo_buf != NULL);
9508         sz = dp->dtdo_len * sizeof (dif_instr_t);
9509         new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9510         bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9511         new->dtdo_len = dp->dtdo_len;
9512
9513         if (dp->dtdo_strtab != NULL) {
9514                 ASSERT(dp->dtdo_strlen != 0);
9515                 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9516                 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9517                 new->dtdo_strlen = dp->dtdo_strlen;
9518         }
9519
9520         if (dp->dtdo_inttab != NULL) {
9521                 ASSERT(dp->dtdo_intlen != 0);
9522                 sz = dp->dtdo_intlen * sizeof (uint64_t);
9523                 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9524                 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9525                 new->dtdo_intlen = dp->dtdo_intlen;
9526         }
9527
9528         if (dp->dtdo_vartab != NULL) {
9529                 ASSERT(dp->dtdo_varlen != 0);
9530                 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9531                 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9532                 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9533                 new->dtdo_varlen = dp->dtdo_varlen;
9534         }
9535
9536         dtrace_difo_init(new, vstate);
9537         return (new);
9538 }
9539
9540 static void
9541 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9542 {
9543         int i;
9544
9545         ASSERT(dp->dtdo_refcnt == 0);
9546
9547         for (i = 0; i < dp->dtdo_varlen; i++) {
9548                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9549                 dtrace_statvar_t *svar, **svarp = NULL;
9550                 uint_t id;
9551                 uint8_t scope = v->dtdv_scope;
9552                 int *np = NULL;
9553
9554                 switch (scope) {
9555                 case DIFV_SCOPE_THREAD:
9556                         continue;
9557
9558                 case DIFV_SCOPE_LOCAL:
9559                         np = &vstate->dtvs_nlocals;
9560                         svarp = vstate->dtvs_locals;
9561                         break;
9562
9563                 case DIFV_SCOPE_GLOBAL:
9564                         np = &vstate->dtvs_nglobals;
9565                         svarp = vstate->dtvs_globals;
9566                         break;
9567
9568                 default:
9569                         ASSERT(0);
9570                 }
9571
9572                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9573                         continue;
9574
9575                 id -= DIF_VAR_OTHER_UBASE;
9576                 ASSERT(id < *np);
9577
9578                 svar = svarp[id];
9579                 ASSERT(svar != NULL);
9580                 ASSERT(svar->dtsv_refcnt > 0);
9581
9582                 if (--svar->dtsv_refcnt > 0)
9583                         continue;
9584
9585                 if (svar->dtsv_size != 0) {
9586                         ASSERT(svar->dtsv_data != 0);
9587                         kmem_free((void *)(uintptr_t)svar->dtsv_data,
9588                             svar->dtsv_size);
9589                 }
9590
9591                 kmem_free(svar, sizeof (dtrace_statvar_t));
9592                 svarp[id] = NULL;
9593         }
9594
9595         if (dp->dtdo_buf != NULL)
9596                 kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9597         if (dp->dtdo_inttab != NULL)
9598                 kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9599         if (dp->dtdo_strtab != NULL)
9600                 kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9601         if (dp->dtdo_vartab != NULL)
9602                 kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9603
9604         kmem_free(dp, sizeof (dtrace_difo_t));
9605 }
9606
9607 static void
9608 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9609 {
9610         int i;
9611
9612         ASSERT(MUTEX_HELD(&dtrace_lock));
9613         ASSERT(dp->dtdo_refcnt != 0);
9614
9615         for (i = 0; i < dp->dtdo_varlen; i++) {
9616                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9617
9618                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9619                         continue;
9620
9621                 ASSERT(dtrace_vtime_references > 0);
9622                 if (--dtrace_vtime_references == 0)
9623                         dtrace_vtime_disable();
9624         }
9625
9626         if (--dp->dtdo_refcnt == 0)
9627                 dtrace_difo_destroy(dp, vstate);
9628 }
9629
9630 /*
9631  * DTrace Format Functions
9632  */
9633 static uint16_t
9634 dtrace_format_add(dtrace_state_t *state, char *str)
9635 {
9636         char *fmt, **new;
9637         uint16_t ndx, len = strlen(str) + 1;
9638
9639         fmt = kmem_zalloc(len, KM_SLEEP);
9640         bcopy(str, fmt, len);
9641
9642         for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9643                 if (state->dts_formats[ndx] == NULL) {
9644                         state->dts_formats[ndx] = fmt;
9645                         return (ndx + 1);
9646                 }
9647         }
9648
9649         if (state->dts_nformats == USHRT_MAX) {
9650                 /*
9651                  * This is only likely if a denial-of-service attack is being
9652                  * attempted.  As such, it's okay to fail silently here.
9653                  */
9654                 kmem_free(fmt, len);
9655                 return (0);
9656         }
9657
9658         /*
9659          * For simplicity, we always resize the formats array to be exactly the
9660          * number of formats.
9661          */
9662         ndx = state->dts_nformats++;
9663         new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9664
9665         if (state->dts_formats != NULL) {
9666                 ASSERT(ndx != 0);
9667                 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9668                 kmem_free(state->dts_formats, ndx * sizeof (char *));
9669         }
9670
9671         state->dts_formats = new;
9672         state->dts_formats[ndx] = fmt;
9673
9674         return (ndx + 1);
9675 }
9676
9677 static void
9678 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9679 {
9680         char *fmt;
9681
9682         ASSERT(state->dts_formats != NULL);
9683         ASSERT(format <= state->dts_nformats);
9684         ASSERT(state->dts_formats[format - 1] != NULL);
9685
9686         fmt = state->dts_formats[format - 1];
9687         kmem_free(fmt, strlen(fmt) + 1);
9688         state->dts_formats[format - 1] = NULL;
9689 }
9690
9691 static void
9692 dtrace_format_destroy(dtrace_state_t *state)
9693 {
9694         int i;
9695
9696         if (state->dts_nformats == 0) {
9697                 ASSERT(state->dts_formats == NULL);
9698                 return;
9699         }
9700
9701         ASSERT(state->dts_formats != NULL);
9702
9703         for (i = 0; i < state->dts_nformats; i++) {
9704                 char *fmt = state->dts_formats[i];
9705
9706                 if (fmt == NULL)
9707                         continue;
9708
9709                 kmem_free(fmt, strlen(fmt) + 1);
9710         }
9711
9712         kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9713         state->dts_nformats = 0;
9714         state->dts_formats = NULL;
9715 }
9716
9717 /*
9718  * DTrace Predicate Functions
9719  */
9720 static dtrace_predicate_t *
9721 dtrace_predicate_create(dtrace_difo_t *dp)
9722 {
9723         dtrace_predicate_t *pred;
9724
9725         ASSERT(MUTEX_HELD(&dtrace_lock));
9726         ASSERT(dp->dtdo_refcnt != 0);
9727
9728         pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9729         pred->dtp_difo = dp;
9730         pred->dtp_refcnt = 1;
9731
9732         if (!dtrace_difo_cacheable(dp))
9733                 return (pred);
9734
9735         if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9736                 /*
9737                  * This is only theoretically possible -- we have had 2^32
9738                  * cacheable predicates on this machine.  We cannot allow any
9739                  * more predicates to become cacheable:  as unlikely as it is,
9740                  * there may be a thread caching a (now stale) predicate cache
9741                  * ID. (N.B.: the temptation is being successfully resisted to
9742                  * have this cmn_err() "Holy shit -- we executed this code!")
9743                  */
9744                 return (pred);
9745         }
9746
9747         pred->dtp_cacheid = dtrace_predcache_id++;
9748
9749         return (pred);
9750 }
9751
9752 static void
9753 dtrace_predicate_hold(dtrace_predicate_t *pred)
9754 {
9755         ASSERT(MUTEX_HELD(&dtrace_lock));
9756         ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9757         ASSERT(pred->dtp_refcnt > 0);
9758
9759         pred->dtp_refcnt++;
9760 }
9761
9762 static void
9763 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9764 {
9765         dtrace_difo_t *dp = pred->dtp_difo;
9766
9767         ASSERT(MUTEX_HELD(&dtrace_lock));
9768         ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9769         ASSERT(pred->dtp_refcnt > 0);
9770
9771         if (--pred->dtp_refcnt == 0) {
9772                 dtrace_difo_release(pred->dtp_difo, vstate);
9773                 kmem_free(pred, sizeof (dtrace_predicate_t));
9774         }
9775 }
9776
9777 /*
9778  * DTrace Action Description Functions
9779  */
9780 static dtrace_actdesc_t *
9781 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9782     uint64_t uarg, uint64_t arg)
9783 {
9784         dtrace_actdesc_t *act;
9785
9786 #if defined(sun)
9787         ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9788             arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
9789 #endif
9790
9791         act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9792         act->dtad_kind = kind;
9793         act->dtad_ntuple = ntuple;
9794         act->dtad_uarg = uarg;
9795         act->dtad_arg = arg;
9796         act->dtad_refcnt = 1;
9797
9798         return (act);
9799 }
9800
9801 static void
9802 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9803 {
9804         ASSERT(act->dtad_refcnt >= 1);
9805         act->dtad_refcnt++;
9806 }
9807
9808 static void
9809 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9810 {
9811         dtrace_actkind_t kind = act->dtad_kind;
9812         dtrace_difo_t *dp;
9813
9814         ASSERT(act->dtad_refcnt >= 1);
9815
9816         if (--act->dtad_refcnt != 0)
9817                 return;
9818
9819         if ((dp = act->dtad_difo) != NULL)
9820                 dtrace_difo_release(dp, vstate);
9821
9822         if (DTRACEACT_ISPRINTFLIKE(kind)) {
9823                 char *str = (char *)(uintptr_t)act->dtad_arg;
9824
9825 #if defined(sun)
9826                 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9827                     (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9828 #endif
9829
9830                 if (str != NULL)
9831                         kmem_free(str, strlen(str) + 1);
9832         }
9833
9834         kmem_free(act, sizeof (dtrace_actdesc_t));
9835 }
9836
9837 /*
9838  * DTrace ECB Functions
9839  */
9840 static dtrace_ecb_t *
9841 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9842 {
9843         dtrace_ecb_t *ecb;
9844         dtrace_epid_t epid;
9845
9846         ASSERT(MUTEX_HELD(&dtrace_lock));
9847
9848         ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9849         ecb->dte_predicate = NULL;
9850         ecb->dte_probe = probe;
9851
9852         /*
9853          * The default size is the size of the default action: recording
9854          * the header.
9855          */
9856         ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9857         ecb->dte_alignment = sizeof (dtrace_epid_t);
9858
9859         epid = state->dts_epid++;
9860
9861         if (epid - 1 >= state->dts_necbs) {
9862                 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9863                 int necbs = state->dts_necbs << 1;
9864
9865                 ASSERT(epid == state->dts_necbs + 1);
9866
9867                 if (necbs == 0) {
9868                         ASSERT(oecbs == NULL);
9869                         necbs = 1;
9870                 }
9871
9872                 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9873
9874                 if (oecbs != NULL)
9875                         bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9876
9877                 dtrace_membar_producer();
9878                 state->dts_ecbs = ecbs;
9879
9880                 if (oecbs != NULL) {
9881                         /*
9882                          * If this state is active, we must dtrace_sync()
9883                          * before we can free the old dts_ecbs array:  we're
9884                          * coming in hot, and there may be active ring
9885                          * buffer processing (which indexes into the dts_ecbs
9886                          * array) on another CPU.
9887                          */
9888                         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9889                                 dtrace_sync();
9890
9891                         kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9892                 }
9893
9894                 dtrace_membar_producer();
9895                 state->dts_necbs = necbs;
9896         }
9897
9898         ecb->dte_state = state;
9899
9900         ASSERT(state->dts_ecbs[epid - 1] == NULL);
9901         dtrace_membar_producer();
9902         state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9903
9904         return (ecb);
9905 }
9906
9907 static void
9908 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9909 {
9910         dtrace_probe_t *probe = ecb->dte_probe;
9911
9912         ASSERT(MUTEX_HELD(&cpu_lock));
9913         ASSERT(MUTEX_HELD(&dtrace_lock));
9914         ASSERT(ecb->dte_next == NULL);
9915
9916         if (probe == NULL) {
9917                 /*
9918                  * This is the NULL probe -- there's nothing to do.
9919                  */
9920                 return;
9921         }
9922
9923         if (probe->dtpr_ecb == NULL) {
9924                 dtrace_provider_t *prov = probe->dtpr_provider;
9925
9926                 /*
9927                  * We're the first ECB on this probe.
9928                  */
9929                 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9930
9931                 if (ecb->dte_predicate != NULL)
9932                         probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9933
9934                 prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9935                     probe->dtpr_id, probe->dtpr_arg);
9936         } else {
9937                 /*
9938                  * This probe is already active.  Swing the last pointer to
9939                  * point to the new ECB, and issue a dtrace_sync() to assure
9940                  * that all CPUs have seen the change.
9941                  */
9942                 ASSERT(probe->dtpr_ecb_last != NULL);
9943                 probe->dtpr_ecb_last->dte_next = ecb;
9944                 probe->dtpr_ecb_last = ecb;
9945                 probe->dtpr_predcache = 0;
9946
9947                 dtrace_sync();
9948         }
9949 }
9950
9951 static void
9952 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9953 {
9954         dtrace_action_t *act;
9955         uint32_t curneeded = UINT32_MAX;
9956         uint32_t aggbase = UINT32_MAX;
9957
9958         /*
9959          * If we record anything, we always record the dtrace_rechdr_t.  (And
9960          * we always record it first.)
9961          */
9962         ecb->dte_size = sizeof (dtrace_rechdr_t);
9963         ecb->dte_alignment = sizeof (dtrace_epid_t);
9964
9965         for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9966                 dtrace_recdesc_t *rec = &act->dta_rec;
9967                 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
9968
9969                 ecb->dte_alignment = MAX(ecb->dte_alignment,
9970                     rec->dtrd_alignment);
9971
9972                 if (DTRACEACT_ISAGG(act->dta_kind)) {
9973                         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9974
9975                         ASSERT(rec->dtrd_size != 0);
9976                         ASSERT(agg->dtag_first != NULL);
9977                         ASSERT(act->dta_prev->dta_intuple);
9978                         ASSERT(aggbase != UINT32_MAX);
9979                         ASSERT(curneeded != UINT32_MAX);
9980
9981                         agg->dtag_base = aggbase;
9982
9983                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9984                         rec->dtrd_offset = curneeded;
9985                         curneeded += rec->dtrd_size;
9986                         ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
9987
9988                         aggbase = UINT32_MAX;
9989                         curneeded = UINT32_MAX;
9990                 } else if (act->dta_intuple) {
9991                         if (curneeded == UINT32_MAX) {
9992                                 /*
9993                                  * This is the first record in a tuple.  Align
9994                                  * curneeded to be at offset 4 in an 8-byte
9995                                  * aligned block.
9996                                  */
9997                                 ASSERT(act->dta_prev == NULL ||
9998                                     !act->dta_prev->dta_intuple);
9999                                 ASSERT3U(aggbase, ==, UINT32_MAX);
10000                                 curneeded = P2PHASEUP(ecb->dte_size,
10001                                     sizeof (uint64_t), sizeof (dtrace_aggid_t));
10002
10003                                 aggbase = curneeded - sizeof (dtrace_aggid_t);
10004                                 ASSERT(IS_P2ALIGNED(aggbase,
10005                                     sizeof (uint64_t)));
10006                         }
10007                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10008                         rec->dtrd_offset = curneeded;
10009                         curneeded += rec->dtrd_size;
10010                 } else {
10011                         /* tuples must be followed by an aggregation */
10012                         ASSERT(act->dta_prev == NULL ||
10013                             !act->dta_prev->dta_intuple);
10014
10015                         ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10016                             rec->dtrd_alignment);
10017                         rec->dtrd_offset = ecb->dte_size;
10018                         ecb->dte_size += rec->dtrd_size;
10019                         ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10020                 }
10021         }
10022
10023         if ((act = ecb->dte_action) != NULL &&
10024             !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10025             ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10026                 /*
10027                  * If the size is still sizeof (dtrace_rechdr_t), then all
10028                  * actions store no data; set the size to 0.
10029                  */
10030                 ecb->dte_size = 0;
10031         }
10032
10033         ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10034         ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10035         ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10036             ecb->dte_needed);
10037 }
10038
10039 static dtrace_action_t *
10040 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10041 {
10042         dtrace_aggregation_t *agg;
10043         size_t size = sizeof (uint64_t);
10044         int ntuple = desc->dtad_ntuple;
10045         dtrace_action_t *act;
10046         dtrace_recdesc_t *frec;
10047         dtrace_aggid_t aggid;
10048         dtrace_state_t *state = ecb->dte_state;
10049
10050         agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10051         agg->dtag_ecb = ecb;
10052
10053         ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10054
10055         switch (desc->dtad_kind) {
10056         case DTRACEAGG_MIN:
10057                 agg->dtag_initial = INT64_MAX;
10058                 agg->dtag_aggregate = dtrace_aggregate_min;
10059                 break;
10060
10061         case DTRACEAGG_MAX:
10062                 agg->dtag_initial = INT64_MIN;
10063                 agg->dtag_aggregate = dtrace_aggregate_max;
10064                 break;
10065
10066         case DTRACEAGG_COUNT:
10067                 agg->dtag_aggregate = dtrace_aggregate_count;
10068                 break;
10069
10070         case DTRACEAGG_QUANTIZE:
10071                 agg->dtag_aggregate = dtrace_aggregate_quantize;
10072                 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10073                     sizeof (uint64_t);
10074                 break;
10075
10076         case DTRACEAGG_LQUANTIZE: {
10077                 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10078                 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10079
10080                 agg->dtag_initial = desc->dtad_arg;
10081                 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10082
10083                 if (step == 0 || levels == 0)
10084                         goto err;
10085
10086                 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10087                 break;
10088         }
10089
10090         case DTRACEAGG_LLQUANTIZE: {
10091                 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10092                 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10093                 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10094                 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10095                 int64_t v;
10096
10097                 agg->dtag_initial = desc->dtad_arg;
10098                 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10099
10100                 if (factor < 2 || low >= high || nsteps < factor)
10101                         goto err;
10102
10103                 /*
10104                  * Now check that the number of steps evenly divides a power
10105                  * of the factor.  (This assures both integer bucket size and
10106                  * linearity within each magnitude.)
10107                  */
10108                 for (v = factor; v < nsteps; v *= factor)
10109                         continue;
10110
10111                 if ((v % nsteps) || (nsteps % factor))
10112                         goto err;
10113
10114                 size = (dtrace_aggregate_llquantize_bucket(factor,
10115                     low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10116                 break;
10117         }
10118
10119         case DTRACEAGG_AVG:
10120                 agg->dtag_aggregate = dtrace_aggregate_avg;
10121                 size = sizeof (uint64_t) * 2;
10122                 break;
10123
10124         case DTRACEAGG_STDDEV:
10125                 agg->dtag_aggregate = dtrace_aggregate_stddev;
10126                 size = sizeof (uint64_t) * 4;
10127                 break;
10128
10129         case DTRACEAGG_SUM:
10130                 agg->dtag_aggregate = dtrace_aggregate_sum;
10131                 break;
10132
10133         default:
10134                 goto err;
10135         }
10136
10137         agg->dtag_action.dta_rec.dtrd_size = size;
10138
10139         if (ntuple == 0)
10140                 goto err;
10141
10142         /*
10143          * We must make sure that we have enough actions for the n-tuple.
10144          */
10145         for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10146                 if (DTRACEACT_ISAGG(act->dta_kind))
10147                         break;
10148
10149                 if (--ntuple == 0) {
10150                         /*
10151                          * This is the action with which our n-tuple begins.
10152                          */
10153                         agg->dtag_first = act;
10154                         goto success;
10155                 }
10156         }
10157
10158         /*
10159          * This n-tuple is short by ntuple elements.  Return failure.
10160          */
10161         ASSERT(ntuple != 0);
10162 err:
10163         kmem_free(agg, sizeof (dtrace_aggregation_t));
10164         return (NULL);
10165
10166 success:
10167         /*
10168          * If the last action in the tuple has a size of zero, it's actually
10169          * an expression argument for the aggregating action.
10170          */
10171         ASSERT(ecb->dte_action_last != NULL);
10172         act = ecb->dte_action_last;
10173
10174         if (act->dta_kind == DTRACEACT_DIFEXPR) {
10175                 ASSERT(act->dta_difo != NULL);
10176
10177                 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10178                         agg->dtag_hasarg = 1;
10179         }
10180
10181         /*
10182          * We need to allocate an id for this aggregation.
10183          */
10184 #if defined(sun)
10185         aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10186             VM_BESTFIT | VM_SLEEP);
10187 #else
10188         aggid = alloc_unr(state->dts_aggid_arena);
10189 #endif
10190
10191         if (aggid - 1 >= state->dts_naggregations) {
10192                 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10193                 dtrace_aggregation_t **aggs;
10194                 int naggs = state->dts_naggregations << 1;
10195                 int onaggs = state->dts_naggregations;
10196
10197                 ASSERT(aggid == state->dts_naggregations + 1);
10198
10199                 if (naggs == 0) {
10200                         ASSERT(oaggs == NULL);
10201                         naggs = 1;
10202                 }
10203
10204                 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10205
10206                 if (oaggs != NULL) {
10207                         bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10208                         kmem_free(oaggs, onaggs * sizeof (*aggs));
10209                 }
10210
10211                 state->dts_aggregations = aggs;
10212                 state->dts_naggregations = naggs;
10213         }
10214
10215         ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10216         state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10217
10218         frec = &agg->dtag_first->dta_rec;
10219         if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10220                 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10221
10222         for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10223                 ASSERT(!act->dta_intuple);
10224                 act->dta_intuple = 1;
10225         }
10226
10227         return (&agg->dtag_action);
10228 }
10229
10230 static void
10231 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10232 {
10233         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10234         dtrace_state_t *state = ecb->dte_state;
10235         dtrace_aggid_t aggid = agg->dtag_id;
10236
10237         ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10238 #if defined(sun)
10239         vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10240 #else
10241         free_unr(state->dts_aggid_arena, aggid);
10242 #endif
10243
10244         ASSERT(state->dts_aggregations[aggid - 1] == agg);
10245         state->dts_aggregations[aggid - 1] = NULL;
10246
10247         kmem_free(agg, sizeof (dtrace_aggregation_t));
10248 }
10249
10250 static int
10251 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10252 {
10253         dtrace_action_t *action, *last;
10254         dtrace_difo_t *dp = desc->dtad_difo;
10255         uint32_t size = 0, align = sizeof (uint8_t), mask;
10256         uint16_t format = 0;
10257         dtrace_recdesc_t *rec;
10258         dtrace_state_t *state = ecb->dte_state;
10259         dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
10260         uint64_t arg = desc->dtad_arg;
10261
10262         ASSERT(MUTEX_HELD(&dtrace_lock));
10263         ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10264
10265         if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10266                 /*
10267                  * If this is an aggregating action, there must be neither
10268                  * a speculate nor a commit on the action chain.
10269                  */
10270                 dtrace_action_t *act;
10271
10272                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10273                         if (act->dta_kind == DTRACEACT_COMMIT)
10274                                 return (EINVAL);
10275
10276                         if (act->dta_kind == DTRACEACT_SPECULATE)
10277                                 return (EINVAL);
10278                 }
10279
10280                 action = dtrace_ecb_aggregation_create(ecb, desc);
10281
10282                 if (action == NULL)
10283                         return (EINVAL);
10284         } else {
10285                 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10286                     (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10287                     dp != NULL && dp->dtdo_destructive)) {
10288                         state->dts_destructive = 1;
10289                 }
10290
10291                 switch (desc->dtad_kind) {
10292                 case DTRACEACT_PRINTF:
10293                 case DTRACEACT_PRINTA:
10294                 case DTRACEACT_SYSTEM:
10295                 case DTRACEACT_FREOPEN:
10296                 case DTRACEACT_DIFEXPR:
10297                         /*
10298                          * We know that our arg is a string -- turn it into a
10299                          * format.
10300                          */
10301                         if (arg == 0) {
10302                                 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10303                                     desc->dtad_kind == DTRACEACT_DIFEXPR);
10304                                 format = 0;
10305                         } else {
10306                                 ASSERT(arg != 0);
10307 #if defined(sun)
10308                                 ASSERT(arg > KERNELBASE);
10309 #endif
10310                                 format = dtrace_format_add(state,
10311                                     (char *)(uintptr_t)arg);
10312                         }
10313
10314                         /*FALLTHROUGH*/
10315                 case DTRACEACT_LIBACT:
10316                 case DTRACEACT_TRACEMEM:
10317                 case DTRACEACT_TRACEMEM_DYNSIZE:
10318                         if (dp == NULL)
10319                                 return (EINVAL);
10320
10321                         if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10322                                 break;
10323
10324                         if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10325                                 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10326                                         return (EINVAL);
10327
10328                                 size = opt[DTRACEOPT_STRSIZE];
10329                         }
10330
10331                         break;
10332
10333                 case DTRACEACT_STACK:
10334                         if ((nframes = arg) == 0) {
10335                                 nframes = opt[DTRACEOPT_STACKFRAMES];
10336                                 ASSERT(nframes > 0);
10337                                 arg = nframes;
10338                         }
10339
10340                         size = nframes * sizeof (pc_t);
10341                         break;
10342
10343                 case DTRACEACT_JSTACK:
10344                         if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10345                                 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10346
10347                         if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10348                                 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10349
10350                         arg = DTRACE_USTACK_ARG(nframes, strsize);
10351
10352                         /*FALLTHROUGH*/
10353                 case DTRACEACT_USTACK:
10354                         if (desc->dtad_kind != DTRACEACT_JSTACK &&
10355                             (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10356                                 strsize = DTRACE_USTACK_STRSIZE(arg);
10357                                 nframes = opt[DTRACEOPT_USTACKFRAMES];
10358                                 ASSERT(nframes > 0);
10359                                 arg = DTRACE_USTACK_ARG(nframes, strsize);
10360                         }
10361
10362                         /*
10363                          * Save a slot for the pid.
10364                          */
10365                         size = (nframes + 1) * sizeof (uint64_t);
10366                         size += DTRACE_USTACK_STRSIZE(arg);
10367                         size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10368
10369                         break;
10370
10371                 case DTRACEACT_SYM:
10372                 case DTRACEACT_MOD:
10373                         if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10374                             sizeof (uint64_t)) ||
10375                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10376                                 return (EINVAL);
10377                         break;
10378
10379                 case DTRACEACT_USYM:
10380                 case DTRACEACT_UMOD:
10381                 case DTRACEACT_UADDR:
10382                         if (dp == NULL ||
10383                             (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10384                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10385                                 return (EINVAL);
10386
10387                         /*
10388                          * We have a slot for the pid, plus a slot for the
10389                          * argument.  To keep things simple (aligned with
10390                          * bitness-neutral sizing), we store each as a 64-bit
10391                          * quantity.
10392                          */
10393                         size = 2 * sizeof (uint64_t);
10394                         break;
10395
10396                 case DTRACEACT_STOP:
10397                 case DTRACEACT_BREAKPOINT:
10398                 case DTRACEACT_PANIC:
10399                         break;
10400
10401                 case DTRACEACT_CHILL:
10402                 case DTRACEACT_DISCARD:
10403                 case DTRACEACT_RAISE:
10404                         if (dp == NULL)
10405                                 return (EINVAL);
10406                         break;
10407
10408                 case DTRACEACT_EXIT:
10409                         if (dp == NULL ||
10410                             (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10411                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10412                                 return (EINVAL);
10413                         break;
10414
10415                 case DTRACEACT_SPECULATE:
10416                         if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10417                                 return (EINVAL);
10418
10419                         if (dp == NULL)
10420                                 return (EINVAL);
10421
10422                         state->dts_speculates = 1;
10423                         break;
10424
10425                 case DTRACEACT_PRINTM:
10426                         size = dp->dtdo_rtype.dtdt_size;
10427                         break;
10428
10429                 case DTRACEACT_PRINTT:
10430                         size = dp->dtdo_rtype.dtdt_size;
10431                         break;
10432
10433                 case DTRACEACT_COMMIT: {
10434                         dtrace_action_t *act = ecb->dte_action;
10435
10436                         for (; act != NULL; act = act->dta_next) {
10437                                 if (act->dta_kind == DTRACEACT_COMMIT)
10438                                         return (EINVAL);
10439                         }
10440
10441                         if (dp == NULL)
10442                                 return (EINVAL);
10443                         break;
10444                 }
10445
10446                 default:
10447                         return (EINVAL);
10448                 }
10449
10450                 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10451                         /*
10452                          * If this is a data-storing action or a speculate,
10453                          * we must be sure that there isn't a commit on the
10454                          * action chain.
10455                          */
10456                         dtrace_action_t *act = ecb->dte_action;
10457
10458                         for (; act != NULL; act = act->dta_next) {
10459                                 if (act->dta_kind == DTRACEACT_COMMIT)
10460                                         return (EINVAL);
10461                         }
10462                 }
10463
10464                 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10465                 action->dta_rec.dtrd_size = size;
10466         }
10467
10468         action->dta_refcnt = 1;
10469         rec = &action->dta_rec;
10470         size = rec->dtrd_size;
10471
10472         for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10473                 if (!(size & mask)) {
10474                         align = mask + 1;
10475                         break;
10476                 }
10477         }
10478
10479         action->dta_kind = desc->dtad_kind;
10480
10481         if ((action->dta_difo = dp) != NULL)
10482                 dtrace_difo_hold(dp);
10483
10484         rec->dtrd_action = action->dta_kind;
10485         rec->dtrd_arg = arg;
10486         rec->dtrd_uarg = desc->dtad_uarg;
10487         rec->dtrd_alignment = (uint16_t)align;
10488         rec->dtrd_format = format;
10489
10490         if ((last = ecb->dte_action_last) != NULL) {
10491                 ASSERT(ecb->dte_action != NULL);
10492                 action->dta_prev = last;
10493                 last->dta_next = action;
10494         } else {
10495                 ASSERT(ecb->dte_action == NULL);
10496                 ecb->dte_action = action;
10497         }
10498
10499         ecb->dte_action_last = action;
10500
10501         return (0);
10502 }
10503
10504 static void
10505 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10506 {
10507         dtrace_action_t *act = ecb->dte_action, *next;
10508         dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10509         dtrace_difo_t *dp;
10510         uint16_t format;
10511
10512         if (act != NULL && act->dta_refcnt > 1) {
10513                 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10514                 act->dta_refcnt--;
10515         } else {
10516                 for (; act != NULL; act = next) {
10517                         next = act->dta_next;
10518                         ASSERT(next != NULL || act == ecb->dte_action_last);
10519                         ASSERT(act->dta_refcnt == 1);
10520
10521                         if ((format = act->dta_rec.dtrd_format) != 0)
10522                                 dtrace_format_remove(ecb->dte_state, format);
10523
10524                         if ((dp = act->dta_difo) != NULL)
10525                                 dtrace_difo_release(dp, vstate);
10526
10527                         if (DTRACEACT_ISAGG(act->dta_kind)) {
10528                                 dtrace_ecb_aggregation_destroy(ecb, act);
10529                         } else {
10530                                 kmem_free(act, sizeof (dtrace_action_t));
10531                         }
10532                 }
10533         }
10534
10535         ecb->dte_action = NULL;
10536         ecb->dte_action_last = NULL;
10537         ecb->dte_size = 0;
10538 }
10539
10540 static void
10541 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10542 {
10543         /*
10544          * We disable the ECB by removing it from its probe.
10545          */
10546         dtrace_ecb_t *pecb, *prev = NULL;
10547         dtrace_probe_t *probe = ecb->dte_probe;
10548
10549         ASSERT(MUTEX_HELD(&dtrace_lock));
10550
10551         if (probe == NULL) {
10552                 /*
10553                  * This is the NULL probe; there is nothing to disable.
10554                  */
10555                 return;
10556         }
10557
10558         for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10559                 if (pecb == ecb)
10560                         break;
10561                 prev = pecb;
10562         }
10563
10564         ASSERT(pecb != NULL);
10565
10566         if (prev == NULL) {
10567                 probe->dtpr_ecb = ecb->dte_next;
10568         } else {
10569                 prev->dte_next = ecb->dte_next;
10570         }
10571
10572         if (ecb == probe->dtpr_ecb_last) {
10573                 ASSERT(ecb->dte_next == NULL);
10574                 probe->dtpr_ecb_last = prev;
10575         }
10576
10577         /*
10578          * The ECB has been disconnected from the probe; now sync to assure
10579          * that all CPUs have seen the change before returning.
10580          */
10581         dtrace_sync();
10582
10583         if (probe->dtpr_ecb == NULL) {
10584                 /*
10585                  * That was the last ECB on the probe; clear the predicate
10586                  * cache ID for the probe, disable it and sync one more time
10587                  * to assure that we'll never hit it again.
10588                  */
10589                 dtrace_provider_t *prov = probe->dtpr_provider;
10590
10591                 ASSERT(ecb->dte_next == NULL);
10592                 ASSERT(probe->dtpr_ecb_last == NULL);
10593                 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10594                 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10595                     probe->dtpr_id, probe->dtpr_arg);
10596                 dtrace_sync();
10597         } else {
10598                 /*
10599                  * There is at least one ECB remaining on the probe.  If there
10600                  * is _exactly_ one, set the probe's predicate cache ID to be
10601                  * the predicate cache ID of the remaining ECB.
10602                  */
10603                 ASSERT(probe->dtpr_ecb_last != NULL);
10604                 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10605
10606                 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10607                         dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10608
10609                         ASSERT(probe->dtpr_ecb->dte_next == NULL);
10610
10611                         if (p != NULL)
10612                                 probe->dtpr_predcache = p->dtp_cacheid;
10613                 }
10614
10615                 ecb->dte_next = NULL;
10616         }
10617 }
10618
10619 static void
10620 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10621 {
10622         dtrace_state_t *state = ecb->dte_state;
10623         dtrace_vstate_t *vstate = &state->dts_vstate;
10624         dtrace_predicate_t *pred;
10625         dtrace_epid_t epid = ecb->dte_epid;
10626
10627         ASSERT(MUTEX_HELD(&dtrace_lock));
10628         ASSERT(ecb->dte_next == NULL);
10629         ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10630
10631         if ((pred = ecb->dte_predicate) != NULL)
10632                 dtrace_predicate_release(pred, vstate);
10633
10634         dtrace_ecb_action_remove(ecb);
10635
10636         ASSERT(state->dts_ecbs[epid - 1] == ecb);
10637         state->dts_ecbs[epid - 1] = NULL;
10638
10639         kmem_free(ecb, sizeof (dtrace_ecb_t));
10640 }
10641
10642 static dtrace_ecb_t *
10643 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10644     dtrace_enabling_t *enab)
10645 {
10646         dtrace_ecb_t *ecb;
10647         dtrace_predicate_t *pred;
10648         dtrace_actdesc_t *act;
10649         dtrace_provider_t *prov;
10650         dtrace_ecbdesc_t *desc = enab->dten_current;
10651
10652         ASSERT(MUTEX_HELD(&dtrace_lock));
10653         ASSERT(state != NULL);
10654
10655         ecb = dtrace_ecb_add(state, probe);
10656         ecb->dte_uarg = desc->dted_uarg;
10657
10658         if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10659                 dtrace_predicate_hold(pred);
10660                 ecb->dte_predicate = pred;
10661         }
10662
10663         if (probe != NULL) {
10664                 /*
10665                  * If the provider shows more leg than the consumer is old
10666                  * enough to see, we need to enable the appropriate implicit
10667                  * predicate bits to prevent the ecb from activating at
10668                  * revealing times.
10669                  *
10670                  * Providers specifying DTRACE_PRIV_USER at register time
10671                  * are stating that they need the /proc-style privilege
10672                  * model to be enforced, and this is what DTRACE_COND_OWNER
10673                  * and DTRACE_COND_ZONEOWNER will then do at probe time.
10674                  */
10675                 prov = probe->dtpr_provider;
10676                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10677                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10678                         ecb->dte_cond |= DTRACE_COND_OWNER;
10679
10680                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10681                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10682                         ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10683
10684                 /*
10685                  * If the provider shows us kernel innards and the user
10686                  * is lacking sufficient privilege, enable the
10687                  * DTRACE_COND_USERMODE implicit predicate.
10688                  */
10689                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10690                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10691                         ecb->dte_cond |= DTRACE_COND_USERMODE;
10692         }
10693
10694         if (dtrace_ecb_create_cache != NULL) {
10695                 /*
10696                  * If we have a cached ecb, we'll use its action list instead
10697                  * of creating our own (saving both time and space).
10698                  */
10699                 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10700                 dtrace_action_t *act = cached->dte_action;
10701
10702                 if (act != NULL) {
10703                         ASSERT(act->dta_refcnt > 0);
10704                         act->dta_refcnt++;
10705                         ecb->dte_action = act;
10706                         ecb->dte_action_last = cached->dte_action_last;
10707                         ecb->dte_needed = cached->dte_needed;
10708                         ecb->dte_size = cached->dte_size;
10709                         ecb->dte_alignment = cached->dte_alignment;
10710                 }
10711
10712                 return (ecb);
10713         }
10714
10715         for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10716                 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10717                         dtrace_ecb_destroy(ecb);
10718                         return (NULL);
10719                 }
10720         }
10721
10722         dtrace_ecb_resize(ecb);
10723
10724         return (dtrace_ecb_create_cache = ecb);
10725 }
10726
10727 static int
10728 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10729 {
10730         dtrace_ecb_t *ecb;
10731         dtrace_enabling_t *enab = arg;
10732         dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10733
10734         ASSERT(state != NULL);
10735
10736         if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10737                 /*
10738                  * This probe was created in a generation for which this
10739                  * enabling has previously created ECBs; we don't want to
10740                  * enable it again, so just kick out.
10741                  */
10742                 return (DTRACE_MATCH_NEXT);
10743         }
10744
10745         if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10746                 return (DTRACE_MATCH_DONE);
10747
10748         dtrace_ecb_enable(ecb);
10749         return (DTRACE_MATCH_NEXT);
10750 }
10751
10752 static dtrace_ecb_t *
10753 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10754 {
10755         dtrace_ecb_t *ecb;
10756
10757         ASSERT(MUTEX_HELD(&dtrace_lock));
10758
10759         if (id == 0 || id > state->dts_necbs)
10760                 return (NULL);
10761
10762         ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10763         ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10764
10765         return (state->dts_ecbs[id - 1]);
10766 }
10767
10768 static dtrace_aggregation_t *
10769 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10770 {
10771         dtrace_aggregation_t *agg;
10772
10773         ASSERT(MUTEX_HELD(&dtrace_lock));
10774
10775         if (id == 0 || id > state->dts_naggregations)
10776                 return (NULL);
10777
10778         ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10779         ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10780             agg->dtag_id == id);
10781
10782         return (state->dts_aggregations[id - 1]);
10783 }
10784
10785 /*
10786  * DTrace Buffer Functions
10787  *
10788  * The following functions manipulate DTrace buffers.  Most of these functions
10789  * are called in the context of establishing or processing consumer state;
10790  * exceptions are explicitly noted.
10791  */
10792
10793 /*
10794  * Note:  called from cross call context.  This function switches the two
10795  * buffers on a given CPU.  The atomicity of this operation is assured by
10796  * disabling interrupts while the actual switch takes place; the disabling of
10797  * interrupts serializes the execution with any execution of dtrace_probe() on
10798  * the same CPU.
10799  */
10800 static void
10801 dtrace_buffer_switch(dtrace_buffer_t *buf)
10802 {
10803         caddr_t tomax = buf->dtb_tomax;
10804         caddr_t xamot = buf->dtb_xamot;
10805         dtrace_icookie_t cookie;
10806         hrtime_t now;
10807
10808         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10809         ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10810
10811         cookie = dtrace_interrupt_disable();
10812         now = dtrace_gethrtime();
10813         buf->dtb_tomax = xamot;
10814         buf->dtb_xamot = tomax;
10815         buf->dtb_xamot_drops = buf->dtb_drops;
10816         buf->dtb_xamot_offset = buf->dtb_offset;
10817         buf->dtb_xamot_errors = buf->dtb_errors;
10818         buf->dtb_xamot_flags = buf->dtb_flags;
10819         buf->dtb_offset = 0;
10820         buf->dtb_drops = 0;
10821         buf->dtb_errors = 0;
10822         buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10823         buf->dtb_interval = now - buf->dtb_switched;
10824         buf->dtb_switched = now;
10825         dtrace_interrupt_enable(cookie);
10826 }
10827
10828 /*
10829  * Note:  called from cross call context.  This function activates a buffer
10830  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
10831  * is guaranteed by the disabling of interrupts.
10832  */
10833 static void
10834 dtrace_buffer_activate(dtrace_state_t *state)
10835 {
10836         dtrace_buffer_t *buf;
10837         dtrace_icookie_t cookie = dtrace_interrupt_disable();
10838
10839         buf = &state->dts_buffer[curcpu];
10840
10841         if (buf->dtb_tomax != NULL) {
10842                 /*
10843                  * We might like to assert that the buffer is marked inactive,
10844                  * but this isn't necessarily true:  the buffer for the CPU
10845                  * that processes the BEGIN probe has its buffer activated
10846                  * manually.  In this case, we take the (harmless) action
10847                  * re-clearing the bit INACTIVE bit.
10848                  */
10849                 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10850         }
10851
10852         dtrace_interrupt_enable(cookie);
10853 }
10854
10855 static int
10856 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10857     processorid_t cpu, int *factor)
10858 {
10859 #if defined(sun)
10860         cpu_t *cp;
10861 #endif
10862         dtrace_buffer_t *buf;
10863         int allocated = 0, desired = 0;
10864
10865 #if defined(sun)
10866         ASSERT(MUTEX_HELD(&cpu_lock));
10867         ASSERT(MUTEX_HELD(&dtrace_lock));
10868
10869         *factor = 1;
10870
10871         if (size > dtrace_nonroot_maxsize &&
10872             !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10873                 return (EFBIG);
10874
10875         cp = cpu_list;
10876
10877         do {
10878                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10879                         continue;
10880
10881                 buf = &bufs[cp->cpu_id];
10882
10883                 /*
10884                  * If there is already a buffer allocated for this CPU, it
10885                  * is only possible that this is a DR event.  In this case,
10886                  */
10887                 if (buf->dtb_tomax != NULL) {
10888                         ASSERT(buf->dtb_size == size);
10889                         continue;
10890                 }
10891
10892                 ASSERT(buf->dtb_xamot == NULL);
10893
10894                 if ((buf->dtb_tomax = kmem_zalloc(size,
10895                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10896                         goto err;
10897
10898                 buf->dtb_size = size;
10899                 buf->dtb_flags = flags;
10900                 buf->dtb_offset = 0;
10901                 buf->dtb_drops = 0;
10902
10903                 if (flags & DTRACEBUF_NOSWITCH)
10904                         continue;
10905
10906                 if ((buf->dtb_xamot = kmem_zalloc(size,
10907                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10908                         goto err;
10909         } while ((cp = cp->cpu_next) != cpu_list);
10910
10911         return (0);
10912
10913 err:
10914         cp = cpu_list;
10915
10916         do {
10917                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10918                         continue;
10919
10920                 buf = &bufs[cp->cpu_id];
10921                 desired += 2;
10922
10923                 if (buf->dtb_xamot != NULL) {
10924                         ASSERT(buf->dtb_tomax != NULL);
10925                         ASSERT(buf->dtb_size == size);
10926                         kmem_free(buf->dtb_xamot, size);
10927                         allocated++;
10928                 }
10929
10930                 if (buf->dtb_tomax != NULL) {
10931                         ASSERT(buf->dtb_size == size);
10932                         kmem_free(buf->dtb_tomax, size);
10933                         allocated++;
10934                 }
10935
10936                 buf->dtb_tomax = NULL;
10937                 buf->dtb_xamot = NULL;
10938                 buf->dtb_size = 0;
10939         } while ((cp = cp->cpu_next) != cpu_list);
10940 #else
10941         int i;
10942
10943         *factor = 1;
10944 #if defined(__amd64__)
10945         /*
10946          * FreeBSD isn't good at limiting the amount of memory we
10947          * ask to malloc, so let's place a limit here before trying
10948          * to do something that might well end in tears at bedtime.
10949          */
10950         if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
10951                 return (ENOMEM);
10952 #endif
10953
10954         ASSERT(MUTEX_HELD(&dtrace_lock));
10955         CPU_FOREACH(i) {
10956                 if (cpu != DTRACE_CPUALL && cpu != i)
10957                         continue;
10958
10959                 buf = &bufs[i];
10960
10961                 /*
10962                  * If there is already a buffer allocated for this CPU, it
10963                  * is only possible that this is a DR event.  In this case,
10964                  * the buffer size must match our specified size.
10965                  */
10966                 if (buf->dtb_tomax != NULL) {
10967                         ASSERT(buf->dtb_size == size);
10968                         continue;
10969                 }
10970
10971                 ASSERT(buf->dtb_xamot == NULL);
10972
10973                 if ((buf->dtb_tomax = kmem_zalloc(size,
10974                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10975                         goto err;
10976
10977                 buf->dtb_size = size;
10978                 buf->dtb_flags = flags;
10979                 buf->dtb_offset = 0;
10980                 buf->dtb_drops = 0;
10981
10982                 if (flags & DTRACEBUF_NOSWITCH)
10983                         continue;
10984
10985                 if ((buf->dtb_xamot = kmem_zalloc(size,
10986                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10987                         goto err;
10988         }
10989
10990         return (0);
10991
10992 err:
10993         /*
10994          * Error allocating memory, so free the buffers that were
10995          * allocated before the failed allocation.
10996          */
10997         CPU_FOREACH(i) {
10998                 if (cpu != DTRACE_CPUALL && cpu != i)
10999                         continue;
11000
11001                 buf = &bufs[i];
11002                 desired += 2;
11003
11004                 if (buf->dtb_xamot != NULL) {
11005                         ASSERT(buf->dtb_tomax != NULL);
11006                         ASSERT(buf->dtb_size == size);
11007                         kmem_free(buf->dtb_xamot, size);
11008                         allocated++;
11009                 }
11010
11011                 if (buf->dtb_tomax != NULL) {
11012                         ASSERT(buf->dtb_size == size);
11013                         kmem_free(buf->dtb_tomax, size);
11014                         allocated++;
11015                 }
11016
11017                 buf->dtb_tomax = NULL;
11018                 buf->dtb_xamot = NULL;
11019                 buf->dtb_size = 0;
11020
11021         }
11022 #endif
11023         *factor = desired / (allocated > 0 ? allocated : 1);
11024
11025         return (ENOMEM);
11026 }
11027
11028 /*
11029  * Note:  called from probe context.  This function just increments the drop
11030  * count on a buffer.  It has been made a function to allow for the
11031  * possibility of understanding the source of mysterious drop counts.  (A
11032  * problem for which one may be particularly disappointed that DTrace cannot
11033  * be used to understand DTrace.)
11034  */
11035 static void
11036 dtrace_buffer_drop(dtrace_buffer_t *buf)
11037 {
11038         buf->dtb_drops++;
11039 }
11040
11041 /*
11042  * Note:  called from probe context.  This function is called to reserve space
11043  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11044  * mstate.  Returns the new offset in the buffer, or a negative value if an
11045  * error has occurred.
11046  */
11047 static intptr_t
11048 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11049     dtrace_state_t *state, dtrace_mstate_t *mstate)
11050 {
11051         intptr_t offs = buf->dtb_offset, soffs;
11052         intptr_t woffs;
11053         caddr_t tomax;
11054         size_t total;
11055
11056         if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11057                 return (-1);
11058
11059         if ((tomax = buf->dtb_tomax) == NULL) {
11060                 dtrace_buffer_drop(buf);
11061                 return (-1);
11062         }
11063
11064         if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11065                 while (offs & (align - 1)) {
11066                         /*
11067                          * Assert that our alignment is off by a number which
11068                          * is itself sizeof (uint32_t) aligned.
11069                          */
11070                         ASSERT(!((align - (offs & (align - 1))) &
11071                             (sizeof (uint32_t) - 1)));
11072                         DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11073                         offs += sizeof (uint32_t);
11074                 }
11075
11076                 if ((soffs = offs + needed) > buf->dtb_size) {
11077                         dtrace_buffer_drop(buf);
11078                         return (-1);
11079                 }
11080
11081                 if (mstate == NULL)
11082                         return (offs);
11083
11084                 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11085                 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11086                 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11087
11088                 return (offs);
11089         }
11090
11091         if (buf->dtb_flags & DTRACEBUF_FILL) {
11092                 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11093                     (buf->dtb_flags & DTRACEBUF_FULL))
11094                         return (-1);
11095                 goto out;
11096         }
11097
11098         total = needed + (offs & (align - 1));
11099
11100         /*
11101          * For a ring buffer, life is quite a bit more complicated.  Before
11102          * we can store any padding, we need to adjust our wrapping offset.
11103          * (If we've never before wrapped or we're not about to, no adjustment
11104          * is required.)
11105          */
11106         if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11107             offs + total > buf->dtb_size) {
11108                 woffs = buf->dtb_xamot_offset;
11109
11110                 if (offs + total > buf->dtb_size) {
11111                         /*
11112                          * We can't fit in the end of the buffer.  First, a
11113                          * sanity check that we can fit in the buffer at all.
11114                          */
11115                         if (total > buf->dtb_size) {
11116                                 dtrace_buffer_drop(buf);
11117                                 return (-1);
11118                         }
11119
11120                         /*
11121                          * We're going to be storing at the top of the buffer,
11122                          * so now we need to deal with the wrapped offset.  We
11123                          * only reset our wrapped offset to 0 if it is
11124                          * currently greater than the current offset.  If it
11125                          * is less than the current offset, it is because a
11126                          * previous allocation induced a wrap -- but the
11127                          * allocation didn't subsequently take the space due
11128                          * to an error or false predicate evaluation.  In this
11129                          * case, we'll just leave the wrapped offset alone: if
11130                          * the wrapped offset hasn't been advanced far enough
11131                          * for this allocation, it will be adjusted in the
11132                          * lower loop.
11133                          */
11134                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11135                                 if (woffs >= offs)
11136                                         woffs = 0;
11137                         } else {
11138                                 woffs = 0;
11139                         }
11140
11141                         /*
11142                          * Now we know that we're going to be storing to the
11143                          * top of the buffer and that there is room for us
11144                          * there.  We need to clear the buffer from the current
11145                          * offset to the end (there may be old gunk there).
11146                          */
11147                         while (offs < buf->dtb_size)
11148                                 tomax[offs++] = 0;
11149
11150                         /*
11151                          * We need to set our offset to zero.  And because we
11152                          * are wrapping, we need to set the bit indicating as
11153                          * much.  We can also adjust our needed space back
11154                          * down to the space required by the ECB -- we know
11155                          * that the top of the buffer is aligned.
11156                          */
11157                         offs = 0;
11158                         total = needed;
11159                         buf->dtb_flags |= DTRACEBUF_WRAPPED;
11160                 } else {
11161                         /*
11162                          * There is room for us in the buffer, so we simply
11163                          * need to check the wrapped offset.
11164                          */
11165                         if (woffs < offs) {
11166                                 /*
11167                                  * The wrapped offset is less than the offset.
11168                                  * This can happen if we allocated buffer space
11169                                  * that induced a wrap, but then we didn't
11170                                  * subsequently take the space due to an error
11171                                  * or false predicate evaluation.  This is
11172                                  * okay; we know that _this_ allocation isn't
11173                                  * going to induce a wrap.  We still can't
11174                                  * reset the wrapped offset to be zero,
11175                                  * however: the space may have been trashed in
11176                                  * the previous failed probe attempt.  But at
11177                                  * least the wrapped offset doesn't need to
11178                                  * be adjusted at all...
11179                                  */
11180                                 goto out;
11181                         }
11182                 }
11183
11184                 while (offs + total > woffs) {
11185                         dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11186                         size_t size;
11187
11188                         if (epid == DTRACE_EPIDNONE) {
11189                                 size = sizeof (uint32_t);
11190                         } else {
11191                                 ASSERT3U(epid, <=, state->dts_necbs);
11192                                 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11193
11194                                 size = state->dts_ecbs[epid - 1]->dte_size;
11195                         }
11196
11197                         ASSERT(woffs + size <= buf->dtb_size);
11198                         ASSERT(size != 0);
11199
11200                         if (woffs + size == buf->dtb_size) {
11201                                 /*
11202                                  * We've reached the end of the buffer; we want
11203                                  * to set the wrapped offset to 0 and break
11204                                  * out.  However, if the offs is 0, then we're
11205                                  * in a strange edge-condition:  the amount of
11206                                  * space that we want to reserve plus the size
11207                                  * of the record that we're overwriting is
11208                                  * greater than the size of the buffer.  This
11209                                  * is problematic because if we reserve the
11210                                  * space but subsequently don't consume it (due
11211                                  * to a failed predicate or error) the wrapped
11212                                  * offset will be 0 -- yet the EPID at offset 0
11213                                  * will not be committed.  This situation is
11214                                  * relatively easy to deal with:  if we're in
11215                                  * this case, the buffer is indistinguishable
11216                                  * from one that hasn't wrapped; we need only
11217                                  * finish the job by clearing the wrapped bit,
11218                                  * explicitly setting the offset to be 0, and
11219                                  * zero'ing out the old data in the buffer.
11220                                  */
11221                                 if (offs == 0) {
11222                                         buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11223                                         buf->dtb_offset = 0;
11224                                         woffs = total;
11225
11226                                         while (woffs < buf->dtb_size)
11227                                                 tomax[woffs++] = 0;
11228                                 }
11229
11230                                 woffs = 0;
11231                                 break;
11232                         }
11233
11234                         woffs += size;
11235                 }
11236
11237                 /*
11238                  * We have a wrapped offset.  It may be that the wrapped offset
11239                  * has become zero -- that's okay.
11240                  */
11241                 buf->dtb_xamot_offset = woffs;
11242         }
11243
11244 out:
11245         /*
11246          * Now we can plow the buffer with any necessary padding.
11247          */
11248         while (offs & (align - 1)) {
11249                 /*
11250                  * Assert that our alignment is off by a number which
11251                  * is itself sizeof (uint32_t) aligned.
11252                  */
11253                 ASSERT(!((align - (offs & (align - 1))) &
11254                     (sizeof (uint32_t) - 1)));
11255                 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11256                 offs += sizeof (uint32_t);
11257         }
11258
11259         if (buf->dtb_flags & DTRACEBUF_FILL) {
11260                 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11261                         buf->dtb_flags |= DTRACEBUF_FULL;
11262                         return (-1);
11263                 }
11264         }
11265
11266         if (mstate == NULL)
11267                 return (offs);
11268
11269         /*
11270          * For ring buffers and fill buffers, the scratch space is always
11271          * the inactive buffer.
11272          */
11273         mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11274         mstate->dtms_scratch_size = buf->dtb_size;
11275         mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11276
11277         return (offs);
11278 }
11279
11280 static void
11281 dtrace_buffer_polish(dtrace_buffer_t *buf)
11282 {
11283         ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11284         ASSERT(MUTEX_HELD(&dtrace_lock));
11285
11286         if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11287                 return;
11288
11289         /*
11290          * We need to polish the ring buffer.  There are three cases:
11291          *
11292          * - The first (and presumably most common) is that there is no gap
11293          *   between the buffer offset and the wrapped offset.  In this case,
11294          *   there is nothing in the buffer that isn't valid data; we can
11295          *   mark the buffer as polished and return.
11296          *
11297          * - The second (less common than the first but still more common
11298          *   than the third) is that there is a gap between the buffer offset
11299          *   and the wrapped offset, and the wrapped offset is larger than the
11300          *   buffer offset.  This can happen because of an alignment issue, or
11301          *   can happen because of a call to dtrace_buffer_reserve() that
11302          *   didn't subsequently consume the buffer space.  In this case,
11303          *   we need to zero the data from the buffer offset to the wrapped
11304          *   offset.
11305          *
11306          * - The third (and least common) is that there is a gap between the
11307          *   buffer offset and the wrapped offset, but the wrapped offset is
11308          *   _less_ than the buffer offset.  This can only happen because a
11309          *   call to dtrace_buffer_reserve() induced a wrap, but the space
11310          *   was not subsequently consumed.  In this case, we need to zero the
11311          *   space from the offset to the end of the buffer _and_ from the
11312          *   top of the buffer to the wrapped offset.
11313          */
11314         if (buf->dtb_offset < buf->dtb_xamot_offset) {
11315                 bzero(buf->dtb_tomax + buf->dtb_offset,
11316                     buf->dtb_xamot_offset - buf->dtb_offset);
11317         }
11318
11319         if (buf->dtb_offset > buf->dtb_xamot_offset) {
11320                 bzero(buf->dtb_tomax + buf->dtb_offset,
11321                     buf->dtb_size - buf->dtb_offset);
11322                 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11323         }
11324 }
11325
11326 /*
11327  * This routine determines if data generated at the specified time has likely
11328  * been entirely consumed at user-level.  This routine is called to determine
11329  * if an ECB on a defunct probe (but for an active enabling) can be safely
11330  * disabled and destroyed.
11331  */
11332 static int
11333 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11334 {
11335         int i;
11336
11337         for (i = 0; i < NCPU; i++) {
11338                 dtrace_buffer_t *buf = &bufs[i];
11339
11340                 if (buf->dtb_size == 0)
11341                         continue;
11342
11343                 if (buf->dtb_flags & DTRACEBUF_RING)
11344                         return (0);
11345
11346                 if (!buf->dtb_switched && buf->dtb_offset != 0)
11347                         return (0);
11348
11349                 if (buf->dtb_switched - buf->dtb_interval < when)
11350                         return (0);
11351         }
11352
11353         return (1);
11354 }
11355
11356 static void
11357 dtrace_buffer_free(dtrace_buffer_t *bufs)
11358 {
11359         int i;
11360
11361         for (i = 0; i < NCPU; i++) {
11362                 dtrace_buffer_t *buf = &bufs[i];
11363
11364                 if (buf->dtb_tomax == NULL) {
11365                         ASSERT(buf->dtb_xamot == NULL);
11366                         ASSERT(buf->dtb_size == 0);
11367                         continue;
11368                 }
11369
11370                 if (buf->dtb_xamot != NULL) {
11371                         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11372                         kmem_free(buf->dtb_xamot, buf->dtb_size);
11373                 }
11374
11375                 kmem_free(buf->dtb_tomax, buf->dtb_size);
11376                 buf->dtb_size = 0;
11377                 buf->dtb_tomax = NULL;
11378                 buf->dtb_xamot = NULL;
11379         }
11380 }
11381
11382 /*
11383  * DTrace Enabling Functions
11384  */
11385 static dtrace_enabling_t *
11386 dtrace_enabling_create(dtrace_vstate_t *vstate)
11387 {
11388         dtrace_enabling_t *enab;
11389
11390         enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11391         enab->dten_vstate = vstate;
11392
11393         return (enab);
11394 }
11395
11396 static void
11397 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11398 {
11399         dtrace_ecbdesc_t **ndesc;
11400         size_t osize, nsize;
11401
11402         /*
11403          * We can't add to enablings after we've enabled them, or after we've
11404          * retained them.
11405          */
11406         ASSERT(enab->dten_probegen == 0);
11407         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11408
11409         if (enab->dten_ndesc < enab->dten_maxdesc) {
11410                 enab->dten_desc[enab->dten_ndesc++] = ecb;
11411                 return;
11412         }
11413
11414         osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11415
11416         if (enab->dten_maxdesc == 0) {
11417                 enab->dten_maxdesc = 1;
11418         } else {
11419                 enab->dten_maxdesc <<= 1;
11420         }
11421
11422         ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11423
11424         nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11425         ndesc = kmem_zalloc(nsize, KM_SLEEP);
11426         bcopy(enab->dten_desc, ndesc, osize);
11427         if (enab->dten_desc != NULL)
11428                 kmem_free(enab->dten_desc, osize);
11429
11430         enab->dten_desc = ndesc;
11431         enab->dten_desc[enab->dten_ndesc++] = ecb;
11432 }
11433
11434 static void
11435 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11436     dtrace_probedesc_t *pd)
11437 {
11438         dtrace_ecbdesc_t *new;
11439         dtrace_predicate_t *pred;
11440         dtrace_actdesc_t *act;
11441
11442         /*
11443          * We're going to create a new ECB description that matches the
11444          * specified ECB in every way, but has the specified probe description.
11445          */
11446         new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11447
11448         if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11449                 dtrace_predicate_hold(pred);
11450
11451         for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11452                 dtrace_actdesc_hold(act);
11453
11454         new->dted_action = ecb->dted_action;
11455         new->dted_pred = ecb->dted_pred;
11456         new->dted_probe = *pd;
11457         new->dted_uarg = ecb->dted_uarg;
11458
11459         dtrace_enabling_add(enab, new);
11460 }
11461
11462 static void
11463 dtrace_enabling_dump(dtrace_enabling_t *enab)
11464 {
11465         int i;
11466
11467         for (i = 0; i < enab->dten_ndesc; i++) {
11468                 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11469
11470                 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11471                     desc->dtpd_provider, desc->dtpd_mod,
11472                     desc->dtpd_func, desc->dtpd_name);
11473         }
11474 }
11475
11476 static void
11477 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11478 {
11479         int i;
11480         dtrace_ecbdesc_t *ep;
11481         dtrace_vstate_t *vstate = enab->dten_vstate;
11482
11483         ASSERT(MUTEX_HELD(&dtrace_lock));
11484
11485         for (i = 0; i < enab->dten_ndesc; i++) {
11486                 dtrace_actdesc_t *act, *next;
11487                 dtrace_predicate_t *pred;
11488
11489                 ep = enab->dten_desc[i];
11490
11491                 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11492                         dtrace_predicate_release(pred, vstate);
11493
11494                 for (act = ep->dted_action; act != NULL; act = next) {
11495                         next = act->dtad_next;
11496                         dtrace_actdesc_release(act, vstate);
11497                 }
11498
11499                 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11500         }
11501
11502         if (enab->dten_desc != NULL)
11503                 kmem_free(enab->dten_desc,
11504                     enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11505
11506         /*
11507          * If this was a retained enabling, decrement the dts_nretained count
11508          * and take it off of the dtrace_retained list.
11509          */
11510         if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11511             dtrace_retained == enab) {
11512                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11513                 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11514                 enab->dten_vstate->dtvs_state->dts_nretained--;
11515         }
11516
11517         if (enab->dten_prev == NULL) {
11518                 if (dtrace_retained == enab) {
11519                         dtrace_retained = enab->dten_next;
11520
11521                         if (dtrace_retained != NULL)
11522                                 dtrace_retained->dten_prev = NULL;
11523                 }
11524         } else {
11525                 ASSERT(enab != dtrace_retained);
11526                 ASSERT(dtrace_retained != NULL);
11527                 enab->dten_prev->dten_next = enab->dten_next;
11528         }
11529
11530         if (enab->dten_next != NULL) {
11531                 ASSERT(dtrace_retained != NULL);
11532                 enab->dten_next->dten_prev = enab->dten_prev;
11533         }
11534
11535         kmem_free(enab, sizeof (dtrace_enabling_t));
11536 }
11537
11538 static int
11539 dtrace_enabling_retain(dtrace_enabling_t *enab)
11540 {
11541         dtrace_state_t *state;
11542
11543         ASSERT(MUTEX_HELD(&dtrace_lock));
11544         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11545         ASSERT(enab->dten_vstate != NULL);
11546
11547         state = enab->dten_vstate->dtvs_state;
11548         ASSERT(state != NULL);
11549
11550         /*
11551          * We only allow each state to retain dtrace_retain_max enablings.
11552          */
11553         if (state->dts_nretained >= dtrace_retain_max)
11554                 return (ENOSPC);
11555
11556         state->dts_nretained++;
11557
11558         if (dtrace_retained == NULL) {
11559                 dtrace_retained = enab;
11560                 return (0);
11561         }
11562
11563         enab->dten_next = dtrace_retained;
11564         dtrace_retained->dten_prev = enab;
11565         dtrace_retained = enab;
11566
11567         return (0);
11568 }
11569
11570 static int
11571 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11572     dtrace_probedesc_t *create)
11573 {
11574         dtrace_enabling_t *new, *enab;
11575         int found = 0, err = ENOENT;
11576
11577         ASSERT(MUTEX_HELD(&dtrace_lock));
11578         ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11579         ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11580         ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11581         ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11582
11583         new = dtrace_enabling_create(&state->dts_vstate);
11584
11585         /*
11586          * Iterate over all retained enablings, looking for enablings that
11587          * match the specified state.
11588          */
11589         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11590                 int i;
11591
11592                 /*
11593                  * dtvs_state can only be NULL for helper enablings -- and
11594                  * helper enablings can't be retained.
11595                  */
11596                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11597
11598                 if (enab->dten_vstate->dtvs_state != state)
11599                         continue;
11600
11601                 /*
11602                  * Now iterate over each probe description; we're looking for
11603                  * an exact match to the specified probe description.
11604                  */
11605                 for (i = 0; i < enab->dten_ndesc; i++) {
11606                         dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11607                         dtrace_probedesc_t *pd = &ep->dted_probe;
11608
11609                         if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11610                                 continue;
11611
11612                         if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11613                                 continue;
11614
11615                         if (strcmp(pd->dtpd_func, match->dtpd_func))
11616                                 continue;
11617
11618                         if (strcmp(pd->dtpd_name, match->dtpd_name))
11619                                 continue;
11620
11621                         /*
11622                          * We have a winning probe!  Add it to our growing
11623                          * enabling.
11624                          */
11625                         found = 1;
11626                         dtrace_enabling_addlike(new, ep, create);
11627                 }
11628         }
11629
11630         if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11631                 dtrace_enabling_destroy(new);
11632                 return (err);
11633         }
11634
11635         return (0);
11636 }
11637
11638 static void
11639 dtrace_enabling_retract(dtrace_state_t *state)
11640 {
11641         dtrace_enabling_t *enab, *next;
11642
11643         ASSERT(MUTEX_HELD(&dtrace_lock));
11644
11645         /*
11646          * Iterate over all retained enablings, destroy the enablings retained
11647          * for the specified state.
11648          */
11649         for (enab = dtrace_retained; enab != NULL; enab = next) {
11650                 next = enab->dten_next;
11651
11652                 /*
11653                  * dtvs_state can only be NULL for helper enablings -- and
11654                  * helper enablings can't be retained.
11655                  */
11656                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11657
11658                 if (enab->dten_vstate->dtvs_state == state) {
11659                         ASSERT(state->dts_nretained > 0);
11660                         dtrace_enabling_destroy(enab);
11661                 }
11662         }
11663
11664         ASSERT(state->dts_nretained == 0);
11665 }
11666
11667 static int
11668 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11669 {
11670         int i = 0;
11671         int matched = 0;
11672
11673         ASSERT(MUTEX_HELD(&cpu_lock));
11674         ASSERT(MUTEX_HELD(&dtrace_lock));
11675
11676         for (i = 0; i < enab->dten_ndesc; i++) {
11677                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11678
11679                 enab->dten_current = ep;
11680                 enab->dten_error = 0;
11681
11682                 matched += dtrace_probe_enable(&ep->dted_probe, enab);
11683
11684                 if (enab->dten_error != 0) {
11685                         /*
11686                          * If we get an error half-way through enabling the
11687                          * probes, we kick out -- perhaps with some number of
11688                          * them enabled.  Leaving enabled probes enabled may
11689                          * be slightly confusing for user-level, but we expect
11690                          * that no one will attempt to actually drive on in
11691                          * the face of such errors.  If this is an anonymous
11692                          * enabling (indicated with a NULL nmatched pointer),
11693                          * we cmn_err() a message.  We aren't expecting to
11694                          * get such an error -- such as it can exist at all,
11695                          * it would be a result of corrupted DOF in the driver
11696                          * properties.
11697                          */
11698                         if (nmatched == NULL) {
11699                                 cmn_err(CE_WARN, "dtrace_enabling_match() "
11700                                     "error on %p: %d", (void *)ep,
11701                                     enab->dten_error);
11702                         }
11703
11704                         return (enab->dten_error);
11705                 }
11706         }
11707
11708         enab->dten_probegen = dtrace_probegen;
11709         if (nmatched != NULL)
11710                 *nmatched = matched;
11711
11712         return (0);
11713 }
11714
11715 static void
11716 dtrace_enabling_matchall(void)
11717 {
11718         dtrace_enabling_t *enab;
11719
11720         mutex_enter(&cpu_lock);
11721         mutex_enter(&dtrace_lock);
11722
11723         /*
11724          * Iterate over all retained enablings to see if any probes match
11725          * against them.  We only perform this operation on enablings for which
11726          * we have sufficient permissions by virtue of being in the global zone
11727          * or in the same zone as the DTrace client.  Because we can be called
11728          * after dtrace_detach() has been called, we cannot assert that there
11729          * are retained enablings.  We can safely load from dtrace_retained,
11730          * however:  the taskq_destroy() at the end of dtrace_detach() will
11731          * block pending our completion.
11732          */
11733         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11734 #if defined(sun)
11735                 cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
11736
11737                 if (INGLOBALZONE(curproc) ||
11738                     cr != NULL && getzoneid() == crgetzoneid(cr))
11739 #endif
11740                         (void) dtrace_enabling_match(enab, NULL);
11741         }
11742
11743         mutex_exit(&dtrace_lock);
11744         mutex_exit(&cpu_lock);
11745 }
11746
11747 /*
11748  * If an enabling is to be enabled without having matched probes (that is, if
11749  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11750  * enabling must be _primed_ by creating an ECB for every ECB description.
11751  * This must be done to assure that we know the number of speculations, the
11752  * number of aggregations, the minimum buffer size needed, etc. before we
11753  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11754  * enabling any probes, we create ECBs for every ECB decription, but with a
11755  * NULL probe -- which is exactly what this function does.
11756  */
11757 static void
11758 dtrace_enabling_prime(dtrace_state_t *state)
11759 {
11760         dtrace_enabling_t *enab;
11761         int i;
11762
11763         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11764                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11765
11766                 if (enab->dten_vstate->dtvs_state != state)
11767                         continue;
11768
11769                 /*
11770                  * We don't want to prime an enabling more than once, lest
11771                  * we allow a malicious user to induce resource exhaustion.
11772                  * (The ECBs that result from priming an enabling aren't
11773                  * leaked -- but they also aren't deallocated until the
11774                  * consumer state is destroyed.)
11775                  */
11776                 if (enab->dten_primed)
11777                         continue;
11778
11779                 for (i = 0; i < enab->dten_ndesc; i++) {
11780                         enab->dten_current = enab->dten_desc[i];
11781                         (void) dtrace_probe_enable(NULL, enab);
11782                 }
11783
11784                 enab->dten_primed = 1;
11785         }
11786 }
11787
11788 /*
11789  * Called to indicate that probes should be provided due to retained
11790  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
11791  * must take an initial lap through the enabling calling the dtps_provide()
11792  * entry point explicitly to allow for autocreated probes.
11793  */
11794 static void
11795 dtrace_enabling_provide(dtrace_provider_t *prv)
11796 {
11797         int i, all = 0;
11798         dtrace_probedesc_t desc;
11799
11800         ASSERT(MUTEX_HELD(&dtrace_lock));
11801         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11802
11803         if (prv == NULL) {
11804                 all = 1;
11805                 prv = dtrace_provider;
11806         }
11807
11808         do {
11809                 dtrace_enabling_t *enab = dtrace_retained;
11810                 void *parg = prv->dtpv_arg;
11811
11812                 for (; enab != NULL; enab = enab->dten_next) {
11813                         for (i = 0; i < enab->dten_ndesc; i++) {
11814                                 desc = enab->dten_desc[i]->dted_probe;
11815                                 mutex_exit(&dtrace_lock);
11816                                 prv->dtpv_pops.dtps_provide(parg, &desc);
11817                                 mutex_enter(&dtrace_lock);
11818                         }
11819                 }
11820         } while (all && (prv = prv->dtpv_next) != NULL);
11821
11822         mutex_exit(&dtrace_lock);
11823         dtrace_probe_provide(NULL, all ? NULL : prv);
11824         mutex_enter(&dtrace_lock);
11825 }
11826
11827 /*
11828  * Called to reap ECBs that are attached to probes from defunct providers.
11829  */
11830 static void
11831 dtrace_enabling_reap(void)
11832 {
11833         dtrace_provider_t *prov;
11834         dtrace_probe_t *probe;
11835         dtrace_ecb_t *ecb;
11836         hrtime_t when;
11837         int i;
11838
11839         mutex_enter(&cpu_lock);
11840         mutex_enter(&dtrace_lock);
11841
11842         for (i = 0; i < dtrace_nprobes; i++) {
11843                 if ((probe = dtrace_probes[i]) == NULL)
11844                         continue;
11845
11846                 if (probe->dtpr_ecb == NULL)
11847                         continue;
11848
11849                 prov = probe->dtpr_provider;
11850
11851                 if ((when = prov->dtpv_defunct) == 0)
11852                         continue;
11853
11854                 /*
11855                  * We have ECBs on a defunct provider:  we want to reap these
11856                  * ECBs to allow the provider to unregister.  The destruction
11857                  * of these ECBs must be done carefully:  if we destroy the ECB
11858                  * and the consumer later wishes to consume an EPID that
11859                  * corresponds to the destroyed ECB (and if the EPID metadata
11860                  * has not been previously consumed), the consumer will abort
11861                  * processing on the unknown EPID.  To reduce (but not, sadly,
11862                  * eliminate) the possibility of this, we will only destroy an
11863                  * ECB for a defunct provider if, for the state that
11864                  * corresponds to the ECB:
11865                  *
11866                  *  (a) There is no speculative tracing (which can effectively
11867                  *      cache an EPID for an arbitrary amount of time).
11868                  *
11869                  *  (b) The principal buffers have been switched twice since the
11870                  *      provider became defunct.
11871                  *
11872                  *  (c) The aggregation buffers are of zero size or have been
11873                  *      switched twice since the provider became defunct.
11874                  *
11875                  * We use dts_speculates to determine (a) and call a function
11876                  * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
11877                  * that as soon as we've been unable to destroy one of the ECBs
11878                  * associated with the probe, we quit trying -- reaping is only
11879                  * fruitful in as much as we can destroy all ECBs associated
11880                  * with the defunct provider's probes.
11881                  */
11882                 while ((ecb = probe->dtpr_ecb) != NULL) {
11883                         dtrace_state_t *state = ecb->dte_state;
11884                         dtrace_buffer_t *buf = state->dts_buffer;
11885                         dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
11886
11887                         if (state->dts_speculates)
11888                                 break;
11889
11890                         if (!dtrace_buffer_consumed(buf, when))
11891                                 break;
11892
11893                         if (!dtrace_buffer_consumed(aggbuf, when))
11894                                 break;
11895
11896                         dtrace_ecb_disable(ecb);
11897                         ASSERT(probe->dtpr_ecb != ecb);
11898                         dtrace_ecb_destroy(ecb);
11899                 }
11900         }
11901
11902         mutex_exit(&dtrace_lock);
11903         mutex_exit(&cpu_lock);
11904 }
11905
11906 /*
11907  * DTrace DOF Functions
11908  */
11909 /*ARGSUSED*/
11910 static void
11911 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11912 {
11913         if (dtrace_err_verbose)
11914                 cmn_err(CE_WARN, "failed to process DOF: %s", str);
11915
11916 #ifdef DTRACE_ERRDEBUG
11917         dtrace_errdebug(str);
11918 #endif
11919 }
11920
11921 /*
11922  * Create DOF out of a currently enabled state.  Right now, we only create
11923  * DOF containing the run-time options -- but this could be expanded to create
11924  * complete DOF representing the enabled state.
11925  */
11926 static dof_hdr_t *
11927 dtrace_dof_create(dtrace_state_t *state)
11928 {
11929         dof_hdr_t *dof;
11930         dof_sec_t *sec;
11931         dof_optdesc_t *opt;
11932         int i, len = sizeof (dof_hdr_t) +
11933             roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11934             sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11935
11936         ASSERT(MUTEX_HELD(&dtrace_lock));
11937
11938         dof = kmem_zalloc(len, KM_SLEEP);
11939         dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11940         dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11941         dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11942         dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11943
11944         dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11945         dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11946         dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11947         dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11948         dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11949         dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11950
11951         dof->dofh_flags = 0;
11952         dof->dofh_hdrsize = sizeof (dof_hdr_t);
11953         dof->dofh_secsize = sizeof (dof_sec_t);
11954         dof->dofh_secnum = 1;   /* only DOF_SECT_OPTDESC */
11955         dof->dofh_secoff = sizeof (dof_hdr_t);
11956         dof->dofh_loadsz = len;
11957         dof->dofh_filesz = len;
11958         dof->dofh_pad = 0;
11959
11960         /*
11961          * Fill in the option section header...
11962          */
11963         sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11964         sec->dofs_type = DOF_SECT_OPTDESC;
11965         sec->dofs_align = sizeof (uint64_t);
11966         sec->dofs_flags = DOF_SECF_LOAD;
11967         sec->dofs_entsize = sizeof (dof_optdesc_t);
11968
11969         opt = (dof_optdesc_t *)((uintptr_t)sec +
11970             roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11971
11972         sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11973         sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11974
11975         for (i = 0; i < DTRACEOPT_MAX; i++) {
11976                 opt[i].dofo_option = i;
11977                 opt[i].dofo_strtab = DOF_SECIDX_NONE;
11978                 opt[i].dofo_value = state->dts_options[i];
11979         }
11980
11981         return (dof);
11982 }
11983
11984 static dof_hdr_t *
11985 dtrace_dof_copyin(uintptr_t uarg, int *errp)
11986 {
11987         dof_hdr_t hdr, *dof;
11988
11989         ASSERT(!MUTEX_HELD(&dtrace_lock));
11990
11991         /*
11992          * First, we're going to copyin() the sizeof (dof_hdr_t).
11993          */
11994         if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11995                 dtrace_dof_error(NULL, "failed to copyin DOF header");
11996                 *errp = EFAULT;
11997                 return (NULL);
11998         }
11999
12000         /*
12001          * Now we'll allocate the entire DOF and copy it in -- provided
12002          * that the length isn't outrageous.
12003          */
12004         if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12005                 dtrace_dof_error(&hdr, "load size exceeds maximum");
12006                 *errp = E2BIG;
12007                 return (NULL);
12008         }
12009
12010         if (hdr.dofh_loadsz < sizeof (hdr)) {
12011                 dtrace_dof_error(&hdr, "invalid load size");
12012                 *errp = EINVAL;
12013                 return (NULL);
12014         }
12015
12016         dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12017
12018         if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
12019                 kmem_free(dof, hdr.dofh_loadsz);
12020                 *errp = EFAULT;
12021                 return (NULL);
12022         }
12023
12024         return (dof);
12025 }
12026
12027 #if !defined(sun)
12028 static __inline uchar_t
12029 dtrace_dof_char(char c) {
12030         switch (c) {
12031         case '0':
12032         case '1':
12033         case '2':
12034         case '3':
12035         case '4':
12036         case '5':
12037         case '6':
12038         case '7':
12039         case '8':
12040         case '9':
12041                 return (c - '0');
12042         case 'A':
12043         case 'B':
12044         case 'C':
12045         case 'D':
12046         case 'E':
12047         case 'F':
12048                 return (c - 'A' + 10);
12049         case 'a':
12050         case 'b':
12051         case 'c':
12052         case 'd':
12053         case 'e':
12054         case 'f':
12055                 return (c - 'a' + 10);
12056         }
12057         /* Should not reach here. */
12058         return (0);
12059 }
12060 #endif
12061
12062 static dof_hdr_t *
12063 dtrace_dof_property(const char *name)
12064 {
12065         uchar_t *buf;
12066         uint64_t loadsz;
12067         unsigned int len, i;
12068         dof_hdr_t *dof;
12069
12070 #if defined(sun)
12071         /*
12072          * Unfortunately, array of values in .conf files are always (and
12073          * only) interpreted to be integer arrays.  We must read our DOF
12074          * as an integer array, and then squeeze it into a byte array.
12075          */
12076         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12077             (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12078                 return (NULL);
12079
12080         for (i = 0; i < len; i++)
12081                 buf[i] = (uchar_t)(((int *)buf)[i]);
12082
12083         if (len < sizeof (dof_hdr_t)) {
12084                 ddi_prop_free(buf);
12085                 dtrace_dof_error(NULL, "truncated header");
12086                 return (NULL);
12087         }
12088
12089         if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12090                 ddi_prop_free(buf);
12091                 dtrace_dof_error(NULL, "truncated DOF");
12092                 return (NULL);
12093         }
12094
12095         if (loadsz >= dtrace_dof_maxsize) {
12096                 ddi_prop_free(buf);
12097                 dtrace_dof_error(NULL, "oversized DOF");
12098                 return (NULL);
12099         }
12100
12101         dof = kmem_alloc(loadsz, KM_SLEEP);
12102         bcopy(buf, dof, loadsz);
12103         ddi_prop_free(buf);
12104 #else
12105         char *p;
12106         char *p_env;
12107
12108         if ((p_env = getenv(name)) == NULL)
12109                 return (NULL);
12110
12111         len = strlen(p_env) / 2;
12112
12113         buf = kmem_alloc(len, KM_SLEEP);
12114
12115         dof = (dof_hdr_t *) buf;
12116
12117         p = p_env;
12118
12119         for (i = 0; i < len; i++) {
12120                 buf[i] = (dtrace_dof_char(p[0]) << 4) |
12121                      dtrace_dof_char(p[1]);
12122                 p += 2;
12123         }
12124
12125         freeenv(p_env);
12126
12127         if (len < sizeof (dof_hdr_t)) {
12128                 kmem_free(buf, 0);
12129                 dtrace_dof_error(NULL, "truncated header");
12130                 return (NULL);
12131         }
12132
12133         if (len < (loadsz = dof->dofh_loadsz)) {
12134                 kmem_free(buf, 0);
12135                 dtrace_dof_error(NULL, "truncated DOF");
12136                 return (NULL);
12137         }
12138
12139         if (loadsz >= dtrace_dof_maxsize) {
12140                 kmem_free(buf, 0);
12141                 dtrace_dof_error(NULL, "oversized DOF");
12142                 return (NULL);
12143         }
12144 #endif
12145
12146         return (dof);
12147 }
12148
12149 static void
12150 dtrace_dof_destroy(dof_hdr_t *dof)
12151 {
12152         kmem_free(dof, dof->dofh_loadsz);
12153 }
12154
12155 /*
12156  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12157  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12158  * a type other than DOF_SECT_NONE is specified, the header is checked against
12159  * this type and NULL is returned if the types do not match.
12160  */
12161 static dof_sec_t *
12162 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12163 {
12164         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12165             ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12166
12167         if (i >= dof->dofh_secnum) {
12168                 dtrace_dof_error(dof, "referenced section index is invalid");
12169                 return (NULL);
12170         }
12171
12172         if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12173                 dtrace_dof_error(dof, "referenced section is not loadable");
12174                 return (NULL);
12175         }
12176
12177         if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12178                 dtrace_dof_error(dof, "referenced section is the wrong type");
12179                 return (NULL);
12180         }
12181
12182         return (sec);
12183 }
12184
12185 static dtrace_probedesc_t *
12186 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12187 {
12188         dof_probedesc_t *probe;
12189         dof_sec_t *strtab;
12190         uintptr_t daddr = (uintptr_t)dof;
12191         uintptr_t str;
12192         size_t size;
12193
12194         if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12195                 dtrace_dof_error(dof, "invalid probe section");
12196                 return (NULL);
12197         }
12198
12199         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12200                 dtrace_dof_error(dof, "bad alignment in probe description");
12201                 return (NULL);
12202         }
12203
12204         if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12205                 dtrace_dof_error(dof, "truncated probe description");
12206                 return (NULL);
12207         }
12208
12209         probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12210         strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12211
12212         if (strtab == NULL)
12213                 return (NULL);
12214
12215         str = daddr + strtab->dofs_offset;
12216         size = strtab->dofs_size;
12217
12218         if (probe->dofp_provider >= strtab->dofs_size) {
12219                 dtrace_dof_error(dof, "corrupt probe provider");
12220                 return (NULL);
12221         }
12222
12223         (void) strncpy(desc->dtpd_provider,
12224             (char *)(str + probe->dofp_provider),
12225             MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12226
12227         if (probe->dofp_mod >= strtab->dofs_size) {
12228                 dtrace_dof_error(dof, "corrupt probe module");
12229                 return (NULL);
12230         }
12231
12232         (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12233             MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12234
12235         if (probe->dofp_func >= strtab->dofs_size) {
12236                 dtrace_dof_error(dof, "corrupt probe function");
12237                 return (NULL);
12238         }
12239
12240         (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12241             MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12242
12243         if (probe->dofp_name >= strtab->dofs_size) {
12244                 dtrace_dof_error(dof, "corrupt probe name");
12245                 return (NULL);
12246         }
12247
12248         (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12249             MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12250
12251         return (desc);
12252 }
12253
12254 static dtrace_difo_t *
12255 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12256     cred_t *cr)
12257 {
12258         dtrace_difo_t *dp;
12259         size_t ttl = 0;
12260         dof_difohdr_t *dofd;
12261         uintptr_t daddr = (uintptr_t)dof;
12262         size_t max = dtrace_difo_maxsize;
12263         int i, l, n;
12264
12265         static const struct {
12266                 int section;
12267                 int bufoffs;
12268                 int lenoffs;
12269                 int entsize;
12270                 int align;
12271                 const char *msg;
12272         } difo[] = {
12273                 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12274                 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12275                 sizeof (dif_instr_t), "multiple DIF sections" },
12276
12277                 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12278                 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12279                 sizeof (uint64_t), "multiple integer tables" },
12280
12281                 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12282                 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12283                 sizeof (char), "multiple string tables" },
12284
12285                 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12286                 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12287                 sizeof (uint_t), "multiple variable tables" },
12288
12289                 { DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12290         };
12291
12292         if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12293                 dtrace_dof_error(dof, "invalid DIFO header section");
12294                 return (NULL);
12295         }
12296
12297         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12298                 dtrace_dof_error(dof, "bad alignment in DIFO header");
12299                 return (NULL);
12300         }
12301
12302         if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12303             sec->dofs_size % sizeof (dof_secidx_t)) {
12304                 dtrace_dof_error(dof, "bad size in DIFO header");
12305                 return (NULL);
12306         }
12307
12308         dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12309         n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12310
12311         dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12312         dp->dtdo_rtype = dofd->dofd_rtype;
12313
12314         for (l = 0; l < n; l++) {
12315                 dof_sec_t *subsec;
12316                 void **bufp;
12317                 uint32_t *lenp;
12318
12319                 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12320                     dofd->dofd_links[l])) == NULL)
12321                         goto err; /* invalid section link */
12322
12323                 if (ttl + subsec->dofs_size > max) {
12324                         dtrace_dof_error(dof, "exceeds maximum size");
12325                         goto err;
12326                 }
12327
12328                 ttl += subsec->dofs_size;
12329
12330                 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12331                         if (subsec->dofs_type != difo[i].section)
12332                                 continue;
12333
12334                         if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12335                                 dtrace_dof_error(dof, "section not loaded");
12336                                 goto err;
12337                         }
12338
12339                         if (subsec->dofs_align != difo[i].align) {
12340                                 dtrace_dof_error(dof, "bad alignment");
12341                                 goto err;
12342                         }
12343
12344                         bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12345                         lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12346
12347                         if (*bufp != NULL) {
12348                                 dtrace_dof_error(dof, difo[i].msg);
12349                                 goto err;
12350                         }
12351
12352                         if (difo[i].entsize != subsec->dofs_entsize) {
12353                                 dtrace_dof_error(dof, "entry size mismatch");
12354                                 goto err;
12355                         }
12356
12357                         if (subsec->dofs_entsize != 0 &&
12358                             (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12359                                 dtrace_dof_error(dof, "corrupt entry size");
12360                                 goto err;
12361                         }
12362
12363                         *lenp = subsec->dofs_size;
12364                         *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12365                         bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12366                             *bufp, subsec->dofs_size);
12367
12368                         if (subsec->dofs_entsize != 0)
12369                                 *lenp /= subsec->dofs_entsize;
12370
12371                         break;
12372                 }
12373
12374                 /*
12375                  * If we encounter a loadable DIFO sub-section that is not
12376                  * known to us, assume this is a broken program and fail.
12377                  */
12378                 if (difo[i].section == DOF_SECT_NONE &&
12379                     (subsec->dofs_flags & DOF_SECF_LOAD)) {
12380                         dtrace_dof_error(dof, "unrecognized DIFO subsection");
12381                         goto err;
12382                 }
12383         }
12384
12385         if (dp->dtdo_buf == NULL) {
12386                 /*
12387                  * We can't have a DIF object without DIF text.
12388                  */
12389                 dtrace_dof_error(dof, "missing DIF text");
12390                 goto err;
12391         }
12392
12393         /*
12394          * Before we validate the DIF object, run through the variable table
12395          * looking for the strings -- if any of their size are under, we'll set
12396          * their size to be the system-wide default string size.  Note that
12397          * this should _not_ happen if the "strsize" option has been set --
12398          * in this case, the compiler should have set the size to reflect the
12399          * setting of the option.
12400          */
12401         for (i = 0; i < dp->dtdo_varlen; i++) {
12402                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12403                 dtrace_diftype_t *t = &v->dtdv_type;
12404
12405                 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12406                         continue;
12407
12408                 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12409                         t->dtdt_size = dtrace_strsize_default;
12410         }
12411
12412         if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12413                 goto err;
12414
12415         dtrace_difo_init(dp, vstate);
12416         return (dp);
12417
12418 err:
12419         kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12420         kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12421         kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12422         kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12423
12424         kmem_free(dp, sizeof (dtrace_difo_t));
12425         return (NULL);
12426 }
12427
12428 static dtrace_predicate_t *
12429 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12430     cred_t *cr)
12431 {
12432         dtrace_difo_t *dp;
12433
12434         if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12435                 return (NULL);
12436
12437         return (dtrace_predicate_create(dp));
12438 }
12439
12440 static dtrace_actdesc_t *
12441 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12442     cred_t *cr)
12443 {
12444         dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12445         dof_actdesc_t *desc;
12446         dof_sec_t *difosec;
12447         size_t offs;
12448         uintptr_t daddr = (uintptr_t)dof;
12449         uint64_t arg;
12450         dtrace_actkind_t kind;
12451
12452         if (sec->dofs_type != DOF_SECT_ACTDESC) {
12453                 dtrace_dof_error(dof, "invalid action section");
12454                 return (NULL);
12455         }
12456
12457         if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12458                 dtrace_dof_error(dof, "truncated action description");
12459                 return (NULL);
12460         }
12461
12462         if (sec->dofs_align != sizeof (uint64_t)) {
12463                 dtrace_dof_error(dof, "bad alignment in action description");
12464                 return (NULL);
12465         }
12466
12467         if (sec->dofs_size < sec->dofs_entsize) {
12468                 dtrace_dof_error(dof, "section entry size exceeds total size");
12469                 return (NULL);
12470         }
12471
12472         if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12473                 dtrace_dof_error(dof, "bad entry size in action description");
12474                 return (NULL);
12475         }
12476
12477         if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12478                 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12479                 return (NULL);
12480         }
12481
12482         for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12483                 desc = (dof_actdesc_t *)(daddr +
12484                     (uintptr_t)sec->dofs_offset + offs);
12485                 kind = (dtrace_actkind_t)desc->dofa_kind;
12486
12487                 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12488                     (kind != DTRACEACT_PRINTA ||
12489                     desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12490                     (kind == DTRACEACT_DIFEXPR &&
12491                     desc->dofa_strtab != DOF_SECIDX_NONE)) {
12492                         dof_sec_t *strtab;
12493                         char *str, *fmt;
12494                         uint64_t i;
12495
12496                         /*
12497                          * The argument to these actions is an index into the
12498                          * DOF string table.  For printf()-like actions, this
12499                          * is the format string.  For print(), this is the
12500                          * CTF type of the expression result.
12501                          */
12502                         if ((strtab = dtrace_dof_sect(dof,
12503                             DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12504                                 goto err;
12505
12506                         str = (char *)((uintptr_t)dof +
12507                             (uintptr_t)strtab->dofs_offset);
12508
12509                         for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12510                                 if (str[i] == '\0')
12511                                         break;
12512                         }
12513
12514                         if (i >= strtab->dofs_size) {
12515                                 dtrace_dof_error(dof, "bogus format string");
12516                                 goto err;
12517                         }
12518
12519                         if (i == desc->dofa_arg) {
12520                                 dtrace_dof_error(dof, "empty format string");
12521                                 goto err;
12522                         }
12523
12524                         i -= desc->dofa_arg;
12525                         fmt = kmem_alloc(i + 1, KM_SLEEP);
12526                         bcopy(&str[desc->dofa_arg], fmt, i + 1);
12527                         arg = (uint64_t)(uintptr_t)fmt;
12528                 } else {
12529                         if (kind == DTRACEACT_PRINTA) {
12530                                 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12531                                 arg = 0;
12532                         } else {
12533                                 arg = desc->dofa_arg;
12534                         }
12535                 }
12536
12537                 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12538                     desc->dofa_uarg, arg);
12539
12540                 if (last != NULL) {
12541                         last->dtad_next = act;
12542                 } else {
12543                         first = act;
12544                 }
12545
12546                 last = act;
12547
12548                 if (desc->dofa_difo == DOF_SECIDX_NONE)
12549                         continue;
12550
12551                 if ((difosec = dtrace_dof_sect(dof,
12552                     DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12553                         goto err;
12554
12555                 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12556
12557                 if (act->dtad_difo == NULL)
12558                         goto err;
12559         }
12560
12561         ASSERT(first != NULL);
12562         return (first);
12563
12564 err:
12565         for (act = first; act != NULL; act = next) {
12566                 next = act->dtad_next;
12567                 dtrace_actdesc_release(act, vstate);
12568         }
12569
12570         return (NULL);
12571 }
12572
12573 static dtrace_ecbdesc_t *
12574 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12575     cred_t *cr)
12576 {
12577         dtrace_ecbdesc_t *ep;
12578         dof_ecbdesc_t *ecb;
12579         dtrace_probedesc_t *desc;
12580         dtrace_predicate_t *pred = NULL;
12581
12582         if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12583                 dtrace_dof_error(dof, "truncated ECB description");
12584                 return (NULL);
12585         }
12586
12587         if (sec->dofs_align != sizeof (uint64_t)) {
12588                 dtrace_dof_error(dof, "bad alignment in ECB description");
12589                 return (NULL);
12590         }
12591
12592         ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12593         sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12594
12595         if (sec == NULL)
12596                 return (NULL);
12597
12598         ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12599         ep->dted_uarg = ecb->dofe_uarg;
12600         desc = &ep->dted_probe;
12601
12602         if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12603                 goto err;
12604
12605         if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12606                 if ((sec = dtrace_dof_sect(dof,
12607                     DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12608                         goto err;
12609
12610                 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12611                         goto err;
12612
12613                 ep->dted_pred.dtpdd_predicate = pred;
12614         }
12615
12616         if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12617                 if ((sec = dtrace_dof_sect(dof,
12618                     DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12619                         goto err;
12620
12621                 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12622
12623                 if (ep->dted_action == NULL)
12624                         goto err;
12625         }
12626
12627         return (ep);
12628
12629 err:
12630         if (pred != NULL)
12631                 dtrace_predicate_release(pred, vstate);
12632         kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12633         return (NULL);
12634 }
12635
12636 /*
12637  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12638  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12639  * site of any user SETX relocations to account for load object base address.
12640  * In the future, if we need other relocations, this function can be extended.
12641  */
12642 static int
12643 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12644 {
12645         uintptr_t daddr = (uintptr_t)dof;
12646         dof_relohdr_t *dofr =
12647             (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12648         dof_sec_t *ss, *rs, *ts;
12649         dof_relodesc_t *r;
12650         uint_t i, n;
12651
12652         if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12653             sec->dofs_align != sizeof (dof_secidx_t)) {
12654                 dtrace_dof_error(dof, "invalid relocation header");
12655                 return (-1);
12656         }
12657
12658         ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12659         rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12660         ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12661
12662         if (ss == NULL || rs == NULL || ts == NULL)
12663                 return (-1); /* dtrace_dof_error() has been called already */
12664
12665         if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12666             rs->dofs_align != sizeof (uint64_t)) {
12667                 dtrace_dof_error(dof, "invalid relocation section");
12668                 return (-1);
12669         }
12670
12671         r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12672         n = rs->dofs_size / rs->dofs_entsize;
12673
12674         for (i = 0; i < n; i++) {
12675                 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12676
12677                 switch (r->dofr_type) {
12678                 case DOF_RELO_NONE:
12679                         break;
12680                 case DOF_RELO_SETX:
12681                         if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12682                             sizeof (uint64_t) > ts->dofs_size) {
12683                                 dtrace_dof_error(dof, "bad relocation offset");
12684                                 return (-1);
12685                         }
12686
12687                         if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12688                                 dtrace_dof_error(dof, "misaligned setx relo");
12689                                 return (-1);
12690                         }
12691
12692                         *(uint64_t *)taddr += ubase;
12693                         break;
12694                 default:
12695                         dtrace_dof_error(dof, "invalid relocation type");
12696                         return (-1);
12697                 }
12698
12699                 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12700         }
12701
12702         return (0);
12703 }
12704
12705 /*
12706  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12707  * header:  it should be at the front of a memory region that is at least
12708  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12709  * size.  It need not be validated in any other way.
12710  */
12711 static int
12712 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12713     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12714 {
12715         uint64_t len = dof->dofh_loadsz, seclen;
12716         uintptr_t daddr = (uintptr_t)dof;
12717         dtrace_ecbdesc_t *ep;
12718         dtrace_enabling_t *enab;
12719         uint_t i;
12720
12721         ASSERT(MUTEX_HELD(&dtrace_lock));
12722         ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12723
12724         /*
12725          * Check the DOF header identification bytes.  In addition to checking
12726          * valid settings, we also verify that unused bits/bytes are zeroed so
12727          * we can use them later without fear of regressing existing binaries.
12728          */
12729         if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12730             DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12731                 dtrace_dof_error(dof, "DOF magic string mismatch");
12732                 return (-1);
12733         }
12734
12735         if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12736             dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12737                 dtrace_dof_error(dof, "DOF has invalid data model");
12738                 return (-1);
12739         }
12740
12741         if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12742                 dtrace_dof_error(dof, "DOF encoding mismatch");
12743                 return (-1);
12744         }
12745
12746         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12747             dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12748                 dtrace_dof_error(dof, "DOF version mismatch");
12749                 return (-1);
12750         }
12751
12752         if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12753                 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12754                 return (-1);
12755         }
12756
12757         if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12758                 dtrace_dof_error(dof, "DOF uses too many integer registers");
12759                 return (-1);
12760         }
12761
12762         if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12763                 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12764                 return (-1);
12765         }
12766
12767         for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12768                 if (dof->dofh_ident[i] != 0) {
12769                         dtrace_dof_error(dof, "DOF has invalid ident byte set");
12770                         return (-1);
12771                 }
12772         }
12773
12774         if (dof->dofh_flags & ~DOF_FL_VALID) {
12775                 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12776                 return (-1);
12777         }
12778
12779         if (dof->dofh_secsize == 0) {
12780                 dtrace_dof_error(dof, "zero section header size");
12781                 return (-1);
12782         }
12783
12784         /*
12785          * Check that the section headers don't exceed the amount of DOF
12786          * data.  Note that we cast the section size and number of sections
12787          * to uint64_t's to prevent possible overflow in the multiplication.
12788          */
12789         seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12790
12791         if (dof->dofh_secoff > len || seclen > len ||
12792             dof->dofh_secoff + seclen > len) {
12793                 dtrace_dof_error(dof, "truncated section headers");
12794                 return (-1);
12795         }
12796
12797         if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12798                 dtrace_dof_error(dof, "misaligned section headers");
12799                 return (-1);
12800         }
12801
12802         if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12803                 dtrace_dof_error(dof, "misaligned section size");
12804                 return (-1);
12805         }
12806
12807         /*
12808          * Take an initial pass through the section headers to be sure that
12809          * the headers don't have stray offsets.  If the 'noprobes' flag is
12810          * set, do not permit sections relating to providers, probes, or args.
12811          */
12812         for (i = 0; i < dof->dofh_secnum; i++) {
12813                 dof_sec_t *sec = (dof_sec_t *)(daddr +
12814                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12815
12816                 if (noprobes) {
12817                         switch (sec->dofs_type) {
12818                         case DOF_SECT_PROVIDER:
12819                         case DOF_SECT_PROBES:
12820                         case DOF_SECT_PRARGS:
12821                         case DOF_SECT_PROFFS:
12822                                 dtrace_dof_error(dof, "illegal sections "
12823                                     "for enabling");
12824                                 return (-1);
12825                         }
12826                 }
12827
12828                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12829                         continue; /* just ignore non-loadable sections */
12830
12831                 if (sec->dofs_align & (sec->dofs_align - 1)) {
12832                         dtrace_dof_error(dof, "bad section alignment");
12833                         return (-1);
12834                 }
12835
12836                 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12837                         dtrace_dof_error(dof, "misaligned section");
12838                         return (-1);
12839                 }
12840
12841                 if (sec->dofs_offset > len || sec->dofs_size > len ||
12842                     sec->dofs_offset + sec->dofs_size > len) {
12843                         dtrace_dof_error(dof, "corrupt section header");
12844                         return (-1);
12845                 }
12846
12847                 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12848                     sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12849                         dtrace_dof_error(dof, "non-terminating string table");
12850                         return (-1);
12851                 }
12852         }
12853
12854         /*
12855          * Take a second pass through the sections and locate and perform any
12856          * relocations that are present.  We do this after the first pass to
12857          * be sure that all sections have had their headers validated.
12858          */
12859         for (i = 0; i < dof->dofh_secnum; i++) {
12860                 dof_sec_t *sec = (dof_sec_t *)(daddr +
12861                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12862
12863                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12864                         continue; /* skip sections that are not loadable */
12865
12866                 switch (sec->dofs_type) {
12867                 case DOF_SECT_URELHDR:
12868                         if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12869                                 return (-1);
12870                         break;
12871                 }
12872         }
12873
12874         if ((enab = *enabp) == NULL)
12875                 enab = *enabp = dtrace_enabling_create(vstate);
12876
12877         for (i = 0; i < dof->dofh_secnum; i++) {
12878                 dof_sec_t *sec = (dof_sec_t *)(daddr +
12879                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12880
12881                 if (sec->dofs_type != DOF_SECT_ECBDESC)
12882                         continue;
12883
12884                 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12885                         dtrace_enabling_destroy(enab);
12886                         *enabp = NULL;
12887                         return (-1);
12888                 }
12889
12890                 dtrace_enabling_add(enab, ep);
12891         }
12892
12893         return (0);
12894 }
12895
12896 /*
12897  * Process DOF for any options.  This routine assumes that the DOF has been
12898  * at least processed by dtrace_dof_slurp().
12899  */
12900 static int
12901 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12902 {
12903         int i, rval;
12904         uint32_t entsize;
12905         size_t offs;
12906         dof_optdesc_t *desc;
12907
12908         for (i = 0; i < dof->dofh_secnum; i++) {
12909                 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12910                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12911
12912                 if (sec->dofs_type != DOF_SECT_OPTDESC)
12913                         continue;
12914
12915                 if (sec->dofs_align != sizeof (uint64_t)) {
12916                         dtrace_dof_error(dof, "bad alignment in "
12917                             "option description");
12918                         return (EINVAL);
12919                 }
12920
12921                 if ((entsize = sec->dofs_entsize) == 0) {
12922                         dtrace_dof_error(dof, "zeroed option entry size");
12923                         return (EINVAL);
12924                 }
12925
12926                 if (entsize < sizeof (dof_optdesc_t)) {
12927                         dtrace_dof_error(dof, "bad option entry size");
12928                         return (EINVAL);
12929                 }
12930
12931                 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12932                         desc = (dof_optdesc_t *)((uintptr_t)dof +
12933                             (uintptr_t)sec->dofs_offset + offs);
12934
12935                         if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12936                                 dtrace_dof_error(dof, "non-zero option string");
12937                                 return (EINVAL);
12938                         }
12939
12940                         if (desc->dofo_value == DTRACEOPT_UNSET) {
12941                                 dtrace_dof_error(dof, "unset option");
12942                                 return (EINVAL);
12943                         }
12944
12945                         if ((rval = dtrace_state_option(state,
12946                             desc->dofo_option, desc->dofo_value)) != 0) {
12947                                 dtrace_dof_error(dof, "rejected option");
12948                                 return (rval);
12949                         }
12950                 }
12951         }
12952
12953         return (0);
12954 }
12955
12956 /*
12957  * DTrace Consumer State Functions
12958  */
12959 static int
12960 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12961 {
12962         size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12963         void *base;
12964         uintptr_t limit;
12965         dtrace_dynvar_t *dvar, *next, *start;
12966         int i;
12967
12968         ASSERT(MUTEX_HELD(&dtrace_lock));
12969         ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12970
12971         bzero(dstate, sizeof (dtrace_dstate_t));
12972
12973         if ((dstate->dtds_chunksize = chunksize) == 0)
12974                 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12975
12976         if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12977                 size = min;
12978
12979         if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12980                 return (ENOMEM);
12981
12982         dstate->dtds_size = size;
12983         dstate->dtds_base = base;
12984         dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12985         bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12986
12987         hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12988
12989         if (hashsize != 1 && (hashsize & 1))
12990                 hashsize--;
12991
12992         dstate->dtds_hashsize = hashsize;
12993         dstate->dtds_hash = dstate->dtds_base;
12994
12995         /*
12996          * Set all of our hash buckets to point to the single sink, and (if
12997          * it hasn't already been set), set the sink's hash value to be the
12998          * sink sentinel value.  The sink is needed for dynamic variable
12999          * lookups to know that they have iterated over an entire, valid hash
13000          * chain.
13001          */
13002         for (i = 0; i < hashsize; i++)
13003                 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13004
13005         if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13006                 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13007
13008         /*
13009          * Determine number of active CPUs.  Divide free list evenly among
13010          * active CPUs.
13011          */
13012         start = (dtrace_dynvar_t *)
13013             ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13014         limit = (uintptr_t)base + size;
13015
13016         maxper = (limit - (uintptr_t)start) / NCPU;
13017         maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13018
13019 #if !defined(sun)
13020         CPU_FOREACH(i) {
13021 #else
13022         for (i = 0; i < NCPU; i++) {
13023 #endif
13024                 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13025
13026                 /*
13027                  * If we don't even have enough chunks to make it once through
13028                  * NCPUs, we're just going to allocate everything to the first
13029                  * CPU.  And if we're on the last CPU, we're going to allocate
13030                  * whatever is left over.  In either case, we set the limit to
13031                  * be the limit of the dynamic variable space.
13032                  */
13033                 if (maxper == 0 || i == NCPU - 1) {
13034                         limit = (uintptr_t)base + size;
13035                         start = NULL;
13036                 } else {
13037                         limit = (uintptr_t)start + maxper;
13038                         start = (dtrace_dynvar_t *)limit;
13039                 }
13040
13041                 ASSERT(limit <= (uintptr_t)base + size);
13042
13043                 for (;;) {
13044                         next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13045                             dstate->dtds_chunksize);
13046
13047                         if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13048                                 break;
13049
13050                         dvar->dtdv_next = next;
13051                         dvar = next;
13052                 }
13053
13054                 if (maxper == 0)
13055                         break;
13056         }
13057
13058         return (0);
13059 }
13060
13061 static void
13062 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13063 {
13064         ASSERT(MUTEX_HELD(&cpu_lock));
13065
13066         if (dstate->dtds_base == NULL)
13067                 return;
13068
13069         kmem_free(dstate->dtds_base, dstate->dtds_size);
13070         kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13071 }
13072
13073 static void
13074 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13075 {
13076         /*
13077          * Logical XOR, where are you?
13078          */
13079         ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13080
13081         if (vstate->dtvs_nglobals > 0) {
13082                 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13083                     sizeof (dtrace_statvar_t *));
13084         }
13085
13086         if (vstate->dtvs_ntlocals > 0) {
13087                 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13088                     sizeof (dtrace_difv_t));
13089         }
13090
13091         ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13092
13093         if (vstate->dtvs_nlocals > 0) {
13094                 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13095                     sizeof (dtrace_statvar_t *));
13096         }
13097 }
13098
13099 #if defined(sun)
13100 static void
13101 dtrace_state_clean(dtrace_state_t *state)
13102 {
13103         if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13104                 return;
13105
13106         dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13107         dtrace_speculation_clean(state);
13108 }
13109
13110 static void
13111 dtrace_state_deadman(dtrace_state_t *state)
13112 {
13113         hrtime_t now;
13114
13115         dtrace_sync();
13116
13117         now = dtrace_gethrtime();
13118
13119         if (state != dtrace_anon.dta_state &&
13120             now - state->dts_laststatus >= dtrace_deadman_user)
13121                 return;
13122
13123         /*
13124          * We must be sure that dts_alive never appears to be less than the
13125          * value upon entry to dtrace_state_deadman(), and because we lack a
13126          * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13127          * store INT64_MAX to it, followed by a memory barrier, followed by
13128          * the new value.  This assures that dts_alive never appears to be
13129          * less than its true value, regardless of the order in which the
13130          * stores to the underlying storage are issued.
13131          */
13132         state->dts_alive = INT64_MAX;
13133         dtrace_membar_producer();
13134         state->dts_alive = now;
13135 }
13136 #else
13137 static void
13138 dtrace_state_clean(void *arg)
13139 {
13140         dtrace_state_t *state = arg;
13141         dtrace_optval_t *opt = state->dts_options;
13142
13143         if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13144                 return;
13145
13146         dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13147         dtrace_speculation_clean(state);
13148
13149         callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13150             dtrace_state_clean, state);
13151 }
13152
13153 static void
13154 dtrace_state_deadman(void *arg)
13155 {
13156         dtrace_state_t *state = arg;
13157         hrtime_t now;
13158
13159         dtrace_sync();
13160
13161         dtrace_debug_output();
13162
13163         now = dtrace_gethrtime();
13164
13165         if (state != dtrace_anon.dta_state &&
13166             now - state->dts_laststatus >= dtrace_deadman_user)
13167                 return;
13168
13169         /*
13170          * We must be sure that dts_alive never appears to be less than the
13171          * value upon entry to dtrace_state_deadman(), and because we lack a
13172          * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13173          * store INT64_MAX to it, followed by a memory barrier, followed by
13174          * the new value.  This assures that dts_alive never appears to be
13175          * less than its true value, regardless of the order in which the
13176          * stores to the underlying storage are issued.
13177          */
13178         state->dts_alive = INT64_MAX;
13179         dtrace_membar_producer();
13180         state->dts_alive = now;
13181
13182         callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13183             dtrace_state_deadman, state);
13184 }
13185 #endif
13186
13187 static dtrace_state_t *
13188 #if defined(sun)
13189 dtrace_state_create(dev_t *devp, cred_t *cr)
13190 #else
13191 dtrace_state_create(struct cdev *dev)
13192 #endif
13193 {
13194 #if defined(sun)
13195         minor_t minor;
13196         major_t major;
13197 #else
13198         cred_t *cr = NULL;
13199         int m = 0;
13200 #endif
13201         char c[30];
13202         dtrace_state_t *state;
13203         dtrace_optval_t *opt;
13204         int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13205
13206         ASSERT(MUTEX_HELD(&dtrace_lock));
13207         ASSERT(MUTEX_HELD(&cpu_lock));
13208
13209 #if defined(sun)
13210         minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13211             VM_BESTFIT | VM_SLEEP);
13212
13213         if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13214                 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13215                 return (NULL);
13216         }
13217
13218         state = ddi_get_soft_state(dtrace_softstate, minor);
13219 #else
13220         if (dev != NULL) {
13221                 cr = dev->si_cred;
13222                 m = dev2unit(dev);
13223                 }
13224
13225         /* Allocate memory for the state. */
13226         state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
13227 #endif
13228
13229         state->dts_epid = DTRACE_EPIDNONE + 1;
13230
13231         (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
13232 #if defined(sun)
13233         state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13234             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13235
13236         if (devp != NULL) {
13237                 major = getemajor(*devp);
13238         } else {
13239                 major = ddi_driver_major(dtrace_devi);
13240         }
13241
13242         state->dts_dev = makedevice(major, minor);
13243
13244         if (devp != NULL)
13245                 *devp = state->dts_dev;
13246 #else
13247         state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
13248         state->dts_dev = dev;
13249 #endif
13250
13251         /*
13252          * We allocate NCPU buffers.  On the one hand, this can be quite
13253          * a bit of memory per instance (nearly 36K on a Starcat).  On the
13254          * other hand, it saves an additional memory reference in the probe
13255          * path.
13256          */
13257         state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13258         state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13259
13260 #if defined(sun)
13261         state->dts_cleaner = CYCLIC_NONE;
13262         state->dts_deadman = CYCLIC_NONE;
13263 #else
13264         callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
13265         callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
13266 #endif
13267         state->dts_vstate.dtvs_state = state;
13268
13269         for (i = 0; i < DTRACEOPT_MAX; i++)
13270                 state->dts_options[i] = DTRACEOPT_UNSET;
13271
13272         /*
13273          * Set the default options.
13274          */
13275         opt = state->dts_options;
13276         opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13277         opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13278         opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13279         opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13280         opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13281         opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13282         opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13283         opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13284         opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13285         opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13286         opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13287         opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13288         opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13289         opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13290
13291         state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13292
13293         /*
13294          * Depending on the user credentials, we set flag bits which alter probe
13295          * visibility or the amount of destructiveness allowed.  In the case of
13296          * actual anonymous tracing, or the possession of all privileges, all of
13297          * the normal checks are bypassed.
13298          */
13299         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13300                 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13301                 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13302         } else {
13303                 /*
13304                  * Set up the credentials for this instantiation.  We take a
13305                  * hold on the credential to prevent it from disappearing on
13306                  * us; this in turn prevents the zone_t referenced by this
13307                  * credential from disappearing.  This means that we can
13308                  * examine the credential and the zone from probe context.
13309                  */
13310                 crhold(cr);
13311                 state->dts_cred.dcr_cred = cr;
13312
13313                 /*
13314                  * CRA_PROC means "we have *some* privilege for dtrace" and
13315                  * unlocks the use of variables like pid, zonename, etc.
13316                  */
13317                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13318                     PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13319                         state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13320                 }
13321
13322                 /*
13323                  * dtrace_user allows use of syscall and profile providers.
13324                  * If the user also has proc_owner and/or proc_zone, we
13325                  * extend the scope to include additional visibility and
13326                  * destructive power.
13327                  */
13328                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13329                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13330                                 state->dts_cred.dcr_visible |=
13331                                     DTRACE_CRV_ALLPROC;
13332
13333                                 state->dts_cred.dcr_action |=
13334                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13335                         }
13336
13337                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13338                                 state->dts_cred.dcr_visible |=
13339                                     DTRACE_CRV_ALLZONE;
13340
13341                                 state->dts_cred.dcr_action |=
13342                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13343                         }
13344
13345                         /*
13346                          * If we have all privs in whatever zone this is,
13347                          * we can do destructive things to processes which
13348                          * have altered credentials.
13349                          */
13350 #if defined(sun)
13351                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13352                             cr->cr_zone->zone_privset)) {
13353                                 state->dts_cred.dcr_action |=
13354                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13355                         }
13356 #endif
13357                 }
13358
13359                 /*
13360                  * Holding the dtrace_kernel privilege also implies that
13361                  * the user has the dtrace_user privilege from a visibility
13362                  * perspective.  But without further privileges, some
13363                  * destructive actions are not available.
13364                  */
13365                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13366                         /*
13367                          * Make all probes in all zones visible.  However,
13368                          * this doesn't mean that all actions become available
13369                          * to all zones.
13370                          */
13371                         state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13372                             DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13373
13374                         state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13375                             DTRACE_CRA_PROC;
13376                         /*
13377                          * Holding proc_owner means that destructive actions
13378                          * for *this* zone are allowed.
13379                          */
13380                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13381                                 state->dts_cred.dcr_action |=
13382                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13383
13384                         /*
13385                          * Holding proc_zone means that destructive actions
13386                          * for this user/group ID in all zones is allowed.
13387                          */
13388                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13389                                 state->dts_cred.dcr_action |=
13390                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13391
13392 #if defined(sun)
13393                         /*
13394                          * If we have all privs in whatever zone this is,
13395                          * we can do destructive things to processes which
13396                          * have altered credentials.
13397                          */
13398                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13399                             cr->cr_zone->zone_privset)) {
13400                                 state->dts_cred.dcr_action |=
13401                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13402                         }
13403 #endif
13404                 }
13405
13406                 /*
13407                  * Holding the dtrace_proc privilege gives control over fasttrap
13408                  * and pid providers.  We need to grant wider destructive
13409                  * privileges in the event that the user has proc_owner and/or
13410                  * proc_zone.
13411                  */
13412                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13413                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13414                                 state->dts_cred.dcr_action |=
13415                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13416
13417                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13418                                 state->dts_cred.dcr_action |=
13419                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13420                 }
13421         }
13422
13423         return (state);
13424 }
13425
13426 static int
13427 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13428 {
13429         dtrace_optval_t *opt = state->dts_options, size;
13430         processorid_t cpu = 0;;
13431         int flags = 0, rval, factor, divisor = 1;
13432
13433         ASSERT(MUTEX_HELD(&dtrace_lock));
13434         ASSERT(MUTEX_HELD(&cpu_lock));
13435         ASSERT(which < DTRACEOPT_MAX);
13436         ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13437             (state == dtrace_anon.dta_state &&
13438             state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13439
13440         if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13441                 return (0);
13442
13443         if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13444                 cpu = opt[DTRACEOPT_CPU];
13445
13446         if (which == DTRACEOPT_SPECSIZE)
13447                 flags |= DTRACEBUF_NOSWITCH;
13448
13449         if (which == DTRACEOPT_BUFSIZE) {
13450                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13451                         flags |= DTRACEBUF_RING;
13452
13453                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13454                         flags |= DTRACEBUF_FILL;
13455
13456                 if (state != dtrace_anon.dta_state ||
13457                     state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13458                         flags |= DTRACEBUF_INACTIVE;
13459         }
13460
13461         for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13462                 /*
13463                  * The size must be 8-byte aligned.  If the size is not 8-byte
13464                  * aligned, drop it down by the difference.
13465                  */
13466                 if (size & (sizeof (uint64_t) - 1))
13467                         size -= size & (sizeof (uint64_t) - 1);
13468
13469                 if (size < state->dts_reserve) {
13470                         /*
13471                          * Buffers always must be large enough to accommodate
13472                          * their prereserved space.  We return E2BIG instead
13473                          * of ENOMEM in this case to allow for user-level
13474                          * software to differentiate the cases.
13475                          */
13476                         return (E2BIG);
13477                 }
13478
13479                 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13480
13481                 if (rval != ENOMEM) {
13482                         opt[which] = size;
13483                         return (rval);
13484                 }
13485
13486                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13487                         return (rval);
13488
13489                 for (divisor = 2; divisor < factor; divisor <<= 1)
13490                         continue;
13491         }
13492
13493         return (ENOMEM);
13494 }
13495
13496 static int
13497 dtrace_state_buffers(dtrace_state_t *state)
13498 {
13499         dtrace_speculation_t *spec = state->dts_speculations;
13500         int rval, i;
13501
13502         if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13503             DTRACEOPT_BUFSIZE)) != 0)
13504                 return (rval);
13505
13506         if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13507             DTRACEOPT_AGGSIZE)) != 0)
13508                 return (rval);
13509
13510         for (i = 0; i < state->dts_nspeculations; i++) {
13511                 if ((rval = dtrace_state_buffer(state,
13512                     spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13513                         return (rval);
13514         }
13515
13516         return (0);
13517 }
13518
13519 static void
13520 dtrace_state_prereserve(dtrace_state_t *state)
13521 {
13522         dtrace_ecb_t *ecb;
13523         dtrace_probe_t *probe;
13524
13525         state->dts_reserve = 0;
13526
13527         if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13528                 return;
13529
13530         /*
13531          * If our buffer policy is a "fill" buffer policy, we need to set the
13532          * prereserved space to be the space required by the END probes.
13533          */
13534         probe = dtrace_probes[dtrace_probeid_end - 1];
13535         ASSERT(probe != NULL);
13536
13537         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13538                 if (ecb->dte_state != state)
13539                         continue;
13540
13541                 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13542         }
13543 }
13544
13545 static int
13546 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13547 {
13548         dtrace_optval_t *opt = state->dts_options, sz, nspec;
13549         dtrace_speculation_t *spec;
13550         dtrace_buffer_t *buf;
13551 #if defined(sun)
13552         cyc_handler_t hdlr;
13553         cyc_time_t when;
13554 #endif
13555         int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13556         dtrace_icookie_t cookie;
13557
13558         mutex_enter(&cpu_lock);
13559         mutex_enter(&dtrace_lock);
13560
13561         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13562                 rval = EBUSY;
13563                 goto out;
13564         }
13565
13566         /*
13567          * Before we can perform any checks, we must prime all of the
13568          * retained enablings that correspond to this state.
13569          */
13570         dtrace_enabling_prime(state);
13571
13572         if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13573                 rval = EACCES;
13574                 goto out;
13575         }
13576
13577         dtrace_state_prereserve(state);
13578
13579         /*
13580          * Now we want to do is try to allocate our speculations.
13581          * We do not automatically resize the number of speculations; if
13582          * this fails, we will fail the operation.
13583          */
13584         nspec = opt[DTRACEOPT_NSPEC];
13585         ASSERT(nspec != DTRACEOPT_UNSET);
13586
13587         if (nspec > INT_MAX) {
13588                 rval = ENOMEM;
13589                 goto out;
13590         }
13591
13592         spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13593             KM_NOSLEEP | KM_NORMALPRI);
13594
13595         if (spec == NULL) {
13596                 rval = ENOMEM;
13597                 goto out;
13598         }
13599
13600         state->dts_speculations = spec;
13601         state->dts_nspeculations = (int)nspec;
13602
13603         for (i = 0; i < nspec; i++) {
13604                 if ((buf = kmem_zalloc(bufsize,
13605                     KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13606                         rval = ENOMEM;
13607                         goto err;
13608                 }
13609
13610                 spec[i].dtsp_buffer = buf;
13611         }
13612
13613         if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13614                 if (dtrace_anon.dta_state == NULL) {
13615                         rval = ENOENT;
13616                         goto out;
13617                 }
13618
13619                 if (state->dts_necbs != 0) {
13620                         rval = EALREADY;
13621                         goto out;
13622                 }
13623
13624                 state->dts_anon = dtrace_anon_grab();
13625                 ASSERT(state->dts_anon != NULL);
13626                 state = state->dts_anon;
13627
13628                 /*
13629                  * We want "grabanon" to be set in the grabbed state, so we'll
13630                  * copy that option value from the grabbing state into the
13631                  * grabbed state.
13632                  */
13633                 state->dts_options[DTRACEOPT_GRABANON] =
13634                     opt[DTRACEOPT_GRABANON];
13635
13636                 *cpu = dtrace_anon.dta_beganon;
13637
13638                 /*
13639                  * If the anonymous state is active (as it almost certainly
13640                  * is if the anonymous enabling ultimately matched anything),
13641                  * we don't allow any further option processing -- but we
13642                  * don't return failure.
13643                  */
13644                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13645                         goto out;
13646         }
13647
13648         if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13649             opt[DTRACEOPT_AGGSIZE] != 0) {
13650                 if (state->dts_aggregations == NULL) {
13651                         /*
13652                          * We're not going to create an aggregation buffer
13653                          * because we don't have any ECBs that contain
13654                          * aggregations -- set this option to 0.
13655                          */
13656                         opt[DTRACEOPT_AGGSIZE] = 0;
13657                 } else {
13658                         /*
13659                          * If we have an aggregation buffer, we must also have
13660                          * a buffer to use as scratch.
13661                          */
13662                         if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13663                             opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13664                                 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13665                         }
13666                 }
13667         }
13668
13669         if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13670             opt[DTRACEOPT_SPECSIZE] != 0) {
13671                 if (!state->dts_speculates) {
13672                         /*
13673                          * We're not going to create speculation buffers
13674                          * because we don't have any ECBs that actually
13675                          * speculate -- set the speculation size to 0.
13676                          */
13677                         opt[DTRACEOPT_SPECSIZE] = 0;
13678                 }
13679         }
13680
13681         /*
13682          * The bare minimum size for any buffer that we're actually going to
13683          * do anything to is sizeof (uint64_t).
13684          */
13685         sz = sizeof (uint64_t);
13686
13687         if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13688             (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13689             (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13690                 /*
13691                  * A buffer size has been explicitly set to 0 (or to a size
13692                  * that will be adjusted to 0) and we need the space -- we
13693                  * need to return failure.  We return ENOSPC to differentiate
13694                  * it from failing to allocate a buffer due to failure to meet
13695                  * the reserve (for which we return E2BIG).
13696                  */
13697                 rval = ENOSPC;
13698                 goto out;
13699         }
13700
13701         if ((rval = dtrace_state_buffers(state)) != 0)
13702                 goto err;
13703
13704         if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13705                 sz = dtrace_dstate_defsize;
13706
13707         do {
13708                 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13709
13710                 if (rval == 0)
13711                         break;
13712
13713                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13714                         goto err;
13715         } while (sz >>= 1);
13716
13717         opt[DTRACEOPT_DYNVARSIZE] = sz;
13718
13719         if (rval != 0)
13720                 goto err;
13721
13722         if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13723                 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13724
13725         if (opt[DTRACEOPT_CLEANRATE] == 0)
13726                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13727
13728         if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13729                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13730
13731         if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13732                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13733
13734         state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13735 #if defined(sun)
13736         hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13737         hdlr.cyh_arg = state;
13738         hdlr.cyh_level = CY_LOW_LEVEL;
13739
13740         when.cyt_when = 0;
13741         when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13742
13743         state->dts_cleaner = cyclic_add(&hdlr, &when);
13744
13745         hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13746         hdlr.cyh_arg = state;
13747         hdlr.cyh_level = CY_LOW_LEVEL;
13748
13749         when.cyt_when = 0;
13750         when.cyt_interval = dtrace_deadman_interval;
13751
13752         state->dts_deadman = cyclic_add(&hdlr, &when);
13753 #else
13754         callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13755             dtrace_state_clean, state);
13756         callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13757             dtrace_state_deadman, state);
13758 #endif
13759
13760         state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13761
13762         /*
13763          * Now it's time to actually fire the BEGIN probe.  We need to disable
13764          * interrupts here both to record the CPU on which we fired the BEGIN
13765          * probe (the data from this CPU will be processed first at user
13766          * level) and to manually activate the buffer for this CPU.
13767          */
13768         cookie = dtrace_interrupt_disable();
13769         *cpu = curcpu;
13770         ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13771         state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13772
13773         dtrace_probe(dtrace_probeid_begin,
13774             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13775         dtrace_interrupt_enable(cookie);
13776         /*
13777          * We may have had an exit action from a BEGIN probe; only change our
13778          * state to ACTIVE if we're still in WARMUP.
13779          */
13780         ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13781             state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13782
13783         if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13784                 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13785
13786         /*
13787          * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13788          * want each CPU to transition its principal buffer out of the
13789          * INACTIVE state.  Doing this assures that no CPU will suddenly begin
13790          * processing an ECB halfway down a probe's ECB chain; all CPUs will
13791          * atomically transition from processing none of a state's ECBs to
13792          * processing all of them.
13793          */
13794         dtrace_xcall(DTRACE_CPUALL,
13795             (dtrace_xcall_t)dtrace_buffer_activate, state);
13796         goto out;
13797
13798 err:
13799         dtrace_buffer_free(state->dts_buffer);
13800         dtrace_buffer_free(state->dts_aggbuffer);
13801
13802         if ((nspec = state->dts_nspeculations) == 0) {
13803                 ASSERT(state->dts_speculations == NULL);
13804                 goto out;
13805         }
13806
13807         spec = state->dts_speculations;
13808         ASSERT(spec != NULL);
13809
13810         for (i = 0; i < state->dts_nspeculations; i++) {
13811                 if ((buf = spec[i].dtsp_buffer) == NULL)
13812                         break;
13813
13814                 dtrace_buffer_free(buf);
13815                 kmem_free(buf, bufsize);
13816         }
13817
13818         kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13819         state->dts_nspeculations = 0;
13820         state->dts_speculations = NULL;
13821
13822 out:
13823         mutex_exit(&dtrace_lock);
13824         mutex_exit(&cpu_lock);
13825
13826         return (rval);
13827 }
13828
13829 static int
13830 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13831 {
13832         dtrace_icookie_t cookie;
13833
13834         ASSERT(MUTEX_HELD(&dtrace_lock));
13835
13836         if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13837             state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13838                 return (EINVAL);
13839
13840         /*
13841          * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13842          * to be sure that every CPU has seen it.  See below for the details
13843          * on why this is done.
13844          */
13845         state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13846         dtrace_sync();
13847
13848         /*
13849          * By this point, it is impossible for any CPU to be still processing
13850          * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
13851          * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13852          * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
13853          * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13854          * iff we're in the END probe.
13855          */
13856         state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13857         dtrace_sync();
13858         ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13859
13860         /*
13861          * Finally, we can release the reserve and call the END probe.  We
13862          * disable interrupts across calling the END probe to allow us to
13863          * return the CPU on which we actually called the END probe.  This
13864          * allows user-land to be sure that this CPU's principal buffer is
13865          * processed last.
13866          */
13867         state->dts_reserve = 0;
13868
13869         cookie = dtrace_interrupt_disable();
13870         *cpu = curcpu;
13871         dtrace_probe(dtrace_probeid_end,
13872             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13873         dtrace_interrupt_enable(cookie);
13874
13875         state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13876         dtrace_sync();
13877
13878         return (0);
13879 }
13880
13881 static int
13882 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13883     dtrace_optval_t val)
13884 {
13885         ASSERT(MUTEX_HELD(&dtrace_lock));
13886
13887         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13888                 return (EBUSY);
13889
13890         if (option >= DTRACEOPT_MAX)
13891                 return (EINVAL);
13892
13893         if (option != DTRACEOPT_CPU && val < 0)
13894                 return (EINVAL);
13895
13896         switch (option) {
13897         case DTRACEOPT_DESTRUCTIVE:
13898                 if (dtrace_destructive_disallow)
13899                         return (EACCES);
13900
13901                 state->dts_cred.dcr_destructive = 1;
13902                 break;
13903
13904         case DTRACEOPT_BUFSIZE:
13905         case DTRACEOPT_DYNVARSIZE:
13906         case DTRACEOPT_AGGSIZE:
13907         case DTRACEOPT_SPECSIZE:
13908         case DTRACEOPT_STRSIZE:
13909                 if (val < 0)
13910                         return (EINVAL);
13911
13912                 if (val >= LONG_MAX) {
13913                         /*
13914                          * If this is an otherwise negative value, set it to
13915                          * the highest multiple of 128m less than LONG_MAX.
13916                          * Technically, we're adjusting the size without
13917                          * regard to the buffer resizing policy, but in fact,
13918                          * this has no effect -- if we set the buffer size to
13919                          * ~LONG_MAX and the buffer policy is ultimately set to
13920                          * be "manual", the buffer allocation is guaranteed to
13921                          * fail, if only because the allocation requires two
13922                          * buffers.  (We set the the size to the highest
13923                          * multiple of 128m because it ensures that the size
13924                          * will remain a multiple of a megabyte when
13925                          * repeatedly halved -- all the way down to 15m.)
13926                          */
13927                         val = LONG_MAX - (1 << 27) + 1;
13928                 }
13929         }
13930
13931         state->dts_options[option] = val;
13932
13933         return (0);
13934 }
13935
13936 static void
13937 dtrace_state_destroy(dtrace_state_t *state)
13938 {
13939         dtrace_ecb_t *ecb;
13940         dtrace_vstate_t *vstate = &state->dts_vstate;
13941 #if defined(sun)
13942         minor_t minor = getminor(state->dts_dev);
13943 #endif
13944         int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13945         dtrace_speculation_t *spec = state->dts_speculations;
13946         int nspec = state->dts_nspeculations;
13947         uint32_t match;
13948
13949         ASSERT(MUTEX_HELD(&dtrace_lock));
13950         ASSERT(MUTEX_HELD(&cpu_lock));
13951
13952         /*
13953          * First, retract any retained enablings for this state.
13954          */
13955         dtrace_enabling_retract(state);
13956         ASSERT(state->dts_nretained == 0);
13957
13958         if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13959             state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13960                 /*
13961                  * We have managed to come into dtrace_state_destroy() on a
13962                  * hot enabling -- almost certainly because of a disorderly
13963                  * shutdown of a consumer.  (That is, a consumer that is
13964                  * exiting without having called dtrace_stop().) In this case,
13965                  * we're going to set our activity to be KILLED, and then
13966                  * issue a sync to be sure that everyone is out of probe
13967                  * context before we start blowing away ECBs.
13968                  */
13969                 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13970                 dtrace_sync();
13971         }
13972
13973         /*
13974          * Release the credential hold we took in dtrace_state_create().
13975          */
13976         if (state->dts_cred.dcr_cred != NULL)
13977                 crfree(state->dts_cred.dcr_cred);
13978
13979         /*
13980          * Now we can safely disable and destroy any enabled probes.  Because
13981          * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13982          * (especially if they're all enabled), we take two passes through the
13983          * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13984          * in the second we disable whatever is left over.
13985          */
13986         for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13987                 for (i = 0; i < state->dts_necbs; i++) {
13988                         if ((ecb = state->dts_ecbs[i]) == NULL)
13989                                 continue;
13990
13991                         if (match && ecb->dte_probe != NULL) {
13992                                 dtrace_probe_t *probe = ecb->dte_probe;
13993                                 dtrace_provider_t *prov = probe->dtpr_provider;
13994
13995                                 if (!(prov->dtpv_priv.dtpp_flags & match))
13996                                         continue;
13997                         }
13998
13999                         dtrace_ecb_disable(ecb);
14000                         dtrace_ecb_destroy(ecb);
14001                 }
14002
14003                 if (!match)
14004                         break;
14005         }
14006
14007         /*
14008          * Before we free the buffers, perform one more sync to assure that
14009          * every CPU is out of probe context.
14010          */
14011         dtrace_sync();
14012
14013         dtrace_buffer_free(state->dts_buffer);
14014         dtrace_buffer_free(state->dts_aggbuffer);
14015
14016         for (i = 0; i < nspec; i++)
14017                 dtrace_buffer_free(spec[i].dtsp_buffer);
14018
14019 #if defined(sun)
14020         if (state->dts_cleaner != CYCLIC_NONE)
14021                 cyclic_remove(state->dts_cleaner);
14022
14023         if (state->dts_deadman != CYCLIC_NONE)
14024                 cyclic_remove(state->dts_deadman);
14025 #else
14026         callout_stop(&state->dts_cleaner);
14027         callout_drain(&state->dts_cleaner);
14028         callout_stop(&state->dts_deadman);
14029         callout_drain(&state->dts_deadman);
14030 #endif
14031
14032         dtrace_dstate_fini(&vstate->dtvs_dynvars);
14033         dtrace_vstate_fini(vstate);
14034         if (state->dts_ecbs != NULL)
14035                 kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14036
14037         if (state->dts_aggregations != NULL) {
14038 #ifdef DEBUG
14039                 for (i = 0; i < state->dts_naggregations; i++)
14040                         ASSERT(state->dts_aggregations[i] == NULL);
14041 #endif
14042                 ASSERT(state->dts_naggregations > 0);
14043                 kmem_free(state->dts_aggregations,
14044                     state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14045         }
14046
14047         kmem_free(state->dts_buffer, bufsize);
14048         kmem_free(state->dts_aggbuffer, bufsize);
14049
14050         for (i = 0; i < nspec; i++)
14051                 kmem_free(spec[i].dtsp_buffer, bufsize);
14052
14053         if (spec != NULL)
14054                 kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14055
14056         dtrace_format_destroy(state);
14057
14058         if (state->dts_aggid_arena != NULL) {
14059 #if defined(sun)
14060                 vmem_destroy(state->dts_aggid_arena);
14061 #else
14062                 delete_unrhdr(state->dts_aggid_arena);
14063 #endif
14064                 state->dts_aggid_arena = NULL;
14065         }
14066 #if defined(sun)
14067         ddi_soft_state_free(dtrace_softstate, minor);
14068         vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14069 #endif
14070 }
14071
14072 /*
14073  * DTrace Anonymous Enabling Functions
14074  */
14075 static dtrace_state_t *
14076 dtrace_anon_grab(void)
14077 {
14078         dtrace_state_t *state;
14079
14080         ASSERT(MUTEX_HELD(&dtrace_lock));
14081
14082         if ((state = dtrace_anon.dta_state) == NULL) {
14083                 ASSERT(dtrace_anon.dta_enabling == NULL);
14084                 return (NULL);
14085         }
14086
14087         ASSERT(dtrace_anon.dta_enabling != NULL);
14088         ASSERT(dtrace_retained != NULL);
14089
14090         dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14091         dtrace_anon.dta_enabling = NULL;
14092         dtrace_anon.dta_state = NULL;
14093
14094         return (state);
14095 }
14096
14097 static void
14098 dtrace_anon_property(void)
14099 {
14100         int i, rv;
14101         dtrace_state_t *state;
14102         dof_hdr_t *dof;
14103         char c[32];             /* enough for "dof-data-" + digits */
14104
14105         ASSERT(MUTEX_HELD(&dtrace_lock));
14106         ASSERT(MUTEX_HELD(&cpu_lock));
14107
14108         for (i = 0; ; i++) {
14109                 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14110
14111                 dtrace_err_verbose = 1;
14112
14113                 if ((dof = dtrace_dof_property(c)) == NULL) {
14114                         dtrace_err_verbose = 0;
14115                         break;
14116                 }
14117
14118 #if defined(sun)
14119                 /*
14120                  * We want to create anonymous state, so we need to transition
14121                  * the kernel debugger to indicate that DTrace is active.  If
14122                  * this fails (e.g. because the debugger has modified text in
14123                  * some way), we won't continue with the processing.
14124                  */
14125                 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14126                         cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14127                             "enabling ignored.");
14128                         dtrace_dof_destroy(dof);
14129                         break;
14130                 }
14131 #endif
14132
14133                 /*
14134                  * If we haven't allocated an anonymous state, we'll do so now.
14135                  */
14136                 if ((state = dtrace_anon.dta_state) == NULL) {
14137 #if defined(sun)
14138                         state = dtrace_state_create(NULL, NULL);
14139 #else
14140                         state = dtrace_state_create(NULL);
14141 #endif
14142                         dtrace_anon.dta_state = state;
14143
14144                         if (state == NULL) {
14145                                 /*
14146                                  * This basically shouldn't happen:  the only
14147                                  * failure mode from dtrace_state_create() is a
14148                                  * failure of ddi_soft_state_zalloc() that
14149                                  * itself should never happen.  Still, the
14150                                  * interface allows for a failure mode, and
14151                                  * we want to fail as gracefully as possible:
14152                                  * we'll emit an error message and cease
14153                                  * processing anonymous state in this case.
14154                                  */
14155                                 cmn_err(CE_WARN, "failed to create "
14156                                     "anonymous state");
14157                                 dtrace_dof_destroy(dof);
14158                                 break;
14159                         }
14160                 }
14161
14162                 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14163                     &dtrace_anon.dta_enabling, 0, B_TRUE);
14164
14165                 if (rv == 0)
14166                         rv = dtrace_dof_options(dof, state);
14167
14168                 dtrace_err_verbose = 0;
14169                 dtrace_dof_destroy(dof);
14170
14171                 if (rv != 0) {
14172                         /*
14173                          * This is malformed DOF; chuck any anonymous state
14174                          * that we created.
14175                          */
14176                         ASSERT(dtrace_anon.dta_enabling == NULL);
14177                         dtrace_state_destroy(state);
14178                         dtrace_anon.dta_state = NULL;
14179                         break;
14180                 }
14181
14182                 ASSERT(dtrace_anon.dta_enabling != NULL);
14183         }
14184
14185         if (dtrace_anon.dta_enabling != NULL) {
14186                 int rval;
14187
14188                 /*
14189                  * dtrace_enabling_retain() can only fail because we are
14190                  * trying to retain more enablings than are allowed -- but
14191                  * we only have one anonymous enabling, and we are guaranteed
14192                  * to be allowed at least one retained enabling; we assert
14193                  * that dtrace_enabling_retain() returns success.
14194                  */
14195                 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14196                 ASSERT(rval == 0);
14197
14198                 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14199         }
14200 }
14201
14202 /*
14203  * DTrace Helper Functions
14204  */
14205 static void
14206 dtrace_helper_trace(dtrace_helper_action_t *helper,
14207     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14208 {
14209         uint32_t size, next, nnext, i;
14210         dtrace_helptrace_t *ent;
14211         uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
14212
14213         if (!dtrace_helptrace_enabled)
14214                 return;
14215
14216         ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14217
14218         /*
14219          * What would a tracing framework be without its own tracing
14220          * framework?  (Well, a hell of a lot simpler, for starters...)
14221          */
14222         size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14223             sizeof (uint64_t) - sizeof (uint64_t);
14224
14225         /*
14226          * Iterate until we can allocate a slot in the trace buffer.
14227          */
14228         do {
14229                 next = dtrace_helptrace_next;
14230
14231                 if (next + size < dtrace_helptrace_bufsize) {
14232                         nnext = next + size;
14233                 } else {
14234                         nnext = size;
14235                 }
14236         } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14237
14238         /*
14239          * We have our slot; fill it in.
14240          */
14241         if (nnext == size)
14242                 next = 0;
14243
14244         ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14245         ent->dtht_helper = helper;
14246         ent->dtht_where = where;
14247         ent->dtht_nlocals = vstate->dtvs_nlocals;
14248
14249         ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14250             mstate->dtms_fltoffs : -1;
14251         ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14252         ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
14253
14254         for (i = 0; i < vstate->dtvs_nlocals; i++) {
14255                 dtrace_statvar_t *svar;
14256
14257                 if ((svar = vstate->dtvs_locals[i]) == NULL)
14258                         continue;
14259
14260                 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14261                 ent->dtht_locals[i] =
14262                     ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
14263         }
14264 }
14265
14266 static uint64_t
14267 dtrace_helper(int which, dtrace_mstate_t *mstate,
14268     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14269 {
14270         uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
14271         uint64_t sarg0 = mstate->dtms_arg[0];
14272         uint64_t sarg1 = mstate->dtms_arg[1];
14273         uint64_t rval = 0;
14274         dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14275         dtrace_helper_action_t *helper;
14276         dtrace_vstate_t *vstate;
14277         dtrace_difo_t *pred;
14278         int i, trace = dtrace_helptrace_enabled;
14279
14280         ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14281
14282         if (helpers == NULL)
14283                 return (0);
14284
14285         if ((helper = helpers->dthps_actions[which]) == NULL)
14286                 return (0);
14287
14288         vstate = &helpers->dthps_vstate;
14289         mstate->dtms_arg[0] = arg0;
14290         mstate->dtms_arg[1] = arg1;
14291
14292         /*
14293          * Now iterate over each helper.  If its predicate evaluates to 'true',
14294          * we'll call the corresponding actions.  Note that the below calls
14295          * to dtrace_dif_emulate() may set faults in machine state.  This is
14296          * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14297          * the stored DIF offset with its own (which is the desired behavior).
14298          * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14299          * from machine state; this is okay, too.
14300          */
14301         for (; helper != NULL; helper = helper->dtha_next) {
14302                 if ((pred = helper->dtha_predicate) != NULL) {
14303                         if (trace)
14304                                 dtrace_helper_trace(helper, mstate, vstate, 0);
14305
14306                         if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14307                                 goto next;
14308
14309                         if (*flags & CPU_DTRACE_FAULT)
14310                                 goto err;
14311                 }
14312
14313                 for (i = 0; i < helper->dtha_nactions; i++) {
14314                         if (trace)
14315                                 dtrace_helper_trace(helper,
14316                                     mstate, vstate, i + 1);
14317
14318                         rval = dtrace_dif_emulate(helper->dtha_actions[i],
14319                             mstate, vstate, state);
14320
14321                         if (*flags & CPU_DTRACE_FAULT)
14322                                 goto err;
14323                 }
14324
14325 next:
14326                 if (trace)
14327                         dtrace_helper_trace(helper, mstate, vstate,
14328                             DTRACE_HELPTRACE_NEXT);
14329         }
14330
14331         if (trace)
14332                 dtrace_helper_trace(helper, mstate, vstate,
14333                     DTRACE_HELPTRACE_DONE);
14334
14335         /*
14336          * Restore the arg0 that we saved upon entry.
14337          */
14338         mstate->dtms_arg[0] = sarg0;
14339         mstate->dtms_arg[1] = sarg1;
14340
14341         return (rval);
14342
14343 err:
14344         if (trace)
14345                 dtrace_helper_trace(helper, mstate, vstate,
14346                     DTRACE_HELPTRACE_ERR);
14347
14348         /*
14349          * Restore the arg0 that we saved upon entry.
14350          */
14351         mstate->dtms_arg[0] = sarg0;
14352         mstate->dtms_arg[1] = sarg1;
14353
14354         return (0);
14355 }
14356
14357 static void
14358 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14359     dtrace_vstate_t *vstate)
14360 {
14361         int i;
14362
14363         if (helper->dtha_predicate != NULL)
14364                 dtrace_difo_release(helper->dtha_predicate, vstate);
14365
14366         for (i = 0; i < helper->dtha_nactions; i++) {
14367                 ASSERT(helper->dtha_actions[i] != NULL);
14368                 dtrace_difo_release(helper->dtha_actions[i], vstate);
14369         }
14370
14371         kmem_free(helper->dtha_actions,
14372             helper->dtha_nactions * sizeof (dtrace_difo_t *));
14373         kmem_free(helper, sizeof (dtrace_helper_action_t));
14374 }
14375
14376 static int
14377 dtrace_helper_destroygen(int gen)
14378 {
14379         proc_t *p = curproc;
14380         dtrace_helpers_t *help = p->p_dtrace_helpers;
14381         dtrace_vstate_t *vstate;
14382         int i;
14383
14384         ASSERT(MUTEX_HELD(&dtrace_lock));
14385
14386         if (help == NULL || gen > help->dthps_generation)
14387                 return (EINVAL);
14388
14389         vstate = &help->dthps_vstate;
14390
14391         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14392                 dtrace_helper_action_t *last = NULL, *h, *next;
14393
14394                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14395                         next = h->dtha_next;
14396
14397                         if (h->dtha_generation == gen) {
14398                                 if (last != NULL) {
14399                                         last->dtha_next = next;
14400                                 } else {
14401                                         help->dthps_actions[i] = next;
14402                                 }
14403
14404                                 dtrace_helper_action_destroy(h, vstate);
14405                         } else {
14406                                 last = h;
14407                         }
14408                 }
14409         }
14410
14411         /*
14412          * Interate until we've cleared out all helper providers with the
14413          * given generation number.
14414          */
14415         for (;;) {
14416                 dtrace_helper_provider_t *prov;
14417
14418                 /*
14419                  * Look for a helper provider with the right generation. We
14420                  * have to start back at the beginning of the list each time
14421                  * because we drop dtrace_lock. It's unlikely that we'll make
14422                  * more than two passes.
14423                  */
14424                 for (i = 0; i < help->dthps_nprovs; i++) {
14425                         prov = help->dthps_provs[i];
14426
14427                         if (prov->dthp_generation == gen)
14428                                 break;
14429                 }
14430
14431                 /*
14432                  * If there were no matches, we're done.
14433                  */
14434                 if (i == help->dthps_nprovs)
14435                         break;
14436
14437                 /*
14438                  * Move the last helper provider into this slot.
14439                  */
14440                 help->dthps_nprovs--;
14441                 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14442                 help->dthps_provs[help->dthps_nprovs] = NULL;
14443
14444                 mutex_exit(&dtrace_lock);
14445
14446                 /*
14447                  * If we have a meta provider, remove this helper provider.
14448                  */
14449                 mutex_enter(&dtrace_meta_lock);
14450                 if (dtrace_meta_pid != NULL) {
14451                         ASSERT(dtrace_deferred_pid == NULL);
14452                         dtrace_helper_provider_remove(&prov->dthp_prov,
14453                             p->p_pid);
14454                 }
14455                 mutex_exit(&dtrace_meta_lock);
14456
14457                 dtrace_helper_provider_destroy(prov);
14458
14459                 mutex_enter(&dtrace_lock);
14460         }
14461
14462         return (0);
14463 }
14464
14465 static int
14466 dtrace_helper_validate(dtrace_helper_action_t *helper)
14467 {
14468         int err = 0, i;
14469         dtrace_difo_t *dp;
14470
14471         if ((dp = helper->dtha_predicate) != NULL)
14472                 err += dtrace_difo_validate_helper(dp);
14473
14474         for (i = 0; i < helper->dtha_nactions; i++)
14475                 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14476
14477         return (err == 0);
14478 }
14479
14480 static int
14481 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14482 {
14483         dtrace_helpers_t *help;
14484         dtrace_helper_action_t *helper, *last;
14485         dtrace_actdesc_t *act;
14486         dtrace_vstate_t *vstate;
14487         dtrace_predicate_t *pred;
14488         int count = 0, nactions = 0, i;
14489
14490         if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14491                 return (EINVAL);
14492
14493         help = curproc->p_dtrace_helpers;
14494         last = help->dthps_actions[which];
14495         vstate = &help->dthps_vstate;
14496
14497         for (count = 0; last != NULL; last = last->dtha_next) {
14498                 count++;
14499                 if (last->dtha_next == NULL)
14500                         break;
14501         }
14502
14503         /*
14504          * If we already have dtrace_helper_actions_max helper actions for this
14505          * helper action type, we'll refuse to add a new one.
14506          */
14507         if (count >= dtrace_helper_actions_max)
14508                 return (ENOSPC);
14509
14510         helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14511         helper->dtha_generation = help->dthps_generation;
14512
14513         if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14514                 ASSERT(pred->dtp_difo != NULL);
14515                 dtrace_difo_hold(pred->dtp_difo);
14516                 helper->dtha_predicate = pred->dtp_difo;
14517         }
14518
14519         for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14520                 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14521                         goto err;
14522
14523                 if (act->dtad_difo == NULL)
14524                         goto err;
14525
14526                 nactions++;
14527         }
14528
14529         helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14530             (helper->dtha_nactions = nactions), KM_SLEEP);
14531
14532         for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14533                 dtrace_difo_hold(act->dtad_difo);
14534                 helper->dtha_actions[i++] = act->dtad_difo;
14535         }
14536
14537         if (!dtrace_helper_validate(helper))
14538                 goto err;
14539
14540         if (last == NULL) {
14541                 help->dthps_actions[which] = helper;
14542         } else {
14543                 last->dtha_next = helper;
14544         }
14545
14546         if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14547                 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14548                 dtrace_helptrace_next = 0;
14549         }
14550
14551         return (0);
14552 err:
14553         dtrace_helper_action_destroy(helper, vstate);
14554         return (EINVAL);
14555 }
14556
14557 static void
14558 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14559     dof_helper_t *dofhp)
14560 {
14561         ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14562
14563         mutex_enter(&dtrace_meta_lock);
14564         mutex_enter(&dtrace_lock);
14565
14566         if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14567                 /*
14568                  * If the dtrace module is loaded but not attached, or if
14569                  * there aren't isn't a meta provider registered to deal with
14570                  * these provider descriptions, we need to postpone creating
14571                  * the actual providers until later.
14572                  */
14573
14574                 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14575                     dtrace_deferred_pid != help) {
14576                         help->dthps_deferred = 1;
14577                         help->dthps_pid = p->p_pid;
14578                         help->dthps_next = dtrace_deferred_pid;
14579                         help->dthps_prev = NULL;
14580                         if (dtrace_deferred_pid != NULL)
14581                                 dtrace_deferred_pid->dthps_prev = help;
14582                         dtrace_deferred_pid = help;
14583                 }
14584
14585                 mutex_exit(&dtrace_lock);
14586
14587         } else if (dofhp != NULL) {
14588                 /*
14589                  * If the dtrace module is loaded and we have a particular
14590                  * helper provider description, pass that off to the
14591                  * meta provider.
14592                  */
14593
14594                 mutex_exit(&dtrace_lock);
14595
14596                 dtrace_helper_provide(dofhp, p->p_pid);
14597
14598         } else {
14599                 /*
14600                  * Otherwise, just pass all the helper provider descriptions
14601                  * off to the meta provider.
14602                  */
14603
14604                 int i;
14605                 mutex_exit(&dtrace_lock);
14606
14607                 for (i = 0; i < help->dthps_nprovs; i++) {
14608                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14609                             p->p_pid);
14610                 }
14611         }
14612
14613         mutex_exit(&dtrace_meta_lock);
14614 }
14615
14616 static int
14617 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14618 {
14619         dtrace_helpers_t *help;
14620         dtrace_helper_provider_t *hprov, **tmp_provs;
14621         uint_t tmp_maxprovs, i;
14622
14623         ASSERT(MUTEX_HELD(&dtrace_lock));
14624
14625         help = curproc->p_dtrace_helpers;
14626         ASSERT(help != NULL);
14627
14628         /*
14629          * If we already have dtrace_helper_providers_max helper providers,
14630          * we're refuse to add a new one.
14631          */
14632         if (help->dthps_nprovs >= dtrace_helper_providers_max)
14633                 return (ENOSPC);
14634
14635         /*
14636          * Check to make sure this isn't a duplicate.
14637          */
14638         for (i = 0; i < help->dthps_nprovs; i++) {
14639                 if (dofhp->dofhp_dof ==
14640                     help->dthps_provs[i]->dthp_prov.dofhp_dof)
14641                         return (EALREADY);
14642         }
14643
14644         hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14645         hprov->dthp_prov = *dofhp;
14646         hprov->dthp_ref = 1;
14647         hprov->dthp_generation = gen;
14648
14649         /*
14650          * Allocate a bigger table for helper providers if it's already full.
14651          */
14652         if (help->dthps_maxprovs == help->dthps_nprovs) {
14653                 tmp_maxprovs = help->dthps_maxprovs;
14654                 tmp_provs = help->dthps_provs;
14655
14656                 if (help->dthps_maxprovs == 0)
14657                         help->dthps_maxprovs = 2;
14658                 else
14659                         help->dthps_maxprovs *= 2;
14660                 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14661                         help->dthps_maxprovs = dtrace_helper_providers_max;
14662
14663                 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14664
14665                 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14666                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14667
14668                 if (tmp_provs != NULL) {
14669                         bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14670                             sizeof (dtrace_helper_provider_t *));
14671                         kmem_free(tmp_provs, tmp_maxprovs *
14672                             sizeof (dtrace_helper_provider_t *));
14673                 }
14674         }
14675
14676         help->dthps_provs[help->dthps_nprovs] = hprov;
14677         help->dthps_nprovs++;
14678
14679         return (0);
14680 }
14681
14682 static void
14683 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14684 {
14685         mutex_enter(&dtrace_lock);
14686
14687         if (--hprov->dthp_ref == 0) {
14688                 dof_hdr_t *dof;
14689                 mutex_exit(&dtrace_lock);
14690                 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14691                 dtrace_dof_destroy(dof);
14692                 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14693         } else {
14694                 mutex_exit(&dtrace_lock);
14695         }
14696 }
14697
14698 static int
14699 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14700 {
14701         uintptr_t daddr = (uintptr_t)dof;
14702         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14703         dof_provider_t *provider;
14704         dof_probe_t *probe;
14705         uint8_t *arg;
14706         char *strtab, *typestr;
14707         dof_stridx_t typeidx;
14708         size_t typesz;
14709         uint_t nprobes, j, k;
14710
14711         ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14712
14713         if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14714                 dtrace_dof_error(dof, "misaligned section offset");
14715                 return (-1);
14716         }
14717
14718         /*
14719          * The section needs to be large enough to contain the DOF provider
14720          * structure appropriate for the given version.
14721          */
14722         if (sec->dofs_size <
14723             ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14724             offsetof(dof_provider_t, dofpv_prenoffs) :
14725             sizeof (dof_provider_t))) {
14726                 dtrace_dof_error(dof, "provider section too small");
14727                 return (-1);
14728         }
14729
14730         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14731         str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14732         prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14733         arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14734         off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14735
14736         if (str_sec == NULL || prb_sec == NULL ||
14737             arg_sec == NULL || off_sec == NULL)
14738                 return (-1);
14739
14740         enoff_sec = NULL;
14741
14742         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14743             provider->dofpv_prenoffs != DOF_SECT_NONE &&
14744             (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14745             provider->dofpv_prenoffs)) == NULL)
14746                 return (-1);
14747
14748         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14749
14750         if (provider->dofpv_name >= str_sec->dofs_size ||
14751             strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14752                 dtrace_dof_error(dof, "invalid provider name");
14753                 return (-1);
14754         }
14755
14756         if (prb_sec->dofs_entsize == 0 ||
14757             prb_sec->dofs_entsize > prb_sec->dofs_size) {
14758                 dtrace_dof_error(dof, "invalid entry size");
14759                 return (-1);
14760         }
14761
14762         if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14763                 dtrace_dof_error(dof, "misaligned entry size");
14764                 return (-1);
14765         }
14766
14767         if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14768                 dtrace_dof_error(dof, "invalid entry size");
14769                 return (-1);
14770         }
14771
14772         if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14773                 dtrace_dof_error(dof, "misaligned section offset");
14774                 return (-1);
14775         }
14776
14777         if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14778                 dtrace_dof_error(dof, "invalid entry size");
14779                 return (-1);
14780         }
14781
14782         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14783
14784         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14785
14786         /*
14787          * Take a pass through the probes to check for errors.
14788          */
14789         for (j = 0; j < nprobes; j++) {
14790                 probe = (dof_probe_t *)(uintptr_t)(daddr +
14791                     prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14792
14793                 if (probe->dofpr_func >= str_sec->dofs_size) {
14794                         dtrace_dof_error(dof, "invalid function name");
14795                         return (-1);
14796                 }
14797
14798                 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14799                         dtrace_dof_error(dof, "function name too long");
14800                         return (-1);
14801                 }
14802
14803                 if (probe->dofpr_name >= str_sec->dofs_size ||
14804                     strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14805                         dtrace_dof_error(dof, "invalid probe name");
14806                         return (-1);
14807                 }
14808
14809                 /*
14810                  * The offset count must not wrap the index, and the offsets
14811                  * must also not overflow the section's data.
14812                  */
14813                 if (probe->dofpr_offidx + probe->dofpr_noffs <
14814                     probe->dofpr_offidx ||
14815                     (probe->dofpr_offidx + probe->dofpr_noffs) *
14816                     off_sec->dofs_entsize > off_sec->dofs_size) {
14817                         dtrace_dof_error(dof, "invalid probe offset");
14818                         return (-1);
14819                 }
14820
14821                 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14822                         /*
14823                          * If there's no is-enabled offset section, make sure
14824                          * there aren't any is-enabled offsets. Otherwise
14825                          * perform the same checks as for probe offsets
14826                          * (immediately above).
14827                          */
14828                         if (enoff_sec == NULL) {
14829                                 if (probe->dofpr_enoffidx != 0 ||
14830                                     probe->dofpr_nenoffs != 0) {
14831                                         dtrace_dof_error(dof, "is-enabled "
14832                                             "offsets with null section");
14833                                         return (-1);
14834                                 }
14835                         } else if (probe->dofpr_enoffidx +
14836                             probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14837                             (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14838                             enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14839                                 dtrace_dof_error(dof, "invalid is-enabled "
14840                                     "offset");
14841                                 return (-1);
14842                         }
14843
14844                         if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14845                                 dtrace_dof_error(dof, "zero probe and "
14846                                     "is-enabled offsets");
14847                                 return (-1);
14848                         }
14849                 } else if (probe->dofpr_noffs == 0) {
14850                         dtrace_dof_error(dof, "zero probe offsets");
14851                         return (-1);
14852                 }
14853
14854                 if (probe->dofpr_argidx + probe->dofpr_xargc <
14855                     probe->dofpr_argidx ||
14856                     (probe->dofpr_argidx + probe->dofpr_xargc) *
14857                     arg_sec->dofs_entsize > arg_sec->dofs_size) {
14858                         dtrace_dof_error(dof, "invalid args");
14859                         return (-1);
14860                 }
14861
14862                 typeidx = probe->dofpr_nargv;
14863                 typestr = strtab + probe->dofpr_nargv;
14864                 for (k = 0; k < probe->dofpr_nargc; k++) {
14865                         if (typeidx >= str_sec->dofs_size) {
14866                                 dtrace_dof_error(dof, "bad "
14867                                     "native argument type");
14868                                 return (-1);
14869                         }
14870
14871                         typesz = strlen(typestr) + 1;
14872                         if (typesz > DTRACE_ARGTYPELEN) {
14873                                 dtrace_dof_error(dof, "native "
14874                                     "argument type too long");
14875                                 return (-1);
14876                         }
14877                         typeidx += typesz;
14878                         typestr += typesz;
14879                 }
14880
14881                 typeidx = probe->dofpr_xargv;
14882                 typestr = strtab + probe->dofpr_xargv;
14883                 for (k = 0; k < probe->dofpr_xargc; k++) {
14884                         if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14885                                 dtrace_dof_error(dof, "bad "
14886                                     "native argument index");
14887                                 return (-1);
14888                         }
14889
14890                         if (typeidx >= str_sec->dofs_size) {
14891                                 dtrace_dof_error(dof, "bad "
14892                                     "translated argument type");
14893                                 return (-1);
14894                         }
14895
14896                         typesz = strlen(typestr) + 1;
14897                         if (typesz > DTRACE_ARGTYPELEN) {
14898                                 dtrace_dof_error(dof, "translated argument "
14899                                     "type too long");
14900                                 return (-1);
14901                         }
14902
14903                         typeidx += typesz;
14904                         typestr += typesz;
14905                 }
14906         }
14907
14908         return (0);
14909 }
14910
14911 static int
14912 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14913 {
14914         dtrace_helpers_t *help;
14915         dtrace_vstate_t *vstate;
14916         dtrace_enabling_t *enab = NULL;
14917         int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14918         uintptr_t daddr = (uintptr_t)dof;
14919
14920         ASSERT(MUTEX_HELD(&dtrace_lock));
14921
14922         if ((help = curproc->p_dtrace_helpers) == NULL)
14923                 help = dtrace_helpers_create(curproc);
14924
14925         vstate = &help->dthps_vstate;
14926
14927         if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14928             dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14929                 dtrace_dof_destroy(dof);
14930                 return (rv);
14931         }
14932
14933         /*
14934          * Look for helper providers and validate their descriptions.
14935          */
14936         if (dhp != NULL) {
14937                 for (i = 0; i < dof->dofh_secnum; i++) {
14938                         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14939                             dof->dofh_secoff + i * dof->dofh_secsize);
14940
14941                         if (sec->dofs_type != DOF_SECT_PROVIDER)
14942                                 continue;
14943
14944                         if (dtrace_helper_provider_validate(dof, sec) != 0) {
14945                                 dtrace_enabling_destroy(enab);
14946                                 dtrace_dof_destroy(dof);
14947                                 return (-1);
14948                         }
14949
14950                         nprovs++;
14951                 }
14952         }
14953
14954         /*
14955          * Now we need to walk through the ECB descriptions in the enabling.
14956          */
14957         for (i = 0; i < enab->dten_ndesc; i++) {
14958                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14959                 dtrace_probedesc_t *desc = &ep->dted_probe;
14960
14961                 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14962                         continue;
14963
14964                 if (strcmp(desc->dtpd_mod, "helper") != 0)
14965                         continue;
14966
14967                 if (strcmp(desc->dtpd_func, "ustack") != 0)
14968                         continue;
14969
14970                 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14971                     ep)) != 0) {
14972                         /*
14973                          * Adding this helper action failed -- we are now going
14974                          * to rip out the entire generation and return failure.
14975                          */
14976                         (void) dtrace_helper_destroygen(help->dthps_generation);
14977                         dtrace_enabling_destroy(enab);
14978                         dtrace_dof_destroy(dof);
14979                         return (-1);
14980                 }
14981
14982                 nhelpers++;
14983         }
14984
14985         if (nhelpers < enab->dten_ndesc)
14986                 dtrace_dof_error(dof, "unmatched helpers");
14987
14988         gen = help->dthps_generation++;
14989         dtrace_enabling_destroy(enab);
14990
14991         if (dhp != NULL && nprovs > 0) {
14992                 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14993                 if (dtrace_helper_provider_add(dhp, gen) == 0) {
14994                         mutex_exit(&dtrace_lock);
14995                         dtrace_helper_provider_register(curproc, help, dhp);
14996                         mutex_enter(&dtrace_lock);
14997
14998                         destroy = 0;
14999                 }
15000         }
15001
15002         if (destroy)
15003                 dtrace_dof_destroy(dof);
15004
15005         return (gen);
15006 }
15007
15008 static dtrace_helpers_t *
15009 dtrace_helpers_create(proc_t *p)
15010 {
15011         dtrace_helpers_t *help;
15012
15013         ASSERT(MUTEX_HELD(&dtrace_lock));
15014         ASSERT(p->p_dtrace_helpers == NULL);
15015
15016         help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15017         help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15018             DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15019
15020         p->p_dtrace_helpers = help;
15021         dtrace_helpers++;
15022
15023         return (help);
15024 }
15025
15026 #if defined(sun)
15027 static
15028 #endif
15029 void
15030 dtrace_helpers_destroy(proc_t *p)
15031 {
15032         dtrace_helpers_t *help;
15033         dtrace_vstate_t *vstate;
15034 #if defined(sun)
15035         proc_t *p = curproc;
15036 #endif
15037         int i;
15038
15039         mutex_enter(&dtrace_lock);
15040
15041         ASSERT(p->p_dtrace_helpers != NULL);
15042         ASSERT(dtrace_helpers > 0);
15043
15044         help = p->p_dtrace_helpers;
15045         vstate = &help->dthps_vstate;
15046
15047         /*
15048          * We're now going to lose the help from this process.
15049          */
15050         p->p_dtrace_helpers = NULL;
15051         dtrace_sync();
15052
15053         /*
15054          * Destory the helper actions.
15055          */
15056         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15057                 dtrace_helper_action_t *h, *next;
15058
15059                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15060                         next = h->dtha_next;
15061                         dtrace_helper_action_destroy(h, vstate);
15062                         h = next;
15063                 }
15064         }
15065
15066         mutex_exit(&dtrace_lock);
15067
15068         /*
15069          * Destroy the helper providers.
15070          */
15071         if (help->dthps_maxprovs > 0) {
15072                 mutex_enter(&dtrace_meta_lock);
15073                 if (dtrace_meta_pid != NULL) {
15074                         ASSERT(dtrace_deferred_pid == NULL);
15075
15076                         for (i = 0; i < help->dthps_nprovs; i++) {
15077                                 dtrace_helper_provider_remove(
15078                                     &help->dthps_provs[i]->dthp_prov, p->p_pid);
15079                         }
15080                 } else {
15081                         mutex_enter(&dtrace_lock);
15082                         ASSERT(help->dthps_deferred == 0 ||
15083                             help->dthps_next != NULL ||
15084                             help->dthps_prev != NULL ||
15085                             help == dtrace_deferred_pid);
15086
15087                         /*
15088                          * Remove the helper from the deferred list.
15089                          */
15090                         if (help->dthps_next != NULL)
15091                                 help->dthps_next->dthps_prev = help->dthps_prev;
15092                         if (help->dthps_prev != NULL)
15093                                 help->dthps_prev->dthps_next = help->dthps_next;
15094                         if (dtrace_deferred_pid == help) {
15095                                 dtrace_deferred_pid = help->dthps_next;
15096                                 ASSERT(help->dthps_prev == NULL);
15097                         }
15098
15099                         mutex_exit(&dtrace_lock);
15100                 }
15101
15102                 mutex_exit(&dtrace_meta_lock);
15103
15104                 for (i = 0; i < help->dthps_nprovs; i++) {
15105                         dtrace_helper_provider_destroy(help->dthps_provs[i]);
15106                 }
15107
15108                 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15109                     sizeof (dtrace_helper_provider_t *));
15110         }
15111
15112         mutex_enter(&dtrace_lock);
15113
15114         dtrace_vstate_fini(&help->dthps_vstate);
15115         kmem_free(help->dthps_actions,
15116             sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15117         kmem_free(help, sizeof (dtrace_helpers_t));
15118
15119         --dtrace_helpers;
15120         mutex_exit(&dtrace_lock);
15121 }
15122
15123 #if defined(sun)
15124 static
15125 #endif
15126 void
15127 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15128 {
15129         dtrace_helpers_t *help, *newhelp;
15130         dtrace_helper_action_t *helper, *new, *last;
15131         dtrace_difo_t *dp;
15132         dtrace_vstate_t *vstate;
15133         int i, j, sz, hasprovs = 0;
15134
15135         mutex_enter(&dtrace_lock);
15136         ASSERT(from->p_dtrace_helpers != NULL);
15137         ASSERT(dtrace_helpers > 0);
15138
15139         help = from->p_dtrace_helpers;
15140         newhelp = dtrace_helpers_create(to);
15141         ASSERT(to->p_dtrace_helpers != NULL);
15142
15143         newhelp->dthps_generation = help->dthps_generation;
15144         vstate = &newhelp->dthps_vstate;
15145
15146         /*
15147          * Duplicate the helper actions.
15148          */
15149         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15150                 if ((helper = help->dthps_actions[i]) == NULL)
15151                         continue;
15152
15153                 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15154                         new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15155                             KM_SLEEP);
15156                         new->dtha_generation = helper->dtha_generation;
15157
15158                         if ((dp = helper->dtha_predicate) != NULL) {
15159                                 dp = dtrace_difo_duplicate(dp, vstate);
15160                                 new->dtha_predicate = dp;
15161                         }
15162
15163                         new->dtha_nactions = helper->dtha_nactions;
15164                         sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15165                         new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15166
15167                         for (j = 0; j < new->dtha_nactions; j++) {
15168                                 dtrace_difo_t *dp = helper->dtha_actions[j];
15169
15170                                 ASSERT(dp != NULL);
15171                                 dp = dtrace_difo_duplicate(dp, vstate);
15172                                 new->dtha_actions[j] = dp;
15173                         }
15174
15175                         if (last != NULL) {
15176                                 last->dtha_next = new;
15177                         } else {
15178                                 newhelp->dthps_actions[i] = new;
15179                         }
15180
15181                         last = new;
15182                 }
15183         }
15184
15185         /*
15186          * Duplicate the helper providers and register them with the
15187          * DTrace framework.
15188          */
15189         if (help->dthps_nprovs > 0) {
15190                 newhelp->dthps_nprovs = help->dthps_nprovs;
15191                 newhelp->dthps_maxprovs = help->dthps_nprovs;
15192                 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15193                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15194                 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15195                         newhelp->dthps_provs[i] = help->dthps_provs[i];
15196                         newhelp->dthps_provs[i]->dthp_ref++;
15197                 }
15198
15199                 hasprovs = 1;
15200         }
15201
15202         mutex_exit(&dtrace_lock);
15203
15204         if (hasprovs)
15205                 dtrace_helper_provider_register(to, newhelp, NULL);
15206 }
15207
15208 /*
15209  * DTrace Hook Functions
15210  */
15211 static void
15212 dtrace_module_loaded(modctl_t *ctl)
15213 {
15214         dtrace_provider_t *prv;
15215
15216         mutex_enter(&dtrace_provider_lock);
15217 #if defined(sun)
15218         mutex_enter(&mod_lock);
15219 #endif
15220
15221 #if defined(sun)
15222         ASSERT(ctl->mod_busy);
15223 #endif
15224
15225         /*
15226          * We're going to call each providers per-module provide operation
15227          * specifying only this module.
15228          */
15229         for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15230                 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15231
15232 #if defined(sun)
15233         mutex_exit(&mod_lock);
15234 #endif
15235         mutex_exit(&dtrace_provider_lock);
15236
15237         /*
15238          * If we have any retained enablings, we need to match against them.
15239          * Enabling probes requires that cpu_lock be held, and we cannot hold
15240          * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15241          * module.  (In particular, this happens when loading scheduling
15242          * classes.)  So if we have any retained enablings, we need to dispatch
15243          * our task queue to do the match for us.
15244          */
15245         mutex_enter(&dtrace_lock);
15246
15247         if (dtrace_retained == NULL) {
15248                 mutex_exit(&dtrace_lock);
15249                 return;
15250         }
15251
15252         (void) taskq_dispatch(dtrace_taskq,
15253             (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15254
15255         mutex_exit(&dtrace_lock);
15256
15257         /*
15258          * And now, for a little heuristic sleaze:  in general, we want to
15259          * match modules as soon as they load.  However, we cannot guarantee
15260          * this, because it would lead us to the lock ordering violation
15261          * outlined above.  The common case, of course, is that cpu_lock is
15262          * _not_ held -- so we delay here for a clock tick, hoping that that's
15263          * long enough for the task queue to do its work.  If it's not, it's
15264          * not a serious problem -- it just means that the module that we
15265          * just loaded may not be immediately instrumentable.
15266          */
15267         delay(1);
15268 }
15269
15270 static void
15271 #if defined(sun)
15272 dtrace_module_unloaded(modctl_t *ctl)
15273 #else
15274 dtrace_module_unloaded(modctl_t *ctl, int *error)
15275 #endif
15276 {
15277         dtrace_probe_t template, *probe, *first, *next;
15278         dtrace_provider_t *prov;
15279 #if !defined(sun)
15280         char modname[DTRACE_MODNAMELEN];
15281         size_t len;
15282 #endif
15283
15284 #if defined(sun)
15285         template.dtpr_mod = ctl->mod_modname;
15286 #else
15287         /* Handle the fact that ctl->filename may end in ".ko". */
15288         strlcpy(modname, ctl->filename, sizeof(modname));
15289         len = strlen(ctl->filename);
15290         if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
15291                 modname[len - 3] = '\0';
15292         template.dtpr_mod = modname;
15293 #endif
15294
15295         mutex_enter(&dtrace_provider_lock);
15296 #if defined(sun)
15297         mutex_enter(&mod_lock);
15298 #endif
15299         mutex_enter(&dtrace_lock);
15300
15301 #if !defined(sun)
15302         if (ctl->nenabled > 0) {
15303                 /* Don't allow unloads if a probe is enabled. */
15304                 mutex_exit(&dtrace_provider_lock);
15305                 mutex_exit(&dtrace_lock);
15306                 *error = -1;
15307                 printf(
15308         "kldunload: attempt to unload module that has DTrace probes enabled\n");
15309                 return;
15310         }
15311 #endif
15312
15313         if (dtrace_bymod == NULL) {
15314                 /*
15315                  * The DTrace module is loaded (obviously) but not attached;
15316                  * we don't have any work to do.
15317                  */
15318                 mutex_exit(&dtrace_provider_lock);
15319 #if defined(sun)
15320                 mutex_exit(&mod_lock);
15321 #endif
15322                 mutex_exit(&dtrace_lock);
15323                 return;
15324         }
15325
15326         for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15327             probe != NULL; probe = probe->dtpr_nextmod) {
15328                 if (probe->dtpr_ecb != NULL) {
15329                         mutex_exit(&dtrace_provider_lock);
15330 #if defined(sun)
15331                         mutex_exit(&mod_lock);
15332 #endif
15333                         mutex_exit(&dtrace_lock);
15334
15335                         /*
15336                          * This shouldn't _actually_ be possible -- we're
15337                          * unloading a module that has an enabled probe in it.
15338                          * (It's normally up to the provider to make sure that
15339                          * this can't happen.)  However, because dtps_enable()
15340                          * doesn't have a failure mode, there can be an
15341                          * enable/unload race.  Upshot:  we don't want to
15342                          * assert, but we're not going to disable the
15343                          * probe, either.
15344                          */
15345                         if (dtrace_err_verbose) {
15346 #if defined(sun)
15347                                 cmn_err(CE_WARN, "unloaded module '%s' had "
15348                                     "enabled probes", ctl->mod_modname);
15349 #else
15350                                 cmn_err(CE_WARN, "unloaded module '%s' had "
15351                                     "enabled probes", modname);
15352 #endif
15353                         }
15354
15355                         return;
15356                 }
15357         }
15358
15359         probe = first;
15360
15361         for (first = NULL; probe != NULL; probe = next) {
15362                 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15363
15364                 dtrace_probes[probe->dtpr_id - 1] = NULL;
15365
15366                 next = probe->dtpr_nextmod;
15367                 dtrace_hash_remove(dtrace_bymod, probe);
15368                 dtrace_hash_remove(dtrace_byfunc, probe);
15369                 dtrace_hash_remove(dtrace_byname, probe);
15370
15371                 if (first == NULL) {
15372                         first = probe;
15373                         probe->dtpr_nextmod = NULL;
15374                 } else {
15375                         probe->dtpr_nextmod = first;
15376                         first = probe;
15377                 }
15378         }
15379
15380         /*
15381          * We've removed all of the module's probes from the hash chains and
15382          * from the probe array.  Now issue a dtrace_sync() to be sure that
15383          * everyone has cleared out from any probe array processing.
15384          */
15385         dtrace_sync();
15386
15387         for (probe = first; probe != NULL; probe = first) {
15388                 first = probe->dtpr_nextmod;
15389                 prov = probe->dtpr_provider;
15390                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15391                     probe->dtpr_arg);
15392                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15393                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15394                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15395 #if defined(sun)
15396                 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15397 #else
15398                 free_unr(dtrace_arena, probe->dtpr_id);
15399 #endif
15400                 kmem_free(probe, sizeof (dtrace_probe_t));
15401         }
15402
15403         mutex_exit(&dtrace_lock);
15404 #if defined(sun)
15405         mutex_exit(&mod_lock);
15406 #endif
15407         mutex_exit(&dtrace_provider_lock);
15408 }
15409
15410 #if !defined(sun)
15411 static void
15412 dtrace_kld_load(void *arg __unused, linker_file_t lf)
15413 {
15414
15415         dtrace_module_loaded(lf);
15416 }
15417
15418 static void
15419 dtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
15420 {
15421
15422         if (*error != 0)
15423                 /* We already have an error, so don't do anything. */
15424                 return;
15425         dtrace_module_unloaded(lf, error);
15426 }
15427 #endif
15428
15429 #if defined(sun)
15430 static void
15431 dtrace_suspend(void)
15432 {
15433         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15434 }
15435
15436 static void
15437 dtrace_resume(void)
15438 {
15439         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15440 }
15441 #endif
15442
15443 static int
15444 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15445 {
15446         ASSERT(MUTEX_HELD(&cpu_lock));
15447         mutex_enter(&dtrace_lock);
15448
15449         switch (what) {
15450         case CPU_CONFIG: {
15451                 dtrace_state_t *state;
15452                 dtrace_optval_t *opt, rs, c;
15453
15454                 /*
15455                  * For now, we only allocate a new buffer for anonymous state.
15456                  */
15457                 if ((state = dtrace_anon.dta_state) == NULL)
15458                         break;
15459
15460                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15461                         break;
15462
15463                 opt = state->dts_options;
15464                 c = opt[DTRACEOPT_CPU];
15465
15466                 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15467                         break;
15468
15469                 /*
15470                  * Regardless of what the actual policy is, we're going to
15471                  * temporarily set our resize policy to be manual.  We're
15472                  * also going to temporarily set our CPU option to denote
15473                  * the newly configured CPU.
15474                  */
15475                 rs = opt[DTRACEOPT_BUFRESIZE];
15476                 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15477                 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15478
15479                 (void) dtrace_state_buffers(state);
15480
15481                 opt[DTRACEOPT_BUFRESIZE] = rs;
15482                 opt[DTRACEOPT_CPU] = c;
15483
15484                 break;
15485         }
15486
15487         case CPU_UNCONFIG:
15488                 /*
15489                  * We don't free the buffer in the CPU_UNCONFIG case.  (The
15490                  * buffer will be freed when the consumer exits.)
15491                  */
15492                 break;
15493
15494         default:
15495                 break;
15496         }
15497
15498         mutex_exit(&dtrace_lock);
15499         return (0);
15500 }
15501
15502 #if defined(sun)
15503 static void
15504 dtrace_cpu_setup_initial(processorid_t cpu)
15505 {
15506         (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15507 }
15508 #endif
15509
15510 static void
15511 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15512 {
15513         if (dtrace_toxranges >= dtrace_toxranges_max) {
15514                 int osize, nsize;
15515                 dtrace_toxrange_t *range;
15516
15517                 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15518
15519                 if (osize == 0) {
15520                         ASSERT(dtrace_toxrange == NULL);
15521                         ASSERT(dtrace_toxranges_max == 0);
15522                         dtrace_toxranges_max = 1;
15523                 } else {
15524                         dtrace_toxranges_max <<= 1;
15525                 }
15526
15527                 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15528                 range = kmem_zalloc(nsize, KM_SLEEP);
15529
15530                 if (dtrace_toxrange != NULL) {
15531                         ASSERT(osize != 0);
15532                         bcopy(dtrace_toxrange, range, osize);
15533                         kmem_free(dtrace_toxrange, osize);
15534                 }
15535
15536                 dtrace_toxrange = range;
15537         }
15538
15539         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15540         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15541
15542         dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15543         dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15544         dtrace_toxranges++;
15545 }
15546
15547 /*
15548  * DTrace Driver Cookbook Functions
15549  */
15550 #if defined(sun)
15551 /*ARGSUSED*/
15552 static int
15553 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15554 {
15555         dtrace_provider_id_t id;
15556         dtrace_state_t *state = NULL;
15557         dtrace_enabling_t *enab;
15558
15559         mutex_enter(&cpu_lock);
15560         mutex_enter(&dtrace_provider_lock);
15561         mutex_enter(&dtrace_lock);
15562
15563         if (ddi_soft_state_init(&dtrace_softstate,
15564             sizeof (dtrace_state_t), 0) != 0) {
15565                 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15566                 mutex_exit(&cpu_lock);
15567                 mutex_exit(&dtrace_provider_lock);
15568                 mutex_exit(&dtrace_lock);
15569                 return (DDI_FAILURE);
15570         }
15571
15572         if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15573             DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15574             ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15575             DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15576                 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15577                 ddi_remove_minor_node(devi, NULL);
15578                 ddi_soft_state_fini(&dtrace_softstate);
15579                 mutex_exit(&cpu_lock);
15580                 mutex_exit(&dtrace_provider_lock);
15581                 mutex_exit(&dtrace_lock);
15582                 return (DDI_FAILURE);
15583         }
15584
15585         ddi_report_dev(devi);
15586         dtrace_devi = devi;
15587
15588         dtrace_modload = dtrace_module_loaded;
15589         dtrace_modunload = dtrace_module_unloaded;
15590         dtrace_cpu_init = dtrace_cpu_setup_initial;
15591         dtrace_helpers_cleanup = dtrace_helpers_destroy;
15592         dtrace_helpers_fork = dtrace_helpers_duplicate;
15593         dtrace_cpustart_init = dtrace_suspend;
15594         dtrace_cpustart_fini = dtrace_resume;
15595         dtrace_debugger_init = dtrace_suspend;
15596         dtrace_debugger_fini = dtrace_resume;
15597
15598         register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15599
15600         ASSERT(MUTEX_HELD(&cpu_lock));
15601
15602         dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15603             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15604         dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15605             UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15606             VM_SLEEP | VMC_IDENTIFIER);
15607         dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15608             1, INT_MAX, 0);
15609
15610         dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15611             sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15612             NULL, NULL, NULL, NULL, NULL, 0);
15613
15614         ASSERT(MUTEX_HELD(&cpu_lock));
15615         dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15616             offsetof(dtrace_probe_t, dtpr_nextmod),
15617             offsetof(dtrace_probe_t, dtpr_prevmod));
15618
15619         dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15620             offsetof(dtrace_probe_t, dtpr_nextfunc),
15621             offsetof(dtrace_probe_t, dtpr_prevfunc));
15622
15623         dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15624             offsetof(dtrace_probe_t, dtpr_nextname),
15625             offsetof(dtrace_probe_t, dtpr_prevname));
15626
15627         if (dtrace_retain_max < 1) {
15628                 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15629                     "setting to 1", dtrace_retain_max);
15630                 dtrace_retain_max = 1;
15631         }
15632
15633         /*
15634          * Now discover our toxic ranges.
15635          */
15636         dtrace_toxic_ranges(dtrace_toxrange_add);
15637
15638         /*
15639          * Before we register ourselves as a provider to our own framework,
15640          * we would like to assert that dtrace_provider is NULL -- but that's
15641          * not true if we were loaded as a dependency of a DTrace provider.
15642          * Once we've registered, we can assert that dtrace_provider is our
15643          * pseudo provider.
15644          */
15645         (void) dtrace_register("dtrace", &dtrace_provider_attr,
15646             DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15647
15648         ASSERT(dtrace_provider != NULL);
15649         ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15650
15651         dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15652             dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15653         dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15654             dtrace_provider, NULL, NULL, "END", 0, NULL);
15655         dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15656             dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15657
15658         dtrace_anon_property();
15659         mutex_exit(&cpu_lock);
15660
15661         /*
15662          * If DTrace helper tracing is enabled, we need to allocate the
15663          * trace buffer and initialize the values.
15664          */
15665         if (dtrace_helptrace_enabled) {
15666                 ASSERT(dtrace_helptrace_buffer == NULL);
15667                 dtrace_helptrace_buffer =
15668                     kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15669                 dtrace_helptrace_next = 0;
15670         }
15671
15672         /*
15673          * If there are already providers, we must ask them to provide their
15674          * probes, and then match any anonymous enabling against them.  Note
15675          * that there should be no other retained enablings at this time:
15676          * the only retained enablings at this time should be the anonymous
15677          * enabling.
15678          */
15679         if (dtrace_anon.dta_enabling != NULL) {
15680                 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15681
15682                 dtrace_enabling_provide(NULL);
15683                 state = dtrace_anon.dta_state;
15684
15685                 /*
15686                  * We couldn't hold cpu_lock across the above call to
15687                  * dtrace_enabling_provide(), but we must hold it to actually
15688                  * enable the probes.  We have to drop all of our locks, pick
15689                  * up cpu_lock, and regain our locks before matching the
15690                  * retained anonymous enabling.
15691                  */
15692                 mutex_exit(&dtrace_lock);
15693                 mutex_exit(&dtrace_provider_lock);
15694
15695                 mutex_enter(&cpu_lock);
15696                 mutex_enter(&dtrace_provider_lock);
15697                 mutex_enter(&dtrace_lock);
15698
15699                 if ((enab = dtrace_anon.dta_enabling) != NULL)
15700                         (void) dtrace_enabling_match(enab, NULL);
15701
15702                 mutex_exit(&cpu_lock);
15703         }
15704
15705         mutex_exit(&dtrace_lock);
15706         mutex_exit(&dtrace_provider_lock);
15707
15708         if (state != NULL) {
15709                 /*
15710                  * If we created any anonymous state, set it going now.
15711                  */
15712                 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15713         }
15714
15715         return (DDI_SUCCESS);
15716 }
15717 #endif
15718
15719 #if !defined(sun)
15720 #if __FreeBSD_version >= 800039
15721 static void
15722 dtrace_dtr(void *data __unused)
15723 {
15724 }
15725 #endif
15726 #endif
15727
15728 /*ARGSUSED*/
15729 static int
15730 #if defined(sun)
15731 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15732 #else
15733 dtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
15734 #endif
15735 {
15736         dtrace_state_t *state;
15737         uint32_t priv;
15738         uid_t uid;
15739         zoneid_t zoneid;
15740
15741 #if defined(sun)
15742         if (getminor(*devp) == DTRACEMNRN_HELPER)
15743                 return (0);
15744
15745         /*
15746          * If this wasn't an open with the "helper" minor, then it must be
15747          * the "dtrace" minor.
15748          */
15749         if (getminor(*devp) == DTRACEMNRN_DTRACE)
15750                 return (ENXIO);
15751 #else
15752         cred_t *cred_p = NULL;
15753
15754 #if __FreeBSD_version < 800039
15755         /*
15756          * The first minor device is the one that is cloned so there is
15757          * nothing more to do here.
15758          */
15759         if (dev2unit(dev) == 0)
15760                 return 0;
15761
15762         /*
15763          * Devices are cloned, so if the DTrace state has already
15764          * been allocated, that means this device belongs to a
15765          * different client. Each client should open '/dev/dtrace'
15766          * to get a cloned device.
15767          */
15768         if (dev->si_drv1 != NULL)
15769                 return (EBUSY);
15770 #endif
15771
15772         cred_p = dev->si_cred;
15773 #endif
15774
15775         /*
15776          * If no DTRACE_PRIV_* bits are set in the credential, then the
15777          * caller lacks sufficient permission to do anything with DTrace.
15778          */
15779         dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15780         if (priv == DTRACE_PRIV_NONE) {
15781 #if !defined(sun)
15782 #if __FreeBSD_version < 800039
15783                 /* Destroy the cloned device. */
15784                 destroy_dev(dev);
15785 #endif
15786 #endif
15787
15788                 return (EACCES);
15789         }
15790
15791         /*
15792          * Ask all providers to provide all their probes.
15793          */
15794         mutex_enter(&dtrace_provider_lock);
15795         dtrace_probe_provide(NULL, NULL);
15796         mutex_exit(&dtrace_provider_lock);
15797
15798         mutex_enter(&cpu_lock);
15799         mutex_enter(&dtrace_lock);
15800         dtrace_opens++;
15801         dtrace_membar_producer();
15802
15803 #if defined(sun)
15804         /*
15805          * If the kernel debugger is active (that is, if the kernel debugger
15806          * modified text in some way), we won't allow the open.
15807          */
15808         if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15809                 dtrace_opens--;
15810                 mutex_exit(&cpu_lock);
15811                 mutex_exit(&dtrace_lock);
15812                 return (EBUSY);
15813         }
15814
15815         state = dtrace_state_create(devp, cred_p);
15816 #else
15817         state = dtrace_state_create(dev);
15818 #if __FreeBSD_version < 800039
15819         dev->si_drv1 = state;
15820 #else
15821         devfs_set_cdevpriv(state, dtrace_dtr);
15822 #endif
15823 #endif
15824
15825         mutex_exit(&cpu_lock);
15826
15827         if (state == NULL) {
15828 #if defined(sun)
15829                 if (--dtrace_opens == 0)
15830                         (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15831 #else
15832                 --dtrace_opens;
15833 #endif
15834                 mutex_exit(&dtrace_lock);
15835 #if !defined(sun)
15836 #if __FreeBSD_version < 800039
15837                 /* Destroy the cloned device. */
15838                 destroy_dev(dev);
15839 #endif
15840 #endif
15841                 return (EAGAIN);
15842         }
15843
15844         mutex_exit(&dtrace_lock);
15845
15846         return (0);
15847 }
15848
15849 /*ARGSUSED*/
15850 static int
15851 #if defined(sun)
15852 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15853 #else
15854 dtrace_close(struct cdev *dev, int flags, int fmt __unused, struct thread *td)
15855 #endif
15856 {
15857 #if defined(sun)
15858         minor_t minor = getminor(dev);
15859         dtrace_state_t *state;
15860
15861         if (minor == DTRACEMNRN_HELPER)
15862                 return (0);
15863
15864         state = ddi_get_soft_state(dtrace_softstate, minor);
15865 #else
15866 #if __FreeBSD_version < 800039
15867         dtrace_state_t *state = dev->si_drv1;
15868
15869         /* Check if this is not a cloned device. */
15870         if (dev2unit(dev) == 0)
15871                 return (0);
15872 #else
15873         dtrace_state_t *state;
15874         devfs_get_cdevpriv((void **) &state);
15875 #endif
15876
15877 #endif
15878
15879         mutex_enter(&cpu_lock);
15880         mutex_enter(&dtrace_lock);
15881
15882         if (state != NULL) {
15883                 if (state->dts_anon) {
15884                         /*
15885                          * There is anonymous state. Destroy that first.
15886                          */
15887                         ASSERT(dtrace_anon.dta_state == NULL);
15888                         dtrace_state_destroy(state->dts_anon);
15889                 }
15890
15891                 dtrace_state_destroy(state);
15892
15893 #if !defined(sun)
15894                 kmem_free(state, 0);
15895 #if __FreeBSD_version < 800039
15896                 dev->si_drv1 = NULL;
15897 #endif
15898 #endif
15899         }
15900
15901         ASSERT(dtrace_opens > 0);
15902 #if defined(sun)
15903         if (--dtrace_opens == 0)
15904                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15905 #else
15906         --dtrace_opens;
15907 #endif
15908
15909         mutex_exit(&dtrace_lock);
15910         mutex_exit(&cpu_lock);
15911
15912 #if __FreeBSD_version < 800039
15913         /* Schedule this cloned device to be destroyed. */
15914         destroy_dev_sched(dev);
15915 #endif
15916
15917         return (0);
15918 }
15919
15920 #if defined(sun)
15921 /*ARGSUSED*/
15922 static int
15923 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15924 {
15925         int rval;
15926         dof_helper_t help, *dhp = NULL;
15927
15928         switch (cmd) {
15929         case DTRACEHIOC_ADDDOF:
15930                 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15931                         dtrace_dof_error(NULL, "failed to copyin DOF helper");
15932                         return (EFAULT);
15933                 }
15934
15935                 dhp = &help;
15936                 arg = (intptr_t)help.dofhp_dof;
15937                 /*FALLTHROUGH*/
15938
15939         case DTRACEHIOC_ADD: {
15940                 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15941
15942                 if (dof == NULL)
15943                         return (rval);
15944
15945                 mutex_enter(&dtrace_lock);
15946
15947                 /*
15948                  * dtrace_helper_slurp() takes responsibility for the dof --
15949                  * it may free it now or it may save it and free it later.
15950                  */
15951                 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15952                         *rv = rval;
15953                         rval = 0;
15954                 } else {
15955                         rval = EINVAL;
15956                 }
15957
15958                 mutex_exit(&dtrace_lock);
15959                 return (rval);
15960         }
15961
15962         case DTRACEHIOC_REMOVE: {
15963                 mutex_enter(&dtrace_lock);
15964                 rval = dtrace_helper_destroygen(arg);
15965                 mutex_exit(&dtrace_lock);
15966
15967                 return (rval);
15968         }
15969
15970         default:
15971                 break;
15972         }
15973
15974         return (ENOTTY);
15975 }
15976
15977 /*ARGSUSED*/
15978 static int
15979 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15980 {
15981         minor_t minor = getminor(dev);
15982         dtrace_state_t *state;
15983         int rval;
15984
15985         if (minor == DTRACEMNRN_HELPER)
15986                 return (dtrace_ioctl_helper(cmd, arg, rv));
15987
15988         state = ddi_get_soft_state(dtrace_softstate, minor);
15989
15990         if (state->dts_anon) {
15991                 ASSERT(dtrace_anon.dta_state == NULL);
15992                 state = state->dts_anon;
15993         }
15994
15995         switch (cmd) {
15996         case DTRACEIOC_PROVIDER: {
15997                 dtrace_providerdesc_t pvd;
15998                 dtrace_provider_t *pvp;
15999
16000                 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16001                         return (EFAULT);
16002
16003                 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16004                 mutex_enter(&dtrace_provider_lock);
16005
16006                 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16007                         if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16008                                 break;
16009                 }
16010
16011                 mutex_exit(&dtrace_provider_lock);
16012
16013                 if (pvp == NULL)
16014                         return (ESRCH);
16015
16016                 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16017                 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16018
16019                 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16020                         return (EFAULT);
16021
16022                 return (0);
16023         }
16024
16025         case DTRACEIOC_EPROBE: {
16026                 dtrace_eprobedesc_t epdesc;
16027                 dtrace_ecb_t *ecb;
16028                 dtrace_action_t *act;
16029                 void *buf;
16030                 size_t size;
16031                 uintptr_t dest;
16032                 int nrecs;
16033
16034                 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16035                         return (EFAULT);
16036
16037                 mutex_enter(&dtrace_lock);
16038
16039                 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16040                         mutex_exit(&dtrace_lock);
16041                         return (EINVAL);
16042                 }
16043
16044                 if (ecb->dte_probe == NULL) {
16045                         mutex_exit(&dtrace_lock);
16046                         return (EINVAL);
16047                 }
16048
16049                 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16050                 epdesc.dtepd_uarg = ecb->dte_uarg;
16051                 epdesc.dtepd_size = ecb->dte_size;
16052
16053                 nrecs = epdesc.dtepd_nrecs;
16054                 epdesc.dtepd_nrecs = 0;
16055                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16056                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16057                                 continue;
16058
16059                         epdesc.dtepd_nrecs++;
16060                 }
16061
16062                 /*
16063                  * Now that we have the size, we need to allocate a temporary
16064                  * buffer in which to store the complete description.  We need
16065                  * the temporary buffer to be able to drop dtrace_lock()
16066                  * across the copyout(), below.
16067                  */
16068                 size = sizeof (dtrace_eprobedesc_t) +
16069                     (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16070
16071                 buf = kmem_alloc(size, KM_SLEEP);
16072                 dest = (uintptr_t)buf;
16073
16074                 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16075                 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16076
16077                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16078                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16079                                 continue;
16080
16081                         if (nrecs-- == 0)
16082                                 break;
16083
16084                         bcopy(&act->dta_rec, (void *)dest,
16085                             sizeof (dtrace_recdesc_t));
16086                         dest += sizeof (dtrace_recdesc_t);
16087                 }
16088
16089                 mutex_exit(&dtrace_lock);
16090
16091                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16092                         kmem_free(buf, size);
16093                         return (EFAULT);
16094                 }
16095
16096                 kmem_free(buf, size);
16097                 return (0);
16098         }
16099
16100         case DTRACEIOC_AGGDESC: {
16101                 dtrace_aggdesc_t aggdesc;
16102                 dtrace_action_t *act;
16103                 dtrace_aggregation_t *agg;
16104                 int nrecs;
16105                 uint32_t offs;
16106                 dtrace_recdesc_t *lrec;
16107                 void *buf;
16108                 size_t size;
16109                 uintptr_t dest;
16110
16111                 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16112                         return (EFAULT);
16113
16114                 mutex_enter(&dtrace_lock);
16115
16116                 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16117                         mutex_exit(&dtrace_lock);
16118                         return (EINVAL);
16119                 }
16120
16121                 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16122
16123                 nrecs = aggdesc.dtagd_nrecs;
16124                 aggdesc.dtagd_nrecs = 0;
16125
16126                 offs = agg->dtag_base;
16127                 lrec = &agg->dtag_action.dta_rec;
16128                 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16129
16130                 for (act = agg->dtag_first; ; act = act->dta_next) {
16131                         ASSERT(act->dta_intuple ||
16132                             DTRACEACT_ISAGG(act->dta_kind));
16133
16134                         /*
16135                          * If this action has a record size of zero, it
16136                          * denotes an argument to the aggregating action.
16137                          * Because the presence of this record doesn't (or
16138                          * shouldn't) affect the way the data is interpreted,
16139                          * we don't copy it out to save user-level the
16140                          * confusion of dealing with a zero-length record.
16141                          */
16142                         if (act->dta_rec.dtrd_size == 0) {
16143                                 ASSERT(agg->dtag_hasarg);
16144                                 continue;
16145                         }
16146
16147                         aggdesc.dtagd_nrecs++;
16148
16149                         if (act == &agg->dtag_action)
16150                                 break;
16151                 }
16152
16153                 /*
16154                  * Now that we have the size, we need to allocate a temporary
16155                  * buffer in which to store the complete description.  We need
16156                  * the temporary buffer to be able to drop dtrace_lock()
16157                  * across the copyout(), below.
16158                  */
16159                 size = sizeof (dtrace_aggdesc_t) +
16160                     (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16161
16162                 buf = kmem_alloc(size, KM_SLEEP);
16163                 dest = (uintptr_t)buf;
16164
16165                 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16166                 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16167
16168                 for (act = agg->dtag_first; ; act = act->dta_next) {
16169                         dtrace_recdesc_t rec = act->dta_rec;
16170
16171                         /*
16172                          * See the comment in the above loop for why we pass
16173                          * over zero-length records.
16174                          */
16175                         if (rec.dtrd_size == 0) {
16176                                 ASSERT(agg->dtag_hasarg);
16177                                 continue;
16178                         }
16179
16180                         if (nrecs-- == 0)
16181                                 break;
16182
16183                         rec.dtrd_offset -= offs;
16184                         bcopy(&rec, (void *)dest, sizeof (rec));
16185                         dest += sizeof (dtrace_recdesc_t);
16186
16187                         if (act == &agg->dtag_action)
16188                                 break;
16189                 }
16190
16191                 mutex_exit(&dtrace_lock);
16192
16193                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16194                         kmem_free(buf, size);
16195                         return (EFAULT);
16196                 }
16197
16198                 kmem_free(buf, size);
16199                 return (0);
16200         }
16201
16202         case DTRACEIOC_ENABLE: {
16203                 dof_hdr_t *dof;
16204                 dtrace_enabling_t *enab = NULL;
16205                 dtrace_vstate_t *vstate;
16206                 int err = 0;
16207
16208                 *rv = 0;
16209
16210                 /*
16211                  * If a NULL argument has been passed, we take this as our
16212                  * cue to reevaluate our enablings.
16213                  */
16214                 if (arg == NULL) {
16215                         dtrace_enabling_matchall();
16216
16217                         return (0);
16218                 }
16219
16220                 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16221                         return (rval);
16222
16223                 mutex_enter(&cpu_lock);
16224                 mutex_enter(&dtrace_lock);
16225                 vstate = &state->dts_vstate;
16226
16227                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16228                         mutex_exit(&dtrace_lock);
16229                         mutex_exit(&cpu_lock);
16230                         dtrace_dof_destroy(dof);
16231                         return (EBUSY);
16232                 }
16233
16234                 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16235                         mutex_exit(&dtrace_lock);
16236                         mutex_exit(&cpu_lock);
16237                         dtrace_dof_destroy(dof);
16238                         return (EINVAL);
16239                 }
16240
16241                 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16242                         dtrace_enabling_destroy(enab);
16243                         mutex_exit(&dtrace_lock);
16244                         mutex_exit(&cpu_lock);
16245                         dtrace_dof_destroy(dof);
16246                         return (rval);
16247                 }
16248
16249                 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16250                         err = dtrace_enabling_retain(enab);
16251                 } else {
16252                         dtrace_enabling_destroy(enab);
16253                 }
16254
16255                 mutex_exit(&cpu_lock);
16256                 mutex_exit(&dtrace_lock);
16257                 dtrace_dof_destroy(dof);
16258
16259                 return (err);
16260         }
16261
16262         case DTRACEIOC_REPLICATE: {
16263                 dtrace_repldesc_t desc;
16264                 dtrace_probedesc_t *match = &desc.dtrpd_match;
16265                 dtrace_probedesc_t *create = &desc.dtrpd_create;
16266                 int err;
16267
16268                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16269                         return (EFAULT);
16270
16271                 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16272                 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16273                 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16274                 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16275
16276                 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16277                 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16278                 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16279                 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16280
16281                 mutex_enter(&dtrace_lock);
16282                 err = dtrace_enabling_replicate(state, match, create);
16283                 mutex_exit(&dtrace_lock);
16284
16285                 return (err);
16286         }
16287
16288         case DTRACEIOC_PROBEMATCH:
16289         case DTRACEIOC_PROBES: {
16290                 dtrace_probe_t *probe = NULL;
16291                 dtrace_probedesc_t desc;
16292                 dtrace_probekey_t pkey;
16293                 dtrace_id_t i;
16294                 int m = 0;
16295                 uint32_t priv;
16296                 uid_t uid;
16297                 zoneid_t zoneid;
16298
16299                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16300                         return (EFAULT);
16301
16302                 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16303                 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16304                 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16305                 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16306
16307                 /*
16308                  * Before we attempt to match this probe, we want to give
16309                  * all providers the opportunity to provide it.
16310                  */
16311                 if (desc.dtpd_id == DTRACE_IDNONE) {
16312                         mutex_enter(&dtrace_provider_lock);
16313                         dtrace_probe_provide(&desc, NULL);
16314                         mutex_exit(&dtrace_provider_lock);
16315                         desc.dtpd_id++;
16316                 }
16317
16318                 if (cmd == DTRACEIOC_PROBEMATCH)  {
16319                         dtrace_probekey(&desc, &pkey);
16320                         pkey.dtpk_id = DTRACE_IDNONE;
16321                 }
16322
16323                 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16324
16325                 mutex_enter(&dtrace_lock);
16326
16327                 if (cmd == DTRACEIOC_PROBEMATCH) {
16328                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16329                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16330                                     (m = dtrace_match_probe(probe, &pkey,
16331                                     priv, uid, zoneid)) != 0)
16332                                         break;
16333                         }
16334
16335                         if (m < 0) {
16336                                 mutex_exit(&dtrace_lock);
16337                                 return (EINVAL);
16338                         }
16339
16340                 } else {
16341                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16342                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16343                                     dtrace_match_priv(probe, priv, uid, zoneid))
16344                                         break;
16345                         }
16346                 }
16347
16348                 if (probe == NULL) {
16349                         mutex_exit(&dtrace_lock);
16350                         return (ESRCH);
16351                 }
16352
16353                 dtrace_probe_description(probe, &desc);
16354                 mutex_exit(&dtrace_lock);
16355
16356                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16357                         return (EFAULT);
16358
16359                 return (0);
16360         }
16361
16362         case DTRACEIOC_PROBEARG: {
16363                 dtrace_argdesc_t desc;
16364                 dtrace_probe_t *probe;
16365                 dtrace_provider_t *prov;
16366
16367                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16368                         return (EFAULT);
16369
16370                 if (desc.dtargd_id == DTRACE_IDNONE)
16371                         return (EINVAL);
16372
16373                 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16374                         return (EINVAL);
16375
16376                 mutex_enter(&dtrace_provider_lock);
16377                 mutex_enter(&mod_lock);
16378                 mutex_enter(&dtrace_lock);
16379
16380                 if (desc.dtargd_id > dtrace_nprobes) {
16381                         mutex_exit(&dtrace_lock);
16382                         mutex_exit(&mod_lock);
16383                         mutex_exit(&dtrace_provider_lock);
16384                         return (EINVAL);
16385                 }
16386
16387                 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16388                         mutex_exit(&dtrace_lock);
16389                         mutex_exit(&mod_lock);
16390                         mutex_exit(&dtrace_provider_lock);
16391                         return (EINVAL);
16392                 }
16393
16394                 mutex_exit(&dtrace_lock);
16395
16396                 prov = probe->dtpr_provider;
16397
16398                 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16399                         /*
16400                          * There isn't any typed information for this probe.
16401                          * Set the argument number to DTRACE_ARGNONE.
16402                          */
16403                         desc.dtargd_ndx = DTRACE_ARGNONE;
16404                 } else {
16405                         desc.dtargd_native[0] = '\0';
16406                         desc.dtargd_xlate[0] = '\0';
16407                         desc.dtargd_mapping = desc.dtargd_ndx;
16408
16409                         prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16410                             probe->dtpr_id, probe->dtpr_arg, &desc);
16411                 }
16412
16413                 mutex_exit(&mod_lock);
16414                 mutex_exit(&dtrace_provider_lock);
16415
16416                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16417                         return (EFAULT);
16418
16419                 return (0);
16420         }
16421
16422         case DTRACEIOC_GO: {
16423                 processorid_t cpuid;
16424                 rval = dtrace_state_go(state, &cpuid);
16425
16426                 if (rval != 0)
16427                         return (rval);
16428
16429                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16430                         return (EFAULT);
16431
16432                 return (0);
16433         }
16434
16435         case DTRACEIOC_STOP: {
16436                 processorid_t cpuid;
16437
16438                 mutex_enter(&dtrace_lock);
16439                 rval = dtrace_state_stop(state, &cpuid);
16440                 mutex_exit(&dtrace_lock);
16441
16442                 if (rval != 0)
16443                         return (rval);
16444
16445                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16446                         return (EFAULT);
16447
16448                 return (0);
16449         }
16450
16451         case DTRACEIOC_DOFGET: {
16452                 dof_hdr_t hdr, *dof;
16453                 uint64_t len;
16454
16455                 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16456                         return (EFAULT);
16457
16458                 mutex_enter(&dtrace_lock);
16459                 dof = dtrace_dof_create(state);
16460                 mutex_exit(&dtrace_lock);
16461
16462                 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16463                 rval = copyout(dof, (void *)arg, len);
16464                 dtrace_dof_destroy(dof);
16465
16466                 return (rval == 0 ? 0 : EFAULT);
16467         }
16468
16469         case DTRACEIOC_AGGSNAP:
16470         case DTRACEIOC_BUFSNAP: {
16471                 dtrace_bufdesc_t desc;
16472                 caddr_t cached;
16473                 dtrace_buffer_t *buf;
16474
16475                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16476                         return (EFAULT);
16477
16478                 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16479                         return (EINVAL);
16480
16481                 mutex_enter(&dtrace_lock);
16482
16483                 if (cmd == DTRACEIOC_BUFSNAP) {
16484                         buf = &state->dts_buffer[desc.dtbd_cpu];
16485                 } else {
16486                         buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16487                 }
16488
16489                 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16490                         size_t sz = buf->dtb_offset;
16491
16492                         if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16493                                 mutex_exit(&dtrace_lock);
16494                                 return (EBUSY);
16495                         }
16496
16497                         /*
16498                          * If this buffer has already been consumed, we're
16499                          * going to indicate that there's nothing left here
16500                          * to consume.
16501                          */
16502                         if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16503                                 mutex_exit(&dtrace_lock);
16504
16505                                 desc.dtbd_size = 0;
16506                                 desc.dtbd_drops = 0;
16507                                 desc.dtbd_errors = 0;
16508                                 desc.dtbd_oldest = 0;
16509                                 sz = sizeof (desc);
16510
16511                                 if (copyout(&desc, (void *)arg, sz) != 0)
16512                                         return (EFAULT);
16513
16514                                 return (0);
16515                         }
16516
16517                         /*
16518                          * If this is a ring buffer that has wrapped, we want
16519                          * to copy the whole thing out.
16520                          */
16521                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16522                                 dtrace_buffer_polish(buf);
16523                                 sz = buf->dtb_size;
16524                         }
16525
16526                         if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16527                                 mutex_exit(&dtrace_lock);
16528                                 return (EFAULT);
16529                         }
16530
16531                         desc.dtbd_size = sz;
16532                         desc.dtbd_drops = buf->dtb_drops;
16533                         desc.dtbd_errors = buf->dtb_errors;
16534                         desc.dtbd_oldest = buf->dtb_xamot_offset;
16535                         desc.dtbd_timestamp = dtrace_gethrtime();
16536
16537                         mutex_exit(&dtrace_lock);
16538
16539                         if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16540                                 return (EFAULT);
16541
16542                         buf->dtb_flags |= DTRACEBUF_CONSUMED;
16543
16544                         return (0);
16545                 }
16546
16547                 if (buf->dtb_tomax == NULL) {
16548                         ASSERT(buf->dtb_xamot == NULL);
16549                         mutex_exit(&dtrace_lock);
16550                         return (ENOENT);
16551                 }
16552
16553                 cached = buf->dtb_tomax;
16554                 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16555
16556                 dtrace_xcall(desc.dtbd_cpu,
16557                     (dtrace_xcall_t)dtrace_buffer_switch, buf);
16558
16559                 state->dts_errors += buf->dtb_xamot_errors;
16560
16561                 /*
16562                  * If the buffers did not actually switch, then the cross call
16563                  * did not take place -- presumably because the given CPU is
16564                  * not in the ready set.  If this is the case, we'll return
16565                  * ENOENT.
16566                  */
16567                 if (buf->dtb_tomax == cached) {
16568                         ASSERT(buf->dtb_xamot != cached);
16569                         mutex_exit(&dtrace_lock);
16570                         return (ENOENT);
16571                 }
16572
16573                 ASSERT(cached == buf->dtb_xamot);
16574
16575                 /*
16576                  * We have our snapshot; now copy it out.
16577                  */
16578                 if (copyout(buf->dtb_xamot, desc.dtbd_data,
16579                     buf->dtb_xamot_offset) != 0) {
16580                         mutex_exit(&dtrace_lock);
16581                         return (EFAULT);
16582                 }
16583
16584                 desc.dtbd_size = buf->dtb_xamot_offset;
16585                 desc.dtbd_drops = buf->dtb_xamot_drops;
16586                 desc.dtbd_errors = buf->dtb_xamot_errors;
16587                 desc.dtbd_oldest = 0;
16588                 desc.dtbd_timestamp = buf->dtb_switched;
16589
16590                 mutex_exit(&dtrace_lock);
16591
16592                 /*
16593                  * Finally, copy out the buffer description.
16594                  */
16595                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16596                         return (EFAULT);
16597
16598                 return (0);
16599         }
16600
16601         case DTRACEIOC_CONF: {
16602                 dtrace_conf_t conf;
16603
16604                 bzero(&conf, sizeof (conf));
16605                 conf.dtc_difversion = DIF_VERSION;
16606                 conf.dtc_difintregs = DIF_DIR_NREGS;
16607                 conf.dtc_diftupregs = DIF_DTR_NREGS;
16608                 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16609
16610                 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16611                         return (EFAULT);
16612
16613                 return (0);
16614         }
16615
16616         case DTRACEIOC_STATUS: {
16617                 dtrace_status_t stat;
16618                 dtrace_dstate_t *dstate;
16619                 int i, j;
16620                 uint64_t nerrs;
16621
16622                 /*
16623                  * See the comment in dtrace_state_deadman() for the reason
16624                  * for setting dts_laststatus to INT64_MAX before setting
16625                  * it to the correct value.
16626                  */
16627                 state->dts_laststatus = INT64_MAX;
16628                 dtrace_membar_producer();
16629                 state->dts_laststatus = dtrace_gethrtime();
16630
16631                 bzero(&stat, sizeof (stat));
16632
16633                 mutex_enter(&dtrace_lock);
16634
16635                 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16636                         mutex_exit(&dtrace_lock);
16637                         return (ENOENT);
16638                 }
16639
16640                 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16641                         stat.dtst_exiting = 1;
16642
16643                 nerrs = state->dts_errors;
16644                 dstate = &state->dts_vstate.dtvs_dynvars;
16645
16646                 for (i = 0; i < NCPU; i++) {
16647                         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16648
16649                         stat.dtst_dyndrops += dcpu->dtdsc_drops;
16650                         stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16651                         stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16652
16653                         if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16654                                 stat.dtst_filled++;
16655
16656                         nerrs += state->dts_buffer[i].dtb_errors;
16657
16658                         for (j = 0; j < state->dts_nspeculations; j++) {
16659                                 dtrace_speculation_t *spec;
16660                                 dtrace_buffer_t *buf;
16661
16662                                 spec = &state->dts_speculations[j];
16663                                 buf = &spec->dtsp_buffer[i];
16664                                 stat.dtst_specdrops += buf->dtb_xamot_drops;
16665                         }
16666                 }
16667
16668                 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16669                 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16670                 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16671                 stat.dtst_dblerrors = state->dts_dblerrors;
16672                 stat.dtst_killed =
16673                     (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16674                 stat.dtst_errors = nerrs;
16675
16676                 mutex_exit(&dtrace_lock);
16677
16678                 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16679                         return (EFAULT);
16680
16681                 return (0);
16682         }
16683
16684         case DTRACEIOC_FORMAT: {
16685                 dtrace_fmtdesc_t fmt;
16686                 char *str;
16687                 int len;
16688
16689                 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16690                         return (EFAULT);
16691
16692                 mutex_enter(&dtrace_lock);
16693
16694                 if (fmt.dtfd_format == 0 ||
16695                     fmt.dtfd_format > state->dts_nformats) {
16696                         mutex_exit(&dtrace_lock);
16697                         return (EINVAL);
16698                 }
16699
16700                 /*
16701                  * Format strings are allocated contiguously and they are
16702                  * never freed; if a format index is less than the number
16703                  * of formats, we can assert that the format map is non-NULL
16704                  * and that the format for the specified index is non-NULL.
16705                  */
16706                 ASSERT(state->dts_formats != NULL);
16707                 str = state->dts_formats[fmt.dtfd_format - 1];
16708                 ASSERT(str != NULL);
16709
16710                 len = strlen(str) + 1;
16711
16712                 if (len > fmt.dtfd_length) {
16713                         fmt.dtfd_length = len;
16714
16715                         if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16716                                 mutex_exit(&dtrace_lock);
16717                                 return (EINVAL);
16718                         }
16719                 } else {
16720                         if (copyout(str, fmt.dtfd_string, len) != 0) {
16721                                 mutex_exit(&dtrace_lock);
16722                                 return (EINVAL);
16723                         }
16724                 }
16725
16726                 mutex_exit(&dtrace_lock);
16727                 return (0);
16728         }
16729
16730         default:
16731                 break;
16732         }
16733
16734         return (ENOTTY);
16735 }
16736
16737 /*ARGSUSED*/
16738 static int
16739 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16740 {
16741         dtrace_state_t *state;
16742
16743         switch (cmd) {
16744         case DDI_DETACH:
16745                 break;
16746
16747         case DDI_SUSPEND:
16748                 return (DDI_SUCCESS);
16749
16750         default:
16751                 return (DDI_FAILURE);
16752         }
16753
16754         mutex_enter(&cpu_lock);
16755         mutex_enter(&dtrace_provider_lock);
16756         mutex_enter(&dtrace_lock);
16757
16758         ASSERT(dtrace_opens == 0);
16759
16760         if (dtrace_helpers > 0) {
16761                 mutex_exit(&dtrace_provider_lock);
16762                 mutex_exit(&dtrace_lock);
16763                 mutex_exit(&cpu_lock);
16764                 return (DDI_FAILURE);
16765         }
16766
16767         if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16768                 mutex_exit(&dtrace_provider_lock);
16769                 mutex_exit(&dtrace_lock);
16770                 mutex_exit(&cpu_lock);
16771                 return (DDI_FAILURE);
16772         }
16773
16774         dtrace_provider = NULL;
16775
16776         if ((state = dtrace_anon_grab()) != NULL) {
16777                 /*
16778                  * If there were ECBs on this state, the provider should
16779                  * have not been allowed to detach; assert that there is
16780                  * none.
16781                  */
16782                 ASSERT(state->dts_necbs == 0);
16783                 dtrace_state_destroy(state);
16784
16785                 /*
16786                  * If we're being detached with anonymous state, we need to
16787                  * indicate to the kernel debugger that DTrace is now inactive.
16788                  */
16789                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16790         }
16791
16792         bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16793         unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16794         dtrace_cpu_init = NULL;
16795         dtrace_helpers_cleanup = NULL;
16796         dtrace_helpers_fork = NULL;
16797         dtrace_cpustart_init = NULL;
16798         dtrace_cpustart_fini = NULL;
16799         dtrace_debugger_init = NULL;
16800         dtrace_debugger_fini = NULL;
16801         dtrace_modload = NULL;
16802         dtrace_modunload = NULL;
16803
16804         mutex_exit(&cpu_lock);
16805
16806         if (dtrace_helptrace_enabled) {
16807                 kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
16808                 dtrace_helptrace_buffer = NULL;
16809         }
16810
16811         kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16812         dtrace_probes = NULL;
16813         dtrace_nprobes = 0;
16814
16815         dtrace_hash_destroy(dtrace_bymod);
16816         dtrace_hash_destroy(dtrace_byfunc);
16817         dtrace_hash_destroy(dtrace_byname);
16818         dtrace_bymod = NULL;
16819         dtrace_byfunc = NULL;
16820         dtrace_byname = NULL;
16821
16822         kmem_cache_destroy(dtrace_state_cache);
16823         vmem_destroy(dtrace_minor);
16824         vmem_destroy(dtrace_arena);
16825
16826         if (dtrace_toxrange != NULL) {
16827                 kmem_free(dtrace_toxrange,
16828                     dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16829                 dtrace_toxrange = NULL;
16830                 dtrace_toxranges = 0;
16831                 dtrace_toxranges_max = 0;
16832         }
16833
16834         ddi_remove_minor_node(dtrace_devi, NULL);
16835         dtrace_devi = NULL;
16836
16837         ddi_soft_state_fini(&dtrace_softstate);
16838
16839         ASSERT(dtrace_vtime_references == 0);
16840         ASSERT(dtrace_opens == 0);
16841         ASSERT(dtrace_retained == NULL);
16842
16843         mutex_exit(&dtrace_lock);
16844         mutex_exit(&dtrace_provider_lock);
16845
16846         /*
16847          * We don't destroy the task queue until after we have dropped our
16848          * locks (taskq_destroy() may block on running tasks).  To prevent
16849          * attempting to do work after we have effectively detached but before
16850          * the task queue has been destroyed, all tasks dispatched via the
16851          * task queue must check that DTrace is still attached before
16852          * performing any operation.
16853          */
16854         taskq_destroy(dtrace_taskq);
16855         dtrace_taskq = NULL;
16856
16857         return (DDI_SUCCESS);
16858 }
16859 #endif
16860
16861 #if defined(sun)
16862 /*ARGSUSED*/
16863 static int
16864 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16865 {
16866         int error;
16867
16868         switch (infocmd) {
16869         case DDI_INFO_DEVT2DEVINFO:
16870                 *result = (void *)dtrace_devi;
16871                 error = DDI_SUCCESS;
16872                 break;
16873         case DDI_INFO_DEVT2INSTANCE:
16874                 *result = (void *)0;
16875                 error = DDI_SUCCESS;
16876                 break;
16877         default:
16878                 error = DDI_FAILURE;
16879         }
16880         return (error);
16881 }
16882 #endif
16883
16884 #if defined(sun)
16885 static struct cb_ops dtrace_cb_ops = {
16886         dtrace_open,            /* open */
16887         dtrace_close,           /* close */
16888         nulldev,                /* strategy */
16889         nulldev,                /* print */
16890         nodev,                  /* dump */
16891         nodev,                  /* read */
16892         nodev,                  /* write */
16893         dtrace_ioctl,           /* ioctl */
16894         nodev,                  /* devmap */
16895         nodev,                  /* mmap */
16896         nodev,                  /* segmap */
16897         nochpoll,               /* poll */
16898         ddi_prop_op,            /* cb_prop_op */
16899         0,                      /* streamtab  */
16900         D_NEW | D_MP            /* Driver compatibility flag */
16901 };
16902
16903 static struct dev_ops dtrace_ops = {
16904         DEVO_REV,               /* devo_rev */
16905         0,                      /* refcnt */
16906         dtrace_info,            /* get_dev_info */
16907         nulldev,                /* identify */
16908         nulldev,                /* probe */
16909         dtrace_attach,          /* attach */
16910         dtrace_detach,          /* detach */
16911         nodev,                  /* reset */
16912         &dtrace_cb_ops,         /* driver operations */
16913         NULL,                   /* bus operations */
16914         nodev                   /* dev power */
16915 };
16916
16917 static struct modldrv modldrv = {
16918         &mod_driverops,         /* module type (this is a pseudo driver) */
16919         "Dynamic Tracing",      /* name of module */
16920         &dtrace_ops,            /* driver ops */
16921 };
16922
16923 static struct modlinkage modlinkage = {
16924         MODREV_1,
16925         (void *)&modldrv,
16926         NULL
16927 };
16928
16929 int
16930 _init(void)
16931 {
16932         return (mod_install(&modlinkage));
16933 }
16934
16935 int
16936 _info(struct modinfo *modinfop)
16937 {
16938         return (mod_info(&modlinkage, modinfop));
16939 }
16940
16941 int
16942 _fini(void)
16943 {
16944         return (mod_remove(&modlinkage));
16945 }
16946 #else
16947
16948 static d_ioctl_t        dtrace_ioctl;
16949 static d_ioctl_t        dtrace_ioctl_helper;
16950 static void             dtrace_load(void *);
16951 static int              dtrace_unload(void);
16952 #if __FreeBSD_version < 800039
16953 static void             dtrace_clone(void *, struct ucred *, char *, int , struct cdev **);
16954 static struct clonedevs *dtrace_clones;         /* Ptr to the array of cloned devices. */
16955 static eventhandler_tag eh_tag;                 /* Event handler tag. */
16956 #else
16957 static struct cdev      *dtrace_dev;
16958 static struct cdev      *helper_dev;
16959 #endif
16960
16961 void dtrace_invop_init(void);
16962 void dtrace_invop_uninit(void);
16963
16964 static struct cdevsw dtrace_cdevsw = {
16965         .d_version      = D_VERSION,
16966         .d_flags        = D_TRACKCLOSE | D_NEEDMINOR,
16967         .d_close        = dtrace_close,
16968         .d_ioctl        = dtrace_ioctl,
16969         .d_open         = dtrace_open,
16970         .d_name         = "dtrace",
16971 };
16972
16973 static struct cdevsw helper_cdevsw = {
16974         .d_version      = D_VERSION,
16975         .d_flags        = D_TRACKCLOSE | D_NEEDMINOR,
16976         .d_ioctl        = dtrace_ioctl_helper,
16977         .d_name         = "helper",
16978 };
16979
16980 #include <dtrace_anon.c>
16981 #if __FreeBSD_version < 800039
16982 #include <dtrace_clone.c>
16983 #endif
16984 #include <dtrace_ioctl.c>
16985 #include <dtrace_load.c>
16986 #include <dtrace_modevent.c>
16987 #include <dtrace_sysctl.c>
16988 #include <dtrace_unload.c>
16989 #include <dtrace_vtime.c>
16990 #include <dtrace_hacks.c>
16991 #include <dtrace_isa.c>
16992
16993 SYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
16994 SYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
16995 SYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
16996
16997 DEV_MODULE(dtrace, dtrace_modevent, NULL);
16998 MODULE_VERSION(dtrace, 1);
16999 MODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
17000 MODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
17001 #endif