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