1179193Sjb/*
2179193Sjb * CDDL HEADER START
3179193Sjb *
4179193Sjb * The contents of this file are subject to the terms of the
5179193Sjb * Common Development and Distribution License (the "License").
6179193Sjb * You may not use this file except in compliance with the License.
7179193Sjb *
8179193Sjb * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9179193Sjb * or http://www.opensolaris.org/os/licensing.
10179193Sjb * See the License for the specific language governing permissions
11179193Sjb * and limitations under the License.
12179193Sjb *
13179193Sjb * When distributing Covered Code, include this CDDL HEADER in each
14179193Sjb * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15179193Sjb * If applicable, add the following below this CDDL HEADER, with the
16179193Sjb * fields enclosed by brackets "[]" replaced with your own identifying
17179193Sjb * information: Portions Copyright [yyyy] [name of copyright owner]
18179193Sjb *
19179193Sjb * CDDL HEADER END
20179469Sjb *
21179469Sjb * $FreeBSD$
22179193Sjb */
23179193Sjb
24179193Sjb/*
25265235Spfg * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
26265235Spfg * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27265235Spfg * Copyright (c) 2012 by Delphix. All rights reserved.
28179193Sjb */
29179193Sjb
30179193Sjb#pragma ident	"%Z%%M%	%I%	%E% SMI"
31179193Sjb
32179193Sjb/*
33179193Sjb * DTrace - Dynamic Tracing for Solaris
34179193Sjb *
35179193Sjb * This is the implementation of the Solaris Dynamic Tracing framework
36179193Sjb * (DTrace).  The user-visible interface to DTrace is described at length in
37179193Sjb * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
38179193Sjb * library, the in-kernel DTrace framework, and the DTrace providers are
39179193Sjb * described in the block comments in the <sys/dtrace.h> header file.  The
40179193Sjb * internal architecture of DTrace is described in the block comments in the
41179193Sjb * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
42179193Sjb * implementation very much assume mastery of all of these sources; if one has
43179193Sjb * an unanswered question about the implementation, one should consult them
44179193Sjb * first.
45179193Sjb *
46179193Sjb * The functions here are ordered roughly as follows:
47179193Sjb *
48179193Sjb *   - Probe context functions
49179193Sjb *   - Probe hashing functions
50179193Sjb *   - Non-probe context utility functions
51179193Sjb *   - Matching functions
52179193Sjb *   - Provider-to-Framework API functions
53179193Sjb *   - Probe management functions
54179193Sjb *   - DIF object functions
55179193Sjb *   - Format functions
56179193Sjb *   - Predicate functions
57179193Sjb *   - ECB functions
58179193Sjb *   - Buffer functions
59179193Sjb *   - Enabling functions
60179193Sjb *   - DOF functions
61179193Sjb *   - Anonymous enabling functions
62179193Sjb *   - Consumer state functions
63179193Sjb *   - Helper functions
64179193Sjb *   - Hook functions
65179193Sjb *   - Driver cookbook functions
66179193Sjb *
67179193Sjb * Each group of functions begins with a block comment labelled the "DTrace
68179193Sjb * [Group] Functions", allowing one to find each block by searching forward
69179193Sjb * on capital-f functions.
70179193Sjb */
71179193Sjb#include <sys/errno.h>
72179198Sjb#if !defined(sun)
73179198Sjb#include <sys/time.h>
74179198Sjb#endif
75179193Sjb#include <sys/stat.h>
76179193Sjb#include <sys/modctl.h>
77179193Sjb#include <sys/conf.h>
78179193Sjb#include <sys/systm.h>
79179198Sjb#if defined(sun)
80179193Sjb#include <sys/ddi.h>
81179193Sjb#include <sys/sunddi.h>
82179198Sjb#endif
83179193Sjb#include <sys/cpuvar.h>
84179193Sjb#include <sys/kmem.h>
85179198Sjb#if defined(sun)
86179193Sjb#include <sys/strsubr.h>
87179198Sjb#endif
88179193Sjb#include <sys/sysmacros.h>
89179193Sjb#include <sys/dtrace_impl.h>
90179193Sjb#include <sys/atomic.h>
91179193Sjb#include <sys/cmn_err.h>
92179198Sjb#if defined(sun)
93179193Sjb#include <sys/mutex_impl.h>
94179193Sjb#include <sys/rwlock_impl.h>
95179198Sjb#endif
96179193Sjb#include <sys/ctf_api.h>
97179198Sjb#if defined(sun)
98179193Sjb#include <sys/panic.h>
99179193Sjb#include <sys/priv_impl.h>
100179198Sjb#endif
101179193Sjb#include <sys/policy.h>
102179198Sjb#if defined(sun)
103179193Sjb#include <sys/cred_impl.h>
104179193Sjb#include <sys/procfs_isa.h>
105179198Sjb#endif
106179193Sjb#include <sys/taskq.h>
107179198Sjb#if defined(sun)
108179193Sjb#include <sys/mkdev.h>
109179193Sjb#include <sys/kdi.h>
110179198Sjb#endif
111179193Sjb#include <sys/zone.h>
112179193Sjb#include <sys/socket.h>
113179193Sjb#include <netinet/in.h>
114179193Sjb
115179198Sjb/* FreeBSD includes: */
116179198Sjb#if !defined(sun)
117179469Sjb#include <sys/callout.h>
118179198Sjb#include <sys/ctype.h>
119255763Smarkj#include <sys/eventhandler.h>
120179198Sjb#include <sys/limits.h>
121179198Sjb#include <sys/kdb.h>
122179198Sjb#include <sys/kernel.h>
123179198Sjb#include <sys/malloc.h>
124179198Sjb#include <sys/sysctl.h>
125179198Sjb#include <sys/lock.h>
126179198Sjb#include <sys/mutex.h>
127192853Ssson#include <sys/rwlock.h>
128179198Sjb#include <sys/sx.h>
129179198Sjb#include <sys/dtrace_bsd.h>
130179198Sjb#include <netinet/in.h>
131179198Sjb#include "dtrace_cddl.h"
132179198Sjb#include "dtrace_debug.c"
133179198Sjb#endif
134179198Sjb
135179193Sjb/*
136179193Sjb * DTrace Tunable Variables
137179193Sjb *
138179193Sjb * The following variables may be tuned by adding a line to /etc/system that
139179193Sjb * includes both the name of the DTrace module ("dtrace") and the name of the
140179193Sjb * variable.  For example:
141179193Sjb *
142179193Sjb *   set dtrace:dtrace_destructive_disallow = 1
143179193Sjb *
144179193Sjb * In general, the only variables that one should be tuning this way are those
145179193Sjb * that affect system-wide DTrace behavior, and for which the default behavior
146179193Sjb * is undesirable.  Most of these variables are tunable on a per-consumer
147179193Sjb * basis using DTrace options, and need not be tuned on a system-wide basis.
148179193Sjb * When tuning these variables, avoid pathological values; while some attempt
149179193Sjb * is made to verify the integrity of these variables, they are not considered
150179193Sjb * part of the supported interface to DTrace, and they are therefore not
151179193Sjb * checked comprehensively.  Further, these variables should not be tuned
152179193Sjb * dynamically via "mdb -kw" or other means; they should only be tuned via
153179193Sjb * /etc/system.
154179193Sjb */
155179193Sjbint		dtrace_destructive_disallow = 0;
156179193Sjbdtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
157179193Sjbsize_t		dtrace_difo_maxsize = (256 * 1024);
158264797Smarkjdtrace_optval_t	dtrace_dof_maxsize = (8 * 1024 * 1024);
159179193Sjbsize_t		dtrace_global_maxsize = (16 * 1024);
160179193Sjbsize_t		dtrace_actions_max = (16 * 1024);
161179193Sjbsize_t		dtrace_retain_max = 1024;
162239540Spfgdtrace_optval_t	dtrace_helper_actions_max = 128;
163179193Sjbdtrace_optval_t	dtrace_helper_providers_max = 32;
164179193Sjbdtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
165179193Sjbsize_t		dtrace_strsize_default = 256;
166179193Sjbdtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
167179193Sjbdtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
168179193Sjbdtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
169179193Sjbdtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
170179193Sjbdtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
171179193Sjbdtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
172179193Sjbdtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
173179193Sjbdtrace_optval_t	dtrace_nspec_default = 1;
174179193Sjbdtrace_optval_t	dtrace_specsize_default = 32 * 1024;
175179193Sjbdtrace_optval_t dtrace_stackframes_default = 20;
176179193Sjbdtrace_optval_t dtrace_ustackframes_default = 20;
177179193Sjbdtrace_optval_t dtrace_jstackframes_default = 50;
178179193Sjbdtrace_optval_t dtrace_jstackstrsize_default = 512;
179179193Sjbint		dtrace_msgdsize_max = 128;
180179193Sjbhrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
181179193Sjbhrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
182179193Sjbint		dtrace_devdepth_max = 32;
183179193Sjbint		dtrace_err_verbose;
184179193Sjbhrtime_t	dtrace_deadman_interval = NANOSEC;
185179193Sjbhrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
186179193Sjbhrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
187250484Spfghrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
188179193Sjb
189179193Sjb/*
190179193Sjb * DTrace External Variables
191179193Sjb *
192179193Sjb * As dtrace(7D) is a kernel module, any DTrace variables are obviously
193179193Sjb * available to DTrace consumers via the backtick (`) syntax.  One of these,
194179193Sjb * dtrace_zero, is made deliberately so:  it is provided as a source of
195179193Sjb * well-known, zero-filled memory.  While this variable is not documented,
196179193Sjb * it is used by some translators as an implementation detail.
197179193Sjb */
198179193Sjbconst char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
199179193Sjb
200179193Sjb/*
201179193Sjb * DTrace Internal Variables
202179193Sjb */
203179198Sjb#if defined(sun)
204179193Sjbstatic dev_info_t	*dtrace_devi;		/* device info */
205179198Sjb#endif
206179198Sjb#if defined(sun)
207179193Sjbstatic vmem_t		*dtrace_arena;		/* probe ID arena */
208179193Sjbstatic vmem_t		*dtrace_minor;		/* minor number arena */
209250484Spfg#else
210179193Sjbstatic taskq_t		*dtrace_taskq;		/* task queue */
211179198Sjbstatic struct unrhdr	*dtrace_arena;		/* Probe ID number.     */
212179198Sjb#endif
213179193Sjbstatic dtrace_probe_t	**dtrace_probes;	/* array of all probes */
214179193Sjbstatic int		dtrace_nprobes;		/* number of probes */
215179193Sjbstatic dtrace_provider_t *dtrace_provider;	/* provider list */
216179193Sjbstatic dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
217179193Sjbstatic int		dtrace_opens;		/* number of opens */
218179193Sjbstatic int		dtrace_helpers;		/* number of helpers */
219179198Sjb#if defined(sun)
220179193Sjbstatic void		*dtrace_softstate;	/* softstate pointer */
221179198Sjb#endif
222179193Sjbstatic dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
223179193Sjbstatic dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
224179193Sjbstatic dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
225179193Sjbstatic dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
226179193Sjbstatic int		dtrace_toxranges;	/* number of toxic ranges */
227179193Sjbstatic int		dtrace_toxranges_max;	/* size of toxic range array */
228179193Sjbstatic dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
229179193Sjbstatic kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
230179193Sjbstatic uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
231179193Sjbstatic kthread_t	*dtrace_panicked;	/* panicking thread */
232179193Sjbstatic dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
233179193Sjbstatic dtrace_genid_t	dtrace_probegen;	/* current probe generation */
234179193Sjbstatic dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
235179193Sjbstatic dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
236179193Sjbstatic dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
237179198Sjb#if !defined(sun)
238179198Sjbstatic struct mtx	dtrace_unr_mtx;
239179198SjbMTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier", MTX_DEF);
240179198Sjbint		dtrace_in_probe;	/* non-zero if executing a probe */
241179198Sjb#if defined(__i386__) || defined(__amd64__)
242179198Sjbuintptr_t	dtrace_in_probe_addr;	/* Address of invop when already in probe */
243179198Sjb#endif
244255763Smarkjstatic eventhandler_tag	dtrace_kld_load_tag;
245262038Savgstatic eventhandler_tag	dtrace_kld_unload_try_tag;
246179198Sjb#endif
247179193Sjb
248179193Sjb/*
249179193Sjb * DTrace Locking
250179193Sjb * DTrace is protected by three (relatively coarse-grained) locks:
251179193Sjb *
252179193Sjb * (1) dtrace_lock is required to manipulate essentially any DTrace state,
253179193Sjb *     including enabling state, probes, ECBs, consumer state, helper state,
254179193Sjb *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
255179193Sjb *     probe context is lock-free -- synchronization is handled via the
256179193Sjb *     dtrace_sync() cross call mechanism.
257179193Sjb *
258179193Sjb * (2) dtrace_provider_lock is required when manipulating provider state, or
259179193Sjb *     when provider state must be held constant.
260179193Sjb *
261179193Sjb * (3) dtrace_meta_lock is required when manipulating meta provider state, or
262179193Sjb *     when meta provider state must be held constant.
263179193Sjb *
264179193Sjb * The lock ordering between these three locks is dtrace_meta_lock before
265179193Sjb * dtrace_provider_lock before dtrace_lock.  (In particular, there are
266179193Sjb * several places where dtrace_provider_lock is held by the framework as it
267179193Sjb * calls into the providers -- which then call back into the framework,
268179193Sjb * grabbing dtrace_lock.)
269179193Sjb *
270179193Sjb * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
271179193Sjb * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
272179193Sjb * role as a coarse-grained lock; it is acquired before both of these locks.
273179193Sjb * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
274179193Sjb * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
275179193Sjb * mod_lock is similar with respect to dtrace_provider_lock in that it must be
276179193Sjb * acquired _between_ dtrace_provider_lock and dtrace_lock.
277179193Sjb */
278179193Sjbstatic kmutex_t		dtrace_lock;		/* probe state lock */
279179193Sjbstatic kmutex_t		dtrace_provider_lock;	/* provider state lock */
280179193Sjbstatic kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
281179193Sjb
282179198Sjb#if !defined(sun)
283179198Sjb/* XXX FreeBSD hacks. */
284179198Sjb#define cr_suid		cr_svuid
285179198Sjb#define cr_sgid		cr_svgid
286179198Sjb#define	ipaddr_t	in_addr_t
287179198Sjb#define mod_modname	pathname
288179198Sjb#define vuprintf	vprintf
289179198Sjb#define ttoproc(_a)	((_a)->td_proc)
290179198Sjb#define crgetzoneid(_a)	0
291179198Sjb#define	NCPU		MAXCPU
292179198Sjb#define SNOCD		0
293179198Sjb#define CPU_ON_INTR(_a)	0
294179198Sjb
295179198Sjb#define PRIV_EFFECTIVE		(1 << 0)
296179198Sjb#define PRIV_DTRACE_KERNEL	(1 << 1)
297179198Sjb#define PRIV_DTRACE_PROC	(1 << 2)
298179198Sjb#define PRIV_DTRACE_USER	(1 << 3)
299179198Sjb#define PRIV_PROC_OWNER		(1 << 4)
300179198Sjb#define PRIV_PROC_ZONE		(1 << 5)
301179198Sjb#define PRIV_ALL		~0
302179198Sjb
303266101SmarkjSYSCTL_DECL(_debug_dtrace);
304266101SmarkjSYSCTL_DECL(_kern_dtrace);
305179198Sjb#endif
306179198Sjb
307179198Sjb#if defined(sun)
308179198Sjb#define curcpu	CPU->cpu_id
309179198Sjb#endif
310179198Sjb
311179198Sjb
312179193Sjb/*
313179193Sjb * DTrace Provider Variables
314179193Sjb *
315179193Sjb * These are the variables relating to DTrace as a provider (that is, the
316179193Sjb * provider of the BEGIN, END, and ERROR probes).
317179193Sjb */
318179193Sjbstatic dtrace_pattr_t	dtrace_provider_attr = {
319179193Sjb{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
320179193Sjb{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
321179193Sjb{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
322179193Sjb{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
323179193Sjb{ DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
324179193Sjb};
325179193Sjb
326179193Sjbstatic void
327179193Sjbdtrace_nullop(void)
328179193Sjb{}
329179193Sjb
330179193Sjbstatic dtrace_pops_t	dtrace_provider_ops = {
331179198Sjb	(void (*)(void *, dtrace_probedesc_t *))dtrace_nullop,
332179198Sjb	(void (*)(void *, modctl_t *))dtrace_nullop,
333179193Sjb	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
334179193Sjb	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
335179193Sjb	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
336179193Sjb	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
337179193Sjb	NULL,
338179193Sjb	NULL,
339179193Sjb	NULL,
340179193Sjb	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
341179193Sjb};
342179193Sjb
343179193Sjbstatic dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
344179193Sjbstatic dtrace_id_t	dtrace_probeid_end;	/* special END probe */
345179193Sjbdtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
346179193Sjb
347179193Sjb/*
348179193Sjb * DTrace Helper Tracing Variables
349179193Sjb */
350179193Sjbuint32_t dtrace_helptrace_next = 0;
351179193Sjbuint32_t dtrace_helptrace_nlocals;
352179193Sjbchar	*dtrace_helptrace_buffer;
353179193Sjbint	dtrace_helptrace_bufsize = 512 * 1024;
354179193Sjb
355179193Sjb#ifdef DEBUG
356179193Sjbint	dtrace_helptrace_enabled = 1;
357179193Sjb#else
358179193Sjbint	dtrace_helptrace_enabled = 0;
359179193Sjb#endif
360179193Sjb
361179193Sjb/*
362179193Sjb * DTrace Error Hashing
363179193Sjb *
364179193Sjb * On DEBUG kernels, DTrace will track the errors that has seen in a hash
365179193Sjb * table.  This is very useful for checking coverage of tests that are
366179193Sjb * expected to induce DIF or DOF processing errors, and may be useful for
367179193Sjb * debugging problems in the DIF code generator or in DOF generation .  The
368179193Sjb * error hash may be examined with the ::dtrace_errhash MDB dcmd.
369179193Sjb */
370179193Sjb#ifdef DEBUG
371179193Sjbstatic dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
372179193Sjbstatic const char *dtrace_errlast;
373179193Sjbstatic kthread_t *dtrace_errthread;
374179193Sjbstatic kmutex_t dtrace_errlock;
375179193Sjb#endif
376179193Sjb
377179193Sjb/*
378179193Sjb * DTrace Macros and Constants
379179193Sjb *
380179193Sjb * These are various macros that are useful in various spots in the
381179193Sjb * implementation, along with a few random constants that have no meaning
382179193Sjb * outside of the implementation.  There is no real structure to this cpp
383179193Sjb * mishmash -- but is there ever?
384179193Sjb */
385179193Sjb#define	DTRACE_HASHSTR(hash, probe)	\
386179193Sjb	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
387179193Sjb
388179193Sjb#define	DTRACE_HASHNEXT(hash, probe)	\
389179193Sjb	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
390179193Sjb
391179193Sjb#define	DTRACE_HASHPREV(hash, probe)	\
392179193Sjb	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
393179193Sjb
394179193Sjb#define	DTRACE_HASHEQ(hash, lhs, rhs)	\
395179193Sjb	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
396179193Sjb	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
397179193Sjb
398179193Sjb#define	DTRACE_AGGHASHSIZE_SLEW		17
399179193Sjb
400179193Sjb#define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
401179193Sjb
402179193Sjb/*
403179193Sjb * The key for a thread-local variable consists of the lower 61 bits of the
404179193Sjb * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
405179193Sjb * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
406179193Sjb * equal to a variable identifier.  This is necessary (but not sufficient) to
407179193Sjb * assure that global associative arrays never collide with thread-local
408179193Sjb * variables.  To guarantee that they cannot collide, we must also define the
409179193Sjb * order for keying dynamic variables.  That order is:
410179193Sjb *
411179193Sjb *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
412179193Sjb *
413179193Sjb * Because the variable-key and the tls-key are in orthogonal spaces, there is
414179193Sjb * no way for a global variable key signature to match a thread-local key
415179193Sjb * signature.
416179193Sjb */
417179198Sjb#if defined(sun)
418179193Sjb#define	DTRACE_TLS_THRKEY(where) { \
419179193Sjb	uint_t intr = 0; \
420179193Sjb	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
421179193Sjb	for (; actv; actv >>= 1) \
422179193Sjb		intr++; \
423179193Sjb	ASSERT(intr < (1 << 3)); \
424179193Sjb	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
425179193Sjb	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
426179193Sjb}
427179198Sjb#else
428179198Sjb#define	DTRACE_TLS_THRKEY(where) { \
429179198Sjb	solaris_cpu_t *_c = &solaris_cpu[curcpu]; \
430179198Sjb	uint_t intr = 0; \
431179198Sjb	uint_t actv = _c->cpu_intr_actv; \
432179198Sjb	for (; actv; actv >>= 1) \
433179198Sjb		intr++; \
434179198Sjb	ASSERT(intr < (1 << 3)); \
435179198Sjb	(where) = ((curthread->td_tid + DIF_VARIABLE_MAX) & \
436179198Sjb	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
437179198Sjb}
438179198Sjb#endif
439179193Sjb
440179193Sjb#define	DT_BSWAP_8(x)	((x) & 0xff)
441179193Sjb#define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
442179193Sjb#define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
443179193Sjb#define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
444179193Sjb
445179193Sjb#define	DT_MASK_LO 0x00000000FFFFFFFFULL
446179193Sjb
447179193Sjb#define	DTRACE_STORE(type, tomax, offset, what) \
448179193Sjb	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
449179193Sjb
450249856Spfg#ifndef __x86
451179193Sjb#define	DTRACE_ALIGNCHECK(addr, size, flags)				\
452179193Sjb	if (addr & (size - 1)) {					\
453179193Sjb		*flags |= CPU_DTRACE_BADALIGN;				\
454179198Sjb		cpu_core[curcpu].cpuc_dtrace_illval = addr;	\
455179193Sjb		return (0);						\
456179193Sjb	}
457179193Sjb#else
458179193Sjb#define	DTRACE_ALIGNCHECK(addr, size, flags)
459179193Sjb#endif
460179193Sjb
461179193Sjb/*
462179193Sjb * Test whether a range of memory starting at testaddr of size testsz falls
463179193Sjb * within the range of memory described by addr, sz.  We take care to avoid
464179193Sjb * problems with overflow and underflow of the unsigned quantities, and
465179193Sjb * disallow all negative sizes.  Ranges of size 0 are allowed.
466179193Sjb */
467179193Sjb#define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
468179193Sjb	((testaddr) - (baseaddr) < (basesz) && \
469179193Sjb	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
470179193Sjb	(testaddr) + (testsz) >= (testaddr))
471179193Sjb
472179193Sjb/*
473179193Sjb * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
474179193Sjb * alloc_sz on the righthand side of the comparison in order to avoid overflow
475179193Sjb * or underflow in the comparison with it.  This is simpler than the INRANGE
476179193Sjb * check above, because we know that the dtms_scratch_ptr is valid in the
477179193Sjb * range.  Allocations of size zero are allowed.
478179193Sjb */
479179193Sjb#define	DTRACE_INSCRATCH(mstate, alloc_sz) \
480179193Sjb	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
481179193Sjb	(mstate)->dtms_scratch_ptr >= (alloc_sz))
482179193Sjb
483179193Sjb#define	DTRACE_LOADFUNC(bits)						\
484179193Sjb/*CSTYLED*/								\
485179193Sjbuint##bits##_t								\
486179193Sjbdtrace_load##bits(uintptr_t addr)					\
487179193Sjb{									\
488179193Sjb	size_t size = bits / NBBY;					\
489179193Sjb	/*CSTYLED*/							\
490179193Sjb	uint##bits##_t rval;						\
491179193Sjb	int i;								\
492179193Sjb	volatile uint16_t *flags = (volatile uint16_t *)		\
493179198Sjb	    &cpu_core[curcpu].cpuc_dtrace_flags;			\
494179193Sjb									\
495179193Sjb	DTRACE_ALIGNCHECK(addr, size, flags);				\
496179193Sjb									\
497179193Sjb	for (i = 0; i < dtrace_toxranges; i++) {			\
498179193Sjb		if (addr >= dtrace_toxrange[i].dtt_limit)		\
499179193Sjb			continue;					\
500179193Sjb									\
501179193Sjb		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
502179193Sjb			continue;					\
503179193Sjb									\
504179193Sjb		/*							\
505179193Sjb		 * This address falls within a toxic region; return 0.	\
506179193Sjb		 */							\
507179193Sjb		*flags |= CPU_DTRACE_BADADDR;				\
508179198Sjb		cpu_core[curcpu].cpuc_dtrace_illval = addr;		\
509179193Sjb		return (0);						\
510179193Sjb	}								\
511179193Sjb									\
512179193Sjb	*flags |= CPU_DTRACE_NOFAULT;					\
513179193Sjb	/*CSTYLED*/							\
514179193Sjb	rval = *((volatile uint##bits##_t *)addr);			\
515179193Sjb	*flags &= ~CPU_DTRACE_NOFAULT;					\
516179193Sjb									\
517179193Sjb	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
518179193Sjb}
519179193Sjb
520179193Sjb#ifdef _LP64
521179193Sjb#define	dtrace_loadptr	dtrace_load64
522179193Sjb#else
523179193Sjb#define	dtrace_loadptr	dtrace_load32
524179193Sjb#endif
525179193Sjb
526179193Sjb#define	DTRACE_DYNHASH_FREE	0
527179193Sjb#define	DTRACE_DYNHASH_SINK	1
528179193Sjb#define	DTRACE_DYNHASH_VALID	2
529179193Sjb
530179193Sjb#define	DTRACE_MATCH_NEXT	0
531179193Sjb#define	DTRACE_MATCH_DONE	1
532179193Sjb#define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
533179193Sjb#define	DTRACE_STATE_ALIGN	64
534179193Sjb
535179193Sjb#define	DTRACE_FLAGS2FLT(flags)						\
536179193Sjb	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
537179193Sjb	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
538179193Sjb	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
539179193Sjb	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
540179193Sjb	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
541179193Sjb	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
542179193Sjb	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
543179193Sjb	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
544179193Sjb	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
545179193Sjb	DTRACEFLT_UNKNOWN)
546179193Sjb
547179193Sjb#define	DTRACEACT_ISSTRING(act)						\
548179193Sjb	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
549179193Sjb	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
550179193Sjb
551179198Sjb/* Function prototype definitions: */
552179193Sjbstatic size_t dtrace_strlen(const char *, size_t);
553179193Sjbstatic dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
554179193Sjbstatic void dtrace_enabling_provide(dtrace_provider_t *);
555179193Sjbstatic int dtrace_enabling_match(dtrace_enabling_t *, int *);
556179193Sjbstatic void dtrace_enabling_matchall(void);
557250484Spfgstatic void dtrace_enabling_reap(void);
558179193Sjbstatic dtrace_state_t *dtrace_anon_grab(void);
559179193Sjbstatic uint64_t dtrace_helper(int, dtrace_mstate_t *,
560179193Sjb    dtrace_state_t *, uint64_t, uint64_t);
561179193Sjbstatic dtrace_helpers_t *dtrace_helpers_create(proc_t *);
562179193Sjbstatic void dtrace_buffer_drop(dtrace_buffer_t *);
563250484Spfgstatic int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
564179193Sjbstatic intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
565179193Sjb    dtrace_state_t *, dtrace_mstate_t *);
566179193Sjbstatic int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
567179193Sjb    dtrace_optval_t);
568179193Sjbstatic int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
569179193Sjbstatic void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
570179198Sjbuint16_t dtrace_load16(uintptr_t);
571179198Sjbuint32_t dtrace_load32(uintptr_t);
572179198Sjbuint64_t dtrace_load64(uintptr_t);
573179198Sjbuint8_t dtrace_load8(uintptr_t);
574179198Sjbvoid dtrace_dynvar_clean(dtrace_dstate_t *);
575179198Sjbdtrace_dynvar_t *dtrace_dynvar(dtrace_dstate_t *, uint_t, dtrace_key_t *,
576179198Sjb    size_t, dtrace_dynvar_op_t, dtrace_mstate_t *, dtrace_vstate_t *);
577179198Sjbuintptr_t dtrace_dif_varstr(uintptr_t, dtrace_state_t *, dtrace_mstate_t *);
578179193Sjb
579179193Sjb/*
580179193Sjb * DTrace Probe Context Functions
581179193Sjb *
582179193Sjb * These functions are called from probe context.  Because probe context is
583179193Sjb * any context in which C may be called, arbitrarily locks may be held,
584179193Sjb * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
585179193Sjb * As a result, functions called from probe context may only call other DTrace
586179193Sjb * support functions -- they may not interact at all with the system at large.
587179193Sjb * (Note that the ASSERT macro is made probe-context safe by redefining it in
588179193Sjb * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
589179193Sjb * loads are to be performed from probe context, they _must_ be in terms of
590179193Sjb * the safe dtrace_load*() variants.
591179193Sjb *
592179193Sjb * Some functions in this block are not actually called from probe context;
593179193Sjb * for these functions, there will be a comment above the function reading
594179193Sjb * "Note:  not called from probe context."
595179193Sjb */
596179193Sjbvoid
597179193Sjbdtrace_panic(const char *format, ...)
598179193Sjb{
599179193Sjb	va_list alist;
600179193Sjb
601179193Sjb	va_start(alist, format);
602179193Sjb	dtrace_vpanic(format, alist);
603179193Sjb	va_end(alist);
604179193Sjb}
605179193Sjb
606179193Sjbint
607179193Sjbdtrace_assfail(const char *a, const char *f, int l)
608179193Sjb{
609179193Sjb	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
610179193Sjb
611179193Sjb	/*
612179193Sjb	 * We just need something here that even the most clever compiler
613179193Sjb	 * cannot optimize away.
614179193Sjb	 */
615179193Sjb	return (a[(uintptr_t)f]);
616179193Sjb}
617179193Sjb
618179193Sjb/*
619179193Sjb * Atomically increment a specified error counter from probe context.
620179193Sjb */
621179193Sjbstatic void
622179193Sjbdtrace_error(uint32_t *counter)
623179193Sjb{
624179193Sjb	/*
625179193Sjb	 * Most counters stored to in probe context are per-CPU counters.
626179193Sjb	 * However, there are some error conditions that are sufficiently
627179193Sjb	 * arcane that they don't merit per-CPU storage.  If these counters
628179193Sjb	 * are incremented concurrently on different CPUs, scalability will be
629179193Sjb	 * adversely affected -- but we don't expect them to be white-hot in a
630179193Sjb	 * correctly constructed enabling...
631179193Sjb	 */
632179193Sjb	uint32_t oval, nval;
633179193Sjb
634179193Sjb	do {
635179193Sjb		oval = *counter;
636179193Sjb
637179193Sjb		if ((nval = oval + 1) == 0) {
638179193Sjb			/*
639179193Sjb			 * If the counter would wrap, set it to 1 -- assuring
640179193Sjb			 * that the counter is never zero when we have seen
641179193Sjb			 * errors.  (The counter must be 32-bits because we
642179193Sjb			 * aren't guaranteed a 64-bit compare&swap operation.)
643179193Sjb			 * To save this code both the infamy of being fingered
644179193Sjb			 * by a priggish news story and the indignity of being
645179193Sjb			 * the target of a neo-puritan witch trial, we're
646179193Sjb			 * carefully avoiding any colorful description of the
647179193Sjb			 * likelihood of this condition -- but suffice it to
648179193Sjb			 * say that it is only slightly more likely than the
649179193Sjb			 * overflow of predicate cache IDs, as discussed in
650179193Sjb			 * dtrace_predicate_create().
651179193Sjb			 */
652179193Sjb			nval = 1;
653179193Sjb		}
654179193Sjb	} while (dtrace_cas32(counter, oval, nval) != oval);
655179193Sjb}
656179193Sjb
657179193Sjb/*
658179193Sjb * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
659179193Sjb * uint8_t, a uint16_t, a uint32_t and a uint64_t.
660179193Sjb */
661179193SjbDTRACE_LOADFUNC(8)
662179193SjbDTRACE_LOADFUNC(16)
663179193SjbDTRACE_LOADFUNC(32)
664179193SjbDTRACE_LOADFUNC(64)
665179193Sjb
666179193Sjbstatic int
667179193Sjbdtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
668179193Sjb{
669179193Sjb	if (dest < mstate->dtms_scratch_base)
670179193Sjb		return (0);
671179193Sjb
672179193Sjb	if (dest + size < dest)
673179193Sjb		return (0);
674179193Sjb
675179193Sjb	if (dest + size > mstate->dtms_scratch_ptr)
676179193Sjb		return (0);
677179193Sjb
678179193Sjb	return (1);
679179193Sjb}
680179193Sjb
681179193Sjbstatic int
682179193Sjbdtrace_canstore_statvar(uint64_t addr, size_t sz,
683179193Sjb    dtrace_statvar_t **svars, int nsvars)
684179193Sjb{
685179193Sjb	int i;
686179193Sjb
687179193Sjb	for (i = 0; i < nsvars; i++) {
688179193Sjb		dtrace_statvar_t *svar = svars[i];
689179193Sjb
690179193Sjb		if (svar == NULL || svar->dtsv_size == 0)
691179193Sjb			continue;
692179193Sjb
693179193Sjb		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
694179193Sjb			return (1);
695179193Sjb	}
696179193Sjb
697179193Sjb	return (0);
698179193Sjb}
699179193Sjb
700179193Sjb/*
701179193Sjb * Check to see if the address is within a memory region to which a store may
702179193Sjb * be issued.  This includes the DTrace scratch areas, and any DTrace variable
703179193Sjb * region.  The caller of dtrace_canstore() is responsible for performing any
704179193Sjb * alignment checks that are needed before stores are actually executed.
705179193Sjb */
706179193Sjbstatic int
707179193Sjbdtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
708179193Sjb    dtrace_vstate_t *vstate)
709179193Sjb{
710179193Sjb	/*
711179193Sjb	 * First, check to see if the address is in scratch space...
712179193Sjb	 */
713179193Sjb	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
714179193Sjb	    mstate->dtms_scratch_size))
715179193Sjb		return (1);
716179193Sjb
717179193Sjb	/*
718179193Sjb	 * Now check to see if it's a dynamic variable.  This check will pick
719179193Sjb	 * up both thread-local variables and any global dynamically-allocated
720179193Sjb	 * variables.
721179193Sjb	 */
722179193Sjb	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
723179193Sjb	    vstate->dtvs_dynvars.dtds_size)) {
724179193Sjb		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
725179193Sjb		uintptr_t base = (uintptr_t)dstate->dtds_base +
726179193Sjb		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
727179193Sjb		uintptr_t chunkoffs;
728179193Sjb
729179193Sjb		/*
730179193Sjb		 * Before we assume that we can store here, we need to make
731179193Sjb		 * sure that it isn't in our metadata -- storing to our
732179193Sjb		 * dynamic variable metadata would corrupt our state.  For
733179193Sjb		 * the range to not include any dynamic variable metadata,
734179193Sjb		 * it must:
735179193Sjb		 *
736179193Sjb		 *	(1) Start above the hash table that is at the base of
737179193Sjb		 *	the dynamic variable space
738179193Sjb		 *
739179193Sjb		 *	(2) Have a starting chunk offset that is beyond the
740179193Sjb		 *	dtrace_dynvar_t that is at the base of every chunk
741179193Sjb		 *
742179193Sjb		 *	(3) Not span a chunk boundary
743179193Sjb		 *
744179193Sjb		 */
745179193Sjb		if (addr < base)
746179193Sjb			return (0);
747179193Sjb
748179193Sjb		chunkoffs = (addr - base) % dstate->dtds_chunksize;
749179193Sjb
750179193Sjb		if (chunkoffs < sizeof (dtrace_dynvar_t))
751179193Sjb			return (0);
752179193Sjb
753179193Sjb		if (chunkoffs + sz > dstate->dtds_chunksize)
754179193Sjb			return (0);
755179193Sjb
756179193Sjb		return (1);
757179193Sjb	}
758179193Sjb
759179193Sjb	/*
760179193Sjb	 * Finally, check the static local and global variables.  These checks
761179193Sjb	 * take the longest, so we perform them last.
762179193Sjb	 */
763179193Sjb	if (dtrace_canstore_statvar(addr, sz,
764179193Sjb	    vstate->dtvs_locals, vstate->dtvs_nlocals))
765179193Sjb		return (1);
766179193Sjb
767179193Sjb	if (dtrace_canstore_statvar(addr, sz,
768179193Sjb	    vstate->dtvs_globals, vstate->dtvs_nglobals))
769179193Sjb		return (1);
770179193Sjb
771179193Sjb	return (0);
772179193Sjb}
773179193Sjb
774179193Sjb
775179193Sjb/*
776179193Sjb * Convenience routine to check to see if the address is within a memory
777179193Sjb * region in which a load may be issued given the user's privilege level;
778179193Sjb * if not, it sets the appropriate error flags and loads 'addr' into the
779179193Sjb * illegal value slot.
780179193Sjb *
781179193Sjb * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
782179193Sjb * appropriate memory access protection.
783179193Sjb */
784179193Sjbstatic int
785179193Sjbdtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
786179193Sjb    dtrace_vstate_t *vstate)
787179193Sjb{
788179198Sjb	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
789179193Sjb
790179193Sjb	/*
791179193Sjb	 * If we hold the privilege to read from kernel memory, then
792179193Sjb	 * everything is readable.
793179193Sjb	 */
794179193Sjb	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
795179193Sjb		return (1);
796179193Sjb
797179193Sjb	/*
798179193Sjb	 * You can obviously read that which you can store.
799179193Sjb	 */
800179193Sjb	if (dtrace_canstore(addr, sz, mstate, vstate))
801179193Sjb		return (1);
802179193Sjb
803179193Sjb	/*
804179193Sjb	 * We're allowed to read from our own string table.
805179193Sjb	 */
806179193Sjb	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
807179193Sjb	    mstate->dtms_difo->dtdo_strlen))
808179193Sjb		return (1);
809179193Sjb
810179193Sjb	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
811179193Sjb	*illval = addr;
812179193Sjb	return (0);
813179193Sjb}
814179193Sjb
815179193Sjb/*
816179193Sjb * Convenience routine to check to see if a given string is within a memory
817179193Sjb * region in which a load may be issued given the user's privilege level;
818179193Sjb * this exists so that we don't need to issue unnecessary dtrace_strlen()
819179193Sjb * calls in the event that the user has all privileges.
820179193Sjb */
821179193Sjbstatic int
822179193Sjbdtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
823179193Sjb    dtrace_vstate_t *vstate)
824179193Sjb{
825179193Sjb	size_t strsz;
826179193Sjb
827179193Sjb	/*
828179193Sjb	 * If we hold the privilege to read from kernel memory, then
829179193Sjb	 * everything is readable.
830179193Sjb	 */
831179193Sjb	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
832179193Sjb		return (1);
833179193Sjb
834179193Sjb	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
835179193Sjb	if (dtrace_canload(addr, strsz, mstate, vstate))
836179193Sjb		return (1);
837179193Sjb
838179193Sjb	return (0);
839179193Sjb}
840179193Sjb
841179193Sjb/*
842179193Sjb * Convenience routine to check to see if a given variable is within a memory
843179193Sjb * region in which a load may be issued given the user's privilege level.
844179193Sjb */
845179193Sjbstatic int
846179193Sjbdtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
847179193Sjb    dtrace_vstate_t *vstate)
848179193Sjb{
849179193Sjb	size_t sz;
850179193Sjb	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
851179193Sjb
852179193Sjb	/*
853179193Sjb	 * If we hold the privilege to read from kernel memory, then
854179193Sjb	 * everything is readable.
855179193Sjb	 */
856179193Sjb	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
857179193Sjb		return (1);
858179193Sjb
859179193Sjb	if (type->dtdt_kind == DIF_TYPE_STRING)
860179193Sjb		sz = dtrace_strlen(src,
861179193Sjb		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
862179193Sjb	else
863179193Sjb		sz = type->dtdt_size;
864179193Sjb
865179193Sjb	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
866179193Sjb}
867179193Sjb
868179193Sjb/*
869179193Sjb * Compare two strings using safe loads.
870179193Sjb */
871179193Sjbstatic int
872179193Sjbdtrace_strncmp(char *s1, char *s2, size_t limit)
873179193Sjb{
874179193Sjb	uint8_t c1, c2;
875179193Sjb	volatile uint16_t *flags;
876179193Sjb
877179193Sjb	if (s1 == s2 || limit == 0)
878179193Sjb		return (0);
879179193Sjb
880179198Sjb	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
881179193Sjb
882179193Sjb	do {
883179193Sjb		if (s1 == NULL) {
884179193Sjb			c1 = '\0';
885179193Sjb		} else {
886179193Sjb			c1 = dtrace_load8((uintptr_t)s1++);
887179193Sjb		}
888179193Sjb
889179193Sjb		if (s2 == NULL) {
890179193Sjb			c2 = '\0';
891179193Sjb		} else {
892179193Sjb			c2 = dtrace_load8((uintptr_t)s2++);
893179193Sjb		}
894179193Sjb
895179193Sjb		if (c1 != c2)
896179193Sjb			return (c1 - c2);
897179193Sjb	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
898179193Sjb
899179193Sjb	return (0);
900179193Sjb}
901179193Sjb
902179193Sjb/*
903179193Sjb * Compute strlen(s) for a string using safe memory accesses.  The additional
904179193Sjb * len parameter is used to specify a maximum length to ensure completion.
905179193Sjb */
906179193Sjbstatic size_t
907179193Sjbdtrace_strlen(const char *s, size_t lim)
908179193Sjb{
909179193Sjb	uint_t len;
910179193Sjb
911179193Sjb	for (len = 0; len != lim; len++) {
912179193Sjb		if (dtrace_load8((uintptr_t)s++) == '\0')
913179193Sjb			break;
914179193Sjb	}
915179193Sjb
916179193Sjb	return (len);
917179193Sjb}
918179193Sjb
919179193Sjb/*
920179193Sjb * Check if an address falls within a toxic region.
921179193Sjb */
922179193Sjbstatic int
923179193Sjbdtrace_istoxic(uintptr_t kaddr, size_t size)
924179193Sjb{
925179193Sjb	uintptr_t taddr, tsize;
926179193Sjb	int i;
927179193Sjb
928179193Sjb	for (i = 0; i < dtrace_toxranges; i++) {
929179193Sjb		taddr = dtrace_toxrange[i].dtt_base;
930179193Sjb		tsize = dtrace_toxrange[i].dtt_limit - taddr;
931179193Sjb
932179193Sjb		if (kaddr - taddr < tsize) {
933179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
934179198Sjb			cpu_core[curcpu].cpuc_dtrace_illval = kaddr;
935179193Sjb			return (1);
936179193Sjb		}
937179193Sjb
938179193Sjb		if (taddr - kaddr < size) {
939179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
940179198Sjb			cpu_core[curcpu].cpuc_dtrace_illval = taddr;
941179193Sjb			return (1);
942179193Sjb		}
943179193Sjb	}
944179193Sjb
945179193Sjb	return (0);
946179193Sjb}
947179193Sjb
948179193Sjb/*
949179193Sjb * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
950179193Sjb * memory specified by the DIF program.  The dst is assumed to be safe memory
951179193Sjb * that we can store to directly because it is managed by DTrace.  As with
952179193Sjb * standard bcopy, overlapping copies are handled properly.
953179193Sjb */
954179193Sjbstatic void
955179193Sjbdtrace_bcopy(const void *src, void *dst, size_t len)
956179193Sjb{
957179193Sjb	if (len != 0) {
958179193Sjb		uint8_t *s1 = dst;
959179193Sjb		const uint8_t *s2 = src;
960179193Sjb
961179193Sjb		if (s1 <= s2) {
962179193Sjb			do {
963179193Sjb				*s1++ = dtrace_load8((uintptr_t)s2++);
964179193Sjb			} while (--len != 0);
965179193Sjb		} else {
966179193Sjb			s2 += len;
967179193Sjb			s1 += len;
968179193Sjb
969179193Sjb			do {
970179193Sjb				*--s1 = dtrace_load8((uintptr_t)--s2);
971179193Sjb			} while (--len != 0);
972179193Sjb		}
973179193Sjb	}
974179193Sjb}
975179193Sjb
976179193Sjb/*
977179193Sjb * Copy src to dst using safe memory accesses, up to either the specified
978179193Sjb * length, or the point that a nul byte is encountered.  The src is assumed to
979179193Sjb * be unsafe memory specified by the DIF program.  The dst is assumed to be
980179193Sjb * safe memory that we can store to directly because it is managed by DTrace.
981179193Sjb * Unlike dtrace_bcopy(), overlapping regions are not handled.
982179193Sjb */
983179193Sjbstatic void
984179193Sjbdtrace_strcpy(const void *src, void *dst, size_t len)
985179193Sjb{
986179193Sjb	if (len != 0) {
987179193Sjb		uint8_t *s1 = dst, c;
988179193Sjb		const uint8_t *s2 = src;
989179193Sjb
990179193Sjb		do {
991179193Sjb			*s1++ = c = dtrace_load8((uintptr_t)s2++);
992179193Sjb		} while (--len != 0 && c != '\0');
993179193Sjb	}
994179193Sjb}
995179193Sjb
996179193Sjb/*
997179193Sjb * Copy src to dst, deriving the size and type from the specified (BYREF)
998179193Sjb * variable type.  The src is assumed to be unsafe memory specified by the DIF
999179193Sjb * program.  The dst is assumed to be DTrace variable memory that is of the
1000179193Sjb * specified type; we assume that we can store to directly.
1001179193Sjb */
1002179193Sjbstatic void
1003179193Sjbdtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1004179193Sjb{
1005179193Sjb	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1006179193Sjb
1007179193Sjb	if (type->dtdt_kind == DIF_TYPE_STRING) {
1008179193Sjb		dtrace_strcpy(src, dst, type->dtdt_size);
1009179193Sjb	} else {
1010179193Sjb		dtrace_bcopy(src, dst, type->dtdt_size);
1011179193Sjb	}
1012179193Sjb}
1013179193Sjb
1014179193Sjb/*
1015179193Sjb * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1016179193Sjb * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1017179193Sjb * safe memory that we can access directly because it is managed by DTrace.
1018179193Sjb */
1019179193Sjbstatic int
1020179193Sjbdtrace_bcmp(const void *s1, const void *s2, size_t len)
1021179193Sjb{
1022179193Sjb	volatile uint16_t *flags;
1023179193Sjb
1024179198Sjb	flags = (volatile uint16_t *)&cpu_core[curcpu].cpuc_dtrace_flags;
1025179193Sjb
1026179193Sjb	if (s1 == s2)
1027179193Sjb		return (0);
1028179193Sjb
1029179193Sjb	if (s1 == NULL || s2 == NULL)
1030179193Sjb		return (1);
1031179193Sjb
1032179193Sjb	if (s1 != s2 && len != 0) {
1033179193Sjb		const uint8_t *ps1 = s1;
1034179193Sjb		const uint8_t *ps2 = s2;
1035179193Sjb
1036179193Sjb		do {
1037179193Sjb			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1038179193Sjb				return (1);
1039179193Sjb		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1040179193Sjb	}
1041179193Sjb	return (0);
1042179193Sjb}
1043179193Sjb
1044179193Sjb/*
1045179193Sjb * Zero the specified region using a simple byte-by-byte loop.  Note that this
1046179193Sjb * is for safe DTrace-managed memory only.
1047179193Sjb */
1048179193Sjbstatic void
1049179193Sjbdtrace_bzero(void *dst, size_t len)
1050179193Sjb{
1051179193Sjb	uchar_t *cp;
1052179193Sjb
1053179193Sjb	for (cp = dst; len != 0; len--)
1054179193Sjb		*cp++ = 0;
1055179193Sjb}
1056179193Sjb
1057179193Sjbstatic void
1058179193Sjbdtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1059179193Sjb{
1060179193Sjb	uint64_t result[2];
1061179193Sjb
1062179193Sjb	result[0] = addend1[0] + addend2[0];
1063179193Sjb	result[1] = addend1[1] + addend2[1] +
1064179193Sjb	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1065179193Sjb
1066179193Sjb	sum[0] = result[0];
1067179193Sjb	sum[1] = result[1];
1068179193Sjb}
1069179193Sjb
1070179193Sjb/*
1071179193Sjb * Shift the 128-bit value in a by b. If b is positive, shift left.
1072179193Sjb * If b is negative, shift right.
1073179193Sjb */
1074179193Sjbstatic void
1075179193Sjbdtrace_shift_128(uint64_t *a, int b)
1076179193Sjb{
1077179193Sjb	uint64_t mask;
1078179193Sjb
1079179193Sjb	if (b == 0)
1080179193Sjb		return;
1081179193Sjb
1082179193Sjb	if (b < 0) {
1083179193Sjb		b = -b;
1084179193Sjb		if (b >= 64) {
1085179193Sjb			a[0] = a[1] >> (b - 64);
1086179193Sjb			a[1] = 0;
1087179193Sjb		} else {
1088179193Sjb			a[0] >>= b;
1089179193Sjb			mask = 1LL << (64 - b);
1090179193Sjb			mask -= 1;
1091179193Sjb			a[0] |= ((a[1] & mask) << (64 - b));
1092179193Sjb			a[1] >>= b;
1093179193Sjb		}
1094179193Sjb	} else {
1095179193Sjb		if (b >= 64) {
1096179193Sjb			a[1] = a[0] << (b - 64);
1097179193Sjb			a[0] = 0;
1098179193Sjb		} else {
1099179193Sjb			a[1] <<= b;
1100179193Sjb			mask = a[0] >> (64 - b);
1101179193Sjb			a[1] |= mask;
1102179193Sjb			a[0] <<= b;
1103179193Sjb		}
1104179193Sjb	}
1105179193Sjb}
1106179193Sjb
1107179193Sjb/*
1108179193Sjb * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1109179193Sjb * use native multiplication on those, and then re-combine into the
1110179193Sjb * resulting 128-bit value.
1111179193Sjb *
1112179193Sjb * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1113179193Sjb *     hi1 * hi2 << 64 +
1114179193Sjb *     hi1 * lo2 << 32 +
1115179193Sjb *     hi2 * lo1 << 32 +
1116179193Sjb *     lo1 * lo2
1117179193Sjb */
1118179193Sjbstatic void
1119179193Sjbdtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1120179193Sjb{
1121179193Sjb	uint64_t hi1, hi2, lo1, lo2;
1122179193Sjb	uint64_t tmp[2];
1123179193Sjb
1124179193Sjb	hi1 = factor1 >> 32;
1125179193Sjb	hi2 = factor2 >> 32;
1126179193Sjb
1127179193Sjb	lo1 = factor1 & DT_MASK_LO;
1128179193Sjb	lo2 = factor2 & DT_MASK_LO;
1129179193Sjb
1130179193Sjb	product[0] = lo1 * lo2;
1131179193Sjb	product[1] = hi1 * hi2;
1132179193Sjb
1133179193Sjb	tmp[0] = hi1 * lo2;
1134179193Sjb	tmp[1] = 0;
1135179193Sjb	dtrace_shift_128(tmp, 32);
1136179193Sjb	dtrace_add_128(product, tmp, product);
1137179193Sjb
1138179193Sjb	tmp[0] = hi2 * lo1;
1139179193Sjb	tmp[1] = 0;
1140179193Sjb	dtrace_shift_128(tmp, 32);
1141179193Sjb	dtrace_add_128(product, tmp, product);
1142179193Sjb}
1143179193Sjb
1144179193Sjb/*
1145179193Sjb * This privilege check should be used by actions and subroutines to
1146179193Sjb * verify that the user credentials of the process that enabled the
1147179193Sjb * invoking ECB match the target credentials
1148179193Sjb */
1149179193Sjbstatic int
1150179193Sjbdtrace_priv_proc_common_user(dtrace_state_t *state)
1151179193Sjb{
1152179193Sjb	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1153179193Sjb
1154179193Sjb	/*
1155179193Sjb	 * We should always have a non-NULL state cred here, since if cred
1156179193Sjb	 * is null (anonymous tracing), we fast-path bypass this routine.
1157179193Sjb	 */
1158179193Sjb	ASSERT(s_cr != NULL);
1159179193Sjb
1160179193Sjb	if ((cr = CRED()) != NULL &&
1161179193Sjb	    s_cr->cr_uid == cr->cr_uid &&
1162179193Sjb	    s_cr->cr_uid == cr->cr_ruid &&
1163179193Sjb	    s_cr->cr_uid == cr->cr_suid &&
1164179193Sjb	    s_cr->cr_gid == cr->cr_gid &&
1165179193Sjb	    s_cr->cr_gid == cr->cr_rgid &&
1166179193Sjb	    s_cr->cr_gid == cr->cr_sgid)
1167179193Sjb		return (1);
1168179193Sjb
1169179193Sjb	return (0);
1170179193Sjb}
1171179193Sjb
1172179193Sjb/*
1173179193Sjb * This privilege check should be used by actions and subroutines to
1174179193Sjb * verify that the zone of the process that enabled the invoking ECB
1175179193Sjb * matches the target credentials
1176179193Sjb */
1177179193Sjbstatic int
1178179193Sjbdtrace_priv_proc_common_zone(dtrace_state_t *state)
1179179193Sjb{
1180179198Sjb#if defined(sun)
1181179193Sjb	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1182179193Sjb
1183179193Sjb	/*
1184179193Sjb	 * We should always have a non-NULL state cred here, since if cred
1185179193Sjb	 * is null (anonymous tracing), we fast-path bypass this routine.
1186179193Sjb	 */
1187179193Sjb	ASSERT(s_cr != NULL);
1188179193Sjb
1189179193Sjb	if ((cr = CRED()) != NULL &&
1190179193Sjb	    s_cr->cr_zone == cr->cr_zone)
1191179193Sjb		return (1);
1192179193Sjb
1193179193Sjb	return (0);
1194179198Sjb#else
1195179198Sjb	return (1);
1196179198Sjb#endif
1197179193Sjb}
1198179193Sjb
1199179193Sjb/*
1200179193Sjb * This privilege check should be used by actions and subroutines to
1201179193Sjb * verify that the process has not setuid or changed credentials.
1202179193Sjb */
1203179193Sjbstatic int
1204179198Sjbdtrace_priv_proc_common_nocd(void)
1205179193Sjb{
1206179193Sjb	proc_t *proc;
1207179193Sjb
1208179193Sjb	if ((proc = ttoproc(curthread)) != NULL &&
1209179193Sjb	    !(proc->p_flag & SNOCD))
1210179193Sjb		return (1);
1211179193Sjb
1212179193Sjb	return (0);
1213179193Sjb}
1214179193Sjb
1215179193Sjbstatic int
1216179193Sjbdtrace_priv_proc_destructive(dtrace_state_t *state)
1217179193Sjb{
1218179193Sjb	int action = state->dts_cred.dcr_action;
1219179193Sjb
1220179193Sjb	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1221179193Sjb	    dtrace_priv_proc_common_zone(state) == 0)
1222179193Sjb		goto bad;
1223179193Sjb
1224179193Sjb	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1225179193Sjb	    dtrace_priv_proc_common_user(state) == 0)
1226179193Sjb		goto bad;
1227179193Sjb
1228179193Sjb	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1229179193Sjb	    dtrace_priv_proc_common_nocd() == 0)
1230179193Sjb		goto bad;
1231179193Sjb
1232179193Sjb	return (1);
1233179193Sjb
1234179193Sjbbad:
1235179198Sjb	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1236179193Sjb
1237179193Sjb	return (0);
1238179193Sjb}
1239179193Sjb
1240179193Sjbstatic int
1241179193Sjbdtrace_priv_proc_control(dtrace_state_t *state)
1242179193Sjb{
1243179193Sjb	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1244179193Sjb		return (1);
1245179193Sjb
1246179193Sjb	if (dtrace_priv_proc_common_zone(state) &&
1247179193Sjb	    dtrace_priv_proc_common_user(state) &&
1248179193Sjb	    dtrace_priv_proc_common_nocd())
1249179193Sjb		return (1);
1250179193Sjb
1251179198Sjb	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1252179193Sjb
1253179193Sjb	return (0);
1254179193Sjb}
1255179193Sjb
1256179193Sjbstatic int
1257179193Sjbdtrace_priv_proc(dtrace_state_t *state)
1258179193Sjb{
1259179193Sjb	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1260179193Sjb		return (1);
1261179193Sjb
1262179198Sjb	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1263179193Sjb
1264179193Sjb	return (0);
1265179193Sjb}
1266179193Sjb
1267179193Sjbstatic int
1268179193Sjbdtrace_priv_kernel(dtrace_state_t *state)
1269179193Sjb{
1270179193Sjb	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1271179193Sjb		return (1);
1272179193Sjb
1273179198Sjb	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1274179193Sjb
1275179193Sjb	return (0);
1276179193Sjb}
1277179193Sjb
1278179193Sjbstatic int
1279179193Sjbdtrace_priv_kernel_destructive(dtrace_state_t *state)
1280179193Sjb{
1281179193Sjb	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1282179193Sjb		return (1);
1283179193Sjb
1284179198Sjb	cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1285179193Sjb
1286179193Sjb	return (0);
1287179193Sjb}
1288179193Sjb
1289179193Sjb/*
1290179193Sjb * Note:  not called from probe context.  This function is called
1291179193Sjb * asynchronously (and at a regular interval) from outside of probe context to
1292179193Sjb * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1293179193Sjb * cleaning is explained in detail in <sys/dtrace_impl.h>.
1294179193Sjb */
1295179193Sjbvoid
1296179193Sjbdtrace_dynvar_clean(dtrace_dstate_t *dstate)
1297179193Sjb{
1298179193Sjb	dtrace_dynvar_t *dirty;
1299179193Sjb	dtrace_dstate_percpu_t *dcpu;
1300179193Sjb	int i, work = 0;
1301179193Sjb
1302179193Sjb	for (i = 0; i < NCPU; i++) {
1303179193Sjb		dcpu = &dstate->dtds_percpu[i];
1304179193Sjb
1305179193Sjb		ASSERT(dcpu->dtdsc_rinsing == NULL);
1306179193Sjb
1307179193Sjb		/*
1308179193Sjb		 * If the dirty list is NULL, there is no dirty work to do.
1309179193Sjb		 */
1310179193Sjb		if (dcpu->dtdsc_dirty == NULL)
1311179193Sjb			continue;
1312179193Sjb
1313179193Sjb		/*
1314179193Sjb		 * If the clean list is non-NULL, then we're not going to do
1315179193Sjb		 * any work for this CPU -- it means that there has not been
1316179193Sjb		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1317179193Sjb		 * since the last time we cleaned house.
1318179193Sjb		 */
1319179193Sjb		if (dcpu->dtdsc_clean != NULL)
1320179193Sjb			continue;
1321179193Sjb
1322179193Sjb		work = 1;
1323179193Sjb
1324179193Sjb		/*
1325179193Sjb		 * Atomically move the dirty list aside.
1326179193Sjb		 */
1327179193Sjb		do {
1328179193Sjb			dirty = dcpu->dtdsc_dirty;
1329179193Sjb
1330179193Sjb			/*
1331179193Sjb			 * Before we zap the dirty list, set the rinsing list.
1332179193Sjb			 * (This allows for a potential assertion in
1333179193Sjb			 * dtrace_dynvar():  if a free dynamic variable appears
1334179193Sjb			 * on a hash chain, either the dirty list or the
1335179193Sjb			 * rinsing list for some CPU must be non-NULL.)
1336179193Sjb			 */
1337179193Sjb			dcpu->dtdsc_rinsing = dirty;
1338179193Sjb			dtrace_membar_producer();
1339179193Sjb		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1340179193Sjb		    dirty, NULL) != dirty);
1341179193Sjb	}
1342179193Sjb
1343179193Sjb	if (!work) {
1344179193Sjb		/*
1345179193Sjb		 * We have no work to do; we can simply return.
1346179193Sjb		 */
1347179193Sjb		return;
1348179193Sjb	}
1349179193Sjb
1350179193Sjb	dtrace_sync();
1351179193Sjb
1352179193Sjb	for (i = 0; i < NCPU; i++) {
1353179193Sjb		dcpu = &dstate->dtds_percpu[i];
1354179193Sjb
1355179193Sjb		if (dcpu->dtdsc_rinsing == NULL)
1356179193Sjb			continue;
1357179193Sjb
1358179193Sjb		/*
1359179193Sjb		 * We are now guaranteed that no hash chain contains a pointer
1360179193Sjb		 * into this dirty list; we can make it clean.
1361179193Sjb		 */
1362179193Sjb		ASSERT(dcpu->dtdsc_clean == NULL);
1363179193Sjb		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1364179193Sjb		dcpu->dtdsc_rinsing = NULL;
1365179193Sjb	}
1366179193Sjb
1367179193Sjb	/*
1368179193Sjb	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1369179193Sjb	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1370179193Sjb	 * This prevents a race whereby a CPU incorrectly decides that
1371179193Sjb	 * the state should be something other than DTRACE_DSTATE_CLEAN
1372179193Sjb	 * after dtrace_dynvar_clean() has completed.
1373179193Sjb	 */
1374179193Sjb	dtrace_sync();
1375179193Sjb
1376179193Sjb	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1377179193Sjb}
1378179193Sjb
1379179193Sjb/*
1380179193Sjb * Depending on the value of the op parameter, this function looks-up,
1381179193Sjb * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1382179193Sjb * allocation is requested, this function will return a pointer to a
1383179193Sjb * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1384179193Sjb * variable can be allocated.  If NULL is returned, the appropriate counter
1385179193Sjb * will be incremented.
1386179193Sjb */
1387179193Sjbdtrace_dynvar_t *
1388179193Sjbdtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1389179193Sjb    dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1390179193Sjb    dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1391179193Sjb{
1392179193Sjb	uint64_t hashval = DTRACE_DYNHASH_VALID;
1393179193Sjb	dtrace_dynhash_t *hash = dstate->dtds_hash;
1394179193Sjb	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1395179198Sjb	processorid_t me = curcpu, cpu = me;
1396179193Sjb	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1397179193Sjb	size_t bucket, ksize;
1398179193Sjb	size_t chunksize = dstate->dtds_chunksize;
1399179193Sjb	uintptr_t kdata, lock, nstate;
1400179193Sjb	uint_t i;
1401179193Sjb
1402179193Sjb	ASSERT(nkeys != 0);
1403179193Sjb
1404179193Sjb	/*
1405179193Sjb	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1406179193Sjb	 * algorithm.  For the by-value portions, we perform the algorithm in
1407179193Sjb	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1408179193Sjb	 * bit, and seems to have only a minute effect on distribution.  For
1409179193Sjb	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1410179193Sjb	 * over each referenced byte.  It's painful to do this, but it's much
1411179193Sjb	 * better than pathological hash distribution.  The efficacy of the
1412179193Sjb	 * hashing algorithm (and a comparison with other algorithms) may be
1413179193Sjb	 * found by running the ::dtrace_dynstat MDB dcmd.
1414179193Sjb	 */
1415179193Sjb	for (i = 0; i < nkeys; i++) {
1416179193Sjb		if (key[i].dttk_size == 0) {
1417179193Sjb			uint64_t val = key[i].dttk_value;
1418179193Sjb
1419179193Sjb			hashval += (val >> 48) & 0xffff;
1420179193Sjb			hashval += (hashval << 10);
1421179193Sjb			hashval ^= (hashval >> 6);
1422179193Sjb
1423179193Sjb			hashval += (val >> 32) & 0xffff;
1424179193Sjb			hashval += (hashval << 10);
1425179193Sjb			hashval ^= (hashval >> 6);
1426179193Sjb
1427179193Sjb			hashval += (val >> 16) & 0xffff;
1428179193Sjb			hashval += (hashval << 10);
1429179193Sjb			hashval ^= (hashval >> 6);
1430179193Sjb
1431179193Sjb			hashval += val & 0xffff;
1432179193Sjb			hashval += (hashval << 10);
1433179193Sjb			hashval ^= (hashval >> 6);
1434179193Sjb		} else {
1435179193Sjb			/*
1436179193Sjb			 * This is incredibly painful, but it beats the hell
1437179193Sjb			 * out of the alternative.
1438179193Sjb			 */
1439179193Sjb			uint64_t j, size = key[i].dttk_size;
1440179193Sjb			uintptr_t base = (uintptr_t)key[i].dttk_value;
1441179193Sjb
1442179193Sjb			if (!dtrace_canload(base, size, mstate, vstate))
1443179193Sjb				break;
1444179193Sjb
1445179193Sjb			for (j = 0; j < size; j++) {
1446179193Sjb				hashval += dtrace_load8(base + j);
1447179193Sjb				hashval += (hashval << 10);
1448179193Sjb				hashval ^= (hashval >> 6);
1449179193Sjb			}
1450179193Sjb		}
1451179193Sjb	}
1452179193Sjb
1453179193Sjb	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1454179193Sjb		return (NULL);
1455179193Sjb
1456179193Sjb	hashval += (hashval << 3);
1457179193Sjb	hashval ^= (hashval >> 11);
1458179193Sjb	hashval += (hashval << 15);
1459179193Sjb
1460179193Sjb	/*
1461179193Sjb	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1462179193Sjb	 * comes out to be one of our two sentinel hash values.  If this
1463179193Sjb	 * actually happens, we set the hashval to be a value known to be a
1464179193Sjb	 * non-sentinel value.
1465179193Sjb	 */
1466179193Sjb	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1467179193Sjb		hashval = DTRACE_DYNHASH_VALID;
1468179193Sjb
1469179193Sjb	/*
1470179193Sjb	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1471179193Sjb	 * important here, tricks can be pulled to reduce it.  (However, it's
1472179193Sjb	 * critical that hash collisions be kept to an absolute minimum;
1473179193Sjb	 * they're much more painful than a divide.)  It's better to have a
1474179193Sjb	 * solution that generates few collisions and still keeps things
1475179193Sjb	 * relatively simple.
1476179193Sjb	 */
1477179193Sjb	bucket = hashval % dstate->dtds_hashsize;
1478179193Sjb
1479179193Sjb	if (op == DTRACE_DYNVAR_DEALLOC) {
1480179193Sjb		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1481179193Sjb
1482179193Sjb		for (;;) {
1483179193Sjb			while ((lock = *lockp) & 1)
1484179193Sjb				continue;
1485179193Sjb
1486179198Sjb			if (dtrace_casptr((volatile void *)lockp,
1487179198Sjb			    (volatile void *)lock, (volatile void *)(lock + 1)) == (void *)lock)
1488179193Sjb				break;
1489179193Sjb		}
1490179193Sjb
1491179193Sjb		dtrace_membar_producer();
1492179193Sjb	}
1493179193Sjb
1494179193Sjbtop:
1495179193Sjb	prev = NULL;
1496179193Sjb	lock = hash[bucket].dtdh_lock;
1497179193Sjb
1498179193Sjb	dtrace_membar_consumer();
1499179193Sjb
1500179193Sjb	start = hash[bucket].dtdh_chain;
1501179193Sjb	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1502179193Sjb	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1503179193Sjb	    op != DTRACE_DYNVAR_DEALLOC));
1504179193Sjb
1505179193Sjb	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1506179193Sjb		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1507179193Sjb		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1508179193Sjb
1509179193Sjb		if (dvar->dtdv_hashval != hashval) {
1510179193Sjb			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1511179193Sjb				/*
1512179193Sjb				 * We've reached the sink, and therefore the
1513179193Sjb				 * end of the hash chain; we can kick out of
1514179193Sjb				 * the loop knowing that we have seen a valid
1515179193Sjb				 * snapshot of state.
1516179193Sjb				 */
1517179193Sjb				ASSERT(dvar->dtdv_next == NULL);
1518179193Sjb				ASSERT(dvar == &dtrace_dynhash_sink);
1519179193Sjb				break;
1520179193Sjb			}
1521179193Sjb
1522179193Sjb			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1523179193Sjb				/*
1524179193Sjb				 * We've gone off the rails:  somewhere along
1525179193Sjb				 * the line, one of the members of this hash
1526179193Sjb				 * chain was deleted.  Note that we could also
1527179193Sjb				 * detect this by simply letting this loop run
1528179193Sjb				 * to completion, as we would eventually hit
1529179193Sjb				 * the end of the dirty list.  However, we
1530179193Sjb				 * want to avoid running the length of the
1531179193Sjb				 * dirty list unnecessarily (it might be quite
1532179193Sjb				 * long), so we catch this as early as
1533179193Sjb				 * possible by detecting the hash marker.  In
1534179193Sjb				 * this case, we simply set dvar to NULL and
1535179193Sjb				 * break; the conditional after the loop will
1536179193Sjb				 * send us back to top.
1537179193Sjb				 */
1538179193Sjb				dvar = NULL;
1539179193Sjb				break;
1540179193Sjb			}
1541179193Sjb
1542179193Sjb			goto next;
1543179193Sjb		}
1544179193Sjb
1545179193Sjb		if (dtuple->dtt_nkeys != nkeys)
1546179193Sjb			goto next;
1547179193Sjb
1548179193Sjb		for (i = 0; i < nkeys; i++, dkey++) {
1549179193Sjb			if (dkey->dttk_size != key[i].dttk_size)
1550179193Sjb				goto next; /* size or type mismatch */
1551179193Sjb
1552179193Sjb			if (dkey->dttk_size != 0) {
1553179193Sjb				if (dtrace_bcmp(
1554179193Sjb				    (void *)(uintptr_t)key[i].dttk_value,
1555179193Sjb				    (void *)(uintptr_t)dkey->dttk_value,
1556179193Sjb				    dkey->dttk_size))
1557179193Sjb					goto next;
1558179193Sjb			} else {
1559179193Sjb				if (dkey->dttk_value != key[i].dttk_value)
1560179193Sjb					goto next;
1561179193Sjb			}
1562179193Sjb		}
1563179193Sjb
1564179193Sjb		if (op != DTRACE_DYNVAR_DEALLOC)
1565179193Sjb			return (dvar);
1566179193Sjb
1567179193Sjb		ASSERT(dvar->dtdv_next == NULL ||
1568179193Sjb		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1569179193Sjb
1570179193Sjb		if (prev != NULL) {
1571179193Sjb			ASSERT(hash[bucket].dtdh_chain != dvar);
1572179193Sjb			ASSERT(start != dvar);
1573179193Sjb			ASSERT(prev->dtdv_next == dvar);
1574179193Sjb			prev->dtdv_next = dvar->dtdv_next;
1575179193Sjb		} else {
1576179193Sjb			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1577179193Sjb			    start, dvar->dtdv_next) != start) {
1578179193Sjb				/*
1579179193Sjb				 * We have failed to atomically swing the
1580179193Sjb				 * hash table head pointer, presumably because
1581179193Sjb				 * of a conflicting allocation on another CPU.
1582179193Sjb				 * We need to reread the hash chain and try
1583179193Sjb				 * again.
1584179193Sjb				 */
1585179193Sjb				goto top;
1586179193Sjb			}
1587179193Sjb		}
1588179193Sjb
1589179193Sjb		dtrace_membar_producer();
1590179193Sjb
1591179193Sjb		/*
1592179193Sjb		 * Now set the hash value to indicate that it's free.
1593179193Sjb		 */
1594179193Sjb		ASSERT(hash[bucket].dtdh_chain != dvar);
1595179193Sjb		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1596179193Sjb
1597179193Sjb		dtrace_membar_producer();
1598179193Sjb
1599179193Sjb		/*
1600179193Sjb		 * Set the next pointer to point at the dirty list, and
1601179193Sjb		 * atomically swing the dirty pointer to the newly freed dvar.
1602179193Sjb		 */
1603179193Sjb		do {
1604179193Sjb			next = dcpu->dtdsc_dirty;
1605179193Sjb			dvar->dtdv_next = next;
1606179193Sjb		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1607179193Sjb
1608179193Sjb		/*
1609179193Sjb		 * Finally, unlock this hash bucket.
1610179193Sjb		 */
1611179193Sjb		ASSERT(hash[bucket].dtdh_lock == lock);
1612179193Sjb		ASSERT(lock & 1);
1613179193Sjb		hash[bucket].dtdh_lock++;
1614179193Sjb
1615179193Sjb		return (NULL);
1616179193Sjbnext:
1617179193Sjb		prev = dvar;
1618179193Sjb		continue;
1619179193Sjb	}
1620179193Sjb
1621179193Sjb	if (dvar == NULL) {
1622179193Sjb		/*
1623179193Sjb		 * If dvar is NULL, it is because we went off the rails:
1624179193Sjb		 * one of the elements that we traversed in the hash chain
1625179193Sjb		 * was deleted while we were traversing it.  In this case,
1626179193Sjb		 * we assert that we aren't doing a dealloc (deallocs lock
1627179193Sjb		 * the hash bucket to prevent themselves from racing with
1628179193Sjb		 * one another), and retry the hash chain traversal.
1629179193Sjb		 */
1630179193Sjb		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1631179193Sjb		goto top;
1632179193Sjb	}
1633179193Sjb
1634179193Sjb	if (op != DTRACE_DYNVAR_ALLOC) {
1635179193Sjb		/*
1636179193Sjb		 * If we are not to allocate a new variable, we want to
1637179193Sjb		 * return NULL now.  Before we return, check that the value
1638179193Sjb		 * of the lock word hasn't changed.  If it has, we may have
1639179193Sjb		 * seen an inconsistent snapshot.
1640179193Sjb		 */
1641179193Sjb		if (op == DTRACE_DYNVAR_NOALLOC) {
1642179193Sjb			if (hash[bucket].dtdh_lock != lock)
1643179193Sjb				goto top;
1644179193Sjb		} else {
1645179193Sjb			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1646179193Sjb			ASSERT(hash[bucket].dtdh_lock == lock);
1647179193Sjb			ASSERT(lock & 1);
1648179193Sjb			hash[bucket].dtdh_lock++;
1649179193Sjb		}
1650179193Sjb
1651179193Sjb		return (NULL);
1652179193Sjb	}
1653179193Sjb
1654179193Sjb	/*
1655179193Sjb	 * We need to allocate a new dynamic variable.  The size we need is the
1656179193Sjb	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1657179193Sjb	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1658179193Sjb	 * the size of any referred-to data (dsize).  We then round the final
1659179193Sjb	 * size up to the chunksize for allocation.
1660179193Sjb	 */
1661179193Sjb	for (ksize = 0, i = 0; i < nkeys; i++)
1662179193Sjb		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1663179193Sjb
1664179193Sjb	/*
1665179193Sjb	 * This should be pretty much impossible, but could happen if, say,
1666179193Sjb	 * strange DIF specified the tuple.  Ideally, this should be an
1667179193Sjb	 * assertion and not an error condition -- but that requires that the
1668179193Sjb	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1669179193Sjb	 * bullet-proof.  (That is, it must not be able to be fooled by
1670179193Sjb	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1671179193Sjb	 * solving this would presumably not amount to solving the Halting
1672179193Sjb	 * Problem -- but it still seems awfully hard.
1673179193Sjb	 */
1674179193Sjb	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1675179193Sjb	    ksize + dsize > chunksize) {
1676179193Sjb		dcpu->dtdsc_drops++;
1677179193Sjb		return (NULL);
1678179193Sjb	}
1679179193Sjb
1680179193Sjb	nstate = DTRACE_DSTATE_EMPTY;
1681179193Sjb
1682179193Sjb	do {
1683179193Sjbretry:
1684179193Sjb		free = dcpu->dtdsc_free;
1685179193Sjb
1686179193Sjb		if (free == NULL) {
1687179193Sjb			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1688179193Sjb			void *rval;
1689179193Sjb
1690179193Sjb			if (clean == NULL) {
1691179193Sjb				/*
1692179193Sjb				 * We're out of dynamic variable space on
1693179193Sjb				 * this CPU.  Unless we have tried all CPUs,
1694179193Sjb				 * we'll try to allocate from a different
1695179193Sjb				 * CPU.
1696179193Sjb				 */
1697179193Sjb				switch (dstate->dtds_state) {
1698179193Sjb				case DTRACE_DSTATE_CLEAN: {
1699179193Sjb					void *sp = &dstate->dtds_state;
1700179193Sjb
1701179193Sjb					if (++cpu >= NCPU)
1702179193Sjb						cpu = 0;
1703179193Sjb
1704179193Sjb					if (dcpu->dtdsc_dirty != NULL &&
1705179193Sjb					    nstate == DTRACE_DSTATE_EMPTY)
1706179193Sjb						nstate = DTRACE_DSTATE_DIRTY;
1707179193Sjb
1708179193Sjb					if (dcpu->dtdsc_rinsing != NULL)
1709179193Sjb						nstate = DTRACE_DSTATE_RINSING;
1710179193Sjb
1711179193Sjb					dcpu = &dstate->dtds_percpu[cpu];
1712179193Sjb
1713179193Sjb					if (cpu != me)
1714179193Sjb						goto retry;
1715179193Sjb
1716179193Sjb					(void) dtrace_cas32(sp,
1717179193Sjb					    DTRACE_DSTATE_CLEAN, nstate);
1718179193Sjb
1719179193Sjb					/*
1720179193Sjb					 * To increment the correct bean
1721179193Sjb					 * counter, take another lap.
1722179193Sjb					 */
1723179193Sjb					goto retry;
1724179193Sjb				}
1725179193Sjb
1726179193Sjb				case DTRACE_DSTATE_DIRTY:
1727179193Sjb					dcpu->dtdsc_dirty_drops++;
1728179193Sjb					break;
1729179193Sjb
1730179193Sjb				case DTRACE_DSTATE_RINSING:
1731179193Sjb					dcpu->dtdsc_rinsing_drops++;
1732179193Sjb					break;
1733179193Sjb
1734179193Sjb				case DTRACE_DSTATE_EMPTY:
1735179193Sjb					dcpu->dtdsc_drops++;
1736179193Sjb					break;
1737179193Sjb				}
1738179193Sjb
1739179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1740179193Sjb				return (NULL);
1741179193Sjb			}
1742179193Sjb
1743179193Sjb			/*
1744179193Sjb			 * The clean list appears to be non-empty.  We want to
1745179193Sjb			 * move the clean list to the free list; we start by
1746179193Sjb			 * moving the clean pointer aside.
1747179193Sjb			 */
1748179193Sjb			if (dtrace_casptr(&dcpu->dtdsc_clean,
1749179193Sjb			    clean, NULL) != clean) {
1750179193Sjb				/*
1751179193Sjb				 * We are in one of two situations:
1752179193Sjb				 *
1753179193Sjb				 *  (a)	The clean list was switched to the
1754179193Sjb				 *	free list by another CPU.
1755179193Sjb				 *
1756179193Sjb				 *  (b)	The clean list was added to by the
1757179193Sjb				 *	cleansing cyclic.
1758179193Sjb				 *
1759179193Sjb				 * In either of these situations, we can
1760179193Sjb				 * just reattempt the free list allocation.
1761179193Sjb				 */
1762179193Sjb				goto retry;
1763179193Sjb			}
1764179193Sjb
1765179193Sjb			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1766179193Sjb
1767179193Sjb			/*
1768179193Sjb			 * Now we'll move the clean list to the free list.
1769179193Sjb			 * It's impossible for this to fail:  the only way
1770179193Sjb			 * the free list can be updated is through this
1771179193Sjb			 * code path, and only one CPU can own the clean list.
1772179193Sjb			 * Thus, it would only be possible for this to fail if
1773179193Sjb			 * this code were racing with dtrace_dynvar_clean().
1774179193Sjb			 * (That is, if dtrace_dynvar_clean() updated the clean
1775179193Sjb			 * list, and we ended up racing to update the free
1776179193Sjb			 * list.)  This race is prevented by the dtrace_sync()
1777179193Sjb			 * in dtrace_dynvar_clean() -- which flushes the
1778179193Sjb			 * owners of the clean lists out before resetting
1779179193Sjb			 * the clean lists.
1780179193Sjb			 */
1781179193Sjb			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1782179193Sjb			ASSERT(rval == NULL);
1783179193Sjb			goto retry;
1784179193Sjb		}
1785179193Sjb
1786179193Sjb		dvar = free;
1787179193Sjb		new_free = dvar->dtdv_next;
1788179193Sjb	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1789179193Sjb
1790179193Sjb	/*
1791179193Sjb	 * We have now allocated a new chunk.  We copy the tuple keys into the
1792179193Sjb	 * tuple array and copy any referenced key data into the data space
1793179193Sjb	 * following the tuple array.  As we do this, we relocate dttk_value
1794179193Sjb	 * in the final tuple to point to the key data address in the chunk.
1795179193Sjb	 */
1796179193Sjb	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1797179193Sjb	dvar->dtdv_data = (void *)(kdata + ksize);
1798179193Sjb	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1799179193Sjb
1800179193Sjb	for (i = 0; i < nkeys; i++) {
1801179193Sjb		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1802179193Sjb		size_t kesize = key[i].dttk_size;
1803179193Sjb
1804179193Sjb		if (kesize != 0) {
1805179193Sjb			dtrace_bcopy(
1806179193Sjb			    (const void *)(uintptr_t)key[i].dttk_value,
1807179193Sjb			    (void *)kdata, kesize);
1808179193Sjb			dkey->dttk_value = kdata;
1809179193Sjb			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1810179193Sjb		} else {
1811179193Sjb			dkey->dttk_value = key[i].dttk_value;
1812179193Sjb		}
1813179193Sjb
1814179193Sjb		dkey->dttk_size = kesize;
1815179193Sjb	}
1816179193Sjb
1817179193Sjb	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1818179193Sjb	dvar->dtdv_hashval = hashval;
1819179193Sjb	dvar->dtdv_next = start;
1820179193Sjb
1821179193Sjb	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1822179193Sjb		return (dvar);
1823179193Sjb
1824179193Sjb	/*
1825179193Sjb	 * The cas has failed.  Either another CPU is adding an element to
1826179193Sjb	 * this hash chain, or another CPU is deleting an element from this
1827179193Sjb	 * hash chain.  The simplest way to deal with both of these cases
1828179193Sjb	 * (though not necessarily the most efficient) is to free our
1829179193Sjb	 * allocated block and tail-call ourselves.  Note that the free is
1830179193Sjb	 * to the dirty list and _not_ to the free list.  This is to prevent
1831179193Sjb	 * races with allocators, above.
1832179193Sjb	 */
1833179193Sjb	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1834179193Sjb
1835179193Sjb	dtrace_membar_producer();
1836179193Sjb
1837179193Sjb	do {
1838179193Sjb		free = dcpu->dtdsc_dirty;
1839179193Sjb		dvar->dtdv_next = free;
1840179193Sjb	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1841179193Sjb
1842179193Sjb	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1843179193Sjb}
1844179193Sjb
1845179193Sjb/*ARGSUSED*/
1846179193Sjbstatic void
1847179193Sjbdtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1848179193Sjb{
1849179193Sjb	if ((int64_t)nval < (int64_t)*oval)
1850179193Sjb		*oval = nval;
1851179193Sjb}
1852179193Sjb
1853179193Sjb/*ARGSUSED*/
1854179193Sjbstatic void
1855179193Sjbdtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1856179193Sjb{
1857179193Sjb	if ((int64_t)nval > (int64_t)*oval)
1858179193Sjb		*oval = nval;
1859179193Sjb}
1860179193Sjb
1861179193Sjbstatic void
1862179193Sjbdtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1863179193Sjb{
1864179193Sjb	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1865179193Sjb	int64_t val = (int64_t)nval;
1866179193Sjb
1867179193Sjb	if (val < 0) {
1868179193Sjb		for (i = 0; i < zero; i++) {
1869179193Sjb			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1870179193Sjb				quanta[i] += incr;
1871179193Sjb				return;
1872179193Sjb			}
1873179193Sjb		}
1874179193Sjb	} else {
1875179193Sjb		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1876179193Sjb			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1877179193Sjb				quanta[i - 1] += incr;
1878179193Sjb				return;
1879179193Sjb			}
1880179193Sjb		}
1881179193Sjb
1882179193Sjb		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1883179193Sjb		return;
1884179193Sjb	}
1885179193Sjb
1886179193Sjb	ASSERT(0);
1887179193Sjb}
1888179193Sjb
1889179193Sjbstatic void
1890179193Sjbdtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1891179193Sjb{
1892179193Sjb	uint64_t arg = *lquanta++;
1893179193Sjb	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1894179193Sjb	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1895179193Sjb	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1896179193Sjb	int32_t val = (int32_t)nval, level;
1897179193Sjb
1898179193Sjb	ASSERT(step != 0);
1899179193Sjb	ASSERT(levels != 0);
1900179193Sjb
1901179193Sjb	if (val < base) {
1902179193Sjb		/*
1903179193Sjb		 * This is an underflow.
1904179193Sjb		 */
1905179193Sjb		lquanta[0] += incr;
1906179193Sjb		return;
1907179193Sjb	}
1908179193Sjb
1909179193Sjb	level = (val - base) / step;
1910179193Sjb
1911179193Sjb	if (level < levels) {
1912179193Sjb		lquanta[level + 1] += incr;
1913179193Sjb		return;
1914179193Sjb	}
1915179193Sjb
1916179193Sjb	/*
1917179193Sjb	 * This is an overflow.
1918179193Sjb	 */
1919179193Sjb	lquanta[levels + 1] += incr;
1920179193Sjb}
1921179193Sjb
1922237870Spfgstatic int
1923237870Spfgdtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
1924237870Spfg    uint16_t high, uint16_t nsteps, int64_t value)
1925237870Spfg{
1926237870Spfg	int64_t this = 1, last, next;
1927237870Spfg	int base = 1, order;
1928237870Spfg
1929237870Spfg	ASSERT(factor <= nsteps);
1930237870Spfg	ASSERT(nsteps % factor == 0);
1931237870Spfg
1932237870Spfg	for (order = 0; order < low; order++)
1933237870Spfg		this *= factor;
1934237870Spfg
1935237870Spfg	/*
1936237870Spfg	 * If our value is less than our factor taken to the power of the
1937237870Spfg	 * low order of magnitude, it goes into the zeroth bucket.
1938237870Spfg	 */
1939237870Spfg	if (value < (last = this))
1940237870Spfg		return (0);
1941237870Spfg
1942237870Spfg	for (this *= factor; order <= high; order++) {
1943237870Spfg		int nbuckets = this > nsteps ? nsteps : this;
1944237870Spfg
1945237870Spfg		if ((next = this * factor) < this) {
1946237870Spfg			/*
1947237870Spfg			 * We should not generally get log/linear quantizations
1948237870Spfg			 * with a high magnitude that allows 64-bits to
1949237870Spfg			 * overflow, but we nonetheless protect against this
1950237870Spfg			 * by explicitly checking for overflow, and clamping
1951237870Spfg			 * our value accordingly.
1952237870Spfg			 */
1953237870Spfg			value = this - 1;
1954237870Spfg		}
1955237870Spfg
1956237870Spfg		if (value < this) {
1957237870Spfg			/*
1958237870Spfg			 * If our value lies within this order of magnitude,
1959237870Spfg			 * determine its position by taking the offset within
1960237870Spfg			 * the order of magnitude, dividing by the bucket
1961237870Spfg			 * width, and adding to our (accumulated) base.
1962237870Spfg			 */
1963237870Spfg			return (base + (value - last) / (this / nbuckets));
1964237870Spfg		}
1965237870Spfg
1966237870Spfg		base += nbuckets - (nbuckets / factor);
1967237870Spfg		last = this;
1968237870Spfg		this = next;
1969237870Spfg	}
1970237870Spfg
1971237870Spfg	/*
1972237870Spfg	 * Our value is greater than or equal to our factor taken to the
1973237870Spfg	 * power of one plus the high magnitude -- return the top bucket.
1974237870Spfg	 */
1975237870Spfg	return (base);
1976237870Spfg}
1977237870Spfg
1978237870Spfgstatic void
1979237870Spfgdtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
1980237870Spfg{
1981237870Spfg	uint64_t arg = *llquanta++;
1982237870Spfg	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
1983237870Spfg	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
1984237870Spfg	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
1985237870Spfg	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
1986237870Spfg
1987237870Spfg	llquanta[dtrace_aggregate_llquantize_bucket(factor,
1988237870Spfg	    low, high, nsteps, nval)] += incr;
1989237870Spfg}
1990237870Spfg
1991179193Sjb/*ARGSUSED*/
1992179193Sjbstatic void
1993179193Sjbdtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1994179193Sjb{
1995179193Sjb	data[0]++;
1996179193Sjb	data[1] += nval;
1997179193Sjb}
1998179193Sjb
1999179193Sjb/*ARGSUSED*/
2000179193Sjbstatic void
2001179193Sjbdtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2002179193Sjb{
2003179193Sjb	int64_t snval = (int64_t)nval;
2004179193Sjb	uint64_t tmp[2];
2005179193Sjb
2006179193Sjb	data[0]++;
2007179193Sjb	data[1] += nval;
2008179193Sjb
2009179193Sjb	/*
2010179193Sjb	 * What we want to say here is:
2011179193Sjb	 *
2012179193Sjb	 * data[2] += nval * nval;
2013179193Sjb	 *
2014179193Sjb	 * But given that nval is 64-bit, we could easily overflow, so
2015179193Sjb	 * we do this as 128-bit arithmetic.
2016179193Sjb	 */
2017179193Sjb	if (snval < 0)
2018179193Sjb		snval = -snval;
2019179193Sjb
2020179193Sjb	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2021179193Sjb	dtrace_add_128(data + 2, tmp, data + 2);
2022179193Sjb}
2023179193Sjb
2024179193Sjb/*ARGSUSED*/
2025179193Sjbstatic void
2026179193Sjbdtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2027179193Sjb{
2028179193Sjb	*oval = *oval + 1;
2029179193Sjb}
2030179193Sjb
2031179193Sjb/*ARGSUSED*/
2032179193Sjbstatic void
2033179193Sjbdtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2034179193Sjb{
2035179193Sjb	*oval += nval;
2036179193Sjb}
2037179193Sjb
2038179193Sjb/*
2039179193Sjb * Aggregate given the tuple in the principal data buffer, and the aggregating
2040179193Sjb * action denoted by the specified dtrace_aggregation_t.  The aggregation
2041179193Sjb * buffer is specified as the buf parameter.  This routine does not return
2042179193Sjb * failure; if there is no space in the aggregation buffer, the data will be
2043179193Sjb * dropped, and a corresponding counter incremented.
2044179193Sjb */
2045179193Sjbstatic void
2046179193Sjbdtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2047179193Sjb    intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2048179193Sjb{
2049179193Sjb	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2050179193Sjb	uint32_t i, ndx, size, fsize;
2051179193Sjb	uint32_t align = sizeof (uint64_t) - 1;
2052179193Sjb	dtrace_aggbuffer_t *agb;
2053179193Sjb	dtrace_aggkey_t *key;
2054179193Sjb	uint32_t hashval = 0, limit, isstr;
2055179193Sjb	caddr_t tomax, data, kdata;
2056179193Sjb	dtrace_actkind_t action;
2057179193Sjb	dtrace_action_t *act;
2058179193Sjb	uintptr_t offs;
2059179193Sjb
2060179193Sjb	if (buf == NULL)
2061179193Sjb		return;
2062179193Sjb
2063179193Sjb	if (!agg->dtag_hasarg) {
2064179193Sjb		/*
2065179193Sjb		 * Currently, only quantize() and lquantize() take additional
2066179193Sjb		 * arguments, and they have the same semantics:  an increment
2067179193Sjb		 * value that defaults to 1 when not present.  If additional
2068179193Sjb		 * aggregating actions take arguments, the setting of the
2069179193Sjb		 * default argument value will presumably have to become more
2070179193Sjb		 * sophisticated...
2071179193Sjb		 */
2072179193Sjb		arg = 1;
2073179193Sjb	}
2074179193Sjb
2075179193Sjb	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2076179193Sjb	size = rec->dtrd_offset - agg->dtag_base;
2077179193Sjb	fsize = size + rec->dtrd_size;
2078179193Sjb
2079179193Sjb	ASSERT(dbuf->dtb_tomax != NULL);
2080179193Sjb	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2081179193Sjb
2082179193Sjb	if ((tomax = buf->dtb_tomax) == NULL) {
2083179193Sjb		dtrace_buffer_drop(buf);
2084179193Sjb		return;
2085179193Sjb	}
2086179193Sjb
2087179193Sjb	/*
2088179193Sjb	 * The metastructure is always at the bottom of the buffer.
2089179193Sjb	 */
2090179193Sjb	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2091179193Sjb	    sizeof (dtrace_aggbuffer_t));
2092179193Sjb
2093179193Sjb	if (buf->dtb_offset == 0) {
2094179193Sjb		/*
2095179193Sjb		 * We just kludge up approximately 1/8th of the size to be
2096179193Sjb		 * buckets.  If this guess ends up being routinely
2097179193Sjb		 * off-the-mark, we may need to dynamically readjust this
2098179193Sjb		 * based on past performance.
2099179193Sjb		 */
2100179193Sjb		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2101179193Sjb
2102179193Sjb		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2103179193Sjb		    (uintptr_t)tomax || hashsize == 0) {
2104179193Sjb			/*
2105179193Sjb			 * We've been given a ludicrously small buffer;
2106179193Sjb			 * increment our drop count and leave.
2107179193Sjb			 */
2108179193Sjb			dtrace_buffer_drop(buf);
2109179193Sjb			return;
2110179193Sjb		}
2111179193Sjb
2112179193Sjb		/*
2113179193Sjb		 * And now, a pathetic attempt to try to get a an odd (or
2114179193Sjb		 * perchance, a prime) hash size for better hash distribution.
2115179193Sjb		 */
2116179193Sjb		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2117179193Sjb			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2118179193Sjb
2119179193Sjb		agb->dtagb_hashsize = hashsize;
2120179193Sjb		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2121179193Sjb		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2122179193Sjb		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2123179193Sjb
2124179193Sjb		for (i = 0; i < agb->dtagb_hashsize; i++)
2125179193Sjb			agb->dtagb_hash[i] = NULL;
2126179193Sjb	}
2127179193Sjb
2128179193Sjb	ASSERT(agg->dtag_first != NULL);
2129179193Sjb	ASSERT(agg->dtag_first->dta_intuple);
2130179193Sjb
2131179193Sjb	/*
2132179193Sjb	 * Calculate the hash value based on the key.  Note that we _don't_
2133179193Sjb	 * include the aggid in the hashing (but we will store it as part of
2134179193Sjb	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2135179193Sjb	 * algorithm: a simple, quick algorithm that has no known funnels, and
2136179193Sjb	 * gets good distribution in practice.  The efficacy of the hashing
2137179193Sjb	 * algorithm (and a comparison with other algorithms) may be found by
2138179193Sjb	 * running the ::dtrace_aggstat MDB dcmd.
2139179193Sjb	 */
2140179193Sjb	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2141179193Sjb		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2142179193Sjb		limit = i + act->dta_rec.dtrd_size;
2143179193Sjb		ASSERT(limit <= size);
2144179193Sjb		isstr = DTRACEACT_ISSTRING(act);
2145179193Sjb
2146179193Sjb		for (; i < limit; i++) {
2147179193Sjb			hashval += data[i];
2148179193Sjb			hashval += (hashval << 10);
2149179193Sjb			hashval ^= (hashval >> 6);
2150179193Sjb
2151179193Sjb			if (isstr && data[i] == '\0')
2152179193Sjb				break;
2153179193Sjb		}
2154179193Sjb	}
2155179193Sjb
2156179193Sjb	hashval += (hashval << 3);
2157179193Sjb	hashval ^= (hashval >> 11);
2158179193Sjb	hashval += (hashval << 15);
2159179193Sjb
2160179193Sjb	/*
2161179193Sjb	 * Yes, the divide here is expensive -- but it's generally the least
2162179193Sjb	 * of the performance issues given the amount of data that we iterate
2163179193Sjb	 * over to compute hash values, compare data, etc.
2164179193Sjb	 */
2165179193Sjb	ndx = hashval % agb->dtagb_hashsize;
2166179193Sjb
2167179193Sjb	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2168179193Sjb		ASSERT((caddr_t)key >= tomax);
2169179193Sjb		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2170179193Sjb
2171179193Sjb		if (hashval != key->dtak_hashval || key->dtak_size != size)
2172179193Sjb			continue;
2173179193Sjb
2174179193Sjb		kdata = key->dtak_data;
2175179193Sjb		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2176179193Sjb
2177179193Sjb		for (act = agg->dtag_first; act->dta_intuple;
2178179193Sjb		    act = act->dta_next) {
2179179193Sjb			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2180179193Sjb			limit = i + act->dta_rec.dtrd_size;
2181179193Sjb			ASSERT(limit <= size);
2182179193Sjb			isstr = DTRACEACT_ISSTRING(act);
2183179193Sjb
2184179193Sjb			for (; i < limit; i++) {
2185179193Sjb				if (kdata[i] != data[i])
2186179193Sjb					goto next;
2187179193Sjb
2188179193Sjb				if (isstr && data[i] == '\0')
2189179193Sjb					break;
2190179193Sjb			}
2191179193Sjb		}
2192179193Sjb
2193179193Sjb		if (action != key->dtak_action) {
2194179193Sjb			/*
2195179193Sjb			 * We are aggregating on the same value in the same
2196179193Sjb			 * aggregation with two different aggregating actions.
2197179193Sjb			 * (This should have been picked up in the compiler,
2198179193Sjb			 * so we may be dealing with errant or devious DIF.)
2199179193Sjb			 * This is an error condition; we indicate as much,
2200179193Sjb			 * and return.
2201179193Sjb			 */
2202179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2203179193Sjb			return;
2204179193Sjb		}
2205179193Sjb
2206179193Sjb		/*
2207179193Sjb		 * This is a hit:  we need to apply the aggregator to
2208179193Sjb		 * the value at this key.
2209179193Sjb		 */
2210179193Sjb		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2211179193Sjb		return;
2212179193Sjbnext:
2213179193Sjb		continue;
2214179193Sjb	}
2215179193Sjb
2216179193Sjb	/*
2217179193Sjb	 * We didn't find it.  We need to allocate some zero-filled space,
2218179193Sjb	 * link it into the hash table appropriately, and apply the aggregator
2219179193Sjb	 * to the (zero-filled) value.
2220179193Sjb	 */
2221179193Sjb	offs = buf->dtb_offset;
2222179193Sjb	while (offs & (align - 1))
2223179193Sjb		offs += sizeof (uint32_t);
2224179193Sjb
2225179193Sjb	/*
2226179193Sjb	 * If we don't have enough room to both allocate a new key _and_
2227179193Sjb	 * its associated data, increment the drop count and return.
2228179193Sjb	 */
2229179193Sjb	if ((uintptr_t)tomax + offs + fsize >
2230179193Sjb	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2231179193Sjb		dtrace_buffer_drop(buf);
2232179193Sjb		return;
2233179193Sjb	}
2234179193Sjb
2235179193Sjb	/*CONSTCOND*/
2236179193Sjb	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2237179193Sjb	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2238179193Sjb	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2239179193Sjb
2240179193Sjb	key->dtak_data = kdata = tomax + offs;
2241179193Sjb	buf->dtb_offset = offs + fsize;
2242179193Sjb
2243179193Sjb	/*
2244179193Sjb	 * Now copy the data across.
2245179193Sjb	 */
2246179193Sjb	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2247179193Sjb
2248179193Sjb	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2249179193Sjb		kdata[i] = data[i];
2250179193Sjb
2251179193Sjb	/*
2252179193Sjb	 * Because strings are not zeroed out by default, we need to iterate
2253179193Sjb	 * looking for actions that store strings, and we need to explicitly
2254179193Sjb	 * pad these strings out with zeroes.
2255179193Sjb	 */
2256179193Sjb	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2257179193Sjb		int nul;
2258179193Sjb
2259179193Sjb		if (!DTRACEACT_ISSTRING(act))
2260179193Sjb			continue;
2261179193Sjb
2262179193Sjb		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2263179193Sjb		limit = i + act->dta_rec.dtrd_size;
2264179193Sjb		ASSERT(limit <= size);
2265179193Sjb
2266179193Sjb		for (nul = 0; i < limit; i++) {
2267179193Sjb			if (nul) {
2268179193Sjb				kdata[i] = '\0';
2269179193Sjb				continue;
2270179193Sjb			}
2271179193Sjb
2272179193Sjb			if (data[i] != '\0')
2273179193Sjb				continue;
2274179193Sjb
2275179193Sjb			nul = 1;
2276179193Sjb		}
2277179193Sjb	}
2278179193Sjb
2279179193Sjb	for (i = size; i < fsize; i++)
2280179193Sjb		kdata[i] = 0;
2281179193Sjb
2282179193Sjb	key->dtak_hashval = hashval;
2283179193Sjb	key->dtak_size = size;
2284179193Sjb	key->dtak_action = action;
2285179193Sjb	key->dtak_next = agb->dtagb_hash[ndx];
2286179193Sjb	agb->dtagb_hash[ndx] = key;
2287179193Sjb
2288179193Sjb	/*
2289179193Sjb	 * Finally, apply the aggregator.
2290179193Sjb	 */
2291179193Sjb	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2292179193Sjb	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2293179193Sjb}
2294179193Sjb
2295179193Sjb/*
2296179193Sjb * Given consumer state, this routine finds a speculation in the INACTIVE
2297179193Sjb * state and transitions it into the ACTIVE state.  If there is no speculation
2298179193Sjb * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2299179193Sjb * incremented -- it is up to the caller to take appropriate action.
2300179193Sjb */
2301179193Sjbstatic int
2302179193Sjbdtrace_speculation(dtrace_state_t *state)
2303179193Sjb{
2304179193Sjb	int i = 0;
2305179193Sjb	dtrace_speculation_state_t current;
2306179193Sjb	uint32_t *stat = &state->dts_speculations_unavail, count;
2307179193Sjb
2308179193Sjb	while (i < state->dts_nspeculations) {
2309179193Sjb		dtrace_speculation_t *spec = &state->dts_speculations[i];
2310179193Sjb
2311179193Sjb		current = spec->dtsp_state;
2312179193Sjb
2313179193Sjb		if (current != DTRACESPEC_INACTIVE) {
2314179193Sjb			if (current == DTRACESPEC_COMMITTINGMANY ||
2315179193Sjb			    current == DTRACESPEC_COMMITTING ||
2316179193Sjb			    current == DTRACESPEC_DISCARDING)
2317179193Sjb				stat = &state->dts_speculations_busy;
2318179193Sjb			i++;
2319179193Sjb			continue;
2320179193Sjb		}
2321179193Sjb
2322179193Sjb		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2323179193Sjb		    current, DTRACESPEC_ACTIVE) == current)
2324179193Sjb			return (i + 1);
2325179193Sjb	}
2326179193Sjb
2327179193Sjb	/*
2328179193Sjb	 * We couldn't find a speculation.  If we found as much as a single
2329179193Sjb	 * busy speculation buffer, we'll attribute this failure as "busy"
2330179193Sjb	 * instead of "unavail".
2331179193Sjb	 */
2332179193Sjb	do {
2333179193Sjb		count = *stat;
2334179193Sjb	} while (dtrace_cas32(stat, count, count + 1) != count);
2335179193Sjb
2336179193Sjb	return (0);
2337179193Sjb}
2338179193Sjb
2339179193Sjb/*
2340179193Sjb * This routine commits an active speculation.  If the specified speculation
2341179193Sjb * is not in a valid state to perform a commit(), this routine will silently do
2342179193Sjb * nothing.  The state of the specified speculation is transitioned according
2343179193Sjb * to the state transition diagram outlined in <sys/dtrace_impl.h>
2344179193Sjb */
2345179193Sjbstatic void
2346179193Sjbdtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2347179193Sjb    dtrace_specid_t which)
2348179193Sjb{
2349179193Sjb	dtrace_speculation_t *spec;
2350179193Sjb	dtrace_buffer_t *src, *dest;
2351256002Spfg	uintptr_t daddr, saddr, dlimit, slimit;
2352179198Sjb	dtrace_speculation_state_t current, new = 0;
2353179193Sjb	intptr_t offs;
2354256002Spfg	uint64_t timestamp;
2355179193Sjb
2356179193Sjb	if (which == 0)
2357179193Sjb		return;
2358179193Sjb
2359179193Sjb	if (which > state->dts_nspeculations) {
2360179193Sjb		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2361179193Sjb		return;
2362179193Sjb	}
2363179193Sjb
2364179193Sjb	spec = &state->dts_speculations[which - 1];
2365179193Sjb	src = &spec->dtsp_buffer[cpu];
2366179193Sjb	dest = &state->dts_buffer[cpu];
2367179193Sjb
2368179193Sjb	do {
2369179193Sjb		current = spec->dtsp_state;
2370179193Sjb
2371179193Sjb		if (current == DTRACESPEC_COMMITTINGMANY)
2372179193Sjb			break;
2373179193Sjb
2374179193Sjb		switch (current) {
2375179193Sjb		case DTRACESPEC_INACTIVE:
2376179193Sjb		case DTRACESPEC_DISCARDING:
2377179193Sjb			return;
2378179193Sjb
2379179193Sjb		case DTRACESPEC_COMMITTING:
2380179193Sjb			/*
2381179193Sjb			 * This is only possible if we are (a) commit()'ing
2382179193Sjb			 * without having done a prior speculate() on this CPU
2383179193Sjb			 * and (b) racing with another commit() on a different
2384179193Sjb			 * CPU.  There's nothing to do -- we just assert that
2385179193Sjb			 * our offset is 0.
2386179193Sjb			 */
2387179193Sjb			ASSERT(src->dtb_offset == 0);
2388179193Sjb			return;
2389179193Sjb
2390179193Sjb		case DTRACESPEC_ACTIVE:
2391179193Sjb			new = DTRACESPEC_COMMITTING;
2392179193Sjb			break;
2393179193Sjb
2394179193Sjb		case DTRACESPEC_ACTIVEONE:
2395179193Sjb			/*
2396179193Sjb			 * This speculation is active on one CPU.  If our
2397179193Sjb			 * buffer offset is non-zero, we know that the one CPU
2398179193Sjb			 * must be us.  Otherwise, we are committing on a
2399179193Sjb			 * different CPU from the speculate(), and we must
2400179193Sjb			 * rely on being asynchronously cleaned.
2401179193Sjb			 */
2402179193Sjb			if (src->dtb_offset != 0) {
2403179193Sjb				new = DTRACESPEC_COMMITTING;
2404179193Sjb				break;
2405179193Sjb			}
2406179193Sjb			/*FALLTHROUGH*/
2407179193Sjb
2408179193Sjb		case DTRACESPEC_ACTIVEMANY:
2409179193Sjb			new = DTRACESPEC_COMMITTINGMANY;
2410179193Sjb			break;
2411179193Sjb
2412179193Sjb		default:
2413179193Sjb			ASSERT(0);
2414179193Sjb		}
2415179193Sjb	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2416179193Sjb	    current, new) != current);
2417179193Sjb
2418179193Sjb	/*
2419179193Sjb	 * We have set the state to indicate that we are committing this
2420179193Sjb	 * speculation.  Now reserve the necessary space in the destination
2421179193Sjb	 * buffer.
2422179193Sjb	 */
2423179193Sjb	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2424179193Sjb	    sizeof (uint64_t), state, NULL)) < 0) {
2425179193Sjb		dtrace_buffer_drop(dest);
2426179193Sjb		goto out;
2427179193Sjb	}
2428179193Sjb
2429179193Sjb	/*
2430256002Spfg	 * We have sufficient space to copy the speculative buffer into the
2431256002Spfg	 * primary buffer.  First, modify the speculative buffer, filling
2432256002Spfg	 * in the timestamp of all entries with the current time.  The data
2433256002Spfg	 * must have the commit() time rather than the time it was traced,
2434256002Spfg	 * so that all entries in the primary buffer are in timestamp order.
2435256002Spfg	 */
2436256002Spfg	timestamp = dtrace_gethrtime();
2437256002Spfg	saddr = (uintptr_t)src->dtb_tomax;
2438256002Spfg	slimit = saddr + src->dtb_offset;
2439256002Spfg	while (saddr < slimit) {
2440256002Spfg		size_t size;
2441256002Spfg		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2442256002Spfg
2443256002Spfg		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2444256002Spfg			saddr += sizeof (dtrace_epid_t);
2445256002Spfg			continue;
2446256002Spfg		}
2447256002Spfg		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2448256002Spfg		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2449256002Spfg
2450256002Spfg		ASSERT3U(saddr + size, <=, slimit);
2451256002Spfg		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2452256002Spfg		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2453256002Spfg
2454256002Spfg		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2455256002Spfg
2456256002Spfg		saddr += size;
2457256002Spfg	}
2458256002Spfg
2459256002Spfg	/*
2460256002Spfg	 * Copy the buffer across.  (Note that this is a
2461179193Sjb	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2462179193Sjb	 * a serious performance issue, a high-performance DTrace-specific
2463179193Sjb	 * bcopy() should obviously be invented.)
2464179193Sjb	 */
2465179193Sjb	daddr = (uintptr_t)dest->dtb_tomax + offs;
2466179193Sjb	dlimit = daddr + src->dtb_offset;
2467179193Sjb	saddr = (uintptr_t)src->dtb_tomax;
2468179193Sjb
2469179193Sjb	/*
2470179193Sjb	 * First, the aligned portion.
2471179193Sjb	 */
2472179193Sjb	while (dlimit - daddr >= sizeof (uint64_t)) {
2473179193Sjb		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2474179193Sjb
2475179193Sjb		daddr += sizeof (uint64_t);
2476179193Sjb		saddr += sizeof (uint64_t);
2477179193Sjb	}
2478179193Sjb
2479179193Sjb	/*
2480179193Sjb	 * Now any left-over bit...
2481179193Sjb	 */
2482179193Sjb	while (dlimit - daddr)
2483179193Sjb		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2484179193Sjb
2485179193Sjb	/*
2486179193Sjb	 * Finally, commit the reserved space in the destination buffer.
2487179193Sjb	 */
2488179193Sjb	dest->dtb_offset = offs + src->dtb_offset;
2489179193Sjb
2490179193Sjbout:
2491179193Sjb	/*
2492179193Sjb	 * If we're lucky enough to be the only active CPU on this speculation
2493179193Sjb	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2494179193Sjb	 */
2495179193Sjb	if (current == DTRACESPEC_ACTIVE ||
2496179193Sjb	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2497179193Sjb		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2498179193Sjb		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2499179193Sjb
2500179193Sjb		ASSERT(rval == DTRACESPEC_COMMITTING);
2501179193Sjb	}
2502179193Sjb
2503179193Sjb	src->dtb_offset = 0;
2504179193Sjb	src->dtb_xamot_drops += src->dtb_drops;
2505179193Sjb	src->dtb_drops = 0;
2506179193Sjb}
2507179193Sjb
2508179193Sjb/*
2509179193Sjb * This routine discards an active speculation.  If the specified speculation
2510179193Sjb * is not in a valid state to perform a discard(), this routine will silently
2511179193Sjb * do nothing.  The state of the specified speculation is transitioned
2512179193Sjb * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2513179193Sjb */
2514179193Sjbstatic void
2515179193Sjbdtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2516179193Sjb    dtrace_specid_t which)
2517179193Sjb{
2518179193Sjb	dtrace_speculation_t *spec;
2519179198Sjb	dtrace_speculation_state_t current, new = 0;
2520179193Sjb	dtrace_buffer_t *buf;
2521179193Sjb
2522179193Sjb	if (which == 0)
2523179193Sjb		return;
2524179193Sjb
2525179193Sjb	if (which > state->dts_nspeculations) {
2526179193Sjb		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2527179193Sjb		return;
2528179193Sjb	}
2529179193Sjb
2530179193Sjb	spec = &state->dts_speculations[which - 1];
2531179193Sjb	buf = &spec->dtsp_buffer[cpu];
2532179193Sjb
2533179193Sjb	do {
2534179193Sjb		current = spec->dtsp_state;
2535179193Sjb
2536179193Sjb		switch (current) {
2537179193Sjb		case DTRACESPEC_INACTIVE:
2538179193Sjb		case DTRACESPEC_COMMITTINGMANY:
2539179193Sjb		case DTRACESPEC_COMMITTING:
2540179193Sjb		case DTRACESPEC_DISCARDING:
2541179193Sjb			return;
2542179193Sjb
2543179193Sjb		case DTRACESPEC_ACTIVE:
2544179193Sjb		case DTRACESPEC_ACTIVEMANY:
2545179193Sjb			new = DTRACESPEC_DISCARDING;
2546179193Sjb			break;
2547179193Sjb
2548179193Sjb		case DTRACESPEC_ACTIVEONE:
2549179193Sjb			if (buf->dtb_offset != 0) {
2550179193Sjb				new = DTRACESPEC_INACTIVE;
2551179193Sjb			} else {
2552179193Sjb				new = DTRACESPEC_DISCARDING;
2553179193Sjb			}
2554179193Sjb			break;
2555179193Sjb
2556179193Sjb		default:
2557179193Sjb			ASSERT(0);
2558179193Sjb		}
2559179193Sjb	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2560179193Sjb	    current, new) != current);
2561179193Sjb
2562179193Sjb	buf->dtb_offset = 0;
2563179193Sjb	buf->dtb_drops = 0;
2564179193Sjb}
2565179193Sjb
2566179193Sjb/*
2567179193Sjb * Note:  not called from probe context.  This function is called
2568179193Sjb * asynchronously from cross call context to clean any speculations that are
2569179193Sjb * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2570179193Sjb * transitioned back to the INACTIVE state until all CPUs have cleaned the
2571179193Sjb * speculation.
2572179193Sjb */
2573179193Sjbstatic void
2574179193Sjbdtrace_speculation_clean_here(dtrace_state_t *state)
2575179193Sjb{
2576179193Sjb	dtrace_icookie_t cookie;
2577179198Sjb	processorid_t cpu = curcpu;
2578179193Sjb	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2579179193Sjb	dtrace_specid_t i;
2580179193Sjb
2581179193Sjb	cookie = dtrace_interrupt_disable();
2582179193Sjb
2583179193Sjb	if (dest->dtb_tomax == NULL) {
2584179193Sjb		dtrace_interrupt_enable(cookie);
2585179193Sjb		return;
2586179193Sjb	}
2587179193Sjb
2588179193Sjb	for (i = 0; i < state->dts_nspeculations; i++) {
2589179193Sjb		dtrace_speculation_t *spec = &state->dts_speculations[i];
2590179193Sjb		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2591179193Sjb
2592179193Sjb		if (src->dtb_tomax == NULL)
2593179193Sjb			continue;
2594179193Sjb
2595179193Sjb		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2596179193Sjb			src->dtb_offset = 0;
2597179193Sjb			continue;
2598179193Sjb		}
2599179193Sjb
2600179193Sjb		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2601179193Sjb			continue;
2602179193Sjb
2603179193Sjb		if (src->dtb_offset == 0)
2604179193Sjb			continue;
2605179193Sjb
2606179193Sjb		dtrace_speculation_commit(state, cpu, i + 1);
2607179193Sjb	}
2608179193Sjb
2609179193Sjb	dtrace_interrupt_enable(cookie);
2610179193Sjb}
2611179193Sjb
2612179193Sjb/*
2613179193Sjb * Note:  not called from probe context.  This function is called
2614179193Sjb * asynchronously (and at a regular interval) to clean any speculations that
2615179193Sjb * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2616179193Sjb * is work to be done, it cross calls all CPUs to perform that work;
2617179193Sjb * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2618179193Sjb * INACTIVE state until they have been cleaned by all CPUs.
2619179193Sjb */
2620179193Sjbstatic void
2621179193Sjbdtrace_speculation_clean(dtrace_state_t *state)
2622179193Sjb{
2623179193Sjb	int work = 0, rv;
2624179193Sjb	dtrace_specid_t i;
2625179193Sjb
2626179193Sjb	for (i = 0; i < state->dts_nspeculations; i++) {
2627179193Sjb		dtrace_speculation_t *spec = &state->dts_speculations[i];
2628179193Sjb
2629179193Sjb		ASSERT(!spec->dtsp_cleaning);
2630179193Sjb
2631179193Sjb		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2632179193Sjb		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2633179193Sjb			continue;
2634179193Sjb
2635179193Sjb		work++;
2636179193Sjb		spec->dtsp_cleaning = 1;
2637179193Sjb	}
2638179193Sjb
2639179193Sjb	if (!work)
2640179193Sjb		return;
2641179193Sjb
2642179193Sjb	dtrace_xcall(DTRACE_CPUALL,
2643179193Sjb	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2644179193Sjb
2645179193Sjb	/*
2646179193Sjb	 * We now know that all CPUs have committed or discarded their
2647179193Sjb	 * speculation buffers, as appropriate.  We can now set the state
2648179193Sjb	 * to inactive.
2649179193Sjb	 */
2650179193Sjb	for (i = 0; i < state->dts_nspeculations; i++) {
2651179193Sjb		dtrace_speculation_t *spec = &state->dts_speculations[i];
2652179193Sjb		dtrace_speculation_state_t current, new;
2653179193Sjb
2654179193Sjb		if (!spec->dtsp_cleaning)
2655179193Sjb			continue;
2656179193Sjb
2657179193Sjb		current = spec->dtsp_state;
2658179193Sjb		ASSERT(current == DTRACESPEC_DISCARDING ||
2659179193Sjb		    current == DTRACESPEC_COMMITTINGMANY);
2660179193Sjb
2661179193Sjb		new = DTRACESPEC_INACTIVE;
2662179193Sjb
2663179193Sjb		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2664179193Sjb		ASSERT(rv == current);
2665179193Sjb		spec->dtsp_cleaning = 0;
2666179193Sjb	}
2667179193Sjb}
2668179193Sjb
2669179193Sjb/*
2670179193Sjb * Called as part of a speculate() to get the speculative buffer associated
2671179193Sjb * with a given speculation.  Returns NULL if the specified speculation is not
2672179193Sjb * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2673179193Sjb * the active CPU is not the specified CPU -- the speculation will be
2674179193Sjb * atomically transitioned into the ACTIVEMANY state.
2675179193Sjb */
2676179193Sjbstatic dtrace_buffer_t *
2677179193Sjbdtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2678179193Sjb    dtrace_specid_t which)
2679179193Sjb{
2680179193Sjb	dtrace_speculation_t *spec;
2681179198Sjb	dtrace_speculation_state_t current, new = 0;
2682179193Sjb	dtrace_buffer_t *buf;
2683179193Sjb
2684179193Sjb	if (which == 0)
2685179193Sjb		return (NULL);
2686179193Sjb
2687179193Sjb	if (which > state->dts_nspeculations) {
2688179193Sjb		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2689179193Sjb		return (NULL);
2690179193Sjb	}
2691179193Sjb
2692179193Sjb	spec = &state->dts_speculations[which - 1];
2693179193Sjb	buf = &spec->dtsp_buffer[cpuid];
2694179193Sjb
2695179193Sjb	do {
2696179193Sjb		current = spec->dtsp_state;
2697179193Sjb
2698179193Sjb		switch (current) {
2699179193Sjb		case DTRACESPEC_INACTIVE:
2700179193Sjb		case DTRACESPEC_COMMITTINGMANY:
2701179193Sjb		case DTRACESPEC_DISCARDING:
2702179193Sjb			return (NULL);
2703179193Sjb
2704179193Sjb		case DTRACESPEC_COMMITTING:
2705179193Sjb			ASSERT(buf->dtb_offset == 0);
2706179193Sjb			return (NULL);
2707179193Sjb
2708179193Sjb		case DTRACESPEC_ACTIVEONE:
2709179193Sjb			/*
2710179193Sjb			 * This speculation is currently active on one CPU.
2711179193Sjb			 * Check the offset in the buffer; if it's non-zero,
2712179193Sjb			 * that CPU must be us (and we leave the state alone).
2713179193Sjb			 * If it's zero, assume that we're starting on a new
2714179193Sjb			 * CPU -- and change the state to indicate that the
2715179193Sjb			 * speculation is active on more than one CPU.
2716179193Sjb			 */
2717179193Sjb			if (buf->dtb_offset != 0)
2718179193Sjb				return (buf);
2719179193Sjb
2720179193Sjb			new = DTRACESPEC_ACTIVEMANY;
2721179193Sjb			break;
2722179193Sjb
2723179193Sjb		case DTRACESPEC_ACTIVEMANY:
2724179193Sjb			return (buf);
2725179193Sjb
2726179193Sjb		case DTRACESPEC_ACTIVE:
2727179193Sjb			new = DTRACESPEC_ACTIVEONE;
2728179193Sjb			break;
2729179193Sjb
2730179193Sjb		default:
2731179193Sjb			ASSERT(0);
2732179193Sjb		}
2733179193Sjb	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2734179193Sjb	    current, new) != current);
2735179193Sjb
2736179193Sjb	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2737179193Sjb	return (buf);
2738179193Sjb}
2739179193Sjb
2740179193Sjb/*
2741179193Sjb * Return a string.  In the event that the user lacks the privilege to access
2742179193Sjb * arbitrary kernel memory, we copy the string out to scratch memory so that we
2743179193Sjb * don't fail access checking.
2744179193Sjb *
2745179193Sjb * dtrace_dif_variable() uses this routine as a helper for various
2746179193Sjb * builtin values such as 'execname' and 'probefunc.'
2747179193Sjb */
2748179193Sjbuintptr_t
2749179193Sjbdtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2750179193Sjb    dtrace_mstate_t *mstate)
2751179193Sjb{
2752179193Sjb	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2753179193Sjb	uintptr_t ret;
2754179193Sjb	size_t strsz;
2755179193Sjb
2756179193Sjb	/*
2757179193Sjb	 * The easy case: this probe is allowed to read all of memory, so
2758179193Sjb	 * we can just return this as a vanilla pointer.
2759179193Sjb	 */
2760179193Sjb	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2761179193Sjb		return (addr);
2762179193Sjb
2763179193Sjb	/*
2764179193Sjb	 * This is the tougher case: we copy the string in question from
2765179193Sjb	 * kernel memory into scratch memory and return it that way: this
2766179193Sjb	 * ensures that we won't trip up when access checking tests the
2767179193Sjb	 * BYREF return value.
2768179193Sjb	 */
2769179193Sjb	strsz = dtrace_strlen((char *)addr, size) + 1;
2770179193Sjb
2771179193Sjb	if (mstate->dtms_scratch_ptr + strsz >
2772179193Sjb	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2773179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2774179198Sjb		return (0);
2775179193Sjb	}
2776179193Sjb
2777179193Sjb	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2778179193Sjb	    strsz);
2779179193Sjb	ret = mstate->dtms_scratch_ptr;
2780179193Sjb	mstate->dtms_scratch_ptr += strsz;
2781179193Sjb	return (ret);
2782179193Sjb}
2783179193Sjb
2784179193Sjb/*
2785179198Sjb * Return a string from a memoy address which is known to have one or
2786179198Sjb * more concatenated, individually zero terminated, sub-strings.
2787179198Sjb * In the event that the user lacks the privilege to access
2788179198Sjb * arbitrary kernel memory, we copy the string out to scratch memory so that we
2789179198Sjb * don't fail access checking.
2790179198Sjb *
2791179198Sjb * dtrace_dif_variable() uses this routine as a helper for various
2792179198Sjb * builtin values such as 'execargs'.
2793179198Sjb */
2794179198Sjbstatic uintptr_t
2795179198Sjbdtrace_dif_varstrz(uintptr_t addr, size_t strsz, dtrace_state_t *state,
2796179198Sjb    dtrace_mstate_t *mstate)
2797179198Sjb{
2798179198Sjb	char *p;
2799179198Sjb	size_t i;
2800179198Sjb	uintptr_t ret;
2801179198Sjb
2802179198Sjb	if (mstate->dtms_scratch_ptr + strsz >
2803179198Sjb	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2804179198Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2805179198Sjb		return (0);
2806179198Sjb	}
2807179198Sjb
2808179198Sjb	dtrace_bcopy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2809179198Sjb	    strsz);
2810179198Sjb
2811179198Sjb	/* Replace sub-string termination characters with a space. */
2812179198Sjb	for (p = (char *) mstate->dtms_scratch_ptr, i = 0; i < strsz - 1;
2813179198Sjb	    p++, i++)
2814179198Sjb		if (*p == '\0')
2815179198Sjb			*p = ' ';
2816179198Sjb
2817179198Sjb	ret = mstate->dtms_scratch_ptr;
2818179198Sjb	mstate->dtms_scratch_ptr += strsz;
2819179198Sjb	return (ret);
2820179198Sjb}
2821179198Sjb
2822179198Sjb/*
2823179193Sjb * This function implements the DIF emulator's variable lookups.  The emulator
2824179193Sjb * passes a reserved variable identifier and optional built-in array index.
2825179193Sjb */
2826179193Sjbstatic uint64_t
2827179193Sjbdtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2828179193Sjb    uint64_t ndx)
2829179193Sjb{
2830179193Sjb	/*
2831179193Sjb	 * If we're accessing one of the uncached arguments, we'll turn this
2832179193Sjb	 * into a reference in the args array.
2833179193Sjb	 */
2834179193Sjb	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2835179193Sjb		ndx = v - DIF_VAR_ARG0;
2836179193Sjb		v = DIF_VAR_ARGS;
2837179193Sjb	}
2838179193Sjb
2839179193Sjb	switch (v) {
2840179193Sjb	case DIF_VAR_ARGS:
2841179193Sjb		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2842179193Sjb		if (ndx >= sizeof (mstate->dtms_arg) /
2843179193Sjb		    sizeof (mstate->dtms_arg[0])) {
2844179193Sjb			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2845179193Sjb			dtrace_provider_t *pv;
2846179193Sjb			uint64_t val;
2847179193Sjb
2848179193Sjb			pv = mstate->dtms_probe->dtpr_provider;
2849179193Sjb			if (pv->dtpv_pops.dtps_getargval != NULL)
2850179193Sjb				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2851179193Sjb				    mstate->dtms_probe->dtpr_id,
2852179193Sjb				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2853179193Sjb			else
2854179193Sjb				val = dtrace_getarg(ndx, aframes);
2855179193Sjb
2856179193Sjb			/*
2857179193Sjb			 * This is regrettably required to keep the compiler
2858179193Sjb			 * from tail-optimizing the call to dtrace_getarg().
2859179193Sjb			 * The condition always evaluates to true, but the
2860179193Sjb			 * compiler has no way of figuring that out a priori.
2861179193Sjb			 * (None of this would be necessary if the compiler
2862179193Sjb			 * could be relied upon to _always_ tail-optimize
2863179193Sjb			 * the call to dtrace_getarg() -- but it can't.)
2864179193Sjb			 */
2865179193Sjb			if (mstate->dtms_probe != NULL)
2866179193Sjb				return (val);
2867179193Sjb
2868179193Sjb			ASSERT(0);
2869179193Sjb		}
2870179193Sjb
2871179193Sjb		return (mstate->dtms_arg[ndx]);
2872179193Sjb
2873179198Sjb#if defined(sun)
2874179193Sjb	case DIF_VAR_UREGS: {
2875179193Sjb		klwp_t *lwp;
2876179193Sjb
2877179193Sjb		if (!dtrace_priv_proc(state))
2878179193Sjb			return (0);
2879179193Sjb
2880179193Sjb		if ((lwp = curthread->t_lwp) == NULL) {
2881179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2882179198Sjb			cpu_core[curcpu].cpuc_dtrace_illval = NULL;
2883179193Sjb			return (0);
2884179193Sjb		}
2885179193Sjb
2886179193Sjb		return (dtrace_getreg(lwp->lwp_regs, ndx));
2887179198Sjb		return (0);
2888179193Sjb	}
2889211608Srpaulo#else
2890211608Srpaulo	case DIF_VAR_UREGS: {
2891211608Srpaulo		struct trapframe *tframe;
2892211608Srpaulo
2893211608Srpaulo		if (!dtrace_priv_proc(state))
2894211608Srpaulo			return (0);
2895211608Srpaulo
2896211608Srpaulo		if ((tframe = curthread->td_frame) == NULL) {
2897211608Srpaulo			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2898211608Srpaulo			cpu_core[curcpu].cpuc_dtrace_illval = 0;
2899211608Srpaulo			return (0);
2900211608Srpaulo		}
2901211608Srpaulo
2902211608Srpaulo		return (dtrace_getreg(tframe, ndx));
2903211608Srpaulo	}
2904179198Sjb#endif
2905179193Sjb
2906179193Sjb	case DIF_VAR_CURTHREAD:
2907179193Sjb		if (!dtrace_priv_kernel(state))
2908179193Sjb			return (0);
2909179193Sjb		return ((uint64_t)(uintptr_t)curthread);
2910179193Sjb
2911179193Sjb	case DIF_VAR_TIMESTAMP:
2912179193Sjb		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2913179193Sjb			mstate->dtms_timestamp = dtrace_gethrtime();
2914179193Sjb			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2915179193Sjb		}
2916179193Sjb		return (mstate->dtms_timestamp);
2917179193Sjb
2918179193Sjb	case DIF_VAR_VTIMESTAMP:
2919179193Sjb		ASSERT(dtrace_vtime_references != 0);
2920179193Sjb		return (curthread->t_dtrace_vtime);
2921179193Sjb
2922179193Sjb	case DIF_VAR_WALLTIMESTAMP:
2923179193Sjb		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2924179193Sjb			mstate->dtms_walltimestamp = dtrace_gethrestime();
2925179193Sjb			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2926179193Sjb		}
2927179193Sjb		return (mstate->dtms_walltimestamp);
2928179193Sjb
2929179198Sjb#if defined(sun)
2930179193Sjb	case DIF_VAR_IPL:
2931179193Sjb		if (!dtrace_priv_kernel(state))
2932179193Sjb			return (0);
2933179193Sjb		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2934179193Sjb			mstate->dtms_ipl = dtrace_getipl();
2935179193Sjb			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2936179193Sjb		}
2937179193Sjb		return (mstate->dtms_ipl);
2938179198Sjb#endif
2939179193Sjb
2940179193Sjb	case DIF_VAR_EPID:
2941179193Sjb		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2942179193Sjb		return (mstate->dtms_epid);
2943179193Sjb
2944179193Sjb	case DIF_VAR_ID:
2945179193Sjb		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2946179193Sjb		return (mstate->dtms_probe->dtpr_id);
2947179193Sjb
2948179193Sjb	case DIF_VAR_STACKDEPTH:
2949179193Sjb		if (!dtrace_priv_kernel(state))
2950179193Sjb			return (0);
2951179193Sjb		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2952179193Sjb			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2953179193Sjb
2954179193Sjb			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2955179193Sjb			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2956179193Sjb		}
2957179193Sjb		return (mstate->dtms_stackdepth);
2958179193Sjb
2959179193Sjb	case DIF_VAR_USTACKDEPTH:
2960179193Sjb		if (!dtrace_priv_proc(state))
2961179193Sjb			return (0);
2962179193Sjb		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2963179193Sjb			/*
2964179193Sjb			 * See comment in DIF_VAR_PID.
2965179193Sjb			 */
2966179193Sjb			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2967179193Sjb			    CPU_ON_INTR(CPU)) {
2968179193Sjb				mstate->dtms_ustackdepth = 0;
2969179193Sjb			} else {
2970179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2971179193Sjb				mstate->dtms_ustackdepth =
2972179193Sjb				    dtrace_getustackdepth();
2973179193Sjb				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2974179193Sjb			}
2975179193Sjb			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2976179193Sjb		}
2977179193Sjb		return (mstate->dtms_ustackdepth);
2978179193Sjb
2979179193Sjb	case DIF_VAR_CALLER:
2980179193Sjb		if (!dtrace_priv_kernel(state))
2981179193Sjb			return (0);
2982179193Sjb		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2983179193Sjb			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2984179193Sjb
2985179193Sjb			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2986179193Sjb				/*
2987179193Sjb				 * If this is an unanchored probe, we are
2988179193Sjb				 * required to go through the slow path:
2989179193Sjb				 * dtrace_caller() only guarantees correct
2990179193Sjb				 * results for anchored probes.
2991179193Sjb				 */
2992179198Sjb				pc_t caller[2] = {0, 0};
2993179193Sjb
2994179193Sjb				dtrace_getpcstack(caller, 2, aframes,
2995179193Sjb				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2996179193Sjb				mstate->dtms_caller = caller[1];
2997179193Sjb			} else if ((mstate->dtms_caller =
2998179193Sjb			    dtrace_caller(aframes)) == -1) {
2999179193Sjb				/*
3000179193Sjb				 * We have failed to do this the quick way;
3001179193Sjb				 * we must resort to the slower approach of
3002179193Sjb				 * calling dtrace_getpcstack().
3003179193Sjb				 */
3004179198Sjb				pc_t caller = 0;
3005179193Sjb
3006179193Sjb				dtrace_getpcstack(&caller, 1, aframes, NULL);
3007179193Sjb				mstate->dtms_caller = caller;
3008179193Sjb			}
3009179193Sjb
3010179193Sjb			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3011179193Sjb		}
3012179193Sjb		return (mstate->dtms_caller);
3013179193Sjb
3014179193Sjb	case DIF_VAR_UCALLER:
3015179193Sjb		if (!dtrace_priv_proc(state))
3016179193Sjb			return (0);
3017179193Sjb
3018179193Sjb		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3019179193Sjb			uint64_t ustack[3];
3020179193Sjb
3021179193Sjb			/*
3022179193Sjb			 * dtrace_getupcstack() fills in the first uint64_t
3023179193Sjb			 * with the current PID.  The second uint64_t will
3024179193Sjb			 * be the program counter at user-level.  The third
3025179193Sjb			 * uint64_t will contain the caller, which is what
3026179193Sjb			 * we're after.
3027179193Sjb			 */
3028179198Sjb			ustack[2] = 0;
3029179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3030179193Sjb			dtrace_getupcstack(ustack, 3);
3031179193Sjb			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3032179193Sjb			mstate->dtms_ucaller = ustack[2];
3033179193Sjb			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3034179193Sjb		}
3035179193Sjb
3036179193Sjb		return (mstate->dtms_ucaller);
3037179193Sjb
3038179193Sjb	case DIF_VAR_PROBEPROV:
3039179193Sjb		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3040179193Sjb		return (dtrace_dif_varstr(
3041179193Sjb		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3042179193Sjb		    state, mstate));
3043179193Sjb
3044179193Sjb	case DIF_VAR_PROBEMOD:
3045179193Sjb		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3046179193Sjb		return (dtrace_dif_varstr(
3047179193Sjb		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3048179193Sjb		    state, mstate));
3049179193Sjb
3050179193Sjb	case DIF_VAR_PROBEFUNC:
3051179193Sjb		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3052179193Sjb		return (dtrace_dif_varstr(
3053179193Sjb		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3054179193Sjb		    state, mstate));
3055179193Sjb
3056179193Sjb	case DIF_VAR_PROBENAME:
3057179193Sjb		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3058179193Sjb		return (dtrace_dif_varstr(
3059179193Sjb		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3060179193Sjb		    state, mstate));
3061179193Sjb
3062179193Sjb	case DIF_VAR_PID:
3063179193Sjb		if (!dtrace_priv_proc(state))
3064179193Sjb			return (0);
3065179193Sjb
3066179198Sjb#if defined(sun)
3067179193Sjb		/*
3068179193Sjb		 * Note that we are assuming that an unanchored probe is
3069179193Sjb		 * always due to a high-level interrupt.  (And we're assuming
3070179193Sjb		 * that there is only a single high level interrupt.)
3071179193Sjb		 */
3072179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3073179193Sjb			return (pid0.pid_id);
3074179193Sjb
3075179193Sjb		/*
3076179193Sjb		 * It is always safe to dereference one's own t_procp pointer:
3077179193Sjb		 * it always points to a valid, allocated proc structure.
3078179193Sjb		 * Further, it is always safe to dereference the p_pidp member
3079179193Sjb		 * of one's own proc structure.  (These are truisms becuase
3080179193Sjb		 * threads and processes don't clean up their own state --
3081179193Sjb		 * they leave that task to whomever reaps them.)
3082179193Sjb		 */
3083179193Sjb		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3084179198Sjb#else
3085179198Sjb		return ((uint64_t)curproc->p_pid);
3086179198Sjb#endif
3087179193Sjb
3088179193Sjb	case DIF_VAR_PPID:
3089179193Sjb		if (!dtrace_priv_proc(state))
3090179193Sjb			return (0);
3091179193Sjb
3092179198Sjb#if defined(sun)
3093179193Sjb		/*
3094179193Sjb		 * See comment in DIF_VAR_PID.
3095179193Sjb		 */
3096179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3097179193Sjb			return (pid0.pid_id);
3098179193Sjb
3099179193Sjb		/*
3100179193Sjb		 * It is always safe to dereference one's own t_procp pointer:
3101179193Sjb		 * it always points to a valid, allocated proc structure.
3102179193Sjb		 * (This is true because threads don't clean up their own
3103179193Sjb		 * state -- they leave that task to whomever reaps them.)
3104179193Sjb		 */
3105179193Sjb		return ((uint64_t)curthread->t_procp->p_ppid);
3106179198Sjb#else
3107179198Sjb		return ((uint64_t)curproc->p_pptr->p_pid);
3108179198Sjb#endif
3109179193Sjb
3110179193Sjb	case DIF_VAR_TID:
3111179198Sjb#if defined(sun)
3112179193Sjb		/*
3113179193Sjb		 * See comment in DIF_VAR_PID.
3114179193Sjb		 */
3115179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3116179193Sjb			return (0);
3117179198Sjb#endif
3118179193Sjb
3119179193Sjb		return ((uint64_t)curthread->t_tid);
3120179193Sjb
3121179198Sjb	case DIF_VAR_EXECARGS: {
3122179198Sjb		struct pargs *p_args = curthread->td_proc->p_args;
3123179198Sjb
3124184698Srodrigc		if (p_args == NULL)
3125184698Srodrigc			return(0);
3126184698Srodrigc
3127179198Sjb		return (dtrace_dif_varstrz(
3128179198Sjb		    (uintptr_t) p_args->ar_args, p_args->ar_length, state, mstate));
3129179198Sjb	}
3130179198Sjb
3131179193Sjb	case DIF_VAR_EXECNAME:
3132179198Sjb#if defined(sun)
3133179193Sjb		if (!dtrace_priv_proc(state))
3134179193Sjb			return (0);
3135179193Sjb
3136179193Sjb		/*
3137179193Sjb		 * See comment in DIF_VAR_PID.
3138179193Sjb		 */
3139179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3140179193Sjb			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3141179193Sjb
3142179193Sjb		/*
3143179193Sjb		 * It is always safe to dereference one's own t_procp pointer:
3144179193Sjb		 * it always points to a valid, allocated proc structure.
3145179193Sjb		 * (This is true because threads don't clean up their own
3146179193Sjb		 * state -- they leave that task to whomever reaps them.)
3147179193Sjb		 */
3148179193Sjb		return (dtrace_dif_varstr(
3149179193Sjb		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3150179193Sjb		    state, mstate));
3151179198Sjb#else
3152179198Sjb		return (dtrace_dif_varstr(
3153179198Sjb		    (uintptr_t) curthread->td_proc->p_comm, state, mstate));
3154179198Sjb#endif
3155179193Sjb
3156179193Sjb	case DIF_VAR_ZONENAME:
3157179198Sjb#if defined(sun)
3158179193Sjb		if (!dtrace_priv_proc(state))
3159179193Sjb			return (0);
3160179193Sjb
3161179193Sjb		/*
3162179193Sjb		 * See comment in DIF_VAR_PID.
3163179193Sjb		 */
3164179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3165179193Sjb			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3166179193Sjb
3167179193Sjb		/*
3168179193Sjb		 * It is always safe to dereference one's own t_procp pointer:
3169179193Sjb		 * it always points to a valid, allocated proc structure.
3170179193Sjb		 * (This is true because threads don't clean up their own
3171179193Sjb		 * state -- they leave that task to whomever reaps them.)
3172179193Sjb		 */
3173179193Sjb		return (dtrace_dif_varstr(
3174179193Sjb		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3175179193Sjb		    state, mstate));
3176179198Sjb#else
3177179198Sjb		return (0);
3178179198Sjb#endif
3179179193Sjb
3180179193Sjb	case DIF_VAR_UID:
3181179193Sjb		if (!dtrace_priv_proc(state))
3182179193Sjb			return (0);
3183179193Sjb
3184179198Sjb#if defined(sun)
3185179193Sjb		/*
3186179193Sjb		 * See comment in DIF_VAR_PID.
3187179193Sjb		 */
3188179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3189179193Sjb			return ((uint64_t)p0.p_cred->cr_uid);
3190179198Sjb#endif
3191179193Sjb
3192179193Sjb		/*
3193179193Sjb		 * It is always safe to dereference one's own t_procp pointer:
3194179193Sjb		 * it always points to a valid, allocated proc structure.
3195179193Sjb		 * (This is true because threads don't clean up their own
3196179193Sjb		 * state -- they leave that task to whomever reaps them.)
3197179193Sjb		 *
3198179193Sjb		 * Additionally, it is safe to dereference one's own process
3199179193Sjb		 * credential, since this is never NULL after process birth.
3200179193Sjb		 */
3201179193Sjb		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3202179193Sjb
3203179193Sjb	case DIF_VAR_GID:
3204179193Sjb		if (!dtrace_priv_proc(state))
3205179193Sjb			return (0);
3206179193Sjb
3207179198Sjb#if defined(sun)
3208179193Sjb		/*
3209179193Sjb		 * See comment in DIF_VAR_PID.
3210179193Sjb		 */
3211179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3212179193Sjb			return ((uint64_t)p0.p_cred->cr_gid);
3213179198Sjb#endif
3214179193Sjb
3215179193Sjb		/*
3216179193Sjb		 * It is always safe to dereference one's own t_procp pointer:
3217179193Sjb		 * it always points to a valid, allocated proc structure.
3218179193Sjb		 * (This is true because threads don't clean up their own
3219179193Sjb		 * state -- they leave that task to whomever reaps them.)
3220179193Sjb		 *
3221179193Sjb		 * Additionally, it is safe to dereference one's own process
3222179193Sjb		 * credential, since this is never NULL after process birth.
3223179193Sjb		 */
3224179193Sjb		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3225179193Sjb
3226179193Sjb	case DIF_VAR_ERRNO: {
3227179198Sjb#if defined(sun)
3228179193Sjb		klwp_t *lwp;
3229179193Sjb		if (!dtrace_priv_proc(state))
3230179193Sjb			return (0);
3231179193Sjb
3232179193Sjb		/*
3233179193Sjb		 * See comment in DIF_VAR_PID.
3234179193Sjb		 */
3235179193Sjb		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3236179193Sjb			return (0);
3237179193Sjb
3238179193Sjb		/*
3239179193Sjb		 * It is always safe to dereference one's own t_lwp pointer in
3240179193Sjb		 * the event that this pointer is non-NULL.  (This is true
3241179193Sjb		 * because threads and lwps don't clean up their own state --
3242179193Sjb		 * they leave that task to whomever reaps them.)
3243179193Sjb		 */
3244179193Sjb		if ((lwp = curthread->t_lwp) == NULL)
3245179193Sjb			return (0);
3246179193Sjb
3247179193Sjb		return ((uint64_t)lwp->lwp_errno);
3248179198Sjb#else
3249179198Sjb		return (curthread->td_errno);
3250179198Sjb#endif
3251179193Sjb	}
3252236160Srstone#if !defined(sun)
3253236160Srstone	case DIF_VAR_CPU: {
3254236160Srstone		return curcpu;
3255236160Srstone	}
3256236160Srstone#endif
3257179193Sjb	default:
3258179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3259179193Sjb		return (0);
3260179193Sjb	}
3261179193Sjb}
3262179193Sjb
3263179193Sjb/*
3264179193Sjb * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3265179193Sjb * Notice that we don't bother validating the proper number of arguments or
3266179193Sjb * their types in the tuple stack.  This isn't needed because all argument
3267179193Sjb * interpretation is safe because of our load safety -- the worst that can
3268179193Sjb * happen is that a bogus program can obtain bogus results.
3269179193Sjb */
3270179193Sjbstatic void
3271179193Sjbdtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3272179193Sjb    dtrace_key_t *tupregs, int nargs,
3273179193Sjb    dtrace_mstate_t *mstate, dtrace_state_t *state)
3274179193Sjb{
3275179198Sjb	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
3276179198Sjb	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
3277179193Sjb	dtrace_vstate_t *vstate = &state->dts_vstate;
3278179193Sjb
3279179198Sjb#if defined(sun)
3280179193Sjb	union {
3281179193Sjb		mutex_impl_t mi;
3282179193Sjb		uint64_t mx;
3283179193Sjb	} m;
3284179193Sjb
3285179193Sjb	union {
3286179193Sjb		krwlock_t ri;
3287179193Sjb		uintptr_t rw;
3288179193Sjb	} r;
3289179198Sjb#else
3290192853Ssson	struct thread *lowner;
3291179198Sjb	union {
3292192853Ssson		struct lock_object *li;
3293192853Ssson		uintptr_t lx;
3294192853Ssson	} l;
3295179198Sjb#endif
3296179193Sjb
3297179193Sjb	switch (subr) {
3298179193Sjb	case DIF_SUBR_RAND:
3299179193Sjb		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3300179193Sjb		break;
3301179193Sjb
3302179198Sjb#if defined(sun)
3303179193Sjb	case DIF_SUBR_MUTEX_OWNED:
3304179193Sjb		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3305179193Sjb		    mstate, vstate)) {
3306179198Sjb			regs[rd] = 0;
3307179193Sjb			break;
3308179193Sjb		}
3309179193Sjb
3310179193Sjb		m.mx = dtrace_load64(tupregs[0].dttk_value);
3311179193Sjb		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3312179193Sjb			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3313179193Sjb		else
3314179193Sjb			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3315179193Sjb		break;
3316179193Sjb
3317179193Sjb	case DIF_SUBR_MUTEX_OWNER:
3318179193Sjb		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3319179193Sjb		    mstate, vstate)) {
3320179198Sjb			regs[rd] = 0;
3321179193Sjb			break;
3322179193Sjb		}
3323179193Sjb
3324179193Sjb		m.mx = dtrace_load64(tupregs[0].dttk_value);
3325179193Sjb		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3326179193Sjb		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3327179193Sjb			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3328179193Sjb		else
3329179193Sjb			regs[rd] = 0;
3330179193Sjb		break;
3331179193Sjb
3332179193Sjb	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3333179193Sjb		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3334179193Sjb		    mstate, vstate)) {
3335179198Sjb			regs[rd] = 0;
3336179193Sjb			break;
3337179193Sjb		}
3338179193Sjb
3339179193Sjb		m.mx = dtrace_load64(tupregs[0].dttk_value);
3340179193Sjb		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3341179193Sjb		break;
3342179193Sjb
3343179193Sjb	case DIF_SUBR_MUTEX_TYPE_SPIN:
3344179193Sjb		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3345179193Sjb		    mstate, vstate)) {
3346179198Sjb			regs[rd] = 0;
3347179193Sjb			break;
3348179193Sjb		}
3349179193Sjb
3350179193Sjb		m.mx = dtrace_load64(tupregs[0].dttk_value);
3351179193Sjb		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3352179193Sjb		break;
3353179193Sjb
3354179193Sjb	case DIF_SUBR_RW_READ_HELD: {
3355179193Sjb		uintptr_t tmp;
3356179193Sjb
3357179193Sjb		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3358179193Sjb		    mstate, vstate)) {
3359179198Sjb			regs[rd] = 0;
3360179193Sjb			break;
3361179193Sjb		}
3362179193Sjb
3363179193Sjb		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3364179193Sjb		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3365179193Sjb		break;
3366179193Sjb	}
3367179193Sjb
3368179193Sjb	case DIF_SUBR_RW_WRITE_HELD:
3369179193Sjb		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3370179193Sjb		    mstate, vstate)) {
3371179198Sjb			regs[rd] = 0;
3372179193Sjb			break;
3373179193Sjb		}
3374179193Sjb
3375179193Sjb		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3376179193Sjb		regs[rd] = _RW_WRITE_HELD(&r.ri);
3377179193Sjb		break;
3378179193Sjb
3379179193Sjb	case DIF_SUBR_RW_ISWRITER:
3380179193Sjb		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3381179193Sjb		    mstate, vstate)) {
3382179198Sjb			regs[rd] = 0;
3383179193Sjb			break;
3384179193Sjb		}
3385179193Sjb
3386179193Sjb		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3387179193Sjb		regs[rd] = _RW_ISWRITER(&r.ri);
3388179193Sjb		break;
3389179193Sjb
3390179198Sjb#else
3391179198Sjb	case DIF_SUBR_MUTEX_OWNED:
3392192853Ssson		if (!dtrace_canload(tupregs[0].dttk_value,
3393192853Ssson			sizeof (struct lock_object), mstate, vstate)) {
3394192853Ssson			regs[rd] = 0;
3395192853Ssson			break;
3396179198Sjb		}
3397192853Ssson		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3398192853Ssson		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3399179198Sjb		break;
3400179198Sjb
3401179198Sjb	case DIF_SUBR_MUTEX_OWNER:
3402192853Ssson		if (!dtrace_canload(tupregs[0].dttk_value,
3403192853Ssson			sizeof (struct lock_object), mstate, vstate)) {
3404192853Ssson			regs[rd] = 0;
3405192853Ssson			break;
3406179198Sjb		}
3407192853Ssson		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3408192853Ssson		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3409192853Ssson		regs[rd] = (uintptr_t)lowner;
3410179198Sjb		break;
3411179198Sjb
3412179198Sjb	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3413192853Ssson		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3414192853Ssson		    mstate, vstate)) {
3415192853Ssson			regs[rd] = 0;
3416192853Ssson			break;
3417192853Ssson		}
3418192853Ssson		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3419192853Ssson		/* XXX - should be only LC_SLEEPABLE? */
3420192853Ssson		regs[rd] = (LOCK_CLASS(l.li)->lc_flags &
3421192853Ssson		    (LC_SLEEPLOCK | LC_SLEEPABLE)) != 0;
3422179198Sjb		break;
3423179198Sjb
3424179198Sjb	case DIF_SUBR_MUTEX_TYPE_SPIN:
3425192853Ssson		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (struct mtx),
3426192853Ssson		    mstate, vstate)) {
3427192853Ssson			regs[rd] = 0;
3428192853Ssson			break;
3429192853Ssson		}
3430192853Ssson		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3431192853Ssson		regs[rd] = (LOCK_CLASS(l.li)->lc_flags & LC_SPINLOCK) != 0;
3432179198Sjb		break;
3433179198Sjb
3434179198Sjb	case DIF_SUBR_RW_READ_HELD:
3435179198Sjb	case DIF_SUBR_SX_SHARED_HELD:
3436192853Ssson		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3437192853Ssson		    mstate, vstate)) {
3438192853Ssson			regs[rd] = 0;
3439192853Ssson			break;
3440192853Ssson		}
3441192853Ssson		l.lx = dtrace_loadptr((uintptr_t)&tupregs[0].dttk_value);
3442192853Ssson		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3443192853Ssson		    lowner == NULL;
3444179198Sjb		break;
3445179198Sjb
3446179198Sjb	case DIF_SUBR_RW_WRITE_HELD:
3447179198Sjb	case DIF_SUBR_SX_EXCLUSIVE_HELD:
3448192853Ssson		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3449192853Ssson		    mstate, vstate)) {
3450192853Ssson			regs[rd] = 0;
3451192853Ssson			break;
3452192853Ssson		}
3453192853Ssson		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3454192853Ssson		LOCK_CLASS(l.li)->lc_owner(l.li, &lowner);
3455192853Ssson		regs[rd] = (lowner == curthread);
3456179198Sjb		break;
3457179198Sjb
3458179198Sjb	case DIF_SUBR_RW_ISWRITER:
3459179198Sjb	case DIF_SUBR_SX_ISEXCLUSIVE:
3460192853Ssson		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3461192853Ssson		    mstate, vstate)) {
3462192853Ssson			regs[rd] = 0;
3463192853Ssson			break;
3464192853Ssson		}
3465192853Ssson		l.lx = dtrace_loadptr(tupregs[0].dttk_value);
3466192853Ssson		regs[rd] = LOCK_CLASS(l.li)->lc_owner(l.li, &lowner) &&
3467192853Ssson		    lowner != NULL;
3468179198Sjb		break;
3469179198Sjb#endif /* ! defined(sun) */
3470179198Sjb
3471179193Sjb	case DIF_SUBR_BCOPY: {
3472179193Sjb		/*
3473179193Sjb		 * We need to be sure that the destination is in the scratch
3474179193Sjb		 * region -- no other region is allowed.
3475179193Sjb		 */
3476179193Sjb		uintptr_t src = tupregs[0].dttk_value;
3477179193Sjb		uintptr_t dest = tupregs[1].dttk_value;
3478179193Sjb		size_t size = tupregs[2].dttk_value;
3479179193Sjb
3480179193Sjb		if (!dtrace_inscratch(dest, size, mstate)) {
3481179193Sjb			*flags |= CPU_DTRACE_BADADDR;
3482179193Sjb			*illval = regs[rd];
3483179193Sjb			break;
3484179193Sjb		}
3485179193Sjb
3486179193Sjb		if (!dtrace_canload(src, size, mstate, vstate)) {
3487179198Sjb			regs[rd] = 0;
3488179193Sjb			break;
3489179193Sjb		}
3490179193Sjb
3491179193Sjb		dtrace_bcopy((void *)src, (void *)dest, size);
3492179193Sjb		break;
3493179193Sjb	}
3494179193Sjb
3495179193Sjb	case DIF_SUBR_ALLOCA:
3496179193Sjb	case DIF_SUBR_COPYIN: {
3497179193Sjb		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3498179193Sjb		uint64_t size =
3499179193Sjb		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3500179193Sjb		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3501179193Sjb
3502179193Sjb		/*
3503179193Sjb		 * This action doesn't require any credential checks since
3504179193Sjb		 * probes will not activate in user contexts to which the
3505179193Sjb		 * enabling user does not have permissions.
3506179193Sjb		 */
3507179193Sjb
3508179193Sjb		/*
3509179193Sjb		 * Rounding up the user allocation size could have overflowed
3510179193Sjb		 * a large, bogus allocation (like -1ULL) to 0.
3511179193Sjb		 */
3512179193Sjb		if (scratch_size < size ||
3513179193Sjb		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
3514179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3515179198Sjb			regs[rd] = 0;
3516179193Sjb			break;
3517179193Sjb		}
3518179193Sjb
3519179193Sjb		if (subr == DIF_SUBR_COPYIN) {
3520179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3521179193Sjb			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3522179193Sjb			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3523179193Sjb		}
3524179193Sjb
3525179193Sjb		mstate->dtms_scratch_ptr += scratch_size;
3526179193Sjb		regs[rd] = dest;
3527179193Sjb		break;
3528179193Sjb	}
3529179193Sjb
3530179193Sjb	case DIF_SUBR_COPYINTO: {
3531179193Sjb		uint64_t size = tupregs[1].dttk_value;
3532179193Sjb		uintptr_t dest = tupregs[2].dttk_value;
3533179193Sjb
3534179193Sjb		/*
3535179193Sjb		 * This action doesn't require any credential checks since
3536179193Sjb		 * probes will not activate in user contexts to which the
3537179193Sjb		 * enabling user does not have permissions.
3538179193Sjb		 */
3539179193Sjb		if (!dtrace_inscratch(dest, size, mstate)) {
3540179193Sjb			*flags |= CPU_DTRACE_BADADDR;
3541179193Sjb			*illval = regs[rd];
3542179193Sjb			break;
3543179193Sjb		}
3544179193Sjb
3545179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3546179193Sjb		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3547179193Sjb		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3548179193Sjb		break;
3549179193Sjb	}
3550179193Sjb
3551179193Sjb	case DIF_SUBR_COPYINSTR: {
3552179193Sjb		uintptr_t dest = mstate->dtms_scratch_ptr;
3553179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3554179193Sjb
3555179193Sjb		if (nargs > 1 && tupregs[1].dttk_value < size)
3556179193Sjb			size = tupregs[1].dttk_value + 1;
3557179193Sjb
3558179193Sjb		/*
3559179193Sjb		 * This action doesn't require any credential checks since
3560179193Sjb		 * probes will not activate in user contexts to which the
3561179193Sjb		 * enabling user does not have permissions.
3562179193Sjb		 */
3563179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
3564179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3565179198Sjb			regs[rd] = 0;
3566179193Sjb			break;
3567179193Sjb		}
3568179193Sjb
3569179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3570179193Sjb		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3571179193Sjb		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3572179193Sjb
3573179193Sjb		((char *)dest)[size - 1] = '\0';
3574179193Sjb		mstate->dtms_scratch_ptr += size;
3575179193Sjb		regs[rd] = dest;
3576179193Sjb		break;
3577179193Sjb	}
3578179193Sjb
3579179198Sjb#if defined(sun)
3580179193Sjb	case DIF_SUBR_MSGSIZE:
3581179193Sjb	case DIF_SUBR_MSGDSIZE: {
3582179193Sjb		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3583179193Sjb		uintptr_t wptr, rptr;
3584179193Sjb		size_t count = 0;
3585179193Sjb		int cont = 0;
3586179193Sjb
3587179198Sjb		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
3588179193Sjb
3589179193Sjb			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3590179193Sjb			    vstate)) {
3591179198Sjb				regs[rd] = 0;
3592179193Sjb				break;
3593179193Sjb			}
3594179193Sjb
3595179193Sjb			wptr = dtrace_loadptr(baddr +
3596179193Sjb			    offsetof(mblk_t, b_wptr));
3597179193Sjb
3598179193Sjb			rptr = dtrace_loadptr(baddr +
3599179193Sjb			    offsetof(mblk_t, b_rptr));
3600179193Sjb
3601179193Sjb			if (wptr < rptr) {
3602179193Sjb				*flags |= CPU_DTRACE_BADADDR;
3603179193Sjb				*illval = tupregs[0].dttk_value;
3604179193Sjb				break;
3605179193Sjb			}
3606179193Sjb
3607179193Sjb			daddr = dtrace_loadptr(baddr +
3608179193Sjb			    offsetof(mblk_t, b_datap));
3609179193Sjb
3610179193Sjb			baddr = dtrace_loadptr(baddr +
3611179193Sjb			    offsetof(mblk_t, b_cont));
3612179193Sjb
3613179193Sjb			/*
3614179193Sjb			 * We want to prevent against denial-of-service here,
3615179193Sjb			 * so we're only going to search the list for
3616179193Sjb			 * dtrace_msgdsize_max mblks.
3617179193Sjb			 */
3618179193Sjb			if (cont++ > dtrace_msgdsize_max) {
3619179193Sjb				*flags |= CPU_DTRACE_ILLOP;
3620179193Sjb				break;
3621179193Sjb			}
3622179193Sjb
3623179193Sjb			if (subr == DIF_SUBR_MSGDSIZE) {
3624179193Sjb				if (dtrace_load8(daddr +
3625179193Sjb				    offsetof(dblk_t, db_type)) != M_DATA)
3626179193Sjb					continue;
3627179193Sjb			}
3628179193Sjb
3629179193Sjb			count += wptr - rptr;
3630179193Sjb		}
3631179193Sjb
3632179193Sjb		if (!(*flags & CPU_DTRACE_FAULT))
3633179193Sjb			regs[rd] = count;
3634179193Sjb
3635179193Sjb		break;
3636179193Sjb	}
3637179198Sjb#endif
3638179193Sjb
3639179193Sjb	case DIF_SUBR_PROGENYOF: {
3640179193Sjb		pid_t pid = tupregs[0].dttk_value;
3641179193Sjb		proc_t *p;
3642179193Sjb		int rval = 0;
3643179193Sjb
3644179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3645179193Sjb
3646179193Sjb		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3647179198Sjb#if defined(sun)
3648179193Sjb			if (p->p_pidp->pid_id == pid) {
3649179198Sjb#else
3650179198Sjb			if (p->p_pid == pid) {
3651179198Sjb#endif
3652179193Sjb				rval = 1;
3653179193Sjb				break;
3654179193Sjb			}
3655179193Sjb		}
3656179193Sjb
3657179193Sjb		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3658179193Sjb
3659179193Sjb		regs[rd] = rval;
3660179193Sjb		break;
3661179193Sjb	}
3662179193Sjb
3663179193Sjb	case DIF_SUBR_SPECULATION:
3664179193Sjb		regs[rd] = dtrace_speculation(state);
3665179193Sjb		break;
3666179193Sjb
3667179193Sjb	case DIF_SUBR_COPYOUT: {
3668179193Sjb		uintptr_t kaddr = tupregs[0].dttk_value;
3669179193Sjb		uintptr_t uaddr = tupregs[1].dttk_value;
3670179193Sjb		uint64_t size = tupregs[2].dttk_value;
3671179193Sjb
3672179193Sjb		if (!dtrace_destructive_disallow &&
3673179193Sjb		    dtrace_priv_proc_control(state) &&
3674179193Sjb		    !dtrace_istoxic(kaddr, size)) {
3675179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3676179193Sjb			dtrace_copyout(kaddr, uaddr, size, flags);
3677179193Sjb			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3678179193Sjb		}
3679179193Sjb		break;
3680179193Sjb	}
3681179193Sjb
3682179193Sjb	case DIF_SUBR_COPYOUTSTR: {
3683179193Sjb		uintptr_t kaddr = tupregs[0].dttk_value;
3684179193Sjb		uintptr_t uaddr = tupregs[1].dttk_value;
3685179193Sjb		uint64_t size = tupregs[2].dttk_value;
3686179193Sjb
3687179193Sjb		if (!dtrace_destructive_disallow &&
3688179193Sjb		    dtrace_priv_proc_control(state) &&
3689179193Sjb		    !dtrace_istoxic(kaddr, size)) {
3690179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3691179193Sjb			dtrace_copyoutstr(kaddr, uaddr, size, flags);
3692179193Sjb			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3693179193Sjb		}
3694179193Sjb		break;
3695179193Sjb	}
3696179193Sjb
3697179193Sjb	case DIF_SUBR_STRLEN: {
3698179193Sjb		size_t sz;
3699179193Sjb		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3700179193Sjb		sz = dtrace_strlen((char *)addr,
3701179193Sjb		    state->dts_options[DTRACEOPT_STRSIZE]);
3702179193Sjb
3703179193Sjb		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3704179198Sjb			regs[rd] = 0;
3705179193Sjb			break;
3706179193Sjb		}
3707179193Sjb
3708179193Sjb		regs[rd] = sz;
3709179193Sjb
3710179193Sjb		break;
3711179193Sjb	}
3712179193Sjb
3713179193Sjb	case DIF_SUBR_STRCHR:
3714179193Sjb	case DIF_SUBR_STRRCHR: {
3715179193Sjb		/*
3716179193Sjb		 * We're going to iterate over the string looking for the
3717179193Sjb		 * specified character.  We will iterate until we have reached
3718179193Sjb		 * the string length or we have found the character.  If this
3719179193Sjb		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3720179193Sjb		 * of the specified character instead of the first.
3721179193Sjb		 */
3722179193Sjb		uintptr_t saddr = tupregs[0].dttk_value;
3723179193Sjb		uintptr_t addr = tupregs[0].dttk_value;
3724179193Sjb		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3725179193Sjb		char c, target = (char)tupregs[1].dttk_value;
3726179193Sjb
3727179198Sjb		for (regs[rd] = 0; addr < limit; addr++) {
3728179193Sjb			if ((c = dtrace_load8(addr)) == target) {
3729179193Sjb				regs[rd] = addr;
3730179193Sjb
3731179193Sjb				if (subr == DIF_SUBR_STRCHR)
3732179193Sjb					break;
3733179193Sjb			}
3734179193Sjb
3735179193Sjb			if (c == '\0')
3736179193Sjb				break;
3737179193Sjb		}
3738179193Sjb
3739179193Sjb		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3740179198Sjb			regs[rd] = 0;
3741179193Sjb			break;
3742179193Sjb		}
3743179193Sjb
3744179193Sjb		break;
3745179193Sjb	}
3746179193Sjb
3747179193Sjb	case DIF_SUBR_STRSTR:
3748179193Sjb	case DIF_SUBR_INDEX:
3749179193Sjb	case DIF_SUBR_RINDEX: {
3750179193Sjb		/*
3751179193Sjb		 * We're going to iterate over the string looking for the
3752179193Sjb		 * specified string.  We will iterate until we have reached
3753179193Sjb		 * the string length or we have found the string.  (Yes, this
3754179193Sjb		 * is done in the most naive way possible -- but considering
3755179193Sjb		 * that the string we're searching for is likely to be
3756179193Sjb		 * relatively short, the complexity of Rabin-Karp or similar
3757179193Sjb		 * hardly seems merited.)
3758179193Sjb		 */
3759179193Sjb		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3760179193Sjb		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3761179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3762179193Sjb		size_t len = dtrace_strlen(addr, size);
3763179193Sjb		size_t sublen = dtrace_strlen(substr, size);
3764179193Sjb		char *limit = addr + len, *orig = addr;
3765179193Sjb		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3766179193Sjb		int inc = 1;
3767179193Sjb
3768179193Sjb		regs[rd] = notfound;
3769179193Sjb
3770179193Sjb		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3771179198Sjb			regs[rd] = 0;
3772179193Sjb			break;
3773179193Sjb		}
3774179193Sjb
3775179193Sjb		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3776179193Sjb		    vstate)) {
3777179198Sjb			regs[rd] = 0;
3778179193Sjb			break;
3779179193Sjb		}
3780179193Sjb
3781179193Sjb		/*
3782179193Sjb		 * strstr() and index()/rindex() have similar semantics if
3783179193Sjb		 * both strings are the empty string: strstr() returns a
3784179193Sjb		 * pointer to the (empty) string, and index() and rindex()
3785179193Sjb		 * both return index 0 (regardless of any position argument).
3786179193Sjb		 */
3787179193Sjb		if (sublen == 0 && len == 0) {
3788179193Sjb			if (subr == DIF_SUBR_STRSTR)
3789179193Sjb				regs[rd] = (uintptr_t)addr;
3790179193Sjb			else
3791179193Sjb				regs[rd] = 0;
3792179193Sjb			break;
3793179193Sjb		}
3794179193Sjb
3795179193Sjb		if (subr != DIF_SUBR_STRSTR) {
3796179193Sjb			if (subr == DIF_SUBR_RINDEX) {
3797179193Sjb				limit = orig - 1;
3798179193Sjb				addr += len;
3799179193Sjb				inc = -1;
3800179193Sjb			}
3801179193Sjb
3802179193Sjb			/*
3803179193Sjb			 * Both index() and rindex() take an optional position
3804179193Sjb			 * argument that denotes the starting position.
3805179193Sjb			 */
3806179193Sjb			if (nargs == 3) {
3807179193Sjb				int64_t pos = (int64_t)tupregs[2].dttk_value;
3808179193Sjb
3809179193Sjb				/*
3810179193Sjb				 * If the position argument to index() is
3811179193Sjb				 * negative, Perl implicitly clamps it at
3812179193Sjb				 * zero.  This semantic is a little surprising
3813179193Sjb				 * given the special meaning of negative
3814179193Sjb				 * positions to similar Perl functions like
3815179193Sjb				 * substr(), but it appears to reflect a
3816179193Sjb				 * notion that index() can start from a
3817179193Sjb				 * negative index and increment its way up to
3818179193Sjb				 * the string.  Given this notion, Perl's
3819179193Sjb				 * rindex() is at least self-consistent in
3820179193Sjb				 * that it implicitly clamps positions greater
3821179193Sjb				 * than the string length to be the string
3822179193Sjb				 * length.  Where Perl completely loses
3823179193Sjb				 * coherence, however, is when the specified
3824179193Sjb				 * substring is the empty string ("").  In
3825179193Sjb				 * this case, even if the position is
3826179193Sjb				 * negative, rindex() returns 0 -- and even if
3827179193Sjb				 * the position is greater than the length,
3828179193Sjb				 * index() returns the string length.  These
3829179193Sjb				 * semantics violate the notion that index()
3830179193Sjb				 * should never return a value less than the
3831179193Sjb				 * specified position and that rindex() should
3832179193Sjb				 * never return a value greater than the
3833179193Sjb				 * specified position.  (One assumes that
3834179193Sjb				 * these semantics are artifacts of Perl's
3835179193Sjb				 * implementation and not the results of
3836179193Sjb				 * deliberate design -- it beggars belief that
3837179193Sjb				 * even Larry Wall could desire such oddness.)
3838179193Sjb				 * While in the abstract one would wish for
3839179193Sjb				 * consistent position semantics across
3840179193Sjb				 * substr(), index() and rindex() -- or at the
3841179193Sjb				 * very least self-consistent position
3842179193Sjb				 * semantics for index() and rindex() -- we
3843179193Sjb				 * instead opt to keep with the extant Perl
3844179193Sjb				 * semantics, in all their broken glory.  (Do
3845179193Sjb				 * we have more desire to maintain Perl's
3846179193Sjb				 * semantics than Perl does?  Probably.)
3847179193Sjb				 */
3848179193Sjb				if (subr == DIF_SUBR_RINDEX) {
3849179193Sjb					if (pos < 0) {
3850179193Sjb						if (sublen == 0)
3851179193Sjb							regs[rd] = 0;
3852179193Sjb						break;
3853179193Sjb					}
3854179193Sjb
3855179193Sjb					if (pos > len)
3856179193Sjb						pos = len;
3857179193Sjb				} else {
3858179193Sjb					if (pos < 0)
3859179193Sjb						pos = 0;
3860179193Sjb
3861179193Sjb					if (pos >= len) {
3862179193Sjb						if (sublen == 0)
3863179193Sjb							regs[rd] = len;
3864179193Sjb						break;
3865179193Sjb					}
3866179193Sjb				}
3867179193Sjb
3868179193Sjb				addr = orig + pos;
3869179193Sjb			}
3870179193Sjb		}
3871179193Sjb
3872179193Sjb		for (regs[rd] = notfound; addr != limit; addr += inc) {
3873179193Sjb			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3874179193Sjb				if (subr != DIF_SUBR_STRSTR) {
3875179193Sjb					/*
3876179193Sjb					 * As D index() and rindex() are
3877179193Sjb					 * modeled on Perl (and not on awk),
3878179193Sjb					 * we return a zero-based (and not a
3879179193Sjb					 * one-based) index.  (For you Perl
3880179193Sjb					 * weenies: no, we're not going to add
3881179193Sjb					 * $[ -- and shouldn't you be at a con
3882179193Sjb					 * or something?)
3883179193Sjb					 */
3884179193Sjb					regs[rd] = (uintptr_t)(addr - orig);
3885179193Sjb					break;
3886179193Sjb				}
3887179193Sjb
3888179193Sjb				ASSERT(subr == DIF_SUBR_STRSTR);
3889179193Sjb				regs[rd] = (uintptr_t)addr;
3890179193Sjb				break;
3891179193Sjb			}
3892179193Sjb		}
3893179193Sjb
3894179193Sjb		break;
3895179193Sjb	}
3896179193Sjb
3897179193Sjb	case DIF_SUBR_STRTOK: {
3898179193Sjb		uintptr_t addr = tupregs[0].dttk_value;
3899179193Sjb		uintptr_t tokaddr = tupregs[1].dttk_value;
3900179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3901179193Sjb		uintptr_t limit, toklimit = tokaddr + size;
3902179198Sjb		uint8_t c = 0, tokmap[32];	 /* 256 / 8 */
3903179193Sjb		char *dest = (char *)mstate->dtms_scratch_ptr;
3904179193Sjb		int i;
3905179193Sjb
3906179193Sjb		/*
3907179193Sjb		 * Check both the token buffer and (later) the input buffer,
3908179193Sjb		 * since both could be non-scratch addresses.
3909179193Sjb		 */
3910179193Sjb		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3911179198Sjb			regs[rd] = 0;
3912179193Sjb			break;
3913179193Sjb		}
3914179193Sjb
3915179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
3916179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3917179198Sjb			regs[rd] = 0;
3918179193Sjb			break;
3919179193Sjb		}
3920179193Sjb
3921179198Sjb		if (addr == 0) {
3922179193Sjb			/*
3923179193Sjb			 * If the address specified is NULL, we use our saved
3924179193Sjb			 * strtok pointer from the mstate.  Note that this
3925179193Sjb			 * means that the saved strtok pointer is _only_
3926179193Sjb			 * valid within multiple enablings of the same probe --
3927179193Sjb			 * it behaves like an implicit clause-local variable.
3928179193Sjb			 */
3929179193Sjb			addr = mstate->dtms_strtok;
3930179193Sjb		} else {
3931179193Sjb			/*
3932179193Sjb			 * If the user-specified address is non-NULL we must
3933179193Sjb			 * access check it.  This is the only time we have
3934179193Sjb			 * a chance to do so, since this address may reside
3935179193Sjb			 * in the string table of this clause-- future calls
3936179193Sjb			 * (when we fetch addr from mstate->dtms_strtok)
3937179193Sjb			 * would fail this access check.
3938179193Sjb			 */
3939179193Sjb			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3940179198Sjb				regs[rd] = 0;
3941179193Sjb				break;
3942179193Sjb			}
3943179193Sjb		}
3944179193Sjb
3945179193Sjb		/*
3946179193Sjb		 * First, zero the token map, and then process the token
3947179193Sjb		 * string -- setting a bit in the map for every character
3948179193Sjb		 * found in the token string.
3949179193Sjb		 */
3950179193Sjb		for (i = 0; i < sizeof (tokmap); i++)
3951179193Sjb			tokmap[i] = 0;
3952179193Sjb
3953179193Sjb		for (; tokaddr < toklimit; tokaddr++) {
3954179193Sjb			if ((c = dtrace_load8(tokaddr)) == '\0')
3955179193Sjb				break;
3956179193Sjb
3957179193Sjb			ASSERT((c >> 3) < sizeof (tokmap));
3958179193Sjb			tokmap[c >> 3] |= (1 << (c & 0x7));
3959179193Sjb		}
3960179193Sjb
3961179193Sjb		for (limit = addr + size; addr < limit; addr++) {
3962179193Sjb			/*
3963179193Sjb			 * We're looking for a character that is _not_ contained
3964179193Sjb			 * in the token string.
3965179193Sjb			 */
3966179193Sjb			if ((c = dtrace_load8(addr)) == '\0')
3967179193Sjb				break;
3968179193Sjb
3969179193Sjb			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3970179193Sjb				break;
3971179193Sjb		}
3972179193Sjb
3973179193Sjb		if (c == '\0') {
3974179193Sjb			/*
3975179193Sjb			 * We reached the end of the string without finding
3976179193Sjb			 * any character that was not in the token string.
3977179193Sjb			 * We return NULL in this case, and we set the saved
3978179193Sjb			 * address to NULL as well.
3979179193Sjb			 */
3980179198Sjb			regs[rd] = 0;
3981179198Sjb			mstate->dtms_strtok = 0;
3982179193Sjb			break;
3983179193Sjb		}
3984179193Sjb
3985179193Sjb		/*
3986179193Sjb		 * From here on, we're copying into the destination string.
3987179193Sjb		 */
3988179193Sjb		for (i = 0; addr < limit && i < size - 1; addr++) {
3989179193Sjb			if ((c = dtrace_load8(addr)) == '\0')
3990179193Sjb				break;
3991179193Sjb
3992179193Sjb			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3993179193Sjb				break;
3994179193Sjb
3995179193Sjb			ASSERT(i < size);
3996179193Sjb			dest[i++] = c;
3997179193Sjb		}
3998179193Sjb
3999179193Sjb		ASSERT(i < size);
4000179193Sjb		dest[i] = '\0';
4001179193Sjb		regs[rd] = (uintptr_t)dest;
4002179193Sjb		mstate->dtms_scratch_ptr += size;
4003179193Sjb		mstate->dtms_strtok = addr;
4004179193Sjb		break;
4005179193Sjb	}
4006179193Sjb
4007179193Sjb	case DIF_SUBR_SUBSTR: {
4008179193Sjb		uintptr_t s = tupregs[0].dttk_value;
4009179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4010179193Sjb		char *d = (char *)mstate->dtms_scratch_ptr;
4011179193Sjb		int64_t index = (int64_t)tupregs[1].dttk_value;
4012179193Sjb		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4013179193Sjb		size_t len = dtrace_strlen((char *)s, size);
4014179193Sjb		int64_t i = 0;
4015179193Sjb
4016179193Sjb		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4017179198Sjb			regs[rd] = 0;
4018179193Sjb			break;
4019179193Sjb		}
4020179193Sjb
4021179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
4022179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4023179198Sjb			regs[rd] = 0;
4024179193Sjb			break;
4025179193Sjb		}
4026179193Sjb
4027179198Sjb		if (nargs <= 2)
4028179198Sjb			remaining = (int64_t)size;
4029179198Sjb
4030179193Sjb		if (index < 0) {
4031179193Sjb			index += len;
4032179193Sjb
4033179193Sjb			if (index < 0 && index + remaining > 0) {
4034179193Sjb				remaining += index;
4035179193Sjb				index = 0;
4036179193Sjb			}
4037179193Sjb		}
4038179193Sjb
4039179198Sjb		if (index >= len || index < 0) {
4040179198Sjb			remaining = 0;
4041179198Sjb		} else if (remaining < 0) {
4042179198Sjb			remaining += len - index;
4043179198Sjb		} else if (index + remaining > size) {
4044179198Sjb			remaining = size - index;
4045179198Sjb		}
4046179193Sjb
4047179198Sjb		for (i = 0; i < remaining; i++) {
4048179198Sjb			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4049179193Sjb				break;
4050179193Sjb		}
4051179193Sjb
4052179198Sjb		d[i] = '\0';
4053179198Sjb
4054179193Sjb		mstate->dtms_scratch_ptr += size;
4055179193Sjb		regs[rd] = (uintptr_t)d;
4056179193Sjb		break;
4057179193Sjb	}
4058179193Sjb
4059249856Spfg	case DIF_SUBR_TOUPPER:
4060249856Spfg	case DIF_SUBR_TOLOWER: {
4061249856Spfg		uintptr_t s = tupregs[0].dttk_value;
4062249856Spfg		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4063249856Spfg		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4064249856Spfg		size_t len = dtrace_strlen((char *)s, size);
4065249856Spfg		char lower, upper, convert;
4066249856Spfg		int64_t i;
4067249856Spfg
4068249856Spfg		if (subr == DIF_SUBR_TOUPPER) {
4069249856Spfg			lower = 'a';
4070249856Spfg			upper = 'z';
4071249856Spfg			convert = 'A';
4072249856Spfg		} else {
4073249856Spfg			lower = 'A';
4074249856Spfg			upper = 'Z';
4075249856Spfg			convert = 'a';
4076249856Spfg		}
4077249856Spfg
4078249856Spfg		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4079249856Spfg			regs[rd] = 0;
4080249856Spfg			break;
4081249856Spfg		}
4082249856Spfg
4083249856Spfg		if (!DTRACE_INSCRATCH(mstate, size)) {
4084249856Spfg			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4085249856Spfg			regs[rd] = 0;
4086249856Spfg			break;
4087249856Spfg		}
4088249856Spfg
4089249856Spfg		for (i = 0; i < size - 1; i++) {
4090249856Spfg			if ((c = dtrace_load8(s + i)) == '\0')
4091249856Spfg				break;
4092249856Spfg
4093249856Spfg			if (c >= lower && c <= upper)
4094249856Spfg				c = convert + (c - lower);
4095249856Spfg
4096249856Spfg			dest[i] = c;
4097249856Spfg		}
4098249856Spfg
4099249856Spfg		ASSERT(i < size);
4100249856Spfg		dest[i] = '\0';
4101249856Spfg		regs[rd] = (uintptr_t)dest;
4102249856Spfg		mstate->dtms_scratch_ptr += size;
4103249856Spfg		break;
4104249856Spfg	}
4105249856Spfg
4106179198Sjb#if defined(sun)
4107179193Sjb	case DIF_SUBR_GETMAJOR:
4108179193Sjb#ifdef _LP64
4109179193Sjb		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4110179193Sjb#else
4111179193Sjb		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4112179193Sjb#endif
4113179193Sjb		break;
4114179193Sjb
4115179193Sjb	case DIF_SUBR_GETMINOR:
4116179193Sjb#ifdef _LP64
4117179193Sjb		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4118179193Sjb#else
4119179193Sjb		regs[rd] = tupregs[0].dttk_value & MAXMIN;
4120179193Sjb#endif
4121179193Sjb		break;
4122179193Sjb
4123179193Sjb	case DIF_SUBR_DDI_PATHNAME: {
4124179193Sjb		/*
4125179193Sjb		 * This one is a galactic mess.  We are going to roughly
4126179193Sjb		 * emulate ddi_pathname(), but it's made more complicated
4127179193Sjb		 * by the fact that we (a) want to include the minor name and
4128179193Sjb		 * (b) must proceed iteratively instead of recursively.
4129179193Sjb		 */
4130179193Sjb		uintptr_t dest = mstate->dtms_scratch_ptr;
4131179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4132179193Sjb		char *start = (char *)dest, *end = start + size - 1;
4133179193Sjb		uintptr_t daddr = tupregs[0].dttk_value;
4134179193Sjb		int64_t minor = (int64_t)tupregs[1].dttk_value;
4135179193Sjb		char *s;
4136179193Sjb		int i, len, depth = 0;
4137179193Sjb
4138179193Sjb		/*
4139179193Sjb		 * Due to all the pointer jumping we do and context we must
4140179193Sjb		 * rely upon, we just mandate that the user must have kernel
4141179193Sjb		 * read privileges to use this routine.
4142179193Sjb		 */
4143179193Sjb		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4144179193Sjb			*flags |= CPU_DTRACE_KPRIV;
4145179193Sjb			*illval = daddr;
4146179198Sjb			regs[rd] = 0;
4147179193Sjb		}
4148179193Sjb
4149179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
4150179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4151179198Sjb			regs[rd] = 0;
4152179193Sjb			break;
4153179193Sjb		}
4154179193Sjb
4155179193Sjb		*end = '\0';
4156179193Sjb
4157179193Sjb		/*
4158179193Sjb		 * We want to have a name for the minor.  In order to do this,
4159179193Sjb		 * we need to walk the minor list from the devinfo.  We want
4160179193Sjb		 * to be sure that we don't infinitely walk a circular list,
4161179193Sjb		 * so we check for circularity by sending a scout pointer
4162179193Sjb		 * ahead two elements for every element that we iterate over;
4163179193Sjb		 * if the list is circular, these will ultimately point to the
4164179193Sjb		 * same element.  You may recognize this little trick as the
4165179193Sjb		 * answer to a stupid interview question -- one that always
4166179193Sjb		 * seems to be asked by those who had to have it laboriously
4167179193Sjb		 * explained to them, and who can't even concisely describe
4168179193Sjb		 * the conditions under which one would be forced to resort to
4169179193Sjb		 * this technique.  Needless to say, those conditions are
4170179198Sjb		 * found here -- and probably only here.  Is this the only use
4171179198Sjb		 * of this infamous trick in shipping, production code?  If it
4172179198Sjb		 * isn't, it probably should be...
4173179193Sjb		 */
4174179193Sjb		if (minor != -1) {
4175179193Sjb			uintptr_t maddr = dtrace_loadptr(daddr +
4176179193Sjb			    offsetof(struct dev_info, devi_minor));
4177179193Sjb
4178179193Sjb			uintptr_t next = offsetof(struct ddi_minor_data, next);
4179179193Sjb			uintptr_t name = offsetof(struct ddi_minor_data,
4180179193Sjb			    d_minor) + offsetof(struct ddi_minor, name);
4181179193Sjb			uintptr_t dev = offsetof(struct ddi_minor_data,
4182179193Sjb			    d_minor) + offsetof(struct ddi_minor, dev);
4183179193Sjb			uintptr_t scout;
4184179193Sjb
4185179193Sjb			if (maddr != NULL)
4186179193Sjb				scout = dtrace_loadptr(maddr + next);
4187179193Sjb
4188179193Sjb			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4189179193Sjb				uint64_t m;
4190179193Sjb#ifdef _LP64
4191179193Sjb				m = dtrace_load64(maddr + dev) & MAXMIN64;
4192179193Sjb#else
4193179193Sjb				m = dtrace_load32(maddr + dev) & MAXMIN;
4194179193Sjb#endif
4195179193Sjb				if (m != minor) {
4196179193Sjb					maddr = dtrace_loadptr(maddr + next);
4197179193Sjb
4198179193Sjb					if (scout == NULL)
4199179193Sjb						continue;
4200179193Sjb
4201179193Sjb					scout = dtrace_loadptr(scout + next);
4202179193Sjb
4203179193Sjb					if (scout == NULL)
4204179193Sjb						continue;
4205179193Sjb
4206179193Sjb					scout = dtrace_loadptr(scout + next);
4207179193Sjb
4208179193Sjb					if (scout == NULL)
4209179193Sjb						continue;
4210179193Sjb
4211179193Sjb					if (scout == maddr) {
4212179193Sjb						*flags |= CPU_DTRACE_ILLOP;
4213179193Sjb						break;
4214179193Sjb					}
4215179193Sjb
4216179193Sjb					continue;
4217179193Sjb				}
4218179193Sjb
4219179193Sjb				/*
4220179193Sjb				 * We have the minor data.  Now we need to
4221179193Sjb				 * copy the minor's name into the end of the
4222179193Sjb				 * pathname.
4223179193Sjb				 */
4224179193Sjb				s = (char *)dtrace_loadptr(maddr + name);
4225179193Sjb				len = dtrace_strlen(s, size);
4226179193Sjb
4227179193Sjb				if (*flags & CPU_DTRACE_FAULT)
4228179193Sjb					break;
4229179193Sjb
4230179193Sjb				if (len != 0) {
4231179193Sjb					if ((end -= (len + 1)) < start)
4232179193Sjb						break;
4233179193Sjb
4234179193Sjb					*end = ':';
4235179193Sjb				}
4236179193Sjb
4237179193Sjb				for (i = 1; i <= len; i++)
4238179193Sjb					end[i] = dtrace_load8((uintptr_t)s++);
4239179193Sjb				break;
4240179193Sjb			}
4241179193Sjb		}
4242179193Sjb
4243179193Sjb		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4244179193Sjb			ddi_node_state_t devi_state;
4245179193Sjb
4246179193Sjb			devi_state = dtrace_load32(daddr +
4247179193Sjb			    offsetof(struct dev_info, devi_node_state));
4248179193Sjb
4249179193Sjb			if (*flags & CPU_DTRACE_FAULT)
4250179193Sjb				break;
4251179193Sjb
4252179193Sjb			if (devi_state >= DS_INITIALIZED) {
4253179193Sjb				s = (char *)dtrace_loadptr(daddr +
4254179193Sjb				    offsetof(struct dev_info, devi_addr));
4255179193Sjb				len = dtrace_strlen(s, size);
4256179193Sjb
4257179193Sjb				if (*flags & CPU_DTRACE_FAULT)
4258179193Sjb					break;
4259179193Sjb
4260179193Sjb				if (len != 0) {
4261179193Sjb					if ((end -= (len + 1)) < start)
4262179193Sjb						break;
4263179193Sjb
4264179193Sjb					*end = '@';
4265179193Sjb				}
4266179193Sjb
4267179193Sjb				for (i = 1; i <= len; i++)
4268179193Sjb					end[i] = dtrace_load8((uintptr_t)s++);
4269179193Sjb			}
4270179193Sjb
4271179193Sjb			/*
4272179193Sjb			 * Now for the node name...
4273179193Sjb			 */
4274179193Sjb			s = (char *)dtrace_loadptr(daddr +
4275179193Sjb			    offsetof(struct dev_info, devi_node_name));
4276179193Sjb
4277179193Sjb			daddr = dtrace_loadptr(daddr +
4278179193Sjb			    offsetof(struct dev_info, devi_parent));
4279179193Sjb
4280179193Sjb			/*
4281179193Sjb			 * If our parent is NULL (that is, if we're the root
4282179193Sjb			 * node), we're going to use the special path
4283179193Sjb			 * "devices".
4284179193Sjb			 */
4285179198Sjb			if (daddr == 0)
4286179193Sjb				s = "devices";
4287179193Sjb
4288179193Sjb			len = dtrace_strlen(s, size);
4289179193Sjb			if (*flags & CPU_DTRACE_FAULT)
4290179193Sjb				break;
4291179193Sjb
4292179193Sjb			if ((end -= (len + 1)) < start)
4293179193Sjb				break;
4294179193Sjb
4295179193Sjb			for (i = 1; i <= len; i++)
4296179193Sjb				end[i] = dtrace_load8((uintptr_t)s++);
4297179193Sjb			*end = '/';
4298179193Sjb
4299179193Sjb			if (depth++ > dtrace_devdepth_max) {
4300179193Sjb				*flags |= CPU_DTRACE_ILLOP;
4301179193Sjb				break;
4302179193Sjb			}
4303179193Sjb		}
4304179193Sjb
4305179193Sjb		if (end < start)
4306179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4307179193Sjb
4308179198Sjb		if (daddr == 0) {
4309179193Sjb			regs[rd] = (uintptr_t)end;
4310179193Sjb			mstate->dtms_scratch_ptr += size;
4311179193Sjb		}
4312179193Sjb
4313179193Sjb		break;
4314179193Sjb	}
4315179198Sjb#endif
4316179193Sjb
4317179193Sjb	case DIF_SUBR_STRJOIN: {
4318179193Sjb		char *d = (char *)mstate->dtms_scratch_ptr;
4319179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4320179193Sjb		uintptr_t s1 = tupregs[0].dttk_value;
4321179193Sjb		uintptr_t s2 = tupregs[1].dttk_value;
4322179193Sjb		int i = 0;
4323179193Sjb
4324179193Sjb		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4325179193Sjb		    !dtrace_strcanload(s2, size, mstate, vstate)) {
4326179198Sjb			regs[rd] = 0;
4327179193Sjb			break;
4328179193Sjb		}
4329179193Sjb
4330179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
4331179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4332179198Sjb			regs[rd] = 0;
4333179193Sjb			break;
4334179193Sjb		}
4335179193Sjb
4336179193Sjb		for (;;) {
4337179193Sjb			if (i >= size) {
4338179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4339179198Sjb				regs[rd] = 0;
4340179193Sjb				break;
4341179193Sjb			}
4342179193Sjb
4343179193Sjb			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4344179193Sjb				i--;
4345179193Sjb				break;
4346179193Sjb			}
4347179193Sjb		}
4348179193Sjb
4349179193Sjb		for (;;) {
4350179193Sjb			if (i >= size) {
4351179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4352179198Sjb				regs[rd] = 0;
4353179193Sjb				break;
4354179193Sjb			}
4355179193Sjb
4356179193Sjb			if ((d[i++] = dtrace_load8(s2++)) == '\0')
4357179193Sjb				break;
4358179193Sjb		}
4359179193Sjb
4360179193Sjb		if (i < size) {
4361179193Sjb			mstate->dtms_scratch_ptr += i;
4362179193Sjb			regs[rd] = (uintptr_t)d;
4363179193Sjb		}
4364179193Sjb
4365179193Sjb		break;
4366179193Sjb	}
4367179193Sjb
4368179193Sjb	case DIF_SUBR_LLTOSTR: {
4369179193Sjb		int64_t i = (int64_t)tupregs[0].dttk_value;
4370249856Spfg		uint64_t val, digit;
4371249856Spfg		uint64_t size = 65;	/* enough room for 2^64 in binary */
4372179193Sjb		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4373249856Spfg		int base = 10;
4374179193Sjb
4375249856Spfg		if (nargs > 1) {
4376249856Spfg			if ((base = tupregs[1].dttk_value) <= 1 ||
4377249856Spfg			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4378249856Spfg				*flags |= CPU_DTRACE_ILLOP;
4379249856Spfg				break;
4380249856Spfg			}
4381249856Spfg		}
4382249856Spfg
4383249856Spfg		val = (base == 10 && i < 0) ? i * -1 : i;
4384249856Spfg
4385179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
4386179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4387179198Sjb			regs[rd] = 0;
4388179193Sjb			break;
4389179193Sjb		}
4390179193Sjb
4391249856Spfg		for (*end-- = '\0'; val; val /= base) {
4392249856Spfg			if ((digit = val % base) <= '9' - '0') {
4393249856Spfg				*end-- = '0' + digit;
4394249856Spfg			} else {
4395249856Spfg				*end-- = 'a' + (digit - ('9' - '0') - 1);
4396249856Spfg			}
4397249856Spfg		}
4398179193Sjb
4399249856Spfg		if (i == 0 && base == 16)
4400179193Sjb			*end-- = '0';
4401179193Sjb
4402249856Spfg		if (base == 16)
4403249856Spfg			*end-- = 'x';
4404249856Spfg
4405249856Spfg		if (i == 0 || base == 8 || base == 16)
4406249856Spfg			*end-- = '0';
4407249856Spfg
4408249856Spfg		if (i < 0 && base == 10)
4409179193Sjb			*end-- = '-';
4410179193Sjb
4411179193Sjb		regs[rd] = (uintptr_t)end + 1;
4412179193Sjb		mstate->dtms_scratch_ptr += size;
4413179193Sjb		break;
4414179193Sjb	}
4415179193Sjb
4416179193Sjb	case DIF_SUBR_HTONS:
4417179193Sjb	case DIF_SUBR_NTOHS:
4418179198Sjb#if BYTE_ORDER == BIG_ENDIAN
4419179193Sjb		regs[rd] = (uint16_t)tupregs[0].dttk_value;
4420179193Sjb#else
4421179193Sjb		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4422179193Sjb#endif
4423179193Sjb		break;
4424179193Sjb
4425179193Sjb
4426179193Sjb	case DIF_SUBR_HTONL:
4427179193Sjb	case DIF_SUBR_NTOHL:
4428179198Sjb#if BYTE_ORDER == BIG_ENDIAN
4429179193Sjb		regs[rd] = (uint32_t)tupregs[0].dttk_value;
4430179193Sjb#else
4431179193Sjb		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4432179193Sjb#endif
4433179193Sjb		break;
4434179193Sjb
4435179193Sjb
4436179193Sjb	case DIF_SUBR_HTONLL:
4437179193Sjb	case DIF_SUBR_NTOHLL:
4438179198Sjb#if BYTE_ORDER == BIG_ENDIAN
4439179193Sjb		regs[rd] = (uint64_t)tupregs[0].dttk_value;
4440179193Sjb#else
4441179193Sjb		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4442179193Sjb#endif
4443179193Sjb		break;
4444179193Sjb
4445179193Sjb
4446179193Sjb	case DIF_SUBR_DIRNAME:
4447179193Sjb	case DIF_SUBR_BASENAME: {
4448179193Sjb		char *dest = (char *)mstate->dtms_scratch_ptr;
4449179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4450179193Sjb		uintptr_t src = tupregs[0].dttk_value;
4451179193Sjb		int i, j, len = dtrace_strlen((char *)src, size);
4452179193Sjb		int lastbase = -1, firstbase = -1, lastdir = -1;
4453179193Sjb		int start, end;
4454179193Sjb
4455179193Sjb		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4456179198Sjb			regs[rd] = 0;
4457179193Sjb			break;
4458179193Sjb		}
4459179193Sjb
4460179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
4461179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4462179198Sjb			regs[rd] = 0;
4463179193Sjb			break;
4464179193Sjb		}
4465179193Sjb
4466179193Sjb		/*
4467179193Sjb		 * The basename and dirname for a zero-length string is
4468179193Sjb		 * defined to be "."
4469179193Sjb		 */
4470179193Sjb		if (len == 0) {
4471179193Sjb			len = 1;
4472179193Sjb			src = (uintptr_t)".";
4473179193Sjb		}
4474179193Sjb
4475179193Sjb		/*
4476179193Sjb		 * Start from the back of the string, moving back toward the
4477179193Sjb		 * front until we see a character that isn't a slash.  That
4478179193Sjb		 * character is the last character in the basename.
4479179193Sjb		 */
4480179193Sjb		for (i = len - 1; i >= 0; i--) {
4481179193Sjb			if (dtrace_load8(src + i) != '/')
4482179193Sjb				break;
4483179193Sjb		}
4484179193Sjb
4485179193Sjb		if (i >= 0)
4486179193Sjb			lastbase = i;
4487179193Sjb
4488179193Sjb		/*
4489179193Sjb		 * Starting from the last character in the basename, move
4490179193Sjb		 * towards the front until we find a slash.  The character
4491179193Sjb		 * that we processed immediately before that is the first
4492179193Sjb		 * character in the basename.
4493179193Sjb		 */
4494179193Sjb		for (; i >= 0; i--) {
4495179193Sjb			if (dtrace_load8(src + i) == '/')
4496179193Sjb				break;
4497179193Sjb		}
4498179193Sjb
4499179193Sjb		if (i >= 0)
4500179193Sjb			firstbase = i + 1;
4501179193Sjb
4502179193Sjb		/*
4503179193Sjb		 * Now keep going until we find a non-slash character.  That
4504179193Sjb		 * character is the last character in the dirname.
4505179193Sjb		 */
4506179193Sjb		for (; i >= 0; i--) {
4507179193Sjb			if (dtrace_load8(src + i) != '/')
4508179193Sjb				break;
4509179193Sjb		}
4510179193Sjb
4511179193Sjb		if (i >= 0)
4512179193Sjb			lastdir = i;
4513179193Sjb
4514179193Sjb		ASSERT(!(lastbase == -1 && firstbase != -1));
4515179193Sjb		ASSERT(!(firstbase == -1 && lastdir != -1));
4516179193Sjb
4517179193Sjb		if (lastbase == -1) {
4518179193Sjb			/*
4519179193Sjb			 * We didn't find a non-slash character.  We know that
4520179193Sjb			 * the length is non-zero, so the whole string must be
4521179193Sjb			 * slashes.  In either the dirname or the basename
4522179193Sjb			 * case, we return '/'.
4523179193Sjb			 */
4524179193Sjb			ASSERT(firstbase == -1);
4525179193Sjb			firstbase = lastbase = lastdir = 0;
4526179193Sjb		}
4527179193Sjb
4528179193Sjb		if (firstbase == -1) {
4529179193Sjb			/*
4530179193Sjb			 * The entire string consists only of a basename
4531179193Sjb			 * component.  If we're looking for dirname, we need
4532179193Sjb			 * to change our string to be just "."; if we're
4533179193Sjb			 * looking for a basename, we'll just set the first
4534179193Sjb			 * character of the basename to be 0.
4535179193Sjb			 */
4536179193Sjb			if (subr == DIF_SUBR_DIRNAME) {
4537179193Sjb				ASSERT(lastdir == -1);
4538179193Sjb				src = (uintptr_t)".";
4539179193Sjb				lastdir = 0;
4540179193Sjb			} else {
4541179193Sjb				firstbase = 0;
4542179193Sjb			}
4543179193Sjb		}
4544179193Sjb
4545179193Sjb		if (subr == DIF_SUBR_DIRNAME) {
4546179193Sjb			if (lastdir == -1) {
4547179193Sjb				/*
4548179193Sjb				 * We know that we have a slash in the name --
4549179193Sjb				 * or lastdir would be set to 0, above.  And
4550179193Sjb				 * because lastdir is -1, we know that this
4551179193Sjb				 * slash must be the first character.  (That
4552179193Sjb				 * is, the full string must be of the form
4553179193Sjb				 * "/basename".)  In this case, the last
4554179193Sjb				 * character of the directory name is 0.
4555179193Sjb				 */
4556179193Sjb				lastdir = 0;
4557179193Sjb			}
4558179193Sjb
4559179193Sjb			start = 0;
4560179193Sjb			end = lastdir;
4561179193Sjb		} else {
4562179193Sjb			ASSERT(subr == DIF_SUBR_BASENAME);
4563179193Sjb			ASSERT(firstbase != -1 && lastbase != -1);
4564179193Sjb			start = firstbase;
4565179193Sjb			end = lastbase;
4566179193Sjb		}
4567179193Sjb
4568179193Sjb		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4569179193Sjb			dest[j] = dtrace_load8(src + i);
4570179193Sjb
4571179193Sjb		dest[j] = '\0';
4572179193Sjb		regs[rd] = (uintptr_t)dest;
4573179193Sjb		mstate->dtms_scratch_ptr += size;
4574179193Sjb		break;
4575179193Sjb	}
4576179193Sjb
4577179193Sjb	case DIF_SUBR_CLEANPATH: {
4578179193Sjb		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4579179193Sjb		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4580179193Sjb		uintptr_t src = tupregs[0].dttk_value;
4581179193Sjb		int i = 0, j = 0;
4582179193Sjb
4583179193Sjb		if (!dtrace_strcanload(src, size, mstate, vstate)) {
4584179198Sjb			regs[rd] = 0;
4585179193Sjb			break;
4586179193Sjb		}
4587179193Sjb
4588179193Sjb		if (!DTRACE_INSCRATCH(mstate, size)) {
4589179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4590179198Sjb			regs[rd] = 0;
4591179193Sjb			break;
4592179193Sjb		}
4593179193Sjb
4594179193Sjb		/*
4595179193Sjb		 * Move forward, loading each character.
4596179193Sjb		 */
4597179193Sjb		do {
4598179193Sjb			c = dtrace_load8(src + i++);
4599179193Sjbnext:
4600179193Sjb			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
4601179193Sjb				break;
4602179193Sjb
4603179193Sjb			if (c != '/') {
4604179193Sjb				dest[j++] = c;
4605179193Sjb				continue;
4606179193Sjb			}
4607179193Sjb
4608179193Sjb			c = dtrace_load8(src + i++);
4609179193Sjb
4610179193Sjb			if (c == '/') {
4611179193Sjb				/*
4612179193Sjb				 * We have two slashes -- we can just advance
4613179193Sjb				 * to the next character.
4614179193Sjb				 */
4615179193Sjb				goto next;
4616179193Sjb			}
4617179193Sjb
4618179193Sjb			if (c != '.') {
4619179193Sjb				/*
4620179193Sjb				 * This is not "." and it's not ".." -- we can
4621179193Sjb				 * just store the "/" and this character and
4622179193Sjb				 * drive on.
4623179193Sjb				 */
4624179193Sjb				dest[j++] = '/';
4625179193Sjb				dest[j++] = c;
4626179193Sjb				continue;
4627179193Sjb			}
4628179193Sjb
4629179193Sjb			c = dtrace_load8(src + i++);
4630179193Sjb
4631179193Sjb			if (c == '/') {
4632179193Sjb				/*
4633179193Sjb				 * This is a "/./" component.  We're not going
4634179193Sjb				 * to store anything in the destination buffer;
4635179193Sjb				 * we're just going to go to the next component.
4636179193Sjb				 */
4637179193Sjb				goto next;
4638179193Sjb			}
4639179193Sjb
4640179193Sjb			if (c != '.') {
4641179193Sjb				/*
4642179193Sjb				 * This is not ".." -- we can just store the
4643179193Sjb				 * "/." and this character and continue
4644179193Sjb				 * processing.
4645179193Sjb				 */
4646179193Sjb				dest[j++] = '/';
4647179193Sjb				dest[j++] = '.';
4648179193Sjb				dest[j++] = c;
4649179193Sjb				continue;
4650179193Sjb			}
4651179193Sjb
4652179193Sjb			c = dtrace_load8(src + i++);
4653179193Sjb
4654179193Sjb			if (c != '/' && c != '\0') {
4655179193Sjb				/*
4656179193Sjb				 * This is not ".." -- it's "..[mumble]".
4657179193Sjb				 * We'll store the "/.." and this character
4658179193Sjb				 * and continue processing.
4659179193Sjb				 */
4660179193Sjb				dest[j++] = '/';
4661179193Sjb				dest[j++] = '.';
4662179193Sjb				dest[j++] = '.';
4663179193Sjb				dest[j++] = c;
4664179193Sjb				continue;
4665179193Sjb			}
4666179193Sjb
4667179193Sjb			/*
4668179193Sjb			 * This is "/../" or "/..\0".  We need to back up
4669179193Sjb			 * our destination pointer until we find a "/".
4670179193Sjb			 */
4671179193Sjb			i--;
4672179193Sjb			while (j != 0 && dest[--j] != '/')
4673179193Sjb				continue;
4674179193Sjb
4675179193Sjb			if (c == '\0')
4676179193Sjb				dest[++j] = '/';
4677179193Sjb		} while (c != '\0');
4678179193Sjb
4679179193Sjb		dest[j] = '\0';
4680179193Sjb		regs[rd] = (uintptr_t)dest;
4681179193Sjb		mstate->dtms_scratch_ptr += size;
4682179193Sjb		break;
4683179193Sjb	}
4684179193Sjb
4685179193Sjb	case DIF_SUBR_INET_NTOA:
4686179193Sjb	case DIF_SUBR_INET_NTOA6:
4687179193Sjb	case DIF_SUBR_INET_NTOP: {
4688179193Sjb		size_t size;
4689179193Sjb		int af, argi, i;
4690179193Sjb		char *base, *end;
4691179193Sjb
4692179193Sjb		if (subr == DIF_SUBR_INET_NTOP) {
4693179193Sjb			af = (int)tupregs[0].dttk_value;
4694179193Sjb			argi = 1;
4695179193Sjb		} else {
4696179193Sjb			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4697179193Sjb			argi = 0;
4698179193Sjb		}
4699179193Sjb
4700179193Sjb		if (af == AF_INET) {
4701179193Sjb			ipaddr_t ip4;
4702179193Sjb			uint8_t *ptr8, val;
4703179193Sjb
4704179193Sjb			/*
4705179193Sjb			 * Safely load the IPv4 address.
4706179193Sjb			 */
4707179193Sjb			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4708179193Sjb
4709179193Sjb			/*
4710179193Sjb			 * Check an IPv4 string will fit in scratch.
4711179193Sjb			 */
4712179193Sjb			size = INET_ADDRSTRLEN;
4713179193Sjb			if (!DTRACE_INSCRATCH(mstate, size)) {
4714179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4715179198Sjb				regs[rd] = 0;
4716179193Sjb				break;
4717179193Sjb			}
4718179193Sjb			base = (char *)mstate->dtms_scratch_ptr;
4719179193Sjb			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4720179193Sjb
4721179193Sjb			/*
4722179193Sjb			 * Stringify as a dotted decimal quad.
4723179193Sjb			 */
4724179193Sjb			*end-- = '\0';
4725179193Sjb			ptr8 = (uint8_t *)&ip4;
4726179193Sjb			for (i = 3; i >= 0; i--) {
4727179193Sjb				val = ptr8[i];
4728179193Sjb
4729179193Sjb				if (val == 0) {
4730179193Sjb					*end-- = '0';
4731179193Sjb				} else {
4732179193Sjb					for (; val; val /= 10) {
4733179193Sjb						*end-- = '0' + (val % 10);
4734179193Sjb					}
4735179193Sjb				}
4736179193Sjb
4737179193Sjb				if (i > 0)
4738179193Sjb					*end-- = '.';
4739179193Sjb			}
4740179193Sjb			ASSERT(end + 1 >= base);
4741179193Sjb
4742179193Sjb		} else if (af == AF_INET6) {
4743179193Sjb			struct in6_addr ip6;
4744179193Sjb			int firstzero, tryzero, numzero, v6end;
4745179193Sjb			uint16_t val;
4746179193Sjb			const char digits[] = "0123456789abcdef";
4747179193Sjb
4748179193Sjb			/*
4749179193Sjb			 * Stringify using RFC 1884 convention 2 - 16 bit
4750179193Sjb			 * hexadecimal values with a zero-run compression.
4751179193Sjb			 * Lower case hexadecimal digits are used.
4752179193Sjb			 * 	eg, fe80::214:4fff:fe0b:76c8.
4753179193Sjb			 * The IPv4 embedded form is returned for inet_ntop,
4754179193Sjb			 * just the IPv4 string is returned for inet_ntoa6.
4755179193Sjb			 */
4756179193Sjb
4757179193Sjb			/*
4758179193Sjb			 * Safely load the IPv6 address.
4759179193Sjb			 */
4760179193Sjb			dtrace_bcopy(
4761179193Sjb			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4762179193Sjb			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4763179193Sjb
4764179193Sjb			/*
4765179193Sjb			 * Check an IPv6 string will fit in scratch.
4766179193Sjb			 */
4767179193Sjb			size = INET6_ADDRSTRLEN;
4768179193Sjb			if (!DTRACE_INSCRATCH(mstate, size)) {
4769179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4770179198Sjb				regs[rd] = 0;
4771179193Sjb				break;
4772179193Sjb			}
4773179193Sjb			base = (char *)mstate->dtms_scratch_ptr;
4774179193Sjb			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4775179193Sjb			*end-- = '\0';
4776179193Sjb
4777179193Sjb			/*
4778179193Sjb			 * Find the longest run of 16 bit zero values
4779179193Sjb			 * for the single allowed zero compression - "::".
4780179193Sjb			 */
4781179193Sjb			firstzero = -1;
4782179193Sjb			tryzero = -1;
4783179193Sjb			numzero = 1;
4784179193Sjb			for (i = 0; i < sizeof (struct in6_addr); i++) {
4785179198Sjb#if defined(sun)
4786179193Sjb				if (ip6._S6_un._S6_u8[i] == 0 &&
4787179198Sjb#else
4788179198Sjb				if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4789179198Sjb#endif
4790179193Sjb				    tryzero == -1 && i % 2 == 0) {
4791179193Sjb					tryzero = i;
4792179193Sjb					continue;
4793179193Sjb				}
4794179193Sjb
4795179193Sjb				if (tryzero != -1 &&
4796179198Sjb#if defined(sun)
4797179193Sjb				    (ip6._S6_un._S6_u8[i] != 0 ||
4798179198Sjb#else
4799179198Sjb				    (ip6.__u6_addr.__u6_addr8[i] != 0 ||
4800179198Sjb#endif
4801179193Sjb				    i == sizeof (struct in6_addr) - 1)) {
4802179193Sjb
4803179193Sjb					if (i - tryzero <= numzero) {
4804179193Sjb						tryzero = -1;
4805179193Sjb						continue;
4806179193Sjb					}
4807179193Sjb
4808179193Sjb					firstzero = tryzero;
4809179193Sjb					numzero = i - i % 2 - tryzero;
4810179193Sjb					tryzero = -1;
4811179193Sjb
4812179198Sjb#if defined(sun)
4813179193Sjb					if (ip6._S6_un._S6_u8[i] == 0 &&
4814179198Sjb#else
4815179198Sjb					if (ip6.__u6_addr.__u6_addr8[i] == 0 &&
4816179198Sjb#endif
4817179193Sjb					    i == sizeof (struct in6_addr) - 1)
4818179193Sjb						numzero += 2;
4819179193Sjb				}
4820179193Sjb			}
4821179193Sjb			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4822179193Sjb
4823179193Sjb			/*
4824179193Sjb			 * Check for an IPv4 embedded address.
4825179193Sjb			 */
4826179193Sjb			v6end = sizeof (struct in6_addr) - 2;
4827179193Sjb			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4828179193Sjb			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4829179193Sjb				for (i = sizeof (struct in6_addr) - 1;
4830179193Sjb				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4831179193Sjb					ASSERT(end >= base);
4832179193Sjb
4833179198Sjb#if defined(sun)
4834179193Sjb					val = ip6._S6_un._S6_u8[i];
4835179198Sjb#else
4836179198Sjb					val = ip6.__u6_addr.__u6_addr8[i];
4837179198Sjb#endif
4838179193Sjb
4839179193Sjb					if (val == 0) {
4840179193Sjb						*end-- = '0';
4841179193Sjb					} else {
4842179193Sjb						for (; val; val /= 10) {
4843179193Sjb							*end-- = '0' + val % 10;
4844179193Sjb						}
4845179193Sjb					}
4846179193Sjb
4847179193Sjb					if (i > DTRACE_V4MAPPED_OFFSET)
4848179193Sjb						*end-- = '.';
4849179193Sjb				}
4850179193Sjb
4851179193Sjb				if (subr == DIF_SUBR_INET_NTOA6)
4852179193Sjb					goto inetout;
4853179193Sjb
4854179193Sjb				/*
4855179193Sjb				 * Set v6end to skip the IPv4 address that
4856179193Sjb				 * we have already stringified.
4857179193Sjb				 */
4858179193Sjb				v6end = 10;
4859179193Sjb			}
4860179193Sjb
4861179193Sjb			/*
4862179193Sjb			 * Build the IPv6 string by working through the
4863179193Sjb			 * address in reverse.
4864179193Sjb			 */
4865179193Sjb			for (i = v6end; i >= 0; i -= 2) {
4866179193Sjb				ASSERT(end >= base);
4867179193Sjb
4868179193Sjb				if (i == firstzero + numzero - 2) {
4869179193Sjb					*end-- = ':';
4870179193Sjb					*end-- = ':';
4871179193Sjb					i -= numzero - 2;
4872179193Sjb					continue;
4873179193Sjb				}
4874179193Sjb
4875179193Sjb				if (i < 14 && i != firstzero - 2)
4876179193Sjb					*end-- = ':';
4877179193Sjb
4878179198Sjb#if defined(sun)
4879179193Sjb				val = (ip6._S6_un._S6_u8[i] << 8) +
4880179193Sjb				    ip6._S6_un._S6_u8[i + 1];
4881179198Sjb#else
4882179198Sjb				val = (ip6.__u6_addr.__u6_addr8[i] << 8) +
4883179198Sjb				    ip6.__u6_addr.__u6_addr8[i + 1];
4884179198Sjb#endif
4885179193Sjb
4886179193Sjb				if (val == 0) {
4887179193Sjb					*end-- = '0';
4888179193Sjb				} else {
4889179193Sjb					for (; val; val /= 16) {
4890179193Sjb						*end-- = digits[val % 16];
4891179193Sjb					}
4892179193Sjb				}
4893179193Sjb			}
4894179193Sjb			ASSERT(end + 1 >= base);
4895179193Sjb
4896179193Sjb		} else {
4897179193Sjb			/*
4898179193Sjb			 * The user didn't use AH_INET or AH_INET6.
4899179193Sjb			 */
4900179193Sjb			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4901179198Sjb			regs[rd] = 0;
4902179193Sjb			break;
4903179193Sjb		}
4904179193Sjb
4905179193Sjbinetout:	regs[rd] = (uintptr_t)end + 1;
4906179193Sjb		mstate->dtms_scratch_ptr += size;
4907179193Sjb		break;
4908179193Sjb	}
4909179193Sjb
4910179198Sjb	case DIF_SUBR_MEMREF: {
4911179198Sjb		uintptr_t size = 2 * sizeof(uintptr_t);
4912179198Sjb		uintptr_t *memref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4913179198Sjb		size_t scratch_size = ((uintptr_t) memref - mstate->dtms_scratch_ptr) + size;
4914179198Sjb
4915179198Sjb		/* address and length */
4916179198Sjb		memref[0] = tupregs[0].dttk_value;
4917179198Sjb		memref[1] = tupregs[1].dttk_value;
4918179198Sjb
4919179198Sjb		regs[rd] = (uintptr_t) memref;
4920179198Sjb		mstate->dtms_scratch_ptr += scratch_size;
4921179198Sjb		break;
4922179193Sjb	}
4923179198Sjb
4924179198Sjb	case DIF_SUBR_TYPEREF: {
4925179198Sjb		uintptr_t size = 4 * sizeof(uintptr_t);
4926179198Sjb		uintptr_t *typeref = (uintptr_t *) P2ROUNDUP(mstate->dtms_scratch_ptr, sizeof(uintptr_t));
4927179198Sjb		size_t scratch_size = ((uintptr_t) typeref - mstate->dtms_scratch_ptr) + size;
4928179198Sjb
4929179198Sjb		/* address, num_elements, type_str, type_len */
4930179198Sjb		typeref[0] = tupregs[0].dttk_value;
4931179198Sjb		typeref[1] = tupregs[1].dttk_value;
4932179198Sjb		typeref[2] = tupregs[2].dttk_value;
4933179198Sjb		typeref[3] = tupregs[3].dttk_value;
4934179198Sjb
4935179198Sjb		regs[rd] = (uintptr_t) typeref;
4936179198Sjb		mstate->dtms_scratch_ptr += scratch_size;
4937179198Sjb		break;
4938179198Sjb	}
4939179198Sjb	}
4940179193Sjb}
4941179193Sjb
4942179193Sjb/*
4943179193Sjb * Emulate the execution of DTrace IR instructions specified by the given
4944179193Sjb * DIF object.  This function is deliberately void of assertions as all of
4945179193Sjb * the necessary checks are handled by a call to dtrace_difo_validate().
4946179193Sjb */
4947179193Sjbstatic uint64_t
4948179193Sjbdtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4949179193Sjb    dtrace_vstate_t *vstate, dtrace_state_t *state)
4950179193Sjb{
4951179193Sjb	const dif_instr_t *text = difo->dtdo_buf;
4952179193Sjb	const uint_t textlen = difo->dtdo_len;
4953179193Sjb	const char *strtab = difo->dtdo_strtab;
4954179193Sjb	const uint64_t *inttab = difo->dtdo_inttab;
4955179193Sjb
4956179193Sjb	uint64_t rval = 0;
4957179193Sjb	dtrace_statvar_t *svar;
4958179193Sjb	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4959179193Sjb	dtrace_difv_t *v;
4960179198Sjb	volatile uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
4961179198Sjb	volatile uintptr_t *illval = &cpu_core[curcpu].cpuc_dtrace_illval;
4962179193Sjb
4963179193Sjb	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4964179193Sjb	uint64_t regs[DIF_DIR_NREGS];
4965179193Sjb	uint64_t *tmp;
4966179193Sjb
4967179193Sjb	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4968179193Sjb	int64_t cc_r;
4969179198Sjb	uint_t pc = 0, id, opc = 0;
4970179193Sjb	uint8_t ttop = 0;
4971179193Sjb	dif_instr_t instr;
4972179193Sjb	uint_t r1, r2, rd;
4973179193Sjb
4974179193Sjb	/*
4975179193Sjb	 * We stash the current DIF object into the machine state: we need it
4976179193Sjb	 * for subsequent access checking.
4977179193Sjb	 */
4978179193Sjb	mstate->dtms_difo = difo;
4979179193Sjb
4980179193Sjb	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4981179193Sjb
4982179193Sjb	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4983179193Sjb		opc = pc;
4984179193Sjb
4985179193Sjb		instr = text[pc++];
4986179193Sjb		r1 = DIF_INSTR_R1(instr);
4987179193Sjb		r2 = DIF_INSTR_R2(instr);
4988179193Sjb		rd = DIF_INSTR_RD(instr);
4989179193Sjb
4990179193Sjb		switch (DIF_INSTR_OP(instr)) {
4991179193Sjb		case DIF_OP_OR:
4992179193Sjb			regs[rd] = regs[r1] | regs[r2];
4993179193Sjb			break;
4994179193Sjb		case DIF_OP_XOR:
4995179193Sjb			regs[rd] = regs[r1] ^ regs[r2];
4996179193Sjb			break;
4997179193Sjb		case DIF_OP_AND:
4998179193Sjb			regs[rd] = regs[r1] & regs[r2];
4999179193Sjb			break;
5000179193Sjb		case DIF_OP_SLL:
5001179193Sjb			regs[rd] = regs[r1] << regs[r2];
5002179193Sjb			break;
5003179193Sjb		case DIF_OP_SRL:
5004179193Sjb			regs[rd] = regs[r1] >> regs[r2];
5005179193Sjb			break;
5006179193Sjb		case DIF_OP_SUB:
5007179193Sjb			regs[rd] = regs[r1] - regs[r2];
5008179193Sjb			break;
5009179193Sjb		case DIF_OP_ADD:
5010179193Sjb			regs[rd] = regs[r1] + regs[r2];
5011179193Sjb			break;
5012179193Sjb		case DIF_OP_MUL:
5013179193Sjb			regs[rd] = regs[r1] * regs[r2];
5014179193Sjb			break;
5015179193Sjb		case DIF_OP_SDIV:
5016179193Sjb			if (regs[r2] == 0) {
5017179193Sjb				regs[rd] = 0;
5018179193Sjb				*flags |= CPU_DTRACE_DIVZERO;
5019179193Sjb			} else {
5020179193Sjb				regs[rd] = (int64_t)regs[r1] /
5021179193Sjb				    (int64_t)regs[r2];
5022179193Sjb			}
5023179193Sjb			break;
5024179193Sjb
5025179193Sjb		case DIF_OP_UDIV:
5026179193Sjb			if (regs[r2] == 0) {
5027179193Sjb				regs[rd] = 0;
5028179193Sjb				*flags |= CPU_DTRACE_DIVZERO;
5029179193Sjb			} else {
5030179193Sjb				regs[rd] = regs[r1] / regs[r2];
5031179193Sjb			}
5032179193Sjb			break;
5033179193Sjb
5034179193Sjb		case DIF_OP_SREM:
5035179193Sjb			if (regs[r2] == 0) {
5036179193Sjb				regs[rd] = 0;
5037179193Sjb				*flags |= CPU_DTRACE_DIVZERO;
5038179193Sjb			} else {
5039179193Sjb				regs[rd] = (int64_t)regs[r1] %
5040179193Sjb				    (int64_t)regs[r2];
5041179193Sjb			}
5042179193Sjb			break;
5043179193Sjb
5044179193Sjb		case DIF_OP_UREM:
5045179193Sjb			if (regs[r2] == 0) {
5046179193Sjb				regs[rd] = 0;
5047179193Sjb				*flags |= CPU_DTRACE_DIVZERO;
5048179193Sjb			} else {
5049179193Sjb				regs[rd] = regs[r1] % regs[r2];
5050179193Sjb			}
5051179193Sjb			break;
5052179193Sjb
5053179193Sjb		case DIF_OP_NOT:
5054179193Sjb			regs[rd] = ~regs[r1];
5055179193Sjb			break;
5056179193Sjb		case DIF_OP_MOV:
5057179193Sjb			regs[rd] = regs[r1];
5058179193Sjb			break;
5059179193Sjb		case DIF_OP_CMP:
5060179193Sjb			cc_r = regs[r1] - regs[r2];
5061179193Sjb			cc_n = cc_r < 0;
5062179193Sjb			cc_z = cc_r == 0;
5063179193Sjb			cc_v = 0;
5064179193Sjb			cc_c = regs[r1] < regs[r2];
5065179193Sjb			break;
5066179193Sjb		case DIF_OP_TST:
5067179193Sjb			cc_n = cc_v = cc_c = 0;
5068179193Sjb			cc_z = regs[r1] == 0;
5069179193Sjb			break;
5070179193Sjb		case DIF_OP_BA:
5071179193Sjb			pc = DIF_INSTR_LABEL(instr);
5072179193Sjb			break;
5073179193Sjb		case DIF_OP_BE:
5074179193Sjb			if (cc_z)
5075179193Sjb				pc = DIF_INSTR_LABEL(instr);
5076179193Sjb			break;
5077179193Sjb		case DIF_OP_BNE:
5078179193Sjb			if (cc_z == 0)
5079179193Sjb				pc = DIF_INSTR_LABEL(instr);
5080179193Sjb			break;
5081179193Sjb		case DIF_OP_BG:
5082179193Sjb			if ((cc_z | (cc_n ^ cc_v)) == 0)
5083179193Sjb				pc = DIF_INSTR_LABEL(instr);
5084179193Sjb			break;
5085179193Sjb		case DIF_OP_BGU:
5086179193Sjb			if ((cc_c | cc_z) == 0)
5087179193Sjb				pc = DIF_INSTR_LABEL(instr);
5088179193Sjb			break;
5089179193Sjb		case DIF_OP_BGE:
5090179193Sjb			if ((cc_n ^ cc_v) == 0)
5091179193Sjb				pc = DIF_INSTR_LABEL(instr);
5092179193Sjb			break;
5093179193Sjb		case DIF_OP_BGEU:
5094179193Sjb			if (cc_c == 0)
5095179193Sjb				pc = DIF_INSTR_LABEL(instr);
5096179193Sjb			break;
5097179193Sjb		case DIF_OP_BL:
5098179193Sjb			if (cc_n ^ cc_v)
5099179193Sjb				pc = DIF_INSTR_LABEL(instr);
5100179193Sjb			break;
5101179193Sjb		case DIF_OP_BLU:
5102179193Sjb			if (cc_c)
5103179193Sjb				pc = DIF_INSTR_LABEL(instr);
5104179193Sjb			break;
5105179193Sjb		case DIF_OP_BLE:
5106179193Sjb			if (cc_z | (cc_n ^ cc_v))
5107179193Sjb				pc = DIF_INSTR_LABEL(instr);
5108179193Sjb			break;
5109179193Sjb		case DIF_OP_BLEU:
5110179193Sjb			if (cc_c | cc_z)
5111179193Sjb				pc = DIF_INSTR_LABEL(instr);
5112179193Sjb			break;
5113179193Sjb		case DIF_OP_RLDSB:
5114179193Sjb			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5115179193Sjb				*flags |= CPU_DTRACE_KPRIV;
5116179193Sjb				*illval = regs[r1];
5117179193Sjb				break;
5118179193Sjb			}
5119179193Sjb			/*FALLTHROUGH*/
5120179193Sjb		case DIF_OP_LDSB:
5121179193Sjb			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5122179193Sjb			break;
5123179193Sjb		case DIF_OP_RLDSH:
5124179193Sjb			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5125179193Sjb				*flags |= CPU_DTRACE_KPRIV;
5126179193Sjb				*illval = regs[r1];
5127179193Sjb				break;
5128179193Sjb			}
5129179193Sjb			/*FALLTHROUGH*/
5130179193Sjb		case DIF_OP_LDSH:
5131179193Sjb			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5132179193Sjb			break;
5133179193Sjb		case DIF_OP_RLDSW:
5134179193Sjb			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5135179193Sjb				*flags |= CPU_DTRACE_KPRIV;
5136179193Sjb				*illval = regs[r1];
5137179193Sjb				break;
5138179193Sjb			}
5139179193Sjb			/*FALLTHROUGH*/
5140179193Sjb		case DIF_OP_LDSW:
5141179193Sjb			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5142179193Sjb			break;
5143179193Sjb		case DIF_OP_RLDUB:
5144179193Sjb			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
5145179193Sjb				*flags |= CPU_DTRACE_KPRIV;
5146179193Sjb				*illval = regs[r1];
5147179193Sjb				break;
5148179193Sjb			}
5149179193Sjb			/*FALLTHROUGH*/
5150179193Sjb		case DIF_OP_LDUB:
5151179193Sjb			regs[rd] = dtrace_load8(regs[r1]);
5152179193Sjb			break;
5153179193Sjb		case DIF_OP_RLDUH:
5154179193Sjb			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
5155179193Sjb				*flags |= CPU_DTRACE_KPRIV;
5156179193Sjb				*illval = regs[r1];
5157179193Sjb				break;
5158179193Sjb			}
5159179193Sjb			/*FALLTHROUGH*/
5160179193Sjb		case DIF_OP_LDUH:
5161179193Sjb			regs[rd] = dtrace_load16(regs[r1]);
5162179193Sjb			break;
5163179193Sjb		case DIF_OP_RLDUW:
5164179193Sjb			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
5165179193Sjb				*flags |= CPU_DTRACE_KPRIV;
5166179193Sjb				*illval = regs[r1];
5167179193Sjb				break;
5168179193Sjb			}
5169179193Sjb			/*FALLTHROUGH*/
5170179193Sjb		case DIF_OP_LDUW:
5171179193Sjb			regs[rd] = dtrace_load32(regs[r1]);
5172179193Sjb			break;
5173179193Sjb		case DIF_OP_RLDX:
5174179193Sjb			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
5175179193Sjb				*flags |= CPU_DTRACE_KPRIV;
5176179193Sjb				*illval = regs[r1];
5177179193Sjb				break;
5178179193Sjb			}
5179179193Sjb			/*FALLTHROUGH*/
5180179193Sjb		case DIF_OP_LDX:
5181179193Sjb			regs[rd] = dtrace_load64(regs[r1]);
5182179193Sjb			break;
5183179193Sjb		case DIF_OP_ULDSB:
5184179193Sjb			regs[rd] = (int8_t)
5185179193Sjb			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5186179193Sjb			break;
5187179193Sjb		case DIF_OP_ULDSH:
5188179193Sjb			regs[rd] = (int16_t)
5189179193Sjb			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5190179193Sjb			break;
5191179193Sjb		case DIF_OP_ULDSW:
5192179193Sjb			regs[rd] = (int32_t)
5193179193Sjb			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5194179193Sjb			break;
5195179193Sjb		case DIF_OP_ULDUB:
5196179193Sjb			regs[rd] =
5197179193Sjb			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5198179193Sjb			break;
5199179193Sjb		case DIF_OP_ULDUH:
5200179193Sjb			regs[rd] =
5201179193Sjb			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5202179193Sjb			break;
5203179193Sjb		case DIF_OP_ULDUW:
5204179193Sjb			regs[rd] =
5205179193Sjb			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5206179193Sjb			break;
5207179193Sjb		case DIF_OP_ULDX:
5208179193Sjb			regs[rd] =
5209179193Sjb			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5210179193Sjb			break;
5211179193Sjb		case DIF_OP_RET:
5212179193Sjb			rval = regs[rd];
5213179193Sjb			pc = textlen;
5214179193Sjb			break;
5215179193Sjb		case DIF_OP_NOP:
5216179193Sjb			break;
5217179193Sjb		case DIF_OP_SETX:
5218179193Sjb			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5219179193Sjb			break;
5220179193Sjb		case DIF_OP_SETS:
5221179193Sjb			regs[rd] = (uint64_t)(uintptr_t)
5222179193Sjb			    (strtab + DIF_INSTR_STRING(instr));
5223179193Sjb			break;
5224179193Sjb		case DIF_OP_SCMP: {
5225179193Sjb			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5226179193Sjb			uintptr_t s1 = regs[r1];
5227179193Sjb			uintptr_t s2 = regs[r2];
5228179193Sjb
5229179198Sjb			if (s1 != 0 &&
5230179193Sjb			    !dtrace_strcanload(s1, sz, mstate, vstate))
5231179193Sjb				break;
5232179198Sjb			if (s2 != 0 &&
5233179193Sjb			    !dtrace_strcanload(s2, sz, mstate, vstate))
5234179193Sjb				break;
5235179193Sjb
5236179193Sjb			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5237179193Sjb
5238179193Sjb			cc_n = cc_r < 0;
5239179193Sjb			cc_z = cc_r == 0;
5240179193Sjb			cc_v = cc_c = 0;
5241179193Sjb			break;
5242179193Sjb		}
5243179193Sjb		case DIF_OP_LDGA:
5244179193Sjb			regs[rd] = dtrace_dif_variable(mstate, state,
5245179193Sjb			    r1, regs[r2]);
5246179193Sjb			break;
5247179193Sjb		case DIF_OP_LDGS:
5248179193Sjb			id = DIF_INSTR_VAR(instr);
5249179193Sjb
5250179193Sjb			if (id >= DIF_VAR_OTHER_UBASE) {
5251179193Sjb				uintptr_t a;
5252179193Sjb
5253179193Sjb				id -= DIF_VAR_OTHER_UBASE;
5254179193Sjb				svar = vstate->dtvs_globals[id];
5255179193Sjb				ASSERT(svar != NULL);
5256179193Sjb				v = &svar->dtsv_var;
5257179193Sjb
5258179193Sjb				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5259179193Sjb					regs[rd] = svar->dtsv_data;
5260179193Sjb					break;
5261179193Sjb				}
5262179193Sjb
5263179193Sjb				a = (uintptr_t)svar->dtsv_data;
5264179193Sjb
5265179193Sjb				if (*(uint8_t *)a == UINT8_MAX) {
5266179193Sjb					/*
5267179193Sjb					 * If the 0th byte is set to UINT8_MAX
5268179193Sjb					 * then this is to be treated as a
5269179193Sjb					 * reference to a NULL variable.
5270179193Sjb					 */
5271179198Sjb					regs[rd] = 0;
5272179193Sjb				} else {
5273179193Sjb					regs[rd] = a + sizeof (uint64_t);
5274179193Sjb				}
5275179193Sjb
5276179193Sjb				break;
5277179193Sjb			}
5278179193Sjb
5279179193Sjb			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5280179193Sjb			break;
5281179193Sjb
5282179193Sjb		case DIF_OP_STGS:
5283179193Sjb			id = DIF_INSTR_VAR(instr);
5284179193Sjb
5285179193Sjb			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5286179193Sjb			id -= DIF_VAR_OTHER_UBASE;
5287179193Sjb
5288179193Sjb			svar = vstate->dtvs_globals[id];
5289179193Sjb			ASSERT(svar != NULL);
5290179193Sjb			v = &svar->dtsv_var;
5291179193Sjb
5292179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5293179193Sjb				uintptr_t a = (uintptr_t)svar->dtsv_data;
5294179193Sjb
5295179198Sjb				ASSERT(a != 0);
5296179193Sjb				ASSERT(svar->dtsv_size != 0);
5297179193Sjb
5298179198Sjb				if (regs[rd] == 0) {
5299179193Sjb					*(uint8_t *)a = UINT8_MAX;
5300179193Sjb					break;
5301179193Sjb				} else {
5302179193Sjb					*(uint8_t *)a = 0;
5303179193Sjb					a += sizeof (uint64_t);
5304179193Sjb				}
5305179193Sjb				if (!dtrace_vcanload(
5306179193Sjb				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5307179193Sjb				    mstate, vstate))
5308179193Sjb					break;
5309179193Sjb
5310179193Sjb				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5311179193Sjb				    (void *)a, &v->dtdv_type);
5312179193Sjb				break;
5313179193Sjb			}
5314179193Sjb
5315179193Sjb			svar->dtsv_data = regs[rd];
5316179193Sjb			break;
5317179193Sjb
5318179193Sjb		case DIF_OP_LDTA:
5319179193Sjb			/*
5320179193Sjb			 * There are no DTrace built-in thread-local arrays at
5321179193Sjb			 * present.  This opcode is saved for future work.
5322179193Sjb			 */
5323179193Sjb			*flags |= CPU_DTRACE_ILLOP;
5324179193Sjb			regs[rd] = 0;
5325179193Sjb			break;
5326179193Sjb
5327179193Sjb		case DIF_OP_LDLS:
5328179193Sjb			id = DIF_INSTR_VAR(instr);
5329179193Sjb
5330179193Sjb			if (id < DIF_VAR_OTHER_UBASE) {
5331179193Sjb				/*
5332179193Sjb				 * For now, this has no meaning.
5333179193Sjb				 */
5334179193Sjb				regs[rd] = 0;
5335179193Sjb				break;
5336179193Sjb			}
5337179193Sjb
5338179193Sjb			id -= DIF_VAR_OTHER_UBASE;
5339179193Sjb
5340179193Sjb			ASSERT(id < vstate->dtvs_nlocals);
5341179193Sjb			ASSERT(vstate->dtvs_locals != NULL);
5342179193Sjb
5343179193Sjb			svar = vstate->dtvs_locals[id];
5344179193Sjb			ASSERT(svar != NULL);
5345179193Sjb			v = &svar->dtsv_var;
5346179193Sjb
5347179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5348179193Sjb				uintptr_t a = (uintptr_t)svar->dtsv_data;
5349179193Sjb				size_t sz = v->dtdv_type.dtdt_size;
5350179193Sjb
5351179193Sjb				sz += sizeof (uint64_t);
5352179193Sjb				ASSERT(svar->dtsv_size == NCPU * sz);
5353179198Sjb				a += curcpu * sz;
5354179193Sjb
5355179193Sjb				if (*(uint8_t *)a == UINT8_MAX) {
5356179193Sjb					/*
5357179193Sjb					 * If the 0th byte is set to UINT8_MAX
5358179193Sjb					 * then this is to be treated as a
5359179193Sjb					 * reference to a NULL variable.
5360179193Sjb					 */
5361179198Sjb					regs[rd] = 0;
5362179193Sjb				} else {
5363179193Sjb					regs[rd] = a + sizeof (uint64_t);
5364179193Sjb				}
5365179193Sjb
5366179193Sjb				break;
5367179193Sjb			}
5368179193Sjb
5369179193Sjb			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5370179193Sjb			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5371179198Sjb			regs[rd] = tmp[curcpu];
5372179193Sjb			break;
5373179193Sjb
5374179193Sjb		case DIF_OP_STLS:
5375179193Sjb			id = DIF_INSTR_VAR(instr);
5376179193Sjb
5377179193Sjb			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5378179193Sjb			id -= DIF_VAR_OTHER_UBASE;
5379179193Sjb			ASSERT(id < vstate->dtvs_nlocals);
5380179193Sjb
5381179193Sjb			ASSERT(vstate->dtvs_locals != NULL);
5382179193Sjb			svar = vstate->dtvs_locals[id];
5383179193Sjb			ASSERT(svar != NULL);
5384179193Sjb			v = &svar->dtsv_var;
5385179193Sjb
5386179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5387179193Sjb				uintptr_t a = (uintptr_t)svar->dtsv_data;
5388179193Sjb				size_t sz = v->dtdv_type.dtdt_size;
5389179193Sjb
5390179193Sjb				sz += sizeof (uint64_t);
5391179193Sjb				ASSERT(svar->dtsv_size == NCPU * sz);
5392179198Sjb				a += curcpu * sz;
5393179193Sjb
5394179198Sjb				if (regs[rd] == 0) {
5395179193Sjb					*(uint8_t *)a = UINT8_MAX;
5396179193Sjb					break;
5397179193Sjb				} else {
5398179193Sjb					*(uint8_t *)a = 0;
5399179193Sjb					a += sizeof (uint64_t);
5400179193Sjb				}
5401179193Sjb
5402179193Sjb				if (!dtrace_vcanload(
5403179193Sjb				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5404179193Sjb				    mstate, vstate))
5405179193Sjb					break;
5406179193Sjb
5407179193Sjb				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5408179193Sjb				    (void *)a, &v->dtdv_type);
5409179193Sjb				break;
5410179193Sjb			}
5411179193Sjb
5412179193Sjb			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5413179193Sjb			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5414179198Sjb			tmp[curcpu] = regs[rd];
5415179193Sjb			break;
5416179193Sjb
5417179193Sjb		case DIF_OP_LDTS: {
5418179193Sjb			dtrace_dynvar_t *dvar;
5419179193Sjb			dtrace_key_t *key;
5420179193Sjb
5421179193Sjb			id = DIF_INSTR_VAR(instr);
5422179193Sjb			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5423179193Sjb			id -= DIF_VAR_OTHER_UBASE;
5424179193Sjb			v = &vstate->dtvs_tlocals[id];
5425179193Sjb
5426179193Sjb			key = &tupregs[DIF_DTR_NREGS];
5427179193Sjb			key[0].dttk_value = (uint64_t)id;
5428179193Sjb			key[0].dttk_size = 0;
5429179193Sjb			DTRACE_TLS_THRKEY(key[1].dttk_value);
5430179193Sjb			key[1].dttk_size = 0;
5431179193Sjb
5432179193Sjb			dvar = dtrace_dynvar(dstate, 2, key,
5433179193Sjb			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5434179193Sjb			    mstate, vstate);
5435179193Sjb
5436179193Sjb			if (dvar == NULL) {
5437179193Sjb				regs[rd] = 0;
5438179193Sjb				break;
5439179193Sjb			}
5440179193Sjb
5441179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5442179193Sjb				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5443179193Sjb			} else {
5444179193Sjb				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5445179193Sjb			}
5446179193Sjb
5447179193Sjb			break;
5448179193Sjb		}
5449179193Sjb
5450179193Sjb		case DIF_OP_STTS: {
5451179193Sjb			dtrace_dynvar_t *dvar;
5452179193Sjb			dtrace_key_t *key;
5453179193Sjb
5454179193Sjb			id = DIF_INSTR_VAR(instr);
5455179193Sjb			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5456179193Sjb			id -= DIF_VAR_OTHER_UBASE;
5457179193Sjb
5458179193Sjb			key = &tupregs[DIF_DTR_NREGS];
5459179193Sjb			key[0].dttk_value = (uint64_t)id;
5460179193Sjb			key[0].dttk_size = 0;
5461179193Sjb			DTRACE_TLS_THRKEY(key[1].dttk_value);
5462179193Sjb			key[1].dttk_size = 0;
5463179193Sjb			v = &vstate->dtvs_tlocals[id];
5464179193Sjb
5465179193Sjb			dvar = dtrace_dynvar(dstate, 2, key,
5466179193Sjb			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5467179193Sjb			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5468179193Sjb			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5469179193Sjb			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5470179193Sjb
5471179193Sjb			/*
5472179193Sjb			 * Given that we're storing to thread-local data,
5473179193Sjb			 * we need to flush our predicate cache.
5474179193Sjb			 */
5475179198Sjb			curthread->t_predcache = 0;
5476179193Sjb
5477179193Sjb			if (dvar == NULL)
5478179193Sjb				break;
5479179193Sjb
5480179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5481179193Sjb				if (!dtrace_vcanload(
5482179193Sjb				    (void *)(uintptr_t)regs[rd],
5483179193Sjb				    &v->dtdv_type, mstate, vstate))
5484179193Sjb					break;
5485179193Sjb
5486179193Sjb				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5487179193Sjb				    dvar->dtdv_data, &v->dtdv_type);
5488179193Sjb			} else {
5489179193Sjb				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5490179193Sjb			}
5491179193Sjb
5492179193Sjb			break;
5493179193Sjb		}
5494179193Sjb
5495179193Sjb		case DIF_OP_SRA:
5496179193Sjb			regs[rd] = (int64_t)regs[r1] >> regs[r2];
5497179193Sjb			break;
5498179193Sjb
5499179193Sjb		case DIF_OP_CALL:
5500179193Sjb			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5501179193Sjb			    regs, tupregs, ttop, mstate, state);
5502179193Sjb			break;
5503179193Sjb
5504179193Sjb		case DIF_OP_PUSHTR:
5505179193Sjb			if (ttop == DIF_DTR_NREGS) {
5506179193Sjb				*flags |= CPU_DTRACE_TUPOFLOW;
5507179193Sjb				break;
5508179193Sjb			}
5509179193Sjb
5510179193Sjb			if (r1 == DIF_TYPE_STRING) {
5511179193Sjb				/*
5512179193Sjb				 * If this is a string type and the size is 0,
5513179193Sjb				 * we'll use the system-wide default string
5514179193Sjb				 * size.  Note that we are _not_ looking at
5515179193Sjb				 * the value of the DTRACEOPT_STRSIZE option;
5516179193Sjb				 * had this been set, we would expect to have
5517179193Sjb				 * a non-zero size value in the "pushtr".
5518179193Sjb				 */
5519179193Sjb				tupregs[ttop].dttk_size =
5520179193Sjb				    dtrace_strlen((char *)(uintptr_t)regs[rd],
5521179193Sjb				    regs[r2] ? regs[r2] :
5522179193Sjb				    dtrace_strsize_default) + 1;
5523179193Sjb			} else {
5524179193Sjb				tupregs[ttop].dttk_size = regs[r2];
5525179193Sjb			}
5526179193Sjb
5527179193Sjb			tupregs[ttop++].dttk_value = regs[rd];
5528179193Sjb			break;
5529179193Sjb
5530179193Sjb		case DIF_OP_PUSHTV:
5531179193Sjb			if (ttop == DIF_DTR_NREGS) {
5532179193Sjb				*flags |= CPU_DTRACE_TUPOFLOW;
5533179193Sjb				break;
5534179193Sjb			}
5535179193Sjb
5536179193Sjb			tupregs[ttop].dttk_value = regs[rd];
5537179193Sjb			tupregs[ttop++].dttk_size = 0;
5538179193Sjb			break;
5539179193Sjb
5540179193Sjb		case DIF_OP_POPTS:
5541179193Sjb			if (ttop != 0)
5542179193Sjb				ttop--;
5543179193Sjb			break;
5544179193Sjb
5545179193Sjb		case DIF_OP_FLUSHTS:
5546179193Sjb			ttop = 0;
5547179193Sjb			break;
5548179193Sjb
5549179193Sjb		case DIF_OP_LDGAA:
5550179193Sjb		case DIF_OP_LDTAA: {
5551179193Sjb			dtrace_dynvar_t *dvar;
5552179193Sjb			dtrace_key_t *key = tupregs;
5553179193Sjb			uint_t nkeys = ttop;
5554179193Sjb
5555179193Sjb			id = DIF_INSTR_VAR(instr);
5556179193Sjb			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5557179193Sjb			id -= DIF_VAR_OTHER_UBASE;
5558179193Sjb
5559179193Sjb			key[nkeys].dttk_value = (uint64_t)id;
5560179193Sjb			key[nkeys++].dttk_size = 0;
5561179193Sjb
5562179193Sjb			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5563179193Sjb				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5564179193Sjb				key[nkeys++].dttk_size = 0;
5565179193Sjb				v = &vstate->dtvs_tlocals[id];
5566179193Sjb			} else {
5567179193Sjb				v = &vstate->dtvs_globals[id]->dtsv_var;
5568179193Sjb			}
5569179193Sjb
5570179193Sjb			dvar = dtrace_dynvar(dstate, nkeys, key,
5571179193Sjb			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5572179193Sjb			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5573179193Sjb			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5574179193Sjb
5575179193Sjb			if (dvar == NULL) {
5576179193Sjb				regs[rd] = 0;
5577179193Sjb				break;
5578179193Sjb			}
5579179193Sjb
5580179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5581179193Sjb				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5582179193Sjb			} else {
5583179193Sjb				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5584179193Sjb			}
5585179193Sjb
5586179193Sjb			break;
5587179193Sjb		}
5588179193Sjb
5589179193Sjb		case DIF_OP_STGAA:
5590179193Sjb		case DIF_OP_STTAA: {
5591179193Sjb			dtrace_dynvar_t *dvar;
5592179193Sjb			dtrace_key_t *key = tupregs;
5593179193Sjb			uint_t nkeys = ttop;
5594179193Sjb
5595179193Sjb			id = DIF_INSTR_VAR(instr);
5596179193Sjb			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5597179193Sjb			id -= DIF_VAR_OTHER_UBASE;
5598179193Sjb
5599179193Sjb			key[nkeys].dttk_value = (uint64_t)id;
5600179193Sjb			key[nkeys++].dttk_size = 0;
5601179193Sjb
5602179193Sjb			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5603179193Sjb				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5604179193Sjb				key[nkeys++].dttk_size = 0;
5605179193Sjb				v = &vstate->dtvs_tlocals[id];
5606179193Sjb			} else {
5607179193Sjb				v = &vstate->dtvs_globals[id]->dtsv_var;
5608179193Sjb			}
5609179193Sjb
5610179193Sjb			dvar = dtrace_dynvar(dstate, nkeys, key,
5611179193Sjb			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5612179193Sjb			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5613179193Sjb			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5614179193Sjb			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5615179193Sjb
5616179193Sjb			if (dvar == NULL)
5617179193Sjb				break;
5618179193Sjb
5619179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5620179193Sjb				if (!dtrace_vcanload(
5621179193Sjb				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5622179193Sjb				    mstate, vstate))
5623179193Sjb					break;
5624179193Sjb
5625179193Sjb				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5626179193Sjb				    dvar->dtdv_data, &v->dtdv_type);
5627179193Sjb			} else {
5628179193Sjb				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5629179193Sjb			}
5630179193Sjb
5631179193Sjb			break;
5632179193Sjb		}
5633179193Sjb
5634179193Sjb		case DIF_OP_ALLOCS: {
5635179193Sjb			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5636179193Sjb			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5637179193Sjb
5638179193Sjb			/*
5639179193Sjb			 * Rounding up the user allocation size could have
5640179193Sjb			 * overflowed large, bogus allocations (like -1ULL) to
5641179193Sjb			 * 0.
5642179193Sjb			 */
5643179193Sjb			if (size < regs[r1] ||
5644179193Sjb			    !DTRACE_INSCRATCH(mstate, size)) {
5645179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5646179198Sjb				regs[rd] = 0;
5647179193Sjb				break;
5648179193Sjb			}
5649179193Sjb
5650179193Sjb			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5651179193Sjb			mstate->dtms_scratch_ptr += size;
5652179193Sjb			regs[rd] = ptr;
5653179193Sjb			break;
5654179193Sjb		}
5655179193Sjb
5656179193Sjb		case DIF_OP_COPYS:
5657179193Sjb			if (!dtrace_canstore(regs[rd], regs[r2],
5658179193Sjb			    mstate, vstate)) {
5659179193Sjb				*flags |= CPU_DTRACE_BADADDR;
5660179193Sjb				*illval = regs[rd];
5661179193Sjb				break;
5662179193Sjb			}
5663179193Sjb
5664179193Sjb			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5665179193Sjb				break;
5666179193Sjb
5667179193Sjb			dtrace_bcopy((void *)(uintptr_t)regs[r1],
5668179193Sjb			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5669179193Sjb			break;
5670179193Sjb
5671179193Sjb		case DIF_OP_STB:
5672179193Sjb			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5673179193Sjb				*flags |= CPU_DTRACE_BADADDR;
5674179193Sjb				*illval = regs[rd];
5675179193Sjb				break;
5676179193Sjb			}
5677179193Sjb			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5678179193Sjb			break;
5679179193Sjb
5680179193Sjb		case DIF_OP_STH:
5681179193Sjb			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5682179193Sjb				*flags |= CPU_DTRACE_BADADDR;
5683179193Sjb				*illval = regs[rd];
5684179193Sjb				break;
5685179193Sjb			}
5686179193Sjb			if (regs[rd] & 1) {
5687179193Sjb				*flags |= CPU_DTRACE_BADALIGN;
5688179193Sjb				*illval = regs[rd];
5689179193Sjb				break;
5690179193Sjb			}
5691179193Sjb			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5692179193Sjb			break;
5693179193Sjb
5694179193Sjb		case DIF_OP_STW:
5695179193Sjb			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5696179193Sjb				*flags |= CPU_DTRACE_BADADDR;
5697179193Sjb				*illval = regs[rd];
5698179193Sjb				break;
5699179193Sjb			}
5700179193Sjb			if (regs[rd] & 3) {
5701179193Sjb				*flags |= CPU_DTRACE_BADALIGN;
5702179193Sjb				*illval = regs[rd];
5703179193Sjb				break;
5704179193Sjb			}
5705179193Sjb			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5706179193Sjb			break;
5707179193Sjb
5708179193Sjb		case DIF_OP_STX:
5709179193Sjb			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5710179193Sjb				*flags |= CPU_DTRACE_BADADDR;
5711179193Sjb				*illval = regs[rd];
5712179193Sjb				break;
5713179193Sjb			}
5714179193Sjb			if (regs[rd] & 7) {
5715179193Sjb				*flags |= CPU_DTRACE_BADALIGN;
5716179193Sjb				*illval = regs[rd];
5717179193Sjb				break;
5718179193Sjb			}
5719179193Sjb			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5720179193Sjb			break;
5721179193Sjb		}
5722179193Sjb	}
5723179193Sjb
5724179193Sjb	if (!(*flags & CPU_DTRACE_FAULT))
5725179193Sjb		return (rval);
5726179193Sjb
5727179193Sjb	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5728179193Sjb	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5729179193Sjb
5730179193Sjb	return (0);
5731179193Sjb}
5732179193Sjb
5733179193Sjbstatic void
5734179193Sjbdtrace_action_breakpoint(dtrace_ecb_t *ecb)
5735179193Sjb{
5736179193Sjb	dtrace_probe_t *probe = ecb->dte_probe;
5737179193Sjb	dtrace_provider_t *prov = probe->dtpr_provider;
5738179193Sjb	char c[DTRACE_FULLNAMELEN + 80], *str;
5739179193Sjb	char *msg = "dtrace: breakpoint action at probe ";
5740179193Sjb	char *ecbmsg = " (ecb ";
5741179193Sjb	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5742179193Sjb	uintptr_t val = (uintptr_t)ecb;
5743179193Sjb	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5744179193Sjb
5745179193Sjb	if (dtrace_destructive_disallow)
5746179193Sjb		return;
5747179193Sjb
5748179193Sjb	/*
5749179193Sjb	 * It's impossible to be taking action on the NULL probe.
5750179193Sjb	 */
5751179193Sjb	ASSERT(probe != NULL);
5752179193Sjb
5753179193Sjb	/*
5754179193Sjb	 * This is a poor man's (destitute man's?) sprintf():  we want to
5755179193Sjb	 * print the provider name, module name, function name and name of
5756179193Sjb	 * the probe, along with the hex address of the ECB with the breakpoint
5757179193Sjb	 * action -- all of which we must place in the character buffer by
5758179193Sjb	 * hand.
5759179193Sjb	 */
5760179193Sjb	while (*msg != '\0')
5761179193Sjb		c[i++] = *msg++;
5762179193Sjb
5763179193Sjb	for (str = prov->dtpv_name; *str != '\0'; str++)
5764179193Sjb		c[i++] = *str;
5765179193Sjb	c[i++] = ':';
5766179193Sjb
5767179193Sjb	for (str = probe->dtpr_mod; *str != '\0'; str++)
5768179193Sjb		c[i++] = *str;
5769179193Sjb	c[i++] = ':';
5770179193Sjb
5771179193Sjb	for (str = probe->dtpr_func; *str != '\0'; str++)
5772179193Sjb		c[i++] = *str;
5773179193Sjb	c[i++] = ':';
5774179193Sjb
5775179193Sjb	for (str = probe->dtpr_name; *str != '\0'; str++)
5776179193Sjb		c[i++] = *str;
5777179193Sjb
5778179193Sjb	while (*ecbmsg != '\0')
5779179193Sjb		c[i++] = *ecbmsg++;
5780179193Sjb
5781179193Sjb	while (shift >= 0) {
5782179193Sjb		mask = (uintptr_t)0xf << shift;
5783179193Sjb
5784179193Sjb		if (val >= ((uintptr_t)1 << shift))
5785179193Sjb			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5786179193Sjb		shift -= 4;
5787179193Sjb	}
5788179193Sjb
5789179193Sjb	c[i++] = ')';
5790179193Sjb	c[i] = '\0';
5791179193Sjb
5792179198Sjb#if defined(sun)
5793179193Sjb	debug_enter(c);
5794179198Sjb#else
5795179198Sjb	kdb_enter(KDB_WHY_DTRACE, "breakpoint action");
5796179198Sjb#endif
5797179193Sjb}
5798179193Sjb
5799179193Sjbstatic void
5800179193Sjbdtrace_action_panic(dtrace_ecb_t *ecb)
5801179193Sjb{
5802179193Sjb	dtrace_probe_t *probe = ecb->dte_probe;
5803179193Sjb
5804179193Sjb	/*
5805179193Sjb	 * It's impossible to be taking action on the NULL probe.
5806179193Sjb	 */
5807179193Sjb	ASSERT(probe != NULL);
5808179193Sjb
5809179193Sjb	if (dtrace_destructive_disallow)
5810179193Sjb		return;
5811179193Sjb
5812179193Sjb	if (dtrace_panicked != NULL)
5813179193Sjb		return;
5814179193Sjb
5815179193Sjb	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5816179193Sjb		return;
5817179193Sjb
5818179193Sjb	/*
5819179193Sjb	 * We won the right to panic.  (We want to be sure that only one
5820179193Sjb	 * thread calls panic() from dtrace_probe(), and that panic() is
5821179193Sjb	 * called exactly once.)
5822179193Sjb	 */
5823179193Sjb	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5824179193Sjb	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5825179193Sjb	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5826179193Sjb}
5827179193Sjb
5828179193Sjbstatic void
5829179193Sjbdtrace_action_raise(uint64_t sig)
5830179193Sjb{
5831179193Sjb	if (dtrace_destructive_disallow)
5832179193Sjb		return;
5833179193Sjb
5834179193Sjb	if (sig >= NSIG) {
5835179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5836179193Sjb		return;
5837179193Sjb	}
5838179193Sjb
5839179198Sjb#if defined(sun)
5840179193Sjb	/*
5841179193Sjb	 * raise() has a queue depth of 1 -- we ignore all subsequent
5842179193Sjb	 * invocations of the raise() action.
5843179193Sjb	 */
5844179193Sjb	if (curthread->t_dtrace_sig == 0)
5845179193Sjb		curthread->t_dtrace_sig = (uint8_t)sig;
5846179193Sjb
5847179193Sjb	curthread->t_sig_check = 1;
5848179193Sjb	aston(curthread);
5849179198Sjb#else
5850179198Sjb	struct proc *p = curproc;
5851179198Sjb	PROC_LOCK(p);
5852225617Skmacy	kern_psignal(p, sig);
5853179198Sjb	PROC_UNLOCK(p);
5854179198Sjb#endif
5855179193Sjb}
5856179193Sjb
5857179193Sjbstatic void
5858179193Sjbdtrace_action_stop(void)
5859179193Sjb{
5860179193Sjb	if (dtrace_destructive_disallow)
5861179193Sjb		return;
5862179193Sjb
5863179198Sjb#if defined(sun)
5864179193Sjb	if (!curthread->t_dtrace_stop) {
5865179193Sjb		curthread->t_dtrace_stop = 1;
5866179193Sjb		curthread->t_sig_check = 1;
5867179193Sjb		aston(curthread);
5868179193Sjb	}
5869179198Sjb#else
5870179198Sjb	struct proc *p = curproc;
5871179198Sjb	PROC_LOCK(p);
5872225617Skmacy	kern_psignal(p, SIGSTOP);
5873179198Sjb	PROC_UNLOCK(p);
5874179198Sjb#endif
5875179193Sjb}
5876179193Sjb
5877179193Sjbstatic void
5878179193Sjbdtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5879179193Sjb{
5880179193Sjb	hrtime_t now;
5881179193Sjb	volatile uint16_t *flags;
5882179198Sjb#if defined(sun)
5883179193Sjb	cpu_t *cpu = CPU;
5884179198Sjb#else
5885179198Sjb	cpu_t *cpu = &solaris_cpu[curcpu];
5886179198Sjb#endif
5887179193Sjb
5888179193Sjb	if (dtrace_destructive_disallow)
5889179193Sjb		return;
5890179193Sjb
5891179193Sjb	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5892179193Sjb
5893179193Sjb	now = dtrace_gethrtime();
5894179193Sjb
5895179193Sjb	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5896179193Sjb		/*
5897179193Sjb		 * We need to advance the mark to the current time.
5898179193Sjb		 */
5899179193Sjb		cpu->cpu_dtrace_chillmark = now;
5900179193Sjb		cpu->cpu_dtrace_chilled = 0;
5901179193Sjb	}
5902179193Sjb
5903179193Sjb	/*
5904179193Sjb	 * Now check to see if the requested chill time would take us over
5905179193Sjb	 * the maximum amount of time allowed in the chill interval.  (Or
5906179193Sjb	 * worse, if the calculation itself induces overflow.)
5907179193Sjb	 */
5908179193Sjb	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5909179193Sjb	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5910179193Sjb		*flags |= CPU_DTRACE_ILLOP;
5911179193Sjb		return;
5912179193Sjb	}
5913179193Sjb
5914179193Sjb	while (dtrace_gethrtime() - now < val)
5915179193Sjb		continue;
5916179193Sjb
5917179193Sjb	/*
5918179193Sjb	 * Normally, we assure that the value of the variable "timestamp" does
5919179193Sjb	 * not change within an ECB.  The presence of chill() represents an
5920179193Sjb	 * exception to this rule, however.
5921179193Sjb	 */
5922179193Sjb	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5923179193Sjb	cpu->cpu_dtrace_chilled += val;
5924179193Sjb}
5925179193Sjb
5926179193Sjbstatic void
5927179193Sjbdtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5928179193Sjb    uint64_t *buf, uint64_t arg)
5929179193Sjb{
5930179193Sjb	int nframes = DTRACE_USTACK_NFRAMES(arg);
5931179193Sjb	int strsize = DTRACE_USTACK_STRSIZE(arg);
5932179193Sjb	uint64_t *pcs = &buf[1], *fps;
5933179193Sjb	char *str = (char *)&pcs[nframes];
5934179193Sjb	int size, offs = 0, i, j;
5935179193Sjb	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5936179198Sjb	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
5937179193Sjb	char *sym;
5938179193Sjb
5939179193Sjb	/*
5940179193Sjb	 * Should be taking a faster path if string space has not been
5941179193Sjb	 * allocated.
5942179193Sjb	 */
5943179193Sjb	ASSERT(strsize != 0);
5944179193Sjb
5945179193Sjb	/*
5946179193Sjb	 * We will first allocate some temporary space for the frame pointers.
5947179193Sjb	 */
5948179193Sjb	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5949179193Sjb	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5950179193Sjb	    (nframes * sizeof (uint64_t));
5951179193Sjb
5952179193Sjb	if (!DTRACE_INSCRATCH(mstate, size)) {
5953179193Sjb		/*
5954179193Sjb		 * Not enough room for our frame pointers -- need to indicate
5955179193Sjb		 * that we ran out of scratch space.
5956179193Sjb		 */
5957179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5958179193Sjb		return;
5959179193Sjb	}
5960179193Sjb
5961179193Sjb	mstate->dtms_scratch_ptr += size;
5962179193Sjb	saved = mstate->dtms_scratch_ptr;
5963179193Sjb
5964179193Sjb	/*
5965179193Sjb	 * Now get a stack with both program counters and frame pointers.
5966179193Sjb	 */
5967179193Sjb	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5968179193Sjb	dtrace_getufpstack(buf, fps, nframes + 1);
5969179193Sjb	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5970179193Sjb
5971179193Sjb	/*
5972179193Sjb	 * If that faulted, we're cooked.
5973179193Sjb	 */
5974179193Sjb	if (*flags & CPU_DTRACE_FAULT)
5975179193Sjb		goto out;
5976179193Sjb
5977179193Sjb	/*
5978179193Sjb	 * Now we want to walk up the stack, calling the USTACK helper.  For
5979179193Sjb	 * each iteration, we restore the scratch pointer.
5980179193Sjb	 */
5981179193Sjb	for (i = 0; i < nframes; i++) {
5982179193Sjb		mstate->dtms_scratch_ptr = saved;
5983179193Sjb
5984179193Sjb		if (offs >= strsize)
5985179193Sjb			break;
5986179193Sjb
5987179193Sjb		sym = (char *)(uintptr_t)dtrace_helper(
5988179193Sjb		    DTRACE_HELPER_ACTION_USTACK,
5989179193Sjb		    mstate, state, pcs[i], fps[i]);
5990179193Sjb
5991179193Sjb		/*
5992179193Sjb		 * If we faulted while running the helper, we're going to
5993179193Sjb		 * clear the fault and null out the corresponding string.
5994179193Sjb		 */
5995179193Sjb		if (*flags & CPU_DTRACE_FAULT) {
5996179193Sjb			*flags &= ~CPU_DTRACE_FAULT;
5997179193Sjb			str[offs++] = '\0';
5998179193Sjb			continue;
5999179193Sjb		}
6000179193Sjb
6001179193Sjb		if (sym == NULL) {
6002179193Sjb			str[offs++] = '\0';
6003179193Sjb			continue;
6004179193Sjb		}
6005179193Sjb
6006179193Sjb		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6007179193Sjb
6008179193Sjb		/*
6009179193Sjb		 * Now copy in the string that the helper returned to us.
6010179193Sjb		 */
6011179193Sjb		for (j = 0; offs + j < strsize; j++) {
6012179193Sjb			if ((str[offs + j] = sym[j]) == '\0')
6013179193Sjb				break;
6014179193Sjb		}
6015179193Sjb
6016179193Sjb		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6017179193Sjb
6018179193Sjb		offs += j + 1;
6019179193Sjb	}
6020179193Sjb
6021179193Sjb	if (offs >= strsize) {
6022179193Sjb		/*
6023179193Sjb		 * If we didn't have room for all of the strings, we don't
6024179193Sjb		 * abort processing -- this needn't be a fatal error -- but we
6025179193Sjb		 * still want to increment a counter (dts_stkstroverflows) to
6026179193Sjb		 * allow this condition to be warned about.  (If this is from
6027179193Sjb		 * a jstack() action, it is easily tuned via jstackstrsize.)
6028179193Sjb		 */
6029179193Sjb		dtrace_error(&state->dts_stkstroverflows);
6030179193Sjb	}
6031179193Sjb
6032179193Sjb	while (offs < strsize)
6033179193Sjb		str[offs++] = '\0';
6034179193Sjb
6035179193Sjbout:
6036179193Sjb	mstate->dtms_scratch_ptr = old;
6037179193Sjb}
6038179193Sjb
6039179193Sjb/*
6040179193Sjb * If you're looking for the epicenter of DTrace, you just found it.  This
6041179193Sjb * is the function called by the provider to fire a probe -- from which all
6042179193Sjb * subsequent probe-context DTrace activity emanates.
6043179193Sjb */
6044179193Sjbvoid
6045179193Sjbdtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6046179193Sjb    uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6047179193Sjb{
6048179193Sjb	processorid_t cpuid;
6049179193Sjb	dtrace_icookie_t cookie;
6050179193Sjb	dtrace_probe_t *probe;
6051179193Sjb	dtrace_mstate_t mstate;
6052179193Sjb	dtrace_ecb_t *ecb;
6053179193Sjb	dtrace_action_t *act;
6054179193Sjb	intptr_t offs;
6055179193Sjb	size_t size;
6056179193Sjb	int vtime, onintr;
6057179193Sjb	volatile uint16_t *flags;
6058179193Sjb	hrtime_t now;
6059179193Sjb
6060235404Savg	if (panicstr != NULL)
6061235404Savg		return;
6062235404Savg
6063179198Sjb#if defined(sun)
6064179193Sjb	/*
6065179193Sjb	 * Kick out immediately if this CPU is still being born (in which case
6066179193Sjb	 * curthread will be set to -1) or the current thread can't allow
6067179193Sjb	 * probes in its current context.
6068179193Sjb	 */
6069179193Sjb	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6070179193Sjb		return;
6071179198Sjb#endif
6072179193Sjb
6073179193Sjb	cookie = dtrace_interrupt_disable();
6074179193Sjb	probe = dtrace_probes[id - 1];
6075179198Sjb	cpuid = curcpu;
6076179193Sjb	onintr = CPU_ON_INTR(CPU);
6077179193Sjb
6078179193Sjb	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6079179193Sjb	    probe->dtpr_predcache == curthread->t_predcache) {
6080179193Sjb		/*
6081179193Sjb		 * We have hit in the predicate cache; we know that
6082179193Sjb		 * this predicate would evaluate to be false.
6083179193Sjb		 */
6084179193Sjb		dtrace_interrupt_enable(cookie);
6085179193Sjb		return;
6086179193Sjb	}
6087179193Sjb
6088179198Sjb#if defined(sun)
6089179193Sjb	if (panic_quiesce) {
6090179198Sjb#else
6091179198Sjb	if (panicstr != NULL) {
6092179198Sjb#endif
6093179193Sjb		/*
6094179193Sjb		 * We don't trace anything if we're panicking.
6095179193Sjb		 */
6096179193Sjb		dtrace_interrupt_enable(cookie);
6097179193Sjb		return;
6098179193Sjb	}
6099179193Sjb
6100179193Sjb	now = dtrace_gethrtime();
6101179193Sjb	vtime = dtrace_vtime_references != 0;
6102179193Sjb
6103179193Sjb	if (vtime && curthread->t_dtrace_start)
6104179193Sjb		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6105179193Sjb
6106179193Sjb	mstate.dtms_difo = NULL;
6107179193Sjb	mstate.dtms_probe = probe;
6108179198Sjb	mstate.dtms_strtok = 0;
6109179193Sjb	mstate.dtms_arg[0] = arg0;
6110179193Sjb	mstate.dtms_arg[1] = arg1;
6111179193Sjb	mstate.dtms_arg[2] = arg2;
6112179193Sjb	mstate.dtms_arg[3] = arg3;
6113179193Sjb	mstate.dtms_arg[4] = arg4;
6114179193Sjb
6115179193Sjb	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6116179193Sjb
6117179193Sjb	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6118179193Sjb		dtrace_predicate_t *pred = ecb->dte_predicate;
6119179193Sjb		dtrace_state_t *state = ecb->dte_state;
6120179193Sjb		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6121179193Sjb		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6122179193Sjb		dtrace_vstate_t *vstate = &state->dts_vstate;
6123179193Sjb		dtrace_provider_t *prov = probe->dtpr_provider;
6124249856Spfg		uint64_t tracememsize = 0;
6125179193Sjb		int committed = 0;
6126179193Sjb		caddr_t tomax;
6127179193Sjb
6128179193Sjb		/*
6129179193Sjb		 * A little subtlety with the following (seemingly innocuous)
6130179193Sjb		 * declaration of the automatic 'val':  by looking at the
6131179193Sjb		 * code, you might think that it could be declared in the
6132179193Sjb		 * action processing loop, below.  (That is, it's only used in
6133179193Sjb		 * the action processing loop.)  However, it must be declared
6134179193Sjb		 * out of that scope because in the case of DIF expression
6135179193Sjb		 * arguments to aggregating actions, one iteration of the
6136179193Sjb		 * action loop will use the last iteration's value.
6137179193Sjb		 */
6138179193Sjb		uint64_t val = 0;
6139179193Sjb
6140179193Sjb		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6141179193Sjb		*flags &= ~CPU_DTRACE_ERROR;
6142179193Sjb
6143179193Sjb		if (prov == dtrace_provider) {
6144179193Sjb			/*
6145179193Sjb			 * If dtrace itself is the provider of this probe,
6146179193Sjb			 * we're only going to continue processing the ECB if
6147179193Sjb			 * arg0 (the dtrace_state_t) is equal to the ECB's
6148179193Sjb			 * creating state.  (This prevents disjoint consumers
6149179193Sjb			 * from seeing one another's metaprobes.)
6150179193Sjb			 */
6151179193Sjb			if (arg0 != (uint64_t)(uintptr_t)state)
6152179193Sjb				continue;
6153179193Sjb		}
6154179193Sjb
6155179193Sjb		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6156179193Sjb			/*
6157179193Sjb			 * We're not currently active.  If our provider isn't
6158179193Sjb			 * the dtrace pseudo provider, we're not interested.
6159179193Sjb			 */
6160179193Sjb			if (prov != dtrace_provider)
6161179193Sjb				continue;
6162179193Sjb
6163179193Sjb			/*
6164179193Sjb			 * Now we must further check if we are in the BEGIN
6165179193Sjb			 * probe.  If we are, we will only continue processing
6166179193Sjb			 * if we're still in WARMUP -- if one BEGIN enabling
6167179193Sjb			 * has invoked the exit() action, we don't want to
6168179193Sjb			 * evaluate subsequent BEGIN enablings.
6169179193Sjb			 */
6170179193Sjb			if (probe->dtpr_id == dtrace_probeid_begin &&
6171179193Sjb			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6172179193Sjb				ASSERT(state->dts_activity ==
6173179193Sjb				    DTRACE_ACTIVITY_DRAINING);
6174179193Sjb				continue;
6175179193Sjb			}
6176179193Sjb		}
6177179193Sjb
6178179193Sjb		if (ecb->dte_cond) {
6179179193Sjb			/*
6180179193Sjb			 * If the dte_cond bits indicate that this
6181179193Sjb			 * consumer is only allowed to see user-mode firings
6182179193Sjb			 * of this probe, call the provider's dtps_usermode()
6183179193Sjb			 * entry point to check that the probe was fired
6184179193Sjb			 * while in a user context. Skip this ECB if that's
6185179193Sjb			 * not the case.
6186179193Sjb			 */
6187179193Sjb			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
6188179193Sjb			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
6189179193Sjb			    probe->dtpr_id, probe->dtpr_arg) == 0)
6190179193Sjb				continue;
6191179193Sjb
6192179198Sjb#if defined(sun)
6193179193Sjb			/*
6194179193Sjb			 * This is more subtle than it looks. We have to be
6195179193Sjb			 * absolutely certain that CRED() isn't going to
6196179193Sjb			 * change out from under us so it's only legit to
6197179193Sjb			 * examine that structure if we're in constrained
6198179193Sjb			 * situations. Currently, the only times we'll this
6199179193Sjb			 * check is if a non-super-user has enabled the
6200179193Sjb			 * profile or syscall providers -- providers that
6201179193Sjb			 * allow visibility of all processes. For the
6202179193Sjb			 * profile case, the check above will ensure that
6203179193Sjb			 * we're examining a user context.
6204179193Sjb			 */
6205179193Sjb			if (ecb->dte_cond & DTRACE_COND_OWNER) {
6206179193Sjb				cred_t *cr;
6207179193Sjb				cred_t *s_cr =
6208179193Sjb				    ecb->dte_state->dts_cred.dcr_cred;
6209179193Sjb				proc_t *proc;
6210179193Sjb
6211179193Sjb				ASSERT(s_cr != NULL);
6212179193Sjb
6213179193Sjb				if ((cr = CRED()) == NULL ||
6214179193Sjb				    s_cr->cr_uid != cr->cr_uid ||
6215179193Sjb				    s_cr->cr_uid != cr->cr_ruid ||
6216179193Sjb				    s_cr->cr_uid != cr->cr_suid ||
6217179193Sjb				    s_cr->cr_gid != cr->cr_gid ||
6218179193Sjb				    s_cr->cr_gid != cr->cr_rgid ||
6219179193Sjb				    s_cr->cr_gid != cr->cr_sgid ||
6220179193Sjb				    (proc = ttoproc(curthread)) == NULL ||
6221179193Sjb				    (proc->p_flag & SNOCD))
6222179193Sjb					continue;
6223179193Sjb			}
6224179193Sjb
6225179193Sjb			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
6226179193Sjb				cred_t *cr;
6227179193Sjb				cred_t *s_cr =
6228179193Sjb				    ecb->dte_state->dts_cred.dcr_cred;
6229179193Sjb
6230179193Sjb				ASSERT(s_cr != NULL);
6231179193Sjb
6232179193Sjb				if ((cr = CRED()) == NULL ||
6233179193Sjb				    s_cr->cr_zone->zone_id !=
6234179193Sjb				    cr->cr_zone->zone_id)
6235179193Sjb					continue;
6236179193Sjb			}
6237179198Sjb#endif
6238179193Sjb		}
6239179193Sjb
6240179193Sjb		if (now - state->dts_alive > dtrace_deadman_timeout) {
6241179193Sjb			/*
6242179193Sjb			 * We seem to be dead.  Unless we (a) have kernel
6243256002Spfg			 * destructive permissions (b) have explicitly enabled
6244179193Sjb			 * destructive actions and (c) destructive actions have
6245179193Sjb			 * not been disabled, we're going to transition into
6246179193Sjb			 * the KILLED state, from which no further processing
6247179193Sjb			 * on this state will be performed.
6248179193Sjb			 */
6249179193Sjb			if (!dtrace_priv_kernel_destructive(state) ||
6250179193Sjb			    !state->dts_cred.dcr_destructive ||
6251179193Sjb			    dtrace_destructive_disallow) {
6252179193Sjb				void *activity = &state->dts_activity;
6253179193Sjb				dtrace_activity_t current;
6254179193Sjb
6255179193Sjb				do {
6256179193Sjb					current = state->dts_activity;
6257179193Sjb				} while (dtrace_cas32(activity, current,
6258179193Sjb				    DTRACE_ACTIVITY_KILLED) != current);
6259179193Sjb
6260179193Sjb				continue;
6261179193Sjb			}
6262179193Sjb		}
6263179193Sjb
6264179193Sjb		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6265179193Sjb		    ecb->dte_alignment, state, &mstate)) < 0)
6266179193Sjb			continue;
6267179193Sjb
6268179193Sjb		tomax = buf->dtb_tomax;
6269179193Sjb		ASSERT(tomax != NULL);
6270179193Sjb
6271256002Spfg		if (ecb->dte_size != 0) {
6272256002Spfg			dtrace_rechdr_t dtrh;
6273256002Spfg			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6274256002Spfg				mstate.dtms_timestamp = dtrace_gethrtime();
6275256002Spfg				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6276256002Spfg			}
6277256002Spfg			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6278256002Spfg			dtrh.dtrh_epid = ecb->dte_epid;
6279256002Spfg			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6280256002Spfg			    mstate.dtms_timestamp);
6281256002Spfg			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6282256002Spfg		}
6283179193Sjb
6284179193Sjb		mstate.dtms_epid = ecb->dte_epid;
6285179193Sjb		mstate.dtms_present |= DTRACE_MSTATE_EPID;
6286179193Sjb
6287179193Sjb		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6288179193Sjb			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
6289179193Sjb		else
6290179193Sjb			mstate.dtms_access = 0;
6291179193Sjb
6292179193Sjb		if (pred != NULL) {
6293179193Sjb			dtrace_difo_t *dp = pred->dtp_difo;
6294179193Sjb			int rval;
6295179193Sjb
6296179193Sjb			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6297179193Sjb
6298179193Sjb			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6299179193Sjb				dtrace_cacheid_t cid = probe->dtpr_predcache;
6300179193Sjb
6301179193Sjb				if (cid != DTRACE_CACHEIDNONE && !onintr) {
6302179193Sjb					/*
6303179193Sjb					 * Update the predicate cache...
6304179193Sjb					 */
6305179193Sjb					ASSERT(cid == pred->dtp_cacheid);
6306179193Sjb					curthread->t_predcache = cid;
6307179193Sjb				}
6308179193Sjb
6309179193Sjb				continue;
6310179193Sjb			}
6311179193Sjb		}
6312179193Sjb
6313179193Sjb		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6314179193Sjb		    act != NULL; act = act->dta_next) {
6315179193Sjb			size_t valoffs;
6316179193Sjb			dtrace_difo_t *dp;
6317179193Sjb			dtrace_recdesc_t *rec = &act->dta_rec;
6318179193Sjb
6319179193Sjb			size = rec->dtrd_size;
6320179193Sjb			valoffs = offs + rec->dtrd_offset;
6321179193Sjb
6322179193Sjb			if (DTRACEACT_ISAGG(act->dta_kind)) {
6323179193Sjb				uint64_t v = 0xbad;
6324179193Sjb				dtrace_aggregation_t *agg;
6325179193Sjb
6326179193Sjb				agg = (dtrace_aggregation_t *)act;
6327179193Sjb
6328179193Sjb				if ((dp = act->dta_difo) != NULL)
6329179193Sjb					v = dtrace_dif_emulate(dp,
6330179193Sjb					    &mstate, vstate, state);
6331179193Sjb
6332179193Sjb				if (*flags & CPU_DTRACE_ERROR)
6333179193Sjb					continue;
6334179193Sjb
6335179193Sjb				/*
6336179193Sjb				 * Note that we always pass the expression
6337179193Sjb				 * value from the previous iteration of the
6338179193Sjb				 * action loop.  This value will only be used
6339179193Sjb				 * if there is an expression argument to the
6340179193Sjb				 * aggregating action, denoted by the
6341179193Sjb				 * dtag_hasarg field.
6342179193Sjb				 */
6343179193Sjb				dtrace_aggregate(agg, buf,
6344179193Sjb				    offs, aggbuf, v, val);
6345179193Sjb				continue;
6346179193Sjb			}
6347179193Sjb
6348179193Sjb			switch (act->dta_kind) {
6349179193Sjb			case DTRACEACT_STOP:
6350179193Sjb				if (dtrace_priv_proc_destructive(state))
6351179193Sjb					dtrace_action_stop();
6352179193Sjb				continue;
6353179193Sjb
6354179193Sjb			case DTRACEACT_BREAKPOINT:
6355179193Sjb				if (dtrace_priv_kernel_destructive(state))
6356179193Sjb					dtrace_action_breakpoint(ecb);
6357179193Sjb				continue;
6358179193Sjb
6359179193Sjb			case DTRACEACT_PANIC:
6360179193Sjb				if (dtrace_priv_kernel_destructive(state))
6361179193Sjb					dtrace_action_panic(ecb);
6362179193Sjb				continue;
6363179193Sjb
6364179193Sjb			case DTRACEACT_STACK:
6365179193Sjb				if (!dtrace_priv_kernel(state))
6366179193Sjb					continue;
6367179193Sjb
6368179193Sjb				dtrace_getpcstack((pc_t *)(tomax + valoffs),
6369179193Sjb				    size / sizeof (pc_t), probe->dtpr_aframes,
6370179193Sjb				    DTRACE_ANCHORED(probe) ? NULL :
6371179193Sjb				    (uint32_t *)arg0);
6372179193Sjb				continue;
6373179193Sjb
6374179193Sjb			case DTRACEACT_JSTACK:
6375179193Sjb			case DTRACEACT_USTACK:
6376179193Sjb				if (!dtrace_priv_proc(state))
6377179193Sjb					continue;
6378179193Sjb
6379179193Sjb				/*
6380179193Sjb				 * See comment in DIF_VAR_PID.
6381179193Sjb				 */
6382179193Sjb				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6383179193Sjb				    CPU_ON_INTR(CPU)) {
6384179193Sjb					int depth = DTRACE_USTACK_NFRAMES(
6385179193Sjb					    rec->dtrd_arg) + 1;
6386179193Sjb
6387179193Sjb					dtrace_bzero((void *)(tomax + valoffs),
6388179193Sjb					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6389179193Sjb					    + depth * sizeof (uint64_t));
6390179193Sjb
6391179193Sjb					continue;
6392179193Sjb				}
6393179193Sjb
6394179193Sjb				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6395179193Sjb				    curproc->p_dtrace_helpers != NULL) {
6396179193Sjb					/*
6397179193Sjb					 * This is the slow path -- we have
6398179193Sjb					 * allocated string space, and we're
6399179193Sjb					 * getting the stack of a process that
6400179193Sjb					 * has helpers.  Call into a separate
6401179193Sjb					 * routine to perform this processing.
6402179193Sjb					 */
6403179193Sjb					dtrace_action_ustack(&mstate, state,
6404179193Sjb					    (uint64_t *)(tomax + valoffs),
6405179193Sjb					    rec->dtrd_arg);
6406179193Sjb					continue;
6407179193Sjb				}
6408179193Sjb
6409179193Sjb				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6410179193Sjb				dtrace_getupcstack((uint64_t *)
6411179193Sjb				    (tomax + valoffs),
6412179193Sjb				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6413179193Sjb				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6414179193Sjb				continue;
6415179193Sjb
6416179193Sjb			default:
6417179193Sjb				break;
6418179193Sjb			}
6419179193Sjb
6420179193Sjb			dp = act->dta_difo;
6421179193Sjb			ASSERT(dp != NULL);
6422179193Sjb
6423179193Sjb			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6424179193Sjb
6425179193Sjb			if (*flags & CPU_DTRACE_ERROR)
6426179193Sjb				continue;
6427179193Sjb
6428179193Sjb			switch (act->dta_kind) {
6429256002Spfg			case DTRACEACT_SPECULATE: {
6430256002Spfg				dtrace_rechdr_t *dtrh;
6431256002Spfg
6432179193Sjb				ASSERT(buf == &state->dts_buffer[cpuid]);
6433179193Sjb				buf = dtrace_speculation_buffer(state,
6434179193Sjb				    cpuid, val);
6435179193Sjb
6436179193Sjb				if (buf == NULL) {
6437179193Sjb					*flags |= CPU_DTRACE_DROP;
6438179193Sjb					continue;
6439179193Sjb				}
6440179193Sjb
6441179193Sjb				offs = dtrace_buffer_reserve(buf,
6442179193Sjb				    ecb->dte_needed, ecb->dte_alignment,
6443179193Sjb				    state, NULL);
6444179193Sjb
6445179193Sjb				if (offs < 0) {
6446179193Sjb					*flags |= CPU_DTRACE_DROP;
6447179193Sjb					continue;
6448179193Sjb				}
6449179193Sjb
6450179193Sjb				tomax = buf->dtb_tomax;
6451179193Sjb				ASSERT(tomax != NULL);
6452179193Sjb
6453256002Spfg				if (ecb->dte_size == 0)
6454256002Spfg					continue;
6455256002Spfg
6456256002Spfg				ASSERT3U(ecb->dte_size, >=,
6457256002Spfg				    sizeof (dtrace_rechdr_t));
6458256002Spfg				dtrh = ((void *)(tomax + offs));
6459256002Spfg				dtrh->dtrh_epid = ecb->dte_epid;
6460256002Spfg				/*
6461256002Spfg				 * When the speculation is committed, all of
6462256002Spfg				 * the records in the speculative buffer will
6463256002Spfg				 * have their timestamps set to the commit
6464256002Spfg				 * time.  Until then, it is set to a sentinel
6465256002Spfg				 * value, for debugability.
6466256002Spfg				 */
6467256002Spfg				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6468179193Sjb				continue;
6469256002Spfg			}
6470179193Sjb
6471179198Sjb			case DTRACEACT_PRINTM: {
6472179198Sjb				/* The DIF returns a 'memref'. */
6473179198Sjb				uintptr_t *memref = (uintptr_t *)(uintptr_t) val;
6474179198Sjb
6475179198Sjb				/* Get the size from the memref. */
6476179198Sjb				size = memref[1];
6477179198Sjb
6478179198Sjb				/*
6479179198Sjb				 * Check if the size exceeds the allocated
6480179198Sjb				 * buffer size.
6481179198Sjb				 */
6482179198Sjb				if (size + sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6483179198Sjb					/* Flag a drop! */
6484179198Sjb					*flags |= CPU_DTRACE_DROP;
6485179198Sjb					continue;
6486179198Sjb				}
6487179198Sjb
6488179198Sjb				/* Store the size in the buffer first. */
6489179198Sjb				DTRACE_STORE(uintptr_t, tomax,
6490179198Sjb				    valoffs, size);
6491179198Sjb
6492179198Sjb				/*
6493179198Sjb				 * Offset the buffer address to the start
6494179198Sjb				 * of the data.
6495179198Sjb				 */
6496179198Sjb				valoffs += sizeof(uintptr_t);
6497179198Sjb
6498179198Sjb				/*
6499179198Sjb				 * Reset to the memory address rather than
6500179198Sjb				 * the memref array, then let the BYREF
6501179198Sjb				 * code below do the work to store the
6502179198Sjb				 * memory data in the buffer.
6503179198Sjb				 */
6504179198Sjb				val = memref[0];
6505179198Sjb				break;
6506179198Sjb			}
6507179198Sjb
6508179198Sjb			case DTRACEACT_PRINTT: {
6509179198Sjb				/* The DIF returns a 'typeref'. */
6510179198Sjb				uintptr_t *typeref = (uintptr_t *)(uintptr_t) val;
6511179198Sjb				char c = '\0' + 1;
6512179198Sjb				size_t s;
6513179198Sjb
6514179198Sjb				/*
6515179198Sjb				 * Get the type string length and round it
6516179198Sjb				 * up so that the data that follows is
6517179198Sjb				 * aligned for easy access.
6518179198Sjb				 */
6519179198Sjb				size_t typs = strlen((char *) typeref[2]) + 1;
6520179198Sjb				typs = roundup(typs,  sizeof(uintptr_t));
6521179198Sjb
6522179198Sjb				/*
6523179198Sjb				 *Get the size from the typeref using the
6524179198Sjb				 * number of elements and the type size.
6525179198Sjb				 */
6526179198Sjb				size = typeref[1] * typeref[3];
6527179198Sjb
6528179198Sjb				/*
6529179198Sjb				 * Check if the size exceeds the allocated
6530179198Sjb				 * buffer size.
6531179198Sjb				 */
6532179198Sjb				if (size + typs + 2 * sizeof(uintptr_t) > dp->dtdo_rtype.dtdt_size) {
6533179198Sjb					/* Flag a drop! */
6534179198Sjb					*flags |= CPU_DTRACE_DROP;
6535179198Sjb
6536179198Sjb				}
6537179198Sjb
6538179198Sjb				/* Store the size in the buffer first. */
6539179198Sjb				DTRACE_STORE(uintptr_t, tomax,
6540179198Sjb				    valoffs, size);
6541179198Sjb				valoffs += sizeof(uintptr_t);
6542179198Sjb
6543179198Sjb				/* Store the type size in the buffer. */
6544179198Sjb				DTRACE_STORE(uintptr_t, tomax,
6545179198Sjb				    valoffs, typeref[3]);
6546179198Sjb				valoffs += sizeof(uintptr_t);
6547179198Sjb
6548179198Sjb				val = typeref[2];
6549179198Sjb
6550179198Sjb				for (s = 0; s < typs; s++) {
6551179198Sjb					if (c != '\0')
6552179198Sjb						c = dtrace_load8(val++);
6553179198Sjb
6554179198Sjb					DTRACE_STORE(uint8_t, tomax,
6555179198Sjb					    valoffs++, c);
6556179198Sjb				}
6557179198Sjb
6558179198Sjb				/*
6559179198Sjb				 * Reset to the memory address rather than
6560179198Sjb				 * the typeref array, then let the BYREF
6561179198Sjb				 * code below do the work to store the
6562179198Sjb				 * memory data in the buffer.
6563179198Sjb				 */
6564179198Sjb				val = typeref[0];
6565179198Sjb				break;
6566179198Sjb			}
6567179198Sjb
6568179193Sjb			case DTRACEACT_CHILL:
6569179193Sjb				if (dtrace_priv_kernel_destructive(state))
6570179193Sjb					dtrace_action_chill(&mstate, val);
6571179193Sjb				continue;
6572179193Sjb
6573179193Sjb			case DTRACEACT_RAISE:
6574179193Sjb				if (dtrace_priv_proc_destructive(state))
6575179193Sjb					dtrace_action_raise(val);
6576179193Sjb				continue;
6577179193Sjb
6578179193Sjb			case DTRACEACT_COMMIT:
6579179193Sjb				ASSERT(!committed);
6580179193Sjb
6581179193Sjb				/*
6582179193Sjb				 * We need to commit our buffer state.
6583179193Sjb				 */
6584179193Sjb				if (ecb->dte_size)
6585179193Sjb					buf->dtb_offset = offs + ecb->dte_size;
6586179193Sjb				buf = &state->dts_buffer[cpuid];
6587179193Sjb				dtrace_speculation_commit(state, cpuid, val);
6588179193Sjb				committed = 1;
6589179193Sjb				continue;
6590179193Sjb
6591179193Sjb			case DTRACEACT_DISCARD:
6592179193Sjb				dtrace_speculation_discard(state, cpuid, val);
6593179193Sjb				continue;
6594179193Sjb
6595179193Sjb			case DTRACEACT_DIFEXPR:
6596179193Sjb			case DTRACEACT_LIBACT:
6597179193Sjb			case DTRACEACT_PRINTF:
6598179193Sjb			case DTRACEACT_PRINTA:
6599179193Sjb			case DTRACEACT_SYSTEM:
6600179193Sjb			case DTRACEACT_FREOPEN:
6601249856Spfg			case DTRACEACT_TRACEMEM:
6602179193Sjb				break;
6603179193Sjb
6604249856Spfg			case DTRACEACT_TRACEMEM_DYNSIZE:
6605249856Spfg				tracememsize = val;
6606249856Spfg				break;
6607249856Spfg
6608179193Sjb			case DTRACEACT_SYM:
6609179193Sjb			case DTRACEACT_MOD:
6610179193Sjb				if (!dtrace_priv_kernel(state))
6611179193Sjb					continue;
6612179193Sjb				break;
6613179193Sjb
6614179193Sjb			case DTRACEACT_USYM:
6615179193Sjb			case DTRACEACT_UMOD:
6616179193Sjb			case DTRACEACT_UADDR: {
6617179198Sjb#if defined(sun)
6618179193Sjb				struct pid *pid = curthread->t_procp->p_pidp;
6619179198Sjb#endif
6620179193Sjb
6621179193Sjb				if (!dtrace_priv_proc(state))
6622179193Sjb					continue;
6623179193Sjb
6624179193Sjb				DTRACE_STORE(uint64_t, tomax,
6625179198Sjb#if defined(sun)
6626179193Sjb				    valoffs, (uint64_t)pid->pid_id);
6627179198Sjb#else
6628179198Sjb				    valoffs, (uint64_t) curproc->p_pid);
6629179198Sjb#endif
6630179193Sjb				DTRACE_STORE(uint64_t, tomax,
6631179193Sjb				    valoffs + sizeof (uint64_t), val);
6632179193Sjb
6633179193Sjb				continue;
6634179193Sjb			}
6635179193Sjb
6636179193Sjb			case DTRACEACT_EXIT: {
6637179193Sjb				/*
6638179193Sjb				 * For the exit action, we are going to attempt
6639179193Sjb				 * to atomically set our activity to be
6640179193Sjb				 * draining.  If this fails (either because
6641179193Sjb				 * another CPU has beat us to the exit action,
6642179193Sjb				 * or because our current activity is something
6643179193Sjb				 * other than ACTIVE or WARMUP), we will
6644179193Sjb				 * continue.  This assures that the exit action
6645179193Sjb				 * can be successfully recorded at most once
6646179193Sjb				 * when we're in the ACTIVE state.  If we're
6647179193Sjb				 * encountering the exit() action while in
6648179193Sjb				 * COOLDOWN, however, we want to honor the new
6649179193Sjb				 * status code.  (We know that we're the only
6650179193Sjb				 * thread in COOLDOWN, so there is no race.)
6651179193Sjb				 */
6652179193Sjb				void *activity = &state->dts_activity;
6653179193Sjb				dtrace_activity_t current = state->dts_activity;
6654179193Sjb
6655179193Sjb				if (current == DTRACE_ACTIVITY_COOLDOWN)
6656179193Sjb					break;
6657179193Sjb
6658179193Sjb				if (current != DTRACE_ACTIVITY_WARMUP)
6659179193Sjb					current = DTRACE_ACTIVITY_ACTIVE;
6660179193Sjb
6661179193Sjb				if (dtrace_cas32(activity, current,
6662179193Sjb				    DTRACE_ACTIVITY_DRAINING) != current) {
6663179193Sjb					*flags |= CPU_DTRACE_DROP;
6664179193Sjb					continue;
6665179193Sjb				}
6666179193Sjb
6667179193Sjb				break;
6668179193Sjb			}
6669179193Sjb
6670179193Sjb			default:
6671179193Sjb				ASSERT(0);
6672179193Sjb			}
6673179193Sjb
6674179193Sjb			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6675179193Sjb				uintptr_t end = valoffs + size;
6676179193Sjb
6677249856Spfg				if (tracememsize != 0 &&
6678249856Spfg				    valoffs + tracememsize < end) {
6679249856Spfg					end = valoffs + tracememsize;
6680249856Spfg					tracememsize = 0;
6681249856Spfg				}
6682249856Spfg
6683179193Sjb				if (!dtrace_vcanload((void *)(uintptr_t)val,
6684179193Sjb				    &dp->dtdo_rtype, &mstate, vstate))
6685179193Sjb					continue;
6686179193Sjb
6687179193Sjb				/*
6688179193Sjb				 * If this is a string, we're going to only
6689179193Sjb				 * load until we find the zero byte -- after
6690179193Sjb				 * which we'll store zero bytes.
6691179193Sjb				 */
6692179193Sjb				if (dp->dtdo_rtype.dtdt_kind ==
6693179193Sjb				    DIF_TYPE_STRING) {
6694179193Sjb					char c = '\0' + 1;
6695179193Sjb					int intuple = act->dta_intuple;
6696179193Sjb					size_t s;
6697179193Sjb
6698179193Sjb					for (s = 0; s < size; s++) {
6699179193Sjb						if (c != '\0')
6700179193Sjb							c = dtrace_load8(val++);
6701179193Sjb
6702179193Sjb						DTRACE_STORE(uint8_t, tomax,
6703179193Sjb						    valoffs++, c);
6704179193Sjb
6705179193Sjb						if (c == '\0' && intuple)
6706179193Sjb							break;
6707179193Sjb					}
6708179193Sjb
6709179193Sjb					continue;
6710179193Sjb				}
6711179193Sjb
6712179193Sjb				while (valoffs < end) {
6713179193Sjb					DTRACE_STORE(uint8_t, tomax, valoffs++,
6714179193Sjb					    dtrace_load8(val++));
6715179193Sjb				}
6716179193Sjb
6717179193Sjb				continue;
6718179193Sjb			}
6719179193Sjb
6720179193Sjb			switch (size) {
6721179193Sjb			case 0:
6722179193Sjb				break;
6723179193Sjb
6724179193Sjb			case sizeof (uint8_t):
6725179193Sjb				DTRACE_STORE(uint8_t, tomax, valoffs, val);
6726179193Sjb				break;
6727179193Sjb			case sizeof (uint16_t):
6728179193Sjb				DTRACE_STORE(uint16_t, tomax, valoffs, val);
6729179193Sjb				break;
6730179193Sjb			case sizeof (uint32_t):
6731179193Sjb				DTRACE_STORE(uint32_t, tomax, valoffs, val);
6732179193Sjb				break;
6733179193Sjb			case sizeof (uint64_t):
6734179193Sjb				DTRACE_STORE(uint64_t, tomax, valoffs, val);
6735179193Sjb				break;
6736179193Sjb			default:
6737179193Sjb				/*
6738179193Sjb				 * Any other size should have been returned by
6739179193Sjb				 * reference, not by value.
6740179193Sjb				 */
6741179193Sjb				ASSERT(0);
6742179193Sjb				break;
6743179193Sjb			}
6744179193Sjb		}
6745179193Sjb
6746179193Sjb		if (*flags & CPU_DTRACE_DROP)
6747179193Sjb			continue;
6748179193Sjb
6749179193Sjb		if (*flags & CPU_DTRACE_FAULT) {
6750179193Sjb			int ndx;
6751179193Sjb			dtrace_action_t *err;
6752179193Sjb
6753179193Sjb			buf->dtb_errors++;
6754179193Sjb
6755179193Sjb			if (probe->dtpr_id == dtrace_probeid_error) {
6756179193Sjb				/*
6757179193Sjb				 * There's nothing we can do -- we had an
6758179193Sjb				 * error on the error probe.  We bump an
6759179193Sjb				 * error counter to at least indicate that
6760179193Sjb				 * this condition happened.
6761179193Sjb				 */
6762179193Sjb				dtrace_error(&state->dts_dblerrors);
6763179193Sjb				continue;
6764179193Sjb			}
6765179193Sjb
6766179193Sjb			if (vtime) {
6767179193Sjb				/*
6768179193Sjb				 * Before recursing on dtrace_probe(), we
6769179193Sjb				 * need to explicitly clear out our start
6770179193Sjb				 * time to prevent it from being accumulated
6771179193Sjb				 * into t_dtrace_vtime.
6772179193Sjb				 */
6773179193Sjb				curthread->t_dtrace_start = 0;
6774179193Sjb			}
6775179193Sjb
6776179193Sjb			/*
6777179193Sjb			 * Iterate over the actions to figure out which action
6778179193Sjb			 * we were processing when we experienced the error.
6779179193Sjb			 * Note that act points _past_ the faulting action; if
6780179193Sjb			 * act is ecb->dte_action, the fault was in the
6781179193Sjb			 * predicate, if it's ecb->dte_action->dta_next it's
6782179193Sjb			 * in action #1, and so on.
6783179193Sjb			 */
6784179193Sjb			for (err = ecb->dte_action, ndx = 0;
6785179193Sjb			    err != act; err = err->dta_next, ndx++)
6786179193Sjb				continue;
6787179193Sjb
6788179193Sjb			dtrace_probe_error(state, ecb->dte_epid, ndx,
6789179193Sjb			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6790179193Sjb			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6791179193Sjb			    cpu_core[cpuid].cpuc_dtrace_illval);
6792179193Sjb
6793179193Sjb			continue;
6794179193Sjb		}
6795179193Sjb
6796179193Sjb		if (!committed)
6797179193Sjb			buf->dtb_offset = offs + ecb->dte_size;
6798179193Sjb	}
6799179193Sjb
6800179193Sjb	if (vtime)
6801179193Sjb		curthread->t_dtrace_start = dtrace_gethrtime();
6802179193Sjb
6803179193Sjb	dtrace_interrupt_enable(cookie);
6804179193Sjb}
6805179193Sjb
6806179193Sjb/*
6807179193Sjb * DTrace Probe Hashing Functions
6808179193Sjb *
6809179193Sjb * The functions in this section (and indeed, the functions in remaining
6810179193Sjb * sections) are not _called_ from probe context.  (Any exceptions to this are
6811179193Sjb * marked with a "Note:".)  Rather, they are called from elsewhere in the
6812179193Sjb * DTrace framework to look-up probes in, add probes to and remove probes from
6813179193Sjb * the DTrace probe hashes.  (Each probe is hashed by each element of the
6814179193Sjb * probe tuple -- allowing for fast lookups, regardless of what was
6815179193Sjb * specified.)
6816179193Sjb */
6817179193Sjbstatic uint_t
6818179198Sjbdtrace_hash_str(const char *p)
6819179193Sjb{
6820179193Sjb	unsigned int g;
6821179193Sjb	uint_t hval = 0;
6822179193Sjb
6823179193Sjb	while (*p) {
6824179193Sjb		hval = (hval << 4) + *p++;
6825179193Sjb		if ((g = (hval & 0xf0000000)) != 0)
6826179193Sjb			hval ^= g >> 24;
6827179193Sjb		hval &= ~g;
6828179193Sjb	}
6829179193Sjb	return (hval);
6830179193Sjb}
6831179193Sjb
6832179193Sjbstatic dtrace_hash_t *
6833179193Sjbdtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6834179193Sjb{
6835179193Sjb	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6836179193Sjb
6837179193Sjb	hash->dth_stroffs = stroffs;
6838179193Sjb	hash->dth_nextoffs = nextoffs;
6839179193Sjb	hash->dth_prevoffs = prevoffs;
6840179193Sjb
6841179193Sjb	hash->dth_size = 1;
6842179193Sjb	hash->dth_mask = hash->dth_size - 1;
6843179193Sjb
6844179193Sjb	hash->dth_tab = kmem_zalloc(hash->dth_size *
6845179193Sjb	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6846179193Sjb
6847179193Sjb	return (hash);
6848179193Sjb}
6849179193Sjb
6850179193Sjbstatic void
6851179193Sjbdtrace_hash_destroy(dtrace_hash_t *hash)
6852179193Sjb{
6853179193Sjb#ifdef DEBUG
6854179193Sjb	int i;
6855179193Sjb
6856179193Sjb	for (i = 0; i < hash->dth_size; i++)
6857179193Sjb		ASSERT(hash->dth_tab[i] == NULL);
6858179193Sjb#endif
6859179193Sjb
6860179193Sjb	kmem_free(hash->dth_tab,
6861179193Sjb	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6862179193Sjb	kmem_free(hash, sizeof (dtrace_hash_t));
6863179193Sjb}
6864179193Sjb
6865179193Sjbstatic void
6866179193Sjbdtrace_hash_resize(dtrace_hash_t *hash)
6867179193Sjb{
6868179193Sjb	int size = hash->dth_size, i, ndx;
6869179193Sjb	int new_size = hash->dth_size << 1;
6870179193Sjb	int new_mask = new_size - 1;
6871179193Sjb	dtrace_hashbucket_t **new_tab, *bucket, *next;
6872179193Sjb
6873179193Sjb	ASSERT((new_size & new_mask) == 0);
6874179193Sjb
6875179193Sjb	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6876179193Sjb
6877179193Sjb	for (i = 0; i < size; i++) {
6878179193Sjb		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6879179193Sjb			dtrace_probe_t *probe = bucket->dthb_chain;
6880179193Sjb
6881179193Sjb			ASSERT(probe != NULL);
6882179193Sjb			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6883179193Sjb
6884179193Sjb			next = bucket->dthb_next;
6885179193Sjb			bucket->dthb_next = new_tab[ndx];
6886179193Sjb			new_tab[ndx] = bucket;
6887179193Sjb		}
6888179193Sjb	}
6889179193Sjb
6890179193Sjb	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6891179193Sjb	hash->dth_tab = new_tab;
6892179193Sjb	hash->dth_size = new_size;
6893179193Sjb	hash->dth_mask = new_mask;
6894179193Sjb}
6895179193Sjb
6896179193Sjbstatic void
6897179193Sjbdtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6898179193Sjb{
6899179193Sjb	int hashval = DTRACE_HASHSTR(hash, new);
6900179193Sjb	int ndx = hashval & hash->dth_mask;
6901179193Sjb	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6902179193Sjb	dtrace_probe_t **nextp, **prevp;
6903179193Sjb
6904179193Sjb	for (; bucket != NULL; bucket = bucket->dthb_next) {
6905179193Sjb		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6906179193Sjb			goto add;
6907179193Sjb	}
6908179193Sjb
6909179193Sjb	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6910179193Sjb		dtrace_hash_resize(hash);
6911179193Sjb		dtrace_hash_add(hash, new);
6912179193Sjb		return;
6913179193Sjb	}
6914179193Sjb
6915179193Sjb	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6916179193Sjb	bucket->dthb_next = hash->dth_tab[ndx];
6917179193Sjb	hash->dth_tab[ndx] = bucket;
6918179193Sjb	hash->dth_nbuckets++;
6919179193Sjb
6920179193Sjbadd:
6921179193Sjb	nextp = DTRACE_HASHNEXT(hash, new);
6922179193Sjb	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6923179193Sjb	*nextp = bucket->dthb_chain;
6924179193Sjb
6925179193Sjb	if (bucket->dthb_chain != NULL) {
6926179193Sjb		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6927179193Sjb		ASSERT(*prevp == NULL);
6928179193Sjb		*prevp = new;
6929179193Sjb	}
6930179193Sjb
6931179193Sjb	bucket->dthb_chain = new;
6932179193Sjb	bucket->dthb_len++;
6933179193Sjb}
6934179193Sjb
6935179193Sjbstatic dtrace_probe_t *
6936179193Sjbdtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6937179193Sjb{
6938179193Sjb	int hashval = DTRACE_HASHSTR(hash, template);
6939179193Sjb	int ndx = hashval & hash->dth_mask;
6940179193Sjb	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6941179193Sjb
6942179193Sjb	for (; bucket != NULL; bucket = bucket->dthb_next) {
6943179193Sjb		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6944179193Sjb			return (bucket->dthb_chain);
6945179193Sjb	}
6946179193Sjb
6947179193Sjb	return (NULL);
6948179193Sjb}
6949179193Sjb
6950179193Sjbstatic int
6951179193Sjbdtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6952179193Sjb{
6953179193Sjb	int hashval = DTRACE_HASHSTR(hash, template);
6954179193Sjb	int ndx = hashval & hash->dth_mask;
6955179193Sjb	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6956179193Sjb
6957179193Sjb	for (; bucket != NULL; bucket = bucket->dthb_next) {
6958179193Sjb		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6959179193Sjb			return (bucket->dthb_len);
6960179193Sjb	}
6961179193Sjb
6962179198Sjb	return (0);
6963179193Sjb}
6964179193Sjb
6965179193Sjbstatic void
6966179193Sjbdtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6967179193Sjb{
6968179193Sjb	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6969179193Sjb	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6970179193Sjb
6971179193Sjb	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6972179193Sjb	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6973179193Sjb
6974179193Sjb	/*
6975179193Sjb	 * Find the bucket that we're removing this probe from.
6976179193Sjb	 */
6977179193Sjb	for (; bucket != NULL; bucket = bucket->dthb_next) {
6978179193Sjb		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6979179193Sjb			break;
6980179193Sjb	}
6981179193Sjb
6982179193Sjb	ASSERT(bucket != NULL);
6983179193Sjb
6984179193Sjb	if (*prevp == NULL) {
6985179193Sjb		if (*nextp == NULL) {
6986179193Sjb			/*
6987179193Sjb			 * The removed probe was the only probe on this
6988179193Sjb			 * bucket; we need to remove the bucket.
6989179193Sjb			 */
6990179193Sjb			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6991179193Sjb
6992179193Sjb			ASSERT(bucket->dthb_chain == probe);
6993179193Sjb			ASSERT(b != NULL);
6994179193Sjb
6995179193Sjb			if (b == bucket) {
6996179193Sjb				hash->dth_tab[ndx] = bucket->dthb_next;
6997179193Sjb			} else {
6998179193Sjb				while (b->dthb_next != bucket)
6999179193Sjb					b = b->dthb_next;
7000179193Sjb				b->dthb_next = bucket->dthb_next;
7001179193Sjb			}
7002179193Sjb
7003179193Sjb			ASSERT(hash->dth_nbuckets > 0);
7004179193Sjb			hash->dth_nbuckets--;
7005179193Sjb			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7006179193Sjb			return;
7007179193Sjb		}
7008179193Sjb
7009179193Sjb		bucket->dthb_chain = *nextp;
7010179193Sjb	} else {
7011179193Sjb		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7012179193Sjb	}
7013179193Sjb
7014179193Sjb	if (*nextp != NULL)
7015179193Sjb		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7016179193Sjb}
7017179193Sjb
7018179193Sjb/*
7019179193Sjb * DTrace Utility Functions
7020179193Sjb *
7021179193Sjb * These are random utility functions that are _not_ called from probe context.
7022179193Sjb */
7023179193Sjbstatic int
7024179193Sjbdtrace_badattr(const dtrace_attribute_t *a)
7025179193Sjb{
7026179193Sjb	return (a->dtat_name > DTRACE_STABILITY_MAX ||
7027179193Sjb	    a->dtat_data > DTRACE_STABILITY_MAX ||
7028179193Sjb	    a->dtat_class > DTRACE_CLASS_MAX);
7029179193Sjb}
7030179193Sjb
7031179193Sjb/*
7032179193Sjb * Return a duplicate copy of a string.  If the specified string is NULL,
7033179193Sjb * this function returns a zero-length string.
7034179193Sjb */
7035179193Sjbstatic char *
7036179193Sjbdtrace_strdup(const char *str)
7037179193Sjb{
7038179193Sjb	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7039179193Sjb
7040179193Sjb	if (str != NULL)
7041179193Sjb		(void) strcpy(new, str);
7042179193Sjb
7043179193Sjb	return (new);
7044179193Sjb}
7045179193Sjb
7046179193Sjb#define	DTRACE_ISALPHA(c)	\
7047179193Sjb	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7048179193Sjb
7049179193Sjbstatic int
7050179193Sjbdtrace_badname(const char *s)
7051179193Sjb{
7052179193Sjb	char c;
7053179193Sjb
7054179193Sjb	if (s == NULL || (c = *s++) == '\0')
7055179193Sjb		return (0);
7056179193Sjb
7057179193Sjb	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7058179193Sjb		return (1);
7059179193Sjb
7060179193Sjb	while ((c = *s++) != '\0') {
7061179193Sjb		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7062179193Sjb		    c != '-' && c != '_' && c != '.' && c != '`')
7063179193Sjb			return (1);
7064179193Sjb	}
7065179193Sjb
7066179193Sjb	return (0);
7067179193Sjb}
7068179193Sjb
7069179193Sjbstatic void
7070179193Sjbdtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7071179193Sjb{
7072179193Sjb	uint32_t priv;
7073179193Sjb
7074179198Sjb#if defined(sun)
7075179193Sjb	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7076179193Sjb		/*
7077179193Sjb		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7078179193Sjb		 */
7079179193Sjb		priv = DTRACE_PRIV_ALL;
7080179193Sjb	} else {
7081179193Sjb		*uidp = crgetuid(cr);
7082179193Sjb		*zoneidp = crgetzoneid(cr);
7083179193Sjb
7084179193Sjb		priv = 0;
7085179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7086179193Sjb			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7087179193Sjb		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7088179193Sjb			priv |= DTRACE_PRIV_USER;
7089179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7090179193Sjb			priv |= DTRACE_PRIV_PROC;
7091179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7092179193Sjb			priv |= DTRACE_PRIV_OWNER;
7093179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7094179193Sjb			priv |= DTRACE_PRIV_ZONEOWNER;
7095179193Sjb	}
7096179198Sjb#else
7097179198Sjb	priv = DTRACE_PRIV_ALL;
7098179198Sjb#endif
7099179193Sjb
7100179193Sjb	*privp = priv;
7101179193Sjb}
7102179193Sjb
7103179193Sjb#ifdef DTRACE_ERRDEBUG
7104179193Sjbstatic void
7105179193Sjbdtrace_errdebug(const char *str)
7106179193Sjb{
7107179198Sjb	int hval = dtrace_hash_str(str) % DTRACE_ERRHASHSZ;
7108179193Sjb	int occupied = 0;
7109179193Sjb
7110179193Sjb	mutex_enter(&dtrace_errlock);
7111179193Sjb	dtrace_errlast = str;
7112179193Sjb	dtrace_errthread = curthread;
7113179193Sjb
7114179193Sjb	while (occupied++ < DTRACE_ERRHASHSZ) {
7115179193Sjb		if (dtrace_errhash[hval].dter_msg == str) {
7116179193Sjb			dtrace_errhash[hval].dter_count++;
7117179193Sjb			goto out;
7118179193Sjb		}
7119179193Sjb
7120179193Sjb		if (dtrace_errhash[hval].dter_msg != NULL) {
7121179193Sjb			hval = (hval + 1) % DTRACE_ERRHASHSZ;
7122179193Sjb			continue;
7123179193Sjb		}
7124179193Sjb
7125179193Sjb		dtrace_errhash[hval].dter_msg = str;
7126179193Sjb		dtrace_errhash[hval].dter_count = 1;
7127179193Sjb		goto out;
7128179193Sjb	}
7129179193Sjb
7130179193Sjb	panic("dtrace: undersized error hash");
7131179193Sjbout:
7132179193Sjb	mutex_exit(&dtrace_errlock);
7133179193Sjb}
7134179193Sjb#endif
7135179193Sjb
7136179193Sjb/*
7137179193Sjb * DTrace Matching Functions
7138179193Sjb *
7139179193Sjb * These functions are used to match groups of probes, given some elements of
7140179193Sjb * a probe tuple, or some globbed expressions for elements of a probe tuple.
7141179193Sjb */
7142179193Sjbstatic int
7143179193Sjbdtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7144179193Sjb    zoneid_t zoneid)
7145179193Sjb{
7146179193Sjb	if (priv != DTRACE_PRIV_ALL) {
7147179193Sjb		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7148179193Sjb		uint32_t match = priv & ppriv;
7149179193Sjb
7150179193Sjb		/*
7151179193Sjb		 * No PRIV_DTRACE_* privileges...
7152179193Sjb		 */
7153179193Sjb		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7154179193Sjb		    DTRACE_PRIV_KERNEL)) == 0)
7155179193Sjb			return (0);
7156179193Sjb
7157179193Sjb		/*
7158179193Sjb		 * No matching bits, but there were bits to match...
7159179193Sjb		 */
7160179193Sjb		if (match == 0 && ppriv != 0)
7161179193Sjb			return (0);
7162179193Sjb
7163179193Sjb		/*
7164179193Sjb		 * Need to have permissions to the process, but don't...
7165179193Sjb		 */
7166179193Sjb		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7167179193Sjb		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7168179193Sjb			return (0);
7169179193Sjb		}
7170179193Sjb
7171179193Sjb		/*
7172179193Sjb		 * Need to be in the same zone unless we possess the
7173179193Sjb		 * privilege to examine all zones.
7174179193Sjb		 */
7175179193Sjb		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7176179193Sjb		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7177179193Sjb			return (0);
7178179193Sjb		}
7179179193Sjb	}
7180179193Sjb
7181179193Sjb	return (1);
7182179193Sjb}
7183179193Sjb
7184179193Sjb/*
7185179193Sjb * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7186179193Sjb * consists of input pattern strings and an ops-vector to evaluate them.
7187179193Sjb * This function returns >0 for match, 0 for no match, and <0 for error.
7188179193Sjb */
7189179193Sjbstatic int
7190179193Sjbdtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7191179193Sjb    uint32_t priv, uid_t uid, zoneid_t zoneid)
7192179193Sjb{
7193179193Sjb	dtrace_provider_t *pvp = prp->dtpr_provider;
7194179193Sjb	int rv;
7195179193Sjb
7196179193Sjb	if (pvp->dtpv_defunct)
7197179193Sjb		return (0);
7198179193Sjb
7199179193Sjb	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7200179193Sjb		return (rv);
7201179193Sjb
7202179193Sjb	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7203179193Sjb		return (rv);
7204179193Sjb
7205179193Sjb	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7206179193Sjb		return (rv);
7207179193Sjb
7208179193Sjb	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7209179193Sjb		return (rv);
7210179193Sjb
7211179193Sjb	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7212179193Sjb		return (0);
7213179193Sjb
7214179193Sjb	return (rv);
7215179193Sjb}
7216179193Sjb
7217179193Sjb/*
7218179193Sjb * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7219179193Sjb * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7220179193Sjb * libc's version, the kernel version only applies to 8-bit ASCII strings.
7221179193Sjb * In addition, all of the recursion cases except for '*' matching have been
7222179193Sjb * unwound.  For '*', we still implement recursive evaluation, but a depth
7223179193Sjb * counter is maintained and matching is aborted if we recurse too deep.
7224179193Sjb * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7225179193Sjb */
7226179193Sjbstatic int
7227179193Sjbdtrace_match_glob(const char *s, const char *p, int depth)
7228179193Sjb{
7229179193Sjb	const char *olds;
7230179193Sjb	char s1, c;
7231179193Sjb	int gs;
7232179193Sjb
7233179193Sjb	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7234179193Sjb		return (-1);
7235179193Sjb
7236179193Sjb	if (s == NULL)
7237179193Sjb		s = ""; /* treat NULL as empty string */
7238179193Sjb
7239179193Sjbtop:
7240179193Sjb	olds = s;
7241179193Sjb	s1 = *s++;
7242179193Sjb
7243179193Sjb	if (p == NULL)
7244179193Sjb		return (0);
7245179193Sjb
7246179193Sjb	if ((c = *p++) == '\0')
7247179193Sjb		return (s1 == '\0');
7248179193Sjb
7249179193Sjb	switch (c) {
7250179193Sjb	case '[': {
7251179193Sjb		int ok = 0, notflag = 0;
7252179193Sjb		char lc = '\0';
7253179193Sjb
7254179193Sjb		if (s1 == '\0')
7255179193Sjb			return (0);
7256179193Sjb
7257179193Sjb		if (*p == '!') {
7258179193Sjb			notflag = 1;
7259179193Sjb			p++;
7260179193Sjb		}
7261179193Sjb
7262179193Sjb		if ((c = *p++) == '\0')
7263179193Sjb			return (0);
7264179193Sjb
7265179193Sjb		do {
7266179193Sjb			if (c == '-' && lc != '\0' && *p != ']') {
7267179193Sjb				if ((c = *p++) == '\0')
7268179193Sjb					return (0);
7269179193Sjb				if (c == '\\' && (c = *p++) == '\0')
7270179193Sjb					return (0);
7271179193Sjb
7272179193Sjb				if (notflag) {
7273179193Sjb					if (s1 < lc || s1 > c)
7274179193Sjb						ok++;
7275179193Sjb					else
7276179193Sjb						return (0);
7277179193Sjb				} else if (lc <= s1 && s1 <= c)
7278179193Sjb					ok++;
7279179193Sjb
7280179193Sjb			} else if (c == '\\' && (c = *p++) == '\0')
7281179193Sjb				return (0);
7282179193Sjb
7283179193Sjb			lc = c; /* save left-hand 'c' for next iteration */
7284179193Sjb
7285179193Sjb			if (notflag) {
7286179193Sjb				if (s1 != c)
7287179193Sjb					ok++;
7288179193Sjb				else
7289179193Sjb					return (0);
7290179193Sjb			} else if (s1 == c)
7291179193Sjb				ok++;
7292179193Sjb
7293179193Sjb			if ((c = *p++) == '\0')
7294179193Sjb				return (0);
7295179193Sjb
7296179193Sjb		} while (c != ']');
7297179193Sjb
7298179193Sjb		if (ok)
7299179193Sjb			goto top;
7300179193Sjb
7301179193Sjb		return (0);
7302179193Sjb	}
7303179193Sjb
7304179193Sjb	case '\\':
7305179193Sjb		if ((c = *p++) == '\0')
7306179193Sjb			return (0);
7307179193Sjb		/*FALLTHRU*/
7308179193Sjb
7309179193Sjb	default:
7310179193Sjb		if (c != s1)
7311179193Sjb			return (0);
7312179193Sjb		/*FALLTHRU*/
7313179193Sjb
7314179193Sjb	case '?':
7315179193Sjb		if (s1 != '\0')
7316179193Sjb			goto top;
7317179193Sjb		return (0);
7318179193Sjb
7319179193Sjb	case '*':
7320179193Sjb		while (*p == '*')
7321179193Sjb			p++; /* consecutive *'s are identical to a single one */
7322179193Sjb
7323179193Sjb		if (*p == '\0')
7324179193Sjb			return (1);
7325179193Sjb
7326179193Sjb		for (s = olds; *s != '\0'; s++) {
7327179193Sjb			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7328179193Sjb				return (gs);
7329179193Sjb		}
7330179193Sjb
7331179193Sjb		return (0);
7332179193Sjb	}
7333179193Sjb}
7334179193Sjb
7335179193Sjb/*ARGSUSED*/
7336179193Sjbstatic int
7337179193Sjbdtrace_match_string(const char *s, const char *p, int depth)
7338179193Sjb{
7339179193Sjb	return (s != NULL && strcmp(s, p) == 0);
7340179193Sjb}
7341179193Sjb
7342179193Sjb/*ARGSUSED*/
7343179193Sjbstatic int
7344179193Sjbdtrace_match_nul(const char *s, const char *p, int depth)
7345179193Sjb{
7346179193Sjb	return (1); /* always match the empty pattern */
7347179193Sjb}
7348179193Sjb
7349179193Sjb/*ARGSUSED*/
7350179193Sjbstatic int
7351179193Sjbdtrace_match_nonzero(const char *s, const char *p, int depth)
7352179193Sjb{
7353179193Sjb	return (s != NULL && s[0] != '\0');
7354179193Sjb}
7355179193Sjb
7356179193Sjbstatic int
7357179193Sjbdtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7358179193Sjb    zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7359179193Sjb{
7360179193Sjb	dtrace_probe_t template, *probe;
7361179193Sjb	dtrace_hash_t *hash = NULL;
7362179193Sjb	int len, best = INT_MAX, nmatched = 0;
7363179193Sjb	dtrace_id_t i;
7364179193Sjb
7365179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
7366179193Sjb
7367179193Sjb	/*
7368179193Sjb	 * If the probe ID is specified in the key, just lookup by ID and
7369179193Sjb	 * invoke the match callback once if a matching probe is found.
7370179193Sjb	 */
7371179193Sjb	if (pkp->dtpk_id != DTRACE_IDNONE) {
7372179193Sjb		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7373179193Sjb		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7374179193Sjb			(void) (*matched)(probe, arg);
7375179193Sjb			nmatched++;
7376179193Sjb		}
7377179193Sjb		return (nmatched);
7378179193Sjb	}
7379179193Sjb
7380179193Sjb	template.dtpr_mod = (char *)pkp->dtpk_mod;
7381179193Sjb	template.dtpr_func = (char *)pkp->dtpk_func;
7382179193Sjb	template.dtpr_name = (char *)pkp->dtpk_name;
7383179193Sjb
7384179193Sjb	/*
7385179193Sjb	 * We want to find the most distinct of the module name, function
7386179193Sjb	 * name, and name.  So for each one that is not a glob pattern or
7387179193Sjb	 * empty string, we perform a lookup in the corresponding hash and
7388179193Sjb	 * use the hash table with the fewest collisions to do our search.
7389179193Sjb	 */
7390179193Sjb	if (pkp->dtpk_mmatch == &dtrace_match_string &&
7391179193Sjb	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7392179193Sjb		best = len;
7393179193Sjb		hash = dtrace_bymod;
7394179193Sjb	}
7395179193Sjb
7396179193Sjb	if (pkp->dtpk_fmatch == &dtrace_match_string &&
7397179193Sjb	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7398179193Sjb		best = len;
7399179193Sjb		hash = dtrace_byfunc;
7400179193Sjb	}
7401179193Sjb
7402179193Sjb	if (pkp->dtpk_nmatch == &dtrace_match_string &&
7403179193Sjb	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7404179193Sjb		best = len;
7405179193Sjb		hash = dtrace_byname;
7406179193Sjb	}
7407179193Sjb
7408179193Sjb	/*
7409179193Sjb	 * If we did not select a hash table, iterate over every probe and
7410179193Sjb	 * invoke our callback for each one that matches our input probe key.
7411179193Sjb	 */
7412179193Sjb	if (hash == NULL) {
7413179193Sjb		for (i = 0; i < dtrace_nprobes; i++) {
7414179193Sjb			if ((probe = dtrace_probes[i]) == NULL ||
7415179193Sjb			    dtrace_match_probe(probe, pkp, priv, uid,
7416179193Sjb			    zoneid) <= 0)
7417179193Sjb				continue;
7418179193Sjb
7419179193Sjb			nmatched++;
7420179193Sjb
7421179193Sjb			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7422179193Sjb				break;
7423179193Sjb		}
7424179193Sjb
7425179193Sjb		return (nmatched);
7426179193Sjb	}
7427179193Sjb
7428179193Sjb	/*
7429179193Sjb	 * If we selected a hash table, iterate over each probe of the same key
7430179193Sjb	 * name and invoke the callback for every probe that matches the other
7431179193Sjb	 * attributes of our input probe key.
7432179193Sjb	 */
7433179193Sjb	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7434179193Sjb	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
7435179193Sjb
7436179193Sjb		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7437179193Sjb			continue;
7438179193Sjb
7439179193Sjb		nmatched++;
7440179193Sjb
7441179193Sjb		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
7442179193Sjb			break;
7443179193Sjb	}
7444179193Sjb
7445179193Sjb	return (nmatched);
7446179193Sjb}
7447179193Sjb
7448179193Sjb/*
7449179193Sjb * Return the function pointer dtrace_probecmp() should use to compare the
7450179193Sjb * specified pattern with a string.  For NULL or empty patterns, we select
7451179193Sjb * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7452179193Sjb * For non-empty non-glob strings, we use dtrace_match_string().
7453179193Sjb */
7454179193Sjbstatic dtrace_probekey_f *
7455179193Sjbdtrace_probekey_func(const char *p)
7456179193Sjb{
7457179193Sjb	char c;
7458179193Sjb
7459179193Sjb	if (p == NULL || *p == '\0')
7460179193Sjb		return (&dtrace_match_nul);
7461179193Sjb
7462179193Sjb	while ((c = *p++) != '\0') {
7463179193Sjb		if (c == '[' || c == '?' || c == '*' || c == '\\')
7464179193Sjb			return (&dtrace_match_glob);
7465179193Sjb	}
7466179193Sjb
7467179193Sjb	return (&dtrace_match_string);
7468179193Sjb}
7469179193Sjb
7470179193Sjb/*
7471179193Sjb * Build a probe comparison key for use with dtrace_match_probe() from the
7472179193Sjb * given probe description.  By convention, a null key only matches anchored
7473179193Sjb * probes: if each field is the empty string, reset dtpk_fmatch to
7474179193Sjb * dtrace_match_nonzero().
7475179193Sjb */
7476179193Sjbstatic void
7477179198Sjbdtrace_probekey(dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7478179193Sjb{
7479179193Sjb	pkp->dtpk_prov = pdp->dtpd_provider;
7480179193Sjb	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7481179193Sjb
7482179193Sjb	pkp->dtpk_mod = pdp->dtpd_mod;
7483179193Sjb	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7484179193Sjb
7485179193Sjb	pkp->dtpk_func = pdp->dtpd_func;
7486179193Sjb	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7487179193Sjb
7488179193Sjb	pkp->dtpk_name = pdp->dtpd_name;
7489179193Sjb	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7490179193Sjb
7491179193Sjb	pkp->dtpk_id = pdp->dtpd_id;
7492179193Sjb
7493179193Sjb	if (pkp->dtpk_id == DTRACE_IDNONE &&
7494179193Sjb	    pkp->dtpk_pmatch == &dtrace_match_nul &&
7495179193Sjb	    pkp->dtpk_mmatch == &dtrace_match_nul &&
7496179193Sjb	    pkp->dtpk_fmatch == &dtrace_match_nul &&
7497179193Sjb	    pkp->dtpk_nmatch == &dtrace_match_nul)
7498179193Sjb		pkp->dtpk_fmatch = &dtrace_match_nonzero;
7499179193Sjb}
7500179193Sjb
7501179193Sjb/*
7502179193Sjb * DTrace Provider-to-Framework API Functions
7503179193Sjb *
7504179193Sjb * These functions implement much of the Provider-to-Framework API, as
7505179193Sjb * described in <sys/dtrace.h>.  The parts of the API not in this section are
7506179193Sjb * the functions in the API for probe management (found below), and
7507179193Sjb * dtrace_probe() itself (found above).
7508179193Sjb */
7509179193Sjb
7510179193Sjb/*
7511179193Sjb * Register the calling provider with the DTrace framework.  This should
7512179193Sjb * generally be called by DTrace providers in their attach(9E) entry point.
7513179193Sjb */
7514179193Sjbint
7515179193Sjbdtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7516179193Sjb    cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7517179193Sjb{
7518179193Sjb	dtrace_provider_t *provider;
7519179193Sjb
7520179193Sjb	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7521179193Sjb		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7522179193Sjb		    "arguments", name ? name : "<NULL>");
7523179193Sjb		return (EINVAL);
7524179193Sjb	}
7525179193Sjb
7526179193Sjb	if (name[0] == '\0' || dtrace_badname(name)) {
7527179193Sjb		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7528179193Sjb		    "provider name", name);
7529179193Sjb		return (EINVAL);
7530179193Sjb	}
7531179193Sjb
7532179193Sjb	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7533179193Sjb	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7534179193Sjb	    pops->dtps_destroy == NULL ||
7535179193Sjb	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7536179193Sjb		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7537179193Sjb		    "provider ops", name);
7538179193Sjb		return (EINVAL);
7539179193Sjb	}
7540179193Sjb
7541179193Sjb	if (dtrace_badattr(&pap->dtpa_provider) ||
7542179193Sjb	    dtrace_badattr(&pap->dtpa_mod) ||
7543179193Sjb	    dtrace_badattr(&pap->dtpa_func) ||
7544179193Sjb	    dtrace_badattr(&pap->dtpa_name) ||
7545179193Sjb	    dtrace_badattr(&pap->dtpa_args)) {
7546179193Sjb		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7547179193Sjb		    "provider attributes", name);
7548179193Sjb		return (EINVAL);
7549179193Sjb	}
7550179193Sjb
7551179193Sjb	if (priv & ~DTRACE_PRIV_ALL) {
7552179193Sjb		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7553179193Sjb		    "privilege attributes", name);
7554179193Sjb		return (EINVAL);
7555179193Sjb	}
7556179193Sjb
7557179193Sjb	if ((priv & DTRACE_PRIV_KERNEL) &&
7558179193Sjb	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7559179193Sjb	    pops->dtps_usermode == NULL) {
7560179193Sjb		cmn_err(CE_WARN, "failed to register provider '%s': need "
7561179193Sjb		    "dtps_usermode() op for given privilege attributes", name);
7562179193Sjb		return (EINVAL);
7563179193Sjb	}
7564179193Sjb
7565179193Sjb	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7566179193Sjb	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7567179193Sjb	(void) strcpy(provider->dtpv_name, name);
7568179193Sjb
7569179193Sjb	provider->dtpv_attr = *pap;
7570179193Sjb	provider->dtpv_priv.dtpp_flags = priv;
7571179193Sjb	if (cr != NULL) {
7572179193Sjb		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7573179193Sjb		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7574179193Sjb	}
7575179193Sjb	provider->dtpv_pops = *pops;
7576179193Sjb
7577179193Sjb	if (pops->dtps_provide == NULL) {
7578179193Sjb		ASSERT(pops->dtps_provide_module != NULL);
7579179193Sjb		provider->dtpv_pops.dtps_provide =
7580179198Sjb		    (void (*)(void *, dtrace_probedesc_t *))dtrace_nullop;
7581179193Sjb	}
7582179193Sjb
7583179193Sjb	if (pops->dtps_provide_module == NULL) {
7584179193Sjb		ASSERT(pops->dtps_provide != NULL);
7585179193Sjb		provider->dtpv_pops.dtps_provide_module =
7586179198Sjb		    (void (*)(void *, modctl_t *))dtrace_nullop;
7587179193Sjb	}
7588179193Sjb
7589179193Sjb	if (pops->dtps_suspend == NULL) {
7590179193Sjb		ASSERT(pops->dtps_resume == NULL);
7591179193Sjb		provider->dtpv_pops.dtps_suspend =
7592179193Sjb		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7593179193Sjb		provider->dtpv_pops.dtps_resume =
7594179193Sjb		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7595179193Sjb	}
7596179193Sjb
7597179193Sjb	provider->dtpv_arg = arg;
7598179193Sjb	*idp = (dtrace_provider_id_t)provider;
7599179193Sjb
7600179193Sjb	if (pops == &dtrace_provider_ops) {
7601179193Sjb		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7602179193Sjb		ASSERT(MUTEX_HELD(&dtrace_lock));
7603179193Sjb		ASSERT(dtrace_anon.dta_enabling == NULL);
7604179193Sjb
7605179193Sjb		/*
7606179193Sjb		 * We make sure that the DTrace provider is at the head of
7607179193Sjb		 * the provider chain.
7608179193Sjb		 */
7609179193Sjb		provider->dtpv_next = dtrace_provider;
7610179193Sjb		dtrace_provider = provider;
7611179193Sjb		return (0);
7612179193Sjb	}
7613179193Sjb
7614179193Sjb	mutex_enter(&dtrace_provider_lock);
7615179193Sjb	mutex_enter(&dtrace_lock);
7616179193Sjb
7617179193Sjb	/*
7618179193Sjb	 * If there is at least one provider registered, we'll add this
7619179193Sjb	 * provider after the first provider.
7620179193Sjb	 */
7621179193Sjb	if (dtrace_provider != NULL) {
7622179193Sjb		provider->dtpv_next = dtrace_provider->dtpv_next;
7623179193Sjb		dtrace_provider->dtpv_next = provider;
7624179193Sjb	} else {
7625179193Sjb		dtrace_provider = provider;
7626179193Sjb	}
7627179193Sjb
7628179193Sjb	if (dtrace_retained != NULL) {
7629179193Sjb		dtrace_enabling_provide(provider);
7630179193Sjb
7631179193Sjb		/*
7632179193Sjb		 * Now we need to call dtrace_enabling_matchall() -- which
7633179193Sjb		 * will acquire cpu_lock and dtrace_lock.  We therefore need
7634179193Sjb		 * to drop all of our locks before calling into it...
7635179193Sjb		 */
7636179193Sjb		mutex_exit(&dtrace_lock);
7637179193Sjb		mutex_exit(&dtrace_provider_lock);
7638179193Sjb		dtrace_enabling_matchall();
7639179193Sjb
7640179193Sjb		return (0);
7641179193Sjb	}
7642179193Sjb
7643179193Sjb	mutex_exit(&dtrace_lock);
7644179193Sjb	mutex_exit(&dtrace_provider_lock);
7645179193Sjb
7646179193Sjb	return (0);
7647179193Sjb}
7648179193Sjb
7649179193Sjb/*
7650179193Sjb * Unregister the specified provider from the DTrace framework.  This should
7651179193Sjb * generally be called by DTrace providers in their detach(9E) entry point.
7652179193Sjb */
7653179193Sjbint
7654179193Sjbdtrace_unregister(dtrace_provider_id_t id)
7655179193Sjb{
7656179193Sjb	dtrace_provider_t *old = (dtrace_provider_t *)id;
7657179193Sjb	dtrace_provider_t *prev = NULL;
7658250484Spfg	int i, self = 0, noreap = 0;
7659179193Sjb	dtrace_probe_t *probe, *first = NULL;
7660179193Sjb
7661179193Sjb	if (old->dtpv_pops.dtps_enable ==
7662179193Sjb	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
7663179193Sjb		/*
7664179193Sjb		 * If DTrace itself is the provider, we're called with locks
7665179193Sjb		 * already held.
7666179193Sjb		 */
7667179193Sjb		ASSERT(old == dtrace_provider);
7668179198Sjb#if defined(sun)
7669179193Sjb		ASSERT(dtrace_devi != NULL);
7670179198Sjb#endif
7671179193Sjb		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7672179193Sjb		ASSERT(MUTEX_HELD(&dtrace_lock));
7673179193Sjb		self = 1;
7674179193Sjb
7675179193Sjb		if (dtrace_provider->dtpv_next != NULL) {
7676179193Sjb			/*
7677179193Sjb			 * There's another provider here; return failure.
7678179193Sjb			 */
7679179193Sjb			return (EBUSY);
7680179193Sjb		}
7681179193Sjb	} else {
7682179193Sjb		mutex_enter(&dtrace_provider_lock);
7683262052Savg#if defined(sun)
7684179193Sjb		mutex_enter(&mod_lock);
7685262052Savg#endif
7686179193Sjb		mutex_enter(&dtrace_lock);
7687179193Sjb	}
7688179193Sjb
7689179193Sjb	/*
7690179193Sjb	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7691179193Sjb	 * probes, we refuse to let providers slither away, unless this
7692179193Sjb	 * provider has already been explicitly invalidated.
7693179193Sjb	 */
7694179193Sjb	if (!old->dtpv_defunct &&
7695179193Sjb	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7696179193Sjb	    dtrace_anon.dta_state->dts_necbs > 0))) {
7697179193Sjb		if (!self) {
7698179193Sjb			mutex_exit(&dtrace_lock);
7699262052Savg#if defined(sun)
7700179193Sjb			mutex_exit(&mod_lock);
7701262052Savg#endif
7702179193Sjb			mutex_exit(&dtrace_provider_lock);
7703179193Sjb		}
7704179193Sjb		return (EBUSY);
7705179193Sjb	}
7706179193Sjb
7707179193Sjb	/*
7708179193Sjb	 * Attempt to destroy the probes associated with this provider.
7709179193Sjb	 */
7710179193Sjb	for (i = 0; i < dtrace_nprobes; i++) {
7711179193Sjb		if ((probe = dtrace_probes[i]) == NULL)
7712179193Sjb			continue;
7713179193Sjb
7714179193Sjb		if (probe->dtpr_provider != old)
7715179193Sjb			continue;
7716179193Sjb
7717179193Sjb		if (probe->dtpr_ecb == NULL)
7718179193Sjb			continue;
7719179193Sjb
7720179193Sjb		/*
7721250484Spfg		 * If we are trying to unregister a defunct provider, and the
7722250484Spfg		 * provider was made defunct within the interval dictated by
7723250484Spfg		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
7724250484Spfg		 * attempt to reap our enablings.  To denote that the provider
7725250484Spfg		 * should reattempt to unregister itself at some point in the
7726250484Spfg		 * future, we will return a differentiable error code (EAGAIN
7727250484Spfg		 * instead of EBUSY) in this case.
7728179193Sjb		 */
7729250484Spfg		if (dtrace_gethrtime() - old->dtpv_defunct >
7730250484Spfg		    dtrace_unregister_defunct_reap)
7731250484Spfg			noreap = 1;
7732250484Spfg
7733179193Sjb		if (!self) {
7734179193Sjb			mutex_exit(&dtrace_lock);
7735262052Savg#if defined(sun)
7736179193Sjb			mutex_exit(&mod_lock);
7737262052Savg#endif
7738179193Sjb			mutex_exit(&dtrace_provider_lock);
7739179193Sjb		}
7740250484Spfg
7741250484Spfg		if (noreap)
7742250484Spfg			return (EBUSY);
7743250484Spfg
7744250484Spfg		(void) taskq_dispatch(dtrace_taskq,
7745250484Spfg		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
7746250484Spfg
7747250484Spfg		return (EAGAIN);
7748179193Sjb	}
7749179193Sjb
7750179193Sjb	/*
7751179193Sjb	 * All of the probes for this provider are disabled; we can safely
7752179193Sjb	 * remove all of them from their hash chains and from the probe array.
7753179193Sjb	 */
7754179193Sjb	for (i = 0; i < dtrace_nprobes; i++) {
7755179193Sjb		if ((probe = dtrace_probes[i]) == NULL)
7756179193Sjb			continue;
7757179193Sjb
7758179193Sjb		if (probe->dtpr_provider != old)
7759179193Sjb			continue;
7760179193Sjb
7761179193Sjb		dtrace_probes[i] = NULL;
7762179193Sjb
7763179193Sjb		dtrace_hash_remove(dtrace_bymod, probe);
7764179193Sjb		dtrace_hash_remove(dtrace_byfunc, probe);
7765179193Sjb		dtrace_hash_remove(dtrace_byname, probe);
7766179193Sjb
7767179193Sjb		if (first == NULL) {
7768179193Sjb			first = probe;
7769179193Sjb			probe->dtpr_nextmod = NULL;
7770179193Sjb		} else {
7771179193Sjb			probe->dtpr_nextmod = first;
7772179193Sjb			first = probe;
7773179193Sjb		}
7774179193Sjb	}
7775179193Sjb
7776179193Sjb	/*
7777179193Sjb	 * The provider's probes have been removed from the hash chains and
7778179193Sjb	 * from the probe array.  Now issue a dtrace_sync() to be sure that
7779179193Sjb	 * everyone has cleared out from any probe array processing.
7780179193Sjb	 */
7781179193Sjb	dtrace_sync();
7782179193Sjb
7783179193Sjb	for (probe = first; probe != NULL; probe = first) {
7784179193Sjb		first = probe->dtpr_nextmod;
7785179193Sjb
7786179193Sjb		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7787179193Sjb		    probe->dtpr_arg);
7788179193Sjb		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7789179193Sjb		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7790179193Sjb		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7791179198Sjb#if defined(sun)
7792179193Sjb		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7793179198Sjb#else
7794179198Sjb		free_unr(dtrace_arena, probe->dtpr_id);
7795179198Sjb#endif
7796179193Sjb		kmem_free(probe, sizeof (dtrace_probe_t));
7797179193Sjb	}
7798179193Sjb
7799179193Sjb	if ((prev = dtrace_provider) == old) {
7800179198Sjb#if defined(sun)
7801179193Sjb		ASSERT(self || dtrace_devi == NULL);
7802179193Sjb		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7803179198Sjb#endif
7804179193Sjb		dtrace_provider = old->dtpv_next;
7805179193Sjb	} else {
7806179193Sjb		while (prev != NULL && prev->dtpv_next != old)
7807179193Sjb			prev = prev->dtpv_next;
7808179193Sjb
7809179193Sjb		if (prev == NULL) {
7810179193Sjb			panic("attempt to unregister non-existent "
7811179193Sjb			    "dtrace provider %p\n", (void *)id);
7812179193Sjb		}
7813179193Sjb
7814179193Sjb		prev->dtpv_next = old->dtpv_next;
7815179193Sjb	}
7816179193Sjb
7817179193Sjb	if (!self) {
7818179193Sjb		mutex_exit(&dtrace_lock);
7819262052Savg#if defined(sun)
7820179193Sjb		mutex_exit(&mod_lock);
7821262052Savg#endif
7822179193Sjb		mutex_exit(&dtrace_provider_lock);
7823179193Sjb	}
7824179193Sjb
7825179193Sjb	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7826179193Sjb	kmem_free(old, sizeof (dtrace_provider_t));
7827179193Sjb
7828179193Sjb	return (0);
7829179193Sjb}
7830179193Sjb
7831179193Sjb/*
7832179193Sjb * Invalidate the specified provider.  All subsequent probe lookups for the
7833179193Sjb * specified provider will fail, but its probes will not be removed.
7834179193Sjb */
7835179193Sjbvoid
7836179193Sjbdtrace_invalidate(dtrace_provider_id_t id)
7837179193Sjb{
7838179193Sjb	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7839179193Sjb
7840179193Sjb	ASSERT(pvp->dtpv_pops.dtps_enable !=
7841179193Sjb	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7842179193Sjb
7843179193Sjb	mutex_enter(&dtrace_provider_lock);
7844179193Sjb	mutex_enter(&dtrace_lock);
7845179193Sjb
7846250484Spfg	pvp->dtpv_defunct = dtrace_gethrtime();
7847179193Sjb
7848179193Sjb	mutex_exit(&dtrace_lock);
7849179193Sjb	mutex_exit(&dtrace_provider_lock);
7850179193Sjb}
7851179193Sjb
7852179193Sjb/*
7853179193Sjb * Indicate whether or not DTrace has attached.
7854179193Sjb */
7855179193Sjbint
7856179193Sjbdtrace_attached(void)
7857179193Sjb{
7858179193Sjb	/*
7859179193Sjb	 * dtrace_provider will be non-NULL iff the DTrace driver has
7860179193Sjb	 * attached.  (It's non-NULL because DTrace is always itself a
7861179193Sjb	 * provider.)
7862179193Sjb	 */
7863179193Sjb	return (dtrace_provider != NULL);
7864179193Sjb}
7865179193Sjb
7866179193Sjb/*
7867179193Sjb * Remove all the unenabled probes for the given provider.  This function is
7868179193Sjb * not unlike dtrace_unregister(), except that it doesn't remove the provider
7869179193Sjb * -- just as many of its associated probes as it can.
7870179193Sjb */
7871179193Sjbint
7872179193Sjbdtrace_condense(dtrace_provider_id_t id)
7873179193Sjb{
7874179193Sjb	dtrace_provider_t *prov = (dtrace_provider_t *)id;
7875179193Sjb	int i;
7876179193Sjb	dtrace_probe_t *probe;
7877179193Sjb
7878179193Sjb	/*
7879179193Sjb	 * Make sure this isn't the dtrace provider itself.
7880179193Sjb	 */
7881179193Sjb	ASSERT(prov->dtpv_pops.dtps_enable !=
7882179193Sjb	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7883179193Sjb
7884179193Sjb	mutex_enter(&dtrace_provider_lock);
7885179193Sjb	mutex_enter(&dtrace_lock);
7886179193Sjb
7887179193Sjb	/*
7888179193Sjb	 * Attempt to destroy the probes associated with this provider.
7889179193Sjb	 */
7890179193Sjb	for (i = 0; i < dtrace_nprobes; i++) {
7891179193Sjb		if ((probe = dtrace_probes[i]) == NULL)
7892179193Sjb			continue;
7893179193Sjb
7894179193Sjb		if (probe->dtpr_provider != prov)
7895179193Sjb			continue;
7896179193Sjb
7897179193Sjb		if (probe->dtpr_ecb != NULL)
7898179193Sjb			continue;
7899179193Sjb
7900179193Sjb		dtrace_probes[i] = NULL;
7901179193Sjb
7902179193Sjb		dtrace_hash_remove(dtrace_bymod, probe);
7903179193Sjb		dtrace_hash_remove(dtrace_byfunc, probe);
7904179193Sjb		dtrace_hash_remove(dtrace_byname, probe);
7905179193Sjb
7906179193Sjb		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7907179193Sjb		    probe->dtpr_arg);
7908179193Sjb		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7909179193Sjb		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7910179193Sjb		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7911179193Sjb		kmem_free(probe, sizeof (dtrace_probe_t));
7912179198Sjb#if defined(sun)
7913179193Sjb		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7914179198Sjb#else
7915179198Sjb		free_unr(dtrace_arena, i + 1);
7916179198Sjb#endif
7917179193Sjb	}
7918179193Sjb
7919179193Sjb	mutex_exit(&dtrace_lock);
7920179193Sjb	mutex_exit(&dtrace_provider_lock);
7921179193Sjb
7922179193Sjb	return (0);
7923179193Sjb}
7924179193Sjb
7925179193Sjb/*
7926179193Sjb * DTrace Probe Management Functions
7927179193Sjb *
7928179193Sjb * The functions in this section perform the DTrace probe management,
7929179193Sjb * including functions to create probes, look-up probes, and call into the
7930179193Sjb * providers to request that probes be provided.  Some of these functions are
7931179193Sjb * in the Provider-to-Framework API; these functions can be identified by the
7932179193Sjb * fact that they are not declared "static".
7933179193Sjb */
7934179193Sjb
7935179193Sjb/*
7936179193Sjb * Create a probe with the specified module name, function name, and name.
7937179193Sjb */
7938179193Sjbdtrace_id_t
7939179193Sjbdtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7940179193Sjb    const char *func, const char *name, int aframes, void *arg)
7941179193Sjb{
7942179193Sjb	dtrace_probe_t *probe, **probes;
7943179193Sjb	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7944179193Sjb	dtrace_id_t id;
7945179193Sjb
7946179193Sjb	if (provider == dtrace_provider) {
7947179193Sjb		ASSERT(MUTEX_HELD(&dtrace_lock));
7948179193Sjb	} else {
7949179193Sjb		mutex_enter(&dtrace_lock);
7950179193Sjb	}
7951179193Sjb
7952179198Sjb#if defined(sun)
7953179193Sjb	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7954179193Sjb	    VM_BESTFIT | VM_SLEEP);
7955179198Sjb#else
7956179198Sjb	id = alloc_unr(dtrace_arena);
7957179198Sjb#endif
7958179193Sjb	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7959179193Sjb
7960179193Sjb	probe->dtpr_id = id;
7961179193Sjb	probe->dtpr_gen = dtrace_probegen++;
7962179193Sjb	probe->dtpr_mod = dtrace_strdup(mod);
7963179193Sjb	probe->dtpr_func = dtrace_strdup(func);
7964179193Sjb	probe->dtpr_name = dtrace_strdup(name);
7965179193Sjb	probe->dtpr_arg = arg;
7966179193Sjb	probe->dtpr_aframes = aframes;
7967179193Sjb	probe->dtpr_provider = provider;
7968179193Sjb
7969179193Sjb	dtrace_hash_add(dtrace_bymod, probe);
7970179193Sjb	dtrace_hash_add(dtrace_byfunc, probe);
7971179193Sjb	dtrace_hash_add(dtrace_byname, probe);
7972179193Sjb
7973179193Sjb	if (id - 1 >= dtrace_nprobes) {
7974179193Sjb		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7975179193Sjb		size_t nsize = osize << 1;
7976179193Sjb
7977179193Sjb		if (nsize == 0) {
7978179193Sjb			ASSERT(osize == 0);
7979179193Sjb			ASSERT(dtrace_probes == NULL);
7980179193Sjb			nsize = sizeof (dtrace_probe_t *);
7981179193Sjb		}
7982179193Sjb
7983179193Sjb		probes = kmem_zalloc(nsize, KM_SLEEP);
7984179193Sjb
7985179193Sjb		if (dtrace_probes == NULL) {
7986179193Sjb			ASSERT(osize == 0);
7987179193Sjb			dtrace_probes = probes;
7988179193Sjb			dtrace_nprobes = 1;
7989179193Sjb		} else {
7990179193Sjb			dtrace_probe_t **oprobes = dtrace_probes;
7991179193Sjb
7992179193Sjb			bcopy(oprobes, probes, osize);
7993179193Sjb			dtrace_membar_producer();
7994179193Sjb			dtrace_probes = probes;
7995179193Sjb
7996179193Sjb			dtrace_sync();
7997179193Sjb
7998179193Sjb			/*
7999179193Sjb			 * All CPUs are now seeing the new probes array; we can
8000179193Sjb			 * safely free the old array.
8001179193Sjb			 */
8002179193Sjb			kmem_free(oprobes, osize);
8003179193Sjb			dtrace_nprobes <<= 1;
8004179193Sjb		}
8005179193Sjb
8006179193Sjb		ASSERT(id - 1 < dtrace_nprobes);
8007179193Sjb	}
8008179193Sjb
8009179193Sjb	ASSERT(dtrace_probes[id - 1] == NULL);
8010179193Sjb	dtrace_probes[id - 1] = probe;
8011179193Sjb
8012179193Sjb	if (provider != dtrace_provider)
8013179193Sjb		mutex_exit(&dtrace_lock);
8014179193Sjb
8015179193Sjb	return (id);
8016179193Sjb}
8017179193Sjb
8018179193Sjbstatic dtrace_probe_t *
8019179193Sjbdtrace_probe_lookup_id(dtrace_id_t id)
8020179193Sjb{
8021179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
8022179193Sjb
8023179193Sjb	if (id == 0 || id > dtrace_nprobes)
8024179193Sjb		return (NULL);
8025179193Sjb
8026179193Sjb	return (dtrace_probes[id - 1]);
8027179193Sjb}
8028179193Sjb
8029179193Sjbstatic int
8030179193Sjbdtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8031179193Sjb{
8032179193Sjb	*((dtrace_id_t *)arg) = probe->dtpr_id;
8033179193Sjb
8034179193Sjb	return (DTRACE_MATCH_DONE);
8035179193Sjb}
8036179193Sjb
8037179193Sjb/*
8038179193Sjb * Look up a probe based on provider and one or more of module name, function
8039179193Sjb * name and probe name.
8040179193Sjb */
8041179193Sjbdtrace_id_t
8042179198Sjbdtrace_probe_lookup(dtrace_provider_id_t prid, char *mod,
8043179198Sjb    char *func, char *name)
8044179193Sjb{
8045179193Sjb	dtrace_probekey_t pkey;
8046179193Sjb	dtrace_id_t id;
8047179193Sjb	int match;
8048179193Sjb
8049179193Sjb	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8050179193Sjb	pkey.dtpk_pmatch = &dtrace_match_string;
8051179193Sjb	pkey.dtpk_mod = mod;
8052179193Sjb	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8053179193Sjb	pkey.dtpk_func = func;
8054179193Sjb	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8055179193Sjb	pkey.dtpk_name = name;
8056179193Sjb	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8057179193Sjb	pkey.dtpk_id = DTRACE_IDNONE;
8058179193Sjb
8059179193Sjb	mutex_enter(&dtrace_lock);
8060179193Sjb	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8061179193Sjb	    dtrace_probe_lookup_match, &id);
8062179193Sjb	mutex_exit(&dtrace_lock);
8063179193Sjb
8064179193Sjb	ASSERT(match == 1 || match == 0);
8065179193Sjb	return (match ? id : 0);
8066179193Sjb}
8067179193Sjb
8068179193Sjb/*
8069179193Sjb * Returns the probe argument associated with the specified probe.
8070179193Sjb */
8071179193Sjbvoid *
8072179193Sjbdtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8073179193Sjb{
8074179193Sjb	dtrace_probe_t *probe;
8075179193Sjb	void *rval = NULL;
8076179193Sjb
8077179193Sjb	mutex_enter(&dtrace_lock);
8078179193Sjb
8079179193Sjb	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8080179193Sjb	    probe->dtpr_provider == (dtrace_provider_t *)id)
8081179193Sjb		rval = probe->dtpr_arg;
8082179193Sjb
8083179193Sjb	mutex_exit(&dtrace_lock);
8084179193Sjb
8085179193Sjb	return (rval);
8086179193Sjb}
8087179193Sjb
8088179193Sjb/*
8089179193Sjb * Copy a probe into a probe description.
8090179193Sjb */
8091179193Sjbstatic void
8092179193Sjbdtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8093179193Sjb{
8094179193Sjb	bzero(pdp, sizeof (dtrace_probedesc_t));
8095179193Sjb	pdp->dtpd_id = prp->dtpr_id;
8096179193Sjb
8097179193Sjb	(void) strncpy(pdp->dtpd_provider,
8098179193Sjb	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8099179193Sjb
8100179193Sjb	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8101179193Sjb	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8102179193Sjb	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8103179193Sjb}
8104179193Sjb
8105179193Sjb/*
8106179193Sjb * Called to indicate that a probe -- or probes -- should be provided by a
8107179193Sjb * specfied provider.  If the specified description is NULL, the provider will
8108179193Sjb * be told to provide all of its probes.  (This is done whenever a new
8109179193Sjb * consumer comes along, or whenever a retained enabling is to be matched.) If
8110179193Sjb * the specified description is non-NULL, the provider is given the
8111179193Sjb * opportunity to dynamically provide the specified probe, allowing providers
8112179193Sjb * to support the creation of probes on-the-fly.  (So-called _autocreated_
8113179193Sjb * probes.)  If the provider is NULL, the operations will be applied to all
8114179193Sjb * providers; if the provider is non-NULL the operations will only be applied
8115179193Sjb * to the specified provider.  The dtrace_provider_lock must be held, and the
8116179193Sjb * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8117179193Sjb * will need to grab the dtrace_lock when it reenters the framework through
8118179193Sjb * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8119179193Sjb */
8120179193Sjbstatic void
8121179193Sjbdtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8122179193Sjb{
8123179198Sjb#if defined(sun)
8124179198Sjb	modctl_t *ctl;
8125179198Sjb#endif
8126179193Sjb	int all = 0;
8127179193Sjb
8128179193Sjb	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8129179193Sjb
8130179193Sjb	if (prv == NULL) {
8131179193Sjb		all = 1;
8132179193Sjb		prv = dtrace_provider;
8133179193Sjb	}
8134179193Sjb
8135179193Sjb	do {
8136179193Sjb		/*
8137179193Sjb		 * First, call the blanket provide operation.
8138179193Sjb		 */
8139179193Sjb		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8140179193Sjb
8141262052Savg#if defined(sun)
8142179193Sjb		/*
8143179193Sjb		 * Now call the per-module provide operation.  We will grab
8144179193Sjb		 * mod_lock to prevent the list from being modified.  Note
8145179193Sjb		 * that this also prevents the mod_busy bits from changing.
8146179193Sjb		 * (mod_busy can only be changed with mod_lock held.)
8147179193Sjb		 */
8148179193Sjb		mutex_enter(&mod_lock);
8149179193Sjb
8150179193Sjb		ctl = &modules;
8151179193Sjb		do {
8152179193Sjb			if (ctl->mod_busy || ctl->mod_mp == NULL)
8153179193Sjb				continue;
8154179193Sjb
8155179193Sjb			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8156179193Sjb
8157179193Sjb		} while ((ctl = ctl->mod_next) != &modules);
8158179193Sjb
8159179193Sjb		mutex_exit(&mod_lock);
8160262052Savg#endif
8161179193Sjb	} while (all && (prv = prv->dtpv_next) != NULL);
8162179193Sjb}
8163179193Sjb
8164179198Sjb#if defined(sun)
8165179193Sjb/*
8166179193Sjb * Iterate over each probe, and call the Framework-to-Provider API function
8167179193Sjb * denoted by offs.
8168179193Sjb */
8169179193Sjbstatic void
8170179193Sjbdtrace_probe_foreach(uintptr_t offs)
8171179193Sjb{
8172179193Sjb	dtrace_provider_t *prov;
8173179193Sjb	void (*func)(void *, dtrace_id_t, void *);
8174179193Sjb	dtrace_probe_t *probe;
8175179193Sjb	dtrace_icookie_t cookie;
8176179193Sjb	int i;
8177179193Sjb
8178179193Sjb	/*
8179179193Sjb	 * We disable interrupts to walk through the probe array.  This is
8180179193Sjb	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8181179193Sjb	 * won't see stale data.
8182179193Sjb	 */
8183179193Sjb	cookie = dtrace_interrupt_disable();
8184179193Sjb
8185179193Sjb	for (i = 0; i < dtrace_nprobes; i++) {
8186179193Sjb		if ((probe = dtrace_probes[i]) == NULL)
8187179193Sjb			continue;
8188179193Sjb
8189179193Sjb		if (probe->dtpr_ecb == NULL) {
8190179193Sjb			/*
8191179193Sjb			 * This probe isn't enabled -- don't call the function.
8192179193Sjb			 */
8193179193Sjb			continue;
8194179193Sjb		}
8195179193Sjb
8196179193Sjb		prov = probe->dtpr_provider;
8197179193Sjb		func = *((void(**)(void *, dtrace_id_t, void *))
8198179193Sjb		    ((uintptr_t)&prov->dtpv_pops + offs));
8199179193Sjb
8200179193Sjb		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8201179193Sjb	}
8202179193Sjb
8203179193Sjb	dtrace_interrupt_enable(cookie);
8204179193Sjb}
8205179198Sjb#endif
8206179193Sjb
8207179193Sjbstatic int
8208179198Sjbdtrace_probe_enable(dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8209179193Sjb{
8210179193Sjb	dtrace_probekey_t pkey;
8211179193Sjb	uint32_t priv;
8212179193Sjb	uid_t uid;
8213179193Sjb	zoneid_t zoneid;
8214179193Sjb
8215179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
8216179193Sjb	dtrace_ecb_create_cache = NULL;
8217179193Sjb
8218179193Sjb	if (desc == NULL) {
8219179193Sjb		/*
8220179193Sjb		 * If we're passed a NULL description, we're being asked to
8221179193Sjb		 * create an ECB with a NULL probe.
8222179193Sjb		 */
8223179193Sjb		(void) dtrace_ecb_create_enable(NULL, enab);
8224179193Sjb		return (0);
8225179193Sjb	}
8226179193Sjb
8227179193Sjb	dtrace_probekey(desc, &pkey);
8228179193Sjb	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8229179193Sjb	    &priv, &uid, &zoneid);
8230179193Sjb
8231179193Sjb	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8232179193Sjb	    enab));
8233179193Sjb}
8234179193Sjb
8235179193Sjb/*
8236179193Sjb * DTrace Helper Provider Functions
8237179193Sjb */
8238179193Sjbstatic void
8239179193Sjbdtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8240179193Sjb{
8241179193Sjb	attr->dtat_name = DOF_ATTR_NAME(dofattr);
8242179193Sjb	attr->dtat_data = DOF_ATTR_DATA(dofattr);
8243179193Sjb	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8244179193Sjb}
8245179193Sjb
8246179193Sjbstatic void
8247179193Sjbdtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8248179193Sjb    const dof_provider_t *dofprov, char *strtab)
8249179193Sjb{
8250179193Sjb	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8251179193Sjb	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8252179193Sjb	    dofprov->dofpv_provattr);
8253179193Sjb	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8254179193Sjb	    dofprov->dofpv_modattr);
8255179193Sjb	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8256179193Sjb	    dofprov->dofpv_funcattr);
8257179193Sjb	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8258179193Sjb	    dofprov->dofpv_nameattr);
8259179193Sjb	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8260179193Sjb	    dofprov->dofpv_argsattr);
8261179193Sjb}
8262179193Sjb
8263179193Sjbstatic void
8264179193Sjbdtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8265179193Sjb{
8266179193Sjb	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8267179193Sjb	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8268179193Sjb	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8269179193Sjb	dof_provider_t *provider;
8270179193Sjb	dof_probe_t *probe;
8271179193Sjb	uint32_t *off, *enoff;
8272179193Sjb	uint8_t *arg;
8273179193Sjb	char *strtab;
8274179193Sjb	uint_t i, nprobes;
8275179193Sjb	dtrace_helper_provdesc_t dhpv;
8276179193Sjb	dtrace_helper_probedesc_t dhpb;
8277179193Sjb	dtrace_meta_t *meta = dtrace_meta_pid;
8278179193Sjb	dtrace_mops_t *mops = &meta->dtm_mops;
8279179193Sjb	void *parg;
8280179193Sjb
8281179193Sjb	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8282179193Sjb	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8283179193Sjb	    provider->dofpv_strtab * dof->dofh_secsize);
8284179193Sjb	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8285179193Sjb	    provider->dofpv_probes * dof->dofh_secsize);
8286179193Sjb	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8287179193Sjb	    provider->dofpv_prargs * dof->dofh_secsize);
8288179193Sjb	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8289179193Sjb	    provider->dofpv_proffs * dof->dofh_secsize);
8290179193Sjb
8291179193Sjb	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8292179193Sjb	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8293179193Sjb	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8294179193Sjb	enoff = NULL;
8295179193Sjb
8296179193Sjb	/*
8297179193Sjb	 * See dtrace_helper_provider_validate().
8298179193Sjb	 */
8299179193Sjb	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8300179193Sjb	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
8301179193Sjb		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8302179193Sjb		    provider->dofpv_prenoffs * dof->dofh_secsize);
8303179193Sjb		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8304179193Sjb	}
8305179193Sjb
8306179193Sjb	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8307179193Sjb
8308179193Sjb	/*
8309179193Sjb	 * Create the provider.
8310179193Sjb	 */
8311179193Sjb	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8312179193Sjb
8313179193Sjb	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8314179193Sjb		return;
8315179193Sjb
8316179193Sjb	meta->dtm_count++;
8317179193Sjb
8318179193Sjb	/*
8319179193Sjb	 * Create the probes.
8320179193Sjb	 */
8321179193Sjb	for (i = 0; i < nprobes; i++) {
8322179193Sjb		probe = (dof_probe_t *)(uintptr_t)(daddr +
8323179193Sjb		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8324179193Sjb
8325179193Sjb		dhpb.dthpb_mod = dhp->dofhp_mod;
8326179193Sjb		dhpb.dthpb_func = strtab + probe->dofpr_func;
8327179193Sjb		dhpb.dthpb_name = strtab + probe->dofpr_name;
8328179193Sjb		dhpb.dthpb_base = probe->dofpr_addr;
8329179193Sjb		dhpb.dthpb_offs = off + probe->dofpr_offidx;
8330179193Sjb		dhpb.dthpb_noffs = probe->dofpr_noffs;
8331179193Sjb		if (enoff != NULL) {
8332179193Sjb			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8333179193Sjb			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8334179193Sjb		} else {
8335179193Sjb			dhpb.dthpb_enoffs = NULL;
8336179193Sjb			dhpb.dthpb_nenoffs = 0;
8337179193Sjb		}
8338179193Sjb		dhpb.dthpb_args = arg + probe->dofpr_argidx;
8339179193Sjb		dhpb.dthpb_nargc = probe->dofpr_nargc;
8340179193Sjb		dhpb.dthpb_xargc = probe->dofpr_xargc;
8341179193Sjb		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8342179193Sjb		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8343179193Sjb
8344179193Sjb		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8345179193Sjb	}
8346179193Sjb}
8347179193Sjb
8348179193Sjbstatic void
8349179193Sjbdtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8350179193Sjb{
8351179193Sjb	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8352179193Sjb	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8353179193Sjb	int i;
8354179193Sjb
8355179193Sjb	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8356179193Sjb
8357179193Sjb	for (i = 0; i < dof->dofh_secnum; i++) {
8358179193Sjb		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8359179193Sjb		    dof->dofh_secoff + i * dof->dofh_secsize);
8360179193Sjb
8361179193Sjb		if (sec->dofs_type != DOF_SECT_PROVIDER)
8362179193Sjb			continue;
8363179193Sjb
8364179193Sjb		dtrace_helper_provide_one(dhp, sec, pid);
8365179193Sjb	}
8366179193Sjb
8367179193Sjb	/*
8368179193Sjb	 * We may have just created probes, so we must now rematch against
8369179193Sjb	 * any retained enablings.  Note that this call will acquire both
8370179193Sjb	 * cpu_lock and dtrace_lock; the fact that we are holding
8371179193Sjb	 * dtrace_meta_lock now is what defines the ordering with respect to
8372179193Sjb	 * these three locks.
8373179193Sjb	 */
8374179193Sjb	dtrace_enabling_matchall();
8375179193Sjb}
8376179193Sjb
8377179193Sjbstatic void
8378179193Sjbdtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8379179193Sjb{
8380179193Sjb	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8381179193Sjb	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8382179193Sjb	dof_sec_t *str_sec;
8383179193Sjb	dof_provider_t *provider;
8384179193Sjb	char *strtab;
8385179193Sjb	dtrace_helper_provdesc_t dhpv;
8386179193Sjb	dtrace_meta_t *meta = dtrace_meta_pid;
8387179193Sjb	dtrace_mops_t *mops = &meta->dtm_mops;
8388179193Sjb
8389179193Sjb	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8390179193Sjb	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8391179193Sjb	    provider->dofpv_strtab * dof->dofh_secsize);
8392179193Sjb
8393179193Sjb	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8394179193Sjb
8395179193Sjb	/*
8396179193Sjb	 * Create the provider.
8397179193Sjb	 */
8398179193Sjb	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8399179193Sjb
8400179193Sjb	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8401179193Sjb
8402179193Sjb	meta->dtm_count--;
8403179193Sjb}
8404179193Sjb
8405179193Sjbstatic void
8406179193Sjbdtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8407179193Sjb{
8408179193Sjb	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8409179193Sjb	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8410179193Sjb	int i;
8411179193Sjb
8412179193Sjb	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8413179193Sjb
8414179193Sjb	for (i = 0; i < dof->dofh_secnum; i++) {
8415179193Sjb		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8416179193Sjb		    dof->dofh_secoff + i * dof->dofh_secsize);
8417179193Sjb
8418179193Sjb		if (sec->dofs_type != DOF_SECT_PROVIDER)
8419179193Sjb			continue;
8420179193Sjb
8421179193Sjb		dtrace_helper_provider_remove_one(dhp, sec, pid);
8422179193Sjb	}
8423179193Sjb}
8424179193Sjb
8425179193Sjb/*
8426179193Sjb * DTrace Meta Provider-to-Framework API Functions
8427179193Sjb *
8428179193Sjb * These functions implement the Meta Provider-to-Framework API, as described
8429179193Sjb * in <sys/dtrace.h>.
8430179193Sjb */
8431179193Sjbint
8432179193Sjbdtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8433179193Sjb    dtrace_meta_provider_id_t *idp)
8434179193Sjb{
8435179193Sjb	dtrace_meta_t *meta;
8436179193Sjb	dtrace_helpers_t *help, *next;
8437179193Sjb	int i;
8438179193Sjb
8439179193Sjb	*idp = DTRACE_METAPROVNONE;
8440179193Sjb
8441179193Sjb	/*
8442179193Sjb	 * We strictly don't need the name, but we hold onto it for
8443179193Sjb	 * debuggability. All hail error queues!
8444179193Sjb	 */
8445179193Sjb	if (name == NULL) {
8446179193Sjb		cmn_err(CE_WARN, "failed to register meta-provider: "
8447179193Sjb		    "invalid name");
8448179193Sjb		return (EINVAL);
8449179193Sjb	}
8450179193Sjb
8451179193Sjb	if (mops == NULL ||
8452179193Sjb	    mops->dtms_create_probe == NULL ||
8453179193Sjb	    mops->dtms_provide_pid == NULL ||
8454179193Sjb	    mops->dtms_remove_pid == NULL) {
8455179193Sjb		cmn_err(CE_WARN, "failed to register meta-register %s: "
8456179193Sjb		    "invalid ops", name);
8457179193Sjb		return (EINVAL);
8458179193Sjb	}
8459179193Sjb
8460179193Sjb	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8461179193Sjb	meta->dtm_mops = *mops;
8462179193Sjb	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8463179193Sjb	(void) strcpy(meta->dtm_name, name);
8464179193Sjb	meta->dtm_arg = arg;
8465179193Sjb
8466179193Sjb	mutex_enter(&dtrace_meta_lock);
8467179193Sjb	mutex_enter(&dtrace_lock);
8468179193Sjb
8469179193Sjb	if (dtrace_meta_pid != NULL) {
8470179193Sjb		mutex_exit(&dtrace_lock);
8471179193Sjb		mutex_exit(&dtrace_meta_lock);
8472179193Sjb		cmn_err(CE_WARN, "failed to register meta-register %s: "
8473179193Sjb		    "user-land meta-provider exists", name);
8474179193Sjb		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8475179193Sjb		kmem_free(meta, sizeof (dtrace_meta_t));
8476179193Sjb		return (EINVAL);
8477179193Sjb	}
8478179193Sjb
8479179193Sjb	dtrace_meta_pid = meta;
8480179193Sjb	*idp = (dtrace_meta_provider_id_t)meta;
8481179193Sjb
8482179193Sjb	/*
8483179193Sjb	 * If there are providers and probes ready to go, pass them
8484179193Sjb	 * off to the new meta provider now.
8485179193Sjb	 */
8486179193Sjb
8487179193Sjb	help = dtrace_deferred_pid;
8488179193Sjb	dtrace_deferred_pid = NULL;
8489179193Sjb
8490179193Sjb	mutex_exit(&dtrace_lock);
8491179193Sjb
8492179193Sjb	while (help != NULL) {
8493179193Sjb		for (i = 0; i < help->dthps_nprovs; i++) {
8494179193Sjb			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8495179193Sjb			    help->dthps_pid);
8496179193Sjb		}
8497179193Sjb
8498179193Sjb		next = help->dthps_next;
8499179193Sjb		help->dthps_next = NULL;
8500179193Sjb		help->dthps_prev = NULL;
8501179193Sjb		help->dthps_deferred = 0;
8502179193Sjb		help = next;
8503179193Sjb	}
8504179193Sjb
8505179193Sjb	mutex_exit(&dtrace_meta_lock);
8506179193Sjb
8507179193Sjb	return (0);
8508179193Sjb}
8509179193Sjb
8510179193Sjbint
8511179193Sjbdtrace_meta_unregister(dtrace_meta_provider_id_t id)
8512179193Sjb{
8513179193Sjb	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8514179193Sjb
8515179193Sjb	mutex_enter(&dtrace_meta_lock);
8516179193Sjb	mutex_enter(&dtrace_lock);
8517179193Sjb
8518179193Sjb	if (old == dtrace_meta_pid) {
8519179193Sjb		pp = &dtrace_meta_pid;
8520179193Sjb	} else {
8521179193Sjb		panic("attempt to unregister non-existent "
8522179193Sjb		    "dtrace meta-provider %p\n", (void *)old);
8523179193Sjb	}
8524179193Sjb
8525179193Sjb	if (old->dtm_count != 0) {
8526179193Sjb		mutex_exit(&dtrace_lock);
8527179193Sjb		mutex_exit(&dtrace_meta_lock);
8528179193Sjb		return (EBUSY);
8529179193Sjb	}
8530179193Sjb
8531179193Sjb	*pp = NULL;
8532179193Sjb
8533179193Sjb	mutex_exit(&dtrace_lock);
8534179193Sjb	mutex_exit(&dtrace_meta_lock);
8535179193Sjb
8536179193Sjb	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8537179193Sjb	kmem_free(old, sizeof (dtrace_meta_t));
8538179193Sjb
8539179193Sjb	return (0);
8540179193Sjb}
8541179193Sjb
8542179193Sjb
8543179193Sjb/*
8544179193Sjb * DTrace DIF Object Functions
8545179193Sjb */
8546179193Sjbstatic int
8547179193Sjbdtrace_difo_err(uint_t pc, const char *format, ...)
8548179193Sjb{
8549179193Sjb	if (dtrace_err_verbose) {
8550179193Sjb		va_list alist;
8551179193Sjb
8552179193Sjb		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
8553179193Sjb		va_start(alist, format);
8554179193Sjb		(void) vuprintf(format, alist);
8555179193Sjb		va_end(alist);
8556179193Sjb	}
8557179193Sjb
8558179193Sjb#ifdef DTRACE_ERRDEBUG
8559179193Sjb	dtrace_errdebug(format);
8560179193Sjb#endif
8561179193Sjb	return (1);
8562179193Sjb}
8563179193Sjb
8564179193Sjb/*
8565179193Sjb * Validate a DTrace DIF object by checking the IR instructions.  The following
8566179193Sjb * rules are currently enforced by dtrace_difo_validate():
8567179193Sjb *
8568179193Sjb * 1. Each instruction must have a valid opcode
8569179193Sjb * 2. Each register, string, variable, or subroutine reference must be valid
8570179193Sjb * 3. No instruction can modify register %r0 (must be zero)
8571179193Sjb * 4. All instruction reserved bits must be set to zero
8572179193Sjb * 5. The last instruction must be a "ret" instruction
8573179193Sjb * 6. All branch targets must reference a valid instruction _after_ the branch
8574179193Sjb */
8575179193Sjbstatic int
8576179193Sjbdtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8577179193Sjb    cred_t *cr)
8578179193Sjb{
8579179193Sjb	int err = 0, i;
8580179193Sjb	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8581179193Sjb	int kcheckload;
8582179193Sjb	uint_t pc;
8583179193Sjb
8584179193Sjb	kcheckload = cr == NULL ||
8585179193Sjb	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8586179193Sjb
8587179193Sjb	dp->dtdo_destructive = 0;
8588179193Sjb
8589179193Sjb	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8590179193Sjb		dif_instr_t instr = dp->dtdo_buf[pc];
8591179193Sjb
8592179193Sjb		uint_t r1 = DIF_INSTR_R1(instr);
8593179193Sjb		uint_t r2 = DIF_INSTR_R2(instr);
8594179193Sjb		uint_t rd = DIF_INSTR_RD(instr);
8595179193Sjb		uint_t rs = DIF_INSTR_RS(instr);
8596179193Sjb		uint_t label = DIF_INSTR_LABEL(instr);
8597179193Sjb		uint_t v = DIF_INSTR_VAR(instr);
8598179193Sjb		uint_t subr = DIF_INSTR_SUBR(instr);
8599179193Sjb		uint_t type = DIF_INSTR_TYPE(instr);
8600179193Sjb		uint_t op = DIF_INSTR_OP(instr);
8601179193Sjb
8602179193Sjb		switch (op) {
8603179193Sjb		case DIF_OP_OR:
8604179193Sjb		case DIF_OP_XOR:
8605179193Sjb		case DIF_OP_AND:
8606179193Sjb		case DIF_OP_SLL:
8607179193Sjb		case DIF_OP_SRL:
8608179193Sjb		case DIF_OP_SRA:
8609179193Sjb		case DIF_OP_SUB:
8610179193Sjb		case DIF_OP_ADD:
8611179193Sjb		case DIF_OP_MUL:
8612179193Sjb		case DIF_OP_SDIV:
8613179193Sjb		case DIF_OP_UDIV:
8614179193Sjb		case DIF_OP_SREM:
8615179193Sjb		case DIF_OP_UREM:
8616179193Sjb		case DIF_OP_COPYS:
8617179193Sjb			if (r1 >= nregs)
8618179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8619179193Sjb			if (r2 >= nregs)
8620179193Sjb				err += efunc(pc, "invalid register %u\n", r2);
8621179193Sjb			if (rd >= nregs)
8622179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8623179193Sjb			if (rd == 0)
8624179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8625179193Sjb			break;
8626179193Sjb		case DIF_OP_NOT:
8627179193Sjb		case DIF_OP_MOV:
8628179193Sjb		case DIF_OP_ALLOCS:
8629179193Sjb			if (r1 >= nregs)
8630179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8631179193Sjb			if (r2 != 0)
8632179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8633179193Sjb			if (rd >= nregs)
8634179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8635179193Sjb			if (rd == 0)
8636179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8637179193Sjb			break;
8638179193Sjb		case DIF_OP_LDSB:
8639179193Sjb		case DIF_OP_LDSH:
8640179193Sjb		case DIF_OP_LDSW:
8641179193Sjb		case DIF_OP_LDUB:
8642179193Sjb		case DIF_OP_LDUH:
8643179193Sjb		case DIF_OP_LDUW:
8644179193Sjb		case DIF_OP_LDX:
8645179193Sjb			if (r1 >= nregs)
8646179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8647179193Sjb			if (r2 != 0)
8648179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8649179193Sjb			if (rd >= nregs)
8650179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8651179193Sjb			if (rd == 0)
8652179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8653179193Sjb			if (kcheckload)
8654179193Sjb				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8655179193Sjb				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8656179193Sjb			break;
8657179193Sjb		case DIF_OP_RLDSB:
8658179193Sjb		case DIF_OP_RLDSH:
8659179193Sjb		case DIF_OP_RLDSW:
8660179193Sjb		case DIF_OP_RLDUB:
8661179193Sjb		case DIF_OP_RLDUH:
8662179193Sjb		case DIF_OP_RLDUW:
8663179193Sjb		case DIF_OP_RLDX:
8664179193Sjb			if (r1 >= nregs)
8665179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8666179193Sjb			if (r2 != 0)
8667179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8668179193Sjb			if (rd >= nregs)
8669179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8670179193Sjb			if (rd == 0)
8671179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8672179193Sjb			break;
8673179193Sjb		case DIF_OP_ULDSB:
8674179193Sjb		case DIF_OP_ULDSH:
8675179193Sjb		case DIF_OP_ULDSW:
8676179193Sjb		case DIF_OP_ULDUB:
8677179193Sjb		case DIF_OP_ULDUH:
8678179193Sjb		case DIF_OP_ULDUW:
8679179193Sjb		case DIF_OP_ULDX:
8680179193Sjb			if (r1 >= nregs)
8681179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8682179193Sjb			if (r2 != 0)
8683179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8684179193Sjb			if (rd >= nregs)
8685179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8686179193Sjb			if (rd == 0)
8687179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8688179193Sjb			break;
8689179193Sjb		case DIF_OP_STB:
8690179193Sjb		case DIF_OP_STH:
8691179193Sjb		case DIF_OP_STW:
8692179193Sjb		case DIF_OP_STX:
8693179193Sjb			if (r1 >= nregs)
8694179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8695179193Sjb			if (r2 != 0)
8696179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8697179193Sjb			if (rd >= nregs)
8698179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8699179193Sjb			if (rd == 0)
8700179193Sjb				err += efunc(pc, "cannot write to 0 address\n");
8701179193Sjb			break;
8702179193Sjb		case DIF_OP_CMP:
8703179193Sjb		case DIF_OP_SCMP:
8704179193Sjb			if (r1 >= nregs)
8705179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8706179193Sjb			if (r2 >= nregs)
8707179193Sjb				err += efunc(pc, "invalid register %u\n", r2);
8708179193Sjb			if (rd != 0)
8709179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8710179193Sjb			break;
8711179193Sjb		case DIF_OP_TST:
8712179193Sjb			if (r1 >= nregs)
8713179193Sjb				err += efunc(pc, "invalid register %u\n", r1);
8714179193Sjb			if (r2 != 0 || rd != 0)
8715179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8716179193Sjb			break;
8717179193Sjb		case DIF_OP_BA:
8718179193Sjb		case DIF_OP_BE:
8719179193Sjb		case DIF_OP_BNE:
8720179193Sjb		case DIF_OP_BG:
8721179193Sjb		case DIF_OP_BGU:
8722179193Sjb		case DIF_OP_BGE:
8723179193Sjb		case DIF_OP_BGEU:
8724179193Sjb		case DIF_OP_BL:
8725179193Sjb		case DIF_OP_BLU:
8726179193Sjb		case DIF_OP_BLE:
8727179193Sjb		case DIF_OP_BLEU:
8728179193Sjb			if (label >= dp->dtdo_len) {
8729179193Sjb				err += efunc(pc, "invalid branch target %u\n",
8730179193Sjb				    label);
8731179193Sjb			}
8732179193Sjb			if (label <= pc) {
8733179193Sjb				err += efunc(pc, "backward branch to %u\n",
8734179193Sjb				    label);
8735179193Sjb			}
8736179193Sjb			break;
8737179193Sjb		case DIF_OP_RET:
8738179193Sjb			if (r1 != 0 || r2 != 0)
8739179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8740179193Sjb			if (rd >= nregs)
8741179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8742179193Sjb			break;
8743179193Sjb		case DIF_OP_NOP:
8744179193Sjb		case DIF_OP_POPTS:
8745179193Sjb		case DIF_OP_FLUSHTS:
8746179193Sjb			if (r1 != 0 || r2 != 0 || rd != 0)
8747179193Sjb				err += efunc(pc, "non-zero reserved bits\n");
8748179193Sjb			break;
8749179193Sjb		case DIF_OP_SETX:
8750179193Sjb			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8751179193Sjb				err += efunc(pc, "invalid integer ref %u\n",
8752179193Sjb				    DIF_INSTR_INTEGER(instr));
8753179193Sjb			}
8754179193Sjb			if (rd >= nregs)
8755179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8756179193Sjb			if (rd == 0)
8757179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8758179193Sjb			break;
8759179193Sjb		case DIF_OP_SETS:
8760179193Sjb			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8761179193Sjb				err += efunc(pc, "invalid string ref %u\n",
8762179193Sjb				    DIF_INSTR_STRING(instr));
8763179193Sjb			}
8764179193Sjb			if (rd >= nregs)
8765179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8766179193Sjb			if (rd == 0)
8767179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8768179193Sjb			break;
8769179193Sjb		case DIF_OP_LDGA:
8770179193Sjb		case DIF_OP_LDTA:
8771179193Sjb			if (r1 > DIF_VAR_ARRAY_MAX)
8772179193Sjb				err += efunc(pc, "invalid array %u\n", r1);
8773179193Sjb			if (r2 >= nregs)
8774179193Sjb				err += efunc(pc, "invalid register %u\n", r2);
8775179193Sjb			if (rd >= nregs)
8776179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8777179193Sjb			if (rd == 0)
8778179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8779179193Sjb			break;
8780179193Sjb		case DIF_OP_LDGS:
8781179193Sjb		case DIF_OP_LDTS:
8782179193Sjb		case DIF_OP_LDLS:
8783179193Sjb		case DIF_OP_LDGAA:
8784179193Sjb		case DIF_OP_LDTAA:
8785179193Sjb			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8786179193Sjb				err += efunc(pc, "invalid variable %u\n", v);
8787179193Sjb			if (rd >= nregs)
8788179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8789179193Sjb			if (rd == 0)
8790179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8791179193Sjb			break;
8792179193Sjb		case DIF_OP_STGS:
8793179193Sjb		case DIF_OP_STTS:
8794179193Sjb		case DIF_OP_STLS:
8795179193Sjb		case DIF_OP_STGAA:
8796179193Sjb		case DIF_OP_STTAA:
8797179193Sjb			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8798179193Sjb				err += efunc(pc, "invalid variable %u\n", v);
8799179193Sjb			if (rs >= nregs)
8800179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8801179193Sjb			break;
8802179193Sjb		case DIF_OP_CALL:
8803179193Sjb			if (subr > DIF_SUBR_MAX)
8804179193Sjb				err += efunc(pc, "invalid subr %u\n", subr);
8805179193Sjb			if (rd >= nregs)
8806179193Sjb				err += efunc(pc, "invalid register %u\n", rd);
8807179193Sjb			if (rd == 0)
8808179193Sjb				err += efunc(pc, "cannot write to %r0\n");
8809179193Sjb
8810179193Sjb			if (subr == DIF_SUBR_COPYOUT ||
8811179193Sjb			    subr == DIF_SUBR_COPYOUTSTR) {
8812179193Sjb				dp->dtdo_destructive = 1;
8813179193Sjb			}
8814179193Sjb			break;
8815179193Sjb		case DIF_OP_PUSHTR:
8816179193Sjb			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8817179193Sjb				err += efunc(pc, "invalid ref type %u\n", type);
8818179193Sjb			if (r2 >= nregs)
8819179193Sjb				err += efunc(pc, "invalid register %u\n", r2);
8820179193Sjb			if (rs >= nregs)
8821179193Sjb				err += efunc(pc, "invalid register %u\n", rs);
8822179193Sjb			break;
8823179193Sjb		case DIF_OP_PUSHTV:
8824179193Sjb			if (type != DIF_TYPE_CTF)
8825179193Sjb				err += efunc(pc, "invalid val type %u\n", type);
8826179193Sjb			if (r2 >= nregs)
8827179193Sjb				err += efunc(pc, "invalid register %u\n", r2);
8828179193Sjb			if (rs >= nregs)
8829179193Sjb				err += efunc(pc, "invalid register %u\n", rs);
8830179193Sjb			break;
8831179193Sjb		default:
8832179193Sjb			err += efunc(pc, "invalid opcode %u\n",
8833179193Sjb			    DIF_INSTR_OP(instr));
8834179193Sjb		}
8835179193Sjb	}
8836179193Sjb
8837179193Sjb	if (dp->dtdo_len != 0 &&
8838179193Sjb	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8839179193Sjb		err += efunc(dp->dtdo_len - 1,
8840179193Sjb		    "expected 'ret' as last DIF instruction\n");
8841179193Sjb	}
8842179193Sjb
8843179193Sjb	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8844179193Sjb		/*
8845179193Sjb		 * If we're not returning by reference, the size must be either
8846179193Sjb		 * 0 or the size of one of the base types.
8847179193Sjb		 */
8848179193Sjb		switch (dp->dtdo_rtype.dtdt_size) {
8849179193Sjb		case 0:
8850179193Sjb		case sizeof (uint8_t):
8851179193Sjb		case sizeof (uint16_t):
8852179193Sjb		case sizeof (uint32_t):
8853179193Sjb		case sizeof (uint64_t):
8854179193Sjb			break;
8855179193Sjb
8856179193Sjb		default:
8857179193Sjb			err += efunc(dp->dtdo_len - 1, "bad return size");
8858179193Sjb		}
8859179193Sjb	}
8860179193Sjb
8861179193Sjb	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8862179193Sjb		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8863179193Sjb		dtrace_diftype_t *vt, *et;
8864179193Sjb		uint_t id, ndx;
8865179193Sjb
8866179193Sjb		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8867179193Sjb		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
8868179193Sjb		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8869179193Sjb			err += efunc(i, "unrecognized variable scope %d\n",
8870179193Sjb			    v->dtdv_scope);
8871179193Sjb			break;
8872179193Sjb		}
8873179193Sjb
8874179193Sjb		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8875179193Sjb		    v->dtdv_kind != DIFV_KIND_SCALAR) {
8876179193Sjb			err += efunc(i, "unrecognized variable type %d\n",
8877179193Sjb			    v->dtdv_kind);
8878179193Sjb			break;
8879179193Sjb		}
8880179193Sjb
8881179193Sjb		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8882179193Sjb			err += efunc(i, "%d exceeds variable id limit\n", id);
8883179193Sjb			break;
8884179193Sjb		}
8885179193Sjb
8886179193Sjb		if (id < DIF_VAR_OTHER_UBASE)
8887179193Sjb			continue;
8888179193Sjb
8889179193Sjb		/*
8890179193Sjb		 * For user-defined variables, we need to check that this
8891179193Sjb		 * definition is identical to any previous definition that we
8892179193Sjb		 * encountered.
8893179193Sjb		 */
8894179193Sjb		ndx = id - DIF_VAR_OTHER_UBASE;
8895179193Sjb
8896179193Sjb		switch (v->dtdv_scope) {
8897179193Sjb		case DIFV_SCOPE_GLOBAL:
8898179193Sjb			if (ndx < vstate->dtvs_nglobals) {
8899179193Sjb				dtrace_statvar_t *svar;
8900179193Sjb
8901179193Sjb				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8902179193Sjb					existing = &svar->dtsv_var;
8903179193Sjb			}
8904179193Sjb
8905179193Sjb			break;
8906179193Sjb
8907179193Sjb		case DIFV_SCOPE_THREAD:
8908179193Sjb			if (ndx < vstate->dtvs_ntlocals)
8909179193Sjb				existing = &vstate->dtvs_tlocals[ndx];
8910179193Sjb			break;
8911179193Sjb
8912179193Sjb		case DIFV_SCOPE_LOCAL:
8913179193Sjb			if (ndx < vstate->dtvs_nlocals) {
8914179193Sjb				dtrace_statvar_t *svar;
8915179193Sjb
8916179193Sjb				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8917179193Sjb					existing = &svar->dtsv_var;
8918179193Sjb			}
8919179193Sjb
8920179193Sjb			break;
8921179193Sjb		}
8922179193Sjb
8923179193Sjb		vt = &v->dtdv_type;
8924179193Sjb
8925179193Sjb		if (vt->dtdt_flags & DIF_TF_BYREF) {
8926179193Sjb			if (vt->dtdt_size == 0) {
8927179193Sjb				err += efunc(i, "zero-sized variable\n");
8928179193Sjb				break;
8929179193Sjb			}
8930179193Sjb
8931179193Sjb			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8932179193Sjb			    vt->dtdt_size > dtrace_global_maxsize) {
8933179193Sjb				err += efunc(i, "oversized by-ref global\n");
8934179193Sjb				break;
8935179193Sjb			}
8936179193Sjb		}
8937179193Sjb
8938179193Sjb		if (existing == NULL || existing->dtdv_id == 0)
8939179193Sjb			continue;
8940179193Sjb
8941179193Sjb		ASSERT(existing->dtdv_id == v->dtdv_id);
8942179193Sjb		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8943179193Sjb
8944179193Sjb		if (existing->dtdv_kind != v->dtdv_kind)
8945179193Sjb			err += efunc(i, "%d changed variable kind\n", id);
8946179193Sjb
8947179193Sjb		et = &existing->dtdv_type;
8948179193Sjb
8949179193Sjb		if (vt->dtdt_flags != et->dtdt_flags) {
8950179193Sjb			err += efunc(i, "%d changed variable type flags\n", id);
8951179193Sjb			break;
8952179193Sjb		}
8953179193Sjb
8954179193Sjb		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8955179193Sjb			err += efunc(i, "%d changed variable type size\n", id);
8956179193Sjb			break;
8957179193Sjb		}
8958179193Sjb	}
8959179193Sjb
8960179193Sjb	return (err);
8961179193Sjb}
8962179193Sjb
8963179193Sjb/*
8964179193Sjb * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
8965179193Sjb * are much more constrained than normal DIFOs.  Specifically, they may
8966179193Sjb * not:
8967179193Sjb *
8968179193Sjb * 1. Make calls to subroutines other than copyin(), copyinstr() or
8969179193Sjb *    miscellaneous string routines
8970179193Sjb * 2. Access DTrace variables other than the args[] array, and the
8971179193Sjb *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8972179193Sjb * 3. Have thread-local variables.
8973179193Sjb * 4. Have dynamic variables.
8974179193Sjb */
8975179193Sjbstatic int
8976179193Sjbdtrace_difo_validate_helper(dtrace_difo_t *dp)
8977179193Sjb{
8978179193Sjb	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8979179193Sjb	int err = 0;
8980179193Sjb	uint_t pc;
8981179193Sjb
8982179193Sjb	for (pc = 0; pc < dp->dtdo_len; pc++) {
8983179193Sjb		dif_instr_t instr = dp->dtdo_buf[pc];
8984179193Sjb
8985179193Sjb		uint_t v = DIF_INSTR_VAR(instr);
8986179193Sjb		uint_t subr = DIF_INSTR_SUBR(instr);
8987179193Sjb		uint_t op = DIF_INSTR_OP(instr);
8988179193Sjb
8989179193Sjb		switch (op) {
8990179193Sjb		case DIF_OP_OR:
8991179193Sjb		case DIF_OP_XOR:
8992179193Sjb		case DIF_OP_AND:
8993179193Sjb		case DIF_OP_SLL:
8994179193Sjb		case DIF_OP_SRL:
8995179193Sjb		case DIF_OP_SRA:
8996179193Sjb		case DIF_OP_SUB:
8997179193Sjb		case DIF_OP_ADD:
8998179193Sjb		case DIF_OP_MUL:
8999179193Sjb		case DIF_OP_SDIV:
9000179193Sjb		case DIF_OP_UDIV:
9001179193Sjb		case DIF_OP_SREM:
9002179193Sjb		case DIF_OP_UREM:
9003179193Sjb		case DIF_OP_COPYS:
9004179193Sjb		case DIF_OP_NOT:
9005179193Sjb		case DIF_OP_MOV:
9006179193Sjb		case DIF_OP_RLDSB:
9007179193Sjb		case DIF_OP_RLDSH:
9008179193Sjb		case DIF_OP_RLDSW:
9009179193Sjb		case DIF_OP_RLDUB:
9010179193Sjb		case DIF_OP_RLDUH:
9011179193Sjb		case DIF_OP_RLDUW:
9012179193Sjb		case DIF_OP_RLDX:
9013179193Sjb		case DIF_OP_ULDSB:
9014179193Sjb		case DIF_OP_ULDSH:
9015179193Sjb		case DIF_OP_ULDSW:
9016179193Sjb		case DIF_OP_ULDUB:
9017179193Sjb		case DIF_OP_ULDUH:
9018179193Sjb		case DIF_OP_ULDUW:
9019179193Sjb		case DIF_OP_ULDX:
9020179193Sjb		case DIF_OP_STB:
9021179193Sjb		case DIF_OP_STH:
9022179193Sjb		case DIF_OP_STW:
9023179193Sjb		case DIF_OP_STX:
9024179193Sjb		case DIF_OP_ALLOCS:
9025179193Sjb		case DIF_OP_CMP:
9026179193Sjb		case DIF_OP_SCMP:
9027179193Sjb		case DIF_OP_TST:
9028179193Sjb		case DIF_OP_BA:
9029179193Sjb		case DIF_OP_BE:
9030179193Sjb		case DIF_OP_BNE:
9031179193Sjb		case DIF_OP_BG:
9032179193Sjb		case DIF_OP_BGU:
9033179193Sjb		case DIF_OP_BGE:
9034179193Sjb		case DIF_OP_BGEU:
9035179193Sjb		case DIF_OP_BL:
9036179193Sjb		case DIF_OP_BLU:
9037179193Sjb		case DIF_OP_BLE:
9038179193Sjb		case DIF_OP_BLEU:
9039179193Sjb		case DIF_OP_RET:
9040179193Sjb		case DIF_OP_NOP:
9041179193Sjb		case DIF_OP_POPTS:
9042179193Sjb		case DIF_OP_FLUSHTS:
9043179193Sjb		case DIF_OP_SETX:
9044179193Sjb		case DIF_OP_SETS:
9045179193Sjb		case DIF_OP_LDGA:
9046179193Sjb		case DIF_OP_LDLS:
9047179193Sjb		case DIF_OP_STGS:
9048179193Sjb		case DIF_OP_STLS:
9049179193Sjb		case DIF_OP_PUSHTR:
9050179193Sjb		case DIF_OP_PUSHTV:
9051179193Sjb			break;
9052179193Sjb
9053179193Sjb		case DIF_OP_LDGS:
9054179193Sjb			if (v >= DIF_VAR_OTHER_UBASE)
9055179193Sjb				break;
9056179193Sjb
9057179193Sjb			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9058179193Sjb				break;
9059179193Sjb
9060179193Sjb			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9061179193Sjb			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9062179198Sjb			    v == DIF_VAR_EXECARGS ||
9063179193Sjb			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9064179193Sjb			    v == DIF_VAR_UID || v == DIF_VAR_GID)
9065179193Sjb				break;
9066179193Sjb
9067179193Sjb			err += efunc(pc, "illegal variable %u\n", v);
9068179193Sjb			break;
9069179193Sjb
9070179193Sjb		case DIF_OP_LDTA:
9071179193Sjb		case DIF_OP_LDTS:
9072179193Sjb		case DIF_OP_LDGAA:
9073179193Sjb		case DIF_OP_LDTAA:
9074179193Sjb			err += efunc(pc, "illegal dynamic variable load\n");
9075179193Sjb			break;
9076179193Sjb
9077179193Sjb		case DIF_OP_STTS:
9078179193Sjb		case DIF_OP_STGAA:
9079179193Sjb		case DIF_OP_STTAA:
9080179193Sjb			err += efunc(pc, "illegal dynamic variable store\n");
9081179193Sjb			break;
9082179193Sjb
9083179193Sjb		case DIF_OP_CALL:
9084179193Sjb			if (subr == DIF_SUBR_ALLOCA ||
9085179193Sjb			    subr == DIF_SUBR_BCOPY ||
9086179193Sjb			    subr == DIF_SUBR_COPYIN ||
9087179193Sjb			    subr == DIF_SUBR_COPYINTO ||
9088179193Sjb			    subr == DIF_SUBR_COPYINSTR ||
9089179193Sjb			    subr == DIF_SUBR_INDEX ||
9090179193Sjb			    subr == DIF_SUBR_INET_NTOA ||
9091179193Sjb			    subr == DIF_SUBR_INET_NTOA6 ||
9092179193Sjb			    subr == DIF_SUBR_INET_NTOP ||
9093179193Sjb			    subr == DIF_SUBR_LLTOSTR ||
9094179193Sjb			    subr == DIF_SUBR_RINDEX ||
9095179193Sjb			    subr == DIF_SUBR_STRCHR ||
9096179193Sjb			    subr == DIF_SUBR_STRJOIN ||
9097179193Sjb			    subr == DIF_SUBR_STRRCHR ||
9098179193Sjb			    subr == DIF_SUBR_STRSTR ||
9099179193Sjb			    subr == DIF_SUBR_HTONS ||
9100179193Sjb			    subr == DIF_SUBR_HTONL ||
9101179193Sjb			    subr == DIF_SUBR_HTONLL ||
9102179193Sjb			    subr == DIF_SUBR_NTOHS ||
9103179193Sjb			    subr == DIF_SUBR_NTOHL ||
9104179198Sjb			    subr == DIF_SUBR_NTOHLL ||
9105179198Sjb			    subr == DIF_SUBR_MEMREF ||
9106179198Sjb			    subr == DIF_SUBR_TYPEREF)
9107179193Sjb				break;
9108179193Sjb
9109179193Sjb			err += efunc(pc, "invalid subr %u\n", subr);
9110179193Sjb			break;
9111179193Sjb
9112179193Sjb		default:
9113179193Sjb			err += efunc(pc, "invalid opcode %u\n",
9114179193Sjb			    DIF_INSTR_OP(instr));
9115179193Sjb		}
9116179193Sjb	}
9117179193Sjb
9118179193Sjb	return (err);
9119179193Sjb}
9120179193Sjb
9121179193Sjb/*
9122179193Sjb * Returns 1 if the expression in the DIF object can be cached on a per-thread
9123179193Sjb * basis; 0 if not.
9124179193Sjb */
9125179193Sjbstatic int
9126179193Sjbdtrace_difo_cacheable(dtrace_difo_t *dp)
9127179193Sjb{
9128179193Sjb	int i;
9129179193Sjb
9130179193Sjb	if (dp == NULL)
9131179193Sjb		return (0);
9132179193Sjb
9133179193Sjb	for (i = 0; i < dp->dtdo_varlen; i++) {
9134179193Sjb		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9135179193Sjb
9136179193Sjb		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9137179193Sjb			continue;
9138179193Sjb
9139179193Sjb		switch (v->dtdv_id) {
9140179193Sjb		case DIF_VAR_CURTHREAD:
9141179193Sjb		case DIF_VAR_PID:
9142179193Sjb		case DIF_VAR_TID:
9143179198Sjb		case DIF_VAR_EXECARGS:
9144179193Sjb		case DIF_VAR_EXECNAME:
9145179193Sjb		case DIF_VAR_ZONENAME:
9146179193Sjb			break;
9147179193Sjb
9148179193Sjb		default:
9149179193Sjb			return (0);
9150179193Sjb		}
9151179193Sjb	}
9152179193Sjb
9153179193Sjb	/*
9154179193Sjb	 * This DIF object may be cacheable.  Now we need to look for any
9155179193Sjb	 * array loading instructions, any memory loading instructions, or
9156179193Sjb	 * any stores to thread-local variables.
9157179193Sjb	 */
9158179193Sjb	for (i = 0; i < dp->dtdo_len; i++) {
9159179193Sjb		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9160179193Sjb
9161179193Sjb		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9162179193Sjb		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9163179193Sjb		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9164179193Sjb		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
9165179193Sjb			return (0);
9166179193Sjb	}
9167179193Sjb
9168179193Sjb	return (1);
9169179193Sjb}
9170179193Sjb
9171179193Sjbstatic void
9172179193Sjbdtrace_difo_hold(dtrace_difo_t *dp)
9173179193Sjb{
9174179193Sjb	int i;
9175179193Sjb
9176179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9177179193Sjb
9178179193Sjb	dp->dtdo_refcnt++;
9179179193Sjb	ASSERT(dp->dtdo_refcnt != 0);
9180179193Sjb
9181179193Sjb	/*
9182179193Sjb	 * We need to check this DIF object for references to the variable
9183179193Sjb	 * DIF_VAR_VTIMESTAMP.
9184179193Sjb	 */
9185179193Sjb	for (i = 0; i < dp->dtdo_varlen; i++) {
9186179193Sjb		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9187179193Sjb
9188179193Sjb		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9189179193Sjb			continue;
9190179193Sjb
9191179193Sjb		if (dtrace_vtime_references++ == 0)
9192179193Sjb			dtrace_vtime_enable();
9193179193Sjb	}
9194179193Sjb}
9195179193Sjb
9196179193Sjb/*
9197179193Sjb * This routine calculates the dynamic variable chunksize for a given DIF
9198179193Sjb * object.  The calculation is not fool-proof, and can probably be tricked by
9199179193Sjb * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9200179193Sjb * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9201179193Sjb * if a dynamic variable size exceeds the chunksize.
9202179193Sjb */
9203179193Sjbstatic void
9204179193Sjbdtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9205179193Sjb{
9206179198Sjb	uint64_t sval = 0;
9207179193Sjb	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9208179193Sjb	const dif_instr_t *text = dp->dtdo_buf;
9209179193Sjb	uint_t pc, srd = 0;
9210179193Sjb	uint_t ttop = 0;
9211179193Sjb	size_t size, ksize;
9212179193Sjb	uint_t id, i;
9213179193Sjb
9214179193Sjb	for (pc = 0; pc < dp->dtdo_len; pc++) {
9215179193Sjb		dif_instr_t instr = text[pc];
9216179193Sjb		uint_t op = DIF_INSTR_OP(instr);
9217179193Sjb		uint_t rd = DIF_INSTR_RD(instr);
9218179193Sjb		uint_t r1 = DIF_INSTR_R1(instr);
9219179193Sjb		uint_t nkeys = 0;
9220179198Sjb		uchar_t scope = 0;
9221179193Sjb
9222179193Sjb		dtrace_key_t *key = tupregs;
9223179193Sjb
9224179193Sjb		switch (op) {
9225179193Sjb		case DIF_OP_SETX:
9226179193Sjb			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9227179193Sjb			srd = rd;
9228179193Sjb			continue;
9229179193Sjb
9230179193Sjb		case DIF_OP_STTS:
9231179193Sjb			key = &tupregs[DIF_DTR_NREGS];
9232179193Sjb			key[0].dttk_size = 0;
9233179193Sjb			key[1].dttk_size = 0;
9234179193Sjb			nkeys = 2;
9235179193Sjb			scope = DIFV_SCOPE_THREAD;
9236179193Sjb			break;
9237179193Sjb
9238179193Sjb		case DIF_OP_STGAA:
9239179193Sjb		case DIF_OP_STTAA:
9240179193Sjb			nkeys = ttop;
9241179193Sjb
9242179193Sjb			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9243179193Sjb				key[nkeys++].dttk_size = 0;
9244179193Sjb
9245179193Sjb			key[nkeys++].dttk_size = 0;
9246179193Sjb
9247179193Sjb			if (op == DIF_OP_STTAA) {
9248179193Sjb				scope = DIFV_SCOPE_THREAD;
9249179193Sjb			} else {
9250179193Sjb				scope = DIFV_SCOPE_GLOBAL;
9251179193Sjb			}
9252179193Sjb
9253179193Sjb			break;
9254179193Sjb
9255179193Sjb		case DIF_OP_PUSHTR:
9256179193Sjb			if (ttop == DIF_DTR_NREGS)
9257179193Sjb				return;
9258179193Sjb
9259179193Sjb			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9260179193Sjb				/*
9261179193Sjb				 * If the register for the size of the "pushtr"
9262179193Sjb				 * is %r0 (or the value is 0) and the type is
9263179193Sjb				 * a string, we'll use the system-wide default
9264179193Sjb				 * string size.
9265179193Sjb				 */
9266179193Sjb				tupregs[ttop++].dttk_size =
9267179193Sjb				    dtrace_strsize_default;
9268179193Sjb			} else {
9269179193Sjb				if (srd == 0)
9270179193Sjb					return;
9271179193Sjb
9272179193Sjb				tupregs[ttop++].dttk_size = sval;
9273179193Sjb			}
9274179193Sjb
9275179193Sjb			break;
9276179193Sjb
9277179193Sjb		case DIF_OP_PUSHTV:
9278179193Sjb			if (ttop == DIF_DTR_NREGS)
9279179193Sjb				return;
9280179193Sjb
9281179193Sjb			tupregs[ttop++].dttk_size = 0;
9282179193Sjb			break;
9283179193Sjb
9284179193Sjb		case DIF_OP_FLUSHTS:
9285179193Sjb			ttop = 0;
9286179193Sjb			break;
9287179193Sjb
9288179193Sjb		case DIF_OP_POPTS:
9289179193Sjb			if (ttop != 0)
9290179193Sjb				ttop--;
9291179193Sjb			break;
9292179193Sjb		}
9293179193Sjb
9294179193Sjb		sval = 0;
9295179193Sjb		srd = 0;
9296179193Sjb
9297179193Sjb		if (nkeys == 0)
9298179193Sjb			continue;
9299179193Sjb
9300179193Sjb		/*
9301179193Sjb		 * We have a dynamic variable allocation; calculate its size.
9302179193Sjb		 */
9303179193Sjb		for (ksize = 0, i = 0; i < nkeys; i++)
9304179193Sjb			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9305179193Sjb
9306179193Sjb		size = sizeof (dtrace_dynvar_t);
9307179193Sjb		size += sizeof (dtrace_key_t) * (nkeys - 1);
9308179193Sjb		size += ksize;
9309179193Sjb
9310179193Sjb		/*
9311179193Sjb		 * Now we need to determine the size of the stored data.
9312179193Sjb		 */
9313179193Sjb		id = DIF_INSTR_VAR(instr);
9314179193Sjb
9315179193Sjb		for (i = 0; i < dp->dtdo_varlen; i++) {
9316179193Sjb			dtrace_difv_t *v = &dp->dtdo_vartab[i];
9317179193Sjb
9318179193Sjb			if (v->dtdv_id == id && v->dtdv_scope == scope) {
9319179193Sjb				size += v->dtdv_type.dtdt_size;
9320179193Sjb				break;
9321179193Sjb			}
9322179193Sjb		}
9323179193Sjb
9324179193Sjb		if (i == dp->dtdo_varlen)
9325179193Sjb			return;
9326179193Sjb
9327179193Sjb		/*
9328179193Sjb		 * We have the size.  If this is larger than the chunk size
9329179193Sjb		 * for our dynamic variable state, reset the chunk size.
9330179193Sjb		 */
9331179193Sjb		size = P2ROUNDUP(size, sizeof (uint64_t));
9332179193Sjb
9333179193Sjb		if (size > vstate->dtvs_dynvars.dtds_chunksize)
9334179193Sjb			vstate->dtvs_dynvars.dtds_chunksize = size;
9335179193Sjb	}
9336179193Sjb}
9337179193Sjb
9338179193Sjbstatic void
9339179193Sjbdtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9340179193Sjb{
9341179193Sjb	int i, oldsvars, osz, nsz, otlocals, ntlocals;
9342179193Sjb	uint_t id;
9343179193Sjb
9344179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9345179193Sjb	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9346179193Sjb
9347179193Sjb	for (i = 0; i < dp->dtdo_varlen; i++) {
9348179193Sjb		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9349179198Sjb		dtrace_statvar_t *svar, ***svarp = NULL;
9350179193Sjb		size_t dsize = 0;
9351179193Sjb		uint8_t scope = v->dtdv_scope;
9352179198Sjb		int *np = NULL;
9353179193Sjb
9354179193Sjb		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9355179193Sjb			continue;
9356179193Sjb
9357179193Sjb		id -= DIF_VAR_OTHER_UBASE;
9358179193Sjb
9359179193Sjb		switch (scope) {
9360179193Sjb		case DIFV_SCOPE_THREAD:
9361179193Sjb			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9362179193Sjb				dtrace_difv_t *tlocals;
9363179193Sjb
9364179193Sjb				if ((ntlocals = (otlocals << 1)) == 0)
9365179193Sjb					ntlocals = 1;
9366179193Sjb
9367179193Sjb				osz = otlocals * sizeof (dtrace_difv_t);
9368179193Sjb				nsz = ntlocals * sizeof (dtrace_difv_t);
9369179193Sjb
9370179193Sjb				tlocals = kmem_zalloc(nsz, KM_SLEEP);
9371179193Sjb
9372179193Sjb				if (osz != 0) {
9373179193Sjb					bcopy(vstate->dtvs_tlocals,
9374179193Sjb					    tlocals, osz);
9375179193Sjb					kmem_free(vstate->dtvs_tlocals, osz);
9376179193Sjb				}
9377179193Sjb
9378179193Sjb				vstate->dtvs_tlocals = tlocals;
9379179193Sjb				vstate->dtvs_ntlocals = ntlocals;
9380179193Sjb			}
9381179193Sjb
9382179193Sjb			vstate->dtvs_tlocals[id] = *v;
9383179193Sjb			continue;
9384179193Sjb
9385179193Sjb		case DIFV_SCOPE_LOCAL:
9386179193Sjb			np = &vstate->dtvs_nlocals;
9387179193Sjb			svarp = &vstate->dtvs_locals;
9388179193Sjb
9389179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9390179193Sjb				dsize = NCPU * (v->dtdv_type.dtdt_size +
9391179193Sjb				    sizeof (uint64_t));
9392179193Sjb			else
9393179193Sjb				dsize = NCPU * sizeof (uint64_t);
9394179193Sjb
9395179193Sjb			break;
9396179193Sjb
9397179193Sjb		case DIFV_SCOPE_GLOBAL:
9398179193Sjb			np = &vstate->dtvs_nglobals;
9399179193Sjb			svarp = &vstate->dtvs_globals;
9400179193Sjb
9401179193Sjb			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9402179193Sjb				dsize = v->dtdv_type.dtdt_size +
9403179193Sjb				    sizeof (uint64_t);
9404179193Sjb
9405179193Sjb			break;
9406179193Sjb
9407179193Sjb		default:
9408179193Sjb			ASSERT(0);
9409179193Sjb		}
9410179193Sjb
9411179193Sjb		while (id >= (oldsvars = *np)) {
9412179193Sjb			dtrace_statvar_t **statics;
9413179193Sjb			int newsvars, oldsize, newsize;
9414179193Sjb
9415179193Sjb			if ((newsvars = (oldsvars << 1)) == 0)
9416179193Sjb				newsvars = 1;
9417179193Sjb
9418179193Sjb			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9419179193Sjb			newsize = newsvars * sizeof (dtrace_statvar_t *);
9420179193Sjb
9421179193Sjb			statics = kmem_zalloc(newsize, KM_SLEEP);
9422179193Sjb
9423179193Sjb			if (oldsize != 0) {
9424179193Sjb				bcopy(*svarp, statics, oldsize);
9425179193Sjb				kmem_free(*svarp, oldsize);
9426179193Sjb			}
9427179193Sjb
9428179193Sjb			*svarp = statics;
9429179193Sjb			*np = newsvars;
9430179193Sjb		}
9431179193Sjb
9432179193Sjb		if ((svar = (*svarp)[id]) == NULL) {
9433179193Sjb			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9434179193Sjb			svar->dtsv_var = *v;
9435179193Sjb
9436179193Sjb			if ((svar->dtsv_size = dsize) != 0) {
9437179193Sjb				svar->dtsv_data = (uint64_t)(uintptr_t)
9438179193Sjb				    kmem_zalloc(dsize, KM_SLEEP);
9439179193Sjb			}
9440179193Sjb
9441179193Sjb			(*svarp)[id] = svar;
9442179193Sjb		}
9443179193Sjb
9444179193Sjb		svar->dtsv_refcnt++;
9445179193Sjb	}
9446179193Sjb
9447179193Sjb	dtrace_difo_chunksize(dp, vstate);
9448179193Sjb	dtrace_difo_hold(dp);
9449179193Sjb}
9450179193Sjb
9451179193Sjbstatic dtrace_difo_t *
9452179193Sjbdtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9453179193Sjb{
9454179193Sjb	dtrace_difo_t *new;
9455179193Sjb	size_t sz;
9456179193Sjb
9457179193Sjb	ASSERT(dp->dtdo_buf != NULL);
9458179193Sjb	ASSERT(dp->dtdo_refcnt != 0);
9459179193Sjb
9460179193Sjb	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9461179193Sjb
9462179193Sjb	ASSERT(dp->dtdo_buf != NULL);
9463179193Sjb	sz = dp->dtdo_len * sizeof (dif_instr_t);
9464179193Sjb	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9465179193Sjb	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9466179193Sjb	new->dtdo_len = dp->dtdo_len;
9467179193Sjb
9468179193Sjb	if (dp->dtdo_strtab != NULL) {
9469179193Sjb		ASSERT(dp->dtdo_strlen != 0);
9470179193Sjb		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9471179193Sjb		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9472179193Sjb		new->dtdo_strlen = dp->dtdo_strlen;
9473179193Sjb	}
9474179193Sjb
9475179193Sjb	if (dp->dtdo_inttab != NULL) {
9476179193Sjb		ASSERT(dp->dtdo_intlen != 0);
9477179193Sjb		sz = dp->dtdo_intlen * sizeof (uint64_t);
9478179193Sjb		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9479179193Sjb		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9480179193Sjb		new->dtdo_intlen = dp->dtdo_intlen;
9481179193Sjb	}
9482179193Sjb
9483179193Sjb	if (dp->dtdo_vartab != NULL) {
9484179193Sjb		ASSERT(dp->dtdo_varlen != 0);
9485179193Sjb		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9486179193Sjb		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9487179193Sjb		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9488179193Sjb		new->dtdo_varlen = dp->dtdo_varlen;
9489179193Sjb	}
9490179193Sjb
9491179193Sjb	dtrace_difo_init(new, vstate);
9492179193Sjb	return (new);
9493179193Sjb}
9494179193Sjb
9495179193Sjbstatic void
9496179193Sjbdtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9497179193Sjb{
9498179193Sjb	int i;
9499179193Sjb
9500179193Sjb	ASSERT(dp->dtdo_refcnt == 0);
9501179193Sjb
9502179193Sjb	for (i = 0; i < dp->dtdo_varlen; i++) {
9503179193Sjb		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9504179198Sjb		dtrace_statvar_t *svar, **svarp = NULL;
9505179193Sjb		uint_t id;
9506179193Sjb		uint8_t scope = v->dtdv_scope;
9507179198Sjb		int *np = NULL;
9508179193Sjb
9509179193Sjb		switch (scope) {
9510179193Sjb		case DIFV_SCOPE_THREAD:
9511179193Sjb			continue;
9512179193Sjb
9513179193Sjb		case DIFV_SCOPE_LOCAL:
9514179193Sjb			np = &vstate->dtvs_nlocals;
9515179193Sjb			svarp = vstate->dtvs_locals;
9516179193Sjb			break;
9517179193Sjb
9518179193Sjb		case DIFV_SCOPE_GLOBAL:
9519179193Sjb			np = &vstate->dtvs_nglobals;
9520179193Sjb			svarp = vstate->dtvs_globals;
9521179193Sjb			break;
9522179193Sjb
9523179193Sjb		default:
9524179193Sjb			ASSERT(0);
9525179193Sjb		}
9526179193Sjb
9527179193Sjb		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9528179193Sjb			continue;
9529179193Sjb
9530179193Sjb		id -= DIF_VAR_OTHER_UBASE;
9531179193Sjb		ASSERT(id < *np);
9532179193Sjb
9533179193Sjb		svar = svarp[id];
9534179193Sjb		ASSERT(svar != NULL);
9535179193Sjb		ASSERT(svar->dtsv_refcnt > 0);
9536179193Sjb
9537179193Sjb		if (--svar->dtsv_refcnt > 0)
9538179193Sjb			continue;
9539179193Sjb
9540179193Sjb		if (svar->dtsv_size != 0) {
9541179198Sjb			ASSERT(svar->dtsv_data != 0);
9542179193Sjb			kmem_free((void *)(uintptr_t)svar->dtsv_data,
9543179193Sjb			    svar->dtsv_size);
9544179193Sjb		}
9545179193Sjb
9546179193Sjb		kmem_free(svar, sizeof (dtrace_statvar_t));
9547179193Sjb		svarp[id] = NULL;
9548179193Sjb	}
9549179193Sjb
9550179198Sjb	if (dp->dtdo_buf != NULL)
9551179198Sjb		kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9552179198Sjb	if (dp->dtdo_inttab != NULL)
9553179198Sjb		kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9554179198Sjb	if (dp->dtdo_strtab != NULL)
9555179198Sjb		kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9556179198Sjb	if (dp->dtdo_vartab != NULL)
9557179198Sjb		kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9558179193Sjb
9559179193Sjb	kmem_free(dp, sizeof (dtrace_difo_t));
9560179193Sjb}
9561179193Sjb
9562179193Sjbstatic void
9563179193Sjbdtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9564179193Sjb{
9565179193Sjb	int i;
9566179193Sjb
9567179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9568179193Sjb	ASSERT(dp->dtdo_refcnt != 0);
9569179193Sjb
9570179193Sjb	for (i = 0; i < dp->dtdo_varlen; i++) {
9571179193Sjb		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9572179193Sjb
9573179193Sjb		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9574179193Sjb			continue;
9575179193Sjb
9576179193Sjb		ASSERT(dtrace_vtime_references > 0);
9577179193Sjb		if (--dtrace_vtime_references == 0)
9578179193Sjb			dtrace_vtime_disable();
9579179193Sjb	}
9580179193Sjb
9581179193Sjb	if (--dp->dtdo_refcnt == 0)
9582179193Sjb		dtrace_difo_destroy(dp, vstate);
9583179193Sjb}
9584179193Sjb
9585179193Sjb/*
9586179193Sjb * DTrace Format Functions
9587179193Sjb */
9588179193Sjbstatic uint16_t
9589179193Sjbdtrace_format_add(dtrace_state_t *state, char *str)
9590179193Sjb{
9591179193Sjb	char *fmt, **new;
9592179193Sjb	uint16_t ndx, len = strlen(str) + 1;
9593179193Sjb
9594179193Sjb	fmt = kmem_zalloc(len, KM_SLEEP);
9595179193Sjb	bcopy(str, fmt, len);
9596179193Sjb
9597179193Sjb	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9598179193Sjb		if (state->dts_formats[ndx] == NULL) {
9599179193Sjb			state->dts_formats[ndx] = fmt;
9600179193Sjb			return (ndx + 1);
9601179193Sjb		}
9602179193Sjb	}
9603179193Sjb
9604179193Sjb	if (state->dts_nformats == USHRT_MAX) {
9605179193Sjb		/*
9606179193Sjb		 * This is only likely if a denial-of-service attack is being
9607179193Sjb		 * attempted.  As such, it's okay to fail silently here.
9608179193Sjb		 */
9609179193Sjb		kmem_free(fmt, len);
9610179193Sjb		return (0);
9611179193Sjb	}
9612179193Sjb
9613179193Sjb	/*
9614179193Sjb	 * For simplicity, we always resize the formats array to be exactly the
9615179193Sjb	 * number of formats.
9616179193Sjb	 */
9617179193Sjb	ndx = state->dts_nformats++;
9618179193Sjb	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9619179193Sjb
9620179193Sjb	if (state->dts_formats != NULL) {
9621179193Sjb		ASSERT(ndx != 0);
9622179193Sjb		bcopy(state->dts_formats, new, ndx * sizeof (char *));
9623179193Sjb		kmem_free(state->dts_formats, ndx * sizeof (char *));
9624179193Sjb	}
9625179193Sjb
9626179193Sjb	state->dts_formats = new;
9627179193Sjb	state->dts_formats[ndx] = fmt;
9628179193Sjb
9629179193Sjb	return (ndx + 1);
9630179193Sjb}
9631179193Sjb
9632179193Sjbstatic void
9633179193Sjbdtrace_format_remove(dtrace_state_t *state, uint16_t format)
9634179193Sjb{
9635179193Sjb	char *fmt;
9636179193Sjb
9637179193Sjb	ASSERT(state->dts_formats != NULL);
9638179193Sjb	ASSERT(format <= state->dts_nformats);
9639179193Sjb	ASSERT(state->dts_formats[format - 1] != NULL);
9640179193Sjb
9641179193Sjb	fmt = state->dts_formats[format - 1];
9642179193Sjb	kmem_free(fmt, strlen(fmt) + 1);
9643179193Sjb	state->dts_formats[format - 1] = NULL;
9644179193Sjb}
9645179193Sjb
9646179193Sjbstatic void
9647179193Sjbdtrace_format_destroy(dtrace_state_t *state)
9648179193Sjb{
9649179193Sjb	int i;
9650179193Sjb
9651179193Sjb	if (state->dts_nformats == 0) {
9652179193Sjb		ASSERT(state->dts_formats == NULL);
9653179193Sjb		return;
9654179193Sjb	}
9655179193Sjb
9656179193Sjb	ASSERT(state->dts_formats != NULL);
9657179193Sjb
9658179193Sjb	for (i = 0; i < state->dts_nformats; i++) {
9659179193Sjb		char *fmt = state->dts_formats[i];
9660179193Sjb
9661179193Sjb		if (fmt == NULL)
9662179193Sjb			continue;
9663179193Sjb
9664179193Sjb		kmem_free(fmt, strlen(fmt) + 1);
9665179193Sjb	}
9666179193Sjb
9667179193Sjb	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9668179193Sjb	state->dts_nformats = 0;
9669179193Sjb	state->dts_formats = NULL;
9670179193Sjb}
9671179193Sjb
9672179193Sjb/*
9673179193Sjb * DTrace Predicate Functions
9674179193Sjb */
9675179193Sjbstatic dtrace_predicate_t *
9676179193Sjbdtrace_predicate_create(dtrace_difo_t *dp)
9677179193Sjb{
9678179193Sjb	dtrace_predicate_t *pred;
9679179193Sjb
9680179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9681179193Sjb	ASSERT(dp->dtdo_refcnt != 0);
9682179193Sjb
9683179193Sjb	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9684179193Sjb	pred->dtp_difo = dp;
9685179193Sjb	pred->dtp_refcnt = 1;
9686179193Sjb
9687179193Sjb	if (!dtrace_difo_cacheable(dp))
9688179193Sjb		return (pred);
9689179193Sjb
9690179193Sjb	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9691179193Sjb		/*
9692179193Sjb		 * This is only theoretically possible -- we have had 2^32
9693179193Sjb		 * cacheable predicates on this machine.  We cannot allow any
9694179193Sjb		 * more predicates to become cacheable:  as unlikely as it is,
9695179193Sjb		 * there may be a thread caching a (now stale) predicate cache
9696179193Sjb		 * ID. (N.B.: the temptation is being successfully resisted to
9697179193Sjb		 * have this cmn_err() "Holy shit -- we executed this code!")
9698179193Sjb		 */
9699179193Sjb		return (pred);
9700179193Sjb	}
9701179193Sjb
9702179193Sjb	pred->dtp_cacheid = dtrace_predcache_id++;
9703179193Sjb
9704179193Sjb	return (pred);
9705179193Sjb}
9706179193Sjb
9707179193Sjbstatic void
9708179193Sjbdtrace_predicate_hold(dtrace_predicate_t *pred)
9709179193Sjb{
9710179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9711179193Sjb	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9712179193Sjb	ASSERT(pred->dtp_refcnt > 0);
9713179193Sjb
9714179193Sjb	pred->dtp_refcnt++;
9715179193Sjb}
9716179193Sjb
9717179193Sjbstatic void
9718179193Sjbdtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9719179193Sjb{
9720179193Sjb	dtrace_difo_t *dp = pred->dtp_difo;
9721179193Sjb
9722179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9723179193Sjb	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9724179193Sjb	ASSERT(pred->dtp_refcnt > 0);
9725179193Sjb
9726179193Sjb	if (--pred->dtp_refcnt == 0) {
9727179193Sjb		dtrace_difo_release(pred->dtp_difo, vstate);
9728179193Sjb		kmem_free(pred, sizeof (dtrace_predicate_t));
9729179193Sjb	}
9730179193Sjb}
9731179193Sjb
9732179193Sjb/*
9733179193Sjb * DTrace Action Description Functions
9734179193Sjb */
9735179193Sjbstatic dtrace_actdesc_t *
9736179193Sjbdtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9737179193Sjb    uint64_t uarg, uint64_t arg)
9738179193Sjb{
9739179193Sjb	dtrace_actdesc_t *act;
9740179193Sjb
9741179198Sjb#if defined(sun)
9742179193Sjb	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9743179193Sjb	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
9744179198Sjb#endif
9745179193Sjb
9746179193Sjb	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9747179193Sjb	act->dtad_kind = kind;
9748179193Sjb	act->dtad_ntuple = ntuple;
9749179193Sjb	act->dtad_uarg = uarg;
9750179193Sjb	act->dtad_arg = arg;
9751179193Sjb	act->dtad_refcnt = 1;
9752179193Sjb
9753179193Sjb	return (act);
9754179193Sjb}
9755179193Sjb
9756179193Sjbstatic void
9757179193Sjbdtrace_actdesc_hold(dtrace_actdesc_t *act)
9758179193Sjb{
9759179193Sjb	ASSERT(act->dtad_refcnt >= 1);
9760179193Sjb	act->dtad_refcnt++;
9761179193Sjb}
9762179193Sjb
9763179193Sjbstatic void
9764179193Sjbdtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9765179193Sjb{
9766179193Sjb	dtrace_actkind_t kind = act->dtad_kind;
9767179193Sjb	dtrace_difo_t *dp;
9768179193Sjb
9769179193Sjb	ASSERT(act->dtad_refcnt >= 1);
9770179193Sjb
9771179193Sjb	if (--act->dtad_refcnt != 0)
9772179193Sjb		return;
9773179193Sjb
9774179193Sjb	if ((dp = act->dtad_difo) != NULL)
9775179193Sjb		dtrace_difo_release(dp, vstate);
9776179193Sjb
9777179193Sjb	if (DTRACEACT_ISPRINTFLIKE(kind)) {
9778179193Sjb		char *str = (char *)(uintptr_t)act->dtad_arg;
9779179193Sjb
9780179198Sjb#if defined(sun)
9781179193Sjb		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9782179193Sjb		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9783179198Sjb#endif
9784179193Sjb
9785179193Sjb		if (str != NULL)
9786179193Sjb			kmem_free(str, strlen(str) + 1);
9787179193Sjb	}
9788179193Sjb
9789179193Sjb	kmem_free(act, sizeof (dtrace_actdesc_t));
9790179193Sjb}
9791179193Sjb
9792179193Sjb/*
9793179193Sjb * DTrace ECB Functions
9794179193Sjb */
9795179193Sjbstatic dtrace_ecb_t *
9796179193Sjbdtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9797179193Sjb{
9798179193Sjb	dtrace_ecb_t *ecb;
9799179193Sjb	dtrace_epid_t epid;
9800179193Sjb
9801179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9802179193Sjb
9803179193Sjb	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9804179193Sjb	ecb->dte_predicate = NULL;
9805179193Sjb	ecb->dte_probe = probe;
9806179193Sjb
9807179193Sjb	/*
9808179193Sjb	 * The default size is the size of the default action: recording
9809256002Spfg	 * the header.
9810179193Sjb	 */
9811256002Spfg	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
9812179193Sjb	ecb->dte_alignment = sizeof (dtrace_epid_t);
9813179193Sjb
9814179193Sjb	epid = state->dts_epid++;
9815179193Sjb
9816179193Sjb	if (epid - 1 >= state->dts_necbs) {
9817179193Sjb		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9818179193Sjb		int necbs = state->dts_necbs << 1;
9819179193Sjb
9820179193Sjb		ASSERT(epid == state->dts_necbs + 1);
9821179193Sjb
9822179193Sjb		if (necbs == 0) {
9823179193Sjb			ASSERT(oecbs == NULL);
9824179193Sjb			necbs = 1;
9825179193Sjb		}
9826179193Sjb
9827179193Sjb		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9828179193Sjb
9829179193Sjb		if (oecbs != NULL)
9830179193Sjb			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9831179193Sjb
9832179193Sjb		dtrace_membar_producer();
9833179193Sjb		state->dts_ecbs = ecbs;
9834179193Sjb
9835179193Sjb		if (oecbs != NULL) {
9836179193Sjb			/*
9837179193Sjb			 * If this state is active, we must dtrace_sync()
9838179193Sjb			 * before we can free the old dts_ecbs array:  we're
9839179193Sjb			 * coming in hot, and there may be active ring
9840179193Sjb			 * buffer processing (which indexes into the dts_ecbs
9841179193Sjb			 * array) on another CPU.
9842179193Sjb			 */
9843179193Sjb			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9844179193Sjb				dtrace_sync();
9845179193Sjb
9846179193Sjb			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9847179193Sjb		}
9848179193Sjb
9849179193Sjb		dtrace_membar_producer();
9850179193Sjb		state->dts_necbs = necbs;
9851179193Sjb	}
9852179193Sjb
9853179193Sjb	ecb->dte_state = state;
9854179193Sjb
9855179193Sjb	ASSERT(state->dts_ecbs[epid - 1] == NULL);
9856179193Sjb	dtrace_membar_producer();
9857179193Sjb	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9858179193Sjb
9859179193Sjb	return (ecb);
9860179193Sjb}
9861179193Sjb
9862179193Sjbstatic void
9863179193Sjbdtrace_ecb_enable(dtrace_ecb_t *ecb)
9864179193Sjb{
9865179193Sjb	dtrace_probe_t *probe = ecb->dte_probe;
9866179193Sjb
9867179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
9868179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
9869179193Sjb	ASSERT(ecb->dte_next == NULL);
9870179193Sjb
9871179193Sjb	if (probe == NULL) {
9872179193Sjb		/*
9873179193Sjb		 * This is the NULL probe -- there's nothing to do.
9874179193Sjb		 */
9875179193Sjb		return;
9876179193Sjb	}
9877179193Sjb
9878179193Sjb	if (probe->dtpr_ecb == NULL) {
9879179193Sjb		dtrace_provider_t *prov = probe->dtpr_provider;
9880179193Sjb
9881179193Sjb		/*
9882179193Sjb		 * We're the first ECB on this probe.
9883179193Sjb		 */
9884179193Sjb		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9885179193Sjb
9886179193Sjb		if (ecb->dte_predicate != NULL)
9887179193Sjb			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9888179193Sjb
9889179193Sjb		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9890179193Sjb		    probe->dtpr_id, probe->dtpr_arg);
9891179193Sjb	} else {
9892179193Sjb		/*
9893179193Sjb		 * This probe is already active.  Swing the last pointer to
9894179193Sjb		 * point to the new ECB, and issue a dtrace_sync() to assure
9895179193Sjb		 * that all CPUs have seen the change.
9896179193Sjb		 */
9897179193Sjb		ASSERT(probe->dtpr_ecb_last != NULL);
9898179193Sjb		probe->dtpr_ecb_last->dte_next = ecb;
9899179193Sjb		probe->dtpr_ecb_last = ecb;
9900179193Sjb		probe->dtpr_predcache = 0;
9901179193Sjb
9902179193Sjb		dtrace_sync();
9903179193Sjb	}
9904179193Sjb}
9905179193Sjb
9906179193Sjbstatic void
9907179193Sjbdtrace_ecb_resize(dtrace_ecb_t *ecb)
9908179193Sjb{
9909179193Sjb	dtrace_action_t *act;
9910256002Spfg	uint32_t curneeded = UINT32_MAX;
9911179193Sjb	uint32_t aggbase = UINT32_MAX;
9912179193Sjb
9913179193Sjb	/*
9914256002Spfg	 * If we record anything, we always record the dtrace_rechdr_t.  (And
9915256002Spfg	 * we always record it first.)
9916179193Sjb	 */
9917256002Spfg	ecb->dte_size = sizeof (dtrace_rechdr_t);
9918256002Spfg	ecb->dte_alignment = sizeof (dtrace_epid_t);
9919179193Sjb
9920179193Sjb	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9921179193Sjb		dtrace_recdesc_t *rec = &act->dta_rec;
9922256002Spfg		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
9923179193Sjb
9924256002Spfg		ecb->dte_alignment = MAX(ecb->dte_alignment,
9925256002Spfg		    rec->dtrd_alignment);
9926179193Sjb
9927179193Sjb		if (DTRACEACT_ISAGG(act->dta_kind)) {
9928179193Sjb			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9929179193Sjb
9930256002Spfg			ASSERT(rec->dtrd_size != 0);
9931256002Spfg			ASSERT(agg->dtag_first != NULL);
9932256002Spfg			ASSERT(act->dta_prev->dta_intuple);
9933179193Sjb			ASSERT(aggbase != UINT32_MAX);
9934256002Spfg			ASSERT(curneeded != UINT32_MAX);
9935179193Sjb
9936179193Sjb			agg->dtag_base = aggbase;
9937179193Sjb
9938256002Spfg			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9939256002Spfg			rec->dtrd_offset = curneeded;
9940256002Spfg			curneeded += rec->dtrd_size;
9941256002Spfg			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
9942179193Sjb
9943256002Spfg			aggbase = UINT32_MAX;
9944256002Spfg			curneeded = UINT32_MAX;
9945256002Spfg		} else if (act->dta_intuple) {
9946256002Spfg			if (curneeded == UINT32_MAX) {
9947256002Spfg				/*
9948256002Spfg				 * This is the first record in a tuple.  Align
9949256002Spfg				 * curneeded to be at offset 4 in an 8-byte
9950256002Spfg				 * aligned block.
9951256002Spfg				 */
9952256002Spfg				ASSERT(act->dta_prev == NULL ||
9953256002Spfg				    !act->dta_prev->dta_intuple);
9954256002Spfg				ASSERT3U(aggbase, ==, UINT32_MAX);
9955256002Spfg				curneeded = P2PHASEUP(ecb->dte_size,
9956256002Spfg				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
9957256002Spfg
9958256002Spfg				aggbase = curneeded - sizeof (dtrace_aggid_t);
9959256002Spfg				ASSERT(IS_P2ALIGNED(aggbase,
9960256002Spfg				    sizeof (uint64_t)));
9961179193Sjb			}
9962256002Spfg			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
9963256002Spfg			rec->dtrd_offset = curneeded;
9964256002Spfg			curneeded += rec->dtrd_size;
9965179193Sjb		} else {
9966256002Spfg			/* tuples must be followed by an aggregation */
9967256002Spfg			ASSERT(act->dta_prev == NULL ||
9968256002Spfg			    !act->dta_prev->dta_intuple);
9969179193Sjb
9970256002Spfg			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
9971256002Spfg			    rec->dtrd_alignment);
9972256002Spfg			rec->dtrd_offset = ecb->dte_size;
9973256002Spfg			ecb->dte_size += rec->dtrd_size;
9974256002Spfg			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
9975179193Sjb		}
9976179193Sjb	}
9977179193Sjb
9978179193Sjb	if ((act = ecb->dte_action) != NULL &&
9979179193Sjb	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9980256002Spfg	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
9981179193Sjb		/*
9982256002Spfg		 * If the size is still sizeof (dtrace_rechdr_t), then all
9983179193Sjb		 * actions store no data; set the size to 0.
9984179193Sjb		 */
9985179193Sjb		ecb->dte_size = 0;
9986179193Sjb	}
9987179193Sjb
9988256002Spfg	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
9989256002Spfg	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
9990256002Spfg	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
9991256002Spfg	    ecb->dte_needed);
9992179193Sjb}
9993179193Sjb
9994179193Sjbstatic dtrace_action_t *
9995179193Sjbdtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9996179193Sjb{
9997179193Sjb	dtrace_aggregation_t *agg;
9998179193Sjb	size_t size = sizeof (uint64_t);
9999179193Sjb	int ntuple = desc->dtad_ntuple;
10000179193Sjb	dtrace_action_t *act;
10001179193Sjb	dtrace_recdesc_t *frec;
10002179193Sjb	dtrace_aggid_t aggid;
10003179193Sjb	dtrace_state_t *state = ecb->dte_state;
10004179193Sjb
10005179193Sjb	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10006179193Sjb	agg->dtag_ecb = ecb;
10007179193Sjb
10008179193Sjb	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10009179193Sjb
10010179193Sjb	switch (desc->dtad_kind) {
10011179193Sjb	case DTRACEAGG_MIN:
10012179193Sjb		agg->dtag_initial = INT64_MAX;
10013179193Sjb		agg->dtag_aggregate = dtrace_aggregate_min;
10014179193Sjb		break;
10015179193Sjb
10016179193Sjb	case DTRACEAGG_MAX:
10017179193Sjb		agg->dtag_initial = INT64_MIN;
10018179193Sjb		agg->dtag_aggregate = dtrace_aggregate_max;
10019179193Sjb		break;
10020179193Sjb
10021179193Sjb	case DTRACEAGG_COUNT:
10022179193Sjb		agg->dtag_aggregate = dtrace_aggregate_count;
10023179193Sjb		break;
10024179193Sjb
10025179193Sjb	case DTRACEAGG_QUANTIZE:
10026179193Sjb		agg->dtag_aggregate = dtrace_aggregate_quantize;
10027179193Sjb		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10028179193Sjb		    sizeof (uint64_t);
10029179193Sjb		break;
10030179193Sjb
10031179193Sjb	case DTRACEAGG_LQUANTIZE: {
10032179193Sjb		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10033179193Sjb		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10034179193Sjb
10035179193Sjb		agg->dtag_initial = desc->dtad_arg;
10036179193Sjb		agg->dtag_aggregate = dtrace_aggregate_lquantize;
10037179193Sjb
10038179193Sjb		if (step == 0 || levels == 0)
10039179193Sjb			goto err;
10040179193Sjb
10041179193Sjb		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10042179193Sjb		break;
10043179193Sjb	}
10044179193Sjb
10045237870Spfg	case DTRACEAGG_LLQUANTIZE: {
10046237870Spfg		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10047237870Spfg		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10048237870Spfg		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10049237870Spfg		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10050237870Spfg		int64_t v;
10051237870Spfg
10052237870Spfg		agg->dtag_initial = desc->dtad_arg;
10053237870Spfg		agg->dtag_aggregate = dtrace_aggregate_llquantize;
10054237870Spfg
10055237870Spfg		if (factor < 2 || low >= high || nsteps < factor)
10056237870Spfg			goto err;
10057237870Spfg
10058237870Spfg		/*
10059237870Spfg		 * Now check that the number of steps evenly divides a power
10060237870Spfg		 * of the factor.  (This assures both integer bucket size and
10061237870Spfg		 * linearity within each magnitude.)
10062237870Spfg		 */
10063237870Spfg		for (v = factor; v < nsteps; v *= factor)
10064237870Spfg			continue;
10065237870Spfg
10066237870Spfg		if ((v % nsteps) || (nsteps % factor))
10067237870Spfg			goto err;
10068237870Spfg
10069237870Spfg		size = (dtrace_aggregate_llquantize_bucket(factor,
10070237870Spfg		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10071237870Spfg		break;
10072237870Spfg	}
10073237870Spfg
10074179193Sjb	case DTRACEAGG_AVG:
10075179193Sjb		agg->dtag_aggregate = dtrace_aggregate_avg;
10076179193Sjb		size = sizeof (uint64_t) * 2;
10077179193Sjb		break;
10078179193Sjb
10079179193Sjb	case DTRACEAGG_STDDEV:
10080179193Sjb		agg->dtag_aggregate = dtrace_aggregate_stddev;
10081179193Sjb		size = sizeof (uint64_t) * 4;
10082179193Sjb		break;
10083179193Sjb
10084179193Sjb	case DTRACEAGG_SUM:
10085179193Sjb		agg->dtag_aggregate = dtrace_aggregate_sum;
10086179193Sjb		break;
10087179193Sjb
10088179193Sjb	default:
10089179193Sjb		goto err;
10090179193Sjb	}
10091179193Sjb
10092179193Sjb	agg->dtag_action.dta_rec.dtrd_size = size;
10093179193Sjb
10094179193Sjb	if (ntuple == 0)
10095179193Sjb		goto err;
10096179193Sjb
10097179193Sjb	/*
10098179193Sjb	 * We must make sure that we have enough actions for the n-tuple.
10099179193Sjb	 */
10100179193Sjb	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10101179193Sjb		if (DTRACEACT_ISAGG(act->dta_kind))
10102179193Sjb			break;
10103179193Sjb
10104179193Sjb		if (--ntuple == 0) {
10105179193Sjb			/*
10106179193Sjb			 * This is the action with which our n-tuple begins.
10107179193Sjb			 */
10108179193Sjb			agg->dtag_first = act;
10109179193Sjb			goto success;
10110179193Sjb		}
10111179193Sjb	}
10112179193Sjb
10113179193Sjb	/*
10114179193Sjb	 * This n-tuple is short by ntuple elements.  Return failure.
10115179193Sjb	 */
10116179193Sjb	ASSERT(ntuple != 0);
10117179193Sjberr:
10118179193Sjb	kmem_free(agg, sizeof (dtrace_aggregation_t));
10119179193Sjb	return (NULL);
10120179193Sjb
10121179193Sjbsuccess:
10122179193Sjb	/*
10123179193Sjb	 * If the last action in the tuple has a size of zero, it's actually
10124179193Sjb	 * an expression argument for the aggregating action.
10125179193Sjb	 */
10126179193Sjb	ASSERT(ecb->dte_action_last != NULL);
10127179193Sjb	act = ecb->dte_action_last;
10128179193Sjb
10129179193Sjb	if (act->dta_kind == DTRACEACT_DIFEXPR) {
10130179193Sjb		ASSERT(act->dta_difo != NULL);
10131179193Sjb
10132179193Sjb		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10133179193Sjb			agg->dtag_hasarg = 1;
10134179193Sjb	}
10135179193Sjb
10136179193Sjb	/*
10137179193Sjb	 * We need to allocate an id for this aggregation.
10138179193Sjb	 */
10139179198Sjb#if defined(sun)
10140179193Sjb	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10141179193Sjb	    VM_BESTFIT | VM_SLEEP);
10142179198Sjb#else
10143179198Sjb	aggid = alloc_unr(state->dts_aggid_arena);
10144179198Sjb#endif
10145179193Sjb
10146179193Sjb	if (aggid - 1 >= state->dts_naggregations) {
10147179193Sjb		dtrace_aggregation_t **oaggs = state->dts_aggregations;
10148179193Sjb		dtrace_aggregation_t **aggs;
10149179193Sjb		int naggs = state->dts_naggregations << 1;
10150179193Sjb		int onaggs = state->dts_naggregations;
10151179193Sjb
10152179193Sjb		ASSERT(aggid == state->dts_naggregations + 1);
10153179193Sjb
10154179193Sjb		if (naggs == 0) {
10155179193Sjb			ASSERT(oaggs == NULL);
10156179193Sjb			naggs = 1;
10157179193Sjb		}
10158179193Sjb
10159179193Sjb		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10160179193Sjb
10161179193Sjb		if (oaggs != NULL) {
10162179193Sjb			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10163179193Sjb			kmem_free(oaggs, onaggs * sizeof (*aggs));
10164179193Sjb		}
10165179193Sjb
10166179193Sjb		state->dts_aggregations = aggs;
10167179193Sjb		state->dts_naggregations = naggs;
10168179193Sjb	}
10169179193Sjb
10170179193Sjb	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10171179193Sjb	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10172179193Sjb
10173179193Sjb	frec = &agg->dtag_first->dta_rec;
10174179193Sjb	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10175179193Sjb		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10176179193Sjb
10177179193Sjb	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10178179193Sjb		ASSERT(!act->dta_intuple);
10179179193Sjb		act->dta_intuple = 1;
10180179193Sjb	}
10181179193Sjb
10182179193Sjb	return (&agg->dtag_action);
10183179193Sjb}
10184179193Sjb
10185179193Sjbstatic void
10186179193Sjbdtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10187179193Sjb{
10188179193Sjb	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10189179193Sjb	dtrace_state_t *state = ecb->dte_state;
10190179193Sjb	dtrace_aggid_t aggid = agg->dtag_id;
10191179193Sjb
10192179193Sjb	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10193179198Sjb#if defined(sun)
10194179193Sjb	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10195179198Sjb#else
10196179198Sjb	free_unr(state->dts_aggid_arena, aggid);
10197179198Sjb#endif
10198179193Sjb
10199179193Sjb	ASSERT(state->dts_aggregations[aggid - 1] == agg);
10200179193Sjb	state->dts_aggregations[aggid - 1] = NULL;
10201179193Sjb
10202179193Sjb	kmem_free(agg, sizeof (dtrace_aggregation_t));
10203179193Sjb}
10204179193Sjb
10205179193Sjbstatic int
10206179193Sjbdtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10207179193Sjb{
10208179193Sjb	dtrace_action_t *action, *last;
10209179193Sjb	dtrace_difo_t *dp = desc->dtad_difo;
10210179193Sjb	uint32_t size = 0, align = sizeof (uint8_t), mask;
10211179193Sjb	uint16_t format = 0;
10212179193Sjb	dtrace_recdesc_t *rec;
10213179193Sjb	dtrace_state_t *state = ecb->dte_state;
10214179198Sjb	dtrace_optval_t *opt = state->dts_options, nframes = 0, strsize;
10215179193Sjb	uint64_t arg = desc->dtad_arg;
10216179193Sjb
10217179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10218179193Sjb	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10219179193Sjb
10220179193Sjb	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10221179193Sjb		/*
10222179193Sjb		 * If this is an aggregating action, there must be neither
10223179193Sjb		 * a speculate nor a commit on the action chain.
10224179193Sjb		 */
10225179193Sjb		dtrace_action_t *act;
10226179193Sjb
10227179193Sjb		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10228179193Sjb			if (act->dta_kind == DTRACEACT_COMMIT)
10229179193Sjb				return (EINVAL);
10230179193Sjb
10231179193Sjb			if (act->dta_kind == DTRACEACT_SPECULATE)
10232179193Sjb				return (EINVAL);
10233179193Sjb		}
10234179193Sjb
10235179193Sjb		action = dtrace_ecb_aggregation_create(ecb, desc);
10236179193Sjb
10237179193Sjb		if (action == NULL)
10238179193Sjb			return (EINVAL);
10239179193Sjb	} else {
10240179193Sjb		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10241179193Sjb		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10242179193Sjb		    dp != NULL && dp->dtdo_destructive)) {
10243179193Sjb			state->dts_destructive = 1;
10244179193Sjb		}
10245179193Sjb
10246179193Sjb		switch (desc->dtad_kind) {
10247179193Sjb		case DTRACEACT_PRINTF:
10248179193Sjb		case DTRACEACT_PRINTA:
10249179193Sjb		case DTRACEACT_SYSTEM:
10250179193Sjb		case DTRACEACT_FREOPEN:
10251249856Spfg		case DTRACEACT_DIFEXPR:
10252179193Sjb			/*
10253179193Sjb			 * We know that our arg is a string -- turn it into a
10254179193Sjb			 * format.
10255179193Sjb			 */
10256179198Sjb			if (arg == 0) {
10257249856Spfg				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10258249856Spfg				    desc->dtad_kind == DTRACEACT_DIFEXPR);
10259179193Sjb				format = 0;
10260179193Sjb			} else {
10261179198Sjb				ASSERT(arg != 0);
10262179198Sjb#if defined(sun)
10263179193Sjb				ASSERT(arg > KERNELBASE);
10264179198Sjb#endif
10265179193Sjb				format = dtrace_format_add(state,
10266179193Sjb				    (char *)(uintptr_t)arg);
10267179193Sjb			}
10268179193Sjb
10269179193Sjb			/*FALLTHROUGH*/
10270179193Sjb		case DTRACEACT_LIBACT:
10271249856Spfg		case DTRACEACT_TRACEMEM:
10272249856Spfg		case DTRACEACT_TRACEMEM_DYNSIZE:
10273179193Sjb			if (dp == NULL)
10274179193Sjb				return (EINVAL);
10275179193Sjb
10276179193Sjb			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10277179193Sjb				break;
10278179193Sjb
10279179193Sjb			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10280179193Sjb				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10281179193Sjb					return (EINVAL);
10282179193Sjb
10283179193Sjb				size = opt[DTRACEOPT_STRSIZE];
10284179193Sjb			}
10285179193Sjb
10286179193Sjb			break;
10287179193Sjb
10288179193Sjb		case DTRACEACT_STACK:
10289179193Sjb			if ((nframes = arg) == 0) {
10290179193Sjb				nframes = opt[DTRACEOPT_STACKFRAMES];
10291179193Sjb				ASSERT(nframes > 0);
10292179193Sjb				arg = nframes;
10293179193Sjb			}
10294179193Sjb
10295179193Sjb			size = nframes * sizeof (pc_t);
10296179193Sjb			break;
10297179193Sjb
10298179193Sjb		case DTRACEACT_JSTACK:
10299179193Sjb			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10300179193Sjb				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10301179193Sjb
10302179193Sjb			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10303179193Sjb				nframes = opt[DTRACEOPT_JSTACKFRAMES];
10304179193Sjb
10305179193Sjb			arg = DTRACE_USTACK_ARG(nframes, strsize);
10306179193Sjb
10307179193Sjb			/*FALLTHROUGH*/
10308179193Sjb		case DTRACEACT_USTACK:
10309179193Sjb			if (desc->dtad_kind != DTRACEACT_JSTACK &&
10310179193Sjb			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10311179193Sjb				strsize = DTRACE_USTACK_STRSIZE(arg);
10312179193Sjb				nframes = opt[DTRACEOPT_USTACKFRAMES];
10313179193Sjb				ASSERT(nframes > 0);
10314179193Sjb				arg = DTRACE_USTACK_ARG(nframes, strsize);
10315179193Sjb			}
10316179193Sjb
10317179193Sjb			/*
10318179193Sjb			 * Save a slot for the pid.
10319179193Sjb			 */
10320179193Sjb			size = (nframes + 1) * sizeof (uint64_t);
10321179193Sjb			size += DTRACE_USTACK_STRSIZE(arg);
10322179193Sjb			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10323179193Sjb
10324179193Sjb			break;
10325179193Sjb
10326179193Sjb		case DTRACEACT_SYM:
10327179193Sjb		case DTRACEACT_MOD:
10328179193Sjb			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10329179193Sjb			    sizeof (uint64_t)) ||
10330179193Sjb			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10331179193Sjb				return (EINVAL);
10332179193Sjb			break;
10333179193Sjb
10334179193Sjb		case DTRACEACT_USYM:
10335179193Sjb		case DTRACEACT_UMOD:
10336179193Sjb		case DTRACEACT_UADDR:
10337179193Sjb			if (dp == NULL ||
10338179193Sjb			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10339179193Sjb			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10340179193Sjb				return (EINVAL);
10341179193Sjb
10342179193Sjb			/*
10343179193Sjb			 * We have a slot for the pid, plus a slot for the
10344179193Sjb			 * argument.  To keep things simple (aligned with
10345179193Sjb			 * bitness-neutral sizing), we store each as a 64-bit
10346179193Sjb			 * quantity.
10347179193Sjb			 */
10348179193Sjb			size = 2 * sizeof (uint64_t);
10349179193Sjb			break;
10350179193Sjb
10351179193Sjb		case DTRACEACT_STOP:
10352179193Sjb		case DTRACEACT_BREAKPOINT:
10353179193Sjb		case DTRACEACT_PANIC:
10354179193Sjb			break;
10355179193Sjb
10356179193Sjb		case DTRACEACT_CHILL:
10357179193Sjb		case DTRACEACT_DISCARD:
10358179193Sjb		case DTRACEACT_RAISE:
10359179193Sjb			if (dp == NULL)
10360179193Sjb				return (EINVAL);
10361179193Sjb			break;
10362179193Sjb
10363179193Sjb		case DTRACEACT_EXIT:
10364179193Sjb			if (dp == NULL ||
10365179193Sjb			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10366179193Sjb			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10367179193Sjb				return (EINVAL);
10368179193Sjb			break;
10369179193Sjb
10370179193Sjb		case DTRACEACT_SPECULATE:
10371256002Spfg			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10372179193Sjb				return (EINVAL);
10373179193Sjb
10374179193Sjb			if (dp == NULL)
10375179193Sjb				return (EINVAL);
10376179193Sjb
10377179193Sjb			state->dts_speculates = 1;
10378179193Sjb			break;
10379179193Sjb
10380179198Sjb		case DTRACEACT_PRINTM:
10381179198Sjb		    	size = dp->dtdo_rtype.dtdt_size;
10382179198Sjb			break;
10383179198Sjb
10384179198Sjb		case DTRACEACT_PRINTT:
10385179198Sjb		    	size = dp->dtdo_rtype.dtdt_size;
10386179198Sjb			break;
10387179198Sjb
10388179193Sjb		case DTRACEACT_COMMIT: {
10389179193Sjb			dtrace_action_t *act = ecb->dte_action;
10390179193Sjb
10391179193Sjb			for (; act != NULL; act = act->dta_next) {
10392179193Sjb				if (act->dta_kind == DTRACEACT_COMMIT)
10393179193Sjb					return (EINVAL);
10394179193Sjb			}
10395179193Sjb
10396179193Sjb			if (dp == NULL)
10397179193Sjb				return (EINVAL);
10398179193Sjb			break;
10399179193Sjb		}
10400179193Sjb
10401179193Sjb		default:
10402179193Sjb			return (EINVAL);
10403179193Sjb		}
10404179193Sjb
10405179193Sjb		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10406179193Sjb			/*
10407179193Sjb			 * If this is a data-storing action or a speculate,
10408179193Sjb			 * we must be sure that there isn't a commit on the
10409179193Sjb			 * action chain.
10410179193Sjb			 */
10411179193Sjb			dtrace_action_t *act = ecb->dte_action;
10412179193Sjb
10413179193Sjb			for (; act != NULL; act = act->dta_next) {
10414179193Sjb				if (act->dta_kind == DTRACEACT_COMMIT)
10415179193Sjb					return (EINVAL);
10416179193Sjb			}
10417179193Sjb		}
10418179193Sjb
10419179193Sjb		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10420179193Sjb		action->dta_rec.dtrd_size = size;
10421179193Sjb	}
10422179193Sjb
10423179193Sjb	action->dta_refcnt = 1;
10424179193Sjb	rec = &action->dta_rec;
10425179193Sjb	size = rec->dtrd_size;
10426179193Sjb
10427179193Sjb	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10428179193Sjb		if (!(size & mask)) {
10429179193Sjb			align = mask + 1;
10430179193Sjb			break;
10431179193Sjb		}
10432179193Sjb	}
10433179193Sjb
10434179193Sjb	action->dta_kind = desc->dtad_kind;
10435179193Sjb
10436179193Sjb	if ((action->dta_difo = dp) != NULL)
10437179193Sjb		dtrace_difo_hold(dp);
10438179193Sjb
10439179193Sjb	rec->dtrd_action = action->dta_kind;
10440179193Sjb	rec->dtrd_arg = arg;
10441179193Sjb	rec->dtrd_uarg = desc->dtad_uarg;
10442179193Sjb	rec->dtrd_alignment = (uint16_t)align;
10443179193Sjb	rec->dtrd_format = format;
10444179193Sjb
10445179193Sjb	if ((last = ecb->dte_action_last) != NULL) {
10446179193Sjb		ASSERT(ecb->dte_action != NULL);
10447179193Sjb		action->dta_prev = last;
10448179193Sjb		last->dta_next = action;
10449179193Sjb	} else {
10450179193Sjb		ASSERT(ecb->dte_action == NULL);
10451179193Sjb		ecb->dte_action = action;
10452179193Sjb	}
10453179193Sjb
10454179193Sjb	ecb->dte_action_last = action;
10455179193Sjb
10456179193Sjb	return (0);
10457179193Sjb}
10458179193Sjb
10459179193Sjbstatic void
10460179193Sjbdtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10461179193Sjb{
10462179193Sjb	dtrace_action_t *act = ecb->dte_action, *next;
10463179193Sjb	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10464179193Sjb	dtrace_difo_t *dp;
10465179193Sjb	uint16_t format;
10466179193Sjb
10467179193Sjb	if (act != NULL && act->dta_refcnt > 1) {
10468179193Sjb		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10469179193Sjb		act->dta_refcnt--;
10470179193Sjb	} else {
10471179193Sjb		for (; act != NULL; act = next) {
10472179193Sjb			next = act->dta_next;
10473179193Sjb			ASSERT(next != NULL || act == ecb->dte_action_last);
10474179193Sjb			ASSERT(act->dta_refcnt == 1);
10475179193Sjb
10476179193Sjb			if ((format = act->dta_rec.dtrd_format) != 0)
10477179193Sjb				dtrace_format_remove(ecb->dte_state, format);
10478179193Sjb
10479179193Sjb			if ((dp = act->dta_difo) != NULL)
10480179193Sjb				dtrace_difo_release(dp, vstate);
10481179193Sjb
10482179193Sjb			if (DTRACEACT_ISAGG(act->dta_kind)) {
10483179193Sjb				dtrace_ecb_aggregation_destroy(ecb, act);
10484179193Sjb			} else {
10485179193Sjb				kmem_free(act, sizeof (dtrace_action_t));
10486179193Sjb			}
10487179193Sjb		}
10488179193Sjb	}
10489179193Sjb
10490179193Sjb	ecb->dte_action = NULL;
10491179193Sjb	ecb->dte_action_last = NULL;
10492256002Spfg	ecb->dte_size = 0;
10493179193Sjb}
10494179193Sjb
10495179193Sjbstatic void
10496179193Sjbdtrace_ecb_disable(dtrace_ecb_t *ecb)
10497179193Sjb{
10498179193Sjb	/*
10499179193Sjb	 * We disable the ECB by removing it from its probe.
10500179193Sjb	 */
10501179193Sjb	dtrace_ecb_t *pecb, *prev = NULL;
10502179193Sjb	dtrace_probe_t *probe = ecb->dte_probe;
10503179193Sjb
10504179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10505179193Sjb
10506179193Sjb	if (probe == NULL) {
10507179193Sjb		/*
10508179193Sjb		 * This is the NULL probe; there is nothing to disable.
10509179193Sjb		 */
10510179193Sjb		return;
10511179193Sjb	}
10512179193Sjb
10513179193Sjb	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10514179193Sjb		if (pecb == ecb)
10515179193Sjb			break;
10516179193Sjb		prev = pecb;
10517179193Sjb	}
10518179193Sjb
10519179193Sjb	ASSERT(pecb != NULL);
10520179193Sjb
10521179193Sjb	if (prev == NULL) {
10522179193Sjb		probe->dtpr_ecb = ecb->dte_next;
10523179193Sjb	} else {
10524179193Sjb		prev->dte_next = ecb->dte_next;
10525179193Sjb	}
10526179193Sjb
10527179193Sjb	if (ecb == probe->dtpr_ecb_last) {
10528179193Sjb		ASSERT(ecb->dte_next == NULL);
10529179193Sjb		probe->dtpr_ecb_last = prev;
10530179193Sjb	}
10531179193Sjb
10532179193Sjb	/*
10533179193Sjb	 * The ECB has been disconnected from the probe; now sync to assure
10534179193Sjb	 * that all CPUs have seen the change before returning.
10535179193Sjb	 */
10536179193Sjb	dtrace_sync();
10537179193Sjb
10538179193Sjb	if (probe->dtpr_ecb == NULL) {
10539179193Sjb		/*
10540179193Sjb		 * That was the last ECB on the probe; clear the predicate
10541179193Sjb		 * cache ID for the probe, disable it and sync one more time
10542179193Sjb		 * to assure that we'll never hit it again.
10543179193Sjb		 */
10544179193Sjb		dtrace_provider_t *prov = probe->dtpr_provider;
10545179193Sjb
10546179193Sjb		ASSERT(ecb->dte_next == NULL);
10547179193Sjb		ASSERT(probe->dtpr_ecb_last == NULL);
10548179193Sjb		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10549179193Sjb		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10550179193Sjb		    probe->dtpr_id, probe->dtpr_arg);
10551179193Sjb		dtrace_sync();
10552179193Sjb	} else {
10553179193Sjb		/*
10554179193Sjb		 * There is at least one ECB remaining on the probe.  If there
10555179193Sjb		 * is _exactly_ one, set the probe's predicate cache ID to be
10556179193Sjb		 * the predicate cache ID of the remaining ECB.
10557179193Sjb		 */
10558179193Sjb		ASSERT(probe->dtpr_ecb_last != NULL);
10559179193Sjb		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10560179193Sjb
10561179193Sjb		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10562179193Sjb			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10563179193Sjb
10564179193Sjb			ASSERT(probe->dtpr_ecb->dte_next == NULL);
10565179193Sjb
10566179193Sjb			if (p != NULL)
10567179193Sjb				probe->dtpr_predcache = p->dtp_cacheid;
10568179193Sjb		}
10569179193Sjb
10570179193Sjb		ecb->dte_next = NULL;
10571179193Sjb	}
10572179193Sjb}
10573179193Sjb
10574179193Sjbstatic void
10575179193Sjbdtrace_ecb_destroy(dtrace_ecb_t *ecb)
10576179193Sjb{
10577179193Sjb	dtrace_state_t *state = ecb->dte_state;
10578179193Sjb	dtrace_vstate_t *vstate = &state->dts_vstate;
10579179193Sjb	dtrace_predicate_t *pred;
10580179193Sjb	dtrace_epid_t epid = ecb->dte_epid;
10581179193Sjb
10582179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10583179193Sjb	ASSERT(ecb->dte_next == NULL);
10584179193Sjb	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10585179193Sjb
10586179193Sjb	if ((pred = ecb->dte_predicate) != NULL)
10587179193Sjb		dtrace_predicate_release(pred, vstate);
10588179193Sjb
10589179193Sjb	dtrace_ecb_action_remove(ecb);
10590179193Sjb
10591179193Sjb	ASSERT(state->dts_ecbs[epid - 1] == ecb);
10592179193Sjb	state->dts_ecbs[epid - 1] = NULL;
10593179193Sjb
10594179193Sjb	kmem_free(ecb, sizeof (dtrace_ecb_t));
10595179193Sjb}
10596179193Sjb
10597179193Sjbstatic dtrace_ecb_t *
10598179193Sjbdtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10599179193Sjb    dtrace_enabling_t *enab)
10600179193Sjb{
10601179193Sjb	dtrace_ecb_t *ecb;
10602179193Sjb	dtrace_predicate_t *pred;
10603179193Sjb	dtrace_actdesc_t *act;
10604179193Sjb	dtrace_provider_t *prov;
10605179193Sjb	dtrace_ecbdesc_t *desc = enab->dten_current;
10606179193Sjb
10607179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10608179193Sjb	ASSERT(state != NULL);
10609179193Sjb
10610179193Sjb	ecb = dtrace_ecb_add(state, probe);
10611179193Sjb	ecb->dte_uarg = desc->dted_uarg;
10612179193Sjb
10613179193Sjb	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10614179193Sjb		dtrace_predicate_hold(pred);
10615179193Sjb		ecb->dte_predicate = pred;
10616179193Sjb	}
10617179193Sjb
10618179193Sjb	if (probe != NULL) {
10619179193Sjb		/*
10620179193Sjb		 * If the provider shows more leg than the consumer is old
10621179193Sjb		 * enough to see, we need to enable the appropriate implicit
10622179193Sjb		 * predicate bits to prevent the ecb from activating at
10623179193Sjb		 * revealing times.
10624179193Sjb		 *
10625179193Sjb		 * Providers specifying DTRACE_PRIV_USER at register time
10626179193Sjb		 * are stating that they need the /proc-style privilege
10627179193Sjb		 * model to be enforced, and this is what DTRACE_COND_OWNER
10628179193Sjb		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10629179193Sjb		 */
10630179193Sjb		prov = probe->dtpr_provider;
10631179193Sjb		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10632179193Sjb		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10633179193Sjb			ecb->dte_cond |= DTRACE_COND_OWNER;
10634179193Sjb
10635179193Sjb		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10636179193Sjb		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10637179193Sjb			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10638179193Sjb
10639179193Sjb		/*
10640179193Sjb		 * If the provider shows us kernel innards and the user
10641179193Sjb		 * is lacking sufficient privilege, enable the
10642179193Sjb		 * DTRACE_COND_USERMODE implicit predicate.
10643179193Sjb		 */
10644179193Sjb		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10645179193Sjb		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10646179193Sjb			ecb->dte_cond |= DTRACE_COND_USERMODE;
10647179193Sjb	}
10648179193Sjb
10649179193Sjb	if (dtrace_ecb_create_cache != NULL) {
10650179193Sjb		/*
10651179193Sjb		 * If we have a cached ecb, we'll use its action list instead
10652179193Sjb		 * of creating our own (saving both time and space).
10653179193Sjb		 */
10654179193Sjb		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10655179193Sjb		dtrace_action_t *act = cached->dte_action;
10656179193Sjb
10657179193Sjb		if (act != NULL) {
10658179193Sjb			ASSERT(act->dta_refcnt > 0);
10659179193Sjb			act->dta_refcnt++;
10660179193Sjb			ecb->dte_action = act;
10661179193Sjb			ecb->dte_action_last = cached->dte_action_last;
10662179193Sjb			ecb->dte_needed = cached->dte_needed;
10663179193Sjb			ecb->dte_size = cached->dte_size;
10664179193Sjb			ecb->dte_alignment = cached->dte_alignment;
10665179193Sjb		}
10666179193Sjb
10667179193Sjb		return (ecb);
10668179193Sjb	}
10669179193Sjb
10670179193Sjb	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10671179193Sjb		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10672179193Sjb			dtrace_ecb_destroy(ecb);
10673179193Sjb			return (NULL);
10674179193Sjb		}
10675179193Sjb	}
10676179193Sjb
10677179193Sjb	dtrace_ecb_resize(ecb);
10678179193Sjb
10679179193Sjb	return (dtrace_ecb_create_cache = ecb);
10680179193Sjb}
10681179193Sjb
10682179193Sjbstatic int
10683179193Sjbdtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10684179193Sjb{
10685179193Sjb	dtrace_ecb_t *ecb;
10686179193Sjb	dtrace_enabling_t *enab = arg;
10687179193Sjb	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10688179193Sjb
10689179193Sjb	ASSERT(state != NULL);
10690179193Sjb
10691179193Sjb	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10692179193Sjb		/*
10693179193Sjb		 * This probe was created in a generation for which this
10694179193Sjb		 * enabling has previously created ECBs; we don't want to
10695179193Sjb		 * enable it again, so just kick out.
10696179193Sjb		 */
10697179193Sjb		return (DTRACE_MATCH_NEXT);
10698179193Sjb	}
10699179193Sjb
10700179193Sjb	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10701179193Sjb		return (DTRACE_MATCH_DONE);
10702179193Sjb
10703179193Sjb	dtrace_ecb_enable(ecb);
10704179193Sjb	return (DTRACE_MATCH_NEXT);
10705179193Sjb}
10706179193Sjb
10707179193Sjbstatic dtrace_ecb_t *
10708179193Sjbdtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10709179193Sjb{
10710179193Sjb	dtrace_ecb_t *ecb;
10711179193Sjb
10712179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10713179193Sjb
10714179193Sjb	if (id == 0 || id > state->dts_necbs)
10715179193Sjb		return (NULL);
10716179193Sjb
10717179193Sjb	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10718179193Sjb	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10719179193Sjb
10720179193Sjb	return (state->dts_ecbs[id - 1]);
10721179193Sjb}
10722179193Sjb
10723179193Sjbstatic dtrace_aggregation_t *
10724179193Sjbdtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10725179193Sjb{
10726179193Sjb	dtrace_aggregation_t *agg;
10727179193Sjb
10728179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10729179193Sjb
10730179193Sjb	if (id == 0 || id > state->dts_naggregations)
10731179193Sjb		return (NULL);
10732179193Sjb
10733179193Sjb	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10734179193Sjb	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10735179193Sjb	    agg->dtag_id == id);
10736179193Sjb
10737179193Sjb	return (state->dts_aggregations[id - 1]);
10738179193Sjb}
10739179193Sjb
10740179193Sjb/*
10741179193Sjb * DTrace Buffer Functions
10742179193Sjb *
10743179193Sjb * The following functions manipulate DTrace buffers.  Most of these functions
10744179193Sjb * are called in the context of establishing or processing consumer state;
10745179193Sjb * exceptions are explicitly noted.
10746179193Sjb */
10747179193Sjb
10748179193Sjb/*
10749179193Sjb * Note:  called from cross call context.  This function switches the two
10750179193Sjb * buffers on a given CPU.  The atomicity of this operation is assured by
10751179193Sjb * disabling interrupts while the actual switch takes place; the disabling of
10752179193Sjb * interrupts serializes the execution with any execution of dtrace_probe() on
10753179193Sjb * the same CPU.
10754179193Sjb */
10755179193Sjbstatic void
10756179193Sjbdtrace_buffer_switch(dtrace_buffer_t *buf)
10757179193Sjb{
10758179193Sjb	caddr_t tomax = buf->dtb_tomax;
10759179193Sjb	caddr_t xamot = buf->dtb_xamot;
10760179193Sjb	dtrace_icookie_t cookie;
10761256002Spfg	hrtime_t now;
10762179193Sjb
10763179193Sjb	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10764179193Sjb	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10765179193Sjb
10766179193Sjb	cookie = dtrace_interrupt_disable();
10767256002Spfg	now = dtrace_gethrtime();
10768179193Sjb	buf->dtb_tomax = xamot;
10769179193Sjb	buf->dtb_xamot = tomax;
10770179193Sjb	buf->dtb_xamot_drops = buf->dtb_drops;
10771179193Sjb	buf->dtb_xamot_offset = buf->dtb_offset;
10772179193Sjb	buf->dtb_xamot_errors = buf->dtb_errors;
10773179193Sjb	buf->dtb_xamot_flags = buf->dtb_flags;
10774179193Sjb	buf->dtb_offset = 0;
10775179193Sjb	buf->dtb_drops = 0;
10776179193Sjb	buf->dtb_errors = 0;
10777179193Sjb	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10778250484Spfg	buf->dtb_interval = now - buf->dtb_switched;
10779250484Spfg	buf->dtb_switched = now;
10780179193Sjb	dtrace_interrupt_enable(cookie);
10781179193Sjb}
10782179193Sjb
10783179193Sjb/*
10784179193Sjb * Note:  called from cross call context.  This function activates a buffer
10785179193Sjb * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
10786179193Sjb * is guaranteed by the disabling of interrupts.
10787179193Sjb */
10788179193Sjbstatic void
10789179193Sjbdtrace_buffer_activate(dtrace_state_t *state)
10790179193Sjb{
10791179193Sjb	dtrace_buffer_t *buf;
10792179193Sjb	dtrace_icookie_t cookie = dtrace_interrupt_disable();
10793179193Sjb
10794179198Sjb	buf = &state->dts_buffer[curcpu];
10795179193Sjb
10796179193Sjb	if (buf->dtb_tomax != NULL) {
10797179193Sjb		/*
10798179193Sjb		 * We might like to assert that the buffer is marked inactive,
10799179193Sjb		 * but this isn't necessarily true:  the buffer for the CPU
10800179193Sjb		 * that processes the BEGIN probe has its buffer activated
10801179193Sjb		 * manually.  In this case, we take the (harmless) action
10802179193Sjb		 * re-clearing the bit INACTIVE bit.
10803179193Sjb		 */
10804179193Sjb		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10805179193Sjb	}
10806179193Sjb
10807179193Sjb	dtrace_interrupt_enable(cookie);
10808179193Sjb}
10809179193Sjb
10810179193Sjbstatic int
10811179193Sjbdtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10812179193Sjb    processorid_t cpu)
10813179193Sjb{
10814179198Sjb#if defined(sun)
10815179193Sjb	cpu_t *cp;
10816179198Sjb#endif
10817179193Sjb	dtrace_buffer_t *buf;
10818179193Sjb
10819179198Sjb#if defined(sun)
10820179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
10821179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10822179193Sjb
10823179193Sjb	if (size > dtrace_nonroot_maxsize &&
10824179193Sjb	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10825179193Sjb		return (EFBIG);
10826179193Sjb
10827179193Sjb	cp = cpu_list;
10828179193Sjb
10829179193Sjb	do {
10830179193Sjb		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10831179193Sjb			continue;
10832179193Sjb
10833179193Sjb		buf = &bufs[cp->cpu_id];
10834179193Sjb
10835179193Sjb		/*
10836179193Sjb		 * If there is already a buffer allocated for this CPU, it
10837179193Sjb		 * is only possible that this is a DR event.  In this case,
10838179193Sjb		 */
10839179193Sjb		if (buf->dtb_tomax != NULL) {
10840179193Sjb			ASSERT(buf->dtb_size == size);
10841179193Sjb			continue;
10842179193Sjb		}
10843179193Sjb
10844179193Sjb		ASSERT(buf->dtb_xamot == NULL);
10845179193Sjb
10846179193Sjb		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10847179193Sjb			goto err;
10848179193Sjb
10849179193Sjb		buf->dtb_size = size;
10850179193Sjb		buf->dtb_flags = flags;
10851179193Sjb		buf->dtb_offset = 0;
10852179193Sjb		buf->dtb_drops = 0;
10853179193Sjb
10854179193Sjb		if (flags & DTRACEBUF_NOSWITCH)
10855179193Sjb			continue;
10856179193Sjb
10857179193Sjb		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10858179193Sjb			goto err;
10859179193Sjb	} while ((cp = cp->cpu_next) != cpu_list);
10860179193Sjb
10861179193Sjb	return (0);
10862179193Sjb
10863179193Sjberr:
10864179193Sjb	cp = cpu_list;
10865179193Sjb
10866179193Sjb	do {
10867179193Sjb		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10868179193Sjb			continue;
10869179193Sjb
10870179193Sjb		buf = &bufs[cp->cpu_id];
10871179193Sjb
10872179193Sjb		if (buf->dtb_xamot != NULL) {
10873179193Sjb			ASSERT(buf->dtb_tomax != NULL);
10874179193Sjb			ASSERT(buf->dtb_size == size);
10875179193Sjb			kmem_free(buf->dtb_xamot, size);
10876179193Sjb		}
10877179193Sjb
10878179193Sjb		if (buf->dtb_tomax != NULL) {
10879179193Sjb			ASSERT(buf->dtb_size == size);
10880179193Sjb			kmem_free(buf->dtb_tomax, size);
10881179193Sjb		}
10882179193Sjb
10883179193Sjb		buf->dtb_tomax = NULL;
10884179193Sjb		buf->dtb_xamot = NULL;
10885179193Sjb		buf->dtb_size = 0;
10886179193Sjb	} while ((cp = cp->cpu_next) != cpu_list);
10887179193Sjb
10888179193Sjb	return (ENOMEM);
10889179198Sjb#else
10890179198Sjb	int i;
10891179198Sjb
10892179198Sjb#if defined(__amd64__)
10893179198Sjb	/*
10894179198Sjb	 * FreeBSD isn't good at limiting the amount of memory we
10895179198Sjb	 * ask to malloc, so let's place a limit here before trying
10896179198Sjb	 * to do something that might well end in tears at bedtime.
10897179198Sjb	 */
10898179198Sjb	if (size > physmem * PAGE_SIZE / (128 * (mp_maxid + 1)))
10899179198Sjb		return(ENOMEM);
10900179198Sjb#endif
10901179198Sjb
10902179198Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
10903209059Sjhb	CPU_FOREACH(i) {
10904179198Sjb		if (cpu != DTRACE_CPUALL && cpu != i)
10905179198Sjb			continue;
10906179198Sjb
10907179198Sjb		buf = &bufs[i];
10908179198Sjb
10909179198Sjb		/*
10910179198Sjb		 * If there is already a buffer allocated for this CPU, it
10911179198Sjb		 * is only possible that this is a DR event.  In this case,
10912179198Sjb		 * the buffer size must match our specified size.
10913179198Sjb		 */
10914179198Sjb		if (buf->dtb_tomax != NULL) {
10915179198Sjb			ASSERT(buf->dtb_size == size);
10916179198Sjb			continue;
10917179198Sjb		}
10918179198Sjb
10919179198Sjb		ASSERT(buf->dtb_xamot == NULL);
10920179198Sjb
10921179198Sjb		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10922179198Sjb			goto err;
10923179198Sjb
10924179198Sjb		buf->dtb_size = size;
10925179198Sjb		buf->dtb_flags = flags;
10926179198Sjb		buf->dtb_offset = 0;
10927179198Sjb		buf->dtb_drops = 0;
10928179198Sjb
10929179198Sjb		if (flags & DTRACEBUF_NOSWITCH)
10930179198Sjb			continue;
10931179198Sjb
10932179198Sjb		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10933179198Sjb			goto err;
10934179198Sjb	}
10935179198Sjb
10936179198Sjb	return (0);
10937179198Sjb
10938179198Sjberr:
10939179198Sjb	/*
10940179198Sjb	 * Error allocating memory, so free the buffers that were
10941179198Sjb	 * allocated before the failed allocation.
10942179198Sjb	 */
10943209059Sjhb	CPU_FOREACH(i) {
10944179198Sjb		if (cpu != DTRACE_CPUALL && cpu != i)
10945179198Sjb			continue;
10946179198Sjb
10947179198Sjb		buf = &bufs[i];
10948179198Sjb
10949179198Sjb		if (buf->dtb_xamot != NULL) {
10950179198Sjb			ASSERT(buf->dtb_tomax != NULL);
10951179198Sjb			ASSERT(buf->dtb_size == size);
10952179198Sjb			kmem_free(buf->dtb_xamot, size);
10953179198Sjb		}
10954179198Sjb
10955179198Sjb		if (buf->dtb_tomax != NULL) {
10956179198Sjb			ASSERT(buf->dtb_size == size);
10957179198Sjb			kmem_free(buf->dtb_tomax, size);
10958179198Sjb		}
10959179198Sjb
10960179198Sjb		buf->dtb_tomax = NULL;
10961179198Sjb		buf->dtb_xamot = NULL;
10962179198Sjb		buf->dtb_size = 0;
10963179198Sjb
10964179198Sjb	}
10965179198Sjb
10966179198Sjb	return (ENOMEM);
10967179198Sjb#endif
10968179193Sjb}
10969179193Sjb
10970179193Sjb/*
10971179193Sjb * Note:  called from probe context.  This function just increments the drop
10972179193Sjb * count on a buffer.  It has been made a function to allow for the
10973179193Sjb * possibility of understanding the source of mysterious drop counts.  (A
10974179193Sjb * problem for which one may be particularly disappointed that DTrace cannot
10975179193Sjb * be used to understand DTrace.)
10976179193Sjb */
10977179193Sjbstatic void
10978179193Sjbdtrace_buffer_drop(dtrace_buffer_t *buf)
10979179193Sjb{
10980179193Sjb	buf->dtb_drops++;
10981179193Sjb}
10982179193Sjb
10983179193Sjb/*
10984179193Sjb * Note:  called from probe context.  This function is called to reserve space
10985179193Sjb * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
10986179193Sjb * mstate.  Returns the new offset in the buffer, or a negative value if an
10987179193Sjb * error has occurred.
10988179193Sjb */
10989179193Sjbstatic intptr_t
10990179193Sjbdtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10991179193Sjb    dtrace_state_t *state, dtrace_mstate_t *mstate)
10992179193Sjb{
10993179193Sjb	intptr_t offs = buf->dtb_offset, soffs;
10994179193Sjb	intptr_t woffs;
10995179193Sjb	caddr_t tomax;
10996179193Sjb	size_t total;
10997179193Sjb
10998179193Sjb	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10999179193Sjb		return (-1);
11000179193Sjb
11001179193Sjb	if ((tomax = buf->dtb_tomax) == NULL) {
11002179193Sjb		dtrace_buffer_drop(buf);
11003179193Sjb		return (-1);
11004179193Sjb	}
11005179193Sjb
11006179193Sjb	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11007179193Sjb		while (offs & (align - 1)) {
11008179193Sjb			/*
11009179193Sjb			 * Assert that our alignment is off by a number which
11010179193Sjb			 * is itself sizeof (uint32_t) aligned.
11011179193Sjb			 */
11012179193Sjb			ASSERT(!((align - (offs & (align - 1))) &
11013179193Sjb			    (sizeof (uint32_t) - 1)));
11014179193Sjb			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11015179193Sjb			offs += sizeof (uint32_t);
11016179193Sjb		}
11017179193Sjb
11018179193Sjb		if ((soffs = offs + needed) > buf->dtb_size) {
11019179193Sjb			dtrace_buffer_drop(buf);
11020179193Sjb			return (-1);
11021179193Sjb		}
11022179193Sjb
11023179193Sjb		if (mstate == NULL)
11024179193Sjb			return (offs);
11025179193Sjb
11026179193Sjb		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11027179193Sjb		mstate->dtms_scratch_size = buf->dtb_size - soffs;
11028179193Sjb		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11029179193Sjb
11030179193Sjb		return (offs);
11031179193Sjb	}
11032179193Sjb
11033179193Sjb	if (buf->dtb_flags & DTRACEBUF_FILL) {
11034179193Sjb		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11035179193Sjb		    (buf->dtb_flags & DTRACEBUF_FULL))
11036179193Sjb			return (-1);
11037179193Sjb		goto out;
11038179193Sjb	}
11039179193Sjb
11040179193Sjb	total = needed + (offs & (align - 1));
11041179193Sjb
11042179193Sjb	/*
11043179193Sjb	 * For a ring buffer, life is quite a bit more complicated.  Before
11044179193Sjb	 * we can store any padding, we need to adjust our wrapping offset.
11045179193Sjb	 * (If we've never before wrapped or we're not about to, no adjustment
11046179193Sjb	 * is required.)
11047179193Sjb	 */
11048179193Sjb	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11049179193Sjb	    offs + total > buf->dtb_size) {
11050179193Sjb		woffs = buf->dtb_xamot_offset;
11051179193Sjb
11052179193Sjb		if (offs + total > buf->dtb_size) {
11053179193Sjb			/*
11054179193Sjb			 * We can't fit in the end of the buffer.  First, a
11055179193Sjb			 * sanity check that we can fit in the buffer at all.
11056179193Sjb			 */
11057179193Sjb			if (total > buf->dtb_size) {
11058179193Sjb				dtrace_buffer_drop(buf);
11059179193Sjb				return (-1);
11060179193Sjb			}
11061179193Sjb
11062179193Sjb			/*
11063179193Sjb			 * We're going to be storing at the top of the buffer,
11064179193Sjb			 * so now we need to deal with the wrapped offset.  We
11065179193Sjb			 * only reset our wrapped offset to 0 if it is
11066179193Sjb			 * currently greater than the current offset.  If it
11067179193Sjb			 * is less than the current offset, it is because a
11068179193Sjb			 * previous allocation induced a wrap -- but the
11069179193Sjb			 * allocation didn't subsequently take the space due
11070179193Sjb			 * to an error or false predicate evaluation.  In this
11071179193Sjb			 * case, we'll just leave the wrapped offset alone: if
11072179193Sjb			 * the wrapped offset hasn't been advanced far enough
11073179193Sjb			 * for this allocation, it will be adjusted in the
11074179193Sjb			 * lower loop.
11075179193Sjb			 */
11076179193Sjb			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11077179193Sjb				if (woffs >= offs)
11078179193Sjb					woffs = 0;
11079179193Sjb			} else {
11080179193Sjb				woffs = 0;
11081179193Sjb			}
11082179193Sjb
11083179193Sjb			/*
11084179193Sjb			 * Now we know that we're going to be storing to the
11085179193Sjb			 * top of the buffer and that there is room for us
11086179193Sjb			 * there.  We need to clear the buffer from the current
11087179193Sjb			 * offset to the end (there may be old gunk there).
11088179193Sjb			 */
11089179193Sjb			while (offs < buf->dtb_size)
11090179193Sjb				tomax[offs++] = 0;
11091179193Sjb
11092179193Sjb			/*
11093179193Sjb			 * We need to set our offset to zero.  And because we
11094179193Sjb			 * are wrapping, we need to set the bit indicating as
11095179193Sjb			 * much.  We can also adjust our needed space back
11096179193Sjb			 * down to the space required by the ECB -- we know
11097179193Sjb			 * that the top of the buffer is aligned.
11098179193Sjb			 */
11099179193Sjb			offs = 0;
11100179193Sjb			total = needed;
11101179193Sjb			buf->dtb_flags |= DTRACEBUF_WRAPPED;
11102179193Sjb		} else {
11103179193Sjb			/*
11104179193Sjb			 * There is room for us in the buffer, so we simply
11105179193Sjb			 * need to check the wrapped offset.
11106179193Sjb			 */
11107179193Sjb			if (woffs < offs) {
11108179193Sjb				/*
11109179193Sjb				 * The wrapped offset is less than the offset.
11110179193Sjb				 * This can happen if we allocated buffer space
11111179193Sjb				 * that induced a wrap, but then we didn't
11112179193Sjb				 * subsequently take the space due to an error
11113179193Sjb				 * or false predicate evaluation.  This is
11114179193Sjb				 * okay; we know that _this_ allocation isn't
11115179193Sjb				 * going to induce a wrap.  We still can't
11116179193Sjb				 * reset the wrapped offset to be zero,
11117179193Sjb				 * however: the space may have been trashed in
11118179193Sjb				 * the previous failed probe attempt.  But at
11119179193Sjb				 * least the wrapped offset doesn't need to
11120179193Sjb				 * be adjusted at all...
11121179193Sjb				 */
11122179193Sjb				goto out;
11123179193Sjb			}
11124179193Sjb		}
11125179193Sjb
11126179193Sjb		while (offs + total > woffs) {
11127179193Sjb			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11128179193Sjb			size_t size;
11129179193Sjb
11130179193Sjb			if (epid == DTRACE_EPIDNONE) {
11131179193Sjb				size = sizeof (uint32_t);
11132179193Sjb			} else {
11133256002Spfg				ASSERT3U(epid, <=, state->dts_necbs);
11134179193Sjb				ASSERT(state->dts_ecbs[epid - 1] != NULL);
11135179193Sjb
11136179193Sjb				size = state->dts_ecbs[epid - 1]->dte_size;
11137179193Sjb			}
11138179193Sjb
11139179193Sjb			ASSERT(woffs + size <= buf->dtb_size);
11140179193Sjb			ASSERT(size != 0);
11141179193Sjb
11142179193Sjb			if (woffs + size == buf->dtb_size) {
11143179193Sjb				/*
11144179193Sjb				 * We've reached the end of the buffer; we want
11145179193Sjb				 * to set the wrapped offset to 0 and break
11146179193Sjb				 * out.  However, if the offs is 0, then we're
11147179193Sjb				 * in a strange edge-condition:  the amount of
11148179193Sjb				 * space that we want to reserve plus the size
11149179193Sjb				 * of the record that we're overwriting is
11150179193Sjb				 * greater than the size of the buffer.  This
11151179193Sjb				 * is problematic because if we reserve the
11152179193Sjb				 * space but subsequently don't consume it (due
11153179193Sjb				 * to a failed predicate or error) the wrapped
11154179193Sjb				 * offset will be 0 -- yet the EPID at offset 0
11155179193Sjb				 * will not be committed.  This situation is
11156179193Sjb				 * relatively easy to deal with:  if we're in
11157179193Sjb				 * this case, the buffer is indistinguishable
11158179193Sjb				 * from one that hasn't wrapped; we need only
11159179193Sjb				 * finish the job by clearing the wrapped bit,
11160179193Sjb				 * explicitly setting the offset to be 0, and
11161179193Sjb				 * zero'ing out the old data in the buffer.
11162179193Sjb				 */
11163179193Sjb				if (offs == 0) {
11164179193Sjb					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11165179193Sjb					buf->dtb_offset = 0;
11166179193Sjb					woffs = total;
11167179193Sjb
11168179193Sjb					while (woffs < buf->dtb_size)
11169179193Sjb						tomax[woffs++] = 0;
11170179193Sjb				}
11171179193Sjb
11172179193Sjb				woffs = 0;
11173179193Sjb				break;
11174179193Sjb			}
11175179193Sjb
11176179193Sjb			woffs += size;
11177179193Sjb		}
11178179193Sjb
11179179193Sjb		/*
11180179193Sjb		 * We have a wrapped offset.  It may be that the wrapped offset
11181179193Sjb		 * has become zero -- that's okay.
11182179193Sjb		 */
11183179193Sjb		buf->dtb_xamot_offset = woffs;
11184179193Sjb	}
11185179193Sjb
11186179193Sjbout:
11187179193Sjb	/*
11188179193Sjb	 * Now we can plow the buffer with any necessary padding.
11189179193Sjb	 */
11190179193Sjb	while (offs & (align - 1)) {
11191179193Sjb		/*
11192179193Sjb		 * Assert that our alignment is off by a number which
11193179193Sjb		 * is itself sizeof (uint32_t) aligned.
11194179193Sjb		 */
11195179193Sjb		ASSERT(!((align - (offs & (align - 1))) &
11196179193Sjb		    (sizeof (uint32_t) - 1)));
11197179193Sjb		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11198179193Sjb		offs += sizeof (uint32_t);
11199179193Sjb	}
11200179193Sjb
11201179193Sjb	if (buf->dtb_flags & DTRACEBUF_FILL) {
11202179193Sjb		if (offs + needed > buf->dtb_size - state->dts_reserve) {
11203179193Sjb			buf->dtb_flags |= DTRACEBUF_FULL;
11204179193Sjb			return (-1);
11205179193Sjb		}
11206179193Sjb	}
11207179193Sjb
11208179193Sjb	if (mstate == NULL)
11209179193Sjb		return (offs);
11210179193Sjb
11211179193Sjb	/*
11212179193Sjb	 * For ring buffers and fill buffers, the scratch space is always
11213179193Sjb	 * the inactive buffer.
11214179193Sjb	 */
11215179193Sjb	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11216179193Sjb	mstate->dtms_scratch_size = buf->dtb_size;
11217179193Sjb	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11218179193Sjb
11219179193Sjb	return (offs);
11220179193Sjb}
11221179193Sjb
11222179193Sjbstatic void
11223179193Sjbdtrace_buffer_polish(dtrace_buffer_t *buf)
11224179193Sjb{
11225179193Sjb	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11226179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11227179193Sjb
11228179193Sjb	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11229179193Sjb		return;
11230179193Sjb
11231179193Sjb	/*
11232179193Sjb	 * We need to polish the ring buffer.  There are three cases:
11233179193Sjb	 *
11234179193Sjb	 * - The first (and presumably most common) is that there is no gap
11235179193Sjb	 *   between the buffer offset and the wrapped offset.  In this case,
11236179193Sjb	 *   there is nothing in the buffer that isn't valid data; we can
11237179193Sjb	 *   mark the buffer as polished and return.
11238179193Sjb	 *
11239179193Sjb	 * - The second (less common than the first but still more common
11240179193Sjb	 *   than the third) is that there is a gap between the buffer offset
11241179193Sjb	 *   and the wrapped offset, and the wrapped offset is larger than the
11242179193Sjb	 *   buffer offset.  This can happen because of an alignment issue, or
11243179193Sjb	 *   can happen because of a call to dtrace_buffer_reserve() that
11244179193Sjb	 *   didn't subsequently consume the buffer space.  In this case,
11245179193Sjb	 *   we need to zero the data from the buffer offset to the wrapped
11246179193Sjb	 *   offset.
11247179193Sjb	 *
11248179193Sjb	 * - The third (and least common) is that there is a gap between the
11249179193Sjb	 *   buffer offset and the wrapped offset, but the wrapped offset is
11250179193Sjb	 *   _less_ than the buffer offset.  This can only happen because a
11251179193Sjb	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
11252179193Sjb	 *   was not subsequently consumed.  In this case, we need to zero the
11253179193Sjb	 *   space from the offset to the end of the buffer _and_ from the
11254179193Sjb	 *   top of the buffer to the wrapped offset.
11255179193Sjb	 */
11256179193Sjb	if (buf->dtb_offset < buf->dtb_xamot_offset) {
11257179193Sjb		bzero(buf->dtb_tomax + buf->dtb_offset,
11258179193Sjb		    buf->dtb_xamot_offset - buf->dtb_offset);
11259179193Sjb	}
11260179193Sjb
11261179193Sjb	if (buf->dtb_offset > buf->dtb_xamot_offset) {
11262179193Sjb		bzero(buf->dtb_tomax + buf->dtb_offset,
11263179193Sjb		    buf->dtb_size - buf->dtb_offset);
11264179193Sjb		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11265179193Sjb	}
11266179193Sjb}
11267179193Sjb
11268250484Spfg/*
11269250484Spfg * This routine determines if data generated at the specified time has likely
11270250484Spfg * been entirely consumed at user-level.  This routine is called to determine
11271250484Spfg * if an ECB on a defunct probe (but for an active enabling) can be safely
11272250484Spfg * disabled and destroyed.
11273250484Spfg */
11274250484Spfgstatic int
11275250484Spfgdtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11276250484Spfg{
11277250484Spfg	int i;
11278250484Spfg
11279250484Spfg	for (i = 0; i < NCPU; i++) {
11280250484Spfg		dtrace_buffer_t *buf = &bufs[i];
11281250484Spfg
11282250484Spfg		if (buf->dtb_size == 0)
11283250484Spfg			continue;
11284250484Spfg
11285250484Spfg		if (buf->dtb_flags & DTRACEBUF_RING)
11286250484Spfg			return (0);
11287250484Spfg
11288250484Spfg		if (!buf->dtb_switched && buf->dtb_offset != 0)
11289250484Spfg			return (0);
11290250484Spfg
11291250484Spfg		if (buf->dtb_switched - buf->dtb_interval < when)
11292250484Spfg			return (0);
11293250484Spfg	}
11294250484Spfg
11295250484Spfg	return (1);
11296250484Spfg}
11297250484Spfg
11298179193Sjbstatic void
11299179193Sjbdtrace_buffer_free(dtrace_buffer_t *bufs)
11300179193Sjb{
11301179193Sjb	int i;
11302179193Sjb
11303179193Sjb	for (i = 0; i < NCPU; i++) {
11304179193Sjb		dtrace_buffer_t *buf = &bufs[i];
11305179193Sjb
11306179193Sjb		if (buf->dtb_tomax == NULL) {
11307179193Sjb			ASSERT(buf->dtb_xamot == NULL);
11308179193Sjb			ASSERT(buf->dtb_size == 0);
11309179193Sjb			continue;
11310179193Sjb		}
11311179193Sjb
11312179193Sjb		if (buf->dtb_xamot != NULL) {
11313179193Sjb			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11314179193Sjb			kmem_free(buf->dtb_xamot, buf->dtb_size);
11315179193Sjb		}
11316179193Sjb
11317179193Sjb		kmem_free(buf->dtb_tomax, buf->dtb_size);
11318179193Sjb		buf->dtb_size = 0;
11319179193Sjb		buf->dtb_tomax = NULL;
11320179193Sjb		buf->dtb_xamot = NULL;
11321179193Sjb	}
11322179193Sjb}
11323179193Sjb
11324179193Sjb/*
11325179193Sjb * DTrace Enabling Functions
11326179193Sjb */
11327179193Sjbstatic dtrace_enabling_t *
11328179193Sjbdtrace_enabling_create(dtrace_vstate_t *vstate)
11329179193Sjb{
11330179193Sjb	dtrace_enabling_t *enab;
11331179193Sjb
11332179193Sjb	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11333179193Sjb	enab->dten_vstate = vstate;
11334179193Sjb
11335179193Sjb	return (enab);
11336179193Sjb}
11337179193Sjb
11338179193Sjbstatic void
11339179193Sjbdtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11340179193Sjb{
11341179193Sjb	dtrace_ecbdesc_t **ndesc;
11342179193Sjb	size_t osize, nsize;
11343179193Sjb
11344179193Sjb	/*
11345179193Sjb	 * We can't add to enablings after we've enabled them, or after we've
11346179193Sjb	 * retained them.
11347179193Sjb	 */
11348179193Sjb	ASSERT(enab->dten_probegen == 0);
11349179193Sjb	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11350179193Sjb
11351179193Sjb	if (enab->dten_ndesc < enab->dten_maxdesc) {
11352179193Sjb		enab->dten_desc[enab->dten_ndesc++] = ecb;
11353179193Sjb		return;
11354179193Sjb	}
11355179193Sjb
11356179193Sjb	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11357179193Sjb
11358179193Sjb	if (enab->dten_maxdesc == 0) {
11359179193Sjb		enab->dten_maxdesc = 1;
11360179193Sjb	} else {
11361179193Sjb		enab->dten_maxdesc <<= 1;
11362179193Sjb	}
11363179193Sjb
11364179193Sjb	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11365179193Sjb
11366179193Sjb	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11367179193Sjb	ndesc = kmem_zalloc(nsize, KM_SLEEP);
11368179193Sjb	bcopy(enab->dten_desc, ndesc, osize);
11369179198Sjb	if (enab->dten_desc != NULL)
11370179198Sjb		kmem_free(enab->dten_desc, osize);
11371179193Sjb
11372179193Sjb	enab->dten_desc = ndesc;
11373179193Sjb	enab->dten_desc[enab->dten_ndesc++] = ecb;
11374179193Sjb}
11375179193Sjb
11376179193Sjbstatic void
11377179193Sjbdtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11378179193Sjb    dtrace_probedesc_t *pd)
11379179193Sjb{
11380179193Sjb	dtrace_ecbdesc_t *new;
11381179193Sjb	dtrace_predicate_t *pred;
11382179193Sjb	dtrace_actdesc_t *act;
11383179193Sjb
11384179193Sjb	/*
11385179193Sjb	 * We're going to create a new ECB description that matches the
11386179193Sjb	 * specified ECB in every way, but has the specified probe description.
11387179193Sjb	 */
11388179193Sjb	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11389179193Sjb
11390179193Sjb	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11391179193Sjb		dtrace_predicate_hold(pred);
11392179193Sjb
11393179193Sjb	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11394179193Sjb		dtrace_actdesc_hold(act);
11395179193Sjb
11396179193Sjb	new->dted_action = ecb->dted_action;
11397179193Sjb	new->dted_pred = ecb->dted_pred;
11398179193Sjb	new->dted_probe = *pd;
11399179193Sjb	new->dted_uarg = ecb->dted_uarg;
11400179193Sjb
11401179193Sjb	dtrace_enabling_add(enab, new);
11402179193Sjb}
11403179193Sjb
11404179193Sjbstatic void
11405179193Sjbdtrace_enabling_dump(dtrace_enabling_t *enab)
11406179193Sjb{
11407179193Sjb	int i;
11408179193Sjb
11409179193Sjb	for (i = 0; i < enab->dten_ndesc; i++) {
11410179193Sjb		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11411179193Sjb
11412179193Sjb		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11413179193Sjb		    desc->dtpd_provider, desc->dtpd_mod,
11414179193Sjb		    desc->dtpd_func, desc->dtpd_name);
11415179193Sjb	}
11416179193Sjb}
11417179193Sjb
11418179193Sjbstatic void
11419179193Sjbdtrace_enabling_destroy(dtrace_enabling_t *enab)
11420179193Sjb{
11421179193Sjb	int i;
11422179193Sjb	dtrace_ecbdesc_t *ep;
11423179193Sjb	dtrace_vstate_t *vstate = enab->dten_vstate;
11424179193Sjb
11425179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11426179193Sjb
11427179193Sjb	for (i = 0; i < enab->dten_ndesc; i++) {
11428179193Sjb		dtrace_actdesc_t *act, *next;
11429179193Sjb		dtrace_predicate_t *pred;
11430179193Sjb
11431179193Sjb		ep = enab->dten_desc[i];
11432179193Sjb
11433179193Sjb		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11434179193Sjb			dtrace_predicate_release(pred, vstate);
11435179193Sjb
11436179193Sjb		for (act = ep->dted_action; act != NULL; act = next) {
11437179193Sjb			next = act->dtad_next;
11438179193Sjb			dtrace_actdesc_release(act, vstate);
11439179193Sjb		}
11440179193Sjb
11441179193Sjb		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11442179193Sjb	}
11443179193Sjb
11444179198Sjb	if (enab->dten_desc != NULL)
11445179198Sjb		kmem_free(enab->dten_desc,
11446179198Sjb		    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11447179193Sjb
11448179193Sjb	/*
11449179193Sjb	 * If this was a retained enabling, decrement the dts_nretained count
11450179193Sjb	 * and take it off of the dtrace_retained list.
11451179193Sjb	 */
11452179193Sjb	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11453179193Sjb	    dtrace_retained == enab) {
11454179193Sjb		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11455179193Sjb		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11456179193Sjb		enab->dten_vstate->dtvs_state->dts_nretained--;
11457179193Sjb	}
11458179193Sjb
11459179193Sjb	if (enab->dten_prev == NULL) {
11460179193Sjb		if (dtrace_retained == enab) {
11461179193Sjb			dtrace_retained = enab->dten_next;
11462179193Sjb
11463179193Sjb			if (dtrace_retained != NULL)
11464179193Sjb				dtrace_retained->dten_prev = NULL;
11465179193Sjb		}
11466179193Sjb	} else {
11467179193Sjb		ASSERT(enab != dtrace_retained);
11468179193Sjb		ASSERT(dtrace_retained != NULL);
11469179193Sjb		enab->dten_prev->dten_next = enab->dten_next;
11470179193Sjb	}
11471179193Sjb
11472179193Sjb	if (enab->dten_next != NULL) {
11473179193Sjb		ASSERT(dtrace_retained != NULL);
11474179193Sjb		enab->dten_next->dten_prev = enab->dten_prev;
11475179193Sjb	}
11476179193Sjb
11477179193Sjb	kmem_free(enab, sizeof (dtrace_enabling_t));
11478179193Sjb}
11479179193Sjb
11480179193Sjbstatic int
11481179193Sjbdtrace_enabling_retain(dtrace_enabling_t *enab)
11482179193Sjb{
11483179193Sjb	dtrace_state_t *state;
11484179193Sjb
11485179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11486179193Sjb	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11487179193Sjb	ASSERT(enab->dten_vstate != NULL);
11488179193Sjb
11489179193Sjb	state = enab->dten_vstate->dtvs_state;
11490179193Sjb	ASSERT(state != NULL);
11491179193Sjb
11492179193Sjb	/*
11493179193Sjb	 * We only allow each state to retain dtrace_retain_max enablings.
11494179193Sjb	 */
11495179193Sjb	if (state->dts_nretained >= dtrace_retain_max)
11496179193Sjb		return (ENOSPC);
11497179193Sjb
11498179193Sjb	state->dts_nretained++;
11499179193Sjb
11500179193Sjb	if (dtrace_retained == NULL) {
11501179193Sjb		dtrace_retained = enab;
11502179193Sjb		return (0);
11503179193Sjb	}
11504179193Sjb
11505179193Sjb	enab->dten_next = dtrace_retained;
11506179193Sjb	dtrace_retained->dten_prev = enab;
11507179193Sjb	dtrace_retained = enab;
11508179193Sjb
11509179193Sjb	return (0);
11510179193Sjb}
11511179193Sjb
11512179193Sjbstatic int
11513179193Sjbdtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11514179193Sjb    dtrace_probedesc_t *create)
11515179193Sjb{
11516179193Sjb	dtrace_enabling_t *new, *enab;
11517179193Sjb	int found = 0, err = ENOENT;
11518179193Sjb
11519179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11520179193Sjb	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11521179193Sjb	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11522179193Sjb	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11523179193Sjb	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11524179193Sjb
11525179193Sjb	new = dtrace_enabling_create(&state->dts_vstate);
11526179193Sjb
11527179193Sjb	/*
11528179193Sjb	 * Iterate over all retained enablings, looking for enablings that
11529179193Sjb	 * match the specified state.
11530179193Sjb	 */
11531179193Sjb	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11532179193Sjb		int i;
11533179193Sjb
11534179193Sjb		/*
11535179193Sjb		 * dtvs_state can only be NULL for helper enablings -- and
11536179193Sjb		 * helper enablings can't be retained.
11537179193Sjb		 */
11538179193Sjb		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11539179193Sjb
11540179193Sjb		if (enab->dten_vstate->dtvs_state != state)
11541179193Sjb			continue;
11542179193Sjb
11543179193Sjb		/*
11544179193Sjb		 * Now iterate over each probe description; we're looking for
11545179193Sjb		 * an exact match to the specified probe description.
11546179193Sjb		 */
11547179193Sjb		for (i = 0; i < enab->dten_ndesc; i++) {
11548179193Sjb			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11549179193Sjb			dtrace_probedesc_t *pd = &ep->dted_probe;
11550179193Sjb
11551179193Sjb			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11552179193Sjb				continue;
11553179193Sjb
11554179193Sjb			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11555179193Sjb				continue;
11556179193Sjb
11557179193Sjb			if (strcmp(pd->dtpd_func, match->dtpd_func))
11558179193Sjb				continue;
11559179193Sjb
11560179193Sjb			if (strcmp(pd->dtpd_name, match->dtpd_name))
11561179193Sjb				continue;
11562179193Sjb
11563179193Sjb			/*
11564179193Sjb			 * We have a winning probe!  Add it to our growing
11565179193Sjb			 * enabling.
11566179193Sjb			 */
11567179193Sjb			found = 1;
11568179193Sjb			dtrace_enabling_addlike(new, ep, create);
11569179193Sjb		}
11570179193Sjb	}
11571179193Sjb
11572179193Sjb	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11573179193Sjb		dtrace_enabling_destroy(new);
11574179193Sjb		return (err);
11575179193Sjb	}
11576179193Sjb
11577179193Sjb	return (0);
11578179193Sjb}
11579179193Sjb
11580179193Sjbstatic void
11581179193Sjbdtrace_enabling_retract(dtrace_state_t *state)
11582179193Sjb{
11583179193Sjb	dtrace_enabling_t *enab, *next;
11584179193Sjb
11585179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11586179193Sjb
11587179193Sjb	/*
11588179193Sjb	 * Iterate over all retained enablings, destroy the enablings retained
11589179193Sjb	 * for the specified state.
11590179193Sjb	 */
11591179193Sjb	for (enab = dtrace_retained; enab != NULL; enab = next) {
11592179193Sjb		next = enab->dten_next;
11593179193Sjb
11594179193Sjb		/*
11595179193Sjb		 * dtvs_state can only be NULL for helper enablings -- and
11596179193Sjb		 * helper enablings can't be retained.
11597179193Sjb		 */
11598179193Sjb		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11599179193Sjb
11600179193Sjb		if (enab->dten_vstate->dtvs_state == state) {
11601179193Sjb			ASSERT(state->dts_nretained > 0);
11602179193Sjb			dtrace_enabling_destroy(enab);
11603179193Sjb		}
11604179193Sjb	}
11605179193Sjb
11606179193Sjb	ASSERT(state->dts_nretained == 0);
11607179193Sjb}
11608179193Sjb
11609179193Sjbstatic int
11610179193Sjbdtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11611179193Sjb{
11612179193Sjb	int i = 0;
11613179193Sjb	int matched = 0;
11614179193Sjb
11615179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
11616179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11617179193Sjb
11618179193Sjb	for (i = 0; i < enab->dten_ndesc; i++) {
11619179193Sjb		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11620179193Sjb
11621179193Sjb		enab->dten_current = ep;
11622179193Sjb		enab->dten_error = 0;
11623179193Sjb
11624179193Sjb		matched += dtrace_probe_enable(&ep->dted_probe, enab);
11625179193Sjb
11626179193Sjb		if (enab->dten_error != 0) {
11627179193Sjb			/*
11628179193Sjb			 * If we get an error half-way through enabling the
11629179193Sjb			 * probes, we kick out -- perhaps with some number of
11630179193Sjb			 * them enabled.  Leaving enabled probes enabled may
11631179193Sjb			 * be slightly confusing for user-level, but we expect
11632179193Sjb			 * that no one will attempt to actually drive on in
11633179193Sjb			 * the face of such errors.  If this is an anonymous
11634179193Sjb			 * enabling (indicated with a NULL nmatched pointer),
11635179193Sjb			 * we cmn_err() a message.  We aren't expecting to
11636179193Sjb			 * get such an error -- such as it can exist at all,
11637179193Sjb			 * it would be a result of corrupted DOF in the driver
11638179193Sjb			 * properties.
11639179193Sjb			 */
11640179193Sjb			if (nmatched == NULL) {
11641179193Sjb				cmn_err(CE_WARN, "dtrace_enabling_match() "
11642179193Sjb				    "error on %p: %d", (void *)ep,
11643179193Sjb				    enab->dten_error);
11644179193Sjb			}
11645179193Sjb
11646179193Sjb			return (enab->dten_error);
11647179193Sjb		}
11648179193Sjb	}
11649179193Sjb
11650179193Sjb	enab->dten_probegen = dtrace_probegen;
11651179193Sjb	if (nmatched != NULL)
11652179193Sjb		*nmatched = matched;
11653179193Sjb
11654179193Sjb	return (0);
11655179193Sjb}
11656179193Sjb
11657179193Sjbstatic void
11658179193Sjbdtrace_enabling_matchall(void)
11659179193Sjb{
11660179193Sjb	dtrace_enabling_t *enab;
11661179193Sjb
11662179193Sjb	mutex_enter(&cpu_lock);
11663179193Sjb	mutex_enter(&dtrace_lock);
11664179193Sjb
11665179193Sjb	/*
11666179469Sjb	 * Iterate over all retained enablings to see if any probes match
11667179469Sjb	 * against them.  We only perform this operation on enablings for which
11668179469Sjb	 * we have sufficient permissions by virtue of being in the global zone
11669179469Sjb	 * or in the same zone as the DTrace client.  Because we can be called
11670179469Sjb	 * after dtrace_detach() has been called, we cannot assert that there
11671179469Sjb	 * are retained enablings.  We can safely load from dtrace_retained,
11672179469Sjb	 * however:  the taskq_destroy() at the end of dtrace_detach() will
11673179469Sjb	 * block pending our completion.
11674179193Sjb	 */
11675179469Sjb	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11676179469Sjb#if defined(sun)
11677179469Sjb		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
11678179193Sjb
11679179469Sjb		if (INGLOBALZONE(curproc) || getzoneid() == crgetzoneid(cr))
11680179469Sjb#endif
11681179469Sjb			(void) dtrace_enabling_match(enab, NULL);
11682179469Sjb	}
11683179469Sjb
11684179193Sjb	mutex_exit(&dtrace_lock);
11685179193Sjb	mutex_exit(&cpu_lock);
11686179193Sjb}
11687179193Sjb
11688179193Sjb/*
11689179193Sjb * If an enabling is to be enabled without having matched probes (that is, if
11690179193Sjb * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11691179193Sjb * enabling must be _primed_ by creating an ECB for every ECB description.
11692179193Sjb * This must be done to assure that we know the number of speculations, the
11693179193Sjb * number of aggregations, the minimum buffer size needed, etc. before we
11694179193Sjb * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11695179193Sjb * enabling any probes, we create ECBs for every ECB decription, but with a
11696179193Sjb * NULL probe -- which is exactly what this function does.
11697179193Sjb */
11698179193Sjbstatic void
11699179193Sjbdtrace_enabling_prime(dtrace_state_t *state)
11700179193Sjb{
11701179193Sjb	dtrace_enabling_t *enab;
11702179193Sjb	int i;
11703179193Sjb
11704179193Sjb	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11705179193Sjb		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11706179193Sjb
11707179193Sjb		if (enab->dten_vstate->dtvs_state != state)
11708179193Sjb			continue;
11709179193Sjb
11710179193Sjb		/*
11711179193Sjb		 * We don't want to prime an enabling more than once, lest
11712179193Sjb		 * we allow a malicious user to induce resource exhaustion.
11713179193Sjb		 * (The ECBs that result from priming an enabling aren't
11714179193Sjb		 * leaked -- but they also aren't deallocated until the
11715179193Sjb		 * consumer state is destroyed.)
11716179193Sjb		 */
11717179193Sjb		if (enab->dten_primed)
11718179193Sjb			continue;
11719179193Sjb
11720179193Sjb		for (i = 0; i < enab->dten_ndesc; i++) {
11721179193Sjb			enab->dten_current = enab->dten_desc[i];
11722179193Sjb			(void) dtrace_probe_enable(NULL, enab);
11723179193Sjb		}
11724179193Sjb
11725179193Sjb		enab->dten_primed = 1;
11726179193Sjb	}
11727179193Sjb}
11728179193Sjb
11729179193Sjb/*
11730179193Sjb * Called to indicate that probes should be provided due to retained
11731179193Sjb * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
11732179193Sjb * must take an initial lap through the enabling calling the dtps_provide()
11733179193Sjb * entry point explicitly to allow for autocreated probes.
11734179193Sjb */
11735179193Sjbstatic void
11736179193Sjbdtrace_enabling_provide(dtrace_provider_t *prv)
11737179193Sjb{
11738179193Sjb	int i, all = 0;
11739179193Sjb	dtrace_probedesc_t desc;
11740179193Sjb
11741179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11742179193Sjb	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11743179193Sjb
11744179193Sjb	if (prv == NULL) {
11745179193Sjb		all = 1;
11746179193Sjb		prv = dtrace_provider;
11747179193Sjb	}
11748179193Sjb
11749179193Sjb	do {
11750179193Sjb		dtrace_enabling_t *enab = dtrace_retained;
11751179193Sjb		void *parg = prv->dtpv_arg;
11752179193Sjb
11753179193Sjb		for (; enab != NULL; enab = enab->dten_next) {
11754179193Sjb			for (i = 0; i < enab->dten_ndesc; i++) {
11755179193Sjb				desc = enab->dten_desc[i]->dted_probe;
11756179193Sjb				mutex_exit(&dtrace_lock);
11757179193Sjb				prv->dtpv_pops.dtps_provide(parg, &desc);
11758179193Sjb				mutex_enter(&dtrace_lock);
11759179193Sjb			}
11760179193Sjb		}
11761179193Sjb	} while (all && (prv = prv->dtpv_next) != NULL);
11762179193Sjb
11763179193Sjb	mutex_exit(&dtrace_lock);
11764179193Sjb	dtrace_probe_provide(NULL, all ? NULL : prv);
11765179193Sjb	mutex_enter(&dtrace_lock);
11766179193Sjb}
11767179193Sjb
11768179193Sjb/*
11769250484Spfg * Called to reap ECBs that are attached to probes from defunct providers.
11770250484Spfg */
11771250484Spfgstatic void
11772250484Spfgdtrace_enabling_reap(void)
11773250484Spfg{
11774250484Spfg	dtrace_provider_t *prov;
11775250484Spfg	dtrace_probe_t *probe;
11776250484Spfg	dtrace_ecb_t *ecb;
11777250484Spfg	hrtime_t when;
11778250484Spfg	int i;
11779250484Spfg
11780250484Spfg	mutex_enter(&cpu_lock);
11781250484Spfg	mutex_enter(&dtrace_lock);
11782250484Spfg
11783250484Spfg	for (i = 0; i < dtrace_nprobes; i++) {
11784250484Spfg		if ((probe = dtrace_probes[i]) == NULL)
11785250484Spfg			continue;
11786250484Spfg
11787250484Spfg		if (probe->dtpr_ecb == NULL)
11788250484Spfg			continue;
11789250484Spfg
11790250484Spfg		prov = probe->dtpr_provider;
11791250484Spfg
11792250484Spfg		if ((when = prov->dtpv_defunct) == 0)
11793250484Spfg			continue;
11794250484Spfg
11795250484Spfg		/*
11796250484Spfg		 * We have ECBs on a defunct provider:  we want to reap these
11797250484Spfg		 * ECBs to allow the provider to unregister.  The destruction
11798250484Spfg		 * of these ECBs must be done carefully:  if we destroy the ECB
11799250484Spfg		 * and the consumer later wishes to consume an EPID that
11800250484Spfg		 * corresponds to the destroyed ECB (and if the EPID metadata
11801250484Spfg		 * has not been previously consumed), the consumer will abort
11802250484Spfg		 * processing on the unknown EPID.  To reduce (but not, sadly,
11803250484Spfg		 * eliminate) the possibility of this, we will only destroy an
11804250484Spfg		 * ECB for a defunct provider if, for the state that
11805250484Spfg		 * corresponds to the ECB:
11806250484Spfg		 *
11807250484Spfg		 *  (a)	There is no speculative tracing (which can effectively
11808250484Spfg		 *	cache an EPID for an arbitrary amount of time).
11809250484Spfg		 *
11810250484Spfg		 *  (b)	The principal buffers have been switched twice since the
11811250484Spfg		 *	provider became defunct.
11812250484Spfg		 *
11813250484Spfg		 *  (c)	The aggregation buffers are of zero size or have been
11814250484Spfg		 *	switched twice since the provider became defunct.
11815250484Spfg		 *
11816250484Spfg		 * We use dts_speculates to determine (a) and call a function
11817250484Spfg		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
11818250484Spfg		 * that as soon as we've been unable to destroy one of the ECBs
11819250484Spfg		 * associated with the probe, we quit trying -- reaping is only
11820250484Spfg		 * fruitful in as much as we can destroy all ECBs associated
11821250484Spfg		 * with the defunct provider's probes.
11822250484Spfg		 */
11823250484Spfg		while ((ecb = probe->dtpr_ecb) != NULL) {
11824250484Spfg			dtrace_state_t *state = ecb->dte_state;
11825250484Spfg			dtrace_buffer_t *buf = state->dts_buffer;
11826250484Spfg			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
11827250484Spfg
11828250484Spfg			if (state->dts_speculates)
11829250484Spfg				break;
11830250484Spfg
11831250484Spfg			if (!dtrace_buffer_consumed(buf, when))
11832250484Spfg				break;
11833250484Spfg
11834250484Spfg			if (!dtrace_buffer_consumed(aggbuf, when))
11835250484Spfg				break;
11836250484Spfg
11837250484Spfg			dtrace_ecb_disable(ecb);
11838250484Spfg			ASSERT(probe->dtpr_ecb != ecb);
11839250484Spfg			dtrace_ecb_destroy(ecb);
11840250484Spfg		}
11841250484Spfg	}
11842250484Spfg
11843250484Spfg	mutex_exit(&dtrace_lock);
11844250484Spfg	mutex_exit(&cpu_lock);
11845250484Spfg}
11846250484Spfg
11847250484Spfg/*
11848179193Sjb * DTrace DOF Functions
11849179193Sjb */
11850179193Sjb/*ARGSUSED*/
11851179193Sjbstatic void
11852179193Sjbdtrace_dof_error(dof_hdr_t *dof, const char *str)
11853179193Sjb{
11854179193Sjb	if (dtrace_err_verbose)
11855179193Sjb		cmn_err(CE_WARN, "failed to process DOF: %s", str);
11856179193Sjb
11857179193Sjb#ifdef DTRACE_ERRDEBUG
11858179193Sjb	dtrace_errdebug(str);
11859179193Sjb#endif
11860179193Sjb}
11861179193Sjb
11862179193Sjb/*
11863179193Sjb * Create DOF out of a currently enabled state.  Right now, we only create
11864179193Sjb * DOF containing the run-time options -- but this could be expanded to create
11865179193Sjb * complete DOF representing the enabled state.
11866179193Sjb */
11867179193Sjbstatic dof_hdr_t *
11868179193Sjbdtrace_dof_create(dtrace_state_t *state)
11869179193Sjb{
11870179193Sjb	dof_hdr_t *dof;
11871179193Sjb	dof_sec_t *sec;
11872179193Sjb	dof_optdesc_t *opt;
11873179193Sjb	int i, len = sizeof (dof_hdr_t) +
11874179193Sjb	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11875179193Sjb	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11876179193Sjb
11877179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
11878179193Sjb
11879179193Sjb	dof = kmem_zalloc(len, KM_SLEEP);
11880179193Sjb	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11881179193Sjb	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11882179193Sjb	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11883179193Sjb	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11884179193Sjb
11885179193Sjb	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11886179193Sjb	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11887179193Sjb	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11888179193Sjb	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11889179193Sjb	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11890179193Sjb	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11891179193Sjb
11892179193Sjb	dof->dofh_flags = 0;
11893179193Sjb	dof->dofh_hdrsize = sizeof (dof_hdr_t);
11894179193Sjb	dof->dofh_secsize = sizeof (dof_sec_t);
11895179193Sjb	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
11896179193Sjb	dof->dofh_secoff = sizeof (dof_hdr_t);
11897179193Sjb	dof->dofh_loadsz = len;
11898179193Sjb	dof->dofh_filesz = len;
11899179193Sjb	dof->dofh_pad = 0;
11900179193Sjb
11901179193Sjb	/*
11902179193Sjb	 * Fill in the option section header...
11903179193Sjb	 */
11904179193Sjb	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11905179193Sjb	sec->dofs_type = DOF_SECT_OPTDESC;
11906179193Sjb	sec->dofs_align = sizeof (uint64_t);
11907179193Sjb	sec->dofs_flags = DOF_SECF_LOAD;
11908179193Sjb	sec->dofs_entsize = sizeof (dof_optdesc_t);
11909179193Sjb
11910179193Sjb	opt = (dof_optdesc_t *)((uintptr_t)sec +
11911179193Sjb	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11912179193Sjb
11913179193Sjb	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11914179193Sjb	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11915179193Sjb
11916179193Sjb	for (i = 0; i < DTRACEOPT_MAX; i++) {
11917179193Sjb		opt[i].dofo_option = i;
11918179193Sjb		opt[i].dofo_strtab = DOF_SECIDX_NONE;
11919179193Sjb		opt[i].dofo_value = state->dts_options[i];
11920179193Sjb	}
11921179193Sjb
11922179193Sjb	return (dof);
11923179193Sjb}
11924179193Sjb
11925179193Sjbstatic dof_hdr_t *
11926179193Sjbdtrace_dof_copyin(uintptr_t uarg, int *errp)
11927179193Sjb{
11928179193Sjb	dof_hdr_t hdr, *dof;
11929179193Sjb
11930179193Sjb	ASSERT(!MUTEX_HELD(&dtrace_lock));
11931179193Sjb
11932179193Sjb	/*
11933179193Sjb	 * First, we're going to copyin() the sizeof (dof_hdr_t).
11934179193Sjb	 */
11935179193Sjb	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11936179193Sjb		dtrace_dof_error(NULL, "failed to copyin DOF header");
11937179193Sjb		*errp = EFAULT;
11938179193Sjb		return (NULL);
11939179193Sjb	}
11940179193Sjb
11941179193Sjb	/*
11942179193Sjb	 * Now we'll allocate the entire DOF and copy it in -- provided
11943179193Sjb	 * that the length isn't outrageous.
11944179193Sjb	 */
11945179193Sjb	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
11946179193Sjb		dtrace_dof_error(&hdr, "load size exceeds maximum");
11947179193Sjb		*errp = E2BIG;
11948179193Sjb		return (NULL);
11949179193Sjb	}
11950179193Sjb
11951179193Sjb	if (hdr.dofh_loadsz < sizeof (hdr)) {
11952179193Sjb		dtrace_dof_error(&hdr, "invalid load size");
11953179193Sjb		*errp = EINVAL;
11954179193Sjb		return (NULL);
11955179193Sjb	}
11956179193Sjb
11957179193Sjb	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
11958179193Sjb
11959179193Sjb	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
11960179193Sjb		kmem_free(dof, hdr.dofh_loadsz);
11961179193Sjb		*errp = EFAULT;
11962179193Sjb		return (NULL);
11963179193Sjb	}
11964179193Sjb
11965179193Sjb	return (dof);
11966179193Sjb}
11967179193Sjb
11968179198Sjb#if !defined(sun)
11969179198Sjbstatic __inline uchar_t
11970179198Sjbdtrace_dof_char(char c) {
11971179198Sjb	switch (c) {
11972179198Sjb	case '0':
11973179198Sjb	case '1':
11974179198Sjb	case '2':
11975179198Sjb	case '3':
11976179198Sjb	case '4':
11977179198Sjb	case '5':
11978179198Sjb	case '6':
11979179198Sjb	case '7':
11980179198Sjb	case '8':
11981179198Sjb	case '9':
11982179198Sjb		return (c - '0');
11983179198Sjb	case 'A':
11984179198Sjb	case 'B':
11985179198Sjb	case 'C':
11986179198Sjb	case 'D':
11987179198Sjb	case 'E':
11988179198Sjb	case 'F':
11989179198Sjb		return (c - 'A' + 10);
11990179198Sjb	case 'a':
11991179198Sjb	case 'b':
11992179198Sjb	case 'c':
11993179198Sjb	case 'd':
11994179198Sjb	case 'e':
11995179198Sjb	case 'f':
11996179198Sjb		return (c - 'a' + 10);
11997179198Sjb	}
11998179198Sjb	/* Should not reach here. */
11999179198Sjb	return (0);
12000179198Sjb}
12001179198Sjb#endif
12002179198Sjb
12003179193Sjbstatic dof_hdr_t *
12004179193Sjbdtrace_dof_property(const char *name)
12005179193Sjb{
12006179193Sjb	uchar_t *buf;
12007179193Sjb	uint64_t loadsz;
12008179193Sjb	unsigned int len, i;
12009179193Sjb	dof_hdr_t *dof;
12010179193Sjb
12011179198Sjb#if defined(sun)
12012179193Sjb	/*
12013179193Sjb	 * Unfortunately, array of values in .conf files are always (and
12014179193Sjb	 * only) interpreted to be integer arrays.  We must read our DOF
12015179193Sjb	 * as an integer array, and then squeeze it into a byte array.
12016179193Sjb	 */
12017179193Sjb	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12018179193Sjb	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12019179193Sjb		return (NULL);
12020179193Sjb
12021179193Sjb	for (i = 0; i < len; i++)
12022179193Sjb		buf[i] = (uchar_t)(((int *)buf)[i]);
12023179193Sjb
12024179193Sjb	if (len < sizeof (dof_hdr_t)) {
12025179193Sjb		ddi_prop_free(buf);
12026179193Sjb		dtrace_dof_error(NULL, "truncated header");
12027179193Sjb		return (NULL);
12028179193Sjb	}
12029179193Sjb
12030179193Sjb	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12031179193Sjb		ddi_prop_free(buf);
12032179193Sjb		dtrace_dof_error(NULL, "truncated DOF");
12033179193Sjb		return (NULL);
12034179193Sjb	}
12035179193Sjb
12036179193Sjb	if (loadsz >= dtrace_dof_maxsize) {
12037179193Sjb		ddi_prop_free(buf);
12038179193Sjb		dtrace_dof_error(NULL, "oversized DOF");
12039179193Sjb		return (NULL);
12040179193Sjb	}
12041179193Sjb
12042179193Sjb	dof = kmem_alloc(loadsz, KM_SLEEP);
12043179193Sjb	bcopy(buf, dof, loadsz);
12044179193Sjb	ddi_prop_free(buf);
12045179198Sjb#else
12046179198Sjb	char *p;
12047179198Sjb	char *p_env;
12048179193Sjb
12049179198Sjb	if ((p_env = getenv(name)) == NULL)
12050179198Sjb		return (NULL);
12051179198Sjb
12052179198Sjb	len = strlen(p_env) / 2;
12053179198Sjb
12054179198Sjb	buf = kmem_alloc(len, KM_SLEEP);
12055179198Sjb
12056179198Sjb	dof = (dof_hdr_t *) buf;
12057179198Sjb
12058179198Sjb	p = p_env;
12059179198Sjb
12060179198Sjb	for (i = 0; i < len; i++) {
12061179198Sjb		buf[i] = (dtrace_dof_char(p[0]) << 4) |
12062179198Sjb		     dtrace_dof_char(p[1]);
12063179198Sjb		p += 2;
12064179198Sjb	}
12065179198Sjb
12066179198Sjb	freeenv(p_env);
12067179198Sjb
12068179198Sjb	if (len < sizeof (dof_hdr_t)) {
12069179198Sjb		kmem_free(buf, 0);
12070179198Sjb		dtrace_dof_error(NULL, "truncated header");
12071179198Sjb		return (NULL);
12072179198Sjb	}
12073179198Sjb
12074179198Sjb	if (len < (loadsz = dof->dofh_loadsz)) {
12075179198Sjb		kmem_free(buf, 0);
12076179198Sjb		dtrace_dof_error(NULL, "truncated DOF");
12077179198Sjb		return (NULL);
12078179198Sjb	}
12079179198Sjb
12080179198Sjb	if (loadsz >= dtrace_dof_maxsize) {
12081179198Sjb		kmem_free(buf, 0);
12082179198Sjb		dtrace_dof_error(NULL, "oversized DOF");
12083179198Sjb		return (NULL);
12084179198Sjb	}
12085179198Sjb#endif
12086179198Sjb
12087179193Sjb	return (dof);
12088179193Sjb}
12089179193Sjb
12090179193Sjbstatic void
12091179193Sjbdtrace_dof_destroy(dof_hdr_t *dof)
12092179193Sjb{
12093179193Sjb	kmem_free(dof, dof->dofh_loadsz);
12094179193Sjb}
12095179193Sjb
12096179193Sjb/*
12097179193Sjb * Return the dof_sec_t pointer corresponding to a given section index.  If the
12098179193Sjb * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12099179193Sjb * a type other than DOF_SECT_NONE is specified, the header is checked against
12100179193Sjb * this type and NULL is returned if the types do not match.
12101179193Sjb */
12102179193Sjbstatic dof_sec_t *
12103179193Sjbdtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12104179193Sjb{
12105179193Sjb	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12106179193Sjb	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12107179193Sjb
12108179193Sjb	if (i >= dof->dofh_secnum) {
12109179193Sjb		dtrace_dof_error(dof, "referenced section index is invalid");
12110179193Sjb		return (NULL);
12111179193Sjb	}
12112179193Sjb
12113179193Sjb	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12114179193Sjb		dtrace_dof_error(dof, "referenced section is not loadable");
12115179193Sjb		return (NULL);
12116179193Sjb	}
12117179193Sjb
12118179193Sjb	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12119179193Sjb		dtrace_dof_error(dof, "referenced section is the wrong type");
12120179193Sjb		return (NULL);
12121179193Sjb	}
12122179193Sjb
12123179193Sjb	return (sec);
12124179193Sjb}
12125179193Sjb
12126179193Sjbstatic dtrace_probedesc_t *
12127179193Sjbdtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12128179193Sjb{
12129179193Sjb	dof_probedesc_t *probe;
12130179193Sjb	dof_sec_t *strtab;
12131179193Sjb	uintptr_t daddr = (uintptr_t)dof;
12132179193Sjb	uintptr_t str;
12133179193Sjb	size_t size;
12134179193Sjb
12135179193Sjb	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12136179193Sjb		dtrace_dof_error(dof, "invalid probe section");
12137179193Sjb		return (NULL);
12138179193Sjb	}
12139179193Sjb
12140179193Sjb	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12141179193Sjb		dtrace_dof_error(dof, "bad alignment in probe description");
12142179193Sjb		return (NULL);
12143179193Sjb	}
12144179193Sjb
12145179193Sjb	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12146179193Sjb		dtrace_dof_error(dof, "truncated probe description");
12147179193Sjb		return (NULL);
12148179193Sjb	}
12149179193Sjb
12150179193Sjb	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12151179193Sjb	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12152179193Sjb
12153179193Sjb	if (strtab == NULL)
12154179193Sjb		return (NULL);
12155179193Sjb
12156179193Sjb	str = daddr + strtab->dofs_offset;
12157179193Sjb	size = strtab->dofs_size;
12158179193Sjb
12159179193Sjb	if (probe->dofp_provider >= strtab->dofs_size) {
12160179193Sjb		dtrace_dof_error(dof, "corrupt probe provider");
12161179193Sjb		return (NULL);
12162179193Sjb	}
12163179193Sjb
12164179193Sjb	(void) strncpy(desc->dtpd_provider,
12165179193Sjb	    (char *)(str + probe->dofp_provider),
12166179193Sjb	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12167179193Sjb
12168179193Sjb	if (probe->dofp_mod >= strtab->dofs_size) {
12169179193Sjb		dtrace_dof_error(dof, "corrupt probe module");
12170179193Sjb		return (NULL);
12171179193Sjb	}
12172179193Sjb
12173179193Sjb	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12174179193Sjb	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12175179193Sjb
12176179193Sjb	if (probe->dofp_func >= strtab->dofs_size) {
12177179193Sjb		dtrace_dof_error(dof, "corrupt probe function");
12178179193Sjb		return (NULL);
12179179193Sjb	}
12180179193Sjb
12181179193Sjb	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12182179193Sjb	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12183179193Sjb
12184179193Sjb	if (probe->dofp_name >= strtab->dofs_size) {
12185179193Sjb		dtrace_dof_error(dof, "corrupt probe name");
12186179193Sjb		return (NULL);
12187179193Sjb	}
12188179193Sjb
12189179193Sjb	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12190179193Sjb	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12191179193Sjb
12192179193Sjb	return (desc);
12193179193Sjb}
12194179193Sjb
12195179193Sjbstatic dtrace_difo_t *
12196179193Sjbdtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12197179193Sjb    cred_t *cr)
12198179193Sjb{
12199179193Sjb	dtrace_difo_t *dp;
12200179193Sjb	size_t ttl = 0;
12201179193Sjb	dof_difohdr_t *dofd;
12202179193Sjb	uintptr_t daddr = (uintptr_t)dof;
12203179193Sjb	size_t max = dtrace_difo_maxsize;
12204179193Sjb	int i, l, n;
12205179193Sjb
12206179193Sjb	static const struct {
12207179193Sjb		int section;
12208179193Sjb		int bufoffs;
12209179193Sjb		int lenoffs;
12210179193Sjb		int entsize;
12211179193Sjb		int align;
12212179193Sjb		const char *msg;
12213179193Sjb	} difo[] = {
12214179193Sjb		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12215179193Sjb		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12216179193Sjb		sizeof (dif_instr_t), "multiple DIF sections" },
12217179193Sjb
12218179193Sjb		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12219179193Sjb		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12220179193Sjb		sizeof (uint64_t), "multiple integer tables" },
12221179193Sjb
12222179193Sjb		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12223179193Sjb		offsetof(dtrace_difo_t, dtdo_strlen), 0,
12224179193Sjb		sizeof (char), "multiple string tables" },
12225179193Sjb
12226179193Sjb		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12227179193Sjb		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12228179193Sjb		sizeof (uint_t), "multiple variable tables" },
12229179193Sjb
12230179198Sjb		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12231179193Sjb	};
12232179193Sjb
12233179193Sjb	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12234179193Sjb		dtrace_dof_error(dof, "invalid DIFO header section");
12235179193Sjb		return (NULL);
12236179193Sjb	}
12237179193Sjb
12238179193Sjb	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12239179193Sjb		dtrace_dof_error(dof, "bad alignment in DIFO header");
12240179193Sjb		return (NULL);
12241179193Sjb	}
12242179193Sjb
12243179193Sjb	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12244179193Sjb	    sec->dofs_size % sizeof (dof_secidx_t)) {
12245179193Sjb		dtrace_dof_error(dof, "bad size in DIFO header");
12246179193Sjb		return (NULL);
12247179193Sjb	}
12248179193Sjb
12249179193Sjb	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12250179193Sjb	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12251179193Sjb
12252179193Sjb	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12253179193Sjb	dp->dtdo_rtype = dofd->dofd_rtype;
12254179193Sjb
12255179193Sjb	for (l = 0; l < n; l++) {
12256179193Sjb		dof_sec_t *subsec;
12257179193Sjb		void **bufp;
12258179193Sjb		uint32_t *lenp;
12259179193Sjb
12260179193Sjb		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12261179193Sjb		    dofd->dofd_links[l])) == NULL)
12262179193Sjb			goto err; /* invalid section link */
12263179193Sjb
12264179193Sjb		if (ttl + subsec->dofs_size > max) {
12265179193Sjb			dtrace_dof_error(dof, "exceeds maximum size");
12266179193Sjb			goto err;
12267179193Sjb		}
12268179193Sjb
12269179193Sjb		ttl += subsec->dofs_size;
12270179193Sjb
12271179193Sjb		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12272179193Sjb			if (subsec->dofs_type != difo[i].section)
12273179193Sjb				continue;
12274179193Sjb
12275179193Sjb			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12276179193Sjb				dtrace_dof_error(dof, "section not loaded");
12277179193Sjb				goto err;
12278179193Sjb			}
12279179193Sjb
12280179193Sjb			if (subsec->dofs_align != difo[i].align) {
12281179193Sjb				dtrace_dof_error(dof, "bad alignment");
12282179193Sjb				goto err;
12283179193Sjb			}
12284179193Sjb
12285179193Sjb			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12286179193Sjb			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12287179193Sjb
12288179193Sjb			if (*bufp != NULL) {
12289179193Sjb				dtrace_dof_error(dof, difo[i].msg);
12290179193Sjb				goto err;
12291179193Sjb			}
12292179193Sjb
12293179193Sjb			if (difo[i].entsize != subsec->dofs_entsize) {
12294179193Sjb				dtrace_dof_error(dof, "entry size mismatch");
12295179193Sjb				goto err;
12296179193Sjb			}
12297179193Sjb
12298179193Sjb			if (subsec->dofs_entsize != 0 &&
12299179193Sjb			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12300179193Sjb				dtrace_dof_error(dof, "corrupt entry size");
12301179193Sjb				goto err;
12302179193Sjb			}
12303179193Sjb
12304179193Sjb			*lenp = subsec->dofs_size;
12305179193Sjb			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12306179193Sjb			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12307179193Sjb			    *bufp, subsec->dofs_size);
12308179193Sjb
12309179193Sjb			if (subsec->dofs_entsize != 0)
12310179193Sjb				*lenp /= subsec->dofs_entsize;
12311179193Sjb
12312179193Sjb			break;
12313179193Sjb		}
12314179193Sjb
12315179193Sjb		/*
12316179193Sjb		 * If we encounter a loadable DIFO sub-section that is not
12317179193Sjb		 * known to us, assume this is a broken program and fail.
12318179193Sjb		 */
12319179193Sjb		if (difo[i].section == DOF_SECT_NONE &&
12320179193Sjb		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
12321179193Sjb			dtrace_dof_error(dof, "unrecognized DIFO subsection");
12322179193Sjb			goto err;
12323179193Sjb		}
12324179193Sjb	}
12325179193Sjb
12326179193Sjb	if (dp->dtdo_buf == NULL) {
12327179193Sjb		/*
12328179193Sjb		 * We can't have a DIF object without DIF text.
12329179193Sjb		 */
12330179193Sjb		dtrace_dof_error(dof, "missing DIF text");
12331179193Sjb		goto err;
12332179193Sjb	}
12333179193Sjb
12334179193Sjb	/*
12335179193Sjb	 * Before we validate the DIF object, run through the variable table
12336179193Sjb	 * looking for the strings -- if any of their size are under, we'll set
12337179193Sjb	 * their size to be the system-wide default string size.  Note that
12338179193Sjb	 * this should _not_ happen if the "strsize" option has been set --
12339179193Sjb	 * in this case, the compiler should have set the size to reflect the
12340179193Sjb	 * setting of the option.
12341179193Sjb	 */
12342179193Sjb	for (i = 0; i < dp->dtdo_varlen; i++) {
12343179193Sjb		dtrace_difv_t *v = &dp->dtdo_vartab[i];
12344179193Sjb		dtrace_diftype_t *t = &v->dtdv_type;
12345179193Sjb
12346179193Sjb		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12347179193Sjb			continue;
12348179193Sjb
12349179193Sjb		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12350179193Sjb			t->dtdt_size = dtrace_strsize_default;
12351179193Sjb	}
12352179193Sjb
12353179193Sjb	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12354179193Sjb		goto err;
12355179193Sjb
12356179193Sjb	dtrace_difo_init(dp, vstate);
12357179193Sjb	return (dp);
12358179193Sjb
12359179193Sjberr:
12360179193Sjb	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12361179193Sjb	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12362179193Sjb	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12363179193Sjb	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12364179193Sjb
12365179193Sjb	kmem_free(dp, sizeof (dtrace_difo_t));
12366179193Sjb	return (NULL);
12367179193Sjb}
12368179193Sjb
12369179193Sjbstatic dtrace_predicate_t *
12370179193Sjbdtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12371179193Sjb    cred_t *cr)
12372179193Sjb{
12373179193Sjb	dtrace_difo_t *dp;
12374179193Sjb
12375179193Sjb	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12376179193Sjb		return (NULL);
12377179193Sjb
12378179193Sjb	return (dtrace_predicate_create(dp));
12379179193Sjb}
12380179193Sjb
12381179193Sjbstatic dtrace_actdesc_t *
12382179193Sjbdtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12383179193Sjb    cred_t *cr)
12384179193Sjb{
12385179193Sjb	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12386179193Sjb	dof_actdesc_t *desc;
12387179193Sjb	dof_sec_t *difosec;
12388179193Sjb	size_t offs;
12389179193Sjb	uintptr_t daddr = (uintptr_t)dof;
12390179193Sjb	uint64_t arg;
12391179193Sjb	dtrace_actkind_t kind;
12392179193Sjb
12393179193Sjb	if (sec->dofs_type != DOF_SECT_ACTDESC) {
12394179193Sjb		dtrace_dof_error(dof, "invalid action section");
12395179193Sjb		return (NULL);
12396179193Sjb	}
12397179193Sjb
12398179193Sjb	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12399179193Sjb		dtrace_dof_error(dof, "truncated action description");
12400179193Sjb		return (NULL);
12401179193Sjb	}
12402179193Sjb
12403179193Sjb	if (sec->dofs_align != sizeof (uint64_t)) {
12404179193Sjb		dtrace_dof_error(dof, "bad alignment in action description");
12405179193Sjb		return (NULL);
12406179193Sjb	}
12407179193Sjb
12408179193Sjb	if (sec->dofs_size < sec->dofs_entsize) {
12409179193Sjb		dtrace_dof_error(dof, "section entry size exceeds total size");
12410179193Sjb		return (NULL);
12411179193Sjb	}
12412179193Sjb
12413179193Sjb	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12414179193Sjb		dtrace_dof_error(dof, "bad entry size in action description");
12415179193Sjb		return (NULL);
12416179193Sjb	}
12417179193Sjb
12418179193Sjb	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12419179193Sjb		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12420179193Sjb		return (NULL);
12421179193Sjb	}
12422179193Sjb
12423179193Sjb	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12424179193Sjb		desc = (dof_actdesc_t *)(daddr +
12425179193Sjb		    (uintptr_t)sec->dofs_offset + offs);
12426179193Sjb		kind = (dtrace_actkind_t)desc->dofa_kind;
12427179193Sjb
12428249856Spfg		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12429179193Sjb		    (kind != DTRACEACT_PRINTA ||
12430249856Spfg		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12431249856Spfg		    (kind == DTRACEACT_DIFEXPR &&
12432179193Sjb		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
12433179193Sjb			dof_sec_t *strtab;
12434179193Sjb			char *str, *fmt;
12435179193Sjb			uint64_t i;
12436179193Sjb
12437179193Sjb			/*
12438249856Spfg			 * The argument to these actions is an index into the
12439249856Spfg			 * DOF string table.  For printf()-like actions, this
12440249856Spfg			 * is the format string.  For print(), this is the
12441249856Spfg			 * CTF type of the expression result.
12442179193Sjb			 */
12443179193Sjb			if ((strtab = dtrace_dof_sect(dof,
12444179193Sjb			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12445179193Sjb				goto err;
12446179193Sjb
12447179193Sjb			str = (char *)((uintptr_t)dof +
12448179193Sjb			    (uintptr_t)strtab->dofs_offset);
12449179193Sjb
12450179193Sjb			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12451179193Sjb				if (str[i] == '\0')
12452179193Sjb					break;
12453179193Sjb			}
12454179193Sjb
12455179193Sjb			if (i >= strtab->dofs_size) {
12456179193Sjb				dtrace_dof_error(dof, "bogus format string");
12457179193Sjb				goto err;
12458179193Sjb			}
12459179193Sjb
12460179193Sjb			if (i == desc->dofa_arg) {
12461179193Sjb				dtrace_dof_error(dof, "empty format string");
12462179193Sjb				goto err;
12463179193Sjb			}
12464179193Sjb
12465179193Sjb			i -= desc->dofa_arg;
12466179193Sjb			fmt = kmem_alloc(i + 1, KM_SLEEP);
12467179193Sjb			bcopy(&str[desc->dofa_arg], fmt, i + 1);
12468179193Sjb			arg = (uint64_t)(uintptr_t)fmt;
12469179193Sjb		} else {
12470179193Sjb			if (kind == DTRACEACT_PRINTA) {
12471179193Sjb				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12472179193Sjb				arg = 0;
12473179193Sjb			} else {
12474179193Sjb				arg = desc->dofa_arg;
12475179193Sjb			}
12476179193Sjb		}
12477179193Sjb
12478179193Sjb		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12479179193Sjb		    desc->dofa_uarg, arg);
12480179193Sjb
12481179193Sjb		if (last != NULL) {
12482179193Sjb			last->dtad_next = act;
12483179193Sjb		} else {
12484179193Sjb			first = act;
12485179193Sjb		}
12486179193Sjb
12487179193Sjb		last = act;
12488179193Sjb
12489179193Sjb		if (desc->dofa_difo == DOF_SECIDX_NONE)
12490179193Sjb			continue;
12491179193Sjb
12492179193Sjb		if ((difosec = dtrace_dof_sect(dof,
12493179193Sjb		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12494179193Sjb			goto err;
12495179193Sjb
12496179193Sjb		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12497179193Sjb
12498179193Sjb		if (act->dtad_difo == NULL)
12499179193Sjb			goto err;
12500179193Sjb	}
12501179193Sjb
12502179193Sjb	ASSERT(first != NULL);
12503179193Sjb	return (first);
12504179193Sjb
12505179193Sjberr:
12506179193Sjb	for (act = first; act != NULL; act = next) {
12507179193Sjb		next = act->dtad_next;
12508179193Sjb		dtrace_actdesc_release(act, vstate);
12509179193Sjb	}
12510179193Sjb
12511179193Sjb	return (NULL);
12512179193Sjb}
12513179193Sjb
12514179193Sjbstatic dtrace_ecbdesc_t *
12515179193Sjbdtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12516179193Sjb    cred_t *cr)
12517179193Sjb{
12518179193Sjb	dtrace_ecbdesc_t *ep;
12519179193Sjb	dof_ecbdesc_t *ecb;
12520179193Sjb	dtrace_probedesc_t *desc;
12521179193Sjb	dtrace_predicate_t *pred = NULL;
12522179193Sjb
12523179193Sjb	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12524179193Sjb		dtrace_dof_error(dof, "truncated ECB description");
12525179193Sjb		return (NULL);
12526179193Sjb	}
12527179193Sjb
12528179193Sjb	if (sec->dofs_align != sizeof (uint64_t)) {
12529179193Sjb		dtrace_dof_error(dof, "bad alignment in ECB description");
12530179193Sjb		return (NULL);
12531179193Sjb	}
12532179193Sjb
12533179193Sjb	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12534179193Sjb	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12535179193Sjb
12536179193Sjb	if (sec == NULL)
12537179193Sjb		return (NULL);
12538179193Sjb
12539179193Sjb	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12540179193Sjb	ep->dted_uarg = ecb->dofe_uarg;
12541179193Sjb	desc = &ep->dted_probe;
12542179193Sjb
12543179193Sjb	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12544179193Sjb		goto err;
12545179193Sjb
12546179193Sjb	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12547179193Sjb		if ((sec = dtrace_dof_sect(dof,
12548179193Sjb		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12549179193Sjb			goto err;
12550179193Sjb
12551179193Sjb		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12552179193Sjb			goto err;
12553179193Sjb
12554179193Sjb		ep->dted_pred.dtpdd_predicate = pred;
12555179193Sjb	}
12556179193Sjb
12557179193Sjb	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12558179193Sjb		if ((sec = dtrace_dof_sect(dof,
12559179193Sjb		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12560179193Sjb			goto err;
12561179193Sjb
12562179193Sjb		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12563179193Sjb
12564179193Sjb		if (ep->dted_action == NULL)
12565179193Sjb			goto err;
12566179193Sjb	}
12567179193Sjb
12568179193Sjb	return (ep);
12569179193Sjb
12570179193Sjberr:
12571179193Sjb	if (pred != NULL)
12572179193Sjb		dtrace_predicate_release(pred, vstate);
12573179193Sjb	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12574179193Sjb	return (NULL);
12575179193Sjb}
12576179193Sjb
12577179193Sjb/*
12578179193Sjb * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12579179193Sjb * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12580179193Sjb * site of any user SETX relocations to account for load object base address.
12581179193Sjb * In the future, if we need other relocations, this function can be extended.
12582179193Sjb */
12583179193Sjbstatic int
12584179193Sjbdtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12585179193Sjb{
12586179193Sjb	uintptr_t daddr = (uintptr_t)dof;
12587179193Sjb	dof_relohdr_t *dofr =
12588179193Sjb	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12589179193Sjb	dof_sec_t *ss, *rs, *ts;
12590179193Sjb	dof_relodesc_t *r;
12591179193Sjb	uint_t i, n;
12592179193Sjb
12593179193Sjb	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12594179193Sjb	    sec->dofs_align != sizeof (dof_secidx_t)) {
12595179193Sjb		dtrace_dof_error(dof, "invalid relocation header");
12596179193Sjb		return (-1);
12597179193Sjb	}
12598179193Sjb
12599179193Sjb	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12600179193Sjb	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12601179193Sjb	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12602179193Sjb
12603179193Sjb	if (ss == NULL || rs == NULL || ts == NULL)
12604179193Sjb		return (-1); /* dtrace_dof_error() has been called already */
12605179193Sjb
12606179193Sjb	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12607179193Sjb	    rs->dofs_align != sizeof (uint64_t)) {
12608179193Sjb		dtrace_dof_error(dof, "invalid relocation section");
12609179193Sjb		return (-1);
12610179193Sjb	}
12611179193Sjb
12612179193Sjb	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12613179193Sjb	n = rs->dofs_size / rs->dofs_entsize;
12614179193Sjb
12615179193Sjb	for (i = 0; i < n; i++) {
12616179193Sjb		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12617179193Sjb
12618179193Sjb		switch (r->dofr_type) {
12619179193Sjb		case DOF_RELO_NONE:
12620179193Sjb			break;
12621179193Sjb		case DOF_RELO_SETX:
12622179193Sjb			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12623179193Sjb			    sizeof (uint64_t) > ts->dofs_size) {
12624179193Sjb				dtrace_dof_error(dof, "bad relocation offset");
12625179193Sjb				return (-1);
12626179193Sjb			}
12627179193Sjb
12628179193Sjb			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12629179193Sjb				dtrace_dof_error(dof, "misaligned setx relo");
12630179193Sjb				return (-1);
12631179193Sjb			}
12632179193Sjb
12633179193Sjb			*(uint64_t *)taddr += ubase;
12634179193Sjb			break;
12635179193Sjb		default:
12636179193Sjb			dtrace_dof_error(dof, "invalid relocation type");
12637179193Sjb			return (-1);
12638179193Sjb		}
12639179193Sjb
12640179193Sjb		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12641179193Sjb	}
12642179193Sjb
12643179193Sjb	return (0);
12644179193Sjb}
12645179193Sjb
12646179193Sjb/*
12647179193Sjb * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12648179193Sjb * header:  it should be at the front of a memory region that is at least
12649179193Sjb * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12650179193Sjb * size.  It need not be validated in any other way.
12651179193Sjb */
12652179193Sjbstatic int
12653179193Sjbdtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12654179193Sjb    dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12655179193Sjb{
12656179193Sjb	uint64_t len = dof->dofh_loadsz, seclen;
12657179193Sjb	uintptr_t daddr = (uintptr_t)dof;
12658179193Sjb	dtrace_ecbdesc_t *ep;
12659179193Sjb	dtrace_enabling_t *enab;
12660179193Sjb	uint_t i;
12661179193Sjb
12662179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
12663179193Sjb	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12664179193Sjb
12665179193Sjb	/*
12666179193Sjb	 * Check the DOF header identification bytes.  In addition to checking
12667179193Sjb	 * valid settings, we also verify that unused bits/bytes are zeroed so
12668179193Sjb	 * we can use them later without fear of regressing existing binaries.
12669179193Sjb	 */
12670179193Sjb	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12671179193Sjb	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12672179193Sjb		dtrace_dof_error(dof, "DOF magic string mismatch");
12673179193Sjb		return (-1);
12674179193Sjb	}
12675179193Sjb
12676179193Sjb	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12677179193Sjb	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12678179193Sjb		dtrace_dof_error(dof, "DOF has invalid data model");
12679179193Sjb		return (-1);
12680179193Sjb	}
12681179193Sjb
12682179193Sjb	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12683179193Sjb		dtrace_dof_error(dof, "DOF encoding mismatch");
12684179193Sjb		return (-1);
12685179193Sjb	}
12686179193Sjb
12687179193Sjb	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12688179193Sjb	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12689179193Sjb		dtrace_dof_error(dof, "DOF version mismatch");
12690179193Sjb		return (-1);
12691179193Sjb	}
12692179193Sjb
12693179193Sjb	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12694179193Sjb		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12695179193Sjb		return (-1);
12696179193Sjb	}
12697179193Sjb
12698179193Sjb	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12699179193Sjb		dtrace_dof_error(dof, "DOF uses too many integer registers");
12700179193Sjb		return (-1);
12701179193Sjb	}
12702179193Sjb
12703179193Sjb	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12704179193Sjb		dtrace_dof_error(dof, "DOF uses too many tuple registers");
12705179193Sjb		return (-1);
12706179193Sjb	}
12707179193Sjb
12708179193Sjb	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12709179193Sjb		if (dof->dofh_ident[i] != 0) {
12710179193Sjb			dtrace_dof_error(dof, "DOF has invalid ident byte set");
12711179193Sjb			return (-1);
12712179193Sjb		}
12713179193Sjb	}
12714179193Sjb
12715179193Sjb	if (dof->dofh_flags & ~DOF_FL_VALID) {
12716179193Sjb		dtrace_dof_error(dof, "DOF has invalid flag bits set");
12717179193Sjb		return (-1);
12718179193Sjb	}
12719179193Sjb
12720179193Sjb	if (dof->dofh_secsize == 0) {
12721179193Sjb		dtrace_dof_error(dof, "zero section header size");
12722179193Sjb		return (-1);
12723179193Sjb	}
12724179193Sjb
12725179193Sjb	/*
12726179193Sjb	 * Check that the section headers don't exceed the amount of DOF
12727179193Sjb	 * data.  Note that we cast the section size and number of sections
12728179193Sjb	 * to uint64_t's to prevent possible overflow in the multiplication.
12729179193Sjb	 */
12730179193Sjb	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12731179193Sjb
12732179193Sjb	if (dof->dofh_secoff > len || seclen > len ||
12733179193Sjb	    dof->dofh_secoff + seclen > len) {
12734179193Sjb		dtrace_dof_error(dof, "truncated section headers");
12735179193Sjb		return (-1);
12736179193Sjb	}
12737179193Sjb
12738179193Sjb	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12739179193Sjb		dtrace_dof_error(dof, "misaligned section headers");
12740179193Sjb		return (-1);
12741179193Sjb	}
12742179193Sjb
12743179193Sjb	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12744179193Sjb		dtrace_dof_error(dof, "misaligned section size");
12745179193Sjb		return (-1);
12746179193Sjb	}
12747179193Sjb
12748179193Sjb	/*
12749179193Sjb	 * Take an initial pass through the section headers to be sure that
12750179193Sjb	 * the headers don't have stray offsets.  If the 'noprobes' flag is
12751179193Sjb	 * set, do not permit sections relating to providers, probes, or args.
12752179193Sjb	 */
12753179193Sjb	for (i = 0; i < dof->dofh_secnum; i++) {
12754179193Sjb		dof_sec_t *sec = (dof_sec_t *)(daddr +
12755179193Sjb		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12756179193Sjb
12757179193Sjb		if (noprobes) {
12758179193Sjb			switch (sec->dofs_type) {
12759179193Sjb			case DOF_SECT_PROVIDER:
12760179193Sjb			case DOF_SECT_PROBES:
12761179193Sjb			case DOF_SECT_PRARGS:
12762179193Sjb			case DOF_SECT_PROFFS:
12763179193Sjb				dtrace_dof_error(dof, "illegal sections "
12764179193Sjb				    "for enabling");
12765179193Sjb				return (-1);
12766179193Sjb			}
12767179193Sjb		}
12768179193Sjb
12769179193Sjb		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12770179193Sjb			continue; /* just ignore non-loadable sections */
12771179193Sjb
12772179193Sjb		if (sec->dofs_align & (sec->dofs_align - 1)) {
12773179193Sjb			dtrace_dof_error(dof, "bad section alignment");
12774179193Sjb			return (-1);
12775179193Sjb		}
12776179193Sjb
12777179193Sjb		if (sec->dofs_offset & (sec->dofs_align - 1)) {
12778179193Sjb			dtrace_dof_error(dof, "misaligned section");
12779179193Sjb			return (-1);
12780179193Sjb		}
12781179193Sjb
12782179193Sjb		if (sec->dofs_offset > len || sec->dofs_size > len ||
12783179193Sjb		    sec->dofs_offset + sec->dofs_size > len) {
12784179193Sjb			dtrace_dof_error(dof, "corrupt section header");
12785179193Sjb			return (-1);
12786179193Sjb		}
12787179193Sjb
12788179193Sjb		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12789179193Sjb		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12790179193Sjb			dtrace_dof_error(dof, "non-terminating string table");
12791179193Sjb			return (-1);
12792179193Sjb		}
12793179193Sjb	}
12794179193Sjb
12795179193Sjb	/*
12796179193Sjb	 * Take a second pass through the sections and locate and perform any
12797179193Sjb	 * relocations that are present.  We do this after the first pass to
12798179193Sjb	 * be sure that all sections have had their headers validated.
12799179193Sjb	 */
12800179193Sjb	for (i = 0; i < dof->dofh_secnum; i++) {
12801179193Sjb		dof_sec_t *sec = (dof_sec_t *)(daddr +
12802179193Sjb		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12803179193Sjb
12804179193Sjb		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12805179193Sjb			continue; /* skip sections that are not loadable */
12806179193Sjb
12807179193Sjb		switch (sec->dofs_type) {
12808179193Sjb		case DOF_SECT_URELHDR:
12809179193Sjb			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12810179193Sjb				return (-1);
12811179193Sjb			break;
12812179193Sjb		}
12813179193Sjb	}
12814179193Sjb
12815179193Sjb	if ((enab = *enabp) == NULL)
12816179193Sjb		enab = *enabp = dtrace_enabling_create(vstate);
12817179193Sjb
12818179193Sjb	for (i = 0; i < dof->dofh_secnum; i++) {
12819179193Sjb		dof_sec_t *sec = (dof_sec_t *)(daddr +
12820179193Sjb		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12821179193Sjb
12822179193Sjb		if (sec->dofs_type != DOF_SECT_ECBDESC)
12823179193Sjb			continue;
12824179193Sjb
12825179193Sjb		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12826179193Sjb			dtrace_enabling_destroy(enab);
12827179193Sjb			*enabp = NULL;
12828179193Sjb			return (-1);
12829179193Sjb		}
12830179193Sjb
12831179193Sjb		dtrace_enabling_add(enab, ep);
12832179193Sjb	}
12833179193Sjb
12834179193Sjb	return (0);
12835179193Sjb}
12836179193Sjb
12837179193Sjb/*
12838179193Sjb * Process DOF for any options.  This routine assumes that the DOF has been
12839179193Sjb * at least processed by dtrace_dof_slurp().
12840179193Sjb */
12841179193Sjbstatic int
12842179193Sjbdtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12843179193Sjb{
12844179193Sjb	int i, rval;
12845179193Sjb	uint32_t entsize;
12846179193Sjb	size_t offs;
12847179193Sjb	dof_optdesc_t *desc;
12848179193Sjb
12849179193Sjb	for (i = 0; i < dof->dofh_secnum; i++) {
12850179193Sjb		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12851179193Sjb		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12852179193Sjb
12853179193Sjb		if (sec->dofs_type != DOF_SECT_OPTDESC)
12854179193Sjb			continue;
12855179193Sjb
12856179193Sjb		if (sec->dofs_align != sizeof (uint64_t)) {
12857179193Sjb			dtrace_dof_error(dof, "bad alignment in "
12858179193Sjb			    "option description");
12859179193Sjb			return (EINVAL);
12860179193Sjb		}
12861179193Sjb
12862179193Sjb		if ((entsize = sec->dofs_entsize) == 0) {
12863179193Sjb			dtrace_dof_error(dof, "zeroed option entry size");
12864179193Sjb			return (EINVAL);
12865179193Sjb		}
12866179193Sjb
12867179193Sjb		if (entsize < sizeof (dof_optdesc_t)) {
12868179193Sjb			dtrace_dof_error(dof, "bad option entry size");
12869179193Sjb			return (EINVAL);
12870179193Sjb		}
12871179193Sjb
12872179193Sjb		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12873179193Sjb			desc = (dof_optdesc_t *)((uintptr_t)dof +
12874179193Sjb			    (uintptr_t)sec->dofs_offset + offs);
12875179193Sjb
12876179193Sjb			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12877179193Sjb				dtrace_dof_error(dof, "non-zero option string");
12878179193Sjb				return (EINVAL);
12879179193Sjb			}
12880179193Sjb
12881179193Sjb			if (desc->dofo_value == DTRACEOPT_UNSET) {
12882179193Sjb				dtrace_dof_error(dof, "unset option");
12883179193Sjb				return (EINVAL);
12884179193Sjb			}
12885179193Sjb
12886179193Sjb			if ((rval = dtrace_state_option(state,
12887179193Sjb			    desc->dofo_option, desc->dofo_value)) != 0) {
12888179193Sjb				dtrace_dof_error(dof, "rejected option");
12889179193Sjb				return (rval);
12890179193Sjb			}
12891179193Sjb		}
12892179193Sjb	}
12893179193Sjb
12894179193Sjb	return (0);
12895179193Sjb}
12896179193Sjb
12897179193Sjb/*
12898179193Sjb * DTrace Consumer State Functions
12899179193Sjb */
12900179198Sjbstatic int
12901179193Sjbdtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12902179193Sjb{
12903179193Sjb	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12904179193Sjb	void *base;
12905179193Sjb	uintptr_t limit;
12906179193Sjb	dtrace_dynvar_t *dvar, *next, *start;
12907179193Sjb	int i;
12908179193Sjb
12909179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
12910179193Sjb	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12911179193Sjb
12912179193Sjb	bzero(dstate, sizeof (dtrace_dstate_t));
12913179193Sjb
12914179193Sjb	if ((dstate->dtds_chunksize = chunksize) == 0)
12915179193Sjb		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12916179193Sjb
12917179193Sjb	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12918179193Sjb		size = min;
12919179193Sjb
12920179193Sjb	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
12921179193Sjb		return (ENOMEM);
12922179193Sjb
12923179193Sjb	dstate->dtds_size = size;
12924179193Sjb	dstate->dtds_base = base;
12925179193Sjb	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12926179193Sjb	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12927179193Sjb
12928179193Sjb	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12929179193Sjb
12930179193Sjb	if (hashsize != 1 && (hashsize & 1))
12931179193Sjb		hashsize--;
12932179193Sjb
12933179193Sjb	dstate->dtds_hashsize = hashsize;
12934179193Sjb	dstate->dtds_hash = dstate->dtds_base;
12935179193Sjb
12936179193Sjb	/*
12937179193Sjb	 * Set all of our hash buckets to point to the single sink, and (if
12938179193Sjb	 * it hasn't already been set), set the sink's hash value to be the
12939179193Sjb	 * sink sentinel value.  The sink is needed for dynamic variable
12940179193Sjb	 * lookups to know that they have iterated over an entire, valid hash
12941179193Sjb	 * chain.
12942179193Sjb	 */
12943179193Sjb	for (i = 0; i < hashsize; i++)
12944179193Sjb		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12945179193Sjb
12946179193Sjb	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12947179193Sjb		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12948179193Sjb
12949179193Sjb	/*
12950179193Sjb	 * Determine number of active CPUs.  Divide free list evenly among
12951179193Sjb	 * active CPUs.
12952179193Sjb	 */
12953179193Sjb	start = (dtrace_dynvar_t *)
12954179193Sjb	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12955179193Sjb	limit = (uintptr_t)base + size;
12956179193Sjb
12957179193Sjb	maxper = (limit - (uintptr_t)start) / NCPU;
12958179193Sjb	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12959179193Sjb
12960209059Sjhb#if !defined(sun)
12961209059Sjhb	CPU_FOREACH(i) {
12962209059Sjhb#else
12963179193Sjb	for (i = 0; i < NCPU; i++) {
12964179198Sjb#endif
12965179193Sjb		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12966179193Sjb
12967179193Sjb		/*
12968179193Sjb		 * If we don't even have enough chunks to make it once through
12969179193Sjb		 * NCPUs, we're just going to allocate everything to the first
12970179193Sjb		 * CPU.  And if we're on the last CPU, we're going to allocate
12971179193Sjb		 * whatever is left over.  In either case, we set the limit to
12972179193Sjb		 * be the limit of the dynamic variable space.
12973179193Sjb		 */
12974179193Sjb		if (maxper == 0 || i == NCPU - 1) {
12975179193Sjb			limit = (uintptr_t)base + size;
12976179193Sjb			start = NULL;
12977179193Sjb		} else {
12978179193Sjb			limit = (uintptr_t)start + maxper;
12979179193Sjb			start = (dtrace_dynvar_t *)limit;
12980179193Sjb		}
12981179193Sjb
12982179193Sjb		ASSERT(limit <= (uintptr_t)base + size);
12983179193Sjb
12984179193Sjb		for (;;) {
12985179193Sjb			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12986179193Sjb			    dstate->dtds_chunksize);
12987179193Sjb
12988179193Sjb			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12989179193Sjb				break;
12990179193Sjb
12991179193Sjb			dvar->dtdv_next = next;
12992179193Sjb			dvar = next;
12993179193Sjb		}
12994179193Sjb
12995179193Sjb		if (maxper == 0)
12996179193Sjb			break;
12997179193Sjb	}
12998179193Sjb
12999179193Sjb	return (0);
13000179193Sjb}
13001179193Sjb
13002179198Sjbstatic void
13003179193Sjbdtrace_dstate_fini(dtrace_dstate_t *dstate)
13004179193Sjb{
13005179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
13006179193Sjb
13007179193Sjb	if (dstate->dtds_base == NULL)
13008179193Sjb		return;
13009179193Sjb
13010179193Sjb	kmem_free(dstate->dtds_base, dstate->dtds_size);
13011179193Sjb	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13012179193Sjb}
13013179193Sjb
13014179193Sjbstatic void
13015179193Sjbdtrace_vstate_fini(dtrace_vstate_t *vstate)
13016179193Sjb{
13017179193Sjb	/*
13018179193Sjb	 * Logical XOR, where are you?
13019179193Sjb	 */
13020179193Sjb	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13021179193Sjb
13022179193Sjb	if (vstate->dtvs_nglobals > 0) {
13023179193Sjb		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13024179193Sjb		    sizeof (dtrace_statvar_t *));
13025179193Sjb	}
13026179193Sjb
13027179193Sjb	if (vstate->dtvs_ntlocals > 0) {
13028179193Sjb		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13029179193Sjb		    sizeof (dtrace_difv_t));
13030179193Sjb	}
13031179193Sjb
13032179193Sjb	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13033179193Sjb
13034179193Sjb	if (vstate->dtvs_nlocals > 0) {
13035179193Sjb		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13036179193Sjb		    sizeof (dtrace_statvar_t *));
13037179193Sjb	}
13038179193Sjb}
13039179193Sjb
13040179469Sjb#if defined(sun)
13041179193Sjbstatic void
13042179193Sjbdtrace_state_clean(dtrace_state_t *state)
13043179193Sjb{
13044179193Sjb	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13045179193Sjb		return;
13046179193Sjb
13047179193Sjb	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13048179193Sjb	dtrace_speculation_clean(state);
13049179193Sjb}
13050179193Sjb
13051179193Sjbstatic void
13052179193Sjbdtrace_state_deadman(dtrace_state_t *state)
13053179193Sjb{
13054179193Sjb	hrtime_t now;
13055179193Sjb
13056179193Sjb	dtrace_sync();
13057179193Sjb
13058179469Sjb	now = dtrace_gethrtime();
13059179469Sjb
13060179469Sjb	if (state != dtrace_anon.dta_state &&
13061179469Sjb	    now - state->dts_laststatus >= dtrace_deadman_user)
13062179469Sjb		return;
13063179469Sjb
13064179469Sjb	/*
13065179469Sjb	 * We must be sure that dts_alive never appears to be less than the
13066179469Sjb	 * value upon entry to dtrace_state_deadman(), and because we lack a
13067179469Sjb	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13068179469Sjb	 * store INT64_MAX to it, followed by a memory barrier, followed by
13069179469Sjb	 * the new value.  This assures that dts_alive never appears to be
13070179469Sjb	 * less than its true value, regardless of the order in which the
13071179469Sjb	 * stores to the underlying storage are issued.
13072179469Sjb	 */
13073179469Sjb	state->dts_alive = INT64_MAX;
13074179469Sjb	dtrace_membar_producer();
13075179469Sjb	state->dts_alive = now;
13076179469Sjb}
13077179469Sjb#else
13078179469Sjbstatic void
13079179469Sjbdtrace_state_clean(void *arg)
13080179469Sjb{
13081179469Sjb	dtrace_state_t *state = arg;
13082179469Sjb	dtrace_optval_t *opt = state->dts_options;
13083179469Sjb
13084179469Sjb	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13085179469Sjb		return;
13086179469Sjb
13087179469Sjb	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13088179469Sjb	dtrace_speculation_clean(state);
13089179469Sjb
13090179469Sjb	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13091179469Sjb	    dtrace_state_clean, state);
13092179469Sjb}
13093179469Sjb
13094179469Sjbstatic void
13095179469Sjbdtrace_state_deadman(void *arg)
13096179469Sjb{
13097179469Sjb	dtrace_state_t *state = arg;
13098179469Sjb	hrtime_t now;
13099179469Sjb
13100179469Sjb	dtrace_sync();
13101179469Sjb
13102179198Sjb	dtrace_debug_output();
13103179198Sjb
13104179193Sjb	now = dtrace_gethrtime();
13105179193Sjb
13106179193Sjb	if (state != dtrace_anon.dta_state &&
13107179193Sjb	    now - state->dts_laststatus >= dtrace_deadman_user)
13108179193Sjb		return;
13109179193Sjb
13110179193Sjb	/*
13111179193Sjb	 * We must be sure that dts_alive never appears to be less than the
13112179193Sjb	 * value upon entry to dtrace_state_deadman(), and because we lack a
13113179193Sjb	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13114179193Sjb	 * store INT64_MAX to it, followed by a memory barrier, followed by
13115179193Sjb	 * the new value.  This assures that dts_alive never appears to be
13116179193Sjb	 * less than its true value, regardless of the order in which the
13117179193Sjb	 * stores to the underlying storage are issued.
13118179193Sjb	 */
13119179193Sjb	state->dts_alive = INT64_MAX;
13120179193Sjb	dtrace_membar_producer();
13121179193Sjb	state->dts_alive = now;
13122179469Sjb
13123179469Sjb	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13124179469Sjb	    dtrace_state_deadman, state);
13125179193Sjb}
13126179469Sjb#endif
13127179193Sjb
13128179198Sjbstatic dtrace_state_t *
13129179198Sjb#if defined(sun)
13130179193Sjbdtrace_state_create(dev_t *devp, cred_t *cr)
13131179198Sjb#else
13132179198Sjbdtrace_state_create(struct cdev *dev)
13133179198Sjb#endif
13134179193Sjb{
13135179198Sjb#if defined(sun)
13136179193Sjb	minor_t minor;
13137179193Sjb	major_t major;
13138179198Sjb#else
13139179198Sjb	cred_t *cr = NULL;
13140179198Sjb	int m = 0;
13141179198Sjb#endif
13142179193Sjb	char c[30];
13143179193Sjb	dtrace_state_t *state;
13144179193Sjb	dtrace_optval_t *opt;
13145179193Sjb	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13146179193Sjb
13147179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
13148179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
13149179193Sjb
13150179198Sjb#if defined(sun)
13151179193Sjb	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13152179193Sjb	    VM_BESTFIT | VM_SLEEP);
13153179193Sjb
13154179193Sjb	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13155179193Sjb		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13156179193Sjb		return (NULL);
13157179193Sjb	}
13158179193Sjb
13159179193Sjb	state = ddi_get_soft_state(dtrace_softstate, minor);
13160179198Sjb#else
13161179198Sjb	if (dev != NULL) {
13162184698Srodrigc		cr = dev->si_cred;
13163183397Sed		m = dev2unit(dev);
13164179198Sjb		}
13165179198Sjb
13166179198Sjb	/* Allocate memory for the state. */
13167179198Sjb	state = kmem_zalloc(sizeof(dtrace_state_t), KM_SLEEP);
13168179198Sjb#endif
13169179198Sjb
13170179193Sjb	state->dts_epid = DTRACE_EPIDNONE + 1;
13171179193Sjb
13172179198Sjb	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", m);
13173179198Sjb#if defined(sun)
13174179193Sjb	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13175179193Sjb	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13176179193Sjb
13177179193Sjb	if (devp != NULL) {
13178179193Sjb		major = getemajor(*devp);
13179179193Sjb	} else {
13180179193Sjb		major = ddi_driver_major(dtrace_devi);
13181179193Sjb	}
13182179193Sjb
13183179193Sjb	state->dts_dev = makedevice(major, minor);
13184179193Sjb
13185179193Sjb	if (devp != NULL)
13186179193Sjb		*devp = state->dts_dev;
13187179198Sjb#else
13188179198Sjb	state->dts_aggid_arena = new_unrhdr(1, INT_MAX, &dtrace_unr_mtx);
13189179198Sjb	state->dts_dev = dev;
13190179198Sjb#endif
13191179193Sjb
13192179193Sjb	/*
13193179193Sjb	 * We allocate NCPU buffers.  On the one hand, this can be quite
13194179193Sjb	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
13195179193Sjb	 * other hand, it saves an additional memory reference in the probe
13196179193Sjb	 * path.
13197179193Sjb	 */
13198179193Sjb	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13199179193Sjb	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13200179469Sjb
13201179469Sjb#if defined(sun)
13202179193Sjb	state->dts_cleaner = CYCLIC_NONE;
13203179193Sjb	state->dts_deadman = CYCLIC_NONE;
13204179469Sjb#else
13205179469Sjb	callout_init(&state->dts_cleaner, CALLOUT_MPSAFE);
13206179469Sjb	callout_init(&state->dts_deadman, CALLOUT_MPSAFE);
13207179469Sjb#endif
13208179193Sjb	state->dts_vstate.dtvs_state = state;
13209179193Sjb
13210179193Sjb	for (i = 0; i < DTRACEOPT_MAX; i++)
13211179193Sjb		state->dts_options[i] = DTRACEOPT_UNSET;
13212179193Sjb
13213179193Sjb	/*
13214179193Sjb	 * Set the default options.
13215179193Sjb	 */
13216179193Sjb	opt = state->dts_options;
13217179193Sjb	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13218179193Sjb	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13219179193Sjb	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13220179193Sjb	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13221179193Sjb	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13222179193Sjb	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13223179193Sjb	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13224179193Sjb	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13225179193Sjb	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13226179193Sjb	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13227179193Sjb	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13228179193Sjb	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13229179193Sjb	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13230179193Sjb	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13231179193Sjb
13232179193Sjb	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13233179193Sjb
13234179193Sjb	/*
13235179193Sjb	 * Depending on the user credentials, we set flag bits which alter probe
13236179193Sjb	 * visibility or the amount of destructiveness allowed.  In the case of
13237179193Sjb	 * actual anonymous tracing, or the possession of all privileges, all of
13238179193Sjb	 * the normal checks are bypassed.
13239179193Sjb	 */
13240179193Sjb	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13241179193Sjb		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13242179193Sjb		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13243179193Sjb	} else {
13244179193Sjb		/*
13245179193Sjb		 * Set up the credentials for this instantiation.  We take a
13246179193Sjb		 * hold on the credential to prevent it from disappearing on
13247179193Sjb		 * us; this in turn prevents the zone_t referenced by this
13248179193Sjb		 * credential from disappearing.  This means that we can
13249179193Sjb		 * examine the credential and the zone from probe context.
13250179193Sjb		 */
13251179193Sjb		crhold(cr);
13252179193Sjb		state->dts_cred.dcr_cred = cr;
13253179193Sjb
13254179193Sjb		/*
13255179193Sjb		 * CRA_PROC means "we have *some* privilege for dtrace" and
13256179193Sjb		 * unlocks the use of variables like pid, zonename, etc.
13257179193Sjb		 */
13258179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13259179193Sjb		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13260179193Sjb			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13261179193Sjb		}
13262179193Sjb
13263179193Sjb		/*
13264179193Sjb		 * dtrace_user allows use of syscall and profile providers.
13265179193Sjb		 * If the user also has proc_owner and/or proc_zone, we
13266179193Sjb		 * extend the scope to include additional visibility and
13267179193Sjb		 * destructive power.
13268179193Sjb		 */
13269179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13270179193Sjb			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13271179193Sjb				state->dts_cred.dcr_visible |=
13272179193Sjb				    DTRACE_CRV_ALLPROC;
13273179193Sjb
13274179193Sjb				state->dts_cred.dcr_action |=
13275179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13276179193Sjb			}
13277179193Sjb
13278179193Sjb			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13279179193Sjb				state->dts_cred.dcr_visible |=
13280179193Sjb				    DTRACE_CRV_ALLZONE;
13281179193Sjb
13282179193Sjb				state->dts_cred.dcr_action |=
13283179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13284179193Sjb			}
13285179193Sjb
13286179193Sjb			/*
13287179193Sjb			 * If we have all privs in whatever zone this is,
13288179193Sjb			 * we can do destructive things to processes which
13289179193Sjb			 * have altered credentials.
13290179193Sjb			 */
13291179198Sjb#if defined(sun)
13292179193Sjb			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13293179193Sjb			    cr->cr_zone->zone_privset)) {
13294179193Sjb				state->dts_cred.dcr_action |=
13295179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13296179193Sjb			}
13297179198Sjb#endif
13298179193Sjb		}
13299179193Sjb
13300179193Sjb		/*
13301179193Sjb		 * Holding the dtrace_kernel privilege also implies that
13302179193Sjb		 * the user has the dtrace_user privilege from a visibility
13303179193Sjb		 * perspective.  But without further privileges, some
13304179193Sjb		 * destructive actions are not available.
13305179193Sjb		 */
13306179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13307179193Sjb			/*
13308179193Sjb			 * Make all probes in all zones visible.  However,
13309179193Sjb			 * this doesn't mean that all actions become available
13310179193Sjb			 * to all zones.
13311179193Sjb			 */
13312179193Sjb			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13313179193Sjb			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13314179193Sjb
13315179193Sjb			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13316179193Sjb			    DTRACE_CRA_PROC;
13317179193Sjb			/*
13318179193Sjb			 * Holding proc_owner means that destructive actions
13319179193Sjb			 * for *this* zone are allowed.
13320179193Sjb			 */
13321179193Sjb			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13322179193Sjb				state->dts_cred.dcr_action |=
13323179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13324179193Sjb
13325179193Sjb			/*
13326179193Sjb			 * Holding proc_zone means that destructive actions
13327179193Sjb			 * for this user/group ID in all zones is allowed.
13328179193Sjb			 */
13329179193Sjb			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13330179193Sjb				state->dts_cred.dcr_action |=
13331179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13332179193Sjb
13333179198Sjb#if defined(sun)
13334179193Sjb			/*
13335179193Sjb			 * If we have all privs in whatever zone this is,
13336179193Sjb			 * we can do destructive things to processes which
13337179193Sjb			 * have altered credentials.
13338179193Sjb			 */
13339179193Sjb			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13340179193Sjb			    cr->cr_zone->zone_privset)) {
13341179193Sjb				state->dts_cred.dcr_action |=
13342179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13343179193Sjb			}
13344179198Sjb#endif
13345179193Sjb		}
13346179193Sjb
13347179193Sjb		/*
13348179193Sjb		 * Holding the dtrace_proc privilege gives control over fasttrap
13349179193Sjb		 * and pid providers.  We need to grant wider destructive
13350179193Sjb		 * privileges in the event that the user has proc_owner and/or
13351179193Sjb		 * proc_zone.
13352179193Sjb		 */
13353179193Sjb		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13354179193Sjb			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13355179193Sjb				state->dts_cred.dcr_action |=
13356179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13357179193Sjb
13358179193Sjb			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13359179193Sjb				state->dts_cred.dcr_action |=
13360179193Sjb				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13361179193Sjb		}
13362179193Sjb	}
13363179193Sjb
13364179193Sjb	return (state);
13365179193Sjb}
13366179193Sjb
13367179193Sjbstatic int
13368179193Sjbdtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13369179193Sjb{
13370179193Sjb	dtrace_optval_t *opt = state->dts_options, size;
13371179198Sjb	processorid_t cpu = 0;;
13372179193Sjb	int flags = 0, rval;
13373179193Sjb
13374179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
13375179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
13376179193Sjb	ASSERT(which < DTRACEOPT_MAX);
13377179193Sjb	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13378179193Sjb	    (state == dtrace_anon.dta_state &&
13379179193Sjb	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13380179193Sjb
13381179193Sjb	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13382179193Sjb		return (0);
13383179193Sjb
13384179193Sjb	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13385179193Sjb		cpu = opt[DTRACEOPT_CPU];
13386179193Sjb
13387179193Sjb	if (which == DTRACEOPT_SPECSIZE)
13388179193Sjb		flags |= DTRACEBUF_NOSWITCH;
13389179193Sjb
13390179193Sjb	if (which == DTRACEOPT_BUFSIZE) {
13391179193Sjb		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13392179193Sjb			flags |= DTRACEBUF_RING;
13393179193Sjb
13394179193Sjb		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13395179193Sjb			flags |= DTRACEBUF_FILL;
13396179193Sjb
13397179193Sjb		if (state != dtrace_anon.dta_state ||
13398179193Sjb		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13399179193Sjb			flags |= DTRACEBUF_INACTIVE;
13400179193Sjb	}
13401179193Sjb
13402179193Sjb	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
13403179193Sjb		/*
13404179193Sjb		 * The size must be 8-byte aligned.  If the size is not 8-byte
13405179193Sjb		 * aligned, drop it down by the difference.
13406179193Sjb		 */
13407179193Sjb		if (size & (sizeof (uint64_t) - 1))
13408179193Sjb			size -= size & (sizeof (uint64_t) - 1);
13409179193Sjb
13410179193Sjb		if (size < state->dts_reserve) {
13411179193Sjb			/*
13412179193Sjb			 * Buffers always must be large enough to accommodate
13413179193Sjb			 * their prereserved space.  We return E2BIG instead
13414179193Sjb			 * of ENOMEM in this case to allow for user-level
13415179193Sjb			 * software to differentiate the cases.
13416179193Sjb			 */
13417179193Sjb			return (E2BIG);
13418179193Sjb		}
13419179193Sjb
13420179193Sjb		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
13421179193Sjb
13422179193Sjb		if (rval != ENOMEM) {
13423179193Sjb			opt[which] = size;
13424179193Sjb			return (rval);
13425179193Sjb		}
13426179193Sjb
13427179193Sjb		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13428179193Sjb			return (rval);
13429179193Sjb	}
13430179193Sjb
13431179193Sjb	return (ENOMEM);
13432179193Sjb}
13433179193Sjb
13434179193Sjbstatic int
13435179193Sjbdtrace_state_buffers(dtrace_state_t *state)
13436179193Sjb{
13437179193Sjb	dtrace_speculation_t *spec = state->dts_speculations;
13438179193Sjb	int rval, i;
13439179193Sjb
13440179193Sjb	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13441179193Sjb	    DTRACEOPT_BUFSIZE)) != 0)
13442179193Sjb		return (rval);
13443179193Sjb
13444179193Sjb	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13445179193Sjb	    DTRACEOPT_AGGSIZE)) != 0)
13446179193Sjb		return (rval);
13447179193Sjb
13448179193Sjb	for (i = 0; i < state->dts_nspeculations; i++) {
13449179193Sjb		if ((rval = dtrace_state_buffer(state,
13450179193Sjb		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13451179193Sjb			return (rval);
13452179193Sjb	}
13453179193Sjb
13454179193Sjb	return (0);
13455179193Sjb}
13456179193Sjb
13457179193Sjbstatic void
13458179193Sjbdtrace_state_prereserve(dtrace_state_t *state)
13459179193Sjb{
13460179193Sjb	dtrace_ecb_t *ecb;
13461179193Sjb	dtrace_probe_t *probe;
13462179193Sjb
13463179193Sjb	state->dts_reserve = 0;
13464179193Sjb
13465179193Sjb	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13466179193Sjb		return;
13467179193Sjb
13468179193Sjb	/*
13469179193Sjb	 * If our buffer policy is a "fill" buffer policy, we need to set the
13470179193Sjb	 * prereserved space to be the space required by the END probes.
13471179193Sjb	 */
13472179193Sjb	probe = dtrace_probes[dtrace_probeid_end - 1];
13473179193Sjb	ASSERT(probe != NULL);
13474179193Sjb
13475179193Sjb	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13476179193Sjb		if (ecb->dte_state != state)
13477179193Sjb			continue;
13478179193Sjb
13479179193Sjb		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13480179193Sjb	}
13481179193Sjb}
13482179193Sjb
13483179193Sjbstatic int
13484179193Sjbdtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13485179193Sjb{
13486179193Sjb	dtrace_optval_t *opt = state->dts_options, sz, nspec;
13487179193Sjb	dtrace_speculation_t *spec;
13488179193Sjb	dtrace_buffer_t *buf;
13489179469Sjb#if defined(sun)
13490179193Sjb	cyc_handler_t hdlr;
13491179193Sjb	cyc_time_t when;
13492179469Sjb#endif
13493179193Sjb	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13494179193Sjb	dtrace_icookie_t cookie;
13495179193Sjb
13496179193Sjb	mutex_enter(&cpu_lock);
13497179193Sjb	mutex_enter(&dtrace_lock);
13498179193Sjb
13499179193Sjb	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13500179193Sjb		rval = EBUSY;
13501179193Sjb		goto out;
13502179193Sjb	}
13503179193Sjb
13504179193Sjb	/*
13505179193Sjb	 * Before we can perform any checks, we must prime all of the
13506179193Sjb	 * retained enablings that correspond to this state.
13507179193Sjb	 */
13508179193Sjb	dtrace_enabling_prime(state);
13509179193Sjb
13510179193Sjb	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13511179193Sjb		rval = EACCES;
13512179193Sjb		goto out;
13513179193Sjb	}
13514179193Sjb
13515179193Sjb	dtrace_state_prereserve(state);
13516179193Sjb
13517179193Sjb	/*
13518179193Sjb	 * Now we want to do is try to allocate our speculations.
13519179193Sjb	 * We do not automatically resize the number of speculations; if
13520179193Sjb	 * this fails, we will fail the operation.
13521179193Sjb	 */
13522179193Sjb	nspec = opt[DTRACEOPT_NSPEC];
13523179193Sjb	ASSERT(nspec != DTRACEOPT_UNSET);
13524179193Sjb
13525179193Sjb	if (nspec > INT_MAX) {
13526179193Sjb		rval = ENOMEM;
13527179193Sjb		goto out;
13528179193Sjb	}
13529179193Sjb
13530179193Sjb	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
13531179193Sjb
13532179193Sjb	if (spec == NULL) {
13533179193Sjb		rval = ENOMEM;
13534179193Sjb		goto out;
13535179193Sjb	}
13536179193Sjb
13537179193Sjb	state->dts_speculations = spec;
13538179193Sjb	state->dts_nspeculations = (int)nspec;
13539179193Sjb
13540179193Sjb	for (i = 0; i < nspec; i++) {
13541179193Sjb		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
13542179193Sjb			rval = ENOMEM;
13543179193Sjb			goto err;
13544179193Sjb		}
13545179193Sjb
13546179193Sjb		spec[i].dtsp_buffer = buf;
13547179193Sjb	}
13548179193Sjb
13549179193Sjb	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13550179193Sjb		if (dtrace_anon.dta_state == NULL) {
13551179193Sjb			rval = ENOENT;
13552179193Sjb			goto out;
13553179193Sjb		}
13554179193Sjb
13555179193Sjb		if (state->dts_necbs != 0) {
13556179193Sjb			rval = EALREADY;
13557179193Sjb			goto out;
13558179193Sjb		}
13559179193Sjb
13560179193Sjb		state->dts_anon = dtrace_anon_grab();
13561179193Sjb		ASSERT(state->dts_anon != NULL);
13562179193Sjb		state = state->dts_anon;
13563179193Sjb
13564179193Sjb		/*
13565179193Sjb		 * We want "grabanon" to be set in the grabbed state, so we'll
13566179193Sjb		 * copy that option value from the grabbing state into the
13567179193Sjb		 * grabbed state.
13568179193Sjb		 */
13569179193Sjb		state->dts_options[DTRACEOPT_GRABANON] =
13570179193Sjb		    opt[DTRACEOPT_GRABANON];
13571179193Sjb
13572179193Sjb		*cpu = dtrace_anon.dta_beganon;
13573179193Sjb
13574179193Sjb		/*
13575179193Sjb		 * If the anonymous state is active (as it almost certainly
13576179193Sjb		 * is if the anonymous enabling ultimately matched anything),
13577179193Sjb		 * we don't allow any further option processing -- but we
13578179193Sjb		 * don't return failure.
13579179193Sjb		 */
13580179193Sjb		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13581179193Sjb			goto out;
13582179193Sjb	}
13583179193Sjb
13584179193Sjb	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13585179193Sjb	    opt[DTRACEOPT_AGGSIZE] != 0) {
13586179193Sjb		if (state->dts_aggregations == NULL) {
13587179193Sjb			/*
13588179193Sjb			 * We're not going to create an aggregation buffer
13589179193Sjb			 * because we don't have any ECBs that contain
13590179193Sjb			 * aggregations -- set this option to 0.
13591179193Sjb			 */
13592179193Sjb			opt[DTRACEOPT_AGGSIZE] = 0;
13593179193Sjb		} else {
13594179193Sjb			/*
13595179193Sjb			 * If we have an aggregation buffer, we must also have
13596179193Sjb			 * a buffer to use as scratch.
13597179193Sjb			 */
13598179193Sjb			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13599179193Sjb			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13600179193Sjb				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13601179193Sjb			}
13602179193Sjb		}
13603179193Sjb	}
13604179193Sjb
13605179193Sjb	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13606179193Sjb	    opt[DTRACEOPT_SPECSIZE] != 0) {
13607179193Sjb		if (!state->dts_speculates) {
13608179193Sjb			/*
13609179193Sjb			 * We're not going to create speculation buffers
13610179193Sjb			 * because we don't have any ECBs that actually
13611179193Sjb			 * speculate -- set the speculation size to 0.
13612179193Sjb			 */
13613179193Sjb			opt[DTRACEOPT_SPECSIZE] = 0;
13614179193Sjb		}
13615179193Sjb	}
13616179193Sjb
13617179193Sjb	/*
13618179193Sjb	 * The bare minimum size for any buffer that we're actually going to
13619179193Sjb	 * do anything to is sizeof (uint64_t).
13620179193Sjb	 */
13621179193Sjb	sz = sizeof (uint64_t);
13622179193Sjb
13623179193Sjb	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13624179193Sjb	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13625179193Sjb	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13626179193Sjb		/*
13627179193Sjb		 * A buffer size has been explicitly set to 0 (or to a size
13628179193Sjb		 * that will be adjusted to 0) and we need the space -- we
13629179193Sjb		 * need to return failure.  We return ENOSPC to differentiate
13630179193Sjb		 * it from failing to allocate a buffer due to failure to meet
13631179193Sjb		 * the reserve (for which we return E2BIG).
13632179193Sjb		 */
13633179193Sjb		rval = ENOSPC;
13634179193Sjb		goto out;
13635179193Sjb	}
13636179193Sjb
13637179193Sjb	if ((rval = dtrace_state_buffers(state)) != 0)
13638179193Sjb		goto err;
13639179193Sjb
13640179193Sjb	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13641179193Sjb		sz = dtrace_dstate_defsize;
13642179193Sjb
13643179193Sjb	do {
13644179193Sjb		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13645179193Sjb
13646179193Sjb		if (rval == 0)
13647179193Sjb			break;
13648179193Sjb
13649179193Sjb		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13650179193Sjb			goto err;
13651179193Sjb	} while (sz >>= 1);
13652179193Sjb
13653179193Sjb	opt[DTRACEOPT_DYNVARSIZE] = sz;
13654179193Sjb
13655179193Sjb	if (rval != 0)
13656179193Sjb		goto err;
13657179193Sjb
13658179193Sjb	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13659179193Sjb		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13660179193Sjb
13661179193Sjb	if (opt[DTRACEOPT_CLEANRATE] == 0)
13662179193Sjb		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13663179193Sjb
13664179193Sjb	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13665179193Sjb		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13666179193Sjb
13667179193Sjb	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13668179193Sjb		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13669179193Sjb
13670179469Sjb	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13671179469Sjb#if defined(sun)
13672179193Sjb	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13673179193Sjb	hdlr.cyh_arg = state;
13674179193Sjb	hdlr.cyh_level = CY_LOW_LEVEL;
13675179193Sjb
13676179193Sjb	when.cyt_when = 0;
13677179193Sjb	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13678179193Sjb
13679179193Sjb	state->dts_cleaner = cyclic_add(&hdlr, &when);
13680179193Sjb
13681179193Sjb	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13682179193Sjb	hdlr.cyh_arg = state;
13683179193Sjb	hdlr.cyh_level = CY_LOW_LEVEL;
13684179193Sjb
13685179193Sjb	when.cyt_when = 0;
13686179193Sjb	when.cyt_interval = dtrace_deadman_interval;
13687179193Sjb
13688179193Sjb	state->dts_deadman = cyclic_add(&hdlr, &when);
13689179469Sjb#else
13690179469Sjb	callout_reset(&state->dts_cleaner, hz * opt[DTRACEOPT_CLEANRATE] / NANOSEC,
13691179469Sjb	    dtrace_state_clean, state);
13692179469Sjb	callout_reset(&state->dts_deadman, hz * dtrace_deadman_interval / NANOSEC,
13693179469Sjb	    dtrace_state_deadman, state);
13694179469Sjb#endif
13695179193Sjb
13696179193Sjb	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13697179193Sjb
13698179193Sjb	/*
13699179193Sjb	 * Now it's time to actually fire the BEGIN probe.  We need to disable
13700179193Sjb	 * interrupts here both to record the CPU on which we fired the BEGIN
13701179193Sjb	 * probe (the data from this CPU will be processed first at user
13702179193Sjb	 * level) and to manually activate the buffer for this CPU.
13703179193Sjb	 */
13704179193Sjb	cookie = dtrace_interrupt_disable();
13705179198Sjb	*cpu = curcpu;
13706179193Sjb	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13707179193Sjb	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13708179193Sjb
13709179193Sjb	dtrace_probe(dtrace_probeid_begin,
13710179193Sjb	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13711179193Sjb	dtrace_interrupt_enable(cookie);
13712179193Sjb	/*
13713179193Sjb	 * We may have had an exit action from a BEGIN probe; only change our
13714179193Sjb	 * state to ACTIVE if we're still in WARMUP.
13715179193Sjb	 */
13716179193Sjb	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13717179193Sjb	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13718179193Sjb
13719179193Sjb	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13720179193Sjb		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13721179193Sjb
13722179193Sjb	/*
13723179193Sjb	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13724179193Sjb	 * want each CPU to transition its principal buffer out of the
13725179193Sjb	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
13726179193Sjb	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13727179193Sjb	 * atomically transition from processing none of a state's ECBs to
13728179193Sjb	 * processing all of them.
13729179193Sjb	 */
13730179193Sjb	dtrace_xcall(DTRACE_CPUALL,
13731179193Sjb	    (dtrace_xcall_t)dtrace_buffer_activate, state);
13732179193Sjb	goto out;
13733179193Sjb
13734179193Sjberr:
13735179193Sjb	dtrace_buffer_free(state->dts_buffer);
13736179193Sjb	dtrace_buffer_free(state->dts_aggbuffer);
13737179193Sjb
13738179193Sjb	if ((nspec = state->dts_nspeculations) == 0) {
13739179193Sjb		ASSERT(state->dts_speculations == NULL);
13740179193Sjb		goto out;
13741179193Sjb	}
13742179193Sjb
13743179193Sjb	spec = state->dts_speculations;
13744179193Sjb	ASSERT(spec != NULL);
13745179193Sjb
13746179193Sjb	for (i = 0; i < state->dts_nspeculations; i++) {
13747179193Sjb		if ((buf = spec[i].dtsp_buffer) == NULL)
13748179193Sjb			break;
13749179193Sjb
13750179193Sjb		dtrace_buffer_free(buf);
13751179193Sjb		kmem_free(buf, bufsize);
13752179193Sjb	}
13753179193Sjb
13754179193Sjb	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13755179193Sjb	state->dts_nspeculations = 0;
13756179193Sjb	state->dts_speculations = NULL;
13757179193Sjb
13758179193Sjbout:
13759179193Sjb	mutex_exit(&dtrace_lock);
13760179193Sjb	mutex_exit(&cpu_lock);
13761179193Sjb
13762179193Sjb	return (rval);
13763179193Sjb}
13764179193Sjb
13765179193Sjbstatic int
13766179193Sjbdtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13767179193Sjb{
13768179193Sjb	dtrace_icookie_t cookie;
13769179193Sjb
13770179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
13771179193Sjb
13772179193Sjb	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13773179193Sjb	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13774179193Sjb		return (EINVAL);
13775179193Sjb
13776179193Sjb	/*
13777179193Sjb	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13778179193Sjb	 * to be sure that every CPU has seen it.  See below for the details
13779179193Sjb	 * on why this is done.
13780179193Sjb	 */
13781179193Sjb	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13782179193Sjb	dtrace_sync();
13783179193Sjb
13784179193Sjb	/*
13785179193Sjb	 * By this point, it is impossible for any CPU to be still processing
13786179193Sjb	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
13787179193Sjb	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13788179193Sjb	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
13789179193Sjb	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13790179193Sjb	 * iff we're in the END probe.
13791179193Sjb	 */
13792179193Sjb	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13793179193Sjb	dtrace_sync();
13794179193Sjb	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13795179193Sjb
13796179193Sjb	/*
13797179193Sjb	 * Finally, we can release the reserve and call the END probe.  We
13798179193Sjb	 * disable interrupts across calling the END probe to allow us to
13799179193Sjb	 * return the CPU on which we actually called the END probe.  This
13800179193Sjb	 * allows user-land to be sure that this CPU's principal buffer is
13801179193Sjb	 * processed last.
13802179193Sjb	 */
13803179193Sjb	state->dts_reserve = 0;
13804179193Sjb
13805179193Sjb	cookie = dtrace_interrupt_disable();
13806179198Sjb	*cpu = curcpu;
13807179193Sjb	dtrace_probe(dtrace_probeid_end,
13808179193Sjb	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13809179193Sjb	dtrace_interrupt_enable(cookie);
13810179193Sjb
13811179193Sjb	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13812179193Sjb	dtrace_sync();
13813179193Sjb
13814179193Sjb	return (0);
13815179193Sjb}
13816179193Sjb
13817179193Sjbstatic int
13818179193Sjbdtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13819179193Sjb    dtrace_optval_t val)
13820179193Sjb{
13821179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
13822179193Sjb
13823179193Sjb	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13824179193Sjb		return (EBUSY);
13825179193Sjb
13826179193Sjb	if (option >= DTRACEOPT_MAX)
13827179193Sjb		return (EINVAL);
13828179193Sjb
13829179193Sjb	if (option != DTRACEOPT_CPU && val < 0)
13830179193Sjb		return (EINVAL);
13831179193Sjb
13832179193Sjb	switch (option) {
13833179193Sjb	case DTRACEOPT_DESTRUCTIVE:
13834179193Sjb		if (dtrace_destructive_disallow)
13835179193Sjb			return (EACCES);
13836179193Sjb
13837179193Sjb		state->dts_cred.dcr_destructive = 1;
13838179193Sjb		break;
13839179193Sjb
13840179193Sjb	case DTRACEOPT_BUFSIZE:
13841179193Sjb	case DTRACEOPT_DYNVARSIZE:
13842179193Sjb	case DTRACEOPT_AGGSIZE:
13843179193Sjb	case DTRACEOPT_SPECSIZE:
13844179193Sjb	case DTRACEOPT_STRSIZE:
13845179193Sjb		if (val < 0)
13846179193Sjb			return (EINVAL);
13847179193Sjb
13848179193Sjb		if (val >= LONG_MAX) {
13849179193Sjb			/*
13850179193Sjb			 * If this is an otherwise negative value, set it to
13851179193Sjb			 * the highest multiple of 128m less than LONG_MAX.
13852179193Sjb			 * Technically, we're adjusting the size without
13853179193Sjb			 * regard to the buffer resizing policy, but in fact,
13854179193Sjb			 * this has no effect -- if we set the buffer size to
13855179193Sjb			 * ~LONG_MAX and the buffer policy is ultimately set to
13856179193Sjb			 * be "manual", the buffer allocation is guaranteed to
13857179193Sjb			 * fail, if only because the allocation requires two
13858179193Sjb			 * buffers.  (We set the the size to the highest
13859179193Sjb			 * multiple of 128m because it ensures that the size
13860179193Sjb			 * will remain a multiple of a megabyte when
13861179193Sjb			 * repeatedly halved -- all the way down to 15m.)
13862179193Sjb			 */
13863179193Sjb			val = LONG_MAX - (1 << 27) + 1;
13864179193Sjb		}
13865179193Sjb	}
13866179193Sjb
13867179193Sjb	state->dts_options[option] = val;
13868179193Sjb
13869179193Sjb	return (0);
13870179193Sjb}
13871179193Sjb
13872179193Sjbstatic void
13873179193Sjbdtrace_state_destroy(dtrace_state_t *state)
13874179193Sjb{
13875179193Sjb	dtrace_ecb_t *ecb;
13876179193Sjb	dtrace_vstate_t *vstate = &state->dts_vstate;
13877179198Sjb#if defined(sun)
13878179193Sjb	minor_t minor = getminor(state->dts_dev);
13879179198Sjb#endif
13880179193Sjb	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13881179193Sjb	dtrace_speculation_t *spec = state->dts_speculations;
13882179193Sjb	int nspec = state->dts_nspeculations;
13883179193Sjb	uint32_t match;
13884179193Sjb
13885179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
13886179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
13887179193Sjb
13888179193Sjb	/*
13889179193Sjb	 * First, retract any retained enablings for this state.
13890179193Sjb	 */
13891179193Sjb	dtrace_enabling_retract(state);
13892179193Sjb	ASSERT(state->dts_nretained == 0);
13893179193Sjb
13894179193Sjb	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13895179193Sjb	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13896179193Sjb		/*
13897179193Sjb		 * We have managed to come into dtrace_state_destroy() on a
13898179193Sjb		 * hot enabling -- almost certainly because of a disorderly
13899179193Sjb		 * shutdown of a consumer.  (That is, a consumer that is
13900179193Sjb		 * exiting without having called dtrace_stop().) In this case,
13901179193Sjb		 * we're going to set our activity to be KILLED, and then
13902179193Sjb		 * issue a sync to be sure that everyone is out of probe
13903179193Sjb		 * context before we start blowing away ECBs.
13904179193Sjb		 */
13905179193Sjb		state->dts_activity = DTRACE_ACTIVITY_KILLED;
13906179193Sjb		dtrace_sync();
13907179193Sjb	}
13908179193Sjb
13909179193Sjb	/*
13910179193Sjb	 * Release the credential hold we took in dtrace_state_create().
13911179193Sjb	 */
13912179193Sjb	if (state->dts_cred.dcr_cred != NULL)
13913179193Sjb		crfree(state->dts_cred.dcr_cred);
13914179193Sjb
13915179193Sjb	/*
13916179193Sjb	 * Now we can safely disable and destroy any enabled probes.  Because
13917179193Sjb	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13918179193Sjb	 * (especially if they're all enabled), we take two passes through the
13919179193Sjb	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13920179193Sjb	 * in the second we disable whatever is left over.
13921179193Sjb	 */
13922179193Sjb	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13923179193Sjb		for (i = 0; i < state->dts_necbs; i++) {
13924179193Sjb			if ((ecb = state->dts_ecbs[i]) == NULL)
13925179193Sjb				continue;
13926179193Sjb
13927179193Sjb			if (match && ecb->dte_probe != NULL) {
13928179193Sjb				dtrace_probe_t *probe = ecb->dte_probe;
13929179193Sjb				dtrace_provider_t *prov = probe->dtpr_provider;
13930179193Sjb
13931179193Sjb				if (!(prov->dtpv_priv.dtpp_flags & match))
13932179193Sjb					continue;
13933179193Sjb			}
13934179193Sjb
13935179193Sjb			dtrace_ecb_disable(ecb);
13936179193Sjb			dtrace_ecb_destroy(ecb);
13937179193Sjb		}
13938179193Sjb
13939179193Sjb		if (!match)
13940179193Sjb			break;
13941179193Sjb	}
13942179193Sjb
13943179193Sjb	/*
13944179193Sjb	 * Before we free the buffers, perform one more sync to assure that
13945179193Sjb	 * every CPU is out of probe context.
13946179193Sjb	 */
13947179193Sjb	dtrace_sync();
13948179193Sjb
13949179193Sjb	dtrace_buffer_free(state->dts_buffer);
13950179193Sjb	dtrace_buffer_free(state->dts_aggbuffer);
13951179193Sjb
13952179193Sjb	for (i = 0; i < nspec; i++)
13953179193Sjb		dtrace_buffer_free(spec[i].dtsp_buffer);
13954179193Sjb
13955179469Sjb#if defined(sun)
13956179193Sjb	if (state->dts_cleaner != CYCLIC_NONE)
13957179193Sjb		cyclic_remove(state->dts_cleaner);
13958179193Sjb
13959179193Sjb	if (state->dts_deadman != CYCLIC_NONE)
13960179193Sjb		cyclic_remove(state->dts_deadman);
13961179469Sjb#else
13962179469Sjb	callout_stop(&state->dts_cleaner);
13963181879Sjb	callout_drain(&state->dts_cleaner);
13964179469Sjb	callout_stop(&state->dts_deadman);
13965181879Sjb	callout_drain(&state->dts_deadman);
13966179469Sjb#endif
13967179193Sjb
13968179193Sjb	dtrace_dstate_fini(&vstate->dtvs_dynvars);
13969179193Sjb	dtrace_vstate_fini(vstate);
13970179198Sjb	if (state->dts_ecbs != NULL)
13971179198Sjb		kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13972179193Sjb
13973179193Sjb	if (state->dts_aggregations != NULL) {
13974179193Sjb#ifdef DEBUG
13975179193Sjb		for (i = 0; i < state->dts_naggregations; i++)
13976179193Sjb			ASSERT(state->dts_aggregations[i] == NULL);
13977179193Sjb#endif
13978179193Sjb		ASSERT(state->dts_naggregations > 0);
13979179193Sjb		kmem_free(state->dts_aggregations,
13980179193Sjb		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13981179193Sjb	}
13982179193Sjb
13983179193Sjb	kmem_free(state->dts_buffer, bufsize);
13984179193Sjb	kmem_free(state->dts_aggbuffer, bufsize);
13985179193Sjb
13986179193Sjb	for (i = 0; i < nspec; i++)
13987179193Sjb		kmem_free(spec[i].dtsp_buffer, bufsize);
13988179193Sjb
13989179198Sjb	if (spec != NULL)
13990179198Sjb		kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13991179193Sjb
13992179193Sjb	dtrace_format_destroy(state);
13993179193Sjb
13994179198Sjb	if (state->dts_aggid_arena != NULL) {
13995179198Sjb#if defined(sun)
13996179198Sjb		vmem_destroy(state->dts_aggid_arena);
13997179198Sjb#else
13998179198Sjb		delete_unrhdr(state->dts_aggid_arena);
13999179198Sjb#endif
14000179198Sjb		state->dts_aggid_arena = NULL;
14001179198Sjb	}
14002179198Sjb#if defined(sun)
14003179193Sjb	ddi_soft_state_free(dtrace_softstate, minor);
14004179193Sjb	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14005179198Sjb#endif
14006179193Sjb}
14007179193Sjb
14008179193Sjb/*
14009179193Sjb * DTrace Anonymous Enabling Functions
14010179193Sjb */
14011179193Sjbstatic dtrace_state_t *
14012179193Sjbdtrace_anon_grab(void)
14013179193Sjb{
14014179193Sjb	dtrace_state_t *state;
14015179193Sjb
14016179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
14017179193Sjb
14018179193Sjb	if ((state = dtrace_anon.dta_state) == NULL) {
14019179193Sjb		ASSERT(dtrace_anon.dta_enabling == NULL);
14020179193Sjb		return (NULL);
14021179193Sjb	}
14022179193Sjb
14023179193Sjb	ASSERT(dtrace_anon.dta_enabling != NULL);
14024179193Sjb	ASSERT(dtrace_retained != NULL);
14025179193Sjb
14026179193Sjb	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14027179193Sjb	dtrace_anon.dta_enabling = NULL;
14028179193Sjb	dtrace_anon.dta_state = NULL;
14029179193Sjb
14030179193Sjb	return (state);
14031179193Sjb}
14032179193Sjb
14033179193Sjbstatic void
14034179193Sjbdtrace_anon_property(void)
14035179193Sjb{
14036179193Sjb	int i, rv;
14037179193Sjb	dtrace_state_t *state;
14038179193Sjb	dof_hdr_t *dof;
14039179193Sjb	char c[32];		/* enough for "dof-data-" + digits */
14040179193Sjb
14041179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
14042179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
14043179193Sjb
14044179193Sjb	for (i = 0; ; i++) {
14045179193Sjb		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
14046179193Sjb
14047179193Sjb		dtrace_err_verbose = 1;
14048179193Sjb
14049179193Sjb		if ((dof = dtrace_dof_property(c)) == NULL) {
14050179193Sjb			dtrace_err_verbose = 0;
14051179193Sjb			break;
14052179193Sjb		}
14053179193Sjb
14054179198Sjb#if defined(sun)
14055179193Sjb		/*
14056179193Sjb		 * We want to create anonymous state, so we need to transition
14057179193Sjb		 * the kernel debugger to indicate that DTrace is active.  If
14058179193Sjb		 * this fails (e.g. because the debugger has modified text in
14059179193Sjb		 * some way), we won't continue with the processing.
14060179193Sjb		 */
14061179193Sjb		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14062179193Sjb			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14063179193Sjb			    "enabling ignored.");
14064179193Sjb			dtrace_dof_destroy(dof);
14065179193Sjb			break;
14066179193Sjb		}
14067179198Sjb#endif
14068179193Sjb
14069179193Sjb		/*
14070179193Sjb		 * If we haven't allocated an anonymous state, we'll do so now.
14071179193Sjb		 */
14072179193Sjb		if ((state = dtrace_anon.dta_state) == NULL) {
14073179198Sjb#if defined(sun)
14074179193Sjb			state = dtrace_state_create(NULL, NULL);
14075179198Sjb#else
14076179198Sjb			state = dtrace_state_create(NULL);
14077179198Sjb#endif
14078179193Sjb			dtrace_anon.dta_state = state;
14079179193Sjb
14080179193Sjb			if (state == NULL) {
14081179193Sjb				/*
14082179193Sjb				 * This basically shouldn't happen:  the only
14083179193Sjb				 * failure mode from dtrace_state_create() is a
14084179193Sjb				 * failure of ddi_soft_state_zalloc() that
14085179193Sjb				 * itself should never happen.  Still, the
14086179193Sjb				 * interface allows for a failure mode, and
14087179193Sjb				 * we want to fail as gracefully as possible:
14088179193Sjb				 * we'll emit an error message and cease
14089179193Sjb				 * processing anonymous state in this case.
14090179193Sjb				 */
14091179193Sjb				cmn_err(CE_WARN, "failed to create "
14092179193Sjb				    "anonymous state");
14093179193Sjb				dtrace_dof_destroy(dof);
14094179193Sjb				break;
14095179193Sjb			}
14096179193Sjb		}
14097179193Sjb
14098179193Sjb		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14099179193Sjb		    &dtrace_anon.dta_enabling, 0, B_TRUE);
14100179193Sjb
14101179193Sjb		if (rv == 0)
14102179193Sjb			rv = dtrace_dof_options(dof, state);
14103179193Sjb
14104179193Sjb		dtrace_err_verbose = 0;
14105179193Sjb		dtrace_dof_destroy(dof);
14106179193Sjb
14107179193Sjb		if (rv != 0) {
14108179193Sjb			/*
14109179193Sjb			 * This is malformed DOF; chuck any anonymous state
14110179193Sjb			 * that we created.
14111179193Sjb			 */
14112179193Sjb			ASSERT(dtrace_anon.dta_enabling == NULL);
14113179193Sjb			dtrace_state_destroy(state);
14114179193Sjb			dtrace_anon.dta_state = NULL;
14115179193Sjb			break;
14116179193Sjb		}
14117179193Sjb
14118179193Sjb		ASSERT(dtrace_anon.dta_enabling != NULL);
14119179193Sjb	}
14120179193Sjb
14121179193Sjb	if (dtrace_anon.dta_enabling != NULL) {
14122179193Sjb		int rval;
14123179193Sjb
14124179193Sjb		/*
14125179193Sjb		 * dtrace_enabling_retain() can only fail because we are
14126179193Sjb		 * trying to retain more enablings than are allowed -- but
14127179193Sjb		 * we only have one anonymous enabling, and we are guaranteed
14128179193Sjb		 * to be allowed at least one retained enabling; we assert
14129179193Sjb		 * that dtrace_enabling_retain() returns success.
14130179193Sjb		 */
14131179193Sjb		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14132179193Sjb		ASSERT(rval == 0);
14133179193Sjb
14134179193Sjb		dtrace_enabling_dump(dtrace_anon.dta_enabling);
14135179193Sjb	}
14136179193Sjb}
14137179193Sjb
14138179193Sjb/*
14139179193Sjb * DTrace Helper Functions
14140179193Sjb */
14141179193Sjbstatic void
14142179193Sjbdtrace_helper_trace(dtrace_helper_action_t *helper,
14143179193Sjb    dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14144179193Sjb{
14145179193Sjb	uint32_t size, next, nnext, i;
14146179193Sjb	dtrace_helptrace_t *ent;
14147179198Sjb	uint16_t flags = cpu_core[curcpu].cpuc_dtrace_flags;
14148179193Sjb
14149179193Sjb	if (!dtrace_helptrace_enabled)
14150179193Sjb		return;
14151179193Sjb
14152179193Sjb	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14153179193Sjb
14154179193Sjb	/*
14155179193Sjb	 * What would a tracing framework be without its own tracing
14156179193Sjb	 * framework?  (Well, a hell of a lot simpler, for starters...)
14157179193Sjb	 */
14158179193Sjb	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14159179193Sjb	    sizeof (uint64_t) - sizeof (uint64_t);
14160179193Sjb
14161179193Sjb	/*
14162179193Sjb	 * Iterate until we can allocate a slot in the trace buffer.
14163179193Sjb	 */
14164179193Sjb	do {
14165179193Sjb		next = dtrace_helptrace_next;
14166179193Sjb
14167179193Sjb		if (next + size < dtrace_helptrace_bufsize) {
14168179193Sjb			nnext = next + size;
14169179193Sjb		} else {
14170179193Sjb			nnext = size;
14171179193Sjb		}
14172179193Sjb	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14173179193Sjb
14174179193Sjb	/*
14175179193Sjb	 * We have our slot; fill it in.
14176179193Sjb	 */
14177179193Sjb	if (nnext == size)
14178179193Sjb		next = 0;
14179179193Sjb
14180179193Sjb	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
14181179193Sjb	ent->dtht_helper = helper;
14182179193Sjb	ent->dtht_where = where;
14183179193Sjb	ent->dtht_nlocals = vstate->dtvs_nlocals;
14184179193Sjb
14185179193Sjb	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14186179193Sjb	    mstate->dtms_fltoffs : -1;
14187179193Sjb	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14188179198Sjb	ent->dtht_illval = cpu_core[curcpu].cpuc_dtrace_illval;
14189179193Sjb
14190179193Sjb	for (i = 0; i < vstate->dtvs_nlocals; i++) {
14191179193Sjb		dtrace_statvar_t *svar;
14192179193Sjb
14193179193Sjb		if ((svar = vstate->dtvs_locals[i]) == NULL)
14194179193Sjb			continue;
14195179193Sjb
14196179193Sjb		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14197179193Sjb		ent->dtht_locals[i] =
14198179198Sjb		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[curcpu];
14199179193Sjb	}
14200179193Sjb}
14201179193Sjb
14202179193Sjbstatic uint64_t
14203179193Sjbdtrace_helper(int which, dtrace_mstate_t *mstate,
14204179193Sjb    dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14205179193Sjb{
14206179198Sjb	uint16_t *flags = &cpu_core[curcpu].cpuc_dtrace_flags;
14207179193Sjb	uint64_t sarg0 = mstate->dtms_arg[0];
14208179193Sjb	uint64_t sarg1 = mstate->dtms_arg[1];
14209211608Srpaulo	uint64_t rval = 0;
14210179193Sjb	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14211179193Sjb	dtrace_helper_action_t *helper;
14212179193Sjb	dtrace_vstate_t *vstate;
14213179193Sjb	dtrace_difo_t *pred;
14214179193Sjb	int i, trace = dtrace_helptrace_enabled;
14215179193Sjb
14216179193Sjb	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14217179193Sjb
14218179193Sjb	if (helpers == NULL)
14219179193Sjb		return (0);
14220179193Sjb
14221179193Sjb	if ((helper = helpers->dthps_actions[which]) == NULL)
14222179193Sjb		return (0);
14223179193Sjb
14224179193Sjb	vstate = &helpers->dthps_vstate;
14225179193Sjb	mstate->dtms_arg[0] = arg0;
14226179193Sjb	mstate->dtms_arg[1] = arg1;
14227179193Sjb
14228179193Sjb	/*
14229179193Sjb	 * Now iterate over each helper.  If its predicate evaluates to 'true',
14230179193Sjb	 * we'll call the corresponding actions.  Note that the below calls
14231179193Sjb	 * to dtrace_dif_emulate() may set faults in machine state.  This is
14232179193Sjb	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14233179193Sjb	 * the stored DIF offset with its own (which is the desired behavior).
14234179193Sjb	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14235179193Sjb	 * from machine state; this is okay, too.
14236179193Sjb	 */
14237179193Sjb	for (; helper != NULL; helper = helper->dtha_next) {
14238179193Sjb		if ((pred = helper->dtha_predicate) != NULL) {
14239179193Sjb			if (trace)
14240179193Sjb				dtrace_helper_trace(helper, mstate, vstate, 0);
14241179193Sjb
14242179193Sjb			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14243179193Sjb				goto next;
14244179193Sjb
14245179193Sjb			if (*flags & CPU_DTRACE_FAULT)
14246179193Sjb				goto err;
14247179193Sjb		}
14248179193Sjb
14249179193Sjb		for (i = 0; i < helper->dtha_nactions; i++) {
14250179193Sjb			if (trace)
14251179193Sjb				dtrace_helper_trace(helper,
14252179193Sjb				    mstate, vstate, i + 1);
14253179193Sjb
14254179193Sjb			rval = dtrace_dif_emulate(helper->dtha_actions[i],
14255179193Sjb			    mstate, vstate, state);
14256179193Sjb
14257179193Sjb			if (*flags & CPU_DTRACE_FAULT)
14258179193Sjb				goto err;
14259179193Sjb		}
14260179193Sjb
14261179193Sjbnext:
14262179193Sjb		if (trace)
14263179193Sjb			dtrace_helper_trace(helper, mstate, vstate,
14264179193Sjb			    DTRACE_HELPTRACE_NEXT);
14265179193Sjb	}
14266179193Sjb
14267179193Sjb	if (trace)
14268179193Sjb		dtrace_helper_trace(helper, mstate, vstate,
14269179193Sjb		    DTRACE_HELPTRACE_DONE);
14270179193Sjb
14271179193Sjb	/*
14272179193Sjb	 * Restore the arg0 that we saved upon entry.
14273179193Sjb	 */
14274179193Sjb	mstate->dtms_arg[0] = sarg0;
14275179193Sjb	mstate->dtms_arg[1] = sarg1;
14276179193Sjb
14277179193Sjb	return (rval);
14278179193Sjb
14279179193Sjberr:
14280179193Sjb	if (trace)
14281179193Sjb		dtrace_helper_trace(helper, mstate, vstate,
14282179193Sjb		    DTRACE_HELPTRACE_ERR);
14283179193Sjb
14284179193Sjb	/*
14285179193Sjb	 * Restore the arg0 that we saved upon entry.
14286179193Sjb	 */
14287179193Sjb	mstate->dtms_arg[0] = sarg0;
14288179193Sjb	mstate->dtms_arg[1] = sarg1;
14289179193Sjb
14290179198Sjb	return (0);
14291179193Sjb}
14292179193Sjb
14293179193Sjbstatic void
14294179193Sjbdtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14295179193Sjb    dtrace_vstate_t *vstate)
14296179193Sjb{
14297179193Sjb	int i;
14298179193Sjb
14299179193Sjb	if (helper->dtha_predicate != NULL)
14300179193Sjb		dtrace_difo_release(helper->dtha_predicate, vstate);
14301179193Sjb
14302179193Sjb	for (i = 0; i < helper->dtha_nactions; i++) {
14303179193Sjb		ASSERT(helper->dtha_actions[i] != NULL);
14304179193Sjb		dtrace_difo_release(helper->dtha_actions[i], vstate);
14305179193Sjb	}
14306179193Sjb
14307179193Sjb	kmem_free(helper->dtha_actions,
14308179193Sjb	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
14309179193Sjb	kmem_free(helper, sizeof (dtrace_helper_action_t));
14310179193Sjb}
14311179193Sjb
14312179193Sjbstatic int
14313179193Sjbdtrace_helper_destroygen(int gen)
14314179193Sjb{
14315179193Sjb	proc_t *p = curproc;
14316179193Sjb	dtrace_helpers_t *help = p->p_dtrace_helpers;
14317179193Sjb	dtrace_vstate_t *vstate;
14318179193Sjb	int i;
14319179193Sjb
14320179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
14321179193Sjb
14322179193Sjb	if (help == NULL || gen > help->dthps_generation)
14323179193Sjb		return (EINVAL);
14324179193Sjb
14325179193Sjb	vstate = &help->dthps_vstate;
14326179193Sjb
14327179193Sjb	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14328179193Sjb		dtrace_helper_action_t *last = NULL, *h, *next;
14329179193Sjb
14330179193Sjb		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14331179193Sjb			next = h->dtha_next;
14332179193Sjb
14333179193Sjb			if (h->dtha_generation == gen) {
14334179193Sjb				if (last != NULL) {
14335179193Sjb					last->dtha_next = next;
14336179193Sjb				} else {
14337179193Sjb					help->dthps_actions[i] = next;
14338179193Sjb				}
14339179193Sjb
14340179193Sjb				dtrace_helper_action_destroy(h, vstate);
14341179193Sjb			} else {
14342179193Sjb				last = h;
14343179193Sjb			}
14344179193Sjb		}
14345179193Sjb	}
14346179193Sjb
14347179193Sjb	/*
14348179193Sjb	 * Interate until we've cleared out all helper providers with the
14349179193Sjb	 * given generation number.
14350179193Sjb	 */
14351179193Sjb	for (;;) {
14352179193Sjb		dtrace_helper_provider_t *prov;
14353179193Sjb
14354179193Sjb		/*
14355179193Sjb		 * Look for a helper provider with the right generation. We
14356179193Sjb		 * have to start back at the beginning of the list each time
14357179193Sjb		 * because we drop dtrace_lock. It's unlikely that we'll make
14358179193Sjb		 * more than two passes.
14359179193Sjb		 */
14360179193Sjb		for (i = 0; i < help->dthps_nprovs; i++) {
14361179193Sjb			prov = help->dthps_provs[i];
14362179193Sjb
14363179193Sjb			if (prov->dthp_generation == gen)
14364179193Sjb				break;
14365179193Sjb		}
14366179193Sjb
14367179193Sjb		/*
14368179193Sjb		 * If there were no matches, we're done.
14369179193Sjb		 */
14370179193Sjb		if (i == help->dthps_nprovs)
14371179193Sjb			break;
14372179193Sjb
14373179193Sjb		/*
14374179193Sjb		 * Move the last helper provider into this slot.
14375179193Sjb		 */
14376179193Sjb		help->dthps_nprovs--;
14377179193Sjb		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14378179193Sjb		help->dthps_provs[help->dthps_nprovs] = NULL;
14379179193Sjb
14380179193Sjb		mutex_exit(&dtrace_lock);
14381179193Sjb
14382179193Sjb		/*
14383179193Sjb		 * If we have a meta provider, remove this helper provider.
14384179193Sjb		 */
14385179193Sjb		mutex_enter(&dtrace_meta_lock);
14386179193Sjb		if (dtrace_meta_pid != NULL) {
14387179193Sjb			ASSERT(dtrace_deferred_pid == NULL);
14388179193Sjb			dtrace_helper_provider_remove(&prov->dthp_prov,
14389179193Sjb			    p->p_pid);
14390179193Sjb		}
14391179193Sjb		mutex_exit(&dtrace_meta_lock);
14392179193Sjb
14393179193Sjb		dtrace_helper_provider_destroy(prov);
14394179193Sjb
14395179193Sjb		mutex_enter(&dtrace_lock);
14396179193Sjb	}
14397179193Sjb
14398179193Sjb	return (0);
14399179193Sjb}
14400179193Sjb
14401179193Sjbstatic int
14402179193Sjbdtrace_helper_validate(dtrace_helper_action_t *helper)
14403179193Sjb{
14404179193Sjb	int err = 0, i;
14405179193Sjb	dtrace_difo_t *dp;
14406179193Sjb
14407179193Sjb	if ((dp = helper->dtha_predicate) != NULL)
14408179193Sjb		err += dtrace_difo_validate_helper(dp);
14409179193Sjb
14410179193Sjb	for (i = 0; i < helper->dtha_nactions; i++)
14411179193Sjb		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14412179193Sjb
14413179193Sjb	return (err == 0);
14414179193Sjb}
14415179193Sjb
14416179193Sjbstatic int
14417179193Sjbdtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14418179193Sjb{
14419179193Sjb	dtrace_helpers_t *help;
14420179193Sjb	dtrace_helper_action_t *helper, *last;
14421179193Sjb	dtrace_actdesc_t *act;
14422179193Sjb	dtrace_vstate_t *vstate;
14423179193Sjb	dtrace_predicate_t *pred;
14424179193Sjb	int count = 0, nactions = 0, i;
14425179193Sjb
14426179193Sjb	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14427179193Sjb		return (EINVAL);
14428179193Sjb
14429179193Sjb	help = curproc->p_dtrace_helpers;
14430179193Sjb	last = help->dthps_actions[which];
14431179193Sjb	vstate = &help->dthps_vstate;
14432179193Sjb
14433179193Sjb	for (count = 0; last != NULL; last = last->dtha_next) {
14434179193Sjb		count++;
14435179193Sjb		if (last->dtha_next == NULL)
14436179193Sjb			break;
14437179193Sjb	}
14438179193Sjb
14439179193Sjb	/*
14440179193Sjb	 * If we already have dtrace_helper_actions_max helper actions for this
14441179193Sjb	 * helper action type, we'll refuse to add a new one.
14442179193Sjb	 */
14443179193Sjb	if (count >= dtrace_helper_actions_max)
14444179193Sjb		return (ENOSPC);
14445179193Sjb
14446179193Sjb	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14447179193Sjb	helper->dtha_generation = help->dthps_generation;
14448179193Sjb
14449179193Sjb	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14450179193Sjb		ASSERT(pred->dtp_difo != NULL);
14451179193Sjb		dtrace_difo_hold(pred->dtp_difo);
14452179193Sjb		helper->dtha_predicate = pred->dtp_difo;
14453179193Sjb	}
14454179193Sjb
14455179193Sjb	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14456179193Sjb		if (act->dtad_kind != DTRACEACT_DIFEXPR)
14457179193Sjb			goto err;
14458179193Sjb
14459179193Sjb		if (act->dtad_difo == NULL)
14460179193Sjb			goto err;
14461179193Sjb
14462179193Sjb		nactions++;
14463179193Sjb	}
14464179193Sjb
14465179193Sjb	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14466179193Sjb	    (helper->dtha_nactions = nactions), KM_SLEEP);
14467179193Sjb
14468179193Sjb	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14469179193Sjb		dtrace_difo_hold(act->dtad_difo);
14470179193Sjb		helper->dtha_actions[i++] = act->dtad_difo;
14471179193Sjb	}
14472179193Sjb
14473179193Sjb	if (!dtrace_helper_validate(helper))
14474179193Sjb		goto err;
14475179193Sjb
14476179193Sjb	if (last == NULL) {
14477179193Sjb		help->dthps_actions[which] = helper;
14478179193Sjb	} else {
14479179193Sjb		last->dtha_next = helper;
14480179193Sjb	}
14481179193Sjb
14482179193Sjb	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14483179193Sjb		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14484179193Sjb		dtrace_helptrace_next = 0;
14485179193Sjb	}
14486179193Sjb
14487179193Sjb	return (0);
14488179193Sjberr:
14489179193Sjb	dtrace_helper_action_destroy(helper, vstate);
14490179193Sjb	return (EINVAL);
14491179193Sjb}
14492179193Sjb
14493179193Sjbstatic void
14494179193Sjbdtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14495179193Sjb    dof_helper_t *dofhp)
14496179193Sjb{
14497179193Sjb	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14498179193Sjb
14499179193Sjb	mutex_enter(&dtrace_meta_lock);
14500179193Sjb	mutex_enter(&dtrace_lock);
14501179193Sjb
14502179193Sjb	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14503179193Sjb		/*
14504179193Sjb		 * If the dtrace module is loaded but not attached, or if
14505179193Sjb		 * there aren't isn't a meta provider registered to deal with
14506179193Sjb		 * these provider descriptions, we need to postpone creating
14507179193Sjb		 * the actual providers until later.
14508179193Sjb		 */
14509179193Sjb
14510179193Sjb		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14511179193Sjb		    dtrace_deferred_pid != help) {
14512179193Sjb			help->dthps_deferred = 1;
14513179193Sjb			help->dthps_pid = p->p_pid;
14514179193Sjb			help->dthps_next = dtrace_deferred_pid;
14515179193Sjb			help->dthps_prev = NULL;
14516179193Sjb			if (dtrace_deferred_pid != NULL)
14517179193Sjb				dtrace_deferred_pid->dthps_prev = help;
14518179193Sjb			dtrace_deferred_pid = help;
14519179193Sjb		}
14520179193Sjb
14521179193Sjb		mutex_exit(&dtrace_lock);
14522179193Sjb
14523179193Sjb	} else if (dofhp != NULL) {
14524179193Sjb		/*
14525179193Sjb		 * If the dtrace module is loaded and we have a particular
14526179193Sjb		 * helper provider description, pass that off to the
14527179193Sjb		 * meta provider.
14528179193Sjb		 */
14529179193Sjb
14530179193Sjb		mutex_exit(&dtrace_lock);
14531179193Sjb
14532179193Sjb		dtrace_helper_provide(dofhp, p->p_pid);
14533179193Sjb
14534179193Sjb	} else {
14535179193Sjb		/*
14536179193Sjb		 * Otherwise, just pass all the helper provider descriptions
14537179193Sjb		 * off to the meta provider.
14538179193Sjb		 */
14539179193Sjb
14540179193Sjb		int i;
14541179193Sjb		mutex_exit(&dtrace_lock);
14542179193Sjb
14543179193Sjb		for (i = 0; i < help->dthps_nprovs; i++) {
14544179193Sjb			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14545179193Sjb			    p->p_pid);
14546179193Sjb		}
14547179193Sjb	}
14548179193Sjb
14549179193Sjb	mutex_exit(&dtrace_meta_lock);
14550179193Sjb}
14551179193Sjb
14552179193Sjbstatic int
14553179193Sjbdtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14554179193Sjb{
14555179193Sjb	dtrace_helpers_t *help;
14556179193Sjb	dtrace_helper_provider_t *hprov, **tmp_provs;
14557179193Sjb	uint_t tmp_maxprovs, i;
14558179193Sjb
14559179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
14560179193Sjb
14561179193Sjb	help = curproc->p_dtrace_helpers;
14562179193Sjb	ASSERT(help != NULL);
14563179193Sjb
14564179193Sjb	/*
14565179193Sjb	 * If we already have dtrace_helper_providers_max helper providers,
14566179193Sjb	 * we're refuse to add a new one.
14567179193Sjb	 */
14568179193Sjb	if (help->dthps_nprovs >= dtrace_helper_providers_max)
14569179193Sjb		return (ENOSPC);
14570179193Sjb
14571179193Sjb	/*
14572179193Sjb	 * Check to make sure this isn't a duplicate.
14573179193Sjb	 */
14574179193Sjb	for (i = 0; i < help->dthps_nprovs; i++) {
14575265235Spfg		if (dofhp->dofhp_dof ==
14576265235Spfg		    help->dthps_provs[i]->dthp_prov.dofhp_dof)
14577179193Sjb			return (EALREADY);
14578179193Sjb	}
14579179193Sjb
14580179193Sjb	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14581179193Sjb	hprov->dthp_prov = *dofhp;
14582179193Sjb	hprov->dthp_ref = 1;
14583179193Sjb	hprov->dthp_generation = gen;
14584179193Sjb
14585179193Sjb	/*
14586179193Sjb	 * Allocate a bigger table for helper providers if it's already full.
14587179193Sjb	 */
14588179193Sjb	if (help->dthps_maxprovs == help->dthps_nprovs) {
14589179193Sjb		tmp_maxprovs = help->dthps_maxprovs;
14590179193Sjb		tmp_provs = help->dthps_provs;
14591179193Sjb
14592179193Sjb		if (help->dthps_maxprovs == 0)
14593179193Sjb			help->dthps_maxprovs = 2;
14594179193Sjb		else
14595179193Sjb			help->dthps_maxprovs *= 2;
14596179193Sjb		if (help->dthps_maxprovs > dtrace_helper_providers_max)
14597179193Sjb			help->dthps_maxprovs = dtrace_helper_providers_max;
14598179193Sjb
14599179193Sjb		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14600179193Sjb
14601179193Sjb		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14602179193Sjb		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14603179193Sjb
14604179193Sjb		if (tmp_provs != NULL) {
14605179193Sjb			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14606179193Sjb			    sizeof (dtrace_helper_provider_t *));
14607179193Sjb			kmem_free(tmp_provs, tmp_maxprovs *
14608179193Sjb			    sizeof (dtrace_helper_provider_t *));
14609179193Sjb		}
14610179193Sjb	}
14611179193Sjb
14612179193Sjb	help->dthps_provs[help->dthps_nprovs] = hprov;
14613179193Sjb	help->dthps_nprovs++;
14614179193Sjb
14615179193Sjb	return (0);
14616179193Sjb}
14617179193Sjb
14618179193Sjbstatic void
14619179193Sjbdtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14620179193Sjb{
14621179193Sjb	mutex_enter(&dtrace_lock);
14622179193Sjb
14623179193Sjb	if (--hprov->dthp_ref == 0) {
14624179193Sjb		dof_hdr_t *dof;
14625179193Sjb		mutex_exit(&dtrace_lock);
14626179193Sjb		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14627179193Sjb		dtrace_dof_destroy(dof);
14628179193Sjb		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14629179193Sjb	} else {
14630179193Sjb		mutex_exit(&dtrace_lock);
14631179193Sjb	}
14632179193Sjb}
14633179193Sjb
14634179193Sjbstatic int
14635179193Sjbdtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14636179193Sjb{
14637179193Sjb	uintptr_t daddr = (uintptr_t)dof;
14638179193Sjb	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14639179193Sjb	dof_provider_t *provider;
14640179193Sjb	dof_probe_t *probe;
14641179193Sjb	uint8_t *arg;
14642179193Sjb	char *strtab, *typestr;
14643179193Sjb	dof_stridx_t typeidx;
14644179193Sjb	size_t typesz;
14645179193Sjb	uint_t nprobes, j, k;
14646179193Sjb
14647179193Sjb	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14648179193Sjb
14649179193Sjb	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14650179193Sjb		dtrace_dof_error(dof, "misaligned section offset");
14651179193Sjb		return (-1);
14652179193Sjb	}
14653179193Sjb
14654179193Sjb	/*
14655179193Sjb	 * The section needs to be large enough to contain the DOF provider
14656179193Sjb	 * structure appropriate for the given version.
14657179193Sjb	 */
14658179193Sjb	if (sec->dofs_size <
14659179193Sjb	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14660179193Sjb	    offsetof(dof_provider_t, dofpv_prenoffs) :
14661179193Sjb	    sizeof (dof_provider_t))) {
14662179193Sjb		dtrace_dof_error(dof, "provider section too small");
14663179193Sjb		return (-1);
14664179193Sjb	}
14665179193Sjb
14666179193Sjb	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14667179193Sjb	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14668179193Sjb	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14669179193Sjb	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14670179193Sjb	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14671179193Sjb
14672179193Sjb	if (str_sec == NULL || prb_sec == NULL ||
14673179193Sjb	    arg_sec == NULL || off_sec == NULL)
14674179193Sjb		return (-1);
14675179193Sjb
14676179193Sjb	enoff_sec = NULL;
14677179193Sjb
14678179193Sjb	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14679179193Sjb	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
14680179193Sjb	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14681179193Sjb	    provider->dofpv_prenoffs)) == NULL)
14682179193Sjb		return (-1);
14683179193Sjb
14684179193Sjb	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14685179193Sjb
14686179193Sjb	if (provider->dofpv_name >= str_sec->dofs_size ||
14687179193Sjb	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14688179193Sjb		dtrace_dof_error(dof, "invalid provider name");
14689179193Sjb		return (-1);
14690179193Sjb	}
14691179193Sjb
14692179193Sjb	if (prb_sec->dofs_entsize == 0 ||
14693179193Sjb	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
14694179193Sjb		dtrace_dof_error(dof, "invalid entry size");
14695179193Sjb		return (-1);
14696179193Sjb	}
14697179193Sjb
14698179193Sjb	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14699179193Sjb		dtrace_dof_error(dof, "misaligned entry size");
14700179193Sjb		return (-1);
14701179193Sjb	}
14702179193Sjb
14703179193Sjb	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14704179193Sjb		dtrace_dof_error(dof, "invalid entry size");
14705179193Sjb		return (-1);
14706179193Sjb	}
14707179193Sjb
14708179193Sjb	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14709179193Sjb		dtrace_dof_error(dof, "misaligned section offset");
14710179193Sjb		return (-1);
14711179193Sjb	}
14712179193Sjb
14713179193Sjb	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14714179193Sjb		dtrace_dof_error(dof, "invalid entry size");
14715179193Sjb		return (-1);
14716179193Sjb	}
14717179193Sjb
14718179193Sjb	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14719179193Sjb
14720179193Sjb	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14721179193Sjb
14722179193Sjb	/*
14723179193Sjb	 * Take a pass through the probes to check for errors.
14724179193Sjb	 */
14725179193Sjb	for (j = 0; j < nprobes; j++) {
14726179193Sjb		probe = (dof_probe_t *)(uintptr_t)(daddr +
14727179193Sjb		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14728179193Sjb
14729179193Sjb		if (probe->dofpr_func >= str_sec->dofs_size) {
14730179193Sjb			dtrace_dof_error(dof, "invalid function name");
14731179193Sjb			return (-1);
14732179193Sjb		}
14733179193Sjb
14734179193Sjb		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14735179193Sjb			dtrace_dof_error(dof, "function name too long");
14736179193Sjb			return (-1);
14737179193Sjb		}
14738179193Sjb
14739179193Sjb		if (probe->dofpr_name >= str_sec->dofs_size ||
14740179193Sjb		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14741179193Sjb			dtrace_dof_error(dof, "invalid probe name");
14742179193Sjb			return (-1);
14743179193Sjb		}
14744179193Sjb
14745179193Sjb		/*
14746179193Sjb		 * The offset count must not wrap the index, and the offsets
14747179193Sjb		 * must also not overflow the section's data.
14748179193Sjb		 */
14749179193Sjb		if (probe->dofpr_offidx + probe->dofpr_noffs <
14750179193Sjb		    probe->dofpr_offidx ||
14751179193Sjb		    (probe->dofpr_offidx + probe->dofpr_noffs) *
14752179193Sjb		    off_sec->dofs_entsize > off_sec->dofs_size) {
14753179193Sjb			dtrace_dof_error(dof, "invalid probe offset");
14754179193Sjb			return (-1);
14755179193Sjb		}
14756179193Sjb
14757179193Sjb		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14758179193Sjb			/*
14759179193Sjb			 * If there's no is-enabled offset section, make sure
14760179193Sjb			 * there aren't any is-enabled offsets. Otherwise
14761179193Sjb			 * perform the same checks as for probe offsets
14762179193Sjb			 * (immediately above).
14763179193Sjb			 */
14764179193Sjb			if (enoff_sec == NULL) {
14765179193Sjb				if (probe->dofpr_enoffidx != 0 ||
14766179193Sjb				    probe->dofpr_nenoffs != 0) {
14767179193Sjb					dtrace_dof_error(dof, "is-enabled "
14768179193Sjb					    "offsets with null section");
14769179193Sjb					return (-1);
14770179193Sjb				}
14771179193Sjb			} else if (probe->dofpr_enoffidx +
14772179193Sjb			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14773179193Sjb			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14774179193Sjb			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14775179193Sjb				dtrace_dof_error(dof, "invalid is-enabled "
14776179193Sjb				    "offset");
14777179193Sjb				return (-1);
14778179193Sjb			}
14779179193Sjb
14780179193Sjb			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14781179193Sjb				dtrace_dof_error(dof, "zero probe and "
14782179193Sjb				    "is-enabled offsets");
14783179193Sjb				return (-1);
14784179193Sjb			}
14785179193Sjb		} else if (probe->dofpr_noffs == 0) {
14786179193Sjb			dtrace_dof_error(dof, "zero probe offsets");
14787179193Sjb			return (-1);
14788179193Sjb		}
14789179193Sjb
14790179193Sjb		if (probe->dofpr_argidx + probe->dofpr_xargc <
14791179193Sjb		    probe->dofpr_argidx ||
14792179193Sjb		    (probe->dofpr_argidx + probe->dofpr_xargc) *
14793179193Sjb		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
14794179193Sjb			dtrace_dof_error(dof, "invalid args");
14795179193Sjb			return (-1);
14796179193Sjb		}
14797179193Sjb
14798179193Sjb		typeidx = probe->dofpr_nargv;
14799179193Sjb		typestr = strtab + probe->dofpr_nargv;
14800179193Sjb		for (k = 0; k < probe->dofpr_nargc; k++) {
14801179193Sjb			if (typeidx >= str_sec->dofs_size) {
14802179193Sjb				dtrace_dof_error(dof, "bad "
14803179193Sjb				    "native argument type");
14804179193Sjb				return (-1);
14805179193Sjb			}
14806179193Sjb
14807179193Sjb			typesz = strlen(typestr) + 1;
14808179193Sjb			if (typesz > DTRACE_ARGTYPELEN) {
14809179193Sjb				dtrace_dof_error(dof, "native "
14810179193Sjb				    "argument type too long");
14811179193Sjb				return (-1);
14812179193Sjb			}
14813179193Sjb			typeidx += typesz;
14814179193Sjb			typestr += typesz;
14815179193Sjb		}
14816179193Sjb
14817179193Sjb		typeidx = probe->dofpr_xargv;
14818179193Sjb		typestr = strtab + probe->dofpr_xargv;
14819179193Sjb		for (k = 0; k < probe->dofpr_xargc; k++) {
14820179193Sjb			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14821179193Sjb				dtrace_dof_error(dof, "bad "
14822179193Sjb				    "native argument index");
14823179193Sjb				return (-1);
14824179193Sjb			}
14825179193Sjb
14826179193Sjb			if (typeidx >= str_sec->dofs_size) {
14827179193Sjb				dtrace_dof_error(dof, "bad "
14828179193Sjb				    "translated argument type");
14829179193Sjb				return (-1);
14830179193Sjb			}
14831179193Sjb
14832179193Sjb			typesz = strlen(typestr) + 1;
14833179193Sjb			if (typesz > DTRACE_ARGTYPELEN) {
14834179193Sjb				dtrace_dof_error(dof, "translated argument "
14835179193Sjb				    "type too long");
14836179193Sjb				return (-1);
14837179193Sjb			}
14838179193Sjb
14839179193Sjb			typeidx += typesz;
14840179193Sjb			typestr += typesz;
14841179193Sjb		}
14842179193Sjb	}
14843179193Sjb
14844179193Sjb	return (0);
14845179193Sjb}
14846179193Sjb
14847179193Sjbstatic int
14848179193Sjbdtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14849179193Sjb{
14850179193Sjb	dtrace_helpers_t *help;
14851179193Sjb	dtrace_vstate_t *vstate;
14852179193Sjb	dtrace_enabling_t *enab = NULL;
14853179193Sjb	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14854179193Sjb	uintptr_t daddr = (uintptr_t)dof;
14855179193Sjb
14856179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
14857179193Sjb
14858179193Sjb	if ((help = curproc->p_dtrace_helpers) == NULL)
14859179193Sjb		help = dtrace_helpers_create(curproc);
14860179193Sjb
14861179193Sjb	vstate = &help->dthps_vstate;
14862179193Sjb
14863179193Sjb	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14864179193Sjb	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14865179193Sjb		dtrace_dof_destroy(dof);
14866179193Sjb		return (rv);
14867179193Sjb	}
14868179193Sjb
14869179193Sjb	/*
14870179193Sjb	 * Look for helper providers and validate their descriptions.
14871179193Sjb	 */
14872179193Sjb	if (dhp != NULL) {
14873179193Sjb		for (i = 0; i < dof->dofh_secnum; i++) {
14874179193Sjb			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14875179193Sjb			    dof->dofh_secoff + i * dof->dofh_secsize);
14876179193Sjb
14877179193Sjb			if (sec->dofs_type != DOF_SECT_PROVIDER)
14878179193Sjb				continue;
14879179193Sjb
14880179193Sjb			if (dtrace_helper_provider_validate(dof, sec) != 0) {
14881179193Sjb				dtrace_enabling_destroy(enab);
14882179193Sjb				dtrace_dof_destroy(dof);
14883179193Sjb				return (-1);
14884179193Sjb			}
14885179193Sjb
14886179193Sjb			nprovs++;
14887179193Sjb		}
14888179193Sjb	}
14889179193Sjb
14890179193Sjb	/*
14891179193Sjb	 * Now we need to walk through the ECB descriptions in the enabling.
14892179193Sjb	 */
14893179193Sjb	for (i = 0; i < enab->dten_ndesc; i++) {
14894179193Sjb		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14895179193Sjb		dtrace_probedesc_t *desc = &ep->dted_probe;
14896179193Sjb
14897179193Sjb		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14898179193Sjb			continue;
14899179193Sjb
14900179193Sjb		if (strcmp(desc->dtpd_mod, "helper") != 0)
14901179193Sjb			continue;
14902179193Sjb
14903179193Sjb		if (strcmp(desc->dtpd_func, "ustack") != 0)
14904179193Sjb			continue;
14905179193Sjb
14906179193Sjb		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14907179193Sjb		    ep)) != 0) {
14908179193Sjb			/*
14909179193Sjb			 * Adding this helper action failed -- we are now going
14910179193Sjb			 * to rip out the entire generation and return failure.
14911179193Sjb			 */
14912179193Sjb			(void) dtrace_helper_destroygen(help->dthps_generation);
14913179193Sjb			dtrace_enabling_destroy(enab);
14914179193Sjb			dtrace_dof_destroy(dof);
14915179193Sjb			return (-1);
14916179193Sjb		}
14917179193Sjb
14918179193Sjb		nhelpers++;
14919179193Sjb	}
14920179193Sjb
14921179193Sjb	if (nhelpers < enab->dten_ndesc)
14922179193Sjb		dtrace_dof_error(dof, "unmatched helpers");
14923179193Sjb
14924179193Sjb	gen = help->dthps_generation++;
14925179193Sjb	dtrace_enabling_destroy(enab);
14926179193Sjb
14927179193Sjb	if (dhp != NULL && nprovs > 0) {
14928179193Sjb		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14929179193Sjb		if (dtrace_helper_provider_add(dhp, gen) == 0) {
14930179193Sjb			mutex_exit(&dtrace_lock);
14931179193Sjb			dtrace_helper_provider_register(curproc, help, dhp);
14932179193Sjb			mutex_enter(&dtrace_lock);
14933179193Sjb
14934179193Sjb			destroy = 0;
14935179193Sjb		}
14936179193Sjb	}
14937179193Sjb
14938179193Sjb	if (destroy)
14939179193Sjb		dtrace_dof_destroy(dof);
14940179193Sjb
14941179193Sjb	return (gen);
14942179193Sjb}
14943179193Sjb
14944179193Sjbstatic dtrace_helpers_t *
14945179193Sjbdtrace_helpers_create(proc_t *p)
14946179193Sjb{
14947179193Sjb	dtrace_helpers_t *help;
14948179193Sjb
14949179193Sjb	ASSERT(MUTEX_HELD(&dtrace_lock));
14950179193Sjb	ASSERT(p->p_dtrace_helpers == NULL);
14951179193Sjb
14952179193Sjb	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14953179193Sjb	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14954179193Sjb	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14955179193Sjb
14956179193Sjb	p->p_dtrace_helpers = help;
14957179193Sjb	dtrace_helpers++;
14958179193Sjb
14959179193Sjb	return (help);
14960179193Sjb}
14961179193Sjb
14962211608Srpaulo#if defined(sun)
14963212357Srpaulostatic
14964212357Srpaulo#endif
14965212357Srpaulovoid
14966212357Srpaulodtrace_helpers_destroy(proc_t *p)
14967179193Sjb{
14968179193Sjb	dtrace_helpers_t *help;
14969179193Sjb	dtrace_vstate_t *vstate;
14970212357Srpaulo#if defined(sun)
14971179193Sjb	proc_t *p = curproc;
14972212357Srpaulo#endif
14973179193Sjb	int i;
14974179193Sjb
14975179193Sjb	mutex_enter(&dtrace_lock);
14976179193Sjb
14977179193Sjb	ASSERT(p->p_dtrace_helpers != NULL);
14978179193Sjb	ASSERT(dtrace_helpers > 0);
14979179193Sjb
14980179193Sjb	help = p->p_dtrace_helpers;
14981179193Sjb	vstate = &help->dthps_vstate;
14982179193Sjb
14983179193Sjb	/*
14984179193Sjb	 * We're now going to lose the help from this process.
14985179193Sjb	 */
14986179193Sjb	p->p_dtrace_helpers = NULL;
14987179193Sjb	dtrace_sync();
14988179193Sjb
14989179193Sjb	/*
14990179193Sjb	 * Destory the helper actions.
14991179193Sjb	 */
14992179193Sjb	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14993179193Sjb		dtrace_helper_action_t *h, *next;
14994179193Sjb
14995179193Sjb		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14996179193Sjb			next = h->dtha_next;
14997179193Sjb			dtrace_helper_action_destroy(h, vstate);
14998179193Sjb			h = next;
14999179193Sjb		}
15000179193Sjb	}
15001179193Sjb
15002179193Sjb	mutex_exit(&dtrace_lock);
15003179193Sjb
15004179193Sjb	/*
15005179193Sjb	 * Destroy the helper providers.
15006179193Sjb	 */
15007179193Sjb	if (help->dthps_maxprovs > 0) {
15008179193Sjb		mutex_enter(&dtrace_meta_lock);
15009179193Sjb		if (dtrace_meta_pid != NULL) {
15010179193Sjb			ASSERT(dtrace_deferred_pid == NULL);
15011179193Sjb
15012179193Sjb			for (i = 0; i < help->dthps_nprovs; i++) {
15013179193Sjb				dtrace_helper_provider_remove(
15014179193Sjb				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
15015179193Sjb			}
15016179193Sjb		} else {
15017179193Sjb			mutex_enter(&dtrace_lock);
15018179193Sjb			ASSERT(help->dthps_deferred == 0 ||
15019179193Sjb			    help->dthps_next != NULL ||
15020179193Sjb			    help->dthps_prev != NULL ||
15021179193Sjb			    help == dtrace_deferred_pid);
15022179193Sjb
15023179193Sjb			/*
15024179193Sjb			 * Remove the helper from the deferred list.
15025179193Sjb			 */
15026179193Sjb			if (help->dthps_next != NULL)
15027179193Sjb				help->dthps_next->dthps_prev = help->dthps_prev;
15028179193Sjb			if (help->dthps_prev != NULL)
15029179193Sjb				help->dthps_prev->dthps_next = help->dthps_next;
15030179193Sjb			if (dtrace_deferred_pid == help) {
15031179193Sjb				dtrace_deferred_pid = help->dthps_next;
15032179193Sjb				ASSERT(help->dthps_prev == NULL);
15033179193Sjb			}
15034179193Sjb
15035179193Sjb			mutex_exit(&dtrace_lock);
15036179193Sjb		}
15037179193Sjb
15038179193Sjb		mutex_exit(&dtrace_meta_lock);
15039179193Sjb
15040179193Sjb		for (i = 0; i < help->dthps_nprovs; i++) {
15041179193Sjb			dtrace_helper_provider_destroy(help->dthps_provs[i]);
15042179193Sjb		}
15043179193Sjb
15044179193Sjb		kmem_free(help->dthps_provs, help->dthps_maxprovs *
15045179193Sjb		    sizeof (dtrace_helper_provider_t *));
15046179193Sjb	}
15047179193Sjb
15048179193Sjb	mutex_enter(&dtrace_lock);
15049179193Sjb
15050179193Sjb	dtrace_vstate_fini(&help->dthps_vstate);
15051179193Sjb	kmem_free(help->dthps_actions,
15052179193Sjb	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15053179193Sjb	kmem_free(help, sizeof (dtrace_helpers_t));
15054179193Sjb
15055179193Sjb	--dtrace_helpers;
15056179193Sjb	mutex_exit(&dtrace_lock);
15057179193Sjb}
15058179193Sjb
15059212357Srpaulo#if defined(sun)
15060212357Srpaulostatic
15061212357Srpaulo#endif
15062212357Srpaulovoid
15063179193Sjbdtrace_helpers_duplicate(proc_t *from, proc_t *to)
15064179193Sjb{
15065179193Sjb	dtrace_helpers_t *help, *newhelp;
15066179193Sjb	dtrace_helper_action_t *helper, *new, *last;
15067179193Sjb	dtrace_difo_t *dp;
15068179193Sjb	dtrace_vstate_t *vstate;
15069179193Sjb	int i, j, sz, hasprovs = 0;
15070179193Sjb
15071179193Sjb	mutex_enter(&dtrace_lock);
15072179193Sjb	ASSERT(from->p_dtrace_helpers != NULL);
15073179193Sjb	ASSERT(dtrace_helpers > 0);
15074179193Sjb
15075179193Sjb	help = from->p_dtrace_helpers;
15076179193Sjb	newhelp = dtrace_helpers_create(to);
15077179193Sjb	ASSERT(to->p_dtrace_helpers != NULL);
15078179193Sjb
15079179193Sjb	newhelp->dthps_generation = help->dthps_generation;
15080179193Sjb	vstate = &newhelp->dthps_vstate;
15081179193Sjb
15082179193Sjb	/*
15083179193Sjb	 * Duplicate the helper actions.
15084179193Sjb	 */
15085179193Sjb	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15086179193Sjb		if ((helper = help->dthps_actions[i]) == NULL)
15087179193Sjb			continue;
15088179193Sjb
15089179193Sjb		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15090179193Sjb			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15091179193Sjb			    KM_SLEEP);
15092179193Sjb			new->dtha_generation = helper->dtha_generation;
15093179193Sjb
15094179193Sjb			if ((dp = helper->dtha_predicate) != NULL) {
15095179193Sjb				dp = dtrace_difo_duplicate(dp, vstate);
15096179193Sjb				new->dtha_predicate = dp;
15097179193Sjb			}
15098179193Sjb
15099179193Sjb			new->dtha_nactions = helper->dtha_nactions;
15100179193Sjb			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15101179193Sjb			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15102179193Sjb
15103179193Sjb			for (j = 0; j < new->dtha_nactions; j++) {
15104179193Sjb				dtrace_difo_t *dp = helper->dtha_actions[j];
15105179193Sjb
15106179193Sjb				ASSERT(dp != NULL);
15107179193Sjb				dp = dtrace_difo_duplicate(dp, vstate);
15108179193Sjb				new->dtha_actions[j] = dp;
15109179193Sjb			}
15110179193Sjb
15111179193Sjb			if (last != NULL) {
15112179193Sjb				last->dtha_next = new;
15113179193Sjb			} else {
15114179193Sjb				newhelp->dthps_actions[i] = new;
15115179193Sjb			}
15116179193Sjb
15117179193Sjb			last = new;
15118179193Sjb		}
15119179193Sjb	}
15120179193Sjb
15121179193Sjb	/*
15122179193Sjb	 * Duplicate the helper providers and register them with the
15123179193Sjb	 * DTrace framework.
15124179193Sjb	 */
15125179193Sjb	if (help->dthps_nprovs > 0) {
15126179193Sjb		newhelp->dthps_nprovs = help->dthps_nprovs;
15127179193Sjb		newhelp->dthps_maxprovs = help->dthps_nprovs;
15128179193Sjb		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15129179193Sjb		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15130179193Sjb		for (i = 0; i < newhelp->dthps_nprovs; i++) {
15131179193Sjb			newhelp->dthps_provs[i] = help->dthps_provs[i];
15132179193Sjb			newhelp->dthps_provs[i]->dthp_ref++;
15133179193Sjb		}
15134179193Sjb
15135179193Sjb		hasprovs = 1;
15136179193Sjb	}
15137179193Sjb
15138179193Sjb	mutex_exit(&dtrace_lock);
15139179193Sjb
15140179193Sjb	if (hasprovs)
15141179193Sjb		dtrace_helper_provider_register(to, newhelp, NULL);
15142179193Sjb}
15143179193Sjb
15144179193Sjb/*
15145179193Sjb * DTrace Hook Functions
15146179193Sjb */
15147179193Sjbstatic void
15148179198Sjbdtrace_module_loaded(modctl_t *ctl)
15149179193Sjb{
15150179193Sjb	dtrace_provider_t *prv;
15151179193Sjb
15152179193Sjb	mutex_enter(&dtrace_provider_lock);
15153262052Savg#if defined(sun)
15154179193Sjb	mutex_enter(&mod_lock);
15155262052Savg#endif
15156179193Sjb
15157255763Smarkj#if defined(sun)
15158179193Sjb	ASSERT(ctl->mod_busy);
15159255763Smarkj#endif
15160179193Sjb
15161179193Sjb	/*
15162179193Sjb	 * We're going to call each providers per-module provide operation
15163179193Sjb	 * specifying only this module.
15164179193Sjb	 */
15165179193Sjb	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15166179193Sjb		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15167179193Sjb
15168262052Savg#if defined(sun)
15169179193Sjb	mutex_exit(&mod_lock);
15170262052Savg#endif
15171179193Sjb	mutex_exit(&dtrace_provider_lock);
15172179193Sjb
15173179193Sjb	/*
15174179193Sjb	 * If we have any retained enablings, we need to match against them.
15175179193Sjb	 * Enabling probes requires that cpu_lock be held, and we cannot hold
15176179193Sjb	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15177179193Sjb	 * module.  (In particular, this happens when loading scheduling
15178179193Sjb	 * classes.)  So if we have any retained enablings, we need to dispatch
15179179193Sjb	 * our task queue to do the match for us.
15180179193Sjb	 */
15181179193Sjb	mutex_enter(&dtrace_lock);
15182179193Sjb
15183179193Sjb	if (dtrace_retained == NULL) {
15184179193Sjb		mutex_exit(&dtrace_lock);
15185179193Sjb		return;
15186179193Sjb	}
15187179193Sjb
15188179193Sjb	(void) taskq_dispatch(dtrace_taskq,
15189179193Sjb	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15190179193Sjb
15191179193Sjb	mutex_exit(&dtrace_lock);
15192179193Sjb
15193179193Sjb	/*
15194179193Sjb	 * And now, for a little heuristic sleaze:  in general, we want to
15195179193Sjb	 * match modules as soon as they load.  However, we cannot guarantee
15196179193Sjb	 * this, because it would lead us to the lock ordering violation
15197179193Sjb	 * outlined above.  The common case, of course, is that cpu_lock is
15198179193Sjb	 * _not_ held -- so we delay here for a clock tick, hoping that that's
15199179193Sjb	 * long enough for the task queue to do its work.  If it's not, it's
15200179193Sjb	 * not a serious problem -- it just means that the module that we
15201179193Sjb	 * just loaded may not be immediately instrumentable.
15202179193Sjb	 */
15203179193Sjb	delay(1);
15204179193Sjb}
15205179193Sjb
15206179193Sjbstatic void
15207255763Smarkj#if defined(sun)
15208179198Sjbdtrace_module_unloaded(modctl_t *ctl)
15209255763Smarkj#else
15210255763Smarkjdtrace_module_unloaded(modctl_t *ctl, int *error)
15211255763Smarkj#endif
15212179193Sjb{
15213179193Sjb	dtrace_probe_t template, *probe, *first, *next;
15214179193Sjb	dtrace_provider_t *prov;
15215255763Smarkj#if !defined(sun)
15216255763Smarkj	char modname[DTRACE_MODNAMELEN];
15217255763Smarkj	size_t len;
15218255763Smarkj#endif
15219179193Sjb
15220255763Smarkj#if defined(sun)
15221179193Sjb	template.dtpr_mod = ctl->mod_modname;
15222255763Smarkj#else
15223255763Smarkj	/* Handle the fact that ctl->filename may end in ".ko". */
15224255763Smarkj	strlcpy(modname, ctl->filename, sizeof(modname));
15225255763Smarkj	len = strlen(ctl->filename);
15226255763Smarkj	if (len > 3 && strcmp(modname + len - 3, ".ko") == 0)
15227255763Smarkj		modname[len - 3] = '\0';
15228255763Smarkj	template.dtpr_mod = modname;
15229255763Smarkj#endif
15230179193Sjb
15231179193Sjb	mutex_enter(&dtrace_provider_lock);
15232262052Savg#if defined(sun)
15233179193Sjb	mutex_enter(&mod_lock);
15234262052Savg#endif
15235179193Sjb	mutex_enter(&dtrace_lock);
15236179193Sjb
15237255763Smarkj#if !defined(sun)
15238255763Smarkj	if (ctl->nenabled > 0) {
15239255763Smarkj		/* Don't allow unloads if a probe is enabled. */
15240255763Smarkj		mutex_exit(&dtrace_provider_lock);
15241255763Smarkj		mutex_exit(&dtrace_lock);
15242255763Smarkj		*error = -1;
15243255763Smarkj		printf(
15244255763Smarkj	"kldunload: attempt to unload module that has DTrace probes enabled\n");
15245255763Smarkj		return;
15246255763Smarkj	}
15247255763Smarkj#endif
15248255763Smarkj
15249179193Sjb	if (dtrace_bymod == NULL) {
15250179193Sjb		/*
15251179193Sjb		 * The DTrace module is loaded (obviously) but not attached;
15252179193Sjb		 * we don't have any work to do.
15253179193Sjb		 */
15254179193Sjb		mutex_exit(&dtrace_provider_lock);
15255262052Savg#if defined(sun)
15256179193Sjb		mutex_exit(&mod_lock);
15257262052Savg#endif
15258179193Sjb		mutex_exit(&dtrace_lock);
15259179193Sjb		return;
15260179193Sjb	}
15261179193Sjb
15262179193Sjb	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15263179193Sjb	    probe != NULL; probe = probe->dtpr_nextmod) {
15264179193Sjb		if (probe->dtpr_ecb != NULL) {
15265179193Sjb			mutex_exit(&dtrace_provider_lock);
15266262052Savg#if defined(sun)
15267179193Sjb			mutex_exit(&mod_lock);
15268262052Savg#endif
15269179193Sjb			mutex_exit(&dtrace_lock);
15270179193Sjb
15271179193Sjb			/*
15272179193Sjb			 * This shouldn't _actually_ be possible -- we're
15273179193Sjb			 * unloading a module that has an enabled probe in it.
15274179193Sjb			 * (It's normally up to the provider to make sure that
15275179193Sjb			 * this can't happen.)  However, because dtps_enable()
15276179193Sjb			 * doesn't have a failure mode, there can be an
15277179193Sjb			 * enable/unload race.  Upshot:  we don't want to
15278179193Sjb			 * assert, but we're not going to disable the
15279179193Sjb			 * probe, either.
15280179193Sjb			 */
15281179193Sjb			if (dtrace_err_verbose) {
15282255763Smarkj#if defined(sun)
15283179193Sjb				cmn_err(CE_WARN, "unloaded module '%s' had "
15284179193Sjb				    "enabled probes", ctl->mod_modname);
15285255763Smarkj#else
15286255763Smarkj				cmn_err(CE_WARN, "unloaded module '%s' had "
15287255763Smarkj				    "enabled probes", modname);
15288255763Smarkj#endif
15289179193Sjb			}
15290179193Sjb
15291179193Sjb			return;
15292179193Sjb		}
15293179193Sjb	}
15294179193Sjb
15295179193Sjb	probe = first;
15296179193Sjb
15297179193Sjb	for (first = NULL; probe != NULL; probe = next) {
15298179193Sjb		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15299179193Sjb
15300179193Sjb		dtrace_probes[probe->dtpr_id - 1] = NULL;
15301179193Sjb
15302179193Sjb		next = probe->dtpr_nextmod;
15303179193Sjb		dtrace_hash_remove(dtrace_bymod, probe);
15304179193Sjb		dtrace_hash_remove(dtrace_byfunc, probe);
15305179193Sjb		dtrace_hash_remove(dtrace_byname, probe);
15306179193Sjb
15307179193Sjb		if (first == NULL) {
15308179193Sjb			first = probe;
15309179193Sjb			probe->dtpr_nextmod = NULL;
15310179193Sjb		} else {
15311179193Sjb			probe->dtpr_nextmod = first;
15312179193Sjb			first = probe;
15313179193Sjb		}
15314179193Sjb	}
15315179193Sjb
15316179193Sjb	/*
15317179193Sjb	 * We've removed all of the module's probes from the hash chains and
15318179193Sjb	 * from the probe array.  Now issue a dtrace_sync() to be sure that
15319179193Sjb	 * everyone has cleared out from any probe array processing.
15320179193Sjb	 */
15321179193Sjb	dtrace_sync();
15322179193Sjb
15323179193Sjb	for (probe = first; probe != NULL; probe = first) {
15324179193Sjb		first = probe->dtpr_nextmod;
15325179193Sjb		prov = probe->dtpr_provider;
15326179193Sjb		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15327179193Sjb		    probe->dtpr_arg);
15328179193Sjb		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15329179193Sjb		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15330179193Sjb		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15331255763Smarkj#if defined(sun)
15332179193Sjb		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15333255763Smarkj#else
15334255763Smarkj		free_unr(dtrace_arena, probe->dtpr_id);
15335255763Smarkj#endif
15336179193Sjb		kmem_free(probe, sizeof (dtrace_probe_t));
15337179193Sjb	}
15338179193Sjb
15339179193Sjb	mutex_exit(&dtrace_lock);
15340262052Savg#if defined(sun)
15341179193Sjb	mutex_exit(&mod_lock);
15342262052Savg#endif
15343179193Sjb	mutex_exit(&dtrace_provider_lock);
15344179193Sjb}
15345179193Sjb
15346255763Smarkj#if !defined(sun)
15347179198Sjbstatic void
15348255763Smarkjdtrace_kld_load(void *arg __unused, linker_file_t lf)
15349255763Smarkj{
15350255763Smarkj
15351255763Smarkj	dtrace_module_loaded(lf);
15352255763Smarkj}
15353255763Smarkj
15354255763Smarkjstatic void
15355262038Savgdtrace_kld_unload_try(void *arg __unused, linker_file_t lf, int *error)
15356255763Smarkj{
15357255763Smarkj
15358255763Smarkj	if (*error != 0)
15359255763Smarkj		/* We already have an error, so don't do anything. */
15360255763Smarkj		return;
15361255763Smarkj	dtrace_module_unloaded(lf, error);
15362255763Smarkj}
15363255763Smarkj#endif
15364255763Smarkj
15365255763Smarkj#if defined(sun)
15366255763Smarkjstatic void
15367179193Sjbdtrace_suspend(void)
15368179193Sjb{
15369179193Sjb	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15370179193Sjb}
15371179193Sjb
15372179198Sjbstatic void
15373179193Sjbdtrace_resume(void)
15374179193Sjb{
15375179193Sjb	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15376179193Sjb}
15377179198Sjb#endif
15378179193Sjb
15379179193Sjbstatic int
15380179193Sjbdtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15381179193Sjb{
15382179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
15383179193Sjb	mutex_enter(&dtrace_lock);
15384179193Sjb
15385179193Sjb	switch (what) {
15386179193Sjb	case CPU_CONFIG: {
15387179193Sjb		dtrace_state_t *state;
15388179193Sjb		dtrace_optval_t *opt, rs, c;
15389179193Sjb
15390179193Sjb		/*
15391179193Sjb		 * For now, we only allocate a new buffer for anonymous state.
15392179193Sjb		 */
15393179193Sjb		if ((state = dtrace_anon.dta_state) == NULL)
15394179193Sjb			break;
15395179193Sjb
15396179193Sjb		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15397179193Sjb			break;
15398179193Sjb
15399179193Sjb		opt = state->dts_options;
15400179193Sjb		c = opt[DTRACEOPT_CPU];
15401179193Sjb
15402179193Sjb		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15403179193Sjb			break;
15404179193Sjb
15405179193Sjb		/*
15406179193Sjb		 * Regardless of what the actual policy is, we're going to
15407179193Sjb		 * temporarily set our resize policy to be manual.  We're
15408179193Sjb		 * also going to temporarily set our CPU option to denote
15409179193Sjb		 * the newly configured CPU.
15410179193Sjb		 */
15411179193Sjb		rs = opt[DTRACEOPT_BUFRESIZE];
15412179193Sjb		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15413179193Sjb		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15414179193Sjb
15415179193Sjb		(void) dtrace_state_buffers(state);
15416179193Sjb
15417179193Sjb		opt[DTRACEOPT_BUFRESIZE] = rs;
15418179193Sjb		opt[DTRACEOPT_CPU] = c;
15419179193Sjb
15420179193Sjb		break;
15421179193Sjb	}
15422179193Sjb
15423179193Sjb	case CPU_UNCONFIG:
15424179193Sjb		/*
15425179193Sjb		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
15426179193Sjb		 * buffer will be freed when the consumer exits.)
15427179193Sjb		 */
15428179193Sjb		break;
15429179193Sjb
15430179193Sjb	default:
15431179193Sjb		break;
15432179193Sjb	}
15433179193Sjb
15434179193Sjb	mutex_exit(&dtrace_lock);
15435179193Sjb	return (0);
15436179193Sjb}
15437179193Sjb
15438179198Sjb#if defined(sun)
15439179193Sjbstatic void
15440179193Sjbdtrace_cpu_setup_initial(processorid_t cpu)
15441179193Sjb{
15442179193Sjb	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15443179193Sjb}
15444179198Sjb#endif
15445179193Sjb
15446179193Sjbstatic void
15447179193Sjbdtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15448179193Sjb{
15449179193Sjb	if (dtrace_toxranges >= dtrace_toxranges_max) {
15450179193Sjb		int osize, nsize;
15451179193Sjb		dtrace_toxrange_t *range;
15452179193Sjb
15453179193Sjb		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15454179193Sjb
15455179193Sjb		if (osize == 0) {
15456179193Sjb			ASSERT(dtrace_toxrange == NULL);
15457179193Sjb			ASSERT(dtrace_toxranges_max == 0);
15458179193Sjb			dtrace_toxranges_max = 1;
15459179193Sjb		} else {
15460179193Sjb			dtrace_toxranges_max <<= 1;
15461179193Sjb		}
15462179193Sjb
15463179193Sjb		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15464179193Sjb		range = kmem_zalloc(nsize, KM_SLEEP);
15465179193Sjb
15466179193Sjb		if (dtrace_toxrange != NULL) {
15467179193Sjb			ASSERT(osize != 0);
15468179193Sjb			bcopy(dtrace_toxrange, range, osize);
15469179193Sjb			kmem_free(dtrace_toxrange, osize);
15470179193Sjb		}
15471179193Sjb
15472179193Sjb		dtrace_toxrange = range;
15473179193Sjb	}
15474179193Sjb
15475179198Sjb	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == 0);
15476179198Sjb	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == 0);
15477179193Sjb
15478179193Sjb	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15479179193Sjb	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15480179193Sjb	dtrace_toxranges++;
15481179193Sjb}
15482179193Sjb
15483179193Sjb/*
15484179193Sjb * DTrace Driver Cookbook Functions
15485179193Sjb */
15486179198Sjb#if defined(sun)
15487179193Sjb/*ARGSUSED*/
15488179193Sjbstatic int
15489179193Sjbdtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15490179193Sjb{
15491179193Sjb	dtrace_provider_id_t id;
15492179193Sjb	dtrace_state_t *state = NULL;
15493179193Sjb	dtrace_enabling_t *enab;
15494179193Sjb
15495179193Sjb	mutex_enter(&cpu_lock);
15496179193Sjb	mutex_enter(&dtrace_provider_lock);
15497179193Sjb	mutex_enter(&dtrace_lock);
15498179193Sjb
15499179193Sjb	if (ddi_soft_state_init(&dtrace_softstate,
15500179193Sjb	    sizeof (dtrace_state_t), 0) != 0) {
15501179193Sjb		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15502179193Sjb		mutex_exit(&cpu_lock);
15503179193Sjb		mutex_exit(&dtrace_provider_lock);
15504179193Sjb		mutex_exit(&dtrace_lock);
15505179193Sjb		return (DDI_FAILURE);
15506179193Sjb	}
15507179193Sjb
15508179193Sjb	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15509179193Sjb	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15510179193Sjb	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15511179193Sjb	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15512179193Sjb		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15513179193Sjb		ddi_remove_minor_node(devi, NULL);
15514179193Sjb		ddi_soft_state_fini(&dtrace_softstate);
15515179193Sjb		mutex_exit(&cpu_lock);
15516179193Sjb		mutex_exit(&dtrace_provider_lock);
15517179193Sjb		mutex_exit(&dtrace_lock);
15518179193Sjb		return (DDI_FAILURE);
15519179193Sjb	}
15520179193Sjb
15521179193Sjb	ddi_report_dev(devi);
15522179193Sjb	dtrace_devi = devi;
15523179193Sjb
15524179193Sjb	dtrace_modload = dtrace_module_loaded;
15525179193Sjb	dtrace_modunload = dtrace_module_unloaded;
15526179193Sjb	dtrace_cpu_init = dtrace_cpu_setup_initial;
15527179193Sjb	dtrace_helpers_cleanup = dtrace_helpers_destroy;
15528179193Sjb	dtrace_helpers_fork = dtrace_helpers_duplicate;
15529179193Sjb	dtrace_cpustart_init = dtrace_suspend;
15530179193Sjb	dtrace_cpustart_fini = dtrace_resume;
15531179193Sjb	dtrace_debugger_init = dtrace_suspend;
15532179193Sjb	dtrace_debugger_fini = dtrace_resume;
15533179193Sjb
15534179193Sjb	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15535179193Sjb
15536179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
15537179193Sjb
15538179193Sjb	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15539179193Sjb	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15540179193Sjb	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15541179193Sjb	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15542179193Sjb	    VM_SLEEP | VMC_IDENTIFIER);
15543179193Sjb	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15544179193Sjb	    1, INT_MAX, 0);
15545179193Sjb
15546179193Sjb	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15547179193Sjb	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15548179193Sjb	    NULL, NULL, NULL, NULL, NULL, 0);
15549179193Sjb
15550179193Sjb	ASSERT(MUTEX_HELD(&cpu_lock));
15551179193Sjb	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15552179193Sjb	    offsetof(dtrace_probe_t, dtpr_nextmod),
15553179193Sjb	    offsetof(dtrace_probe_t, dtpr_prevmod));
15554179193Sjb
15555179193Sjb	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15556179193Sjb	    offsetof(dtrace_probe_t, dtpr_nextfunc),
15557179193Sjb	    offsetof(dtrace_probe_t, dtpr_prevfunc));
15558179193Sjb
15559179193Sjb	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15560179193Sjb	    offsetof(dtrace_probe_t, dtpr_nextname),
15561179193Sjb	    offsetof(dtrace_probe_t, dtpr_prevname));
15562179193Sjb
15563179193Sjb	if (dtrace_retain_max < 1) {
15564179193Sjb		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15565179193Sjb		    "setting to 1", dtrace_retain_max);
15566179193Sjb		dtrace_retain_max = 1;
15567179193Sjb	}
15568179193Sjb
15569179193Sjb	/*
15570179193Sjb	 * Now discover our toxic ranges.
15571179193Sjb	 */
15572179193Sjb	dtrace_toxic_ranges(dtrace_toxrange_add);
15573179193Sjb
15574179193Sjb	/*
15575179193Sjb	 * Before we register ourselves as a provider to our own framework,
15576179193Sjb	 * we would like to assert that dtrace_provider is NULL -- but that's
15577179193Sjb	 * not true if we were loaded as a dependency of a DTrace provider.
15578179193Sjb	 * Once we've registered, we can assert that dtrace_provider is our
15579179193Sjb	 * pseudo provider.
15580179193Sjb	 */
15581179193Sjb	(void) dtrace_register("dtrace", &dtrace_provider_attr,
15582179193Sjb	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15583179193Sjb
15584179193Sjb	ASSERT(dtrace_provider != NULL);
15585179193Sjb	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15586179193Sjb
15587179193Sjb	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15588179193Sjb	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15589179193Sjb	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15590179193Sjb	    dtrace_provider, NULL, NULL, "END", 0, NULL);
15591179193Sjb	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15592179193Sjb	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15593179193Sjb
15594179193Sjb	dtrace_anon_property();
15595179193Sjb	mutex_exit(&cpu_lock);
15596179193Sjb
15597179193Sjb	/*
15598179193Sjb	 * If DTrace helper tracing is enabled, we need to allocate the
15599179193Sjb	 * trace buffer and initialize the values.
15600179193Sjb	 */
15601179193Sjb	if (dtrace_helptrace_enabled) {
15602179193Sjb		ASSERT(dtrace_helptrace_buffer == NULL);
15603179193Sjb		dtrace_helptrace_buffer =
15604179193Sjb		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15605179193Sjb		dtrace_helptrace_next = 0;
15606179193Sjb	}
15607179193Sjb
15608179193Sjb	/*
15609179193Sjb	 * If there are already providers, we must ask them to provide their
15610179193Sjb	 * probes, and then match any anonymous enabling against them.  Note
15611179193Sjb	 * that there should be no other retained enablings at this time:
15612179193Sjb	 * the only retained enablings at this time should be the anonymous
15613179193Sjb	 * enabling.
15614179193Sjb	 */
15615179193Sjb	if (dtrace_anon.dta_enabling != NULL) {
15616179193Sjb		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15617179193Sjb
15618179193Sjb		dtrace_enabling_provide(NULL);
15619179193Sjb		state = dtrace_anon.dta_state;
15620179193Sjb
15621179193Sjb		/*
15622179193Sjb		 * We couldn't hold cpu_lock across the above call to
15623179193Sjb		 * dtrace_enabling_provide(), but we must hold it to actually
15624179193Sjb		 * enable the probes.  We have to drop all of our locks, pick
15625179193Sjb		 * up cpu_lock, and regain our locks before matching the
15626179193Sjb		 * retained anonymous enabling.
15627179193Sjb		 */
15628179193Sjb		mutex_exit(&dtrace_lock);
15629179193Sjb		mutex_exit(&dtrace_provider_lock);
15630179193Sjb
15631179193Sjb		mutex_enter(&cpu_lock);
15632179193Sjb		mutex_enter(&dtrace_provider_lock);
15633179193Sjb		mutex_enter(&dtrace_lock);
15634179193Sjb
15635179193Sjb		if ((enab = dtrace_anon.dta_enabling) != NULL)
15636179193Sjb			(void) dtrace_enabling_match(enab, NULL);
15637179193Sjb
15638179193Sjb		mutex_exit(&cpu_lock);
15639179193Sjb	}
15640179193Sjb
15641179193Sjb	mutex_exit(&dtrace_lock);
15642179193Sjb	mutex_exit(&dtrace_provider_lock);
15643179193Sjb
15644179193Sjb	if (state != NULL) {
15645179193Sjb		/*
15646179193Sjb		 * If we created any anonymous state, set it going now.
15647179193Sjb		 */
15648179193Sjb		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15649179193Sjb	}
15650179193Sjb
15651179193Sjb	return (DDI_SUCCESS);
15652179193Sjb}
15653179198Sjb#endif
15654179193Sjb
15655184698Srodrigc#if !defined(sun)
15656184698Srodrigc#if __FreeBSD_version >= 800039
15657184698Srodrigcstatic void
15658184698Srodrigcdtrace_dtr(void *data __unused)
15659184698Srodrigc{
15660184698Srodrigc}
15661184698Srodrigc#endif
15662184698Srodrigc#endif
15663184698Srodrigc
15664179193Sjb/*ARGSUSED*/
15665179193Sjbstatic int
15666179198Sjb#if defined(sun)
15667179193Sjbdtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15668179198Sjb#else
15669179198Sjbdtrace_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
15670179198Sjb#endif
15671179193Sjb{
15672179193Sjb	dtrace_state_t *state;
15673179193Sjb	uint32_t priv;
15674179193Sjb	uid_t uid;
15675179193Sjb	zoneid_t zoneid;
15676179193Sjb
15677179198Sjb#if defined(sun)
15678179193Sjb	if (getminor(*devp) == DTRACEMNRN_HELPER)
15679179193Sjb		return (0);
15680179193Sjb
15681179193Sjb	/*
15682179193Sjb	 * If this wasn't an open with the "helper" minor, then it must be
15683179193Sjb	 * the "dtrace" minor.
15684179193Sjb	 */
15685179193Sjb	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
15686179198Sjb#else
15687179198Sjb	cred_t *cred_p = NULL;
15688179193Sjb
15689184698Srodrigc#if __FreeBSD_version < 800039
15690179193Sjb	/*
15691179198Sjb	 * The first minor device is the one that is cloned so there is
15692179198Sjb	 * nothing more to do here.
15693179198Sjb	 */
15694183397Sed	if (dev2unit(dev) == 0)
15695179198Sjb		return 0;
15696179198Sjb
15697179198Sjb	/*
15698179198Sjb	 * Devices are cloned, so if the DTrace state has already
15699179198Sjb	 * been allocated, that means this device belongs to a
15700179198Sjb	 * different client. Each client should open '/dev/dtrace'
15701179198Sjb	 * to get a cloned device.
15702179198Sjb	 */
15703179198Sjb	if (dev->si_drv1 != NULL)
15704179198Sjb		return (EBUSY);
15705184698Srodrigc#endif
15706179198Sjb
15707179198Sjb	cred_p = dev->si_cred;
15708179198Sjb#endif
15709179198Sjb
15710179198Sjb	/*
15711179193Sjb	 * If no DTRACE_PRIV_* bits are set in the credential, then the
15712179193Sjb	 * caller lacks sufficient permission to do anything with DTrace.
15713179193Sjb	 */
15714179193Sjb	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15715179198Sjb	if (priv == DTRACE_PRIV_NONE) {
15716179198Sjb#if !defined(sun)
15717184698Srodrigc#if __FreeBSD_version < 800039
15718179198Sjb		/* Destroy the cloned device. */
15719179198Sjb                destroy_dev(dev);
15720179198Sjb#endif
15721184698Srodrigc#endif
15722179198Sjb
15723179193Sjb		return (EACCES);
15724179198Sjb	}
15725179193Sjb
15726179193Sjb	/*
15727179193Sjb	 * Ask all providers to provide all their probes.
15728179193Sjb	 */
15729179193Sjb	mutex_enter(&dtrace_provider_lock);
15730179193Sjb	dtrace_probe_provide(NULL, NULL);
15731179193Sjb	mutex_exit(&dtrace_provider_lock);
15732179193Sjb
15733179193Sjb	mutex_enter(&cpu_lock);
15734179193Sjb	mutex_enter(&dtrace_lock);
15735179193Sjb	dtrace_opens++;
15736179193Sjb	dtrace_membar_producer();
15737179193Sjb
15738179198Sjb#if defined(sun)
15739179193Sjb	/*
15740179193Sjb	 * If the kernel debugger is active (that is, if the kernel debugger
15741179193Sjb	 * modified text in some way), we won't allow the open.
15742179193Sjb	 */
15743179193Sjb	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15744179193Sjb		dtrace_opens--;
15745179193Sjb		mutex_exit(&cpu_lock);
15746179193Sjb		mutex_exit(&dtrace_lock);
15747179193Sjb		return (EBUSY);
15748179193Sjb	}
15749179193Sjb
15750179193Sjb	state = dtrace_state_create(devp, cred_p);
15751179198Sjb#else
15752179198Sjb	state = dtrace_state_create(dev);
15753184698Srodrigc#if __FreeBSD_version < 800039
15754179198Sjb	dev->si_drv1 = state;
15755184698Srodrigc#else
15756184698Srodrigc	devfs_set_cdevpriv(state, dtrace_dtr);
15757179198Sjb#endif
15758184698Srodrigc#endif
15759179198Sjb
15760179193Sjb	mutex_exit(&cpu_lock);
15761179193Sjb
15762179193Sjb	if (state == NULL) {
15763179198Sjb#if defined(sun)
15764179193Sjb		if (--dtrace_opens == 0)
15765179193Sjb			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15766179198Sjb#else
15767179198Sjb		--dtrace_opens;
15768179198Sjb#endif
15769179193Sjb		mutex_exit(&dtrace_lock);
15770179198Sjb#if !defined(sun)
15771184698Srodrigc#if __FreeBSD_version < 800039
15772179198Sjb		/* Destroy the cloned device. */
15773179198Sjb                destroy_dev(dev);
15774179198Sjb#endif
15775184698Srodrigc#endif
15776179193Sjb		return (EAGAIN);
15777179193Sjb	}
15778179193Sjb
15779179193Sjb	mutex_exit(&dtrace_lock);
15780179193Sjb
15781179193Sjb	return (0);
15782179193Sjb}
15783179193Sjb
15784179193Sjb/*ARGSUSED*/
15785179193Sjbstatic int
15786179198Sjb#if defined(sun)
15787179193Sjbdtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15788179198Sjb#else
15789179198Sjbdtrace_close(struct cdev *dev, int flags, int fmt __unused, struct thread *td)
15790179198Sjb#endif
15791179193Sjb{
15792179198Sjb#if defined(sun)
15793179193Sjb	minor_t minor = getminor(dev);
15794179193Sjb	dtrace_state_t *state;
15795179193Sjb
15796179193Sjb	if (minor == DTRACEMNRN_HELPER)
15797179193Sjb		return (0);
15798179193Sjb
15799179193Sjb	state = ddi_get_soft_state(dtrace_softstate, minor);
15800179198Sjb#else
15801184698Srodrigc#if __FreeBSD_version < 800039
15802179198Sjb	dtrace_state_t *state = dev->si_drv1;
15803179193Sjb
15804179198Sjb	/* Check if this is not a cloned device. */
15805183397Sed	if (dev2unit(dev) == 0)
15806179198Sjb		return (0);
15807184698Srodrigc#else
15808184698Srodrigc	dtrace_state_t *state;
15809184698Srodrigc	devfs_get_cdevpriv((void **) &state);
15810184698Srodrigc#endif
15811179198Sjb
15812179198Sjb#endif
15813179198Sjb
15814179193Sjb	mutex_enter(&cpu_lock);
15815179193Sjb	mutex_enter(&dtrace_lock);
15816179193Sjb
15817179198Sjb	if (state != NULL) {
15818179198Sjb		if (state->dts_anon) {
15819179198Sjb			/*
15820179198Sjb			 * There is anonymous state. Destroy that first.
15821179198Sjb			 */
15822179198Sjb			ASSERT(dtrace_anon.dta_state == NULL);
15823179198Sjb			dtrace_state_destroy(state->dts_anon);
15824179198Sjb		}
15825179198Sjb
15826179198Sjb		dtrace_state_destroy(state);
15827179198Sjb
15828179198Sjb#if !defined(sun)
15829179198Sjb		kmem_free(state, 0);
15830184698Srodrigc#if __FreeBSD_version < 800039
15831179198Sjb		dev->si_drv1 = NULL;
15832179198Sjb#endif
15833184698Srodrigc#endif
15834179193Sjb	}
15835179193Sjb
15836179193Sjb	ASSERT(dtrace_opens > 0);
15837179198Sjb#if defined(sun)
15838179193Sjb	if (--dtrace_opens == 0)
15839179193Sjb		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15840179198Sjb#else
15841179198Sjb	--dtrace_opens;
15842179198Sjb#endif
15843179193Sjb
15844179193Sjb	mutex_exit(&dtrace_lock);
15845179193Sjb	mutex_exit(&cpu_lock);
15846179193Sjb
15847184698Srodrigc#if __FreeBSD_version < 800039
15848179198Sjb	/* Schedule this cloned device to be destroyed. */
15849179198Sjb	destroy_dev_sched(dev);
15850184698Srodrigc#endif
15851179198Sjb
15852179193Sjb	return (0);
15853179193Sjb}
15854179193Sjb
15855179198Sjb#if defined(sun)
15856179193Sjb/*ARGSUSED*/
15857179193Sjbstatic int
15858179193Sjbdtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15859179193Sjb{
15860179193Sjb	int rval;
15861179193Sjb	dof_helper_t help, *dhp = NULL;
15862179193Sjb
15863179193Sjb	switch (cmd) {
15864179193Sjb	case DTRACEHIOC_ADDDOF:
15865179193Sjb		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15866179193Sjb			dtrace_dof_error(NULL, "failed to copyin DOF helper");
15867179193Sjb			return (EFAULT);
15868179193Sjb		}
15869179193Sjb
15870179193Sjb		dhp = &help;
15871179193Sjb		arg = (intptr_t)help.dofhp_dof;
15872179193Sjb		/*FALLTHROUGH*/
15873179193Sjb
15874179193Sjb	case DTRACEHIOC_ADD: {
15875179193Sjb		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15876179193Sjb
15877179193Sjb		if (dof == NULL)
15878179193Sjb			return (rval);
15879179193Sjb
15880179193Sjb		mutex_enter(&dtrace_lock);
15881179193Sjb
15882179193Sjb		/*
15883179193Sjb		 * dtrace_helper_slurp() takes responsibility for the dof --
15884179193Sjb		 * it may free it now or it may save it and free it later.
15885179193Sjb		 */
15886179193Sjb		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15887179193Sjb			*rv = rval;
15888179193Sjb			rval = 0;
15889179193Sjb		} else {
15890179193Sjb			rval = EINVAL;
15891179193Sjb		}
15892179193Sjb
15893179193Sjb		mutex_exit(&dtrace_lock);
15894179193Sjb		return (rval);
15895179193Sjb	}
15896179193Sjb
15897179193Sjb	case DTRACEHIOC_REMOVE: {
15898179193Sjb		mutex_enter(&dtrace_lock);
15899179193Sjb		rval = dtrace_helper_destroygen(arg);
15900179193Sjb		mutex_exit(&dtrace_lock);
15901179193Sjb
15902179193Sjb		return (rval);
15903179193Sjb	}
15904179193Sjb
15905179193Sjb	default:
15906179193Sjb		break;
15907179193Sjb	}
15908179193Sjb
15909179193Sjb	return (ENOTTY);
15910179193Sjb}
15911179193Sjb
15912179193Sjb/*ARGSUSED*/
15913179193Sjbstatic int
15914179193Sjbdtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15915179193Sjb{
15916179193Sjb	minor_t minor = getminor(dev);
15917179193Sjb	dtrace_state_t *state;
15918179193Sjb	int rval;
15919179193Sjb
15920179193Sjb	if (minor == DTRACEMNRN_HELPER)
15921179193Sjb		return (dtrace_ioctl_helper(cmd, arg, rv));
15922179193Sjb
15923179193Sjb	state = ddi_get_soft_state(dtrace_softstate, minor);
15924179193Sjb
15925179193Sjb	if (state->dts_anon) {
15926179193Sjb		ASSERT(dtrace_anon.dta_state == NULL);
15927179193Sjb		state = state->dts_anon;
15928179193Sjb	}
15929179193Sjb
15930179193Sjb	switch (cmd) {
15931179193Sjb	case DTRACEIOC_PROVIDER: {
15932179193Sjb		dtrace_providerdesc_t pvd;
15933179193Sjb		dtrace_provider_t *pvp;
15934179193Sjb
15935179193Sjb		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15936179193Sjb			return (EFAULT);
15937179193Sjb
15938179193Sjb		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15939179193Sjb		mutex_enter(&dtrace_provider_lock);
15940179193Sjb
15941179193Sjb		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15942179193Sjb			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15943179193Sjb				break;
15944179193Sjb		}
15945179193Sjb
15946179193Sjb		mutex_exit(&dtrace_provider_lock);
15947179193Sjb
15948179193Sjb		if (pvp == NULL)
15949179193Sjb			return (ESRCH);
15950179193Sjb
15951179193Sjb		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15952179193Sjb		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15953179198Sjb
15954179193Sjb		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15955179193Sjb			return (EFAULT);
15956179193Sjb
15957179193Sjb		return (0);
15958179193Sjb	}
15959179193Sjb
15960179193Sjb	case DTRACEIOC_EPROBE: {
15961179193Sjb		dtrace_eprobedesc_t epdesc;
15962179193Sjb		dtrace_ecb_t *ecb;
15963179193Sjb		dtrace_action_t *act;
15964179193Sjb		void *buf;
15965179193Sjb		size_t size;
15966179193Sjb		uintptr_t dest;
15967179193Sjb		int nrecs;
15968179193Sjb
15969179193Sjb		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15970179193Sjb			return (EFAULT);
15971179193Sjb
15972179193Sjb		mutex_enter(&dtrace_lock);
15973179193Sjb
15974179193Sjb		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15975179193Sjb			mutex_exit(&dtrace_lock);
15976179193Sjb			return (EINVAL);
15977179193Sjb		}
15978179193Sjb
15979179193Sjb		if (ecb->dte_probe == NULL) {
15980179193Sjb			mutex_exit(&dtrace_lock);
15981179193Sjb			return (EINVAL);
15982179193Sjb		}
15983179193Sjb
15984179193Sjb		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15985179193Sjb		epdesc.dtepd_uarg = ecb->dte_uarg;
15986179193Sjb		epdesc.dtepd_size = ecb->dte_size;
15987179193Sjb
15988179193Sjb		nrecs = epdesc.dtepd_nrecs;
15989179193Sjb		epdesc.dtepd_nrecs = 0;
15990179193Sjb		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15991179193Sjb			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15992179193Sjb				continue;
15993179193Sjb
15994179193Sjb			epdesc.dtepd_nrecs++;
15995179193Sjb		}
15996179193Sjb
15997179193Sjb		/*
15998179193Sjb		 * Now that we have the size, we need to allocate a temporary
15999179193Sjb		 * buffer in which to store the complete description.  We need
16000179193Sjb		 * the temporary buffer to be able to drop dtrace_lock()
16001179193Sjb		 * across the copyout(), below.
16002179193Sjb		 */
16003179193Sjb		size = sizeof (dtrace_eprobedesc_t) +
16004179193Sjb		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16005179193Sjb
16006179193Sjb		buf = kmem_alloc(size, KM_SLEEP);
16007179193Sjb		dest = (uintptr_t)buf;
16008179193Sjb
16009179193Sjb		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16010179193Sjb		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16011179193Sjb
16012179193Sjb		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16013179193Sjb			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16014179193Sjb				continue;
16015179193Sjb
16016179193Sjb			if (nrecs-- == 0)
16017179193Sjb				break;
16018179193Sjb
16019179193Sjb			bcopy(&act->dta_rec, (void *)dest,
16020179193Sjb			    sizeof (dtrace_recdesc_t));
16021179193Sjb			dest += sizeof (dtrace_recdesc_t);
16022179193Sjb		}
16023179193Sjb
16024179193Sjb		mutex_exit(&dtrace_lock);
16025179193Sjb
16026179193Sjb		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16027179193Sjb			kmem_free(buf, size);
16028179193Sjb			return (EFAULT);
16029179193Sjb		}
16030179193Sjb
16031179193Sjb		kmem_free(buf, size);
16032179193Sjb		return (0);
16033179193Sjb	}
16034179193Sjb
16035179193Sjb	case DTRACEIOC_AGGDESC: {
16036179193Sjb		dtrace_aggdesc_t aggdesc;
16037179193Sjb		dtrace_action_t *act;
16038179193Sjb		dtrace_aggregation_t *agg;
16039179193Sjb		int nrecs;
16040179193Sjb		uint32_t offs;
16041179193Sjb		dtrace_recdesc_t *lrec;
16042179193Sjb		void *buf;
16043179193Sjb		size_t size;
16044179193Sjb		uintptr_t dest;
16045179193Sjb
16046179193Sjb		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16047179193Sjb			return (EFAULT);
16048179193Sjb
16049179193Sjb		mutex_enter(&dtrace_lock);
16050179193Sjb
16051179193Sjb		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16052179193Sjb			mutex_exit(&dtrace_lock);
16053179193Sjb			return (EINVAL);
16054179193Sjb		}
16055179193Sjb
16056179193Sjb		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16057179193Sjb
16058179193Sjb		nrecs = aggdesc.dtagd_nrecs;
16059179193Sjb		aggdesc.dtagd_nrecs = 0;
16060179193Sjb
16061179193Sjb		offs = agg->dtag_base;
16062179193Sjb		lrec = &agg->dtag_action.dta_rec;
16063179193Sjb		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16064179193Sjb
16065179193Sjb		for (act = agg->dtag_first; ; act = act->dta_next) {
16066179193Sjb			ASSERT(act->dta_intuple ||
16067179193Sjb			    DTRACEACT_ISAGG(act->dta_kind));
16068179193Sjb
16069179193Sjb			/*
16070179193Sjb			 * If this action has a record size of zero, it
16071179193Sjb			 * denotes an argument to the aggregating action.
16072179193Sjb			 * Because the presence of this record doesn't (or
16073179193Sjb			 * shouldn't) affect the way the data is interpreted,
16074179193Sjb			 * we don't copy it out to save user-level the
16075179193Sjb			 * confusion of dealing with a zero-length record.
16076179193Sjb			 */
16077179193Sjb			if (act->dta_rec.dtrd_size == 0) {
16078179193Sjb				ASSERT(agg->dtag_hasarg);
16079179193Sjb				continue;
16080179193Sjb			}
16081179193Sjb
16082179193Sjb			aggdesc.dtagd_nrecs++;
16083179193Sjb
16084179193Sjb			if (act == &agg->dtag_action)
16085179193Sjb				break;
16086179193Sjb		}
16087179193Sjb
16088179193Sjb		/*
16089179193Sjb		 * Now that we have the size, we need to allocate a temporary
16090179193Sjb		 * buffer in which to store the complete description.  We need
16091179193Sjb		 * the temporary buffer to be able to drop dtrace_lock()
16092179193Sjb		 * across the copyout(), below.
16093179193Sjb		 */
16094179193Sjb		size = sizeof (dtrace_aggdesc_t) +
16095179193Sjb		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16096179193Sjb
16097179193Sjb		buf = kmem_alloc(size, KM_SLEEP);
16098179193Sjb		dest = (uintptr_t)buf;
16099179193Sjb
16100179193Sjb		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16101179193Sjb		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16102179193Sjb
16103179193Sjb		for (act = agg->dtag_first; ; act = act->dta_next) {
16104179193Sjb			dtrace_recdesc_t rec = act->dta_rec;
16105179193Sjb
16106179193Sjb			/*
16107179193Sjb			 * See the comment in the above loop for why we pass
16108179193Sjb			 * over zero-length records.
16109179193Sjb			 */
16110179193Sjb			if (rec.dtrd_size == 0) {
16111179193Sjb				ASSERT(agg->dtag_hasarg);
16112179193Sjb				continue;
16113179193Sjb			}
16114179193Sjb
16115179193Sjb			if (nrecs-- == 0)
16116179193Sjb				break;
16117179193Sjb
16118179193Sjb			rec.dtrd_offset -= offs;
16119179193Sjb			bcopy(&rec, (void *)dest, sizeof (rec));
16120179193Sjb			dest += sizeof (dtrace_recdesc_t);
16121179193Sjb
16122179193Sjb			if (act == &agg->dtag_action)
16123179193Sjb				break;
16124179193Sjb		}
16125179193Sjb
16126179193Sjb		mutex_exit(&dtrace_lock);
16127179193Sjb
16128179193Sjb		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16129179193Sjb			kmem_free(buf, size);
16130179193Sjb			return (EFAULT);
16131179193Sjb		}
16132179193Sjb
16133179193Sjb		kmem_free(buf, size);
16134179193Sjb		return (0);
16135179193Sjb	}
16136179193Sjb
16137179193Sjb	case DTRACEIOC_ENABLE: {
16138179193Sjb		dof_hdr_t *dof;
16139179193Sjb		dtrace_enabling_t *enab = NULL;
16140179193Sjb		dtrace_vstate_t *vstate;
16141179193Sjb		int err = 0;
16142179193Sjb
16143179193Sjb		*rv = 0;
16144179193Sjb
16145179193Sjb		/*
16146179193Sjb		 * If a NULL argument has been passed, we take this as our
16147179193Sjb		 * cue to reevaluate our enablings.
16148179193Sjb		 */
16149179193Sjb		if (arg == NULL) {
16150179198Sjb			dtrace_enabling_matchall();
16151179193Sjb
16152179198Sjb			return (0);
16153179193Sjb		}
16154179193Sjb
16155179193Sjb		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16156179193Sjb			return (rval);
16157179193Sjb
16158179193Sjb		mutex_enter(&cpu_lock);
16159179193Sjb		mutex_enter(&dtrace_lock);
16160179193Sjb		vstate = &state->dts_vstate;
16161179193Sjb
16162179193Sjb		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16163179193Sjb			mutex_exit(&dtrace_lock);
16164179193Sjb			mutex_exit(&cpu_lock);
16165179193Sjb			dtrace_dof_destroy(dof);
16166179193Sjb			return (EBUSY);
16167179193Sjb		}
16168179193Sjb
16169179193Sjb		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16170179193Sjb			mutex_exit(&dtrace_lock);
16171179193Sjb			mutex_exit(&cpu_lock);
16172179193Sjb			dtrace_dof_destroy(dof);
16173179193Sjb			return (EINVAL);
16174179193Sjb		}
16175179193Sjb
16176179193Sjb		if ((rval = dtrace_dof_options(dof, state)) != 0) {
16177179193Sjb			dtrace_enabling_destroy(enab);
16178179193Sjb			mutex_exit(&dtrace_lock);
16179179193Sjb			mutex_exit(&cpu_lock);
16180179193Sjb			dtrace_dof_destroy(dof);
16181179193Sjb			return (rval);
16182179193Sjb		}
16183179193Sjb
16184179193Sjb		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16185179193Sjb			err = dtrace_enabling_retain(enab);
16186179193Sjb		} else {
16187179193Sjb			dtrace_enabling_destroy(enab);
16188179193Sjb		}
16189179193Sjb
16190179193Sjb		mutex_exit(&cpu_lock);
16191179193Sjb		mutex_exit(&dtrace_lock);
16192179193Sjb		dtrace_dof_destroy(dof);
16193179193Sjb
16194179193Sjb		return (err);
16195179193Sjb	}
16196179193Sjb
16197179193Sjb	case DTRACEIOC_REPLICATE: {
16198179193Sjb		dtrace_repldesc_t desc;
16199179193Sjb		dtrace_probedesc_t *match = &desc.dtrpd_match;
16200179193Sjb		dtrace_probedesc_t *create = &desc.dtrpd_create;
16201179193Sjb		int err;
16202179193Sjb
16203179193Sjb		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16204179193Sjb			return (EFAULT);
16205179193Sjb
16206179193Sjb		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16207179193Sjb		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16208179193Sjb		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16209179193Sjb		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16210179193Sjb
16211179193Sjb		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16212179193Sjb		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16213179193Sjb		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16214179193Sjb		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16215179193Sjb
16216179193Sjb		mutex_enter(&dtrace_lock);
16217179193Sjb		err = dtrace_enabling_replicate(state, match, create);
16218179193Sjb		mutex_exit(&dtrace_lock);
16219179193Sjb
16220179193Sjb		return (err);
16221179193Sjb	}
16222179193Sjb
16223179193Sjb	case DTRACEIOC_PROBEMATCH:
16224179193Sjb	case DTRACEIOC_PROBES: {
16225179193Sjb		dtrace_probe_t *probe = NULL;
16226179193Sjb		dtrace_probedesc_t desc;
16227179193Sjb		dtrace_probekey_t pkey;
16228179193Sjb		dtrace_id_t i;
16229179193Sjb		int m = 0;
16230179193Sjb		uint32_t priv;
16231179193Sjb		uid_t uid;
16232179193Sjb		zoneid_t zoneid;
16233179193Sjb
16234179193Sjb		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16235179193Sjb			return (EFAULT);
16236179193Sjb
16237179193Sjb		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16238179193Sjb		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16239179193Sjb		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16240179193Sjb		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16241179193Sjb
16242179193Sjb		/*
16243179193Sjb		 * Before we attempt to match this probe, we want to give
16244179193Sjb		 * all providers the opportunity to provide it.
16245179193Sjb		 */
16246179193Sjb		if (desc.dtpd_id == DTRACE_IDNONE) {
16247179193Sjb			mutex_enter(&dtrace_provider_lock);
16248179193Sjb			dtrace_probe_provide(&desc, NULL);
16249179193Sjb			mutex_exit(&dtrace_provider_lock);
16250179193Sjb			desc.dtpd_id++;
16251179193Sjb		}
16252179193Sjb
16253179193Sjb		if (cmd == DTRACEIOC_PROBEMATCH)  {
16254179193Sjb			dtrace_probekey(&desc, &pkey);
16255179193Sjb			pkey.dtpk_id = DTRACE_IDNONE;
16256179193Sjb		}
16257179193Sjb
16258179193Sjb		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16259179193Sjb
16260179193Sjb		mutex_enter(&dtrace_lock);
16261179193Sjb
16262179193Sjb		if (cmd == DTRACEIOC_PROBEMATCH) {
16263179193Sjb			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16264179193Sjb				if ((probe = dtrace_probes[i - 1]) != NULL &&
16265179193Sjb				    (m = dtrace_match_probe(probe, &pkey,
16266179193Sjb				    priv, uid, zoneid)) != 0)
16267179193Sjb					break;
16268179193Sjb			}
16269179193Sjb
16270179193Sjb			if (m < 0) {
16271179193Sjb				mutex_exit(&dtrace_lock);
16272179193Sjb				return (EINVAL);
16273179193Sjb			}
16274179193Sjb
16275179193Sjb		} else {
16276179193Sjb			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16277179193Sjb				if ((probe = dtrace_probes[i - 1]) != NULL &&
16278179193Sjb				    dtrace_match_priv(probe, priv, uid, zoneid))
16279179193Sjb					break;
16280179193Sjb			}
16281179193Sjb		}
16282179193Sjb
16283179193Sjb		if (probe == NULL) {
16284179193Sjb			mutex_exit(&dtrace_lock);
16285179193Sjb			return (ESRCH);
16286179193Sjb		}
16287179193Sjb
16288179193Sjb		dtrace_probe_description(probe, &desc);
16289179193Sjb		mutex_exit(&dtrace_lock);
16290179193Sjb
16291179193Sjb		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16292179193Sjb			return (EFAULT);
16293179193Sjb
16294179193Sjb		return (0);
16295179193Sjb	}
16296179193Sjb
16297179193Sjb	case DTRACEIOC_PROBEARG: {
16298179193Sjb		dtrace_argdesc_t desc;
16299179193Sjb		dtrace_probe_t *probe;
16300179193Sjb		dtrace_provider_t *prov;
16301179193Sjb
16302179193Sjb		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16303179193Sjb			return (EFAULT);
16304179193Sjb
16305179193Sjb		if (desc.dtargd_id == DTRACE_IDNONE)
16306179193Sjb			return (EINVAL);
16307179193Sjb
16308179193Sjb		if (desc.dtargd_ndx == DTRACE_ARGNONE)
16309179193Sjb			return (EINVAL);
16310179193Sjb
16311179193Sjb		mutex_enter(&dtrace_provider_lock);
16312179193Sjb		mutex_enter(&mod_lock);
16313179193Sjb		mutex_enter(&dtrace_lock);
16314179193Sjb
16315179193Sjb		if (desc.dtargd_id > dtrace_nprobes) {
16316179193Sjb			mutex_exit(&dtrace_lock);
16317179193Sjb			mutex_exit(&mod_lock);
16318179193Sjb			mutex_exit(&dtrace_provider_lock);
16319179193Sjb			return (EINVAL);
16320179193Sjb		}
16321179193Sjb
16322179193Sjb		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16323179193Sjb			mutex_exit(&dtrace_lock);
16324179193Sjb			mutex_exit(&mod_lock);
16325179193Sjb			mutex_exit(&dtrace_provider_lock);
16326179193Sjb			return (EINVAL);
16327179193Sjb		}
16328179193Sjb
16329179193Sjb		mutex_exit(&dtrace_lock);
16330179193Sjb
16331179193Sjb		prov = probe->dtpr_provider;
16332179193Sjb
16333179193Sjb		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16334179193Sjb			/*
16335179193Sjb			 * There isn't any typed information for this probe.
16336179193Sjb			 * Set the argument number to DTRACE_ARGNONE.
16337179193Sjb			 */
16338179193Sjb			desc.dtargd_ndx = DTRACE_ARGNONE;
16339179193Sjb		} else {
16340179193Sjb			desc.dtargd_native[0] = '\0';
16341179193Sjb			desc.dtargd_xlate[0] = '\0';
16342179193Sjb			desc.dtargd_mapping = desc.dtargd_ndx;
16343179193Sjb
16344179193Sjb			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16345179193Sjb			    probe->dtpr_id, probe->dtpr_arg, &desc);
16346179193Sjb		}
16347179193Sjb
16348179193Sjb		mutex_exit(&mod_lock);
16349179193Sjb		mutex_exit(&dtrace_provider_lock);
16350179193Sjb
16351179193Sjb		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16352179193Sjb			return (EFAULT);
16353179193Sjb
16354179193Sjb		return (0);
16355179193Sjb	}
16356179193Sjb
16357179193Sjb	case DTRACEIOC_GO: {
16358179193Sjb		processorid_t cpuid;
16359179193Sjb		rval = dtrace_state_go(state, &cpuid);
16360179193Sjb
16361179193Sjb		if (rval != 0)
16362179193Sjb			return (rval);
16363179193Sjb
16364179193Sjb		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16365179193Sjb			return (EFAULT);
16366179193Sjb
16367179193Sjb		return (0);
16368179193Sjb	}
16369179193Sjb
16370179193Sjb	case DTRACEIOC_STOP: {
16371179193Sjb		processorid_t cpuid;
16372179193Sjb
16373179193Sjb		mutex_enter(&dtrace_lock);
16374179193Sjb		rval = dtrace_state_stop(state, &cpuid);
16375179193Sjb		mutex_exit(&dtrace_lock);
16376179193Sjb
16377179193Sjb		if (rval != 0)
16378179193Sjb			return (rval);
16379179193Sjb
16380179193Sjb		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16381179193Sjb			return (EFAULT);
16382179193Sjb
16383179193Sjb		return (0);
16384179193Sjb	}
16385179193Sjb
16386179193Sjb	case DTRACEIOC_DOFGET: {
16387179193Sjb		dof_hdr_t hdr, *dof;
16388179193Sjb		uint64_t len;
16389179193Sjb
16390179193Sjb		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16391179193Sjb			return (EFAULT);
16392179193Sjb
16393179193Sjb		mutex_enter(&dtrace_lock);
16394179193Sjb		dof = dtrace_dof_create(state);
16395179193Sjb		mutex_exit(&dtrace_lock);
16396179193Sjb
16397179193Sjb		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16398179193Sjb		rval = copyout(dof, (void *)arg, len);
16399179193Sjb		dtrace_dof_destroy(dof);
16400179193Sjb
16401179193Sjb		return (rval == 0 ? 0 : EFAULT);
16402179193Sjb	}
16403179193Sjb
16404179193Sjb	case DTRACEIOC_AGGSNAP:
16405179193Sjb	case DTRACEIOC_BUFSNAP: {
16406179193Sjb		dtrace_bufdesc_t desc;
16407179193Sjb		caddr_t cached;
16408179193Sjb		dtrace_buffer_t *buf;
16409179193Sjb
16410179193Sjb		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16411179193Sjb			return (EFAULT);
16412179193Sjb
16413179193Sjb		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16414179193Sjb			return (EINVAL);
16415179193Sjb
16416179193Sjb		mutex_enter(&dtrace_lock);
16417179193Sjb
16418179193Sjb		if (cmd == DTRACEIOC_BUFSNAP) {
16419179193Sjb			buf = &state->dts_buffer[desc.dtbd_cpu];
16420179193Sjb		} else {
16421179193Sjb			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16422179193Sjb		}
16423179193Sjb
16424179193Sjb		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16425179193Sjb			size_t sz = buf->dtb_offset;
16426179193Sjb
16427179193Sjb			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16428179193Sjb				mutex_exit(&dtrace_lock);
16429179193Sjb				return (EBUSY);
16430179193Sjb			}
16431179193Sjb
16432179193Sjb			/*
16433179193Sjb			 * If this buffer has already been consumed, we're
16434179193Sjb			 * going to indicate that there's nothing left here
16435179193Sjb			 * to consume.
16436179193Sjb			 */
16437179193Sjb			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16438179193Sjb				mutex_exit(&dtrace_lock);
16439179193Sjb
16440179193Sjb				desc.dtbd_size = 0;
16441179193Sjb				desc.dtbd_drops = 0;
16442179193Sjb				desc.dtbd_errors = 0;
16443179193Sjb				desc.dtbd_oldest = 0;
16444179193Sjb				sz = sizeof (desc);
16445179193Sjb
16446179193Sjb				if (copyout(&desc, (void *)arg, sz) != 0)
16447179193Sjb					return (EFAULT);
16448179193Sjb
16449179193Sjb				return (0);
16450179193Sjb			}
16451179193Sjb
16452179193Sjb			/*
16453179193Sjb			 * If this is a ring buffer that has wrapped, we want
16454179193Sjb			 * to copy the whole thing out.
16455179193Sjb			 */
16456179193Sjb			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16457179193Sjb				dtrace_buffer_polish(buf);
16458179193Sjb				sz = buf->dtb_size;
16459179193Sjb			}
16460179193Sjb
16461179193Sjb			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16462179193Sjb				mutex_exit(&dtrace_lock);
16463179193Sjb				return (EFAULT);
16464179193Sjb			}
16465179193Sjb
16466179193Sjb			desc.dtbd_size = sz;
16467179193Sjb			desc.dtbd_drops = buf->dtb_drops;
16468179193Sjb			desc.dtbd_errors = buf->dtb_errors;
16469179193Sjb			desc.dtbd_oldest = buf->dtb_xamot_offset;
16470256002Spfg			desc.dtbd_timestamp = dtrace_gethrtime();
16471179193Sjb
16472179193Sjb			mutex_exit(&dtrace_lock);
16473179193Sjb
16474179193Sjb			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16475179193Sjb				return (EFAULT);
16476179193Sjb
16477179193Sjb			buf->dtb_flags |= DTRACEBUF_CONSUMED;
16478179193Sjb
16479179193Sjb			return (0);
16480179193Sjb		}
16481179193Sjb
16482179193Sjb		if (buf->dtb_tomax == NULL) {
16483179193Sjb			ASSERT(buf->dtb_xamot == NULL);
16484179193Sjb			mutex_exit(&dtrace_lock);
16485179193Sjb			return (ENOENT);
16486179193Sjb		}
16487179193Sjb
16488179193Sjb		cached = buf->dtb_tomax;
16489179193Sjb		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16490179193Sjb
16491179193Sjb		dtrace_xcall(desc.dtbd_cpu,
16492179193Sjb		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
16493179193Sjb
16494179193Sjb		state->dts_errors += buf->dtb_xamot_errors;
16495179193Sjb
16496179193Sjb		/*
16497179193Sjb		 * If the buffers did not actually switch, then the cross call
16498179193Sjb		 * did not take place -- presumably because the given CPU is
16499179193Sjb		 * not in the ready set.  If this is the case, we'll return
16500179193Sjb		 * ENOENT.
16501179193Sjb		 */
16502179193Sjb		if (buf->dtb_tomax == cached) {
16503179193Sjb			ASSERT(buf->dtb_xamot != cached);
16504179193Sjb			mutex_exit(&dtrace_lock);
16505179193Sjb			return (ENOENT);
16506179193Sjb		}
16507179193Sjb
16508179193Sjb		ASSERT(cached == buf->dtb_xamot);
16509179193Sjb
16510179193Sjb		/*
16511179193Sjb		 * We have our snapshot; now copy it out.
16512179193Sjb		 */
16513179193Sjb		if (copyout(buf->dtb_xamot, desc.dtbd_data,
16514179193Sjb		    buf->dtb_xamot_offset) != 0) {
16515179193Sjb			mutex_exit(&dtrace_lock);
16516179193Sjb			return (EFAULT);
16517179193Sjb		}
16518179193Sjb
16519179193Sjb		desc.dtbd_size = buf->dtb_xamot_offset;
16520179193Sjb		desc.dtbd_drops = buf->dtb_xamot_drops;
16521179193Sjb		desc.dtbd_errors = buf->dtb_xamot_errors;
16522179193Sjb		desc.dtbd_oldest = 0;
16523256002Spfg		desc.dtbd_timestamp = buf->dtb_switched;
16524179193Sjb
16525179193Sjb		mutex_exit(&dtrace_lock);
16526179193Sjb
16527179193Sjb		/*
16528179193Sjb		 * Finally, copy out the buffer description.
16529179193Sjb		 */
16530179193Sjb		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16531179193Sjb			return (EFAULT);
16532179193Sjb
16533179193Sjb		return (0);
16534179193Sjb	}
16535179193Sjb
16536179193Sjb	case DTRACEIOC_CONF: {
16537179193Sjb		dtrace_conf_t conf;
16538179193Sjb
16539179193Sjb		bzero(&conf, sizeof (conf));
16540179193Sjb		conf.dtc_difversion = DIF_VERSION;
16541179193Sjb		conf.dtc_difintregs = DIF_DIR_NREGS;
16542179193Sjb		conf.dtc_diftupregs = DIF_DTR_NREGS;
16543179193Sjb		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16544179193Sjb
16545179193Sjb		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16546179193Sjb			return (EFAULT);
16547179193Sjb
16548179193Sjb		return (0);
16549179193Sjb	}
16550179193Sjb
16551179193Sjb	case DTRACEIOC_STATUS: {
16552179193Sjb		dtrace_status_t stat;
16553179193Sjb		dtrace_dstate_t *dstate;
16554179193Sjb		int i, j;
16555179193Sjb		uint64_t nerrs;
16556179193Sjb
16557179193Sjb		/*
16558179193Sjb		 * See the comment in dtrace_state_deadman() for the reason
16559179193Sjb		 * for setting dts_laststatus to INT64_MAX before setting
16560179193Sjb		 * it to the correct value.
16561179193Sjb		 */
16562179193Sjb		state->dts_laststatus = INT64_MAX;
16563179193Sjb		dtrace_membar_producer();
16564179193Sjb		state->dts_laststatus = dtrace_gethrtime();
16565179193Sjb
16566179193Sjb		bzero(&stat, sizeof (stat));
16567179193Sjb
16568179193Sjb		mutex_enter(&dtrace_lock);
16569179193Sjb
16570179193Sjb		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16571179193Sjb			mutex_exit(&dtrace_lock);
16572179193Sjb			return (ENOENT);
16573179193Sjb		}
16574179193Sjb
16575179193Sjb		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16576179193Sjb			stat.dtst_exiting = 1;
16577179193Sjb
16578179193Sjb		nerrs = state->dts_errors;
16579179193Sjb		dstate = &state->dts_vstate.dtvs_dynvars;
16580179193Sjb
16581179193Sjb		for (i = 0; i < NCPU; i++) {
16582179193Sjb			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16583179193Sjb
16584179193Sjb			stat.dtst_dyndrops += dcpu->dtdsc_drops;
16585179193Sjb			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16586179193Sjb			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16587179193Sjb
16588179193Sjb			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16589179193Sjb				stat.dtst_filled++;
16590179193Sjb
16591179193Sjb			nerrs += state->dts_buffer[i].dtb_errors;
16592179193Sjb
16593179193Sjb			for (j = 0; j < state->dts_nspeculations; j++) {
16594179193Sjb				dtrace_speculation_t *spec;
16595179193Sjb				dtrace_buffer_t *buf;
16596179193Sjb
16597179193Sjb				spec = &state->dts_speculations[j];
16598179193Sjb				buf = &spec->dtsp_buffer[i];
16599179193Sjb				stat.dtst_specdrops += buf->dtb_xamot_drops;
16600179193Sjb			}
16601179193Sjb		}
16602179193Sjb
16603179193Sjb		stat.dtst_specdrops_busy = state->dts_speculations_busy;
16604179193Sjb		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16605179193Sjb		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16606179193Sjb		stat.dtst_dblerrors = state->dts_dblerrors;
16607179193Sjb		stat.dtst_killed =
16608179193Sjb		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16609179193Sjb		stat.dtst_errors = nerrs;
16610179193Sjb
16611179193Sjb		mutex_exit(&dtrace_lock);
16612179193Sjb
16613179193Sjb		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16614179193Sjb			return (EFAULT);
16615179193Sjb
16616179193Sjb		return (0);
16617179193Sjb	}
16618179193Sjb
16619179193Sjb	case DTRACEIOC_FORMAT: {
16620179193Sjb		dtrace_fmtdesc_t fmt;
16621179193Sjb		char *str;
16622179193Sjb		int len;
16623179193Sjb
16624179193Sjb		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16625179193Sjb			return (EFAULT);
16626179193Sjb
16627179193Sjb		mutex_enter(&dtrace_lock);
16628179193Sjb
16629179193Sjb		if (fmt.dtfd_format == 0 ||
16630179193Sjb		    fmt.dtfd_format > state->dts_nformats) {
16631179193Sjb			mutex_exit(&dtrace_lock);
16632179193Sjb			return (EINVAL);
16633179193Sjb		}
16634179193Sjb
16635179193Sjb		/*
16636179193Sjb		 * Format strings are allocated contiguously and they are
16637179193Sjb		 * never freed; if a format index is less than the number
16638179193Sjb		 * of formats, we can assert that the format map is non-NULL
16639179193Sjb		 * and that the format for the specified index is non-NULL.
16640179193Sjb		 */
16641179193Sjb		ASSERT(state->dts_formats != NULL);
16642179193Sjb		str = state->dts_formats[fmt.dtfd_format - 1];
16643179193Sjb		ASSERT(str != NULL);
16644179193Sjb
16645179193Sjb		len = strlen(str) + 1;
16646179193Sjb
16647179193Sjb		if (len > fmt.dtfd_length) {
16648179193Sjb			fmt.dtfd_length = len;
16649179193Sjb
16650179193Sjb			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16651179193Sjb				mutex_exit(&dtrace_lock);
16652179193Sjb				return (EINVAL);
16653179193Sjb			}
16654179193Sjb		} else {
16655179193Sjb			if (copyout(str, fmt.dtfd_string, len) != 0) {
16656179193Sjb				mutex_exit(&dtrace_lock);
16657179193Sjb				return (EINVAL);
16658179193Sjb			}
16659179193Sjb		}
16660179193Sjb
16661179193Sjb		mutex_exit(&dtrace_lock);
16662179193Sjb		return (0);
16663179193Sjb	}
16664179193Sjb
16665179193Sjb	default:
16666179193Sjb		break;
16667179193Sjb	}
16668179193Sjb
16669179193Sjb	return (ENOTTY);
16670179193Sjb}
16671179193Sjb
16672179193Sjb/*ARGSUSED*/
16673179193Sjbstatic int
16674179193Sjbdtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16675179193Sjb{
16676179193Sjb	dtrace_state_t *state;
16677179193Sjb
16678179193Sjb	switch (cmd) {
16679179193Sjb	case DDI_DETACH:
16680179193Sjb		break;
16681179193Sjb
16682179193Sjb	case DDI_SUSPEND:
16683179193Sjb		return (DDI_SUCCESS);
16684179193Sjb
16685179193Sjb	default:
16686179193Sjb		return (DDI_FAILURE);
16687179193Sjb	}
16688179193Sjb
16689179193Sjb	mutex_enter(&cpu_lock);
16690179193Sjb	mutex_enter(&dtrace_provider_lock);
16691179193Sjb	mutex_enter(&dtrace_lock);
16692179193Sjb
16693179193Sjb	ASSERT(dtrace_opens == 0);
16694179193Sjb
16695179193Sjb	if (dtrace_helpers > 0) {
16696179193Sjb		mutex_exit(&dtrace_provider_lock);
16697179193Sjb		mutex_exit(&dtrace_lock);
16698179193Sjb		mutex_exit(&cpu_lock);
16699179193Sjb		return (DDI_FAILURE);
16700179193Sjb	}
16701179193Sjb
16702179193Sjb	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16703179193Sjb		mutex_exit(&dtrace_provider_lock);
16704179193Sjb		mutex_exit(&dtrace_lock);
16705179193Sjb		mutex_exit(&cpu_lock);
16706179193Sjb		return (DDI_FAILURE);
16707179193Sjb	}
16708179193Sjb
16709179193Sjb	dtrace_provider = NULL;
16710179193Sjb
16711179193Sjb	if ((state = dtrace_anon_grab()) != NULL) {
16712179193Sjb		/*
16713179193Sjb		 * If there were ECBs on this state, the provider should
16714179193Sjb		 * have not been allowed to detach; assert that there is
16715179193Sjb		 * none.
16716179193Sjb		 */
16717179193Sjb		ASSERT(state->dts_necbs == 0);
16718179193Sjb		dtrace_state_destroy(state);
16719179193Sjb
16720179193Sjb		/*
16721179193Sjb		 * If we're being detached with anonymous state, we need to
16722179193Sjb		 * indicate to the kernel debugger that DTrace is now inactive.
16723179193Sjb		 */
16724179193Sjb		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16725179193Sjb	}
16726179193Sjb
16727179193Sjb	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16728179193Sjb	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16729179193Sjb	dtrace_cpu_init = NULL;
16730179193Sjb	dtrace_helpers_cleanup = NULL;
16731179193Sjb	dtrace_helpers_fork = NULL;
16732179193Sjb	dtrace_cpustart_init = NULL;
16733179193Sjb	dtrace_cpustart_fini = NULL;
16734179193Sjb	dtrace_debugger_init = NULL;
16735179193Sjb	dtrace_debugger_fini = NULL;
16736179193Sjb	dtrace_modload = NULL;
16737179193Sjb	dtrace_modunload = NULL;
16738179193Sjb
16739179193Sjb	mutex_exit(&cpu_lock);
16740179193Sjb
16741179193Sjb	if (dtrace_helptrace_enabled) {
16742179193Sjb		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
16743179193Sjb		dtrace_helptrace_buffer = NULL;
16744179193Sjb	}
16745179193Sjb
16746179193Sjb	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16747179193Sjb	dtrace_probes = NULL;
16748179193Sjb	dtrace_nprobes = 0;
16749179193Sjb
16750179193Sjb	dtrace_hash_destroy(dtrace_bymod);
16751179193Sjb	dtrace_hash_destroy(dtrace_byfunc);
16752179193Sjb	dtrace_hash_destroy(dtrace_byname);
16753179193Sjb	dtrace_bymod = NULL;
16754179193Sjb	dtrace_byfunc = NULL;
16755179193Sjb	dtrace_byname = NULL;
16756179193Sjb
16757179193Sjb	kmem_cache_destroy(dtrace_state_cache);
16758179193Sjb	vmem_destroy(dtrace_minor);
16759179193Sjb	vmem_destroy(dtrace_arena);
16760179193Sjb
16761179193Sjb	if (dtrace_toxrange != NULL) {
16762179193Sjb		kmem_free(dtrace_toxrange,
16763179193Sjb		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16764179193Sjb		dtrace_toxrange = NULL;
16765179193Sjb		dtrace_toxranges = 0;
16766179193Sjb		dtrace_toxranges_max = 0;
16767179193Sjb	}
16768179193Sjb
16769179193Sjb	ddi_remove_minor_node(dtrace_devi, NULL);
16770179193Sjb	dtrace_devi = NULL;
16771179193Sjb
16772179193Sjb	ddi_soft_state_fini(&dtrace_softstate);
16773179193Sjb
16774179193Sjb	ASSERT(dtrace_vtime_references == 0);
16775179193Sjb	ASSERT(dtrace_opens == 0);
16776179193Sjb	ASSERT(dtrace_retained == NULL);
16777179193Sjb
16778179193Sjb	mutex_exit(&dtrace_lock);
16779179193Sjb	mutex_exit(&dtrace_provider_lock);
16780179193Sjb
16781179193Sjb	/*
16782179193Sjb	 * We don't destroy the task queue until after we have dropped our
16783179193Sjb	 * locks (taskq_destroy() may block on running tasks).  To prevent
16784179193Sjb	 * attempting to do work after we have effectively detached but before
16785179193Sjb	 * the task queue has been destroyed, all tasks dispatched via the
16786179193Sjb	 * task queue must check that DTrace is still attached before
16787179193Sjb	 * performing any operation.
16788179193Sjb	 */
16789179193Sjb	taskq_destroy(dtrace_taskq);
16790179193Sjb	dtrace_taskq = NULL;
16791179193Sjb
16792179193Sjb	return (DDI_SUCCESS);
16793179193Sjb}
16794179198Sjb#endif
16795179193Sjb
16796179198Sjb#if defined(sun)
16797179193Sjb/*ARGSUSED*/
16798179193Sjbstatic int
16799179193Sjbdtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16800179193Sjb{
16801179193Sjb	int error;
16802179193Sjb
16803179193Sjb	switch (infocmd) {
16804179193Sjb	case DDI_INFO_DEVT2DEVINFO:
16805179193Sjb		*result = (void *)dtrace_devi;
16806179193Sjb		error = DDI_SUCCESS;
16807179193Sjb		break;
16808179193Sjb	case DDI_INFO_DEVT2INSTANCE:
16809179193Sjb		*result = (void *)0;
16810179193Sjb		error = DDI_SUCCESS;
16811179193Sjb		break;
16812179193Sjb	default:
16813179193Sjb		error = DDI_FAILURE;
16814179193Sjb	}
16815179193Sjb	return (error);
16816179193Sjb}
16817179198Sjb#endif
16818179193Sjb
16819179198Sjb#if defined(sun)
16820179193Sjbstatic struct cb_ops dtrace_cb_ops = {
16821179193Sjb	dtrace_open,		/* open */
16822179193Sjb	dtrace_close,		/* close */
16823179193Sjb	nulldev,		/* strategy */
16824179193Sjb	nulldev,		/* print */
16825179193Sjb	nodev,			/* dump */
16826179193Sjb	nodev,			/* read */
16827179193Sjb	nodev,			/* write */
16828179193Sjb	dtrace_ioctl,		/* ioctl */
16829179193Sjb	nodev,			/* devmap */
16830179193Sjb	nodev,			/* mmap */
16831179193Sjb	nodev,			/* segmap */
16832179193Sjb	nochpoll,		/* poll */
16833179193Sjb	ddi_prop_op,		/* cb_prop_op */
16834179193Sjb	0,			/* streamtab  */
16835179193Sjb	D_NEW | D_MP		/* Driver compatibility flag */
16836179193Sjb};
16837179193Sjb
16838179193Sjbstatic struct dev_ops dtrace_ops = {
16839179193Sjb	DEVO_REV,		/* devo_rev */
16840179193Sjb	0,			/* refcnt */
16841179193Sjb	dtrace_info,		/* get_dev_info */
16842179193Sjb	nulldev,		/* identify */
16843179193Sjb	nulldev,		/* probe */
16844179193Sjb	dtrace_attach,		/* attach */
16845179193Sjb	dtrace_detach,		/* detach */
16846179193Sjb	nodev,			/* reset */
16847179193Sjb	&dtrace_cb_ops,		/* driver operations */
16848179193Sjb	NULL,			/* bus operations */
16849179193Sjb	nodev			/* dev power */
16850179193Sjb};
16851179193Sjb
16852179193Sjbstatic struct modldrv modldrv = {
16853179193Sjb	&mod_driverops,		/* module type (this is a pseudo driver) */
16854179193Sjb	"Dynamic Tracing",	/* name of module */
16855179193Sjb	&dtrace_ops,		/* driver ops */
16856179193Sjb};
16857179193Sjb
16858179193Sjbstatic struct modlinkage modlinkage = {
16859179193Sjb	MODREV_1,
16860179193Sjb	(void *)&modldrv,
16861179193Sjb	NULL
16862179193Sjb};
16863179193Sjb
16864179193Sjbint
16865179193Sjb_init(void)
16866179193Sjb{
16867179193Sjb	return (mod_install(&modlinkage));
16868179193Sjb}
16869179193Sjb
16870179193Sjbint
16871179193Sjb_info(struct modinfo *modinfop)
16872179193Sjb{
16873179193Sjb	return (mod_info(&modlinkage, modinfop));
16874179193Sjb}
16875179193Sjb
16876179193Sjbint
16877179193Sjb_fini(void)
16878179193Sjb{
16879179193Sjb	return (mod_remove(&modlinkage));
16880179193Sjb}
16881179198Sjb#else
16882179198Sjb
16883179198Sjbstatic d_ioctl_t	dtrace_ioctl;
16884211608Srpaulostatic d_ioctl_t	dtrace_ioctl_helper;
16885179198Sjbstatic void		dtrace_load(void *);
16886179198Sjbstatic int		dtrace_unload(void);
16887184698Srodrigc#if __FreeBSD_version < 800039
16888179198Sjbstatic void		dtrace_clone(void *, struct ucred *, char *, int , struct cdev **);
16889179198Sjbstatic struct clonedevs	*dtrace_clones;		/* Ptr to the array of cloned devices. */
16890179198Sjbstatic eventhandler_tag	eh_tag;			/* Event handler tag. */
16891184698Srodrigc#else
16892184698Srodrigcstatic struct cdev	*dtrace_dev;
16893211608Srpaulostatic struct cdev	*helper_dev;
16894184698Srodrigc#endif
16895179198Sjb
16896179198Sjbvoid dtrace_invop_init(void);
16897179198Sjbvoid dtrace_invop_uninit(void);
16898179198Sjb
16899179198Sjbstatic struct cdevsw dtrace_cdevsw = {
16900179198Sjb	.d_version	= D_VERSION,
16901184698Srodrigc	.d_flags	= D_TRACKCLOSE | D_NEEDMINOR,
16902179198Sjb	.d_close	= dtrace_close,
16903179198Sjb	.d_ioctl	= dtrace_ioctl,
16904179198Sjb	.d_open		= dtrace_open,
16905179198Sjb	.d_name		= "dtrace",
16906179198Sjb};
16907179198Sjb
16908211608Srpaulostatic struct cdevsw helper_cdevsw = {
16909211608Srpaulo	.d_version	= D_VERSION,
16910211608Srpaulo	.d_flags	= D_TRACKCLOSE | D_NEEDMINOR,
16911211608Srpaulo	.d_ioctl	= dtrace_ioctl_helper,
16912211608Srpaulo	.d_name		= "helper",
16913211608Srpaulo};
16914211608Srpaulo
16915179198Sjb#include <dtrace_anon.c>
16916184698Srodrigc#if __FreeBSD_version < 800039
16917179198Sjb#include <dtrace_clone.c>
16918184698Srodrigc#endif
16919179198Sjb#include <dtrace_ioctl.c>
16920179198Sjb#include <dtrace_load.c>
16921179198Sjb#include <dtrace_modevent.c>
16922179198Sjb#include <dtrace_sysctl.c>
16923179198Sjb#include <dtrace_unload.c>
16924179198Sjb#include <dtrace_vtime.c>
16925179198Sjb#include <dtrace_hacks.c>
16926179198Sjb#include <dtrace_isa.c>
16927179198Sjb
16928179198SjbSYSINIT(dtrace_load, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_load, NULL);
16929179198SjbSYSUNINIT(dtrace_unload, SI_SUB_DTRACE, SI_ORDER_FIRST, dtrace_unload, NULL);
16930179198SjbSYSINIT(dtrace_anon_init, SI_SUB_DTRACE_ANON, SI_ORDER_FIRST, dtrace_anon_init, NULL);
16931179198Sjb
16932179198SjbDEV_MODULE(dtrace, dtrace_modevent, NULL);
16933179198SjbMODULE_VERSION(dtrace, 1);
16934179198SjbMODULE_DEPEND(dtrace, cyclic, 1, 1, 1);
16935179198SjbMODULE_DEPEND(dtrace, opensolaris, 1, 1, 1);
16936179198Sjb#endif
16937