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