OSDN Git Service

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