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