xref: /freebsd/sys/dev/acpica/acpi_timer.c (revision c03c5b1c)
1 /*-
2  * Copyright (c) 2000, 2001 Michael Smith
3  * Copyright (c) 2000 BSDi
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_acpi.h"
32 #include <sys/param.h>
33 #include <sys/bus.h>
34 #include <sys/eventhandler.h>
35 #include <sys/kernel.h>
36 #include <sys/module.h>
37 #include <sys/sysctl.h>
38 #include <sys/timetc.h>
39 
40 #include <machine/bus.h>
41 #include <machine/resource.h>
42 #include <sys/rman.h>
43 
44 #include <contrib/dev/acpica/include/acpi.h>
45 #include <contrib/dev/acpica/include/accommon.h>
46 
47 #include <dev/acpica/acpivar.h>
48 #include <dev/pci/pcivar.h>
49 
50 /*
51  * A timecounter based on the free-running ACPI timer.
52  *
53  * Based on the i386-only mp_clock.c by <phk@FreeBSD.ORG>.
54  */
55 
56 /* Hooks for the ACPI CA debugging infrastructure */
57 #define _COMPONENT	ACPI_TIMER
58 ACPI_MODULE_NAME("TIMER")
59 
60 static device_t			acpi_timer_dev;
61 static struct resource		*acpi_timer_reg;
62 static bus_space_handle_t	acpi_timer_bsh;
63 static bus_space_tag_t		acpi_timer_bst;
64 static eventhandler_tag		acpi_timer_eh;
65 
66 static u_int	acpi_timer_frequency = 14318182 / 4;
67 
68 /* Knob to disable acpi_timer device */
69 bool acpi_timer_disabled = false;
70 
71 static void	acpi_timer_identify(driver_t *driver, device_t parent);
72 static int	acpi_timer_probe(device_t dev);
73 static int	acpi_timer_attach(device_t dev);
74 static void	acpi_timer_resume_handler(struct timecounter *);
75 static void	acpi_timer_suspend_handler(struct timecounter *);
76 static u_int	acpi_timer_get_timecount(struct timecounter *tc);
77 static u_int	acpi_timer_get_timecount_safe(struct timecounter *tc);
78 static int	acpi_timer_sysctl_freq(SYSCTL_HANDLER_ARGS);
79 static void	acpi_timer_boot_test(void);
80 
81 static int	acpi_timer_test(void);
82 static int	acpi_timer_test_enabled = 0;
83 TUNABLE_INT("hw.acpi.timer_test_enabled", &acpi_timer_test_enabled);
84 
85 static device_method_t acpi_timer_methods[] = {
86     DEVMETHOD(device_identify,	acpi_timer_identify),
87     DEVMETHOD(device_probe,	acpi_timer_probe),
88     DEVMETHOD(device_attach,	acpi_timer_attach),
89 
90     DEVMETHOD_END
91 };
92 
93 static driver_t acpi_timer_driver = {
94     "acpi_timer",
95     acpi_timer_methods,
96     0,
97 };
98 
99 static devclass_t acpi_timer_devclass;
100 DRIVER_MODULE(acpi_timer, acpi, acpi_timer_driver, acpi_timer_devclass, 0, 0);
101 MODULE_DEPEND(acpi_timer, acpi, 1, 1, 1);
102 
103 static struct timecounter acpi_timer_timecounter = {
104 	acpi_timer_get_timecount_safe,	/* get_timecount function */
105 	0,				/* no poll_pps */
106 	0,				/* no default counter_mask */
107 	0,				/* no default frequency */
108 	"ACPI",				/* name */
109 	-1				/* quality (chosen later) */
110 };
111 
112 static __inline uint32_t
113 acpi_timer_read(void)
114 {
115 
116     return (bus_space_read_4(acpi_timer_bst, acpi_timer_bsh, 0));
117 }
118 
119 /*
120  * Locate the ACPI timer using the FADT, set up and allocate the I/O resources
121  * we will be using.
122  */
123 static void
124 acpi_timer_identify(driver_t *driver, device_t parent)
125 {
126     device_t dev;
127     rman_res_t rlen, rstart;
128     int rid, rtype;
129 
130     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
131 
132     if (acpi_disabled("timer") || (acpi_quirks & ACPI_Q_TIMER) ||
133 	acpi_timer_dev || acpi_timer_disabled ||
134 	AcpiGbl_FADT.PmTimerLength == 0)
135 	return_VOID;
136 
137     if ((dev = BUS_ADD_CHILD(parent, 2, "acpi_timer", 0)) == NULL) {
138 	device_printf(parent, "could not add acpi_timer0\n");
139 	return_VOID;
140     }
141     acpi_timer_dev = dev;
142 
143     switch (AcpiGbl_FADT.XPmTimerBlock.SpaceId) {
144     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
145 	rtype = SYS_RES_MEMORY;
146 	break;
147     case ACPI_ADR_SPACE_SYSTEM_IO:
148 	rtype = SYS_RES_IOPORT;
149 	break;
150     default:
151 	return_VOID;
152     }
153     rid = 0;
154     rlen = AcpiGbl_FADT.PmTimerLength;
155     rstart = AcpiGbl_FADT.XPmTimerBlock.Address;
156     if (bus_set_resource(dev, rtype, rid, rstart, rlen))
157 	device_printf(dev, "couldn't set resource (%s 0x%jx+0x%jx)\n",
158 	    (rtype == SYS_RES_IOPORT) ? "port" : "mem", rstart, rlen);
159     return_VOID;
160 }
161 
162 static int
163 acpi_timer_probe(device_t dev)
164 {
165     char desc[40];
166     int i, j, rid, rtype;
167 
168     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
169 
170     if (dev != acpi_timer_dev)
171 	return (ENXIO);
172 
173     switch (AcpiGbl_FADT.XPmTimerBlock.SpaceId) {
174     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
175 	rtype = SYS_RES_MEMORY;
176 	break;
177     case ACPI_ADR_SPACE_SYSTEM_IO:
178 	rtype = SYS_RES_IOPORT;
179 	break;
180     default:
181 	return (ENXIO);
182     }
183     rid = 0;
184     acpi_timer_reg = bus_alloc_resource_any(dev, rtype, &rid, RF_ACTIVE);
185     if (acpi_timer_reg == NULL) {
186 	device_printf(dev, "couldn't allocate resource (%s 0x%lx)\n",
187 	    (rtype == SYS_RES_IOPORT) ? "port" : "mem",
188 	    (u_long)AcpiGbl_FADT.XPmTimerBlock.Address);
189 	return (ENXIO);
190     }
191     acpi_timer_bsh = rman_get_bushandle(acpi_timer_reg);
192     acpi_timer_bst = rman_get_bustag(acpi_timer_reg);
193     if (AcpiGbl_FADT.Flags & ACPI_FADT_32BIT_TIMER)
194 	acpi_timer_timecounter.tc_counter_mask = 0xffffffff;
195     else
196 	acpi_timer_timecounter.tc_counter_mask = 0x00ffffff;
197     acpi_timer_timecounter.tc_frequency = acpi_timer_frequency;
198     acpi_timer_timecounter.tc_flags = TC_FLAGS_SUSPEND_SAFE;
199     if (testenv("debug.acpi.timer_test"))
200 	acpi_timer_boot_test();
201 
202     /*
203      * If all tests of the counter succeed, use the ACPI-fast method.  If
204      * at least one failed, default to using the safe routine, which reads
205      * the timer multiple times to get a consistent value before returning.
206      */
207     j = 0;
208     if (bootverbose)
209 	printf("ACPI timer:");
210     for (i = 0; i < 10; i++)
211 	j += acpi_timer_test();
212     if (bootverbose)
213 	printf(" -> %d\n", j);
214     if (j == 10) {
215 	acpi_timer_timecounter.tc_name = "ACPI-fast";
216 	acpi_timer_timecounter.tc_get_timecount = acpi_timer_get_timecount;
217 	acpi_timer_timecounter.tc_quality = 900;
218     } else {
219 	acpi_timer_timecounter.tc_name = "ACPI-safe";
220 	acpi_timer_timecounter.tc_get_timecount = acpi_timer_get_timecount_safe;
221 	acpi_timer_timecounter.tc_quality = 850;
222     }
223     tc_init(&acpi_timer_timecounter);
224 
225     sprintf(desc, "%d-bit timer at %u.%06uMHz",
226 	(AcpiGbl_FADT.Flags & ACPI_FADT_32BIT_TIMER) != 0 ? 32 : 24,
227 	acpi_timer_frequency / 1000000, acpi_timer_frequency % 1000000);
228     device_set_desc_copy(dev, desc);
229 
230     /* Release the resource, we'll allocate it again during attach. */
231     bus_release_resource(dev, rtype, rid, acpi_timer_reg);
232     return (0);
233 }
234 
235 static int
236 acpi_timer_attach(device_t dev)
237 {
238     int rid, rtype;
239 
240     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
241 
242     switch (AcpiGbl_FADT.XPmTimerBlock.SpaceId) {
243     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
244 	rtype = SYS_RES_MEMORY;
245 	break;
246     case ACPI_ADR_SPACE_SYSTEM_IO:
247 	rtype = SYS_RES_IOPORT;
248 	break;
249     default:
250 	return (ENXIO);
251     }
252     rid = 0;
253     acpi_timer_reg = bus_alloc_resource_any(dev, rtype, &rid, RF_ACTIVE);
254     if (acpi_timer_reg == NULL)
255 	return (ENXIO);
256     acpi_timer_bsh = rman_get_bushandle(acpi_timer_reg);
257     acpi_timer_bst = rman_get_bustag(acpi_timer_reg);
258 
259     /* Register suspend event handler. */
260     if (EVENTHANDLER_REGISTER(power_suspend, acpi_timer_suspend_handler,
261 	&acpi_timer_timecounter, EVENTHANDLER_PRI_LAST) == NULL)
262 	device_printf(dev, "failed to register suspend event handler\n");
263 
264     return (0);
265 }
266 
267 static void
268 acpi_timer_resume_handler(struct timecounter *newtc)
269 {
270 	struct timecounter *tc;
271 
272 	tc = timecounter;
273 	if (tc != newtc) {
274 		if (bootverbose)
275 			device_printf(acpi_timer_dev,
276 			    "restoring timecounter, %s -> %s\n",
277 			    tc->tc_name, newtc->tc_name);
278 		(void)newtc->tc_get_timecount(newtc);
279 		timecounter = newtc;
280 	}
281 }
282 
283 static void
284 acpi_timer_suspend_handler(struct timecounter *newtc)
285 {
286 	struct timecounter *tc;
287 
288 	/* Deregister existing resume event handler. */
289 	if (acpi_timer_eh != NULL) {
290 		EVENTHANDLER_DEREGISTER(power_resume, acpi_timer_eh);
291 		acpi_timer_eh = NULL;
292 	}
293 
294 	if ((timecounter->tc_flags & TC_FLAGS_SUSPEND_SAFE) != 0) {
295 		/*
296 		 * If we are using a suspend safe timecounter, don't
297 		 * save/restore it across suspend/resume.
298 		 */
299 		return;
300 	}
301 
302 	KASSERT(newtc == &acpi_timer_timecounter,
303 	    ("acpi_timer_suspend_handler: wrong timecounter"));
304 
305 	tc = timecounter;
306 	if (tc != newtc) {
307 		if (bootverbose)
308 			device_printf(acpi_timer_dev,
309 			    "switching timecounter, %s -> %s\n",
310 			    tc->tc_name, newtc->tc_name);
311 		(void)acpi_timer_read();
312 		(void)acpi_timer_read();
313 		timecounter = newtc;
314 		acpi_timer_eh = EVENTHANDLER_REGISTER(power_resume,
315 		    acpi_timer_resume_handler, tc, EVENTHANDLER_PRI_LAST);
316 	}
317 }
318 
319 /*
320  * Fetch current time value from reliable hardware.
321  */
322 static u_int
323 acpi_timer_get_timecount(struct timecounter *tc)
324 {
325     return (acpi_timer_read());
326 }
327 
328 /*
329  * Fetch current time value from hardware that may not correctly
330  * latch the counter.  We need to read until we have three monotonic
331  * samples and then use the middle one, otherwise we are not protected
332  * against the fact that the bits can be wrong in two directions.  If
333  * we only cared about monosity, two reads would be enough.
334  */
335 static u_int
336 acpi_timer_get_timecount_safe(struct timecounter *tc)
337 {
338     u_int u1, u2, u3;
339 
340     u2 = acpi_timer_read();
341     u3 = acpi_timer_read();
342     do {
343 	u1 = u2;
344 	u2 = u3;
345 	u3 = acpi_timer_read();
346     } while (u1 > u2 || u2 > u3);
347 
348     return (u2);
349 }
350 
351 /*
352  * Timecounter freqency adjustment interface.
353  */
354 static int
355 acpi_timer_sysctl_freq(SYSCTL_HANDLER_ARGS)
356 {
357     int error;
358     u_int freq;
359 
360     if (acpi_timer_timecounter.tc_frequency == 0)
361 	return (EOPNOTSUPP);
362     freq = acpi_timer_frequency;
363     error = sysctl_handle_int(oidp, &freq, 0, req);
364     if (error == 0 && req->newptr != NULL) {
365 	acpi_timer_frequency = freq;
366 	acpi_timer_timecounter.tc_frequency = acpi_timer_frequency;
367     }
368 
369     return (error);
370 }
371 
372 SYSCTL_PROC(_machdep, OID_AUTO, acpi_timer_freq,
373     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
374     acpi_timer_sysctl_freq, "I",
375     "ACPI timer frequency");
376 
377 /*
378  * Some ACPI timers are known or believed to suffer from implementation
379  * problems which can lead to erroneous values being read.  This function
380  * tests for consistent results from the timer and returns 1 if it believes
381  * the timer is consistent, otherwise it returns 0.
382  *
383  * It appears the cause is that the counter is not latched to the PCI bus
384  * clock when read:
385  *
386  * ] 20. ACPI Timer Errata
387  * ]
388  * ]   Problem: The power management timer may return improper result when
389  * ]   read. Although the timer value settles properly after incrementing,
390  * ]   while incrementing there is a 3nS window every 69.8nS where the
391  * ]   timer value is indeterminate (a 4.2% chance that the data will be
392  * ]   incorrect when read). As a result, the ACPI free running count up
393  * ]   timer specification is violated due to erroneous reads.  Implication:
394  * ]   System hangs due to the "inaccuracy" of the timer when used by
395  * ]   software for time critical events and delays.
396  * ]
397  * ] Workaround: Read the register twice and compare.
398  * ] Status: This will not be fixed in the PIIX4 or PIIX4E, it is fixed
399  * ] in the PIIX4M.
400  */
401 #define N 2000
402 static int
403 acpi_timer_test()
404 {
405     uint32_t last, this;
406     int delta, max, max2, min, n;
407     register_t s;
408 
409     /* Skip the test based on the hw.acpi.timer_test_enabled tunable. */
410     if (!acpi_timer_test_enabled)
411 	return (1);
412 
413     TSENTER();
414 
415     min = INT32_MAX;
416     max = max2 = 0;
417 
418     /* Test the timer with interrupts disabled to get accurate results. */
419     s = intr_disable();
420     last = acpi_timer_read();
421     for (n = 0; n < N; n++) {
422 	this = acpi_timer_read();
423 	delta = acpi_TimerDelta(this, last);
424 	if (delta > max) {
425 	    max2 = max;
426 	    max = delta;
427 	} else if (delta > max2)
428 	    max2 = delta;
429 	if (delta < min)
430 	    min = delta;
431 	last = this;
432     }
433     intr_restore(s);
434 
435     delta = max2 - min;
436     if ((max - min > 8 || delta > 3) && vm_guest == VM_GUEST_NO)
437 	n = 0;
438     else if (min < 0 || max == 0 || max2 == 0)
439 	n = 0;
440     else
441 	n = 1;
442     if (bootverbose)
443 	printf(" %d/%d", n, delta);
444 
445     TSEXIT();
446 
447     return (n);
448 }
449 #undef N
450 
451 /*
452  * Test harness for verifying ACPI timer behaviour.
453  * Boot with debug.acpi.timer_test set to invoke this.
454  */
455 static void
456 acpi_timer_boot_test(void)
457 {
458     uint32_t u1, u2, u3;
459 
460     u1 = acpi_timer_read();
461     u2 = acpi_timer_read();
462     u3 = acpi_timer_read();
463 
464     device_printf(acpi_timer_dev, "timer test in progress, reboot to quit.\n");
465     for (;;) {
466 	/*
467 	 * The failure case is where u3 > u1, but u2 does not fall between
468 	 * the two, ie. it contains garbage.
469 	 */
470 	if (u3 > u1) {
471 	    if (u2 < u1 || u2 > u3)
472 		device_printf(acpi_timer_dev,
473 			      "timer is not monotonic: 0x%08x,0x%08x,0x%08x\n",
474 			      u1, u2, u3);
475 	}
476 	u1 = u2;
477 	u2 = u3;
478 	u3 = acpi_timer_read();
479     }
480 }
481