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