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