1/*
2 * Cirrus Logic CLPS711X clocksource driver
3 *
4 * Copyright (C) 2014 Alexander Shiyan <shc_work@mail.ru>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 */
11
12#include <linux/clk.h>
13#include <linux/clockchips.h>
14#include <linux/clocksource.h>
15#include <linux/interrupt.h>
16#include <linux/io.h>
17#include <linux/of_address.h>
18#include <linux/of_irq.h>
19#include <linux/sched_clock.h>
20#include <linux/slab.h>
21
22enum {
23 CLPS711X_CLKSRC_CLOCKSOURCE,
24 CLPS711X_CLKSRC_CLOCKEVENT,
25};
26
27static void __iomem *tcd;
28
29static u64 notrace clps711x_sched_clock_read(void)
30{
31 return ~readw(tcd);
32}
33
34static void __init clps711x_clksrc_init(struct clk *clock, void __iomem *base)
35{
36 unsigned long rate = clk_get_rate(clock);
37
38 tcd = base;
39
40 clocksource_mmio_init(tcd, "clps711x-clocksource", rate, 300, 16,
41 clocksource_mmio_readw_down);
42
43 sched_clock_register(clps711x_sched_clock_read, 16, rate);
44}
45
46static irqreturn_t clps711x_timer_interrupt(int irq, void *dev_id)
47{
48 struct clock_event_device *evt = dev_id;
49
50 evt->event_handler(evt);
51
52 return IRQ_HANDLED;
53}
54
55static int __init _clps711x_clkevt_init(struct clk *clock, void __iomem *base,
56 unsigned int irq)
57{
58 struct clock_event_device *clkevt;
59 unsigned long rate;
60
61 clkevt = kzalloc(sizeof(*clkevt), GFP_KERNEL);
62 if (!clkevt)
63 return -ENOMEM;
64
65 rate = clk_get_rate(clock);
66
67 /* Set Timer prescaler */
68 writew(DIV_ROUND_CLOSEST(rate, HZ), base);
69
70 clkevt->name = "clps711x-clockevent";
71 clkevt->rating = 300;
72 clkevt->features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_C3STOP;
73 clkevt->cpumask = cpumask_of(0);
74 clockevents_config_and_register(clkevt, HZ, 0, 0);
75
76 return request_irq(irq, clps711x_timer_interrupt, IRQF_TIMER,
77 "clps711x-timer", clkevt);
78}
79
80static int __init clps711x_timer_init(struct device_node *np)
81{
82 unsigned int irq = irq_of_parse_and_map(np, 0);
83 struct clk *clock = of_clk_get(np, 0);
84 void __iomem *base = of_iomap(np, 0);
85
86 if (!base)
87 return -ENOMEM;
88 if (!irq)
89 return -EINVAL;
90 if (IS_ERR(clock))
91 return PTR_ERR(clock);
92
93 switch (of_alias_get_id(np, "timer")) {
94 case CLPS711X_CLKSRC_CLOCKSOURCE:
95 clps711x_clksrc_init(clock, base);
96 break;
97 case CLPS711X_CLKSRC_CLOCKEVENT:
98 return _clps711x_clkevt_init(clock, base, irq);
99 default:
100 return -EINVAL;
101 }
102
103 return 0;
104}
105TIMER_OF_DECLARE(clps711x, "cirrus,ep7209-timer", clps711x_timer_init);
106