xref: /linux/drivers/clocksource/arm_arch_timer.c (revision 43347d56c8d9dd732cee2f8efd384ad21dd1f6c4)
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_ARM_ARCH_TIMER_OOL_WORKAROUND
302 DEFINE_PER_CPU(const struct arch_timer_erratum_workaround *, timer_unstable_counter_workaround);
303 EXPORT_SYMBOL_GPL(timer_unstable_counter_workaround);
304 
305 DEFINE_STATIC_KEY_FALSE(arch_timer_read_ool_enabled);
306 EXPORT_SYMBOL_GPL(arch_timer_read_ool_enabled);
307 
308 static void erratum_set_next_event_tval_generic(const int access, unsigned long evt,
309 						struct clock_event_device *clk)
310 {
311 	unsigned long ctrl;
312 	u64 cval = evt + arch_counter_get_cntvct();
313 
314 	ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
315 	ctrl |= ARCH_TIMER_CTRL_ENABLE;
316 	ctrl &= ~ARCH_TIMER_CTRL_IT_MASK;
317 
318 	if (access == ARCH_TIMER_PHYS_ACCESS)
319 		write_sysreg(cval, cntp_cval_el0);
320 	else
321 		write_sysreg(cval, cntv_cval_el0);
322 
323 	arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
324 }
325 
326 static __maybe_unused int erratum_set_next_event_tval_virt(unsigned long evt,
327 					    struct clock_event_device *clk)
328 {
329 	erratum_set_next_event_tval_generic(ARCH_TIMER_VIRT_ACCESS, evt, clk);
330 	return 0;
331 }
332 
333 static __maybe_unused int erratum_set_next_event_tval_phys(unsigned long evt,
334 					    struct clock_event_device *clk)
335 {
336 	erratum_set_next_event_tval_generic(ARCH_TIMER_PHYS_ACCESS, evt, clk);
337 	return 0;
338 }
339 
340 static const struct arch_timer_erratum_workaround ool_workarounds[] = {
341 #ifdef CONFIG_FSL_ERRATUM_A008585
342 	{
343 		.match_type = ate_match_dt,
344 		.id = "fsl,erratum-a008585",
345 		.desc = "Freescale erratum a005858",
346 		.read_cntp_tval_el0 = fsl_a008585_read_cntp_tval_el0,
347 		.read_cntv_tval_el0 = fsl_a008585_read_cntv_tval_el0,
348 		.read_cntvct_el0 = fsl_a008585_read_cntvct_el0,
349 		.set_next_event_phys = erratum_set_next_event_tval_phys,
350 		.set_next_event_virt = erratum_set_next_event_tval_virt,
351 	},
352 #endif
353 #ifdef CONFIG_HISILICON_ERRATUM_161010101
354 	{
355 		.match_type = ate_match_dt,
356 		.id = "hisilicon,erratum-161010101",
357 		.desc = "HiSilicon erratum 161010101",
358 		.read_cntp_tval_el0 = hisi_161010101_read_cntp_tval_el0,
359 		.read_cntv_tval_el0 = hisi_161010101_read_cntv_tval_el0,
360 		.read_cntvct_el0 = hisi_161010101_read_cntvct_el0,
361 		.set_next_event_phys = erratum_set_next_event_tval_phys,
362 		.set_next_event_virt = erratum_set_next_event_tval_virt,
363 	},
364 	{
365 		.match_type = ate_match_acpi_oem_info,
366 		.id = hisi_161010101_oem_info,
367 		.desc = "HiSilicon erratum 161010101",
368 		.read_cntp_tval_el0 = hisi_161010101_read_cntp_tval_el0,
369 		.read_cntv_tval_el0 = hisi_161010101_read_cntv_tval_el0,
370 		.read_cntvct_el0 = hisi_161010101_read_cntvct_el0,
371 		.set_next_event_phys = erratum_set_next_event_tval_phys,
372 		.set_next_event_virt = erratum_set_next_event_tval_virt,
373 	},
374 #endif
375 #ifdef CONFIG_ARM64_ERRATUM_858921
376 	{
377 		.match_type = ate_match_local_cap_id,
378 		.id = (void *)ARM64_WORKAROUND_858921,
379 		.desc = "ARM erratum 858921",
380 		.read_cntvct_el0 = arm64_858921_read_cntvct_el0,
381 	},
382 #endif
383 };
384 
385 typedef bool (*ate_match_fn_t)(const struct arch_timer_erratum_workaround *,
386 			       const void *);
387 
388 static
389 bool arch_timer_check_dt_erratum(const struct arch_timer_erratum_workaround *wa,
390 				 const void *arg)
391 {
392 	const struct device_node *np = arg;
393 
394 	return of_property_read_bool(np, wa->id);
395 }
396 
397 static
398 bool arch_timer_check_local_cap_erratum(const struct arch_timer_erratum_workaround *wa,
399 					const void *arg)
400 {
401 	return this_cpu_has_cap((uintptr_t)wa->id);
402 }
403 
404 
405 static
406 bool arch_timer_check_acpi_oem_erratum(const struct arch_timer_erratum_workaround *wa,
407 				       const void *arg)
408 {
409 	static const struct ate_acpi_oem_info empty_oem_info = {};
410 	const struct ate_acpi_oem_info *info = wa->id;
411 	const struct acpi_table_header *table = arg;
412 
413 	/* Iterate over the ACPI OEM info array, looking for a match */
414 	while (memcmp(info, &empty_oem_info, sizeof(*info))) {
415 		if (!memcmp(info->oem_id, table->oem_id, ACPI_OEM_ID_SIZE) &&
416 		    !memcmp(info->oem_table_id, table->oem_table_id, ACPI_OEM_TABLE_ID_SIZE) &&
417 		    info->oem_revision == table->oem_revision)
418 			return true;
419 
420 		info++;
421 	}
422 
423 	return false;
424 }
425 
426 static const struct arch_timer_erratum_workaround *
427 arch_timer_iterate_errata(enum arch_timer_erratum_match_type type,
428 			  ate_match_fn_t match_fn,
429 			  void *arg)
430 {
431 	int i;
432 
433 	for (i = 0; i < ARRAY_SIZE(ool_workarounds); i++) {
434 		if (ool_workarounds[i].match_type != type)
435 			continue;
436 
437 		if (match_fn(&ool_workarounds[i], arg))
438 			return &ool_workarounds[i];
439 	}
440 
441 	return NULL;
442 }
443 
444 static
445 void arch_timer_enable_workaround(const struct arch_timer_erratum_workaround *wa,
446 				  bool local)
447 {
448 	int i;
449 
450 	if (local) {
451 		__this_cpu_write(timer_unstable_counter_workaround, wa);
452 	} else {
453 		for_each_possible_cpu(i)
454 			per_cpu(timer_unstable_counter_workaround, i) = wa;
455 	}
456 
457 	/*
458 	 * Use the locked version, as we're called from the CPU
459 	 * hotplug framework. Otherwise, we end-up in deadlock-land.
460 	 */
461 	static_branch_enable_cpuslocked(&arch_timer_read_ool_enabled);
462 
463 	/*
464 	 * Don't use the vdso fastpath if errata require using the
465 	 * out-of-line counter accessor. We may change our mind pretty
466 	 * late in the game (with a per-CPU erratum, for example), so
467 	 * change both the default value and the vdso itself.
468 	 */
469 	if (wa->read_cntvct_el0) {
470 		clocksource_counter.archdata.vdso_direct = false;
471 		vdso_default = false;
472 	}
473 }
474 
475 static void arch_timer_check_ool_workaround(enum arch_timer_erratum_match_type type,
476 					    void *arg)
477 {
478 	const struct arch_timer_erratum_workaround *wa;
479 	ate_match_fn_t match_fn = NULL;
480 	bool local = false;
481 
482 	switch (type) {
483 	case ate_match_dt:
484 		match_fn = arch_timer_check_dt_erratum;
485 		break;
486 	case ate_match_local_cap_id:
487 		match_fn = arch_timer_check_local_cap_erratum;
488 		local = true;
489 		break;
490 	case ate_match_acpi_oem_info:
491 		match_fn = arch_timer_check_acpi_oem_erratum;
492 		break;
493 	default:
494 		WARN_ON(1);
495 		return;
496 	}
497 
498 	wa = arch_timer_iterate_errata(type, match_fn, arg);
499 	if (!wa)
500 		return;
501 
502 	if (needs_unstable_timer_counter_workaround()) {
503 		const struct arch_timer_erratum_workaround *__wa;
504 		__wa = __this_cpu_read(timer_unstable_counter_workaround);
505 		if (__wa && wa != __wa)
506 			pr_warn("Can't enable workaround for %s (clashes with %s\n)",
507 				wa->desc, __wa->desc);
508 
509 		if (__wa)
510 			return;
511 	}
512 
513 	arch_timer_enable_workaround(wa, local);
514 	pr_info("Enabling %s workaround for %s\n",
515 		local ? "local" : "global", wa->desc);
516 }
517 
518 #define erratum_handler(fn, r, ...)					\
519 ({									\
520 	bool __val;							\
521 	if (needs_unstable_timer_counter_workaround()) {		\
522 		const struct arch_timer_erratum_workaround *__wa;	\
523 		__wa = __this_cpu_read(timer_unstable_counter_workaround); \
524 		if (__wa && __wa->fn) {					\
525 			r = __wa->fn(__VA_ARGS__);			\
526 			__val = true;					\
527 		} else {						\
528 			__val = false;					\
529 		}							\
530 	} else {							\
531 		__val = false;						\
532 	}								\
533 	__val;								\
534 })
535 
536 static bool arch_timer_this_cpu_has_cntvct_wa(void)
537 {
538 	const struct arch_timer_erratum_workaround *wa;
539 
540 	wa = __this_cpu_read(timer_unstable_counter_workaround);
541 	return wa && wa->read_cntvct_el0;
542 }
543 #else
544 #define arch_timer_check_ool_workaround(t,a)		do { } while(0)
545 #define erratum_set_next_event_tval_virt(...)		({BUG(); 0;})
546 #define erratum_set_next_event_tval_phys(...)		({BUG(); 0;})
547 #define erratum_handler(fn, r, ...)			({false;})
548 #define arch_timer_this_cpu_has_cntvct_wa()		({false;})
549 #endif /* CONFIG_ARM_ARCH_TIMER_OOL_WORKAROUND */
550 
551 static __always_inline irqreturn_t timer_handler(const int access,
552 					struct clock_event_device *evt)
553 {
554 	unsigned long ctrl;
555 
556 	ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, evt);
557 	if (ctrl & ARCH_TIMER_CTRL_IT_STAT) {
558 		ctrl |= ARCH_TIMER_CTRL_IT_MASK;
559 		arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, evt);
560 		evt->event_handler(evt);
561 		return IRQ_HANDLED;
562 	}
563 
564 	return IRQ_NONE;
565 }
566 
567 static irqreturn_t arch_timer_handler_virt(int irq, void *dev_id)
568 {
569 	struct clock_event_device *evt = dev_id;
570 
571 	return timer_handler(ARCH_TIMER_VIRT_ACCESS, evt);
572 }
573 
574 static irqreturn_t arch_timer_handler_phys(int irq, void *dev_id)
575 {
576 	struct clock_event_device *evt = dev_id;
577 
578 	return timer_handler(ARCH_TIMER_PHYS_ACCESS, evt);
579 }
580 
581 static irqreturn_t arch_timer_handler_phys_mem(int irq, void *dev_id)
582 {
583 	struct clock_event_device *evt = dev_id;
584 
585 	return timer_handler(ARCH_TIMER_MEM_PHYS_ACCESS, evt);
586 }
587 
588 static irqreturn_t arch_timer_handler_virt_mem(int irq, void *dev_id)
589 {
590 	struct clock_event_device *evt = dev_id;
591 
592 	return timer_handler(ARCH_TIMER_MEM_VIRT_ACCESS, evt);
593 }
594 
595 static __always_inline int timer_shutdown(const int access,
596 					  struct clock_event_device *clk)
597 {
598 	unsigned long ctrl;
599 
600 	ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
601 	ctrl &= ~ARCH_TIMER_CTRL_ENABLE;
602 	arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
603 
604 	return 0;
605 }
606 
607 static int arch_timer_shutdown_virt(struct clock_event_device *clk)
608 {
609 	return timer_shutdown(ARCH_TIMER_VIRT_ACCESS, clk);
610 }
611 
612 static int arch_timer_shutdown_phys(struct clock_event_device *clk)
613 {
614 	return timer_shutdown(ARCH_TIMER_PHYS_ACCESS, clk);
615 }
616 
617 static int arch_timer_shutdown_virt_mem(struct clock_event_device *clk)
618 {
619 	return timer_shutdown(ARCH_TIMER_MEM_VIRT_ACCESS, clk);
620 }
621 
622 static int arch_timer_shutdown_phys_mem(struct clock_event_device *clk)
623 {
624 	return timer_shutdown(ARCH_TIMER_MEM_PHYS_ACCESS, clk);
625 }
626 
627 static __always_inline void set_next_event(const int access, unsigned long evt,
628 					   struct clock_event_device *clk)
629 {
630 	unsigned long ctrl;
631 	ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
632 	ctrl |= ARCH_TIMER_CTRL_ENABLE;
633 	ctrl &= ~ARCH_TIMER_CTRL_IT_MASK;
634 	arch_timer_reg_write(access, ARCH_TIMER_REG_TVAL, evt, clk);
635 	arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
636 }
637 
638 static int arch_timer_set_next_event_virt(unsigned long evt,
639 					  struct clock_event_device *clk)
640 {
641 	int ret;
642 
643 	if (erratum_handler(set_next_event_virt, ret, evt, clk))
644 		return ret;
645 
646 	set_next_event(ARCH_TIMER_VIRT_ACCESS, evt, clk);
647 	return 0;
648 }
649 
650 static int arch_timer_set_next_event_phys(unsigned long evt,
651 					  struct clock_event_device *clk)
652 {
653 	int ret;
654 
655 	if (erratum_handler(set_next_event_phys, ret, evt, clk))
656 		return ret;
657 
658 	set_next_event(ARCH_TIMER_PHYS_ACCESS, evt, clk);
659 	return 0;
660 }
661 
662 static int arch_timer_set_next_event_virt_mem(unsigned long evt,
663 					      struct clock_event_device *clk)
664 {
665 	set_next_event(ARCH_TIMER_MEM_VIRT_ACCESS, evt, clk);
666 	return 0;
667 }
668 
669 static int arch_timer_set_next_event_phys_mem(unsigned long evt,
670 					      struct clock_event_device *clk)
671 {
672 	set_next_event(ARCH_TIMER_MEM_PHYS_ACCESS, evt, clk);
673 	return 0;
674 }
675 
676 static void __arch_timer_setup(unsigned type,
677 			       struct clock_event_device *clk)
678 {
679 	clk->features = CLOCK_EVT_FEAT_ONESHOT;
680 
681 	if (type == ARCH_TIMER_TYPE_CP15) {
682 		if (arch_timer_c3stop)
683 			clk->features |= CLOCK_EVT_FEAT_C3STOP;
684 		clk->name = "arch_sys_timer";
685 		clk->rating = 450;
686 		clk->cpumask = cpumask_of(smp_processor_id());
687 		clk->irq = arch_timer_ppi[arch_timer_uses_ppi];
688 		switch (arch_timer_uses_ppi) {
689 		case ARCH_TIMER_VIRT_PPI:
690 			clk->set_state_shutdown = arch_timer_shutdown_virt;
691 			clk->set_state_oneshot_stopped = arch_timer_shutdown_virt;
692 			clk->set_next_event = arch_timer_set_next_event_virt;
693 			break;
694 		case ARCH_TIMER_PHYS_SECURE_PPI:
695 		case ARCH_TIMER_PHYS_NONSECURE_PPI:
696 		case ARCH_TIMER_HYP_PPI:
697 			clk->set_state_shutdown = arch_timer_shutdown_phys;
698 			clk->set_state_oneshot_stopped = arch_timer_shutdown_phys;
699 			clk->set_next_event = arch_timer_set_next_event_phys;
700 			break;
701 		default:
702 			BUG();
703 		}
704 
705 		arch_timer_check_ool_workaround(ate_match_local_cap_id, NULL);
706 	} else {
707 		clk->features |= CLOCK_EVT_FEAT_DYNIRQ;
708 		clk->name = "arch_mem_timer";
709 		clk->rating = 400;
710 		clk->cpumask = cpu_all_mask;
711 		if (arch_timer_mem_use_virtual) {
712 			clk->set_state_shutdown = arch_timer_shutdown_virt_mem;
713 			clk->set_state_oneshot_stopped = arch_timer_shutdown_virt_mem;
714 			clk->set_next_event =
715 				arch_timer_set_next_event_virt_mem;
716 		} else {
717 			clk->set_state_shutdown = arch_timer_shutdown_phys_mem;
718 			clk->set_state_oneshot_stopped = arch_timer_shutdown_phys_mem;
719 			clk->set_next_event =
720 				arch_timer_set_next_event_phys_mem;
721 		}
722 	}
723 
724 	clk->set_state_shutdown(clk);
725 
726 	clockevents_config_and_register(clk, arch_timer_rate, 0xf, 0x7fffffff);
727 }
728 
729 static void arch_timer_evtstrm_enable(int divider)
730 {
731 	u32 cntkctl = arch_timer_get_cntkctl();
732 
733 	cntkctl &= ~ARCH_TIMER_EVT_TRIGGER_MASK;
734 	/* Set the divider and enable virtual event stream */
735 	cntkctl |= (divider << ARCH_TIMER_EVT_TRIGGER_SHIFT)
736 			| ARCH_TIMER_VIRT_EVT_EN;
737 	arch_timer_set_cntkctl(cntkctl);
738 	elf_hwcap |= HWCAP_EVTSTRM;
739 #ifdef CONFIG_COMPAT
740 	compat_elf_hwcap |= COMPAT_HWCAP_EVTSTRM;
741 #endif
742 }
743 
744 static void arch_timer_configure_evtstream(void)
745 {
746 	int evt_stream_div, pos;
747 
748 	/* Find the closest power of two to the divisor */
749 	evt_stream_div = arch_timer_rate / ARCH_TIMER_EVT_STREAM_FREQ;
750 	pos = fls(evt_stream_div);
751 	if (pos > 1 && !(evt_stream_div & (1 << (pos - 2))))
752 		pos--;
753 	/* enable event stream */
754 	arch_timer_evtstrm_enable(min(pos, 15));
755 }
756 
757 static void arch_counter_set_user_access(void)
758 {
759 	u32 cntkctl = arch_timer_get_cntkctl();
760 
761 	/* Disable user access to the timers and both counters */
762 	/* Also disable virtual event stream */
763 	cntkctl &= ~(ARCH_TIMER_USR_PT_ACCESS_EN
764 			| ARCH_TIMER_USR_VT_ACCESS_EN
765 		        | ARCH_TIMER_USR_VCT_ACCESS_EN
766 			| ARCH_TIMER_VIRT_EVT_EN
767 			| ARCH_TIMER_USR_PCT_ACCESS_EN);
768 
769 	/*
770 	 * Enable user access to the virtual counter if it doesn't
771 	 * need to be workaround. The vdso may have been already
772 	 * disabled though.
773 	 */
774 	if (arch_timer_this_cpu_has_cntvct_wa())
775 		pr_info("CPU%d: Trapping CNTVCT access\n", smp_processor_id());
776 	else
777 		cntkctl |= ARCH_TIMER_USR_VCT_ACCESS_EN;
778 
779 	arch_timer_set_cntkctl(cntkctl);
780 }
781 
782 static bool arch_timer_has_nonsecure_ppi(void)
783 {
784 	return (arch_timer_uses_ppi == ARCH_TIMER_PHYS_SECURE_PPI &&
785 		arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]);
786 }
787 
788 static u32 check_ppi_trigger(int irq)
789 {
790 	u32 flags = irq_get_trigger_type(irq);
791 
792 	if (flags != IRQF_TRIGGER_HIGH && flags != IRQF_TRIGGER_LOW) {
793 		pr_warn("WARNING: Invalid trigger for IRQ%d, assuming level low\n", irq);
794 		pr_warn("WARNING: Please fix your firmware\n");
795 		flags = IRQF_TRIGGER_LOW;
796 	}
797 
798 	return flags;
799 }
800 
801 static int arch_timer_starting_cpu(unsigned int cpu)
802 {
803 	struct clock_event_device *clk = this_cpu_ptr(arch_timer_evt);
804 	u32 flags;
805 
806 	__arch_timer_setup(ARCH_TIMER_TYPE_CP15, clk);
807 
808 	flags = check_ppi_trigger(arch_timer_ppi[arch_timer_uses_ppi]);
809 	enable_percpu_irq(arch_timer_ppi[arch_timer_uses_ppi], flags);
810 
811 	if (arch_timer_has_nonsecure_ppi()) {
812 		flags = check_ppi_trigger(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]);
813 		enable_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI],
814 				  flags);
815 	}
816 
817 	arch_counter_set_user_access();
818 	if (evtstrm_enable)
819 		arch_timer_configure_evtstream();
820 
821 	return 0;
822 }
823 
824 /*
825  * For historical reasons, when probing with DT we use whichever (non-zero)
826  * rate was probed first, and don't verify that others match. If the first node
827  * probed has a clock-frequency property, this overrides the HW register.
828  */
829 static void arch_timer_of_configure_rate(u32 rate, struct device_node *np)
830 {
831 	/* Who has more than one independent system counter? */
832 	if (arch_timer_rate)
833 		return;
834 
835 	if (of_property_read_u32(np, "clock-frequency", &arch_timer_rate))
836 		arch_timer_rate = rate;
837 
838 	/* Check the timer frequency. */
839 	if (arch_timer_rate == 0)
840 		pr_warn("frequency not available\n");
841 }
842 
843 static void arch_timer_banner(unsigned type)
844 {
845 	pr_info("%s%s%s timer(s) running at %lu.%02luMHz (%s%s%s).\n",
846 		type & ARCH_TIMER_TYPE_CP15 ? "cp15" : "",
847 		type == (ARCH_TIMER_TYPE_CP15 | ARCH_TIMER_TYPE_MEM) ?
848 			" and " : "",
849 		type & ARCH_TIMER_TYPE_MEM ? "mmio" : "",
850 		(unsigned long)arch_timer_rate / 1000000,
851 		(unsigned long)(arch_timer_rate / 10000) % 100,
852 		type & ARCH_TIMER_TYPE_CP15 ?
853 			(arch_timer_uses_ppi == ARCH_TIMER_VIRT_PPI) ? "virt" : "phys" :
854 			"",
855 		type == (ARCH_TIMER_TYPE_CP15 | ARCH_TIMER_TYPE_MEM) ? "/" : "",
856 		type & ARCH_TIMER_TYPE_MEM ?
857 			arch_timer_mem_use_virtual ? "virt" : "phys" :
858 			"");
859 }
860 
861 u32 arch_timer_get_rate(void)
862 {
863 	return arch_timer_rate;
864 }
865 
866 static u64 arch_counter_get_cntvct_mem(void)
867 {
868 	u32 vct_lo, vct_hi, tmp_hi;
869 
870 	do {
871 		vct_hi = readl_relaxed(arch_counter_base + CNTVCT_HI);
872 		vct_lo = readl_relaxed(arch_counter_base + CNTVCT_LO);
873 		tmp_hi = readl_relaxed(arch_counter_base + CNTVCT_HI);
874 	} while (vct_hi != tmp_hi);
875 
876 	return ((u64) vct_hi << 32) | vct_lo;
877 }
878 
879 static struct arch_timer_kvm_info arch_timer_kvm_info;
880 
881 struct arch_timer_kvm_info *arch_timer_get_kvm_info(void)
882 {
883 	return &arch_timer_kvm_info;
884 }
885 
886 static void __init arch_counter_register(unsigned type)
887 {
888 	u64 start_count;
889 
890 	/* Register the CP15 based counter if we have one */
891 	if (type & ARCH_TIMER_TYPE_CP15) {
892 		if (IS_ENABLED(CONFIG_ARM64) ||
893 		    arch_timer_uses_ppi == ARCH_TIMER_VIRT_PPI)
894 			arch_timer_read_counter = arch_counter_get_cntvct;
895 		else
896 			arch_timer_read_counter = arch_counter_get_cntpct;
897 
898 		clocksource_counter.archdata.vdso_direct = vdso_default;
899 	} else {
900 		arch_timer_read_counter = arch_counter_get_cntvct_mem;
901 	}
902 
903 	if (!arch_counter_suspend_stop)
904 		clocksource_counter.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
905 	start_count = arch_timer_read_counter();
906 	clocksource_register_hz(&clocksource_counter, arch_timer_rate);
907 	cyclecounter.mult = clocksource_counter.mult;
908 	cyclecounter.shift = clocksource_counter.shift;
909 	timecounter_init(&arch_timer_kvm_info.timecounter,
910 			 &cyclecounter, start_count);
911 
912 	/* 56 bits minimum, so we assume worst case rollover */
913 	sched_clock_register(arch_timer_read_counter, 56, arch_timer_rate);
914 }
915 
916 static void arch_timer_stop(struct clock_event_device *clk)
917 {
918 	pr_debug("disable IRQ%d cpu #%d\n", clk->irq, smp_processor_id());
919 
920 	disable_percpu_irq(arch_timer_ppi[arch_timer_uses_ppi]);
921 	if (arch_timer_has_nonsecure_ppi())
922 		disable_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI]);
923 
924 	clk->set_state_shutdown(clk);
925 }
926 
927 static int arch_timer_dying_cpu(unsigned int cpu)
928 {
929 	struct clock_event_device *clk = this_cpu_ptr(arch_timer_evt);
930 
931 	arch_timer_stop(clk);
932 	return 0;
933 }
934 
935 #ifdef CONFIG_CPU_PM
936 static DEFINE_PER_CPU(unsigned long, saved_cntkctl);
937 static int arch_timer_cpu_pm_notify(struct notifier_block *self,
938 				    unsigned long action, void *hcpu)
939 {
940 	if (action == CPU_PM_ENTER)
941 		__this_cpu_write(saved_cntkctl, arch_timer_get_cntkctl());
942 	else if (action == CPU_PM_ENTER_FAILED || action == CPU_PM_EXIT)
943 		arch_timer_set_cntkctl(__this_cpu_read(saved_cntkctl));
944 	return NOTIFY_OK;
945 }
946 
947 static struct notifier_block arch_timer_cpu_pm_notifier = {
948 	.notifier_call = arch_timer_cpu_pm_notify,
949 };
950 
951 static int __init arch_timer_cpu_pm_init(void)
952 {
953 	return cpu_pm_register_notifier(&arch_timer_cpu_pm_notifier);
954 }
955 
956 static void __init arch_timer_cpu_pm_deinit(void)
957 {
958 	WARN_ON(cpu_pm_unregister_notifier(&arch_timer_cpu_pm_notifier));
959 }
960 
961 #else
962 static int __init arch_timer_cpu_pm_init(void)
963 {
964 	return 0;
965 }
966 
967 static void __init arch_timer_cpu_pm_deinit(void)
968 {
969 }
970 #endif
971 
972 static int __init arch_timer_register(void)
973 {
974 	int err;
975 	int ppi;
976 
977 	arch_timer_evt = alloc_percpu(struct clock_event_device);
978 	if (!arch_timer_evt) {
979 		err = -ENOMEM;
980 		goto out;
981 	}
982 
983 	ppi = arch_timer_ppi[arch_timer_uses_ppi];
984 	switch (arch_timer_uses_ppi) {
985 	case ARCH_TIMER_VIRT_PPI:
986 		err = request_percpu_irq(ppi, arch_timer_handler_virt,
987 					 "arch_timer", arch_timer_evt);
988 		break;
989 	case ARCH_TIMER_PHYS_SECURE_PPI:
990 	case ARCH_TIMER_PHYS_NONSECURE_PPI:
991 		err = request_percpu_irq(ppi, arch_timer_handler_phys,
992 					 "arch_timer", arch_timer_evt);
993 		if (!err && arch_timer_has_nonsecure_ppi()) {
994 			ppi = arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI];
995 			err = request_percpu_irq(ppi, arch_timer_handler_phys,
996 						 "arch_timer", arch_timer_evt);
997 			if (err)
998 				free_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_SECURE_PPI],
999 						arch_timer_evt);
1000 		}
1001 		break;
1002 	case ARCH_TIMER_HYP_PPI:
1003 		err = request_percpu_irq(ppi, arch_timer_handler_phys,
1004 					 "arch_timer", arch_timer_evt);
1005 		break;
1006 	default:
1007 		BUG();
1008 	}
1009 
1010 	if (err) {
1011 		pr_err("can't register interrupt %d (%d)\n", ppi, err);
1012 		goto out_free;
1013 	}
1014 
1015 	err = arch_timer_cpu_pm_init();
1016 	if (err)
1017 		goto out_unreg_notify;
1018 
1019 
1020 	/* Register and immediately configure the timer on the boot CPU */
1021 	err = cpuhp_setup_state(CPUHP_AP_ARM_ARCH_TIMER_STARTING,
1022 				"clockevents/arm/arch_timer:starting",
1023 				arch_timer_starting_cpu, arch_timer_dying_cpu);
1024 	if (err)
1025 		goto out_unreg_cpupm;
1026 	return 0;
1027 
1028 out_unreg_cpupm:
1029 	arch_timer_cpu_pm_deinit();
1030 
1031 out_unreg_notify:
1032 	free_percpu_irq(arch_timer_ppi[arch_timer_uses_ppi], arch_timer_evt);
1033 	if (arch_timer_has_nonsecure_ppi())
1034 		free_percpu_irq(arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI],
1035 				arch_timer_evt);
1036 
1037 out_free:
1038 	free_percpu(arch_timer_evt);
1039 out:
1040 	return err;
1041 }
1042 
1043 static int __init arch_timer_mem_register(void __iomem *base, unsigned int irq)
1044 {
1045 	int ret;
1046 	irq_handler_t func;
1047 	struct arch_timer *t;
1048 
1049 	t = kzalloc(sizeof(*t), GFP_KERNEL);
1050 	if (!t)
1051 		return -ENOMEM;
1052 
1053 	t->base = base;
1054 	t->evt.irq = irq;
1055 	__arch_timer_setup(ARCH_TIMER_TYPE_MEM, &t->evt);
1056 
1057 	if (arch_timer_mem_use_virtual)
1058 		func = arch_timer_handler_virt_mem;
1059 	else
1060 		func = arch_timer_handler_phys_mem;
1061 
1062 	ret = request_irq(irq, func, IRQF_TIMER, "arch_mem_timer", &t->evt);
1063 	if (ret) {
1064 		pr_err("Failed to request mem timer irq\n");
1065 		kfree(t);
1066 	}
1067 
1068 	return ret;
1069 }
1070 
1071 static const struct of_device_id arch_timer_of_match[] __initconst = {
1072 	{ .compatible   = "arm,armv7-timer",    },
1073 	{ .compatible   = "arm,armv8-timer",    },
1074 	{},
1075 };
1076 
1077 static const struct of_device_id arch_timer_mem_of_match[] __initconst = {
1078 	{ .compatible   = "arm,armv7-timer-mem", },
1079 	{},
1080 };
1081 
1082 static bool __init arch_timer_needs_of_probing(void)
1083 {
1084 	struct device_node *dn;
1085 	bool needs_probing = false;
1086 	unsigned int mask = ARCH_TIMER_TYPE_CP15 | ARCH_TIMER_TYPE_MEM;
1087 
1088 	/* We have two timers, and both device-tree nodes are probed. */
1089 	if ((arch_timers_present & mask) == mask)
1090 		return false;
1091 
1092 	/*
1093 	 * Only one type of timer is probed,
1094 	 * check if we have another type of timer node in device-tree.
1095 	 */
1096 	if (arch_timers_present & ARCH_TIMER_TYPE_CP15)
1097 		dn = of_find_matching_node(NULL, arch_timer_mem_of_match);
1098 	else
1099 		dn = of_find_matching_node(NULL, arch_timer_of_match);
1100 
1101 	if (dn && of_device_is_available(dn))
1102 		needs_probing = true;
1103 
1104 	of_node_put(dn);
1105 
1106 	return needs_probing;
1107 }
1108 
1109 static int __init arch_timer_common_init(void)
1110 {
1111 	arch_timer_banner(arch_timers_present);
1112 	arch_counter_register(arch_timers_present);
1113 	return arch_timer_arch_init();
1114 }
1115 
1116 /**
1117  * arch_timer_select_ppi() - Select suitable PPI for the current system.
1118  *
1119  * If HYP mode is available, we know that the physical timer
1120  * has been configured to be accessible from PL1. Use it, so
1121  * that a guest can use the virtual timer instead.
1122  *
1123  * On ARMv8.1 with VH extensions, the kernel runs in HYP. VHE
1124  * accesses to CNTP_*_EL1 registers are silently redirected to
1125  * their CNTHP_*_EL2 counterparts, and use a different PPI
1126  * number.
1127  *
1128  * If no interrupt provided for virtual timer, we'll have to
1129  * stick to the physical timer. It'd better be accessible...
1130  * For arm64 we never use the secure interrupt.
1131  *
1132  * Return: a suitable PPI type for the current system.
1133  */
1134 static enum arch_timer_ppi_nr __init arch_timer_select_ppi(void)
1135 {
1136 	if (is_kernel_in_hyp_mode())
1137 		return ARCH_TIMER_HYP_PPI;
1138 
1139 	if (!is_hyp_mode_available() && arch_timer_ppi[ARCH_TIMER_VIRT_PPI])
1140 		return ARCH_TIMER_VIRT_PPI;
1141 
1142 	if (IS_ENABLED(CONFIG_ARM64))
1143 		return ARCH_TIMER_PHYS_NONSECURE_PPI;
1144 
1145 	return ARCH_TIMER_PHYS_SECURE_PPI;
1146 }
1147 
1148 static int __init arch_timer_of_init(struct device_node *np)
1149 {
1150 	int i, ret;
1151 	u32 rate;
1152 
1153 	if (arch_timers_present & ARCH_TIMER_TYPE_CP15) {
1154 		pr_warn("multiple nodes in dt, skipping\n");
1155 		return 0;
1156 	}
1157 
1158 	arch_timers_present |= ARCH_TIMER_TYPE_CP15;
1159 	for (i = ARCH_TIMER_PHYS_SECURE_PPI; i < ARCH_TIMER_MAX_TIMER_PPI; i++)
1160 		arch_timer_ppi[i] = irq_of_parse_and_map(np, i);
1161 
1162 	arch_timer_kvm_info.virtual_irq = arch_timer_ppi[ARCH_TIMER_VIRT_PPI];
1163 
1164 	rate = arch_timer_get_cntfrq();
1165 	arch_timer_of_configure_rate(rate, np);
1166 
1167 	arch_timer_c3stop = !of_property_read_bool(np, "always-on");
1168 
1169 	/* Check for globally applicable workarounds */
1170 	arch_timer_check_ool_workaround(ate_match_dt, np);
1171 
1172 	/*
1173 	 * If we cannot rely on firmware initializing the timer registers then
1174 	 * we should use the physical timers instead.
1175 	 */
1176 	if (IS_ENABLED(CONFIG_ARM) &&
1177 	    of_property_read_bool(np, "arm,cpu-registers-not-fw-configured"))
1178 		arch_timer_uses_ppi = ARCH_TIMER_PHYS_SECURE_PPI;
1179 	else
1180 		arch_timer_uses_ppi = arch_timer_select_ppi();
1181 
1182 	if (!arch_timer_ppi[arch_timer_uses_ppi]) {
1183 		pr_err("No interrupt available, giving up\n");
1184 		return -EINVAL;
1185 	}
1186 
1187 	/* On some systems, the counter stops ticking when in suspend. */
1188 	arch_counter_suspend_stop = of_property_read_bool(np,
1189 							 "arm,no-tick-in-suspend");
1190 
1191 	ret = arch_timer_register();
1192 	if (ret)
1193 		return ret;
1194 
1195 	if (arch_timer_needs_of_probing())
1196 		return 0;
1197 
1198 	return arch_timer_common_init();
1199 }
1200 TIMER_OF_DECLARE(armv7_arch_timer, "arm,armv7-timer", arch_timer_of_init);
1201 TIMER_OF_DECLARE(armv8_arch_timer, "arm,armv8-timer", arch_timer_of_init);
1202 
1203 static u32 __init
1204 arch_timer_mem_frame_get_cntfrq(struct arch_timer_mem_frame *frame)
1205 {
1206 	void __iomem *base;
1207 	u32 rate;
1208 
1209 	base = ioremap(frame->cntbase, frame->size);
1210 	if (!base) {
1211 		pr_err("Unable to map frame @ %pa\n", &frame->cntbase);
1212 		return 0;
1213 	}
1214 
1215 	rate = readl_relaxed(base + CNTFRQ);
1216 
1217 	iounmap(base);
1218 
1219 	return rate;
1220 }
1221 
1222 static struct arch_timer_mem_frame * __init
1223 arch_timer_mem_find_best_frame(struct arch_timer_mem *timer_mem)
1224 {
1225 	struct arch_timer_mem_frame *frame, *best_frame = NULL;
1226 	void __iomem *cntctlbase;
1227 	u32 cnttidr;
1228 	int i;
1229 
1230 	cntctlbase = ioremap(timer_mem->cntctlbase, timer_mem->size);
1231 	if (!cntctlbase) {
1232 		pr_err("Can't map CNTCTLBase @ %pa\n",
1233 			&timer_mem->cntctlbase);
1234 		return NULL;
1235 	}
1236 
1237 	cnttidr = readl_relaxed(cntctlbase + CNTTIDR);
1238 
1239 	/*
1240 	 * Try to find a virtual capable frame. Otherwise fall back to a
1241 	 * physical capable frame.
1242 	 */
1243 	for (i = 0; i < ARCH_TIMER_MEM_MAX_FRAMES; i++) {
1244 		u32 cntacr = CNTACR_RFRQ | CNTACR_RWPT | CNTACR_RPCT |
1245 			     CNTACR_RWVT | CNTACR_RVOFF | CNTACR_RVCT;
1246 
1247 		frame = &timer_mem->frame[i];
1248 		if (!frame->valid)
1249 			continue;
1250 
1251 		/* Try enabling everything, and see what sticks */
1252 		writel_relaxed(cntacr, cntctlbase + CNTACR(i));
1253 		cntacr = readl_relaxed(cntctlbase + CNTACR(i));
1254 
1255 		if ((cnttidr & CNTTIDR_VIRT(i)) &&
1256 		    !(~cntacr & (CNTACR_RWVT | CNTACR_RVCT))) {
1257 			best_frame = frame;
1258 			arch_timer_mem_use_virtual = true;
1259 			break;
1260 		}
1261 
1262 		if (~cntacr & (CNTACR_RWPT | CNTACR_RPCT))
1263 			continue;
1264 
1265 		best_frame = frame;
1266 	}
1267 
1268 	iounmap(cntctlbase);
1269 
1270 	return best_frame;
1271 }
1272 
1273 static int __init
1274 arch_timer_mem_frame_register(struct arch_timer_mem_frame *frame)
1275 {
1276 	void __iomem *base;
1277 	int ret, irq = 0;
1278 
1279 	if (arch_timer_mem_use_virtual)
1280 		irq = frame->virt_irq;
1281 	else
1282 		irq = frame->phys_irq;
1283 
1284 	if (!irq) {
1285 		pr_err("Frame missing %s irq.\n",
1286 		       arch_timer_mem_use_virtual ? "virt" : "phys");
1287 		return -EINVAL;
1288 	}
1289 
1290 	if (!request_mem_region(frame->cntbase, frame->size,
1291 				"arch_mem_timer"))
1292 		return -EBUSY;
1293 
1294 	base = ioremap(frame->cntbase, frame->size);
1295 	if (!base) {
1296 		pr_err("Can't map frame's registers\n");
1297 		return -ENXIO;
1298 	}
1299 
1300 	ret = arch_timer_mem_register(base, irq);
1301 	if (ret) {
1302 		iounmap(base);
1303 		return ret;
1304 	}
1305 
1306 	arch_counter_base = base;
1307 	arch_timers_present |= ARCH_TIMER_TYPE_MEM;
1308 
1309 	return 0;
1310 }
1311 
1312 static int __init arch_timer_mem_of_init(struct device_node *np)
1313 {
1314 	struct arch_timer_mem *timer_mem;
1315 	struct arch_timer_mem_frame *frame;
1316 	struct device_node *frame_node;
1317 	struct resource res;
1318 	int ret = -EINVAL;
1319 	u32 rate;
1320 
1321 	timer_mem = kzalloc(sizeof(*timer_mem), GFP_KERNEL);
1322 	if (!timer_mem)
1323 		return -ENOMEM;
1324 
1325 	if (of_address_to_resource(np, 0, &res))
1326 		goto out;
1327 	timer_mem->cntctlbase = res.start;
1328 	timer_mem->size = resource_size(&res);
1329 
1330 	for_each_available_child_of_node(np, frame_node) {
1331 		u32 n;
1332 		struct arch_timer_mem_frame *frame;
1333 
1334 		if (of_property_read_u32(frame_node, "frame-number", &n)) {
1335 			pr_err(FW_BUG "Missing frame-number.\n");
1336 			of_node_put(frame_node);
1337 			goto out;
1338 		}
1339 		if (n >= ARCH_TIMER_MEM_MAX_FRAMES) {
1340 			pr_err(FW_BUG "Wrong frame-number, only 0-%u are permitted.\n",
1341 			       ARCH_TIMER_MEM_MAX_FRAMES - 1);
1342 			of_node_put(frame_node);
1343 			goto out;
1344 		}
1345 		frame = &timer_mem->frame[n];
1346 
1347 		if (frame->valid) {
1348 			pr_err(FW_BUG "Duplicated frame-number.\n");
1349 			of_node_put(frame_node);
1350 			goto out;
1351 		}
1352 
1353 		if (of_address_to_resource(frame_node, 0, &res)) {
1354 			of_node_put(frame_node);
1355 			goto out;
1356 		}
1357 		frame->cntbase = res.start;
1358 		frame->size = resource_size(&res);
1359 
1360 		frame->virt_irq = irq_of_parse_and_map(frame_node,
1361 						       ARCH_TIMER_VIRT_SPI);
1362 		frame->phys_irq = irq_of_parse_and_map(frame_node,
1363 						       ARCH_TIMER_PHYS_SPI);
1364 
1365 		frame->valid = true;
1366 	}
1367 
1368 	frame = arch_timer_mem_find_best_frame(timer_mem);
1369 	if (!frame) {
1370 		pr_err("Unable to find a suitable frame in timer @ %pa\n",
1371 			&timer_mem->cntctlbase);
1372 		ret = -EINVAL;
1373 		goto out;
1374 	}
1375 
1376 	rate = arch_timer_mem_frame_get_cntfrq(frame);
1377 	arch_timer_of_configure_rate(rate, np);
1378 
1379 	ret = arch_timer_mem_frame_register(frame);
1380 	if (!ret && !arch_timer_needs_of_probing())
1381 		ret = arch_timer_common_init();
1382 out:
1383 	kfree(timer_mem);
1384 	return ret;
1385 }
1386 TIMER_OF_DECLARE(armv7_arch_timer_mem, "arm,armv7-timer-mem",
1387 		       arch_timer_mem_of_init);
1388 
1389 #ifdef CONFIG_ACPI_GTDT
1390 static int __init
1391 arch_timer_mem_verify_cntfrq(struct arch_timer_mem *timer_mem)
1392 {
1393 	struct arch_timer_mem_frame *frame;
1394 	u32 rate;
1395 	int i;
1396 
1397 	for (i = 0; i < ARCH_TIMER_MEM_MAX_FRAMES; i++) {
1398 		frame = &timer_mem->frame[i];
1399 
1400 		if (!frame->valid)
1401 			continue;
1402 
1403 		rate = arch_timer_mem_frame_get_cntfrq(frame);
1404 		if (rate == arch_timer_rate)
1405 			continue;
1406 
1407 		pr_err(FW_BUG "CNTFRQ mismatch: frame @ %pa: (0x%08lx), CPU: (0x%08lx)\n",
1408 			&frame->cntbase,
1409 			(unsigned long)rate, (unsigned long)arch_timer_rate);
1410 
1411 		return -EINVAL;
1412 	}
1413 
1414 	return 0;
1415 }
1416 
1417 static int __init arch_timer_mem_acpi_init(int platform_timer_count)
1418 {
1419 	struct arch_timer_mem *timers, *timer;
1420 	struct arch_timer_mem_frame *frame, *best_frame = NULL;
1421 	int timer_count, i, ret = 0;
1422 
1423 	timers = kcalloc(platform_timer_count, sizeof(*timers),
1424 			    GFP_KERNEL);
1425 	if (!timers)
1426 		return -ENOMEM;
1427 
1428 	ret = acpi_arch_timer_mem_init(timers, &timer_count);
1429 	if (ret || !timer_count)
1430 		goto out;
1431 
1432 	/*
1433 	 * While unlikely, it's theoretically possible that none of the frames
1434 	 * in a timer expose the combination of feature we want.
1435 	 */
1436 	for (i = 0; i < timer_count; i++) {
1437 		timer = &timers[i];
1438 
1439 		frame = arch_timer_mem_find_best_frame(timer);
1440 		if (!best_frame)
1441 			best_frame = frame;
1442 
1443 		ret = arch_timer_mem_verify_cntfrq(timer);
1444 		if (ret) {
1445 			pr_err("Disabling MMIO timers due to CNTFRQ mismatch\n");
1446 			goto out;
1447 		}
1448 
1449 		if (!best_frame) /* implies !frame */
1450 			/*
1451 			 * Only complain about missing suitable frames if we
1452 			 * haven't already found one in a previous iteration.
1453 			 */
1454 			pr_err("Unable to find a suitable frame in timer @ %pa\n",
1455 				&timer->cntctlbase);
1456 	}
1457 
1458 	if (best_frame)
1459 		ret = arch_timer_mem_frame_register(best_frame);
1460 out:
1461 	kfree(timers);
1462 	return ret;
1463 }
1464 
1465 /* Initialize per-processor generic timer and memory-mapped timer(if present) */
1466 static int __init arch_timer_acpi_init(struct acpi_table_header *table)
1467 {
1468 	int ret, platform_timer_count;
1469 
1470 	if (arch_timers_present & ARCH_TIMER_TYPE_CP15) {
1471 		pr_warn("already initialized, skipping\n");
1472 		return -EINVAL;
1473 	}
1474 
1475 	arch_timers_present |= ARCH_TIMER_TYPE_CP15;
1476 
1477 	ret = acpi_gtdt_init(table, &platform_timer_count);
1478 	if (ret) {
1479 		pr_err("Failed to init GTDT table.\n");
1480 		return ret;
1481 	}
1482 
1483 	arch_timer_ppi[ARCH_TIMER_PHYS_NONSECURE_PPI] =
1484 		acpi_gtdt_map_ppi(ARCH_TIMER_PHYS_NONSECURE_PPI);
1485 
1486 	arch_timer_ppi[ARCH_TIMER_VIRT_PPI] =
1487 		acpi_gtdt_map_ppi(ARCH_TIMER_VIRT_PPI);
1488 
1489 	arch_timer_ppi[ARCH_TIMER_HYP_PPI] =
1490 		acpi_gtdt_map_ppi(ARCH_TIMER_HYP_PPI);
1491 
1492 	arch_timer_kvm_info.virtual_irq = arch_timer_ppi[ARCH_TIMER_VIRT_PPI];
1493 
1494 	/*
1495 	 * When probing via ACPI, we have no mechanism to override the sysreg
1496 	 * CNTFRQ value. This *must* be correct.
1497 	 */
1498 	arch_timer_rate = arch_timer_get_cntfrq();
1499 	if (!arch_timer_rate) {
1500 		pr_err(FW_BUG "frequency not available.\n");
1501 		return -EINVAL;
1502 	}
1503 
1504 	arch_timer_uses_ppi = arch_timer_select_ppi();
1505 	if (!arch_timer_ppi[arch_timer_uses_ppi]) {
1506 		pr_err("No interrupt available, giving up\n");
1507 		return -EINVAL;
1508 	}
1509 
1510 	/* Always-on capability */
1511 	arch_timer_c3stop = acpi_gtdt_c3stop(arch_timer_uses_ppi);
1512 
1513 	/* Check for globally applicable workarounds */
1514 	arch_timer_check_ool_workaround(ate_match_acpi_oem_info, table);
1515 
1516 	ret = arch_timer_register();
1517 	if (ret)
1518 		return ret;
1519 
1520 	if (platform_timer_count &&
1521 	    arch_timer_mem_acpi_init(platform_timer_count))
1522 		pr_err("Failed to initialize memory-mapped timer.\n");
1523 
1524 	return arch_timer_common_init();
1525 }
1526 TIMER_ACPI_DECLARE(arch_timer, ACPI_SIG_GTDT, arch_timer_acpi_init);
1527 #endif
1528