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