xref: /freebsd/sys/cddl/dev/dtrace/amd64/dtrace_subr.c (revision a64729f5077d77e13b9497cb33ecb3c82e606ee8)
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 static void
287 dtrace_gethrtime_init(void *arg)
288 {
289 	struct pcpu *pc;
290 	uint64_t tsc_f;
291 	cpuset_t map;
292 	int i;
293 
294 	/*
295 	 * Get TSC frequency known at this moment.
296 	 * This should be constant if TSC is invariant.
297 	 * Otherwise tick->time conversion will be inaccurate, but
298 	 * will preserve monotonic property of TSC.
299 	 */
300 	tsc_f = atomic_load_acq_64(&tsc_freq);
301 
302 	/*
303 	 * The following line checks that nsec_scale calculated below
304 	 * doesn't overflow 32-bit unsigned integer, so that it can multiply
305 	 * another 32-bit integer without overflowing 64-bit.
306 	 * Thus minimum supported TSC frequency is 62.5MHz.
307 	 */
308 	KASSERT(tsc_f > (NANOSEC >> (32 - SCALE_SHIFT)),
309 	    ("TSC frequency is too low"));
310 
311 	/*
312 	 * We scale up NANOSEC/tsc_f ratio to preserve as much precision
313 	 * as possible.
314 	 * 2^28 factor was chosen quite arbitrarily from practical
315 	 * considerations:
316 	 * - it supports TSC frequencies as low as 62.5MHz (see above);
317 	 * - it provides quite good precision (e < 0.01%) up to THz
318 	 *   (terahertz) values;
319 	 */
320 	nsec_scale = ((uint64_t)NANOSEC << SCALE_SHIFT) / tsc_f;
321 
322 	if (vm_guest != VM_GUEST_NO)
323 		return;
324 
325 	/* The current CPU is the reference one. */
326 	sched_pin();
327 	tsc_skew[curcpu] = 0;
328 	CPU_FOREACH(i) {
329 		if (i == curcpu)
330 			continue;
331 
332 		pc = pcpu_find(i);
333 		CPU_SETOF(PCPU_GET(cpuid), &map);
334 		CPU_SET(pc->pc_cpuid, &map);
335 
336 		smp_rendezvous_cpus(map, NULL,
337 		    dtrace_gethrtime_init_cpu,
338 		    smp_no_rendezvous_barrier, (void *)(uintptr_t) i);
339 
340 		tsc_skew[i] = tgt_cpu_tsc - hst_cpu_tsc;
341 	}
342 	sched_unpin();
343 }
344 SYSINIT(dtrace_gethrtime_init, SI_SUB_DTRACE, SI_ORDER_ANY,
345     dtrace_gethrtime_init, NULL);
346 
347 /*
348  * DTrace needs a high resolution time function which can
349  * be called from a probe context and guaranteed not to have
350  * instrumented with probes itself.
351  *
352  * Returns nanoseconds since boot.
353  */
354 uint64_t
355 dtrace_gethrtime(void)
356 {
357 	uint64_t tsc;
358 	uint32_t lo, hi;
359 	register_t rflags;
360 
361 	/*
362 	 * We split TSC value into lower and higher 32-bit halves and separately
363 	 * scale them with nsec_scale, then we scale them down by 2^28
364 	 * (see nsec_scale calculations) taking into account 32-bit shift of
365 	 * the higher half and finally add.
366 	 */
367 	rflags = intr_disable();
368 	tsc = rdtsc() - tsc_skew[curcpu];
369 	intr_restore(rflags);
370 
371 	lo = tsc;
372 	hi = tsc >> 32;
373 	return (((lo * nsec_scale) >> SCALE_SHIFT) +
374 	    ((hi * nsec_scale) << (32 - SCALE_SHIFT)));
375 }
376 
377 uint64_t
378 dtrace_gethrestime(void)
379 {
380 	struct timespec current_time;
381 
382 	dtrace_getnanotime(&current_time);
383 
384 	return (current_time.tv_sec * 1000000000ULL + current_time.tv_nsec);
385 }
386 
387 /* Function to handle DTrace traps during probes. See amd64/amd64/trap.c. */
388 int
389 dtrace_trap(struct trapframe *frame, u_int type)
390 {
391 	uint16_t nofault;
392 
393 	/*
394 	 * A trap can occur while DTrace executes a probe. Before
395 	 * executing the probe, DTrace blocks re-scheduling and sets
396 	 * a flag in its per-cpu flags to indicate that it doesn't
397 	 * want to fault. On returning from the probe, the no-fault
398 	 * flag is cleared and finally re-scheduling is enabled.
399 	 *
400 	 * Check if DTrace has enabled 'no-fault' mode:
401 	 */
402 	sched_pin();
403 	nofault = cpu_core[curcpu].cpuc_dtrace_flags & CPU_DTRACE_NOFAULT;
404 	sched_unpin();
405 	if (nofault) {
406 		KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
407 
408 		/*
409 		 * There are only a couple of trap types that are expected.
410 		 * All the rest will be handled in the usual way.
411 		 */
412 		switch (type) {
413 		/* General protection fault. */
414 		case T_PROTFLT:
415 			/* Flag an illegal operation. */
416 			cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
417 
418 			/*
419 			 * Offset the instruction pointer to the instruction
420 			 * following the one causing the fault.
421 			 */
422 			frame->tf_rip += dtrace_instr_size((uint8_t *) frame->tf_rip);
423 			return (1);
424 		/* Page fault. */
425 		case T_PAGEFLT:
426 			/* Flag a bad address. */
427 			cpu_core[curcpu].cpuc_dtrace_flags |= CPU_DTRACE_BADADDR;
428 			cpu_core[curcpu].cpuc_dtrace_illval = frame->tf_addr;
429 
430 			/*
431 			 * Offset the instruction pointer to the instruction
432 			 * following the one causing the fault.
433 			 */
434 			frame->tf_rip += dtrace_instr_size((uint8_t *) frame->tf_rip);
435 			return (1);
436 		default:
437 			/* Handle all other traps in the usual way. */
438 			break;
439 		}
440 	}
441 
442 	/* Handle the trap in the usual way. */
443 	return (0);
444 }
445