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