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