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