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