xref: /freebsd/sys/cddl/contrib/opensolaris/uts/common/sys/dtrace_impl.h (revision 95ee2897e98f5d444f26ed2334cc7c439f9c16c6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Copyright 2016 Joyent, Inc.
29  * Copyright (c) 2012 by Delphix. All rights reserved.
30  */
31 
32 #ifndef _SYS_DTRACE_IMPL_H
33 #define	_SYS_DTRACE_IMPL_H
34 
35 #ifdef	__cplusplus
36 extern "C" {
37 #endif
38 
39 /*
40  * DTrace Dynamic Tracing Software: Kernel Implementation Interfaces
41  *
42  * Note: The contents of this file are private to the implementation of the
43  * Solaris system and DTrace subsystem and are subject to change at any time
44  * without notice.  Applications and drivers using these interfaces will fail
45  * to run on future releases.  These interfaces should not be used for any
46  * purpose except those expressly outlined in dtrace(7D) and libdtrace(3LIB).
47  * Please refer to the "Solaris Dynamic Tracing Guide" for more information.
48  */
49 
50 #include <sys/dtrace.h>
51 #include <sys/file.h>
52 
53 #ifndef illumos
54 #ifdef __sparcv9
55 typedef uint32_t		pc_t;
56 #else
57 typedef uintptr_t		pc_t;
58 #endif
59 typedef	u_long			greg_t;
60 #endif
61 
62 /*
63  * DTrace Implementation Constants and Typedefs
64  */
65 #define	DTRACE_MAXPROPLEN		128
66 #define	DTRACE_DYNVAR_CHUNKSIZE		256
67 
68 #ifdef __FreeBSD__
69 #define	NCPU		MAXCPU
70 #endif /* __FreeBSD__ */
71 
72 struct dtrace_probe;
73 struct dtrace_ecb;
74 struct dtrace_predicate;
75 struct dtrace_action;
76 struct dtrace_provider;
77 struct dtrace_state;
78 
79 typedef struct dtrace_probe dtrace_probe_t;
80 typedef struct dtrace_ecb dtrace_ecb_t;
81 typedef struct dtrace_predicate dtrace_predicate_t;
82 typedef struct dtrace_action dtrace_action_t;
83 typedef struct dtrace_provider dtrace_provider_t;
84 typedef struct dtrace_meta dtrace_meta_t;
85 typedef struct dtrace_state dtrace_state_t;
86 typedef uint32_t dtrace_optid_t;
87 typedef uint32_t dtrace_specid_t;
88 typedef uint64_t dtrace_genid_t;
89 
90 /*
91  * DTrace Probes
92  *
93  * The probe is the fundamental unit of the DTrace architecture.  Probes are
94  * created by DTrace providers, and managed by the DTrace framework.  A probe
95  * is identified by a unique <provider, module, function, name> tuple, and has
96  * a unique probe identifier assigned to it.  (Some probes are not associated
97  * with a specific point in text; these are called _unanchored probes_ and have
98  * no module or function associated with them.)  Probes are represented as a
99  * dtrace_probe structure.  To allow quick lookups based on each element of the
100  * probe tuple, probes are hashed by each of provider, module, function and
101  * name.  (If a lookup is performed based on a regular expression, a
102  * dtrace_probekey is prepared, and a linear search is performed.) Each probe
103  * is additionally pointed to by a linear array indexed by its identifier.  The
104  * identifier is the provider's mechanism for indicating to the DTrace
105  * framework that a probe has fired:  the identifier is passed as the first
106  * argument to dtrace_probe(), where it is then mapped into the corresponding
107  * dtrace_probe structure.  From the dtrace_probe structure, dtrace_probe() can
108  * iterate over the probe's list of enabling control blocks; see "DTrace
109  * Enabling Control Blocks", below.)
110  */
111 struct dtrace_probe {
112 	dtrace_id_t dtpr_id;			/* probe identifier */
113 	dtrace_ecb_t *dtpr_ecb;			/* ECB list; see below */
114 	dtrace_ecb_t *dtpr_ecb_last;		/* last ECB in list */
115 	void *dtpr_arg;				/* provider argument */
116 	dtrace_cacheid_t dtpr_predcache;	/* predicate cache ID */
117 	int dtpr_aframes;			/* artificial frames */
118 	dtrace_provider_t *dtpr_provider;	/* pointer to provider */
119 	char *dtpr_mod;				/* probe's module name */
120 	char *dtpr_func;			/* probe's function name */
121 	char *dtpr_name;			/* probe's name */
122 	dtrace_probe_t *dtpr_nextmod;		/* next in module hash */
123 	dtrace_probe_t *dtpr_prevmod;		/* previous in module hash */
124 	dtrace_probe_t *dtpr_nextfunc;		/* next in function hash */
125 	dtrace_probe_t *dtpr_prevfunc;		/* previous in function hash */
126 	dtrace_probe_t *dtpr_nextname;		/* next in name hash */
127 	dtrace_probe_t *dtpr_prevname;		/* previous in name hash */
128 	dtrace_genid_t dtpr_gen;		/* probe generation ID */
129 };
130 
131 typedef int dtrace_probekey_f(const char *, const char *, int);
132 
133 typedef struct dtrace_probekey {
134 	char *dtpk_prov;			/* provider name to match */
135 	dtrace_probekey_f *dtpk_pmatch;		/* provider matching function */
136 	char *dtpk_mod;				/* module name to match */
137 	dtrace_probekey_f *dtpk_mmatch;		/* module matching function */
138 	char *dtpk_func;			/* func name to match */
139 	dtrace_probekey_f *dtpk_fmatch;		/* func matching function */
140 	char *dtpk_name;			/* name to match */
141 	dtrace_probekey_f *dtpk_nmatch;		/* name matching function */
142 	dtrace_id_t dtpk_id;			/* identifier to match */
143 } dtrace_probekey_t;
144 
145 typedef struct dtrace_hashbucket {
146 	struct dtrace_hashbucket *dthb_next;	/* next on hash chain */
147 	dtrace_probe_t *dthb_chain;		/* chain of probes */
148 	int dthb_len;				/* number of probes here */
149 } dtrace_hashbucket_t;
150 
151 typedef struct dtrace_hash {
152 	dtrace_hashbucket_t **dth_tab;		/* hash table */
153 	int dth_size;				/* size of hash table */
154 	int dth_mask;				/* mask to index into table */
155 	int dth_nbuckets;			/* total number of buckets */
156 	uintptr_t dth_nextoffs;			/* offset of next in probe */
157 	uintptr_t dth_prevoffs;			/* offset of prev in probe */
158 	uintptr_t dth_stroffs;			/* offset of str in probe */
159 } dtrace_hash_t;
160 
161 /*
162  * DTrace Enabling Control Blocks
163  *
164  * When a provider wishes to fire a probe, it calls into dtrace_probe(),
165  * passing the probe identifier as the first argument.  As described above,
166  * dtrace_probe() maps the identifier into a pointer to a dtrace_probe_t
167  * structure.  This structure contains information about the probe, and a
168  * pointer to the list of Enabling Control Blocks (ECBs).  Each ECB points to
169  * DTrace consumer state, and contains an optional predicate, and a list of
170  * actions.  (Shown schematically below.)  The ECB abstraction allows a single
171  * probe to be multiplexed across disjoint consumers, or across disjoint
172  * enablings of a single probe within one consumer.
173  *
174  *   Enabling Control Block
175  *        dtrace_ecb_t
176  * +------------------------+
177  * | dtrace_epid_t ---------+--------------> Enabled Probe ID (EPID)
178  * | dtrace_state_t * ------+--------------> State associated with this ECB
179  * | dtrace_predicate_t * --+---------+
180  * | dtrace_action_t * -----+----+    |
181  * | dtrace_ecb_t * ---+    |    |    |       Predicate (if any)
182  * +-------------------+----+    |    |       dtrace_predicate_t
183  *                     |         |    +---> +--------------------+
184  *                     |         |          | dtrace_difo_t * ---+----> DIFO
185  *                     |         |          +--------------------+
186  *                     |         |
187  *            Next ECB |         |           Action
188  *            (if any) |         |       dtrace_action_t
189  *                     :         +--> +-------------------+
190  *                     :              | dtrace_actkind_t -+------> kind
191  *                     v              | dtrace_difo_t * --+------> DIFO (if any)
192  *                                    | dtrace_recdesc_t -+------> record descr.
193  *                                    | dtrace_action_t * +------+
194  *                                    +-------------------+      |
195  *                                                               | Next action
196  *                               +-------------------------------+  (if any)
197  *                               |
198  *                               |           Action
199  *                               |       dtrace_action_t
200  *                               +--> +-------------------+
201  *                                    | dtrace_actkind_t -+------> kind
202  *                                    | dtrace_difo_t * --+------> DIFO (if any)
203  *                                    | dtrace_action_t * +------+
204  *                                    +-------------------+      |
205  *                                                               | Next action
206  *                               +-------------------------------+  (if any)
207  *                               |
208  *                               :
209  *                               v
210  *
211  *
212  * dtrace_probe() iterates over the ECB list.  If the ECB needs less space
213  * than is available in the principal buffer, the ECB is processed:  if the
214  * predicate is non-NULL, the DIF object is executed.  If the result is
215  * non-zero, the action list is processed, with each action being executed
216  * accordingly.  When the action list has been completely executed, processing
217  * advances to the next ECB. The ECB abstraction allows disjoint consumers
218  * to multiplex on single probes.
219  *
220  * Execution of the ECB results in consuming dte_size bytes in the buffer
221  * to record data.  During execution, dte_needed bytes must be available in
222  * the buffer.  This space is used for both recorded data and tuple data.
223  */
224 struct dtrace_ecb {
225 	dtrace_epid_t dte_epid;			/* enabled probe ID */
226 	uint32_t dte_alignment;			/* required alignment */
227 	size_t dte_needed;			/* space needed for execution */
228 	size_t dte_size;			/* size of recorded payload */
229 	dtrace_predicate_t *dte_predicate;	/* predicate, if any */
230 	dtrace_action_t *dte_action;		/* actions, if any */
231 	dtrace_ecb_t *dte_next;			/* next ECB on probe */
232 	dtrace_state_t *dte_state;		/* pointer to state */
233 	uint32_t dte_cond;			/* security condition */
234 	dtrace_probe_t *dte_probe;		/* pointer to probe */
235 	dtrace_action_t *dte_action_last;	/* last action on ECB */
236 	uint64_t dte_uarg;			/* library argument */
237 };
238 
239 struct dtrace_predicate {
240 	dtrace_difo_t *dtp_difo;		/* DIF object */
241 	dtrace_cacheid_t dtp_cacheid;		/* cache identifier */
242 	int dtp_refcnt;				/* reference count */
243 };
244 
245 struct dtrace_action {
246 	dtrace_actkind_t dta_kind;		/* kind of action */
247 	uint16_t dta_intuple;			/* boolean:  in aggregation */
248 	uint32_t dta_refcnt;			/* reference count */
249 	dtrace_difo_t *dta_difo;		/* pointer to DIFO */
250 	dtrace_recdesc_t dta_rec;		/* record description */
251 	dtrace_action_t *dta_prev;		/* previous action */
252 	dtrace_action_t *dta_next;		/* next action */
253 };
254 
255 typedef struct dtrace_aggregation {
256 	dtrace_action_t dtag_action;		/* action; must be first */
257 	dtrace_aggid_t dtag_id;			/* identifier */
258 	dtrace_ecb_t *dtag_ecb;			/* corresponding ECB */
259 	dtrace_action_t *dtag_first;		/* first action in tuple */
260 	uint32_t dtag_base;			/* base of aggregation */
261 	uint8_t dtag_hasarg;			/* boolean:  has argument */
262 	uint64_t dtag_initial;			/* initial value */
263 	void (*dtag_aggregate)(uint64_t *, uint64_t, uint64_t);
264 } dtrace_aggregation_t;
265 
266 /*
267  * DTrace Buffers
268  *
269  * Principal buffers, aggregation buffers, and speculative buffers are all
270  * managed with the dtrace_buffer structure.  By default, this structure
271  * includes twin data buffers -- dtb_tomax and dtb_xamot -- that serve as the
272  * active and passive buffers, respectively.  For speculative buffers,
273  * dtb_xamot will be NULL; for "ring" and "fill" buffers, dtb_xamot will point
274  * to a scratch buffer.  For all buffer types, the dtrace_buffer structure is
275  * always allocated on a per-CPU basis; a single dtrace_buffer structure is
276  * never shared among CPUs.  (That is, there is never true sharing of the
277  * dtrace_buffer structure; to prevent false sharing of the structure, it must
278  * always be aligned to the coherence granularity -- generally 64 bytes.)
279  *
280  * One of the critical design decisions of DTrace is that a given ECB always
281  * stores the same quantity and type of data.  This is done to assure that the
282  * only metadata required for an ECB's traced data is the EPID.  That is, from
283  * the EPID, the consumer can determine the data layout.  (The data buffer
284  * layout is shown schematically below.)  By assuring that one can determine
285  * data layout from the EPID, the metadata stream can be separated from the
286  * data stream -- simplifying the data stream enormously.  The ECB always
287  * proceeds the recorded data as part of the dtrace_rechdr_t structure that
288  * includes the EPID and a high-resolution timestamp used for output ordering
289  * consistency.
290  *
291  *      base of data buffer --->  +--------+--------------------+--------+
292  *                                | rechdr | data               | rechdr |
293  *                                +--------+------+--------+----+--------+
294  *                                | data          | rechdr | data        |
295  *                                +---------------+--------+-------------+
296  *                                | data, cont.                          |
297  *                                +--------+--------------------+--------+
298  *                                | rechdr | data               |        |
299  *                                +--------+--------------------+        |
300  *                                |                ||                    |
301  *                                |                ||                    |
302  *                                |                \/                    |
303  *                                :                                      :
304  *                                .                                      .
305  *                                .                                      .
306  *                                .                                      .
307  *                                :                                      :
308  *                                |                                      |
309  *     limit of data buffer --->  +--------------------------------------+
310  *
311  * When evaluating an ECB, dtrace_probe() determines if the ECB's needs of the
312  * principal buffer (both scratch and payload) exceed the available space.  If
313  * the ECB's needs exceed available space (and if the principal buffer policy
314  * is the default "switch" policy), the ECB is dropped, the buffer's drop count
315  * is incremented, and processing advances to the next ECB.  If the ECB's needs
316  * can be met with the available space, the ECB is processed, but the offset in
317  * the principal buffer is only advanced if the ECB completes processing
318  * without error.
319  *
320  * When a buffer is to be switched (either because the buffer is the principal
321  * buffer with a "switch" policy or because it is an aggregation buffer), a
322  * cross call is issued to the CPU associated with the buffer.  In the cross
323  * call context, interrupts are disabled, and the active and the inactive
324  * buffers are atomically switched.  This involves switching the data pointers,
325  * copying the various state fields (offset, drops, errors, etc.) into their
326  * inactive equivalents, and clearing the state fields.  Because interrupts are
327  * disabled during this procedure, the switch is guaranteed to appear atomic to
328  * dtrace_probe().
329  *
330  * DTrace Ring Buffering
331  *
332  * To process a ring buffer correctly, one must know the oldest valid record.
333  * Processing starts at the oldest record in the buffer and continues until
334  * the end of the buffer is reached.  Processing then resumes starting with
335  * the record stored at offset 0 in the buffer, and continues until the
336  * youngest record is processed.  If trace records are of a fixed-length,
337  * determining the oldest record is trivial:
338  *
339  *   - If the ring buffer has not wrapped, the oldest record is the record
340  *     stored at offset 0.
341  *
342  *   - If the ring buffer has wrapped, the oldest record is the record stored
343  *     at the current offset.
344  *
345  * With variable length records, however, just knowing the current offset
346  * doesn't suffice for determining the oldest valid record:  assuming that one
347  * allows for arbitrary data, one has no way of searching forward from the
348  * current offset to find the oldest valid record.  (That is, one has no way
349  * of separating data from metadata.) It would be possible to simply refuse to
350  * process any data in the ring buffer between the current offset and the
351  * limit, but this leaves (potentially) an enormous amount of otherwise valid
352  * data unprocessed.
353  *
354  * To effect ring buffering, we track two offsets in the buffer:  the current
355  * offset and the _wrapped_ offset.  If a request is made to reserve some
356  * amount of data, and the buffer has wrapped, the wrapped offset is
357  * incremented until the wrapped offset minus the current offset is greater
358  * than or equal to the reserve request.  This is done by repeatedly looking
359  * up the ECB corresponding to the EPID at the current wrapped offset, and
360  * incrementing the wrapped offset by the size of the data payload
361  * corresponding to that ECB.  If this offset is greater than or equal to the
362  * limit of the data buffer, the wrapped offset is set to 0.  Thus, the
363  * current offset effectively "chases" the wrapped offset around the buffer.
364  * Schematically:
365  *
366  *      base of data buffer --->  +------+--------------------+------+
367  *                                | EPID | data               | EPID |
368  *                                +------+--------+------+----+------+
369  *                                | data          | EPID | data      |
370  *                                +---------------+------+-----------+
371  *                                | data, cont.                      |
372  *                                +------+---------------------------+
373  *                                | EPID | data                      |
374  *           current offset --->  +------+---------------------------+
375  *                                | invalid data                     |
376  *           wrapped offset --->  +------+--------------------+------+
377  *                                | EPID | data               | EPID |
378  *                                +------+--------+------+----+------+
379  *                                | data          | EPID | data      |
380  *                                +---------------+------+-----------+
381  *                                :                                  :
382  *                                .                                  .
383  *                                .        ... valid data ...        .
384  *                                .                                  .
385  *                                :                                  :
386  *                                +------+-------------+------+------+
387  *                                | EPID | data        | EPID | data |
388  *                                +------+------------++------+------+
389  *                                | data, cont.       | leftover     |
390  *     limit of data buffer --->  +-------------------+--------------+
391  *
392  * If the amount of requested buffer space exceeds the amount of space
393  * available between the current offset and the end of the buffer:
394  *
395  *  (1)  all words in the data buffer between the current offset and the limit
396  *       of the data buffer (marked "leftover", above) are set to
397  *       DTRACE_EPIDNONE
398  *
399  *  (2)  the wrapped offset is set to zero
400  *
401  *  (3)  the iteration process described above occurs until the wrapped offset
402  *       is greater than the amount of desired space.
403  *
404  * The wrapped offset is implemented by (re-)using the inactive offset.
405  * In a "switch" buffer policy, the inactive offset stores the offset in
406  * the inactive buffer; in a "ring" buffer policy, it stores the wrapped
407  * offset.
408  *
409  * DTrace Scratch Buffering
410  *
411  * Some ECBs may wish to allocate dynamically-sized temporary scratch memory.
412  * To accommodate such requests easily, scratch memory may be allocated in
413  * the buffer beyond the current offset plus the needed memory of the current
414  * ECB.  If there isn't sufficient room in the buffer for the requested amount
415  * of scratch space, the allocation fails and an error is generated.  Scratch
416  * memory is tracked in the dtrace_mstate_t and is automatically freed when
417  * the ECB ceases processing.  Note that ring buffers cannot allocate their
418  * scratch from the principal buffer -- lest they needlessly overwrite older,
419  * valid data.  Ring buffers therefore have their own dedicated scratch buffer
420  * from which scratch is allocated.
421  */
422 #define	DTRACEBUF_RING		0x0001		/* bufpolicy set to "ring" */
423 #define	DTRACEBUF_FILL		0x0002		/* bufpolicy set to "fill" */
424 #define	DTRACEBUF_NOSWITCH	0x0004		/* do not switch buffer */
425 #define	DTRACEBUF_WRAPPED	0x0008		/* ring buffer has wrapped */
426 #define	DTRACEBUF_DROPPED	0x0010		/* drops occurred */
427 #define	DTRACEBUF_ERROR		0x0020		/* errors occurred */
428 #define	DTRACEBUF_FULL		0x0040		/* "fill" buffer is full */
429 #define	DTRACEBUF_CONSUMED	0x0080		/* buffer has been consumed */
430 #define	DTRACEBUF_INACTIVE	0x0100		/* buffer is not yet active */
431 
432 typedef struct dtrace_buffer {
433 	uint64_t dtb_offset;			/* current offset in buffer */
434 	uint64_t dtb_size;			/* size of buffer */
435 	uint32_t dtb_flags;			/* flags */
436 	uint32_t dtb_drops;			/* number of drops */
437 	caddr_t dtb_tomax;			/* active buffer */
438 	caddr_t dtb_xamot;			/* inactive buffer */
439 	uint32_t dtb_xamot_flags;		/* inactive flags */
440 	uint32_t dtb_xamot_drops;		/* drops in inactive buffer */
441 	uint64_t dtb_xamot_offset;		/* offset in inactive buffer */
442 	uint32_t dtb_errors;			/* number of errors */
443 	uint32_t dtb_xamot_errors;		/* errors in inactive buffer */
444 #ifndef _LP64
445 	uint64_t dtb_pad1;			/* pad out to 64 bytes */
446 #endif
447 	uint64_t dtb_switched;			/* time of last switch */
448 	uint64_t dtb_interval;			/* observed switch interval */
449 	uint64_t dtb_pad2[6];			/* pad to avoid false sharing */
450 } dtrace_buffer_t;
451 
452 /*
453  * DTrace Aggregation Buffers
454  *
455  * Aggregation buffers use much of the same mechanism as described above
456  * ("DTrace Buffers").  However, because an aggregation is fundamentally a
457  * hash, there exists dynamic metadata associated with an aggregation buffer
458  * that is not associated with other kinds of buffers.  This aggregation
459  * metadata is _only_ relevant for the in-kernel implementation of
460  * aggregations; it is not actually relevant to user-level consumers.  To do
461  * this, we allocate dynamic aggregation data (hash keys and hash buckets)
462  * starting below the _limit_ of the buffer, and we allocate data from the
463  * _base_ of the buffer.  When the aggregation buffer is copied out, _only_ the
464  * data is copied out; the metadata is simply discarded.  Schematically,
465  * aggregation buffers look like:
466  *
467  *      base of data buffer --->  +-------+------+-----------+-------+
468  *                                | aggid | key  | value     | aggid |
469  *                                +-------+------+-----------+-------+
470  *                                | key                              |
471  *                                +-------+-------+-----+------------+
472  *                                | value | aggid | key | value      |
473  *                                +-------+------++-----+------+-----+
474  *                                | aggid | key  | value       |     |
475  *                                +-------+------+-------------+     |
476  *                                |                ||                |
477  *                                |                ||                |
478  *                                |                \/                |
479  *                                :                                  :
480  *                                .                                  .
481  *                                .                                  .
482  *                                .                                  .
483  *                                :                                  :
484  *                                |                /\                |
485  *                                |                ||   +------------+
486  *                                |                ||   |            |
487  *                                +---------------------+            |
488  *                                | hash keys                        |
489  *                                | (dtrace_aggkey structures)       |
490  *                                |                                  |
491  *                                +----------------------------------+
492  *                                | hash buckets                     |
493  *                                | (dtrace_aggbuffer structure)     |
494  *                                |                                  |
495  *     limit of data buffer --->  +----------------------------------+
496  *
497  *
498  * As implied above, just as we assure that ECBs always store a constant
499  * amount of data, we assure that a given aggregation -- identified by its
500  * aggregation ID -- always stores data of a constant quantity and type.
501  * As with EPIDs, this allows the aggregation ID to serve as the metadata for a
502  * given record.
503  *
504  * Note that the size of the dtrace_aggkey structure must be sizeof (uintptr_t)
505  * aligned.  (If this the structure changes such that this becomes false, an
506  * assertion will fail in dtrace_aggregate().)
507  */
508 typedef struct dtrace_aggkey {
509 	uint32_t dtak_hashval;			/* hash value */
510 	uint32_t dtak_action:4;			/* action -- 4 bits */
511 	uint32_t dtak_size:28;			/* size -- 28 bits */
512 	caddr_t dtak_data;			/* data pointer */
513 	struct dtrace_aggkey *dtak_next;	/* next in hash chain */
514 } dtrace_aggkey_t;
515 
516 typedef struct dtrace_aggbuffer {
517 	uintptr_t dtagb_hashsize;		/* number of buckets */
518 	uintptr_t dtagb_free;			/* free list of keys */
519 	dtrace_aggkey_t **dtagb_hash;		/* hash table */
520 } dtrace_aggbuffer_t;
521 
522 /*
523  * DTrace Speculations
524  *
525  * Speculations have a per-CPU buffer and a global state.  Once a speculation
526  * buffer has been comitted or discarded, it cannot be reused until all CPUs
527  * have taken the same action (commit or discard) on their respective
528  * speculative buffer.  However, because DTrace probes may execute in arbitrary
529  * context, other CPUs cannot simply be cross-called at probe firing time to
530  * perform the necessary commit or discard.  The speculation states thus
531  * optimize for the case that a speculative buffer is only active on one CPU at
532  * the time of a commit() or discard() -- for if this is the case, other CPUs
533  * need not take action, and the speculation is immediately available for
534  * reuse.  If the speculation is active on multiple CPUs, it must be
535  * asynchronously cleaned -- potentially leading to a higher rate of dirty
536  * speculative drops.  The speculation states are as follows:
537  *
538  *  DTRACESPEC_INACTIVE       <= Initial state; inactive speculation
539  *  DTRACESPEC_ACTIVE         <= Allocated, but not yet speculatively traced to
540  *  DTRACESPEC_ACTIVEONE      <= Speculatively traced to on one CPU
541  *  DTRACESPEC_ACTIVEMANY     <= Speculatively traced to on more than one CPU
542  *  DTRACESPEC_COMMITTING     <= Currently being commited on one CPU
543  *  DTRACESPEC_COMMITTINGMANY <= Currently being commited on many CPUs
544  *  DTRACESPEC_DISCARDING     <= Currently being discarded on many CPUs
545  *
546  * The state transition diagram is as follows:
547  *
548  *     +----------------------------------------------------------+
549  *     |                                                          |
550  *     |                      +------------+                      |
551  *     |  +-------------------| COMMITTING |<-----------------+   |
552  *     |  |                   +------------+                  |   |
553  *     |  | copied spec.            ^             commit() on |   | discard() on
554  *     |  | into principal          |              active CPU |   | active CPU
555  *     |  |                         | commit()                |   |
556  *     V  V                         |                         |   |
557  * +----------+                 +--------+                +-----------+
558  * | INACTIVE |---------------->| ACTIVE |--------------->| ACTIVEONE |
559  * +----------+  speculation()  +--------+  speculate()   +-----------+
560  *     ^  ^                         |                         |   |
561  *     |  |                         | discard()               |   |
562  *     |  | asynchronously          |            discard() on |   | speculate()
563  *     |  | cleaned                 V            inactive CPU |   | on inactive
564  *     |  |                   +------------+                  |   | CPU
565  *     |  +-------------------| DISCARDING |<-----------------+   |
566  *     |                      +------------+                      |
567  *     | asynchronously             ^                             |
568  *     | copied spec.               |       discard()             |
569  *     | into principal             +------------------------+    |
570  *     |                                                     |    V
571  *  +----------------+             commit()              +------------+
572  *  | COMMITTINGMANY |<----------------------------------| ACTIVEMANY |
573  *  +----------------+                                   +------------+
574  */
575 typedef enum dtrace_speculation_state {
576 	DTRACESPEC_INACTIVE = 0,
577 	DTRACESPEC_ACTIVE,
578 	DTRACESPEC_ACTIVEONE,
579 	DTRACESPEC_ACTIVEMANY,
580 	DTRACESPEC_COMMITTING,
581 	DTRACESPEC_COMMITTINGMANY,
582 	DTRACESPEC_DISCARDING
583 } dtrace_speculation_state_t;
584 
585 typedef struct dtrace_speculation {
586 	dtrace_speculation_state_t dtsp_state;	/* current speculation state */
587 	int dtsp_cleaning;			/* non-zero if being cleaned */
588 	dtrace_buffer_t *dtsp_buffer;		/* speculative buffer */
589 } dtrace_speculation_t;
590 
591 /*
592  * DTrace Dynamic Variables
593  *
594  * The dynamic variable problem is obviously decomposed into two subproblems:
595  * allocating new dynamic storage, and freeing old dynamic storage.  The
596  * presence of the second problem makes the first much more complicated -- or
597  * rather, the absence of the second renders the first trivial.  This is the
598  * case with aggregations, for which there is effectively no deallocation of
599  * dynamic storage.  (Or more accurately, all dynamic storage is deallocated
600  * when a snapshot is taken of the aggregation.)  As DTrace dynamic variables
601  * allow for both dynamic allocation and dynamic deallocation, the
602  * implementation of dynamic variables is quite a bit more complicated than
603  * that of their aggregation kin.
604  *
605  * We observe that allocating new dynamic storage is tricky only because the
606  * size can vary -- the allocation problem is much easier if allocation sizes
607  * are uniform.  We further observe that in D, the size of dynamic variables is
608  * actually _not_ dynamic -- dynamic variable sizes may be determined by static
609  * analysis of DIF text.  (This is true even of putatively dynamically-sized
610  * objects like strings and stacks, the sizes of which are dictated by the
611  * "stringsize" and "stackframes" variables, respectively.)  We exploit this by
612  * performing this analysis on all DIF before enabling any probes.  For each
613  * dynamic load or store, we calculate the dynamically-allocated size plus the
614  * size of the dtrace_dynvar structure plus the storage required to key the
615  * data.  For all DIF, we take the largest value and dub it the _chunksize_.
616  * We then divide dynamic memory into two parts:  a hash table that is wide
617  * enough to have every chunk in its own bucket, and a larger region of equal
618  * chunksize units.  Whenever we wish to dynamically allocate a variable, we
619  * always allocate a single chunk of memory.  Depending on the uniformity of
620  * allocation, this will waste some amount of memory -- but it eliminates the
621  * non-determinism inherent in traditional heap fragmentation.
622  *
623  * Dynamic objects are allocated by storing a non-zero value to them; they are
624  * deallocated by storing a zero value to them.  Dynamic variables are
625  * complicated enormously by being shared between CPUs.  In particular,
626  * consider the following scenario:
627  *
628  *                 CPU A                                 CPU B
629  *  +---------------------------------+   +---------------------------------+
630  *  |                                 |   |                                 |
631  *  | allocates dynamic object a[123] |   |                                 |
632  *  | by storing the value 345 to it  |   |                                 |
633  *  |                               --------->                              |
634  *  |                                 |   | wishing to load from object     |
635  *  |                                 |   | a[123], performs lookup in      |
636  *  |                                 |   | dynamic variable space          |
637  *  |                               <---------                              |
638  *  | deallocates object a[123] by    |   |                                 |
639  *  | storing 0 to it                 |   |                                 |
640  *  |                                 |   |                                 |
641  *  | allocates dynamic object b[567] |   | performs load from a[123]       |
642  *  | by storing the value 789 to it  |   |                                 |
643  *  :                                 :   :                                 :
644  *  .                                 .   .                                 .
645  *
646  * This is obviously a race in the D program, but there are nonetheless only
647  * two valid values for CPU B's load from a[123]:  345 or 0.  Most importantly,
648  * CPU B may _not_ see the value 789 for a[123].
649  *
650  * There are essentially two ways to deal with this:
651  *
652  *  (1)  Explicitly spin-lock variables.  That is, if CPU B wishes to load
653  *       from a[123], it needs to lock a[123] and hold the lock for the
654  *       duration that it wishes to manipulate it.
655  *
656  *  (2)  Avoid reusing freed chunks until it is known that no CPU is referring
657  *       to them.
658  *
659  * The implementation of (1) is rife with complexity, because it requires the
660  * user of a dynamic variable to explicitly decree when they are done using it.
661  * Were all variables by value, this perhaps wouldn't be debilitating -- but
662  * dynamic variables of non-scalar types are tracked by reference.  That is, if
663  * a dynamic variable is, say, a string, and that variable is to be traced to,
664  * say, the principal buffer, the DIF emulation code returns to the main
665  * dtrace_probe() loop a pointer to the underlying storage, not the contents of
666  * the storage.  Further, code calling on DIF emulation would have to be aware
667  * that the DIF emulation has returned a reference to a dynamic variable that
668  * has been potentially locked.  The variable would have to be unlocked after
669  * the main dtrace_probe() loop is finished with the variable, and the main
670  * dtrace_probe() loop would have to be careful to not call any further DIF
671  * emulation while the variable is locked to avoid deadlock.  More generally,
672  * if one were to implement (1), DIF emulation code dealing with dynamic
673  * variables could only deal with one dynamic variable at a time (lest deadlock
674  * result).  To sum, (1) exports too much subtlety to the users of dynamic
675  * variables -- increasing maintenance burden and imposing serious constraints
676  * on future DTrace development.
677  *
678  * The implementation of (2) is also complex, but the complexity is more
679  * manageable.  We need to be sure that when a variable is deallocated, it is
680  * not placed on a traditional free list, but rather on a _dirty_ list.  Once a
681  * variable is on a dirty list, it cannot be found by CPUs performing a
682  * subsequent lookup of the variable -- but it may still be in use by other
683  * CPUs.  To assure that all CPUs that may be seeing the old variable have
684  * cleared out of probe context, a dtrace_sync() can be issued.  Once the
685  * dtrace_sync() has completed, it can be known that all CPUs are done
686  * manipulating the dynamic variable -- the dirty list can be atomically
687  * appended to the free list.  Unfortunately, there's a slight hiccup in this
688  * mechanism:  dtrace_sync() may not be issued from probe context.  The
689  * dtrace_sync() must be therefore issued asynchronously from non-probe
690  * context.  For this we rely on the DTrace cleaner, a cyclic that runs at the
691  * "cleanrate" frequency.  To ease this implementation, we define several chunk
692  * lists:
693  *
694  *   - Dirty.  Deallocated chunks, not yet cleaned.  Not available.
695  *
696  *   - Rinsing.  Formerly dirty chunks that are currently being asynchronously
697  *     cleaned.  Not available, but will be shortly.  Dynamic variable
698  *     allocation may not spin or block for availability, however.
699  *
700  *   - Clean.  Clean chunks, ready for allocation -- but not on the free list.
701  *
702  *   - Free.  Available for allocation.
703  *
704  * Moreover, to avoid absurd contention, _each_ of these lists is implemented
705  * on a per-CPU basis.  This is only for performance, not correctness; chunks
706  * may be allocated from another CPU's free list.  The algorithm for allocation
707  * then is this:
708  *
709  *   (1)  Attempt to atomically allocate from current CPU's free list.  If list
710  *        is non-empty and allocation is successful, allocation is complete.
711  *
712  *   (2)  If the clean list is non-empty, atomically move it to the free list,
713  *        and reattempt (1).
714  *
715  *   (3)  If the dynamic variable space is in the CLEAN state, look for free
716  *        and clean lists on other CPUs by setting the current CPU to the next
717  *        CPU, and reattempting (1).  If the next CPU is the current CPU (that
718  *        is, if all CPUs have been checked), atomically switch the state of
719  *        the dynamic variable space based on the following:
720  *
721  *        - If no free chunks were found and no dirty chunks were found,
722  *          atomically set the state to EMPTY.
723  *
724  *        - If dirty chunks were found, atomically set the state to DIRTY.
725  *
726  *        - If rinsing chunks were found, atomically set the state to RINSING.
727  *
728  *   (4)  Based on state of dynamic variable space state, increment appropriate
729  *        counter to indicate dynamic drops (if in EMPTY state) vs. dynamic
730  *        dirty drops (if in DIRTY state) vs. dynamic rinsing drops (if in
731  *        RINSING state).  Fail the allocation.
732  *
733  * The cleaning cyclic operates with the following algorithm:  for all CPUs
734  * with a non-empty dirty list, atomically move the dirty list to the rinsing
735  * list.  Perform a dtrace_sync().  For all CPUs with a non-empty rinsing list,
736  * atomically move the rinsing list to the clean list.  Perform another
737  * dtrace_sync().  By this point, all CPUs have seen the new clean list; the
738  * state of the dynamic variable space can be restored to CLEAN.
739  *
740  * There exist two final races that merit explanation.  The first is a simple
741  * allocation race:
742  *
743  *                 CPU A                                 CPU B
744  *  +---------------------------------+   +---------------------------------+
745  *  |                                 |   |                                 |
746  *  | allocates dynamic object a[123] |   | allocates dynamic object a[123] |
747  *  | by storing the value 345 to it  |   | by storing the value 567 to it  |
748  *  |                                 |   |                                 |
749  *  :                                 :   :                                 :
750  *  .                                 .   .                                 .
751  *
752  * Again, this is a race in the D program.  It can be resolved by having a[123]
753  * hold the value 345 or a[123] hold the value 567 -- but it must be true that
754  * a[123] have only _one_ of these values.  (That is, the racing CPUs may not
755  * put the same element twice on the same hash chain.)  This is resolved
756  * simply:  before the allocation is undertaken, the start of the new chunk's
757  * hash chain is noted.  Later, after the allocation is complete, the hash
758  * chain is atomically switched to point to the new element.  If this fails
759  * (because of either concurrent allocations or an allocation concurrent with a
760  * deletion), the newly allocated chunk is deallocated to the dirty list, and
761  * the whole process of looking up (and potentially allocating) the dynamic
762  * variable is reattempted.
763  *
764  * The final race is a simple deallocation race:
765  *
766  *                 CPU A                                 CPU B
767  *  +---------------------------------+   +---------------------------------+
768  *  |                                 |   |                                 |
769  *  | deallocates dynamic object      |   | deallocates dynamic object      |
770  *  | a[123] by storing the value 0   |   | a[123] by storing the value 0   |
771  *  | to it                           |   | to it                           |
772  *  |                                 |   |                                 |
773  *  :                                 :   :                                 :
774  *  .                                 .   .                                 .
775  *
776  * Once again, this is a race in the D program, but it is one that we must
777  * handle without corrupting the underlying data structures.  Because
778  * deallocations require the deletion of a chunk from the middle of a hash
779  * chain, we cannot use a single-word atomic operation to remove it.  For this,
780  * we add a spin lock to the hash buckets that is _only_ used for deallocations
781  * (allocation races are handled as above).  Further, this spin lock is _only_
782  * held for the duration of the delete; before control is returned to the DIF
783  * emulation code, the hash bucket is unlocked.
784  */
785 typedef struct dtrace_key {
786 	uint64_t dttk_value;			/* data value or data pointer */
787 	uint64_t dttk_size;			/* 0 if by-val, >0 if by-ref */
788 } dtrace_key_t;
789 
790 typedef struct dtrace_tuple {
791 	uint32_t dtt_nkeys;			/* number of keys in tuple */
792 	uint32_t dtt_pad;			/* padding */
793 	dtrace_key_t dtt_key[1];		/* array of tuple keys */
794 } dtrace_tuple_t;
795 
796 typedef struct dtrace_dynvar {
797 	uint64_t dtdv_hashval;			/* hash value -- 0 if free */
798 	struct dtrace_dynvar *dtdv_next;	/* next on list or hash chain */
799 	void *dtdv_data;			/* pointer to data */
800 	dtrace_tuple_t dtdv_tuple;		/* tuple key */
801 } dtrace_dynvar_t;
802 
803 typedef enum dtrace_dynvar_op {
804 	DTRACE_DYNVAR_ALLOC,
805 	DTRACE_DYNVAR_NOALLOC,
806 	DTRACE_DYNVAR_DEALLOC
807 } dtrace_dynvar_op_t;
808 
809 typedef struct dtrace_dynhash {
810 	dtrace_dynvar_t *dtdh_chain;		/* hash chain for this bucket */
811 	uintptr_t dtdh_lock;			/* deallocation lock */
812 #ifdef _LP64
813 	uintptr_t dtdh_pad[6];			/* pad to avoid false sharing */
814 #else
815 	uintptr_t dtdh_pad[14];			/* pad to avoid false sharing */
816 #endif
817 } dtrace_dynhash_t;
818 
819 typedef struct dtrace_dstate_percpu {
820 	dtrace_dynvar_t *dtdsc_free;		/* free list for this CPU */
821 	dtrace_dynvar_t *dtdsc_dirty;		/* dirty list for this CPU */
822 	dtrace_dynvar_t *dtdsc_rinsing;		/* rinsing list for this CPU */
823 	dtrace_dynvar_t *dtdsc_clean;		/* clean list for this CPU */
824 	uint64_t dtdsc_drops;			/* number of capacity drops */
825 	uint64_t dtdsc_dirty_drops;		/* number of dirty drops */
826 	uint64_t dtdsc_rinsing_drops;		/* number of rinsing drops */
827 #ifdef _LP64
828 	uint64_t dtdsc_pad;			/* pad to avoid false sharing */
829 #else
830 	uint64_t dtdsc_pad[2];			/* pad to avoid false sharing */
831 #endif
832 } dtrace_dstate_percpu_t;
833 
834 typedef enum dtrace_dstate_state {
835 	DTRACE_DSTATE_CLEAN = 0,
836 	DTRACE_DSTATE_EMPTY,
837 	DTRACE_DSTATE_DIRTY,
838 	DTRACE_DSTATE_RINSING
839 } dtrace_dstate_state_t;
840 
841 typedef struct dtrace_dstate {
842 	void *dtds_base;			/* base of dynamic var. space */
843 	size_t dtds_size;			/* size of dynamic var. space */
844 	size_t dtds_hashsize;			/* number of buckets in hash */
845 	size_t dtds_chunksize;			/* size of each chunk */
846 	dtrace_dynhash_t *dtds_hash;		/* pointer to hash table */
847 	dtrace_dstate_state_t dtds_state;	/* current dynamic var. state */
848 	dtrace_dstate_percpu_t *dtds_percpu;	/* per-CPU dyn. var. state */
849 } dtrace_dstate_t;
850 
851 /*
852  * DTrace Variable State
853  *
854  * The DTrace variable state tracks user-defined variables in its dtrace_vstate
855  * structure.  Each DTrace consumer has exactly one dtrace_vstate structure,
856  * but some dtrace_vstate structures may exist without a corresponding DTrace
857  * consumer (see "DTrace Helpers", below).  As described in <sys/dtrace.h>,
858  * user-defined variables can have one of three scopes:
859  *
860  *  DIFV_SCOPE_GLOBAL  =>  global scope
861  *  DIFV_SCOPE_THREAD  =>  thread-local scope (i.e. "self->" variables)
862  *  DIFV_SCOPE_LOCAL   =>  clause-local scope (i.e. "this->" variables)
863  *
864  * The variable state tracks variables by both their scope and their allocation
865  * type:
866  *
867  *  - The dtvs_globals and dtvs_locals members each point to an array of
868  *    dtrace_statvar structures.  These structures contain both the variable
869  *    metadata (dtrace_difv structures) and the underlying storage for all
870  *    statically allocated variables, including statically allocated
871  *    DIFV_SCOPE_GLOBAL variables and all DIFV_SCOPE_LOCAL variables.
872  *
873  *  - The dtvs_tlocals member points to an array of dtrace_difv structures for
874  *    DIFV_SCOPE_THREAD variables.  As such, this array tracks _only_ the
875  *    variable metadata for DIFV_SCOPE_THREAD variables; the underlying storage
876  *    is allocated out of the dynamic variable space.
877  *
878  *  - The dtvs_dynvars member is the dynamic variable state associated with the
879  *    variable state.  The dynamic variable state (described in "DTrace Dynamic
880  *    Variables", above) tracks all DIFV_SCOPE_THREAD variables and all
881  *    dynamically-allocated DIFV_SCOPE_GLOBAL variables.
882  */
883 typedef struct dtrace_statvar {
884 	uint64_t dtsv_data;			/* data or pointer to it */
885 	size_t dtsv_size;			/* size of pointed-to data */
886 	int dtsv_refcnt;			/* reference count */
887 	dtrace_difv_t dtsv_var;			/* variable metadata */
888 } dtrace_statvar_t;
889 
890 typedef struct dtrace_vstate {
891 	dtrace_state_t *dtvs_state;		/* back pointer to state */
892 	dtrace_statvar_t **dtvs_globals;	/* statically-allocated glbls */
893 	int dtvs_nglobals;			/* number of globals */
894 	dtrace_difv_t *dtvs_tlocals;		/* thread-local metadata */
895 	int dtvs_ntlocals;			/* number of thread-locals */
896 	dtrace_statvar_t **dtvs_locals;		/* clause-local data */
897 	int dtvs_nlocals;			/* number of clause-locals */
898 	dtrace_dstate_t dtvs_dynvars;		/* dynamic variable state */
899 } dtrace_vstate_t;
900 
901 /*
902  * DTrace Machine State
903  *
904  * In the process of processing a fired probe, DTrace needs to track and/or
905  * cache some per-CPU state associated with that particular firing.  This is
906  * state that is always discarded after the probe firing has completed, and
907  * much of it is not specific to any DTrace consumer, remaining valid across
908  * all ECBs.  This state is tracked in the dtrace_mstate structure.
909  */
910 #define	DTRACE_MSTATE_ARGS		0x00000001
911 #define	DTRACE_MSTATE_PROBE		0x00000002
912 #define	DTRACE_MSTATE_EPID		0x00000004
913 #define	DTRACE_MSTATE_TIMESTAMP		0x00000008
914 #define	DTRACE_MSTATE_STACKDEPTH	0x00000010
915 #define	DTRACE_MSTATE_CALLER		0x00000020
916 #define	DTRACE_MSTATE_IPL		0x00000040
917 #define	DTRACE_MSTATE_FLTOFFS		0x00000080
918 #define	DTRACE_MSTATE_WALLTIMESTAMP	0x00000100
919 #define	DTRACE_MSTATE_USTACKDEPTH	0x00000200
920 #define	DTRACE_MSTATE_UCALLER		0x00000400
921 
922 typedef struct dtrace_mstate {
923 	uintptr_t dtms_scratch_base;		/* base of scratch space */
924 	uintptr_t dtms_scratch_ptr;		/* current scratch pointer */
925 	size_t dtms_scratch_size;		/* scratch size */
926 	uint32_t dtms_present;			/* variables that are present */
927 	uint64_t dtms_arg[5];			/* cached arguments */
928 	dtrace_epid_t dtms_epid;		/* current EPID */
929 	uint64_t dtms_timestamp;		/* cached timestamp */
930 	hrtime_t dtms_walltimestamp;		/* cached wall timestamp */
931 	int dtms_stackdepth;			/* cached stackdepth */
932 	int dtms_ustackdepth;			/* cached ustackdepth */
933 	struct dtrace_probe *dtms_probe;	/* current probe */
934 	uintptr_t dtms_caller;			/* cached caller */
935 	uint64_t dtms_ucaller;			/* cached user-level caller */
936 	int dtms_ipl;				/* cached interrupt pri lev */
937 	int dtms_fltoffs;			/* faulting DIFO offset */
938 	uintptr_t dtms_strtok;			/* saved strtok() pointer */
939 	uintptr_t dtms_strtok_limit;		/* upper bound of strtok ptr */
940 	uint32_t dtms_access;			/* memory access rights */
941 	dtrace_difo_t *dtms_difo;		/* current dif object */
942 	file_t *dtms_getf;			/* cached rval of getf() */
943 } dtrace_mstate_t;
944 
945 #define	DTRACE_COND_OWNER	0x1
946 #define	DTRACE_COND_USERMODE	0x2
947 #define	DTRACE_COND_ZONEOWNER	0x4
948 
949 #define	DTRACE_PROBEKEY_MAXDEPTH	8	/* max glob recursion depth */
950 
951 /*
952  * Access flag used by dtrace_mstate.dtms_access.
953  */
954 #define	DTRACE_ACCESS_KERNEL	0x1		/* the priv to read kmem */
955 
956 
957 /*
958  * DTrace Activity
959  *
960  * Each DTrace consumer is in one of several states, which (for purposes of
961  * avoiding yet-another overloading of the noun "state") we call the current
962  * _activity_.  The activity transitions on dtrace_go() (from DTRACIOCGO), on
963  * dtrace_stop() (from DTRACIOCSTOP) and on the exit() action.  Activities may
964  * only transition in one direction; the activity transition diagram is a
965  * directed acyclic graph.  The activity transition diagram is as follows:
966  *
967  *
968  * +----------+                   +--------+                   +--------+
969  * | INACTIVE |------------------>| WARMUP |------------------>| ACTIVE |
970  * +----------+   dtrace_go(),    +--------+   dtrace_go(),    +--------+
971  *                before BEGIN        |        after BEGIN       |  |  |
972  *                                    |                          |  |  |
973  *                      exit() action |                          |  |  |
974  *                     from BEGIN ECB |                          |  |  |
975  *                                    |                          |  |  |
976  *                                    v                          |  |  |
977  *                               +----------+     exit() action  |  |  |
978  * +-----------------------------| DRAINING |<-------------------+  |  |
979  * |                             +----------+                       |  |
980  * |                                  |                             |  |
981  * |                   dtrace_stop(), |                             |  |
982  * |                     before END   |                             |  |
983  * |                                  |                             |  |
984  * |                                  v                             |  |
985  * | +---------+                 +----------+                       |  |
986  * | | STOPPED |<----------------| COOLDOWN |<----------------------+  |
987  * | +---------+  dtrace_stop(), +----------+     dtrace_stop(),       |
988  * |                after END                       before END         |
989  * |                                                                   |
990  * |                              +--------+                           |
991  * +----------------------------->| KILLED |<--------------------------+
992  *       deadman timeout or       +--------+     deadman timeout or
993  *        killed consumer                         killed consumer
994  *
995  * Note that once a DTrace consumer has stopped tracing, there is no way to
996  * restart it; if a DTrace consumer wishes to restart tracing, it must reopen
997  * the DTrace pseudodevice.
998  */
999 typedef enum dtrace_activity {
1000 	DTRACE_ACTIVITY_INACTIVE = 0,		/* not yet running */
1001 	DTRACE_ACTIVITY_WARMUP,			/* while starting */
1002 	DTRACE_ACTIVITY_ACTIVE,			/* running */
1003 	DTRACE_ACTIVITY_DRAINING,		/* before stopping */
1004 	DTRACE_ACTIVITY_COOLDOWN,		/* while stopping */
1005 	DTRACE_ACTIVITY_STOPPED,		/* after stopping */
1006 	DTRACE_ACTIVITY_KILLED			/* killed */
1007 } dtrace_activity_t;
1008 
1009 /*
1010  * DTrace Helper Implementation
1011  *
1012  * A description of the helper architecture may be found in <sys/dtrace.h>.
1013  * Each process contains a pointer to its helpers in its p_dtrace_helpers
1014  * member.  This is a pointer to a dtrace_helpers structure, which contains an
1015  * array of pointers to dtrace_helper structures, helper variable state (shared
1016  * among a process's helpers) and a generation count.  (The generation count is
1017  * used to provide an identifier when a helper is added so that it may be
1018  * subsequently removed.)  The dtrace_helper structure is self-explanatory,
1019  * containing pointers to the objects needed to execute the helper.  Note that
1020  * helpers are _duplicated_ across fork(2), and destroyed on exec(2).  No more
1021  * than dtrace_helpers_max are allowed per-process.
1022  */
1023 #define	DTRACE_HELPER_ACTION_USTACK	0
1024 #define	DTRACE_NHELPER_ACTIONS		1
1025 
1026 typedef struct dtrace_helper_action {
1027 	int dtha_generation;			/* helper action generation */
1028 	int dtha_nactions;			/* number of actions */
1029 	dtrace_difo_t *dtha_predicate;		/* helper action predicate */
1030 	dtrace_difo_t **dtha_actions;		/* array of actions */
1031 	struct dtrace_helper_action *dtha_next;	/* next helper action */
1032 } dtrace_helper_action_t;
1033 
1034 typedef struct dtrace_helper_provider {
1035 	int dthp_generation;			/* helper provider generation */
1036 	uint32_t dthp_ref;			/* reference count */
1037 	dof_helper_t dthp_prov;			/* DOF w/ provider and probes */
1038 } dtrace_helper_provider_t;
1039 
1040 typedef struct dtrace_helpers {
1041 	dtrace_helper_action_t **dthps_actions;	/* array of helper actions */
1042 	dtrace_vstate_t dthps_vstate;		/* helper action var. state */
1043 	dtrace_helper_provider_t **dthps_provs;	/* array of providers */
1044 	uint_t dthps_nprovs;			/* count of providers */
1045 	uint_t dthps_maxprovs;			/* provider array size */
1046 	int dthps_generation;			/* current generation */
1047 	pid_t dthps_pid;			/* pid of associated proc */
1048 	int dthps_deferred;			/* helper in deferred list */
1049 	struct dtrace_helpers *dthps_next;	/* next pointer */
1050 	struct dtrace_helpers *dthps_prev;	/* prev pointer */
1051 } dtrace_helpers_t;
1052 
1053 /*
1054  * DTrace Helper Action Tracing
1055  *
1056  * Debugging helper actions can be arduous.  To ease the development and
1057  * debugging of helpers, DTrace contains a tracing-framework-within-a-tracing-
1058  * framework: helper tracing.  If dtrace_helptrace_enabled is non-zero (which
1059  * it is by default on DEBUG kernels), all helper activity will be traced to a
1060  * global, in-kernel ring buffer.  Each entry includes a pointer to the specific
1061  * helper, the location within the helper, and a trace of all local variables.
1062  * The ring buffer may be displayed in a human-readable format with the
1063  * ::dtrace_helptrace mdb(1) dcmd.
1064  */
1065 #define	DTRACE_HELPTRACE_NEXT	(-1)
1066 #define	DTRACE_HELPTRACE_DONE	(-2)
1067 #define	DTRACE_HELPTRACE_ERR	(-3)
1068 
1069 typedef struct dtrace_helptrace {
1070 	dtrace_helper_action_t	*dtht_helper;	/* helper action */
1071 	int dtht_where;				/* where in helper action */
1072 	int dtht_nlocals;			/* number of locals */
1073 	int dtht_fault;				/* type of fault (if any) */
1074 	int dtht_fltoffs;			/* DIF offset */
1075 	uint64_t dtht_illval;			/* faulting value */
1076 	uint64_t dtht_locals[1];		/* local variables */
1077 } dtrace_helptrace_t;
1078 
1079 /*
1080  * DTrace Credentials
1081  *
1082  * In probe context, we have limited flexibility to examine the credentials
1083  * of the DTrace consumer that created a particular enabling.  We use
1084  * the Least Privilege interfaces to cache the consumer's cred pointer and
1085  * some facts about that credential in a dtrace_cred_t structure. These
1086  * can limit the consumer's breadth of visibility and what actions the
1087  * consumer may take.
1088  */
1089 #define	DTRACE_CRV_ALLPROC		0x01
1090 #define	DTRACE_CRV_KERNEL		0x02
1091 #define	DTRACE_CRV_ALLZONE		0x04
1092 
1093 #define	DTRACE_CRV_ALL		(DTRACE_CRV_ALLPROC | DTRACE_CRV_KERNEL | \
1094 	DTRACE_CRV_ALLZONE)
1095 
1096 #define	DTRACE_CRA_PROC				0x0001
1097 #define	DTRACE_CRA_PROC_CONTROL			0x0002
1098 #define	DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER	0x0004
1099 #define	DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE	0x0008
1100 #define	DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG	0x0010
1101 #define	DTRACE_CRA_KERNEL			0x0020
1102 #define	DTRACE_CRA_KERNEL_DESTRUCTIVE		0x0040
1103 
1104 #define	DTRACE_CRA_ALL		(DTRACE_CRA_PROC | \
1105 	DTRACE_CRA_PROC_CONTROL | \
1106 	DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER | \
1107 	DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE | \
1108 	DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG | \
1109 	DTRACE_CRA_KERNEL | \
1110 	DTRACE_CRA_KERNEL_DESTRUCTIVE)
1111 
1112 typedef struct dtrace_cred {
1113 	cred_t			*dcr_cred;
1114 	uint8_t			dcr_destructive;
1115 	uint8_t			dcr_visible;
1116 	uint16_t		dcr_action;
1117 } dtrace_cred_t;
1118 
1119 /*
1120  * DTrace Consumer State
1121  *
1122  * Each DTrace consumer has an associated dtrace_state structure that contains
1123  * its in-kernel DTrace state -- including options, credentials, statistics and
1124  * pointers to ECBs, buffers, speculations and formats.  A dtrace_state
1125  * structure is also allocated for anonymous enablings.  When anonymous state
1126  * is grabbed, the grabbing consumers dts_anon pointer is set to the grabbed
1127  * dtrace_state structure.
1128  */
1129 struct dtrace_state {
1130 #ifdef illumos
1131 	dev_t dts_dev;				/* device */
1132 #else
1133 	struct cdev *dts_dev;			/* device */
1134 #endif
1135 	int dts_necbs;				/* total number of ECBs */
1136 	dtrace_ecb_t **dts_ecbs;		/* array of ECBs */
1137 	dtrace_epid_t dts_epid;			/* next EPID to allocate */
1138 	size_t dts_needed;			/* greatest needed space */
1139 	struct dtrace_state *dts_anon;		/* anon. state, if grabbed */
1140 	dtrace_activity_t dts_activity;		/* current activity */
1141 	dtrace_vstate_t dts_vstate;		/* variable state */
1142 	dtrace_buffer_t *dts_buffer;		/* principal buffer */
1143 	dtrace_buffer_t *dts_aggbuffer;		/* aggregation buffer */
1144 	dtrace_speculation_t *dts_speculations;	/* speculation array */
1145 	int dts_nspeculations;			/* number of speculations */
1146 	int dts_naggregations;			/* number of aggregations */
1147 	dtrace_aggregation_t **dts_aggregations; /* aggregation array */
1148 #ifdef illumos
1149 	vmem_t *dts_aggid_arena;		/* arena for aggregation IDs */
1150 #else
1151 	struct unrhdr *dts_aggid_arena;		/* arena for aggregation IDs */
1152 #endif
1153 	uint64_t dts_errors;			/* total number of errors */
1154 	uint32_t dts_speculations_busy;		/* number of spec. busy */
1155 	uint32_t dts_speculations_unavail;	/* number of spec unavail */
1156 	uint32_t dts_stkstroverflows;		/* stack string tab overflows */
1157 	uint32_t dts_dblerrors;			/* errors in ERROR probes */
1158 	uint32_t dts_reserve;			/* space reserved for END */
1159 	hrtime_t dts_laststatus;		/* time of last status */
1160 #ifdef illumos
1161 	cyclic_id_t dts_cleaner;		/* cleaning cyclic */
1162 	cyclic_id_t dts_deadman;		/* deadman cyclic */
1163 #else
1164 	struct callout dts_cleaner;		/* Cleaning callout. */
1165 	struct callout dts_deadman;		/* Deadman callout. */
1166 #endif
1167 	hrtime_t dts_alive;			/* time last alive */
1168 	char dts_speculates;			/* boolean: has speculations */
1169 	char dts_destructive;			/* boolean: has dest. actions */
1170 	int dts_nformats;			/* number of formats */
1171 	char **dts_formats;			/* format string array */
1172 	dtrace_optval_t dts_options[DTRACEOPT_MAX]; /* options */
1173 	dtrace_cred_t dts_cred;			/* credentials */
1174 	size_t dts_nretained;			/* number of retained enabs */
1175 	int dts_getf;				/* number of getf() calls */
1176 	uint64_t dts_rstate[NCPU][2];		/* per-CPU random state */
1177 };
1178 
1179 struct dtrace_provider {
1180 	dtrace_pattr_t dtpv_attr;		/* provider attributes */
1181 	dtrace_ppriv_t dtpv_priv;		/* provider privileges */
1182 	dtrace_pops_t dtpv_pops;		/* provider operations */
1183 	char *dtpv_name;			/* provider name */
1184 	void *dtpv_arg;				/* provider argument */
1185 	hrtime_t dtpv_defunct;			/* when made defunct */
1186 	struct dtrace_provider *dtpv_next;	/* next provider */
1187 };
1188 
1189 struct dtrace_meta {
1190 	dtrace_mops_t dtm_mops;			/* meta provider operations */
1191 	char *dtm_name;				/* meta provider name */
1192 	void *dtm_arg;				/* meta provider user arg */
1193 	uint64_t dtm_count;			/* no. of associated provs. */
1194 };
1195 
1196 /*
1197  * DTrace Enablings
1198  *
1199  * A dtrace_enabling structure is used to track a collection of ECB
1200  * descriptions -- before they have been turned into actual ECBs.  This is
1201  * created as a result of DOF processing, and is generally used to generate
1202  * ECBs immediately thereafter.  However, enablings are also generally
1203  * retained should the probes they describe be created at a later time; as
1204  * each new module or provider registers with the framework, the retained
1205  * enablings are reevaluated, with any new match resulting in new ECBs.  To
1206  * prevent probes from being matched more than once, the enabling tracks the
1207  * last probe generation matched, and only matches probes from subsequent
1208  * generations.
1209  */
1210 typedef struct dtrace_enabling {
1211 	dtrace_ecbdesc_t **dten_desc;		/* all ECB descriptions */
1212 	int dten_ndesc;				/* number of ECB descriptions */
1213 	int dten_maxdesc;			/* size of ECB array */
1214 	dtrace_vstate_t *dten_vstate;		/* associated variable state */
1215 	dtrace_genid_t dten_probegen;		/* matched probe generation */
1216 	dtrace_ecbdesc_t *dten_current;		/* current ECB description */
1217 	int dten_error;				/* current error value */
1218 	int dten_primed;			/* boolean: set if primed */
1219 	struct dtrace_enabling *dten_prev;	/* previous enabling */
1220 	struct dtrace_enabling *dten_next;	/* next enabling */
1221 } dtrace_enabling_t;
1222 
1223 /*
1224  * DTrace Anonymous Enablings
1225  *
1226  * Anonymous enablings are DTrace enablings that are not associated with a
1227  * controlling process, but rather derive their enabling from DOF stored as
1228  * properties in the dtrace.conf file.  If there is an anonymous enabling, a
1229  * DTrace consumer state and enabling are created on attach.  The state may be
1230  * subsequently grabbed by the first consumer specifying the "grabanon"
1231  * option.  As long as an anonymous DTrace enabling exists, dtrace(7D) will
1232  * refuse to unload.
1233  */
1234 typedef struct dtrace_anon {
1235 	dtrace_state_t *dta_state;		/* DTrace consumer state */
1236 	dtrace_enabling_t *dta_enabling;	/* pointer to enabling */
1237 	processorid_t dta_beganon;		/* which CPU BEGIN ran on */
1238 } dtrace_anon_t;
1239 
1240 /*
1241  * DTrace Error Debugging
1242  */
1243 #ifdef DEBUG
1244 #define	DTRACE_ERRDEBUG
1245 #endif
1246 
1247 #ifdef DTRACE_ERRDEBUG
1248 
1249 typedef struct dtrace_errhash {
1250 	const char	*dter_msg;	/* error message */
1251 	int		dter_count;	/* number of times seen */
1252 } dtrace_errhash_t;
1253 
1254 #define	DTRACE_ERRHASHSZ	256	/* must be > number of err msgs */
1255 
1256 #endif	/* DTRACE_ERRDEBUG */
1257 
1258 /*
1259  * DTrace Toxic Ranges
1260  *
1261  * DTrace supports safe loads from probe context; if the address turns out to
1262  * be invalid, a bit will be set by the kernel indicating that DTrace
1263  * encountered a memory error, and DTrace will propagate the error to the user
1264  * accordingly.  However, there may exist some regions of memory in which an
1265  * arbitrary load can change system state, and from which it is impossible to
1266  * recover from such a load after it has been attempted.  Examples of this may
1267  * include memory in which programmable I/O registers are mapped (for which a
1268  * read may have some implications for the device) or (in the specific case of
1269  * UltraSPARC-I and -II) the virtual address hole.  The platform is required
1270  * to make DTrace aware of these toxic ranges; DTrace will then check that
1271  * target addresses are not in a toxic range before attempting to issue a
1272  * safe load.
1273  */
1274 typedef struct dtrace_toxrange {
1275 	uintptr_t	dtt_base;		/* base of toxic range */
1276 	uintptr_t	dtt_limit;		/* limit of toxic range */
1277 } dtrace_toxrange_t;
1278 
1279 #ifdef illumos
1280 extern uint64_t dtrace_getarg(int, int);
1281 #else
1282 extern uint64_t __noinline dtrace_getarg(int, int);
1283 #endif
1284 extern greg_t dtrace_getfp(void);
1285 extern int dtrace_getipl(void);
1286 extern uintptr_t dtrace_caller(int);
1287 extern uint32_t dtrace_cas32(uint32_t *, uint32_t, uint32_t);
1288 extern void *dtrace_casptr(volatile void *, volatile void *, volatile void *);
1289 extern void dtrace_copyin(uintptr_t, uintptr_t, size_t, volatile uint16_t *);
1290 extern void dtrace_copyinstr(uintptr_t, uintptr_t, size_t, volatile uint16_t *);
1291 extern void dtrace_copyout(uintptr_t, uintptr_t, size_t, volatile uint16_t *);
1292 extern void dtrace_copyoutstr(uintptr_t, uintptr_t, size_t,
1293     volatile uint16_t *);
1294 extern void dtrace_getpcstack(pc_t *, int, int, uint32_t *);
1295 extern ulong_t dtrace_getreg(struct trapframe *, uint_t);
1296 extern int dtrace_getstackdepth(int);
1297 extern void dtrace_getupcstack(uint64_t *, int);
1298 extern void dtrace_getufpstack(uint64_t *, uint64_t *, int);
1299 extern int dtrace_getustackdepth(void);
1300 extern uintptr_t dtrace_fulword(void *);
1301 extern uint8_t dtrace_fuword8(void *);
1302 extern uint16_t dtrace_fuword16(void *);
1303 extern uint32_t dtrace_fuword32(void *);
1304 extern uint64_t dtrace_fuword64(void *);
1305 extern void dtrace_probe_error(dtrace_state_t *, dtrace_epid_t, int, int,
1306     int, uintptr_t);
1307 extern int dtrace_assfail(const char *, const char *, int);
1308 extern int dtrace_attached(void);
1309 #ifdef illumos
1310 extern hrtime_t dtrace_gethrestime(void);
1311 #endif
1312 
1313 #ifdef __sparc
1314 extern void dtrace_flush_windows(void);
1315 extern void dtrace_flush_user_windows(void);
1316 extern uint_t dtrace_getotherwin(void);
1317 extern uint_t dtrace_getfprs(void);
1318 #else
1319 extern void dtrace_copy(uintptr_t, uintptr_t, size_t);
1320 extern void dtrace_copystr(uintptr_t, uintptr_t, size_t, volatile uint16_t *);
1321 #endif
1322 
1323 /*
1324  * DTrace Assertions
1325  *
1326  * DTrace calls ASSERT and VERIFY from probe context.  To assure that a failed
1327  * ASSERT or VERIFY does not induce a markedly more catastrophic failure (e.g.,
1328  * one from which a dump cannot be gleaned), DTrace must define its own ASSERT
1329  * and VERIFY macros to be ones that may safely be called from probe context.
1330  * This header file must thus be included by any DTrace component that calls
1331  * ASSERT and/or VERIFY from probe context, and _only_ by those components.
1332  * (The only exception to this is kernel debugging infrastructure at user-level
1333  * that doesn't depend on calling ASSERT.)
1334  */
1335 #undef ASSERT
1336 #undef VERIFY
1337 #define	VERIFY(EX)	((void)((EX) || \
1338 			dtrace_assfail(#EX, __FILE__, __LINE__)))
1339 #ifdef DEBUG
1340 #define	ASSERT(EX)	((void)((EX) || \
1341 			dtrace_assfail(#EX, __FILE__, __LINE__)))
1342 #else
1343 #define	ASSERT(X)	((void)0)
1344 #endif
1345 
1346 #ifdef	__cplusplus
1347 }
1348 #endif
1349 
1350 #endif /* _SYS_DTRACE_IMPL_H */
1351