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