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