1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License, Version 1.0 only
6 * (the "License").  You may not use this file except in compliance
7 * with the License.
8 *
9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 * or http://www.opensolaris.org/os/licensing.
11 * See the License for the specific language governing permissions
12 * and limitations under the License.
13 *
14 * When distributing Covered Code, include this CDDL HEADER in each
15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 * If applicable, add the following below this CDDL HEADER, with the
17 * fields enclosed by brackets "[]" replaced with your own identifying
18 * information: Portions Copyright [yyyy] [name of copyright owner]
19 *
20 * CDDL HEADER END
21 *
22 * $FreeBSD: stable/11/sys/cddl/dev/dtrace/i386/dtrace_subr.c 345868 2019-04-04 02:07:24Z markj $
23 *
24 */
25/*
26 * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
27 * Use is subject to license terms.
28 */
29
30/*
31 * Copyright (c) 2011, Joyent, Inc. All rights reserved.
32 */
33
34#include <sys/param.h>
35#include <sys/systm.h>
36#include <sys/types.h>
37#include <sys/cpuset.h>
38#include <sys/kernel.h>
39#include <sys/malloc.h>
40#include <sys/kmem.h>
41#include <sys/smp.h>
42#include <sys/dtrace_impl.h>
43#include <sys/dtrace_bsd.h>
44#include <machine/clock.h>
45#include <machine/cpufunc.h>
46#include <machine/frame.h>
47#include <machine/psl.h>
48#include <vm/pmap.h>
49
50extern uintptr_t 	kernelbase;
51
52extern void dtrace_getnanotime(struct timespec *tsp);
53
54int dtrace_invop(uintptr_t, struct trapframe *, uintptr_t);
55
56typedef struct dtrace_invop_hdlr {
57	int (*dtih_func)(uintptr_t, struct trapframe *, uintptr_t);
58	struct dtrace_invop_hdlr *dtih_next;
59} dtrace_invop_hdlr_t;
60
61dtrace_invop_hdlr_t *dtrace_invop_hdlr;
62
63int
64dtrace_invop(uintptr_t addr, struct trapframe *frame, uintptr_t eax)
65{
66	dtrace_invop_hdlr_t *hdlr;
67	int rval;
68
69	for (hdlr = dtrace_invop_hdlr; hdlr != NULL; hdlr = hdlr->dtih_next)
70		if ((rval = hdlr->dtih_func(addr, frame, eax)) != 0)
71			return (rval);
72
73	return (0);
74}
75
76void
77dtrace_invop_add(int (*func)(uintptr_t, struct trapframe *, uintptr_t))
78{
79	dtrace_invop_hdlr_t *hdlr;
80
81	hdlr = kmem_alloc(sizeof (dtrace_invop_hdlr_t), KM_SLEEP);
82	hdlr->dtih_func = func;
83	hdlr->dtih_next = dtrace_invop_hdlr;
84	dtrace_invop_hdlr = hdlr;
85}
86
87void
88dtrace_invop_remove(int (*func)(uintptr_t, struct trapframe *, uintptr_t))
89{
90	dtrace_invop_hdlr_t *hdlr = dtrace_invop_hdlr, *prev = NULL;
91
92	for (;;) {
93		if (hdlr == NULL)
94			panic("attempt to remove non-existent invop handler");
95
96		if (hdlr->dtih_func == func)
97			break;
98
99		prev = hdlr;
100		hdlr = hdlr->dtih_next;
101	}
102
103	if (prev == NULL) {
104		ASSERT(dtrace_invop_hdlr == hdlr);
105		dtrace_invop_hdlr = hdlr->dtih_next;
106	} else {
107		ASSERT(dtrace_invop_hdlr != hdlr);
108		prev->dtih_next = hdlr->dtih_next;
109	}
110
111	kmem_free(hdlr, 0);
112}
113
114void
115dtrace_toxic_ranges(void (*func)(uintptr_t base, uintptr_t limit))
116{
117	(*func)(0, kernelbase);
118}
119
120void
121dtrace_xcall(processorid_t cpu, dtrace_xcall_t func, void *arg)
122{
123	cpuset_t cpus;
124
125	if (cpu == DTRACE_CPUALL)
126		cpus = all_cpus;
127	else
128		CPU_SETOF(cpu, &cpus);
129
130	smp_rendezvous_cpus(cpus, smp_no_rendezvous_barrier, func,
131	    smp_no_rendezvous_barrier, arg);
132}
133
134static void
135dtrace_sync_func(void)
136{
137}
138
139void
140dtrace_sync(void)
141{
142        dtrace_xcall(DTRACE_CPUALL, (dtrace_xcall_t)dtrace_sync_func, NULL);
143}
144
145#ifdef notyet
146void
147dtrace_safe_synchronous_signal(void)
148{
149	kthread_t *t = curthread;
150	struct regs *rp = lwptoregs(ttolwp(t));
151	size_t isz = t->t_dtrace_npc - t->t_dtrace_pc;
152
153	ASSERT(t->t_dtrace_on);
154
155	/*
156	 * If we're not in the range of scratch addresses, we're not actually
157	 * tracing user instructions so turn off the flags. If the instruction
158	 * we copied out caused a synchonous trap, reset the pc back to its
159	 * original value and turn off the flags.
160	 */
161	if (rp->r_pc < t->t_dtrace_scrpc ||
162	    rp->r_pc > t->t_dtrace_astpc + isz) {
163		t->t_dtrace_ft = 0;
164	} else if (rp->r_pc == t->t_dtrace_scrpc ||
165	    rp->r_pc == t->t_dtrace_astpc) {
166		rp->r_pc = t->t_dtrace_pc;
167		t->t_dtrace_ft = 0;
168	}
169}
170
171int
172dtrace_safe_defer_signal(void)
173{
174	kthread_t *t = curthread;
175	struct regs *rp = lwptoregs(ttolwp(t));
176	size_t isz = t->t_dtrace_npc - t->t_dtrace_pc;
177
178	ASSERT(t->t_dtrace_on);
179
180	/*
181	 * If we're not in the range of scratch addresses, we're not actually
182	 * tracing user instructions so turn off the flags.
183	 */
184	if (rp->r_pc < t->t_dtrace_scrpc ||
185	    rp->r_pc > t->t_dtrace_astpc + isz) {
186		t->t_dtrace_ft = 0;
187		return (0);
188	}
189
190	/*
191	 * If we have executed the original instruction, but we have performed
192	 * neither the jmp back to t->t_dtrace_npc nor the clean up of any
193	 * registers used to emulate %rip-relative instructions in 64-bit mode,
194	 * we'll save ourselves some effort by doing that here and taking the
195	 * signal right away.  We detect this condition by seeing if the program
196	 * counter is the range [scrpc + isz, astpc).
197	 */
198	if (rp->r_pc >= t->t_dtrace_scrpc + isz &&
199	    rp->r_pc < t->t_dtrace_astpc) {
200#ifdef __amd64
201		/*
202		 * If there is a scratch register and we're on the
203		 * instruction immediately after the modified instruction,
204		 * restore the value of that scratch register.
205		 */
206		if (t->t_dtrace_reg != 0 &&
207		    rp->r_pc == t->t_dtrace_scrpc + isz) {
208			switch (t->t_dtrace_reg) {
209			case REG_RAX:
210				rp->r_rax = t->t_dtrace_regv;
211				break;
212			case REG_RCX:
213				rp->r_rcx = t->t_dtrace_regv;
214				break;
215			case REG_R8:
216				rp->r_r8 = t->t_dtrace_regv;
217				break;
218			case REG_R9:
219				rp->r_r9 = t->t_dtrace_regv;
220				break;
221			}
222		}
223#endif
224		rp->r_pc = t->t_dtrace_npc;
225		t->t_dtrace_ft = 0;
226		return (0);
227	}
228
229	/*
230	 * Otherwise, make sure we'll return to the kernel after executing
231	 * the copied out instruction and defer the signal.
232	 */
233	if (!t->t_dtrace_step) {
234		ASSERT(rp->r_pc < t->t_dtrace_astpc);
235		rp->r_pc += t->t_dtrace_astpc - t->t_dtrace_scrpc;
236		t->t_dtrace_step = 1;
237	}
238
239	t->t_dtrace_ast = 1;
240
241	return (1);
242}
243#endif
244
245static int64_t	tgt_cpu_tsc;
246static int64_t	hst_cpu_tsc;
247static int64_t	tsc_skew[MAXCPU];
248static uint64_t	nsec_scale;
249
250/* See below for the explanation of this macro. */
251#define SCALE_SHIFT	28
252
253static void
254dtrace_gethrtime_init_cpu(void *arg)
255{
256	uintptr_t cpu = (uintptr_t) arg;
257
258	if (cpu == curcpu)
259		tgt_cpu_tsc = rdtsc();
260	else
261		hst_cpu_tsc = rdtsc();
262}
263
264#ifdef EARLY_AP_STARTUP
265static void
266dtrace_gethrtime_init(void *arg)
267{
268	struct pcpu *pc;
269	uint64_t tsc_f;
270	cpuset_t map;
271	int i;
272#else
273/*
274 * Get the frequency and scale factor as early as possible so that they can be
275 * used for boot-time tracing.
276 */
277static void
278dtrace_gethrtime_init_early(void *arg)
279{
280	uint64_t tsc_f;
281#endif
282
283	/*
284	 * Get TSC frequency known at this moment.
285	 * This should be constant if TSC is invariant.
286	 * Otherwise tick->time conversion will be inaccurate, but
287	 * will preserve monotonic property of TSC.
288	 */
289	tsc_f = atomic_load_acq_64(&tsc_freq);
290
291	/*
292	 * The following line checks that nsec_scale calculated below
293	 * doesn't overflow 32-bit unsigned integer, so that it can multiply
294	 * another 32-bit integer without overflowing 64-bit.
295	 * Thus minimum supported TSC frequency is 62.5MHz.
296	 */
297	KASSERT(tsc_f > (NANOSEC >> (32 - SCALE_SHIFT)),
298	    ("TSC frequency is too low"));
299
300	/*
301	 * We scale up NANOSEC/tsc_f ratio to preserve as much precision
302	 * as possible.
303	 * 2^28 factor was chosen quite arbitrarily from practical
304	 * considerations:
305	 * - it supports TSC frequencies as low as 62.5MHz (see above);
306	 * - it provides quite good precision (e < 0.01%) up to THz
307	 *   (terahertz) values;
308	 */
309	nsec_scale = ((uint64_t)NANOSEC << SCALE_SHIFT) / tsc_f;
310#ifndef EARLY_AP_STARTUP
311}
312SYSINIT(dtrace_gethrtime_init_early, SI_SUB_CPU, SI_ORDER_ANY,
313    dtrace_gethrtime_init_early, NULL);
314
315static void
316dtrace_gethrtime_init(void *arg)
317{
318	cpuset_t map;
319	struct pcpu *pc;
320	int i;
321#endif
322
323	if (vm_guest != VM_GUEST_NO)
324		return;
325
326	/* The current CPU is the reference one. */
327	sched_pin();
328	tsc_skew[curcpu] = 0;
329	CPU_FOREACH(i) {
330		if (i == curcpu)
331			continue;
332
333		pc = pcpu_find(i);
334		CPU_SETOF(PCPU_GET(cpuid), &map);
335		CPU_SET(pc->pc_cpuid, &map);
336
337		smp_rendezvous_cpus(map, NULL,
338		    dtrace_gethrtime_init_cpu,
339		    smp_no_rendezvous_barrier, (void *)(uintptr_t) i);
340
341		tsc_skew[i] = tgt_cpu_tsc - hst_cpu_tsc;
342	}
343	sched_unpin();
344}
345#ifdef EARLY_AP_STARTUP
346SYSINIT(dtrace_gethrtime_init, SI_SUB_DTRACE, SI_ORDER_ANY,
347    dtrace_gethrtime_init, NULL);
348#else
349SYSINIT(dtrace_gethrtime_init, SI_SUB_SMP, SI_ORDER_ANY, dtrace_gethrtime_init,
350    NULL);
351#endif
352
353/*
354 * DTrace needs a high resolution time function which can
355 * be called from a probe context and guaranteed not to have
356 * instrumented with probes itself.
357 *
358 * Returns nanoseconds since boot.
359 */
360uint64_t
361dtrace_gethrtime(void)
362{
363	uint64_t tsc;
364	uint32_t lo, hi;
365	register_t eflags;
366
367	/*
368	 * We split TSC value into lower and higher 32-bit halves and separately
369	 * scale them with nsec_scale, then we scale them down by 2^28
370	 * (see nsec_scale calculations) taking into account 32-bit shift of
371	 * the higher half and finally add.
372	 */
373	eflags = intr_disable();
374	tsc = rdtsc() - tsc_skew[curcpu];
375	intr_restore(eflags);
376
377	lo = tsc;
378	hi = tsc >> 32;
379	return (((lo * nsec_scale) >> SCALE_SHIFT) +
380	    ((hi * nsec_scale) << (32 - SCALE_SHIFT)));
381}
382
383uint64_t
384dtrace_gethrestime(void)
385{
386	struct timespec current_time;
387
388	dtrace_getnanotime(&current_time);
389
390	return (current_time.tv_sec * 1000000000ULL + current_time.tv_nsec);
391}
392
393/* Function to handle DTrace traps during probes. See i386/i386/trap.c */
394int
395dtrace_trap(struct trapframe *frame, u_int type)
396{
397	uint16_t nofault;
398
399	/*
400	 * A trap can occur while DTrace executes a probe. Before
401	 * executing the probe, DTrace blocks re-scheduling and sets
402	 * a flag in its per-cpu flags to indicate that it doesn't
403	 * want to fault. On returning from the probe, the no-fault
404	 * flag is cleared and finally re-scheduling is enabled.
405	 *
406	 * Check if DTrace has enabled 'no-fault' mode:
407	 */
408	sched_pin();
409	nofault = cpu_core[curcpu].cpuc_dtrace_flags & CPU_DTRACE_NOFAULT;
410	sched_unpin();
411	if (nofault) {
412		KASSERT((read_eflags() & PSL_I) == 0, ("interrupts enabled"));
413
414		/*
415		 * There are only a couple of trap types that are expected.
416		 * All the rest will be handled in the usual way.
417		 */
418		switch (type) {
419		/* General protection fault. */
420		case T_PROTFLT:
421			/* Flag an illegal operation. */
422			cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
423
424			/*
425			 * Offset the instruction pointer to the instruction
426			 * following the one causing the fault.
427			 */
428			frame->tf_eip += dtrace_instr_size((u_char *) frame->tf_eip);
429			return (1);
430		/* Page fault. */
431		case T_PAGEFLT:
432			/* Flag a bad address. */
433			cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_BADADDR;
434			cpu_core[curcpu].cpuc_dtrace_illval = rcr2();
435
436			/*
437			 * Offset the instruction pointer to the instruction
438			 * following the one causing the fault.
439			 */
440			frame->tf_eip += dtrace_instr_size((u_char *) frame->tf_eip);
441			return (1);
442		default:
443			/* Handle all other traps in the usual way. */
444			break;
445		}
446	}
447
448	/* Handle the trap in the usual way. */
449	return (0);
450}
451