clocksource/drivers/sh_cmt: Support separate R-Car Gen2 CMT0/1
[linux-block.git] / drivers / clocksource / sh_cmt.c
1 /*
2  * SuperH Timer Support - CMT
3  *
4  *  Copyright (C) 2008 Magnus Damm
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
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16 #include <linux/clk.h>
17 #include <linux/clockchips.h>
18 #include <linux/clocksource.h>
19 #include <linux/delay.h>
20 #include <linux/err.h>
21 #include <linux/init.h>
22 #include <linux/interrupt.h>
23 #include <linux/io.h>
24 #include <linux/ioport.h>
25 #include <linux/irq.h>
26 #include <linux/module.h>
27 #include <linux/of.h>
28 #include <linux/platform_device.h>
29 #include <linux/pm_domain.h>
30 #include <linux/pm_runtime.h>
31 #include <linux/sh_timer.h>
32 #include <linux/slab.h>
33 #include <linux/spinlock.h>
34
35 struct sh_cmt_device;
36
37 /*
38  * The CMT comes in 5 different identified flavours, depending not only on the
39  * SoC but also on the particular instance. The following table lists the main
40  * characteristics of those flavours.
41  *
42  *                      16B     32B     32B-F   48B     R-Car Gen2
43  * -----------------------------------------------------------------------------
44  * Channels             2       1/4     1       6       2/8
45  * Control Width        16      16      16      16      32
46  * Counter Width        16      32      32      32/48   32/48
47  * Shared Start/Stop    Y       Y       Y       Y       N
48  *
49  * The r8a73a4 / R-Car Gen2 version has a per-channel start/stop register
50  * located in the channel registers block. All other versions have a shared
51  * start/stop register located in the global space.
52  *
53  * Channels are indexed from 0 to N-1 in the documentation. The channel index
54  * infers the start/stop bit position in the control register and the channel
55  * registers block address. Some CMT instances have a subset of channels
56  * available, in which case the index in the documentation doesn't match the
57  * "real" index as implemented in hardware. This is for instance the case with
58  * CMT0 on r8a7740, which is a 32-bit variant with a single channel numbered 0
59  * in the documentation but using start/stop bit 5 and having its registers
60  * block at 0x60.
61  *
62  * Similarly CMT0 on r8a73a4, r8a7790 and r8a7791, while implementing 32-bit
63  * channels only, is a 48-bit gen2 CMT with the 48-bit channels unavailable.
64  */
65
66 enum sh_cmt_model {
67         SH_CMT_16BIT,
68         SH_CMT_32BIT,
69         SH_CMT_32BIT_FAST,
70         SH_CMT_48BIT,
71         SH_CMT0_RCAR_GEN2,
72         SH_CMT1_RCAR_GEN2,
73 };
74
75 struct sh_cmt_info {
76         enum sh_cmt_model model;
77
78         unsigned int channels_mask;
79
80         unsigned long width; /* 16 or 32 bit version of hardware block */
81         unsigned long overflow_bit;
82         unsigned long clear_bits;
83
84         /* callbacks for CMSTR and CMCSR access */
85         unsigned long (*read_control)(void __iomem *base, unsigned long offs);
86         void (*write_control)(void __iomem *base, unsigned long offs,
87                               unsigned long value);
88
89         /* callbacks for CMCNT and CMCOR access */
90         unsigned long (*read_count)(void __iomem *base, unsigned long offs);
91         void (*write_count)(void __iomem *base, unsigned long offs,
92                             unsigned long value);
93 };
94
95 struct sh_cmt_channel {
96         struct sh_cmt_device *cmt;
97
98         unsigned int index;     /* Index in the documentation */
99         unsigned int hwidx;     /* Real hardware index */
100
101         void __iomem *iostart;
102         void __iomem *ioctrl;
103
104         unsigned int timer_bit;
105         unsigned long flags;
106         unsigned long match_value;
107         unsigned long next_match_value;
108         unsigned long max_match_value;
109         raw_spinlock_t lock;
110         struct clock_event_device ced;
111         struct clocksource cs;
112         unsigned long total_cycles;
113         bool cs_enabled;
114 };
115
116 struct sh_cmt_device {
117         struct platform_device *pdev;
118
119         const struct sh_cmt_info *info;
120
121         void __iomem *mapbase;
122         struct clk *clk;
123         unsigned long rate;
124
125         raw_spinlock_t lock; /* Protect the shared start/stop register */
126
127         struct sh_cmt_channel *channels;
128         unsigned int num_channels;
129         unsigned int hw_channels;
130
131         bool has_clockevent;
132         bool has_clocksource;
133 };
134
135 #define SH_CMT16_CMCSR_CMF              (1 << 7)
136 #define SH_CMT16_CMCSR_CMIE             (1 << 6)
137 #define SH_CMT16_CMCSR_CKS8             (0 << 0)
138 #define SH_CMT16_CMCSR_CKS32            (1 << 0)
139 #define SH_CMT16_CMCSR_CKS128           (2 << 0)
140 #define SH_CMT16_CMCSR_CKS512           (3 << 0)
141 #define SH_CMT16_CMCSR_CKS_MASK         (3 << 0)
142
143 #define SH_CMT32_CMCSR_CMF              (1 << 15)
144 #define SH_CMT32_CMCSR_OVF              (1 << 14)
145 #define SH_CMT32_CMCSR_WRFLG            (1 << 13)
146 #define SH_CMT32_CMCSR_STTF             (1 << 12)
147 #define SH_CMT32_CMCSR_STPF             (1 << 11)
148 #define SH_CMT32_CMCSR_SSIE             (1 << 10)
149 #define SH_CMT32_CMCSR_CMS              (1 << 9)
150 #define SH_CMT32_CMCSR_CMM              (1 << 8)
151 #define SH_CMT32_CMCSR_CMTOUT_IE        (1 << 7)
152 #define SH_CMT32_CMCSR_CMR_NONE         (0 << 4)
153 #define SH_CMT32_CMCSR_CMR_DMA          (1 << 4)
154 #define SH_CMT32_CMCSR_CMR_IRQ          (2 << 4)
155 #define SH_CMT32_CMCSR_CMR_MASK         (3 << 4)
156 #define SH_CMT32_CMCSR_DBGIVD           (1 << 3)
157 #define SH_CMT32_CMCSR_CKS_RCLK8        (4 << 0)
158 #define SH_CMT32_CMCSR_CKS_RCLK32       (5 << 0)
159 #define SH_CMT32_CMCSR_CKS_RCLK128      (6 << 0)
160 #define SH_CMT32_CMCSR_CKS_RCLK1        (7 << 0)
161 #define SH_CMT32_CMCSR_CKS_MASK         (7 << 0)
162
163 static unsigned long sh_cmt_read16(void __iomem *base, unsigned long offs)
164 {
165         return ioread16(base + (offs << 1));
166 }
167
168 static unsigned long sh_cmt_read32(void __iomem *base, unsigned long offs)
169 {
170         return ioread32(base + (offs << 2));
171 }
172
173 static void sh_cmt_write16(void __iomem *base, unsigned long offs,
174                            unsigned long value)
175 {
176         iowrite16(value, base + (offs << 1));
177 }
178
179 static void sh_cmt_write32(void __iomem *base, unsigned long offs,
180                            unsigned long value)
181 {
182         iowrite32(value, base + (offs << 2));
183 }
184
185 static const struct sh_cmt_info sh_cmt_info[] = {
186         [SH_CMT_16BIT] = {
187                 .model = SH_CMT_16BIT,
188                 .width = 16,
189                 .overflow_bit = SH_CMT16_CMCSR_CMF,
190                 .clear_bits = ~SH_CMT16_CMCSR_CMF,
191                 .read_control = sh_cmt_read16,
192                 .write_control = sh_cmt_write16,
193                 .read_count = sh_cmt_read16,
194                 .write_count = sh_cmt_write16,
195         },
196         [SH_CMT_32BIT] = {
197                 .model = SH_CMT_32BIT,
198                 .width = 32,
199                 .overflow_bit = SH_CMT32_CMCSR_CMF,
200                 .clear_bits = ~(SH_CMT32_CMCSR_CMF | SH_CMT32_CMCSR_OVF),
201                 .read_control = sh_cmt_read16,
202                 .write_control = sh_cmt_write16,
203                 .read_count = sh_cmt_read32,
204                 .write_count = sh_cmt_write32,
205         },
206         [SH_CMT_32BIT_FAST] = {
207                 .model = SH_CMT_32BIT_FAST,
208                 .width = 32,
209                 .overflow_bit = SH_CMT32_CMCSR_CMF,
210                 .clear_bits = ~(SH_CMT32_CMCSR_CMF | SH_CMT32_CMCSR_OVF),
211                 .read_control = sh_cmt_read16,
212                 .write_control = sh_cmt_write16,
213                 .read_count = sh_cmt_read32,
214                 .write_count = sh_cmt_write32,
215         },
216         [SH_CMT_48BIT] = {
217                 .model = SH_CMT_48BIT,
218                 .channels_mask = 0x3f,
219                 .width = 32,
220                 .overflow_bit = SH_CMT32_CMCSR_CMF,
221                 .clear_bits = ~(SH_CMT32_CMCSR_CMF | SH_CMT32_CMCSR_OVF),
222                 .read_control = sh_cmt_read32,
223                 .write_control = sh_cmt_write32,
224                 .read_count = sh_cmt_read32,
225                 .write_count = sh_cmt_write32,
226         },
227         [SH_CMT0_RCAR_GEN2] = {
228                 .model = SH_CMT0_RCAR_GEN2,
229                 .channels_mask = 0x60,
230                 .width = 32,
231                 .overflow_bit = SH_CMT32_CMCSR_CMF,
232                 .clear_bits = ~(SH_CMT32_CMCSR_CMF | SH_CMT32_CMCSR_OVF),
233                 .read_control = sh_cmt_read32,
234                 .write_control = sh_cmt_write32,
235                 .read_count = sh_cmt_read32,
236                 .write_count = sh_cmt_write32,
237         },
238         [SH_CMT1_RCAR_GEN2] = {
239                 .model = SH_CMT1_RCAR_GEN2,
240                 .channels_mask = 0xff,
241                 .width = 32,
242                 .overflow_bit = SH_CMT32_CMCSR_CMF,
243                 .clear_bits = ~(SH_CMT32_CMCSR_CMF | SH_CMT32_CMCSR_OVF),
244                 .read_control = sh_cmt_read32,
245                 .write_control = sh_cmt_write32,
246                 .read_count = sh_cmt_read32,
247                 .write_count = sh_cmt_write32,
248         },
249 };
250
251 #define CMCSR 0 /* channel register */
252 #define CMCNT 1 /* channel register */
253 #define CMCOR 2 /* channel register */
254
255 static inline unsigned long sh_cmt_read_cmstr(struct sh_cmt_channel *ch)
256 {
257         if (ch->iostart)
258                 return ch->cmt->info->read_control(ch->iostart, 0);
259         else
260                 return ch->cmt->info->read_control(ch->cmt->mapbase, 0);
261 }
262
263 static inline void sh_cmt_write_cmstr(struct sh_cmt_channel *ch,
264                                       unsigned long value)
265 {
266         if (ch->iostart)
267                 ch->cmt->info->write_control(ch->iostart, 0, value);
268         else
269                 ch->cmt->info->write_control(ch->cmt->mapbase, 0, value);
270 }
271
272 static inline unsigned long sh_cmt_read_cmcsr(struct sh_cmt_channel *ch)
273 {
274         return ch->cmt->info->read_control(ch->ioctrl, CMCSR);
275 }
276
277 static inline void sh_cmt_write_cmcsr(struct sh_cmt_channel *ch,
278                                       unsigned long value)
279 {
280         ch->cmt->info->write_control(ch->ioctrl, CMCSR, value);
281 }
282
283 static inline unsigned long sh_cmt_read_cmcnt(struct sh_cmt_channel *ch)
284 {
285         return ch->cmt->info->read_count(ch->ioctrl, CMCNT);
286 }
287
288 static inline void sh_cmt_write_cmcnt(struct sh_cmt_channel *ch,
289                                       unsigned long value)
290 {
291         ch->cmt->info->write_count(ch->ioctrl, CMCNT, value);
292 }
293
294 static inline void sh_cmt_write_cmcor(struct sh_cmt_channel *ch,
295                                       unsigned long value)
296 {
297         ch->cmt->info->write_count(ch->ioctrl, CMCOR, value);
298 }
299
300 static unsigned long sh_cmt_get_counter(struct sh_cmt_channel *ch,
301                                         int *has_wrapped)
302 {
303         unsigned long v1, v2, v3;
304         int o1, o2;
305
306         o1 = sh_cmt_read_cmcsr(ch) & ch->cmt->info->overflow_bit;
307
308         /* Make sure the timer value is stable. Stolen from acpi_pm.c */
309         do {
310                 o2 = o1;
311                 v1 = sh_cmt_read_cmcnt(ch);
312                 v2 = sh_cmt_read_cmcnt(ch);
313                 v3 = sh_cmt_read_cmcnt(ch);
314                 o1 = sh_cmt_read_cmcsr(ch) & ch->cmt->info->overflow_bit;
315         } while (unlikely((o1 != o2) || (v1 > v2 && v1 < v3)
316                           || (v2 > v3 && v2 < v1) || (v3 > v1 && v3 < v2)));
317
318         *has_wrapped = o1;
319         return v2;
320 }
321
322 static void sh_cmt_start_stop_ch(struct sh_cmt_channel *ch, int start)
323 {
324         unsigned long flags, value;
325
326         /* start stop register shared by multiple timer channels */
327         raw_spin_lock_irqsave(&ch->cmt->lock, flags);
328         value = sh_cmt_read_cmstr(ch);
329
330         if (start)
331                 value |= 1 << ch->timer_bit;
332         else
333                 value &= ~(1 << ch->timer_bit);
334
335         sh_cmt_write_cmstr(ch, value);
336         raw_spin_unlock_irqrestore(&ch->cmt->lock, flags);
337 }
338
339 static int sh_cmt_enable(struct sh_cmt_channel *ch)
340 {
341         int k, ret;
342
343         pm_runtime_get_sync(&ch->cmt->pdev->dev);
344         dev_pm_syscore_device(&ch->cmt->pdev->dev, true);
345
346         /* enable clock */
347         ret = clk_enable(ch->cmt->clk);
348         if (ret) {
349                 dev_err(&ch->cmt->pdev->dev, "ch%u: cannot enable clock\n",
350                         ch->index);
351                 goto err0;
352         }
353
354         /* make sure channel is disabled */
355         sh_cmt_start_stop_ch(ch, 0);
356
357         /* configure channel, periodic mode and maximum timeout */
358         if (ch->cmt->info->width == 16) {
359                 sh_cmt_write_cmcsr(ch, SH_CMT16_CMCSR_CMIE |
360                                    SH_CMT16_CMCSR_CKS512);
361         } else {
362                 sh_cmt_write_cmcsr(ch, SH_CMT32_CMCSR_CMM |
363                                    SH_CMT32_CMCSR_CMTOUT_IE |
364                                    SH_CMT32_CMCSR_CMR_IRQ |
365                                    SH_CMT32_CMCSR_CKS_RCLK8);
366         }
367
368         sh_cmt_write_cmcor(ch, 0xffffffff);
369         sh_cmt_write_cmcnt(ch, 0);
370
371         /*
372          * According to the sh73a0 user's manual, as CMCNT can be operated
373          * only by the RCLK (Pseudo 32 KHz), there's one restriction on
374          * modifying CMCNT register; two RCLK cycles are necessary before
375          * this register is either read or any modification of the value
376          * it holds is reflected in the LSI's actual operation.
377          *
378          * While at it, we're supposed to clear out the CMCNT as of this
379          * moment, so make sure it's processed properly here.  This will
380          * take RCLKx2 at maximum.
381          */
382         for (k = 0; k < 100; k++) {
383                 if (!sh_cmt_read_cmcnt(ch))
384                         break;
385                 udelay(1);
386         }
387
388         if (sh_cmt_read_cmcnt(ch)) {
389                 dev_err(&ch->cmt->pdev->dev, "ch%u: cannot clear CMCNT\n",
390                         ch->index);
391                 ret = -ETIMEDOUT;
392                 goto err1;
393         }
394
395         /* enable channel */
396         sh_cmt_start_stop_ch(ch, 1);
397         return 0;
398  err1:
399         /* stop clock */
400         clk_disable(ch->cmt->clk);
401
402  err0:
403         return ret;
404 }
405
406 static void sh_cmt_disable(struct sh_cmt_channel *ch)
407 {
408         /* disable channel */
409         sh_cmt_start_stop_ch(ch, 0);
410
411         /* disable interrupts in CMT block */
412         sh_cmt_write_cmcsr(ch, 0);
413
414         /* stop clock */
415         clk_disable(ch->cmt->clk);
416
417         dev_pm_syscore_device(&ch->cmt->pdev->dev, false);
418         pm_runtime_put(&ch->cmt->pdev->dev);
419 }
420
421 /* private flags */
422 #define FLAG_CLOCKEVENT (1 << 0)
423 #define FLAG_CLOCKSOURCE (1 << 1)
424 #define FLAG_REPROGRAM (1 << 2)
425 #define FLAG_SKIPEVENT (1 << 3)
426 #define FLAG_IRQCONTEXT (1 << 4)
427
428 static void sh_cmt_clock_event_program_verify(struct sh_cmt_channel *ch,
429                                               int absolute)
430 {
431         unsigned long new_match;
432         unsigned long value = ch->next_match_value;
433         unsigned long delay = 0;
434         unsigned long now = 0;
435         int has_wrapped;
436
437         now = sh_cmt_get_counter(ch, &has_wrapped);
438         ch->flags |= FLAG_REPROGRAM; /* force reprogram */
439
440         if (has_wrapped) {
441                 /* we're competing with the interrupt handler.
442                  *  -> let the interrupt handler reprogram the timer.
443                  *  -> interrupt number two handles the event.
444                  */
445                 ch->flags |= FLAG_SKIPEVENT;
446                 return;
447         }
448
449         if (absolute)
450                 now = 0;
451
452         do {
453                 /* reprogram the timer hardware,
454                  * but don't save the new match value yet.
455                  */
456                 new_match = now + value + delay;
457                 if (new_match > ch->max_match_value)
458                         new_match = ch->max_match_value;
459
460                 sh_cmt_write_cmcor(ch, new_match);
461
462                 now = sh_cmt_get_counter(ch, &has_wrapped);
463                 if (has_wrapped && (new_match > ch->match_value)) {
464                         /* we are changing to a greater match value,
465                          * so this wrap must be caused by the counter
466                          * matching the old value.
467                          * -> first interrupt reprograms the timer.
468                          * -> interrupt number two handles the event.
469                          */
470                         ch->flags |= FLAG_SKIPEVENT;
471                         break;
472                 }
473
474                 if (has_wrapped) {
475                         /* we are changing to a smaller match value,
476                          * so the wrap must be caused by the counter
477                          * matching the new value.
478                          * -> save programmed match value.
479                          * -> let isr handle the event.
480                          */
481                         ch->match_value = new_match;
482                         break;
483                 }
484
485                 /* be safe: verify hardware settings */
486                 if (now < new_match) {
487                         /* timer value is below match value, all good.
488                          * this makes sure we won't miss any match events.
489                          * -> save programmed match value.
490                          * -> let isr handle the event.
491                          */
492                         ch->match_value = new_match;
493                         break;
494                 }
495
496                 /* the counter has reached a value greater
497                  * than our new match value. and since the
498                  * has_wrapped flag isn't set we must have
499                  * programmed a too close event.
500                  * -> increase delay and retry.
501                  */
502                 if (delay)
503                         delay <<= 1;
504                 else
505                         delay = 1;
506
507                 if (!delay)
508                         dev_warn(&ch->cmt->pdev->dev, "ch%u: too long delay\n",
509                                  ch->index);
510
511         } while (delay);
512 }
513
514 static void __sh_cmt_set_next(struct sh_cmt_channel *ch, unsigned long delta)
515 {
516         if (delta > ch->max_match_value)
517                 dev_warn(&ch->cmt->pdev->dev, "ch%u: delta out of range\n",
518                          ch->index);
519
520         ch->next_match_value = delta;
521         sh_cmt_clock_event_program_verify(ch, 0);
522 }
523
524 static void sh_cmt_set_next(struct sh_cmt_channel *ch, unsigned long delta)
525 {
526         unsigned long flags;
527
528         raw_spin_lock_irqsave(&ch->lock, flags);
529         __sh_cmt_set_next(ch, delta);
530         raw_spin_unlock_irqrestore(&ch->lock, flags);
531 }
532
533 static irqreturn_t sh_cmt_interrupt(int irq, void *dev_id)
534 {
535         struct sh_cmt_channel *ch = dev_id;
536
537         /* clear flags */
538         sh_cmt_write_cmcsr(ch, sh_cmt_read_cmcsr(ch) &
539                            ch->cmt->info->clear_bits);
540
541         /* update clock source counter to begin with if enabled
542          * the wrap flag should be cleared by the timer specific
543          * isr before we end up here.
544          */
545         if (ch->flags & FLAG_CLOCKSOURCE)
546                 ch->total_cycles += ch->match_value + 1;
547
548         if (!(ch->flags & FLAG_REPROGRAM))
549                 ch->next_match_value = ch->max_match_value;
550
551         ch->flags |= FLAG_IRQCONTEXT;
552
553         if (ch->flags & FLAG_CLOCKEVENT) {
554                 if (!(ch->flags & FLAG_SKIPEVENT)) {
555                         if (clockevent_state_oneshot(&ch->ced)) {
556                                 ch->next_match_value = ch->max_match_value;
557                                 ch->flags |= FLAG_REPROGRAM;
558                         }
559
560                         ch->ced.event_handler(&ch->ced);
561                 }
562         }
563
564         ch->flags &= ~FLAG_SKIPEVENT;
565
566         if (ch->flags & FLAG_REPROGRAM) {
567                 ch->flags &= ~FLAG_REPROGRAM;
568                 sh_cmt_clock_event_program_verify(ch, 1);
569
570                 if (ch->flags & FLAG_CLOCKEVENT)
571                         if ((clockevent_state_shutdown(&ch->ced))
572                             || (ch->match_value == ch->next_match_value))
573                                 ch->flags &= ~FLAG_REPROGRAM;
574         }
575
576         ch->flags &= ~FLAG_IRQCONTEXT;
577
578         return IRQ_HANDLED;
579 }
580
581 static int sh_cmt_start(struct sh_cmt_channel *ch, unsigned long flag)
582 {
583         int ret = 0;
584         unsigned long flags;
585
586         raw_spin_lock_irqsave(&ch->lock, flags);
587
588         if (!(ch->flags & (FLAG_CLOCKEVENT | FLAG_CLOCKSOURCE)))
589                 ret = sh_cmt_enable(ch);
590
591         if (ret)
592                 goto out;
593         ch->flags |= flag;
594
595         /* setup timeout if no clockevent */
596         if ((flag == FLAG_CLOCKSOURCE) && (!(ch->flags & FLAG_CLOCKEVENT)))
597                 __sh_cmt_set_next(ch, ch->max_match_value);
598  out:
599         raw_spin_unlock_irqrestore(&ch->lock, flags);
600
601         return ret;
602 }
603
604 static void sh_cmt_stop(struct sh_cmt_channel *ch, unsigned long flag)
605 {
606         unsigned long flags;
607         unsigned long f;
608
609         raw_spin_lock_irqsave(&ch->lock, flags);
610
611         f = ch->flags & (FLAG_CLOCKEVENT | FLAG_CLOCKSOURCE);
612         ch->flags &= ~flag;
613
614         if (f && !(ch->flags & (FLAG_CLOCKEVENT | FLAG_CLOCKSOURCE)))
615                 sh_cmt_disable(ch);
616
617         /* adjust the timeout to maximum if only clocksource left */
618         if ((flag == FLAG_CLOCKEVENT) && (ch->flags & FLAG_CLOCKSOURCE))
619                 __sh_cmt_set_next(ch, ch->max_match_value);
620
621         raw_spin_unlock_irqrestore(&ch->lock, flags);
622 }
623
624 static struct sh_cmt_channel *cs_to_sh_cmt(struct clocksource *cs)
625 {
626         return container_of(cs, struct sh_cmt_channel, cs);
627 }
628
629 static u64 sh_cmt_clocksource_read(struct clocksource *cs)
630 {
631         struct sh_cmt_channel *ch = cs_to_sh_cmt(cs);
632         unsigned long flags, raw;
633         unsigned long value;
634         int has_wrapped;
635
636         raw_spin_lock_irqsave(&ch->lock, flags);
637         value = ch->total_cycles;
638         raw = sh_cmt_get_counter(ch, &has_wrapped);
639
640         if (unlikely(has_wrapped))
641                 raw += ch->match_value + 1;
642         raw_spin_unlock_irqrestore(&ch->lock, flags);
643
644         return value + raw;
645 }
646
647 static int sh_cmt_clocksource_enable(struct clocksource *cs)
648 {
649         int ret;
650         struct sh_cmt_channel *ch = cs_to_sh_cmt(cs);
651
652         WARN_ON(ch->cs_enabled);
653
654         ch->total_cycles = 0;
655
656         ret = sh_cmt_start(ch, FLAG_CLOCKSOURCE);
657         if (!ret)
658                 ch->cs_enabled = true;
659
660         return ret;
661 }
662
663 static void sh_cmt_clocksource_disable(struct clocksource *cs)
664 {
665         struct sh_cmt_channel *ch = cs_to_sh_cmt(cs);
666
667         WARN_ON(!ch->cs_enabled);
668
669         sh_cmt_stop(ch, FLAG_CLOCKSOURCE);
670         ch->cs_enabled = false;
671 }
672
673 static void sh_cmt_clocksource_suspend(struct clocksource *cs)
674 {
675         struct sh_cmt_channel *ch = cs_to_sh_cmt(cs);
676
677         if (!ch->cs_enabled)
678                 return;
679
680         sh_cmt_stop(ch, FLAG_CLOCKSOURCE);
681         pm_genpd_syscore_poweroff(&ch->cmt->pdev->dev);
682 }
683
684 static void sh_cmt_clocksource_resume(struct clocksource *cs)
685 {
686         struct sh_cmt_channel *ch = cs_to_sh_cmt(cs);
687
688         if (!ch->cs_enabled)
689                 return;
690
691         pm_genpd_syscore_poweron(&ch->cmt->pdev->dev);
692         sh_cmt_start(ch, FLAG_CLOCKSOURCE);
693 }
694
695 static int sh_cmt_register_clocksource(struct sh_cmt_channel *ch,
696                                        const char *name)
697 {
698         struct clocksource *cs = &ch->cs;
699
700         cs->name = name;
701         cs->rating = 125;
702         cs->read = sh_cmt_clocksource_read;
703         cs->enable = sh_cmt_clocksource_enable;
704         cs->disable = sh_cmt_clocksource_disable;
705         cs->suspend = sh_cmt_clocksource_suspend;
706         cs->resume = sh_cmt_clocksource_resume;
707         cs->mask = CLOCKSOURCE_MASK(sizeof(unsigned long) * 8);
708         cs->flags = CLOCK_SOURCE_IS_CONTINUOUS;
709
710         dev_info(&ch->cmt->pdev->dev, "ch%u: used as clock source\n",
711                  ch->index);
712
713         clocksource_register_hz(cs, ch->cmt->rate);
714         return 0;
715 }
716
717 static struct sh_cmt_channel *ced_to_sh_cmt(struct clock_event_device *ced)
718 {
719         return container_of(ced, struct sh_cmt_channel, ced);
720 }
721
722 static void sh_cmt_clock_event_start(struct sh_cmt_channel *ch, int periodic)
723 {
724         sh_cmt_start(ch, FLAG_CLOCKEVENT);
725
726         if (periodic)
727                 sh_cmt_set_next(ch, ((ch->cmt->rate + HZ/2) / HZ) - 1);
728         else
729                 sh_cmt_set_next(ch, ch->max_match_value);
730 }
731
732 static int sh_cmt_clock_event_shutdown(struct clock_event_device *ced)
733 {
734         struct sh_cmt_channel *ch = ced_to_sh_cmt(ced);
735
736         sh_cmt_stop(ch, FLAG_CLOCKEVENT);
737         return 0;
738 }
739
740 static int sh_cmt_clock_event_set_state(struct clock_event_device *ced,
741                                         int periodic)
742 {
743         struct sh_cmt_channel *ch = ced_to_sh_cmt(ced);
744
745         /* deal with old setting first */
746         if (clockevent_state_oneshot(ced) || clockevent_state_periodic(ced))
747                 sh_cmt_stop(ch, FLAG_CLOCKEVENT);
748
749         dev_info(&ch->cmt->pdev->dev, "ch%u: used for %s clock events\n",
750                  ch->index, periodic ? "periodic" : "oneshot");
751         sh_cmt_clock_event_start(ch, periodic);
752         return 0;
753 }
754
755 static int sh_cmt_clock_event_set_oneshot(struct clock_event_device *ced)
756 {
757         return sh_cmt_clock_event_set_state(ced, 0);
758 }
759
760 static int sh_cmt_clock_event_set_periodic(struct clock_event_device *ced)
761 {
762         return sh_cmt_clock_event_set_state(ced, 1);
763 }
764
765 static int sh_cmt_clock_event_next(unsigned long delta,
766                                    struct clock_event_device *ced)
767 {
768         struct sh_cmt_channel *ch = ced_to_sh_cmt(ced);
769
770         BUG_ON(!clockevent_state_oneshot(ced));
771         if (likely(ch->flags & FLAG_IRQCONTEXT))
772                 ch->next_match_value = delta - 1;
773         else
774                 sh_cmt_set_next(ch, delta - 1);
775
776         return 0;
777 }
778
779 static void sh_cmt_clock_event_suspend(struct clock_event_device *ced)
780 {
781         struct sh_cmt_channel *ch = ced_to_sh_cmt(ced);
782
783         pm_genpd_syscore_poweroff(&ch->cmt->pdev->dev);
784         clk_unprepare(ch->cmt->clk);
785 }
786
787 static void sh_cmt_clock_event_resume(struct clock_event_device *ced)
788 {
789         struct sh_cmt_channel *ch = ced_to_sh_cmt(ced);
790
791         clk_prepare(ch->cmt->clk);
792         pm_genpd_syscore_poweron(&ch->cmt->pdev->dev);
793 }
794
795 static int sh_cmt_register_clockevent(struct sh_cmt_channel *ch,
796                                       const char *name)
797 {
798         struct clock_event_device *ced = &ch->ced;
799         int irq;
800         int ret;
801
802         irq = platform_get_irq(ch->cmt->pdev, ch->index);
803         if (irq < 0) {
804                 dev_err(&ch->cmt->pdev->dev, "ch%u: failed to get irq\n",
805                         ch->index);
806                 return irq;
807         }
808
809         ret = request_irq(irq, sh_cmt_interrupt,
810                           IRQF_TIMER | IRQF_IRQPOLL | IRQF_NOBALANCING,
811                           dev_name(&ch->cmt->pdev->dev), ch);
812         if (ret) {
813                 dev_err(&ch->cmt->pdev->dev, "ch%u: failed to request irq %d\n",
814                         ch->index, irq);
815                 return ret;
816         }
817
818         ced->name = name;
819         ced->features = CLOCK_EVT_FEAT_PERIODIC;
820         ced->features |= CLOCK_EVT_FEAT_ONESHOT;
821         ced->rating = 125;
822         ced->cpumask = cpu_possible_mask;
823         ced->set_next_event = sh_cmt_clock_event_next;
824         ced->set_state_shutdown = sh_cmt_clock_event_shutdown;
825         ced->set_state_periodic = sh_cmt_clock_event_set_periodic;
826         ced->set_state_oneshot = sh_cmt_clock_event_set_oneshot;
827         ced->suspend = sh_cmt_clock_event_suspend;
828         ced->resume = sh_cmt_clock_event_resume;
829
830         /* TODO: calculate good shift from rate and counter bit width */
831         ced->shift = 32;
832         ced->mult = div_sc(ch->cmt->rate, NSEC_PER_SEC, ced->shift);
833         ced->max_delta_ns = clockevent_delta2ns(ch->max_match_value, ced);
834         ced->max_delta_ticks = ch->max_match_value;
835         ced->min_delta_ns = clockevent_delta2ns(0x1f, ced);
836         ced->min_delta_ticks = 0x1f;
837
838         dev_info(&ch->cmt->pdev->dev, "ch%u: used for clock events\n",
839                  ch->index);
840         clockevents_register_device(ced);
841
842         return 0;
843 }
844
845 static int sh_cmt_register(struct sh_cmt_channel *ch, const char *name,
846                            bool clockevent, bool clocksource)
847 {
848         int ret;
849
850         if (clockevent) {
851                 ch->cmt->has_clockevent = true;
852                 ret = sh_cmt_register_clockevent(ch, name);
853                 if (ret < 0)
854                         return ret;
855         }
856
857         if (clocksource) {
858                 ch->cmt->has_clocksource = true;
859                 sh_cmt_register_clocksource(ch, name);
860         }
861
862         return 0;
863 }
864
865 static int sh_cmt_setup_channel(struct sh_cmt_channel *ch, unsigned int index,
866                                 unsigned int hwidx, bool clockevent,
867                                 bool clocksource, struct sh_cmt_device *cmt)
868 {
869         int ret;
870
871         /* Skip unused channels. */
872         if (!clockevent && !clocksource)
873                 return 0;
874
875         ch->cmt = cmt;
876         ch->index = index;
877         ch->hwidx = hwidx;
878         ch->timer_bit = hwidx;
879
880         /*
881          * Compute the address of the channel control register block. For the
882          * timers with a per-channel start/stop register, compute its address
883          * as well.
884          */
885         switch (cmt->info->model) {
886         case SH_CMT_16BIT:
887                 ch->ioctrl = cmt->mapbase + 2 + ch->hwidx * 6;
888                 break;
889         case SH_CMT_32BIT:
890         case SH_CMT_48BIT:
891                 ch->ioctrl = cmt->mapbase + 0x10 + ch->hwidx * 0x10;
892                 break;
893         case SH_CMT_32BIT_FAST:
894                 /*
895                  * The 32-bit "fast" timer has a single channel at hwidx 5 but
896                  * is located at offset 0x40 instead of 0x60 for some reason.
897                  */
898                 ch->ioctrl = cmt->mapbase + 0x40;
899                 break;
900         case SH_CMT0_RCAR_GEN2:
901         case SH_CMT1_RCAR_GEN2:
902                 ch->iostart = cmt->mapbase + ch->hwidx * 0x100;
903                 ch->ioctrl = ch->iostart + 0x10;
904                 ch->timer_bit = 0;
905                 break;
906         }
907
908         if (cmt->info->width == (sizeof(ch->max_match_value) * 8))
909                 ch->max_match_value = ~0;
910         else
911                 ch->max_match_value = (1 << cmt->info->width) - 1;
912
913         ch->match_value = ch->max_match_value;
914         raw_spin_lock_init(&ch->lock);
915
916         ret = sh_cmt_register(ch, dev_name(&cmt->pdev->dev),
917                               clockevent, clocksource);
918         if (ret) {
919                 dev_err(&cmt->pdev->dev, "ch%u: registration failed\n",
920                         ch->index);
921                 return ret;
922         }
923         ch->cs_enabled = false;
924
925         return 0;
926 }
927
928 static int sh_cmt_map_memory(struct sh_cmt_device *cmt)
929 {
930         struct resource *mem;
931
932         mem = platform_get_resource(cmt->pdev, IORESOURCE_MEM, 0);
933         if (!mem) {
934                 dev_err(&cmt->pdev->dev, "failed to get I/O memory\n");
935                 return -ENXIO;
936         }
937
938         cmt->mapbase = ioremap_nocache(mem->start, resource_size(mem));
939         if (cmt->mapbase == NULL) {
940                 dev_err(&cmt->pdev->dev, "failed to remap I/O memory\n");
941                 return -ENXIO;
942         }
943
944         return 0;
945 }
946
947 static const struct platform_device_id sh_cmt_id_table[] = {
948         { "sh-cmt-16", (kernel_ulong_t)&sh_cmt_info[SH_CMT_16BIT] },
949         { "sh-cmt-32", (kernel_ulong_t)&sh_cmt_info[SH_CMT_32BIT] },
950         { }
951 };
952 MODULE_DEVICE_TABLE(platform, sh_cmt_id_table);
953
954 static const struct of_device_id sh_cmt_of_table[] __maybe_unused = {
955         { .compatible = "renesas,cmt-32", .data = &sh_cmt_info[SH_CMT_32BIT] },
956         { .compatible = "renesas,cmt-32-fast", .data = &sh_cmt_info[SH_CMT_32BIT_FAST] },
957         { .compatible = "renesas,cmt-48", .data = &sh_cmt_info[SH_CMT_48BIT] },
958         { .compatible = "renesas,cmt-48-gen2", .data = &sh_cmt_info[SH_CMT0_RCAR_GEN2] },
959         { .compatible = "renesas,rcar-gen2-cmt0", .data = &sh_cmt_info[SH_CMT0_RCAR_GEN2] },
960         { .compatible = "renesas,rcar-gen2-cmt1", .data = &sh_cmt_info[SH_CMT1_RCAR_GEN2] },
961         { }
962 };
963 MODULE_DEVICE_TABLE(of, sh_cmt_of_table);
964
965 static int sh_cmt_parse_dt(struct sh_cmt_device *cmt)
966 {
967         struct device_node *np = cmt->pdev->dev.of_node;
968
969         return of_property_read_u32(np, "renesas,channels-mask",
970                                     &cmt->hw_channels);
971 }
972
973 static int sh_cmt_setup(struct sh_cmt_device *cmt, struct platform_device *pdev)
974 {
975         unsigned int mask;
976         unsigned int i;
977         int ret;
978
979         cmt->pdev = pdev;
980         raw_spin_lock_init(&cmt->lock);
981
982         if (IS_ENABLED(CONFIG_OF) && pdev->dev.of_node) {
983                 const struct of_device_id *id;
984
985                 id = of_match_node(sh_cmt_of_table, pdev->dev.of_node);
986                 cmt->info = id->data;
987
988                 /* prefer in-driver channel configuration over DT */
989                 if (cmt->info->channels_mask) {
990                         cmt->hw_channels = cmt->info->channels_mask;
991                 } else {
992                         ret = sh_cmt_parse_dt(cmt);
993                         if (ret < 0)
994                                 return ret;
995                 }
996         } else if (pdev->dev.platform_data) {
997                 struct sh_timer_config *cfg = pdev->dev.platform_data;
998                 const struct platform_device_id *id = pdev->id_entry;
999
1000                 cmt->info = (const struct sh_cmt_info *)id->driver_data;
1001                 cmt->hw_channels = cfg->channels_mask;
1002         } else {
1003                 dev_err(&cmt->pdev->dev, "missing platform data\n");
1004                 return -ENXIO;
1005         }
1006
1007         /* Get hold of clock. */
1008         cmt->clk = clk_get(&cmt->pdev->dev, "fck");
1009         if (IS_ERR(cmt->clk)) {
1010                 dev_err(&cmt->pdev->dev, "cannot get clock\n");
1011                 return PTR_ERR(cmt->clk);
1012         }
1013
1014         ret = clk_prepare(cmt->clk);
1015         if (ret < 0)
1016                 goto err_clk_put;
1017
1018         /* Determine clock rate. */
1019         ret = clk_enable(cmt->clk);
1020         if (ret < 0)
1021                 goto err_clk_unprepare;
1022
1023         if (cmt->info->width == 16)
1024                 cmt->rate = clk_get_rate(cmt->clk) / 512;
1025         else
1026                 cmt->rate = clk_get_rate(cmt->clk) / 8;
1027
1028         clk_disable(cmt->clk);
1029
1030         /* Map the memory resource(s). */
1031         ret = sh_cmt_map_memory(cmt);
1032         if (ret < 0)
1033                 goto err_clk_unprepare;
1034
1035         /* Allocate and setup the channels. */
1036         cmt->num_channels = hweight8(cmt->hw_channels);
1037         cmt->channels = kzalloc(cmt->num_channels * sizeof(*cmt->channels),
1038                                 GFP_KERNEL);
1039         if (cmt->channels == NULL) {
1040                 ret = -ENOMEM;
1041                 goto err_unmap;
1042         }
1043
1044         /*
1045          * Use the first channel as a clock event device and the second channel
1046          * as a clock source. If only one channel is available use it for both.
1047          */
1048         for (i = 0, mask = cmt->hw_channels; i < cmt->num_channels; ++i) {
1049                 unsigned int hwidx = ffs(mask) - 1;
1050                 bool clocksource = i == 1 || cmt->num_channels == 1;
1051                 bool clockevent = i == 0;
1052
1053                 ret = sh_cmt_setup_channel(&cmt->channels[i], i, hwidx,
1054                                            clockevent, clocksource, cmt);
1055                 if (ret < 0)
1056                         goto err_unmap;
1057
1058                 mask &= ~(1 << hwidx);
1059         }
1060
1061         platform_set_drvdata(pdev, cmt);
1062
1063         return 0;
1064
1065 err_unmap:
1066         kfree(cmt->channels);
1067         iounmap(cmt->mapbase);
1068 err_clk_unprepare:
1069         clk_unprepare(cmt->clk);
1070 err_clk_put:
1071         clk_put(cmt->clk);
1072         return ret;
1073 }
1074
1075 static int sh_cmt_probe(struct platform_device *pdev)
1076 {
1077         struct sh_cmt_device *cmt = platform_get_drvdata(pdev);
1078         int ret;
1079
1080         if (!is_early_platform_device(pdev)) {
1081                 pm_runtime_set_active(&pdev->dev);
1082                 pm_runtime_enable(&pdev->dev);
1083         }
1084
1085         if (cmt) {
1086                 dev_info(&pdev->dev, "kept as earlytimer\n");
1087                 goto out;
1088         }
1089
1090         cmt = kzalloc(sizeof(*cmt), GFP_KERNEL);
1091         if (cmt == NULL)
1092                 return -ENOMEM;
1093
1094         ret = sh_cmt_setup(cmt, pdev);
1095         if (ret) {
1096                 kfree(cmt);
1097                 pm_runtime_idle(&pdev->dev);
1098                 return ret;
1099         }
1100         if (is_early_platform_device(pdev))
1101                 return 0;
1102
1103  out:
1104         if (cmt->has_clockevent || cmt->has_clocksource)
1105                 pm_runtime_irq_safe(&pdev->dev);
1106         else
1107                 pm_runtime_idle(&pdev->dev);
1108
1109         return 0;
1110 }
1111
1112 static int sh_cmt_remove(struct platform_device *pdev)
1113 {
1114         return -EBUSY; /* cannot unregister clockevent and clocksource */
1115 }
1116
1117 static struct platform_driver sh_cmt_device_driver = {
1118         .probe          = sh_cmt_probe,
1119         .remove         = sh_cmt_remove,
1120         .driver         = {
1121                 .name   = "sh_cmt",
1122                 .of_match_table = of_match_ptr(sh_cmt_of_table),
1123         },
1124         .id_table       = sh_cmt_id_table,
1125 };
1126
1127 static int __init sh_cmt_init(void)
1128 {
1129         return platform_driver_register(&sh_cmt_device_driver);
1130 }
1131
1132 static void __exit sh_cmt_exit(void)
1133 {
1134         platform_driver_unregister(&sh_cmt_device_driver);
1135 }
1136
1137 early_platform_init("earlytimer", &sh_cmt_device_driver);
1138 subsys_initcall(sh_cmt_init);
1139 module_exit(sh_cmt_exit);
1140
1141 MODULE_AUTHOR("Magnus Damm");
1142 MODULE_DESCRIPTION("SuperH CMT Timer Driver");
1143 MODULE_LICENSE("GPL v2");