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