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