xref: /freebsd/sys/dev/acpica/acpi_timer.c (revision 3c4ba5f55438f7afd4f4b0b56f88f2bb505fd6a6)
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 DRIVER_MODULE(acpi_timer, acpi, acpi_timer_driver, 0, 0);
100 MODULE_DEPEND(acpi_timer, acpi, 1, 1, 1);
101 
102 static struct timecounter acpi_timer_timecounter = {
103 	acpi_timer_get_timecount_safe,	/* get_timecount function */
104 	0,				/* no poll_pps */
105 	0,				/* no default counter_mask */
106 	0,				/* no default frequency */
107 	"ACPI",				/* name */
108 	-1				/* quality (chosen later) */
109 };
110 
111 static __inline uint32_t
112 acpi_timer_read(void)
113 {
114 
115     return (bus_space_read_4(acpi_timer_bst, acpi_timer_bsh, 0));
116 }
117 
118 /*
119  * Locate the ACPI timer using the FADT, set up and allocate the I/O resources
120  * we will be using.
121  */
122 static void
123 acpi_timer_identify(driver_t *driver, device_t parent)
124 {
125     device_t dev;
126     rman_res_t rlen, rstart;
127     int rid, rtype;
128 
129     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
130 
131     if (acpi_disabled("timer") || (acpi_quirks & ACPI_Q_TIMER) ||
132 	acpi_timer_dev || acpi_timer_disabled ||
133 	AcpiGbl_FADT.PmTimerLength == 0)
134 	return_VOID;
135 
136     if ((dev = BUS_ADD_CHILD(parent, 2, "acpi_timer", 0)) == NULL) {
137 	device_printf(parent, "could not add acpi_timer0\n");
138 	return_VOID;
139     }
140     acpi_timer_dev = dev;
141 
142     switch (AcpiGbl_FADT.XPmTimerBlock.SpaceId) {
143     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
144 	rtype = SYS_RES_MEMORY;
145 	break;
146     case ACPI_ADR_SPACE_SYSTEM_IO:
147 	rtype = SYS_RES_IOPORT;
148 	break;
149     default:
150 	return_VOID;
151     }
152     rid = 0;
153     rlen = AcpiGbl_FADT.PmTimerLength;
154     rstart = AcpiGbl_FADT.XPmTimerBlock.Address;
155     if (bus_set_resource(dev, rtype, rid, rstart, rlen))
156 	device_printf(dev, "couldn't set resource (%s 0x%jx+0x%jx)\n",
157 	    (rtype == SYS_RES_IOPORT) ? "port" : "mem", rstart, rlen);
158     return_VOID;
159 }
160 
161 static int
162 acpi_timer_probe(device_t dev)
163 {
164     char desc[40];
165     int i, j, rid, rtype;
166 
167     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
168 
169     if (dev != acpi_timer_dev)
170 	return (ENXIO);
171 
172     switch (AcpiGbl_FADT.XPmTimerBlock.SpaceId) {
173     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
174 	rtype = SYS_RES_MEMORY;
175 	break;
176     case ACPI_ADR_SPACE_SYSTEM_IO:
177 	rtype = SYS_RES_IOPORT;
178 	break;
179     default:
180 	return (ENXIO);
181     }
182     rid = 0;
183     acpi_timer_reg = bus_alloc_resource_any(dev, rtype, &rid, RF_ACTIVE);
184     if (acpi_timer_reg == NULL) {
185 	device_printf(dev, "couldn't allocate resource (%s 0x%lx)\n",
186 	    (rtype == SYS_RES_IOPORT) ? "port" : "mem",
187 	    (u_long)AcpiGbl_FADT.XPmTimerBlock.Address);
188 	return (ENXIO);
189     }
190     acpi_timer_bsh = rman_get_bushandle(acpi_timer_reg);
191     acpi_timer_bst = rman_get_bustag(acpi_timer_reg);
192     if (AcpiGbl_FADT.Flags & ACPI_FADT_32BIT_TIMER)
193 	acpi_timer_timecounter.tc_counter_mask = 0xffffffff;
194     else
195 	acpi_timer_timecounter.tc_counter_mask = 0x00ffffff;
196     acpi_timer_timecounter.tc_frequency = acpi_timer_frequency;
197     acpi_timer_timecounter.tc_flags = TC_FLAGS_SUSPEND_SAFE;
198     if (testenv("debug.acpi.timer_test"))
199 	acpi_timer_boot_test();
200 
201     /*
202      * If all tests of the counter succeed, use the ACPI-fast method.  If
203      * at least one failed, default to using the safe routine, which reads
204      * the timer multiple times to get a consistent value before returning.
205      */
206     j = 0;
207     if (bootverbose)
208 	printf("ACPI timer:");
209     for (i = 0; i < 10; i++)
210 	j += acpi_timer_test();
211     if (bootverbose)
212 	printf(" -> %d\n", j);
213     if (j == 10) {
214 	acpi_timer_timecounter.tc_name = "ACPI-fast";
215 	acpi_timer_timecounter.tc_get_timecount = acpi_timer_get_timecount;
216 	acpi_timer_timecounter.tc_quality = 900;
217     } else {
218 	acpi_timer_timecounter.tc_name = "ACPI-safe";
219 	acpi_timer_timecounter.tc_get_timecount = acpi_timer_get_timecount_safe;
220 	acpi_timer_timecounter.tc_quality = 850;
221     }
222     tc_init(&acpi_timer_timecounter);
223 
224     sprintf(desc, "%d-bit timer at %u.%06uMHz",
225 	(AcpiGbl_FADT.Flags & ACPI_FADT_32BIT_TIMER) != 0 ? 32 : 24,
226 	acpi_timer_frequency / 1000000, acpi_timer_frequency % 1000000);
227     device_set_desc_copy(dev, desc);
228 
229     /* Release the resource, we'll allocate it again during attach. */
230     bus_release_resource(dev, rtype, rid, acpi_timer_reg);
231     return (0);
232 }
233 
234 static int
235 acpi_timer_attach(device_t dev)
236 {
237     int rid, rtype;
238 
239     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
240 
241     switch (AcpiGbl_FADT.XPmTimerBlock.SpaceId) {
242     case ACPI_ADR_SPACE_SYSTEM_MEMORY:
243 	rtype = SYS_RES_MEMORY;
244 	break;
245     case ACPI_ADR_SPACE_SYSTEM_IO:
246 	rtype = SYS_RES_IOPORT;
247 	break;
248     default:
249 	return (ENXIO);
250     }
251     rid = 0;
252     acpi_timer_reg = bus_alloc_resource_any(dev, rtype, &rid, RF_ACTIVE);
253     if (acpi_timer_reg == NULL)
254 	return (ENXIO);
255     acpi_timer_bsh = rman_get_bushandle(acpi_timer_reg);
256     acpi_timer_bst = rman_get_bustag(acpi_timer_reg);
257 
258     /* Register suspend event handler. */
259     if (EVENTHANDLER_REGISTER(power_suspend, acpi_timer_suspend_handler,
260 	&acpi_timer_timecounter, EVENTHANDLER_PRI_LAST) == NULL)
261 	device_printf(dev, "failed to register suspend event handler\n");
262 
263     return (0);
264 }
265 
266 static void
267 acpi_timer_resume_handler(struct timecounter *newtc)
268 {
269 	struct timecounter *tc;
270 
271 	tc = timecounter;
272 	if (tc != newtc) {
273 		if (bootverbose)
274 			device_printf(acpi_timer_dev,
275 			    "restoring timecounter, %s -> %s\n",
276 			    tc->tc_name, newtc->tc_name);
277 		(void)newtc->tc_get_timecount(newtc);
278 		timecounter = newtc;
279 	}
280 }
281 
282 static void
283 acpi_timer_suspend_handler(struct timecounter *newtc)
284 {
285 	struct timecounter *tc;
286 
287 	/* Deregister existing resume event handler. */
288 	if (acpi_timer_eh != NULL) {
289 		EVENTHANDLER_DEREGISTER(power_resume, acpi_timer_eh);
290 		acpi_timer_eh = NULL;
291 	}
292 
293 	if ((timecounter->tc_flags & TC_FLAGS_SUSPEND_SAFE) != 0) {
294 		/*
295 		 * If we are using a suspend safe timecounter, don't
296 		 * save/restore it across suspend/resume.
297 		 */
298 		return;
299 	}
300 
301 	KASSERT(newtc == &acpi_timer_timecounter,
302 	    ("acpi_timer_suspend_handler: wrong timecounter"));
303 
304 	tc = timecounter;
305 	if (tc != newtc) {
306 		if (bootverbose)
307 			device_printf(acpi_timer_dev,
308 			    "switching timecounter, %s -> %s\n",
309 			    tc->tc_name, newtc->tc_name);
310 		(void)acpi_timer_read();
311 		(void)acpi_timer_read();
312 		timecounter = newtc;
313 		acpi_timer_eh = EVENTHANDLER_REGISTER(power_resume,
314 		    acpi_timer_resume_handler, tc, EVENTHANDLER_PRI_LAST);
315 	}
316 }
317 
318 /*
319  * Fetch current time value from reliable hardware.
320  */
321 static u_int
322 acpi_timer_get_timecount(struct timecounter *tc)
323 {
324     return (acpi_timer_read());
325 }
326 
327 /*
328  * Fetch current time value from hardware that may not correctly
329  * latch the counter.  We need to read until we have three monotonic
330  * samples and then use the middle one, otherwise we are not protected
331  * against the fact that the bits can be wrong in two directions.  If
332  * we only cared about monosity, two reads would be enough.
333  */
334 static u_int
335 acpi_timer_get_timecount_safe(struct timecounter *tc)
336 {
337     u_int u1, u2, u3;
338 
339     u2 = acpi_timer_read();
340     u3 = acpi_timer_read();
341     do {
342 	u1 = u2;
343 	u2 = u3;
344 	u3 = acpi_timer_read();
345     } while (u1 > u2 || u2 > u3);
346 
347     return (u2);
348 }
349 
350 /*
351  * Timecounter freqency adjustment interface.
352  */
353 static int
354 acpi_timer_sysctl_freq(SYSCTL_HANDLER_ARGS)
355 {
356     int error;
357     u_int freq;
358 
359     if (acpi_timer_timecounter.tc_frequency == 0)
360 	return (EOPNOTSUPP);
361     freq = acpi_timer_frequency;
362     error = sysctl_handle_int(oidp, &freq, 0, req);
363     if (error == 0 && req->newptr != NULL) {
364 	acpi_timer_frequency = freq;
365 	acpi_timer_timecounter.tc_frequency = acpi_timer_frequency;
366     }
367 
368     return (error);
369 }
370 
371 SYSCTL_PROC(_machdep, OID_AUTO, acpi_timer_freq,
372     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
373     acpi_timer_sysctl_freq, "I",
374     "ACPI timer frequency");
375 
376 /*
377  * Some ACPI timers are known or believed to suffer from implementation
378  * problems which can lead to erroneous values being read.  This function
379  * tests for consistent results from the timer and returns 1 if it believes
380  * the timer is consistent, otherwise it returns 0.
381  *
382  * It appears the cause is that the counter is not latched to the PCI bus
383  * clock when read:
384  *
385  * ] 20. ACPI Timer Errata
386  * ]
387  * ]   Problem: The power management timer may return improper result when
388  * ]   read. Although the timer value settles properly after incrementing,
389  * ]   while incrementing there is a 3nS window every 69.8nS where the
390  * ]   timer value is indeterminate (a 4.2% chance that the data will be
391  * ]   incorrect when read). As a result, the ACPI free running count up
392  * ]   timer specification is violated due to erroneous reads.  Implication:
393  * ]   System hangs due to the "inaccuracy" of the timer when used by
394  * ]   software for time critical events and delays.
395  * ]
396  * ] Workaround: Read the register twice and compare.
397  * ] Status: This will not be fixed in the PIIX4 or PIIX4E, it is fixed
398  * ] in the PIIX4M.
399  */
400 #define N 2000
401 static int
402 acpi_timer_test(void)
403 {
404     uint32_t last, this;
405     int delta, max, max2, min, n;
406     register_t s;
407 
408     /* Skip the test based on the hw.acpi.timer_test_enabled tunable. */
409     if (!acpi_timer_test_enabled)
410 	return (1);
411 
412     TSENTER();
413 
414     min = INT32_MAX;
415     max = max2 = 0;
416 
417     /* Test the timer with interrupts disabled to get accurate results. */
418     s = intr_disable();
419     last = acpi_timer_read();
420     for (n = 0; n < N; n++) {
421 	this = acpi_timer_read();
422 	delta = acpi_TimerDelta(this, last);
423 	if (delta > max) {
424 	    max2 = max;
425 	    max = delta;
426 	} else if (delta > max2)
427 	    max2 = delta;
428 	if (delta < min)
429 	    min = delta;
430 	last = this;
431     }
432     intr_restore(s);
433 
434     delta = max2 - min;
435     if ((max - min > 8 || delta > 3) && vm_guest == VM_GUEST_NO)
436 	n = 0;
437     else if (min < 0 || max == 0 || max2 == 0)
438 	n = 0;
439     else
440 	n = 1;
441     if (bootverbose)
442 	printf(" %d/%d", n, delta);
443 
444     TSEXIT();
445 
446     return (n);
447 }
448 #undef N
449 
450 /*
451  * Test harness for verifying ACPI timer behaviour.
452  * Boot with debug.acpi.timer_test set to invoke this.
453  */
454 static void
455 acpi_timer_boot_test(void)
456 {
457     uint32_t u1, u2, u3;
458 
459     u1 = acpi_timer_read();
460     u2 = acpi_timer_read();
461     u3 = acpi_timer_read();
462 
463     device_printf(acpi_timer_dev, "timer test in progress, reboot to quit.\n");
464     for (;;) {
465 	/*
466 	 * The failure case is where u3 > u1, but u2 does not fall between
467 	 * the two, ie. it contains garbage.
468 	 */
469 	if (u3 > u1) {
470 	    if (u2 < u1 || u2 > u3)
471 		device_printf(acpi_timer_dev,
472 			      "timer is not monotonic: 0x%08x,0x%08x,0x%08x\n",
473 			      u1, u2, u3);
474 	}
475 	u1 = u2;
476 	u2 = u3;
477 	u3 = acpi_timer_read();
478     }
479 }
480