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