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