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