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