Merge branches 'clk-doc', 'clk-more-critical', 'clk-meson' and 'clk-basic-be' into...
[linux-2.6-microblaze.git] / drivers / clk / clk.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2010-2011 Canonical Ltd <jeremy.kerr@canonical.com>
4  * Copyright (C) 2011-2012 Linaro Ltd <mturquette@linaro.org>
5  *
6  * Standard functionality for the common clock API.  See Documentation/driver-api/clk.rst
7  */
8
9 #include <linux/clk.h>
10 #include <linux/clk-provider.h>
11 #include <linux/clk/clk-conf.h>
12 #include <linux/module.h>
13 #include <linux/mutex.h>
14 #include <linux/spinlock.h>
15 #include <linux/err.h>
16 #include <linux/list.h>
17 #include <linux/slab.h>
18 #include <linux/of.h>
19 #include <linux/device.h>
20 #include <linux/init.h>
21 #include <linux/pm_runtime.h>
22 #include <linux/sched.h>
23 #include <linux/clkdev.h>
24
25 #include "clk.h"
26
27 static DEFINE_SPINLOCK(enable_lock);
28 static DEFINE_MUTEX(prepare_lock);
29
30 static struct task_struct *prepare_owner;
31 static struct task_struct *enable_owner;
32
33 static int prepare_refcnt;
34 static int enable_refcnt;
35
36 static HLIST_HEAD(clk_root_list);
37 static HLIST_HEAD(clk_orphan_list);
38 static LIST_HEAD(clk_notifier_list);
39
40 /***    private data structures    ***/
41
42 struct clk_core {
43         const char              *name;
44         const struct clk_ops    *ops;
45         struct clk_hw           *hw;
46         struct module           *owner;
47         struct device           *dev;
48         struct clk_core         *parent;
49         const char              **parent_names;
50         struct clk_core         **parents;
51         u8                      num_parents;
52         u8                      new_parent_index;
53         unsigned long           rate;
54         unsigned long           req_rate;
55         unsigned long           new_rate;
56         struct clk_core         *new_parent;
57         struct clk_core         *new_child;
58         unsigned long           flags;
59         bool                    orphan;
60         bool                    rpm_enabled;
61         unsigned int            enable_count;
62         unsigned int            prepare_count;
63         unsigned int            protect_count;
64         unsigned long           min_rate;
65         unsigned long           max_rate;
66         unsigned long           accuracy;
67         int                     phase;
68         struct clk_duty         duty;
69         struct hlist_head       children;
70         struct hlist_node       child_node;
71         struct hlist_head       clks;
72         unsigned int            notifier_count;
73 #ifdef CONFIG_DEBUG_FS
74         struct dentry           *dentry;
75         struct hlist_node       debug_node;
76 #endif
77         struct kref             ref;
78 };
79
80 #define CREATE_TRACE_POINTS
81 #include <trace/events/clk.h>
82
83 struct clk {
84         struct clk_core *core;
85         struct device *dev;
86         const char *dev_id;
87         const char *con_id;
88         unsigned long min_rate;
89         unsigned long max_rate;
90         unsigned int exclusive_count;
91         struct hlist_node clks_node;
92 };
93
94 /***           runtime pm          ***/
95 static int clk_pm_runtime_get(struct clk_core *core)
96 {
97         int ret;
98
99         if (!core->rpm_enabled)
100                 return 0;
101
102         ret = pm_runtime_get_sync(core->dev);
103         return ret < 0 ? ret : 0;
104 }
105
106 static void clk_pm_runtime_put(struct clk_core *core)
107 {
108         if (!core->rpm_enabled)
109                 return;
110
111         pm_runtime_put_sync(core->dev);
112 }
113
114 /***           locking             ***/
115 static void clk_prepare_lock(void)
116 {
117         if (!mutex_trylock(&prepare_lock)) {
118                 if (prepare_owner == current) {
119                         prepare_refcnt++;
120                         return;
121                 }
122                 mutex_lock(&prepare_lock);
123         }
124         WARN_ON_ONCE(prepare_owner != NULL);
125         WARN_ON_ONCE(prepare_refcnt != 0);
126         prepare_owner = current;
127         prepare_refcnt = 1;
128 }
129
130 static void clk_prepare_unlock(void)
131 {
132         WARN_ON_ONCE(prepare_owner != current);
133         WARN_ON_ONCE(prepare_refcnt == 0);
134
135         if (--prepare_refcnt)
136                 return;
137         prepare_owner = NULL;
138         mutex_unlock(&prepare_lock);
139 }
140
141 static unsigned long clk_enable_lock(void)
142         __acquires(enable_lock)
143 {
144         unsigned long flags;
145
146         /*
147          * On UP systems, spin_trylock_irqsave() always returns true, even if
148          * we already hold the lock. So, in that case, we rely only on
149          * reference counting.
150          */
151         if (!IS_ENABLED(CONFIG_SMP) ||
152             !spin_trylock_irqsave(&enable_lock, flags)) {
153                 if (enable_owner == current) {
154                         enable_refcnt++;
155                         __acquire(enable_lock);
156                         if (!IS_ENABLED(CONFIG_SMP))
157                                 local_save_flags(flags);
158                         return flags;
159                 }
160                 spin_lock_irqsave(&enable_lock, flags);
161         }
162         WARN_ON_ONCE(enable_owner != NULL);
163         WARN_ON_ONCE(enable_refcnt != 0);
164         enable_owner = current;
165         enable_refcnt = 1;
166         return flags;
167 }
168
169 static void clk_enable_unlock(unsigned long flags)
170         __releases(enable_lock)
171 {
172         WARN_ON_ONCE(enable_owner != current);
173         WARN_ON_ONCE(enable_refcnt == 0);
174
175         if (--enable_refcnt) {
176                 __release(enable_lock);
177                 return;
178         }
179         enable_owner = NULL;
180         spin_unlock_irqrestore(&enable_lock, flags);
181 }
182
183 static bool clk_core_rate_is_protected(struct clk_core *core)
184 {
185         return core->protect_count;
186 }
187
188 static bool clk_core_is_prepared(struct clk_core *core)
189 {
190         bool ret = false;
191
192         /*
193          * .is_prepared is optional for clocks that can prepare
194          * fall back to software usage counter if it is missing
195          */
196         if (!core->ops->is_prepared)
197                 return core->prepare_count;
198
199         if (!clk_pm_runtime_get(core)) {
200                 ret = core->ops->is_prepared(core->hw);
201                 clk_pm_runtime_put(core);
202         }
203
204         return ret;
205 }
206
207 static bool clk_core_is_enabled(struct clk_core *core)
208 {
209         bool ret = false;
210
211         /*
212          * .is_enabled is only mandatory for clocks that gate
213          * fall back to software usage counter if .is_enabled is missing
214          */
215         if (!core->ops->is_enabled)
216                 return core->enable_count;
217
218         /*
219          * Check if clock controller's device is runtime active before
220          * calling .is_enabled callback. If not, assume that clock is
221          * disabled, because we might be called from atomic context, from
222          * which pm_runtime_get() is not allowed.
223          * This function is called mainly from clk_disable_unused_subtree,
224          * which ensures proper runtime pm activation of controller before
225          * taking enable spinlock, but the below check is needed if one tries
226          * to call it from other places.
227          */
228         if (core->rpm_enabled) {
229                 pm_runtime_get_noresume(core->dev);
230                 if (!pm_runtime_active(core->dev)) {
231                         ret = false;
232                         goto done;
233                 }
234         }
235
236         ret = core->ops->is_enabled(core->hw);
237 done:
238         if (core->rpm_enabled)
239                 pm_runtime_put(core->dev);
240
241         return ret;
242 }
243
244 /***    helper functions   ***/
245
246 const char *__clk_get_name(const struct clk *clk)
247 {
248         return !clk ? NULL : clk->core->name;
249 }
250 EXPORT_SYMBOL_GPL(__clk_get_name);
251
252 const char *clk_hw_get_name(const struct clk_hw *hw)
253 {
254         return hw->core->name;
255 }
256 EXPORT_SYMBOL_GPL(clk_hw_get_name);
257
258 struct clk_hw *__clk_get_hw(struct clk *clk)
259 {
260         return !clk ? NULL : clk->core->hw;
261 }
262 EXPORT_SYMBOL_GPL(__clk_get_hw);
263
264 unsigned int clk_hw_get_num_parents(const struct clk_hw *hw)
265 {
266         return hw->core->num_parents;
267 }
268 EXPORT_SYMBOL_GPL(clk_hw_get_num_parents);
269
270 struct clk_hw *clk_hw_get_parent(const struct clk_hw *hw)
271 {
272         return hw->core->parent ? hw->core->parent->hw : NULL;
273 }
274 EXPORT_SYMBOL_GPL(clk_hw_get_parent);
275
276 static struct clk_core *__clk_lookup_subtree(const char *name,
277                                              struct clk_core *core)
278 {
279         struct clk_core *child;
280         struct clk_core *ret;
281
282         if (!strcmp(core->name, name))
283                 return core;
284
285         hlist_for_each_entry(child, &core->children, child_node) {
286                 ret = __clk_lookup_subtree(name, child);
287                 if (ret)
288                         return ret;
289         }
290
291         return NULL;
292 }
293
294 static struct clk_core *clk_core_lookup(const char *name)
295 {
296         struct clk_core *root_clk;
297         struct clk_core *ret;
298
299         if (!name)
300                 return NULL;
301
302         /* search the 'proper' clk tree first */
303         hlist_for_each_entry(root_clk, &clk_root_list, child_node) {
304                 ret = __clk_lookup_subtree(name, root_clk);
305                 if (ret)
306                         return ret;
307         }
308
309         /* if not found, then search the orphan tree */
310         hlist_for_each_entry(root_clk, &clk_orphan_list, child_node) {
311                 ret = __clk_lookup_subtree(name, root_clk);
312                 if (ret)
313                         return ret;
314         }
315
316         return NULL;
317 }
318
319 static struct clk_core *clk_core_get_parent_by_index(struct clk_core *core,
320                                                          u8 index)
321 {
322         if (!core || index >= core->num_parents)
323                 return NULL;
324
325         if (!core->parents[index])
326                 core->parents[index] =
327                                 clk_core_lookup(core->parent_names[index]);
328
329         return core->parents[index];
330 }
331
332 struct clk_hw *
333 clk_hw_get_parent_by_index(const struct clk_hw *hw, unsigned int index)
334 {
335         struct clk_core *parent;
336
337         parent = clk_core_get_parent_by_index(hw->core, index);
338
339         return !parent ? NULL : parent->hw;
340 }
341 EXPORT_SYMBOL_GPL(clk_hw_get_parent_by_index);
342
343 unsigned int __clk_get_enable_count(struct clk *clk)
344 {
345         return !clk ? 0 : clk->core->enable_count;
346 }
347
348 static unsigned long clk_core_get_rate_nolock(struct clk_core *core)
349 {
350         if (!core)
351                 return 0;
352
353         if (!core->num_parents || core->parent)
354                 return core->rate;
355
356         /*
357          * Clk must have a parent because num_parents > 0 but the parent isn't
358          * known yet. Best to return 0 as the rate of this clk until we can
359          * properly recalc the rate based on the parent's rate.
360          */
361         return 0;
362 }
363
364 unsigned long clk_hw_get_rate(const struct clk_hw *hw)
365 {
366         return clk_core_get_rate_nolock(hw->core);
367 }
368 EXPORT_SYMBOL_GPL(clk_hw_get_rate);
369
370 static unsigned long __clk_get_accuracy(struct clk_core *core)
371 {
372         if (!core)
373                 return 0;
374
375         return core->accuracy;
376 }
377
378 unsigned long __clk_get_flags(struct clk *clk)
379 {
380         return !clk ? 0 : clk->core->flags;
381 }
382 EXPORT_SYMBOL_GPL(__clk_get_flags);
383
384 unsigned long clk_hw_get_flags(const struct clk_hw *hw)
385 {
386         return hw->core->flags;
387 }
388 EXPORT_SYMBOL_GPL(clk_hw_get_flags);
389
390 bool clk_hw_is_prepared(const struct clk_hw *hw)
391 {
392         return clk_core_is_prepared(hw->core);
393 }
394 EXPORT_SYMBOL_GPL(clk_hw_is_prepared);
395
396 bool clk_hw_rate_is_protected(const struct clk_hw *hw)
397 {
398         return clk_core_rate_is_protected(hw->core);
399 }
400 EXPORT_SYMBOL_GPL(clk_hw_rate_is_protected);
401
402 bool clk_hw_is_enabled(const struct clk_hw *hw)
403 {
404         return clk_core_is_enabled(hw->core);
405 }
406 EXPORT_SYMBOL_GPL(clk_hw_is_enabled);
407
408 bool __clk_is_enabled(struct clk *clk)
409 {
410         if (!clk)
411                 return false;
412
413         return clk_core_is_enabled(clk->core);
414 }
415 EXPORT_SYMBOL_GPL(__clk_is_enabled);
416
417 static bool mux_is_better_rate(unsigned long rate, unsigned long now,
418                            unsigned long best, unsigned long flags)
419 {
420         if (flags & CLK_MUX_ROUND_CLOSEST)
421                 return abs(now - rate) < abs(best - rate);
422
423         return now <= rate && now > best;
424 }
425
426 int clk_mux_determine_rate_flags(struct clk_hw *hw,
427                                  struct clk_rate_request *req,
428                                  unsigned long flags)
429 {
430         struct clk_core *core = hw->core, *parent, *best_parent = NULL;
431         int i, num_parents, ret;
432         unsigned long best = 0;
433         struct clk_rate_request parent_req = *req;
434
435         /* if NO_REPARENT flag set, pass through to current parent */
436         if (core->flags & CLK_SET_RATE_NO_REPARENT) {
437                 parent = core->parent;
438                 if (core->flags & CLK_SET_RATE_PARENT) {
439                         ret = __clk_determine_rate(parent ? parent->hw : NULL,
440                                                    &parent_req);
441                         if (ret)
442                                 return ret;
443
444                         best = parent_req.rate;
445                 } else if (parent) {
446                         best = clk_core_get_rate_nolock(parent);
447                 } else {
448                         best = clk_core_get_rate_nolock(core);
449                 }
450
451                 goto out;
452         }
453
454         /* find the parent that can provide the fastest rate <= rate */
455         num_parents = core->num_parents;
456         for (i = 0; i < num_parents; i++) {
457                 parent = clk_core_get_parent_by_index(core, i);
458                 if (!parent)
459                         continue;
460
461                 if (core->flags & CLK_SET_RATE_PARENT) {
462                         parent_req = *req;
463                         ret = __clk_determine_rate(parent->hw, &parent_req);
464                         if (ret)
465                                 continue;
466                 } else {
467                         parent_req.rate = clk_core_get_rate_nolock(parent);
468                 }
469
470                 if (mux_is_better_rate(req->rate, parent_req.rate,
471                                        best, flags)) {
472                         best_parent = parent;
473                         best = parent_req.rate;
474                 }
475         }
476
477         if (!best_parent)
478                 return -EINVAL;
479
480 out:
481         if (best_parent)
482                 req->best_parent_hw = best_parent->hw;
483         req->best_parent_rate = best;
484         req->rate = best;
485
486         return 0;
487 }
488 EXPORT_SYMBOL_GPL(clk_mux_determine_rate_flags);
489
490 struct clk *__clk_lookup(const char *name)
491 {
492         struct clk_core *core = clk_core_lookup(name);
493
494         return !core ? NULL : core->hw->clk;
495 }
496
497 static void clk_core_get_boundaries(struct clk_core *core,
498                                     unsigned long *min_rate,
499                                     unsigned long *max_rate)
500 {
501         struct clk *clk_user;
502
503         *min_rate = core->min_rate;
504         *max_rate = core->max_rate;
505
506         hlist_for_each_entry(clk_user, &core->clks, clks_node)
507                 *min_rate = max(*min_rate, clk_user->min_rate);
508
509         hlist_for_each_entry(clk_user, &core->clks, clks_node)
510                 *max_rate = min(*max_rate, clk_user->max_rate);
511 }
512
513 void clk_hw_set_rate_range(struct clk_hw *hw, unsigned long min_rate,
514                            unsigned long max_rate)
515 {
516         hw->core->min_rate = min_rate;
517         hw->core->max_rate = max_rate;
518 }
519 EXPORT_SYMBOL_GPL(clk_hw_set_rate_range);
520
521 /*
522  * __clk_mux_determine_rate - clk_ops::determine_rate implementation for a mux type clk
523  * @hw: mux type clk to determine rate on
524  * @req: rate request, also used to return preferred parent and frequencies
525  *
526  * Helper for finding best parent to provide a given frequency. This can be used
527  * directly as a determine_rate callback (e.g. for a mux), or from a more
528  * complex clock that may combine a mux with other operations.
529  *
530  * Returns: 0 on success, -EERROR value on error
531  */
532 int __clk_mux_determine_rate(struct clk_hw *hw,
533                              struct clk_rate_request *req)
534 {
535         return clk_mux_determine_rate_flags(hw, req, 0);
536 }
537 EXPORT_SYMBOL_GPL(__clk_mux_determine_rate);
538
539 int __clk_mux_determine_rate_closest(struct clk_hw *hw,
540                                      struct clk_rate_request *req)
541 {
542         return clk_mux_determine_rate_flags(hw, req, CLK_MUX_ROUND_CLOSEST);
543 }
544 EXPORT_SYMBOL_GPL(__clk_mux_determine_rate_closest);
545
546 /***        clk api        ***/
547
548 static void clk_core_rate_unprotect(struct clk_core *core)
549 {
550         lockdep_assert_held(&prepare_lock);
551
552         if (!core)
553                 return;
554
555         if (WARN(core->protect_count == 0,
556             "%s already unprotected\n", core->name))
557                 return;
558
559         if (--core->protect_count > 0)
560                 return;
561
562         clk_core_rate_unprotect(core->parent);
563 }
564
565 static int clk_core_rate_nuke_protect(struct clk_core *core)
566 {
567         int ret;
568
569         lockdep_assert_held(&prepare_lock);
570
571         if (!core)
572                 return -EINVAL;
573
574         if (core->protect_count == 0)
575                 return 0;
576
577         ret = core->protect_count;
578         core->protect_count = 1;
579         clk_core_rate_unprotect(core);
580
581         return ret;
582 }
583
584 /**
585  * clk_rate_exclusive_put - release exclusivity over clock rate control
586  * @clk: the clk over which the exclusivity is released
587  *
588  * clk_rate_exclusive_put() completes a critical section during which a clock
589  * consumer cannot tolerate any other consumer making any operation on the
590  * clock which could result in a rate change or rate glitch. Exclusive clocks
591  * cannot have their rate changed, either directly or indirectly due to changes
592  * further up the parent chain of clocks. As a result, clocks up parent chain
593  * also get under exclusive control of the calling consumer.
594  *
595  * If exlusivity is claimed more than once on clock, even by the same consumer,
596  * the rate effectively gets locked as exclusivity can't be preempted.
597  *
598  * Calls to clk_rate_exclusive_put() must be balanced with calls to
599  * clk_rate_exclusive_get(). Calls to this function may sleep, and do not return
600  * error status.
601  */
602 void clk_rate_exclusive_put(struct clk *clk)
603 {
604         if (!clk)
605                 return;
606
607         clk_prepare_lock();
608
609         /*
610          * if there is something wrong with this consumer protect count, stop
611          * here before messing with the provider
612          */
613         if (WARN_ON(clk->exclusive_count <= 0))
614                 goto out;
615
616         clk_core_rate_unprotect(clk->core);
617         clk->exclusive_count--;
618 out:
619         clk_prepare_unlock();
620 }
621 EXPORT_SYMBOL_GPL(clk_rate_exclusive_put);
622
623 static void clk_core_rate_protect(struct clk_core *core)
624 {
625         lockdep_assert_held(&prepare_lock);
626
627         if (!core)
628                 return;
629
630         if (core->protect_count == 0)
631                 clk_core_rate_protect(core->parent);
632
633         core->protect_count++;
634 }
635
636 static void clk_core_rate_restore_protect(struct clk_core *core, int count)
637 {
638         lockdep_assert_held(&prepare_lock);
639
640         if (!core)
641                 return;
642
643         if (count == 0)
644                 return;
645
646         clk_core_rate_protect(core);
647         core->protect_count = count;
648 }
649
650 /**
651  * clk_rate_exclusive_get - get exclusivity over the clk rate control
652  * @clk: the clk over which the exclusity of rate control is requested
653  *
654  * clk_rate_exlusive_get() begins a critical section during which a clock
655  * consumer cannot tolerate any other consumer making any operation on the
656  * clock which could result in a rate change or rate glitch. Exclusive clocks
657  * cannot have their rate changed, either directly or indirectly due to changes
658  * further up the parent chain of clocks. As a result, clocks up parent chain
659  * also get under exclusive control of the calling consumer.
660  *
661  * If exlusivity is claimed more than once on clock, even by the same consumer,
662  * the rate effectively gets locked as exclusivity can't be preempted.
663  *
664  * Calls to clk_rate_exclusive_get() should be balanced with calls to
665  * clk_rate_exclusive_put(). Calls to this function may sleep.
666  * Returns 0 on success, -EERROR otherwise
667  */
668 int clk_rate_exclusive_get(struct clk *clk)
669 {
670         if (!clk)
671                 return 0;
672
673         clk_prepare_lock();
674         clk_core_rate_protect(clk->core);
675         clk->exclusive_count++;
676         clk_prepare_unlock();
677
678         return 0;
679 }
680 EXPORT_SYMBOL_GPL(clk_rate_exclusive_get);
681
682 static void clk_core_unprepare(struct clk_core *core)
683 {
684         lockdep_assert_held(&prepare_lock);
685
686         if (!core)
687                 return;
688
689         if (WARN(core->prepare_count == 0,
690             "%s already unprepared\n", core->name))
691                 return;
692
693         if (WARN(core->prepare_count == 1 && core->flags & CLK_IS_CRITICAL,
694             "Unpreparing critical %s\n", core->name))
695                 return;
696
697         if (core->flags & CLK_SET_RATE_GATE)
698                 clk_core_rate_unprotect(core);
699
700         if (--core->prepare_count > 0)
701                 return;
702
703         WARN(core->enable_count > 0, "Unpreparing enabled %s\n", core->name);
704
705         trace_clk_unprepare(core);
706
707         if (core->ops->unprepare)
708                 core->ops->unprepare(core->hw);
709
710         clk_pm_runtime_put(core);
711
712         trace_clk_unprepare_complete(core);
713         clk_core_unprepare(core->parent);
714 }
715
716 static void clk_core_unprepare_lock(struct clk_core *core)
717 {
718         clk_prepare_lock();
719         clk_core_unprepare(core);
720         clk_prepare_unlock();
721 }
722
723 /**
724  * clk_unprepare - undo preparation of a clock source
725  * @clk: the clk being unprepared
726  *
727  * clk_unprepare may sleep, which differentiates it from clk_disable.  In a
728  * simple case, clk_unprepare can be used instead of clk_disable to gate a clk
729  * if the operation may sleep.  One example is a clk which is accessed over
730  * I2c.  In the complex case a clk gate operation may require a fast and a slow
731  * part.  It is this reason that clk_unprepare and clk_disable are not mutually
732  * exclusive.  In fact clk_disable must be called before clk_unprepare.
733  */
734 void clk_unprepare(struct clk *clk)
735 {
736         if (IS_ERR_OR_NULL(clk))
737                 return;
738
739         clk_core_unprepare_lock(clk->core);
740 }
741 EXPORT_SYMBOL_GPL(clk_unprepare);
742
743 static int clk_core_prepare(struct clk_core *core)
744 {
745         int ret = 0;
746
747         lockdep_assert_held(&prepare_lock);
748
749         if (!core)
750                 return 0;
751
752         if (core->prepare_count == 0) {
753                 ret = clk_pm_runtime_get(core);
754                 if (ret)
755                         return ret;
756
757                 ret = clk_core_prepare(core->parent);
758                 if (ret)
759                         goto runtime_put;
760
761                 trace_clk_prepare(core);
762
763                 if (core->ops->prepare)
764                         ret = core->ops->prepare(core->hw);
765
766                 trace_clk_prepare_complete(core);
767
768                 if (ret)
769                         goto unprepare;
770         }
771
772         core->prepare_count++;
773
774         /*
775          * CLK_SET_RATE_GATE is a special case of clock protection
776          * Instead of a consumer claiming exclusive rate control, it is
777          * actually the provider which prevents any consumer from making any
778          * operation which could result in a rate change or rate glitch while
779          * the clock is prepared.
780          */
781         if (core->flags & CLK_SET_RATE_GATE)
782                 clk_core_rate_protect(core);
783
784         return 0;
785 unprepare:
786         clk_core_unprepare(core->parent);
787 runtime_put:
788         clk_pm_runtime_put(core);
789         return ret;
790 }
791
792 static int clk_core_prepare_lock(struct clk_core *core)
793 {
794         int ret;
795
796         clk_prepare_lock();
797         ret = clk_core_prepare(core);
798         clk_prepare_unlock();
799
800         return ret;
801 }
802
803 /**
804  * clk_prepare - prepare a clock source
805  * @clk: the clk being prepared
806  *
807  * clk_prepare may sleep, which differentiates it from clk_enable.  In a simple
808  * case, clk_prepare can be used instead of clk_enable to ungate a clk if the
809  * operation may sleep.  One example is a clk which is accessed over I2c.  In
810  * the complex case a clk ungate operation may require a fast and a slow part.
811  * It is this reason that clk_prepare and clk_enable are not mutually
812  * exclusive.  In fact clk_prepare must be called before clk_enable.
813  * Returns 0 on success, -EERROR otherwise.
814  */
815 int clk_prepare(struct clk *clk)
816 {
817         if (!clk)
818                 return 0;
819
820         return clk_core_prepare_lock(clk->core);
821 }
822 EXPORT_SYMBOL_GPL(clk_prepare);
823
824 static void clk_core_disable(struct clk_core *core)
825 {
826         lockdep_assert_held(&enable_lock);
827
828         if (!core)
829                 return;
830
831         if (WARN(core->enable_count == 0, "%s already disabled\n", core->name))
832                 return;
833
834         if (WARN(core->enable_count == 1 && core->flags & CLK_IS_CRITICAL,
835             "Disabling critical %s\n", core->name))
836                 return;
837
838         if (--core->enable_count > 0)
839                 return;
840
841         trace_clk_disable_rcuidle(core);
842
843         if (core->ops->disable)
844                 core->ops->disable(core->hw);
845
846         trace_clk_disable_complete_rcuidle(core);
847
848         clk_core_disable(core->parent);
849 }
850
851 static void clk_core_disable_lock(struct clk_core *core)
852 {
853         unsigned long flags;
854
855         flags = clk_enable_lock();
856         clk_core_disable(core);
857         clk_enable_unlock(flags);
858 }
859
860 /**
861  * clk_disable - gate a clock
862  * @clk: the clk being gated
863  *
864  * clk_disable must not sleep, which differentiates it from clk_unprepare.  In
865  * a simple case, clk_disable can be used instead of clk_unprepare to gate a
866  * clk if the operation is fast and will never sleep.  One example is a
867  * SoC-internal clk which is controlled via simple register writes.  In the
868  * complex case a clk gate operation may require a fast and a slow part.  It is
869  * this reason that clk_unprepare and clk_disable are not mutually exclusive.
870  * In fact clk_disable must be called before clk_unprepare.
871  */
872 void clk_disable(struct clk *clk)
873 {
874         if (IS_ERR_OR_NULL(clk))
875                 return;
876
877         clk_core_disable_lock(clk->core);
878 }
879 EXPORT_SYMBOL_GPL(clk_disable);
880
881 static int clk_core_enable(struct clk_core *core)
882 {
883         int ret = 0;
884
885         lockdep_assert_held(&enable_lock);
886
887         if (!core)
888                 return 0;
889
890         if (WARN(core->prepare_count == 0,
891             "Enabling unprepared %s\n", core->name))
892                 return -ESHUTDOWN;
893
894         if (core->enable_count == 0) {
895                 ret = clk_core_enable(core->parent);
896
897                 if (ret)
898                         return ret;
899
900                 trace_clk_enable_rcuidle(core);
901
902                 if (core->ops->enable)
903                         ret = core->ops->enable(core->hw);
904
905                 trace_clk_enable_complete_rcuidle(core);
906
907                 if (ret) {
908                         clk_core_disable(core->parent);
909                         return ret;
910                 }
911         }
912
913         core->enable_count++;
914         return 0;
915 }
916
917 static int clk_core_enable_lock(struct clk_core *core)
918 {
919         unsigned long flags;
920         int ret;
921
922         flags = clk_enable_lock();
923         ret = clk_core_enable(core);
924         clk_enable_unlock(flags);
925
926         return ret;
927 }
928
929 /**
930  * clk_gate_restore_context - restore context for poweroff
931  * @hw: the clk_hw pointer of clock whose state is to be restored
932  *
933  * The clock gate restore context function enables or disables
934  * the gate clocks based on the enable_count. This is done in cases
935  * where the clock context is lost and based on the enable_count
936  * the clock either needs to be enabled/disabled. This
937  * helps restore the state of gate clocks.
938  */
939 void clk_gate_restore_context(struct clk_hw *hw)
940 {
941         struct clk_core *core = hw->core;
942
943         if (core->enable_count)
944                 core->ops->enable(hw);
945         else
946                 core->ops->disable(hw);
947 }
948 EXPORT_SYMBOL_GPL(clk_gate_restore_context);
949
950 static int clk_core_save_context(struct clk_core *core)
951 {
952         struct clk_core *child;
953         int ret = 0;
954
955         hlist_for_each_entry(child, &core->children, child_node) {
956                 ret = clk_core_save_context(child);
957                 if (ret < 0)
958                         return ret;
959         }
960
961         if (core->ops && core->ops->save_context)
962                 ret = core->ops->save_context(core->hw);
963
964         return ret;
965 }
966
967 static void clk_core_restore_context(struct clk_core *core)
968 {
969         struct clk_core *child;
970
971         if (core->ops && core->ops->restore_context)
972                 core->ops->restore_context(core->hw);
973
974         hlist_for_each_entry(child, &core->children, child_node)
975                 clk_core_restore_context(child);
976 }
977
978 /**
979  * clk_save_context - save clock context for poweroff
980  *
981  * Saves the context of the clock register for powerstates in which the
982  * contents of the registers will be lost. Occurs deep within the suspend
983  * code.  Returns 0 on success.
984  */
985 int clk_save_context(void)
986 {
987         struct clk_core *clk;
988         int ret;
989
990         hlist_for_each_entry(clk, &clk_root_list, child_node) {
991                 ret = clk_core_save_context(clk);
992                 if (ret < 0)
993                         return ret;
994         }
995
996         hlist_for_each_entry(clk, &clk_orphan_list, child_node) {
997                 ret = clk_core_save_context(clk);
998                 if (ret < 0)
999                         return ret;
1000         }
1001
1002         return 0;
1003 }
1004 EXPORT_SYMBOL_GPL(clk_save_context);
1005
1006 /**
1007  * clk_restore_context - restore clock context after poweroff
1008  *
1009  * Restore the saved clock context upon resume.
1010  *
1011  */
1012 void clk_restore_context(void)
1013 {
1014         struct clk_core *core;
1015
1016         hlist_for_each_entry(core, &clk_root_list, child_node)
1017                 clk_core_restore_context(core);
1018
1019         hlist_for_each_entry(core, &clk_orphan_list, child_node)
1020                 clk_core_restore_context(core);
1021 }
1022 EXPORT_SYMBOL_GPL(clk_restore_context);
1023
1024 /**
1025  * clk_enable - ungate a clock
1026  * @clk: the clk being ungated
1027  *
1028  * clk_enable must not sleep, which differentiates it from clk_prepare.  In a
1029  * simple case, clk_enable can be used instead of clk_prepare to ungate a clk
1030  * if the operation will never sleep.  One example is a SoC-internal clk which
1031  * is controlled via simple register writes.  In the complex case a clk ungate
1032  * operation may require a fast and a slow part.  It is this reason that
1033  * clk_enable and clk_prepare are not mutually exclusive.  In fact clk_prepare
1034  * must be called before clk_enable.  Returns 0 on success, -EERROR
1035  * otherwise.
1036  */
1037 int clk_enable(struct clk *clk)
1038 {
1039         if (!clk)
1040                 return 0;
1041
1042         return clk_core_enable_lock(clk->core);
1043 }
1044 EXPORT_SYMBOL_GPL(clk_enable);
1045
1046 static int clk_core_prepare_enable(struct clk_core *core)
1047 {
1048         int ret;
1049
1050         ret = clk_core_prepare_lock(core);
1051         if (ret)
1052                 return ret;
1053
1054         ret = clk_core_enable_lock(core);
1055         if (ret)
1056                 clk_core_unprepare_lock(core);
1057
1058         return ret;
1059 }
1060
1061 static void clk_core_disable_unprepare(struct clk_core *core)
1062 {
1063         clk_core_disable_lock(core);
1064         clk_core_unprepare_lock(core);
1065 }
1066
1067 static void clk_unprepare_unused_subtree(struct clk_core *core)
1068 {
1069         struct clk_core *child;
1070
1071         lockdep_assert_held(&prepare_lock);
1072
1073         hlist_for_each_entry(child, &core->children, child_node)
1074                 clk_unprepare_unused_subtree(child);
1075
1076         if (core->prepare_count)
1077                 return;
1078
1079         if (core->flags & CLK_IGNORE_UNUSED)
1080                 return;
1081
1082         if (clk_pm_runtime_get(core))
1083                 return;
1084
1085         if (clk_core_is_prepared(core)) {
1086                 trace_clk_unprepare(core);
1087                 if (core->ops->unprepare_unused)
1088                         core->ops->unprepare_unused(core->hw);
1089                 else if (core->ops->unprepare)
1090                         core->ops->unprepare(core->hw);
1091                 trace_clk_unprepare_complete(core);
1092         }
1093
1094         clk_pm_runtime_put(core);
1095 }
1096
1097 static void clk_disable_unused_subtree(struct clk_core *core)
1098 {
1099         struct clk_core *child;
1100         unsigned long flags;
1101
1102         lockdep_assert_held(&prepare_lock);
1103
1104         hlist_for_each_entry(child, &core->children, child_node)
1105                 clk_disable_unused_subtree(child);
1106
1107         if (core->flags & CLK_OPS_PARENT_ENABLE)
1108                 clk_core_prepare_enable(core->parent);
1109
1110         if (clk_pm_runtime_get(core))
1111                 goto unprepare_out;
1112
1113         flags = clk_enable_lock();
1114
1115         if (core->enable_count)
1116                 goto unlock_out;
1117
1118         if (core->flags & CLK_IGNORE_UNUSED)
1119                 goto unlock_out;
1120
1121         /*
1122          * some gate clocks have special needs during the disable-unused
1123          * sequence.  call .disable_unused if available, otherwise fall
1124          * back to .disable
1125          */
1126         if (clk_core_is_enabled(core)) {
1127                 trace_clk_disable(core);
1128                 if (core->ops->disable_unused)
1129                         core->ops->disable_unused(core->hw);
1130                 else if (core->ops->disable)
1131                         core->ops->disable(core->hw);
1132                 trace_clk_disable_complete(core);
1133         }
1134
1135 unlock_out:
1136         clk_enable_unlock(flags);
1137         clk_pm_runtime_put(core);
1138 unprepare_out:
1139         if (core->flags & CLK_OPS_PARENT_ENABLE)
1140                 clk_core_disable_unprepare(core->parent);
1141 }
1142
1143 static bool clk_ignore_unused;
1144 static int __init clk_ignore_unused_setup(char *__unused)
1145 {
1146         clk_ignore_unused = true;
1147         return 1;
1148 }
1149 __setup("clk_ignore_unused", clk_ignore_unused_setup);
1150
1151 static int clk_disable_unused(void)
1152 {
1153         struct clk_core *core;
1154
1155         if (clk_ignore_unused) {
1156                 pr_warn("clk: Not disabling unused clocks\n");
1157                 return 0;
1158         }
1159
1160         clk_prepare_lock();
1161
1162         hlist_for_each_entry(core, &clk_root_list, child_node)
1163                 clk_disable_unused_subtree(core);
1164
1165         hlist_for_each_entry(core, &clk_orphan_list, child_node)
1166                 clk_disable_unused_subtree(core);
1167
1168         hlist_for_each_entry(core, &clk_root_list, child_node)
1169                 clk_unprepare_unused_subtree(core);
1170
1171         hlist_for_each_entry(core, &clk_orphan_list, child_node)
1172                 clk_unprepare_unused_subtree(core);
1173
1174         clk_prepare_unlock();
1175
1176         return 0;
1177 }
1178 late_initcall_sync(clk_disable_unused);
1179
1180 static int clk_core_determine_round_nolock(struct clk_core *core,
1181                                            struct clk_rate_request *req)
1182 {
1183         long rate;
1184
1185         lockdep_assert_held(&prepare_lock);
1186
1187         if (!core)
1188                 return 0;
1189
1190         /*
1191          * At this point, core protection will be disabled if
1192          * - if the provider is not protected at all
1193          * - if the calling consumer is the only one which has exclusivity
1194          *   over the provider
1195          */
1196         if (clk_core_rate_is_protected(core)) {
1197                 req->rate = core->rate;
1198         } else if (core->ops->determine_rate) {
1199                 return core->ops->determine_rate(core->hw, req);
1200         } else if (core->ops->round_rate) {
1201                 rate = core->ops->round_rate(core->hw, req->rate,
1202                                              &req->best_parent_rate);
1203                 if (rate < 0)
1204                         return rate;
1205
1206                 req->rate = rate;
1207         } else {
1208                 return -EINVAL;
1209         }
1210
1211         return 0;
1212 }
1213
1214 static void clk_core_init_rate_req(struct clk_core * const core,
1215                                    struct clk_rate_request *req)
1216 {
1217         struct clk_core *parent;
1218
1219         if (WARN_ON(!core || !req))
1220                 return;
1221
1222         parent = core->parent;
1223         if (parent) {
1224                 req->best_parent_hw = parent->hw;
1225                 req->best_parent_rate = parent->rate;
1226         } else {
1227                 req->best_parent_hw = NULL;
1228                 req->best_parent_rate = 0;
1229         }
1230 }
1231
1232 static bool clk_core_can_round(struct clk_core * const core)
1233 {
1234         if (core->ops->determine_rate || core->ops->round_rate)
1235                 return true;
1236
1237         return false;
1238 }
1239
1240 static int clk_core_round_rate_nolock(struct clk_core *core,
1241                                       struct clk_rate_request *req)
1242 {
1243         lockdep_assert_held(&prepare_lock);
1244
1245         if (!core) {
1246                 req->rate = 0;
1247                 return 0;
1248         }
1249
1250         clk_core_init_rate_req(core, req);
1251
1252         if (clk_core_can_round(core))
1253                 return clk_core_determine_round_nolock(core, req);
1254         else if (core->flags & CLK_SET_RATE_PARENT)
1255                 return clk_core_round_rate_nolock(core->parent, req);
1256
1257         req->rate = core->rate;
1258         return 0;
1259 }
1260
1261 /**
1262  * __clk_determine_rate - get the closest rate actually supported by a clock
1263  * @hw: determine the rate of this clock
1264  * @req: target rate request
1265  *
1266  * Useful for clk_ops such as .set_rate and .determine_rate.
1267  */
1268 int __clk_determine_rate(struct clk_hw *hw, struct clk_rate_request *req)
1269 {
1270         if (!hw) {
1271                 req->rate = 0;
1272                 return 0;
1273         }
1274
1275         return clk_core_round_rate_nolock(hw->core, req);
1276 }
1277 EXPORT_SYMBOL_GPL(__clk_determine_rate);
1278
1279 unsigned long clk_hw_round_rate(struct clk_hw *hw, unsigned long rate)
1280 {
1281         int ret;
1282         struct clk_rate_request req;
1283
1284         clk_core_get_boundaries(hw->core, &req.min_rate, &req.max_rate);
1285         req.rate = rate;
1286
1287         ret = clk_core_round_rate_nolock(hw->core, &req);
1288         if (ret)
1289                 return 0;
1290
1291         return req.rate;
1292 }
1293 EXPORT_SYMBOL_GPL(clk_hw_round_rate);
1294
1295 /**
1296  * clk_round_rate - round the given rate for a clk
1297  * @clk: the clk for which we are rounding a rate
1298  * @rate: the rate which is to be rounded
1299  *
1300  * Takes in a rate as input and rounds it to a rate that the clk can actually
1301  * use which is then returned.  If clk doesn't support round_rate operation
1302  * then the parent rate is returned.
1303  */
1304 long clk_round_rate(struct clk *clk, unsigned long rate)
1305 {
1306         struct clk_rate_request req;
1307         int ret;
1308
1309         if (!clk)
1310                 return 0;
1311
1312         clk_prepare_lock();
1313
1314         if (clk->exclusive_count)
1315                 clk_core_rate_unprotect(clk->core);
1316
1317         clk_core_get_boundaries(clk->core, &req.min_rate, &req.max_rate);
1318         req.rate = rate;
1319
1320         ret = clk_core_round_rate_nolock(clk->core, &req);
1321
1322         if (clk->exclusive_count)
1323                 clk_core_rate_protect(clk->core);
1324
1325         clk_prepare_unlock();
1326
1327         if (ret)
1328                 return ret;
1329
1330         return req.rate;
1331 }
1332 EXPORT_SYMBOL_GPL(clk_round_rate);
1333
1334 /**
1335  * __clk_notify - call clk notifier chain
1336  * @core: clk that is changing rate
1337  * @msg: clk notifier type (see include/linux/clk.h)
1338  * @old_rate: old clk rate
1339  * @new_rate: new clk rate
1340  *
1341  * Triggers a notifier call chain on the clk rate-change notification
1342  * for 'clk'.  Passes a pointer to the struct clk and the previous
1343  * and current rates to the notifier callback.  Intended to be called by
1344  * internal clock code only.  Returns NOTIFY_DONE from the last driver
1345  * called if all went well, or NOTIFY_STOP or NOTIFY_BAD immediately if
1346  * a driver returns that.
1347  */
1348 static int __clk_notify(struct clk_core *core, unsigned long msg,
1349                 unsigned long old_rate, unsigned long new_rate)
1350 {
1351         struct clk_notifier *cn;
1352         struct clk_notifier_data cnd;
1353         int ret = NOTIFY_DONE;
1354
1355         cnd.old_rate = old_rate;
1356         cnd.new_rate = new_rate;
1357
1358         list_for_each_entry(cn, &clk_notifier_list, node) {
1359                 if (cn->clk->core == core) {
1360                         cnd.clk = cn->clk;
1361                         ret = srcu_notifier_call_chain(&cn->notifier_head, msg,
1362                                         &cnd);
1363                         if (ret & NOTIFY_STOP_MASK)
1364                                 return ret;
1365                 }
1366         }
1367
1368         return ret;
1369 }
1370
1371 /**
1372  * __clk_recalc_accuracies
1373  * @core: first clk in the subtree
1374  *
1375  * Walks the subtree of clks starting with clk and recalculates accuracies as
1376  * it goes.  Note that if a clk does not implement the .recalc_accuracy
1377  * callback then it is assumed that the clock will take on the accuracy of its
1378  * parent.
1379  */
1380 static void __clk_recalc_accuracies(struct clk_core *core)
1381 {
1382         unsigned long parent_accuracy = 0;
1383         struct clk_core *child;
1384
1385         lockdep_assert_held(&prepare_lock);
1386
1387         if (core->parent)
1388                 parent_accuracy = core->parent->accuracy;
1389
1390         if (core->ops->recalc_accuracy)
1391                 core->accuracy = core->ops->recalc_accuracy(core->hw,
1392                                                           parent_accuracy);
1393         else
1394                 core->accuracy = parent_accuracy;
1395
1396         hlist_for_each_entry(child, &core->children, child_node)
1397                 __clk_recalc_accuracies(child);
1398 }
1399
1400 static long clk_core_get_accuracy(struct clk_core *core)
1401 {
1402         unsigned long accuracy;
1403
1404         clk_prepare_lock();
1405         if (core && (core->flags & CLK_GET_ACCURACY_NOCACHE))
1406                 __clk_recalc_accuracies(core);
1407
1408         accuracy = __clk_get_accuracy(core);
1409         clk_prepare_unlock();
1410
1411         return accuracy;
1412 }
1413
1414 /**
1415  * clk_get_accuracy - return the accuracy of clk
1416  * @clk: the clk whose accuracy is being returned
1417  *
1418  * Simply returns the cached accuracy of the clk, unless
1419  * CLK_GET_ACCURACY_NOCACHE flag is set, which means a recalc_rate will be
1420  * issued.
1421  * If clk is NULL then returns 0.
1422  */
1423 long clk_get_accuracy(struct clk *clk)
1424 {
1425         if (!clk)
1426                 return 0;
1427
1428         return clk_core_get_accuracy(clk->core);
1429 }
1430 EXPORT_SYMBOL_GPL(clk_get_accuracy);
1431
1432 static unsigned long clk_recalc(struct clk_core *core,
1433                                 unsigned long parent_rate)
1434 {
1435         unsigned long rate = parent_rate;
1436
1437         if (core->ops->recalc_rate && !clk_pm_runtime_get(core)) {
1438                 rate = core->ops->recalc_rate(core->hw, parent_rate);
1439                 clk_pm_runtime_put(core);
1440         }
1441         return rate;
1442 }
1443
1444 /**
1445  * __clk_recalc_rates
1446  * @core: first clk in the subtree
1447  * @msg: notification type (see include/linux/clk.h)
1448  *
1449  * Walks the subtree of clks starting with clk and recalculates rates as it
1450  * goes.  Note that if a clk does not implement the .recalc_rate callback then
1451  * it is assumed that the clock will take on the rate of its parent.
1452  *
1453  * clk_recalc_rates also propagates the POST_RATE_CHANGE notification,
1454  * if necessary.
1455  */
1456 static void __clk_recalc_rates(struct clk_core *core, unsigned long msg)
1457 {
1458         unsigned long old_rate;
1459         unsigned long parent_rate = 0;
1460         struct clk_core *child;
1461
1462         lockdep_assert_held(&prepare_lock);
1463
1464         old_rate = core->rate;
1465
1466         if (core->parent)
1467                 parent_rate = core->parent->rate;
1468
1469         core->rate = clk_recalc(core, parent_rate);
1470
1471         /*
1472          * ignore NOTIFY_STOP and NOTIFY_BAD return values for POST_RATE_CHANGE
1473          * & ABORT_RATE_CHANGE notifiers
1474          */
1475         if (core->notifier_count && msg)
1476                 __clk_notify(core, msg, old_rate, core->rate);
1477
1478         hlist_for_each_entry(child, &core->children, child_node)
1479                 __clk_recalc_rates(child, msg);
1480 }
1481
1482 static unsigned long clk_core_get_rate(struct clk_core *core)
1483 {
1484         unsigned long rate;
1485
1486         clk_prepare_lock();
1487
1488         if (core && (core->flags & CLK_GET_RATE_NOCACHE))
1489                 __clk_recalc_rates(core, 0);
1490
1491         rate = clk_core_get_rate_nolock(core);
1492         clk_prepare_unlock();
1493
1494         return rate;
1495 }
1496
1497 /**
1498  * clk_get_rate - return the rate of clk
1499  * @clk: the clk whose rate is being returned
1500  *
1501  * Simply returns the cached rate of the clk, unless CLK_GET_RATE_NOCACHE flag
1502  * is set, which means a recalc_rate will be issued.
1503  * If clk is NULL then returns 0.
1504  */
1505 unsigned long clk_get_rate(struct clk *clk)
1506 {
1507         if (!clk)
1508                 return 0;
1509
1510         return clk_core_get_rate(clk->core);
1511 }
1512 EXPORT_SYMBOL_GPL(clk_get_rate);
1513
1514 static int clk_fetch_parent_index(struct clk_core *core,
1515                                   struct clk_core *parent)
1516 {
1517         int i;
1518
1519         if (!parent)
1520                 return -EINVAL;
1521
1522         for (i = 0; i < core->num_parents; i++) {
1523                 if (core->parents[i] == parent)
1524                         return i;
1525
1526                 if (core->parents[i])
1527                         continue;
1528
1529                 /* Fallback to comparing globally unique names */
1530                 if (!strcmp(parent->name, core->parent_names[i])) {
1531                         core->parents[i] = parent;
1532                         return i;
1533                 }
1534         }
1535
1536         return -EINVAL;
1537 }
1538
1539 /*
1540  * Update the orphan status of @core and all its children.
1541  */
1542 static void clk_core_update_orphan_status(struct clk_core *core, bool is_orphan)
1543 {
1544         struct clk_core *child;
1545
1546         core->orphan = is_orphan;
1547
1548         hlist_for_each_entry(child, &core->children, child_node)
1549                 clk_core_update_orphan_status(child, is_orphan);
1550 }
1551
1552 static void clk_reparent(struct clk_core *core, struct clk_core *new_parent)
1553 {
1554         bool was_orphan = core->orphan;
1555
1556         hlist_del(&core->child_node);
1557
1558         if (new_parent) {
1559                 bool becomes_orphan = new_parent->orphan;
1560
1561                 /* avoid duplicate POST_RATE_CHANGE notifications */
1562                 if (new_parent->new_child == core)
1563                         new_parent->new_child = NULL;
1564
1565                 hlist_add_head(&core->child_node, &new_parent->children);
1566
1567                 if (was_orphan != becomes_orphan)
1568                         clk_core_update_orphan_status(core, becomes_orphan);
1569         } else {
1570                 hlist_add_head(&core->child_node, &clk_orphan_list);
1571                 if (!was_orphan)
1572                         clk_core_update_orphan_status(core, true);
1573         }
1574
1575         core->parent = new_parent;
1576 }
1577
1578 static struct clk_core *__clk_set_parent_before(struct clk_core *core,
1579                                            struct clk_core *parent)
1580 {
1581         unsigned long flags;
1582         struct clk_core *old_parent = core->parent;
1583
1584         /*
1585          * 1. enable parents for CLK_OPS_PARENT_ENABLE clock
1586          *
1587          * 2. Migrate prepare state between parents and prevent race with
1588          * clk_enable().
1589          *
1590          * If the clock is not prepared, then a race with
1591          * clk_enable/disable() is impossible since we already have the
1592          * prepare lock (future calls to clk_enable() need to be preceded by
1593          * a clk_prepare()).
1594          *
1595          * If the clock is prepared, migrate the prepared state to the new
1596          * parent and also protect against a race with clk_enable() by
1597          * forcing the clock and the new parent on.  This ensures that all
1598          * future calls to clk_enable() are practically NOPs with respect to
1599          * hardware and software states.
1600          *
1601          * See also: Comment for clk_set_parent() below.
1602          */
1603
1604         /* enable old_parent & parent if CLK_OPS_PARENT_ENABLE is set */
1605         if (core->flags & CLK_OPS_PARENT_ENABLE) {
1606                 clk_core_prepare_enable(old_parent);
1607                 clk_core_prepare_enable(parent);
1608         }
1609
1610         /* migrate prepare count if > 0 */
1611         if (core->prepare_count) {
1612                 clk_core_prepare_enable(parent);
1613                 clk_core_enable_lock(core);
1614         }
1615
1616         /* update the clk tree topology */
1617         flags = clk_enable_lock();
1618         clk_reparent(core, parent);
1619         clk_enable_unlock(flags);
1620
1621         return old_parent;
1622 }
1623
1624 static void __clk_set_parent_after(struct clk_core *core,
1625                                    struct clk_core *parent,
1626                                    struct clk_core *old_parent)
1627 {
1628         /*
1629          * Finish the migration of prepare state and undo the changes done
1630          * for preventing a race with clk_enable().
1631          */
1632         if (core->prepare_count) {
1633                 clk_core_disable_lock(core);
1634                 clk_core_disable_unprepare(old_parent);
1635         }
1636
1637         /* re-balance ref counting if CLK_OPS_PARENT_ENABLE is set */
1638         if (core->flags & CLK_OPS_PARENT_ENABLE) {
1639                 clk_core_disable_unprepare(parent);
1640                 clk_core_disable_unprepare(old_parent);
1641         }
1642 }
1643
1644 static int __clk_set_parent(struct clk_core *core, struct clk_core *parent,
1645                             u8 p_index)
1646 {
1647         unsigned long flags;
1648         int ret = 0;
1649         struct clk_core *old_parent;
1650
1651         old_parent = __clk_set_parent_before(core, parent);
1652
1653         trace_clk_set_parent(core, parent);
1654
1655         /* change clock input source */
1656         if (parent && core->ops->set_parent)
1657                 ret = core->ops->set_parent(core->hw, p_index);
1658
1659         trace_clk_set_parent_complete(core, parent);
1660
1661         if (ret) {
1662                 flags = clk_enable_lock();
1663                 clk_reparent(core, old_parent);
1664                 clk_enable_unlock(flags);
1665                 __clk_set_parent_after(core, old_parent, parent);
1666
1667                 return ret;
1668         }
1669
1670         __clk_set_parent_after(core, parent, old_parent);
1671
1672         return 0;
1673 }
1674
1675 /**
1676  * __clk_speculate_rates
1677  * @core: first clk in the subtree
1678  * @parent_rate: the "future" rate of clk's parent
1679  *
1680  * Walks the subtree of clks starting with clk, speculating rates as it
1681  * goes and firing off PRE_RATE_CHANGE notifications as necessary.
1682  *
1683  * Unlike clk_recalc_rates, clk_speculate_rates exists only for sending
1684  * pre-rate change notifications and returns early if no clks in the
1685  * subtree have subscribed to the notifications.  Note that if a clk does not
1686  * implement the .recalc_rate callback then it is assumed that the clock will
1687  * take on the rate of its parent.
1688  */
1689 static int __clk_speculate_rates(struct clk_core *core,
1690                                  unsigned long parent_rate)
1691 {
1692         struct clk_core *child;
1693         unsigned long new_rate;
1694         int ret = NOTIFY_DONE;
1695
1696         lockdep_assert_held(&prepare_lock);
1697
1698         new_rate = clk_recalc(core, parent_rate);
1699
1700         /* abort rate change if a driver returns NOTIFY_BAD or NOTIFY_STOP */
1701         if (core->notifier_count)
1702                 ret = __clk_notify(core, PRE_RATE_CHANGE, core->rate, new_rate);
1703
1704         if (ret & NOTIFY_STOP_MASK) {
1705                 pr_debug("%s: clk notifier callback for clock %s aborted with error %d\n",
1706                                 __func__, core->name, ret);
1707                 goto out;
1708         }
1709
1710         hlist_for_each_entry(child, &core->children, child_node) {
1711                 ret = __clk_speculate_rates(child, new_rate);
1712                 if (ret & NOTIFY_STOP_MASK)
1713                         break;
1714         }
1715
1716 out:
1717         return ret;
1718 }
1719
1720 static void clk_calc_subtree(struct clk_core *core, unsigned long new_rate,
1721                              struct clk_core *new_parent, u8 p_index)
1722 {
1723         struct clk_core *child;
1724
1725         core->new_rate = new_rate;
1726         core->new_parent = new_parent;
1727         core->new_parent_index = p_index;
1728         /* include clk in new parent's PRE_RATE_CHANGE notifications */
1729         core->new_child = NULL;
1730         if (new_parent && new_parent != core->parent)
1731                 new_parent->new_child = core;
1732
1733         hlist_for_each_entry(child, &core->children, child_node) {
1734                 child->new_rate = clk_recalc(child, new_rate);
1735                 clk_calc_subtree(child, child->new_rate, NULL, 0);
1736         }
1737 }
1738
1739 /*
1740  * calculate the new rates returning the topmost clock that has to be
1741  * changed.
1742  */
1743 static struct clk_core *clk_calc_new_rates(struct clk_core *core,
1744                                            unsigned long rate)
1745 {
1746         struct clk_core *top = core;
1747         struct clk_core *old_parent, *parent;
1748         unsigned long best_parent_rate = 0;
1749         unsigned long new_rate;
1750         unsigned long min_rate;
1751         unsigned long max_rate;
1752         int p_index = 0;
1753         long ret;
1754
1755         /* sanity */
1756         if (IS_ERR_OR_NULL(core))
1757                 return NULL;
1758
1759         /* save parent rate, if it exists */
1760         parent = old_parent = core->parent;
1761         if (parent)
1762                 best_parent_rate = parent->rate;
1763
1764         clk_core_get_boundaries(core, &min_rate, &max_rate);
1765
1766         /* find the closest rate and parent clk/rate */
1767         if (clk_core_can_round(core)) {
1768                 struct clk_rate_request req;
1769
1770                 req.rate = rate;
1771                 req.min_rate = min_rate;
1772                 req.max_rate = max_rate;
1773
1774                 clk_core_init_rate_req(core, &req);
1775
1776                 ret = clk_core_determine_round_nolock(core, &req);
1777                 if (ret < 0)
1778                         return NULL;
1779
1780                 best_parent_rate = req.best_parent_rate;
1781                 new_rate = req.rate;
1782                 parent = req.best_parent_hw ? req.best_parent_hw->core : NULL;
1783
1784                 if (new_rate < min_rate || new_rate > max_rate)
1785                         return NULL;
1786         } else if (!parent || !(core->flags & CLK_SET_RATE_PARENT)) {
1787                 /* pass-through clock without adjustable parent */
1788                 core->new_rate = core->rate;
1789                 return NULL;
1790         } else {
1791                 /* pass-through clock with adjustable parent */
1792                 top = clk_calc_new_rates(parent, rate);
1793                 new_rate = parent->new_rate;
1794                 goto out;
1795         }
1796
1797         /* some clocks must be gated to change parent */
1798         if (parent != old_parent &&
1799             (core->flags & CLK_SET_PARENT_GATE) && core->prepare_count) {
1800                 pr_debug("%s: %s not gated but wants to reparent\n",
1801                          __func__, core->name);
1802                 return NULL;
1803         }
1804
1805         /* try finding the new parent index */
1806         if (parent && core->num_parents > 1) {
1807                 p_index = clk_fetch_parent_index(core, parent);
1808                 if (p_index < 0) {
1809                         pr_debug("%s: clk %s can not be parent of clk %s\n",
1810                                  __func__, parent->name, core->name);
1811                         return NULL;
1812                 }
1813         }
1814
1815         if ((core->flags & CLK_SET_RATE_PARENT) && parent &&
1816             best_parent_rate != parent->rate)
1817                 top = clk_calc_new_rates(parent, best_parent_rate);
1818
1819 out:
1820         clk_calc_subtree(core, new_rate, parent, p_index);
1821
1822         return top;
1823 }
1824
1825 /*
1826  * Notify about rate changes in a subtree. Always walk down the whole tree
1827  * so that in case of an error we can walk down the whole tree again and
1828  * abort the change.
1829  */
1830 static struct clk_core *clk_propagate_rate_change(struct clk_core *core,
1831                                                   unsigned long event)
1832 {
1833         struct clk_core *child, *tmp_clk, *fail_clk = NULL;
1834         int ret = NOTIFY_DONE;
1835
1836         if (core->rate == core->new_rate)
1837                 return NULL;
1838
1839         if (core->notifier_count) {
1840                 ret = __clk_notify(core, event, core->rate, core->new_rate);
1841                 if (ret & NOTIFY_STOP_MASK)
1842                         fail_clk = core;
1843         }
1844
1845         hlist_for_each_entry(child, &core->children, child_node) {
1846                 /* Skip children who will be reparented to another clock */
1847                 if (child->new_parent && child->new_parent != core)
1848                         continue;
1849                 tmp_clk = clk_propagate_rate_change(child, event);
1850                 if (tmp_clk)
1851                         fail_clk = tmp_clk;
1852         }
1853
1854         /* handle the new child who might not be in core->children yet */
1855         if (core->new_child) {
1856                 tmp_clk = clk_propagate_rate_change(core->new_child, event);
1857                 if (tmp_clk)
1858                         fail_clk = tmp_clk;
1859         }
1860
1861         return fail_clk;
1862 }
1863
1864 /*
1865  * walk down a subtree and set the new rates notifying the rate
1866  * change on the way
1867  */
1868 static void clk_change_rate(struct clk_core *core)
1869 {
1870         struct clk_core *child;
1871         struct hlist_node *tmp;
1872         unsigned long old_rate;
1873         unsigned long best_parent_rate = 0;
1874         bool skip_set_rate = false;
1875         struct clk_core *old_parent;
1876         struct clk_core *parent = NULL;
1877
1878         old_rate = core->rate;
1879
1880         if (core->new_parent) {
1881                 parent = core->new_parent;
1882                 best_parent_rate = core->new_parent->rate;
1883         } else if (core->parent) {
1884                 parent = core->parent;
1885                 best_parent_rate = core->parent->rate;
1886         }
1887
1888         if (clk_pm_runtime_get(core))
1889                 return;
1890
1891         if (core->flags & CLK_SET_RATE_UNGATE) {
1892                 unsigned long flags;
1893
1894                 clk_core_prepare(core);
1895                 flags = clk_enable_lock();
1896                 clk_core_enable(core);
1897                 clk_enable_unlock(flags);
1898         }
1899
1900         if (core->new_parent && core->new_parent != core->parent) {
1901                 old_parent = __clk_set_parent_before(core, core->new_parent);
1902                 trace_clk_set_parent(core, core->new_parent);
1903
1904                 if (core->ops->set_rate_and_parent) {
1905                         skip_set_rate = true;
1906                         core->ops->set_rate_and_parent(core->hw, core->new_rate,
1907                                         best_parent_rate,
1908                                         core->new_parent_index);
1909                 } else if (core->ops->set_parent) {
1910                         core->ops->set_parent(core->hw, core->new_parent_index);
1911                 }
1912
1913                 trace_clk_set_parent_complete(core, core->new_parent);
1914                 __clk_set_parent_after(core, core->new_parent, old_parent);
1915         }
1916
1917         if (core->flags & CLK_OPS_PARENT_ENABLE)
1918                 clk_core_prepare_enable(parent);
1919
1920         trace_clk_set_rate(core, core->new_rate);
1921
1922         if (!skip_set_rate && core->ops->set_rate)
1923                 core->ops->set_rate(core->hw, core->new_rate, best_parent_rate);
1924
1925         trace_clk_set_rate_complete(core, core->new_rate);
1926
1927         core->rate = clk_recalc(core, best_parent_rate);
1928
1929         if (core->flags & CLK_SET_RATE_UNGATE) {
1930                 unsigned long flags;
1931
1932                 flags = clk_enable_lock();
1933                 clk_core_disable(core);
1934                 clk_enable_unlock(flags);
1935                 clk_core_unprepare(core);
1936         }
1937
1938         if (core->flags & CLK_OPS_PARENT_ENABLE)
1939                 clk_core_disable_unprepare(parent);
1940
1941         if (core->notifier_count && old_rate != core->rate)
1942                 __clk_notify(core, POST_RATE_CHANGE, old_rate, core->rate);
1943
1944         if (core->flags & CLK_RECALC_NEW_RATES)
1945                 (void)clk_calc_new_rates(core, core->new_rate);
1946
1947         /*
1948          * Use safe iteration, as change_rate can actually swap parents
1949          * for certain clock types.
1950          */
1951         hlist_for_each_entry_safe(child, tmp, &core->children, child_node) {
1952                 /* Skip children who will be reparented to another clock */
1953                 if (child->new_parent && child->new_parent != core)
1954                         continue;
1955                 clk_change_rate(child);
1956         }
1957
1958         /* handle the new child who might not be in core->children yet */
1959         if (core->new_child)
1960                 clk_change_rate(core->new_child);
1961
1962         clk_pm_runtime_put(core);
1963 }
1964
1965 static unsigned long clk_core_req_round_rate_nolock(struct clk_core *core,
1966                                                      unsigned long req_rate)
1967 {
1968         int ret, cnt;
1969         struct clk_rate_request req;
1970
1971         lockdep_assert_held(&prepare_lock);
1972
1973         if (!core)
1974                 return 0;
1975
1976         /* simulate what the rate would be if it could be freely set */
1977         cnt = clk_core_rate_nuke_protect(core);
1978         if (cnt < 0)
1979                 return cnt;
1980
1981         clk_core_get_boundaries(core, &req.min_rate, &req.max_rate);
1982         req.rate = req_rate;
1983
1984         ret = clk_core_round_rate_nolock(core, &req);
1985
1986         /* restore the protection */
1987         clk_core_rate_restore_protect(core, cnt);
1988
1989         return ret ? 0 : req.rate;
1990 }
1991
1992 static int clk_core_set_rate_nolock(struct clk_core *core,
1993                                     unsigned long req_rate)
1994 {
1995         struct clk_core *top, *fail_clk;
1996         unsigned long rate;
1997         int ret = 0;
1998
1999         if (!core)
2000                 return 0;
2001
2002         rate = clk_core_req_round_rate_nolock(core, req_rate);
2003
2004         /* bail early if nothing to do */
2005         if (rate == clk_core_get_rate_nolock(core))
2006                 return 0;
2007
2008         /* fail on a direct rate set of a protected provider */
2009         if (clk_core_rate_is_protected(core))
2010                 return -EBUSY;
2011
2012         /* calculate new rates and get the topmost changed clock */
2013         top = clk_calc_new_rates(core, req_rate);
2014         if (!top)
2015                 return -EINVAL;
2016
2017         ret = clk_pm_runtime_get(core);
2018         if (ret)
2019                 return ret;
2020
2021         /* notify that we are about to change rates */
2022         fail_clk = clk_propagate_rate_change(top, PRE_RATE_CHANGE);
2023         if (fail_clk) {
2024                 pr_debug("%s: failed to set %s rate\n", __func__,
2025                                 fail_clk->name);
2026                 clk_propagate_rate_change(top, ABORT_RATE_CHANGE);
2027                 ret = -EBUSY;
2028                 goto err;
2029         }
2030
2031         /* change the rates */
2032         clk_change_rate(top);
2033
2034         core->req_rate = req_rate;
2035 err:
2036         clk_pm_runtime_put(core);
2037
2038         return ret;
2039 }
2040
2041 /**
2042  * clk_set_rate - specify a new rate for clk
2043  * @clk: the clk whose rate is being changed
2044  * @rate: the new rate for clk
2045  *
2046  * In the simplest case clk_set_rate will only adjust the rate of clk.
2047  *
2048  * Setting the CLK_SET_RATE_PARENT flag allows the rate change operation to
2049  * propagate up to clk's parent; whether or not this happens depends on the
2050  * outcome of clk's .round_rate implementation.  If *parent_rate is unchanged
2051  * after calling .round_rate then upstream parent propagation is ignored.  If
2052  * *parent_rate comes back with a new rate for clk's parent then we propagate
2053  * up to clk's parent and set its rate.  Upward propagation will continue
2054  * until either a clk does not support the CLK_SET_RATE_PARENT flag or
2055  * .round_rate stops requesting changes to clk's parent_rate.
2056  *
2057  * Rate changes are accomplished via tree traversal that also recalculates the
2058  * rates for the clocks and fires off POST_RATE_CHANGE notifiers.
2059  *
2060  * Returns 0 on success, -EERROR otherwise.
2061  */
2062 int clk_set_rate(struct clk *clk, unsigned long rate)
2063 {
2064         int ret;
2065
2066         if (!clk)
2067                 return 0;
2068
2069         /* prevent racing with updates to the clock topology */
2070         clk_prepare_lock();
2071
2072         if (clk->exclusive_count)
2073                 clk_core_rate_unprotect(clk->core);
2074
2075         ret = clk_core_set_rate_nolock(clk->core, rate);
2076
2077         if (clk->exclusive_count)
2078                 clk_core_rate_protect(clk->core);
2079
2080         clk_prepare_unlock();
2081
2082         return ret;
2083 }
2084 EXPORT_SYMBOL_GPL(clk_set_rate);
2085
2086 /**
2087  * clk_set_rate_exclusive - specify a new rate get exclusive control
2088  * @clk: the clk whose rate is being changed
2089  * @rate: the new rate for clk
2090  *
2091  * This is a combination of clk_set_rate() and clk_rate_exclusive_get()
2092  * within a critical section
2093  *
2094  * This can be used initially to ensure that at least 1 consumer is
2095  * statisfied when several consumers are competing for exclusivity over the
2096  * same clock provider.
2097  *
2098  * The exclusivity is not applied if setting the rate failed.
2099  *
2100  * Calls to clk_rate_exclusive_get() should be balanced with calls to
2101  * clk_rate_exclusive_put().
2102  *
2103  * Returns 0 on success, -EERROR otherwise.
2104  */
2105 int clk_set_rate_exclusive(struct clk *clk, unsigned long rate)
2106 {
2107         int ret;
2108
2109         if (!clk)
2110                 return 0;
2111
2112         /* prevent racing with updates to the clock topology */
2113         clk_prepare_lock();
2114
2115         /*
2116          * The temporary protection removal is not here, on purpose
2117          * This function is meant to be used instead of clk_rate_protect,
2118          * so before the consumer code path protect the clock provider
2119          */
2120
2121         ret = clk_core_set_rate_nolock(clk->core, rate);
2122         if (!ret) {
2123                 clk_core_rate_protect(clk->core);
2124                 clk->exclusive_count++;
2125         }
2126
2127         clk_prepare_unlock();
2128
2129         return ret;
2130 }
2131 EXPORT_SYMBOL_GPL(clk_set_rate_exclusive);
2132
2133 /**
2134  * clk_set_rate_range - set a rate range for a clock source
2135  * @clk: clock source
2136  * @min: desired minimum clock rate in Hz, inclusive
2137  * @max: desired maximum clock rate in Hz, inclusive
2138  *
2139  * Returns success (0) or negative errno.
2140  */
2141 int clk_set_rate_range(struct clk *clk, unsigned long min, unsigned long max)
2142 {
2143         int ret = 0;
2144         unsigned long old_min, old_max, rate;
2145
2146         if (!clk)
2147                 return 0;
2148
2149         if (min > max) {
2150                 pr_err("%s: clk %s dev %s con %s: invalid range [%lu, %lu]\n",
2151                        __func__, clk->core->name, clk->dev_id, clk->con_id,
2152                        min, max);
2153                 return -EINVAL;
2154         }
2155
2156         clk_prepare_lock();
2157
2158         if (clk->exclusive_count)
2159                 clk_core_rate_unprotect(clk->core);
2160
2161         /* Save the current values in case we need to rollback the change */
2162         old_min = clk->min_rate;
2163         old_max = clk->max_rate;
2164         clk->min_rate = min;
2165         clk->max_rate = max;
2166
2167         rate = clk_core_get_rate_nolock(clk->core);
2168         if (rate < min || rate > max) {
2169                 /*
2170                  * FIXME:
2171                  * We are in bit of trouble here, current rate is outside the
2172                  * the requested range. We are going try to request appropriate
2173                  * range boundary but there is a catch. It may fail for the
2174                  * usual reason (clock broken, clock protected, etc) but also
2175                  * because:
2176                  * - round_rate() was not favorable and fell on the wrong
2177                  *   side of the boundary
2178                  * - the determine_rate() callback does not really check for
2179                  *   this corner case when determining the rate
2180                  */
2181
2182                 if (rate < min)
2183                         rate = min;
2184                 else
2185                         rate = max;
2186
2187                 ret = clk_core_set_rate_nolock(clk->core, rate);
2188                 if (ret) {
2189                         /* rollback the changes */
2190                         clk->min_rate = old_min;
2191                         clk->max_rate = old_max;
2192                 }
2193         }
2194
2195         if (clk->exclusive_count)
2196                 clk_core_rate_protect(clk->core);
2197
2198         clk_prepare_unlock();
2199
2200         return ret;
2201 }
2202 EXPORT_SYMBOL_GPL(clk_set_rate_range);
2203
2204 /**
2205  * clk_set_min_rate - set a minimum clock rate for a clock source
2206  * @clk: clock source
2207  * @rate: desired minimum clock rate in Hz, inclusive
2208  *
2209  * Returns success (0) or negative errno.
2210  */
2211 int clk_set_min_rate(struct clk *clk, unsigned long rate)
2212 {
2213         if (!clk)
2214                 return 0;
2215
2216         return clk_set_rate_range(clk, rate, clk->max_rate);
2217 }
2218 EXPORT_SYMBOL_GPL(clk_set_min_rate);
2219
2220 /**
2221  * clk_set_max_rate - set a maximum clock rate for a clock source
2222  * @clk: clock source
2223  * @rate: desired maximum clock rate in Hz, inclusive
2224  *
2225  * Returns success (0) or negative errno.
2226  */
2227 int clk_set_max_rate(struct clk *clk, unsigned long rate)
2228 {
2229         if (!clk)
2230                 return 0;
2231
2232         return clk_set_rate_range(clk, clk->min_rate, rate);
2233 }
2234 EXPORT_SYMBOL_GPL(clk_set_max_rate);
2235
2236 /**
2237  * clk_get_parent - return the parent of a clk
2238  * @clk: the clk whose parent gets returned
2239  *
2240  * Simply returns clk->parent.  Returns NULL if clk is NULL.
2241  */
2242 struct clk *clk_get_parent(struct clk *clk)
2243 {
2244         struct clk *parent;
2245
2246         if (!clk)
2247                 return NULL;
2248
2249         clk_prepare_lock();
2250         /* TODO: Create a per-user clk and change callers to call clk_put */
2251         parent = !clk->core->parent ? NULL : clk->core->parent->hw->clk;
2252         clk_prepare_unlock();
2253
2254         return parent;
2255 }
2256 EXPORT_SYMBOL_GPL(clk_get_parent);
2257
2258 static struct clk_core *__clk_init_parent(struct clk_core *core)
2259 {
2260         u8 index = 0;
2261
2262         if (core->num_parents > 1 && core->ops->get_parent)
2263                 index = core->ops->get_parent(core->hw);
2264
2265         return clk_core_get_parent_by_index(core, index);
2266 }
2267
2268 static void clk_core_reparent(struct clk_core *core,
2269                                   struct clk_core *new_parent)
2270 {
2271         clk_reparent(core, new_parent);
2272         __clk_recalc_accuracies(core);
2273         __clk_recalc_rates(core, POST_RATE_CHANGE);
2274 }
2275
2276 void clk_hw_reparent(struct clk_hw *hw, struct clk_hw *new_parent)
2277 {
2278         if (!hw)
2279                 return;
2280
2281         clk_core_reparent(hw->core, !new_parent ? NULL : new_parent->core);
2282 }
2283
2284 /**
2285  * clk_has_parent - check if a clock is a possible parent for another
2286  * @clk: clock source
2287  * @parent: parent clock source
2288  *
2289  * This function can be used in drivers that need to check that a clock can be
2290  * the parent of another without actually changing the parent.
2291  *
2292  * Returns true if @parent is a possible parent for @clk, false otherwise.
2293  */
2294 bool clk_has_parent(struct clk *clk, struct clk *parent)
2295 {
2296         struct clk_core *core, *parent_core;
2297
2298         /* NULL clocks should be nops, so return success if either is NULL. */
2299         if (!clk || !parent)
2300                 return true;
2301
2302         core = clk->core;
2303         parent_core = parent->core;
2304
2305         /* Optimize for the case where the parent is already the parent. */
2306         if (core->parent == parent_core)
2307                 return true;
2308
2309         return match_string(core->parent_names, core->num_parents,
2310                             parent_core->name) >= 0;
2311 }
2312 EXPORT_SYMBOL_GPL(clk_has_parent);
2313
2314 static int clk_core_set_parent_nolock(struct clk_core *core,
2315                                       struct clk_core *parent)
2316 {
2317         int ret = 0;
2318         int p_index = 0;
2319         unsigned long p_rate = 0;
2320
2321         lockdep_assert_held(&prepare_lock);
2322
2323         if (!core)
2324                 return 0;
2325
2326         if (core->parent == parent)
2327                 return 0;
2328
2329         /* verify ops for for multi-parent clks */
2330         if (core->num_parents > 1 && !core->ops->set_parent)
2331                 return -EPERM;
2332
2333         /* check that we are allowed to re-parent if the clock is in use */
2334         if ((core->flags & CLK_SET_PARENT_GATE) && core->prepare_count)
2335                 return -EBUSY;
2336
2337         if (clk_core_rate_is_protected(core))
2338                 return -EBUSY;
2339
2340         /* try finding the new parent index */
2341         if (parent) {
2342                 p_index = clk_fetch_parent_index(core, parent);
2343                 if (p_index < 0) {
2344                         pr_debug("%s: clk %s can not be parent of clk %s\n",
2345                                         __func__, parent->name, core->name);
2346                         return p_index;
2347                 }
2348                 p_rate = parent->rate;
2349         }
2350
2351         ret = clk_pm_runtime_get(core);
2352         if (ret)
2353                 return ret;
2354
2355         /* propagate PRE_RATE_CHANGE notifications */
2356         ret = __clk_speculate_rates(core, p_rate);
2357
2358         /* abort if a driver objects */
2359         if (ret & NOTIFY_STOP_MASK)
2360                 goto runtime_put;
2361
2362         /* do the re-parent */
2363         ret = __clk_set_parent(core, parent, p_index);
2364
2365         /* propagate rate an accuracy recalculation accordingly */
2366         if (ret) {
2367                 __clk_recalc_rates(core, ABORT_RATE_CHANGE);
2368         } else {
2369                 __clk_recalc_rates(core, POST_RATE_CHANGE);
2370                 __clk_recalc_accuracies(core);
2371         }
2372
2373 runtime_put:
2374         clk_pm_runtime_put(core);
2375
2376         return ret;
2377 }
2378
2379 /**
2380  * clk_set_parent - switch the parent of a mux clk
2381  * @clk: the mux clk whose input we are switching
2382  * @parent: the new input to clk
2383  *
2384  * Re-parent clk to use parent as its new input source.  If clk is in
2385  * prepared state, the clk will get enabled for the duration of this call. If
2386  * that's not acceptable for a specific clk (Eg: the consumer can't handle
2387  * that, the reparenting is glitchy in hardware, etc), use the
2388  * CLK_SET_PARENT_GATE flag to allow reparenting only when clk is unprepared.
2389  *
2390  * After successfully changing clk's parent clk_set_parent will update the
2391  * clk topology, sysfs topology and propagate rate recalculation via
2392  * __clk_recalc_rates.
2393  *
2394  * Returns 0 on success, -EERROR otherwise.
2395  */
2396 int clk_set_parent(struct clk *clk, struct clk *parent)
2397 {
2398         int ret;
2399
2400         if (!clk)
2401                 return 0;
2402
2403         clk_prepare_lock();
2404
2405         if (clk->exclusive_count)
2406                 clk_core_rate_unprotect(clk->core);
2407
2408         ret = clk_core_set_parent_nolock(clk->core,
2409                                          parent ? parent->core : NULL);
2410
2411         if (clk->exclusive_count)
2412                 clk_core_rate_protect(clk->core);
2413
2414         clk_prepare_unlock();
2415
2416         return ret;
2417 }
2418 EXPORT_SYMBOL_GPL(clk_set_parent);
2419
2420 static int clk_core_set_phase_nolock(struct clk_core *core, int degrees)
2421 {
2422         int ret = -EINVAL;
2423
2424         lockdep_assert_held(&prepare_lock);
2425
2426         if (!core)
2427                 return 0;
2428
2429         if (clk_core_rate_is_protected(core))
2430                 return -EBUSY;
2431
2432         trace_clk_set_phase(core, degrees);
2433
2434         if (core->ops->set_phase) {
2435                 ret = core->ops->set_phase(core->hw, degrees);
2436                 if (!ret)
2437                         core->phase = degrees;
2438         }
2439
2440         trace_clk_set_phase_complete(core, degrees);
2441
2442         return ret;
2443 }
2444
2445 /**
2446  * clk_set_phase - adjust the phase shift of a clock signal
2447  * @clk: clock signal source
2448  * @degrees: number of degrees the signal is shifted
2449  *
2450  * Shifts the phase of a clock signal by the specified
2451  * degrees. Returns 0 on success, -EERROR otherwise.
2452  *
2453  * This function makes no distinction about the input or reference
2454  * signal that we adjust the clock signal phase against. For example
2455  * phase locked-loop clock signal generators we may shift phase with
2456  * respect to feedback clock signal input, but for other cases the
2457  * clock phase may be shifted with respect to some other, unspecified
2458  * signal.
2459  *
2460  * Additionally the concept of phase shift does not propagate through
2461  * the clock tree hierarchy, which sets it apart from clock rates and
2462  * clock accuracy. A parent clock phase attribute does not have an
2463  * impact on the phase attribute of a child clock.
2464  */
2465 int clk_set_phase(struct clk *clk, int degrees)
2466 {
2467         int ret;
2468
2469         if (!clk)
2470                 return 0;
2471
2472         /* sanity check degrees */
2473         degrees %= 360;
2474         if (degrees < 0)
2475                 degrees += 360;
2476
2477         clk_prepare_lock();
2478
2479         if (clk->exclusive_count)
2480                 clk_core_rate_unprotect(clk->core);
2481
2482         ret = clk_core_set_phase_nolock(clk->core, degrees);
2483
2484         if (clk->exclusive_count)
2485                 clk_core_rate_protect(clk->core);
2486
2487         clk_prepare_unlock();
2488
2489         return ret;
2490 }
2491 EXPORT_SYMBOL_GPL(clk_set_phase);
2492
2493 static int clk_core_get_phase(struct clk_core *core)
2494 {
2495         int ret;
2496
2497         clk_prepare_lock();
2498         /* Always try to update cached phase if possible */
2499         if (core->ops->get_phase)
2500                 core->phase = core->ops->get_phase(core->hw);
2501         ret = core->phase;
2502         clk_prepare_unlock();
2503
2504         return ret;
2505 }
2506
2507 /**
2508  * clk_get_phase - return the phase shift of a clock signal
2509  * @clk: clock signal source
2510  *
2511  * Returns the phase shift of a clock node in degrees, otherwise returns
2512  * -EERROR.
2513  */
2514 int clk_get_phase(struct clk *clk)
2515 {
2516         if (!clk)
2517                 return 0;
2518
2519         return clk_core_get_phase(clk->core);
2520 }
2521 EXPORT_SYMBOL_GPL(clk_get_phase);
2522
2523 static void clk_core_reset_duty_cycle_nolock(struct clk_core *core)
2524 {
2525         /* Assume a default value of 50% */
2526         core->duty.num = 1;
2527         core->duty.den = 2;
2528 }
2529
2530 static int clk_core_update_duty_cycle_parent_nolock(struct clk_core *core);
2531
2532 static int clk_core_update_duty_cycle_nolock(struct clk_core *core)
2533 {
2534         struct clk_duty *duty = &core->duty;
2535         int ret = 0;
2536
2537         if (!core->ops->get_duty_cycle)
2538                 return clk_core_update_duty_cycle_parent_nolock(core);
2539
2540         ret = core->ops->get_duty_cycle(core->hw, duty);
2541         if (ret)
2542                 goto reset;
2543
2544         /* Don't trust the clock provider too much */
2545         if (duty->den == 0 || duty->num > duty->den) {
2546                 ret = -EINVAL;
2547                 goto reset;
2548         }
2549
2550         return 0;
2551
2552 reset:
2553         clk_core_reset_duty_cycle_nolock(core);
2554         return ret;
2555 }
2556
2557 static int clk_core_update_duty_cycle_parent_nolock(struct clk_core *core)
2558 {
2559         int ret = 0;
2560
2561         if (core->parent &&
2562             core->flags & CLK_DUTY_CYCLE_PARENT) {
2563                 ret = clk_core_update_duty_cycle_nolock(core->parent);
2564                 memcpy(&core->duty, &core->parent->duty, sizeof(core->duty));
2565         } else {
2566                 clk_core_reset_duty_cycle_nolock(core);
2567         }
2568
2569         return ret;
2570 }
2571
2572 static int clk_core_set_duty_cycle_parent_nolock(struct clk_core *core,
2573                                                  struct clk_duty *duty);
2574
2575 static int clk_core_set_duty_cycle_nolock(struct clk_core *core,
2576                                           struct clk_duty *duty)
2577 {
2578         int ret;
2579
2580         lockdep_assert_held(&prepare_lock);
2581
2582         if (clk_core_rate_is_protected(core))
2583                 return -EBUSY;
2584
2585         trace_clk_set_duty_cycle(core, duty);
2586
2587         if (!core->ops->set_duty_cycle)
2588                 return clk_core_set_duty_cycle_parent_nolock(core, duty);
2589
2590         ret = core->ops->set_duty_cycle(core->hw, duty);
2591         if (!ret)
2592                 memcpy(&core->duty, duty, sizeof(*duty));
2593
2594         trace_clk_set_duty_cycle_complete(core, duty);
2595
2596         return ret;
2597 }
2598
2599 static int clk_core_set_duty_cycle_parent_nolock(struct clk_core *core,
2600                                                  struct clk_duty *duty)
2601 {
2602         int ret = 0;
2603
2604         if (core->parent &&
2605             core->flags & (CLK_DUTY_CYCLE_PARENT | CLK_SET_RATE_PARENT)) {
2606                 ret = clk_core_set_duty_cycle_nolock(core->parent, duty);
2607                 memcpy(&core->duty, &core->parent->duty, sizeof(core->duty));
2608         }
2609
2610         return ret;
2611 }
2612
2613 /**
2614  * clk_set_duty_cycle - adjust the duty cycle ratio of a clock signal
2615  * @clk: clock signal source
2616  * @num: numerator of the duty cycle ratio to be applied
2617  * @den: denominator of the duty cycle ratio to be applied
2618  *
2619  * Apply the duty cycle ratio if the ratio is valid and the clock can
2620  * perform this operation
2621  *
2622  * Returns (0) on success, a negative errno otherwise.
2623  */
2624 int clk_set_duty_cycle(struct clk *clk, unsigned int num, unsigned int den)
2625 {
2626         int ret;
2627         struct clk_duty duty;
2628
2629         if (!clk)
2630                 return 0;
2631
2632         /* sanity check the ratio */
2633         if (den == 0 || num > den)
2634                 return -EINVAL;
2635
2636         duty.num = num;
2637         duty.den = den;
2638
2639         clk_prepare_lock();
2640
2641         if (clk->exclusive_count)
2642                 clk_core_rate_unprotect(clk->core);
2643
2644         ret = clk_core_set_duty_cycle_nolock(clk->core, &duty);
2645
2646         if (clk->exclusive_count)
2647                 clk_core_rate_protect(clk->core);
2648
2649         clk_prepare_unlock();
2650
2651         return ret;
2652 }
2653 EXPORT_SYMBOL_GPL(clk_set_duty_cycle);
2654
2655 static int clk_core_get_scaled_duty_cycle(struct clk_core *core,
2656                                           unsigned int scale)
2657 {
2658         struct clk_duty *duty = &core->duty;
2659         int ret;
2660
2661         clk_prepare_lock();
2662
2663         ret = clk_core_update_duty_cycle_nolock(core);
2664         if (!ret)
2665                 ret = mult_frac(scale, duty->num, duty->den);
2666
2667         clk_prepare_unlock();
2668
2669         return ret;
2670 }
2671
2672 /**
2673  * clk_get_scaled_duty_cycle - return the duty cycle ratio of a clock signal
2674  * @clk: clock signal source
2675  * @scale: scaling factor to be applied to represent the ratio as an integer
2676  *
2677  * Returns the duty cycle ratio of a clock node multiplied by the provided
2678  * scaling factor, or negative errno on error.
2679  */
2680 int clk_get_scaled_duty_cycle(struct clk *clk, unsigned int scale)
2681 {
2682         if (!clk)
2683                 return 0;
2684
2685         return clk_core_get_scaled_duty_cycle(clk->core, scale);
2686 }
2687 EXPORT_SYMBOL_GPL(clk_get_scaled_duty_cycle);
2688
2689 /**
2690  * clk_is_match - check if two clk's point to the same hardware clock
2691  * @p: clk compared against q
2692  * @q: clk compared against p
2693  *
2694  * Returns true if the two struct clk pointers both point to the same hardware
2695  * clock node. Put differently, returns true if struct clk *p and struct clk *q
2696  * share the same struct clk_core object.
2697  *
2698  * Returns false otherwise. Note that two NULL clks are treated as matching.
2699  */
2700 bool clk_is_match(const struct clk *p, const struct clk *q)
2701 {
2702         /* trivial case: identical struct clk's or both NULL */
2703         if (p == q)
2704                 return true;
2705
2706         /* true if clk->core pointers match. Avoid dereferencing garbage */
2707         if (!IS_ERR_OR_NULL(p) && !IS_ERR_OR_NULL(q))
2708                 if (p->core == q->core)
2709                         return true;
2710
2711         return false;
2712 }
2713 EXPORT_SYMBOL_GPL(clk_is_match);
2714
2715 /***        debugfs support        ***/
2716
2717 #ifdef CONFIG_DEBUG_FS
2718 #include <linux/debugfs.h>
2719
2720 static struct dentry *rootdir;
2721 static int inited = 0;
2722 static DEFINE_MUTEX(clk_debug_lock);
2723 static HLIST_HEAD(clk_debug_list);
2724
2725 static struct hlist_head *all_lists[] = {
2726         &clk_root_list,
2727         &clk_orphan_list,
2728         NULL,
2729 };
2730
2731 static struct hlist_head *orphan_list[] = {
2732         &clk_orphan_list,
2733         NULL,
2734 };
2735
2736 static void clk_summary_show_one(struct seq_file *s, struct clk_core *c,
2737                                  int level)
2738 {
2739         if (!c)
2740                 return;
2741
2742         seq_printf(s, "%*s%-*s %7d %8d %8d %11lu %10lu %5d %6d\n",
2743                    level * 3 + 1, "",
2744                    30 - level * 3, c->name,
2745                    c->enable_count, c->prepare_count, c->protect_count,
2746                    clk_core_get_rate(c), clk_core_get_accuracy(c),
2747                    clk_core_get_phase(c),
2748                    clk_core_get_scaled_duty_cycle(c, 100000));
2749 }
2750
2751 static void clk_summary_show_subtree(struct seq_file *s, struct clk_core *c,
2752                                      int level)
2753 {
2754         struct clk_core *child;
2755
2756         if (!c)
2757                 return;
2758
2759         clk_summary_show_one(s, c, level);
2760
2761         hlist_for_each_entry(child, &c->children, child_node)
2762                 clk_summary_show_subtree(s, child, level + 1);
2763 }
2764
2765 static int clk_summary_show(struct seq_file *s, void *data)
2766 {
2767         struct clk_core *c;
2768         struct hlist_head **lists = (struct hlist_head **)s->private;
2769
2770         seq_puts(s, "                                 enable  prepare  protect                                duty\n");
2771         seq_puts(s, "   clock                          count    count    count        rate   accuracy phase  cycle\n");
2772         seq_puts(s, "---------------------------------------------------------------------------------------------\n");
2773
2774         clk_prepare_lock();
2775
2776         for (; *lists; lists++)
2777                 hlist_for_each_entry(c, *lists, child_node)
2778                         clk_summary_show_subtree(s, c, 0);
2779
2780         clk_prepare_unlock();
2781
2782         return 0;
2783 }
2784 DEFINE_SHOW_ATTRIBUTE(clk_summary);
2785
2786 static void clk_dump_one(struct seq_file *s, struct clk_core *c, int level)
2787 {
2788         if (!c)
2789                 return;
2790
2791         /* This should be JSON format, i.e. elements separated with a comma */
2792         seq_printf(s, "\"%s\": { ", c->name);
2793         seq_printf(s, "\"enable_count\": %d,", c->enable_count);
2794         seq_printf(s, "\"prepare_count\": %d,", c->prepare_count);
2795         seq_printf(s, "\"protect_count\": %d,", c->protect_count);
2796         seq_printf(s, "\"rate\": %lu,", clk_core_get_rate(c));
2797         seq_printf(s, "\"accuracy\": %lu,", clk_core_get_accuracy(c));
2798         seq_printf(s, "\"phase\": %d,", clk_core_get_phase(c));
2799         seq_printf(s, "\"duty_cycle\": %u",
2800                    clk_core_get_scaled_duty_cycle(c, 100000));
2801 }
2802
2803 static void clk_dump_subtree(struct seq_file *s, struct clk_core *c, int level)
2804 {
2805         struct clk_core *child;
2806
2807         if (!c)
2808                 return;
2809
2810         clk_dump_one(s, c, level);
2811
2812         hlist_for_each_entry(child, &c->children, child_node) {
2813                 seq_putc(s, ',');
2814                 clk_dump_subtree(s, child, level + 1);
2815         }
2816
2817         seq_putc(s, '}');
2818 }
2819
2820 static int clk_dump_show(struct seq_file *s, void *data)
2821 {
2822         struct clk_core *c;
2823         bool first_node = true;
2824         struct hlist_head **lists = (struct hlist_head **)s->private;
2825
2826         seq_putc(s, '{');
2827         clk_prepare_lock();
2828
2829         for (; *lists; lists++) {
2830                 hlist_for_each_entry(c, *lists, child_node) {
2831                         if (!first_node)
2832                                 seq_putc(s, ',');
2833                         first_node = false;
2834                         clk_dump_subtree(s, c, 0);
2835                 }
2836         }
2837
2838         clk_prepare_unlock();
2839
2840         seq_puts(s, "}\n");
2841         return 0;
2842 }
2843 DEFINE_SHOW_ATTRIBUTE(clk_dump);
2844
2845 static const struct {
2846         unsigned long flag;
2847         const char *name;
2848 } clk_flags[] = {
2849 #define ENTRY(f) { f, #f }
2850         ENTRY(CLK_SET_RATE_GATE),
2851         ENTRY(CLK_SET_PARENT_GATE),
2852         ENTRY(CLK_SET_RATE_PARENT),
2853         ENTRY(CLK_IGNORE_UNUSED),
2854         ENTRY(CLK_IS_BASIC),
2855         ENTRY(CLK_GET_RATE_NOCACHE),
2856         ENTRY(CLK_SET_RATE_NO_REPARENT),
2857         ENTRY(CLK_GET_ACCURACY_NOCACHE),
2858         ENTRY(CLK_RECALC_NEW_RATES),
2859         ENTRY(CLK_SET_RATE_UNGATE),
2860         ENTRY(CLK_IS_CRITICAL),
2861         ENTRY(CLK_OPS_PARENT_ENABLE),
2862         ENTRY(CLK_DUTY_CYCLE_PARENT),
2863 #undef ENTRY
2864 };
2865
2866 static int clk_flags_show(struct seq_file *s, void *data)
2867 {
2868         struct clk_core *core = s->private;
2869         unsigned long flags = core->flags;
2870         unsigned int i;
2871
2872         for (i = 0; flags && i < ARRAY_SIZE(clk_flags); i++) {
2873                 if (flags & clk_flags[i].flag) {
2874                         seq_printf(s, "%s\n", clk_flags[i].name);
2875                         flags &= ~clk_flags[i].flag;
2876                 }
2877         }
2878         if (flags) {
2879                 /* Unknown flags */
2880                 seq_printf(s, "0x%lx\n", flags);
2881         }
2882
2883         return 0;
2884 }
2885 DEFINE_SHOW_ATTRIBUTE(clk_flags);
2886
2887 static int possible_parents_show(struct seq_file *s, void *data)
2888 {
2889         struct clk_core *core = s->private;
2890         int i;
2891
2892         for (i = 0; i < core->num_parents - 1; i++)
2893                 seq_printf(s, "%s ", core->parent_names[i]);
2894
2895         seq_printf(s, "%s\n", core->parent_names[i]);
2896
2897         return 0;
2898 }
2899 DEFINE_SHOW_ATTRIBUTE(possible_parents);
2900
2901 static int clk_duty_cycle_show(struct seq_file *s, void *data)
2902 {
2903         struct clk_core *core = s->private;
2904         struct clk_duty *duty = &core->duty;
2905
2906         seq_printf(s, "%u/%u\n", duty->num, duty->den);
2907
2908         return 0;
2909 }
2910 DEFINE_SHOW_ATTRIBUTE(clk_duty_cycle);
2911
2912 static void clk_debug_create_one(struct clk_core *core, struct dentry *pdentry)
2913 {
2914         struct dentry *root;
2915
2916         if (!core || !pdentry)
2917                 return;
2918
2919         root = debugfs_create_dir(core->name, pdentry);
2920         core->dentry = root;
2921
2922         debugfs_create_ulong("clk_rate", 0444, root, &core->rate);
2923         debugfs_create_ulong("clk_accuracy", 0444, root, &core->accuracy);
2924         debugfs_create_u32("clk_phase", 0444, root, &core->phase);
2925         debugfs_create_file("clk_flags", 0444, root, core, &clk_flags_fops);
2926         debugfs_create_u32("clk_prepare_count", 0444, root, &core->prepare_count);
2927         debugfs_create_u32("clk_enable_count", 0444, root, &core->enable_count);
2928         debugfs_create_u32("clk_protect_count", 0444, root, &core->protect_count);
2929         debugfs_create_u32("clk_notifier_count", 0444, root, &core->notifier_count);
2930         debugfs_create_file("clk_duty_cycle", 0444, root, core,
2931                             &clk_duty_cycle_fops);
2932
2933         if (core->num_parents > 1)
2934                 debugfs_create_file("clk_possible_parents", 0444, root, core,
2935                                     &possible_parents_fops);
2936
2937         if (core->ops->debug_init)
2938                 core->ops->debug_init(core->hw, core->dentry);
2939 }
2940
2941 /**
2942  * clk_debug_register - add a clk node to the debugfs clk directory
2943  * @core: the clk being added to the debugfs clk directory
2944  *
2945  * Dynamically adds a clk to the debugfs clk directory if debugfs has been
2946  * initialized.  Otherwise it bails out early since the debugfs clk directory
2947  * will be created lazily by clk_debug_init as part of a late_initcall.
2948  */
2949 static void clk_debug_register(struct clk_core *core)
2950 {
2951         mutex_lock(&clk_debug_lock);
2952         hlist_add_head(&core->debug_node, &clk_debug_list);
2953         if (inited)
2954                 clk_debug_create_one(core, rootdir);
2955         mutex_unlock(&clk_debug_lock);
2956 }
2957
2958  /**
2959  * clk_debug_unregister - remove a clk node from the debugfs clk directory
2960  * @core: the clk being removed from the debugfs clk directory
2961  *
2962  * Dynamically removes a clk and all its child nodes from the
2963  * debugfs clk directory if clk->dentry points to debugfs created by
2964  * clk_debug_register in __clk_core_init.
2965  */
2966 static void clk_debug_unregister(struct clk_core *core)
2967 {
2968         mutex_lock(&clk_debug_lock);
2969         hlist_del_init(&core->debug_node);
2970         debugfs_remove_recursive(core->dentry);
2971         core->dentry = NULL;
2972         mutex_unlock(&clk_debug_lock);
2973 }
2974
2975 /**
2976  * clk_debug_init - lazily populate the debugfs clk directory
2977  *
2978  * clks are often initialized very early during boot before memory can be
2979  * dynamically allocated and well before debugfs is setup. This function
2980  * populates the debugfs clk directory once at boot-time when we know that
2981  * debugfs is setup. It should only be called once at boot-time, all other clks
2982  * added dynamically will be done so with clk_debug_register.
2983  */
2984 static int __init clk_debug_init(void)
2985 {
2986         struct clk_core *core;
2987
2988         rootdir = debugfs_create_dir("clk", NULL);
2989
2990         debugfs_create_file("clk_summary", 0444, rootdir, &all_lists,
2991                             &clk_summary_fops);
2992         debugfs_create_file("clk_dump", 0444, rootdir, &all_lists,
2993                             &clk_dump_fops);
2994         debugfs_create_file("clk_orphan_summary", 0444, rootdir, &orphan_list,
2995                             &clk_summary_fops);
2996         debugfs_create_file("clk_orphan_dump", 0444, rootdir, &orphan_list,
2997                             &clk_dump_fops);
2998
2999         mutex_lock(&clk_debug_lock);
3000         hlist_for_each_entry(core, &clk_debug_list, debug_node)
3001                 clk_debug_create_one(core, rootdir);
3002
3003         inited = 1;
3004         mutex_unlock(&clk_debug_lock);
3005
3006         return 0;
3007 }
3008 late_initcall(clk_debug_init);
3009 #else
3010 static inline void clk_debug_register(struct clk_core *core) { }
3011 static inline void clk_debug_reparent(struct clk_core *core,
3012                                       struct clk_core *new_parent)
3013 {
3014 }
3015 static inline void clk_debug_unregister(struct clk_core *core)
3016 {
3017 }
3018 #endif
3019
3020 /**
3021  * __clk_core_init - initialize the data structures in a struct clk_core
3022  * @core:       clk_core being initialized
3023  *
3024  * Initializes the lists in struct clk_core, queries the hardware for the
3025  * parent and rate and sets them both.
3026  */
3027 static int __clk_core_init(struct clk_core *core)
3028 {
3029         int i, ret;
3030         struct clk_core *orphan;
3031         struct hlist_node *tmp2;
3032         unsigned long rate;
3033
3034         if (!core)
3035                 return -EINVAL;
3036
3037         clk_prepare_lock();
3038
3039         ret = clk_pm_runtime_get(core);
3040         if (ret)
3041                 goto unlock;
3042
3043         /* check to see if a clock with this name is already registered */
3044         if (clk_core_lookup(core->name)) {
3045                 pr_debug("%s: clk %s already initialized\n",
3046                                 __func__, core->name);
3047                 ret = -EEXIST;
3048                 goto out;
3049         }
3050
3051         /* check that clk_ops are sane.  See Documentation/driver-api/clk.rst */
3052         if (core->ops->set_rate &&
3053             !((core->ops->round_rate || core->ops->determine_rate) &&
3054               core->ops->recalc_rate)) {
3055                 pr_err("%s: %s must implement .round_rate or .determine_rate in addition to .recalc_rate\n",
3056                        __func__, core->name);
3057                 ret = -EINVAL;
3058                 goto out;
3059         }
3060
3061         if (core->ops->set_parent && !core->ops->get_parent) {
3062                 pr_err("%s: %s must implement .get_parent & .set_parent\n",
3063                        __func__, core->name);
3064                 ret = -EINVAL;
3065                 goto out;
3066         }
3067
3068         if (core->num_parents > 1 && !core->ops->get_parent) {
3069                 pr_err("%s: %s must implement .get_parent as it has multi parents\n",
3070                        __func__, core->name);
3071                 ret = -EINVAL;
3072                 goto out;
3073         }
3074
3075         if (core->ops->set_rate_and_parent &&
3076                         !(core->ops->set_parent && core->ops->set_rate)) {
3077                 pr_err("%s: %s must implement .set_parent & .set_rate\n",
3078                                 __func__, core->name);
3079                 ret = -EINVAL;
3080                 goto out;
3081         }
3082
3083         /* throw a WARN if any entries in parent_names are NULL */
3084         for (i = 0; i < core->num_parents; i++)
3085                 WARN(!core->parent_names[i],
3086                                 "%s: invalid NULL in %s's .parent_names\n",
3087                                 __func__, core->name);
3088
3089         core->parent = __clk_init_parent(core);
3090
3091         /*
3092          * Populate core->parent if parent has already been clk_core_init'd. If
3093          * parent has not yet been clk_core_init'd then place clk in the orphan
3094          * list.  If clk doesn't have any parents then place it in the root
3095          * clk list.
3096          *
3097          * Every time a new clk is clk_init'd then we walk the list of orphan
3098          * clocks and re-parent any that are children of the clock currently
3099          * being clk_init'd.
3100          */
3101         if (core->parent) {
3102                 hlist_add_head(&core->child_node,
3103                                 &core->parent->children);
3104                 core->orphan = core->parent->orphan;
3105         } else if (!core->num_parents) {
3106                 hlist_add_head(&core->child_node, &clk_root_list);
3107                 core->orphan = false;
3108         } else {
3109                 hlist_add_head(&core->child_node, &clk_orphan_list);
3110                 core->orphan = true;
3111         }
3112
3113         /*
3114          * optional platform-specific magic
3115          *
3116          * The .init callback is not used by any of the basic clock types, but
3117          * exists for weird hardware that must perform initialization magic.
3118          * Please consider other ways of solving initialization problems before
3119          * using this callback, as its use is discouraged.
3120          */
3121         if (core->ops->init)
3122                 core->ops->init(core->hw);
3123
3124         /*
3125          * Set clk's accuracy.  The preferred method is to use
3126          * .recalc_accuracy. For simple clocks and lazy developers the default
3127          * fallback is to use the parent's accuracy.  If a clock doesn't have a
3128          * parent (or is orphaned) then accuracy is set to zero (perfect
3129          * clock).
3130          */
3131         if (core->ops->recalc_accuracy)
3132                 core->accuracy = core->ops->recalc_accuracy(core->hw,
3133                                         __clk_get_accuracy(core->parent));
3134         else if (core->parent)
3135                 core->accuracy = core->parent->accuracy;
3136         else
3137                 core->accuracy = 0;
3138
3139         /*
3140          * Set clk's phase.
3141          * Since a phase is by definition relative to its parent, just
3142          * query the current clock phase, or just assume it's in phase.
3143          */
3144         if (core->ops->get_phase)
3145                 core->phase = core->ops->get_phase(core->hw);
3146         else
3147                 core->phase = 0;
3148
3149         /*
3150          * Set clk's duty cycle.
3151          */
3152         clk_core_update_duty_cycle_nolock(core);
3153
3154         /*
3155          * Set clk's rate.  The preferred method is to use .recalc_rate.  For
3156          * simple clocks and lazy developers the default fallback is to use the
3157          * parent's rate.  If a clock doesn't have a parent (or is orphaned)
3158          * then rate is set to zero.
3159          */
3160         if (core->ops->recalc_rate)
3161                 rate = core->ops->recalc_rate(core->hw,
3162                                 clk_core_get_rate_nolock(core->parent));
3163         else if (core->parent)
3164                 rate = core->parent->rate;
3165         else
3166                 rate = 0;
3167         core->rate = core->req_rate = rate;
3168
3169         /*
3170          * Enable CLK_IS_CRITICAL clocks so newly added critical clocks
3171          * don't get accidentally disabled when walking the orphan tree and
3172          * reparenting clocks
3173          */
3174         if (core->flags & CLK_IS_CRITICAL) {
3175                 unsigned long flags;
3176
3177                 clk_core_prepare(core);
3178
3179                 flags = clk_enable_lock();
3180                 clk_core_enable(core);
3181                 clk_enable_unlock(flags);
3182         }
3183
3184         /*
3185          * walk the list of orphan clocks and reparent any that newly finds a
3186          * parent.
3187          */
3188         hlist_for_each_entry_safe(orphan, tmp2, &clk_orphan_list, child_node) {
3189                 struct clk_core *parent = __clk_init_parent(orphan);
3190
3191                 /*
3192                  * We need to use __clk_set_parent_before() and _after() to
3193                  * to properly migrate any prepare/enable count of the orphan
3194                  * clock. This is important for CLK_IS_CRITICAL clocks, which
3195                  * are enabled during init but might not have a parent yet.
3196                  */
3197                 if (parent) {
3198                         /* update the clk tree topology */
3199                         __clk_set_parent_before(orphan, parent);
3200                         __clk_set_parent_after(orphan, parent, NULL);
3201                         __clk_recalc_accuracies(orphan);
3202                         __clk_recalc_rates(orphan, 0);
3203                 }
3204         }
3205
3206         kref_init(&core->ref);
3207 out:
3208         clk_pm_runtime_put(core);
3209 unlock:
3210         clk_prepare_unlock();
3211
3212         if (!ret)
3213                 clk_debug_register(core);
3214
3215         return ret;
3216 }
3217
3218 /**
3219  * clk_core_link_consumer - Add a clk consumer to the list of consumers in a clk_core
3220  * @core: clk to add consumer to
3221  * @clk: consumer to link to a clk
3222  */
3223 static void clk_core_link_consumer(struct clk_core *core, struct clk *clk)
3224 {
3225         clk_prepare_lock();
3226         hlist_add_head(&clk->clks_node, &core->clks);
3227         clk_prepare_unlock();
3228 }
3229
3230 /**
3231  * clk_core_unlink_consumer - Remove a clk consumer from the list of consumers in a clk_core
3232  * @clk: consumer to unlink
3233  */
3234 static void clk_core_unlink_consumer(struct clk *clk)
3235 {
3236         lockdep_assert_held(&prepare_lock);
3237         hlist_del(&clk->clks_node);
3238 }
3239
3240 /**
3241  * alloc_clk - Allocate a clk consumer, but leave it unlinked to the clk_core
3242  * @core: clk to allocate a consumer for
3243  * @dev_id: string describing device name
3244  * @con_id: connection ID string on device
3245  *
3246  * Returns: clk consumer left unlinked from the consumer list
3247  */
3248 static struct clk *alloc_clk(struct clk_core *core, const char *dev_id,
3249                              const char *con_id)
3250 {
3251         struct clk *clk;
3252
3253         clk = kzalloc(sizeof(*clk), GFP_KERNEL);
3254         if (!clk)
3255                 return ERR_PTR(-ENOMEM);
3256
3257         clk->core = core;
3258         clk->dev_id = dev_id;
3259         clk->con_id = kstrdup_const(con_id, GFP_KERNEL);
3260         clk->max_rate = ULONG_MAX;
3261
3262         return clk;
3263 }
3264
3265 /**
3266  * free_clk - Free a clk consumer
3267  * @clk: clk consumer to free
3268  *
3269  * Note, this assumes the clk has been unlinked from the clk_core consumer
3270  * list.
3271  */
3272 static void free_clk(struct clk *clk)
3273 {
3274         kfree_const(clk->con_id);
3275         kfree(clk);
3276 }
3277
3278 /**
3279  * clk_hw_create_clk: Allocate and link a clk consumer to a clk_core given
3280  * a clk_hw
3281  * @dev: clk consumer device
3282  * @hw: clk_hw associated with the clk being consumed
3283  * @dev_id: string describing device name
3284  * @con_id: connection ID string on device
3285  *
3286  * This is the main function used to create a clk pointer for use by clk
3287  * consumers. It connects a consumer to the clk_core and clk_hw structures
3288  * used by the framework and clk provider respectively.
3289  */
3290 struct clk *clk_hw_create_clk(struct device *dev, struct clk_hw *hw,
3291                               const char *dev_id, const char *con_id)
3292 {
3293         struct clk *clk;
3294         struct clk_core *core;
3295
3296         /* This is to allow this function to be chained to others */
3297         if (IS_ERR_OR_NULL(hw))
3298                 return ERR_CAST(hw);
3299
3300         core = hw->core;
3301         clk = alloc_clk(core, dev_id, con_id);
3302         if (IS_ERR(clk))
3303                 return clk;
3304         clk->dev = dev;
3305
3306         if (!try_module_get(core->owner)) {
3307                 free_clk(clk);
3308                 return ERR_PTR(-ENOENT);
3309         }
3310
3311         kref_get(&core->ref);
3312         clk_core_link_consumer(core, clk);
3313
3314         return clk;
3315 }
3316
3317 /**
3318  * clk_register - allocate a new clock, register it and return an opaque cookie
3319  * @dev: device that is registering this clock
3320  * @hw: link to hardware-specific clock data
3321  *
3322  * clk_register is the *deprecated* interface for populating the clock tree with
3323  * new clock nodes. Use clk_hw_register() instead.
3324  *
3325  * Returns: a pointer to the newly allocated struct clk which
3326  * cannot be dereferenced by driver code but may be used in conjunction with the
3327  * rest of the clock API.  In the event of an error clk_register will return an
3328  * error code; drivers must test for an error code after calling clk_register.
3329  */
3330 struct clk *clk_register(struct device *dev, struct clk_hw *hw)
3331 {
3332         int i, ret;
3333         struct clk_core *core;
3334
3335         core = kzalloc(sizeof(*core), GFP_KERNEL);
3336         if (!core) {
3337                 ret = -ENOMEM;
3338                 goto fail_out;
3339         }
3340
3341         core->name = kstrdup_const(hw->init->name, GFP_KERNEL);
3342         if (!core->name) {
3343                 ret = -ENOMEM;
3344                 goto fail_name;
3345         }
3346
3347         if (WARN_ON(!hw->init->ops)) {
3348                 ret = -EINVAL;
3349                 goto fail_ops;
3350         }
3351         core->ops = hw->init->ops;
3352
3353         if (dev && pm_runtime_enabled(dev))
3354                 core->rpm_enabled = true;
3355         core->dev = dev;
3356         if (dev && dev->driver)
3357                 core->owner = dev->driver->owner;
3358         core->hw = hw;
3359         core->flags = hw->init->flags;
3360         core->num_parents = hw->init->num_parents;
3361         core->min_rate = 0;
3362         core->max_rate = ULONG_MAX;
3363         hw->core = core;
3364
3365         /* allocate local copy in case parent_names is __initdata */
3366         core->parent_names = kcalloc(core->num_parents, sizeof(char *),
3367                                         GFP_KERNEL);
3368
3369         if (!core->parent_names) {
3370                 ret = -ENOMEM;
3371                 goto fail_parent_names;
3372         }
3373
3374
3375         /* copy each string name in case parent_names is __initdata */
3376         for (i = 0; i < core->num_parents; i++) {
3377                 core->parent_names[i] = kstrdup_const(hw->init->parent_names[i],
3378                                                 GFP_KERNEL);
3379                 if (!core->parent_names[i]) {
3380                         ret = -ENOMEM;
3381                         goto fail_parent_names_copy;
3382                 }
3383         }
3384
3385         /* avoid unnecessary string look-ups of clk_core's possible parents. */
3386         core->parents = kcalloc(core->num_parents, sizeof(*core->parents),
3387                                 GFP_KERNEL);
3388         if (!core->parents) {
3389                 ret = -ENOMEM;
3390                 goto fail_parents;
3391         };
3392
3393         INIT_HLIST_HEAD(&core->clks);
3394
3395         /*
3396          * Don't call clk_hw_create_clk() here because that would pin the
3397          * provider module to itself and prevent it from ever being removed.
3398          */
3399         hw->clk = alloc_clk(core, NULL, NULL);
3400         if (IS_ERR(hw->clk)) {
3401                 ret = PTR_ERR(hw->clk);
3402                 goto fail_parents;
3403         }
3404
3405         clk_core_link_consumer(hw->core, hw->clk);
3406
3407         ret = __clk_core_init(core);
3408         if (!ret)
3409                 return hw->clk;
3410
3411         clk_prepare_lock();
3412         clk_core_unlink_consumer(hw->clk);
3413         clk_prepare_unlock();
3414
3415         free_clk(hw->clk);
3416         hw->clk = NULL;
3417
3418 fail_parents:
3419         kfree(core->parents);
3420 fail_parent_names_copy:
3421         while (--i >= 0)
3422                 kfree_const(core->parent_names[i]);
3423         kfree(core->parent_names);
3424 fail_parent_names:
3425 fail_ops:
3426         kfree_const(core->name);
3427 fail_name:
3428         kfree(core);
3429 fail_out:
3430         return ERR_PTR(ret);
3431 }
3432 EXPORT_SYMBOL_GPL(clk_register);
3433
3434 /**
3435  * clk_hw_register - register a clk_hw and return an error code
3436  * @dev: device that is registering this clock
3437  * @hw: link to hardware-specific clock data
3438  *
3439  * clk_hw_register is the primary interface for populating the clock tree with
3440  * new clock nodes. It returns an integer equal to zero indicating success or
3441  * less than zero indicating failure. Drivers must test for an error code after
3442  * calling clk_hw_register().
3443  */
3444 int clk_hw_register(struct device *dev, struct clk_hw *hw)
3445 {
3446         return PTR_ERR_OR_ZERO(clk_register(dev, hw));
3447 }
3448 EXPORT_SYMBOL_GPL(clk_hw_register);
3449
3450 /* Free memory allocated for a clock. */
3451 static void __clk_release(struct kref *ref)
3452 {
3453         struct clk_core *core = container_of(ref, struct clk_core, ref);
3454         int i = core->num_parents;
3455
3456         lockdep_assert_held(&prepare_lock);
3457
3458         kfree(core->parents);
3459         while (--i >= 0)
3460                 kfree_const(core->parent_names[i]);
3461
3462         kfree(core->parent_names);
3463         kfree_const(core->name);
3464         kfree(core);
3465 }
3466
3467 /*
3468  * Empty clk_ops for unregistered clocks. These are used temporarily
3469  * after clk_unregister() was called on a clock and until last clock
3470  * consumer calls clk_put() and the struct clk object is freed.
3471  */
3472 static int clk_nodrv_prepare_enable(struct clk_hw *hw)
3473 {
3474         return -ENXIO;
3475 }
3476
3477 static void clk_nodrv_disable_unprepare(struct clk_hw *hw)
3478 {
3479         WARN_ON_ONCE(1);
3480 }
3481
3482 static int clk_nodrv_set_rate(struct clk_hw *hw, unsigned long rate,
3483                                         unsigned long parent_rate)
3484 {
3485         return -ENXIO;
3486 }
3487
3488 static int clk_nodrv_set_parent(struct clk_hw *hw, u8 index)
3489 {
3490         return -ENXIO;
3491 }
3492
3493 static const struct clk_ops clk_nodrv_ops = {
3494         .enable         = clk_nodrv_prepare_enable,
3495         .disable        = clk_nodrv_disable_unprepare,
3496         .prepare        = clk_nodrv_prepare_enable,
3497         .unprepare      = clk_nodrv_disable_unprepare,
3498         .set_rate       = clk_nodrv_set_rate,
3499         .set_parent     = clk_nodrv_set_parent,
3500 };
3501
3502 /**
3503  * clk_unregister - unregister a currently registered clock
3504  * @clk: clock to unregister
3505  */
3506 void clk_unregister(struct clk *clk)
3507 {
3508         unsigned long flags;
3509
3510         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
3511                 return;
3512
3513         clk_debug_unregister(clk->core);
3514
3515         clk_prepare_lock();
3516
3517         if (clk->core->ops == &clk_nodrv_ops) {
3518                 pr_err("%s: unregistered clock: %s\n", __func__,
3519                        clk->core->name);
3520                 goto unlock;
3521         }
3522         /*
3523          * Assign empty clock ops for consumers that might still hold
3524          * a reference to this clock.
3525          */
3526         flags = clk_enable_lock();
3527         clk->core->ops = &clk_nodrv_ops;
3528         clk_enable_unlock(flags);
3529
3530         if (!hlist_empty(&clk->core->children)) {
3531                 struct clk_core *child;
3532                 struct hlist_node *t;
3533
3534                 /* Reparent all children to the orphan list. */
3535                 hlist_for_each_entry_safe(child, t, &clk->core->children,
3536                                           child_node)
3537                         clk_core_set_parent_nolock(child, NULL);
3538         }
3539
3540         hlist_del_init(&clk->core->child_node);
3541
3542         if (clk->core->prepare_count)
3543                 pr_warn("%s: unregistering prepared clock: %s\n",
3544                                         __func__, clk->core->name);
3545
3546         if (clk->core->protect_count)
3547                 pr_warn("%s: unregistering protected clock: %s\n",
3548                                         __func__, clk->core->name);
3549
3550         kref_put(&clk->core->ref, __clk_release);
3551 unlock:
3552         clk_prepare_unlock();
3553 }
3554 EXPORT_SYMBOL_GPL(clk_unregister);
3555
3556 /**
3557  * clk_hw_unregister - unregister a currently registered clk_hw
3558  * @hw: hardware-specific clock data to unregister
3559  */
3560 void clk_hw_unregister(struct clk_hw *hw)
3561 {
3562         clk_unregister(hw->clk);
3563 }
3564 EXPORT_SYMBOL_GPL(clk_hw_unregister);
3565
3566 static void devm_clk_release(struct device *dev, void *res)
3567 {
3568         clk_unregister(*(struct clk **)res);
3569 }
3570
3571 static void devm_clk_hw_release(struct device *dev, void *res)
3572 {
3573         clk_hw_unregister(*(struct clk_hw **)res);
3574 }
3575
3576 /**
3577  * devm_clk_register - resource managed clk_register()
3578  * @dev: device that is registering this clock
3579  * @hw: link to hardware-specific clock data
3580  *
3581  * Managed clk_register(). This function is *deprecated*, use devm_clk_hw_register() instead.
3582  *
3583  * Clocks returned from this function are automatically clk_unregister()ed on
3584  * driver detach. See clk_register() for more information.
3585  */
3586 struct clk *devm_clk_register(struct device *dev, struct clk_hw *hw)
3587 {
3588         struct clk *clk;
3589         struct clk **clkp;
3590
3591         clkp = devres_alloc(devm_clk_release, sizeof(*clkp), GFP_KERNEL);
3592         if (!clkp)
3593                 return ERR_PTR(-ENOMEM);
3594
3595         clk = clk_register(dev, hw);
3596         if (!IS_ERR(clk)) {
3597                 *clkp = clk;
3598                 devres_add(dev, clkp);
3599         } else {
3600                 devres_free(clkp);
3601         }
3602
3603         return clk;
3604 }
3605 EXPORT_SYMBOL_GPL(devm_clk_register);
3606
3607 /**
3608  * devm_clk_hw_register - resource managed clk_hw_register()
3609  * @dev: device that is registering this clock
3610  * @hw: link to hardware-specific clock data
3611  *
3612  * Managed clk_hw_register(). Clocks registered by this function are
3613  * automatically clk_hw_unregister()ed on driver detach. See clk_hw_register()
3614  * for more information.
3615  */
3616 int devm_clk_hw_register(struct device *dev, struct clk_hw *hw)
3617 {
3618         struct clk_hw **hwp;
3619         int ret;
3620
3621         hwp = devres_alloc(devm_clk_hw_release, sizeof(*hwp), GFP_KERNEL);
3622         if (!hwp)
3623                 return -ENOMEM;
3624
3625         ret = clk_hw_register(dev, hw);
3626         if (!ret) {
3627                 *hwp = hw;
3628                 devres_add(dev, hwp);
3629         } else {
3630                 devres_free(hwp);
3631         }
3632
3633         return ret;
3634 }
3635 EXPORT_SYMBOL_GPL(devm_clk_hw_register);
3636
3637 static int devm_clk_match(struct device *dev, void *res, void *data)
3638 {
3639         struct clk *c = res;
3640         if (WARN_ON(!c))
3641                 return 0;
3642         return c == data;
3643 }
3644
3645 static int devm_clk_hw_match(struct device *dev, void *res, void *data)
3646 {
3647         struct clk_hw *hw = res;
3648
3649         if (WARN_ON(!hw))
3650                 return 0;
3651         return hw == data;
3652 }
3653
3654 /**
3655  * devm_clk_unregister - resource managed clk_unregister()
3656  * @clk: clock to unregister
3657  *
3658  * Deallocate a clock allocated with devm_clk_register(). Normally
3659  * this function will not need to be called and the resource management
3660  * code will ensure that the resource is freed.
3661  */
3662 void devm_clk_unregister(struct device *dev, struct clk *clk)
3663 {
3664         WARN_ON(devres_release(dev, devm_clk_release, devm_clk_match, clk));
3665 }
3666 EXPORT_SYMBOL_GPL(devm_clk_unregister);
3667
3668 /**
3669  * devm_clk_hw_unregister - resource managed clk_hw_unregister()
3670  * @dev: device that is unregistering the hardware-specific clock data
3671  * @hw: link to hardware-specific clock data
3672  *
3673  * Unregister a clk_hw registered with devm_clk_hw_register(). Normally
3674  * this function will not need to be called and the resource management
3675  * code will ensure that the resource is freed.
3676  */
3677 void devm_clk_hw_unregister(struct device *dev, struct clk_hw *hw)
3678 {
3679         WARN_ON(devres_release(dev, devm_clk_hw_release, devm_clk_hw_match,
3680                                 hw));
3681 }
3682 EXPORT_SYMBOL_GPL(devm_clk_hw_unregister);
3683
3684 /*
3685  * clkdev helpers
3686  */
3687
3688 void __clk_put(struct clk *clk)
3689 {
3690         struct module *owner;
3691
3692         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
3693                 return;
3694
3695         clk_prepare_lock();
3696
3697         /*
3698          * Before calling clk_put, all calls to clk_rate_exclusive_get() from a
3699          * given user should be balanced with calls to clk_rate_exclusive_put()
3700          * and by that same consumer
3701          */
3702         if (WARN_ON(clk->exclusive_count)) {
3703                 /* We voiced our concern, let's sanitize the situation */
3704                 clk->core->protect_count -= (clk->exclusive_count - 1);
3705                 clk_core_rate_unprotect(clk->core);
3706                 clk->exclusive_count = 0;
3707         }
3708
3709         hlist_del(&clk->clks_node);
3710         if (clk->min_rate > clk->core->req_rate ||
3711             clk->max_rate < clk->core->req_rate)
3712                 clk_core_set_rate_nolock(clk->core, clk->core->req_rate);
3713
3714         owner = clk->core->owner;
3715         kref_put(&clk->core->ref, __clk_release);
3716
3717         clk_prepare_unlock();
3718
3719         module_put(owner);
3720
3721         free_clk(clk);
3722 }
3723
3724 /***        clk rate change notifiers        ***/
3725
3726 /**
3727  * clk_notifier_register - add a clk rate change notifier
3728  * @clk: struct clk * to watch
3729  * @nb: struct notifier_block * with callback info
3730  *
3731  * Request notification when clk's rate changes.  This uses an SRCU
3732  * notifier because we want it to block and notifier unregistrations are
3733  * uncommon.  The callbacks associated with the notifier must not
3734  * re-enter into the clk framework by calling any top-level clk APIs;
3735  * this will cause a nested prepare_lock mutex.
3736  *
3737  * In all notification cases (pre, post and abort rate change) the original
3738  * clock rate is passed to the callback via struct clk_notifier_data.old_rate
3739  * and the new frequency is passed via struct clk_notifier_data.new_rate.
3740  *
3741  * clk_notifier_register() must be called from non-atomic context.
3742  * Returns -EINVAL if called with null arguments, -ENOMEM upon
3743  * allocation failure; otherwise, passes along the return value of
3744  * srcu_notifier_chain_register().
3745  */
3746 int clk_notifier_register(struct clk *clk, struct notifier_block *nb)
3747 {
3748         struct clk_notifier *cn;
3749         int ret = -ENOMEM;
3750
3751         if (!clk || !nb)
3752                 return -EINVAL;
3753
3754         clk_prepare_lock();
3755
3756         /* search the list of notifiers for this clk */
3757         list_for_each_entry(cn, &clk_notifier_list, node)
3758                 if (cn->clk == clk)
3759                         break;
3760
3761         /* if clk wasn't in the notifier list, allocate new clk_notifier */
3762         if (cn->clk != clk) {
3763                 cn = kzalloc(sizeof(*cn), GFP_KERNEL);
3764                 if (!cn)
3765                         goto out;
3766
3767                 cn->clk = clk;
3768                 srcu_init_notifier_head(&cn->notifier_head);
3769
3770                 list_add(&cn->node, &clk_notifier_list);
3771         }
3772
3773         ret = srcu_notifier_chain_register(&cn->notifier_head, nb);
3774
3775         clk->core->notifier_count++;
3776
3777 out:
3778         clk_prepare_unlock();
3779
3780         return ret;
3781 }
3782 EXPORT_SYMBOL_GPL(clk_notifier_register);
3783
3784 /**
3785  * clk_notifier_unregister - remove a clk rate change notifier
3786  * @clk: struct clk *
3787  * @nb: struct notifier_block * with callback info
3788  *
3789  * Request no further notification for changes to 'clk' and frees memory
3790  * allocated in clk_notifier_register.
3791  *
3792  * Returns -EINVAL if called with null arguments; otherwise, passes
3793  * along the return value of srcu_notifier_chain_unregister().
3794  */
3795 int clk_notifier_unregister(struct clk *clk, struct notifier_block *nb)
3796 {
3797         struct clk_notifier *cn = NULL;
3798         int ret = -EINVAL;
3799
3800         if (!clk || !nb)
3801                 return -EINVAL;
3802
3803         clk_prepare_lock();
3804
3805         list_for_each_entry(cn, &clk_notifier_list, node)
3806                 if (cn->clk == clk)
3807                         break;
3808
3809         if (cn->clk == clk) {
3810                 ret = srcu_notifier_chain_unregister(&cn->notifier_head, nb);
3811
3812                 clk->core->notifier_count--;
3813
3814                 /* XXX the notifier code should handle this better */
3815                 if (!cn->notifier_head.head) {
3816                         srcu_cleanup_notifier_head(&cn->notifier_head);
3817                         list_del(&cn->node);
3818                         kfree(cn);
3819                 }
3820
3821         } else {
3822                 ret = -ENOENT;
3823         }
3824
3825         clk_prepare_unlock();
3826
3827         return ret;
3828 }
3829 EXPORT_SYMBOL_GPL(clk_notifier_unregister);
3830
3831 #ifdef CONFIG_OF
3832 /**
3833  * struct of_clk_provider - Clock provider registration structure
3834  * @link: Entry in global list of clock providers
3835  * @node: Pointer to device tree node of clock provider
3836  * @get: Get clock callback.  Returns NULL or a struct clk for the
3837  *       given clock specifier
3838  * @data: context pointer to be passed into @get callback
3839  */
3840 struct of_clk_provider {
3841         struct list_head link;
3842
3843         struct device_node *node;
3844         struct clk *(*get)(struct of_phandle_args *clkspec, void *data);
3845         struct clk_hw *(*get_hw)(struct of_phandle_args *clkspec, void *data);
3846         void *data;
3847 };
3848
3849 static const struct of_device_id __clk_of_table_sentinel
3850         __used __section(__clk_of_table_end);
3851
3852 static LIST_HEAD(of_clk_providers);
3853 static DEFINE_MUTEX(of_clk_mutex);
3854
3855 struct clk *of_clk_src_simple_get(struct of_phandle_args *clkspec,
3856                                      void *data)
3857 {
3858         return data;
3859 }
3860 EXPORT_SYMBOL_GPL(of_clk_src_simple_get);
3861
3862 struct clk_hw *of_clk_hw_simple_get(struct of_phandle_args *clkspec, void *data)
3863 {
3864         return data;
3865 }
3866 EXPORT_SYMBOL_GPL(of_clk_hw_simple_get);
3867
3868 struct clk *of_clk_src_onecell_get(struct of_phandle_args *clkspec, void *data)
3869 {
3870         struct clk_onecell_data *clk_data = data;
3871         unsigned int idx = clkspec->args[0];
3872
3873         if (idx >= clk_data->clk_num) {
3874                 pr_err("%s: invalid clock index %u\n", __func__, idx);
3875                 return ERR_PTR(-EINVAL);
3876         }
3877
3878         return clk_data->clks[idx];
3879 }
3880 EXPORT_SYMBOL_GPL(of_clk_src_onecell_get);
3881
3882 struct clk_hw *
3883 of_clk_hw_onecell_get(struct of_phandle_args *clkspec, void *data)
3884 {
3885         struct clk_hw_onecell_data *hw_data = data;
3886         unsigned int idx = clkspec->args[0];
3887
3888         if (idx >= hw_data->num) {
3889                 pr_err("%s: invalid index %u\n", __func__, idx);
3890                 return ERR_PTR(-EINVAL);
3891         }
3892
3893         return hw_data->hws[idx];
3894 }
3895 EXPORT_SYMBOL_GPL(of_clk_hw_onecell_get);
3896
3897 /**
3898  * of_clk_add_provider() - Register a clock provider for a node
3899  * @np: Device node pointer associated with clock provider
3900  * @clk_src_get: callback for decoding clock
3901  * @data: context pointer for @clk_src_get callback.
3902  *
3903  * This function is *deprecated*. Use of_clk_add_hw_provider() instead.
3904  */
3905 int of_clk_add_provider(struct device_node *np,
3906                         struct clk *(*clk_src_get)(struct of_phandle_args *clkspec,
3907                                                    void *data),
3908                         void *data)
3909 {
3910         struct of_clk_provider *cp;
3911         int ret;
3912
3913         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
3914         if (!cp)
3915                 return -ENOMEM;
3916
3917         cp->node = of_node_get(np);
3918         cp->data = data;
3919         cp->get = clk_src_get;
3920
3921         mutex_lock(&of_clk_mutex);
3922         list_add(&cp->link, &of_clk_providers);
3923         mutex_unlock(&of_clk_mutex);
3924         pr_debug("Added clock from %pOF\n", np);
3925
3926         ret = of_clk_set_defaults(np, true);
3927         if (ret < 0)
3928                 of_clk_del_provider(np);
3929
3930         return ret;
3931 }
3932 EXPORT_SYMBOL_GPL(of_clk_add_provider);
3933
3934 /**
3935  * of_clk_add_hw_provider() - Register a clock provider for a node
3936  * @np: Device node pointer associated with clock provider
3937  * @get: callback for decoding clk_hw
3938  * @data: context pointer for @get callback.
3939  */
3940 int of_clk_add_hw_provider(struct device_node *np,
3941                            struct clk_hw *(*get)(struct of_phandle_args *clkspec,
3942                                                  void *data),
3943                            void *data)
3944 {
3945         struct of_clk_provider *cp;
3946         int ret;
3947
3948         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
3949         if (!cp)
3950                 return -ENOMEM;
3951
3952         cp->node = of_node_get(np);
3953         cp->data = data;
3954         cp->get_hw = get;
3955
3956         mutex_lock(&of_clk_mutex);
3957         list_add(&cp->link, &of_clk_providers);
3958         mutex_unlock(&of_clk_mutex);
3959         pr_debug("Added clk_hw provider from %pOF\n", np);
3960
3961         ret = of_clk_set_defaults(np, true);
3962         if (ret < 0)
3963                 of_clk_del_provider(np);
3964
3965         return ret;
3966 }
3967 EXPORT_SYMBOL_GPL(of_clk_add_hw_provider);
3968
3969 static void devm_of_clk_release_provider(struct device *dev, void *res)
3970 {
3971         of_clk_del_provider(*(struct device_node **)res);
3972 }
3973
3974 /*
3975  * We allow a child device to use its parent device as the clock provider node
3976  * for cases like MFD sub-devices where the child device driver wants to use
3977  * devm_*() APIs but not list the device in DT as a sub-node.
3978  */
3979 static struct device_node *get_clk_provider_node(struct device *dev)
3980 {
3981         struct device_node *np, *parent_np;
3982
3983         np = dev->of_node;
3984         parent_np = dev->parent ? dev->parent->of_node : NULL;
3985
3986         if (!of_find_property(np, "#clock-cells", NULL))
3987                 if (of_find_property(parent_np, "#clock-cells", NULL))
3988                         np = parent_np;
3989
3990         return np;
3991 }
3992
3993 /**
3994  * devm_of_clk_add_hw_provider() - Managed clk provider node registration
3995  * @dev: Device acting as the clock provider (used for DT node and lifetime)
3996  * @get: callback for decoding clk_hw
3997  * @data: context pointer for @get callback
3998  *
3999  * Registers clock provider for given device's node. If the device has no DT
4000  * node or if the device node lacks of clock provider information (#clock-cells)
4001  * then the parent device's node is scanned for this information. If parent node
4002  * has the #clock-cells then it is used in registration. Provider is
4003  * automatically released at device exit.
4004  *
4005  * Return: 0 on success or an errno on failure.
4006  */
4007 int devm_of_clk_add_hw_provider(struct device *dev,
4008                         struct clk_hw *(*get)(struct of_phandle_args *clkspec,
4009                                               void *data),
4010                         void *data)
4011 {
4012         struct device_node **ptr, *np;
4013         int ret;
4014
4015         ptr = devres_alloc(devm_of_clk_release_provider, sizeof(*ptr),
4016                            GFP_KERNEL);
4017         if (!ptr)
4018                 return -ENOMEM;
4019
4020         np = get_clk_provider_node(dev);
4021         ret = of_clk_add_hw_provider(np, get, data);
4022         if (!ret) {
4023                 *ptr = np;
4024                 devres_add(dev, ptr);
4025         } else {
4026                 devres_free(ptr);
4027         }
4028
4029         return ret;
4030 }
4031 EXPORT_SYMBOL_GPL(devm_of_clk_add_hw_provider);
4032
4033 /**
4034  * of_clk_del_provider() - Remove a previously registered clock provider
4035  * @np: Device node pointer associated with clock provider
4036  */
4037 void of_clk_del_provider(struct device_node *np)
4038 {
4039         struct of_clk_provider *cp;
4040
4041         mutex_lock(&of_clk_mutex);
4042         list_for_each_entry(cp, &of_clk_providers, link) {
4043                 if (cp->node == np) {
4044                         list_del(&cp->link);
4045                         of_node_put(cp->node);
4046                         kfree(cp);
4047                         break;
4048                 }
4049         }
4050         mutex_unlock(&of_clk_mutex);
4051 }
4052 EXPORT_SYMBOL_GPL(of_clk_del_provider);
4053
4054 static int devm_clk_provider_match(struct device *dev, void *res, void *data)
4055 {
4056         struct device_node **np = res;
4057
4058         if (WARN_ON(!np || !*np))
4059                 return 0;
4060
4061         return *np == data;
4062 }
4063
4064 /**
4065  * devm_of_clk_del_provider() - Remove clock provider registered using devm
4066  * @dev: Device to whose lifetime the clock provider was bound
4067  */
4068 void devm_of_clk_del_provider(struct device *dev)
4069 {
4070         int ret;
4071         struct device_node *np = get_clk_provider_node(dev);
4072
4073         ret = devres_release(dev, devm_of_clk_release_provider,
4074                              devm_clk_provider_match, np);
4075
4076         WARN_ON(ret);
4077 }
4078 EXPORT_SYMBOL(devm_of_clk_del_provider);
4079
4080 /*
4081  * Beware the return values when np is valid, but no clock provider is found.
4082  * If name == NULL, the function returns -ENOENT.
4083  * If name != NULL, the function returns -EINVAL. This is because
4084  * of_parse_phandle_with_args() is called even if of_property_match_string()
4085  * returns an error.
4086  */
4087 static int of_parse_clkspec(const struct device_node *np, int index,
4088                             const char *name, struct of_phandle_args *out_args)
4089 {
4090         int ret = -ENOENT;
4091
4092         /* Walk up the tree of devices looking for a clock property that matches */
4093         while (np) {
4094                 /*
4095                  * For named clocks, first look up the name in the
4096                  * "clock-names" property.  If it cannot be found, then index
4097                  * will be an error code and of_parse_phandle_with_args() will
4098                  * return -EINVAL.
4099                  */
4100                 if (name)
4101                         index = of_property_match_string(np, "clock-names", name);
4102                 ret = of_parse_phandle_with_args(np, "clocks", "#clock-cells",
4103                                                  index, out_args);
4104                 if (!ret)
4105                         break;
4106                 if (name && index >= 0)
4107                         break;
4108
4109                 /*
4110                  * No matching clock found on this node.  If the parent node
4111                  * has a "clock-ranges" property, then we can try one of its
4112                  * clocks.
4113                  */
4114                 np = np->parent;
4115                 if (np && !of_get_property(np, "clock-ranges", NULL))
4116                         break;
4117                 index = 0;
4118         }
4119
4120         return ret;
4121 }
4122
4123 static struct clk_hw *
4124 __of_clk_get_hw_from_provider(struct of_clk_provider *provider,
4125                               struct of_phandle_args *clkspec)
4126 {
4127         struct clk *clk;
4128
4129         if (provider->get_hw)
4130                 return provider->get_hw(clkspec, provider->data);
4131
4132         clk = provider->get(clkspec, provider->data);
4133         if (IS_ERR(clk))
4134                 return ERR_CAST(clk);
4135         return __clk_get_hw(clk);
4136 }
4137
4138 static struct clk_hw *
4139 of_clk_get_hw_from_clkspec(struct of_phandle_args *clkspec)
4140 {
4141         struct of_clk_provider *provider;
4142         struct clk_hw *hw = ERR_PTR(-EPROBE_DEFER);
4143
4144         if (!clkspec)
4145                 return ERR_PTR(-EINVAL);
4146
4147         mutex_lock(&of_clk_mutex);
4148         list_for_each_entry(provider, &of_clk_providers, link) {
4149                 if (provider->node == clkspec->np) {
4150                         hw = __of_clk_get_hw_from_provider(provider, clkspec);
4151                         if (!IS_ERR(hw))
4152                                 break;
4153                 }
4154         }
4155         mutex_unlock(&of_clk_mutex);
4156
4157         return hw;
4158 }
4159
4160 /**
4161  * of_clk_get_from_provider() - Lookup a clock from a clock provider
4162  * @clkspec: pointer to a clock specifier data structure
4163  *
4164  * This function looks up a struct clk from the registered list of clock
4165  * providers, an input is a clock specifier data structure as returned
4166  * from the of_parse_phandle_with_args() function call.
4167  */
4168 struct clk *of_clk_get_from_provider(struct of_phandle_args *clkspec)
4169 {
4170         struct clk_hw *hw = of_clk_get_hw_from_clkspec(clkspec);
4171
4172         return clk_hw_create_clk(NULL, hw, NULL, __func__);
4173 }
4174 EXPORT_SYMBOL_GPL(of_clk_get_from_provider);
4175
4176 struct clk_hw *of_clk_get_hw(struct device_node *np, int index,
4177                              const char *con_id)
4178 {
4179         int ret;
4180         struct clk_hw *hw;
4181         struct of_phandle_args clkspec;
4182
4183         ret = of_parse_clkspec(np, index, con_id, &clkspec);
4184         if (ret)
4185                 return ERR_PTR(ret);
4186
4187         hw = of_clk_get_hw_from_clkspec(&clkspec);
4188         of_node_put(clkspec.np);
4189
4190         return hw;
4191 }
4192
4193 static struct clk *__of_clk_get(struct device_node *np,
4194                                 int index, const char *dev_id,
4195                                 const char *con_id)
4196 {
4197         struct clk_hw *hw = of_clk_get_hw(np, index, con_id);
4198
4199         return clk_hw_create_clk(NULL, hw, dev_id, con_id);
4200 }
4201
4202 struct clk *of_clk_get(struct device_node *np, int index)
4203 {
4204         return __of_clk_get(np, index, np->full_name, NULL);
4205 }
4206 EXPORT_SYMBOL(of_clk_get);
4207
4208 /**
4209  * of_clk_get_by_name() - Parse and lookup a clock referenced by a device node
4210  * @np: pointer to clock consumer node
4211  * @name: name of consumer's clock input, or NULL for the first clock reference
4212  *
4213  * This function parses the clocks and clock-names properties,
4214  * and uses them to look up the struct clk from the registered list of clock
4215  * providers.
4216  */
4217 struct clk *of_clk_get_by_name(struct device_node *np, const char *name)
4218 {
4219         if (!np)
4220                 return ERR_PTR(-ENOENT);
4221
4222         return __of_clk_get(np, 0, np->full_name, name);
4223 }
4224 EXPORT_SYMBOL(of_clk_get_by_name);
4225
4226 /**
4227  * of_clk_get_parent_count() - Count the number of clocks a device node has
4228  * @np: device node to count
4229  *
4230  * Returns: The number of clocks that are possible parents of this node
4231  */
4232 unsigned int of_clk_get_parent_count(struct device_node *np)
4233 {
4234         int count;
4235
4236         count = of_count_phandle_with_args(np, "clocks", "#clock-cells");
4237         if (count < 0)
4238                 return 0;
4239
4240         return count;
4241 }
4242 EXPORT_SYMBOL_GPL(of_clk_get_parent_count);
4243
4244 const char *of_clk_get_parent_name(struct device_node *np, int index)
4245 {
4246         struct of_phandle_args clkspec;
4247         struct property *prop;
4248         const char *clk_name;
4249         const __be32 *vp;
4250         u32 pv;
4251         int rc;
4252         int count;
4253         struct clk *clk;
4254
4255         rc = of_parse_phandle_with_args(np, "clocks", "#clock-cells", index,
4256                                         &clkspec);
4257         if (rc)
4258                 return NULL;
4259
4260         index = clkspec.args_count ? clkspec.args[0] : 0;
4261         count = 0;
4262
4263         /* if there is an indices property, use it to transfer the index
4264          * specified into an array offset for the clock-output-names property.
4265          */
4266         of_property_for_each_u32(clkspec.np, "clock-indices", prop, vp, pv) {
4267                 if (index == pv) {
4268                         index = count;
4269                         break;
4270                 }
4271                 count++;
4272         }
4273         /* We went off the end of 'clock-indices' without finding it */
4274         if (prop && !vp)
4275                 return NULL;
4276
4277         if (of_property_read_string_index(clkspec.np, "clock-output-names",
4278                                           index,
4279                                           &clk_name) < 0) {
4280                 /*
4281                  * Best effort to get the name if the clock has been
4282                  * registered with the framework. If the clock isn't
4283                  * registered, we return the node name as the name of
4284                  * the clock as long as #clock-cells = 0.
4285                  */
4286                 clk = of_clk_get_from_provider(&clkspec);
4287                 if (IS_ERR(clk)) {
4288                         if (clkspec.args_count == 0)
4289                                 clk_name = clkspec.np->name;
4290                         else
4291                                 clk_name = NULL;
4292                 } else {
4293                         clk_name = __clk_get_name(clk);
4294                         clk_put(clk);
4295                 }
4296         }
4297
4298
4299         of_node_put(clkspec.np);
4300         return clk_name;
4301 }
4302 EXPORT_SYMBOL_GPL(of_clk_get_parent_name);
4303
4304 /**
4305  * of_clk_parent_fill() - Fill @parents with names of @np's parents and return
4306  * number of parents
4307  * @np: Device node pointer associated with clock provider
4308  * @parents: pointer to char array that hold the parents' names
4309  * @size: size of the @parents array
4310  *
4311  * Return: number of parents for the clock node.
4312  */
4313 int of_clk_parent_fill(struct device_node *np, const char **parents,
4314                        unsigned int size)
4315 {
4316         unsigned int i = 0;
4317
4318         while (i < size && (parents[i] = of_clk_get_parent_name(np, i)) != NULL)
4319                 i++;
4320
4321         return i;
4322 }
4323 EXPORT_SYMBOL_GPL(of_clk_parent_fill);
4324
4325 struct clock_provider {
4326         void (*clk_init_cb)(struct device_node *);
4327         struct device_node *np;
4328         struct list_head node;
4329 };
4330
4331 /*
4332  * This function looks for a parent clock. If there is one, then it
4333  * checks that the provider for this parent clock was initialized, in
4334  * this case the parent clock will be ready.
4335  */
4336 static int parent_ready(struct device_node *np)
4337 {
4338         int i = 0;
4339
4340         while (true) {
4341                 struct clk *clk = of_clk_get(np, i);
4342
4343                 /* this parent is ready we can check the next one */
4344                 if (!IS_ERR(clk)) {
4345                         clk_put(clk);
4346                         i++;
4347                         continue;
4348                 }
4349
4350                 /* at least one parent is not ready, we exit now */
4351                 if (PTR_ERR(clk) == -EPROBE_DEFER)
4352                         return 0;
4353
4354                 /*
4355                  * Here we make assumption that the device tree is
4356                  * written correctly. So an error means that there is
4357                  * no more parent. As we didn't exit yet, then the
4358                  * previous parent are ready. If there is no clock
4359                  * parent, no need to wait for them, then we can
4360                  * consider their absence as being ready
4361                  */
4362                 return 1;
4363         }
4364 }
4365
4366 /**
4367  * of_clk_detect_critical() - set CLK_IS_CRITICAL flag from Device Tree
4368  * @np: Device node pointer associated with clock provider
4369  * @index: clock index
4370  * @flags: pointer to top-level framework flags
4371  *
4372  * Detects if the clock-critical property exists and, if so, sets the
4373  * corresponding CLK_IS_CRITICAL flag.
4374  *
4375  * Do not use this function. It exists only for legacy Device Tree
4376  * bindings, such as the one-clock-per-node style that are outdated.
4377  * Those bindings typically put all clock data into .dts and the Linux
4378  * driver has no clock data, thus making it impossible to set this flag
4379  * correctly from the driver. Only those drivers may call
4380  * of_clk_detect_critical from their setup functions.
4381  *
4382  * Return: error code or zero on success
4383  */
4384 int of_clk_detect_critical(struct device_node *np,
4385                                           int index, unsigned long *flags)
4386 {
4387         struct property *prop;
4388         const __be32 *cur;
4389         uint32_t idx;
4390
4391         if (!np || !flags)
4392                 return -EINVAL;
4393
4394         of_property_for_each_u32(np, "clock-critical", prop, cur, idx)
4395                 if (index == idx)
4396                         *flags |= CLK_IS_CRITICAL;
4397
4398         return 0;
4399 }
4400
4401 /**
4402  * of_clk_init() - Scan and init clock providers from the DT
4403  * @matches: array of compatible values and init functions for providers.
4404  *
4405  * This function scans the device tree for matching clock providers
4406  * and calls their initialization functions. It also does it by trying
4407  * to follow the dependencies.
4408  */
4409 void __init of_clk_init(const struct of_device_id *matches)
4410 {
4411         const struct of_device_id *match;
4412         struct device_node *np;
4413         struct clock_provider *clk_provider, *next;
4414         bool is_init_done;
4415         bool force = false;
4416         LIST_HEAD(clk_provider_list);
4417
4418         if (!matches)
4419                 matches = &__clk_of_table;
4420
4421         /* First prepare the list of the clocks providers */
4422         for_each_matching_node_and_match(np, matches, &match) {
4423                 struct clock_provider *parent;
4424
4425                 if (!of_device_is_available(np))
4426                         continue;
4427
4428                 parent = kzalloc(sizeof(*parent), GFP_KERNEL);
4429                 if (!parent) {
4430                         list_for_each_entry_safe(clk_provider, next,
4431                                                  &clk_provider_list, node) {
4432                                 list_del(&clk_provider->node);
4433                                 of_node_put(clk_provider->np);
4434                                 kfree(clk_provider);
4435                         }
4436                         of_node_put(np);
4437                         return;
4438                 }
4439
4440                 parent->clk_init_cb = match->data;
4441                 parent->np = of_node_get(np);
4442                 list_add_tail(&parent->node, &clk_provider_list);
4443         }
4444
4445         while (!list_empty(&clk_provider_list)) {
4446                 is_init_done = false;
4447                 list_for_each_entry_safe(clk_provider, next,
4448                                         &clk_provider_list, node) {
4449                         if (force || parent_ready(clk_provider->np)) {
4450
4451                                 /* Don't populate platform devices */
4452                                 of_node_set_flag(clk_provider->np,
4453                                                  OF_POPULATED);
4454
4455                                 clk_provider->clk_init_cb(clk_provider->np);
4456                                 of_clk_set_defaults(clk_provider->np, true);
4457
4458                                 list_del(&clk_provider->node);
4459                                 of_node_put(clk_provider->np);
4460                                 kfree(clk_provider);
4461                                 is_init_done = true;
4462                         }
4463                 }
4464
4465                 /*
4466                  * We didn't manage to initialize any of the
4467                  * remaining providers during the last loop, so now we
4468                  * initialize all the remaining ones unconditionally
4469                  * in case the clock parent was not mandatory
4470                  */
4471                 if (!is_init_done)
4472                         force = true;
4473         }
4474 }
4475 #endif