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