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