]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/clk/clk.c
Merge branch 'clk-shmobile-for-4.2' of git://git.kernel.org/pub/scm/linux/kernel...
[karo-tx-linux.git] / drivers / clk / clk.c
1 /*
2  * Copyright (C) 2010-2011 Canonical Ltd <jeremy.kerr@canonical.com>
3  * Copyright (C) 2011-2012 Linaro Ltd <mturquette@linaro.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Standard functionality for the common clock API.  See Documentation/clk.txt
10  */
11
12 #include <linux/clk-provider.h>
13 #include <linux/clk/clk-conf.h>
14 #include <linux/module.h>
15 #include <linux/mutex.h>
16 #include <linux/spinlock.h>
17 #include <linux/err.h>
18 #include <linux/list.h>
19 #include <linux/slab.h>
20 #include <linux/of.h>
21 #include <linux/device.h>
22 #include <linux/init.h>
23 #include <linux/sched.h>
24 #include <linux/clkdev.h>
25
26 #include "clk.h"
27
28 static DEFINE_SPINLOCK(enable_lock);
29 static DEFINE_MUTEX(prepare_lock);
30
31 static struct task_struct *prepare_owner;
32 static struct task_struct *enable_owner;
33
34 static int prepare_refcnt;
35 static int enable_refcnt;
36
37 static HLIST_HEAD(clk_root_list);
38 static HLIST_HEAD(clk_orphan_list);
39 static LIST_HEAD(clk_notifier_list);
40
41 /***    private data structures    ***/
42
43 struct clk_core {
44         const char              *name;
45         const struct clk_ops    *ops;
46         struct clk_hw           *hw;
47         struct module           *owner;
48         struct clk_core         *parent;
49         const char              **parent_names;
50         struct clk_core         **parents;
51         u8                      num_parents;
52         u8                      new_parent_index;
53         unsigned long           rate;
54         unsigned long           req_rate;
55         unsigned long           new_rate;
56         struct clk_core         *new_parent;
57         struct clk_core         *new_child;
58         unsigned long           flags;
59         unsigned int            enable_count;
60         unsigned int            prepare_count;
61         unsigned long           accuracy;
62         int                     phase;
63         struct hlist_head       children;
64         struct hlist_node       child_node;
65         struct hlist_head       clks;
66         unsigned int            notifier_count;
67 #ifdef CONFIG_DEBUG_FS
68         struct dentry           *dentry;
69         struct hlist_node       debug_node;
70 #endif
71         struct kref             ref;
72 };
73
74 #define CREATE_TRACE_POINTS
75 #include <trace/events/clk.h>
76
77 struct clk {
78         struct clk_core *core;
79         const char *dev_id;
80         const char *con_id;
81         unsigned long min_rate;
82         unsigned long max_rate;
83         struct hlist_node clks_node;
84 };
85
86 /***           locking             ***/
87 static void clk_prepare_lock(void)
88 {
89         if (!mutex_trylock(&prepare_lock)) {
90                 if (prepare_owner == current) {
91                         prepare_refcnt++;
92                         return;
93                 }
94                 mutex_lock(&prepare_lock);
95         }
96         WARN_ON_ONCE(prepare_owner != NULL);
97         WARN_ON_ONCE(prepare_refcnt != 0);
98         prepare_owner = current;
99         prepare_refcnt = 1;
100 }
101
102 static void clk_prepare_unlock(void)
103 {
104         WARN_ON_ONCE(prepare_owner != current);
105         WARN_ON_ONCE(prepare_refcnt == 0);
106
107         if (--prepare_refcnt)
108                 return;
109         prepare_owner = NULL;
110         mutex_unlock(&prepare_lock);
111 }
112
113 static unsigned long clk_enable_lock(void)
114 {
115         unsigned long flags;
116
117         if (!spin_trylock_irqsave(&enable_lock, flags)) {
118                 if (enable_owner == current) {
119                         enable_refcnt++;
120                         return flags;
121                 }
122                 spin_lock_irqsave(&enable_lock, flags);
123         }
124         WARN_ON_ONCE(enable_owner != NULL);
125         WARN_ON_ONCE(enable_refcnt != 0);
126         enable_owner = current;
127         enable_refcnt = 1;
128         return flags;
129 }
130
131 static void clk_enable_unlock(unsigned long flags)
132 {
133         WARN_ON_ONCE(enable_owner != current);
134         WARN_ON_ONCE(enable_refcnt == 0);
135
136         if (--enable_refcnt)
137                 return;
138         enable_owner = NULL;
139         spin_unlock_irqrestore(&enable_lock, flags);
140 }
141
142 static bool clk_core_is_prepared(struct clk_core *core)
143 {
144         /*
145          * .is_prepared is optional for clocks that can prepare
146          * fall back to software usage counter if it is missing
147          */
148         if (!core->ops->is_prepared)
149                 return core->prepare_count;
150
151         return core->ops->is_prepared(core->hw);
152 }
153
154 static bool clk_core_is_enabled(struct clk_core *core)
155 {
156         /*
157          * .is_enabled is only mandatory for clocks that gate
158          * fall back to software usage counter if .is_enabled is missing
159          */
160         if (!core->ops->is_enabled)
161                 return core->enable_count;
162
163         return core->ops->is_enabled(core->hw);
164 }
165
166 static void clk_unprepare_unused_subtree(struct clk_core *core)
167 {
168         struct clk_core *child;
169
170         lockdep_assert_held(&prepare_lock);
171
172         hlist_for_each_entry(child, &core->children, child_node)
173                 clk_unprepare_unused_subtree(child);
174
175         if (core->prepare_count)
176                 return;
177
178         if (core->flags & CLK_IGNORE_UNUSED)
179                 return;
180
181         if (clk_core_is_prepared(core)) {
182                 trace_clk_unprepare(core);
183                 if (core->ops->unprepare_unused)
184                         core->ops->unprepare_unused(core->hw);
185                 else if (core->ops->unprepare)
186                         core->ops->unprepare(core->hw);
187                 trace_clk_unprepare_complete(core);
188         }
189 }
190
191 static void clk_disable_unused_subtree(struct clk_core *core)
192 {
193         struct clk_core *child;
194         unsigned long flags;
195
196         lockdep_assert_held(&prepare_lock);
197
198         hlist_for_each_entry(child, &core->children, child_node)
199                 clk_disable_unused_subtree(child);
200
201         flags = clk_enable_lock();
202
203         if (core->enable_count)
204                 goto unlock_out;
205
206         if (core->flags & CLK_IGNORE_UNUSED)
207                 goto unlock_out;
208
209         /*
210          * some gate clocks have special needs during the disable-unused
211          * sequence.  call .disable_unused if available, otherwise fall
212          * back to .disable
213          */
214         if (clk_core_is_enabled(core)) {
215                 trace_clk_disable(core);
216                 if (core->ops->disable_unused)
217                         core->ops->disable_unused(core->hw);
218                 else if (core->ops->disable)
219                         core->ops->disable(core->hw);
220                 trace_clk_disable_complete(core);
221         }
222
223 unlock_out:
224         clk_enable_unlock(flags);
225 }
226
227 static bool clk_ignore_unused;
228 static int __init clk_ignore_unused_setup(char *__unused)
229 {
230         clk_ignore_unused = true;
231         return 1;
232 }
233 __setup("clk_ignore_unused", clk_ignore_unused_setup);
234
235 static int clk_disable_unused(void)
236 {
237         struct clk_core *core;
238
239         if (clk_ignore_unused) {
240                 pr_warn("clk: Not disabling unused clocks\n");
241                 return 0;
242         }
243
244         clk_prepare_lock();
245
246         hlist_for_each_entry(core, &clk_root_list, child_node)
247                 clk_disable_unused_subtree(core);
248
249         hlist_for_each_entry(core, &clk_orphan_list, child_node)
250                 clk_disable_unused_subtree(core);
251
252         hlist_for_each_entry(core, &clk_root_list, child_node)
253                 clk_unprepare_unused_subtree(core);
254
255         hlist_for_each_entry(core, &clk_orphan_list, child_node)
256                 clk_unprepare_unused_subtree(core);
257
258         clk_prepare_unlock();
259
260         return 0;
261 }
262 late_initcall_sync(clk_disable_unused);
263
264 /***    helper functions   ***/
265
266 const char *__clk_get_name(struct clk *clk)
267 {
268         return !clk ? NULL : clk->core->name;
269 }
270 EXPORT_SYMBOL_GPL(__clk_get_name);
271
272 struct clk_hw *__clk_get_hw(struct clk *clk)
273 {
274         return !clk ? NULL : clk->core->hw;
275 }
276 EXPORT_SYMBOL_GPL(__clk_get_hw);
277
278 u8 __clk_get_num_parents(struct clk *clk)
279 {
280         return !clk ? 0 : clk->core->num_parents;
281 }
282 EXPORT_SYMBOL_GPL(__clk_get_num_parents);
283
284 struct clk *__clk_get_parent(struct clk *clk)
285 {
286         if (!clk)
287                 return NULL;
288
289         /* TODO: Create a per-user clk and change callers to call clk_put */
290         return !clk->core->parent ? NULL : clk->core->parent->hw->clk;
291 }
292 EXPORT_SYMBOL_GPL(__clk_get_parent);
293
294 static struct clk_core *__clk_lookup_subtree(const char *name,
295                                              struct clk_core *core)
296 {
297         struct clk_core *child;
298         struct clk_core *ret;
299
300         if (!strcmp(core->name, name))
301                 return core;
302
303         hlist_for_each_entry(child, &core->children, child_node) {
304                 ret = __clk_lookup_subtree(name, child);
305                 if (ret)
306                         return ret;
307         }
308
309         return NULL;
310 }
311
312 static struct clk_core *clk_core_lookup(const char *name)
313 {
314         struct clk_core *root_clk;
315         struct clk_core *ret;
316
317         if (!name)
318                 return NULL;
319
320         /* search the 'proper' clk tree first */
321         hlist_for_each_entry(root_clk, &clk_root_list, child_node) {
322                 ret = __clk_lookup_subtree(name, root_clk);
323                 if (ret)
324                         return ret;
325         }
326
327         /* if not found, then search the orphan tree */
328         hlist_for_each_entry(root_clk, &clk_orphan_list, child_node) {
329                 ret = __clk_lookup_subtree(name, root_clk);
330                 if (ret)
331                         return ret;
332         }
333
334         return NULL;
335 }
336
337 static struct clk_core *clk_core_get_parent_by_index(struct clk_core *core,
338                                                          u8 index)
339 {
340         if (!core || index >= core->num_parents)
341                 return NULL;
342         else if (!core->parents)
343                 return clk_core_lookup(core->parent_names[index]);
344         else if (!core->parents[index])
345                 return core->parents[index] =
346                         clk_core_lookup(core->parent_names[index]);
347         else
348                 return core->parents[index];
349 }
350
351 struct clk *clk_get_parent_by_index(struct clk *clk, u8 index)
352 {
353         struct clk_core *parent;
354
355         if (!clk)
356                 return NULL;
357
358         parent = clk_core_get_parent_by_index(clk->core, index);
359
360         return !parent ? NULL : parent->hw->clk;
361 }
362 EXPORT_SYMBOL_GPL(clk_get_parent_by_index);
363
364 unsigned int __clk_get_enable_count(struct clk *clk)
365 {
366         return !clk ? 0 : clk->core->enable_count;
367 }
368
369 static unsigned long clk_core_get_rate_nolock(struct clk_core *core)
370 {
371         unsigned long ret;
372
373         if (!core) {
374                 ret = 0;
375                 goto out;
376         }
377
378         ret = core->rate;
379
380         if (core->flags & CLK_IS_ROOT)
381                 goto out;
382
383         if (!core->parent)
384                 ret = 0;
385
386 out:
387         return ret;
388 }
389
390 unsigned long __clk_get_rate(struct clk *clk)
391 {
392         if (!clk)
393                 return 0;
394
395         return clk_core_get_rate_nolock(clk->core);
396 }
397 EXPORT_SYMBOL_GPL(__clk_get_rate);
398
399 static unsigned long __clk_get_accuracy(struct clk_core *core)
400 {
401         if (!core)
402                 return 0;
403
404         return core->accuracy;
405 }
406
407 unsigned long __clk_get_flags(struct clk *clk)
408 {
409         return !clk ? 0 : clk->core->flags;
410 }
411 EXPORT_SYMBOL_GPL(__clk_get_flags);
412
413 bool __clk_is_prepared(struct clk *clk)
414 {
415         if (!clk)
416                 return false;
417
418         return clk_core_is_prepared(clk->core);
419 }
420
421 bool __clk_is_enabled(struct clk *clk)
422 {
423         if (!clk)
424                 return false;
425
426         return clk_core_is_enabled(clk->core);
427 }
428 EXPORT_SYMBOL_GPL(__clk_is_enabled);
429
430 static bool mux_is_better_rate(unsigned long rate, unsigned long now,
431                            unsigned long best, unsigned long flags)
432 {
433         if (flags & CLK_MUX_ROUND_CLOSEST)
434                 return abs(now - rate) < abs(best - rate);
435
436         return now <= rate && now > best;
437 }
438
439 static long
440 clk_mux_determine_rate_flags(struct clk_hw *hw, unsigned long rate,
441                              unsigned long min_rate,
442                              unsigned long max_rate,
443                              unsigned long *best_parent_rate,
444                              struct clk_hw **best_parent_p,
445                              unsigned long flags)
446 {
447         struct clk_core *core = hw->core, *parent, *best_parent = NULL;
448         int i, num_parents;
449         unsigned long parent_rate, best = 0;
450
451         /* if NO_REPARENT flag set, pass through to current parent */
452         if (core->flags & CLK_SET_RATE_NO_REPARENT) {
453                 parent = core->parent;
454                 if (core->flags & CLK_SET_RATE_PARENT)
455                         best = __clk_determine_rate(parent ? parent->hw : NULL,
456                                                     rate, min_rate, max_rate);
457                 else if (parent)
458                         best = clk_core_get_rate_nolock(parent);
459                 else
460                         best = clk_core_get_rate_nolock(core);
461                 goto out;
462         }
463
464         /* find the parent that can provide the fastest rate <= rate */
465         num_parents = core->num_parents;
466         for (i = 0; i < num_parents; i++) {
467                 parent = clk_core_get_parent_by_index(core, i);
468                 if (!parent)
469                         continue;
470                 if (core->flags & CLK_SET_RATE_PARENT)
471                         parent_rate = __clk_determine_rate(parent->hw, rate,
472                                                            min_rate,
473                                                            max_rate);
474                 else
475                         parent_rate = clk_core_get_rate_nolock(parent);
476                 if (mux_is_better_rate(rate, parent_rate, best, flags)) {
477                         best_parent = parent;
478                         best = parent_rate;
479                 }
480         }
481
482 out:
483         if (best_parent)
484                 *best_parent_p = best_parent->hw;
485         *best_parent_rate = best;
486
487         return best;
488 }
489
490 struct clk *__clk_lookup(const char *name)
491 {
492         struct clk_core *core = clk_core_lookup(name);
493
494         return !core ? NULL : core->hw->clk;
495 }
496
497 static void clk_core_get_boundaries(struct clk_core *core,
498                                     unsigned long *min_rate,
499                                     unsigned long *max_rate)
500 {
501         struct clk *clk_user;
502
503         *min_rate = 0;
504         *max_rate = ULONG_MAX;
505
506         hlist_for_each_entry(clk_user, &core->clks, clks_node)
507                 *min_rate = max(*min_rate, clk_user->min_rate);
508
509         hlist_for_each_entry(clk_user, &core->clks, clks_node)
510                 *max_rate = min(*max_rate, clk_user->max_rate);
511 }
512
513 /*
514  * Helper for finding best parent to provide a given frequency. This can be used
515  * directly as a determine_rate callback (e.g. for a mux), or from a more
516  * complex clock that may combine a mux with other operations.
517  */
518 long __clk_mux_determine_rate(struct clk_hw *hw, unsigned long rate,
519                               unsigned long min_rate,
520                               unsigned long max_rate,
521                               unsigned long *best_parent_rate,
522                               struct clk_hw **best_parent_p)
523 {
524         return clk_mux_determine_rate_flags(hw, rate, min_rate, max_rate,
525                                             best_parent_rate,
526                                             best_parent_p, 0);
527 }
528 EXPORT_SYMBOL_GPL(__clk_mux_determine_rate);
529
530 long __clk_mux_determine_rate_closest(struct clk_hw *hw, unsigned long rate,
531                               unsigned long min_rate,
532                               unsigned long max_rate,
533                               unsigned long *best_parent_rate,
534                               struct clk_hw **best_parent_p)
535 {
536         return clk_mux_determine_rate_flags(hw, rate, min_rate, max_rate,
537                                             best_parent_rate,
538                                             best_parent_p,
539                                             CLK_MUX_ROUND_CLOSEST);
540 }
541 EXPORT_SYMBOL_GPL(__clk_mux_determine_rate_closest);
542
543 /***        clk api        ***/
544
545 static void clk_core_unprepare(struct clk_core *core)
546 {
547         lockdep_assert_held(&prepare_lock);
548
549         if (!core)
550                 return;
551
552         if (WARN_ON(core->prepare_count == 0))
553                 return;
554
555         if (--core->prepare_count > 0)
556                 return;
557
558         WARN_ON(core->enable_count > 0);
559
560         trace_clk_unprepare(core);
561
562         if (core->ops->unprepare)
563                 core->ops->unprepare(core->hw);
564
565         trace_clk_unprepare_complete(core);
566         clk_core_unprepare(core->parent);
567 }
568
569 /**
570  * clk_unprepare - undo preparation of a clock source
571  * @clk: the clk being unprepared
572  *
573  * clk_unprepare may sleep, which differentiates it from clk_disable.  In a
574  * simple case, clk_unprepare can be used instead of clk_disable to gate a clk
575  * if the operation may sleep.  One example is a clk which is accessed over
576  * I2c.  In the complex case a clk gate operation may require a fast and a slow
577  * part.  It is this reason that clk_unprepare and clk_disable are not mutually
578  * exclusive.  In fact clk_disable must be called before clk_unprepare.
579  */
580 void clk_unprepare(struct clk *clk)
581 {
582         if (IS_ERR_OR_NULL(clk))
583                 return;
584
585         clk_prepare_lock();
586         clk_core_unprepare(clk->core);
587         clk_prepare_unlock();
588 }
589 EXPORT_SYMBOL_GPL(clk_unprepare);
590
591 static int clk_core_prepare(struct clk_core *core)
592 {
593         int ret = 0;
594
595         lockdep_assert_held(&prepare_lock);
596
597         if (!core)
598                 return 0;
599
600         if (core->prepare_count == 0) {
601                 ret = clk_core_prepare(core->parent);
602                 if (ret)
603                         return ret;
604
605                 trace_clk_prepare(core);
606
607                 if (core->ops->prepare)
608                         ret = core->ops->prepare(core->hw);
609
610                 trace_clk_prepare_complete(core);
611
612                 if (ret) {
613                         clk_core_unprepare(core->parent);
614                         return ret;
615                 }
616         }
617
618         core->prepare_count++;
619
620         return 0;
621 }
622
623 /**
624  * clk_prepare - prepare a clock source
625  * @clk: the clk being prepared
626  *
627  * clk_prepare may sleep, which differentiates it from clk_enable.  In a simple
628  * case, clk_prepare can be used instead of clk_enable to ungate a clk if the
629  * operation may sleep.  One example is a clk which is accessed over I2c.  In
630  * the complex case a clk ungate operation may require a fast and a slow part.
631  * It is this reason that clk_prepare and clk_enable are not mutually
632  * exclusive.  In fact clk_prepare must be called before clk_enable.
633  * Returns 0 on success, -EERROR otherwise.
634  */
635 int clk_prepare(struct clk *clk)
636 {
637         int ret;
638
639         if (!clk)
640                 return 0;
641
642         clk_prepare_lock();
643         ret = clk_core_prepare(clk->core);
644         clk_prepare_unlock();
645
646         return ret;
647 }
648 EXPORT_SYMBOL_GPL(clk_prepare);
649
650 static void clk_core_disable(struct clk_core *core)
651 {
652         lockdep_assert_held(&enable_lock);
653
654         if (!core)
655                 return;
656
657         if (WARN_ON(core->enable_count == 0))
658                 return;
659
660         if (--core->enable_count > 0)
661                 return;
662
663         trace_clk_disable(core);
664
665         if (core->ops->disable)
666                 core->ops->disable(core->hw);
667
668         trace_clk_disable_complete(core);
669
670         clk_core_disable(core->parent);
671 }
672
673 /**
674  * clk_disable - gate a clock
675  * @clk: the clk being gated
676  *
677  * clk_disable must not sleep, which differentiates it from clk_unprepare.  In
678  * a simple case, clk_disable can be used instead of clk_unprepare to gate a
679  * clk if the operation is fast and will never sleep.  One example is a
680  * SoC-internal clk which is controlled via simple register writes.  In the
681  * complex case a clk gate operation may require a fast and a slow part.  It is
682  * this reason that clk_unprepare and clk_disable are not mutually exclusive.
683  * In fact clk_disable must be called before clk_unprepare.
684  */
685 void clk_disable(struct clk *clk)
686 {
687         unsigned long flags;
688
689         if (IS_ERR_OR_NULL(clk))
690                 return;
691
692         flags = clk_enable_lock();
693         clk_core_disable(clk->core);
694         clk_enable_unlock(flags);
695 }
696 EXPORT_SYMBOL_GPL(clk_disable);
697
698 static int clk_core_enable(struct clk_core *core)
699 {
700         int ret = 0;
701
702         lockdep_assert_held(&enable_lock);
703
704         if (!core)
705                 return 0;
706
707         if (WARN_ON(core->prepare_count == 0))
708                 return -ESHUTDOWN;
709
710         if (core->enable_count == 0) {
711                 ret = clk_core_enable(core->parent);
712
713                 if (ret)
714                         return ret;
715
716                 trace_clk_enable(core);
717
718                 if (core->ops->enable)
719                         ret = core->ops->enable(core->hw);
720
721                 trace_clk_enable_complete(core);
722
723                 if (ret) {
724                         clk_core_disable(core->parent);
725                         return ret;
726                 }
727         }
728
729         core->enable_count++;
730         return 0;
731 }
732
733 /**
734  * clk_enable - ungate a clock
735  * @clk: the clk being ungated
736  *
737  * clk_enable must not sleep, which differentiates it from clk_prepare.  In a
738  * simple case, clk_enable can be used instead of clk_prepare to ungate a clk
739  * if the operation will never sleep.  One example is a SoC-internal clk which
740  * is controlled via simple register writes.  In the complex case a clk ungate
741  * operation may require a fast and a slow part.  It is this reason that
742  * clk_enable and clk_prepare are not mutually exclusive.  In fact clk_prepare
743  * must be called before clk_enable.  Returns 0 on success, -EERROR
744  * otherwise.
745  */
746 int clk_enable(struct clk *clk)
747 {
748         unsigned long flags;
749         int ret;
750
751         if (!clk)
752                 return 0;
753
754         flags = clk_enable_lock();
755         ret = clk_core_enable(clk->core);
756         clk_enable_unlock(flags);
757
758         return ret;
759 }
760 EXPORT_SYMBOL_GPL(clk_enable);
761
762 static unsigned long clk_core_round_rate_nolock(struct clk_core *core,
763                                                 unsigned long rate,
764                                                 unsigned long min_rate,
765                                                 unsigned long max_rate)
766 {
767         unsigned long parent_rate = 0;
768         struct clk_core *parent;
769         struct clk_hw *parent_hw;
770
771         lockdep_assert_held(&prepare_lock);
772
773         if (!core)
774                 return 0;
775
776         parent = core->parent;
777         if (parent)
778                 parent_rate = parent->rate;
779
780         if (core->ops->determine_rate) {
781                 parent_hw = parent ? parent->hw : NULL;
782                 return core->ops->determine_rate(core->hw, rate,
783                                                 min_rate, max_rate,
784                                                 &parent_rate, &parent_hw);
785         } else if (core->ops->round_rate)
786                 return core->ops->round_rate(core->hw, rate, &parent_rate);
787         else if (core->flags & CLK_SET_RATE_PARENT)
788                 return clk_core_round_rate_nolock(core->parent, rate, min_rate,
789                                                   max_rate);
790         else
791                 return core->rate;
792 }
793
794 /**
795  * __clk_determine_rate - get the closest rate actually supported by a clock
796  * @hw: determine the rate of this clock
797  * @rate: target rate
798  * @min_rate: returned rate must be greater than this rate
799  * @max_rate: returned rate must be less than this rate
800  *
801  * Useful for clk_ops such as .set_rate and .determine_rate.
802  */
803 unsigned long __clk_determine_rate(struct clk_hw *hw,
804                                    unsigned long rate,
805                                    unsigned long min_rate,
806                                    unsigned long max_rate)
807 {
808         if (!hw)
809                 return 0;
810
811         return clk_core_round_rate_nolock(hw->core, rate, min_rate, max_rate);
812 }
813 EXPORT_SYMBOL_GPL(__clk_determine_rate);
814
815 /**
816  * __clk_round_rate - round the given rate for a clk
817  * @clk: round the rate of this clock
818  * @rate: the rate which is to be rounded
819  *
820  * Useful for clk_ops such as .set_rate
821  */
822 unsigned long __clk_round_rate(struct clk *clk, unsigned long rate)
823 {
824         unsigned long min_rate;
825         unsigned long max_rate;
826
827         if (!clk)
828                 return 0;
829
830         clk_core_get_boundaries(clk->core, &min_rate, &max_rate);
831
832         return clk_core_round_rate_nolock(clk->core, rate, min_rate, max_rate);
833 }
834 EXPORT_SYMBOL_GPL(__clk_round_rate);
835
836 /**
837  * clk_round_rate - round the given rate for a clk
838  * @clk: the clk for which we are rounding a rate
839  * @rate: the rate which is to be rounded
840  *
841  * Takes in a rate as input and rounds it to a rate that the clk can actually
842  * use which is then returned.  If clk doesn't support round_rate operation
843  * then the parent rate is returned.
844  */
845 long clk_round_rate(struct clk *clk, unsigned long rate)
846 {
847         unsigned long ret;
848
849         if (!clk)
850                 return 0;
851
852         clk_prepare_lock();
853         ret = __clk_round_rate(clk, rate);
854         clk_prepare_unlock();
855
856         return ret;
857 }
858 EXPORT_SYMBOL_GPL(clk_round_rate);
859
860 /**
861  * __clk_notify - call clk notifier chain
862  * @core: clk that is changing rate
863  * @msg: clk notifier type (see include/linux/clk.h)
864  * @old_rate: old clk rate
865  * @new_rate: new clk rate
866  *
867  * Triggers a notifier call chain on the clk rate-change notification
868  * for 'clk'.  Passes a pointer to the struct clk and the previous
869  * and current rates to the notifier callback.  Intended to be called by
870  * internal clock code only.  Returns NOTIFY_DONE from the last driver
871  * called if all went well, or NOTIFY_STOP or NOTIFY_BAD immediately if
872  * a driver returns that.
873  */
874 static int __clk_notify(struct clk_core *core, unsigned long msg,
875                 unsigned long old_rate, unsigned long new_rate)
876 {
877         struct clk_notifier *cn;
878         struct clk_notifier_data cnd;
879         int ret = NOTIFY_DONE;
880
881         cnd.old_rate = old_rate;
882         cnd.new_rate = new_rate;
883
884         list_for_each_entry(cn, &clk_notifier_list, node) {
885                 if (cn->clk->core == core) {
886                         cnd.clk = cn->clk;
887                         ret = srcu_notifier_call_chain(&cn->notifier_head, msg,
888                                         &cnd);
889                 }
890         }
891
892         return ret;
893 }
894
895 /**
896  * __clk_recalc_accuracies
897  * @core: first clk in the subtree
898  *
899  * Walks the subtree of clks starting with clk and recalculates accuracies as
900  * it goes.  Note that if a clk does not implement the .recalc_accuracy
901  * callback then it is assumed that the clock will take on the accuracy of its
902  * parent.
903  */
904 static void __clk_recalc_accuracies(struct clk_core *core)
905 {
906         unsigned long parent_accuracy = 0;
907         struct clk_core *child;
908
909         lockdep_assert_held(&prepare_lock);
910
911         if (core->parent)
912                 parent_accuracy = core->parent->accuracy;
913
914         if (core->ops->recalc_accuracy)
915                 core->accuracy = core->ops->recalc_accuracy(core->hw,
916                                                           parent_accuracy);
917         else
918                 core->accuracy = parent_accuracy;
919
920         hlist_for_each_entry(child, &core->children, child_node)
921                 __clk_recalc_accuracies(child);
922 }
923
924 static long clk_core_get_accuracy(struct clk_core *core)
925 {
926         unsigned long accuracy;
927
928         clk_prepare_lock();
929         if (core && (core->flags & CLK_GET_ACCURACY_NOCACHE))
930                 __clk_recalc_accuracies(core);
931
932         accuracy = __clk_get_accuracy(core);
933         clk_prepare_unlock();
934
935         return accuracy;
936 }
937
938 /**
939  * clk_get_accuracy - return the accuracy of clk
940  * @clk: the clk whose accuracy is being returned
941  *
942  * Simply returns the cached accuracy of the clk, unless
943  * CLK_GET_ACCURACY_NOCACHE flag is set, which means a recalc_rate will be
944  * issued.
945  * If clk is NULL then returns 0.
946  */
947 long clk_get_accuracy(struct clk *clk)
948 {
949         if (!clk)
950                 return 0;
951
952         return clk_core_get_accuracy(clk->core);
953 }
954 EXPORT_SYMBOL_GPL(clk_get_accuracy);
955
956 static unsigned long clk_recalc(struct clk_core *core,
957                                 unsigned long parent_rate)
958 {
959         if (core->ops->recalc_rate)
960                 return core->ops->recalc_rate(core->hw, parent_rate);
961         return parent_rate;
962 }
963
964 /**
965  * __clk_recalc_rates
966  * @core: first clk in the subtree
967  * @msg: notification type (see include/linux/clk.h)
968  *
969  * Walks the subtree of clks starting with clk and recalculates rates as it
970  * goes.  Note that if a clk does not implement the .recalc_rate callback then
971  * it is assumed that the clock will take on the rate of its parent.
972  *
973  * clk_recalc_rates also propagates the POST_RATE_CHANGE notification,
974  * if necessary.
975  */
976 static void __clk_recalc_rates(struct clk_core *core, unsigned long msg)
977 {
978         unsigned long old_rate;
979         unsigned long parent_rate = 0;
980         struct clk_core *child;
981
982         lockdep_assert_held(&prepare_lock);
983
984         old_rate = core->rate;
985
986         if (core->parent)
987                 parent_rate = core->parent->rate;
988
989         core->rate = clk_recalc(core, parent_rate);
990
991         /*
992          * ignore NOTIFY_STOP and NOTIFY_BAD return values for POST_RATE_CHANGE
993          * & ABORT_RATE_CHANGE notifiers
994          */
995         if (core->notifier_count && msg)
996                 __clk_notify(core, msg, old_rate, core->rate);
997
998         hlist_for_each_entry(child, &core->children, child_node)
999                 __clk_recalc_rates(child, msg);
1000 }
1001
1002 static unsigned long clk_core_get_rate(struct clk_core *core)
1003 {
1004         unsigned long rate;
1005
1006         clk_prepare_lock();
1007
1008         if (core && (core->flags & CLK_GET_RATE_NOCACHE))
1009                 __clk_recalc_rates(core, 0);
1010
1011         rate = clk_core_get_rate_nolock(core);
1012         clk_prepare_unlock();
1013
1014         return rate;
1015 }
1016
1017 /**
1018  * clk_get_rate - return the rate of clk
1019  * @clk: the clk whose rate is being returned
1020  *
1021  * Simply returns the cached rate of the clk, unless CLK_GET_RATE_NOCACHE flag
1022  * is set, which means a recalc_rate will be issued.
1023  * If clk is NULL then returns 0.
1024  */
1025 unsigned long clk_get_rate(struct clk *clk)
1026 {
1027         if (!clk)
1028                 return 0;
1029
1030         return clk_core_get_rate(clk->core);
1031 }
1032 EXPORT_SYMBOL_GPL(clk_get_rate);
1033
1034 static int clk_fetch_parent_index(struct clk_core *core,
1035                                   struct clk_core *parent)
1036 {
1037         int i;
1038
1039         if (!core->parents) {
1040                 core->parents = kcalloc(core->num_parents,
1041                                         sizeof(struct clk *), GFP_KERNEL);
1042                 if (!core->parents)
1043                         return -ENOMEM;
1044         }
1045
1046         /*
1047          * find index of new parent clock using cached parent ptrs,
1048          * or if not yet cached, use string name comparison and cache
1049          * them now to avoid future calls to clk_core_lookup.
1050          */
1051         for (i = 0; i < core->num_parents; i++) {
1052                 if (core->parents[i] == parent)
1053                         return i;
1054
1055                 if (core->parents[i])
1056                         continue;
1057
1058                 if (!strcmp(core->parent_names[i], parent->name)) {
1059                         core->parents[i] = clk_core_lookup(parent->name);
1060                         return i;
1061                 }
1062         }
1063
1064         return -EINVAL;
1065 }
1066
1067 static void clk_reparent(struct clk_core *core, struct clk_core *new_parent)
1068 {
1069         hlist_del(&core->child_node);
1070
1071         if (new_parent) {
1072                 /* avoid duplicate POST_RATE_CHANGE notifications */
1073                 if (new_parent->new_child == core)
1074                         new_parent->new_child = NULL;
1075
1076                 hlist_add_head(&core->child_node, &new_parent->children);
1077         } else {
1078                 hlist_add_head(&core->child_node, &clk_orphan_list);
1079         }
1080
1081         core->parent = new_parent;
1082 }
1083
1084 static struct clk_core *__clk_set_parent_before(struct clk_core *core,
1085                                            struct clk_core *parent)
1086 {
1087         unsigned long flags;
1088         struct clk_core *old_parent = core->parent;
1089
1090         /*
1091          * Migrate prepare state between parents and prevent race with
1092          * clk_enable().
1093          *
1094          * If the clock is not prepared, then a race with
1095          * clk_enable/disable() is impossible since we already have the
1096          * prepare lock (future calls to clk_enable() need to be preceded by
1097          * a clk_prepare()).
1098          *
1099          * If the clock is prepared, migrate the prepared state to the new
1100          * parent and also protect against a race with clk_enable() by
1101          * forcing the clock and the new parent on.  This ensures that all
1102          * future calls to clk_enable() are practically NOPs with respect to
1103          * hardware and software states.
1104          *
1105          * See also: Comment for clk_set_parent() below.
1106          */
1107         if (core->prepare_count) {
1108                 clk_core_prepare(parent);
1109                 flags = clk_enable_lock();
1110                 clk_core_enable(parent);
1111                 clk_core_enable(core);
1112                 clk_enable_unlock(flags);
1113         }
1114
1115         /* update the clk tree topology */
1116         flags = clk_enable_lock();
1117         clk_reparent(core, parent);
1118         clk_enable_unlock(flags);
1119
1120         return old_parent;
1121 }
1122
1123 static void __clk_set_parent_after(struct clk_core *core,
1124                                    struct clk_core *parent,
1125                                    struct clk_core *old_parent)
1126 {
1127         unsigned long flags;
1128
1129         /*
1130          * Finish the migration of prepare state and undo the changes done
1131          * for preventing a race with clk_enable().
1132          */
1133         if (core->prepare_count) {
1134                 flags = clk_enable_lock();
1135                 clk_core_disable(core);
1136                 clk_core_disable(old_parent);
1137                 clk_enable_unlock(flags);
1138                 clk_core_unprepare(old_parent);
1139         }
1140 }
1141
1142 static int __clk_set_parent(struct clk_core *core, struct clk_core *parent,
1143                             u8 p_index)
1144 {
1145         unsigned long flags;
1146         int ret = 0;
1147         struct clk_core *old_parent;
1148
1149         old_parent = __clk_set_parent_before(core, parent);
1150
1151         trace_clk_set_parent(core, parent);
1152
1153         /* change clock input source */
1154         if (parent && core->ops->set_parent)
1155                 ret = core->ops->set_parent(core->hw, p_index);
1156
1157         trace_clk_set_parent_complete(core, parent);
1158
1159         if (ret) {
1160                 flags = clk_enable_lock();
1161                 clk_reparent(core, old_parent);
1162                 clk_enable_unlock(flags);
1163
1164                 if (core->prepare_count) {
1165                         flags = clk_enable_lock();
1166                         clk_core_disable(core);
1167                         clk_core_disable(parent);
1168                         clk_enable_unlock(flags);
1169                         clk_core_unprepare(parent);
1170                 }
1171                 return ret;
1172         }
1173
1174         __clk_set_parent_after(core, parent, old_parent);
1175
1176         return 0;
1177 }
1178
1179 /**
1180  * __clk_speculate_rates
1181  * @core: first clk in the subtree
1182  * @parent_rate: the "future" rate of clk's parent
1183  *
1184  * Walks the subtree of clks starting with clk, speculating rates as it
1185  * goes and firing off PRE_RATE_CHANGE notifications as necessary.
1186  *
1187  * Unlike clk_recalc_rates, clk_speculate_rates exists only for sending
1188  * pre-rate change notifications and returns early if no clks in the
1189  * subtree have subscribed to the notifications.  Note that if a clk does not
1190  * implement the .recalc_rate callback then it is assumed that the clock will
1191  * take on the rate of its parent.
1192  */
1193 static int __clk_speculate_rates(struct clk_core *core,
1194                                  unsigned long parent_rate)
1195 {
1196         struct clk_core *child;
1197         unsigned long new_rate;
1198         int ret = NOTIFY_DONE;
1199
1200         lockdep_assert_held(&prepare_lock);
1201
1202         new_rate = clk_recalc(core, parent_rate);
1203
1204         /* abort rate change if a driver returns NOTIFY_BAD or NOTIFY_STOP */
1205         if (core->notifier_count)
1206                 ret = __clk_notify(core, PRE_RATE_CHANGE, core->rate, new_rate);
1207
1208         if (ret & NOTIFY_STOP_MASK) {
1209                 pr_debug("%s: clk notifier callback for clock %s aborted with error %d\n",
1210                                 __func__, core->name, ret);
1211                 goto out;
1212         }
1213
1214         hlist_for_each_entry(child, &core->children, child_node) {
1215                 ret = __clk_speculate_rates(child, new_rate);
1216                 if (ret & NOTIFY_STOP_MASK)
1217                         break;
1218         }
1219
1220 out:
1221         return ret;
1222 }
1223
1224 static void clk_calc_subtree(struct clk_core *core, unsigned long new_rate,
1225                              struct clk_core *new_parent, u8 p_index)
1226 {
1227         struct clk_core *child;
1228
1229         core->new_rate = new_rate;
1230         core->new_parent = new_parent;
1231         core->new_parent_index = p_index;
1232         /* include clk in new parent's PRE_RATE_CHANGE notifications */
1233         core->new_child = NULL;
1234         if (new_parent && new_parent != core->parent)
1235                 new_parent->new_child = core;
1236
1237         hlist_for_each_entry(child, &core->children, child_node) {
1238                 child->new_rate = clk_recalc(child, new_rate);
1239                 clk_calc_subtree(child, child->new_rate, NULL, 0);
1240         }
1241 }
1242
1243 /*
1244  * calculate the new rates returning the topmost clock that has to be
1245  * changed.
1246  */
1247 static struct clk_core *clk_calc_new_rates(struct clk_core *core,
1248                                            unsigned long rate)
1249 {
1250         struct clk_core *top = core;
1251         struct clk_core *old_parent, *parent;
1252         struct clk_hw *parent_hw;
1253         unsigned long best_parent_rate = 0;
1254         unsigned long new_rate;
1255         unsigned long min_rate;
1256         unsigned long max_rate;
1257         int p_index = 0;
1258         long ret;
1259
1260         /* sanity */
1261         if (IS_ERR_OR_NULL(core))
1262                 return NULL;
1263
1264         /* save parent rate, if it exists */
1265         parent = old_parent = core->parent;
1266         if (parent)
1267                 best_parent_rate = parent->rate;
1268
1269         clk_core_get_boundaries(core, &min_rate, &max_rate);
1270
1271         /* find the closest rate and parent clk/rate */
1272         if (core->ops->determine_rate) {
1273                 parent_hw = parent ? parent->hw : NULL;
1274                 ret = core->ops->determine_rate(core->hw, rate,
1275                                                min_rate,
1276                                                max_rate,
1277                                                &best_parent_rate,
1278                                                &parent_hw);
1279                 if (ret < 0)
1280                         return NULL;
1281
1282                 new_rate = ret;
1283                 parent = parent_hw ? parent_hw->core : NULL;
1284         } else if (core->ops->round_rate) {
1285                 ret = core->ops->round_rate(core->hw, rate,
1286                                            &best_parent_rate);
1287                 if (ret < 0)
1288                         return NULL;
1289
1290                 new_rate = ret;
1291                 if (new_rate < min_rate || new_rate > max_rate)
1292                         return NULL;
1293         } else if (!parent || !(core->flags & CLK_SET_RATE_PARENT)) {
1294                 /* pass-through clock without adjustable parent */
1295                 core->new_rate = core->rate;
1296                 return NULL;
1297         } else {
1298                 /* pass-through clock with adjustable parent */
1299                 top = clk_calc_new_rates(parent, rate);
1300                 new_rate = parent->new_rate;
1301                 goto out;
1302         }
1303
1304         /* some clocks must be gated to change parent */
1305         if (parent != old_parent &&
1306             (core->flags & CLK_SET_PARENT_GATE) && core->prepare_count) {
1307                 pr_debug("%s: %s not gated but wants to reparent\n",
1308                          __func__, core->name);
1309                 return NULL;
1310         }
1311
1312         /* try finding the new parent index */
1313         if (parent && core->num_parents > 1) {
1314                 p_index = clk_fetch_parent_index(core, parent);
1315                 if (p_index < 0) {
1316                         pr_debug("%s: clk %s can not be parent of clk %s\n",
1317                                  __func__, parent->name, core->name);
1318                         return NULL;
1319                 }
1320         }
1321
1322         if ((core->flags & CLK_SET_RATE_PARENT) && parent &&
1323             best_parent_rate != parent->rate)
1324                 top = clk_calc_new_rates(parent, best_parent_rate);
1325
1326 out:
1327         clk_calc_subtree(core, new_rate, parent, p_index);
1328
1329         return top;
1330 }
1331
1332 /*
1333  * Notify about rate changes in a subtree. Always walk down the whole tree
1334  * so that in case of an error we can walk down the whole tree again and
1335  * abort the change.
1336  */
1337 static struct clk_core *clk_propagate_rate_change(struct clk_core *core,
1338                                                   unsigned long event)
1339 {
1340         struct clk_core *child, *tmp_clk, *fail_clk = NULL;
1341         int ret = NOTIFY_DONE;
1342
1343         if (core->rate == core->new_rate)
1344                 return NULL;
1345
1346         if (core->notifier_count) {
1347                 ret = __clk_notify(core, event, core->rate, core->new_rate);
1348                 if (ret & NOTIFY_STOP_MASK)
1349                         fail_clk = core;
1350         }
1351
1352         hlist_for_each_entry(child, &core->children, child_node) {
1353                 /* Skip children who will be reparented to another clock */
1354                 if (child->new_parent && child->new_parent != core)
1355                         continue;
1356                 tmp_clk = clk_propagate_rate_change(child, event);
1357                 if (tmp_clk)
1358                         fail_clk = tmp_clk;
1359         }
1360
1361         /* handle the new child who might not be in core->children yet */
1362         if (core->new_child) {
1363                 tmp_clk = clk_propagate_rate_change(core->new_child, event);
1364                 if (tmp_clk)
1365                         fail_clk = tmp_clk;
1366         }
1367
1368         return fail_clk;
1369 }
1370
1371 /*
1372  * walk down a subtree and set the new rates notifying the rate
1373  * change on the way
1374  */
1375 static void clk_change_rate(struct clk_core *core)
1376 {
1377         struct clk_core *child;
1378         struct hlist_node *tmp;
1379         unsigned long old_rate;
1380         unsigned long best_parent_rate = 0;
1381         bool skip_set_rate = false;
1382         struct clk_core *old_parent;
1383
1384         old_rate = core->rate;
1385
1386         if (core->new_parent)
1387                 best_parent_rate = core->new_parent->rate;
1388         else if (core->parent)
1389                 best_parent_rate = core->parent->rate;
1390
1391         if (core->new_parent && core->new_parent != core->parent) {
1392                 old_parent = __clk_set_parent_before(core, core->new_parent);
1393                 trace_clk_set_parent(core, core->new_parent);
1394
1395                 if (core->ops->set_rate_and_parent) {
1396                         skip_set_rate = true;
1397                         core->ops->set_rate_and_parent(core->hw, core->new_rate,
1398                                         best_parent_rate,
1399                                         core->new_parent_index);
1400                 } else if (core->ops->set_parent) {
1401                         core->ops->set_parent(core->hw, core->new_parent_index);
1402                 }
1403
1404                 trace_clk_set_parent_complete(core, core->new_parent);
1405                 __clk_set_parent_after(core, core->new_parent, old_parent);
1406         }
1407
1408         trace_clk_set_rate(core, core->new_rate);
1409
1410         if (!skip_set_rate && core->ops->set_rate)
1411                 core->ops->set_rate(core->hw, core->new_rate, best_parent_rate);
1412
1413         trace_clk_set_rate_complete(core, core->new_rate);
1414
1415         core->rate = clk_recalc(core, best_parent_rate);
1416
1417         if (core->notifier_count && old_rate != core->rate)
1418                 __clk_notify(core, POST_RATE_CHANGE, old_rate, core->rate);
1419
1420         /*
1421          * Use safe iteration, as change_rate can actually swap parents
1422          * for certain clock types.
1423          */
1424         hlist_for_each_entry_safe(child, tmp, &core->children, child_node) {
1425                 /* Skip children who will be reparented to another clock */
1426                 if (child->new_parent && child->new_parent != core)
1427                         continue;
1428                 clk_change_rate(child);
1429         }
1430
1431         /* handle the new child who might not be in core->children yet */
1432         if (core->new_child)
1433                 clk_change_rate(core->new_child);
1434 }
1435
1436 static int clk_core_set_rate_nolock(struct clk_core *core,
1437                                     unsigned long req_rate)
1438 {
1439         struct clk_core *top, *fail_clk;
1440         unsigned long rate = req_rate;
1441         int ret = 0;
1442
1443         if (!core)
1444                 return 0;
1445
1446         /* bail early if nothing to do */
1447         if (rate == clk_core_get_rate_nolock(core))
1448                 return 0;
1449
1450         if ((core->flags & CLK_SET_RATE_GATE) && core->prepare_count)
1451                 return -EBUSY;
1452
1453         /* calculate new rates and get the topmost changed clock */
1454         top = clk_calc_new_rates(core, rate);
1455         if (!top)
1456                 return -EINVAL;
1457
1458         /* notify that we are about to change rates */
1459         fail_clk = clk_propagate_rate_change(top, PRE_RATE_CHANGE);
1460         if (fail_clk) {
1461                 pr_debug("%s: failed to set %s rate\n", __func__,
1462                                 fail_clk->name);
1463                 clk_propagate_rate_change(top, ABORT_RATE_CHANGE);
1464                 return -EBUSY;
1465         }
1466
1467         /* change the rates */
1468         clk_change_rate(top);
1469
1470         core->req_rate = req_rate;
1471
1472         return ret;
1473 }
1474
1475 /**
1476  * clk_set_rate - specify a new rate for clk
1477  * @clk: the clk whose rate is being changed
1478  * @rate: the new rate for clk
1479  *
1480  * In the simplest case clk_set_rate will only adjust the rate of clk.
1481  *
1482  * Setting the CLK_SET_RATE_PARENT flag allows the rate change operation to
1483  * propagate up to clk's parent; whether or not this happens depends on the
1484  * outcome of clk's .round_rate implementation.  If *parent_rate is unchanged
1485  * after calling .round_rate then upstream parent propagation is ignored.  If
1486  * *parent_rate comes back with a new rate for clk's parent then we propagate
1487  * up to clk's parent and set its rate.  Upward propagation will continue
1488  * until either a clk does not support the CLK_SET_RATE_PARENT flag or
1489  * .round_rate stops requesting changes to clk's parent_rate.
1490  *
1491  * Rate changes are accomplished via tree traversal that also recalculates the
1492  * rates for the clocks and fires off POST_RATE_CHANGE notifiers.
1493  *
1494  * Returns 0 on success, -EERROR otherwise.
1495  */
1496 int clk_set_rate(struct clk *clk, unsigned long rate)
1497 {
1498         int ret;
1499
1500         if (!clk)
1501                 return 0;
1502
1503         /* prevent racing with updates to the clock topology */
1504         clk_prepare_lock();
1505
1506         ret = clk_core_set_rate_nolock(clk->core, rate);
1507
1508         clk_prepare_unlock();
1509
1510         return ret;
1511 }
1512 EXPORT_SYMBOL_GPL(clk_set_rate);
1513
1514 /**
1515  * clk_set_rate_range - set a rate range for a clock source
1516  * @clk: clock source
1517  * @min: desired minimum clock rate in Hz, inclusive
1518  * @max: desired maximum clock rate in Hz, inclusive
1519  *
1520  * Returns success (0) or negative errno.
1521  */
1522 int clk_set_rate_range(struct clk *clk, unsigned long min, unsigned long max)
1523 {
1524         int ret = 0;
1525
1526         if (!clk)
1527                 return 0;
1528
1529         if (min > max) {
1530                 pr_err("%s: clk %s dev %s con %s: invalid range [%lu, %lu]\n",
1531                        __func__, clk->core->name, clk->dev_id, clk->con_id,
1532                        min, max);
1533                 return -EINVAL;
1534         }
1535
1536         clk_prepare_lock();
1537
1538         if (min != clk->min_rate || max != clk->max_rate) {
1539                 clk->min_rate = min;
1540                 clk->max_rate = max;
1541                 ret = clk_core_set_rate_nolock(clk->core, clk->core->req_rate);
1542         }
1543
1544         clk_prepare_unlock();
1545
1546         return ret;
1547 }
1548 EXPORT_SYMBOL_GPL(clk_set_rate_range);
1549
1550 /**
1551  * clk_set_min_rate - set a minimum clock rate for a clock source
1552  * @clk: clock source
1553  * @rate: desired minimum clock rate in Hz, inclusive
1554  *
1555  * Returns success (0) or negative errno.
1556  */
1557 int clk_set_min_rate(struct clk *clk, unsigned long rate)
1558 {
1559         if (!clk)
1560                 return 0;
1561
1562         return clk_set_rate_range(clk, rate, clk->max_rate);
1563 }
1564 EXPORT_SYMBOL_GPL(clk_set_min_rate);
1565
1566 /**
1567  * clk_set_max_rate - set a maximum clock rate for a clock source
1568  * @clk: clock source
1569  * @rate: desired maximum clock rate in Hz, inclusive
1570  *
1571  * Returns success (0) or negative errno.
1572  */
1573 int clk_set_max_rate(struct clk *clk, unsigned long rate)
1574 {
1575         if (!clk)
1576                 return 0;
1577
1578         return clk_set_rate_range(clk, clk->min_rate, rate);
1579 }
1580 EXPORT_SYMBOL_GPL(clk_set_max_rate);
1581
1582 /**
1583  * clk_get_parent - return the parent of a clk
1584  * @clk: the clk whose parent gets returned
1585  *
1586  * Simply returns clk->parent.  Returns NULL if clk is NULL.
1587  */
1588 struct clk *clk_get_parent(struct clk *clk)
1589 {
1590         struct clk *parent;
1591
1592         clk_prepare_lock();
1593         parent = __clk_get_parent(clk);
1594         clk_prepare_unlock();
1595
1596         return parent;
1597 }
1598 EXPORT_SYMBOL_GPL(clk_get_parent);
1599
1600 /*
1601  * .get_parent is mandatory for clocks with multiple possible parents.  It is
1602  * optional for single-parent clocks.  Always call .get_parent if it is
1603  * available and WARN if it is missing for multi-parent clocks.
1604  *
1605  * For single-parent clocks without .get_parent, first check to see if the
1606  * .parents array exists, and if so use it to avoid an expensive tree
1607  * traversal.  If .parents does not exist then walk the tree.
1608  */
1609 static struct clk_core *__clk_init_parent(struct clk_core *core)
1610 {
1611         struct clk_core *ret = NULL;
1612         u8 index;
1613
1614         /* handle the trivial cases */
1615
1616         if (!core->num_parents)
1617                 goto out;
1618
1619         if (core->num_parents == 1) {
1620                 if (IS_ERR_OR_NULL(core->parent))
1621                         core->parent = clk_core_lookup(core->parent_names[0]);
1622                 ret = core->parent;
1623                 goto out;
1624         }
1625
1626         if (!core->ops->get_parent) {
1627                 WARN(!core->ops->get_parent,
1628                         "%s: multi-parent clocks must implement .get_parent\n",
1629                         __func__);
1630                 goto out;
1631         };
1632
1633         /*
1634          * Do our best to cache parent clocks in core->parents.  This prevents
1635          * unnecessary and expensive lookups.  We don't set core->parent here;
1636          * that is done by the calling function.
1637          */
1638
1639         index = core->ops->get_parent(core->hw);
1640
1641         if (!core->parents)
1642                 core->parents =
1643                         kcalloc(core->num_parents, sizeof(struct clk *),
1644                                         GFP_KERNEL);
1645
1646         ret = clk_core_get_parent_by_index(core, index);
1647
1648 out:
1649         return ret;
1650 }
1651
1652 static void clk_core_reparent(struct clk_core *core,
1653                                   struct clk_core *new_parent)
1654 {
1655         clk_reparent(core, new_parent);
1656         __clk_recalc_accuracies(core);
1657         __clk_recalc_rates(core, POST_RATE_CHANGE);
1658 }
1659
1660 /**
1661  * clk_has_parent - check if a clock is a possible parent for another
1662  * @clk: clock source
1663  * @parent: parent clock source
1664  *
1665  * This function can be used in drivers that need to check that a clock can be
1666  * the parent of another without actually changing the parent.
1667  *
1668  * Returns true if @parent is a possible parent for @clk, false otherwise.
1669  */
1670 bool clk_has_parent(struct clk *clk, struct clk *parent)
1671 {
1672         struct clk_core *core, *parent_core;
1673         unsigned int i;
1674
1675         /* NULL clocks should be nops, so return success if either is NULL. */
1676         if (!clk || !parent)
1677                 return true;
1678
1679         core = clk->core;
1680         parent_core = parent->core;
1681
1682         /* Optimize for the case where the parent is already the parent. */
1683         if (core->parent == parent_core)
1684                 return true;
1685
1686         for (i = 0; i < core->num_parents; i++)
1687                 if (strcmp(core->parent_names[i], parent_core->name) == 0)
1688                         return true;
1689
1690         return false;
1691 }
1692 EXPORT_SYMBOL_GPL(clk_has_parent);
1693
1694 static int clk_core_set_parent(struct clk_core *core, struct clk_core *parent)
1695 {
1696         int ret = 0;
1697         int p_index = 0;
1698         unsigned long p_rate = 0;
1699
1700         if (!core)
1701                 return 0;
1702
1703         /* prevent racing with updates to the clock topology */
1704         clk_prepare_lock();
1705
1706         if (core->parent == parent)
1707                 goto out;
1708
1709         /* verify ops for for multi-parent clks */
1710         if ((core->num_parents > 1) && (!core->ops->set_parent)) {
1711                 ret = -ENOSYS;
1712                 goto out;
1713         }
1714
1715         /* check that we are allowed to re-parent if the clock is in use */
1716         if ((core->flags & CLK_SET_PARENT_GATE) && core->prepare_count) {
1717                 ret = -EBUSY;
1718                 goto out;
1719         }
1720
1721         /* try finding the new parent index */
1722         if (parent) {
1723                 p_index = clk_fetch_parent_index(core, parent);
1724                 p_rate = parent->rate;
1725                 if (p_index < 0) {
1726                         pr_debug("%s: clk %s can not be parent of clk %s\n",
1727                                         __func__, parent->name, core->name);
1728                         ret = p_index;
1729                         goto out;
1730                 }
1731         }
1732
1733         /* propagate PRE_RATE_CHANGE notifications */
1734         ret = __clk_speculate_rates(core, p_rate);
1735
1736         /* abort if a driver objects */
1737         if (ret & NOTIFY_STOP_MASK)
1738                 goto out;
1739
1740         /* do the re-parent */
1741         ret = __clk_set_parent(core, parent, p_index);
1742
1743         /* propagate rate an accuracy recalculation accordingly */
1744         if (ret) {
1745                 __clk_recalc_rates(core, ABORT_RATE_CHANGE);
1746         } else {
1747                 __clk_recalc_rates(core, POST_RATE_CHANGE);
1748                 __clk_recalc_accuracies(core);
1749         }
1750
1751 out:
1752         clk_prepare_unlock();
1753
1754         return ret;
1755 }
1756
1757 /**
1758  * clk_set_parent - switch the parent of a mux clk
1759  * @clk: the mux clk whose input we are switching
1760  * @parent: the new input to clk
1761  *
1762  * Re-parent clk to use parent as its new input source.  If clk is in
1763  * prepared state, the clk will get enabled for the duration of this call. If
1764  * that's not acceptable for a specific clk (Eg: the consumer can't handle
1765  * that, the reparenting is glitchy in hardware, etc), use the
1766  * CLK_SET_PARENT_GATE flag to allow reparenting only when clk is unprepared.
1767  *
1768  * After successfully changing clk's parent clk_set_parent will update the
1769  * clk topology, sysfs topology and propagate rate recalculation via
1770  * __clk_recalc_rates.
1771  *
1772  * Returns 0 on success, -EERROR otherwise.
1773  */
1774 int clk_set_parent(struct clk *clk, struct clk *parent)
1775 {
1776         if (!clk)
1777                 return 0;
1778
1779         return clk_core_set_parent(clk->core, parent ? parent->core : NULL);
1780 }
1781 EXPORT_SYMBOL_GPL(clk_set_parent);
1782
1783 /**
1784  * clk_set_phase - adjust the phase shift of a clock signal
1785  * @clk: clock signal source
1786  * @degrees: number of degrees the signal is shifted
1787  *
1788  * Shifts the phase of a clock signal by the specified
1789  * degrees. Returns 0 on success, -EERROR otherwise.
1790  *
1791  * This function makes no distinction about the input or reference
1792  * signal that we adjust the clock signal phase against. For example
1793  * phase locked-loop clock signal generators we may shift phase with
1794  * respect to feedback clock signal input, but for other cases the
1795  * clock phase may be shifted with respect to some other, unspecified
1796  * signal.
1797  *
1798  * Additionally the concept of phase shift does not propagate through
1799  * the clock tree hierarchy, which sets it apart from clock rates and
1800  * clock accuracy. A parent clock phase attribute does not have an
1801  * impact on the phase attribute of a child clock.
1802  */
1803 int clk_set_phase(struct clk *clk, int degrees)
1804 {
1805         int ret = -EINVAL;
1806
1807         if (!clk)
1808                 return 0;
1809
1810         /* sanity check degrees */
1811         degrees %= 360;
1812         if (degrees < 0)
1813                 degrees += 360;
1814
1815         clk_prepare_lock();
1816
1817         trace_clk_set_phase(clk->core, degrees);
1818
1819         if (clk->core->ops->set_phase)
1820                 ret = clk->core->ops->set_phase(clk->core->hw, degrees);
1821
1822         trace_clk_set_phase_complete(clk->core, degrees);
1823
1824         if (!ret)
1825                 clk->core->phase = degrees;
1826
1827         clk_prepare_unlock();
1828
1829         return ret;
1830 }
1831 EXPORT_SYMBOL_GPL(clk_set_phase);
1832
1833 static int clk_core_get_phase(struct clk_core *core)
1834 {
1835         int ret;
1836
1837         clk_prepare_lock();
1838         ret = core->phase;
1839         clk_prepare_unlock();
1840
1841         return ret;
1842 }
1843
1844 /**
1845  * clk_get_phase - return the phase shift of a clock signal
1846  * @clk: clock signal source
1847  *
1848  * Returns the phase shift of a clock node in degrees, otherwise returns
1849  * -EERROR.
1850  */
1851 int clk_get_phase(struct clk *clk)
1852 {
1853         if (!clk)
1854                 return 0;
1855
1856         return clk_core_get_phase(clk->core);
1857 }
1858 EXPORT_SYMBOL_GPL(clk_get_phase);
1859
1860 /**
1861  * clk_is_match - check if two clk's point to the same hardware clock
1862  * @p: clk compared against q
1863  * @q: clk compared against p
1864  *
1865  * Returns true if the two struct clk pointers both point to the same hardware
1866  * clock node. Put differently, returns true if struct clk *p and struct clk *q
1867  * share the same struct clk_core object.
1868  *
1869  * Returns false otherwise. Note that two NULL clks are treated as matching.
1870  */
1871 bool clk_is_match(const struct clk *p, const struct clk *q)
1872 {
1873         /* trivial case: identical struct clk's or both NULL */
1874         if (p == q)
1875                 return true;
1876
1877         /* true if clk->core pointers match. Avoid derefing garbage */
1878         if (!IS_ERR_OR_NULL(p) && !IS_ERR_OR_NULL(q))
1879                 if (p->core == q->core)
1880                         return true;
1881
1882         return false;
1883 }
1884 EXPORT_SYMBOL_GPL(clk_is_match);
1885
1886 /***        debugfs support        ***/
1887
1888 #ifdef CONFIG_DEBUG_FS
1889 #include <linux/debugfs.h>
1890
1891 static struct dentry *rootdir;
1892 static int inited = 0;
1893 static DEFINE_MUTEX(clk_debug_lock);
1894 static HLIST_HEAD(clk_debug_list);
1895
1896 static struct hlist_head *all_lists[] = {
1897         &clk_root_list,
1898         &clk_orphan_list,
1899         NULL,
1900 };
1901
1902 static struct hlist_head *orphan_list[] = {
1903         &clk_orphan_list,
1904         NULL,
1905 };
1906
1907 static void clk_summary_show_one(struct seq_file *s, struct clk_core *c,
1908                                  int level)
1909 {
1910         if (!c)
1911                 return;
1912
1913         seq_printf(s, "%*s%-*s %11d %12d %11lu %10lu %-3d\n",
1914                    level * 3 + 1, "",
1915                    30 - level * 3, c->name,
1916                    c->enable_count, c->prepare_count, clk_core_get_rate(c),
1917                    clk_core_get_accuracy(c), clk_core_get_phase(c));
1918 }
1919
1920 static void clk_summary_show_subtree(struct seq_file *s, struct clk_core *c,
1921                                      int level)
1922 {
1923         struct clk_core *child;
1924
1925         if (!c)
1926                 return;
1927
1928         clk_summary_show_one(s, c, level);
1929
1930         hlist_for_each_entry(child, &c->children, child_node)
1931                 clk_summary_show_subtree(s, child, level + 1);
1932 }
1933
1934 static int clk_summary_show(struct seq_file *s, void *data)
1935 {
1936         struct clk_core *c;
1937         struct hlist_head **lists = (struct hlist_head **)s->private;
1938
1939         seq_puts(s, "   clock                         enable_cnt  prepare_cnt        rate   accuracy   phase\n");
1940         seq_puts(s, "----------------------------------------------------------------------------------------\n");
1941
1942         clk_prepare_lock();
1943
1944         for (; *lists; lists++)
1945                 hlist_for_each_entry(c, *lists, child_node)
1946                         clk_summary_show_subtree(s, c, 0);
1947
1948         clk_prepare_unlock();
1949
1950         return 0;
1951 }
1952
1953
1954 static int clk_summary_open(struct inode *inode, struct file *file)
1955 {
1956         return single_open(file, clk_summary_show, inode->i_private);
1957 }
1958
1959 static const struct file_operations clk_summary_fops = {
1960         .open           = clk_summary_open,
1961         .read           = seq_read,
1962         .llseek         = seq_lseek,
1963         .release        = single_release,
1964 };
1965
1966 static void clk_dump_one(struct seq_file *s, struct clk_core *c, int level)
1967 {
1968         if (!c)
1969                 return;
1970
1971         /* This should be JSON format, i.e. elements separated with a comma */
1972         seq_printf(s, "\"%s\": { ", c->name);
1973         seq_printf(s, "\"enable_count\": %d,", c->enable_count);
1974         seq_printf(s, "\"prepare_count\": %d,", c->prepare_count);
1975         seq_printf(s, "\"rate\": %lu,", clk_core_get_rate(c));
1976         seq_printf(s, "\"accuracy\": %lu,", clk_core_get_accuracy(c));
1977         seq_printf(s, "\"phase\": %d", clk_core_get_phase(c));
1978 }
1979
1980 static void clk_dump_subtree(struct seq_file *s, struct clk_core *c, int level)
1981 {
1982         struct clk_core *child;
1983
1984         if (!c)
1985                 return;
1986
1987         clk_dump_one(s, c, level);
1988
1989         hlist_for_each_entry(child, &c->children, child_node) {
1990                 seq_printf(s, ",");
1991                 clk_dump_subtree(s, child, level + 1);
1992         }
1993
1994         seq_printf(s, "}");
1995 }
1996
1997 static int clk_dump(struct seq_file *s, void *data)
1998 {
1999         struct clk_core *c;
2000         bool first_node = true;
2001         struct hlist_head **lists = (struct hlist_head **)s->private;
2002
2003         seq_printf(s, "{");
2004
2005         clk_prepare_lock();
2006
2007         for (; *lists; lists++) {
2008                 hlist_for_each_entry(c, *lists, child_node) {
2009                         if (!first_node)
2010                                 seq_puts(s, ",");
2011                         first_node = false;
2012                         clk_dump_subtree(s, c, 0);
2013                 }
2014         }
2015
2016         clk_prepare_unlock();
2017
2018         seq_puts(s, "}\n");
2019         return 0;
2020 }
2021
2022
2023 static int clk_dump_open(struct inode *inode, struct file *file)
2024 {
2025         return single_open(file, clk_dump, inode->i_private);
2026 }
2027
2028 static const struct file_operations clk_dump_fops = {
2029         .open           = clk_dump_open,
2030         .read           = seq_read,
2031         .llseek         = seq_lseek,
2032         .release        = single_release,
2033 };
2034
2035 static int clk_debug_create_one(struct clk_core *core, struct dentry *pdentry)
2036 {
2037         struct dentry *d;
2038         int ret = -ENOMEM;
2039
2040         if (!core || !pdentry) {
2041                 ret = -EINVAL;
2042                 goto out;
2043         }
2044
2045         d = debugfs_create_dir(core->name, pdentry);
2046         if (!d)
2047                 goto out;
2048
2049         core->dentry = d;
2050
2051         d = debugfs_create_u32("clk_rate", S_IRUGO, core->dentry,
2052                         (u32 *)&core->rate);
2053         if (!d)
2054                 goto err_out;
2055
2056         d = debugfs_create_u32("clk_accuracy", S_IRUGO, core->dentry,
2057                         (u32 *)&core->accuracy);
2058         if (!d)
2059                 goto err_out;
2060
2061         d = debugfs_create_u32("clk_phase", S_IRUGO, core->dentry,
2062                         (u32 *)&core->phase);
2063         if (!d)
2064                 goto err_out;
2065
2066         d = debugfs_create_x32("clk_flags", S_IRUGO, core->dentry,
2067                         (u32 *)&core->flags);
2068         if (!d)
2069                 goto err_out;
2070
2071         d = debugfs_create_u32("clk_prepare_count", S_IRUGO, core->dentry,
2072                         (u32 *)&core->prepare_count);
2073         if (!d)
2074                 goto err_out;
2075
2076         d = debugfs_create_u32("clk_enable_count", S_IRUGO, core->dentry,
2077                         (u32 *)&core->enable_count);
2078         if (!d)
2079                 goto err_out;
2080
2081         d = debugfs_create_u32("clk_notifier_count", S_IRUGO, core->dentry,
2082                         (u32 *)&core->notifier_count);
2083         if (!d)
2084                 goto err_out;
2085
2086         if (core->ops->debug_init) {
2087                 ret = core->ops->debug_init(core->hw, core->dentry);
2088                 if (ret)
2089                         goto err_out;
2090         }
2091
2092         ret = 0;
2093         goto out;
2094
2095 err_out:
2096         debugfs_remove_recursive(core->dentry);
2097         core->dentry = NULL;
2098 out:
2099         return ret;
2100 }
2101
2102 /**
2103  * clk_debug_register - add a clk node to the debugfs clk directory
2104  * @core: the clk being added to the debugfs clk directory
2105  *
2106  * Dynamically adds a clk to the debugfs clk directory if debugfs has been
2107  * initialized.  Otherwise it bails out early since the debugfs clk directory
2108  * will be created lazily by clk_debug_init as part of a late_initcall.
2109  */
2110 static int clk_debug_register(struct clk_core *core)
2111 {
2112         int ret = 0;
2113
2114         mutex_lock(&clk_debug_lock);
2115         hlist_add_head(&core->debug_node, &clk_debug_list);
2116
2117         if (!inited)
2118                 goto unlock;
2119
2120         ret = clk_debug_create_one(core, rootdir);
2121 unlock:
2122         mutex_unlock(&clk_debug_lock);
2123
2124         return ret;
2125 }
2126
2127  /**
2128  * clk_debug_unregister - remove a clk node from the debugfs clk directory
2129  * @core: the clk being removed from the debugfs clk directory
2130  *
2131  * Dynamically removes a clk and all its child nodes from the
2132  * debugfs clk directory if clk->dentry points to debugfs created by
2133  * clk_debug_register in __clk_init.
2134  */
2135 static void clk_debug_unregister(struct clk_core *core)
2136 {
2137         mutex_lock(&clk_debug_lock);
2138         hlist_del_init(&core->debug_node);
2139         debugfs_remove_recursive(core->dentry);
2140         core->dentry = NULL;
2141         mutex_unlock(&clk_debug_lock);
2142 }
2143
2144 struct dentry *clk_debugfs_add_file(struct clk_hw *hw, char *name, umode_t mode,
2145                                 void *data, const struct file_operations *fops)
2146 {
2147         struct dentry *d = NULL;
2148
2149         if (hw->core->dentry)
2150                 d = debugfs_create_file(name, mode, hw->core->dentry, data,
2151                                         fops);
2152
2153         return d;
2154 }
2155 EXPORT_SYMBOL_GPL(clk_debugfs_add_file);
2156
2157 /**
2158  * clk_debug_init - lazily populate the debugfs clk directory
2159  *
2160  * clks are often initialized very early during boot before memory can be
2161  * dynamically allocated and well before debugfs is setup. This function
2162  * populates the debugfs clk directory once at boot-time when we know that
2163  * debugfs is setup. It should only be called once at boot-time, all other clks
2164  * added dynamically will be done so with clk_debug_register.
2165  */
2166 static int __init clk_debug_init(void)
2167 {
2168         struct clk_core *core;
2169         struct dentry *d;
2170
2171         rootdir = debugfs_create_dir("clk", NULL);
2172
2173         if (!rootdir)
2174                 return -ENOMEM;
2175
2176         d = debugfs_create_file("clk_summary", S_IRUGO, rootdir, &all_lists,
2177                                 &clk_summary_fops);
2178         if (!d)
2179                 return -ENOMEM;
2180
2181         d = debugfs_create_file("clk_dump", S_IRUGO, rootdir, &all_lists,
2182                                 &clk_dump_fops);
2183         if (!d)
2184                 return -ENOMEM;
2185
2186         d = debugfs_create_file("clk_orphan_summary", S_IRUGO, rootdir,
2187                                 &orphan_list, &clk_summary_fops);
2188         if (!d)
2189                 return -ENOMEM;
2190
2191         d = debugfs_create_file("clk_orphan_dump", S_IRUGO, rootdir,
2192                                 &orphan_list, &clk_dump_fops);
2193         if (!d)
2194                 return -ENOMEM;
2195
2196         mutex_lock(&clk_debug_lock);
2197         hlist_for_each_entry(core, &clk_debug_list, debug_node)
2198                 clk_debug_create_one(core, rootdir);
2199
2200         inited = 1;
2201         mutex_unlock(&clk_debug_lock);
2202
2203         return 0;
2204 }
2205 late_initcall(clk_debug_init);
2206 #else
2207 static inline int clk_debug_register(struct clk_core *core) { return 0; }
2208 static inline void clk_debug_reparent(struct clk_core *core,
2209                                       struct clk_core *new_parent)
2210 {
2211 }
2212 static inline void clk_debug_unregister(struct clk_core *core)
2213 {
2214 }
2215 #endif
2216
2217 /**
2218  * __clk_init - initialize the data structures in a struct clk
2219  * @dev:        device initializing this clk, placeholder for now
2220  * @clk:        clk being initialized
2221  *
2222  * Initializes the lists in struct clk_core, queries the hardware for the
2223  * parent and rate and sets them both.
2224  */
2225 static int __clk_init(struct device *dev, struct clk *clk_user)
2226 {
2227         int i, ret = 0;
2228         struct clk_core *orphan;
2229         struct hlist_node *tmp2;
2230         struct clk_core *core;
2231         unsigned long rate;
2232
2233         if (!clk_user)
2234                 return -EINVAL;
2235
2236         core = clk_user->core;
2237
2238         clk_prepare_lock();
2239
2240         /* check to see if a clock with this name is already registered */
2241         if (clk_core_lookup(core->name)) {
2242                 pr_debug("%s: clk %s already initialized\n",
2243                                 __func__, core->name);
2244                 ret = -EEXIST;
2245                 goto out;
2246         }
2247
2248         /* check that clk_ops are sane.  See Documentation/clk.txt */
2249         if (core->ops->set_rate &&
2250             !((core->ops->round_rate || core->ops->determine_rate) &&
2251               core->ops->recalc_rate)) {
2252                 pr_warning("%s: %s must implement .round_rate or .determine_rate in addition to .recalc_rate\n",
2253                                 __func__, core->name);
2254                 ret = -EINVAL;
2255                 goto out;
2256         }
2257
2258         if (core->ops->set_parent && !core->ops->get_parent) {
2259                 pr_warning("%s: %s must implement .get_parent & .set_parent\n",
2260                                 __func__, core->name);
2261                 ret = -EINVAL;
2262                 goto out;
2263         }
2264
2265         if (core->ops->set_rate_and_parent &&
2266                         !(core->ops->set_parent && core->ops->set_rate)) {
2267                 pr_warn("%s: %s must implement .set_parent & .set_rate\n",
2268                                 __func__, core->name);
2269                 ret = -EINVAL;
2270                 goto out;
2271         }
2272
2273         /* throw a WARN if any entries in parent_names are NULL */
2274         for (i = 0; i < core->num_parents; i++)
2275                 WARN(!core->parent_names[i],
2276                                 "%s: invalid NULL in %s's .parent_names\n",
2277                                 __func__, core->name);
2278
2279         /*
2280          * Allocate an array of struct clk *'s to avoid unnecessary string
2281          * look-ups of clk's possible parents.  This can fail for clocks passed
2282          * in to clk_init during early boot; thus any access to core->parents[]
2283          * must always check for a NULL pointer and try to populate it if
2284          * necessary.
2285          *
2286          * If core->parents is not NULL we skip this entire block.  This allows
2287          * for clock drivers to statically initialize core->parents.
2288          */
2289         if (core->num_parents > 1 && !core->parents) {
2290                 core->parents = kcalloc(core->num_parents, sizeof(struct clk *),
2291                                         GFP_KERNEL);
2292                 /*
2293                  * clk_core_lookup returns NULL for parents that have not been
2294                  * clk_init'd; thus any access to clk->parents[] must check
2295                  * for a NULL pointer.  We can always perform lazy lookups for
2296                  * missing parents later on.
2297                  */
2298                 if (core->parents)
2299                         for (i = 0; i < core->num_parents; i++)
2300                                 core->parents[i] =
2301                                         clk_core_lookup(core->parent_names[i]);
2302         }
2303
2304         core->parent = __clk_init_parent(core);
2305
2306         /*
2307          * Populate core->parent if parent has already been __clk_init'd.  If
2308          * parent has not yet been __clk_init'd then place clk in the orphan
2309          * list.  If clk has set the CLK_IS_ROOT flag then place it in the root
2310          * clk list.
2311          *
2312          * Every time a new clk is clk_init'd then we walk the list of orphan
2313          * clocks and re-parent any that are children of the clock currently
2314          * being clk_init'd.
2315          */
2316         if (core->parent)
2317                 hlist_add_head(&core->child_node,
2318                                 &core->parent->children);
2319         else if (core->flags & CLK_IS_ROOT)
2320                 hlist_add_head(&core->child_node, &clk_root_list);
2321         else
2322                 hlist_add_head(&core->child_node, &clk_orphan_list);
2323
2324         /*
2325          * Set clk's accuracy.  The preferred method is to use
2326          * .recalc_accuracy. For simple clocks and lazy developers the default
2327          * fallback is to use the parent's accuracy.  If a clock doesn't have a
2328          * parent (or is orphaned) then accuracy is set to zero (perfect
2329          * clock).
2330          */
2331         if (core->ops->recalc_accuracy)
2332                 core->accuracy = core->ops->recalc_accuracy(core->hw,
2333                                         __clk_get_accuracy(core->parent));
2334         else if (core->parent)
2335                 core->accuracy = core->parent->accuracy;
2336         else
2337                 core->accuracy = 0;
2338
2339         /*
2340          * Set clk's phase.
2341          * Since a phase is by definition relative to its parent, just
2342          * query the current clock phase, or just assume it's in phase.
2343          */
2344         if (core->ops->get_phase)
2345                 core->phase = core->ops->get_phase(core->hw);
2346         else
2347                 core->phase = 0;
2348
2349         /*
2350          * Set clk's rate.  The preferred method is to use .recalc_rate.  For
2351          * simple clocks and lazy developers the default fallback is to use the
2352          * parent's rate.  If a clock doesn't have a parent (or is orphaned)
2353          * then rate is set to zero.
2354          */
2355         if (core->ops->recalc_rate)
2356                 rate = core->ops->recalc_rate(core->hw,
2357                                 clk_core_get_rate_nolock(core->parent));
2358         else if (core->parent)
2359                 rate = core->parent->rate;
2360         else
2361                 rate = 0;
2362         core->rate = core->req_rate = rate;
2363
2364         /*
2365          * walk the list of orphan clocks and reparent any that are children of
2366          * this clock
2367          */
2368         hlist_for_each_entry_safe(orphan, tmp2, &clk_orphan_list, child_node) {
2369                 if (orphan->num_parents && orphan->ops->get_parent) {
2370                         i = orphan->ops->get_parent(orphan->hw);
2371                         if (!strcmp(core->name, orphan->parent_names[i]))
2372                                 clk_core_reparent(orphan, core);
2373                         continue;
2374                 }
2375
2376                 for (i = 0; i < orphan->num_parents; i++)
2377                         if (!strcmp(core->name, orphan->parent_names[i])) {
2378                                 clk_core_reparent(orphan, core);
2379                                 break;
2380                         }
2381          }
2382
2383         /*
2384          * optional platform-specific magic
2385          *
2386          * The .init callback is not used by any of the basic clock types, but
2387          * exists for weird hardware that must perform initialization magic.
2388          * Please consider other ways of solving initialization problems before
2389          * using this callback, as its use is discouraged.
2390          */
2391         if (core->ops->init)
2392                 core->ops->init(core->hw);
2393
2394         kref_init(&core->ref);
2395 out:
2396         clk_prepare_unlock();
2397
2398         if (!ret)
2399                 clk_debug_register(core);
2400
2401         return ret;
2402 }
2403
2404 struct clk *__clk_create_clk(struct clk_hw *hw, const char *dev_id,
2405                              const char *con_id)
2406 {
2407         struct clk *clk;
2408
2409         /* This is to allow this function to be chained to others */
2410         if (!hw || IS_ERR(hw))
2411                 return (struct clk *) hw;
2412
2413         clk = kzalloc(sizeof(*clk), GFP_KERNEL);
2414         if (!clk)
2415                 return ERR_PTR(-ENOMEM);
2416
2417         clk->core = hw->core;
2418         clk->dev_id = dev_id;
2419         clk->con_id = con_id;
2420         clk->max_rate = ULONG_MAX;
2421
2422         clk_prepare_lock();
2423         hlist_add_head(&clk->clks_node, &hw->core->clks);
2424         clk_prepare_unlock();
2425
2426         return clk;
2427 }
2428
2429 void __clk_free_clk(struct clk *clk)
2430 {
2431         clk_prepare_lock();
2432         hlist_del(&clk->clks_node);
2433         clk_prepare_unlock();
2434
2435         kfree(clk);
2436 }
2437
2438 /**
2439  * clk_register - allocate a new clock, register it and return an opaque cookie
2440  * @dev: device that is registering this clock
2441  * @hw: link to hardware-specific clock data
2442  *
2443  * clk_register is the primary interface for populating the clock tree with new
2444  * clock nodes.  It returns a pointer to the newly allocated struct clk which
2445  * cannot be dereferenced by driver code but may be used in conjunction with the
2446  * rest of the clock API.  In the event of an error clk_register will return an
2447  * error code; drivers must test for an error code after calling clk_register.
2448  */
2449 struct clk *clk_register(struct device *dev, struct clk_hw *hw)
2450 {
2451         int i, ret;
2452         struct clk_core *core;
2453
2454         core = kzalloc(sizeof(*core), GFP_KERNEL);
2455         if (!core) {
2456                 ret = -ENOMEM;
2457                 goto fail_out;
2458         }
2459
2460         core->name = kstrdup_const(hw->init->name, GFP_KERNEL);
2461         if (!core->name) {
2462                 ret = -ENOMEM;
2463                 goto fail_name;
2464         }
2465         core->ops = hw->init->ops;
2466         if (dev && dev->driver)
2467                 core->owner = dev->driver->owner;
2468         core->hw = hw;
2469         core->flags = hw->init->flags;
2470         core->num_parents = hw->init->num_parents;
2471         hw->core = core;
2472
2473         /* allocate local copy in case parent_names is __initdata */
2474         core->parent_names = kcalloc(core->num_parents, sizeof(char *),
2475                                         GFP_KERNEL);
2476
2477         if (!core->parent_names) {
2478                 ret = -ENOMEM;
2479                 goto fail_parent_names;
2480         }
2481
2482
2483         /* copy each string name in case parent_names is __initdata */
2484         for (i = 0; i < core->num_parents; i++) {
2485                 core->parent_names[i] = kstrdup_const(hw->init->parent_names[i],
2486                                                 GFP_KERNEL);
2487                 if (!core->parent_names[i]) {
2488                         ret = -ENOMEM;
2489                         goto fail_parent_names_copy;
2490                 }
2491         }
2492
2493         INIT_HLIST_HEAD(&core->clks);
2494
2495         hw->clk = __clk_create_clk(hw, NULL, NULL);
2496         if (IS_ERR(hw->clk)) {
2497                 ret = PTR_ERR(hw->clk);
2498                 goto fail_parent_names_copy;
2499         }
2500
2501         ret = __clk_init(dev, hw->clk);
2502         if (!ret)
2503                 return hw->clk;
2504
2505         __clk_free_clk(hw->clk);
2506         hw->clk = NULL;
2507
2508 fail_parent_names_copy:
2509         while (--i >= 0)
2510                 kfree_const(core->parent_names[i]);
2511         kfree(core->parent_names);
2512 fail_parent_names:
2513         kfree_const(core->name);
2514 fail_name:
2515         kfree(core);
2516 fail_out:
2517         return ERR_PTR(ret);
2518 }
2519 EXPORT_SYMBOL_GPL(clk_register);
2520
2521 /* Free memory allocated for a clock. */
2522 static void __clk_release(struct kref *ref)
2523 {
2524         struct clk_core *core = container_of(ref, struct clk_core, ref);
2525         int i = core->num_parents;
2526
2527         lockdep_assert_held(&prepare_lock);
2528
2529         kfree(core->parents);
2530         while (--i >= 0)
2531                 kfree_const(core->parent_names[i]);
2532
2533         kfree(core->parent_names);
2534         kfree_const(core->name);
2535         kfree(core);
2536 }
2537
2538 /*
2539  * Empty clk_ops for unregistered clocks. These are used temporarily
2540  * after clk_unregister() was called on a clock and until last clock
2541  * consumer calls clk_put() and the struct clk object is freed.
2542  */
2543 static int clk_nodrv_prepare_enable(struct clk_hw *hw)
2544 {
2545         return -ENXIO;
2546 }
2547
2548 static void clk_nodrv_disable_unprepare(struct clk_hw *hw)
2549 {
2550         WARN_ON_ONCE(1);
2551 }
2552
2553 static int clk_nodrv_set_rate(struct clk_hw *hw, unsigned long rate,
2554                                         unsigned long parent_rate)
2555 {
2556         return -ENXIO;
2557 }
2558
2559 static int clk_nodrv_set_parent(struct clk_hw *hw, u8 index)
2560 {
2561         return -ENXIO;
2562 }
2563
2564 static const struct clk_ops clk_nodrv_ops = {
2565         .enable         = clk_nodrv_prepare_enable,
2566         .disable        = clk_nodrv_disable_unprepare,
2567         .prepare        = clk_nodrv_prepare_enable,
2568         .unprepare      = clk_nodrv_disable_unprepare,
2569         .set_rate       = clk_nodrv_set_rate,
2570         .set_parent     = clk_nodrv_set_parent,
2571 };
2572
2573 /**
2574  * clk_unregister - unregister a currently registered clock
2575  * @clk: clock to unregister
2576  */
2577 void clk_unregister(struct clk *clk)
2578 {
2579         unsigned long flags;
2580
2581         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
2582                 return;
2583
2584         clk_debug_unregister(clk->core);
2585
2586         clk_prepare_lock();
2587
2588         if (clk->core->ops == &clk_nodrv_ops) {
2589                 pr_err("%s: unregistered clock: %s\n", __func__,
2590                        clk->core->name);
2591                 return;
2592         }
2593         /*
2594          * Assign empty clock ops for consumers that might still hold
2595          * a reference to this clock.
2596          */
2597         flags = clk_enable_lock();
2598         clk->core->ops = &clk_nodrv_ops;
2599         clk_enable_unlock(flags);
2600
2601         if (!hlist_empty(&clk->core->children)) {
2602                 struct clk_core *child;
2603                 struct hlist_node *t;
2604
2605                 /* Reparent all children to the orphan list. */
2606                 hlist_for_each_entry_safe(child, t, &clk->core->children,
2607                                           child_node)
2608                         clk_core_set_parent(child, NULL);
2609         }
2610
2611         hlist_del_init(&clk->core->child_node);
2612
2613         if (clk->core->prepare_count)
2614                 pr_warn("%s: unregistering prepared clock: %s\n",
2615                                         __func__, clk->core->name);
2616         kref_put(&clk->core->ref, __clk_release);
2617
2618         clk_prepare_unlock();
2619 }
2620 EXPORT_SYMBOL_GPL(clk_unregister);
2621
2622 static void devm_clk_release(struct device *dev, void *res)
2623 {
2624         clk_unregister(*(struct clk **)res);
2625 }
2626
2627 /**
2628  * devm_clk_register - resource managed clk_register()
2629  * @dev: device that is registering this clock
2630  * @hw: link to hardware-specific clock data
2631  *
2632  * Managed clk_register(). Clocks returned from this function are
2633  * automatically clk_unregister()ed on driver detach. See clk_register() for
2634  * more information.
2635  */
2636 struct clk *devm_clk_register(struct device *dev, struct clk_hw *hw)
2637 {
2638         struct clk *clk;
2639         struct clk **clkp;
2640
2641         clkp = devres_alloc(devm_clk_release, sizeof(*clkp), GFP_KERNEL);
2642         if (!clkp)
2643                 return ERR_PTR(-ENOMEM);
2644
2645         clk = clk_register(dev, hw);
2646         if (!IS_ERR(clk)) {
2647                 *clkp = clk;
2648                 devres_add(dev, clkp);
2649         } else {
2650                 devres_free(clkp);
2651         }
2652
2653         return clk;
2654 }
2655 EXPORT_SYMBOL_GPL(devm_clk_register);
2656
2657 static int devm_clk_match(struct device *dev, void *res, void *data)
2658 {
2659         struct clk *c = res;
2660         if (WARN_ON(!c))
2661                 return 0;
2662         return c == data;
2663 }
2664
2665 /**
2666  * devm_clk_unregister - resource managed clk_unregister()
2667  * @clk: clock to unregister
2668  *
2669  * Deallocate a clock allocated with devm_clk_register(). Normally
2670  * this function will not need to be called and the resource management
2671  * code will ensure that the resource is freed.
2672  */
2673 void devm_clk_unregister(struct device *dev, struct clk *clk)
2674 {
2675         WARN_ON(devres_release(dev, devm_clk_release, devm_clk_match, clk));
2676 }
2677 EXPORT_SYMBOL_GPL(devm_clk_unregister);
2678
2679 /*
2680  * clkdev helpers
2681  */
2682 int __clk_get(struct clk *clk)
2683 {
2684         struct clk_core *core = !clk ? NULL : clk->core;
2685
2686         if (core) {
2687                 if (!try_module_get(core->owner))
2688                         return 0;
2689
2690                 kref_get(&core->ref);
2691         }
2692         return 1;
2693 }
2694
2695 void __clk_put(struct clk *clk)
2696 {
2697         struct module *owner;
2698
2699         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
2700                 return;
2701
2702         clk_prepare_lock();
2703
2704         hlist_del(&clk->clks_node);
2705         if (clk->min_rate > clk->core->req_rate ||
2706             clk->max_rate < clk->core->req_rate)
2707                 clk_core_set_rate_nolock(clk->core, clk->core->req_rate);
2708
2709         owner = clk->core->owner;
2710         kref_put(&clk->core->ref, __clk_release);
2711
2712         clk_prepare_unlock();
2713
2714         module_put(owner);
2715
2716         kfree(clk);
2717 }
2718
2719 /***        clk rate change notifiers        ***/
2720
2721 /**
2722  * clk_notifier_register - add a clk rate change notifier
2723  * @clk: struct clk * to watch
2724  * @nb: struct notifier_block * with callback info
2725  *
2726  * Request notification when clk's rate changes.  This uses an SRCU
2727  * notifier because we want it to block and notifier unregistrations are
2728  * uncommon.  The callbacks associated with the notifier must not
2729  * re-enter into the clk framework by calling any top-level clk APIs;
2730  * this will cause a nested prepare_lock mutex.
2731  *
2732  * In all notification cases cases (pre, post and abort rate change) the
2733  * original clock rate is passed to the callback via struct
2734  * clk_notifier_data.old_rate and the new frequency is passed via struct
2735  * clk_notifier_data.new_rate.
2736  *
2737  * clk_notifier_register() must be called from non-atomic context.
2738  * Returns -EINVAL if called with null arguments, -ENOMEM upon
2739  * allocation failure; otherwise, passes along the return value of
2740  * srcu_notifier_chain_register().
2741  */
2742 int clk_notifier_register(struct clk *clk, struct notifier_block *nb)
2743 {
2744         struct clk_notifier *cn;
2745         int ret = -ENOMEM;
2746
2747         if (!clk || !nb)
2748                 return -EINVAL;
2749
2750         clk_prepare_lock();
2751
2752         /* search the list of notifiers for this clk */
2753         list_for_each_entry(cn, &clk_notifier_list, node)
2754                 if (cn->clk == clk)
2755                         break;
2756
2757         /* if clk wasn't in the notifier list, allocate new clk_notifier */
2758         if (cn->clk != clk) {
2759                 cn = kzalloc(sizeof(struct clk_notifier), GFP_KERNEL);
2760                 if (!cn)
2761                         goto out;
2762
2763                 cn->clk = clk;
2764                 srcu_init_notifier_head(&cn->notifier_head);
2765
2766                 list_add(&cn->node, &clk_notifier_list);
2767         }
2768
2769         ret = srcu_notifier_chain_register(&cn->notifier_head, nb);
2770
2771         clk->core->notifier_count++;
2772
2773 out:
2774         clk_prepare_unlock();
2775
2776         return ret;
2777 }
2778 EXPORT_SYMBOL_GPL(clk_notifier_register);
2779
2780 /**
2781  * clk_notifier_unregister - remove a clk rate change notifier
2782  * @clk: struct clk *
2783  * @nb: struct notifier_block * with callback info
2784  *
2785  * Request no further notification for changes to 'clk' and frees memory
2786  * allocated in clk_notifier_register.
2787  *
2788  * Returns -EINVAL if called with null arguments; otherwise, passes
2789  * along the return value of srcu_notifier_chain_unregister().
2790  */
2791 int clk_notifier_unregister(struct clk *clk, struct notifier_block *nb)
2792 {
2793         struct clk_notifier *cn = NULL;
2794         int ret = -EINVAL;
2795
2796         if (!clk || !nb)
2797                 return -EINVAL;
2798
2799         clk_prepare_lock();
2800
2801         list_for_each_entry(cn, &clk_notifier_list, node)
2802                 if (cn->clk == clk)
2803                         break;
2804
2805         if (cn->clk == clk) {
2806                 ret = srcu_notifier_chain_unregister(&cn->notifier_head, nb);
2807
2808                 clk->core->notifier_count--;
2809
2810                 /* XXX the notifier code should handle this better */
2811                 if (!cn->notifier_head.head) {
2812                         srcu_cleanup_notifier_head(&cn->notifier_head);
2813                         list_del(&cn->node);
2814                         kfree(cn);
2815                 }
2816
2817         } else {
2818                 ret = -ENOENT;
2819         }
2820
2821         clk_prepare_unlock();
2822
2823         return ret;
2824 }
2825 EXPORT_SYMBOL_GPL(clk_notifier_unregister);
2826
2827 #ifdef CONFIG_OF
2828 /**
2829  * struct of_clk_provider - Clock provider registration structure
2830  * @link: Entry in global list of clock providers
2831  * @node: Pointer to device tree node of clock provider
2832  * @get: Get clock callback.  Returns NULL or a struct clk for the
2833  *       given clock specifier
2834  * @data: context pointer to be passed into @get callback
2835  */
2836 struct of_clk_provider {
2837         struct list_head link;
2838
2839         struct device_node *node;
2840         struct clk *(*get)(struct of_phandle_args *clkspec, void *data);
2841         void *data;
2842 };
2843
2844 static const struct of_device_id __clk_of_table_sentinel
2845         __used __section(__clk_of_table_end);
2846
2847 static LIST_HEAD(of_clk_providers);
2848 static DEFINE_MUTEX(of_clk_mutex);
2849
2850 struct clk *of_clk_src_simple_get(struct of_phandle_args *clkspec,
2851                                      void *data)
2852 {
2853         return data;
2854 }
2855 EXPORT_SYMBOL_GPL(of_clk_src_simple_get);
2856
2857 struct clk *of_clk_src_onecell_get(struct of_phandle_args *clkspec, void *data)
2858 {
2859         struct clk_onecell_data *clk_data = data;
2860         unsigned int idx = clkspec->args[0];
2861
2862         if (idx >= clk_data->clk_num) {
2863                 pr_err("%s: invalid clock index %d\n", __func__, idx);
2864                 return ERR_PTR(-EINVAL);
2865         }
2866
2867         return clk_data->clks[idx];
2868 }
2869 EXPORT_SYMBOL_GPL(of_clk_src_onecell_get);
2870
2871 /**
2872  * of_clk_add_provider() - Register a clock provider for a node
2873  * @np: Device node pointer associated with clock provider
2874  * @clk_src_get: callback for decoding clock
2875  * @data: context pointer for @clk_src_get callback.
2876  */
2877 int of_clk_add_provider(struct device_node *np,
2878                         struct clk *(*clk_src_get)(struct of_phandle_args *clkspec,
2879                                                    void *data),
2880                         void *data)
2881 {
2882         struct of_clk_provider *cp;
2883         int ret;
2884
2885         cp = kzalloc(sizeof(struct of_clk_provider), GFP_KERNEL);
2886         if (!cp)
2887                 return -ENOMEM;
2888
2889         cp->node = of_node_get(np);
2890         cp->data = data;
2891         cp->get = clk_src_get;
2892
2893         mutex_lock(&of_clk_mutex);
2894         list_add(&cp->link, &of_clk_providers);
2895         mutex_unlock(&of_clk_mutex);
2896         pr_debug("Added clock from %s\n", np->full_name);
2897
2898         ret = of_clk_set_defaults(np, true);
2899         if (ret < 0)
2900                 of_clk_del_provider(np);
2901
2902         return ret;
2903 }
2904 EXPORT_SYMBOL_GPL(of_clk_add_provider);
2905
2906 /**
2907  * of_clk_del_provider() - Remove a previously registered clock provider
2908  * @np: Device node pointer associated with clock provider
2909  */
2910 void of_clk_del_provider(struct device_node *np)
2911 {
2912         struct of_clk_provider *cp;
2913
2914         mutex_lock(&of_clk_mutex);
2915         list_for_each_entry(cp, &of_clk_providers, link) {
2916                 if (cp->node == np) {
2917                         list_del(&cp->link);
2918                         of_node_put(cp->node);
2919                         kfree(cp);
2920                         break;
2921                 }
2922         }
2923         mutex_unlock(&of_clk_mutex);
2924 }
2925 EXPORT_SYMBOL_GPL(of_clk_del_provider);
2926
2927 struct clk *__of_clk_get_from_provider(struct of_phandle_args *clkspec,
2928                                        const char *dev_id, const char *con_id)
2929 {
2930         struct of_clk_provider *provider;
2931         struct clk *clk = ERR_PTR(-EPROBE_DEFER);
2932
2933         if (!clkspec)
2934                 return ERR_PTR(-EINVAL);
2935
2936         /* Check if we have such a provider in our array */
2937         mutex_lock(&of_clk_mutex);
2938         list_for_each_entry(provider, &of_clk_providers, link) {
2939                 if (provider->node == clkspec->np)
2940                         clk = provider->get(clkspec, provider->data);
2941                 if (!IS_ERR(clk)) {
2942                         clk = __clk_create_clk(__clk_get_hw(clk), dev_id,
2943                                                con_id);
2944
2945                         if (!IS_ERR(clk) && !__clk_get(clk)) {
2946                                 __clk_free_clk(clk);
2947                                 clk = ERR_PTR(-ENOENT);
2948                         }
2949
2950                         break;
2951                 }
2952         }
2953         mutex_unlock(&of_clk_mutex);
2954
2955         return clk;
2956 }
2957
2958 /**
2959  * of_clk_get_from_provider() - Lookup a clock from a clock provider
2960  * @clkspec: pointer to a clock specifier data structure
2961  *
2962  * This function looks up a struct clk from the registered list of clock
2963  * providers, an input is a clock specifier data structure as returned
2964  * from the of_parse_phandle_with_args() function call.
2965  */
2966 struct clk *of_clk_get_from_provider(struct of_phandle_args *clkspec)
2967 {
2968         return __of_clk_get_from_provider(clkspec, NULL, __func__);
2969 }
2970
2971 int of_clk_get_parent_count(struct device_node *np)
2972 {
2973         return of_count_phandle_with_args(np, "clocks", "#clock-cells");
2974 }
2975 EXPORT_SYMBOL_GPL(of_clk_get_parent_count);
2976
2977 const char *of_clk_get_parent_name(struct device_node *np, int index)
2978 {
2979         struct of_phandle_args clkspec;
2980         struct property *prop;
2981         const char *clk_name;
2982         const __be32 *vp;
2983         u32 pv;
2984         int rc;
2985         int count;
2986
2987         if (index < 0)
2988                 return NULL;
2989
2990         rc = of_parse_phandle_with_args(np, "clocks", "#clock-cells", index,
2991                                         &clkspec);
2992         if (rc)
2993                 return NULL;
2994
2995         index = clkspec.args_count ? clkspec.args[0] : 0;
2996         count = 0;
2997
2998         /* if there is an indices property, use it to transfer the index
2999          * specified into an array offset for the clock-output-names property.
3000          */
3001         of_property_for_each_u32(clkspec.np, "clock-indices", prop, vp, pv) {
3002                 if (index == pv) {
3003                         index = count;
3004                         break;
3005                 }
3006                 count++;
3007         }
3008
3009         if (of_property_read_string_index(clkspec.np, "clock-output-names",
3010                                           index,
3011                                           &clk_name) < 0)
3012                 clk_name = clkspec.np->name;
3013
3014         of_node_put(clkspec.np);
3015         return clk_name;
3016 }
3017 EXPORT_SYMBOL_GPL(of_clk_get_parent_name);
3018
3019 /**
3020  * of_clk_parent_fill() - Fill @parents with names of @np's parents and return
3021  * number of parents
3022  * @np: Device node pointer associated with clock provider
3023  * @parents: pointer to char array that hold the parents' names
3024  * @size: size of the @parents array
3025  *
3026  * Return: number of parents for the clock node.
3027  */
3028 int of_clk_parent_fill(struct device_node *np, const char **parents,
3029                        unsigned int size)
3030 {
3031         unsigned int i = 0;
3032
3033         while (i < size && (parents[i] = of_clk_get_parent_name(np, i)) != NULL)
3034                 i++;
3035
3036         return i;
3037 }
3038 EXPORT_SYMBOL_GPL(of_clk_parent_fill);
3039
3040 struct clock_provider {
3041         of_clk_init_cb_t clk_init_cb;
3042         struct device_node *np;
3043         struct list_head node;
3044 };
3045
3046 static LIST_HEAD(clk_provider_list);
3047
3048 /*
3049  * This function looks for a parent clock. If there is one, then it
3050  * checks that the provider for this parent clock was initialized, in
3051  * this case the parent clock will be ready.
3052  */
3053 static int parent_ready(struct device_node *np)
3054 {
3055         int i = 0;
3056
3057         while (true) {
3058                 struct clk *clk = of_clk_get(np, i);
3059
3060                 /* this parent is ready we can check the next one */
3061                 if (!IS_ERR(clk)) {
3062                         clk_put(clk);
3063                         i++;
3064                         continue;
3065                 }
3066
3067                 /* at least one parent is not ready, we exit now */
3068                 if (PTR_ERR(clk) == -EPROBE_DEFER)
3069                         return 0;
3070
3071                 /*
3072                  * Here we make assumption that the device tree is
3073                  * written correctly. So an error means that there is
3074                  * no more parent. As we didn't exit yet, then the
3075                  * previous parent are ready. If there is no clock
3076                  * parent, no need to wait for them, then we can
3077                  * consider their absence as being ready
3078                  */
3079                 return 1;
3080         }
3081 }
3082
3083 /**
3084  * of_clk_init() - Scan and init clock providers from the DT
3085  * @matches: array of compatible values and init functions for providers.
3086  *
3087  * This function scans the device tree for matching clock providers
3088  * and calls their initialization functions. It also does it by trying
3089  * to follow the dependencies.
3090  */
3091 void __init of_clk_init(const struct of_device_id *matches)
3092 {
3093         const struct of_device_id *match;
3094         struct device_node *np;
3095         struct clock_provider *clk_provider, *next;
3096         bool is_init_done;
3097         bool force = false;
3098
3099         if (!matches)
3100                 matches = &__clk_of_table;
3101
3102         /* First prepare the list of the clocks providers */
3103         for_each_matching_node_and_match(np, matches, &match) {
3104                 struct clock_provider *parent =
3105                         kzalloc(sizeof(struct clock_provider),  GFP_KERNEL);
3106
3107                 parent->clk_init_cb = match->data;
3108                 parent->np = np;
3109                 list_add_tail(&parent->node, &clk_provider_list);
3110         }
3111
3112         while (!list_empty(&clk_provider_list)) {
3113                 is_init_done = false;
3114                 list_for_each_entry_safe(clk_provider, next,
3115                                         &clk_provider_list, node) {
3116                         if (force || parent_ready(clk_provider->np)) {
3117
3118                                 clk_provider->clk_init_cb(clk_provider->np);
3119                                 of_clk_set_defaults(clk_provider->np, true);
3120
3121                                 list_del(&clk_provider->node);
3122                                 kfree(clk_provider);
3123                                 is_init_done = true;
3124                         }
3125                 }
3126
3127                 /*
3128                  * We didn't manage to initialize any of the
3129                  * remaining providers during the last loop, so now we
3130                  * initialize all the remaining ones unconditionally
3131                  * in case the clock parent was not mandatory
3132                  */
3133                 if (!is_init_done)
3134                         force = true;
3135         }
3136 }
3137 #endif