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