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