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