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