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