xref: /linux/arch/x86/kernel/hpet.c (revision e814f3fd16acfb7f9966773953de8f740a1e3202)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/clockchips.h>
3 #include <linux/interrupt.h>
4 #include <linux/export.h>
5 #include <linux/delay.h>
6 #include <linux/hpet.h>
7 #include <linux/cpu.h>
8 #include <linux/irq.h>
9 
10 #include <asm/cpuid.h>
11 #include <asm/irq_remapping.h>
12 #include <asm/hpet.h>
13 #include <asm/time.h>
14 #include <asm/mwait.h>
15 
16 #undef  pr_fmt
17 #define pr_fmt(fmt) "hpet: " fmt
18 
19 enum hpet_mode {
20 	HPET_MODE_UNUSED,
21 	HPET_MODE_LEGACY,
22 	HPET_MODE_CLOCKEVT,
23 	HPET_MODE_DEVICE,
24 };
25 
26 struct hpet_channel {
27 	struct clock_event_device	evt;
28 	unsigned int			num;
29 	unsigned int			cpu;
30 	unsigned int			irq;
31 	unsigned int			in_use;
32 	enum hpet_mode			mode;
33 	unsigned int			boot_cfg;
34 	char				name[10];
35 };
36 
37 struct hpet_base {
38 	unsigned int			nr_channels;
39 	unsigned int			nr_clockevents;
40 	unsigned int			boot_cfg;
41 	struct hpet_channel		*channels;
42 };
43 
44 #define HPET_MASK			CLOCKSOURCE_MASK(32)
45 
46 #define HPET_MIN_CYCLES			128
47 #define HPET_MIN_PROG_DELTA		(HPET_MIN_CYCLES + (HPET_MIN_CYCLES >> 1))
48 
49 /*
50  * HPET address is set in acpi/boot.c, when an ACPI entry exists
51  */
52 unsigned long				hpet_address;
53 u8					hpet_blockid; /* OS timer block num */
54 bool					hpet_msi_disable;
55 
56 #if defined(CONFIG_X86_LOCAL_APIC) && defined(CONFIG_GENERIC_MSI_IRQ)
57 static DEFINE_PER_CPU(struct hpet_channel *, cpu_hpet_channel);
58 static struct irq_domain		*hpet_domain;
59 #endif
60 
61 static void __iomem			*hpet_virt_address;
62 
63 static struct hpet_base			hpet_base;
64 
65 static bool				hpet_legacy_int_enabled;
66 static unsigned long			hpet_freq;
67 
68 bool					boot_hpet_disable;
69 bool					hpet_force_user;
70 static bool				hpet_verbose;
71 
72 static inline
73 struct hpet_channel *clockevent_to_channel(struct clock_event_device *evt)
74 {
75 	return container_of(evt, struct hpet_channel, evt);
76 }
77 
78 inline unsigned int hpet_readl(unsigned int a)
79 {
80 	return readl(hpet_virt_address + a);
81 }
82 
83 static inline void hpet_writel(unsigned int d, unsigned int a)
84 {
85 	writel(d, hpet_virt_address + a);
86 }
87 
88 static inline void hpet_set_mapping(void)
89 {
90 	hpet_virt_address = ioremap(hpet_address, HPET_MMAP_SIZE);
91 }
92 
93 static inline void hpet_clear_mapping(void)
94 {
95 	iounmap(hpet_virt_address);
96 	hpet_virt_address = NULL;
97 }
98 
99 /*
100  * HPET command line enable / disable
101  */
102 static int __init hpet_setup(char *str)
103 {
104 	while (str) {
105 		char *next = strchr(str, ',');
106 
107 		if (next)
108 			*next++ = 0;
109 		if (!strncmp("disable", str, 7))
110 			boot_hpet_disable = true;
111 		if (!strncmp("force", str, 5))
112 			hpet_force_user = true;
113 		if (!strncmp("verbose", str, 7))
114 			hpet_verbose = true;
115 		str = next;
116 	}
117 	return 1;
118 }
119 __setup("hpet=", hpet_setup);
120 
121 static int __init disable_hpet(char *str)
122 {
123 	boot_hpet_disable = true;
124 	return 1;
125 }
126 __setup("nohpet", disable_hpet);
127 
128 static inline int is_hpet_capable(void)
129 {
130 	return !boot_hpet_disable && hpet_address;
131 }
132 
133 /**
134  * is_hpet_enabled - Check whether the legacy HPET timer interrupt is enabled
135  */
136 int is_hpet_enabled(void)
137 {
138 	return is_hpet_capable() && hpet_legacy_int_enabled;
139 }
140 EXPORT_SYMBOL_GPL(is_hpet_enabled);
141 
142 static void _hpet_print_config(const char *function, int line)
143 {
144 	u32 i, id, period, cfg, status, channels, l, h;
145 
146 	pr_info("%s(%d):\n", function, line);
147 
148 	id = hpet_readl(HPET_ID);
149 	period = hpet_readl(HPET_PERIOD);
150 	pr_info("ID: 0x%x, PERIOD: 0x%x\n", id, period);
151 
152 	cfg = hpet_readl(HPET_CFG);
153 	status = hpet_readl(HPET_STATUS);
154 	pr_info("CFG: 0x%x, STATUS: 0x%x\n", cfg, status);
155 
156 	l = hpet_readl(HPET_COUNTER);
157 	h = hpet_readl(HPET_COUNTER+4);
158 	pr_info("COUNTER_l: 0x%x, COUNTER_h: 0x%x\n", l, h);
159 
160 	channels = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1;
161 
162 	for (i = 0; i < channels; i++) {
163 		l = hpet_readl(HPET_Tn_CFG(i));
164 		h = hpet_readl(HPET_Tn_CFG(i)+4);
165 		pr_info("T%d: CFG_l: 0x%x, CFG_h: 0x%x\n", i, l, h);
166 
167 		l = hpet_readl(HPET_Tn_CMP(i));
168 		h = hpet_readl(HPET_Tn_CMP(i)+4);
169 		pr_info("T%d: CMP_l: 0x%x, CMP_h: 0x%x\n", i, l, h);
170 
171 		l = hpet_readl(HPET_Tn_ROUTE(i));
172 		h = hpet_readl(HPET_Tn_ROUTE(i)+4);
173 		pr_info("T%d ROUTE_l: 0x%x, ROUTE_h: 0x%x\n", i, l, h);
174 	}
175 }
176 
177 #define hpet_print_config()					\
178 do {								\
179 	if (hpet_verbose)					\
180 		_hpet_print_config(__func__, __LINE__);	\
181 } while (0)
182 
183 /*
184  * When the HPET driver (/dev/hpet) is enabled, we need to reserve
185  * timer 0 and timer 1 in case of RTC emulation.
186  */
187 #ifdef CONFIG_HPET
188 
189 static void __init hpet_reserve_platform_timers(void)
190 {
191 	struct hpet_data hd;
192 	unsigned int i;
193 
194 	memset(&hd, 0, sizeof(hd));
195 	hd.hd_phys_address	= hpet_address;
196 	hd.hd_address		= hpet_virt_address;
197 	hd.hd_nirqs		= hpet_base.nr_channels;
198 
199 	/*
200 	 * NOTE that hd_irq[] reflects IOAPIC input pins (LEGACY_8254
201 	 * is wrong for i8259!) not the output IRQ.  Many BIOS writers
202 	 * don't bother configuring *any* comparator interrupts.
203 	 */
204 	hd.hd_irq[0] = HPET_LEGACY_8254;
205 	hd.hd_irq[1] = HPET_LEGACY_RTC;
206 
207 	for (i = 0; i < hpet_base.nr_channels; i++) {
208 		struct hpet_channel *hc = hpet_base.channels + i;
209 
210 		if (i >= 2)
211 			hd.hd_irq[i] = hc->irq;
212 
213 		switch (hc->mode) {
214 		case HPET_MODE_UNUSED:
215 		case HPET_MODE_DEVICE:
216 			hc->mode = HPET_MODE_DEVICE;
217 			break;
218 		case HPET_MODE_CLOCKEVT:
219 		case HPET_MODE_LEGACY:
220 			hpet_reserve_timer(&hd, hc->num);
221 			break;
222 		}
223 	}
224 
225 	hpet_alloc(&hd);
226 }
227 
228 static void __init hpet_select_device_channel(void)
229 {
230 	int i;
231 
232 	for (i = 0; i < hpet_base.nr_channels; i++) {
233 		struct hpet_channel *hc = hpet_base.channels + i;
234 
235 		/* Associate the first unused channel to /dev/hpet */
236 		if (hc->mode == HPET_MODE_UNUSED) {
237 			hc->mode = HPET_MODE_DEVICE;
238 			return;
239 		}
240 	}
241 }
242 
243 #else
244 static inline void hpet_reserve_platform_timers(void) { }
245 static inline void hpet_select_device_channel(void) {}
246 #endif
247 
248 /* Common HPET functions */
249 static void hpet_stop_counter(void)
250 {
251 	u32 cfg = hpet_readl(HPET_CFG);
252 
253 	cfg &= ~HPET_CFG_ENABLE;
254 	hpet_writel(cfg, HPET_CFG);
255 }
256 
257 static void hpet_reset_counter(void)
258 {
259 	hpet_writel(0, HPET_COUNTER);
260 	hpet_writel(0, HPET_COUNTER + 4);
261 }
262 
263 static void hpet_start_counter(void)
264 {
265 	unsigned int cfg = hpet_readl(HPET_CFG);
266 
267 	cfg |= HPET_CFG_ENABLE;
268 	hpet_writel(cfg, HPET_CFG);
269 }
270 
271 static void hpet_restart_counter(void)
272 {
273 	hpet_stop_counter();
274 	hpet_reset_counter();
275 	hpet_start_counter();
276 }
277 
278 static void hpet_resume_device(void)
279 {
280 	force_hpet_resume();
281 }
282 
283 static void hpet_resume_counter(struct clocksource *cs)
284 {
285 	hpet_resume_device();
286 	hpet_restart_counter();
287 }
288 
289 static void hpet_enable_legacy_int(void)
290 {
291 	unsigned int cfg = hpet_readl(HPET_CFG);
292 
293 	cfg |= HPET_CFG_LEGACY;
294 	hpet_writel(cfg, HPET_CFG);
295 	hpet_legacy_int_enabled = true;
296 }
297 
298 static int hpet_clkevt_set_state_periodic(struct clock_event_device *evt)
299 {
300 	unsigned int channel = clockevent_to_channel(evt)->num;
301 	unsigned int cfg, cmp, now;
302 	uint64_t delta;
303 
304 	hpet_stop_counter();
305 	delta = ((uint64_t)(NSEC_PER_SEC / HZ)) * evt->mult;
306 	delta >>= evt->shift;
307 	now = hpet_readl(HPET_COUNTER);
308 	cmp = now + (unsigned int)delta;
309 	cfg = hpet_readl(HPET_Tn_CFG(channel));
310 	cfg |= HPET_TN_ENABLE | HPET_TN_PERIODIC | HPET_TN_SETVAL |
311 	       HPET_TN_32BIT;
312 	hpet_writel(cfg, HPET_Tn_CFG(channel));
313 	hpet_writel(cmp, HPET_Tn_CMP(channel));
314 	udelay(1);
315 	/*
316 	 * HPET on AMD 81xx needs a second write (with HPET_TN_SETVAL
317 	 * cleared) to T0_CMP to set the period. The HPET_TN_SETVAL
318 	 * bit is automatically cleared after the first write.
319 	 * (See AMD-8111 HyperTransport I/O Hub Data Sheet,
320 	 * Publication # 24674)
321 	 */
322 	hpet_writel((unsigned int)delta, HPET_Tn_CMP(channel));
323 	hpet_start_counter();
324 	hpet_print_config();
325 
326 	return 0;
327 }
328 
329 static int hpet_clkevt_set_state_oneshot(struct clock_event_device *evt)
330 {
331 	unsigned int channel = clockevent_to_channel(evt)->num;
332 	unsigned int cfg;
333 
334 	cfg = hpet_readl(HPET_Tn_CFG(channel));
335 	cfg &= ~HPET_TN_PERIODIC;
336 	cfg |= HPET_TN_ENABLE | HPET_TN_32BIT;
337 	hpet_writel(cfg, HPET_Tn_CFG(channel));
338 
339 	return 0;
340 }
341 
342 static int hpet_clkevt_set_state_shutdown(struct clock_event_device *evt)
343 {
344 	unsigned int channel = clockevent_to_channel(evt)->num;
345 	unsigned int cfg;
346 
347 	cfg = hpet_readl(HPET_Tn_CFG(channel));
348 	cfg &= ~HPET_TN_ENABLE;
349 	hpet_writel(cfg, HPET_Tn_CFG(channel));
350 
351 	return 0;
352 }
353 
354 static int hpet_clkevt_legacy_resume(struct clock_event_device *evt)
355 {
356 	hpet_enable_legacy_int();
357 	hpet_print_config();
358 	return 0;
359 }
360 
361 static int
362 hpet_clkevt_set_next_event(unsigned long delta, struct clock_event_device *evt)
363 {
364 	unsigned int channel = clockevent_to_channel(evt)->num;
365 	u32 cnt;
366 	s32 res;
367 
368 	cnt = hpet_readl(HPET_COUNTER);
369 	cnt += (u32) delta;
370 	hpet_writel(cnt, HPET_Tn_CMP(channel));
371 
372 	/*
373 	 * HPETs are a complete disaster. The compare register is
374 	 * based on a equal comparison and neither provides a less
375 	 * than or equal functionality (which would require to take
376 	 * the wraparound into account) nor a simple count down event
377 	 * mode. Further the write to the comparator register is
378 	 * delayed internally up to two HPET clock cycles in certain
379 	 * chipsets (ATI, ICH9,10). Some newer AMD chipsets have even
380 	 * longer delays. We worked around that by reading back the
381 	 * compare register, but that required another workaround for
382 	 * ICH9,10 chips where the first readout after write can
383 	 * return the old stale value. We already had a minimum
384 	 * programming delta of 5us enforced, but a NMI or SMI hitting
385 	 * between the counter readout and the comparator write can
386 	 * move us behind that point easily. Now instead of reading
387 	 * the compare register back several times, we make the ETIME
388 	 * decision based on the following: Return ETIME if the
389 	 * counter value after the write is less than HPET_MIN_CYCLES
390 	 * away from the event or if the counter is already ahead of
391 	 * the event. The minimum programming delta for the generic
392 	 * clockevents code is set to 1.5 * HPET_MIN_CYCLES.
393 	 */
394 	res = (s32)(cnt - hpet_readl(HPET_COUNTER));
395 
396 	return res < HPET_MIN_CYCLES ? -ETIME : 0;
397 }
398 
399 static void hpet_init_clockevent(struct hpet_channel *hc, unsigned int rating)
400 {
401 	struct clock_event_device *evt = &hc->evt;
402 
403 	evt->rating		= rating;
404 	evt->irq		= hc->irq;
405 	evt->name		= hc->name;
406 	evt->cpumask		= cpumask_of(hc->cpu);
407 	evt->set_state_oneshot	= hpet_clkevt_set_state_oneshot;
408 	evt->set_next_event	= hpet_clkevt_set_next_event;
409 	evt->set_state_shutdown	= hpet_clkevt_set_state_shutdown;
410 
411 	evt->features = CLOCK_EVT_FEAT_ONESHOT;
412 	if (hc->boot_cfg & HPET_TN_PERIODIC) {
413 		evt->features		|= CLOCK_EVT_FEAT_PERIODIC;
414 		evt->set_state_periodic	= hpet_clkevt_set_state_periodic;
415 	}
416 }
417 
418 static void __init hpet_legacy_clockevent_register(struct hpet_channel *hc)
419 {
420 	/*
421 	 * Start HPET with the boot CPU's cpumask and make it global after
422 	 * the IO_APIC has been initialized.
423 	 */
424 	hc->cpu = boot_cpu_data.cpu_index;
425 	strscpy(hc->name, "hpet", sizeof(hc->name));
426 	hpet_init_clockevent(hc, 50);
427 
428 	hc->evt.tick_resume	= hpet_clkevt_legacy_resume;
429 
430 	/*
431 	 * Legacy horrors and sins from the past. HPET used periodic mode
432 	 * unconditionally forever on the legacy channel 0. Removing the
433 	 * below hack and using the conditional in hpet_init_clockevent()
434 	 * makes at least Qemu and one hardware machine fail to boot.
435 	 * There are two issues which cause the boot failure:
436 	 *
437 	 * #1 After the timer delivery test in IOAPIC and the IOAPIC setup
438 	 *    the next interrupt is not delivered despite the HPET channel
439 	 *    being programmed correctly. Reprogramming the HPET after
440 	 *    switching to IOAPIC makes it work again. After fixing this,
441 	 *    the next issue surfaces:
442 	 *
443 	 * #2 Due to the unconditional periodic mode availability the Local
444 	 *    APIC timer calibration can hijack the global clockevents
445 	 *    event handler without causing damage. Using oneshot at this
446 	 *    stage makes if hang because the HPET does not get
447 	 *    reprogrammed due to the handler hijacking. Duh, stupid me!
448 	 *
449 	 * Both issues require major surgery and especially the kick HPET
450 	 * again after enabling IOAPIC results in really nasty hackery.
451 	 * This 'assume periodic works' magic has survived since HPET
452 	 * support got added, so it's questionable whether this should be
453 	 * fixed. Both Qemu and the failing hardware machine support
454 	 * periodic mode despite the fact that both don't advertise it in
455 	 * the configuration register and both need that extra kick after
456 	 * switching to IOAPIC. Seems to be a feature...
457 	 */
458 	hc->evt.features		|= CLOCK_EVT_FEAT_PERIODIC;
459 	hc->evt.set_state_periodic	= hpet_clkevt_set_state_periodic;
460 
461 	/* Start HPET legacy interrupts */
462 	hpet_enable_legacy_int();
463 
464 	clockevents_config_and_register(&hc->evt, hpet_freq,
465 					HPET_MIN_PROG_DELTA, 0x7FFFFFFF);
466 	global_clock_event = &hc->evt;
467 	pr_debug("Clockevent registered\n");
468 }
469 
470 /*
471  * HPET MSI Support
472  */
473 #if defined(CONFIG_X86_LOCAL_APIC) && defined(CONFIG_GENERIC_MSI_IRQ)
474 static void hpet_msi_unmask(struct irq_data *data)
475 {
476 	struct hpet_channel *hc = irq_data_get_irq_handler_data(data);
477 	unsigned int cfg;
478 
479 	cfg = hpet_readl(HPET_Tn_CFG(hc->num));
480 	cfg |= HPET_TN_ENABLE | HPET_TN_FSB;
481 	hpet_writel(cfg, HPET_Tn_CFG(hc->num));
482 }
483 
484 static void hpet_msi_mask(struct irq_data *data)
485 {
486 	struct hpet_channel *hc = irq_data_get_irq_handler_data(data);
487 	unsigned int cfg;
488 
489 	cfg = hpet_readl(HPET_Tn_CFG(hc->num));
490 	cfg &= ~(HPET_TN_ENABLE | HPET_TN_FSB);
491 	hpet_writel(cfg, HPET_Tn_CFG(hc->num));
492 }
493 
494 static void hpet_msi_write(struct hpet_channel *hc, struct msi_msg *msg)
495 {
496 	hpet_writel(msg->data, HPET_Tn_ROUTE(hc->num));
497 	hpet_writel(msg->address_lo, HPET_Tn_ROUTE(hc->num) + 4);
498 }
499 
500 static void hpet_msi_write_msg(struct irq_data *data, struct msi_msg *msg)
501 {
502 	hpet_msi_write(irq_data_get_irq_handler_data(data), msg);
503 }
504 
505 static struct irq_chip hpet_msi_controller __ro_after_init = {
506 	.name = "HPET-MSI",
507 	.irq_unmask = hpet_msi_unmask,
508 	.irq_mask = hpet_msi_mask,
509 	.irq_ack = irq_chip_ack_parent,
510 	.irq_set_affinity = msi_domain_set_affinity,
511 	.irq_retrigger = irq_chip_retrigger_hierarchy,
512 	.irq_write_msi_msg = hpet_msi_write_msg,
513 	.flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_AFFINITY_PRE_STARTUP,
514 };
515 
516 static int hpet_msi_init(struct irq_domain *domain,
517 			 struct msi_domain_info *info, unsigned int virq,
518 			 irq_hw_number_t hwirq, msi_alloc_info_t *arg)
519 {
520 	irq_domain_set_info(domain, virq, arg->hwirq, info->chip, NULL,
521 			    handle_edge_irq, arg->data, "edge");
522 
523 	return 0;
524 }
525 
526 static struct msi_domain_ops hpet_msi_domain_ops = {
527 	.msi_init	= hpet_msi_init,
528 };
529 
530 static struct msi_domain_info hpet_msi_domain_info = {
531 	.ops		= &hpet_msi_domain_ops,
532 	.chip		= &hpet_msi_controller,
533 	.flags		= MSI_FLAG_USE_DEF_DOM_OPS,
534 };
535 
536 static struct irq_domain *hpet_create_irq_domain(int hpet_id)
537 {
538 	struct msi_domain_info *domain_info;
539 	struct irq_domain *parent, *d;
540 	struct fwnode_handle *fn;
541 	struct irq_fwspec fwspec;
542 
543 	if (x86_vector_domain == NULL)
544 		return NULL;
545 
546 	domain_info = kzalloc(sizeof(*domain_info), GFP_KERNEL);
547 	if (!domain_info)
548 		return NULL;
549 
550 	*domain_info = hpet_msi_domain_info;
551 	domain_info->data = (void *)(long)hpet_id;
552 
553 	fn = irq_domain_alloc_named_id_fwnode(hpet_msi_controller.name,
554 					      hpet_id);
555 	if (!fn) {
556 		kfree(domain_info);
557 		return NULL;
558 	}
559 
560 	fwspec.fwnode = fn;
561 	fwspec.param_count = 1;
562 	fwspec.param[0] = hpet_id;
563 
564 	parent = irq_find_matching_fwspec(&fwspec, DOMAIN_BUS_GENERIC_MSI);
565 	if (!parent) {
566 		irq_domain_free_fwnode(fn);
567 		kfree(domain_info);
568 		return NULL;
569 	}
570 	if (parent != x86_vector_domain)
571 		hpet_msi_controller.name = "IR-HPET-MSI";
572 
573 	d = msi_create_irq_domain(fn, domain_info, parent);
574 	if (!d) {
575 		irq_domain_free_fwnode(fn);
576 		kfree(domain_info);
577 	}
578 	return d;
579 }
580 
581 static inline int hpet_dev_id(struct irq_domain *domain)
582 {
583 	struct msi_domain_info *info = msi_get_domain_info(domain);
584 
585 	return (int)(long)info->data;
586 }
587 
588 static int hpet_assign_irq(struct irq_domain *domain, struct hpet_channel *hc,
589 			   int dev_num)
590 {
591 	struct irq_alloc_info info;
592 
593 	init_irq_alloc_info(&info, NULL);
594 	info.type = X86_IRQ_ALLOC_TYPE_HPET;
595 	info.data = hc;
596 	info.devid = hpet_dev_id(domain);
597 	info.hwirq = dev_num;
598 
599 	return irq_domain_alloc_irqs(domain, 1, NUMA_NO_NODE, &info);
600 }
601 
602 static int hpet_clkevt_msi_resume(struct clock_event_device *evt)
603 {
604 	struct hpet_channel *hc = clockevent_to_channel(evt);
605 	struct irq_data *data = irq_get_irq_data(hc->irq);
606 	struct msi_msg msg;
607 
608 	/* Restore the MSI msg and unmask the interrupt */
609 	irq_chip_compose_msi_msg(data, &msg);
610 	hpet_msi_write(hc, &msg);
611 	hpet_msi_unmask(data);
612 	return 0;
613 }
614 
615 static irqreturn_t hpet_msi_interrupt_handler(int irq, void *data)
616 {
617 	struct hpet_channel *hc = data;
618 	struct clock_event_device *evt = &hc->evt;
619 
620 	if (!evt->event_handler) {
621 		pr_info("Spurious interrupt HPET channel %d\n", hc->num);
622 		return IRQ_HANDLED;
623 	}
624 
625 	evt->event_handler(evt);
626 	return IRQ_HANDLED;
627 }
628 
629 static int hpet_setup_msi_irq(struct hpet_channel *hc)
630 {
631 	if (request_irq(hc->irq, hpet_msi_interrupt_handler,
632 			IRQF_TIMER | IRQF_NOBALANCING,
633 			hc->name, hc))
634 		return -1;
635 
636 	disable_irq(hc->irq);
637 	irq_set_affinity(hc->irq, cpumask_of(hc->cpu));
638 	enable_irq(hc->irq);
639 
640 	pr_debug("%s irq %u for MSI\n", hc->name, hc->irq);
641 
642 	return 0;
643 }
644 
645 /* Invoked from the hotplug callback on @cpu */
646 static void init_one_hpet_msi_clockevent(struct hpet_channel *hc, int cpu)
647 {
648 	struct clock_event_device *evt = &hc->evt;
649 
650 	hc->cpu = cpu;
651 	per_cpu(cpu_hpet_channel, cpu) = hc;
652 	hpet_setup_msi_irq(hc);
653 
654 	hpet_init_clockevent(hc, 110);
655 	evt->tick_resume = hpet_clkevt_msi_resume;
656 
657 	clockevents_config_and_register(evt, hpet_freq, HPET_MIN_PROG_DELTA,
658 					0x7FFFFFFF);
659 }
660 
661 static struct hpet_channel *hpet_get_unused_clockevent(void)
662 {
663 	int i;
664 
665 	for (i = 0; i < hpet_base.nr_channels; i++) {
666 		struct hpet_channel *hc = hpet_base.channels + i;
667 
668 		if (hc->mode != HPET_MODE_CLOCKEVT || hc->in_use)
669 			continue;
670 		hc->in_use = 1;
671 		return hc;
672 	}
673 	return NULL;
674 }
675 
676 static int hpet_cpuhp_online(unsigned int cpu)
677 {
678 	struct hpet_channel *hc = hpet_get_unused_clockevent();
679 
680 	if (hc)
681 		init_one_hpet_msi_clockevent(hc, cpu);
682 	return 0;
683 }
684 
685 static int hpet_cpuhp_dead(unsigned int cpu)
686 {
687 	struct hpet_channel *hc = per_cpu(cpu_hpet_channel, cpu);
688 
689 	if (!hc)
690 		return 0;
691 	free_irq(hc->irq, hc);
692 	hc->in_use = 0;
693 	per_cpu(cpu_hpet_channel, cpu) = NULL;
694 	return 0;
695 }
696 
697 static void __init hpet_select_clockevents(void)
698 {
699 	unsigned int i;
700 
701 	hpet_base.nr_clockevents = 0;
702 
703 	/* No point if MSI is disabled or CPU has an Always Running APIC Timer */
704 	if (hpet_msi_disable || boot_cpu_has(X86_FEATURE_ARAT))
705 		return;
706 
707 	hpet_print_config();
708 
709 	hpet_domain = hpet_create_irq_domain(hpet_blockid);
710 	if (!hpet_domain)
711 		return;
712 
713 	for (i = 0; i < hpet_base.nr_channels; i++) {
714 		struct hpet_channel *hc = hpet_base.channels + i;
715 		int irq;
716 
717 		if (hc->mode != HPET_MODE_UNUSED)
718 			continue;
719 
720 		/* Only consider HPET channel with MSI support */
721 		if (!(hc->boot_cfg & HPET_TN_FSB_CAP))
722 			continue;
723 
724 		sprintf(hc->name, "hpet%d", i);
725 
726 		irq = hpet_assign_irq(hpet_domain, hc, hc->num);
727 		if (irq <= 0)
728 			continue;
729 
730 		hc->irq = irq;
731 		hc->mode = HPET_MODE_CLOCKEVT;
732 
733 		if (++hpet_base.nr_clockevents == num_possible_cpus())
734 			break;
735 	}
736 
737 	pr_info("%d channels of %d reserved for per-cpu timers\n",
738 		hpet_base.nr_channels, hpet_base.nr_clockevents);
739 }
740 
741 #else
742 
743 static inline void hpet_select_clockevents(void) { }
744 
745 #define hpet_cpuhp_online	NULL
746 #define hpet_cpuhp_dead		NULL
747 
748 #endif
749 
750 /*
751  * Clock source related code
752  */
753 #if defined(CONFIG_SMP) && defined(CONFIG_64BIT)
754 /*
755  * Reading the HPET counter is a very slow operation. If a large number of
756  * CPUs are trying to access the HPET counter simultaneously, it can cause
757  * massive delays and slow down system performance dramatically. This may
758  * happen when HPET is the default clock source instead of TSC. For a
759  * really large system with hundreds of CPUs, the slowdown may be so
760  * severe, that it can actually crash the system because of a NMI watchdog
761  * soft lockup, for example.
762  *
763  * If multiple CPUs are trying to access the HPET counter at the same time,
764  * we don't actually need to read the counter multiple times. Instead, the
765  * other CPUs can use the counter value read by the first CPU in the group.
766  *
767  * This special feature is only enabled on x86-64 systems. It is unlikely
768  * that 32-bit x86 systems will have enough CPUs to require this feature
769  * with its associated locking overhead. We also need 64-bit atomic read.
770  *
771  * The lock and the HPET value are stored together and can be read in a
772  * single atomic 64-bit read. It is explicitly assumed that arch_spinlock_t
773  * is 32 bits in size.
774  */
775 union hpet_lock {
776 	struct {
777 		arch_spinlock_t lock;
778 		u32 value;
779 	};
780 	u64 lockval;
781 };
782 
783 static union hpet_lock hpet __cacheline_aligned = {
784 	{ .lock = __ARCH_SPIN_LOCK_UNLOCKED, },
785 };
786 
787 static u64 read_hpet(struct clocksource *cs)
788 {
789 	unsigned long flags;
790 	union hpet_lock old, new;
791 
792 	BUILD_BUG_ON(sizeof(union hpet_lock) != 8);
793 
794 	/*
795 	 * Read HPET directly if in NMI.
796 	 */
797 	if (in_nmi())
798 		return (u64)hpet_readl(HPET_COUNTER);
799 
800 	/*
801 	 * Read the current state of the lock and HPET value atomically.
802 	 */
803 	old.lockval = READ_ONCE(hpet.lockval);
804 
805 	if (arch_spin_is_locked(&old.lock))
806 		goto contended;
807 
808 	local_irq_save(flags);
809 	if (arch_spin_trylock(&hpet.lock)) {
810 		new.value = hpet_readl(HPET_COUNTER);
811 		/*
812 		 * Use WRITE_ONCE() to prevent store tearing.
813 		 */
814 		WRITE_ONCE(hpet.value, new.value);
815 		arch_spin_unlock(&hpet.lock);
816 		local_irq_restore(flags);
817 		return (u64)new.value;
818 	}
819 	local_irq_restore(flags);
820 
821 contended:
822 	/*
823 	 * Contended case
824 	 * --------------
825 	 * Wait until the HPET value change or the lock is free to indicate
826 	 * its value is up-to-date.
827 	 *
828 	 * It is possible that old.value has already contained the latest
829 	 * HPET value while the lock holder was in the process of releasing
830 	 * the lock. Checking for lock state change will enable us to return
831 	 * the value immediately instead of waiting for the next HPET reader
832 	 * to come along.
833 	 */
834 	do {
835 		cpu_relax();
836 		new.lockval = READ_ONCE(hpet.lockval);
837 	} while ((new.value == old.value) && arch_spin_is_locked(&new.lock));
838 
839 	return (u64)new.value;
840 }
841 #else
842 /*
843  * For UP or 32-bit.
844  */
845 static u64 read_hpet(struct clocksource *cs)
846 {
847 	return (u64)hpet_readl(HPET_COUNTER);
848 }
849 #endif
850 
851 static struct clocksource clocksource_hpet = {
852 	.name		= "hpet",
853 	.rating		= 250,
854 	.read		= read_hpet,
855 	.mask		= HPET_MASK,
856 	.flags		= CLOCK_SOURCE_IS_CONTINUOUS,
857 	.resume		= hpet_resume_counter,
858 };
859 
860 /*
861  * AMD SB700 based systems with spread spectrum enabled use a SMM based
862  * HPET emulation to provide proper frequency setting.
863  *
864  * On such systems the SMM code is initialized with the first HPET register
865  * access and takes some time to complete. During this time the config
866  * register reads 0xffffffff. We check for max 1000 loops whether the
867  * config register reads a non-0xffffffff value to make sure that the
868  * HPET is up and running before we proceed any further.
869  *
870  * A counting loop is safe, as the HPET access takes thousands of CPU cycles.
871  *
872  * On non-SB700 based machines this check is only done once and has no
873  * side effects.
874  */
875 static bool __init hpet_cfg_working(void)
876 {
877 	int i;
878 
879 	for (i = 0; i < 1000; i++) {
880 		if (hpet_readl(HPET_CFG) != 0xFFFFFFFF)
881 			return true;
882 	}
883 
884 	pr_warn("Config register invalid. Disabling HPET\n");
885 	return false;
886 }
887 
888 static bool __init hpet_counting(void)
889 {
890 	u64 start, now, t1;
891 
892 	hpet_restart_counter();
893 
894 	t1 = hpet_readl(HPET_COUNTER);
895 	start = rdtsc();
896 
897 	/*
898 	 * We don't know the TSC frequency yet, but waiting for
899 	 * 200000 TSC cycles is safe:
900 	 * 4 GHz == 50us
901 	 * 1 GHz == 200us
902 	 */
903 	do {
904 		if (t1 != hpet_readl(HPET_COUNTER))
905 			return true;
906 		now = rdtsc();
907 	} while ((now - start) < 200000UL);
908 
909 	pr_warn("Counter not counting. HPET disabled\n");
910 	return false;
911 }
912 
913 static bool __init mwait_pc10_supported(void)
914 {
915 	unsigned int eax, ebx, ecx, mwait_substates;
916 
917 	if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
918 		return false;
919 
920 	if (!cpu_feature_enabled(X86_FEATURE_MWAIT))
921 		return false;
922 
923 	cpuid(CPUID_LEAF_MWAIT, &eax, &ebx, &ecx, &mwait_substates);
924 
925 	return (ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED) &&
926 	       (ecx & CPUID5_ECX_INTERRUPT_BREAK) &&
927 	       (mwait_substates & (0xF << 28));
928 }
929 
930 /*
931  * Check whether the system supports PC10. If so force disable HPET as that
932  * stops counting in PC10. This check is overbroad as it does not take any
933  * of the following into account:
934  *
935  *	- ACPI tables
936  *	- Enablement of intel_idle
937  *	- Command line arguments which limit intel_idle C-state support
938  *
939  * That's perfectly fine. HPET is a piece of hardware designed by committee
940  * and the only reasons why it is still in use on modern systems is the
941  * fact that it is impossible to reliably query TSC and CPU frequency via
942  * CPUID or firmware.
943  *
944  * If HPET is functional it is useful for calibrating TSC, but this can be
945  * done via PMTIMER as well which seems to be the last remaining timer on
946  * X86/INTEL platforms that has not been completely wreckaged by feature
947  * creep.
948  *
949  * In theory HPET support should be removed altogether, but there are older
950  * systems out there which depend on it because TSC and APIC timer are
951  * dysfunctional in deeper C-states.
952  *
953  * It's only 20 years now that hardware people have been asked to provide
954  * reliable and discoverable facilities which can be used for timekeeping
955  * and per CPU timer interrupts.
956  *
957  * The probability that this problem is going to be solved in the
958  * foreseeable future is close to zero, so the kernel has to be cluttered
959  * with heuristics to keep up with the ever growing amount of hardware and
960  * firmware trainwrecks. Hopefully some day hardware people will understand
961  * that the approach of "This can be fixed in software" is not sustainable.
962  * Hope dies last...
963  */
964 static bool __init hpet_is_pc10_damaged(void)
965 {
966 	unsigned long long pcfg;
967 
968 	/* Check whether PC10 substates are supported */
969 	if (!mwait_pc10_supported())
970 		return false;
971 
972 	/* Check whether PC10 is enabled in PKG C-state limit */
973 	rdmsrl(MSR_PKG_CST_CONFIG_CONTROL, pcfg);
974 	if ((pcfg & 0xF) < 8)
975 		return false;
976 
977 	if (hpet_force_user) {
978 		pr_warn("HPET force enabled via command line, but dysfunctional in PC10.\n");
979 		return false;
980 	}
981 
982 	pr_info("HPET dysfunctional in PC10. Force disabled.\n");
983 	boot_hpet_disable = true;
984 	return true;
985 }
986 
987 /**
988  * hpet_enable - Try to setup the HPET timer. Returns 1 on success.
989  */
990 int __init hpet_enable(void)
991 {
992 	u32 hpet_period, cfg, id, irq;
993 	unsigned int i, channels;
994 	struct hpet_channel *hc;
995 	u64 freq;
996 
997 	if (!is_hpet_capable())
998 		return 0;
999 
1000 	if (hpet_is_pc10_damaged())
1001 		return 0;
1002 
1003 	hpet_set_mapping();
1004 	if (!hpet_virt_address)
1005 		return 0;
1006 
1007 	/* Validate that the config register is working */
1008 	if (!hpet_cfg_working())
1009 		goto out_nohpet;
1010 
1011 	/*
1012 	 * Read the period and check for a sane value:
1013 	 */
1014 	hpet_period = hpet_readl(HPET_PERIOD);
1015 	if (hpet_period < HPET_MIN_PERIOD || hpet_period > HPET_MAX_PERIOD)
1016 		goto out_nohpet;
1017 
1018 	/* The period is a femtoseconds value. Convert it to a frequency. */
1019 	freq = FSEC_PER_SEC;
1020 	do_div(freq, hpet_period);
1021 	hpet_freq = freq;
1022 
1023 	/*
1024 	 * Read the HPET ID register to retrieve the IRQ routing
1025 	 * information and the number of channels
1026 	 */
1027 	id = hpet_readl(HPET_ID);
1028 	hpet_print_config();
1029 
1030 	/* This is the HPET channel number which is zero based */
1031 	channels = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1;
1032 
1033 	/*
1034 	 * The legacy routing mode needs at least two channels, tick timer
1035 	 * and the rtc emulation channel.
1036 	 */
1037 	if (IS_ENABLED(CONFIG_HPET_EMULATE_RTC) && channels < 2)
1038 		goto out_nohpet;
1039 
1040 	hc = kcalloc(channels, sizeof(*hc), GFP_KERNEL);
1041 	if (!hc) {
1042 		pr_warn("Disabling HPET.\n");
1043 		goto out_nohpet;
1044 	}
1045 	hpet_base.channels = hc;
1046 	hpet_base.nr_channels = channels;
1047 
1048 	/* Read, store and sanitize the global configuration */
1049 	cfg = hpet_readl(HPET_CFG);
1050 	hpet_base.boot_cfg = cfg;
1051 	cfg &= ~(HPET_CFG_ENABLE | HPET_CFG_LEGACY);
1052 	hpet_writel(cfg, HPET_CFG);
1053 	if (cfg)
1054 		pr_warn("Global config: Unknown bits %#x\n", cfg);
1055 
1056 	/* Read, store and sanitize the per channel configuration */
1057 	for (i = 0; i < channels; i++, hc++) {
1058 		hc->num = i;
1059 
1060 		cfg = hpet_readl(HPET_Tn_CFG(i));
1061 		hc->boot_cfg = cfg;
1062 		irq = (cfg & Tn_INT_ROUTE_CNF_MASK) >> Tn_INT_ROUTE_CNF_SHIFT;
1063 		hc->irq = irq;
1064 
1065 		cfg &= ~(HPET_TN_ENABLE | HPET_TN_LEVEL | HPET_TN_FSB);
1066 		hpet_writel(cfg, HPET_Tn_CFG(i));
1067 
1068 		cfg &= ~(HPET_TN_PERIODIC | HPET_TN_PERIODIC_CAP
1069 			 | HPET_TN_64BIT_CAP | HPET_TN_32BIT | HPET_TN_ROUTE
1070 			 | HPET_TN_FSB | HPET_TN_FSB_CAP);
1071 		if (cfg)
1072 			pr_warn("Channel #%u config: Unknown bits %#x\n", i, cfg);
1073 	}
1074 	hpet_print_config();
1075 
1076 	/*
1077 	 * Validate that the counter is counting. This needs to be done
1078 	 * after sanitizing the config registers to properly deal with
1079 	 * force enabled HPETs.
1080 	 */
1081 	if (!hpet_counting())
1082 		goto out_nohpet;
1083 
1084 	if (tsc_clocksource_watchdog_disabled())
1085 		clocksource_hpet.flags |= CLOCK_SOURCE_MUST_VERIFY;
1086 	clocksource_register_hz(&clocksource_hpet, (u32)hpet_freq);
1087 
1088 	if (id & HPET_ID_LEGSUP) {
1089 		hpet_legacy_clockevent_register(&hpet_base.channels[0]);
1090 		hpet_base.channels[0].mode = HPET_MODE_LEGACY;
1091 		if (IS_ENABLED(CONFIG_HPET_EMULATE_RTC))
1092 			hpet_base.channels[1].mode = HPET_MODE_LEGACY;
1093 		return 1;
1094 	}
1095 	return 0;
1096 
1097 out_nohpet:
1098 	kfree(hpet_base.channels);
1099 	hpet_base.channels = NULL;
1100 	hpet_base.nr_channels = 0;
1101 	hpet_clear_mapping();
1102 	hpet_address = 0;
1103 	return 0;
1104 }
1105 
1106 /*
1107  * The late initialization runs after the PCI quirks have been invoked
1108  * which might have detected a system on which the HPET can be enforced.
1109  *
1110  * Also, the MSI machinery is not working yet when the HPET is initialized
1111  * early.
1112  *
1113  * If the HPET is enabled, then:
1114  *
1115  *  1) Reserve one channel for /dev/hpet if CONFIG_HPET=y
1116  *  2) Reserve up to num_possible_cpus() channels as per CPU clockevents
1117  *  3) Setup /dev/hpet if CONFIG_HPET=y
1118  *  4) Register hotplug callbacks when clockevents are available
1119  */
1120 static __init int hpet_late_init(void)
1121 {
1122 	int ret;
1123 
1124 	if (!hpet_address) {
1125 		if (!force_hpet_address)
1126 			return -ENODEV;
1127 
1128 		hpet_address = force_hpet_address;
1129 		hpet_enable();
1130 	}
1131 
1132 	if (!hpet_virt_address)
1133 		return -ENODEV;
1134 
1135 	hpet_select_device_channel();
1136 	hpet_select_clockevents();
1137 	hpet_reserve_platform_timers();
1138 	hpet_print_config();
1139 
1140 	if (!hpet_base.nr_clockevents)
1141 		return 0;
1142 
1143 	ret = cpuhp_setup_state(CPUHP_AP_X86_HPET_ONLINE, "x86/hpet:online",
1144 				hpet_cpuhp_online, NULL);
1145 	if (ret)
1146 		return ret;
1147 	ret = cpuhp_setup_state(CPUHP_X86_HPET_DEAD, "x86/hpet:dead", NULL,
1148 				hpet_cpuhp_dead);
1149 	if (ret)
1150 		goto err_cpuhp;
1151 	return 0;
1152 
1153 err_cpuhp:
1154 	cpuhp_remove_state(CPUHP_AP_X86_HPET_ONLINE);
1155 	return ret;
1156 }
1157 fs_initcall(hpet_late_init);
1158 
1159 void hpet_disable(void)
1160 {
1161 	unsigned int i;
1162 	u32 cfg;
1163 
1164 	if (!is_hpet_capable() || !hpet_virt_address)
1165 		return;
1166 
1167 	/* Restore boot configuration with the enable bit cleared */
1168 	cfg = hpet_base.boot_cfg;
1169 	cfg &= ~HPET_CFG_ENABLE;
1170 	hpet_writel(cfg, HPET_CFG);
1171 
1172 	/* Restore the channel boot configuration */
1173 	for (i = 0; i < hpet_base.nr_channels; i++)
1174 		hpet_writel(hpet_base.channels[i].boot_cfg, HPET_Tn_CFG(i));
1175 
1176 	/* If the HPET was enabled at boot time, reenable it */
1177 	if (hpet_base.boot_cfg & HPET_CFG_ENABLE)
1178 		hpet_writel(hpet_base.boot_cfg, HPET_CFG);
1179 }
1180 
1181 #ifdef CONFIG_HPET_EMULATE_RTC
1182 
1183 /*
1184  * HPET in LegacyReplacement mode eats up the RTC interrupt line. When HPET
1185  * is enabled, we support RTC interrupt functionality in software.
1186  *
1187  * RTC has 3 kinds of interrupts:
1188  *
1189  *  1) Update Interrupt - generate an interrupt, every second, when the
1190  *     RTC clock is updated
1191  *  2) Alarm Interrupt - generate an interrupt at a specific time of day
1192  *  3) Periodic Interrupt - generate periodic interrupt, with frequencies
1193  *     2Hz-8192Hz (2Hz-64Hz for non-root user) (all frequencies in powers of 2)
1194  *
1195  * (1) and (2) above are implemented using polling at a frequency of 64 Hz:
1196  * DEFAULT_RTC_INT_FREQ.
1197  *
1198  * The exact frequency is a tradeoff between accuracy and interrupt overhead.
1199  *
1200  * For (3), we use interrupts at 64 Hz, or the user specified periodic frequency,
1201  * if it's higher.
1202  */
1203 #include <linux/mc146818rtc.h>
1204 #include <linux/rtc.h>
1205 
1206 #define DEFAULT_RTC_INT_FREQ	64
1207 #define DEFAULT_RTC_SHIFT	6
1208 #define RTC_NUM_INTS		1
1209 
1210 static unsigned long hpet_rtc_flags;
1211 static int hpet_prev_update_sec;
1212 static struct rtc_time hpet_alarm_time;
1213 static unsigned long hpet_pie_count;
1214 static u32 hpet_t1_cmp;
1215 static u32 hpet_default_delta;
1216 static u32 hpet_pie_delta;
1217 static unsigned long hpet_pie_limit;
1218 
1219 static rtc_irq_handler irq_handler;
1220 
1221 /*
1222  * Check that the HPET counter c1 is ahead of c2
1223  */
1224 static inline int hpet_cnt_ahead(u32 c1, u32 c2)
1225 {
1226 	return (s32)(c2 - c1) < 0;
1227 }
1228 
1229 /*
1230  * Registers a IRQ handler.
1231  */
1232 int hpet_register_irq_handler(rtc_irq_handler handler)
1233 {
1234 	if (!is_hpet_enabled())
1235 		return -ENODEV;
1236 	if (irq_handler)
1237 		return -EBUSY;
1238 
1239 	irq_handler = handler;
1240 
1241 	return 0;
1242 }
1243 EXPORT_SYMBOL_GPL(hpet_register_irq_handler);
1244 
1245 /*
1246  * Deregisters the IRQ handler registered with hpet_register_irq_handler()
1247  * and does cleanup.
1248  */
1249 void hpet_unregister_irq_handler(rtc_irq_handler handler)
1250 {
1251 	if (!is_hpet_enabled())
1252 		return;
1253 
1254 	irq_handler = NULL;
1255 	hpet_rtc_flags = 0;
1256 }
1257 EXPORT_SYMBOL_GPL(hpet_unregister_irq_handler);
1258 
1259 /*
1260  * Channel 1 for RTC emulation. We use one shot mode, as periodic mode
1261  * is not supported by all HPET implementations for channel 1.
1262  *
1263  * hpet_rtc_timer_init() is called when the rtc is initialized.
1264  */
1265 int hpet_rtc_timer_init(void)
1266 {
1267 	unsigned int cfg, cnt, delta;
1268 	unsigned long flags;
1269 
1270 	if (!is_hpet_enabled())
1271 		return 0;
1272 
1273 	if (!hpet_default_delta) {
1274 		struct clock_event_device *evt = &hpet_base.channels[0].evt;
1275 		uint64_t clc;
1276 
1277 		clc = (uint64_t) evt->mult * NSEC_PER_SEC;
1278 		clc >>= evt->shift + DEFAULT_RTC_SHIFT;
1279 		hpet_default_delta = clc;
1280 	}
1281 
1282 	if (!(hpet_rtc_flags & RTC_PIE) || hpet_pie_limit)
1283 		delta = hpet_default_delta;
1284 	else
1285 		delta = hpet_pie_delta;
1286 
1287 	local_irq_save(flags);
1288 
1289 	cnt = delta + hpet_readl(HPET_COUNTER);
1290 	hpet_writel(cnt, HPET_T1_CMP);
1291 	hpet_t1_cmp = cnt;
1292 
1293 	cfg = hpet_readl(HPET_T1_CFG);
1294 	cfg &= ~HPET_TN_PERIODIC;
1295 	cfg |= HPET_TN_ENABLE | HPET_TN_32BIT;
1296 	hpet_writel(cfg, HPET_T1_CFG);
1297 
1298 	local_irq_restore(flags);
1299 
1300 	return 1;
1301 }
1302 EXPORT_SYMBOL_GPL(hpet_rtc_timer_init);
1303 
1304 static void hpet_disable_rtc_channel(void)
1305 {
1306 	u32 cfg = hpet_readl(HPET_T1_CFG);
1307 
1308 	cfg &= ~HPET_TN_ENABLE;
1309 	hpet_writel(cfg, HPET_T1_CFG);
1310 }
1311 
1312 /*
1313  * The functions below are called from rtc driver.
1314  * Return 0 if HPET is not being used.
1315  * Otherwise do the necessary changes and return 1.
1316  */
1317 int hpet_mask_rtc_irq_bit(unsigned long bit_mask)
1318 {
1319 	if (!is_hpet_enabled())
1320 		return 0;
1321 
1322 	hpet_rtc_flags &= ~bit_mask;
1323 	if (unlikely(!hpet_rtc_flags))
1324 		hpet_disable_rtc_channel();
1325 
1326 	return 1;
1327 }
1328 EXPORT_SYMBOL_GPL(hpet_mask_rtc_irq_bit);
1329 
1330 int hpet_set_rtc_irq_bit(unsigned long bit_mask)
1331 {
1332 	unsigned long oldbits = hpet_rtc_flags;
1333 
1334 	if (!is_hpet_enabled())
1335 		return 0;
1336 
1337 	hpet_rtc_flags |= bit_mask;
1338 
1339 	if ((bit_mask & RTC_UIE) && !(oldbits & RTC_UIE))
1340 		hpet_prev_update_sec = -1;
1341 
1342 	if (!oldbits)
1343 		hpet_rtc_timer_init();
1344 
1345 	return 1;
1346 }
1347 EXPORT_SYMBOL_GPL(hpet_set_rtc_irq_bit);
1348 
1349 int hpet_set_alarm_time(unsigned char hrs, unsigned char min, unsigned char sec)
1350 {
1351 	if (!is_hpet_enabled())
1352 		return 0;
1353 
1354 	hpet_alarm_time.tm_hour = hrs;
1355 	hpet_alarm_time.tm_min = min;
1356 	hpet_alarm_time.tm_sec = sec;
1357 
1358 	return 1;
1359 }
1360 EXPORT_SYMBOL_GPL(hpet_set_alarm_time);
1361 
1362 int hpet_set_periodic_freq(unsigned long freq)
1363 {
1364 	uint64_t clc;
1365 
1366 	if (!is_hpet_enabled())
1367 		return 0;
1368 
1369 	if (freq <= DEFAULT_RTC_INT_FREQ) {
1370 		hpet_pie_limit = DEFAULT_RTC_INT_FREQ / freq;
1371 	} else {
1372 		struct clock_event_device *evt = &hpet_base.channels[0].evt;
1373 
1374 		clc = (uint64_t) evt->mult * NSEC_PER_SEC;
1375 		do_div(clc, freq);
1376 		clc >>= evt->shift;
1377 		hpet_pie_delta = clc;
1378 		hpet_pie_limit = 0;
1379 	}
1380 
1381 	return 1;
1382 }
1383 EXPORT_SYMBOL_GPL(hpet_set_periodic_freq);
1384 
1385 int hpet_rtc_dropped_irq(void)
1386 {
1387 	return is_hpet_enabled();
1388 }
1389 EXPORT_SYMBOL_GPL(hpet_rtc_dropped_irq);
1390 
1391 static void hpet_rtc_timer_reinit(void)
1392 {
1393 	unsigned int delta;
1394 	int lost_ints = -1;
1395 
1396 	if (unlikely(!hpet_rtc_flags))
1397 		hpet_disable_rtc_channel();
1398 
1399 	if (!(hpet_rtc_flags & RTC_PIE) || hpet_pie_limit)
1400 		delta = hpet_default_delta;
1401 	else
1402 		delta = hpet_pie_delta;
1403 
1404 	/*
1405 	 * Increment the comparator value until we are ahead of the
1406 	 * current count.
1407 	 */
1408 	do {
1409 		hpet_t1_cmp += delta;
1410 		hpet_writel(hpet_t1_cmp, HPET_T1_CMP);
1411 		lost_ints++;
1412 	} while (!hpet_cnt_ahead(hpet_t1_cmp, hpet_readl(HPET_COUNTER)));
1413 
1414 	if (lost_ints) {
1415 		if (hpet_rtc_flags & RTC_PIE)
1416 			hpet_pie_count += lost_ints;
1417 		if (printk_ratelimit())
1418 			pr_warn("Lost %d RTC interrupts\n", lost_ints);
1419 	}
1420 }
1421 
1422 irqreturn_t hpet_rtc_interrupt(int irq, void *dev_id)
1423 {
1424 	struct rtc_time curr_time;
1425 	unsigned long rtc_int_flag = 0;
1426 
1427 	hpet_rtc_timer_reinit();
1428 	memset(&curr_time, 0, sizeof(struct rtc_time));
1429 
1430 	if (hpet_rtc_flags & (RTC_UIE | RTC_AIE)) {
1431 		if (unlikely(mc146818_get_time(&curr_time, 10) < 0)) {
1432 			pr_err_ratelimited("unable to read current time from RTC\n");
1433 			return IRQ_HANDLED;
1434 		}
1435 	}
1436 
1437 	if (hpet_rtc_flags & RTC_UIE &&
1438 	    curr_time.tm_sec != hpet_prev_update_sec) {
1439 		if (hpet_prev_update_sec >= 0)
1440 			rtc_int_flag = RTC_UF;
1441 		hpet_prev_update_sec = curr_time.tm_sec;
1442 	}
1443 
1444 	if (hpet_rtc_flags & RTC_PIE && ++hpet_pie_count >= hpet_pie_limit) {
1445 		rtc_int_flag |= RTC_PF;
1446 		hpet_pie_count = 0;
1447 	}
1448 
1449 	if (hpet_rtc_flags & RTC_AIE &&
1450 	    (curr_time.tm_sec == hpet_alarm_time.tm_sec) &&
1451 	    (curr_time.tm_min == hpet_alarm_time.tm_min) &&
1452 	    (curr_time.tm_hour == hpet_alarm_time.tm_hour))
1453 		rtc_int_flag |= RTC_AF;
1454 
1455 	if (rtc_int_flag) {
1456 		rtc_int_flag |= (RTC_IRQF | (RTC_NUM_INTS << 8));
1457 		if (irq_handler)
1458 			irq_handler(rtc_int_flag, dev_id);
1459 	}
1460 	return IRQ_HANDLED;
1461 }
1462 EXPORT_SYMBOL_GPL(hpet_rtc_interrupt);
1463 #endif
1464