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