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