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