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