xref: /freebsd/sys/dev/acpica/acpi_hpet.c (revision 3eeb75112272ef9ef244a00bc73beef3a146856a)
1 /*-
2  * Copyright (c) 2005 Poul-Henning Kamp
3  * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
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 
33 #if defined(__amd64__)
34 #define	DEV_APIC
35 #else
36 #include "opt_apic.h"
37 #endif
38 #include <sys/param.h>
39 #include <sys/conf.h>
40 #include <sys/bus.h>
41 #include <sys/kernel.h>
42 #include <sys/module.h>
43 #include <sys/proc.h>
44 #include <sys/rman.h>
45 #include <sys/mman.h>
46 #include <sys/time.h>
47 #include <sys/smp.h>
48 #include <sys/sysctl.h>
49 #include <sys/timeet.h>
50 #include <sys/timetc.h>
51 #include <sys/vdso.h>
52 
53 #include <contrib/dev/acpica/include/acpi.h>
54 #include <contrib/dev/acpica/include/accommon.h>
55 
56 #include <dev/acpica/acpivar.h>
57 #include <dev/acpica/acpi_hpet.h>
58 
59 #ifdef DEV_APIC
60 #include "pcib_if.h"
61 #endif
62 
63 #define HPET_VENDID_AMD		0x4353
64 #define HPET_VENDID_AMD2	0x1022
65 #define HPET_VENDID_INTEL	0x8086
66 #define HPET_VENDID_NVIDIA	0x10de
67 #define HPET_VENDID_SW		0x1166
68 
69 ACPI_SERIAL_DECL(hpet, "ACPI HPET support");
70 
71 static devclass_t hpet_devclass;
72 
73 /* ACPI CA debugging */
74 #define _COMPONENT	ACPI_TIMER
75 ACPI_MODULE_NAME("HPET")
76 
77 struct hpet_softc {
78 	device_t		dev;
79 	int			mem_rid;
80 	int			intr_rid;
81 	int			irq;
82 	int			useirq;
83 	int			legacy_route;
84 	int			per_cpu;
85 	uint32_t		allowed_irqs;
86 	struct resource		*mem_res;
87 	struct resource		*intr_res;
88 	void			*intr_handle;
89 	ACPI_HANDLE		handle;
90 	uint32_t		acpi_uid;
91 	uint64_t		freq;
92 	uint32_t		caps;
93 	struct timecounter	tc;
94 	struct hpet_timer {
95 		struct eventtimer	et;
96 		struct hpet_softc	*sc;
97 		int			num;
98 		int			mode;
99 		int			intr_rid;
100 		int			irq;
101 		int			pcpu_cpu;
102 		int			pcpu_misrouted;
103 		int			pcpu_master;
104 		int			pcpu_slaves[MAXCPU];
105 		struct resource		*intr_res;
106 		void			*intr_handle;
107 		uint32_t		caps;
108 		uint32_t		vectors;
109 		uint32_t		div;
110 		uint32_t		next;
111 		char			name[8];
112 	} 			t[32];
113 	int			num_timers;
114 	struct cdev		*pdev;
115 	int			mmap_allow;
116 	int			mmap_allow_write;
117 };
118 
119 static d_open_t hpet_open;
120 static d_mmap_t hpet_mmap;
121 
122 static struct cdevsw hpet_cdevsw = {
123 	.d_version =	D_VERSION,
124 	.d_name =	"hpet",
125 	.d_open =	hpet_open,
126 	.d_mmap =	hpet_mmap,
127 };
128 
129 static u_int hpet_get_timecount(struct timecounter *tc);
130 static void hpet_test(struct hpet_softc *sc);
131 
132 static char *hpet_ids[] = { "PNP0103", NULL };
133 
134 /* Knob to disable acpi_hpet device */
135 bool acpi_hpet_disabled = false;
136 
137 static u_int
138 hpet_get_timecount(struct timecounter *tc)
139 {
140 	struct hpet_softc *sc;
141 
142 	sc = tc->tc_priv;
143 	return (bus_read_4(sc->mem_res, HPET_MAIN_COUNTER));
144 }
145 
146 uint32_t
147 hpet_vdso_timehands(struct vdso_timehands *vdso_th, struct timecounter *tc)
148 {
149 	struct hpet_softc *sc;
150 
151 	sc = tc->tc_priv;
152 	vdso_th->th_algo = VDSO_TH_ALGO_X86_HPET;
153 	vdso_th->th_x86_shift = 0;
154 	vdso_th->th_x86_hpet_idx = device_get_unit(sc->dev);
155 	bzero(vdso_th->th_res, sizeof(vdso_th->th_res));
156 	return (sc->mmap_allow != 0);
157 }
158 
159 #ifdef COMPAT_FREEBSD32
160 uint32_t
161 hpet_vdso_timehands32(struct vdso_timehands32 *vdso_th32,
162     struct timecounter *tc)
163 {
164 	struct hpet_softc *sc;
165 
166 	sc = tc->tc_priv;
167 	vdso_th32->th_algo = VDSO_TH_ALGO_X86_HPET;
168 	vdso_th32->th_x86_shift = 0;
169 	vdso_th32->th_x86_hpet_idx = device_get_unit(sc->dev);
170 	bzero(vdso_th32->th_res, sizeof(vdso_th32->th_res));
171 	return (sc->mmap_allow != 0);
172 }
173 #endif
174 
175 static void
176 hpet_enable(struct hpet_softc *sc)
177 {
178 	uint32_t val;
179 
180 	val = bus_read_4(sc->mem_res, HPET_CONFIG);
181 	if (sc->legacy_route)
182 		val |= HPET_CNF_LEG_RT;
183 	else
184 		val &= ~HPET_CNF_LEG_RT;
185 	val |= HPET_CNF_ENABLE;
186 	bus_write_4(sc->mem_res, HPET_CONFIG, val);
187 }
188 
189 static void
190 hpet_disable(struct hpet_softc *sc)
191 {
192 	uint32_t val;
193 
194 	val = bus_read_4(sc->mem_res, HPET_CONFIG);
195 	val &= ~HPET_CNF_ENABLE;
196 	bus_write_4(sc->mem_res, HPET_CONFIG, val);
197 }
198 
199 static int
200 hpet_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
201 {
202 	struct hpet_timer *mt = (struct hpet_timer *)et->et_priv;
203 	struct hpet_timer *t;
204 	struct hpet_softc *sc = mt->sc;
205 	uint32_t fdiv, now;
206 
207 	t = (mt->pcpu_master < 0) ? mt : &sc->t[mt->pcpu_slaves[curcpu]];
208 	if (period != 0) {
209 		t->mode = 1;
210 		t->div = (sc->freq * period) >> 32;
211 	} else {
212 		t->mode = 2;
213 		t->div = 0;
214 	}
215 	if (first != 0)
216 		fdiv = (sc->freq * first) >> 32;
217 	else
218 		fdiv = t->div;
219 	if (t->irq < 0)
220 		bus_write_4(sc->mem_res, HPET_ISR, 1 << t->num);
221 	t->caps |= HPET_TCNF_INT_ENB;
222 	now = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
223 restart:
224 	t->next = now + fdiv;
225 	if (t->mode == 1 && (t->caps & HPET_TCAP_PER_INT)) {
226 		t->caps |= HPET_TCNF_TYPE;
227 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num),
228 		    t->caps | HPET_TCNF_VAL_SET);
229 		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
230 		    t->next);
231 		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
232 		    t->div);
233 	} else {
234 		t->caps &= ~HPET_TCNF_TYPE;
235 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num),
236 		    t->caps);
237 		bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
238 		    t->next);
239 	}
240 	now = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
241 	if ((int32_t)(now - t->next + HPET_MIN_CYCLES) >= 0) {
242 		fdiv *= 2;
243 		goto restart;
244 	}
245 	return (0);
246 }
247 
248 static int
249 hpet_stop(struct eventtimer *et)
250 {
251 	struct hpet_timer *mt = (struct hpet_timer *)et->et_priv;
252 	struct hpet_timer *t;
253 	struct hpet_softc *sc = mt->sc;
254 
255 	t = (mt->pcpu_master < 0) ? mt : &sc->t[mt->pcpu_slaves[curcpu]];
256 	t->mode = 0;
257 	t->caps &= ~(HPET_TCNF_INT_ENB | HPET_TCNF_TYPE);
258 	bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num), t->caps);
259 	return (0);
260 }
261 
262 static int
263 hpet_intr_single(void *arg)
264 {
265 	struct hpet_timer *t = (struct hpet_timer *)arg;
266 	struct hpet_timer *mt;
267 	struct hpet_softc *sc = t->sc;
268 	uint32_t now;
269 
270 	if (t->mode == 0)
271 		return (FILTER_STRAY);
272 	/* Check that per-CPU timer interrupt reached right CPU. */
273 	if (t->pcpu_cpu >= 0 && t->pcpu_cpu != curcpu) {
274 		if ((++t->pcpu_misrouted) % 32 == 0) {
275 			printf("HPET interrupt routed to the wrong CPU"
276 			    " (timer %d CPU %d -> %d)!\n",
277 			    t->num, t->pcpu_cpu, curcpu);
278 		}
279 
280 		/*
281 		 * Reload timer, hoping that next time may be more lucky
282 		 * (system will manage proper interrupt binding).
283 		 */
284 		if ((t->mode == 1 && (t->caps & HPET_TCAP_PER_INT) == 0) ||
285 		    t->mode == 2) {
286 			t->next = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER) +
287 			    sc->freq / 8;
288 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
289 			    t->next);
290 		}
291 		return (FILTER_HANDLED);
292 	}
293 	if (t->mode == 1 &&
294 	    (t->caps & HPET_TCAP_PER_INT) == 0) {
295 		t->next += t->div;
296 		now = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
297 		if ((int32_t)((now + t->div / 2) - t->next) > 0)
298 			t->next = now + t->div / 2;
299 		bus_write_4(sc->mem_res,
300 		    HPET_TIMER_COMPARATOR(t->num), t->next);
301 	} else if (t->mode == 2)
302 		t->mode = 0;
303 	mt = (t->pcpu_master < 0) ? t : &sc->t[t->pcpu_master];
304 	if (mt->et.et_active)
305 		mt->et.et_event_cb(&mt->et, mt->et.et_arg);
306 	return (FILTER_HANDLED);
307 }
308 
309 static int
310 hpet_intr(void *arg)
311 {
312 	struct hpet_softc *sc = (struct hpet_softc *)arg;
313 	int i;
314 	uint32_t val;
315 
316 	val = bus_read_4(sc->mem_res, HPET_ISR);
317 	if (val) {
318 		bus_write_4(sc->mem_res, HPET_ISR, val);
319 		val &= sc->useirq;
320 		for (i = 0; i < sc->num_timers; i++) {
321 			if ((val & (1 << i)) == 0)
322 				continue;
323 			hpet_intr_single(&sc->t[i]);
324 		}
325 		return (FILTER_HANDLED);
326 	}
327 	return (FILTER_STRAY);
328 }
329 
330 uint32_t
331 hpet_get_uid(device_t dev)
332 {
333 	struct hpet_softc *sc;
334 
335 	sc = device_get_softc(dev);
336 	return (sc->acpi_uid);
337 }
338 
339 static ACPI_STATUS
340 hpet_find(ACPI_HANDLE handle, UINT32 level, void *context,
341     void **status)
342 {
343 	char 		**ids;
344 	uint32_t	id = (uint32_t)(uintptr_t)context;
345 	uint32_t	uid = 0;
346 
347 	for (ids = hpet_ids; *ids != NULL; ids++) {
348 		if (acpi_MatchHid(handle, *ids))
349 		        break;
350 	}
351 	if (*ids == NULL)
352 		return (AE_OK);
353 	if (ACPI_FAILURE(acpi_GetInteger(handle, "_UID", &uid)) ||
354 	    id == uid)
355 		*status = acpi_get_device(handle);
356 	return (AE_OK);
357 }
358 
359 /*
360  * Find an existing IRQ resource that matches the requested IRQ range
361  * and return its RID.  If one is not found, use a new RID.
362  */
363 static int
364 hpet_find_irq_rid(device_t dev, u_long start, u_long end)
365 {
366 	rman_res_t irq;
367 	int error, rid;
368 
369 	for (rid = 0;; rid++) {
370 		error = bus_get_resource(dev, SYS_RES_IRQ, rid, &irq, NULL);
371 		if (error != 0 || (start <= irq && irq <= end))
372 			return (rid);
373 	}
374 }
375 
376 static int
377 hpet_open(struct cdev *cdev, int oflags, int devtype, struct thread *td)
378 {
379 	struct hpet_softc *sc;
380 
381 	sc = cdev->si_drv1;
382 	if (!sc->mmap_allow)
383 		return (EPERM);
384 	else
385 		return (0);
386 }
387 
388 static int
389 hpet_mmap(struct cdev *cdev, vm_ooffset_t offset, vm_paddr_t *paddr,
390     int nprot, vm_memattr_t *memattr)
391 {
392 	struct hpet_softc *sc;
393 
394 	sc = cdev->si_drv1;
395 	if (offset > rman_get_size(sc->mem_res))
396 		return (EINVAL);
397 	if (!sc->mmap_allow_write && (nprot & PROT_WRITE))
398 		return (EPERM);
399 	*paddr = rman_get_start(sc->mem_res) + offset;
400 	*memattr = VM_MEMATTR_UNCACHEABLE;
401 
402 	return (0);
403 }
404 
405 /* Discover the HPET via the ACPI table of the same name. */
406 static void
407 hpet_identify(driver_t *driver, device_t parent)
408 {
409 	ACPI_TABLE_HPET *hpet;
410 	ACPI_STATUS	status;
411 	device_t	child;
412 	int		i;
413 
414 	/* Only one HPET device can be added. */
415 	if (devclass_get_device(hpet_devclass, 0))
416 		return;
417 	for (i = 1; ; i++) {
418 		/* Search for HPET table. */
419 		status = AcpiGetTable(ACPI_SIG_HPET, i, (ACPI_TABLE_HEADER **)&hpet);
420 		if (ACPI_FAILURE(status))
421 			return;
422 		/* Search for HPET device with same ID. */
423 		child = NULL;
424 		AcpiWalkNamespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
425 		    100, hpet_find, NULL, (void *)(uintptr_t)hpet->Sequence,
426 		    (void *)&child);
427 		/* If found - let it be probed in normal way. */
428 		if (child) {
429 			if (bus_get_resource(child, SYS_RES_MEMORY, 0,
430 			    NULL, NULL) != 0)
431 				bus_set_resource(child, SYS_RES_MEMORY, 0,
432 				    hpet->Address.Address, HPET_MEM_WIDTH);
433 			continue;
434 		}
435 		/* If not - create it from table info. */
436 		child = BUS_ADD_CHILD(parent, 2, "hpet", 0);
437 		if (child == NULL) {
438 			printf("%s: can't add child\n", __func__);
439 			continue;
440 		}
441 		bus_set_resource(child, SYS_RES_MEMORY, 0, hpet->Address.Address,
442 		    HPET_MEM_WIDTH);
443 	}
444 }
445 
446 static int
447 hpet_probe(device_t dev)
448 {
449 	ACPI_FUNCTION_TRACE((char *)(uintptr_t) __func__);
450 
451 	if (acpi_disabled("hpet") || acpi_hpet_disabled)
452 		return (ENXIO);
453 	if (acpi_get_handle(dev) != NULL &&
454 	    ACPI_ID_PROBE(device_get_parent(dev), dev, hpet_ids) == NULL)
455 		return (ENXIO);
456 
457 	device_set_desc(dev, "High Precision Event Timer");
458 	return (0);
459 }
460 
461 static int
462 hpet_attach(device_t dev)
463 {
464 	struct hpet_softc *sc;
465 	struct hpet_timer *t;
466 	struct make_dev_args mda;
467 	int i, j, num_msi, num_timers, num_percpu_et, num_percpu_t, cur_cpu;
468 	int pcpu_master, error;
469 	static int maxhpetet = 0;
470 	uint32_t val, val2, cvectors, dvectors;
471 	uint16_t vendor, rev;
472 
473 	ACPI_FUNCTION_TRACE((char *)(uintptr_t) __func__);
474 
475 	sc = device_get_softc(dev);
476 	sc->dev = dev;
477 	sc->handle = acpi_get_handle(dev);
478 
479 	sc->mem_rid = 0;
480 	sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
481 	    RF_ACTIVE);
482 	if (sc->mem_res == NULL)
483 		return (ENOMEM);
484 
485 	/* Validate that we can access the whole region. */
486 	if (rman_get_size(sc->mem_res) < HPET_MEM_WIDTH) {
487 		device_printf(dev, "memory region width %jd too small\n",
488 		    rman_get_size(sc->mem_res));
489 		bus_free_resource(dev, SYS_RES_MEMORY, sc->mem_res);
490 		return (ENXIO);
491 	}
492 
493 	/* Be sure timer is enabled. */
494 	hpet_enable(sc);
495 
496 	/* Read basic statistics about the timer. */
497 	val = bus_read_4(sc->mem_res, HPET_PERIOD);
498 	if (val == 0) {
499 		device_printf(dev, "invalid period\n");
500 		hpet_disable(sc);
501 		bus_free_resource(dev, SYS_RES_MEMORY, sc->mem_res);
502 		return (ENXIO);
503 	}
504 
505 	sc->freq = (1000000000000000LL + val / 2) / val;
506 	sc->caps = bus_read_4(sc->mem_res, HPET_CAPABILITIES);
507 	vendor = (sc->caps & HPET_CAP_VENDOR_ID) >> 16;
508 	rev = sc->caps & HPET_CAP_REV_ID;
509 	num_timers = 1 + ((sc->caps & HPET_CAP_NUM_TIM) >> 8);
510 	/*
511 	 * ATI/AMD violates IA-PC HPET (High Precision Event Timers)
512 	 * Specification and provides an off by one number
513 	 * of timers/comparators.
514 	 * Additionally, they use unregistered value in VENDOR_ID field.
515 	 */
516 	if (vendor == HPET_VENDID_AMD && rev < 0x10 && num_timers > 0)
517 		num_timers--;
518 	sc->num_timers = num_timers;
519 	if (bootverbose) {
520 		device_printf(dev,
521 		    "vendor 0x%x, rev 0x%x, %jdHz%s, %d timers,%s\n",
522 		    vendor, rev, sc->freq,
523 		    (sc->caps & HPET_CAP_COUNT_SIZE) ? " 64bit" : "",
524 		    num_timers,
525 		    (sc->caps & HPET_CAP_LEG_RT) ? " legacy route" : "");
526 	}
527 	for (i = 0; i < num_timers; i++) {
528 		t = &sc->t[i];
529 		t->sc = sc;
530 		t->num = i;
531 		t->mode = 0;
532 		t->intr_rid = -1;
533 		t->irq = -1;
534 		t->pcpu_cpu = -1;
535 		t->pcpu_misrouted = 0;
536 		t->pcpu_master = -1;
537 		t->caps = bus_read_4(sc->mem_res, HPET_TIMER_CAP_CNF(i));
538 		t->vectors = bus_read_4(sc->mem_res, HPET_TIMER_CAP_CNF(i) + 4);
539 		if (bootverbose) {
540 			device_printf(dev,
541 			    " t%d: irqs 0x%08x (%d)%s%s%s\n", i,
542 			    t->vectors, (t->caps & HPET_TCNF_INT_ROUTE) >> 9,
543 			    (t->caps & HPET_TCAP_FSB_INT_DEL) ? ", MSI" : "",
544 			    (t->caps & HPET_TCAP_SIZE) ? ", 64bit" : "",
545 			    (t->caps & HPET_TCAP_PER_INT) ? ", periodic" : "");
546 		}
547 	}
548 	if (testenv("debug.acpi.hpet_test"))
549 		hpet_test(sc);
550 	/*
551 	 * Don't attach if the timer never increments.  Since the spec
552 	 * requires it to be at least 10 MHz, it has to change in 1 us.
553 	 */
554 	val = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
555 	DELAY(1);
556 	val2 = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
557 	if (val == val2) {
558 		device_printf(dev, "HPET never increments, disabling\n");
559 		hpet_disable(sc);
560 		bus_free_resource(dev, SYS_RES_MEMORY, sc->mem_res);
561 		return (ENXIO);
562 	}
563 	/* Announce first HPET as timecounter. */
564 	if (device_get_unit(dev) == 0) {
565 		sc->tc.tc_get_timecount = hpet_get_timecount,
566 		sc->tc.tc_counter_mask = ~0u,
567 		sc->tc.tc_name = "HPET",
568 		sc->tc.tc_quality = 950,
569 		sc->tc.tc_frequency = sc->freq;
570 		sc->tc.tc_priv = sc;
571 		sc->tc.tc_fill_vdso_timehands = hpet_vdso_timehands;
572 #ifdef COMPAT_FREEBSD32
573 		sc->tc.tc_fill_vdso_timehands32 = hpet_vdso_timehands32;
574 #endif
575 		tc_init(&sc->tc);
576 	}
577 	/* If not disabled - setup and announce event timers. */
578 	if (resource_int_value(device_get_name(dev), device_get_unit(dev),
579 	     "clock", &i) == 0 && i == 0)
580 	        return (0);
581 
582 	/* Check whether we can and want legacy routing. */
583 	sc->legacy_route = 0;
584 	resource_int_value(device_get_name(dev), device_get_unit(dev),
585 	     "legacy_route", &sc->legacy_route);
586 	if ((sc->caps & HPET_CAP_LEG_RT) == 0)
587 		sc->legacy_route = 0;
588 	if (sc->legacy_route) {
589 		sc->t[0].vectors = 0;
590 		sc->t[1].vectors = 0;
591 	}
592 
593 	/* Check what IRQs we want use. */
594 	/* By default allow any PCI IRQs. */
595 	sc->allowed_irqs = 0xffff0000;
596 	/*
597 	 * HPETs in AMD chipsets before SB800 have problems with IRQs >= 16
598 	 * Lower are also not always working for different reasons.
599 	 * SB800 fixed it, but seems do not implements level triggering
600 	 * properly, that makes it very unreliable - it freezes after any
601 	 * interrupt loss. Avoid legacy IRQs for AMD.
602 	 */
603 	if (vendor == HPET_VENDID_AMD || vendor == HPET_VENDID_AMD2)
604 		sc->allowed_irqs = 0x00000000;
605 	/*
606 	 * NVidia MCP5x chipsets have number of unexplained interrupt
607 	 * problems. For some reason, using HPET interrupts breaks HDA sound.
608 	 */
609 	if (vendor == HPET_VENDID_NVIDIA && rev <= 0x01)
610 		sc->allowed_irqs = 0x00000000;
611 	/*
612 	 * ServerWorks HT1000 reported to have problems with IRQs >= 16.
613 	 * Lower IRQs are working, but allowed mask is not set correctly.
614 	 * Legacy_route mode works fine.
615 	 */
616 	if (vendor == HPET_VENDID_SW && rev <= 0x01)
617 		sc->allowed_irqs = 0x00000000;
618 	/*
619 	 * Neither QEMU nor VirtualBox report supported IRQs correctly.
620 	 * The only way to use HPET there is to specify IRQs manually
621 	 * and/or use legacy_route. Legacy_route mode works on both.
622 	 */
623 	if (vm_guest)
624 		sc->allowed_irqs = 0x00000000;
625 	/* Let user override. */
626 	resource_int_value(device_get_name(dev), device_get_unit(dev),
627 	     "allowed_irqs", &sc->allowed_irqs);
628 
629 	/* Get how much per-CPU timers we should try to provide. */
630 	sc->per_cpu = 1;
631 	resource_int_value(device_get_name(dev), device_get_unit(dev),
632 	     "per_cpu", &sc->per_cpu);
633 
634 	num_msi = 0;
635 	sc->useirq = 0;
636 	/* Find IRQ vectors for all timers. */
637 	cvectors = sc->allowed_irqs & 0xffff0000;
638 	dvectors = sc->allowed_irqs & 0x0000ffff;
639 	if (sc->legacy_route)
640 		dvectors &= 0x0000fefe;
641 	for (i = 0; i < num_timers; i++) {
642 		t = &sc->t[i];
643 		if (sc->legacy_route && i < 2)
644 			t->irq = (i == 0) ? 0 : 8;
645 #ifdef DEV_APIC
646 		else if (t->caps & HPET_TCAP_FSB_INT_DEL) {
647 			if ((j = PCIB_ALLOC_MSIX(
648 			    device_get_parent(device_get_parent(dev)), dev,
649 			    &t->irq))) {
650 				device_printf(dev,
651 				    "Can't allocate interrupt for t%d: %d\n",
652 				    i, j);
653 			}
654 		}
655 #endif
656 		else if (dvectors & t->vectors) {
657 			t->irq = ffs(dvectors & t->vectors) - 1;
658 			dvectors &= ~(1 << t->irq);
659 		}
660 		if (t->irq >= 0) {
661 			t->intr_rid = hpet_find_irq_rid(dev, t->irq, t->irq);
662 			t->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ,
663 			    &t->intr_rid, t->irq, t->irq, 1, RF_ACTIVE);
664 			if (t->intr_res == NULL) {
665 				t->irq = -1;
666 				device_printf(dev,
667 				    "Can't map interrupt for t%d.\n", i);
668 			} else if (bus_setup_intr(dev, t->intr_res,
669 			    INTR_TYPE_CLK, hpet_intr_single, NULL, t,
670 			    &t->intr_handle) != 0) {
671 				t->irq = -1;
672 				device_printf(dev,
673 				    "Can't setup interrupt for t%d.\n", i);
674 			} else {
675 				bus_describe_intr(dev, t->intr_res,
676 				    t->intr_handle, "t%d", i);
677 				num_msi++;
678 			}
679 		}
680 		if (t->irq < 0 && (cvectors & t->vectors) != 0) {
681 			cvectors &= t->vectors;
682 			sc->useirq |= (1 << i);
683 		}
684 	}
685 	if (sc->legacy_route && sc->t[0].irq < 0 && sc->t[1].irq < 0)
686 		sc->legacy_route = 0;
687 	if (sc->legacy_route)
688 		hpet_enable(sc);
689 	/* Group timers for per-CPU operation. */
690 	num_percpu_et = min(num_msi / mp_ncpus, sc->per_cpu);
691 	num_percpu_t = num_percpu_et * mp_ncpus;
692 	pcpu_master = 0;
693 	cur_cpu = CPU_FIRST();
694 	for (i = 0; i < num_timers; i++) {
695 		t = &sc->t[i];
696 		if (t->irq >= 0 && num_percpu_t > 0) {
697 			if (cur_cpu == CPU_FIRST())
698 				pcpu_master = i;
699 			t->pcpu_cpu = cur_cpu;
700 			t->pcpu_master = pcpu_master;
701 			sc->t[pcpu_master].
702 			    pcpu_slaves[cur_cpu] = i;
703 			bus_bind_intr(dev, t->intr_res, cur_cpu);
704 			cur_cpu = CPU_NEXT(cur_cpu);
705 			num_percpu_t--;
706 		} else if (t->irq >= 0)
707 			bus_bind_intr(dev, t->intr_res, CPU_FIRST());
708 	}
709 	bus_write_4(sc->mem_res, HPET_ISR, 0xffffffff);
710 	sc->irq = -1;
711 	/* If at least one timer needs legacy IRQ - set it up. */
712 	if (sc->useirq) {
713 		j = i = fls(cvectors) - 1;
714 		while (j > 0 && (cvectors & (1 << (j - 1))) != 0)
715 			j--;
716 		sc->intr_rid = hpet_find_irq_rid(dev, j, i);
717 		sc->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ,
718 		    &sc->intr_rid, j, i, 1, RF_SHAREABLE | RF_ACTIVE);
719 		if (sc->intr_res == NULL)
720 			device_printf(dev, "Can't map interrupt.\n");
721 		else if (bus_setup_intr(dev, sc->intr_res, INTR_TYPE_CLK,
722 		    hpet_intr, NULL, sc, &sc->intr_handle) != 0) {
723 			device_printf(dev, "Can't setup interrupt.\n");
724 		} else {
725 			sc->irq = rman_get_start(sc->intr_res);
726 			/* Bind IRQ to BSP to avoid live migration. */
727 			bus_bind_intr(dev, sc->intr_res, CPU_FIRST());
728 		}
729 	}
730 	/* Program and announce event timers. */
731 	for (i = 0; i < num_timers; i++) {
732 		t = &sc->t[i];
733 		t->caps &= ~(HPET_TCNF_FSB_EN | HPET_TCNF_INT_ROUTE);
734 		t->caps &= ~(HPET_TCNF_VAL_SET | HPET_TCNF_INT_ENB);
735 		t->caps &= ~(HPET_TCNF_INT_TYPE);
736 		t->caps |= HPET_TCNF_32MODE;
737 		if (t->irq >= 0 && sc->legacy_route && i < 2) {
738 			/* Legacy route doesn't need more configuration. */
739 		} else
740 #ifdef DEV_APIC
741 		if ((t->caps & HPET_TCAP_FSB_INT_DEL) && t->irq >= 0) {
742 			uint64_t addr;
743 			uint32_t data;
744 
745 			if (PCIB_MAP_MSI(
746 			    device_get_parent(device_get_parent(dev)), dev,
747 			    t->irq, &addr, &data) == 0) {
748 				bus_write_4(sc->mem_res,
749 				    HPET_TIMER_FSB_ADDR(i), addr);
750 				bus_write_4(sc->mem_res,
751 				    HPET_TIMER_FSB_VAL(i), data);
752 				t->caps |= HPET_TCNF_FSB_EN;
753 			} else
754 				t->irq = -2;
755 		} else
756 #endif
757 		if (t->irq >= 0)
758 			t->caps |= (t->irq << 9);
759 		else if (sc->irq >= 0 && (t->vectors & (1 << sc->irq)))
760 			t->caps |= (sc->irq << 9) | HPET_TCNF_INT_TYPE;
761 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(i), t->caps);
762 		/* Skip event timers without set up IRQ. */
763 		if (t->irq < 0 &&
764 		    (sc->irq < 0 || (t->vectors & (1 << sc->irq)) == 0))
765 			continue;
766 		/* Announce the reset. */
767 		if (maxhpetet == 0)
768 			t->et.et_name = "HPET";
769 		else {
770 			sprintf(t->name, "HPET%d", maxhpetet);
771 			t->et.et_name = t->name;
772 		}
773 		t->et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT;
774 		t->et.et_quality = 450;
775 		if (t->pcpu_master >= 0) {
776 			t->et.et_flags |= ET_FLAGS_PERCPU;
777 			t->et.et_quality += 100;
778 		} else if (mp_ncpus >= 8)
779 			t->et.et_quality -= 100;
780 		if ((t->caps & HPET_TCAP_PER_INT) == 0)
781 			t->et.et_quality -= 10;
782 		t->et.et_frequency = sc->freq;
783 		t->et.et_min_period =
784 		    ((uint64_t)(HPET_MIN_CYCLES * 2) << 32) / sc->freq;
785 		t->et.et_max_period = (0xfffffffeLLU << 32) / sc->freq;
786 		t->et.et_start = hpet_start;
787 		t->et.et_stop = hpet_stop;
788 		t->et.et_priv = &sc->t[i];
789 		if (t->pcpu_master < 0 || t->pcpu_master == i) {
790 			et_register(&t->et);
791 			maxhpetet++;
792 		}
793 	}
794 	acpi_GetInteger(sc->handle, "_UID", &sc->acpi_uid);
795 
796 	make_dev_args_init(&mda);
797 	mda.mda_devsw = &hpet_cdevsw;
798 	mda.mda_uid = UID_ROOT;
799 	mda.mda_gid = GID_WHEEL;
800 	mda.mda_mode = 0644;
801 	mda.mda_si_drv1 = sc;
802 	error = make_dev_s(&mda, &sc->pdev, "hpet%d", device_get_unit(dev));
803 	if (error == 0) {
804 		sc->mmap_allow = 1;
805 		TUNABLE_INT_FETCH("hw.acpi.hpet.mmap_allow",
806 		    &sc->mmap_allow);
807 		sc->mmap_allow_write = 0;
808 		TUNABLE_INT_FETCH("hw.acpi.hpet.mmap_allow_write",
809 		    &sc->mmap_allow_write);
810 		SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
811 		    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
812 		    OID_AUTO, "mmap_allow",
813 		    CTLFLAG_RW, &sc->mmap_allow, 0,
814 		    "Allow userland to memory map HPET");
815 		SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
816 		    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
817 		    OID_AUTO, "mmap_allow_write",
818 		    CTLFLAG_RW, &sc->mmap_allow_write, 0,
819 		    "Allow userland write to the HPET register space");
820 	} else {
821 		device_printf(dev, "could not create /dev/hpet%d, error %d\n",
822 		    device_get_unit(dev), error);
823 	}
824 
825 	return (0);
826 }
827 
828 static int
829 hpet_detach(device_t dev)
830 {
831 	ACPI_FUNCTION_TRACE((char *)(uintptr_t) __func__);
832 
833 	/* XXX Without a tc_remove() function, we can't detach. */
834 	return (EBUSY);
835 }
836 
837 static int
838 hpet_suspend(device_t dev)
839 {
840 //	struct hpet_softc *sc;
841 
842 	/*
843 	 * Disable the timer during suspend.  The timer will not lose
844 	 * its state in S1 or S2, but we are required to disable
845 	 * it.
846 	 */
847 //	sc = device_get_softc(dev);
848 //	hpet_disable(sc);
849 
850 	return (0);
851 }
852 
853 static int
854 hpet_resume(device_t dev)
855 {
856 	struct hpet_softc *sc;
857 	struct hpet_timer *t;
858 	int i;
859 
860 	/* Re-enable the timer after a resume to keep the clock advancing. */
861 	sc = device_get_softc(dev);
862 	hpet_enable(sc);
863 	/* Restart event timers that were running on suspend. */
864 	for (i = 0; i < sc->num_timers; i++) {
865 		t = &sc->t[i];
866 #ifdef DEV_APIC
867 		if (t->irq >= 0 && (sc->legacy_route == 0 || i >= 2)) {
868 			uint64_t addr;
869 			uint32_t data;
870 
871 			if (PCIB_MAP_MSI(
872 			    device_get_parent(device_get_parent(dev)), dev,
873 			    t->irq, &addr, &data) == 0) {
874 				bus_write_4(sc->mem_res,
875 				    HPET_TIMER_FSB_ADDR(i), addr);
876 				bus_write_4(sc->mem_res,
877 				    HPET_TIMER_FSB_VAL(i), data);
878 			}
879 		}
880 #endif
881 		if (t->mode == 0)
882 			continue;
883 		t->next = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
884 		if (t->mode == 1 && (t->caps & HPET_TCAP_PER_INT)) {
885 			t->caps |= HPET_TCNF_TYPE;
886 			t->next += t->div;
887 			bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num),
888 			    t->caps | HPET_TCNF_VAL_SET);
889 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
890 			    t->next);
891 			bus_read_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num));
892 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
893 			    t->div);
894 		} else {
895 			t->next += sc->freq / 1024;
896 			bus_write_4(sc->mem_res, HPET_TIMER_COMPARATOR(t->num),
897 			    t->next);
898 		}
899 		bus_write_4(sc->mem_res, HPET_ISR, 1 << t->num);
900 		bus_write_4(sc->mem_res, HPET_TIMER_CAP_CNF(t->num), t->caps);
901 	}
902 	return (0);
903 }
904 
905 /* Print some basic latency/rate information to assist in debugging. */
906 static void
907 hpet_test(struct hpet_softc *sc)
908 {
909 	int i;
910 	uint32_t u1, u2;
911 	struct bintime b0, b1, b2;
912 	struct timespec ts;
913 
914 	binuptime(&b0);
915 	binuptime(&b0);
916 	binuptime(&b1);
917 	u1 = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
918 	for (i = 1; i < 1000; i++)
919 		u2 = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
920 	binuptime(&b2);
921 	u2 = bus_read_4(sc->mem_res, HPET_MAIN_COUNTER);
922 
923 	bintime_sub(&b2, &b1);
924 	bintime_sub(&b1, &b0);
925 	bintime_sub(&b2, &b1);
926 	bintime2timespec(&b2, &ts);
927 
928 	device_printf(sc->dev, "%ld.%09ld: %u ... %u = %u\n",
929 	    (long)ts.tv_sec, ts.tv_nsec, u1, u2, u2 - u1);
930 
931 	device_printf(sc->dev, "time per call: %ld ns\n", ts.tv_nsec / 1000);
932 }
933 
934 #ifdef DEV_APIC
935 static int
936 hpet_remap_intr(device_t dev, device_t child, u_int irq)
937 {
938 	struct hpet_softc *sc = device_get_softc(dev);
939 	struct hpet_timer *t;
940 	uint64_t addr;
941 	uint32_t data;
942 	int error, i;
943 
944 	for (i = 0; i < sc->num_timers; i++) {
945 		t = &sc->t[i];
946 		if (t->irq != irq)
947 			continue;
948 		error = PCIB_MAP_MSI(
949 		    device_get_parent(device_get_parent(dev)), dev,
950 		    irq, &addr, &data);
951 		if (error)
952 			return (error);
953 		hpet_disable(sc); /* Stop timer to avoid interrupt loss. */
954 		bus_write_4(sc->mem_res, HPET_TIMER_FSB_ADDR(i), addr);
955 		bus_write_4(sc->mem_res, HPET_TIMER_FSB_VAL(i), data);
956 		hpet_enable(sc);
957 		return (0);
958 	}
959 	return (ENOENT);
960 }
961 #endif
962 
963 static device_method_t hpet_methods[] = {
964 	/* Device interface */
965 	DEVMETHOD(device_identify, hpet_identify),
966 	DEVMETHOD(device_probe, hpet_probe),
967 	DEVMETHOD(device_attach, hpet_attach),
968 	DEVMETHOD(device_detach, hpet_detach),
969 	DEVMETHOD(device_suspend, hpet_suspend),
970 	DEVMETHOD(device_resume, hpet_resume),
971 
972 #ifdef DEV_APIC
973 	DEVMETHOD(bus_remap_intr, hpet_remap_intr),
974 #endif
975 
976 	DEVMETHOD_END
977 };
978 
979 static driver_t	hpet_driver = {
980 	"hpet",
981 	hpet_methods,
982 	sizeof(struct hpet_softc),
983 };
984 
985 DRIVER_MODULE(hpet, acpi, hpet_driver, hpet_devclass, 0, 0);
986 MODULE_DEPEND(hpet, acpi, 1, 1, 1);
987