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