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