59a81d7fd05b1330a83e3d6da92de82816bf9acf
[sfrench/cifs-2.6.git] / arch / x86 / kernel / hpet.c
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/hpet.h>
11 #include <asm/time.h>
12
13 #undef  pr_fmt
14 #define pr_fmt(fmt) "hpet: " fmt
15
16 struct hpet_dev {
17         struct clock_event_device       evt;
18         unsigned int                    num;
19         int                             cpu;
20         unsigned int                    irq;
21         unsigned int                    flags;
22         char                            name[10];
23 };
24
25 struct hpet_channel {
26         unsigned int                    num;
27         unsigned int                    boot_cfg;
28 };
29
30 struct hpet_base {
31         unsigned int                    nr_channels;
32         unsigned int                    boot_cfg;
33         struct hpet_channel             *channels;
34 };
35
36 #define HPET_MASK                       CLOCKSOURCE_MASK(32)
37
38 #define HPET_DEV_USED_BIT               2
39 #define HPET_DEV_USED                   (1 << HPET_DEV_USED_BIT)
40 #define HPET_DEV_VALID                  0x8
41 #define HPET_DEV_FSB_CAP                0x1000
42 #define HPET_DEV_PERI_CAP               0x2000
43
44 #define HPET_MIN_CYCLES                 128
45 #define HPET_MIN_PROG_DELTA             (HPET_MIN_CYCLES + (HPET_MIN_CYCLES >> 1))
46
47 /*
48  * HPET address is set in acpi/boot.c, when an ACPI entry exists
49  */
50 unsigned long                           hpet_address;
51 u8                                      hpet_blockid; /* OS timer block num */
52 bool                                    hpet_msi_disable;
53
54 #ifdef CONFIG_PCI_MSI
55 static unsigned int                     hpet_num_timers;
56 static struct hpet_dev                  *hpet_devs;
57 static DEFINE_PER_CPU(struct hpet_dev *, cpu_hpet_dev);
58 static struct irq_domain                *hpet_domain;
59 #endif
60
61 static void __iomem                     *hpet_virt_address;
62 static struct hpet_base                 hpet_base;
63
64 static bool                             hpet_legacy_int_enabled;
65 static unsigned long                    hpet_freq;
66
67 bool                                    boot_hpet_disable;
68 bool                                    hpet_force_user;
69 static bool                             hpet_verbose;
70
71 static struct clock_event_device        hpet_clockevent;
72
73 static inline
74 struct hpet_dev *clockevent_to_channel(struct clock_event_device *evt)
75 {
76         return container_of(evt, struct hpet_dev, evt);
77 }
78
79 inline unsigned int hpet_readl(unsigned int a)
80 {
81         return readl(hpet_virt_address + a);
82 }
83
84 static inline void hpet_writel(unsigned int d, unsigned int a)
85 {
86         writel(d, hpet_virt_address + a);
87 }
88
89 static inline void hpet_set_mapping(void)
90 {
91         hpet_virt_address = ioremap_nocache(hpet_address, HPET_MMAP_SIZE);
92 }
93
94 static inline void hpet_clear_mapping(void)
95 {
96         iounmap(hpet_virt_address);
97         hpet_virt_address = NULL;
98 }
99
100 /*
101  * HPET command line enable / disable
102  */
103 static int __init hpet_setup(char *str)
104 {
105         while (str) {
106                 char *next = strchr(str, ',');
107
108                 if (next)
109                         *next++ = 0;
110                 if (!strncmp("disable", str, 7))
111                         boot_hpet_disable = true;
112                 if (!strncmp("force", str, 5))
113                         hpet_force_user = true;
114                 if (!strncmp("verbose", str, 7))
115                         hpet_verbose = true;
116                 str = next;
117         }
118         return 1;
119 }
120 __setup("hpet=", hpet_setup);
121
122 static int __init disable_hpet(char *str)
123 {
124         boot_hpet_disable = true;
125         return 1;
126 }
127 __setup("nohpet", disable_hpet);
128
129 static inline int is_hpet_capable(void)
130 {
131         return !boot_hpet_disable && hpet_address;
132 }
133
134 /**
135  * is_hpet_enabled - Check whether the legacy HPET timer interrupt is enabled
136  */
137 int is_hpet_enabled(void)
138 {
139         return is_hpet_capable() && hpet_legacy_int_enabled;
140 }
141 EXPORT_SYMBOL_GPL(is_hpet_enabled);
142
143 static void _hpet_print_config(const char *function, int line)
144 {
145         u32 i, id, period, cfg, status, channels, l, h;
146
147         pr_info("%s(%d):\n", function, line);
148
149         id = hpet_readl(HPET_ID);
150         period = hpet_readl(HPET_PERIOD);
151         pr_info("ID: 0x%x, PERIOD: 0x%x\n", id, period);
152
153         cfg = hpet_readl(HPET_CFG);
154         status = hpet_readl(HPET_STATUS);
155         pr_info("CFG: 0x%x, STATUS: 0x%x\n", cfg, status);
156
157         l = hpet_readl(HPET_COUNTER);
158         h = hpet_readl(HPET_COUNTER+4);
159         pr_info("COUNTER_l: 0x%x, COUNTER_h: 0x%x\n", l, h);
160
161         channels = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1;
162
163         for (i = 0; i < channels; i++) {
164                 l = hpet_readl(HPET_Tn_CFG(i));
165                 h = hpet_readl(HPET_Tn_CFG(i)+4);
166                 pr_info("T%d: CFG_l: 0x%x, CFG_h: 0x%x\n", i, l, h);
167
168                 l = hpet_readl(HPET_Tn_CMP(i));
169                 h = hpet_readl(HPET_Tn_CMP(i)+4);
170                 pr_info("T%d: CMP_l: 0x%x, CMP_h: 0x%x\n", i, l, h);
171
172                 l = hpet_readl(HPET_Tn_ROUTE(i));
173                 h = hpet_readl(HPET_Tn_ROUTE(i)+4);
174                 pr_info("T%d ROUTE_l: 0x%x, ROUTE_h: 0x%x\n", i, l, h);
175         }
176 }
177
178 #define hpet_print_config()                                     \
179 do {                                                            \
180         if (hpet_verbose)                                       \
181                 _hpet_print_config(__func__, __LINE__); \
182 } while (0)
183
184 /*
185  * When the HPET driver (/dev/hpet) is enabled, we need to reserve
186  * timer 0 and timer 1 in case of RTC emulation.
187  */
188 #ifdef CONFIG_HPET
189
190 static void hpet_reserve_msi_timers(struct hpet_data *hd);
191
192 static void __init hpet_reserve_platform_timers(unsigned int id)
193 {
194         struct hpet __iomem *hpet = hpet_virt_address;
195         struct hpet_timer __iomem *timer = &hpet->hpet_timers[2];
196         unsigned int nrtimers, i;
197         struct hpet_data hd;
198
199         nrtimers = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1;
200
201         memset(&hd, 0, sizeof(hd));
202         hd.hd_phys_address      = hpet_address;
203         hd.hd_address           = hpet;
204         hd.hd_nirqs             = nrtimers;
205         hpet_reserve_timer(&hd, 0);
206
207 #ifdef CONFIG_HPET_EMULATE_RTC
208         hpet_reserve_timer(&hd, 1);
209 #endif
210
211         /*
212          * NOTE that hd_irq[] reflects IOAPIC input pins (LEGACY_8254
213          * is wrong for i8259!) not the output IRQ.  Many BIOS writers
214          * don't bother configuring *any* comparator interrupts.
215          */
216         hd.hd_irq[0] = HPET_LEGACY_8254;
217         hd.hd_irq[1] = HPET_LEGACY_RTC;
218
219         for (i = 2; i < nrtimers; timer++, i++) {
220                 hd.hd_irq[i] = (readl(&timer->hpet_config) &
221                         Tn_INT_ROUTE_CNF_MASK) >> Tn_INT_ROUTE_CNF_SHIFT;
222         }
223
224         hpet_reserve_msi_timers(&hd);
225
226         hpet_alloc(&hd);
227
228 }
229 #else
230 static void hpet_reserve_platform_timers(unsigned int id) { }
231 #endif
232
233 /* Common HPET functions */
234 static void hpet_stop_counter(void)
235 {
236         u32 cfg = hpet_readl(HPET_CFG);
237
238         cfg &= ~HPET_CFG_ENABLE;
239         hpet_writel(cfg, HPET_CFG);
240 }
241
242 static void hpet_reset_counter(void)
243 {
244         hpet_writel(0, HPET_COUNTER);
245         hpet_writel(0, HPET_COUNTER + 4);
246 }
247
248 static void hpet_start_counter(void)
249 {
250         unsigned int cfg = hpet_readl(HPET_CFG);
251
252         cfg |= HPET_CFG_ENABLE;
253         hpet_writel(cfg, HPET_CFG);
254 }
255
256 static void hpet_restart_counter(void)
257 {
258         hpet_stop_counter();
259         hpet_reset_counter();
260         hpet_start_counter();
261 }
262
263 static void hpet_resume_device(void)
264 {
265         force_hpet_resume();
266 }
267
268 static void hpet_resume_counter(struct clocksource *cs)
269 {
270         hpet_resume_device();
271         hpet_restart_counter();
272 }
273
274 static void hpet_enable_legacy_int(void)
275 {
276         unsigned int cfg = hpet_readl(HPET_CFG);
277
278         cfg |= HPET_CFG_LEGACY;
279         hpet_writel(cfg, HPET_CFG);
280         hpet_legacy_int_enabled = true;
281 }
282
283 static void hpet_legacy_clockevent_register(void)
284 {
285         /* Start HPET legacy interrupts */
286         hpet_enable_legacy_int();
287
288         /*
289          * Start HPET with the boot CPU's cpumask and make it global after
290          * the IO_APIC has been initialized.
291          */
292         hpet_clockevent.cpumask = cpumask_of(boot_cpu_data.cpu_index);
293         clockevents_config_and_register(&hpet_clockevent, hpet_freq,
294                                         HPET_MIN_PROG_DELTA, 0x7FFFFFFF);
295         global_clock_event = &hpet_clockevent;
296         pr_debug("Clockevent registered\n");
297 }
298
299 static int hpet_set_periodic(struct clock_event_device *evt, int timer)
300 {
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(timer));
310         cfg |= HPET_TN_ENABLE | HPET_TN_PERIODIC | HPET_TN_SETVAL |
311                HPET_TN_32BIT;
312         hpet_writel(cfg, HPET_Tn_CFG(timer));
313         hpet_writel(cmp, HPET_Tn_CMP(timer));
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(timer));
323         hpet_start_counter();
324         hpet_print_config();
325
326         return 0;
327 }
328
329 static int hpet_set_oneshot(struct clock_event_device *evt, int timer)
330 {
331         unsigned int cfg;
332
333         cfg = hpet_readl(HPET_Tn_CFG(timer));
334         cfg &= ~HPET_TN_PERIODIC;
335         cfg |= HPET_TN_ENABLE | HPET_TN_32BIT;
336         hpet_writel(cfg, HPET_Tn_CFG(timer));
337
338         return 0;
339 }
340
341 static int hpet_shutdown(struct clock_event_device *evt, int timer)
342 {
343         unsigned int cfg;
344
345         cfg = hpet_readl(HPET_Tn_CFG(timer));
346         cfg &= ~HPET_TN_ENABLE;
347         hpet_writel(cfg, HPET_Tn_CFG(timer));
348
349         return 0;
350 }
351
352 static int hpet_resume(struct clock_event_device *evt)
353 {
354         hpet_enable_legacy_int();
355         hpet_print_config();
356         return 0;
357 }
358
359 static int hpet_next_event(unsigned long delta, int channel)
360 {
361         u32 cnt;
362         s32 res;
363
364         cnt = hpet_readl(HPET_COUNTER);
365         cnt += (u32) delta;
366         hpet_writel(cnt, HPET_Tn_CMP(channel));
367
368         /*
369          * HPETs are a complete disaster. The compare register is
370          * based on a equal comparison and neither provides a less
371          * than or equal functionality (which would require to take
372          * the wraparound into account) nor a simple count down event
373          * mode. Further the write to the comparator register is
374          * delayed internally up to two HPET clock cycles in certain
375          * chipsets (ATI, ICH9,10). Some newer AMD chipsets have even
376          * longer delays. We worked around that by reading back the
377          * compare register, but that required another workaround for
378          * ICH9,10 chips where the first readout after write can
379          * return the old stale value. We already had a minimum
380          * programming delta of 5us enforced, but a NMI or SMI hitting
381          * between the counter readout and the comparator write can
382          * move us behind that point easily. Now instead of reading
383          * the compare register back several times, we make the ETIME
384          * decision based on the following: Return ETIME if the
385          * counter value after the write is less than HPET_MIN_CYCLES
386          * away from the event or if the counter is already ahead of
387          * the event. The minimum programming delta for the generic
388          * clockevents code is set to 1.5 * HPET_MIN_CYCLES.
389          */
390         res = (s32)(cnt - hpet_readl(HPET_COUNTER));
391
392         return res < HPET_MIN_CYCLES ? -ETIME : 0;
393 }
394
395 static int hpet_legacy_shutdown(struct clock_event_device *evt)
396 {
397         return hpet_shutdown(evt, 0);
398 }
399
400 static int hpet_legacy_set_oneshot(struct clock_event_device *evt)
401 {
402         return hpet_set_oneshot(evt, 0);
403 }
404
405 static int hpet_legacy_set_periodic(struct clock_event_device *evt)
406 {
407         return hpet_set_periodic(evt, 0);
408 }
409
410 static int hpet_legacy_resume(struct clock_event_device *evt)
411 {
412         return hpet_resume(evt);
413 }
414
415 static int hpet_legacy_next_event(unsigned long delta,
416                                   struct clock_event_device *evt)
417 {
418         return hpet_next_event(delta, 0);
419 }
420
421 /*
422  * The HPET clock event device
423  */
424 static struct clock_event_device hpet_clockevent = {
425         .name                   = "hpet",
426         .features               = CLOCK_EVT_FEAT_PERIODIC |
427                                   CLOCK_EVT_FEAT_ONESHOT,
428         .set_state_periodic     = hpet_legacy_set_periodic,
429         .set_state_oneshot      = hpet_legacy_set_oneshot,
430         .set_state_shutdown     = hpet_legacy_shutdown,
431         .tick_resume            = hpet_legacy_resume,
432         .set_next_event         = hpet_legacy_next_event,
433         .irq                    = 0,
434         .rating                 = 50,
435 };
436
437 /*
438  * HPET MSI Support
439  */
440 #ifdef CONFIG_PCI_MSI
441
442 void hpet_msi_unmask(struct irq_data *data)
443 {
444         struct hpet_dev *hdev = irq_data_get_irq_handler_data(data);
445         unsigned int cfg;
446
447         /* unmask it */
448         cfg = hpet_readl(HPET_Tn_CFG(hdev->num));
449         cfg |= HPET_TN_ENABLE | HPET_TN_FSB;
450         hpet_writel(cfg, HPET_Tn_CFG(hdev->num));
451 }
452
453 void hpet_msi_mask(struct irq_data *data)
454 {
455         struct hpet_dev *hdev = irq_data_get_irq_handler_data(data);
456         unsigned int cfg;
457
458         /* mask it */
459         cfg = hpet_readl(HPET_Tn_CFG(hdev->num));
460         cfg &= ~(HPET_TN_ENABLE | HPET_TN_FSB);
461         hpet_writel(cfg, HPET_Tn_CFG(hdev->num));
462 }
463
464 void hpet_msi_write(struct hpet_dev *hdev, struct msi_msg *msg)
465 {
466         hpet_writel(msg->data, HPET_Tn_ROUTE(hdev->num));
467         hpet_writel(msg->address_lo, HPET_Tn_ROUTE(hdev->num) + 4);
468 }
469
470 static int hpet_msi_shutdown(struct clock_event_device *evt)
471 {
472         return hpet_shutdown(evt, clockevent_to_channel(evt)->num);
473 }
474
475 static int hpet_msi_set_oneshot(struct clock_event_device *evt)
476 {
477         return hpet_set_oneshot(evt, clockevent_to_channel(evt)->num);
478 }
479
480 static int hpet_msi_set_periodic(struct clock_event_device *evt)
481 {
482         return hpet_set_periodic(evt, clockevent_to_channel(evt)->num);
483 }
484
485 static int hpet_msi_resume(struct clock_event_device *evt)
486 {
487         struct hpet_dev *hdev = clockevent_to_channel(evt);
488         struct irq_data *data = irq_get_irq_data(hdev->irq);
489         struct msi_msg msg;
490
491         /* Restore the MSI msg and unmask the interrupt */
492         irq_chip_compose_msi_msg(data, &msg);
493         hpet_msi_write(hdev, &msg);
494         hpet_msi_unmask(data);
495         return 0;
496 }
497
498 static int hpet_msi_next_event(unsigned long delta,
499                                struct clock_event_device *evt)
500 {
501         return hpet_next_event(delta, clockevent_to_channel(evt)->num);
502 }
503
504 static irqreturn_t hpet_interrupt_handler(int irq, void *data)
505 {
506         struct hpet_dev *dev = data;
507         struct clock_event_device *evt = &dev->evt;
508
509         if (!evt->event_handler) {
510                 pr_info("Spurious interrupt HPET timer %d\n", dev->num);
511                 return IRQ_HANDLED;
512         }
513
514         evt->event_handler(evt);
515         return IRQ_HANDLED;
516 }
517
518 static int hpet_setup_irq(struct hpet_dev *dev)
519 {
520
521         if (request_irq(dev->irq, hpet_interrupt_handler,
522                         IRQF_TIMER | IRQF_NOBALANCING,
523                         dev->name, dev))
524                 return -1;
525
526         disable_irq(dev->irq);
527         irq_set_affinity(dev->irq, cpumask_of(dev->cpu));
528         enable_irq(dev->irq);
529
530         pr_debug("%s irq %d for MSI\n", dev->name, dev->irq);
531
532         return 0;
533 }
534
535 static void init_one_hpet_msi_clockevent(struct hpet_dev *hdev, int cpu)
536 {
537         struct clock_event_device *evt = &hdev->evt;
538
539         if (!(hdev->flags & HPET_DEV_VALID))
540                 return;
541
542         hdev->cpu = cpu;
543         per_cpu(cpu_hpet_dev, cpu) = hdev;
544         evt->name = hdev->name;
545         hpet_setup_irq(hdev);
546         evt->irq = hdev->irq;
547
548         evt->rating = 110;
549         evt->features = CLOCK_EVT_FEAT_ONESHOT;
550         if (hdev->flags & HPET_DEV_PERI_CAP) {
551                 evt->features |= CLOCK_EVT_FEAT_PERIODIC;
552                 evt->set_state_periodic = hpet_msi_set_periodic;
553         }
554
555         evt->set_state_shutdown = hpet_msi_shutdown;
556         evt->set_state_oneshot = hpet_msi_set_oneshot;
557         evt->tick_resume = hpet_msi_resume;
558         evt->set_next_event = hpet_msi_next_event;
559         evt->cpumask = cpumask_of(hdev->cpu);
560
561         clockevents_config_and_register(evt, hpet_freq, HPET_MIN_PROG_DELTA,
562                                         0x7FFFFFFF);
563 }
564
565 static struct hpet_dev *hpet_get_unused_timer(void)
566 {
567         int i;
568
569         if (!hpet_devs)
570                 return NULL;
571
572         for (i = 0; i < hpet_num_timers; i++) {
573                 struct hpet_dev *hdev = &hpet_devs[i];
574
575                 if (!(hdev->flags & HPET_DEV_VALID))
576                         continue;
577                 if (test_and_set_bit(HPET_DEV_USED_BIT,
578                         (unsigned long *)&hdev->flags))
579                         continue;
580                 return hdev;
581         }
582         return NULL;
583 }
584
585 static int hpet_cpuhp_online(unsigned int cpu)
586 {
587         struct hpet_dev *hdev = hpet_get_unused_timer();
588
589         if (hdev)
590                 init_one_hpet_msi_clockevent(hdev, cpu);
591         return 0;
592 }
593
594 static int hpet_cpuhp_dead(unsigned int cpu)
595 {
596         struct hpet_dev *hdev = per_cpu(cpu_hpet_dev, cpu);
597
598         if (!hdev)
599                 return 0;
600         free_irq(hdev->irq, hdev);
601         hdev->flags &= ~HPET_DEV_USED;
602         per_cpu(cpu_hpet_dev, cpu) = NULL;
603         return 0;
604 }
605
606 #ifdef CONFIG_HPET
607 /* Reserve at least one timer for userspace (/dev/hpet) */
608 #define RESERVE_TIMERS 1
609 #else
610 #define RESERVE_TIMERS 0
611 #endif
612
613 static void __init hpet_msi_capability_lookup(unsigned int start_timer)
614 {
615         unsigned int id;
616         unsigned int num_timers;
617         unsigned int num_timers_used = 0;
618         int i, irq;
619
620         if (hpet_msi_disable)
621                 return;
622
623         if (boot_cpu_has(X86_FEATURE_ARAT))
624                 return;
625         id = hpet_readl(HPET_ID);
626
627         num_timers = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT);
628         num_timers++; /* Value read out starts from 0 */
629         hpet_print_config();
630
631         hpet_domain = hpet_create_irq_domain(hpet_blockid);
632         if (!hpet_domain)
633                 return;
634
635         hpet_devs = kcalloc(num_timers, sizeof(struct hpet_dev), GFP_KERNEL);
636         if (!hpet_devs)
637                 return;
638
639         hpet_num_timers = num_timers;
640
641         for (i = start_timer; i < num_timers - RESERVE_TIMERS; i++) {
642                 struct hpet_dev *hdev = &hpet_devs[num_timers_used];
643                 unsigned int cfg = hpet_readl(HPET_Tn_CFG(i));
644
645                 /* Only consider HPET timer with MSI support */
646                 if (!(cfg & HPET_TN_FSB_CAP))
647                         continue;
648
649                 hdev->flags = 0;
650                 if (cfg & HPET_TN_PERIODIC_CAP)
651                         hdev->flags |= HPET_DEV_PERI_CAP;
652                 sprintf(hdev->name, "hpet%d", i);
653                 hdev->num = i;
654
655                 irq = hpet_assign_irq(hpet_domain, hdev, hdev->num);
656                 if (irq <= 0)
657                         continue;
658
659                 hdev->irq = irq;
660                 hdev->flags |= HPET_DEV_FSB_CAP;
661                 hdev->flags |= HPET_DEV_VALID;
662                 num_timers_used++;
663                 if (num_timers_used == num_possible_cpus())
664                         break;
665         }
666
667         pr_info("%d channels of %d reserved for per-cpu timers\n",
668                 num_timers, num_timers_used);
669 }
670
671 #ifdef CONFIG_HPET
672 static void __init hpet_reserve_msi_timers(struct hpet_data *hd)
673 {
674         int i;
675
676         if (!hpet_devs)
677                 return;
678
679         for (i = 0; i < hpet_num_timers; i++) {
680                 struct hpet_dev *hdev = &hpet_devs[i];
681
682                 if (!(hdev->flags & HPET_DEV_VALID))
683                         continue;
684
685                 hd->hd_irq[hdev->num] = hdev->irq;
686                 hpet_reserve_timer(hd, hdev->num);
687         }
688 }
689 #endif
690
691 #else
692
693 static inline void hpet_msi_capability_lookup(unsigned int start_timer) { }
694
695 #ifdef CONFIG_HPET
696 static inline void hpet_reserve_msi_timers(struct hpet_data *hd) { }
697 #endif
698
699 #define hpet_cpuhp_online       NULL
700 #define hpet_cpuhp_dead         NULL
701
702 #endif
703
704 /*
705  * Clock source related code
706  */
707 #if defined(CONFIG_SMP) && defined(CONFIG_64BIT)
708 /*
709  * Reading the HPET counter is a very slow operation. If a large number of
710  * CPUs are trying to access the HPET counter simultaneously, it can cause
711  * massive delays and slow down system performance dramatically. This may
712  * happen when HPET is the default clock source instead of TSC. For a
713  * really large system with hundreds of CPUs, the slowdown may be so
714  * severe, that it can actually crash the system because of a NMI watchdog
715  * soft lockup, for example.
716  *
717  * If multiple CPUs are trying to access the HPET counter at the same time,
718  * we don't actually need to read the counter multiple times. Instead, the
719  * other CPUs can use the counter value read by the first CPU in the group.
720  *
721  * This special feature is only enabled on x86-64 systems. It is unlikely
722  * that 32-bit x86 systems will have enough CPUs to require this feature
723  * with its associated locking overhead. We also need 64-bit atomic read.
724  *
725  * The lock and the HPET value are stored together and can be read in a
726  * single atomic 64-bit read. It is explicitly assumed that arch_spinlock_t
727  * is 32 bits in size.
728  */
729 union hpet_lock {
730         struct {
731                 arch_spinlock_t lock;
732                 u32 value;
733         };
734         u64 lockval;
735 };
736
737 static union hpet_lock hpet __cacheline_aligned = {
738         { .lock = __ARCH_SPIN_LOCK_UNLOCKED, },
739 };
740
741 static u64 read_hpet(struct clocksource *cs)
742 {
743         unsigned long flags;
744         union hpet_lock old, new;
745
746         BUILD_BUG_ON(sizeof(union hpet_lock) != 8);
747
748         /*
749          * Read HPET directly if in NMI.
750          */
751         if (in_nmi())
752                 return (u64)hpet_readl(HPET_COUNTER);
753
754         /*
755          * Read the current state of the lock and HPET value atomically.
756          */
757         old.lockval = READ_ONCE(hpet.lockval);
758
759         if (arch_spin_is_locked(&old.lock))
760                 goto contended;
761
762         local_irq_save(flags);
763         if (arch_spin_trylock(&hpet.lock)) {
764                 new.value = hpet_readl(HPET_COUNTER);
765                 /*
766                  * Use WRITE_ONCE() to prevent store tearing.
767                  */
768                 WRITE_ONCE(hpet.value, new.value);
769                 arch_spin_unlock(&hpet.lock);
770                 local_irq_restore(flags);
771                 return (u64)new.value;
772         }
773         local_irq_restore(flags);
774
775 contended:
776         /*
777          * Contended case
778          * --------------
779          * Wait until the HPET value change or the lock is free to indicate
780          * its value is up-to-date.
781          *
782          * It is possible that old.value has already contained the latest
783          * HPET value while the lock holder was in the process of releasing
784          * the lock. Checking for lock state change will enable us to return
785          * the value immediately instead of waiting for the next HPET reader
786          * to come along.
787          */
788         do {
789                 cpu_relax();
790                 new.lockval = READ_ONCE(hpet.lockval);
791         } while ((new.value == old.value) && arch_spin_is_locked(&new.lock));
792
793         return (u64)new.value;
794 }
795 #else
796 /*
797  * For UP or 32-bit.
798  */
799 static u64 read_hpet(struct clocksource *cs)
800 {
801         return (u64)hpet_readl(HPET_COUNTER);
802 }
803 #endif
804
805 static struct clocksource clocksource_hpet = {
806         .name           = "hpet",
807         .rating         = 250,
808         .read           = read_hpet,
809         .mask           = HPET_MASK,
810         .flags          = CLOCK_SOURCE_IS_CONTINUOUS,
811         .resume         = hpet_resume_counter,
812 };
813
814 /*
815  * AMD SB700 based systems with spread spectrum enabled use a SMM based
816  * HPET emulation to provide proper frequency setting.
817  *
818  * On such systems the SMM code is initialized with the first HPET register
819  * access and takes some time to complete. During this time the config
820  * register reads 0xffffffff. We check for max 1000 loops whether the
821  * config register reads a non-0xffffffff value to make sure that the
822  * HPET is up and running before we proceed any further.
823  *
824  * A counting loop is safe, as the HPET access takes thousands of CPU cycles.
825  *
826  * On non-SB700 based machines this check is only done once and has no
827  * side effects.
828  */
829 static bool __init hpet_cfg_working(void)
830 {
831         int i;
832
833         for (i = 0; i < 1000; i++) {
834                 if (hpet_readl(HPET_CFG) != 0xFFFFFFFF)
835                         return true;
836         }
837
838         pr_warn("Config register invalid. Disabling HPET\n");
839         return false;
840 }
841
842 static bool __init hpet_counting(void)
843 {
844         u64 start, now, t1;
845
846         hpet_restart_counter();
847
848         t1 = hpet_readl(HPET_COUNTER);
849         start = rdtsc();
850
851         /*
852          * We don't know the TSC frequency yet, but waiting for
853          * 200000 TSC cycles is safe:
854          * 4 GHz == 50us
855          * 1 GHz == 200us
856          */
857         do {
858                 if (t1 != hpet_readl(HPET_COUNTER))
859                         return true;
860                 now = rdtsc();
861         } while ((now - start) < 200000UL);
862
863         pr_warn("Counter not counting. HPET disabled\n");
864         return false;
865 }
866
867 /**
868  * hpet_enable - Try to setup the HPET timer. Returns 1 on success.
869  */
870 int __init hpet_enable(void)
871 {
872         u32 hpet_period, cfg, id;
873         unsigned int i, channels;
874         struct hpet_channel *hc;
875         u64 freq;
876
877         if (!is_hpet_capable())
878                 return 0;
879
880         hpet_set_mapping();
881         if (!hpet_virt_address)
882                 return 0;
883
884         /* Validate that the config register is working */
885         if (!hpet_cfg_working())
886                 goto out_nohpet;
887
888         /* Validate that the counter is counting */
889         if (!hpet_counting())
890                 goto out_nohpet;
891
892         /*
893          * Read the period and check for a sane value:
894          */
895         hpet_period = hpet_readl(HPET_PERIOD);
896         if (hpet_period < HPET_MIN_PERIOD || hpet_period > HPET_MAX_PERIOD)
897                 goto out_nohpet;
898
899         /* The period is a femtoseconds value. Convert it to a frequency. */
900         freq = FSEC_PER_SEC;
901         do_div(freq, hpet_period);
902         hpet_freq = freq;
903
904         /*
905          * Read the HPET ID register to retrieve the IRQ routing
906          * information and the number of channels
907          */
908         id = hpet_readl(HPET_ID);
909         hpet_print_config();
910
911         /* This is the HPET channel number which is zero based */
912         channels = ((id & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT) + 1;
913
914         /*
915          * The legacy routing mode needs at least two channels, tick timer
916          * and the rtc emulation channel.
917          */
918         if (IS_ENABLED(CONFIG_HPET_EMULATE_RTC) && channels < 2)
919                 goto out_nohpet;
920
921         hc = kcalloc(channels, sizeof(*hc), GFP_KERNEL);
922         if (!hc) {
923                 pr_warn("Disabling HPET.\n");
924                 goto out_nohpet;
925         }
926         hpet_base.channels = hc;
927         hpet_base.nr_channels = channels;
928
929         /* Read, store and sanitize the global configuration */
930         cfg = hpet_readl(HPET_CFG);
931         hpet_base.boot_cfg = cfg;
932         cfg &= ~(HPET_CFG_ENABLE | HPET_CFG_LEGACY);
933         hpet_writel(cfg, HPET_CFG);
934         if (cfg)
935                 pr_warn("Global config: Unknown bits %#x\n", cfg);
936
937         /* Read, store and sanitize the per channel configuration */
938         for (i = 0; i < channels; i++, hc++) {
939                 hc->num = i;
940
941                 cfg = hpet_readl(HPET_Tn_CFG(i));
942                 hc->boot_cfg = cfg;
943
944                 cfg &= ~(HPET_TN_ENABLE | HPET_TN_LEVEL | HPET_TN_FSB);
945                 hpet_writel(cfg, HPET_Tn_CFG(i));
946
947                 cfg &= ~(HPET_TN_PERIODIC | HPET_TN_PERIODIC_CAP
948                          | HPET_TN_64BIT_CAP | HPET_TN_32BIT | HPET_TN_ROUTE
949                          | HPET_TN_FSB | HPET_TN_FSB_CAP);
950                 if (cfg)
951                         pr_warn("Channel #%u config: Unknown bits %#x\n", i, cfg);
952         }
953         hpet_print_config();
954
955         clocksource_register_hz(&clocksource_hpet, (u32)hpet_freq);
956
957         if (id & HPET_ID_LEGSUP) {
958                 hpet_legacy_clockevent_register();
959                 return 1;
960         }
961         return 0;
962
963 out_nohpet:
964         kfree(hpet_base.channels);
965         hpet_base.channels = NULL;
966         hpet_base.nr_channels = 0;
967         hpet_clear_mapping();
968         hpet_address = 0;
969         return 0;
970 }
971
972 /*
973  * The late initialization runs after the PCI quirks have been invoked
974  * which might have detected a system on which the HPET can be enforced.
975  */
976 static __init int hpet_late_init(void)
977 {
978         int ret;
979
980         if (!hpet_address) {
981                 if (!force_hpet_address)
982                         return -ENODEV;
983
984                 hpet_address = force_hpet_address;
985                 hpet_enable();
986         }
987
988         if (!hpet_virt_address)
989                 return -ENODEV;
990
991         if (hpet_readl(HPET_ID) & HPET_ID_LEGSUP)
992                 hpet_msi_capability_lookup(2);
993         else
994                 hpet_msi_capability_lookup(0);
995
996         hpet_reserve_platform_timers(hpet_readl(HPET_ID));
997         hpet_print_config();
998
999         if (hpet_msi_disable)
1000                 return 0;
1001
1002         if (boot_cpu_has(X86_FEATURE_ARAT))
1003                 return 0;
1004
1005         ret = cpuhp_setup_state(CPUHP_AP_X86_HPET_ONLINE, "x86/hpet:online",
1006                                 hpet_cpuhp_online, NULL);
1007         if (ret)
1008                 return ret;
1009         ret = cpuhp_setup_state(CPUHP_X86_HPET_DEAD, "x86/hpet:dead", NULL,
1010                                 hpet_cpuhp_dead);
1011         if (ret)
1012                 goto err_cpuhp;
1013         return 0;
1014
1015 err_cpuhp:
1016         cpuhp_remove_state(CPUHP_AP_X86_HPET_ONLINE);
1017         return ret;
1018 }
1019 fs_initcall(hpet_late_init);
1020
1021 void hpet_disable(void)
1022 {
1023         unsigned int i;
1024         u32 cfg;
1025
1026         if (!is_hpet_capable() || !hpet_virt_address)
1027                 return;
1028
1029         /* Restore boot configuration with the enable bit cleared */
1030         cfg = hpet_base.boot_cfg;
1031         cfg &= ~HPET_CFG_ENABLE;
1032         hpet_writel(cfg, HPET_CFG);
1033
1034         /* Restore the channel boot configuration */
1035         for (i = 0; i < hpet_base.nr_channels; i++)
1036                 hpet_writel(hpet_base.channels[i].boot_cfg, HPET_Tn_CFG(i));
1037
1038         /* If the HPET was enabled at boot time, reenable it */
1039         if (hpet_base.boot_cfg & HPET_CFG_ENABLE)
1040                 hpet_writel(hpet_base.boot_cfg, HPET_CFG);
1041 }
1042
1043 #ifdef CONFIG_HPET_EMULATE_RTC
1044
1045 /*
1046  * HPET in LegacyReplacement mode eats up the RTC interrupt line. When HPET
1047  * is enabled, we support RTC interrupt functionality in software.
1048  *
1049  * RTC has 3 kinds of interrupts:
1050  *
1051  *  1) Update Interrupt - generate an interrupt, every second, when the
1052  *     RTC clock is updated
1053  *  2) Alarm Interrupt - generate an interrupt at a specific time of day
1054  *  3) Periodic Interrupt - generate periodic interrupt, with frequencies
1055  *     2Hz-8192Hz (2Hz-64Hz for non-root user) (all frequencies in powers of 2)
1056  *
1057  * (1) and (2) above are implemented using polling at a frequency of 64 Hz:
1058  * DEFAULT_RTC_INT_FREQ.
1059  *
1060  * The exact frequency is a tradeoff between accuracy and interrupt overhead.
1061  *
1062  * For (3), we use interrupts at 64 Hz, or the user specified periodic frequency,
1063  * if it's higher.
1064  */
1065 #include <linux/mc146818rtc.h>
1066 #include <linux/rtc.h>
1067
1068 #define DEFAULT_RTC_INT_FREQ    64
1069 #define DEFAULT_RTC_SHIFT       6
1070 #define RTC_NUM_INTS            1
1071
1072 static unsigned long hpet_rtc_flags;
1073 static int hpet_prev_update_sec;
1074 static struct rtc_time hpet_alarm_time;
1075 static unsigned long hpet_pie_count;
1076 static u32 hpet_t1_cmp;
1077 static u32 hpet_default_delta;
1078 static u32 hpet_pie_delta;
1079 static unsigned long hpet_pie_limit;
1080
1081 static rtc_irq_handler irq_handler;
1082
1083 /*
1084  * Check that the HPET counter c1 is ahead of c2
1085  */
1086 static inline int hpet_cnt_ahead(u32 c1, u32 c2)
1087 {
1088         return (s32)(c2 - c1) < 0;
1089 }
1090
1091 /*
1092  * Registers a IRQ handler.
1093  */
1094 int hpet_register_irq_handler(rtc_irq_handler handler)
1095 {
1096         if (!is_hpet_enabled())
1097                 return -ENODEV;
1098         if (irq_handler)
1099                 return -EBUSY;
1100
1101         irq_handler = handler;
1102
1103         return 0;
1104 }
1105 EXPORT_SYMBOL_GPL(hpet_register_irq_handler);
1106
1107 /*
1108  * Deregisters the IRQ handler registered with hpet_register_irq_handler()
1109  * and does cleanup.
1110  */
1111 void hpet_unregister_irq_handler(rtc_irq_handler handler)
1112 {
1113         if (!is_hpet_enabled())
1114                 return;
1115
1116         irq_handler = NULL;
1117         hpet_rtc_flags = 0;
1118 }
1119 EXPORT_SYMBOL_GPL(hpet_unregister_irq_handler);
1120
1121 /*
1122  * Timer 1 for RTC emulation. We use one shot mode, as periodic mode
1123  * is not supported by all HPET implementations for timer 1.
1124  *
1125  * hpet_rtc_timer_init() is called when the rtc is initialized.
1126  */
1127 int hpet_rtc_timer_init(void)
1128 {
1129         unsigned int cfg, cnt, delta;
1130         unsigned long flags;
1131
1132         if (!is_hpet_enabled())
1133                 return 0;
1134
1135         if (!hpet_default_delta) {
1136                 uint64_t clc;
1137
1138                 clc = (uint64_t) hpet_clockevent.mult * NSEC_PER_SEC;
1139                 clc >>= hpet_clockevent.shift + DEFAULT_RTC_SHIFT;
1140                 hpet_default_delta = clc;
1141         }
1142
1143         if (!(hpet_rtc_flags & RTC_PIE) || hpet_pie_limit)
1144                 delta = hpet_default_delta;
1145         else
1146                 delta = hpet_pie_delta;
1147
1148         local_irq_save(flags);
1149
1150         cnt = delta + hpet_readl(HPET_COUNTER);
1151         hpet_writel(cnt, HPET_T1_CMP);
1152         hpet_t1_cmp = cnt;
1153
1154         cfg = hpet_readl(HPET_T1_CFG);
1155         cfg &= ~HPET_TN_PERIODIC;
1156         cfg |= HPET_TN_ENABLE | HPET_TN_32BIT;
1157         hpet_writel(cfg, HPET_T1_CFG);
1158
1159         local_irq_restore(flags);
1160
1161         return 1;
1162 }
1163 EXPORT_SYMBOL_GPL(hpet_rtc_timer_init);
1164
1165 static void hpet_disable_rtc_channel(void)
1166 {
1167         u32 cfg = hpet_readl(HPET_T1_CFG);
1168
1169         cfg &= ~HPET_TN_ENABLE;
1170         hpet_writel(cfg, HPET_T1_CFG);
1171 }
1172
1173 /*
1174  * The functions below are called from rtc driver.
1175  * Return 0 if HPET is not being used.
1176  * Otherwise do the necessary changes and return 1.
1177  */
1178 int hpet_mask_rtc_irq_bit(unsigned long bit_mask)
1179 {
1180         if (!is_hpet_enabled())
1181                 return 0;
1182
1183         hpet_rtc_flags &= ~bit_mask;
1184         if (unlikely(!hpet_rtc_flags))
1185                 hpet_disable_rtc_channel();
1186
1187         return 1;
1188 }
1189 EXPORT_SYMBOL_GPL(hpet_mask_rtc_irq_bit);
1190
1191 int hpet_set_rtc_irq_bit(unsigned long bit_mask)
1192 {
1193         unsigned long oldbits = hpet_rtc_flags;
1194
1195         if (!is_hpet_enabled())
1196                 return 0;
1197
1198         hpet_rtc_flags |= bit_mask;
1199
1200         if ((bit_mask & RTC_UIE) && !(oldbits & RTC_UIE))
1201                 hpet_prev_update_sec = -1;
1202
1203         if (!oldbits)
1204                 hpet_rtc_timer_init();
1205
1206         return 1;
1207 }
1208 EXPORT_SYMBOL_GPL(hpet_set_rtc_irq_bit);
1209
1210 int hpet_set_alarm_time(unsigned char hrs, unsigned char min, unsigned char sec)
1211 {
1212         if (!is_hpet_enabled())
1213                 return 0;
1214
1215         hpet_alarm_time.tm_hour = hrs;
1216         hpet_alarm_time.tm_min = min;
1217         hpet_alarm_time.tm_sec = sec;
1218
1219         return 1;
1220 }
1221 EXPORT_SYMBOL_GPL(hpet_set_alarm_time);
1222
1223 int hpet_set_periodic_freq(unsigned long freq)
1224 {
1225         uint64_t clc;
1226
1227         if (!is_hpet_enabled())
1228                 return 0;
1229
1230         if (freq <= DEFAULT_RTC_INT_FREQ) {
1231                 hpet_pie_limit = DEFAULT_RTC_INT_FREQ / freq;
1232         } else {
1233                 clc = (uint64_t) hpet_clockevent.mult * NSEC_PER_SEC;
1234                 do_div(clc, freq);
1235                 clc >>= hpet_clockevent.shift;
1236                 hpet_pie_delta = clc;
1237                 hpet_pie_limit = 0;
1238         }
1239
1240         return 1;
1241 }
1242 EXPORT_SYMBOL_GPL(hpet_set_periodic_freq);
1243
1244 int hpet_rtc_dropped_irq(void)
1245 {
1246         return is_hpet_enabled();
1247 }
1248 EXPORT_SYMBOL_GPL(hpet_rtc_dropped_irq);
1249
1250 static void hpet_rtc_timer_reinit(void)
1251 {
1252         unsigned int delta;
1253         int lost_ints = -1;
1254
1255         if (unlikely(!hpet_rtc_flags))
1256                 hpet_disable_rtc_channel();
1257
1258         if (!(hpet_rtc_flags & RTC_PIE) || hpet_pie_limit)
1259                 delta = hpet_default_delta;
1260         else
1261                 delta = hpet_pie_delta;
1262
1263         /*
1264          * Increment the comparator value until we are ahead of the
1265          * current count.
1266          */
1267         do {
1268                 hpet_t1_cmp += delta;
1269                 hpet_writel(hpet_t1_cmp, HPET_T1_CMP);
1270                 lost_ints++;
1271         } while (!hpet_cnt_ahead(hpet_t1_cmp, hpet_readl(HPET_COUNTER)));
1272
1273         if (lost_ints) {
1274                 if (hpet_rtc_flags & RTC_PIE)
1275                         hpet_pie_count += lost_ints;
1276                 if (printk_ratelimit())
1277                         pr_warn("Lost %d RTC interrupts\n", lost_ints);
1278         }
1279 }
1280
1281 irqreturn_t hpet_rtc_interrupt(int irq, void *dev_id)
1282 {
1283         struct rtc_time curr_time;
1284         unsigned long rtc_int_flag = 0;
1285
1286         hpet_rtc_timer_reinit();
1287         memset(&curr_time, 0, sizeof(struct rtc_time));
1288
1289         if (hpet_rtc_flags & (RTC_UIE | RTC_AIE))
1290                 mc146818_get_time(&curr_time);
1291
1292         if (hpet_rtc_flags & RTC_UIE &&
1293             curr_time.tm_sec != hpet_prev_update_sec) {
1294                 if (hpet_prev_update_sec >= 0)
1295                         rtc_int_flag = RTC_UF;
1296                 hpet_prev_update_sec = curr_time.tm_sec;
1297         }
1298
1299         if (hpet_rtc_flags & RTC_PIE && ++hpet_pie_count >= hpet_pie_limit) {
1300                 rtc_int_flag |= RTC_PF;
1301                 hpet_pie_count = 0;
1302         }
1303
1304         if (hpet_rtc_flags & RTC_AIE &&
1305             (curr_time.tm_sec == hpet_alarm_time.tm_sec) &&
1306             (curr_time.tm_min == hpet_alarm_time.tm_min) &&
1307             (curr_time.tm_hour == hpet_alarm_time.tm_hour))
1308                 rtc_int_flag |= RTC_AF;
1309
1310         if (rtc_int_flag) {
1311                 rtc_int_flag |= (RTC_IRQF | (RTC_NUM_INTS << 8));
1312                 if (irq_handler)
1313                         irq_handler(rtc_int_flag, dev_id);
1314         }
1315         return IRQ_HANDLED;
1316 }
1317 EXPORT_SYMBOL_GPL(hpet_rtc_interrupt);
1318 #endif