]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - rpmsg/hwspinlock.git/blob - drivers/clk/clk.c
8a0254a1c3037e52604a96c217880d420865e157
[rpmsg/hwspinlock.git] / drivers / clk / clk.c
1 /*
2  * Copyright (C) 2010-2011 Canonical Ltd <jeremy.kerr@canonical.com>
3  * Copyright (C) 2011-2012 Linaro Ltd <mturquette@linaro.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Standard functionality for the common clock API.  See Documentation/driver-api/clk.rst
10  */
12 #include <linux/clk.h>
13 #include <linux/clk-provider.h>
14 #include <linux/clk/clk-conf.h>
15 #include <linux/module.h>
16 #include <linux/mutex.h>
17 #include <linux/spinlock.h>
18 #include <linux/err.h>
19 #include <linux/list.h>
20 #include <linux/slab.h>
21 #include <linux/of.h>
22 #include <linux/device.h>
23 #include <linux/init.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/sched.h>
26 #include <linux/clkdev.h>
28 #include "clk.h"
30 static DEFINE_SPINLOCK(enable_lock);
31 static DEFINE_MUTEX(prepare_lock);
33 static struct task_struct *prepare_owner;
34 static struct task_struct *enable_owner;
36 static int prepare_refcnt;
37 static int enable_refcnt;
39 static HLIST_HEAD(clk_root_list);
40 static HLIST_HEAD(clk_orphan_list);
41 static LIST_HEAD(clk_notifier_list);
43 /***    private data structures    ***/
45 struct clk_core {
46         const char              *name;
47         const struct clk_ops    *ops;
48         struct clk_hw           *hw;
49         struct module           *owner;
50         struct device           *dev;
51         struct clk_core         *parent;
52         const char              **parent_names;
53         struct clk_core         **parents;
54         u8                      num_parents;
55         u8                      new_parent_index;
56         unsigned long           rate;
57         unsigned long           req_rate;
58         unsigned long           new_rate;
59         struct clk_core         *new_parent;
60         struct clk_core         *new_child;
61         unsigned long           flags;
62         bool                    orphan;
63         unsigned int            enable_count;
64         unsigned int            prepare_count;
65         unsigned int            protect_count;
66         unsigned long           min_rate;
67         unsigned long           max_rate;
68         unsigned long           accuracy;
69         int                     phase;
70         struct clk_duty         duty;
71         struct hlist_head       children;
72         struct hlist_node       child_node;
73         struct hlist_head       clks;
74         unsigned int            notifier_count;
75 #ifdef CONFIG_DEBUG_FS
76         struct dentry           *dentry;
77         struct hlist_node       debug_node;
78 #endif
79         struct kref             ref;
80 };
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/clk.h>
85 struct clk {
86         struct clk_core *core;
87         const char *dev_id;
88         const char *con_id;
89         unsigned long min_rate;
90         unsigned long max_rate;
91         unsigned int exclusive_count;
92         struct hlist_node clks_node;
93 };
95 /***           runtime pm          ***/
96 static int clk_pm_runtime_get(struct clk_core *core)
97 {
98         int ret = 0;
100         if (!core->dev)
101                 return 0;
103         ret = pm_runtime_get_sync(core->dev);
104         return ret < 0 ? ret : 0;
107 static void clk_pm_runtime_put(struct clk_core *core)
109         if (!core->dev)
110                 return;
112         pm_runtime_put_sync(core->dev);
115 /***           locking             ***/
116 static void clk_prepare_lock(void)
118         if (!mutex_trylock(&prepare_lock)) {
119                 if (prepare_owner == current) {
120                         prepare_refcnt++;
121                         return;
122                 }
123                 mutex_lock(&prepare_lock);
124         }
125         WARN_ON_ONCE(prepare_owner != NULL);
126         WARN_ON_ONCE(prepare_refcnt != 0);
127         prepare_owner = current;
128         prepare_refcnt = 1;
131 static void clk_prepare_unlock(void)
133         WARN_ON_ONCE(prepare_owner != current);
134         WARN_ON_ONCE(prepare_refcnt == 0);
136         if (--prepare_refcnt)
137                 return;
138         prepare_owner = NULL;
139         mutex_unlock(&prepare_lock);
142 static unsigned long clk_enable_lock(void)
143         __acquires(enable_lock)
145         unsigned long flags;
147         /*
148          * On UP systems, spin_trylock_irqsave() always returns true, even if
149          * we already hold the lock. So, in that case, we rely only on
150          * reference counting.
151          */
152         if (!IS_ENABLED(CONFIG_SMP) ||
153             !spin_trylock_irqsave(&enable_lock, flags)) {
154                 if (enable_owner == current) {
155                         enable_refcnt++;
156                         __acquire(enable_lock);
157                         if (!IS_ENABLED(CONFIG_SMP))
158                                 local_save_flags(flags);
159                         return flags;
160                 }
161                 spin_lock_irqsave(&enable_lock, flags);
162         }
163         WARN_ON_ONCE(enable_owner != NULL);
164         WARN_ON_ONCE(enable_refcnt != 0);
165         enable_owner = current;
166         enable_refcnt = 1;
167         return flags;
170 static void clk_enable_unlock(unsigned long flags)
171         __releases(enable_lock)
173         WARN_ON_ONCE(enable_owner != current);
174         WARN_ON_ONCE(enable_refcnt == 0);
176         if (--enable_refcnt) {
177                 __release(enable_lock);
178                 return;
179         }
180         enable_owner = NULL;
181         spin_unlock_irqrestore(&enable_lock, flags);
184 static bool clk_core_rate_is_protected(struct clk_core *core)
186         return core->protect_count;
189 static bool clk_core_is_prepared(struct clk_core *core)
191         bool ret = false;
193         /*
194          * .is_prepared is optional for clocks that can prepare
195          * fall back to software usage counter if it is missing
196          */
197         if (!core->ops->is_prepared)
198                 return core->prepare_count;
200         if (!clk_pm_runtime_get(core)) {
201                 ret = core->ops->is_prepared(core->hw);
202                 clk_pm_runtime_put(core);
203         }
205         return ret;
208 static bool clk_core_is_enabled(struct clk_core *core)
210         bool ret = false;
212         /*
213          * .is_enabled is only mandatory for clocks that gate
214          * fall back to software usage counter if .is_enabled is missing
215          */
216         if (!core->ops->is_enabled)
217                 return core->enable_count;
219         /*
220          * Check if clock controller's device is runtime active before
221          * calling .is_enabled callback. If not, assume that clock is
222          * disabled, because we might be called from atomic context, from
223          * which pm_runtime_get() is not allowed.
224          * This function is called mainly from clk_disable_unused_subtree,
225          * which ensures proper runtime pm activation of controller before
226          * taking enable spinlock, but the below check is needed if one tries
227          * to call it from other places.
228          */
229         if (core->dev) {
230                 pm_runtime_get_noresume(core->dev);
231                 if (!pm_runtime_active(core->dev)) {
232                         ret = false;
233                         goto done;
234                 }
235         }
237         ret = core->ops->is_enabled(core->hw);
238 done:
239         if (core->dev)
240                 pm_runtime_put(core->dev);
242         return ret;
245 /***    helper functions   ***/
247 const char *__clk_get_name(const struct clk *clk)
249         return !clk ? NULL : clk->core->name;
251 EXPORT_SYMBOL_GPL(__clk_get_name);
253 const char *clk_hw_get_name(const struct clk_hw *hw)
255         return hw->core->name;
257 EXPORT_SYMBOL_GPL(clk_hw_get_name);
259 struct clk_hw *__clk_get_hw(struct clk *clk)
261         return !clk ? NULL : clk->core->hw;
263 EXPORT_SYMBOL_GPL(__clk_get_hw);
265 unsigned int clk_hw_get_num_parents(const struct clk_hw *hw)
267         return hw->core->num_parents;
269 EXPORT_SYMBOL_GPL(clk_hw_get_num_parents);
271 struct clk_hw *clk_hw_get_parent(const struct clk_hw *hw)
273         return hw->core->parent ? hw->core->parent->hw : NULL;
275 EXPORT_SYMBOL_GPL(clk_hw_get_parent);
277 static struct clk_core *__clk_lookup_subtree(const char *name,
278                                              struct clk_core *core)
280         struct clk_core *child;
281         struct clk_core *ret;
283         if (!strcmp(core->name, name))
284                 return core;
286         hlist_for_each_entry(child, &core->children, child_node) {
287                 ret = __clk_lookup_subtree(name, child);
288                 if (ret)
289                         return ret;
290         }
292         return NULL;
295 static struct clk_core *clk_core_lookup(const char *name)
297         struct clk_core *root_clk;
298         struct clk_core *ret;
300         if (!name)
301                 return NULL;
303         /* search the 'proper' clk tree first */
304         hlist_for_each_entry(root_clk, &clk_root_list, child_node) {
305                 ret = __clk_lookup_subtree(name, root_clk);
306                 if (ret)
307                         return ret;
308         }
310         /* if not found, then search the orphan tree */
311         hlist_for_each_entry(root_clk, &clk_orphan_list, child_node) {
312                 ret = __clk_lookup_subtree(name, root_clk);
313                 if (ret)
314                         return ret;
315         }
317         return NULL;
320 static struct clk_core *clk_core_get_parent_by_index(struct clk_core *core,
321                                                          u8 index)
323         if (!core || index >= core->num_parents)
324                 return NULL;
326         if (!core->parents[index])
327                 core->parents[index] =
328                                 clk_core_lookup(core->parent_names[index]);
330         return core->parents[index];
333 struct clk_hw *
334 clk_hw_get_parent_by_index(const struct clk_hw *hw, unsigned int index)
336         struct clk_core *parent;
338         parent = clk_core_get_parent_by_index(hw->core, index);
340         return !parent ? NULL : parent->hw;
342 EXPORT_SYMBOL_GPL(clk_hw_get_parent_by_index);
344 unsigned int __clk_get_enable_count(struct clk *clk)
346         return !clk ? 0 : clk->core->enable_count;
349 static unsigned long clk_core_get_rate_nolock(struct clk_core *core)
351         unsigned long ret;
353         if (!core) {
354                 ret = 0;
355                 goto out;
356         }
358         ret = core->rate;
360         if (!core->num_parents)
361                 goto out;
363         if (!core->parent)
364                 ret = 0;
366 out:
367         return ret;
370 unsigned long clk_hw_get_rate(const struct clk_hw *hw)
372         return clk_core_get_rate_nolock(hw->core);
374 EXPORT_SYMBOL_GPL(clk_hw_get_rate);
376 static unsigned long __clk_get_accuracy(struct clk_core *core)
378         if (!core)
379                 return 0;
381         return core->accuracy;
384 unsigned long __clk_get_flags(struct clk *clk)
386         return !clk ? 0 : clk->core->flags;
388 EXPORT_SYMBOL_GPL(__clk_get_flags);
390 unsigned long clk_hw_get_flags(const struct clk_hw *hw)
392         return hw->core->flags;
394 EXPORT_SYMBOL_GPL(clk_hw_get_flags);
396 bool clk_hw_is_prepared(const struct clk_hw *hw)
398         return clk_core_is_prepared(hw->core);
401 bool clk_hw_rate_is_protected(const struct clk_hw *hw)
403         return clk_core_rate_is_protected(hw->core);
406 bool clk_hw_is_enabled(const struct clk_hw *hw)
408         return clk_core_is_enabled(hw->core);
411 bool __clk_is_enabled(struct clk *clk)
413         if (!clk)
414                 return false;
416         return clk_core_is_enabled(clk->core);
418 EXPORT_SYMBOL_GPL(__clk_is_enabled);
420 static bool mux_is_better_rate(unsigned long rate, unsigned long now,
421                            unsigned long best, unsigned long flags)
423         if (flags & CLK_MUX_ROUND_CLOSEST)
424                 return abs(now - rate) < abs(best - rate);
426         return now <= rate && now > best;
429 int clk_mux_determine_rate_flags(struct clk_hw *hw,
430                                  struct clk_rate_request *req,
431                                  unsigned long flags)
433         struct clk_core *core = hw->core, *parent, *best_parent = NULL;
434         int i, num_parents, ret;
435         unsigned long best = 0;
436         struct clk_rate_request parent_req = *req;
438         /* if NO_REPARENT flag set, pass through to current parent */
439         if (core->flags & CLK_SET_RATE_NO_REPARENT) {
440                 parent = core->parent;
441                 if (core->flags & CLK_SET_RATE_PARENT) {
442                         ret = __clk_determine_rate(parent ? parent->hw : NULL,
443                                                    &parent_req);
444                         if (ret)
445                                 return ret;
447                         best = parent_req.rate;
448                 } else if (parent) {
449                         best = clk_core_get_rate_nolock(parent);
450                 } else {
451                         best = clk_core_get_rate_nolock(core);
452                 }
454                 goto out;
455         }
457         /* find the parent that can provide the fastest rate <= rate */
458         num_parents = core->num_parents;
459         for (i = 0; i < num_parents; i++) {
460                 parent = clk_core_get_parent_by_index(core, i);
461                 if (!parent)
462                         continue;
464                 if (core->flags & CLK_SET_RATE_PARENT) {
465                         parent_req = *req;
466                         ret = __clk_determine_rate(parent->hw, &parent_req);
467                         if (ret)
468                                 continue;
469                 } else {
470                         parent_req.rate = clk_core_get_rate_nolock(parent);
471                 }
473                 if (mux_is_better_rate(req->rate, parent_req.rate,
474                                        best, flags)) {
475                         best_parent = parent;
476                         best = parent_req.rate;
477                 }
478         }
480         if (!best_parent)
481                 return -EINVAL;
483 out:
484         if (best_parent)
485                 req->best_parent_hw = best_parent->hw;
486         req->best_parent_rate = best;
487         req->rate = best;
489         return 0;
491 EXPORT_SYMBOL_GPL(clk_mux_determine_rate_flags);
493 struct clk *__clk_lookup(const char *name)
495         struct clk_core *core = clk_core_lookup(name);
497         return !core ? NULL : core->hw->clk;
500 static void clk_core_get_boundaries(struct clk_core *core,
501                                     unsigned long *min_rate,
502                                     unsigned long *max_rate)
504         struct clk *clk_user;
506         *min_rate = core->min_rate;
507         *max_rate = core->max_rate;
509         hlist_for_each_entry(clk_user, &core->clks, clks_node)
510                 *min_rate = max(*min_rate, clk_user->min_rate);
512         hlist_for_each_entry(clk_user, &core->clks, clks_node)
513                 *max_rate = min(*max_rate, clk_user->max_rate);
516 void clk_hw_set_rate_range(struct clk_hw *hw, unsigned long min_rate,
517                            unsigned long max_rate)
519         hw->core->min_rate = min_rate;
520         hw->core->max_rate = max_rate;
522 EXPORT_SYMBOL_GPL(clk_hw_set_rate_range);
524 /*
525  * Helper for finding best parent to provide a given frequency. This can be used
526  * directly as a determine_rate callback (e.g. for a mux), or from a more
527  * complex clock that may combine a mux with other operations.
528  */
529 int __clk_mux_determine_rate(struct clk_hw *hw,
530                              struct clk_rate_request *req)
532         return clk_mux_determine_rate_flags(hw, req, 0);
534 EXPORT_SYMBOL_GPL(__clk_mux_determine_rate);
536 int __clk_mux_determine_rate_closest(struct clk_hw *hw,
537                                      struct clk_rate_request *req)
539         return clk_mux_determine_rate_flags(hw, req, CLK_MUX_ROUND_CLOSEST);
541 EXPORT_SYMBOL_GPL(__clk_mux_determine_rate_closest);
543 /***        clk api        ***/
545 static void clk_core_rate_unprotect(struct clk_core *core)
547         lockdep_assert_held(&prepare_lock);
549         if (!core)
550                 return;
552         if (WARN(core->protect_count == 0,
553             "%s already unprotected\n", core->name))
554                 return;
556         if (--core->protect_count > 0)
557                 return;
559         clk_core_rate_unprotect(core->parent);
562 static int clk_core_rate_nuke_protect(struct clk_core *core)
564         int ret;
566         lockdep_assert_held(&prepare_lock);
568         if (!core)
569                 return -EINVAL;
571         if (core->protect_count == 0)
572                 return 0;
574         ret = core->protect_count;
575         core->protect_count = 1;
576         clk_core_rate_unprotect(core);
578         return ret;
581 /**
582  * clk_rate_exclusive_put - release exclusivity over clock rate control
583  * @clk: the clk over which the exclusivity is released
584  *
585  * clk_rate_exclusive_put() completes a critical section during which a clock
586  * consumer cannot tolerate any other consumer making any operation on the
587  * clock which could result in a rate change or rate glitch. Exclusive clocks
588  * cannot have their rate changed, either directly or indirectly due to changes
589  * further up the parent chain of clocks. As a result, clocks up parent chain
590  * also get under exclusive control of the calling consumer.
591  *
592  * If exlusivity is claimed more than once on clock, even by the same consumer,
593  * the rate effectively gets locked as exclusivity can't be preempted.
594  *
595  * Calls to clk_rate_exclusive_put() must be balanced with calls to
596  * clk_rate_exclusive_get(). Calls to this function may sleep, and do not return
597  * error status.
598  */
599 void clk_rate_exclusive_put(struct clk *clk)
601         if (!clk)
602                 return;
604         clk_prepare_lock();
606         /*
607          * if there is something wrong with this consumer protect count, stop
608          * here before messing with the provider
609          */
610         if (WARN_ON(clk->exclusive_count <= 0))
611                 goto out;
613         clk_core_rate_unprotect(clk->core);
614         clk->exclusive_count--;
615 out:
616         clk_prepare_unlock();
618 EXPORT_SYMBOL_GPL(clk_rate_exclusive_put);
620 static void clk_core_rate_protect(struct clk_core *core)
622         lockdep_assert_held(&prepare_lock);
624         if (!core)
625                 return;
627         if (core->protect_count == 0)
628                 clk_core_rate_protect(core->parent);
630         core->protect_count++;
633 static void clk_core_rate_restore_protect(struct clk_core *core, int count)
635         lockdep_assert_held(&prepare_lock);
637         if (!core)
638                 return;
640         if (count == 0)
641                 return;
643         clk_core_rate_protect(core);
644         core->protect_count = count;
647 /**
648  * clk_rate_exclusive_get - get exclusivity over the clk rate control
649  * @clk: the clk over which the exclusity of rate control is requested
650  *
651  * clk_rate_exlusive_get() begins a critical section during which a clock
652  * consumer cannot tolerate any other consumer making any operation on the
653  * clock which could result in a rate change or rate glitch. Exclusive clocks
654  * cannot have their rate changed, either directly or indirectly due to changes
655  * further up the parent chain of clocks. As a result, clocks up parent chain
656  * also get under exclusive control of the calling consumer.
657  *
658  * If exlusivity is claimed more than once on clock, even by the same consumer,
659  * the rate effectively gets locked as exclusivity can't be preempted.
660  *
661  * Calls to clk_rate_exclusive_get() should be balanced with calls to
662  * clk_rate_exclusive_put(). Calls to this function may sleep.
663  * Returns 0 on success, -EERROR otherwise
664  */
665 int clk_rate_exclusive_get(struct clk *clk)
667         if (!clk)
668                 return 0;
670         clk_prepare_lock();
671         clk_core_rate_protect(clk->core);
672         clk->exclusive_count++;
673         clk_prepare_unlock();
675         return 0;
677 EXPORT_SYMBOL_GPL(clk_rate_exclusive_get);
679 static void clk_core_unprepare(struct clk_core *core)
681         lockdep_assert_held(&prepare_lock);
683         if (!core)
684                 return;
686         if (WARN(core->prepare_count == 0,
687             "%s already unprepared\n", core->name))
688                 return;
690         if (WARN(core->prepare_count == 1 && core->flags & CLK_IS_CRITICAL,
691             "Unpreparing critical %s\n", core->name))
692                 return;
694         if (core->flags & CLK_SET_RATE_GATE)
695                 clk_core_rate_unprotect(core);
697         if (--core->prepare_count > 0)
698                 return;
700         WARN(core->enable_count > 0, "Unpreparing enabled %s\n", core->name);
702         trace_clk_unprepare(core);
704         if (core->ops->unprepare)
705                 core->ops->unprepare(core->hw);
707         clk_pm_runtime_put(core);
709         trace_clk_unprepare_complete(core);
710         clk_core_unprepare(core->parent);
713 static void clk_core_unprepare_lock(struct clk_core *core)
715         clk_prepare_lock();
716         clk_core_unprepare(core);
717         clk_prepare_unlock();
720 /**
721  * clk_unprepare - undo preparation of a clock source
722  * @clk: the clk being unprepared
723  *
724  * clk_unprepare may sleep, which differentiates it from clk_disable.  In a
725  * simple case, clk_unprepare can be used instead of clk_disable to gate a clk
726  * if the operation may sleep.  One example is a clk which is accessed over
727  * I2c.  In the complex case a clk gate operation may require a fast and a slow
728  * part.  It is this reason that clk_unprepare and clk_disable are not mutually
729  * exclusive.  In fact clk_disable must be called before clk_unprepare.
730  */
731 void clk_unprepare(struct clk *clk)
733         if (IS_ERR_OR_NULL(clk))
734                 return;
736         clk_core_unprepare_lock(clk->core);
738 EXPORT_SYMBOL_GPL(clk_unprepare);
740 static int clk_core_prepare(struct clk_core *core)
742         int ret = 0;
744         lockdep_assert_held(&prepare_lock);
746         if (!core)
747                 return 0;
749         if (core->prepare_count == 0) {
750                 ret = clk_pm_runtime_get(core);
751                 if (ret)
752                         return ret;
754                 ret = clk_core_prepare(core->parent);
755                 if (ret)
756                         goto runtime_put;
758                 trace_clk_prepare(core);
760                 if (core->ops->prepare)
761                         ret = core->ops->prepare(core->hw);
763                 trace_clk_prepare_complete(core);
765                 if (ret)
766                         goto unprepare;
767         }
769         core->prepare_count++;
771         /*
772          * CLK_SET_RATE_GATE is a special case of clock protection
773          * Instead of a consumer claiming exclusive rate control, it is
774          * actually the provider which prevents any consumer from making any
775          * operation which could result in a rate change or rate glitch while
776          * the clock is prepared.
777          */
778         if (core->flags & CLK_SET_RATE_GATE)
779                 clk_core_rate_protect(core);
781         return 0;
782 unprepare:
783         clk_core_unprepare(core->parent);
784 runtime_put:
785         clk_pm_runtime_put(core);
786         return ret;
789 static int clk_core_prepare_lock(struct clk_core *core)
791         int ret;
793         clk_prepare_lock();
794         ret = clk_core_prepare(core);
795         clk_prepare_unlock();
797         return ret;
800 /**
801  * clk_prepare - prepare a clock source
802  * @clk: the clk being prepared
803  *
804  * clk_prepare may sleep, which differentiates it from clk_enable.  In a simple
805  * case, clk_prepare can be used instead of clk_enable to ungate a clk if the
806  * operation may sleep.  One example is a clk which is accessed over I2c.  In
807  * the complex case a clk ungate operation may require a fast and a slow part.
808  * It is this reason that clk_prepare and clk_enable are not mutually
809  * exclusive.  In fact clk_prepare must be called before clk_enable.
810  * Returns 0 on success, -EERROR otherwise.
811  */
812 int clk_prepare(struct clk *clk)
814         if (!clk)
815                 return 0;
817         return clk_core_prepare_lock(clk->core);
819 EXPORT_SYMBOL_GPL(clk_prepare);
821 static void clk_core_disable(struct clk_core *core)
823         lockdep_assert_held(&enable_lock);
825         if (!core)
826                 return;
828         if (WARN(core->enable_count == 0, "%s already disabled\n", core->name))
829                 return;
831         if (WARN(core->enable_count == 1 && core->flags & CLK_IS_CRITICAL,
832             "Disabling critical %s\n", core->name))
833                 return;
835         if (--core->enable_count > 0)
836                 return;
838         trace_clk_disable_rcuidle(core);
840         if (core->ops->disable)
841                 core->ops->disable(core->hw);
843         trace_clk_disable_complete_rcuidle(core);
845         clk_core_disable(core->parent);
848 static void clk_core_disable_lock(struct clk_core *core)
850         unsigned long flags;
852         flags = clk_enable_lock();
853         clk_core_disable(core);
854         clk_enable_unlock(flags);
857 /**
858  * clk_disable - gate a clock
859  * @clk: the clk being gated
860  *
861  * clk_disable must not sleep, which differentiates it from clk_unprepare.  In
862  * a simple case, clk_disable can be used instead of clk_unprepare to gate a
863  * clk if the operation is fast and will never sleep.  One example is a
864  * SoC-internal clk which is controlled via simple register writes.  In the
865  * complex case a clk gate operation may require a fast and a slow part.  It is
866  * this reason that clk_unprepare and clk_disable are not mutually exclusive.
867  * In fact clk_disable must be called before clk_unprepare.
868  */
869 void clk_disable(struct clk *clk)
871         if (IS_ERR_OR_NULL(clk))
872                 return;
874         clk_core_disable_lock(clk->core);
876 EXPORT_SYMBOL_GPL(clk_disable);
878 static int clk_core_enable(struct clk_core *core)
880         int ret = 0;
882         lockdep_assert_held(&enable_lock);
884         if (!core)
885                 return 0;
887         if (WARN(core->prepare_count == 0,
888             "Enabling unprepared %s\n", core->name))
889                 return -ESHUTDOWN;
891         if (core->enable_count == 0) {
892                 ret = clk_core_enable(core->parent);
894                 if (ret)
895                         return ret;
897                 trace_clk_enable_rcuidle(core);
899                 if (core->ops->enable)
900                         ret = core->ops->enable(core->hw);
902                 trace_clk_enable_complete_rcuidle(core);
904                 if (ret) {
905                         clk_core_disable(core->parent);
906                         return ret;
907                 }
908         }
910         core->enable_count++;
911         return 0;
914 static int clk_core_enable_lock(struct clk_core *core)
916         unsigned long flags;
917         int ret;
919         flags = clk_enable_lock();
920         ret = clk_core_enable(core);
921         clk_enable_unlock(flags);
923         return ret;
926 static int _clk_save_context(struct clk_core *clk)
928         struct clk_core *child;
929         int ret = 0;
931         hlist_for_each_entry(child, &clk->children, child_node) {
932                 ret = _clk_save_context(child);
933                 if (ret < 0)
934                         return ret;
935         }
937         if (clk->ops && clk->ops->save_context)
938                 ret = clk->ops->save_context(clk->hw);
940         return ret;
943 static void _clk_restore_context(struct clk_core *clk)
945         struct clk_core *child;
947         if (clk->ops && clk->ops->restore_context)
948                 clk->ops->restore_context(clk->hw);
950         hlist_for_each_entry(child, &clk->children, child_node)
951                 _clk_restore_context(child);
954 /**
955  * clk_save_context - save clock context for poweroff
956  *
957  * Saves the context of the clock register for powerstates in which the
958  * contents of the registers will be lost. Occurs deep within the suspend
959  * code.  Returns 0 on success.
960  */
961 int clk_save_context(void)
963         struct clk_core *clk;
964         int ret;
966         hlist_for_each_entry(clk, &clk_root_list, child_node) {
967                 ret = _clk_save_context(clk);
968                 if (ret < 0)
969                         return ret;
970         }
972         hlist_for_each_entry(clk, &clk_orphan_list, child_node) {
973                 ret = _clk_save_context(clk);
974                 if (ret < 0)
975                         return ret;
976         }
978         return 0;
980 EXPORT_SYMBOL_GPL(clk_save_context);
982 /**
983  * clk_restore_context - restore clock context after poweroff
984  *
985  * Restore the saved clock context upon resume.
986  *
987  */
988 void clk_restore_context(void)
990         struct clk_core *clk;
992         hlist_for_each_entry(clk, &clk_root_list, child_node)
993                 _clk_restore_context(clk);
995         hlist_for_each_entry(clk, &clk_orphan_list, child_node)
996                 _clk_restore_context(clk);
998 EXPORT_SYMBOL_GPL(clk_restore_context);
1000 /**
1001  * clk_enable - ungate a clock
1002  * @clk: the clk being ungated
1003  *
1004  * clk_enable must not sleep, which differentiates it from clk_prepare.  In a
1005  * simple case, clk_enable can be used instead of clk_prepare to ungate a clk
1006  * if the operation will never sleep.  One example is a SoC-internal clk which
1007  * is controlled via simple register writes.  In the complex case a clk ungate
1008  * operation may require a fast and a slow part.  It is this reason that
1009  * clk_enable and clk_prepare are not mutually exclusive.  In fact clk_prepare
1010  * must be called before clk_enable.  Returns 0 on success, -EERROR
1011  * otherwise.
1012  */
1013 int clk_enable(struct clk *clk)
1015         if (!clk)
1016                 return 0;
1018         return clk_core_enable_lock(clk->core);
1020 EXPORT_SYMBOL_GPL(clk_enable);
1022 static int clk_core_prepare_enable(struct clk_core *core)
1024         int ret;
1026         ret = clk_core_prepare_lock(core);
1027         if (ret)
1028                 return ret;
1030         ret = clk_core_enable_lock(core);
1031         if (ret)
1032                 clk_core_unprepare_lock(core);
1034         return ret;
1037 static void clk_core_disable_unprepare(struct clk_core *core)
1039         clk_core_disable_lock(core);
1040         clk_core_unprepare_lock(core);
1043 static void clk_unprepare_unused_subtree(struct clk_core *core)
1045         struct clk_core *child;
1047         lockdep_assert_held(&prepare_lock);
1049         hlist_for_each_entry(child, &core->children, child_node)
1050                 clk_unprepare_unused_subtree(child);
1052         if (core->prepare_count)
1053                 return;
1055         if (core->flags & CLK_IGNORE_UNUSED)
1056                 return;
1058         if (clk_pm_runtime_get(core))
1059                 return;
1061         if (clk_core_is_prepared(core)) {
1062                 trace_clk_unprepare(core);
1063                 if (core->ops->unprepare_unused)
1064                         core->ops->unprepare_unused(core->hw);
1065                 else if (core->ops->unprepare)
1066                         core->ops->unprepare(core->hw);
1067                 trace_clk_unprepare_complete(core);
1068         }
1070         clk_pm_runtime_put(core);
1073 static void clk_disable_unused_subtree(struct clk_core *core)
1075         struct clk_core *child;
1076         unsigned long flags;
1078         lockdep_assert_held(&prepare_lock);
1080         hlist_for_each_entry(child, &core->children, child_node)
1081                 clk_disable_unused_subtree(child);
1083         if (core->flags & CLK_OPS_PARENT_ENABLE)
1084                 clk_core_prepare_enable(core->parent);
1086         if (clk_pm_runtime_get(core))
1087                 goto unprepare_out;
1089         flags = clk_enable_lock();
1091         if (core->enable_count)
1092                 goto unlock_out;
1094         if (core->flags & CLK_IGNORE_UNUSED)
1095                 goto unlock_out;
1097         /*
1098          * some gate clocks have special needs during the disable-unused
1099          * sequence.  call .disable_unused if available, otherwise fall
1100          * back to .disable
1101          */
1102         if (clk_core_is_enabled(core)) {
1103                 trace_clk_disable(core);
1104                 if (core->ops->disable_unused)
1105                         core->ops->disable_unused(core->hw);
1106                 else if (core->ops->disable)
1107                         core->ops->disable(core->hw);
1108                 trace_clk_disable_complete(core);
1109         }
1111 unlock_out:
1112         clk_enable_unlock(flags);
1113         clk_pm_runtime_put(core);
1114 unprepare_out:
1115         if (core->flags & CLK_OPS_PARENT_ENABLE)
1116                 clk_core_disable_unprepare(core->parent);
1119 static bool clk_ignore_unused;
1120 static int __init clk_ignore_unused_setup(char *__unused)
1122         clk_ignore_unused = true;
1123         return 1;
1125 __setup("clk_ignore_unused", clk_ignore_unused_setup);
1127 static int clk_disable_unused(void)
1129         struct clk_core *core;
1131         if (clk_ignore_unused) {
1132                 pr_warn("clk: Not disabling unused clocks\n");
1133                 return 0;
1134         }
1136         clk_prepare_lock();
1138         hlist_for_each_entry(core, &clk_root_list, child_node)
1139                 clk_disable_unused_subtree(core);
1141         hlist_for_each_entry(core, &clk_orphan_list, child_node)
1142                 clk_disable_unused_subtree(core);
1144         hlist_for_each_entry(core, &clk_root_list, child_node)
1145                 clk_unprepare_unused_subtree(core);
1147         hlist_for_each_entry(core, &clk_orphan_list, child_node)
1148                 clk_unprepare_unused_subtree(core);
1150         clk_prepare_unlock();
1152         return 0;
1154 late_initcall_sync(clk_disable_unused);
1156 static int clk_core_determine_round_nolock(struct clk_core *core,
1157                                            struct clk_rate_request *req)
1159         long rate;
1161         lockdep_assert_held(&prepare_lock);
1163         if (!core)
1164                 return 0;
1166         /*
1167          * At this point, core protection will be disabled if
1168          * - if the provider is not protected at all
1169          * - if the calling consumer is the only one which has exclusivity
1170          *   over the provider
1171          */
1172         if (clk_core_rate_is_protected(core)) {
1173                 req->rate = core->rate;
1174         } else if (core->ops->determine_rate) {
1175                 return core->ops->determine_rate(core->hw, req);
1176         } else if (core->ops->round_rate) {
1177                 rate = core->ops->round_rate(core->hw, req->rate,
1178                                              &req->best_parent_rate);
1179                 if (rate < 0)
1180                         return rate;
1182                 req->rate = rate;
1183         } else {
1184                 return -EINVAL;
1185         }
1187         return 0;
1190 static void clk_core_init_rate_req(struct clk_core * const core,
1191                                    struct clk_rate_request *req)
1193         struct clk_core *parent;
1195         if (WARN_ON(!core || !req))
1196                 return;
1198         parent = core->parent;
1199         if (parent) {
1200                 req->best_parent_hw = parent->hw;
1201                 req->best_parent_rate = parent->rate;
1202         } else {
1203                 req->best_parent_hw = NULL;
1204                 req->best_parent_rate = 0;
1205         }
1208 static bool clk_core_can_round(struct clk_core * const core)
1210         if (core->ops->determine_rate || core->ops->round_rate)
1211                 return true;
1213         return false;
1216 static int clk_core_round_rate_nolock(struct clk_core *core,
1217                                       struct clk_rate_request *req)
1219         lockdep_assert_held(&prepare_lock);
1221         if (!core) {
1222                 req->rate = 0;
1223                 return 0;
1224         }
1226         clk_core_init_rate_req(core, req);
1228         if (clk_core_can_round(core))
1229                 return clk_core_determine_round_nolock(core, req);
1230         else if (core->flags & CLK_SET_RATE_PARENT)
1231                 return clk_core_round_rate_nolock(core->parent, req);
1233         req->rate = core->rate;
1234         return 0;
1237 /**
1238  * __clk_determine_rate - get the closest rate actually supported by a clock
1239  * @hw: determine the rate of this clock
1240  * @req: target rate request
1241  *
1242  * Useful for clk_ops such as .set_rate and .determine_rate.
1243  */
1244 int __clk_determine_rate(struct clk_hw *hw, struct clk_rate_request *req)
1246         if (!hw) {
1247                 req->rate = 0;
1248                 return 0;
1249         }
1251         return clk_core_round_rate_nolock(hw->core, req);
1253 EXPORT_SYMBOL_GPL(__clk_determine_rate);
1255 unsigned long clk_hw_round_rate(struct clk_hw *hw, unsigned long rate)
1257         int ret;
1258         struct clk_rate_request req;
1260         clk_core_get_boundaries(hw->core, &req.min_rate, &req.max_rate);
1261         req.rate = rate;
1263         ret = clk_core_round_rate_nolock(hw->core, &req);
1264         if (ret)
1265                 return 0;
1267         return req.rate;
1269 EXPORT_SYMBOL_GPL(clk_hw_round_rate);
1271 /**
1272  * clk_round_rate - round the given rate for a clk
1273  * @clk: the clk for which we are rounding a rate
1274  * @rate: the rate which is to be rounded
1275  *
1276  * Takes in a rate as input and rounds it to a rate that the clk can actually
1277  * use which is then returned.  If clk doesn't support round_rate operation
1278  * then the parent rate is returned.
1279  */
1280 long clk_round_rate(struct clk *clk, unsigned long rate)
1282         struct clk_rate_request req;
1283         int ret;
1285         if (!clk)
1286                 return 0;
1288         clk_prepare_lock();
1290         if (clk->exclusive_count)
1291                 clk_core_rate_unprotect(clk->core);
1293         clk_core_get_boundaries(clk->core, &req.min_rate, &req.max_rate);
1294         req.rate = rate;
1296         ret = clk_core_round_rate_nolock(clk->core, &req);
1298         if (clk->exclusive_count)
1299                 clk_core_rate_protect(clk->core);
1301         clk_prepare_unlock();
1303         if (ret)
1304                 return ret;
1306         return req.rate;
1308 EXPORT_SYMBOL_GPL(clk_round_rate);
1310 /**
1311  * __clk_notify - call clk notifier chain
1312  * @core: clk that is changing rate
1313  * @msg: clk notifier type (see include/linux/clk.h)
1314  * @old_rate: old clk rate
1315  * @new_rate: new clk rate
1316  *
1317  * Triggers a notifier call chain on the clk rate-change notification
1318  * for 'clk'.  Passes a pointer to the struct clk and the previous
1319  * and current rates to the notifier callback.  Intended to be called by
1320  * internal clock code only.  Returns NOTIFY_DONE from the last driver
1321  * called if all went well, or NOTIFY_STOP or NOTIFY_BAD immediately if
1322  * a driver returns that.
1323  */
1324 static int __clk_notify(struct clk_core *core, unsigned long msg,
1325                 unsigned long old_rate, unsigned long new_rate)
1327         struct clk_notifier *cn;
1328         struct clk_notifier_data cnd;
1329         int ret = NOTIFY_DONE;
1331         cnd.old_rate = old_rate;
1332         cnd.new_rate = new_rate;
1334         list_for_each_entry(cn, &clk_notifier_list, node) {
1335                 if (cn->clk->core == core) {
1336                         cnd.clk = cn->clk;
1337                         ret = srcu_notifier_call_chain(&cn->notifier_head, msg,
1338                                         &cnd);
1339                         if (ret & NOTIFY_STOP_MASK)
1340                                 return ret;
1341                 }
1342         }
1344         return ret;
1347 /**
1348  * __clk_recalc_accuracies
1349  * @core: first clk in the subtree
1350  *
1351  * Walks the subtree of clks starting with clk and recalculates accuracies as
1352  * it goes.  Note that if a clk does not implement the .recalc_accuracy
1353  * callback then it is assumed that the clock will take on the accuracy of its
1354  * parent.
1355  */
1356 static void __clk_recalc_accuracies(struct clk_core *core)
1358         unsigned long parent_accuracy = 0;
1359         struct clk_core *child;
1361         lockdep_assert_held(&prepare_lock);
1363         if (core->parent)
1364                 parent_accuracy = core->parent->accuracy;
1366         if (core->ops->recalc_accuracy)
1367                 core->accuracy = core->ops->recalc_accuracy(core->hw,
1368                                                           parent_accuracy);
1369         else
1370                 core->accuracy = parent_accuracy;
1372         hlist_for_each_entry(child, &core->children, child_node)
1373                 __clk_recalc_accuracies(child);
1376 static long clk_core_get_accuracy(struct clk_core *core)
1378         unsigned long accuracy;
1380         clk_prepare_lock();
1381         if (core && (core->flags & CLK_GET_ACCURACY_NOCACHE))
1382                 __clk_recalc_accuracies(core);
1384         accuracy = __clk_get_accuracy(core);
1385         clk_prepare_unlock();
1387         return accuracy;
1390 /**
1391  * clk_get_accuracy - return the accuracy of clk
1392  * @clk: the clk whose accuracy is being returned
1393  *
1394  * Simply returns the cached accuracy of the clk, unless
1395  * CLK_GET_ACCURACY_NOCACHE flag is set, which means a recalc_rate will be
1396  * issued.
1397  * If clk is NULL then returns 0.
1398  */
1399 long clk_get_accuracy(struct clk *clk)
1401         if (!clk)
1402                 return 0;
1404         return clk_core_get_accuracy(clk->core);
1406 EXPORT_SYMBOL_GPL(clk_get_accuracy);
1408 static unsigned long clk_recalc(struct clk_core *core,
1409                                 unsigned long parent_rate)
1411         unsigned long rate = parent_rate;
1413         if (core->ops->recalc_rate && !clk_pm_runtime_get(core)) {
1414                 rate = core->ops->recalc_rate(core->hw, parent_rate);
1415                 clk_pm_runtime_put(core);
1416         }
1417         return rate;
1420 /**
1421  * __clk_recalc_rates
1422  * @core: first clk in the subtree
1423  * @msg: notification type (see include/linux/clk.h)
1424  *
1425  * Walks the subtree of clks starting with clk and recalculates rates as it
1426  * goes.  Note that if a clk does not implement the .recalc_rate callback then
1427  * it is assumed that the clock will take on the rate of its parent.
1428  *
1429  * clk_recalc_rates also propagates the POST_RATE_CHANGE notification,
1430  * if necessary.
1431  */
1432 static void __clk_recalc_rates(struct clk_core *core, unsigned long msg)
1434         unsigned long old_rate;
1435         unsigned long parent_rate = 0;
1436         struct clk_core *child;
1438         lockdep_assert_held(&prepare_lock);
1440         old_rate = core->rate;
1442         if (core->parent)
1443                 parent_rate = core->parent->rate;
1445         core->rate = clk_recalc(core, parent_rate);
1447         /*
1448          * ignore NOTIFY_STOP and NOTIFY_BAD return values for POST_RATE_CHANGE
1449          * & ABORT_RATE_CHANGE notifiers
1450          */
1451         if (core->notifier_count && msg)
1452                 __clk_notify(core, msg, old_rate, core->rate);
1454         hlist_for_each_entry(child, &core->children, child_node)
1455                 __clk_recalc_rates(child, msg);
1458 static unsigned long clk_core_get_rate(struct clk_core *core)
1460         unsigned long rate;
1462         clk_prepare_lock();
1464         if (core && (core->flags & CLK_GET_RATE_NOCACHE))
1465                 __clk_recalc_rates(core, 0);
1467         rate = clk_core_get_rate_nolock(core);
1468         clk_prepare_unlock();
1470         return rate;
1473 /**
1474  * clk_get_rate - return the rate of clk
1475  * @clk: the clk whose rate is being returned
1476  *
1477  * Simply returns the cached rate of the clk, unless CLK_GET_RATE_NOCACHE flag
1478  * is set, which means a recalc_rate will be issued.
1479  * If clk is NULL then returns 0.
1480  */
1481 unsigned long clk_get_rate(struct clk *clk)
1483         if (!clk)
1484                 return 0;
1486         return clk_core_get_rate(clk->core);
1488 EXPORT_SYMBOL_GPL(clk_get_rate);
1490 static int clk_fetch_parent_index(struct clk_core *core,
1491                                   struct clk_core *parent)
1493         int i;
1495         if (!parent)
1496                 return -EINVAL;
1498         for (i = 0; i < core->num_parents; i++)
1499                 if (clk_core_get_parent_by_index(core, i) == parent)
1500                         return i;
1502         return -EINVAL;
1505 /*
1506  * Update the orphan status of @core and all its children.
1507  */
1508 static void clk_core_update_orphan_status(struct clk_core *core, bool is_orphan)
1510         struct clk_core *child;
1512         core->orphan = is_orphan;
1514         hlist_for_each_entry(child, &core->children, child_node)
1515                 clk_core_update_orphan_status(child, is_orphan);
1518 static void clk_reparent(struct clk_core *core, struct clk_core *new_parent)
1520         bool was_orphan = core->orphan;
1522         hlist_del(&core->child_node);
1524         if (new_parent) {
1525                 bool becomes_orphan = new_parent->orphan;
1527                 /* avoid duplicate POST_RATE_CHANGE notifications */
1528                 if (new_parent->new_child == core)
1529                         new_parent->new_child = NULL;
1531                 hlist_add_head(&core->child_node, &new_parent->children);
1533                 if (was_orphan != becomes_orphan)
1534                         clk_core_update_orphan_status(core, becomes_orphan);
1535         } else {
1536                 hlist_add_head(&core->child_node, &clk_orphan_list);
1537                 if (!was_orphan)
1538                         clk_core_update_orphan_status(core, true);
1539         }
1541         core->parent = new_parent;
1544 static struct clk_core *__clk_set_parent_before(struct clk_core *core,
1545                                            struct clk_core *parent)
1547         unsigned long flags;
1548         struct clk_core *old_parent = core->parent;
1550         /*
1551          * 1. enable parents for CLK_OPS_PARENT_ENABLE clock
1552          *
1553          * 2. Migrate prepare state between parents and prevent race with
1554          * clk_enable().
1555          *
1556          * If the clock is not prepared, then a race with
1557          * clk_enable/disable() is impossible since we already have the
1558          * prepare lock (future calls to clk_enable() need to be preceded by
1559          * a clk_prepare()).
1560          *
1561          * If the clock is prepared, migrate the prepared state to the new
1562          * parent and also protect against a race with clk_enable() by
1563          * forcing the clock and the new parent on.  This ensures that all
1564          * future calls to clk_enable() are practically NOPs with respect to
1565          * hardware and software states.
1566          *
1567          * See also: Comment for clk_set_parent() below.
1568          */
1570         /* enable old_parent & parent if CLK_OPS_PARENT_ENABLE is set */
1571         if (core->flags & CLK_OPS_PARENT_ENABLE) {
1572                 clk_core_prepare_enable(old_parent);
1573                 clk_core_prepare_enable(parent);
1574         }
1576         /* migrate prepare count if > 0 */
1577         if (core->prepare_count) {
1578                 clk_core_prepare_enable(parent);
1579                 clk_core_enable_lock(core);
1580         }
1582         /* update the clk tree topology */
1583         flags = clk_enable_lock();
1584         clk_reparent(core, parent);
1585         clk_enable_unlock(flags);
1587         return old_parent;
1590 static void __clk_set_parent_after(struct clk_core *core,
1591                                    struct clk_core *parent,
1592                                    struct clk_core *old_parent)
1594         /*
1595          * Finish the migration of prepare state and undo the changes done
1596          * for preventing a race with clk_enable().
1597          */
1598         if (core->prepare_count) {
1599                 clk_core_disable_lock(core);
1600                 clk_core_disable_unprepare(old_parent);
1601         }
1603         /* re-balance ref counting if CLK_OPS_PARENT_ENABLE is set */
1604         if (core->flags & CLK_OPS_PARENT_ENABLE) {
1605                 clk_core_disable_unprepare(parent);
1606                 clk_core_disable_unprepare(old_parent);
1607         }
1610 static int __clk_set_parent(struct clk_core *core, struct clk_core *parent,
1611                             u8 p_index)
1613         unsigned long flags;
1614         int ret = 0;
1615         struct clk_core *old_parent;
1617         old_parent = __clk_set_parent_before(core, parent);
1619         trace_clk_set_parent(core, parent);
1621         /* change clock input source */
1622         if (parent && core->ops->set_parent)
1623                 ret = core->ops->set_parent(core->hw, p_index);
1625         trace_clk_set_parent_complete(core, parent);
1627         if (ret) {
1628                 flags = clk_enable_lock();
1629                 clk_reparent(core, old_parent);
1630                 clk_enable_unlock(flags);
1631                 __clk_set_parent_after(core, old_parent, parent);
1633                 return ret;
1634         }
1636         __clk_set_parent_after(core, parent, old_parent);
1638         return 0;
1641 /**
1642  * __clk_speculate_rates
1643  * @core: first clk in the subtree
1644  * @parent_rate: the "future" rate of clk's parent
1645  *
1646  * Walks the subtree of clks starting with clk, speculating rates as it
1647  * goes and firing off PRE_RATE_CHANGE notifications as necessary.
1648  *
1649  * Unlike clk_recalc_rates, clk_speculate_rates exists only for sending
1650  * pre-rate change notifications and returns early if no clks in the
1651  * subtree have subscribed to the notifications.  Note that if a clk does not
1652  * implement the .recalc_rate callback then it is assumed that the clock will
1653  * take on the rate of its parent.
1654  */
1655 static int __clk_speculate_rates(struct clk_core *core,
1656                                  unsigned long parent_rate)
1658         struct clk_core *child;
1659         unsigned long new_rate;
1660         int ret = NOTIFY_DONE;
1662         lockdep_assert_held(&prepare_lock);
1664         new_rate = clk_recalc(core, parent_rate);
1666         /* abort rate change if a driver returns NOTIFY_BAD or NOTIFY_STOP */
1667         if (core->notifier_count)
1668                 ret = __clk_notify(core, PRE_RATE_CHANGE, core->rate, new_rate);
1670         if (ret & NOTIFY_STOP_MASK) {
1671                 pr_debug("%s: clk notifier callback for clock %s aborted with error %d\n",
1672                                 __func__, core->name, ret);
1673                 goto out;
1674         }
1676         hlist_for_each_entry(child, &core->children, child_node) {
1677                 ret = __clk_speculate_rates(child, new_rate);
1678                 if (ret & NOTIFY_STOP_MASK)
1679                         break;
1680         }
1682 out:
1683         return ret;
1686 static void clk_calc_subtree(struct clk_core *core, unsigned long new_rate,
1687                              struct clk_core *new_parent, u8 p_index)
1689         struct clk_core *child;
1691         core->new_rate = new_rate;
1692         core->new_parent = new_parent;
1693         core->new_parent_index = p_index;
1694         /* include clk in new parent's PRE_RATE_CHANGE notifications */
1695         core->new_child = NULL;
1696         if (new_parent && new_parent != core->parent)
1697                 new_parent->new_child = core;
1699         hlist_for_each_entry(child, &core->children, child_node) {
1700                 child->new_rate = clk_recalc(child, new_rate);
1701                 clk_calc_subtree(child, child->new_rate, NULL, 0);
1702         }
1705 /*
1706  * calculate the new rates returning the topmost clock that has to be
1707  * changed.
1708  */
1709 static struct clk_core *clk_calc_new_rates(struct clk_core *core,
1710                                            unsigned long rate)
1712         struct clk_core *top = core;
1713         struct clk_core *old_parent, *parent;
1714         unsigned long best_parent_rate = 0;
1715         unsigned long new_rate;
1716         unsigned long min_rate;
1717         unsigned long max_rate;
1718         int p_index = 0;
1719         long ret;
1721         /* sanity */
1722         if (IS_ERR_OR_NULL(core))
1723                 return NULL;
1725         /* save parent rate, if it exists */
1726         parent = old_parent = core->parent;
1727         if (parent)
1728                 best_parent_rate = parent->rate;
1730         clk_core_get_boundaries(core, &min_rate, &max_rate);
1732         /* find the closest rate and parent clk/rate */
1733         if (clk_core_can_round(core)) {
1734                 struct clk_rate_request req;
1736                 req.rate = rate;
1737                 req.min_rate = min_rate;
1738                 req.max_rate = max_rate;
1740                 clk_core_init_rate_req(core, &req);
1742                 ret = clk_core_determine_round_nolock(core, &req);
1743                 if (ret < 0)
1744                         return NULL;
1746                 best_parent_rate = req.best_parent_rate;
1747                 new_rate = req.rate;
1748                 parent = req.best_parent_hw ? req.best_parent_hw->core : NULL;
1750                 if (new_rate < min_rate || new_rate > max_rate)
1751                         return NULL;
1752         } else if (!parent || !(core->flags & CLK_SET_RATE_PARENT)) {
1753                 /* pass-through clock without adjustable parent */
1754                 core->new_rate = core->rate;
1755                 return NULL;
1756         } else {
1757                 /* pass-through clock with adjustable parent */
1758                 top = clk_calc_new_rates(parent, rate);
1759                 new_rate = parent->new_rate;
1760                 goto out;
1761         }
1763         /* some clocks must be gated to change parent */
1764         if (parent != old_parent &&
1765             (core->flags & CLK_SET_PARENT_GATE) && core->prepare_count) {
1766                 pr_debug("%s: %s not gated but wants to reparent\n",
1767                          __func__, core->name);
1768                 return NULL;
1769         }
1771         /* try finding the new parent index */
1772         if (parent && core->num_parents > 1) {
1773                 p_index = clk_fetch_parent_index(core, parent);
1774                 if (p_index < 0) {
1775                         pr_debug("%s: clk %s can not be parent of clk %s\n",
1776                                  __func__, parent->name, core->name);
1777                         return NULL;
1778                 }
1779         }
1781         if ((core->flags & CLK_SET_RATE_PARENT) && parent &&
1782             best_parent_rate != parent->rate)
1783                 top = clk_calc_new_rates(parent, best_parent_rate);
1785 out:
1786         clk_calc_subtree(core, new_rate, parent, p_index);
1788         return top;
1791 /*
1792  * Notify about rate changes in a subtree. Always walk down the whole tree
1793  * so that in case of an error we can walk down the whole tree again and
1794  * abort the change.
1795  */
1796 static struct clk_core *clk_propagate_rate_change(struct clk_core *core,
1797                                                   unsigned long event)
1799         struct clk_core *child, *tmp_clk, *fail_clk = NULL;
1800         int ret = NOTIFY_DONE;
1802         if (core->rate == core->new_rate)
1803                 return NULL;
1805         if (core->notifier_count) {
1806                 ret = __clk_notify(core, event, core->rate, core->new_rate);
1807                 if (ret & NOTIFY_STOP_MASK)
1808                         fail_clk = core;
1809         }
1811         hlist_for_each_entry(child, &core->children, child_node) {
1812                 /* Skip children who will be reparented to another clock */
1813                 if (child->new_parent && child->new_parent != core)
1814                         continue;
1815                 tmp_clk = clk_propagate_rate_change(child, event);
1816                 if (tmp_clk)
1817                         fail_clk = tmp_clk;
1818         }
1820         /* handle the new child who might not be in core->children yet */
1821         if (core->new_child) {
1822                 tmp_clk = clk_propagate_rate_change(core->new_child, event);
1823                 if (tmp_clk)
1824                         fail_clk = tmp_clk;
1825         }
1827         return fail_clk;
1830 /*
1831  * walk down a subtree and set the new rates notifying the rate
1832  * change on the way
1833  */
1834 static void clk_change_rate(struct clk_core *core)
1836         struct clk_core *child;
1837         struct hlist_node *tmp;
1838         unsigned long old_rate;
1839         unsigned long best_parent_rate = 0;
1840         bool skip_set_rate = false;
1841         struct clk_core *old_parent;
1842         struct clk_core *parent = NULL;
1844         old_rate = core->rate;
1846         if (core->new_parent) {
1847                 parent = core->new_parent;
1848                 best_parent_rate = core->new_parent->rate;
1849         } else if (core->parent) {
1850                 parent = core->parent;
1851                 best_parent_rate = core->parent->rate;
1852         }
1854         if (clk_pm_runtime_get(core))
1855                 return;
1857         if (core->flags & CLK_SET_RATE_UNGATE) {
1858                 unsigned long flags;
1860                 clk_core_prepare(core);
1861                 flags = clk_enable_lock();
1862                 clk_core_enable(core);
1863                 clk_enable_unlock(flags);
1864         }
1866         if (core->new_parent && core->new_parent != core->parent) {
1867                 old_parent = __clk_set_parent_before(core, core->new_parent);
1868                 trace_clk_set_parent(core, core->new_parent);
1870                 if (core->ops->set_rate_and_parent) {
1871                         skip_set_rate = true;
1872                         core->ops->set_rate_and_parent(core->hw, core->new_rate,
1873                                         best_parent_rate,
1874                                         core->new_parent_index);
1875                 } else if (core->ops->set_parent) {
1876                         core->ops->set_parent(core->hw, core->new_parent_index);
1877                 }
1879                 trace_clk_set_parent_complete(core, core->new_parent);
1880                 __clk_set_parent_after(core, core->new_parent, old_parent);
1881         }
1883         if (core->flags & CLK_OPS_PARENT_ENABLE)
1884                 clk_core_prepare_enable(parent);
1886         trace_clk_set_rate(core, core->new_rate);
1888         if (!skip_set_rate && core->ops->set_rate)
1889                 core->ops->set_rate(core->hw, core->new_rate, best_parent_rate);
1891         trace_clk_set_rate_complete(core, core->new_rate);
1893         core->rate = clk_recalc(core, best_parent_rate);
1895         if (core->flags & CLK_SET_RATE_UNGATE) {
1896                 unsigned long flags;
1898                 flags = clk_enable_lock();
1899                 clk_core_disable(core);
1900                 clk_enable_unlock(flags);
1901                 clk_core_unprepare(core);
1902         }
1904         if (core->flags & CLK_OPS_PARENT_ENABLE)
1905                 clk_core_disable_unprepare(parent);
1907         if (core->notifier_count && old_rate != core->rate)
1908                 __clk_notify(core, POST_RATE_CHANGE, old_rate, core->rate);
1910         if (core->flags & CLK_RECALC_NEW_RATES)
1911                 (void)clk_calc_new_rates(core, core->new_rate);
1913         /*
1914          * Use safe iteration, as change_rate can actually swap parents
1915          * for certain clock types.
1916          */
1917         hlist_for_each_entry_safe(child, tmp, &core->children, child_node) {
1918                 /* Skip children who will be reparented to another clock */
1919                 if (child->new_parent && child->new_parent != core)
1920                         continue;
1921                 clk_change_rate(child);
1922         }
1924         /* handle the new child who might not be in core->children yet */
1925         if (core->new_child)
1926                 clk_change_rate(core->new_child);
1928         clk_pm_runtime_put(core);
1931 static unsigned long clk_core_req_round_rate_nolock(struct clk_core *core,
1932                                                      unsigned long req_rate)
1934         int ret, cnt;
1935         struct clk_rate_request req;
1937         lockdep_assert_held(&prepare_lock);
1939         if (!core)
1940                 return 0;
1942         /* simulate what the rate would be if it could be freely set */
1943         cnt = clk_core_rate_nuke_protect(core);
1944         if (cnt < 0)
1945                 return cnt;
1947         clk_core_get_boundaries(core, &req.min_rate, &req.max_rate);
1948         req.rate = req_rate;
1950         ret = clk_core_round_rate_nolock(core, &req);
1952         /* restore the protection */
1953         clk_core_rate_restore_protect(core, cnt);
1955         return ret ? 0 : req.rate;
1958 static int clk_core_set_rate_nolock(struct clk_core *core,
1959                                     unsigned long req_rate)
1961         struct clk_core *top, *fail_clk;
1962         unsigned long rate;
1963         int ret = 0;
1965         if (!core)
1966                 return 0;
1968         rate = clk_core_req_round_rate_nolock(core, req_rate);
1970         /* bail early if nothing to do */
1971         if (rate == clk_core_get_rate_nolock(core))
1972                 return 0;
1974         /* fail on a direct rate set of a protected provider */
1975         if (clk_core_rate_is_protected(core))
1976                 return -EBUSY;
1978         /* calculate new rates and get the topmost changed clock */
1979         top = clk_calc_new_rates(core, req_rate);
1980         if (!top)
1981                 return -EINVAL;
1983         ret = clk_pm_runtime_get(core);
1984         if (ret)
1985                 return ret;
1987         /* notify that we are about to change rates */
1988         fail_clk = clk_propagate_rate_change(top, PRE_RATE_CHANGE);
1989         if (fail_clk) {
1990                 pr_debug("%s: failed to set %s rate\n", __func__,
1991                                 fail_clk->name);
1992                 clk_propagate_rate_change(top, ABORT_RATE_CHANGE);
1993                 ret = -EBUSY;
1994                 goto err;
1995         }
1997         /* change the rates */
1998         clk_change_rate(top);
2000         core->req_rate = req_rate;
2001 err:
2002         clk_pm_runtime_put(core);
2004         return ret;
2007 /**
2008  * clk_set_rate - specify a new rate for clk
2009  * @clk: the clk whose rate is being changed
2010  * @rate: the new rate for clk
2011  *
2012  * In the simplest case clk_set_rate will only adjust the rate of clk.
2013  *
2014  * Setting the CLK_SET_RATE_PARENT flag allows the rate change operation to
2015  * propagate up to clk's parent; whether or not this happens depends on the
2016  * outcome of clk's .round_rate implementation.  If *parent_rate is unchanged
2017  * after calling .round_rate then upstream parent propagation is ignored.  If
2018  * *parent_rate comes back with a new rate for clk's parent then we propagate
2019  * up to clk's parent and set its rate.  Upward propagation will continue
2020  * until either a clk does not support the CLK_SET_RATE_PARENT flag or
2021  * .round_rate stops requesting changes to clk's parent_rate.
2022  *
2023  * Rate changes are accomplished via tree traversal that also recalculates the
2024  * rates for the clocks and fires off POST_RATE_CHANGE notifiers.
2025  *
2026  * Returns 0 on success, -EERROR otherwise.
2027  */
2028 int clk_set_rate(struct clk *clk, unsigned long rate)
2030         int ret;
2032         if (!clk)
2033                 return 0;
2035         /* prevent racing with updates to the clock topology */
2036         clk_prepare_lock();
2038         if (clk->exclusive_count)
2039                 clk_core_rate_unprotect(clk->core);
2041         ret = clk_core_set_rate_nolock(clk->core, rate);
2043         if (clk->exclusive_count)
2044                 clk_core_rate_protect(clk->core);
2046         clk_prepare_unlock();
2048         return ret;
2050 EXPORT_SYMBOL_GPL(clk_set_rate);
2052 /**
2053  * clk_set_rate_exclusive - specify a new rate get exclusive control
2054  * @clk: the clk whose rate is being changed
2055  * @rate: the new rate for clk
2056  *
2057  * This is a combination of clk_set_rate() and clk_rate_exclusive_get()
2058  * within a critical section
2059  *
2060  * This can be used initially to ensure that at least 1 consumer is
2061  * statisfied when several consumers are competing for exclusivity over the
2062  * same clock provider.
2063  *
2064  * The exclusivity is not applied if setting the rate failed.
2065  *
2066  * Calls to clk_rate_exclusive_get() should be balanced with calls to
2067  * clk_rate_exclusive_put().
2068  *
2069  * Returns 0 on success, -EERROR otherwise.
2070  */
2071 int clk_set_rate_exclusive(struct clk *clk, unsigned long rate)
2073         int ret;
2075         if (!clk)
2076                 return 0;
2078         /* prevent racing with updates to the clock topology */
2079         clk_prepare_lock();
2081         /*
2082          * The temporary protection removal is not here, on purpose
2083          * This function is meant to be used instead of clk_rate_protect,
2084          * so before the consumer code path protect the clock provider
2085          */
2087         ret = clk_core_set_rate_nolock(clk->core, rate);
2088         if (!ret) {
2089                 clk_core_rate_protect(clk->core);
2090                 clk->exclusive_count++;
2091         }
2093         clk_prepare_unlock();
2095         return ret;
2097 EXPORT_SYMBOL_GPL(clk_set_rate_exclusive);
2099 /**
2100  * clk_set_rate_range - set a rate range for a clock source
2101  * @clk: clock source
2102  * @min: desired minimum clock rate in Hz, inclusive
2103  * @max: desired maximum clock rate in Hz, inclusive
2104  *
2105  * Returns success (0) or negative errno.
2106  */
2107 int clk_set_rate_range(struct clk *clk, unsigned long min, unsigned long max)
2109         int ret = 0;
2110         unsigned long old_min, old_max, rate;
2112         if (!clk)
2113                 return 0;
2115         if (min > max) {
2116                 pr_err("%s: clk %s dev %s con %s: invalid range [%lu, %lu]\n",
2117                        __func__, clk->core->name, clk->dev_id, clk->con_id,
2118                        min, max);
2119                 return -EINVAL;
2120         }
2122         clk_prepare_lock();
2124         if (clk->exclusive_count)
2125                 clk_core_rate_unprotect(clk->core);
2127         /* Save the current values in case we need to rollback the change */
2128         old_min = clk->min_rate;
2129         old_max = clk->max_rate;
2130         clk->min_rate = min;
2131         clk->max_rate = max;
2133         rate = clk_core_get_rate_nolock(clk->core);
2134         if (rate < min || rate > max) {
2135                 /*
2136                  * FIXME:
2137                  * We are in bit of trouble here, current rate is outside the
2138                  * the requested range. We are going try to request appropriate
2139                  * range boundary but there is a catch. It may fail for the
2140                  * usual reason (clock broken, clock protected, etc) but also
2141                  * because:
2142                  * - round_rate() was not favorable and fell on the wrong
2143                  *   side of the boundary
2144                  * - the determine_rate() callback does not really check for
2145                  *   this corner case when determining the rate
2146                  */
2148                 if (rate < min)
2149                         rate = min;
2150                 else
2151                         rate = max;
2153                 ret = clk_core_set_rate_nolock(clk->core, rate);
2154                 if (ret) {
2155                         /* rollback the changes */
2156                         clk->min_rate = old_min;
2157                         clk->max_rate = old_max;
2158                 }
2159         }
2161         if (clk->exclusive_count)
2162                 clk_core_rate_protect(clk->core);
2164         clk_prepare_unlock();
2166         return ret;
2168 EXPORT_SYMBOL_GPL(clk_set_rate_range);
2170 /**
2171  * clk_set_min_rate - set a minimum clock rate for a clock source
2172  * @clk: clock source
2173  * @rate: desired minimum clock rate in Hz, inclusive
2174  *
2175  * Returns success (0) or negative errno.
2176  */
2177 int clk_set_min_rate(struct clk *clk, unsigned long rate)
2179         if (!clk)
2180                 return 0;
2182         return clk_set_rate_range(clk, rate, clk->max_rate);
2184 EXPORT_SYMBOL_GPL(clk_set_min_rate);
2186 /**
2187  * clk_set_max_rate - set a maximum clock rate for a clock source
2188  * @clk: clock source
2189  * @rate: desired maximum clock rate in Hz, inclusive
2190  *
2191  * Returns success (0) or negative errno.
2192  */
2193 int clk_set_max_rate(struct clk *clk, unsigned long rate)
2195         if (!clk)
2196                 return 0;
2198         return clk_set_rate_range(clk, clk->min_rate, rate);
2200 EXPORT_SYMBOL_GPL(clk_set_max_rate);
2202 /**
2203  * clk_get_parent - return the parent of a clk
2204  * @clk: the clk whose parent gets returned
2205  *
2206  * Simply returns clk->parent.  Returns NULL if clk is NULL.
2207  */
2208 struct clk *clk_get_parent(struct clk *clk)
2210         struct clk *parent;
2212         if (!clk)
2213                 return NULL;
2215         clk_prepare_lock();
2216         /* TODO: Create a per-user clk and change callers to call clk_put */
2217         parent = !clk->core->parent ? NULL : clk->core->parent->hw->clk;
2218         clk_prepare_unlock();
2220         return parent;
2222 EXPORT_SYMBOL_GPL(clk_get_parent);
2224 static struct clk_core *__clk_init_parent(struct clk_core *core)
2226         u8 index = 0;
2228         if (core->num_parents > 1 && core->ops->get_parent)
2229                 index = core->ops->get_parent(core->hw);
2231         return clk_core_get_parent_by_index(core, index);
2234 static void clk_core_reparent(struct clk_core *core,
2235                                   struct clk_core *new_parent)
2237         clk_reparent(core, new_parent);
2238         __clk_recalc_accuracies(core);
2239         __clk_recalc_rates(core, POST_RATE_CHANGE);
2242 void clk_hw_reparent(struct clk_hw *hw, struct clk_hw *new_parent)
2244         if (!hw)
2245                 return;
2247         clk_core_reparent(hw->core, !new_parent ? NULL : new_parent->core);
2250 /**
2251  * clk_has_parent - check if a clock is a possible parent for another
2252  * @clk: clock source
2253  * @parent: parent clock source
2254  *
2255  * This function can be used in drivers that need to check that a clock can be
2256  * the parent of another without actually changing the parent.
2257  *
2258  * Returns true if @parent is a possible parent for @clk, false otherwise.
2259  */
2260 bool clk_has_parent(struct clk *clk, struct clk *parent)
2262         struct clk_core *core, *parent_core;
2264         /* NULL clocks should be nops, so return success if either is NULL. */
2265         if (!clk || !parent)
2266                 return true;
2268         core = clk->core;
2269         parent_core = parent->core;
2271         /* Optimize for the case where the parent is already the parent. */
2272         if (core->parent == parent_core)
2273                 return true;
2275         return match_string(core->parent_names, core->num_parents,
2276                             parent_core->name) >= 0;
2278 EXPORT_SYMBOL_GPL(clk_has_parent);
2280 static int clk_core_set_parent_nolock(struct clk_core *core,
2281                                       struct clk_core *parent)
2283         int ret = 0;
2284         int p_index = 0;
2285         unsigned long p_rate = 0;
2287         lockdep_assert_held(&prepare_lock);
2289         if (!core)
2290                 return 0;
2292         if (core->parent == parent)
2293                 return 0;
2295         /* verify ops for for multi-parent clks */
2296         if (core->num_parents > 1 && !core->ops->set_parent)
2297                 return -EPERM;
2299         /* check that we are allowed to re-parent if the clock is in use */
2300         if ((core->flags & CLK_SET_PARENT_GATE) && core->prepare_count)
2301                 return -EBUSY;
2303         if (clk_core_rate_is_protected(core))
2304                 return -EBUSY;
2306         /* try finding the new parent index */
2307         if (parent) {
2308                 p_index = clk_fetch_parent_index(core, parent);
2309                 if (p_index < 0) {
2310                         pr_debug("%s: clk %s can not be parent of clk %s\n",
2311                                         __func__, parent->name, core->name);
2312                         return p_index;
2313                 }
2314                 p_rate = parent->rate;
2315         }
2317         ret = clk_pm_runtime_get(core);
2318         if (ret)
2319                 return ret;
2321         /* propagate PRE_RATE_CHANGE notifications */
2322         ret = __clk_speculate_rates(core, p_rate);
2324         /* abort if a driver objects */
2325         if (ret & NOTIFY_STOP_MASK)
2326                 goto runtime_put;
2328         /* do the re-parent */
2329         ret = __clk_set_parent(core, parent, p_index);
2331         /* propagate rate an accuracy recalculation accordingly */
2332         if (ret) {
2333                 __clk_recalc_rates(core, ABORT_RATE_CHANGE);
2334         } else {
2335                 __clk_recalc_rates(core, POST_RATE_CHANGE);
2336                 __clk_recalc_accuracies(core);
2337         }
2339 runtime_put:
2340         clk_pm_runtime_put(core);
2342         return ret;
2345 /**
2346  * clk_set_parent - switch the parent of a mux clk
2347  * @clk: the mux clk whose input we are switching
2348  * @parent: the new input to clk
2349  *
2350  * Re-parent clk to use parent as its new input source.  If clk is in
2351  * prepared state, the clk will get enabled for the duration of this call. If
2352  * that's not acceptable for a specific clk (Eg: the consumer can't handle
2353  * that, the reparenting is glitchy in hardware, etc), use the
2354  * CLK_SET_PARENT_GATE flag to allow reparenting only when clk is unprepared.
2355  *
2356  * After successfully changing clk's parent clk_set_parent will update the
2357  * clk topology, sysfs topology and propagate rate recalculation via
2358  * __clk_recalc_rates.
2359  *
2360  * Returns 0 on success, -EERROR otherwise.
2361  */
2362 int clk_set_parent(struct clk *clk, struct clk *parent)
2364         int ret;
2366         if (!clk)
2367                 return 0;
2369         clk_prepare_lock();
2371         if (clk->exclusive_count)
2372                 clk_core_rate_unprotect(clk->core);
2374         ret = clk_core_set_parent_nolock(clk->core,
2375                                          parent ? parent->core : NULL);
2377         if (clk->exclusive_count)
2378                 clk_core_rate_protect(clk->core);
2380         clk_prepare_unlock();
2382         return ret;
2384 EXPORT_SYMBOL_GPL(clk_set_parent);
2386 static int clk_core_set_phase_nolock(struct clk_core *core, int degrees)
2388         int ret = -EINVAL;
2390         lockdep_assert_held(&prepare_lock);
2392         if (!core)
2393                 return 0;
2395         if (clk_core_rate_is_protected(core))
2396                 return -EBUSY;
2398         trace_clk_set_phase(core, degrees);
2400         if (core->ops->set_phase) {
2401                 ret = core->ops->set_phase(core->hw, degrees);
2402                 if (!ret)
2403                         core->phase = degrees;
2404         }
2406         trace_clk_set_phase_complete(core, degrees);
2408         return ret;
2411 /**
2412  * clk_set_phase - adjust the phase shift of a clock signal
2413  * @clk: clock signal source
2414  * @degrees: number of degrees the signal is shifted
2415  *
2416  * Shifts the phase of a clock signal by the specified
2417  * degrees. Returns 0 on success, -EERROR otherwise.
2418  *
2419  * This function makes no distinction about the input or reference
2420  * signal that we adjust the clock signal phase against. For example
2421  * phase locked-loop clock signal generators we may shift phase with
2422  * respect to feedback clock signal input, but for other cases the
2423  * clock phase may be shifted with respect to some other, unspecified
2424  * signal.
2425  *
2426  * Additionally the concept of phase shift does not propagate through
2427  * the clock tree hierarchy, which sets it apart from clock rates and
2428  * clock accuracy. A parent clock phase attribute does not have an
2429  * impact on the phase attribute of a child clock.
2430  */
2431 int clk_set_phase(struct clk *clk, int degrees)
2433         int ret;
2435         if (!clk)
2436                 return 0;
2438         /* sanity check degrees */
2439         degrees %= 360;
2440         if (degrees < 0)
2441                 degrees += 360;
2443         clk_prepare_lock();
2445         if (clk->exclusive_count)
2446                 clk_core_rate_unprotect(clk->core);
2448         ret = clk_core_set_phase_nolock(clk->core, degrees);
2450         if (clk->exclusive_count)
2451                 clk_core_rate_protect(clk->core);
2453         clk_prepare_unlock();
2455         return ret;
2457 EXPORT_SYMBOL_GPL(clk_set_phase);
2459 static int clk_core_get_phase(struct clk_core *core)
2461         int ret;
2463         clk_prepare_lock();
2464         /* Always try to update cached phase if possible */
2465         if (core->ops->get_phase)
2466                 core->phase = core->ops->get_phase(core->hw);
2467         ret = core->phase;
2468         clk_prepare_unlock();
2470         return ret;
2473 /**
2474  * clk_get_phase - return the phase shift of a clock signal
2475  * @clk: clock signal source
2476  *
2477  * Returns the phase shift of a clock node in degrees, otherwise returns
2478  * -EERROR.
2479  */
2480 int clk_get_phase(struct clk *clk)
2482         if (!clk)
2483                 return 0;
2485         return clk_core_get_phase(clk->core);
2487 EXPORT_SYMBOL_GPL(clk_get_phase);
2489 static void clk_core_reset_duty_cycle_nolock(struct clk_core *core)
2491         /* Assume a default value of 50% */
2492         core->duty.num = 1;
2493         core->duty.den = 2;
2496 static int clk_core_update_duty_cycle_parent_nolock(struct clk_core *core);
2498 static int clk_core_update_duty_cycle_nolock(struct clk_core *core)
2500         struct clk_duty *duty = &core->duty;
2501         int ret = 0;
2503         if (!core->ops->get_duty_cycle)
2504                 return clk_core_update_duty_cycle_parent_nolock(core);
2506         ret = core->ops->get_duty_cycle(core->hw, duty);
2507         if (ret)
2508                 goto reset;
2510         /* Don't trust the clock provider too much */
2511         if (duty->den == 0 || duty->num > duty->den) {
2512                 ret = -EINVAL;
2513                 goto reset;
2514         }
2516         return 0;
2518 reset:
2519         clk_core_reset_duty_cycle_nolock(core);
2520         return ret;
2523 static int clk_core_update_duty_cycle_parent_nolock(struct clk_core *core)
2525         int ret = 0;
2527         if (core->parent &&
2528             core->flags & CLK_DUTY_CYCLE_PARENT) {
2529                 ret = clk_core_update_duty_cycle_nolock(core->parent);
2530                 memcpy(&core->duty, &core->parent->duty, sizeof(core->duty));
2531         } else {
2532                 clk_core_reset_duty_cycle_nolock(core);
2533         }
2535         return ret;
2538 static int clk_core_set_duty_cycle_parent_nolock(struct clk_core *core,
2539                                                  struct clk_duty *duty);
2541 static int clk_core_set_duty_cycle_nolock(struct clk_core *core,
2542                                           struct clk_duty *duty)
2544         int ret;
2546         lockdep_assert_held(&prepare_lock);
2548         if (clk_core_rate_is_protected(core))
2549                 return -EBUSY;
2551         trace_clk_set_duty_cycle(core, duty);
2553         if (!core->ops->set_duty_cycle)
2554                 return clk_core_set_duty_cycle_parent_nolock(core, duty);
2556         ret = core->ops->set_duty_cycle(core->hw, duty);
2557         if (!ret)
2558                 memcpy(&core->duty, duty, sizeof(*duty));
2560         trace_clk_set_duty_cycle_complete(core, duty);
2562         return ret;
2565 static int clk_core_set_duty_cycle_parent_nolock(struct clk_core *core,
2566                                                  struct clk_duty *duty)
2568         int ret = 0;
2570         if (core->parent &&
2571             core->flags & (CLK_DUTY_CYCLE_PARENT | CLK_SET_RATE_PARENT)) {
2572                 ret = clk_core_set_duty_cycle_nolock(core->parent, duty);
2573                 memcpy(&core->duty, &core->parent->duty, sizeof(core->duty));
2574         }
2576         return ret;
2579 /**
2580  * clk_set_duty_cycle - adjust the duty cycle ratio of a clock signal
2581  * @clk: clock signal source
2582  * @num: numerator of the duty cycle ratio to be applied
2583  * @den: denominator of the duty cycle ratio to be applied
2584  *
2585  * Apply the duty cycle ratio if the ratio is valid and the clock can
2586  * perform this operation
2587  *
2588  * Returns (0) on success, a negative errno otherwise.
2589  */
2590 int clk_set_duty_cycle(struct clk *clk, unsigned int num, unsigned int den)
2592         int ret;
2593         struct clk_duty duty;
2595         if (!clk)
2596                 return 0;
2598         /* sanity check the ratio */
2599         if (den == 0 || num > den)
2600                 return -EINVAL;
2602         duty.num = num;
2603         duty.den = den;
2605         clk_prepare_lock();
2607         if (clk->exclusive_count)
2608                 clk_core_rate_unprotect(clk->core);
2610         ret = clk_core_set_duty_cycle_nolock(clk->core, &duty);
2612         if (clk->exclusive_count)
2613                 clk_core_rate_protect(clk->core);
2615         clk_prepare_unlock();
2617         return ret;
2619 EXPORT_SYMBOL_GPL(clk_set_duty_cycle);
2621 static int clk_core_get_scaled_duty_cycle(struct clk_core *core,
2622                                           unsigned int scale)
2624         struct clk_duty *duty = &core->duty;
2625         int ret;
2627         clk_prepare_lock();
2629         ret = clk_core_update_duty_cycle_nolock(core);
2630         if (!ret)
2631                 ret = mult_frac(scale, duty->num, duty->den);
2633         clk_prepare_unlock();
2635         return ret;
2638 /**
2639  * clk_get_scaled_duty_cycle - return the duty cycle ratio of a clock signal
2640  * @clk: clock signal source
2641  * @scale: scaling factor to be applied to represent the ratio as an integer
2642  *
2643  * Returns the duty cycle ratio of a clock node multiplied by the provided
2644  * scaling factor, or negative errno on error.
2645  */
2646 int clk_get_scaled_duty_cycle(struct clk *clk, unsigned int scale)
2648         if (!clk)
2649                 return 0;
2651         return clk_core_get_scaled_duty_cycle(clk->core, scale);
2653 EXPORT_SYMBOL_GPL(clk_get_scaled_duty_cycle);
2655 /**
2656  * clk_is_match - check if two clk's point to the same hardware clock
2657  * @p: clk compared against q
2658  * @q: clk compared against p
2659  *
2660  * Returns true if the two struct clk pointers both point to the same hardware
2661  * clock node. Put differently, returns true if struct clk *p and struct clk *q
2662  * share the same struct clk_core object.
2663  *
2664  * Returns false otherwise. Note that two NULL clks are treated as matching.
2665  */
2666 bool clk_is_match(const struct clk *p, const struct clk *q)
2668         /* trivial case: identical struct clk's or both NULL */
2669         if (p == q)
2670                 return true;
2672         /* true if clk->core pointers match. Avoid dereferencing garbage */
2673         if (!IS_ERR_OR_NULL(p) && !IS_ERR_OR_NULL(q))
2674                 if (p->core == q->core)
2675                         return true;
2677         return false;
2679 EXPORT_SYMBOL_GPL(clk_is_match);
2681 /***        debugfs support        ***/
2683 #ifdef CONFIG_DEBUG_FS
2684 #include <linux/debugfs.h>
2686 static struct dentry *rootdir;
2687 static int inited = 0;
2688 static DEFINE_MUTEX(clk_debug_lock);
2689 static HLIST_HEAD(clk_debug_list);
2691 static struct hlist_head *all_lists[] = {
2692         &clk_root_list,
2693         &clk_orphan_list,
2694         NULL,
2695 };
2697 static struct hlist_head *orphan_list[] = {
2698         &clk_orphan_list,
2699         NULL,
2700 };
2702 static void clk_summary_show_one(struct seq_file *s, struct clk_core *c,
2703                                  int level)
2705         if (!c)
2706                 return;
2708         seq_printf(s, "%*s%-*s %7d %8d %8d %11lu %10lu %5d %6d\n",
2709                    level * 3 + 1, "",
2710                    30 - level * 3, c->name,
2711                    c->enable_count, c->prepare_count, c->protect_count,
2712                    clk_core_get_rate(c), clk_core_get_accuracy(c),
2713                    clk_core_get_phase(c),
2714                    clk_core_get_scaled_duty_cycle(c, 100000));
2717 static void clk_summary_show_subtree(struct seq_file *s, struct clk_core *c,
2718                                      int level)
2720         struct clk_core *child;
2722         if (!c)
2723                 return;
2725         clk_summary_show_one(s, c, level);
2727         hlist_for_each_entry(child, &c->children, child_node)
2728                 clk_summary_show_subtree(s, child, level + 1);
2731 static int clk_summary_show(struct seq_file *s, void *data)
2733         struct clk_core *c;
2734         struct hlist_head **lists = (struct hlist_head **)s->private;
2736         seq_puts(s, "                                 enable  prepare  protect                                duty\n");
2737         seq_puts(s, "   clock                          count    count    count        rate   accuracy phase  cycle\n");
2738         seq_puts(s, "---------------------------------------------------------------------------------------------\n");
2740         clk_prepare_lock();
2742         for (; *lists; lists++)
2743                 hlist_for_each_entry(c, *lists, child_node)
2744                         clk_summary_show_subtree(s, c, 0);
2746         clk_prepare_unlock();
2748         return 0;
2750 DEFINE_SHOW_ATTRIBUTE(clk_summary);
2752 static void clk_dump_one(struct seq_file *s, struct clk_core *c, int level)
2754         if (!c)
2755                 return;
2757         /* This should be JSON format, i.e. elements separated with a comma */
2758         seq_printf(s, "\"%s\": { ", c->name);
2759         seq_printf(s, "\"enable_count\": %d,", c->enable_count);
2760         seq_printf(s, "\"prepare_count\": %d,", c->prepare_count);
2761         seq_printf(s, "\"protect_count\": %d,", c->protect_count);
2762         seq_printf(s, "\"rate\": %lu,", clk_core_get_rate(c));
2763         seq_printf(s, "\"accuracy\": %lu,", clk_core_get_accuracy(c));
2764         seq_printf(s, "\"phase\": %d", clk_core_get_phase(c));
2765         seq_printf(s, "\"duty_cycle\": %u",
2766                    clk_core_get_scaled_duty_cycle(c, 100000));
2769 static void clk_dump_subtree(struct seq_file *s, struct clk_core *c, int level)
2771         struct clk_core *child;
2773         if (!c)
2774                 return;
2776         clk_dump_one(s, c, level);
2778         hlist_for_each_entry(child, &c->children, child_node) {
2779                 seq_putc(s, ',');
2780                 clk_dump_subtree(s, child, level + 1);
2781         }
2783         seq_putc(s, '}');
2786 static int clk_dump_show(struct seq_file *s, void *data)
2788         struct clk_core *c;
2789         bool first_node = true;
2790         struct hlist_head **lists = (struct hlist_head **)s->private;
2792         seq_putc(s, '{');
2793         clk_prepare_lock();
2795         for (; *lists; lists++) {
2796                 hlist_for_each_entry(c, *lists, child_node) {
2797                         if (!first_node)
2798                                 seq_putc(s, ',');
2799                         first_node = false;
2800                         clk_dump_subtree(s, c, 0);
2801                 }
2802         }
2804         clk_prepare_unlock();
2806         seq_puts(s, "}\n");
2807         return 0;
2809 DEFINE_SHOW_ATTRIBUTE(clk_dump);
2811 static const struct {
2812         unsigned long flag;
2813         const char *name;
2814 } clk_flags[] = {
2815 #define ENTRY(f) { f, #f }
2816         ENTRY(CLK_SET_RATE_GATE),
2817         ENTRY(CLK_SET_PARENT_GATE),
2818         ENTRY(CLK_SET_RATE_PARENT),
2819         ENTRY(CLK_IGNORE_UNUSED),
2820         ENTRY(CLK_IS_BASIC),
2821         ENTRY(CLK_GET_RATE_NOCACHE),
2822         ENTRY(CLK_SET_RATE_NO_REPARENT),
2823         ENTRY(CLK_GET_ACCURACY_NOCACHE),
2824         ENTRY(CLK_RECALC_NEW_RATES),
2825         ENTRY(CLK_SET_RATE_UNGATE),
2826         ENTRY(CLK_IS_CRITICAL),
2827         ENTRY(CLK_OPS_PARENT_ENABLE),
2828         ENTRY(CLK_DUTY_CYCLE_PARENT),
2829 #undef ENTRY
2830 };
2832 static int clk_flags_show(struct seq_file *s, void *data)
2834         struct clk_core *core = s->private;
2835         unsigned long flags = core->flags;
2836         unsigned int i;
2838         for (i = 0; flags && i < ARRAY_SIZE(clk_flags); i++) {
2839                 if (flags & clk_flags[i].flag) {
2840                         seq_printf(s, "%s\n", clk_flags[i].name);
2841                         flags &= ~clk_flags[i].flag;
2842                 }
2843         }
2844         if (flags) {
2845                 /* Unknown flags */
2846                 seq_printf(s, "0x%lx\n", flags);
2847         }
2849         return 0;
2851 DEFINE_SHOW_ATTRIBUTE(clk_flags);
2853 static int possible_parents_show(struct seq_file *s, void *data)
2855         struct clk_core *core = s->private;
2856         int i;
2858         for (i = 0; i < core->num_parents - 1; i++)
2859                 seq_printf(s, "%s ", core->parent_names[i]);
2861         seq_printf(s, "%s\n", core->parent_names[i]);
2863         return 0;
2865 DEFINE_SHOW_ATTRIBUTE(possible_parents);
2867 static int clk_duty_cycle_show(struct seq_file *s, void *data)
2869         struct clk_core *core = s->private;
2870         struct clk_duty *duty = &core->duty;
2872         seq_printf(s, "%u/%u\n", duty->num, duty->den);
2874         return 0;
2876 DEFINE_SHOW_ATTRIBUTE(clk_duty_cycle);
2878 static void clk_debug_create_one(struct clk_core *core, struct dentry *pdentry)
2880         struct dentry *root;
2882         if (!core || !pdentry)
2883                 return;
2885         root = debugfs_create_dir(core->name, pdentry);
2886         core->dentry = root;
2888         debugfs_create_ulong("clk_rate", 0444, root, &core->rate);
2889         debugfs_create_ulong("clk_accuracy", 0444, root, &core->accuracy);
2890         debugfs_create_u32("clk_phase", 0444, root, &core->phase);
2891         debugfs_create_file("clk_flags", 0444, root, core, &clk_flags_fops);
2892         debugfs_create_u32("clk_prepare_count", 0444, root, &core->prepare_count);
2893         debugfs_create_u32("clk_enable_count", 0444, root, &core->enable_count);
2894         debugfs_create_u32("clk_protect_count", 0444, root, &core->protect_count);
2895         debugfs_create_u32("clk_notifier_count", 0444, root, &core->notifier_count);
2896         debugfs_create_file("clk_duty_cycle", 0444, root, core,
2897                             &clk_duty_cycle_fops);
2899         if (core->num_parents > 1)
2900                 debugfs_create_file("clk_possible_parents", 0444, root, core,
2901                                     &possible_parents_fops);
2903         if (core->ops->debug_init)
2904                 core->ops->debug_init(core->hw, core->dentry);
2907 /**
2908  * clk_debug_register - add a clk node to the debugfs clk directory
2909  * @core: the clk being added to the debugfs clk directory
2910  *
2911  * Dynamically adds a clk to the debugfs clk directory if debugfs has been
2912  * initialized.  Otherwise it bails out early since the debugfs clk directory
2913  * will be created lazily by clk_debug_init as part of a late_initcall.
2914  */
2915 static void clk_debug_register(struct clk_core *core)
2917         mutex_lock(&clk_debug_lock);
2918         hlist_add_head(&core->debug_node, &clk_debug_list);
2919         if (inited)
2920                 clk_debug_create_one(core, rootdir);
2921         mutex_unlock(&clk_debug_lock);
2924  /**
2925  * clk_debug_unregister - remove a clk node from the debugfs clk directory
2926  * @core: the clk being removed from the debugfs clk directory
2927  *
2928  * Dynamically removes a clk and all its child nodes from the
2929  * debugfs clk directory if clk->dentry points to debugfs created by
2930  * clk_debug_register in __clk_core_init.
2931  */
2932 static void clk_debug_unregister(struct clk_core *core)
2934         mutex_lock(&clk_debug_lock);
2935         hlist_del_init(&core->debug_node);
2936         debugfs_remove_recursive(core->dentry);
2937         core->dentry = NULL;
2938         mutex_unlock(&clk_debug_lock);
2941 /**
2942  * clk_debug_init - lazily populate the debugfs clk directory
2943  *
2944  * clks are often initialized very early during boot before memory can be
2945  * dynamically allocated and well before debugfs is setup. This function
2946  * populates the debugfs clk directory once at boot-time when we know that
2947  * debugfs is setup. It should only be called once at boot-time, all other clks
2948  * added dynamically will be done so with clk_debug_register.
2949  */
2950 static int __init clk_debug_init(void)
2952         struct clk_core *core;
2954         rootdir = debugfs_create_dir("clk", NULL);
2956         debugfs_create_file("clk_summary", 0444, rootdir, &all_lists,
2957                             &clk_summary_fops);
2958         debugfs_create_file("clk_dump", 0444, rootdir, &all_lists,
2959                             &clk_dump_fops);
2960         debugfs_create_file("clk_orphan_summary", 0444, rootdir, &orphan_list,
2961                             &clk_summary_fops);
2962         debugfs_create_file("clk_orphan_dump", 0444, rootdir, &orphan_list,
2963                             &clk_dump_fops);
2965         mutex_lock(&clk_debug_lock);
2966         hlist_for_each_entry(core, &clk_debug_list, debug_node)
2967                 clk_debug_create_one(core, rootdir);
2969         inited = 1;
2970         mutex_unlock(&clk_debug_lock);
2972         return 0;
2974 late_initcall(clk_debug_init);
2975 #else
2976 static inline void clk_debug_register(struct clk_core *core) { }
2977 static inline void clk_debug_reparent(struct clk_core *core,
2978                                       struct clk_core *new_parent)
2981 static inline void clk_debug_unregister(struct clk_core *core)
2984 #endif
2986 /**
2987  * __clk_core_init - initialize the data structures in a struct clk_core
2988  * @core:       clk_core being initialized
2989  *
2990  * Initializes the lists in struct clk_core, queries the hardware for the
2991  * parent and rate and sets them both.
2992  */
2993 static int __clk_core_init(struct clk_core *core)
2995         int i, ret;
2996         struct clk_core *orphan;
2997         struct hlist_node *tmp2;
2998         unsigned long rate;
3000         if (!core)
3001                 return -EINVAL;
3003         clk_prepare_lock();
3005         ret = clk_pm_runtime_get(core);
3006         if (ret)
3007                 goto unlock;
3009         /* check to see if a clock with this name is already registered */
3010         if (clk_core_lookup(core->name)) {
3011                 pr_debug("%s: clk %s already initialized\n",
3012                                 __func__, core->name);
3013                 ret = -EEXIST;
3014                 goto out;
3015         }
3017         /* check that clk_ops are sane.  See Documentation/driver-api/clk.rst */
3018         if (core->ops->set_rate &&
3019             !((core->ops->round_rate || core->ops->determine_rate) &&
3020               core->ops->recalc_rate)) {
3021                 pr_err("%s: %s must implement .round_rate or .determine_rate in addition to .recalc_rate\n",
3022                        __func__, core->name);
3023                 ret = -EINVAL;
3024                 goto out;
3025         }
3027         if (core->ops->set_parent && !core->ops->get_parent) {
3028                 pr_err("%s: %s must implement .get_parent & .set_parent\n",
3029                        __func__, core->name);
3030                 ret = -EINVAL;
3031                 goto out;
3032         }
3034         if (core->num_parents > 1 && !core->ops->get_parent) {
3035                 pr_err("%s: %s must implement .get_parent as it has multi parents\n",
3036                        __func__, core->name);
3037                 ret = -EINVAL;
3038                 goto out;
3039         }
3041         if (core->ops->set_rate_and_parent &&
3042                         !(core->ops->set_parent && core->ops->set_rate)) {
3043                 pr_err("%s: %s must implement .set_parent & .set_rate\n",
3044                                 __func__, core->name);
3045                 ret = -EINVAL;
3046                 goto out;
3047         }
3049         /* throw a WARN if any entries in parent_names are NULL */
3050         for (i = 0; i < core->num_parents; i++)
3051                 WARN(!core->parent_names[i],
3052                                 "%s: invalid NULL in %s's .parent_names\n",
3053                                 __func__, core->name);
3055         core->parent = __clk_init_parent(core);
3057         /*
3058          * Populate core->parent if parent has already been clk_core_init'd. If
3059          * parent has not yet been clk_core_init'd then place clk in the orphan
3060          * list.  If clk doesn't have any parents then place it in the root
3061          * clk list.
3062          *
3063          * Every time a new clk is clk_init'd then we walk the list of orphan
3064          * clocks and re-parent any that are children of the clock currently
3065          * being clk_init'd.
3066          */
3067         if (core->parent) {
3068                 hlist_add_head(&core->child_node,
3069                                 &core->parent->children);
3070                 core->orphan = core->parent->orphan;
3071         } else if (!core->num_parents) {
3072                 hlist_add_head(&core->child_node, &clk_root_list);
3073                 core->orphan = false;
3074         } else {
3075                 hlist_add_head(&core->child_node, &clk_orphan_list);
3076                 core->orphan = true;
3077         }
3079         /*
3080          * optional platform-specific magic
3081          *
3082          * The .init callback is not used by any of the basic clock types, but
3083          * exists for weird hardware that must perform initialization magic.
3084          * Please consider other ways of solving initialization problems before
3085          * using this callback, as its use is discouraged.
3086          */
3087         if (core->ops->init)
3088                 core->ops->init(core->hw);
3090         /*
3091          * Set clk's accuracy.  The preferred method is to use
3092          * .recalc_accuracy. For simple clocks and lazy developers the default
3093          * fallback is to use the parent's accuracy.  If a clock doesn't have a
3094          * parent (or is orphaned) then accuracy is set to zero (perfect
3095          * clock).
3096          */
3097         if (core->ops->recalc_accuracy)
3098                 core->accuracy = core->ops->recalc_accuracy(core->hw,
3099                                         __clk_get_accuracy(core->parent));
3100         else if (core->parent)
3101                 core->accuracy = core->parent->accuracy;
3102         else
3103                 core->accuracy = 0;
3105         /*
3106          * Set clk's phase.
3107          * Since a phase is by definition relative to its parent, just
3108          * query the current clock phase, or just assume it's in phase.
3109          */
3110         if (core->ops->get_phase)
3111                 core->phase = core->ops->get_phase(core->hw);
3112         else
3113                 core->phase = 0;
3115         /*
3116          * Set clk's duty cycle.
3117          */
3118         clk_core_update_duty_cycle_nolock(core);
3120         /*
3121          * Set clk's rate.  The preferred method is to use .recalc_rate.  For
3122          * simple clocks and lazy developers the default fallback is to use the
3123          * parent's rate.  If a clock doesn't have a parent (or is orphaned)
3124          * then rate is set to zero.
3125          */
3126         if (core->ops->recalc_rate)
3127                 rate = core->ops->recalc_rate(core->hw,
3128                                 clk_core_get_rate_nolock(core->parent));
3129         else if (core->parent)
3130                 rate = core->parent->rate;
3131         else
3132                 rate = 0;
3133         core->rate = core->req_rate = rate;
3135         /*
3136          * Enable CLK_IS_CRITICAL clocks so newly added critical clocks
3137          * don't get accidentally disabled when walking the orphan tree and
3138          * reparenting clocks
3139          */
3140         if (core->flags & CLK_IS_CRITICAL) {
3141                 unsigned long flags;
3143                 clk_core_prepare(core);
3145                 flags = clk_enable_lock();
3146                 clk_core_enable(core);
3147                 clk_enable_unlock(flags);
3148         }
3150         /*
3151          * walk the list of orphan clocks and reparent any that newly finds a
3152          * parent.
3153          */
3154         hlist_for_each_entry_safe(orphan, tmp2, &clk_orphan_list, child_node) {
3155                 struct clk_core *parent = __clk_init_parent(orphan);
3157                 /*
3158                  * We need to use __clk_set_parent_before() and _after() to
3159                  * to properly migrate any prepare/enable count of the orphan
3160                  * clock. This is important for CLK_IS_CRITICAL clocks, which
3161                  * are enabled during init but might not have a parent yet.
3162                  */
3163                 if (parent) {
3164                         /* update the clk tree topology */
3165                         __clk_set_parent_before(orphan, parent);
3166                         __clk_set_parent_after(orphan, parent, NULL);
3167                         __clk_recalc_accuracies(orphan);
3168                         __clk_recalc_rates(orphan, 0);
3169                 }
3170         }
3172         kref_init(&core->ref);
3173 out:
3174         clk_pm_runtime_put(core);
3175 unlock:
3176         clk_prepare_unlock();
3178         if (!ret)
3179                 clk_debug_register(core);
3181         return ret;
3184 struct clk *__clk_create_clk(struct clk_hw *hw, const char *dev_id,
3185                              const char *con_id)
3187         struct clk *clk;
3189         /* This is to allow this function to be chained to others */
3190         if (IS_ERR_OR_NULL(hw))
3191                 return ERR_CAST(hw);
3193         clk = kzalloc(sizeof(*clk), GFP_KERNEL);
3194         if (!clk)
3195                 return ERR_PTR(-ENOMEM);
3197         clk->core = hw->core;
3198         clk->dev_id = dev_id;
3199         clk->con_id = kstrdup_const(con_id, GFP_KERNEL);
3200         clk->max_rate = ULONG_MAX;
3202         clk_prepare_lock();
3203         hlist_add_head(&clk->clks_node, &hw->core->clks);
3204         clk_prepare_unlock();
3206         return clk;
3209 /* keep in sync with __clk_put */
3210 void __clk_free_clk(struct clk *clk)
3212         clk_prepare_lock();
3213         hlist_del(&clk->clks_node);
3214         clk_prepare_unlock();
3216         kfree_const(clk->con_id);
3217         kfree(clk);
3220 /**
3221  * clk_register - allocate a new clock, register it and return an opaque cookie
3222  * @dev: device that is registering this clock
3223  * @hw: link to hardware-specific clock data
3224  *
3225  * clk_register is the primary interface for populating the clock tree with new
3226  * clock nodes.  It returns a pointer to the newly allocated struct clk which
3227  * cannot be dereferenced by driver code but may be used in conjunction with the
3228  * rest of the clock API.  In the event of an error clk_register will return an
3229  * error code; drivers must test for an error code after calling clk_register.
3230  */
3231 struct clk *clk_register(struct device *dev, struct clk_hw *hw)
3233         int i, ret;
3234         struct clk_core *core;
3236         core = kzalloc(sizeof(*core), GFP_KERNEL);
3237         if (!core) {
3238                 ret = -ENOMEM;
3239                 goto fail_out;
3240         }
3242         core->name = kstrdup_const(hw->init->name, GFP_KERNEL);
3243         if (!core->name) {
3244                 ret = -ENOMEM;
3245                 goto fail_name;
3246         }
3248         if (WARN_ON(!hw->init->ops)) {
3249                 ret = -EINVAL;
3250                 goto fail_ops;
3251         }
3252         core->ops = hw->init->ops;
3254         if (dev && pm_runtime_enabled(dev))
3255                 core->dev = dev;
3256         if (dev && dev->driver)
3257                 core->owner = dev->driver->owner;
3258         core->hw = hw;
3259         core->flags = hw->init->flags;
3260         core->num_parents = hw->init->num_parents;
3261         core->min_rate = 0;
3262         core->max_rate = ULONG_MAX;
3263         hw->core = core;
3265         /* allocate local copy in case parent_names is __initdata */
3266         core->parent_names = kcalloc(core->num_parents, sizeof(char *),
3267                                         GFP_KERNEL);
3269         if (!core->parent_names) {
3270                 ret = -ENOMEM;
3271                 goto fail_parent_names;
3272         }
3275         /* copy each string name in case parent_names is __initdata */
3276         for (i = 0; i < core->num_parents; i++) {
3277                 core->parent_names[i] = kstrdup_const(hw->init->parent_names[i],
3278                                                 GFP_KERNEL);
3279                 if (!core->parent_names[i]) {
3280                         ret = -ENOMEM;
3281                         goto fail_parent_names_copy;
3282                 }
3283         }
3285         /* avoid unnecessary string look-ups of clk_core's possible parents. */
3286         core->parents = kcalloc(core->num_parents, sizeof(*core->parents),
3287                                 GFP_KERNEL);
3288         if (!core->parents) {
3289                 ret = -ENOMEM;
3290                 goto fail_parents;
3291         };
3293         INIT_HLIST_HEAD(&core->clks);
3295         hw->clk = __clk_create_clk(hw, NULL, NULL);
3296         if (IS_ERR(hw->clk)) {
3297                 ret = PTR_ERR(hw->clk);
3298                 goto fail_parents;
3299         }
3301         ret = __clk_core_init(core);
3302         if (!ret)
3303                 return hw->clk;
3305         __clk_free_clk(hw->clk);
3306         hw->clk = NULL;
3308 fail_parents:
3309         kfree(core->parents);
3310 fail_parent_names_copy:
3311         while (--i >= 0)
3312                 kfree_const(core->parent_names[i]);
3313         kfree(core->parent_names);
3314 fail_parent_names:
3315 fail_ops:
3316         kfree_const(core->name);
3317 fail_name:
3318         kfree(core);
3319 fail_out:
3320         return ERR_PTR(ret);
3322 EXPORT_SYMBOL_GPL(clk_register);
3324 /**
3325  * clk_hw_register - register a clk_hw and return an error code
3326  * @dev: device that is registering this clock
3327  * @hw: link to hardware-specific clock data
3328  *
3329  * clk_hw_register is the primary interface for populating the clock tree with
3330  * new clock nodes. It returns an integer equal to zero indicating success or
3331  * less than zero indicating failure. Drivers must test for an error code after
3332  * calling clk_hw_register().
3333  */
3334 int clk_hw_register(struct device *dev, struct clk_hw *hw)
3336         return PTR_ERR_OR_ZERO(clk_register(dev, hw));
3338 EXPORT_SYMBOL_GPL(clk_hw_register);
3340 /* Free memory allocated for a clock. */
3341 static void __clk_release(struct kref *ref)
3343         struct clk_core *core = container_of(ref, struct clk_core, ref);
3344         int i = core->num_parents;
3346         lockdep_assert_held(&prepare_lock);
3348         kfree(core->parents);
3349         while (--i >= 0)
3350                 kfree_const(core->parent_names[i]);
3352         kfree(core->parent_names);
3353         kfree_const(core->name);
3354         kfree(core);
3357 /*
3358  * Empty clk_ops for unregistered clocks. These are used temporarily
3359  * after clk_unregister() was called on a clock and until last clock
3360  * consumer calls clk_put() and the struct clk object is freed.
3361  */
3362 static int clk_nodrv_prepare_enable(struct clk_hw *hw)
3364         return -ENXIO;
3367 static void clk_nodrv_disable_unprepare(struct clk_hw *hw)
3369         WARN_ON_ONCE(1);
3372 static int clk_nodrv_set_rate(struct clk_hw *hw, unsigned long rate,
3373                                         unsigned long parent_rate)
3375         return -ENXIO;
3378 static int clk_nodrv_set_parent(struct clk_hw *hw, u8 index)
3380         return -ENXIO;
3383 static const struct clk_ops clk_nodrv_ops = {
3384         .enable         = clk_nodrv_prepare_enable,
3385         .disable        = clk_nodrv_disable_unprepare,
3386         .prepare        = clk_nodrv_prepare_enable,
3387         .unprepare      = clk_nodrv_disable_unprepare,
3388         .set_rate       = clk_nodrv_set_rate,
3389         .set_parent     = clk_nodrv_set_parent,
3390 };
3392 /**
3393  * clk_unregister - unregister a currently registered clock
3394  * @clk: clock to unregister
3395  */
3396 void clk_unregister(struct clk *clk)
3398         unsigned long flags;
3400         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
3401                 return;
3403         clk_debug_unregister(clk->core);
3405         clk_prepare_lock();
3407         if (clk->core->ops == &clk_nodrv_ops) {
3408                 pr_err("%s: unregistered clock: %s\n", __func__,
3409                        clk->core->name);
3410                 goto unlock;
3411         }
3412         /*
3413          * Assign empty clock ops for consumers that might still hold
3414          * a reference to this clock.
3415          */
3416         flags = clk_enable_lock();
3417         clk->core->ops = &clk_nodrv_ops;
3418         clk_enable_unlock(flags);
3420         if (!hlist_empty(&clk->core->children)) {
3421                 struct clk_core *child;
3422                 struct hlist_node *t;
3424                 /* Reparent all children to the orphan list. */
3425                 hlist_for_each_entry_safe(child, t, &clk->core->children,
3426                                           child_node)
3427                         clk_core_set_parent_nolock(child, NULL);
3428         }
3430         hlist_del_init(&clk->core->child_node);
3432         if (clk->core->prepare_count)
3433                 pr_warn("%s: unregistering prepared clock: %s\n",
3434                                         __func__, clk->core->name);
3436         if (clk->core->protect_count)
3437                 pr_warn("%s: unregistering protected clock: %s\n",
3438                                         __func__, clk->core->name);
3440         kref_put(&clk->core->ref, __clk_release);
3441 unlock:
3442         clk_prepare_unlock();
3444 EXPORT_SYMBOL_GPL(clk_unregister);
3446 /**
3447  * clk_hw_unregister - unregister a currently registered clk_hw
3448  * @hw: hardware-specific clock data to unregister
3449  */
3450 void clk_hw_unregister(struct clk_hw *hw)
3452         clk_unregister(hw->clk);
3454 EXPORT_SYMBOL_GPL(clk_hw_unregister);
3456 static void devm_clk_release(struct device *dev, void *res)
3458         clk_unregister(*(struct clk **)res);
3461 static void devm_clk_hw_release(struct device *dev, void *res)
3463         clk_hw_unregister(*(struct clk_hw **)res);
3466 /**
3467  * devm_clk_register - resource managed clk_register()
3468  * @dev: device that is registering this clock
3469  * @hw: link to hardware-specific clock data
3470  *
3471  * Managed clk_register(). Clocks returned from this function are
3472  * automatically clk_unregister()ed on driver detach. See clk_register() for
3473  * more information.
3474  */
3475 struct clk *devm_clk_register(struct device *dev, struct clk_hw *hw)
3477         struct clk *clk;
3478         struct clk **clkp;
3480         clkp = devres_alloc(devm_clk_release, sizeof(*clkp), GFP_KERNEL);
3481         if (!clkp)
3482                 return ERR_PTR(-ENOMEM);
3484         clk = clk_register(dev, hw);
3485         if (!IS_ERR(clk)) {
3486                 *clkp = clk;
3487                 devres_add(dev, clkp);
3488         } else {
3489                 devres_free(clkp);
3490         }
3492         return clk;
3494 EXPORT_SYMBOL_GPL(devm_clk_register);
3496 /**
3497  * devm_clk_hw_register - resource managed clk_hw_register()
3498  * @dev: device that is registering this clock
3499  * @hw: link to hardware-specific clock data
3500  *
3501  * Managed clk_hw_register(). Clocks registered by this function are
3502  * automatically clk_hw_unregister()ed on driver detach. See clk_hw_register()
3503  * for more information.
3504  */
3505 int devm_clk_hw_register(struct device *dev, struct clk_hw *hw)
3507         struct clk_hw **hwp;
3508         int ret;
3510         hwp = devres_alloc(devm_clk_hw_release, sizeof(*hwp), GFP_KERNEL);
3511         if (!hwp)
3512                 return -ENOMEM;
3514         ret = clk_hw_register(dev, hw);
3515         if (!ret) {
3516                 *hwp = hw;
3517                 devres_add(dev, hwp);
3518         } else {
3519                 devres_free(hwp);
3520         }
3522         return ret;
3524 EXPORT_SYMBOL_GPL(devm_clk_hw_register);
3526 static int devm_clk_match(struct device *dev, void *res, void *data)
3528         struct clk *c = res;
3529         if (WARN_ON(!c))
3530                 return 0;
3531         return c == data;
3534 static int devm_clk_hw_match(struct device *dev, void *res, void *data)
3536         struct clk_hw *hw = res;
3538         if (WARN_ON(!hw))
3539                 return 0;
3540         return hw == data;
3543 /**
3544  * devm_clk_unregister - resource managed clk_unregister()
3545  * @clk: clock to unregister
3546  *
3547  * Deallocate a clock allocated with devm_clk_register(). Normally
3548  * this function will not need to be called and the resource management
3549  * code will ensure that the resource is freed.
3550  */
3551 void devm_clk_unregister(struct device *dev, struct clk *clk)
3553         WARN_ON(devres_release(dev, devm_clk_release, devm_clk_match, clk));
3555 EXPORT_SYMBOL_GPL(devm_clk_unregister);
3557 /**
3558  * devm_clk_hw_unregister - resource managed clk_hw_unregister()
3559  * @dev: device that is unregistering the hardware-specific clock data
3560  * @hw: link to hardware-specific clock data
3561  *
3562  * Unregister a clk_hw registered with devm_clk_hw_register(). Normally
3563  * this function will not need to be called and the resource management
3564  * code will ensure that the resource is freed.
3565  */
3566 void devm_clk_hw_unregister(struct device *dev, struct clk_hw *hw)
3568         WARN_ON(devres_release(dev, devm_clk_hw_release, devm_clk_hw_match,
3569                                 hw));
3571 EXPORT_SYMBOL_GPL(devm_clk_hw_unregister);
3573 /*
3574  * clkdev helpers
3575  */
3576 int __clk_get(struct clk *clk)
3578         struct clk_core *core = !clk ? NULL : clk->core;
3580         if (core) {
3581                 if (!try_module_get(core->owner))
3582                         return 0;
3584                 kref_get(&core->ref);
3585         }
3586         return 1;
3589 /* keep in sync with __clk_free_clk */
3590 void __clk_put(struct clk *clk)
3592         struct module *owner;
3594         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
3595                 return;
3597         clk_prepare_lock();
3599         /*
3600          * Before calling clk_put, all calls to clk_rate_exclusive_get() from a
3601          * given user should be balanced with calls to clk_rate_exclusive_put()
3602          * and by that same consumer
3603          */
3604         if (WARN_ON(clk->exclusive_count)) {
3605                 /* We voiced our concern, let's sanitize the situation */
3606                 clk->core->protect_count -= (clk->exclusive_count - 1);
3607                 clk_core_rate_unprotect(clk->core);
3608                 clk->exclusive_count = 0;
3609         }
3611         hlist_del(&clk->clks_node);
3612         if (clk->min_rate > clk->core->req_rate ||
3613             clk->max_rate < clk->core->req_rate)
3614                 clk_core_set_rate_nolock(clk->core, clk->core->req_rate);
3616         owner = clk->core->owner;
3617         kref_put(&clk->core->ref, __clk_release);
3619         clk_prepare_unlock();
3621         module_put(owner);
3623         kfree_const(clk->con_id);
3624         kfree(clk);
3627 /***        clk rate change notifiers        ***/
3629 /**
3630  * clk_notifier_register - add a clk rate change notifier
3631  * @clk: struct clk * to watch
3632  * @nb: struct notifier_block * with callback info
3633  *
3634  * Request notification when clk's rate changes.  This uses an SRCU
3635  * notifier because we want it to block and notifier unregistrations are
3636  * uncommon.  The callbacks associated with the notifier must not
3637  * re-enter into the clk framework by calling any top-level clk APIs;
3638  * this will cause a nested prepare_lock mutex.
3639  *
3640  * In all notification cases (pre, post and abort rate change) the original
3641  * clock rate is passed to the callback via struct clk_notifier_data.old_rate
3642  * and the new frequency is passed via struct clk_notifier_data.new_rate.
3643  *
3644  * clk_notifier_register() must be called from non-atomic context.
3645  * Returns -EINVAL if called with null arguments, -ENOMEM upon
3646  * allocation failure; otherwise, passes along the return value of
3647  * srcu_notifier_chain_register().
3648  */
3649 int clk_notifier_register(struct clk *clk, struct notifier_block *nb)
3651         struct clk_notifier *cn;
3652         int ret = -ENOMEM;
3654         if (!clk || !nb)
3655                 return -EINVAL;
3657         clk_prepare_lock();
3659         /* search the list of notifiers for this clk */
3660         list_for_each_entry(cn, &clk_notifier_list, node)
3661                 if (cn->clk == clk)
3662                         break;
3664         /* if clk wasn't in the notifier list, allocate new clk_notifier */
3665         if (cn->clk != clk) {
3666                 cn = kzalloc(sizeof(*cn), GFP_KERNEL);
3667                 if (!cn)
3668                         goto out;
3670                 cn->clk = clk;
3671                 srcu_init_notifier_head(&cn->notifier_head);
3673                 list_add(&cn->node, &clk_notifier_list);
3674         }
3676         ret = srcu_notifier_chain_register(&cn->notifier_head, nb);
3678         clk->core->notifier_count++;
3680 out:
3681         clk_prepare_unlock();
3683         return ret;
3685 EXPORT_SYMBOL_GPL(clk_notifier_register);
3687 /**
3688  * clk_notifier_unregister - remove a clk rate change notifier
3689  * @clk: struct clk *
3690  * @nb: struct notifier_block * with callback info
3691  *
3692  * Request no further notification for changes to 'clk' and frees memory
3693  * allocated in clk_notifier_register.
3694  *
3695  * Returns -EINVAL if called with null arguments; otherwise, passes
3696  * along the return value of srcu_notifier_chain_unregister().
3697  */
3698 int clk_notifier_unregister(struct clk *clk, struct notifier_block *nb)
3700         struct clk_notifier *cn = NULL;
3701         int ret = -EINVAL;
3703         if (!clk || !nb)
3704                 return -EINVAL;
3706         clk_prepare_lock();
3708         list_for_each_entry(cn, &clk_notifier_list, node)
3709                 if (cn->clk == clk)
3710                         break;
3712         if (cn->clk == clk) {
3713                 ret = srcu_notifier_chain_unregister(&cn->notifier_head, nb);
3715                 clk->core->notifier_count--;
3717                 /* XXX the notifier code should handle this better */
3718                 if (!cn->notifier_head.head) {
3719                         srcu_cleanup_notifier_head(&cn->notifier_head);
3720                         list_del(&cn->node);
3721                         kfree(cn);
3722                 }
3724         } else {
3725                 ret = -ENOENT;
3726         }
3728         clk_prepare_unlock();
3730         return ret;
3732 EXPORT_SYMBOL_GPL(clk_notifier_unregister);
3734 #ifdef CONFIG_OF
3735 /**
3736  * struct of_clk_provider - Clock provider registration structure
3737  * @link: Entry in global list of clock providers
3738  * @node: Pointer to device tree node of clock provider
3739  * @get: Get clock callback.  Returns NULL or a struct clk for the
3740  *       given clock specifier
3741  * @data: context pointer to be passed into @get callback
3742  */
3743 struct of_clk_provider {
3744         struct list_head link;
3746         struct device_node *node;
3747         struct clk *(*get)(struct of_phandle_args *clkspec, void *data);
3748         struct clk_hw *(*get_hw)(struct of_phandle_args *clkspec, void *data);
3749         void *data;
3750 };
3752 static const struct of_device_id __clk_of_table_sentinel
3753         __used __section(__clk_of_table_end);
3755 static LIST_HEAD(of_clk_providers);
3756 static DEFINE_MUTEX(of_clk_mutex);
3758 struct clk *of_clk_src_simple_get(struct of_phandle_args *clkspec,
3759                                      void *data)
3761         return data;
3763 EXPORT_SYMBOL_GPL(of_clk_src_simple_get);
3765 struct clk_hw *of_clk_hw_simple_get(struct of_phandle_args *clkspec, void *data)
3767         return data;
3769 EXPORT_SYMBOL_GPL(of_clk_hw_simple_get);
3771 struct clk *of_clk_src_onecell_get(struct of_phandle_args *clkspec, void *data)
3773         struct clk_onecell_data *clk_data = data;
3774         unsigned int idx = clkspec->args[0];
3776         if (idx >= clk_data->clk_num) {
3777                 pr_err("%s: invalid clock index %u\n", __func__, idx);
3778                 return ERR_PTR(-EINVAL);
3779         }
3781         return clk_data->clks[idx];
3783 EXPORT_SYMBOL_GPL(of_clk_src_onecell_get);
3785 struct clk_hw *
3786 of_clk_hw_onecell_get(struct of_phandle_args *clkspec, void *data)
3788         struct clk_hw_onecell_data *hw_data = data;
3789         unsigned int idx = clkspec->args[0];
3791         if (idx >= hw_data->num) {
3792                 pr_err("%s: invalid index %u\n", __func__, idx);
3793                 return ERR_PTR(-EINVAL);
3794         }
3796         return hw_data->hws[idx];
3798 EXPORT_SYMBOL_GPL(of_clk_hw_onecell_get);
3800 /**
3801  * of_clk_add_provider() - Register a clock provider for a node
3802  * @np: Device node pointer associated with clock provider
3803  * @clk_src_get: callback for decoding clock
3804  * @data: context pointer for @clk_src_get callback.
3805  */
3806 int of_clk_add_provider(struct device_node *np,
3807                         struct clk *(*clk_src_get)(struct of_phandle_args *clkspec,
3808                                                    void *data),
3809                         void *data)
3811         struct of_clk_provider *cp;
3812         int ret;
3814         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
3815         if (!cp)
3816                 return -ENOMEM;
3818         cp->node = of_node_get(np);
3819         cp->data = data;
3820         cp->get = clk_src_get;
3822         mutex_lock(&of_clk_mutex);
3823         list_add(&cp->link, &of_clk_providers);
3824         mutex_unlock(&of_clk_mutex);
3825         pr_debug("Added clock from %pOF\n", np);
3827         ret = of_clk_set_defaults(np, true);
3828         if (ret < 0)
3829                 of_clk_del_provider(np);
3831         return ret;
3833 EXPORT_SYMBOL_GPL(of_clk_add_provider);
3835 /**
3836  * of_clk_add_hw_provider() - Register a clock provider for a node
3837  * @np: Device node pointer associated with clock provider
3838  * @get: callback for decoding clk_hw
3839  * @data: context pointer for @get callback.
3840  */
3841 int of_clk_add_hw_provider(struct device_node *np,
3842                            struct clk_hw *(*get)(struct of_phandle_args *clkspec,
3843                                                  void *data),
3844                            void *data)
3846         struct of_clk_provider *cp;
3847         int ret;
3849         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
3850         if (!cp)
3851                 return -ENOMEM;
3853         cp->node = of_node_get(np);
3854         cp->data = data;
3855         cp->get_hw = get;
3857         mutex_lock(&of_clk_mutex);
3858         list_add(&cp->link, &of_clk_providers);
3859         mutex_unlock(&of_clk_mutex);
3860         pr_debug("Added clk_hw provider from %pOF\n", np);
3862         ret = of_clk_set_defaults(np, true);
3863         if (ret < 0)
3864                 of_clk_del_provider(np);
3866         return ret;
3868 EXPORT_SYMBOL_GPL(of_clk_add_hw_provider);
3870 static void devm_of_clk_release_provider(struct device *dev, void *res)
3872         of_clk_del_provider(*(struct device_node **)res);
3875 int devm_of_clk_add_hw_provider(struct device *dev,
3876                         struct clk_hw *(*get)(struct of_phandle_args *clkspec,
3877                                               void *data),
3878                         void *data)
3880         struct device_node **ptr, *np;
3881         int ret;
3883         ptr = devres_alloc(devm_of_clk_release_provider, sizeof(*ptr),
3884                            GFP_KERNEL);
3885         if (!ptr)
3886                 return -ENOMEM;
3888         np = dev->of_node;
3889         ret = of_clk_add_hw_provider(np, get, data);
3890         if (!ret) {
3891                 *ptr = np;
3892                 devres_add(dev, ptr);
3893         } else {
3894                 devres_free(ptr);
3895         }
3897         return ret;
3899 EXPORT_SYMBOL_GPL(devm_of_clk_add_hw_provider);
3901 /**
3902  * of_clk_del_provider() - Remove a previously registered clock provider
3903  * @np: Device node pointer associated with clock provider
3904  */
3905 void of_clk_del_provider(struct device_node *np)
3907         struct of_clk_provider *cp;
3909         mutex_lock(&of_clk_mutex);
3910         list_for_each_entry(cp, &of_clk_providers, link) {
3911                 if (cp->node == np) {
3912                         list_del(&cp->link);
3913                         of_node_put(cp->node);
3914                         kfree(cp);
3915                         break;
3916                 }
3917         }
3918         mutex_unlock(&of_clk_mutex);
3920 EXPORT_SYMBOL_GPL(of_clk_del_provider);
3922 static int devm_clk_provider_match(struct device *dev, void *res, void *data)
3924         struct device_node **np = res;
3926         if (WARN_ON(!np || !*np))
3927                 return 0;
3929         return *np == data;
3932 void devm_of_clk_del_provider(struct device *dev)
3934         int ret;
3936         ret = devres_release(dev, devm_of_clk_release_provider,
3937                              devm_clk_provider_match, dev->of_node);
3939         WARN_ON(ret);
3941 EXPORT_SYMBOL(devm_of_clk_del_provider);
3943 static struct clk_hw *
3944 __of_clk_get_hw_from_provider(struct of_clk_provider *provider,
3945                               struct of_phandle_args *clkspec)
3947         struct clk *clk;
3949         if (provider->get_hw)
3950                 return provider->get_hw(clkspec, provider->data);
3952         clk = provider->get(clkspec, provider->data);
3953         if (IS_ERR(clk))
3954                 return ERR_CAST(clk);
3955         return __clk_get_hw(clk);
3958 struct clk *__of_clk_get_from_provider(struct of_phandle_args *clkspec,
3959                                        const char *dev_id, const char *con_id)
3961         struct of_clk_provider *provider;
3962         struct clk *clk = ERR_PTR(-EPROBE_DEFER);
3963         struct clk_hw *hw;
3965         if (!clkspec)
3966                 return ERR_PTR(-EINVAL);
3968         /* Check if we have such a provider in our array */
3969         mutex_lock(&of_clk_mutex);
3970         list_for_each_entry(provider, &of_clk_providers, link) {
3971                 if (provider->node == clkspec->np) {
3972                         hw = __of_clk_get_hw_from_provider(provider, clkspec);
3973                         clk = __clk_create_clk(hw, dev_id, con_id);
3974                 }
3976                 if (!IS_ERR(clk)) {
3977                         if (!__clk_get(clk)) {
3978                                 __clk_free_clk(clk);
3979                                 clk = ERR_PTR(-ENOENT);
3980                         }
3982                         break;
3983                 }
3984         }
3985         mutex_unlock(&of_clk_mutex);
3987         return clk;
3990 /**
3991  * of_clk_get_from_provider() - Lookup a clock from a clock provider
3992  * @clkspec: pointer to a clock specifier data structure
3993  *
3994  * This function looks up a struct clk from the registered list of clock
3995  * providers, an input is a clock specifier data structure as returned
3996  * from the of_parse_phandle_with_args() function call.
3997  */
3998 struct clk *of_clk_get_from_provider(struct of_phandle_args *clkspec)
4000         return __of_clk_get_from_provider(clkspec, NULL, __func__);
4002 EXPORT_SYMBOL_GPL(of_clk_get_from_provider);
4004 /**
4005  * of_clk_get_parent_count() - Count the number of clocks a device node has
4006  * @np: device node to count
4007  *
4008  * Returns: The number of clocks that are possible parents of this node
4009  */
4010 unsigned int of_clk_get_parent_count(struct device_node *np)
4012         int count;
4014         count = of_count_phandle_with_args(np, "clocks", "#clock-cells");
4015         if (count < 0)
4016                 return 0;
4018         return count;
4020 EXPORT_SYMBOL_GPL(of_clk_get_parent_count);
4022 const char *of_clk_get_parent_name(struct device_node *np, int index)
4024         struct of_phandle_args clkspec;
4025         struct property *prop;
4026         const char *clk_name;
4027         const __be32 *vp;
4028         u32 pv;
4029         int rc;
4030         int count;
4031         struct clk *clk;
4033         rc = of_parse_phandle_with_args(np, "clocks", "#clock-cells", index,
4034                                         &clkspec);
4035         if (rc)
4036                 return NULL;
4038         index = clkspec.args_count ? clkspec.args[0] : 0;
4039         count = 0;
4041         /* if there is an indices property, use it to transfer the index
4042          * specified into an array offset for the clock-output-names property.
4043          */
4044         of_property_for_each_u32(clkspec.np, "clock-indices", prop, vp, pv) {
4045                 if (index == pv) {
4046                         index = count;
4047                         break;
4048                 }
4049                 count++;
4050         }
4051         /* We went off the end of 'clock-indices' without finding it */
4052         if (prop && !vp)
4053                 return NULL;
4055         if (of_property_read_string_index(clkspec.np, "clock-output-names",
4056                                           index,
4057                                           &clk_name) < 0) {
4058                 /*
4059                  * Best effort to get the name if the clock has been
4060                  * registered with the framework. If the clock isn't
4061                  * registered, we return the node name as the name of
4062                  * the clock as long as #clock-cells = 0.
4063                  */
4064                 clk = of_clk_get_from_provider(&clkspec);
4065                 if (IS_ERR(clk)) {
4066                         if (clkspec.args_count == 0)
4067                                 clk_name = clkspec.np->name;
4068                         else
4069                                 clk_name = NULL;
4070                 } else {
4071                         clk_name = __clk_get_name(clk);
4072                         clk_put(clk);
4073                 }
4074         }
4077         of_node_put(clkspec.np);
4078         return clk_name;
4080 EXPORT_SYMBOL_GPL(of_clk_get_parent_name);
4082 /**
4083  * of_clk_parent_fill() - Fill @parents with names of @np's parents and return
4084  * number of parents
4085  * @np: Device node pointer associated with clock provider
4086  * @parents: pointer to char array that hold the parents' names
4087  * @size: size of the @parents array
4088  *
4089  * Return: number of parents for the clock node.
4090  */
4091 int of_clk_parent_fill(struct device_node *np, const char **parents,
4092                        unsigned int size)
4094         unsigned int i = 0;
4096         while (i < size && (parents[i] = of_clk_get_parent_name(np, i)) != NULL)
4097                 i++;
4099         return i;
4101 EXPORT_SYMBOL_GPL(of_clk_parent_fill);
4103 struct clock_provider {
4104         void (*clk_init_cb)(struct device_node *);
4105         struct device_node *np;
4106         struct list_head node;
4107 };
4109 /*
4110  * This function looks for a parent clock. If there is one, then it
4111  * checks that the provider for this parent clock was initialized, in
4112  * this case the parent clock will be ready.
4113  */
4114 static int parent_ready(struct device_node *np)
4116         int i = 0;
4118         while (true) {
4119                 struct clk *clk = of_clk_get(np, i);
4121                 /* this parent is ready we can check the next one */
4122                 if (!IS_ERR(clk)) {
4123                         clk_put(clk);
4124                         i++;
4125                         continue;
4126                 }
4128                 /* at least one parent is not ready, we exit now */
4129                 if (PTR_ERR(clk) == -EPROBE_DEFER)
4130                         return 0;
4132                 /*
4133                  * Here we make assumption that the device tree is
4134                  * written correctly. So an error means that there is
4135                  * no more parent. As we didn't exit yet, then the
4136                  * previous parent are ready. If there is no clock
4137                  * parent, no need to wait for them, then we can
4138                  * consider their absence as being ready
4139                  */
4140                 return 1;
4141         }
4144 /**
4145  * of_clk_detect_critical() - set CLK_IS_CRITICAL flag from Device Tree
4146  * @np: Device node pointer associated with clock provider
4147  * @index: clock index
4148  * @flags: pointer to top-level framework flags
4149  *
4150  * Detects if the clock-critical property exists and, if so, sets the
4151  * corresponding CLK_IS_CRITICAL flag.
4152  *
4153  * Do not use this function. It exists only for legacy Device Tree
4154  * bindings, such as the one-clock-per-node style that are outdated.
4155  * Those bindings typically put all clock data into .dts and the Linux
4156  * driver has no clock data, thus making it impossible to set this flag
4157  * correctly from the driver. Only those drivers may call
4158  * of_clk_detect_critical from their setup functions.
4159  *
4160  * Return: error code or zero on success
4161  */
4162 int of_clk_detect_critical(struct device_node *np,
4163                                           int index, unsigned long *flags)
4165         struct property *prop;
4166         const __be32 *cur;
4167         uint32_t idx;
4169         if (!np || !flags)
4170                 return -EINVAL;
4172         of_property_for_each_u32(np, "clock-critical", prop, cur, idx)
4173                 if (index == idx)
4174                         *flags |= CLK_IS_CRITICAL;
4176         return 0;
4179 /**
4180  * of_clk_init() - Scan and init clock providers from the DT
4181  * @matches: array of compatible values and init functions for providers.
4182  *
4183  * This function scans the device tree for matching clock providers
4184  * and calls their initialization functions. It also does it by trying
4185  * to follow the dependencies.
4186  */
4187 void __init of_clk_init(const struct of_device_id *matches)
4189         const struct of_device_id *match;
4190         struct device_node *np;
4191         struct clock_provider *clk_provider, *next;
4192         bool is_init_done;
4193         bool force = false;
4194         LIST_HEAD(clk_provider_list);
4196         if (!matches)
4197                 matches = &__clk_of_table;
4199         /* First prepare the list of the clocks providers */
4200         for_each_matching_node_and_match(np, matches, &match) {
4201                 struct clock_provider *parent;
4203                 if (!of_device_is_available(np))
4204                         continue;
4206                 parent = kzalloc(sizeof(*parent), GFP_KERNEL);
4207                 if (!parent) {
4208                         list_for_each_entry_safe(clk_provider, next,
4209                                                  &clk_provider_list, node) {
4210                                 list_del(&clk_provider->node);
4211                                 of_node_put(clk_provider->np);
4212                                 kfree(clk_provider);
4213                         }
4214                         of_node_put(np);
4215                         return;
4216                 }
4218                 parent->clk_init_cb = match->data;
4219                 parent->np = of_node_get(np);
4220                 list_add_tail(&parent->node, &clk_provider_list);
4221         }
4223         while (!list_empty(&clk_provider_list)) {
4224                 is_init_done = false;
4225                 list_for_each_entry_safe(clk_provider, next,
4226                                         &clk_provider_list, node) {
4227                         if (force || parent_ready(clk_provider->np)) {
4229                                 /* Don't populate platform devices */
4230                                 of_node_set_flag(clk_provider->np,
4231                                                  OF_POPULATED);
4233                                 clk_provider->clk_init_cb(clk_provider->np);
4234                                 of_clk_set_defaults(clk_provider->np, true);
4236                                 list_del(&clk_provider->node);
4237                                 of_node_put(clk_provider->np);
4238                                 kfree(clk_provider);
4239                                 is_init_done = true;
4240                         }
4241                 }
4243                 /*
4244                  * We didn't manage to initialize any of the
4245                  * remaining providers during the last loop, so now we
4246                  * initialize all the remaining ones unconditionally
4247                  * in case the clock parent was not mandatory
4248                  */
4249                 if (!is_init_done)
4250                         force = true;
4251         }
4253 #endif