GNU Linux-libre 4.14.295-gnu1
[releases.git] / drivers / clocksource / arm_arch_timer.c
1 /*
2  *  linux/drivers/clocksource/arm_arch_timer.c
3  *
4  *  Copyright (C) 2011 ARM Ltd.
5  *  All Rights Reserved
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11
12 #define pr_fmt(fmt)     "arm_arch_timer: " fmt
13
14 #include <linux/init.h>
15 #include <linux/kernel.h>
16 #include <linux/device.h>
17 #include <linux/smp.h>
18 #include <linux/cpu.h>
19 #include <linux/cpu_pm.h>
20 #include <linux/clockchips.h>
21 #include <linux/clocksource.h>
22 #include <linux/interrupt.h>
23 #include <linux/of_irq.h>
24 #include <linux/of_address.h>
25 #include <linux/io.h>
26 #include <linux/slab.h>
27 #include <linux/sched/clock.h>
28 #include <linux/sched_clock.h>
29 #include <linux/acpi.h>
30
31 #include <asm/arch_timer.h>
32 #include <asm/virt.h>
33
34 #include <clocksource/arm_arch_timer.h>
35
36 #undef pr_fmt
37 #define pr_fmt(fmt) "arch_timer: " fmt
38
39 #define CNTTIDR         0x08
40 #define CNTTIDR_VIRT(n) (BIT(1) << ((n) * 4))
41
42 #define CNTACR(n)       (0x40 + ((n) * 4))
43 #define CNTACR_RPCT     BIT(0)
44 #define CNTACR_RVCT     BIT(1)
45 #define CNTACR_RFRQ     BIT(2)
46 #define CNTACR_RVOFF    BIT(3)
47 #define CNTACR_RWVT     BIT(4)
48 #define CNTACR_RWPT     BIT(5)
49
50 #define CNTVCT_LO       0x08
51 #define CNTVCT_HI       0x0c
52 #define CNTFRQ          0x10
53 #define CNTP_TVAL       0x28
54 #define CNTP_CTL        0x2c
55 #define CNTV_TVAL       0x38
56 #define CNTV_CTL        0x3c
57
58 static unsigned arch_timers_present __initdata;
59
60 static void __iomem *arch_counter_base;
61
62 struct arch_timer {
63         void __iomem *base;
64         struct clock_event_device evt;
65 };
66
67 #define to_arch_timer(e) container_of(e, struct arch_timer, evt)
68
69 static u32 arch_timer_rate;
70 static int arch_timer_ppi[ARCH_TIMER_MAX_TIMER_PPI];
71
72 static struct clock_event_device __percpu *arch_timer_evt;
73
74 static enum arch_timer_ppi_nr arch_timer_uses_ppi = ARCH_TIMER_VIRT_PPI;
75 static bool arch_timer_c3stop;
76 static bool arch_timer_mem_use_virtual;
77 static bool arch_counter_suspend_stop;
78 static bool vdso_default = true;
79
80 static bool evtstrm_enable = IS_ENABLED(CONFIG_ARM_ARCH_TIMER_EVTSTREAM);
81
82 static int __init early_evtstrm_cfg(char *buf)
83 {
84         return strtobool(buf, &evtstrm_enable);
85 }
86 early_param("clocksource.arm_arch_timer.evtstrm", early_evtstrm_cfg);
87
88 /*
89  * Architected system timer support.
90  */
91
92 static __always_inline
93 void arch_timer_reg_write(int access, enum arch_timer_reg reg, u32 val,
94                           struct clock_event_device *clk)
95 {
96         if (access == ARCH_TIMER_MEM_PHYS_ACCESS) {
97                 struct arch_timer *timer = to_arch_timer(clk);
98                 switch (reg) {
99                 case ARCH_TIMER_REG_CTRL:
100                         writel_relaxed(val, timer->base + CNTP_CTL);
101                         break;
102                 case ARCH_TIMER_REG_TVAL:
103                         writel_relaxed(val, timer->base + CNTP_TVAL);
104                         break;
105                 }
106         } else if (access == ARCH_TIMER_MEM_VIRT_ACCESS) {
107                 struct arch_timer *timer = to_arch_timer(clk);
108                 switch (reg) {
109                 case ARCH_TIMER_REG_CTRL:
110                         writel_relaxed(val, timer->base + CNTV_CTL);
111                         break;
112                 case ARCH_TIMER_REG_TVAL:
113                         writel_relaxed(val, timer->base + CNTV_TVAL);
114                         break;
115                 }
116         } else {
117                 arch_timer_reg_write_cp15(access, reg, val);
118         }
119 }
120
121 static __always_inline
122 u32 arch_timer_reg_read(int access, enum arch_timer_reg reg,
123                         struct clock_event_device *clk)
124 {
125         u32 val;
126
127         if (access == ARCH_TIMER_MEM_PHYS_ACCESS) {
128                 struct arch_timer *timer = to_arch_timer(clk);
129                 switch (reg) {
130                 case ARCH_TIMER_REG_CTRL:
131                         val = readl_relaxed(timer->base + CNTP_CTL);
132                         break;
133                 case ARCH_TIMER_REG_TVAL:
134                         val = readl_relaxed(timer->base + CNTP_TVAL);
135                         break;
136                 }
137         } else if (access == ARCH_TIMER_MEM_VIRT_ACCESS) {
138                 struct arch_timer *timer = to_arch_timer(clk);
139                 switch (reg) {
140                 case ARCH_TIMER_REG_CTRL:
141                         val = readl_relaxed(timer->base + CNTV_CTL);
142                         break;
143                 case ARCH_TIMER_REG_TVAL:
144                         val = readl_relaxed(timer->base + CNTV_TVAL);
145                         break;
146                 }
147         } else {
148                 val = arch_timer_reg_read_cp15(access, reg);
149         }
150
151         return val;
152 }
153
154 /*
155  * Default to cp15 based access because arm64 uses this function for
156  * sched_clock() before DT is probed and the cp15 method is guaranteed
157  * to exist on arm64. arm doesn't use this before DT is probed so even
158  * if we don't have the cp15 accessors we won't have a problem.
159  */
160 u64 (*arch_timer_read_counter)(void) = arch_counter_get_cntvct;
161
162 static u64 arch_counter_read(struct clocksource *cs)
163 {
164         return arch_timer_read_counter();
165 }
166
167 static u64 arch_counter_read_cc(const struct cyclecounter *cc)
168 {
169         return arch_timer_read_counter();
170 }
171
172 static struct clocksource clocksource_counter = {
173         .name   = "arch_sys_counter",
174         .rating = 400,
175         .read   = arch_counter_read,
176         .mask   = CLOCKSOURCE_MASK(56),
177         .flags  = CLOCK_SOURCE_IS_CONTINUOUS,
178 };
179
180 static struct cyclecounter cyclecounter __ro_after_init = {
181         .read   = arch_counter_read_cc,
182         .mask   = CLOCKSOURCE_MASK(56),
183 };
184
185 struct ate_acpi_oem_info {
186         char oem_id[ACPI_OEM_ID_SIZE + 1];
187         char oem_table_id[ACPI_OEM_TABLE_ID_SIZE + 1];
188         u32 oem_revision;
189 };
190
191 #ifdef CONFIG_FSL_ERRATUM_A008585
192 /*
193  * The number of retries is an arbitrary value well beyond the highest number
194  * of iterations the loop has been observed to take.
195  */
196 #define __fsl_a008585_read_reg(reg) ({                  \
197         u64 _old, _new;                                 \
198         int _retries = 200;                             \
199                                                         \
200         do {                                            \
201                 _old = read_sysreg(reg);                \
202                 _new = read_sysreg(reg);                \
203                 _retries--;                             \
204         } while (unlikely(_old != _new) && _retries);   \
205                                                         \
206         WARN_ON_ONCE(!_retries);                        \
207         _new;                                           \
208 })
209
210 static u32 notrace fsl_a008585_read_cntp_tval_el0(void)
211 {
212         return __fsl_a008585_read_reg(cntp_tval_el0);
213 }
214
215 static u32 notrace fsl_a008585_read_cntv_tval_el0(void)
216 {
217         return __fsl_a008585_read_reg(cntv_tval_el0);
218 }
219
220 static u64 notrace fsl_a008585_read_cntvct_el0(void)
221 {
222         return __fsl_a008585_read_reg(cntvct_el0);
223 }
224 #endif
225
226 #ifdef CONFIG_HISILICON_ERRATUM_161010101
227 /*
228  * Verify whether the value of the second read is larger than the first by
229  * less than 32 is the only way to confirm the value is correct, so clear the
230  * lower 5 bits to check whether the difference is greater than 32 or not.
231  * Theoretically the erratum should not occur more than twice in succession
232  * when reading the system counter, but it is possible that some interrupts
233  * may lead to more than twice read errors, triggering the warning, so setting
234  * the number of retries far beyond the number of iterations the loop has been
235  * observed to take.
236  */
237 #define __hisi_161010101_read_reg(reg) ({                               \
238         u64 _old, _new;                                         \
239         int _retries = 50;                                      \
240                                                                 \
241         do {                                                    \
242                 _old = read_sysreg(reg);                        \
243                 _new = read_sysreg(reg);                        \
244                 _retries--;                                     \
245         } while (unlikely((_new - _old) >> 5) && _retries);     \
246                                                                 \
247         WARN_ON_ONCE(!_retries);                                \
248         _new;                                                   \
249 })
250
251 static u32 notrace hisi_161010101_read_cntp_tval_el0(void)
252 {
253         return __hisi_161010101_read_reg(cntp_tval_el0);
254 }
255
256 static u32 notrace hisi_161010101_read_cntv_tval_el0(void)
257 {
258         return __hisi_161010101_read_reg(cntv_tval_el0);
259 }
260
261 static u64 notrace hisi_161010101_read_cntvct_el0(void)
262 {
263         return __hisi_161010101_read_reg(cntvct_el0);
264 }
265
266 static struct ate_acpi_oem_info hisi_161010101_oem_info[] = {
267         /*
268          * Note that trailing spaces are required to properly match
269          * the OEM table information.
270          */
271         {
272                 .oem_id         = "HISI  ",
273                 .oem_table_id   = "HIP05   ",
274                 .oem_revision   = 0,
275         },
276         {
277                 .oem_id         = "HISI  ",
278                 .oem_table_id   = "HIP06   ",
279                 .oem_revision   = 0,
280         },
281         {
282                 .oem_id         = "HISI  ",
283                 .oem_table_id   = "HIP07   ",
284                 .oem_revision   = 0,
285         },
286         { /* Sentinel indicating the end of the OEM array */ },
287 };
288 #endif
289
290 #ifdef CONFIG_ARM64_ERRATUM_858921
291 static u64 notrace arm64_858921_read_cntvct_el0(void)
292 {
293         u64 old, new;
294
295         old = read_sysreg(cntvct_el0);
296         new = read_sysreg(cntvct_el0);
297         return (((old ^ new) >> 32) & 1) ? old : new;
298 }
299 #endif
300
301 #ifdef CONFIG_ARM64_ERRATUM_1188873
302 static u64 notrace arm64_1188873_read_cntvct_el0(void)
303 {
304         return read_sysreg(cntvct_el0);
305 }
306 #endif
307
308 #ifdef CONFIG_ARM_ARCH_TIMER_OOL_WORKAROUND
309 DEFINE_PER_CPU(const struct arch_timer_erratum_workaround *,
310                timer_unstable_counter_workaround);
311 EXPORT_SYMBOL_GPL(timer_unstable_counter_workaround);
312
313 DEFINE_STATIC_KEY_FALSE(arch_timer_read_ool_enabled);
314 EXPORT_SYMBOL_GPL(arch_timer_read_ool_enabled);
315
316 static void erratum_set_next_event_tval_generic(const int access, unsigned long evt,
317                                                 struct clock_event_device *clk)
318 {
319         unsigned long ctrl;
320         u64 cval = evt + arch_counter_get_cntvct();
321
322         ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
323         ctrl |= ARCH_TIMER_CTRL_ENABLE;
324         ctrl &= ~ARCH_TIMER_CTRL_IT_MASK;
325
326         if (access == ARCH_TIMER_PHYS_ACCESS)
327                 write_sysreg(cval, cntp_cval_el0);
328         else
329                 write_sysreg(cval, cntv_cval_el0);
330
331         arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
332 }
333
334 static __maybe_unused int erratum_set_next_event_tval_virt(unsigned long evt,
335                                             struct clock_event_device *clk)
336 {
337         erratum_set_next_event_tval_generic(ARCH_TIMER_VIRT_ACCESS, evt, clk);
338         return 0;
339 }
340
341 static __maybe_unused int erratum_set_next_event_tval_phys(unsigned long evt,
342                                             struct clock_event_device *clk)
343 {
344         erratum_set_next_event_tval_generic(ARCH_TIMER_PHYS_ACCESS, evt, clk);
345         return 0;
346 }
347
348 static const struct arch_timer_erratum_workaround ool_workarounds[] = {
349 #ifdef CONFIG_FSL_ERRATUM_A008585
350         {
351                 .match_type = ate_match_dt,
352                 .id = "fsl,erratum-a008585",
353                 .desc = "Freescale erratum a005858",
354                 .read_cntp_tval_el0 = fsl_a008585_read_cntp_tval_el0,
355                 .read_cntv_tval_el0 = fsl_a008585_read_cntv_tval_el0,
356                 .read_cntvct_el0 = fsl_a008585_read_cntvct_el0,
357                 .set_next_event_phys = erratum_set_next_event_tval_phys,
358                 .set_next_event_virt = erratum_set_next_event_tval_virt,
359         },
360 #endif
361 #ifdef CONFIG_HISILICON_ERRATUM_161010101
362         {
363                 .match_type = ate_match_dt,
364                 .id = "hisilicon,erratum-161010101",
365                 .desc = "HiSilicon erratum 161010101",
366                 .read_cntp_tval_el0 = hisi_161010101_read_cntp_tval_el0,
367                 .read_cntv_tval_el0 = hisi_161010101_read_cntv_tval_el0,
368                 .read_cntvct_el0 = hisi_161010101_read_cntvct_el0,
369                 .set_next_event_phys = erratum_set_next_event_tval_phys,
370                 .set_next_event_virt = erratum_set_next_event_tval_virt,
371         },
372         {
373                 .match_type = ate_match_acpi_oem_info,
374                 .id = hisi_161010101_oem_info,
375                 .desc = "HiSilicon erratum 161010101",
376                 .read_cntp_tval_el0 = hisi_161010101_read_cntp_tval_el0,
377                 .read_cntv_tval_el0 = hisi_161010101_read_cntv_tval_el0,
378                 .read_cntvct_el0 = hisi_161010101_read_cntvct_el0,
379                 .set_next_event_phys = erratum_set_next_event_tval_phys,
380                 .set_next_event_virt = erratum_set_next_event_tval_virt,
381         },
382 #endif
383 #ifdef CONFIG_ARM64_ERRATUM_858921
384         {
385                 .match_type = ate_match_local_cap_id,
386                 .id = (void *)ARM64_WORKAROUND_858921,
387                 .desc = "ARM erratum 858921",
388                 .read_cntvct_el0 = arm64_858921_read_cntvct_el0,
389         },
390 #endif
391 #ifdef CONFIG_ARM64_ERRATUM_1188873
392         {
393                 .match_type = ate_match_local_cap_id,
394                 .id = (void *)ARM64_WORKAROUND_1188873,
395                 .desc = "ARM erratum 1188873",
396                 .read_cntvct_el0 = arm64_1188873_read_cntvct_el0,
397         },
398 #endif
399 };
400
401 typedef bool (*ate_match_fn_t)(const struct arch_timer_erratum_workaround *,
402                                const void *);
403
404 static
405 bool arch_timer_check_dt_erratum(const struct arch_timer_erratum_workaround *wa,
406                                  const void *arg)
407 {
408         const struct device_node *np = arg;
409
410         return of_property_read_bool(np, wa->id);
411 }
412
413 static
414 bool arch_timer_check_local_cap_erratum(const struct arch_timer_erratum_workaround *wa,
415                                         const void *arg)
416 {
417         return this_cpu_has_cap((uintptr_t)wa->id);
418 }
419
420
421 static
422 bool arch_timer_check_acpi_oem_erratum(const struct arch_timer_erratum_workaround *wa,
423                                        const void *arg)
424 {
425         static const struct ate_acpi_oem_info empty_oem_info = {};
426         const struct ate_acpi_oem_info *info = wa->id;
427         const struct acpi_table_header *table = arg;
428
429         /* Iterate over the ACPI OEM info array, looking for a match */
430         while (memcmp(info, &empty_oem_info, sizeof(*info))) {
431                 if (!memcmp(info->oem_id, table->oem_id, ACPI_OEM_ID_SIZE) &&
432                     !memcmp(info->oem_table_id, table->oem_table_id, ACPI_OEM_TABLE_ID_SIZE) &&
433                     info->oem_revision == table->oem_revision)
434                         return true;
435
436                 info++;
437         }
438
439         return false;
440 }
441
442 static const struct arch_timer_erratum_workaround *
443 arch_timer_iterate_errata(enum arch_timer_erratum_match_type type,
444                           ate_match_fn_t match_fn,
445                           void *arg)
446 {
447         int i;
448
449         for (i = 0; i < ARRAY_SIZE(ool_workarounds); i++) {
450                 if (ool_workarounds[i].match_type != type)
451                         continue;
452
453                 if (match_fn(&ool_workarounds[i], arg))
454                         return &ool_workarounds[i];
455         }
456
457         return NULL;
458 }
459
460 static
461 void arch_timer_enable_workaround(const struct arch_timer_erratum_workaround *wa,
462                                   bool local)
463 {
464         int i;
465
466         if (local) {
467                 __this_cpu_write(timer_unstable_counter_workaround, wa);
468         } else {
469                 for_each_possible_cpu(i)
470                         per_cpu(timer_unstable_counter_workaround, i) = wa;
471         }
472
473         /*
474          * Use the locked version, as we're called from the CPU
475          * hotplug framework. Otherwise, we end-up in deadlock-land.
476          */
477         static_branch_enable_cpuslocked(&arch_timer_read_ool_enabled);
478
479         /*
480          * Don't use the vdso fastpath if errata require using the
481          * out-of-line counter accessor. We may change our mind pretty
482          * late in the game (with a per-CPU erratum, for example), so
483          * change both the default value and the vdso itself.
484          */
485         if (wa->read_cntvct_el0) {
486                 clocksource_counter.archdata.vdso_direct = false;
487                 vdso_default = false;
488         }
489 }
490
491 static void arch_timer_check_ool_workaround(enum arch_timer_erratum_match_type type,
492                                             void *arg)
493 {
494         const struct arch_timer_erratum_workaround *wa;
495         ate_match_fn_t match_fn = NULL;
496         bool local = false;
497
498         switch (type) {
499         case ate_match_dt:
500                 match_fn = arch_timer_check_dt_erratum;
501                 break;
502         case ate_match_local_cap_id:
503                 match_fn = arch_timer_check_local_cap_erratum;
504                 local = true;
505                 break;
506         case ate_match_acpi_oem_info:
507                 match_fn = arch_timer_check_acpi_oem_erratum;
508                 break;
509         default:
510                 WARN_ON(1);
511                 return;
512         }
513
514         wa = arch_timer_iterate_errata(type, match_fn, arg);
515         if (!wa)
516                 return;
517
518         if (needs_unstable_timer_counter_workaround()) {
519                 const struct arch_timer_erratum_workaround *__wa;
520                 __wa = __this_cpu_read(timer_unstable_counter_workaround);
521                 if (__wa && wa != __wa)
522                         pr_warn("Can't enable workaround for %s (clashes with %s\n)",
523                                 wa->desc, __wa->desc);
524
525                 if (__wa)
526                         return;
527         }
528
529         arch_timer_enable_workaround(wa, local);
530         pr_info("Enabling %s workaround for %s\n",
531                 local ? "local" : "global", wa->desc);
532 }
533
534 #define erratum_handler(fn, r, ...)                                     \
535 ({                                                                      \
536         bool __val;                                                     \
537         if (needs_unstable_timer_counter_workaround()) {                \
538                 const struct arch_timer_erratum_workaround *__wa;       \
539                 __wa = __this_cpu_read(timer_unstable_counter_workaround); \
540                 if (__wa && __wa->fn) {                                 \
541                         r = __wa->fn(__VA_ARGS__);                      \
542                         __val = true;                                   \
543                 } else {                                                \
544                         __val = false;                                  \
545                 }                                                       \
546         } else {                                                        \
547                 __val = false;                                          \
548         }                                                               \
549         __val;                                                          \
550 })
551
552 static bool arch_timer_this_cpu_has_cntvct_wa(void)
553 {
554         const struct arch_timer_erratum_workaround *wa;
555
556         wa = __this_cpu_read(timer_unstable_counter_workaround);
557         return wa && wa->read_cntvct_el0;
558 }
559 #else
560 #define arch_timer_check_ool_workaround(t,a)            do { } while(0)
561 #define erratum_set_next_event_tval_virt(...)           ({BUG(); 0;})
562 #define erratum_set_next_event_tval_phys(...)           ({BUG(); 0;})
563 #define erratum_handler(fn, r, ...)                     ({false;})
564 #define arch_timer_this_cpu_has_cntvct_wa()             ({false;})
565 #endif /* CONFIG_ARM_ARCH_TIMER_OOL_WORKAROUND */
566
567 static __always_inline irqreturn_t timer_handler(const int access,
568                                         struct clock_event_device *evt)
569 {
570         unsigned long ctrl;
571
572         ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, evt);
573         if (ctrl & ARCH_TIMER_CTRL_IT_STAT) {
574                 ctrl |= ARCH_TIMER_CTRL_IT_MASK;
575                 arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, evt);
576                 evt->event_handler(evt);
577                 return IRQ_HANDLED;
578         }
579
580         return IRQ_NONE;
581 }
582
583 static irqreturn_t arch_timer_handler_virt(int irq, void *dev_id)
584 {
585         struct clock_event_device *evt = dev_id;
586
587         return timer_handler(ARCH_TIMER_VIRT_ACCESS, evt);
588 }
589
590 static irqreturn_t arch_timer_handler_phys(int irq, void *dev_id)
591 {
592         struct clock_event_device *evt = dev_id;
593
594         return timer_handler(ARCH_TIMER_PHYS_ACCESS, evt);
595 }
596
597 static irqreturn_t arch_timer_handler_phys_mem(int irq, void *dev_id)
598 {
599         struct clock_event_device *evt = dev_id;
600
601         return timer_handler(ARCH_TIMER_MEM_PHYS_ACCESS, evt);
602 }
603
604 static irqreturn_t arch_timer_handler_virt_mem(int irq, void *dev_id)
605 {
606         struct clock_event_device *evt = dev_id;
607
608         return timer_handler(ARCH_TIMER_MEM_VIRT_ACCESS, evt);
609 }
610
611 static __always_inline int timer_shutdown(const int access,
612                                           struct clock_event_device *clk)
613 {
614         unsigned long ctrl;
615
616         ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
617         ctrl &= ~ARCH_TIMER_CTRL_ENABLE;
618         arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
619
620         return 0;
621 }
622
623 static int arch_timer_shutdown_virt(struct clock_event_device *clk)
624 {
625         return timer_shutdown(ARCH_TIMER_VIRT_ACCESS, clk);
626 }
627
628 static int arch_timer_shutdown_phys(struct clock_event_device *clk)
629 {
630         return timer_shutdown(ARCH_TIMER_PHYS_ACCESS, clk);
631 }
632
633 static int arch_timer_shutdown_virt_mem(struct clock_event_device *clk)
634 {
635         return timer_shutdown(ARCH_TIMER_MEM_VIRT_ACCESS, clk);
636 }
637
638 static int arch_timer_shutdown_phys_mem(struct clock_event_device *clk)
639 {
640         return timer_shutdown(ARCH_TIMER_MEM_PHYS_ACCESS, clk);
641 }
642
643 static __always_inline void set_next_event(const int access, unsigned long evt,
644                                            struct clock_event_device *clk)
645 {
646         unsigned long ctrl;
647         ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
648         ctrl |= ARCH_TIMER_CTRL_ENABLE;
649         ctrl &= ~ARCH_TIMER_CTRL_IT_MASK;
650         arch_timer_reg_write(access, ARCH_TIMER_REG_TVAL, evt, clk);
651         arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
652 }
653
654 static int arch_timer_set_next_event_virt(unsigned long evt,
655                                           struct clock_event_device *clk)
656 {
657         int ret;
658
659         if (erratum_handler(set_next_event_virt, ret, evt, clk))
660                 return ret;
661
662         set_next_event(ARCH_TIMER_VIRT_ACCESS, evt, clk);
663         return 0;
664 }
665
666 static int arch_timer_set_next_event_phys(unsigned long evt,
667                                           struct clock_event_device *clk)
668 {
669         int ret;
670
671         if (erratum_handler(set_next_event_phys, ret, evt, clk))
672                 return ret;
673
674         set_next_event(ARCH_TIMER_PHYS_ACCESS, evt, clk);
675         return 0;
676 }
677
678 static int arch_timer_set_next_event_virt_mem(unsigned long evt,
679                                               struct clock_event_device *clk)
680 {
681         set_next_event(ARCH_TIMER_MEM_VIRT_ACCESS, evt, clk);
682         return 0;
683 }
684
685 static int arch_timer_set_next_event_phys_mem(unsigned long evt,
686                                               struct clock_event_device *clk)
687 {
688         set_next_event(ARCH_TIMER_MEM_PHYS_ACCESS, evt, clk);
689         return 0;
690 }
691
692 static void __arch_timer_setup(unsigned type,
693                                struct clock_event_device *clk)
694 {
695         clk->features = CLOCK_EVT_FEAT_ONESHOT;
696
697         if (type == ARCH_TIMER_TYPE_CP15) {
698                 if (arch_timer_c3stop)
699                         clk->features |= CLOCK_EVT_FEAT_C3STOP;
700                 clk->name = "arch_sys_timer";
701                 clk->rating = 450;
702                 clk->cpumask = cpumask_of(smp_processor_id());
703                 clk->irq = arch_timer_ppi[arch_timer_uses_ppi];
704                 switch (arch_timer_uses_ppi) {
705                 case ARCH_TIMER_VIRT_PPI:
706                         clk->set_state_shutdown = arch_timer_shutdown_virt;
707                         clk->set_state_oneshot_stopped = arch_timer_shutdown_virt;
708                         clk->set_next_event = arch_timer_set_next_event_virt;
709                         break;
710                 case ARCH_TIMER_PHYS_SECURE_PPI:
711                 case ARCH_TIMER_PHYS_NONSECURE_PPI:
712                 case ARCH_TIMER_HYP_PPI:
713                         clk->set_state_shutdown = arch_timer_shutdown_phys;
714                         clk->set_state_oneshot_stopped = arch_timer_shutdown_phys;
715                         clk->set_next_event = arch_timer_set_next_event_phys;
716                         break;
717                 default:
718                         BUG();
719                 }
720
721                 arch_timer_check_ool_workaround(ate_match_local_cap_id, NULL);
722         } else {
723                 clk->features |= CLOCK_EVT_FEAT_DYNIRQ;
724                 clk->name = "arch_mem_timer";
725                 clk->rating = 400;
726                 clk->cpumask = cpu_all_mask;
727                 if (arch_timer_mem_use_virtual) {
728                         clk->set_state_shutdown = arch_timer_shutdown_virt_mem;
729                         clk->set_state_oneshot_stopped = arch_timer_shutdown_virt_mem;
730                         clk->set_next_event =
731                                 arch_timer_set_next_event_virt_mem;
732                 } else {
733                         clk->set_state_shutdown = arch_timer_shutdown_phys_mem;
734                         clk->set_state_oneshot_stopped = arch_timer_shutdown_phys_mem;
735                         clk->set_next_event =
736                                 arch_timer_set_next_event_phys_mem;
737                 }
738         }
739
740         clk->set_state_shutdown(clk);
741
742         clockevents_config_and_register(clk, arch_timer_rate, 0xf, 0x7fffffff);
743 }
744
745 static void arch_timer_evtstrm_enable(int divider)
746 {
747         u32 cntkctl = arch_timer_get_cntkctl();
748
749         cntkctl &= ~ARCH_TIMER_EVT_TRIGGER_MASK;
750         /* Set the divider and enable virtual event stream */
751         cntkctl |= (divider << ARCH_TIMER_EVT_TRIGGER_SHIFT)
752                         | ARCH_TIMER_VIRT_EVT_EN;
753         arch_timer_set_cntkctl(cntkctl);
754         elf_hwcap |= HWCAP_EVTSTRM;
755 #ifdef CONFIG_COMPAT
756         compat_elf_hwcap |= COMPAT_HWCAP_EVTSTRM;
757 #endif
758 }
759
760 static void arch_timer_configure_evtstream(void)
761 {
762         int evt_stream_div, lsb;
763
764         /*
765          * As the event stream can at most be generated at half the frequency
766          * of the counter, use half the frequency when computing the divider.
767          */
768         evt_stream_div = arch_timer_rate / ARCH_TIMER_EVT_STREAM_FREQ / 2;
769
770         /*
771          * Find the closest power of two to the divisor. If the adjacent bit
772          * of lsb (last set bit, starts from 0) is set, then we use (lsb + 1).
773          */
774         lsb = fls(evt_stream_div) - 1;
775         if (lsb > 0 && (evt_stream_div & BIT(lsb - 1)))
776                 lsb++;
777
778         /* enable event stream */
779         arch_timer_evtstrm_enable(max(0, min(lsb, 15)));
780 }
781
782 static void arch_counter_set_user_access(void)
783 {
784         u32 cntkctl = arch_timer_get_cntkctl();
785
786         /* Disable user access to the timers and both counters */
787         /* Also disable virtual event stream */
788         cntkctl &= ~(ARCH_TIMER_USR_PT_ACCESS_EN
789                         | ARCH_TIMER_USR_VT_ACCESS_EN
790                         | ARCH_TIMER_USR_VCT_ACCESS_EN
791                         | ARCH_TIMER_VIRT_EVT_EN
792                         | ARCH_TIMER_USR_PCT_ACCESS_EN);
793
794         /*
795          * Enable user access to the virtual counter if it doesn't
796          * need to be workaround. The vdso may have been already
797          * disabled though.
798          */
799         if (arch_timer_this_cpu_has_cntvct_wa())
800                 pr_info("CPU%d: Trapping CNTVCT access\n", smp_processor_id());
801         else
802                 cntkctl |= ARCH_TIMER_USR_VCT_ACCESS_EN;
803
804         arch_timer_set_cntkctl(cntkctl);
805 }
806
807 static bool arch_timer_has_nonsecure_ppi(void)
808 {
809         return (arch_timer_uses_ppi == ARCH_TIMER_PHYS_SECURE_PPI &&
810                 arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]);
811 }
812
813 static u32 check_ppi_trigger(int irq)
814 {
815         u32 flags = irq_get_trigger_type(irq);
816
817         if (flags != IRQF_TRIGGER_HIGH && flags != IRQF_TRIGGER_LOW) {
818                 pr_warn("WARNING: Invalid trigger for IRQ%d, assuming level low\n", irq);
819                 pr_warn("WARNING: Please fix your firmware\n");
820                 flags = IRQF_TRIGGER_LOW;
821         }
822
823         return flags;
824 }
825
826 static int arch_timer_starting_cpu(unsigned int cpu)
827 {
828         struct clock_event_device *clk = this_cpu_ptr(arch_timer_evt);
829         u32 flags;
830
831         __arch_timer_setup(ARCH_TIMER_TYPE_CP15, clk);
832
833         flags = check_ppi_trigger(arch_timer_ppi[arch_timer_uses_ppi]);
834         enable_percpu_irq(arch_timer_ppi[arch_timer_uses_ppi], flags);
835
836         if (arch_timer_has_nonsecure_ppi()) {
837                 flags = check_ppi_trigger(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]);
838                 enable_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI],
839                                   flags);
840         }
841
842         arch_counter_set_user_access();
843         if (evtstrm_enable)
844                 arch_timer_configure_evtstream();
845
846         return 0;
847 }
848
849 /*
850  * For historical reasons, when probing with DT we use whichever (non-zero)
851  * rate was probed first, and don't verify that others match. If the first node
852  * probed has a clock-frequency property, this overrides the HW register.
853  */
854 static void arch_timer_of_configure_rate(u32 rate, struct device_node *np)
855 {
856         /* Who has more than one independent system counter? */
857         if (arch_timer_rate)
858                 return;
859
860         if (of_property_read_u32(np, "clock-frequency", &arch_timer_rate))
861                 arch_timer_rate = rate;
862
863         /* Check the timer frequency. */
864         if (arch_timer_rate == 0)
865                 pr_warn("frequency not available\n");
866 }
867
868 static void arch_timer_banner(unsigned type)
869 {
870         pr_info("%s%s%s timer(s) running at %lu.%02luMHz (%s%s%s).\n",
871                 type & ARCH_TIMER_TYPE_CP15 ? "cp15" : "",
872                 type == (ARCH_TIMER_TYPE_CP15 | ARCH_TIMER_TYPE_MEM) ?
873                         " and " : "",
874                 type & ARCH_TIMER_TYPE_MEM ? "mmio" : "",
875                 (unsigned long)arch_timer_rate / 1000000,
876                 (unsigned long)(arch_timer_rate / 10000) % 100,
877                 type & ARCH_TIMER_TYPE_CP15 ?
878                         (arch_timer_uses_ppi == ARCH_TIMER_VIRT_PPI) ? "virt" : "phys" :
879                         "",
880                 type == (ARCH_TIMER_TYPE_CP15 | ARCH_TIMER_TYPE_MEM) ? "/" : "",
881                 type & ARCH_TIMER_TYPE_MEM ?
882                         arch_timer_mem_use_virtual ? "virt" : "phys" :
883                         "");
884 }
885
886 u32 arch_timer_get_rate(void)
887 {
888         return arch_timer_rate;
889 }
890
891 static u64 arch_counter_get_cntvct_mem(void)
892 {
893         u32 vct_lo, vct_hi, tmp_hi;
894
895         do {
896                 vct_hi = readl_relaxed(arch_counter_base + CNTVCT_HI);
897                 vct_lo = readl_relaxed(arch_counter_base + CNTVCT_LO);
898                 tmp_hi = readl_relaxed(arch_counter_base + CNTVCT_HI);
899         } while (vct_hi != tmp_hi);
900
901         return ((u64) vct_hi << 32) | vct_lo;
902 }
903
904 static struct arch_timer_kvm_info arch_timer_kvm_info;
905
906 struct arch_timer_kvm_info *arch_timer_get_kvm_info(void)
907 {
908         return &arch_timer_kvm_info;
909 }
910
911 static void __init arch_counter_register(unsigned type)
912 {
913         u64 start_count;
914
915         /* Register the CP15 based counter if we have one */
916         if (type & ARCH_TIMER_TYPE_CP15) {
917                 if (IS_ENABLED(CONFIG_ARM64) ||
918                     arch_timer_uses_ppi == ARCH_TIMER_VIRT_PPI)
919                         arch_timer_read_counter = arch_counter_get_cntvct;
920                 else
921                         arch_timer_read_counter = arch_counter_get_cntpct;
922
923                 clocksource_counter.archdata.vdso_direct = vdso_default;
924         } else {
925                 arch_timer_read_counter = arch_counter_get_cntvct_mem;
926         }
927
928         if (!arch_counter_suspend_stop)
929                 clocksource_counter.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
930         start_count = arch_timer_read_counter();
931         clocksource_register_hz(&clocksource_counter, arch_timer_rate);
932         cyclecounter.mult = clocksource_counter.mult;
933         cyclecounter.shift = clocksource_counter.shift;
934         timecounter_init(&arch_timer_kvm_info.timecounter,
935                          &cyclecounter, start_count);
936
937         /* 56 bits minimum, so we assume worst case rollover */
938         sched_clock_register(arch_timer_read_counter, 56, arch_timer_rate);
939 }
940
941 static void arch_timer_stop(struct clock_event_device *clk)
942 {
943         pr_debug("disable IRQ%d cpu #%d\n", clk->irq, smp_processor_id());
944
945         disable_percpu_irq(arch_timer_ppi[arch_timer_uses_ppi]);
946         if (arch_timer_has_nonsecure_ppi())
947                 disable_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]);
948
949         clk->set_state_shutdown(clk);
950 }
951
952 static int arch_timer_dying_cpu(unsigned int cpu)
953 {
954         struct clock_event_device *clk = this_cpu_ptr(arch_timer_evt);
955
956         arch_timer_stop(clk);
957         return 0;
958 }
959
960 #ifdef CONFIG_CPU_PM
961 static DEFINE_PER_CPU(unsigned long, saved_cntkctl);
962 static int arch_timer_cpu_pm_notify(struct notifier_block *self,
963                                     unsigned long action, void *hcpu)
964 {
965         if (action == CPU_PM_ENTER)
966                 __this_cpu_write(saved_cntkctl, arch_timer_get_cntkctl());
967         else if (action == CPU_PM_ENTER_FAILED || action == CPU_PM_EXIT)
968                 arch_timer_set_cntkctl(__this_cpu_read(saved_cntkctl));
969         return NOTIFY_OK;
970 }
971
972 static struct notifier_block arch_timer_cpu_pm_notifier = {
973         .notifier_call = arch_timer_cpu_pm_notify,
974 };
975
976 static int __init arch_timer_cpu_pm_init(void)
977 {
978         return cpu_pm_register_notifier(&arch_timer_cpu_pm_notifier);
979 }
980
981 static void __init arch_timer_cpu_pm_deinit(void)
982 {
983         WARN_ON(cpu_pm_unregister_notifier(&arch_timer_cpu_pm_notifier));
984 }
985
986 #else
987 static int __init arch_timer_cpu_pm_init(void)
988 {
989         return 0;
990 }
991
992 static void __init arch_timer_cpu_pm_deinit(void)
993 {
994 }
995 #endif
996
997 static int __init arch_timer_register(void)
998 {
999         int err;
1000         int ppi;
1001
1002         arch_timer_evt = alloc_percpu(struct clock_event_device);
1003         if (!arch_timer_evt) {
1004                 err = -ENOMEM;
1005                 goto out;
1006         }
1007
1008         ppi = arch_timer_ppi[arch_timer_uses_ppi];
1009         switch (arch_timer_uses_ppi) {
1010         case ARCH_TIMER_VIRT_PPI:
1011                 err = request_percpu_irq(ppi, arch_timer_handler_virt,
1012                                          "arch_timer", arch_timer_evt);
1013                 break;
1014         case ARCH_TIMER_PHYS_SECURE_PPI:
1015         case ARCH_TIMER_PHYS_NONSECURE_PPI:
1016                 err = request_percpu_irq(ppi, arch_timer_handler_phys,
1017                                          "arch_timer", arch_timer_evt);
1018                 if (!err && arch_timer_has_nonsecure_ppi()) {
1019                         ppi = arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI];
1020                         err = request_percpu_irq(ppi, arch_timer_handler_phys,
1021                                                  "arch_timer", arch_timer_evt);
1022                         if (err)
1023                                 free_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_SECURE_PPI],
1024                                                 arch_timer_evt);
1025                 }
1026                 break;
1027         case ARCH_TIMER_HYP_PPI:
1028                 err = request_percpu_irq(ppi, arch_timer_handler_phys,
1029                                          "arch_timer", arch_timer_evt);
1030                 break;
1031         default:
1032                 BUG();
1033         }
1034
1035         if (err) {
1036                 pr_err("can't register interrupt %d (%d)\n", ppi, err);
1037                 goto out_free;
1038         }
1039
1040         err = arch_timer_cpu_pm_init();
1041         if (err)
1042                 goto out_unreg_notify;
1043
1044
1045         /* Register and immediately configure the timer on the boot CPU */
1046         err = cpuhp_setup_state(CPUHP_AP_ARM_ARCH_TIMER_STARTING,
1047                                 "clockevents/arm/arch_timer:starting",
1048                                 arch_timer_starting_cpu, arch_timer_dying_cpu);
1049         if (err)
1050                 goto out_unreg_cpupm;
1051         return 0;
1052
1053 out_unreg_cpupm:
1054         arch_timer_cpu_pm_deinit();
1055
1056 out_unreg_notify:
1057         free_percpu_irq(arch_timer_ppi[arch_timer_uses_ppi], arch_timer_evt);
1058         if (arch_timer_has_nonsecure_ppi())
1059                 free_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI],
1060                                 arch_timer_evt);
1061
1062 out_free:
1063         free_percpu(arch_timer_evt);
1064 out:
1065         return err;
1066 }
1067
1068 static int __init arch_timer_mem_register(void __iomem *base, unsigned int irq)
1069 {
1070         int ret;
1071         irq_handler_t func;
1072         struct arch_timer *t;
1073
1074         t = kzalloc(sizeof(*t), GFP_KERNEL);
1075         if (!t)
1076                 return -ENOMEM;
1077
1078         t->base = base;
1079         t->evt.irq = irq;
1080         __arch_timer_setup(ARCH_TIMER_TYPE_MEM, &t->evt);
1081
1082         if (arch_timer_mem_use_virtual)
1083                 func = arch_timer_handler_virt_mem;
1084         else
1085                 func = arch_timer_handler_phys_mem;
1086
1087         ret = request_irq(irq, func, IRQF_TIMER, "arch_mem_timer", &t->evt);
1088         if (ret) {
1089                 pr_err("Failed to request mem timer irq\n");
1090                 kfree(t);
1091         }
1092
1093         return ret;
1094 }
1095
1096 static const struct of_device_id arch_timer_of_match[] __initconst = {
1097         { .compatible   = "arm,armv7-timer",    },
1098         { .compatible   = "arm,armv8-timer",    },
1099         {},
1100 };
1101
1102 static const struct of_device_id arch_timer_mem_of_match[] __initconst = {
1103         { .compatible   = "arm,armv7-timer-mem", },
1104         {},
1105 };
1106
1107 static bool __init arch_timer_needs_of_probing(void)
1108 {
1109         struct device_node *dn;
1110         bool needs_probing = false;
1111         unsigned int mask = ARCH_TIMER_TYPE_CP15 | ARCH_TIMER_TYPE_MEM;
1112
1113         /* We have two timers, and both device-tree nodes are probed. */
1114         if ((arch_timers_present & mask) == mask)
1115                 return false;
1116
1117         /*
1118          * Only one type of timer is probed,
1119          * check if we have another type of timer node in device-tree.
1120          */
1121         if (arch_timers_present & ARCH_TIMER_TYPE_CP15)
1122                 dn = of_find_matching_node(NULL, arch_timer_mem_of_match);
1123         else
1124                 dn = of_find_matching_node(NULL, arch_timer_of_match);
1125
1126         if (dn && of_device_is_available(dn))
1127                 needs_probing = true;
1128
1129         of_node_put(dn);
1130
1131         return needs_probing;
1132 }
1133
1134 static int __init arch_timer_common_init(void)
1135 {
1136         arch_timer_banner(arch_timers_present);
1137         arch_counter_register(arch_timers_present);
1138         return arch_timer_arch_init();
1139 }
1140
1141 /**
1142  * arch_timer_select_ppi() - Select suitable PPI for the current system.
1143  *
1144  * If HYP mode is available, we know that the physical timer
1145  * has been configured to be accessible from PL1. Use it, so
1146  * that a guest can use the virtual timer instead.
1147  *
1148  * On ARMv8.1 with VH extensions, the kernel runs in HYP. VHE
1149  * accesses to CNTP_*_EL1 registers are silently redirected to
1150  * their CNTHP_*_EL2 counterparts, and use a different PPI
1151  * number.
1152  *
1153  * If no interrupt provided for virtual timer, we'll have to
1154  * stick to the physical timer. It'd better be accessible...
1155  * For arm64 we never use the secure interrupt.
1156  *
1157  * Return: a suitable PPI type for the current system.
1158  */
1159 static enum arch_timer_ppi_nr __init arch_timer_select_ppi(void)
1160 {
1161         if (is_kernel_in_hyp_mode())
1162                 return ARCH_TIMER_HYP_PPI;
1163
1164         if (!is_hyp_mode_available() && arch_timer_ppi[ARCH_TIMER_VIRT_PPI])
1165                 return ARCH_TIMER_VIRT_PPI;
1166
1167         if (IS_ENABLED(CONFIG_ARM64))
1168                 return ARCH_TIMER_PHYS_NONSECURE_PPI;
1169
1170         return ARCH_TIMER_PHYS_SECURE_PPI;
1171 }
1172
1173 static int __init arch_timer_of_init(struct device_node *np)
1174 {
1175         int i, ret;
1176         u32 rate;
1177
1178         if (arch_timers_present & ARCH_TIMER_TYPE_CP15) {
1179                 pr_warn("multiple nodes in dt, skipping\n");
1180                 return 0;
1181         }
1182
1183         arch_timers_present |= ARCH_TIMER_TYPE_CP15;
1184         for (i = ARCH_TIMER_PHYS_SECURE_PPI; i < ARCH_TIMER_MAX_TIMER_PPI; i++)
1185                 arch_timer_ppi[i] = irq_of_parse_and_map(np, i);
1186
1187         arch_timer_kvm_info.virtual_irq = arch_timer_ppi[ARCH_TIMER_VIRT_PPI];
1188
1189         rate = arch_timer_get_cntfrq();
1190         arch_timer_of_configure_rate(rate, np);
1191
1192         arch_timer_c3stop = !of_property_read_bool(np, "always-on");
1193
1194         /* Check for globally applicable workarounds */
1195         arch_timer_check_ool_workaround(ate_match_dt, np);
1196
1197         /*
1198          * If we cannot rely on firmware initializing the timer registers then
1199          * we should use the physical timers instead.
1200          */
1201         if (IS_ENABLED(CONFIG_ARM) &&
1202             of_property_read_bool(np, "arm,cpu-registers-not-fw-configured"))
1203                 arch_timer_uses_ppi = ARCH_TIMER_PHYS_SECURE_PPI;
1204         else
1205                 arch_timer_uses_ppi = arch_timer_select_ppi();
1206
1207         if (!arch_timer_ppi[arch_timer_uses_ppi]) {
1208                 pr_err("No interrupt available, giving up\n");
1209                 return -EINVAL;
1210         }
1211
1212         /* On some systems, the counter stops ticking when in suspend. */
1213         arch_counter_suspend_stop = of_property_read_bool(np,
1214                                                          "arm,no-tick-in-suspend");
1215
1216         ret = arch_timer_register();
1217         if (ret)
1218                 return ret;
1219
1220         if (arch_timer_needs_of_probing())
1221                 return 0;
1222
1223         return arch_timer_common_init();
1224 }
1225 TIMER_OF_DECLARE(armv7_arch_timer, "arm,armv7-timer", arch_timer_of_init);
1226 TIMER_OF_DECLARE(armv8_arch_timer, "arm,armv8-timer", arch_timer_of_init);
1227
1228 static u32 __init
1229 arch_timer_mem_frame_get_cntfrq(struct arch_timer_mem_frame *frame)
1230 {
1231         void __iomem *base;
1232         u32 rate;
1233
1234         base = ioremap(frame->cntbase, frame->size);
1235         if (!base) {
1236                 pr_err("Unable to map frame @ %pa\n", &frame->cntbase);
1237                 return 0;
1238         }
1239
1240         rate = readl_relaxed(base + CNTFRQ);
1241
1242         iounmap(base);
1243
1244         return rate;
1245 }
1246
1247 static struct arch_timer_mem_frame * __init
1248 arch_timer_mem_find_best_frame(struct arch_timer_mem *timer_mem)
1249 {
1250         struct arch_timer_mem_frame *frame, *best_frame = NULL;
1251         void __iomem *cntctlbase;
1252         u32 cnttidr;
1253         int i;
1254
1255         cntctlbase = ioremap(timer_mem->cntctlbase, timer_mem->size);
1256         if (!cntctlbase) {
1257                 pr_err("Can't map CNTCTLBase @ %pa\n",
1258                         &timer_mem->cntctlbase);
1259                 return NULL;
1260         }
1261
1262         cnttidr = readl_relaxed(cntctlbase + CNTTIDR);
1263
1264         /*
1265          * Try to find a virtual capable frame. Otherwise fall back to a
1266          * physical capable frame.
1267          */
1268         for (i = 0; i < ARCH_TIMER_MEM_MAX_FRAMES; i++) {
1269                 u32 cntacr = CNTACR_RFRQ | CNTACR_RWPT | CNTACR_RPCT |
1270                              CNTACR_RWVT | CNTACR_RVOFF | CNTACR_RVCT;
1271
1272                 frame = &timer_mem->frame[i];
1273                 if (!frame->valid)
1274                         continue;
1275
1276                 /* Try enabling everything, and see what sticks */
1277                 writel_relaxed(cntacr, cntctlbase + CNTACR(i));
1278                 cntacr = readl_relaxed(cntctlbase + CNTACR(i));
1279
1280                 if ((cnttidr & CNTTIDR_VIRT(i)) &&
1281                     !(~cntacr & (CNTACR_RWVT | CNTACR_RVCT))) {
1282                         best_frame = frame;
1283                         arch_timer_mem_use_virtual = true;
1284                         break;
1285                 }
1286
1287                 if (~cntacr & (CNTACR_RWPT | CNTACR_RPCT))
1288                         continue;
1289
1290                 best_frame = frame;
1291         }
1292
1293         iounmap(cntctlbase);
1294
1295         return best_frame;
1296 }
1297
1298 static int __init
1299 arch_timer_mem_frame_register(struct arch_timer_mem_frame *frame)
1300 {
1301         void __iomem *base;
1302         int ret, irq = 0;
1303
1304         if (arch_timer_mem_use_virtual)
1305                 irq = frame->virt_irq;
1306         else
1307                 irq = frame->phys_irq;
1308
1309         if (!irq) {
1310                 pr_err("Frame missing %s irq.\n",
1311                        arch_timer_mem_use_virtual ? "virt" : "phys");
1312                 return -EINVAL;
1313         }
1314
1315         if (!request_mem_region(frame->cntbase, frame->size,
1316                                 "arch_mem_timer"))
1317                 return -EBUSY;
1318
1319         base = ioremap(frame->cntbase, frame->size);
1320         if (!base) {
1321                 pr_err("Can't map frame's registers\n");
1322                 return -ENXIO;
1323         }
1324
1325         ret = arch_timer_mem_register(base, irq);
1326         if (ret) {
1327                 iounmap(base);
1328                 return ret;
1329         }
1330
1331         arch_counter_base = base;
1332         arch_timers_present |= ARCH_TIMER_TYPE_MEM;
1333
1334         return 0;
1335 }
1336
1337 static int __init arch_timer_mem_of_init(struct device_node *np)
1338 {
1339         struct arch_timer_mem *timer_mem;
1340         struct arch_timer_mem_frame *frame;
1341         struct device_node *frame_node;
1342         struct resource res;
1343         int ret = -EINVAL;
1344         u32 rate;
1345
1346         timer_mem = kzalloc(sizeof(*timer_mem), GFP_KERNEL);
1347         if (!timer_mem)
1348                 return -ENOMEM;
1349
1350         if (of_address_to_resource(np, 0, &res))
1351                 goto out;
1352         timer_mem->cntctlbase = res.start;
1353         timer_mem->size = resource_size(&res);
1354
1355         for_each_available_child_of_node(np, frame_node) {
1356                 u32 n;
1357                 struct arch_timer_mem_frame *frame;
1358
1359                 if (of_property_read_u32(frame_node, "frame-number", &n)) {
1360                         pr_err(FW_BUG "Missing frame-number.\n");
1361                         of_node_put(frame_node);
1362                         goto out;
1363                 }
1364                 if (n >= ARCH_TIMER_MEM_MAX_FRAMES) {
1365                         pr_err(FW_BUG "Wrong frame-number, only 0-%u are permitted.\n",
1366                                ARCH_TIMER_MEM_MAX_FRAMES - 1);
1367                         of_node_put(frame_node);
1368                         goto out;
1369                 }
1370                 frame = &timer_mem->frame[n];
1371
1372                 if (frame->valid) {
1373                         pr_err(FW_BUG "Duplicated frame-number.\n");
1374                         of_node_put(frame_node);
1375                         goto out;
1376                 }
1377
1378                 if (of_address_to_resource(frame_node, 0, &res)) {
1379                         of_node_put(frame_node);
1380                         goto out;
1381                 }
1382                 frame->cntbase = res.start;
1383                 frame->size = resource_size(&res);
1384
1385                 frame->virt_irq = irq_of_parse_and_map(frame_node,
1386                                                        ARCH_TIMER_VIRT_SPI);
1387                 frame->phys_irq = irq_of_parse_and_map(frame_node,
1388                                                        ARCH_TIMER_PHYS_SPI);
1389
1390                 frame->valid = true;
1391         }
1392
1393         frame = arch_timer_mem_find_best_frame(timer_mem);
1394         if (!frame) {
1395                 pr_err("Unable to find a suitable frame in timer @ %pa\n",
1396                         &timer_mem->cntctlbase);
1397                 ret = -EINVAL;
1398                 goto out;
1399         }
1400
1401         rate = arch_timer_mem_frame_get_cntfrq(frame);
1402         arch_timer_of_configure_rate(rate, np);
1403
1404         ret = arch_timer_mem_frame_register(frame);
1405         if (!ret && !arch_timer_needs_of_probing())
1406                 ret = arch_timer_common_init();
1407 out:
1408         kfree(timer_mem);
1409         return ret;
1410 }
1411 TIMER_OF_DECLARE(armv7_arch_timer_mem, "arm,armv7-timer-mem",
1412                        arch_timer_mem_of_init);
1413
1414 #ifdef CONFIG_ACPI_GTDT
1415 static int __init
1416 arch_timer_mem_verify_cntfrq(struct arch_timer_mem *timer_mem)
1417 {
1418         struct arch_timer_mem_frame *frame;
1419         u32 rate;
1420         int i;
1421
1422         for (i = 0; i < ARCH_TIMER_MEM_MAX_FRAMES; i++) {
1423                 frame = &timer_mem->frame[i];
1424
1425                 if (!frame->valid)
1426                         continue;
1427
1428                 rate = arch_timer_mem_frame_get_cntfrq(frame);
1429                 if (rate == arch_timer_rate)
1430                         continue;
1431
1432                 pr_err(FW_BUG "CNTFRQ mismatch: frame @ %pa: (0x%08lx), CPU: (0x%08lx)\n",
1433                         &frame->cntbase,
1434                         (unsigned long)rate, (unsigned long)arch_timer_rate);
1435
1436                 return -EINVAL;
1437         }
1438
1439         return 0;
1440 }
1441
1442 static int __init arch_timer_mem_acpi_init(int platform_timer_count)
1443 {
1444         struct arch_timer_mem *timers, *timer;
1445         struct arch_timer_mem_frame *frame, *best_frame = NULL;
1446         int timer_count, i, ret = 0;
1447
1448         timers = kcalloc(platform_timer_count, sizeof(*timers),
1449                             GFP_KERNEL);
1450         if (!timers)
1451                 return -ENOMEM;
1452
1453         ret = acpi_arch_timer_mem_init(timers, &timer_count);
1454         if (ret || !timer_count)
1455                 goto out;
1456
1457         /*
1458          * While unlikely, it's theoretically possible that none of the frames
1459          * in a timer expose the combination of feature we want.
1460          */
1461         for (i = 0; i < timer_count; i++) {
1462                 timer = &timers[i];
1463
1464                 frame = arch_timer_mem_find_best_frame(timer);
1465                 if (!best_frame)
1466                         best_frame = frame;
1467
1468                 ret = arch_timer_mem_verify_cntfrq(timer);
1469                 if (ret) {
1470                         pr_err("Disabling MMIO timers due to CNTFRQ mismatch\n");
1471                         goto out;
1472                 }
1473
1474                 if (!best_frame) /* implies !frame */
1475                         /*
1476                          * Only complain about missing suitable frames if we
1477                          * haven't already found one in a previous iteration.
1478                          */
1479                         pr_err("Unable to find a suitable frame in timer @ %pa\n",
1480                                 &timer->cntctlbase);
1481         }
1482
1483         if (best_frame)
1484                 ret = arch_timer_mem_frame_register(best_frame);
1485 out:
1486         kfree(timers);
1487         return ret;
1488 }
1489
1490 /* Initialize per-processor generic timer and memory-mapped timer(if present) */
1491 static int __init arch_timer_acpi_init(struct acpi_table_header *table)
1492 {
1493         int ret, platform_timer_count;
1494
1495         if (arch_timers_present & ARCH_TIMER_TYPE_CP15) {
1496                 pr_warn("already initialized, skipping\n");
1497                 return -EINVAL;
1498         }
1499
1500         arch_timers_present |= ARCH_TIMER_TYPE_CP15;
1501
1502         ret = acpi_gtdt_init(table, &platform_timer_count);
1503         if (ret) {
1504                 pr_err("Failed to init GTDT table.\n");
1505                 return ret;
1506         }
1507
1508         arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI] =
1509                 acpi_gtdt_map_ppi(ARCH_TIMER_PHYS_NONSECURE_PPI);
1510
1511         arch_timer_ppi[ARCH_TIMER_VIRT_PPI] =
1512                 acpi_gtdt_map_ppi(ARCH_TIMER_VIRT_PPI);
1513
1514         arch_timer_ppi[ARCH_TIMER_HYP_PPI] =
1515                 acpi_gtdt_map_ppi(ARCH_TIMER_HYP_PPI);
1516
1517         arch_timer_kvm_info.virtual_irq = arch_timer_ppi[ARCH_TIMER_VIRT_PPI];
1518
1519         /*
1520          * When probing via ACPI, we have no mechanism to override the sysreg
1521          * CNTFRQ value. This *must* be correct.
1522          */
1523         arch_timer_rate = arch_timer_get_cntfrq();
1524         if (!arch_timer_rate) {
1525                 pr_err(FW_BUG "frequency not available.\n");
1526                 return -EINVAL;
1527         }
1528
1529         arch_timer_uses_ppi = arch_timer_select_ppi();
1530         if (!arch_timer_ppi[arch_timer_uses_ppi]) {
1531                 pr_err("No interrupt available, giving up\n");
1532                 return -EINVAL;
1533         }
1534
1535         /* Always-on capability */
1536         arch_timer_c3stop = acpi_gtdt_c3stop(arch_timer_uses_ppi);
1537
1538         /* Check for globally applicable workarounds */
1539         arch_timer_check_ool_workaround(ate_match_acpi_oem_info, table);
1540
1541         ret = arch_timer_register();
1542         if (ret)
1543                 return ret;
1544
1545         if (platform_timer_count &&
1546             arch_timer_mem_acpi_init(platform_timer_count))
1547                 pr_err("Failed to initialize memory-mapped timer.\n");
1548
1549         return arch_timer_common_init();
1550 }
1551 TIMER_ACPI_DECLARE(arch_timer, ACPI_SIG_GTDT, arch_timer_acpi_init);
1552 #endif