]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/clk/clk.c
Merge branches 'clk-aspeed', 'clk-unused', 'clk-of-node-put', 'clk-const-bulk-data...
[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 /**
2493  * clk_set_parent - switch the parent of a mux clk
2494  * @clk: the mux clk whose input we are switching
2495  * @parent: the new input to clk
2496  *
2497  * Re-parent clk to use parent as its new input source.  If clk is in
2498  * prepared state, the clk will get enabled for the duration of this call. If
2499  * that's not acceptable for a specific clk (Eg: the consumer can't handle
2500  * that, the reparenting is glitchy in hardware, etc), use the
2501  * CLK_SET_PARENT_GATE flag to allow reparenting only when clk is unprepared.
2502  *
2503  * After successfully changing clk's parent clk_set_parent will update the
2504  * clk topology, sysfs topology and propagate rate recalculation via
2505  * __clk_recalc_rates.
2506  *
2507  * Returns 0 on success, -EERROR otherwise.
2508  */
2509 int clk_set_parent(struct clk *clk, struct clk *parent)
2510 {
2511         int ret;
2512
2513         if (!clk)
2514                 return 0;
2515
2516         clk_prepare_lock();
2517
2518         if (clk->exclusive_count)
2519                 clk_core_rate_unprotect(clk->core);
2520
2521         ret = clk_core_set_parent_nolock(clk->core,
2522                                          parent ? parent->core : NULL);
2523
2524         if (clk->exclusive_count)
2525                 clk_core_rate_protect(clk->core);
2526
2527         clk_prepare_unlock();
2528
2529         return ret;
2530 }
2531 EXPORT_SYMBOL_GPL(clk_set_parent);
2532
2533 static int clk_core_set_phase_nolock(struct clk_core *core, int degrees)
2534 {
2535         int ret = -EINVAL;
2536
2537         lockdep_assert_held(&prepare_lock);
2538
2539         if (!core)
2540                 return 0;
2541
2542         if (clk_core_rate_is_protected(core))
2543                 return -EBUSY;
2544
2545         trace_clk_set_phase(core, degrees);
2546
2547         if (core->ops->set_phase) {
2548                 ret = core->ops->set_phase(core->hw, degrees);
2549                 if (!ret)
2550                         core->phase = degrees;
2551         }
2552
2553         trace_clk_set_phase_complete(core, degrees);
2554
2555         return ret;
2556 }
2557
2558 /**
2559  * clk_set_phase - adjust the phase shift of a clock signal
2560  * @clk: clock signal source
2561  * @degrees: number of degrees the signal is shifted
2562  *
2563  * Shifts the phase of a clock signal by the specified
2564  * degrees. Returns 0 on success, -EERROR otherwise.
2565  *
2566  * This function makes no distinction about the input or reference
2567  * signal that we adjust the clock signal phase against. For example
2568  * phase locked-loop clock signal generators we may shift phase with
2569  * respect to feedback clock signal input, but for other cases the
2570  * clock phase may be shifted with respect to some other, unspecified
2571  * signal.
2572  *
2573  * Additionally the concept of phase shift does not propagate through
2574  * the clock tree hierarchy, which sets it apart from clock rates and
2575  * clock accuracy. A parent clock phase attribute does not have an
2576  * impact on the phase attribute of a child clock.
2577  */
2578 int clk_set_phase(struct clk *clk, int degrees)
2579 {
2580         int ret;
2581
2582         if (!clk)
2583                 return 0;
2584
2585         /* sanity check degrees */
2586         degrees %= 360;
2587         if (degrees < 0)
2588                 degrees += 360;
2589
2590         clk_prepare_lock();
2591
2592         if (clk->exclusive_count)
2593                 clk_core_rate_unprotect(clk->core);
2594
2595         ret = clk_core_set_phase_nolock(clk->core, degrees);
2596
2597         if (clk->exclusive_count)
2598                 clk_core_rate_protect(clk->core);
2599
2600         clk_prepare_unlock();
2601
2602         return ret;
2603 }
2604 EXPORT_SYMBOL_GPL(clk_set_phase);
2605
2606 static int clk_core_get_phase(struct clk_core *core)
2607 {
2608         int ret;
2609
2610         clk_prepare_lock();
2611         /* Always try to update cached phase if possible */
2612         if (core->ops->get_phase)
2613                 core->phase = core->ops->get_phase(core->hw);
2614         ret = core->phase;
2615         clk_prepare_unlock();
2616
2617         return ret;
2618 }
2619
2620 /**
2621  * clk_get_phase - return the phase shift of a clock signal
2622  * @clk: clock signal source
2623  *
2624  * Returns the phase shift of a clock node in degrees, otherwise returns
2625  * -EERROR.
2626  */
2627 int clk_get_phase(struct clk *clk)
2628 {
2629         if (!clk)
2630                 return 0;
2631
2632         return clk_core_get_phase(clk->core);
2633 }
2634 EXPORT_SYMBOL_GPL(clk_get_phase);
2635
2636 static void clk_core_reset_duty_cycle_nolock(struct clk_core *core)
2637 {
2638         /* Assume a default value of 50% */
2639         core->duty.num = 1;
2640         core->duty.den = 2;
2641 }
2642
2643 static int clk_core_update_duty_cycle_parent_nolock(struct clk_core *core);
2644
2645 static int clk_core_update_duty_cycle_nolock(struct clk_core *core)
2646 {
2647         struct clk_duty *duty = &core->duty;
2648         int ret = 0;
2649
2650         if (!core->ops->get_duty_cycle)
2651                 return clk_core_update_duty_cycle_parent_nolock(core);
2652
2653         ret = core->ops->get_duty_cycle(core->hw, duty);
2654         if (ret)
2655                 goto reset;
2656
2657         /* Don't trust the clock provider too much */
2658         if (duty->den == 0 || duty->num > duty->den) {
2659                 ret = -EINVAL;
2660                 goto reset;
2661         }
2662
2663         return 0;
2664
2665 reset:
2666         clk_core_reset_duty_cycle_nolock(core);
2667         return ret;
2668 }
2669
2670 static int clk_core_update_duty_cycle_parent_nolock(struct clk_core *core)
2671 {
2672         int ret = 0;
2673
2674         if (core->parent &&
2675             core->flags & CLK_DUTY_CYCLE_PARENT) {
2676                 ret = clk_core_update_duty_cycle_nolock(core->parent);
2677                 memcpy(&core->duty, &core->parent->duty, sizeof(core->duty));
2678         } else {
2679                 clk_core_reset_duty_cycle_nolock(core);
2680         }
2681
2682         return ret;
2683 }
2684
2685 static int clk_core_set_duty_cycle_parent_nolock(struct clk_core *core,
2686                                                  struct clk_duty *duty);
2687
2688 static int clk_core_set_duty_cycle_nolock(struct clk_core *core,
2689                                           struct clk_duty *duty)
2690 {
2691         int ret;
2692
2693         lockdep_assert_held(&prepare_lock);
2694
2695         if (clk_core_rate_is_protected(core))
2696                 return -EBUSY;
2697
2698         trace_clk_set_duty_cycle(core, duty);
2699
2700         if (!core->ops->set_duty_cycle)
2701                 return clk_core_set_duty_cycle_parent_nolock(core, duty);
2702
2703         ret = core->ops->set_duty_cycle(core->hw, duty);
2704         if (!ret)
2705                 memcpy(&core->duty, duty, sizeof(*duty));
2706
2707         trace_clk_set_duty_cycle_complete(core, duty);
2708
2709         return ret;
2710 }
2711
2712 static int clk_core_set_duty_cycle_parent_nolock(struct clk_core *core,
2713                                                  struct clk_duty *duty)
2714 {
2715         int ret = 0;
2716
2717         if (core->parent &&
2718             core->flags & (CLK_DUTY_CYCLE_PARENT | CLK_SET_RATE_PARENT)) {
2719                 ret = clk_core_set_duty_cycle_nolock(core->parent, duty);
2720                 memcpy(&core->duty, &core->parent->duty, sizeof(core->duty));
2721         }
2722
2723         return ret;
2724 }
2725
2726 /**
2727  * clk_set_duty_cycle - adjust the duty cycle ratio of a clock signal
2728  * @clk: clock signal source
2729  * @num: numerator of the duty cycle ratio to be applied
2730  * @den: denominator of the duty cycle ratio to be applied
2731  *
2732  * Apply the duty cycle ratio if the ratio is valid and the clock can
2733  * perform this operation
2734  *
2735  * Returns (0) on success, a negative errno otherwise.
2736  */
2737 int clk_set_duty_cycle(struct clk *clk, unsigned int num, unsigned int den)
2738 {
2739         int ret;
2740         struct clk_duty duty;
2741
2742         if (!clk)
2743                 return 0;
2744
2745         /* sanity check the ratio */
2746         if (den == 0 || num > den)
2747                 return -EINVAL;
2748
2749         duty.num = num;
2750         duty.den = den;
2751
2752         clk_prepare_lock();
2753
2754         if (clk->exclusive_count)
2755                 clk_core_rate_unprotect(clk->core);
2756
2757         ret = clk_core_set_duty_cycle_nolock(clk->core, &duty);
2758
2759         if (clk->exclusive_count)
2760                 clk_core_rate_protect(clk->core);
2761
2762         clk_prepare_unlock();
2763
2764         return ret;
2765 }
2766 EXPORT_SYMBOL_GPL(clk_set_duty_cycle);
2767
2768 static int clk_core_get_scaled_duty_cycle(struct clk_core *core,
2769                                           unsigned int scale)
2770 {
2771         struct clk_duty *duty = &core->duty;
2772         int ret;
2773
2774         clk_prepare_lock();
2775
2776         ret = clk_core_update_duty_cycle_nolock(core);
2777         if (!ret)
2778                 ret = mult_frac(scale, duty->num, duty->den);
2779
2780         clk_prepare_unlock();
2781
2782         return ret;
2783 }
2784
2785 /**
2786  * clk_get_scaled_duty_cycle - return the duty cycle ratio of a clock signal
2787  * @clk: clock signal source
2788  * @scale: scaling factor to be applied to represent the ratio as an integer
2789  *
2790  * Returns the duty cycle ratio of a clock node multiplied by the provided
2791  * scaling factor, or negative errno on error.
2792  */
2793 int clk_get_scaled_duty_cycle(struct clk *clk, unsigned int scale)
2794 {
2795         if (!clk)
2796                 return 0;
2797
2798         return clk_core_get_scaled_duty_cycle(clk->core, scale);
2799 }
2800 EXPORT_SYMBOL_GPL(clk_get_scaled_duty_cycle);
2801
2802 /**
2803  * clk_is_match - check if two clk's point to the same hardware clock
2804  * @p: clk compared against q
2805  * @q: clk compared against p
2806  *
2807  * Returns true if the two struct clk pointers both point to the same hardware
2808  * clock node. Put differently, returns true if struct clk *p and struct clk *q
2809  * share the same struct clk_core object.
2810  *
2811  * Returns false otherwise. Note that two NULL clks are treated as matching.
2812  */
2813 bool clk_is_match(const struct clk *p, const struct clk *q)
2814 {
2815         /* trivial case: identical struct clk's or both NULL */
2816         if (p == q)
2817                 return true;
2818
2819         /* true if clk->core pointers match. Avoid dereferencing garbage */
2820         if (!IS_ERR_OR_NULL(p) && !IS_ERR_OR_NULL(q))
2821                 if (p->core == q->core)
2822                         return true;
2823
2824         return false;
2825 }
2826 EXPORT_SYMBOL_GPL(clk_is_match);
2827
2828 /***        debugfs support        ***/
2829
2830 #ifdef CONFIG_DEBUG_FS
2831 #include <linux/debugfs.h>
2832
2833 static struct dentry *rootdir;
2834 static int inited = 0;
2835 static DEFINE_MUTEX(clk_debug_lock);
2836 static HLIST_HEAD(clk_debug_list);
2837
2838 static struct hlist_head *all_lists[] = {
2839         &clk_root_list,
2840         &clk_orphan_list,
2841         NULL,
2842 };
2843
2844 static struct hlist_head *orphan_list[] = {
2845         &clk_orphan_list,
2846         NULL,
2847 };
2848
2849 static void clk_summary_show_one(struct seq_file *s, struct clk_core *c,
2850                                  int level)
2851 {
2852         seq_printf(s, "%*s%-*s %7d %8d %8d %11lu %10lu %5d %6d\n",
2853                    level * 3 + 1, "",
2854                    30 - level * 3, c->name,
2855                    c->enable_count, c->prepare_count, c->protect_count,
2856                    clk_core_get_rate(c), clk_core_get_accuracy(c),
2857                    clk_core_get_phase(c),
2858                    clk_core_get_scaled_duty_cycle(c, 100000));
2859 }
2860
2861 static void clk_summary_show_subtree(struct seq_file *s, struct clk_core *c,
2862                                      int level)
2863 {
2864         struct clk_core *child;
2865
2866         clk_summary_show_one(s, c, level);
2867
2868         hlist_for_each_entry(child, &c->children, child_node)
2869                 clk_summary_show_subtree(s, child, level + 1);
2870 }
2871
2872 static int clk_summary_show(struct seq_file *s, void *data)
2873 {
2874         struct clk_core *c;
2875         struct hlist_head **lists = (struct hlist_head **)s->private;
2876
2877         seq_puts(s, "                                 enable  prepare  protect                                duty\n");
2878         seq_puts(s, "   clock                          count    count    count        rate   accuracy phase  cycle\n");
2879         seq_puts(s, "---------------------------------------------------------------------------------------------\n");
2880
2881         clk_prepare_lock();
2882
2883         for (; *lists; lists++)
2884                 hlist_for_each_entry(c, *lists, child_node)
2885                         clk_summary_show_subtree(s, c, 0);
2886
2887         clk_prepare_unlock();
2888
2889         return 0;
2890 }
2891 DEFINE_SHOW_ATTRIBUTE(clk_summary);
2892
2893 static void clk_dump_one(struct seq_file *s, struct clk_core *c, int level)
2894 {
2895         unsigned long min_rate, max_rate;
2896
2897         clk_core_get_boundaries(c, &min_rate, &max_rate);
2898
2899         /* This should be JSON format, i.e. elements separated with a comma */
2900         seq_printf(s, "\"%s\": { ", c->name);
2901         seq_printf(s, "\"enable_count\": %d,", c->enable_count);
2902         seq_printf(s, "\"prepare_count\": %d,", c->prepare_count);
2903         seq_printf(s, "\"protect_count\": %d,", c->protect_count);
2904         seq_printf(s, "\"rate\": %lu,", clk_core_get_rate(c));
2905         seq_printf(s, "\"min_rate\": %lu,", min_rate);
2906         seq_printf(s, "\"max_rate\": %lu,", max_rate);
2907         seq_printf(s, "\"accuracy\": %lu,", clk_core_get_accuracy(c));
2908         seq_printf(s, "\"phase\": %d,", clk_core_get_phase(c));
2909         seq_printf(s, "\"duty_cycle\": %u",
2910                    clk_core_get_scaled_duty_cycle(c, 100000));
2911 }
2912
2913 static void clk_dump_subtree(struct seq_file *s, struct clk_core *c, int level)
2914 {
2915         struct clk_core *child;
2916
2917         clk_dump_one(s, c, level);
2918
2919         hlist_for_each_entry(child, &c->children, child_node) {
2920                 seq_putc(s, ',');
2921                 clk_dump_subtree(s, child, level + 1);
2922         }
2923
2924         seq_putc(s, '}');
2925 }
2926
2927 static int clk_dump_show(struct seq_file *s, void *data)
2928 {
2929         struct clk_core *c;
2930         bool first_node = true;
2931         struct hlist_head **lists = (struct hlist_head **)s->private;
2932
2933         seq_putc(s, '{');
2934         clk_prepare_lock();
2935
2936         for (; *lists; lists++) {
2937                 hlist_for_each_entry(c, *lists, child_node) {
2938                         if (!first_node)
2939                                 seq_putc(s, ',');
2940                         first_node = false;
2941                         clk_dump_subtree(s, c, 0);
2942                 }
2943         }
2944
2945         clk_prepare_unlock();
2946
2947         seq_puts(s, "}\n");
2948         return 0;
2949 }
2950 DEFINE_SHOW_ATTRIBUTE(clk_dump);
2951
2952 static const struct {
2953         unsigned long flag;
2954         const char *name;
2955 } clk_flags[] = {
2956 #define ENTRY(f) { f, #f }
2957         ENTRY(CLK_SET_RATE_GATE),
2958         ENTRY(CLK_SET_PARENT_GATE),
2959         ENTRY(CLK_SET_RATE_PARENT),
2960         ENTRY(CLK_IGNORE_UNUSED),
2961         ENTRY(CLK_GET_RATE_NOCACHE),
2962         ENTRY(CLK_SET_RATE_NO_REPARENT),
2963         ENTRY(CLK_GET_ACCURACY_NOCACHE),
2964         ENTRY(CLK_RECALC_NEW_RATES),
2965         ENTRY(CLK_SET_RATE_UNGATE),
2966         ENTRY(CLK_IS_CRITICAL),
2967         ENTRY(CLK_OPS_PARENT_ENABLE),
2968         ENTRY(CLK_DUTY_CYCLE_PARENT),
2969 #undef ENTRY
2970 };
2971
2972 static int clk_flags_show(struct seq_file *s, void *data)
2973 {
2974         struct clk_core *core = s->private;
2975         unsigned long flags = core->flags;
2976         unsigned int i;
2977
2978         for (i = 0; flags && i < ARRAY_SIZE(clk_flags); i++) {
2979                 if (flags & clk_flags[i].flag) {
2980                         seq_printf(s, "%s\n", clk_flags[i].name);
2981                         flags &= ~clk_flags[i].flag;
2982                 }
2983         }
2984         if (flags) {
2985                 /* Unknown flags */
2986                 seq_printf(s, "0x%lx\n", flags);
2987         }
2988
2989         return 0;
2990 }
2991 DEFINE_SHOW_ATTRIBUTE(clk_flags);
2992
2993 static void possible_parent_show(struct seq_file *s, struct clk_core *core,
2994                                  unsigned int i, char terminator)
2995 {
2996         struct clk_core *parent;
2997
2998         /*
2999          * Go through the following options to fetch a parent's name.
3000          *
3001          * 1. Fetch the registered parent clock and use its name
3002          * 2. Use the global (fallback) name if specified
3003          * 3. Use the local fw_name if provided
3004          * 4. Fetch parent clock's clock-output-name if DT index was set
3005          *
3006          * This may still fail in some cases, such as when the parent is
3007          * specified directly via a struct clk_hw pointer, but it isn't
3008          * registered (yet).
3009          */
3010         parent = clk_core_get_parent_by_index(core, i);
3011         if (parent)
3012                 seq_puts(s, parent->name);
3013         else if (core->parents[i].name)
3014                 seq_puts(s, core->parents[i].name);
3015         else if (core->parents[i].fw_name)
3016                 seq_printf(s, "<%s>(fw)", core->parents[i].fw_name);
3017         else if (core->parents[i].index >= 0)
3018                 seq_puts(s,
3019                          of_clk_get_parent_name(core->of_node,
3020                                                 core->parents[i].index));
3021         else
3022                 seq_puts(s, "(missing)");
3023
3024         seq_putc(s, terminator);
3025 }
3026
3027 static int possible_parents_show(struct seq_file *s, void *data)
3028 {
3029         struct clk_core *core = s->private;
3030         int i;
3031
3032         for (i = 0; i < core->num_parents - 1; i++)
3033                 possible_parent_show(s, core, i, ' ');
3034
3035         possible_parent_show(s, core, i, '\n');
3036
3037         return 0;
3038 }
3039 DEFINE_SHOW_ATTRIBUTE(possible_parents);
3040
3041 static int current_parent_show(struct seq_file *s, void *data)
3042 {
3043         struct clk_core *core = s->private;
3044
3045         if (core->parent)
3046                 seq_printf(s, "%s\n", core->parent->name);
3047
3048         return 0;
3049 }
3050 DEFINE_SHOW_ATTRIBUTE(current_parent);
3051
3052 static int clk_duty_cycle_show(struct seq_file *s, void *data)
3053 {
3054         struct clk_core *core = s->private;
3055         struct clk_duty *duty = &core->duty;
3056
3057         seq_printf(s, "%u/%u\n", duty->num, duty->den);
3058
3059         return 0;
3060 }
3061 DEFINE_SHOW_ATTRIBUTE(clk_duty_cycle);
3062
3063 static int clk_min_rate_show(struct seq_file *s, void *data)
3064 {
3065         struct clk_core *core = s->private;
3066         unsigned long min_rate, max_rate;
3067
3068         clk_prepare_lock();
3069         clk_core_get_boundaries(core, &min_rate, &max_rate);
3070         clk_prepare_unlock();
3071         seq_printf(s, "%lu\n", min_rate);
3072
3073         return 0;
3074 }
3075 DEFINE_SHOW_ATTRIBUTE(clk_min_rate);
3076
3077 static int clk_max_rate_show(struct seq_file *s, void *data)
3078 {
3079         struct clk_core *core = s->private;
3080         unsigned long min_rate, max_rate;
3081
3082         clk_prepare_lock();
3083         clk_core_get_boundaries(core, &min_rate, &max_rate);
3084         clk_prepare_unlock();
3085         seq_printf(s, "%lu\n", max_rate);
3086
3087         return 0;
3088 }
3089 DEFINE_SHOW_ATTRIBUTE(clk_max_rate);
3090
3091 static void clk_debug_create_one(struct clk_core *core, struct dentry *pdentry)
3092 {
3093         struct dentry *root;
3094
3095         if (!core || !pdentry)
3096                 return;
3097
3098         root = debugfs_create_dir(core->name, pdentry);
3099         core->dentry = root;
3100
3101         debugfs_create_ulong("clk_rate", 0444, root, &core->rate);
3102         debugfs_create_file("clk_min_rate", 0444, root, core, &clk_min_rate_fops);
3103         debugfs_create_file("clk_max_rate", 0444, root, core, &clk_max_rate_fops);
3104         debugfs_create_ulong("clk_accuracy", 0444, root, &core->accuracy);
3105         debugfs_create_u32("clk_phase", 0444, root, &core->phase);
3106         debugfs_create_file("clk_flags", 0444, root, core, &clk_flags_fops);
3107         debugfs_create_u32("clk_prepare_count", 0444, root, &core->prepare_count);
3108         debugfs_create_u32("clk_enable_count", 0444, root, &core->enable_count);
3109         debugfs_create_u32("clk_protect_count", 0444, root, &core->protect_count);
3110         debugfs_create_u32("clk_notifier_count", 0444, root, &core->notifier_count);
3111         debugfs_create_file("clk_duty_cycle", 0444, root, core,
3112                             &clk_duty_cycle_fops);
3113
3114         if (core->num_parents > 0)
3115                 debugfs_create_file("clk_parent", 0444, root, core,
3116                                     &current_parent_fops);
3117
3118         if (core->num_parents > 1)
3119                 debugfs_create_file("clk_possible_parents", 0444, root, core,
3120                                     &possible_parents_fops);
3121
3122         if (core->ops->debug_init)
3123                 core->ops->debug_init(core->hw, core->dentry);
3124 }
3125
3126 /**
3127  * clk_debug_register - add a clk node to the debugfs clk directory
3128  * @core: the clk being added to the debugfs clk directory
3129  *
3130  * Dynamically adds a clk to the debugfs clk directory if debugfs has been
3131  * initialized.  Otherwise it bails out early since the debugfs clk directory
3132  * will be created lazily by clk_debug_init as part of a late_initcall.
3133  */
3134 static void clk_debug_register(struct clk_core *core)
3135 {
3136         mutex_lock(&clk_debug_lock);
3137         hlist_add_head(&core->debug_node, &clk_debug_list);
3138         if (inited)
3139                 clk_debug_create_one(core, rootdir);
3140         mutex_unlock(&clk_debug_lock);
3141 }
3142
3143  /**
3144  * clk_debug_unregister - remove a clk node from the debugfs clk directory
3145  * @core: the clk being removed from the debugfs clk directory
3146  *
3147  * Dynamically removes a clk and all its child nodes from the
3148  * debugfs clk directory if clk->dentry points to debugfs created by
3149  * clk_debug_register in __clk_core_init.
3150  */
3151 static void clk_debug_unregister(struct clk_core *core)
3152 {
3153         mutex_lock(&clk_debug_lock);
3154         hlist_del_init(&core->debug_node);
3155         debugfs_remove_recursive(core->dentry);
3156         core->dentry = NULL;
3157         mutex_unlock(&clk_debug_lock);
3158 }
3159
3160 /**
3161  * clk_debug_init - lazily populate the debugfs clk directory
3162  *
3163  * clks are often initialized very early during boot before memory can be
3164  * dynamically allocated and well before debugfs is setup. This function
3165  * populates the debugfs clk directory once at boot-time when we know that
3166  * debugfs is setup. It should only be called once at boot-time, all other clks
3167  * added dynamically will be done so with clk_debug_register.
3168  */
3169 static int __init clk_debug_init(void)
3170 {
3171         struct clk_core *core;
3172
3173         rootdir = debugfs_create_dir("clk", NULL);
3174
3175         debugfs_create_file("clk_summary", 0444, rootdir, &all_lists,
3176                             &clk_summary_fops);
3177         debugfs_create_file("clk_dump", 0444, rootdir, &all_lists,
3178                             &clk_dump_fops);
3179         debugfs_create_file("clk_orphan_summary", 0444, rootdir, &orphan_list,
3180                             &clk_summary_fops);
3181         debugfs_create_file("clk_orphan_dump", 0444, rootdir, &orphan_list,
3182                             &clk_dump_fops);
3183
3184         mutex_lock(&clk_debug_lock);
3185         hlist_for_each_entry(core, &clk_debug_list, debug_node)
3186                 clk_debug_create_one(core, rootdir);
3187
3188         inited = 1;
3189         mutex_unlock(&clk_debug_lock);
3190
3191         return 0;
3192 }
3193 late_initcall(clk_debug_init);
3194 #else
3195 static inline void clk_debug_register(struct clk_core *core) { }
3196 static inline void clk_debug_reparent(struct clk_core *core,
3197                                       struct clk_core *new_parent)
3198 {
3199 }
3200 static inline void clk_debug_unregister(struct clk_core *core)
3201 {
3202 }
3203 #endif
3204
3205 /**
3206  * __clk_core_init - initialize the data structures in a struct clk_core
3207  * @core:       clk_core being initialized
3208  *
3209  * Initializes the lists in struct clk_core, queries the hardware for the
3210  * parent and rate and sets them both.
3211  */
3212 static int __clk_core_init(struct clk_core *core)
3213 {
3214         int ret;
3215         struct clk_core *orphan;
3216         struct hlist_node *tmp2;
3217         unsigned long rate;
3218
3219         if (!core)
3220                 return -EINVAL;
3221
3222         clk_prepare_lock();
3223
3224         ret = clk_pm_runtime_get(core);
3225         if (ret)
3226                 goto unlock;
3227
3228         /* check to see if a clock with this name is already registered */
3229         if (clk_core_lookup(core->name)) {
3230                 pr_debug("%s: clk %s already initialized\n",
3231                                 __func__, core->name);
3232                 ret = -EEXIST;
3233                 goto out;
3234         }
3235
3236         /* check that clk_ops are sane.  See Documentation/driver-api/clk.rst */
3237         if (core->ops->set_rate &&
3238             !((core->ops->round_rate || core->ops->determine_rate) &&
3239               core->ops->recalc_rate)) {
3240                 pr_err("%s: %s must implement .round_rate or .determine_rate in addition to .recalc_rate\n",
3241                        __func__, core->name);
3242                 ret = -EINVAL;
3243                 goto out;
3244         }
3245
3246         if (core->ops->set_parent && !core->ops->get_parent) {
3247                 pr_err("%s: %s must implement .get_parent & .set_parent\n",
3248                        __func__, core->name);
3249                 ret = -EINVAL;
3250                 goto out;
3251         }
3252
3253         if (core->num_parents > 1 && !core->ops->get_parent) {
3254                 pr_err("%s: %s must implement .get_parent as it has multi parents\n",
3255                        __func__, core->name);
3256                 ret = -EINVAL;
3257                 goto out;
3258         }
3259
3260         if (core->ops->set_rate_and_parent &&
3261                         !(core->ops->set_parent && core->ops->set_rate)) {
3262                 pr_err("%s: %s must implement .set_parent & .set_rate\n",
3263                                 __func__, core->name);
3264                 ret = -EINVAL;
3265                 goto out;
3266         }
3267
3268         core->parent = __clk_init_parent(core);
3269
3270         /*
3271          * Populate core->parent if parent has already been clk_core_init'd. If
3272          * parent has not yet been clk_core_init'd then place clk in the orphan
3273          * list.  If clk doesn't have any parents then place it in the root
3274          * clk list.
3275          *
3276          * Every time a new clk is clk_init'd then we walk the list of orphan
3277          * clocks and re-parent any that are children of the clock currently
3278          * being clk_init'd.
3279          */
3280         if (core->parent) {
3281                 hlist_add_head(&core->child_node,
3282                                 &core->parent->children);
3283                 core->orphan = core->parent->orphan;
3284         } else if (!core->num_parents) {
3285                 hlist_add_head(&core->child_node, &clk_root_list);
3286                 core->orphan = false;
3287         } else {
3288                 hlist_add_head(&core->child_node, &clk_orphan_list);
3289                 core->orphan = true;
3290         }
3291
3292         /*
3293          * optional platform-specific magic
3294          *
3295          * The .init callback is not used by any of the basic clock types, but
3296          * exists for weird hardware that must perform initialization magic.
3297          * Please consider other ways of solving initialization problems before
3298          * using this callback, as its use is discouraged.
3299          */
3300         if (core->ops->init)
3301                 core->ops->init(core->hw);
3302
3303         /*
3304          * Set clk's accuracy.  The preferred method is to use
3305          * .recalc_accuracy. For simple clocks and lazy developers the default
3306          * fallback is to use the parent's accuracy.  If a clock doesn't have a
3307          * parent (or is orphaned) then accuracy is set to zero (perfect
3308          * clock).
3309          */
3310         if (core->ops->recalc_accuracy)
3311                 core->accuracy = core->ops->recalc_accuracy(core->hw,
3312                                         __clk_get_accuracy(core->parent));
3313         else if (core->parent)
3314                 core->accuracy = core->parent->accuracy;
3315         else
3316                 core->accuracy = 0;
3317
3318         /*
3319          * Set clk's phase.
3320          * Since a phase is by definition relative to its parent, just
3321          * query the current clock phase, or just assume it's in phase.
3322          */
3323         if (core->ops->get_phase)
3324                 core->phase = core->ops->get_phase(core->hw);
3325         else
3326                 core->phase = 0;
3327
3328         /*
3329          * Set clk's duty cycle.
3330          */
3331         clk_core_update_duty_cycle_nolock(core);
3332
3333         /*
3334          * Set clk's rate.  The preferred method is to use .recalc_rate.  For
3335          * simple clocks and lazy developers the default fallback is to use the
3336          * parent's rate.  If a clock doesn't have a parent (or is orphaned)
3337          * then rate is set to zero.
3338          */
3339         if (core->ops->recalc_rate)
3340                 rate = core->ops->recalc_rate(core->hw,
3341                                 clk_core_get_rate_nolock(core->parent));
3342         else if (core->parent)
3343                 rate = core->parent->rate;
3344         else
3345                 rate = 0;
3346         core->rate = core->req_rate = rate;
3347
3348         /*
3349          * Enable CLK_IS_CRITICAL clocks so newly added critical clocks
3350          * don't get accidentally disabled when walking the orphan tree and
3351          * reparenting clocks
3352          */
3353         if (core->flags & CLK_IS_CRITICAL) {
3354                 unsigned long flags;
3355
3356                 clk_core_prepare(core);
3357
3358                 flags = clk_enable_lock();
3359                 clk_core_enable(core);
3360                 clk_enable_unlock(flags);
3361         }
3362
3363         /*
3364          * walk the list of orphan clocks and reparent any that newly finds a
3365          * parent.
3366          */
3367         hlist_for_each_entry_safe(orphan, tmp2, &clk_orphan_list, child_node) {
3368                 struct clk_core *parent = __clk_init_parent(orphan);
3369
3370                 /*
3371                  * We need to use __clk_set_parent_before() and _after() to
3372                  * to properly migrate any prepare/enable count of the orphan
3373                  * clock. This is important for CLK_IS_CRITICAL clocks, which
3374                  * are enabled during init but might not have a parent yet.
3375                  */
3376                 if (parent) {
3377                         /* update the clk tree topology */
3378                         __clk_set_parent_before(orphan, parent);
3379                         __clk_set_parent_after(orphan, parent, NULL);
3380                         __clk_recalc_accuracies(orphan);
3381                         __clk_recalc_rates(orphan, 0);
3382                 }
3383         }
3384
3385         kref_init(&core->ref);
3386 out:
3387         clk_pm_runtime_put(core);
3388 unlock:
3389         clk_prepare_unlock();
3390
3391         if (!ret)
3392                 clk_debug_register(core);
3393
3394         return ret;
3395 }
3396
3397 /**
3398  * clk_core_link_consumer - Add a clk consumer to the list of consumers in a clk_core
3399  * @core: clk to add consumer to
3400  * @clk: consumer to link to a clk
3401  */
3402 static void clk_core_link_consumer(struct clk_core *core, struct clk *clk)
3403 {
3404         clk_prepare_lock();
3405         hlist_add_head(&clk->clks_node, &core->clks);
3406         clk_prepare_unlock();
3407 }
3408
3409 /**
3410  * clk_core_unlink_consumer - Remove a clk consumer from the list of consumers in a clk_core
3411  * @clk: consumer to unlink
3412  */
3413 static void clk_core_unlink_consumer(struct clk *clk)
3414 {
3415         lockdep_assert_held(&prepare_lock);
3416         hlist_del(&clk->clks_node);
3417 }
3418
3419 /**
3420  * alloc_clk - Allocate a clk consumer, but leave it unlinked to the clk_core
3421  * @core: clk to allocate a consumer for
3422  * @dev_id: string describing device name
3423  * @con_id: connection ID string on device
3424  *
3425  * Returns: clk consumer left unlinked from the consumer list
3426  */
3427 static struct clk *alloc_clk(struct clk_core *core, const char *dev_id,
3428                              const char *con_id)
3429 {
3430         struct clk *clk;
3431
3432         clk = kzalloc(sizeof(*clk), GFP_KERNEL);
3433         if (!clk)
3434                 return ERR_PTR(-ENOMEM);
3435
3436         clk->core = core;
3437         clk->dev_id = dev_id;
3438         clk->con_id = kstrdup_const(con_id, GFP_KERNEL);
3439         clk->max_rate = ULONG_MAX;
3440
3441         return clk;
3442 }
3443
3444 /**
3445  * free_clk - Free a clk consumer
3446  * @clk: clk consumer to free
3447  *
3448  * Note, this assumes the clk has been unlinked from the clk_core consumer
3449  * list.
3450  */
3451 static void free_clk(struct clk *clk)
3452 {
3453         kfree_const(clk->con_id);
3454         kfree(clk);
3455 }
3456
3457 /**
3458  * clk_hw_create_clk: Allocate and link a clk consumer to a clk_core given
3459  * a clk_hw
3460  * @dev: clk consumer device
3461  * @hw: clk_hw associated with the clk being consumed
3462  * @dev_id: string describing device name
3463  * @con_id: connection ID string on device
3464  *
3465  * This is the main function used to create a clk pointer for use by clk
3466  * consumers. It connects a consumer to the clk_core and clk_hw structures
3467  * used by the framework and clk provider respectively.
3468  */
3469 struct clk *clk_hw_create_clk(struct device *dev, struct clk_hw *hw,
3470                               const char *dev_id, const char *con_id)
3471 {
3472         struct clk *clk;
3473         struct clk_core *core;
3474
3475         /* This is to allow this function to be chained to others */
3476         if (IS_ERR_OR_NULL(hw))
3477                 return ERR_CAST(hw);
3478
3479         core = hw->core;
3480         clk = alloc_clk(core, dev_id, con_id);
3481         if (IS_ERR(clk))
3482                 return clk;
3483         clk->dev = dev;
3484
3485         if (!try_module_get(core->owner)) {
3486                 free_clk(clk);
3487                 return ERR_PTR(-ENOENT);
3488         }
3489
3490         kref_get(&core->ref);
3491         clk_core_link_consumer(core, clk);
3492
3493         return clk;
3494 }
3495
3496 static int clk_cpy_name(const char **dst_p, const char *src, bool must_exist)
3497 {
3498         const char *dst;
3499
3500         if (!src) {
3501                 if (must_exist)
3502                         return -EINVAL;
3503                 return 0;
3504         }
3505
3506         *dst_p = dst = kstrdup_const(src, GFP_KERNEL);
3507         if (!dst)
3508                 return -ENOMEM;
3509
3510         return 0;
3511 }
3512
3513 static int clk_core_populate_parent_map(struct clk_core *core)
3514 {
3515         const struct clk_init_data *init = core->hw->init;
3516         u8 num_parents = init->num_parents;
3517         const char * const *parent_names = init->parent_names;
3518         const struct clk_hw **parent_hws = init->parent_hws;
3519         const struct clk_parent_data *parent_data = init->parent_data;
3520         int i, ret = 0;
3521         struct clk_parent_map *parents, *parent;
3522
3523         if (!num_parents)
3524                 return 0;
3525
3526         /*
3527          * Avoid unnecessary string look-ups of clk_core's possible parents by
3528          * having a cache of names/clk_hw pointers to clk_core pointers.
3529          */
3530         parents = kcalloc(num_parents, sizeof(*parents), GFP_KERNEL);
3531         core->parents = parents;
3532         if (!parents)
3533                 return -ENOMEM;
3534
3535         /* Copy everything over because it might be __initdata */
3536         for (i = 0, parent = parents; i < num_parents; i++, parent++) {
3537                 parent->index = -1;
3538                 if (parent_names) {
3539                         /* throw a WARN if any entries are NULL */
3540                         WARN(!parent_names[i],
3541                                 "%s: invalid NULL in %s's .parent_names\n",
3542                                 __func__, core->name);
3543                         ret = clk_cpy_name(&parent->name, parent_names[i],
3544                                            true);
3545                 } else if (parent_data) {
3546                         parent->hw = parent_data[i].hw;
3547                         parent->index = parent_data[i].index;
3548                         ret = clk_cpy_name(&parent->fw_name,
3549                                            parent_data[i].fw_name, false);
3550                         if (!ret)
3551                                 ret = clk_cpy_name(&parent->name,
3552                                                    parent_data[i].name,
3553                                                    false);
3554                 } else if (parent_hws) {
3555                         parent->hw = parent_hws[i];
3556                 } else {
3557                         ret = -EINVAL;
3558                         WARN(1, "Must specify parents if num_parents > 0\n");
3559                 }
3560
3561                 if (ret) {
3562                         do {
3563                                 kfree_const(parents[i].name);
3564                                 kfree_const(parents[i].fw_name);
3565                         } while (--i >= 0);
3566                         kfree(parents);
3567
3568                         return ret;
3569                 }
3570         }
3571
3572         return 0;
3573 }
3574
3575 static void clk_core_free_parent_map(struct clk_core *core)
3576 {
3577         int i = core->num_parents;
3578
3579         if (!core->num_parents)
3580                 return;
3581
3582         while (--i >= 0) {
3583                 kfree_const(core->parents[i].name);
3584                 kfree_const(core->parents[i].fw_name);
3585         }
3586
3587         kfree(core->parents);
3588 }
3589
3590 static struct clk *
3591 __clk_register(struct device *dev, struct device_node *np, struct clk_hw *hw)
3592 {
3593         int ret;
3594         struct clk_core *core;
3595
3596         core = kzalloc(sizeof(*core), GFP_KERNEL);
3597         if (!core) {
3598                 ret = -ENOMEM;
3599                 goto fail_out;
3600         }
3601
3602         core->name = kstrdup_const(hw->init->name, GFP_KERNEL);
3603         if (!core->name) {
3604                 ret = -ENOMEM;
3605                 goto fail_name;
3606         }
3607
3608         if (WARN_ON(!hw->init->ops)) {
3609                 ret = -EINVAL;
3610                 goto fail_ops;
3611         }
3612         core->ops = hw->init->ops;
3613
3614         if (dev && pm_runtime_enabled(dev))
3615                 core->rpm_enabled = true;
3616         core->dev = dev;
3617         core->of_node = np;
3618         if (dev && dev->driver)
3619                 core->owner = dev->driver->owner;
3620         core->hw = hw;
3621         core->flags = hw->init->flags;
3622         core->num_parents = hw->init->num_parents;
3623         core->min_rate = 0;
3624         core->max_rate = ULONG_MAX;
3625         hw->core = core;
3626
3627         ret = clk_core_populate_parent_map(core);
3628         if (ret)
3629                 goto fail_parents;
3630
3631         INIT_HLIST_HEAD(&core->clks);
3632
3633         /*
3634          * Don't call clk_hw_create_clk() here because that would pin the
3635          * provider module to itself and prevent it from ever being removed.
3636          */
3637         hw->clk = alloc_clk(core, NULL, NULL);
3638         if (IS_ERR(hw->clk)) {
3639                 ret = PTR_ERR(hw->clk);
3640                 goto fail_create_clk;
3641         }
3642
3643         clk_core_link_consumer(hw->core, hw->clk);
3644
3645         ret = __clk_core_init(core);
3646         if (!ret)
3647                 return hw->clk;
3648
3649         clk_prepare_lock();
3650         clk_core_unlink_consumer(hw->clk);
3651         clk_prepare_unlock();
3652
3653         free_clk(hw->clk);
3654         hw->clk = NULL;
3655
3656 fail_create_clk:
3657         clk_core_free_parent_map(core);
3658 fail_parents:
3659 fail_ops:
3660         kfree_const(core->name);
3661 fail_name:
3662         kfree(core);
3663 fail_out:
3664         return ERR_PTR(ret);
3665 }
3666
3667 /**
3668  * clk_register - allocate a new clock, register it and return an opaque cookie
3669  * @dev: device that is registering this clock
3670  * @hw: link to hardware-specific clock data
3671  *
3672  * clk_register is the *deprecated* interface for populating the clock tree with
3673  * new clock nodes. Use clk_hw_register() instead.
3674  *
3675  * Returns: a pointer to the newly allocated struct clk which
3676  * cannot be dereferenced by driver code but may be used in conjunction with the
3677  * rest of the clock API.  In the event of an error clk_register will return an
3678  * error code; drivers must test for an error code after calling clk_register.
3679  */
3680 struct clk *clk_register(struct device *dev, struct clk_hw *hw)
3681 {
3682         return __clk_register(dev, dev_of_node(dev), hw);
3683 }
3684 EXPORT_SYMBOL_GPL(clk_register);
3685
3686 /**
3687  * clk_hw_register - register a clk_hw and return an error code
3688  * @dev: device that is registering this clock
3689  * @hw: link to hardware-specific clock data
3690  *
3691  * clk_hw_register is the primary interface for populating the clock tree with
3692  * new clock nodes. It returns an integer equal to zero indicating success or
3693  * less than zero indicating failure. Drivers must test for an error code after
3694  * calling clk_hw_register().
3695  */
3696 int clk_hw_register(struct device *dev, struct clk_hw *hw)
3697 {
3698         return PTR_ERR_OR_ZERO(__clk_register(dev, dev_of_node(dev), hw));
3699 }
3700 EXPORT_SYMBOL_GPL(clk_hw_register);
3701
3702 /*
3703  * of_clk_hw_register - register a clk_hw and return an error code
3704  * @node: device_node of device that is registering this clock
3705  * @hw: link to hardware-specific clock data
3706  *
3707  * of_clk_hw_register() is the primary interface for populating the clock tree
3708  * with new clock nodes when a struct device is not available, but a struct
3709  * device_node is. It returns an integer equal to zero indicating success or
3710  * less than zero indicating failure. Drivers must test for an error code after
3711  * calling of_clk_hw_register().
3712  */
3713 int of_clk_hw_register(struct device_node *node, struct clk_hw *hw)
3714 {
3715         return PTR_ERR_OR_ZERO(__clk_register(NULL, node, hw));
3716 }
3717 EXPORT_SYMBOL_GPL(of_clk_hw_register);
3718
3719 /* Free memory allocated for a clock. */
3720 static void __clk_release(struct kref *ref)
3721 {
3722         struct clk_core *core = container_of(ref, struct clk_core, ref);
3723
3724         lockdep_assert_held(&prepare_lock);
3725
3726         clk_core_free_parent_map(core);
3727         kfree_const(core->name);
3728         kfree(core);
3729 }
3730
3731 /*
3732  * Empty clk_ops for unregistered clocks. These are used temporarily
3733  * after clk_unregister() was called on a clock and until last clock
3734  * consumer calls clk_put() and the struct clk object is freed.
3735  */
3736 static int clk_nodrv_prepare_enable(struct clk_hw *hw)
3737 {
3738         return -ENXIO;
3739 }
3740
3741 static void clk_nodrv_disable_unprepare(struct clk_hw *hw)
3742 {
3743         WARN_ON_ONCE(1);
3744 }
3745
3746 static int clk_nodrv_set_rate(struct clk_hw *hw, unsigned long rate,
3747                                         unsigned long parent_rate)
3748 {
3749         return -ENXIO;
3750 }
3751
3752 static int clk_nodrv_set_parent(struct clk_hw *hw, u8 index)
3753 {
3754         return -ENXIO;
3755 }
3756
3757 static const struct clk_ops clk_nodrv_ops = {
3758         .enable         = clk_nodrv_prepare_enable,
3759         .disable        = clk_nodrv_disable_unprepare,
3760         .prepare        = clk_nodrv_prepare_enable,
3761         .unprepare      = clk_nodrv_disable_unprepare,
3762         .set_rate       = clk_nodrv_set_rate,
3763         .set_parent     = clk_nodrv_set_parent,
3764 };
3765
3766 /**
3767  * clk_unregister - unregister a currently registered clock
3768  * @clk: clock to unregister
3769  */
3770 void clk_unregister(struct clk *clk)
3771 {
3772         unsigned long flags;
3773
3774         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
3775                 return;
3776
3777         clk_debug_unregister(clk->core);
3778
3779         clk_prepare_lock();
3780
3781         if (clk->core->ops == &clk_nodrv_ops) {
3782                 pr_err("%s: unregistered clock: %s\n", __func__,
3783                        clk->core->name);
3784                 goto unlock;
3785         }
3786         /*
3787          * Assign empty clock ops for consumers that might still hold
3788          * a reference to this clock.
3789          */
3790         flags = clk_enable_lock();
3791         clk->core->ops = &clk_nodrv_ops;
3792         clk_enable_unlock(flags);
3793
3794         if (!hlist_empty(&clk->core->children)) {
3795                 struct clk_core *child;
3796                 struct hlist_node *t;
3797
3798                 /* Reparent all children to the orphan list. */
3799                 hlist_for_each_entry_safe(child, t, &clk->core->children,
3800                                           child_node)
3801                         clk_core_set_parent_nolock(child, NULL);
3802         }
3803
3804         hlist_del_init(&clk->core->child_node);
3805
3806         if (clk->core->prepare_count)
3807                 pr_warn("%s: unregistering prepared clock: %s\n",
3808                                         __func__, clk->core->name);
3809
3810         if (clk->core->protect_count)
3811                 pr_warn("%s: unregistering protected clock: %s\n",
3812                                         __func__, clk->core->name);
3813
3814         kref_put(&clk->core->ref, __clk_release);
3815 unlock:
3816         clk_prepare_unlock();
3817 }
3818 EXPORT_SYMBOL_GPL(clk_unregister);
3819
3820 /**
3821  * clk_hw_unregister - unregister a currently registered clk_hw
3822  * @hw: hardware-specific clock data to unregister
3823  */
3824 void clk_hw_unregister(struct clk_hw *hw)
3825 {
3826         clk_unregister(hw->clk);
3827 }
3828 EXPORT_SYMBOL_GPL(clk_hw_unregister);
3829
3830 static void devm_clk_release(struct device *dev, void *res)
3831 {
3832         clk_unregister(*(struct clk **)res);
3833 }
3834
3835 static void devm_clk_hw_release(struct device *dev, void *res)
3836 {
3837         clk_hw_unregister(*(struct clk_hw **)res);
3838 }
3839
3840 /**
3841  * devm_clk_register - resource managed clk_register()
3842  * @dev: device that is registering this clock
3843  * @hw: link to hardware-specific clock data
3844  *
3845  * Managed clk_register(). This function is *deprecated*, use devm_clk_hw_register() instead.
3846  *
3847  * Clocks returned from this function are automatically clk_unregister()ed on
3848  * driver detach. See clk_register() for more information.
3849  */
3850 struct clk *devm_clk_register(struct device *dev, struct clk_hw *hw)
3851 {
3852         struct clk *clk;
3853         struct clk **clkp;
3854
3855         clkp = devres_alloc(devm_clk_release, sizeof(*clkp), GFP_KERNEL);
3856         if (!clkp)
3857                 return ERR_PTR(-ENOMEM);
3858
3859         clk = clk_register(dev, hw);
3860         if (!IS_ERR(clk)) {
3861                 *clkp = clk;
3862                 devres_add(dev, clkp);
3863         } else {
3864                 devres_free(clkp);
3865         }
3866
3867         return clk;
3868 }
3869 EXPORT_SYMBOL_GPL(devm_clk_register);
3870
3871 /**
3872  * devm_clk_hw_register - resource managed clk_hw_register()
3873  * @dev: device that is registering this clock
3874  * @hw: link to hardware-specific clock data
3875  *
3876  * Managed clk_hw_register(). Clocks registered by this function are
3877  * automatically clk_hw_unregister()ed on driver detach. See clk_hw_register()
3878  * for more information.
3879  */
3880 int devm_clk_hw_register(struct device *dev, struct clk_hw *hw)
3881 {
3882         struct clk_hw **hwp;
3883         int ret;
3884
3885         hwp = devres_alloc(devm_clk_hw_release, sizeof(*hwp), GFP_KERNEL);
3886         if (!hwp)
3887                 return -ENOMEM;
3888
3889         ret = clk_hw_register(dev, hw);
3890         if (!ret) {
3891                 *hwp = hw;
3892                 devres_add(dev, hwp);
3893         } else {
3894                 devres_free(hwp);
3895         }
3896
3897         return ret;
3898 }
3899 EXPORT_SYMBOL_GPL(devm_clk_hw_register);
3900
3901 static int devm_clk_match(struct device *dev, void *res, void *data)
3902 {
3903         struct clk *c = res;
3904         if (WARN_ON(!c))
3905                 return 0;
3906         return c == data;
3907 }
3908
3909 static int devm_clk_hw_match(struct device *dev, void *res, void *data)
3910 {
3911         struct clk_hw *hw = res;
3912
3913         if (WARN_ON(!hw))
3914                 return 0;
3915         return hw == data;
3916 }
3917
3918 /**
3919  * devm_clk_unregister - resource managed clk_unregister()
3920  * @clk: clock to unregister
3921  *
3922  * Deallocate a clock allocated with devm_clk_register(). Normally
3923  * this function will not need to be called and the resource management
3924  * code will ensure that the resource is freed.
3925  */
3926 void devm_clk_unregister(struct device *dev, struct clk *clk)
3927 {
3928         WARN_ON(devres_release(dev, devm_clk_release, devm_clk_match, clk));
3929 }
3930 EXPORT_SYMBOL_GPL(devm_clk_unregister);
3931
3932 /**
3933  * devm_clk_hw_unregister - resource managed clk_hw_unregister()
3934  * @dev: device that is unregistering the hardware-specific clock data
3935  * @hw: link to hardware-specific clock data
3936  *
3937  * Unregister a clk_hw registered with devm_clk_hw_register(). Normally
3938  * this function will not need to be called and the resource management
3939  * code will ensure that the resource is freed.
3940  */
3941 void devm_clk_hw_unregister(struct device *dev, struct clk_hw *hw)
3942 {
3943         WARN_ON(devres_release(dev, devm_clk_hw_release, devm_clk_hw_match,
3944                                 hw));
3945 }
3946 EXPORT_SYMBOL_GPL(devm_clk_hw_unregister);
3947
3948 /*
3949  * clkdev helpers
3950  */
3951
3952 void __clk_put(struct clk *clk)
3953 {
3954         struct module *owner;
3955
3956         if (!clk || WARN_ON_ONCE(IS_ERR(clk)))
3957                 return;
3958
3959         clk_prepare_lock();
3960
3961         /*
3962          * Before calling clk_put, all calls to clk_rate_exclusive_get() from a
3963          * given user should be balanced with calls to clk_rate_exclusive_put()
3964          * and by that same consumer
3965          */
3966         if (WARN_ON(clk->exclusive_count)) {
3967                 /* We voiced our concern, let's sanitize the situation */
3968                 clk->core->protect_count -= (clk->exclusive_count - 1);
3969                 clk_core_rate_unprotect(clk->core);
3970                 clk->exclusive_count = 0;
3971         }
3972
3973         hlist_del(&clk->clks_node);
3974         if (clk->min_rate > clk->core->req_rate ||
3975             clk->max_rate < clk->core->req_rate)
3976                 clk_core_set_rate_nolock(clk->core, clk->core->req_rate);
3977
3978         owner = clk->core->owner;
3979         kref_put(&clk->core->ref, __clk_release);
3980
3981         clk_prepare_unlock();
3982
3983         module_put(owner);
3984
3985         free_clk(clk);
3986 }
3987
3988 /***        clk rate change notifiers        ***/
3989
3990 /**
3991  * clk_notifier_register - add a clk rate change notifier
3992  * @clk: struct clk * to watch
3993  * @nb: struct notifier_block * with callback info
3994  *
3995  * Request notification when clk's rate changes.  This uses an SRCU
3996  * notifier because we want it to block and notifier unregistrations are
3997  * uncommon.  The callbacks associated with the notifier must not
3998  * re-enter into the clk framework by calling any top-level clk APIs;
3999  * this will cause a nested prepare_lock mutex.
4000  *
4001  * In all notification cases (pre, post and abort rate change) the original
4002  * clock rate is passed to the callback via struct clk_notifier_data.old_rate
4003  * and the new frequency is passed via struct clk_notifier_data.new_rate.
4004  *
4005  * clk_notifier_register() must be called from non-atomic context.
4006  * Returns -EINVAL if called with null arguments, -ENOMEM upon
4007  * allocation failure; otherwise, passes along the return value of
4008  * srcu_notifier_chain_register().
4009  */
4010 int clk_notifier_register(struct clk *clk, struct notifier_block *nb)
4011 {
4012         struct clk_notifier *cn;
4013         int ret = -ENOMEM;
4014
4015         if (!clk || !nb)
4016                 return -EINVAL;
4017
4018         clk_prepare_lock();
4019
4020         /* search the list of notifiers for this clk */
4021         list_for_each_entry(cn, &clk_notifier_list, node)
4022                 if (cn->clk == clk)
4023                         break;
4024
4025         /* if clk wasn't in the notifier list, allocate new clk_notifier */
4026         if (cn->clk != clk) {
4027                 cn = kzalloc(sizeof(*cn), GFP_KERNEL);
4028                 if (!cn)
4029                         goto out;
4030
4031                 cn->clk = clk;
4032                 srcu_init_notifier_head(&cn->notifier_head);
4033
4034                 list_add(&cn->node, &clk_notifier_list);
4035         }
4036
4037         ret = srcu_notifier_chain_register(&cn->notifier_head, nb);
4038
4039         clk->core->notifier_count++;
4040
4041 out:
4042         clk_prepare_unlock();
4043
4044         return ret;
4045 }
4046 EXPORT_SYMBOL_GPL(clk_notifier_register);
4047
4048 /**
4049  * clk_notifier_unregister - remove a clk rate change notifier
4050  * @clk: struct clk *
4051  * @nb: struct notifier_block * with callback info
4052  *
4053  * Request no further notification for changes to 'clk' and frees memory
4054  * allocated in clk_notifier_register.
4055  *
4056  * Returns -EINVAL if called with null arguments; otherwise, passes
4057  * along the return value of srcu_notifier_chain_unregister().
4058  */
4059 int clk_notifier_unregister(struct clk *clk, struct notifier_block *nb)
4060 {
4061         struct clk_notifier *cn = NULL;
4062         int ret = -EINVAL;
4063
4064         if (!clk || !nb)
4065                 return -EINVAL;
4066
4067         clk_prepare_lock();
4068
4069         list_for_each_entry(cn, &clk_notifier_list, node)
4070                 if (cn->clk == clk)
4071                         break;
4072
4073         if (cn->clk == clk) {
4074                 ret = srcu_notifier_chain_unregister(&cn->notifier_head, nb);
4075
4076                 clk->core->notifier_count--;
4077
4078                 /* XXX the notifier code should handle this better */
4079                 if (!cn->notifier_head.head) {
4080                         srcu_cleanup_notifier_head(&cn->notifier_head);
4081                         list_del(&cn->node);
4082                         kfree(cn);
4083                 }
4084
4085         } else {
4086                 ret = -ENOENT;
4087         }
4088
4089         clk_prepare_unlock();
4090
4091         return ret;
4092 }
4093 EXPORT_SYMBOL_GPL(clk_notifier_unregister);
4094
4095 #ifdef CONFIG_OF
4096 /**
4097  * struct of_clk_provider - Clock provider registration structure
4098  * @link: Entry in global list of clock providers
4099  * @node: Pointer to device tree node of clock provider
4100  * @get: Get clock callback.  Returns NULL or a struct clk for the
4101  *       given clock specifier
4102  * @data: context pointer to be passed into @get callback
4103  */
4104 struct of_clk_provider {
4105         struct list_head link;
4106
4107         struct device_node *node;
4108         struct clk *(*get)(struct of_phandle_args *clkspec, void *data);
4109         struct clk_hw *(*get_hw)(struct of_phandle_args *clkspec, void *data);
4110         void *data;
4111 };
4112
4113 extern struct of_device_id __clk_of_table;
4114 static const struct of_device_id __clk_of_table_sentinel
4115         __used __section(__clk_of_table_end);
4116
4117 static LIST_HEAD(of_clk_providers);
4118 static DEFINE_MUTEX(of_clk_mutex);
4119
4120 struct clk *of_clk_src_simple_get(struct of_phandle_args *clkspec,
4121                                      void *data)
4122 {
4123         return data;
4124 }
4125 EXPORT_SYMBOL_GPL(of_clk_src_simple_get);
4126
4127 struct clk_hw *of_clk_hw_simple_get(struct of_phandle_args *clkspec, void *data)
4128 {
4129         return data;
4130 }
4131 EXPORT_SYMBOL_GPL(of_clk_hw_simple_get);
4132
4133 struct clk *of_clk_src_onecell_get(struct of_phandle_args *clkspec, void *data)
4134 {
4135         struct clk_onecell_data *clk_data = data;
4136         unsigned int idx = clkspec->args[0];
4137
4138         if (idx >= clk_data->clk_num) {
4139                 pr_err("%s: invalid clock index %u\n", __func__, idx);
4140                 return ERR_PTR(-EINVAL);
4141         }
4142
4143         return clk_data->clks[idx];
4144 }
4145 EXPORT_SYMBOL_GPL(of_clk_src_onecell_get);
4146
4147 struct clk_hw *
4148 of_clk_hw_onecell_get(struct of_phandle_args *clkspec, void *data)
4149 {
4150         struct clk_hw_onecell_data *hw_data = data;
4151         unsigned int idx = clkspec->args[0];
4152
4153         if (idx >= hw_data->num) {
4154                 pr_err("%s: invalid index %u\n", __func__, idx);
4155                 return ERR_PTR(-EINVAL);
4156         }
4157
4158         return hw_data->hws[idx];
4159 }
4160 EXPORT_SYMBOL_GPL(of_clk_hw_onecell_get);
4161
4162 /**
4163  * of_clk_add_provider() - Register a clock provider for a node
4164  * @np: Device node pointer associated with clock provider
4165  * @clk_src_get: callback for decoding clock
4166  * @data: context pointer for @clk_src_get callback.
4167  *
4168  * This function is *deprecated*. Use of_clk_add_hw_provider() instead.
4169  */
4170 int of_clk_add_provider(struct device_node *np,
4171                         struct clk *(*clk_src_get)(struct of_phandle_args *clkspec,
4172                                                    void *data),
4173                         void *data)
4174 {
4175         struct of_clk_provider *cp;
4176         int ret;
4177
4178         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
4179         if (!cp)
4180                 return -ENOMEM;
4181
4182         cp->node = of_node_get(np);
4183         cp->data = data;
4184         cp->get = clk_src_get;
4185
4186         mutex_lock(&of_clk_mutex);
4187         list_add(&cp->link, &of_clk_providers);
4188         mutex_unlock(&of_clk_mutex);
4189         pr_debug("Added clock from %pOF\n", np);
4190
4191         ret = of_clk_set_defaults(np, true);
4192         if (ret < 0)
4193                 of_clk_del_provider(np);
4194
4195         return ret;
4196 }
4197 EXPORT_SYMBOL_GPL(of_clk_add_provider);
4198
4199 /**
4200  * of_clk_add_hw_provider() - Register a clock provider for a node
4201  * @np: Device node pointer associated with clock provider
4202  * @get: callback for decoding clk_hw
4203  * @data: context pointer for @get callback.
4204  */
4205 int of_clk_add_hw_provider(struct device_node *np,
4206                            struct clk_hw *(*get)(struct of_phandle_args *clkspec,
4207                                                  void *data),
4208                            void *data)
4209 {
4210         struct of_clk_provider *cp;
4211         int ret;
4212
4213         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
4214         if (!cp)
4215                 return -ENOMEM;
4216
4217         cp->node = of_node_get(np);
4218         cp->data = data;
4219         cp->get_hw = get;
4220
4221         mutex_lock(&of_clk_mutex);
4222         list_add(&cp->link, &of_clk_providers);
4223         mutex_unlock(&of_clk_mutex);
4224         pr_debug("Added clk_hw provider from %pOF\n", np);
4225
4226         ret = of_clk_set_defaults(np, true);
4227         if (ret < 0)
4228                 of_clk_del_provider(np);
4229
4230         return ret;
4231 }
4232 EXPORT_SYMBOL_GPL(of_clk_add_hw_provider);
4233
4234 static void devm_of_clk_release_provider(struct device *dev, void *res)
4235 {
4236         of_clk_del_provider(*(struct device_node **)res);
4237 }
4238
4239 /*
4240  * We allow a child device to use its parent device as the clock provider node
4241  * for cases like MFD sub-devices where the child device driver wants to use
4242  * devm_*() APIs but not list the device in DT as a sub-node.
4243  */
4244 static struct device_node *get_clk_provider_node(struct device *dev)
4245 {
4246         struct device_node *np, *parent_np;
4247
4248         np = dev->of_node;
4249         parent_np = dev->parent ? dev->parent->of_node : NULL;
4250
4251         if (!of_find_property(np, "#clock-cells", NULL))
4252                 if (of_find_property(parent_np, "#clock-cells", NULL))
4253                         np = parent_np;
4254
4255         return np;
4256 }
4257
4258 /**
4259  * devm_of_clk_add_hw_provider() - Managed clk provider node registration
4260  * @dev: Device acting as the clock provider (used for DT node and lifetime)
4261  * @get: callback for decoding clk_hw
4262  * @data: context pointer for @get callback
4263  *
4264  * Registers clock provider for given device's node. If the device has no DT
4265  * node or if the device node lacks of clock provider information (#clock-cells)
4266  * then the parent device's node is scanned for this information. If parent node
4267  * has the #clock-cells then it is used in registration. Provider is
4268  * automatically released at device exit.
4269  *
4270  * Return: 0 on success or an errno on failure.
4271  */
4272 int devm_of_clk_add_hw_provider(struct device *dev,
4273                         struct clk_hw *(*get)(struct of_phandle_args *clkspec,
4274                                               void *data),
4275                         void *data)
4276 {
4277         struct device_node **ptr, *np;
4278         int ret;
4279
4280         ptr = devres_alloc(devm_of_clk_release_provider, sizeof(*ptr),
4281                            GFP_KERNEL);
4282         if (!ptr)
4283                 return -ENOMEM;
4284
4285         np = get_clk_provider_node(dev);
4286         ret = of_clk_add_hw_provider(np, get, data);
4287         if (!ret) {
4288                 *ptr = np;
4289                 devres_add(dev, ptr);
4290         } else {
4291                 devres_free(ptr);
4292         }
4293
4294         return ret;
4295 }
4296 EXPORT_SYMBOL_GPL(devm_of_clk_add_hw_provider);
4297
4298 /**
4299  * of_clk_del_provider() - Remove a previously registered clock provider
4300  * @np: Device node pointer associated with clock provider
4301  */
4302 void of_clk_del_provider(struct device_node *np)
4303 {
4304         struct of_clk_provider *cp;
4305
4306         mutex_lock(&of_clk_mutex);
4307         list_for_each_entry(cp, &of_clk_providers, link) {
4308                 if (cp->node == np) {
4309                         list_del(&cp->link);
4310                         of_node_put(cp->node);
4311                         kfree(cp);
4312                         break;
4313                 }
4314         }
4315         mutex_unlock(&of_clk_mutex);
4316 }
4317 EXPORT_SYMBOL_GPL(of_clk_del_provider);
4318
4319 static int devm_clk_provider_match(struct device *dev, void *res, void *data)
4320 {
4321         struct device_node **np = res;
4322
4323         if (WARN_ON(!np || !*np))
4324                 return 0;
4325
4326         return *np == data;
4327 }
4328
4329 /**
4330  * devm_of_clk_del_provider() - Remove clock provider registered using devm
4331  * @dev: Device to whose lifetime the clock provider was bound
4332  */
4333 void devm_of_clk_del_provider(struct device *dev)
4334 {
4335         int ret;
4336         struct device_node *np = get_clk_provider_node(dev);
4337
4338         ret = devres_release(dev, devm_of_clk_release_provider,
4339                              devm_clk_provider_match, np);
4340
4341         WARN_ON(ret);
4342 }
4343 EXPORT_SYMBOL(devm_of_clk_del_provider);
4344
4345 /*
4346  * Beware the return values when np is valid, but no clock provider is found.
4347  * If name == NULL, the function returns -ENOENT.
4348  * If name != NULL, the function returns -EINVAL. This is because
4349  * of_parse_phandle_with_args() is called even if of_property_match_string()
4350  * returns an error.
4351  */
4352 static int of_parse_clkspec(const struct device_node *np, int index,
4353                             const char *name, struct of_phandle_args *out_args)
4354 {
4355         int ret = -ENOENT;
4356
4357         /* Walk up the tree of devices looking for a clock property that matches */
4358         while (np) {
4359                 /*
4360                  * For named clocks, first look up the name in the
4361                  * "clock-names" property.  If it cannot be found, then index
4362                  * will be an error code and of_parse_phandle_with_args() will
4363                  * return -EINVAL.
4364                  */
4365                 if (name)
4366                         index = of_property_match_string(np, "clock-names", name);
4367                 ret = of_parse_phandle_with_args(np, "clocks", "#clock-cells",
4368                                                  index, out_args);
4369                 if (!ret)
4370                         break;
4371                 if (name && index >= 0)
4372                         break;
4373
4374                 /*
4375                  * No matching clock found on this node.  If the parent node
4376                  * has a "clock-ranges" property, then we can try one of its
4377                  * clocks.
4378                  */
4379                 np = np->parent;
4380                 if (np && !of_get_property(np, "clock-ranges", NULL))
4381                         break;
4382                 index = 0;
4383         }
4384
4385         return ret;
4386 }
4387
4388 static struct clk_hw *
4389 __of_clk_get_hw_from_provider(struct of_clk_provider *provider,
4390                               struct of_phandle_args *clkspec)
4391 {
4392         struct clk *clk;
4393
4394         if (provider->get_hw)
4395                 return provider->get_hw(clkspec, provider->data);
4396
4397         clk = provider->get(clkspec, provider->data);
4398         if (IS_ERR(clk))
4399                 return ERR_CAST(clk);
4400         return __clk_get_hw(clk);
4401 }
4402
4403 static struct clk_hw *
4404 of_clk_get_hw_from_clkspec(struct of_phandle_args *clkspec)
4405 {
4406         struct of_clk_provider *provider;
4407         struct clk_hw *hw = ERR_PTR(-EPROBE_DEFER);
4408
4409         if (!clkspec)
4410                 return ERR_PTR(-EINVAL);
4411
4412         mutex_lock(&of_clk_mutex);
4413         list_for_each_entry(provider, &of_clk_providers, link) {
4414                 if (provider->node == clkspec->np) {
4415                         hw = __of_clk_get_hw_from_provider(provider, clkspec);
4416                         if (!IS_ERR(hw))
4417                                 break;
4418                 }
4419         }
4420         mutex_unlock(&of_clk_mutex);
4421
4422         return hw;
4423 }
4424
4425 /**
4426  * of_clk_get_from_provider() - Lookup a clock from a clock provider
4427  * @clkspec: pointer to a clock specifier data structure
4428  *
4429  * This function looks up a struct clk from the registered list of clock
4430  * providers, an input is a clock specifier data structure as returned
4431  * from the of_parse_phandle_with_args() function call.
4432  */
4433 struct clk *of_clk_get_from_provider(struct of_phandle_args *clkspec)
4434 {
4435         struct clk_hw *hw = of_clk_get_hw_from_clkspec(clkspec);
4436
4437         return clk_hw_create_clk(NULL, hw, NULL, __func__);
4438 }
4439 EXPORT_SYMBOL_GPL(of_clk_get_from_provider);
4440
4441 struct clk_hw *of_clk_get_hw(struct device_node *np, int index,
4442                              const char *con_id)
4443 {
4444         int ret;
4445         struct clk_hw *hw;
4446         struct of_phandle_args clkspec;
4447
4448         ret = of_parse_clkspec(np, index, con_id, &clkspec);
4449         if (ret)
4450                 return ERR_PTR(ret);
4451
4452         hw = of_clk_get_hw_from_clkspec(&clkspec);
4453         of_node_put(clkspec.np);
4454
4455         return hw;
4456 }
4457
4458 static struct clk *__of_clk_get(struct device_node *np,
4459                                 int index, const char *dev_id,
4460                                 const char *con_id)
4461 {
4462         struct clk_hw *hw = of_clk_get_hw(np, index, con_id);
4463
4464         return clk_hw_create_clk(NULL, hw, dev_id, con_id);
4465 }
4466
4467 struct clk *of_clk_get(struct device_node *np, int index)
4468 {
4469         return __of_clk_get(np, index, np->full_name, NULL);
4470 }
4471 EXPORT_SYMBOL(of_clk_get);
4472
4473 /**
4474  * of_clk_get_by_name() - Parse and lookup a clock referenced by a device node
4475  * @np: pointer to clock consumer node
4476  * @name: name of consumer's clock input, or NULL for the first clock reference
4477  *
4478  * This function parses the clocks and clock-names properties,
4479  * and uses them to look up the struct clk from the registered list of clock
4480  * providers.
4481  */
4482 struct clk *of_clk_get_by_name(struct device_node *np, const char *name)
4483 {
4484         if (!np)
4485                 return ERR_PTR(-ENOENT);
4486
4487         return __of_clk_get(np, 0, np->full_name, name);
4488 }
4489 EXPORT_SYMBOL(of_clk_get_by_name);
4490
4491 /**
4492  * of_clk_get_parent_count() - Count the number of clocks a device node has
4493  * @np: device node to count
4494  *
4495  * Returns: The number of clocks that are possible parents of this node
4496  */
4497 unsigned int of_clk_get_parent_count(struct device_node *np)
4498 {
4499         int count;
4500
4501         count = of_count_phandle_with_args(np, "clocks", "#clock-cells");
4502         if (count < 0)
4503                 return 0;
4504
4505         return count;
4506 }
4507 EXPORT_SYMBOL_GPL(of_clk_get_parent_count);
4508
4509 const char *of_clk_get_parent_name(struct device_node *np, int index)
4510 {
4511         struct of_phandle_args clkspec;
4512         struct property *prop;
4513         const char *clk_name;
4514         const __be32 *vp;
4515         u32 pv;
4516         int rc;
4517         int count;
4518         struct clk *clk;
4519
4520         rc = of_parse_phandle_with_args(np, "clocks", "#clock-cells", index,
4521                                         &clkspec);
4522         if (rc)
4523                 return NULL;
4524
4525         index = clkspec.args_count ? clkspec.args[0] : 0;
4526         count = 0;
4527
4528         /* if there is an indices property, use it to transfer the index
4529          * specified into an array offset for the clock-output-names property.
4530          */
4531         of_property_for_each_u32(clkspec.np, "clock-indices", prop, vp, pv) {
4532                 if (index == pv) {
4533                         index = count;
4534                         break;
4535                 }
4536                 count++;
4537         }
4538         /* We went off the end of 'clock-indices' without finding it */
4539         if (prop && !vp)
4540                 return NULL;
4541
4542         if (of_property_read_string_index(clkspec.np, "clock-output-names",
4543                                           index,
4544                                           &clk_name) < 0) {
4545                 /*
4546                  * Best effort to get the name if the clock has been
4547                  * registered with the framework. If the clock isn't
4548                  * registered, we return the node name as the name of
4549                  * the clock as long as #clock-cells = 0.
4550                  */
4551                 clk = of_clk_get_from_provider(&clkspec);
4552                 if (IS_ERR(clk)) {
4553                         if (clkspec.args_count == 0)
4554                                 clk_name = clkspec.np->name;
4555                         else
4556                                 clk_name = NULL;
4557                 } else {
4558                         clk_name = __clk_get_name(clk);
4559                         clk_put(clk);
4560                 }
4561         }
4562
4563
4564         of_node_put(clkspec.np);
4565         return clk_name;
4566 }
4567 EXPORT_SYMBOL_GPL(of_clk_get_parent_name);
4568
4569 /**
4570  * of_clk_parent_fill() - Fill @parents with names of @np's parents and return
4571  * number of parents
4572  * @np: Device node pointer associated with clock provider
4573  * @parents: pointer to char array that hold the parents' names
4574  * @size: size of the @parents array
4575  *
4576  * Return: number of parents for the clock node.
4577  */
4578 int of_clk_parent_fill(struct device_node *np, const char **parents,
4579                        unsigned int size)
4580 {
4581         unsigned int i = 0;
4582
4583         while (i < size && (parents[i] = of_clk_get_parent_name(np, i)) != NULL)
4584                 i++;
4585
4586         return i;
4587 }
4588 EXPORT_SYMBOL_GPL(of_clk_parent_fill);
4589
4590 struct clock_provider {
4591         void (*clk_init_cb)(struct device_node *);
4592         struct device_node *np;
4593         struct list_head node;
4594 };
4595
4596 /*
4597  * This function looks for a parent clock. If there is one, then it
4598  * checks that the provider for this parent clock was initialized, in
4599  * this case the parent clock will be ready.
4600  */
4601 static int parent_ready(struct device_node *np)
4602 {
4603         int i = 0;
4604
4605         while (true) {
4606                 struct clk *clk = of_clk_get(np, i);
4607
4608                 /* this parent is ready we can check the next one */
4609                 if (!IS_ERR(clk)) {
4610                         clk_put(clk);
4611                         i++;
4612                         continue;
4613                 }
4614
4615                 /* at least one parent is not ready, we exit now */
4616                 if (PTR_ERR(clk) == -EPROBE_DEFER)
4617                         return 0;
4618
4619                 /*
4620                  * Here we make assumption that the device tree is
4621                  * written correctly. So an error means that there is
4622                  * no more parent. As we didn't exit yet, then the
4623                  * previous parent are ready. If there is no clock
4624                  * parent, no need to wait for them, then we can
4625                  * consider their absence as being ready
4626                  */
4627                 return 1;
4628         }
4629 }
4630
4631 /**
4632  * of_clk_detect_critical() - set CLK_IS_CRITICAL flag from Device Tree
4633  * @np: Device node pointer associated with clock provider
4634  * @index: clock index
4635  * @flags: pointer to top-level framework flags
4636  *
4637  * Detects if the clock-critical property exists and, if so, sets the
4638  * corresponding CLK_IS_CRITICAL flag.
4639  *
4640  * Do not use this function. It exists only for legacy Device Tree
4641  * bindings, such as the one-clock-per-node style that are outdated.
4642  * Those bindings typically put all clock data into .dts and the Linux
4643  * driver has no clock data, thus making it impossible to set this flag
4644  * correctly from the driver. Only those drivers may call
4645  * of_clk_detect_critical from their setup functions.
4646  *
4647  * Return: error code or zero on success
4648  */
4649 int of_clk_detect_critical(struct device_node *np,
4650                                           int index, unsigned long *flags)
4651 {
4652         struct property *prop;
4653         const __be32 *cur;
4654         uint32_t idx;
4655
4656         if (!np || !flags)
4657                 return -EINVAL;
4658
4659         of_property_for_each_u32(np, "clock-critical", prop, cur, idx)
4660                 if (index == idx)
4661                         *flags |= CLK_IS_CRITICAL;
4662
4663         return 0;
4664 }
4665
4666 /**
4667  * of_clk_init() - Scan and init clock providers from the DT
4668  * @matches: array of compatible values and init functions for providers.
4669  *
4670  * This function scans the device tree for matching clock providers
4671  * and calls their initialization functions. It also does it by trying
4672  * to follow the dependencies.
4673  */
4674 void __init of_clk_init(const struct of_device_id *matches)
4675 {
4676         const struct of_device_id *match;
4677         struct device_node *np;
4678         struct clock_provider *clk_provider, *next;
4679         bool is_init_done;
4680         bool force = false;
4681         LIST_HEAD(clk_provider_list);
4682
4683         if (!matches)
4684                 matches = &__clk_of_table;
4685
4686         /* First prepare the list of the clocks providers */
4687         for_each_matching_node_and_match(np, matches, &match) {
4688                 struct clock_provider *parent;
4689
4690                 if (!of_device_is_available(np))
4691                         continue;
4692
4693                 parent = kzalloc(sizeof(*parent), GFP_KERNEL);
4694                 if (!parent) {
4695                         list_for_each_entry_safe(clk_provider, next,
4696                                                  &clk_provider_list, node) {
4697                                 list_del(&clk_provider->node);
4698                                 of_node_put(clk_provider->np);
4699                                 kfree(clk_provider);
4700                         }
4701                         of_node_put(np);
4702                         return;
4703                 }
4704
4705                 parent->clk_init_cb = match->data;
4706                 parent->np = of_node_get(np);
4707                 list_add_tail(&parent->node, &clk_provider_list);
4708         }
4709
4710         while (!list_empty(&clk_provider_list)) {
4711                 is_init_done = false;
4712                 list_for_each_entry_safe(clk_provider, next,
4713                                         &clk_provider_list, node) {
4714                         if (force || parent_ready(clk_provider->np)) {
4715
4716                                 /* Don't populate platform devices */
4717                                 of_node_set_flag(clk_provider->np,
4718                                                  OF_POPULATED);
4719
4720                                 clk_provider->clk_init_cb(clk_provider->np);
4721                                 of_clk_set_defaults(clk_provider->np, true);
4722
4723                                 list_del(&clk_provider->node);
4724                                 of_node_put(clk_provider->np);
4725                                 kfree(clk_provider);
4726                                 is_init_done = true;
4727                         }
4728                 }
4729
4730                 /*
4731                  * We didn't manage to initialize any of the
4732                  * remaining providers during the last loop, so now we
4733                  * initialize all the remaining ones unconditionally
4734                  * in case the clock parent was not mandatory
4735                  */
4736                 if (!is_init_done)
4737                         force = true;
4738         }
4739 }
4740 #endif