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