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