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