1/*
2 * SCI Clock driver for keystone based devices
3 *
4 * Copyright (C) 2015-2016 Texas Instruments Incorporated - https://www.ti.com/
5 *	Tero Kristo <t-kristo@ti.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
10 *
11 * This program is distributed "as is" WITHOUT ANY WARRANTY of any
12 * kind, whether express or implied; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 */
16#include <linux/clk-provider.h>
17#include <linux/err.h>
18#include <linux/io.h>
19#include <linux/module.h>
20#include <linux/of_address.h>
21#include <linux/of_device.h>
22#include <linux/platform_device.h>
23#include <linux/slab.h>
24#include <linux/soc/ti/ti_sci_protocol.h>
25#include <linux/bsearch.h>
26#include <linux/list_sort.h>
27
28#define SCI_CLK_SSC_ENABLE		BIT(0)
29#define SCI_CLK_ALLOW_FREQ_CHANGE	BIT(1)
30#define SCI_CLK_INPUT_TERMINATION	BIT(2)
31
32/**
33 * struct sci_clk_provider - TI SCI clock provider representation
34 * @sci: Handle to the System Control Interface protocol handler
35 * @ops: Pointer to the SCI ops to be used by the clocks
36 * @dev: Device pointer for the clock provider
37 * @clocks: Clocks array for this device
38 * @num_clocks: Total number of clocks for this provider
39 */
40struct sci_clk_provider {
41	const struct ti_sci_handle *sci;
42	const struct ti_sci_clk_ops *ops;
43	struct device *dev;
44	struct sci_clk **clocks;
45	int num_clocks;
46};
47
48/**
49 * struct sci_clk - TI SCI clock representation
50 * @hw:		 Hardware clock cookie for common clock framework
51 * @dev_id:	 Device index
52 * @clk_id:	 Clock index
53 * @num_parents: Number of parents for this clock
54 * @provider:	 Master clock provider
55 * @flags:	 Flags for the clock
56 * @node:	 Link for handling clocks probed via DT
57 * @cached_req:	 Cached requested freq for determine rate calls
58 * @cached_res:	 Cached result freq for determine rate calls
59 */
60struct sci_clk {
61	struct clk_hw hw;
62	u16 dev_id;
63	u32 clk_id;
64	u32 num_parents;
65	struct sci_clk_provider *provider;
66	u8 flags;
67	struct list_head node;
68	unsigned long cached_req;
69	unsigned long cached_res;
70};
71
72#define to_sci_clk(_hw) container_of(_hw, struct sci_clk, hw)
73
74/**
75 * sci_clk_prepare - Prepare (enable) a TI SCI clock
76 * @hw: clock to prepare
77 *
78 * Prepares a clock to be actively used. Returns the SCI protocol status.
79 */
80static int sci_clk_prepare(struct clk_hw *hw)
81{
82	struct sci_clk *clk = to_sci_clk(hw);
83	bool enable_ssc = clk->flags & SCI_CLK_SSC_ENABLE;
84	bool allow_freq_change = clk->flags & SCI_CLK_ALLOW_FREQ_CHANGE;
85	bool input_termination = clk->flags & SCI_CLK_INPUT_TERMINATION;
86
87	return clk->provider->ops->get_clock(clk->provider->sci, clk->dev_id,
88					     clk->clk_id, enable_ssc,
89					     allow_freq_change,
90					     input_termination);
91}
92
93/**
94 * sci_clk_unprepare - Un-prepares (disables) a TI SCI clock
95 * @hw: clock to unprepare
96 *
97 * Un-prepares a clock from active state.
98 */
99static void sci_clk_unprepare(struct clk_hw *hw)
100{
101	struct sci_clk *clk = to_sci_clk(hw);
102	int ret;
103
104	ret = clk->provider->ops->put_clock(clk->provider->sci, clk->dev_id,
105					    clk->clk_id);
106	if (ret)
107		dev_err(clk->provider->dev,
108			"unprepare failed for dev=%d, clk=%d, ret=%d\n",
109			clk->dev_id, clk->clk_id, ret);
110}
111
112/**
113 * sci_clk_is_prepared - Check if a TI SCI clock is prepared or not
114 * @hw: clock to check status for
115 *
116 * Checks if a clock is prepared (enabled) in hardware. Returns non-zero
117 * value if clock is enabled, zero otherwise.
118 */
119static int sci_clk_is_prepared(struct clk_hw *hw)
120{
121	struct sci_clk *clk = to_sci_clk(hw);
122	bool req_state, current_state;
123	int ret;
124
125	ret = clk->provider->ops->is_on(clk->provider->sci, clk->dev_id,
126					clk->clk_id, &req_state,
127					&current_state);
128	if (ret) {
129		dev_err(clk->provider->dev,
130			"is_prepared failed for dev=%d, clk=%d, ret=%d\n",
131			clk->dev_id, clk->clk_id, ret);
132		return 0;
133	}
134
135	return req_state;
136}
137
138/**
139 * sci_clk_recalc_rate - Get clock rate for a TI SCI clock
140 * @hw: clock to get rate for
141 * @parent_rate: parent rate provided by common clock framework, not used
142 *
143 * Gets the current clock rate of a TI SCI clock. Returns the current
144 * clock rate, or zero in failure.
145 */
146static unsigned long sci_clk_recalc_rate(struct clk_hw *hw,
147					 unsigned long parent_rate)
148{
149	struct sci_clk *clk = to_sci_clk(hw);
150	u64 freq;
151	int ret;
152
153	ret = clk->provider->ops->get_freq(clk->provider->sci, clk->dev_id,
154					   clk->clk_id, &freq);
155	if (ret) {
156		dev_err(clk->provider->dev,
157			"recalc-rate failed for dev=%d, clk=%d, ret=%d\n",
158			clk->dev_id, clk->clk_id, ret);
159		return 0;
160	}
161
162	return freq;
163}
164
165/**
166 * sci_clk_determine_rate - Determines a clock rate a clock can be set to
167 * @hw: clock to change rate for
168 * @req: requested rate configuration for the clock
169 *
170 * Determines a suitable clock rate and parent for a TI SCI clock.
171 * The parent handling is un-used, as generally the parent clock rates
172 * are not known by the kernel; instead these are internally handled
173 * by the firmware. Returns 0 on success, negative error value on failure.
174 */
175static int sci_clk_determine_rate(struct clk_hw *hw,
176				  struct clk_rate_request *req)
177{
178	struct sci_clk *clk = to_sci_clk(hw);
179	int ret;
180	u64 new_rate;
181
182	if (clk->cached_req && clk->cached_req == req->rate) {
183		req->rate = clk->cached_res;
184		return 0;
185	}
186
187	ret = clk->provider->ops->get_best_match_freq(clk->provider->sci,
188						      clk->dev_id,
189						      clk->clk_id,
190						      req->min_rate,
191						      req->rate,
192						      req->max_rate,
193						      &new_rate);
194	if (ret) {
195		dev_err(clk->provider->dev,
196			"determine-rate failed for dev=%d, clk=%d, ret=%d\n",
197			clk->dev_id, clk->clk_id, ret);
198		return ret;
199	}
200
201	clk->cached_req = req->rate;
202	clk->cached_res = new_rate;
203
204	req->rate = new_rate;
205
206	return 0;
207}
208
209/**
210 * sci_clk_set_rate - Set rate for a TI SCI clock
211 * @hw: clock to change rate for
212 * @rate: target rate for the clock
213 * @parent_rate: rate of the clock parent, not used for TI SCI clocks
214 *
215 * Sets a clock frequency for a TI SCI clock. Returns the TI SCI
216 * protocol status.
217 */
218static int sci_clk_set_rate(struct clk_hw *hw, unsigned long rate,
219			    unsigned long parent_rate)
220{
221	struct sci_clk *clk = to_sci_clk(hw);
222
223	return clk->provider->ops->set_freq(clk->provider->sci, clk->dev_id,
224					    clk->clk_id, rate / 10 * 9, rate,
225					    rate / 10 * 11);
226}
227
228/**
229 * sci_clk_get_parent - Get the current parent of a TI SCI clock
230 * @hw: clock to get parent for
231 *
232 * Returns the index of the currently selected parent for a TI SCI clock.
233 */
234static u8 sci_clk_get_parent(struct clk_hw *hw)
235{
236	struct sci_clk *clk = to_sci_clk(hw);
237	u32 parent_id = 0;
238	int ret;
239
240	ret = clk->provider->ops->get_parent(clk->provider->sci, clk->dev_id,
241					     clk->clk_id, (void *)&parent_id);
242	if (ret) {
243		dev_err(clk->provider->dev,
244			"get-parent failed for dev=%d, clk=%d, ret=%d\n",
245			clk->dev_id, clk->clk_id, ret);
246		return 0;
247	}
248
249	parent_id = parent_id - clk->clk_id - 1;
250
251	return (u8)parent_id;
252}
253
254/**
255 * sci_clk_set_parent - Set the parent of a TI SCI clock
256 * @hw: clock to set parent for
257 * @index: new parent index for the clock
258 *
259 * Sets the parent of a TI SCI clock. Return TI SCI protocol status.
260 */
261static int sci_clk_set_parent(struct clk_hw *hw, u8 index)
262{
263	struct sci_clk *clk = to_sci_clk(hw);
264
265	clk->cached_req = 0;
266
267	return clk->provider->ops->set_parent(clk->provider->sci, clk->dev_id,
268					      clk->clk_id,
269					      index + 1 + clk->clk_id);
270}
271
272static const struct clk_ops sci_clk_ops = {
273	.prepare = sci_clk_prepare,
274	.unprepare = sci_clk_unprepare,
275	.is_prepared = sci_clk_is_prepared,
276	.recalc_rate = sci_clk_recalc_rate,
277	.determine_rate = sci_clk_determine_rate,
278	.set_rate = sci_clk_set_rate,
279	.get_parent = sci_clk_get_parent,
280	.set_parent = sci_clk_set_parent,
281};
282
283/**
284 * _sci_clk_get - Gets a handle for an SCI clock
285 * @provider: Handle to SCI clock provider
286 * @sci_clk: Handle to the SCI clock to populate
287 *
288 * Gets a handle to an existing TI SCI hw clock, or builds a new clock
289 * entry and registers it with the common clock framework. Called from
290 * the common clock framework, when a corresponding of_clk_get call is
291 * executed, or recursively from itself when parsing parent clocks.
292 * Returns 0 on success, negative error code on failure.
293 */
294static int _sci_clk_build(struct sci_clk_provider *provider,
295			  struct sci_clk *sci_clk)
296{
297	struct clk_init_data init = { NULL };
298	char *name = NULL;
299	char **parent_names = NULL;
300	int i;
301	int ret = 0;
302
303	name = kasprintf(GFP_KERNEL, "clk:%d:%d", sci_clk->dev_id,
304			 sci_clk->clk_id);
305	if (!name)
306		return -ENOMEM;
307
308	init.name = name;
309
310	/*
311	 * From kernel point of view, we only care about a clocks parents,
312	 * if it has more than 1 possible parent. In this case, it is going
313	 * to have mux functionality. Otherwise it is going to act as a root
314	 * clock.
315	 */
316	if (sci_clk->num_parents < 2)
317		sci_clk->num_parents = 0;
318
319	if (sci_clk->num_parents) {
320		parent_names = kcalloc(sci_clk->num_parents, sizeof(char *),
321				       GFP_KERNEL);
322
323		if (!parent_names) {
324			ret = -ENOMEM;
325			goto err;
326		}
327
328		for (i = 0; i < sci_clk->num_parents; i++) {
329			char *parent_name;
330
331			parent_name = kasprintf(GFP_KERNEL, "clk:%d:%d",
332						sci_clk->dev_id,
333						sci_clk->clk_id + 1 + i);
334			if (!parent_name) {
335				ret = -ENOMEM;
336				goto err;
337			}
338			parent_names[i] = parent_name;
339		}
340		init.parent_names = (void *)parent_names;
341	}
342
343	init.ops = &sci_clk_ops;
344	init.num_parents = sci_clk->num_parents;
345	sci_clk->hw.init = &init;
346
347	ret = devm_clk_hw_register(provider->dev, &sci_clk->hw);
348	if (ret)
349		dev_err(provider->dev, "failed clk register with %d\n", ret);
350
351err:
352	if (parent_names) {
353		for (i = 0; i < sci_clk->num_parents; i++)
354			kfree(parent_names[i]);
355
356		kfree(parent_names);
357	}
358
359	kfree(name);
360
361	return ret;
362}
363
364static int _cmp_sci_clk(const void *a, const void *b)
365{
366	const struct sci_clk *ca = a;
367	const struct sci_clk *cb = *(struct sci_clk **)b;
368
369	if (ca->dev_id == cb->dev_id && ca->clk_id == cb->clk_id)
370		return 0;
371	if (ca->dev_id > cb->dev_id ||
372	    (ca->dev_id == cb->dev_id && ca->clk_id > cb->clk_id))
373		return 1;
374	return -1;
375}
376
377/**
378 * sci_clk_get - Xlate function for getting clock handles
379 * @clkspec: device tree clock specifier
380 * @data: pointer to the clock provider
381 *
382 * Xlate function for retrieving clock TI SCI hw clock handles based on
383 * device tree clock specifier. Called from the common clock framework,
384 * when a corresponding of_clk_get call is executed. Returns a pointer
385 * to the TI SCI hw clock struct, or ERR_PTR value in failure.
386 */
387static struct clk_hw *sci_clk_get(struct of_phandle_args *clkspec, void *data)
388{
389	struct sci_clk_provider *provider = data;
390	struct sci_clk **clk;
391	struct sci_clk key;
392
393	if (clkspec->args_count != 2)
394		return ERR_PTR(-EINVAL);
395
396	key.dev_id = clkspec->args[0];
397	key.clk_id = clkspec->args[1];
398
399	clk = bsearch(&key, provider->clocks, provider->num_clocks,
400		      sizeof(clk), _cmp_sci_clk);
401
402	if (!clk)
403		return ERR_PTR(-ENODEV);
404
405	return &(*clk)->hw;
406}
407
408static int ti_sci_init_clocks(struct sci_clk_provider *p)
409{
410	int i;
411	int ret;
412
413	for (i = 0; i < p->num_clocks; i++) {
414		ret = _sci_clk_build(p, p->clocks[i]);
415		if (ret)
416			return ret;
417	}
418
419	return 0;
420}
421
422static const struct of_device_id ti_sci_clk_of_match[] = {
423	{ .compatible = "ti,k2g-sci-clk" },
424	{ /* Sentinel */ },
425};
426MODULE_DEVICE_TABLE(of, ti_sci_clk_of_match);
427
428#ifdef CONFIG_TI_SCI_CLK_PROBE_FROM_FW
429static int ti_sci_scan_clocks_from_fw(struct sci_clk_provider *provider)
430{
431	int ret;
432	int num_clks = 0;
433	struct sci_clk **clks = NULL;
434	struct sci_clk **tmp_clks;
435	struct sci_clk *sci_clk;
436	int max_clks = 0;
437	int clk_id = 0;
438	int dev_id = 0;
439	u32 num_parents = 0;
440	int gap_size = 0;
441	struct device *dev = provider->dev;
442
443	while (1) {
444		ret = provider->ops->get_num_parents(provider->sci, dev_id,
445						     clk_id,
446						     (void *)&num_parents);
447		if (ret) {
448			gap_size++;
449			if (!clk_id) {
450				if (gap_size >= 5)
451					break;
452				dev_id++;
453			} else {
454				if (gap_size >= 2) {
455					dev_id++;
456					clk_id = 0;
457					gap_size = 0;
458				} else {
459					clk_id++;
460				}
461			}
462			continue;
463		}
464
465		gap_size = 0;
466
467		if (num_clks == max_clks) {
468			tmp_clks = devm_kmalloc_array(dev, max_clks + 64,
469						      sizeof(sci_clk),
470						      GFP_KERNEL);
471			memcpy(tmp_clks, clks, max_clks * sizeof(sci_clk));
472			if (max_clks)
473				devm_kfree(dev, clks);
474			max_clks += 64;
475			clks = tmp_clks;
476		}
477
478		sci_clk = devm_kzalloc(dev, sizeof(*sci_clk), GFP_KERNEL);
479		if (!sci_clk)
480			return -ENOMEM;
481		sci_clk->dev_id = dev_id;
482		sci_clk->clk_id = clk_id;
483		sci_clk->provider = provider;
484		sci_clk->num_parents = num_parents;
485
486		clks[num_clks] = sci_clk;
487
488		clk_id++;
489		num_clks++;
490	}
491
492	provider->clocks = devm_kmalloc_array(dev, num_clks, sizeof(sci_clk),
493					      GFP_KERNEL);
494	if (!provider->clocks)
495		return -ENOMEM;
496
497	memcpy(provider->clocks, clks, num_clks * sizeof(sci_clk));
498
499	provider->num_clocks = num_clks;
500
501	devm_kfree(dev, clks);
502
503	return 0;
504}
505
506#else
507
508static int _cmp_sci_clk_list(void *priv, const struct list_head *a,
509			     const struct list_head *b)
510{
511	struct sci_clk *ca = container_of(a, struct sci_clk, node);
512	struct sci_clk *cb = container_of(b, struct sci_clk, node);
513
514	return _cmp_sci_clk(ca, &cb);
515}
516
517static int ti_sci_scan_clocks_from_dt(struct sci_clk_provider *provider)
518{
519	struct device *dev = provider->dev;
520	struct device_node *np = NULL;
521	int ret;
522	int index;
523	struct of_phandle_args args;
524	struct list_head clks;
525	struct sci_clk *sci_clk, *prev;
526	int num_clks = 0;
527	int num_parents;
528	int clk_id;
529	const char * const clk_names[] = {
530		"clocks", "assigned-clocks", "assigned-clock-parents", NULL
531	};
532	const char * const *clk_name;
533
534	INIT_LIST_HEAD(&clks);
535
536	clk_name = clk_names;
537
538	while (*clk_name) {
539		np = of_find_node_with_property(np, *clk_name);
540		if (!np) {
541			clk_name++;
542			continue;
543		}
544
545		if (!of_device_is_available(np))
546			continue;
547
548		index = 0;
549
550		do {
551			ret = of_parse_phandle_with_args(np, *clk_name,
552							 "#clock-cells", index,
553							 &args);
554			if (ret)
555				break;
556
557			if (args.args_count == 2 && args.np == dev->of_node) {
558				sci_clk = devm_kzalloc(dev, sizeof(*sci_clk),
559						       GFP_KERNEL);
560				if (!sci_clk)
561					return -ENOMEM;
562
563				sci_clk->dev_id = args.args[0];
564				sci_clk->clk_id = args.args[1];
565				sci_clk->provider = provider;
566				provider->ops->get_num_parents(provider->sci,
567							       sci_clk->dev_id,
568							       sci_clk->clk_id,
569							       (void *)&sci_clk->num_parents);
570				list_add_tail(&sci_clk->node, &clks);
571
572				num_clks++;
573
574				num_parents = sci_clk->num_parents;
575				if (num_parents == 1)
576					num_parents = 0;
577
578				/*
579				 * Linux kernel has inherent limitation
580				 * of 255 clock parents at the moment.
581				 * Right now, it is not expected that
582				 * any mux clock from sci-clk driver
583				 * would exceed that limit either, but
584				 * the ABI basically provides that
585				 * possibility. Print out a warning if
586				 * this happens for any clock.
587				 */
588				if (num_parents >= 255) {
589					dev_warn(dev, "too many parents for dev=%d, clk=%d (%d), cropping to 255.\n",
590						 sci_clk->dev_id,
591						 sci_clk->clk_id, num_parents);
592					num_parents = 255;
593				}
594
595				clk_id = args.args[1] + 1;
596
597				while (num_parents--) {
598					sci_clk = devm_kzalloc(dev,
599							       sizeof(*sci_clk),
600							       GFP_KERNEL);
601					if (!sci_clk)
602						return -ENOMEM;
603					sci_clk->dev_id = args.args[0];
604					sci_clk->clk_id = clk_id++;
605					sci_clk->provider = provider;
606					list_add_tail(&sci_clk->node, &clks);
607
608					num_clks++;
609				}
610			}
611
612			index++;
613		} while (args.np);
614	}
615
616	list_sort(NULL, &clks, _cmp_sci_clk_list);
617
618	provider->clocks = devm_kmalloc_array(dev, num_clks, sizeof(sci_clk),
619					      GFP_KERNEL);
620	if (!provider->clocks)
621		return -ENOMEM;
622
623	num_clks = 0;
624	prev = NULL;
625
626	list_for_each_entry(sci_clk, &clks, node) {
627		if (prev && prev->dev_id == sci_clk->dev_id &&
628		    prev->clk_id == sci_clk->clk_id)
629			continue;
630
631		provider->clocks[num_clks++] = sci_clk;
632		prev = sci_clk;
633	}
634
635	provider->num_clocks = num_clks;
636
637	return 0;
638}
639#endif
640
641/**
642 * ti_sci_clk_probe - Probe function for the TI SCI clock driver
643 * @pdev: platform device pointer to be probed
644 *
645 * Probes the TI SCI clock device. Allocates a new clock provider
646 * and registers this to the common clock framework. Also applies
647 * any required flags to the identified clocks via clock lists
648 * supplied from DT. Returns 0 for success, negative error value
649 * for failure.
650 */
651static int ti_sci_clk_probe(struct platform_device *pdev)
652{
653	struct device *dev = &pdev->dev;
654	struct device_node *np = dev->of_node;
655	struct sci_clk_provider *provider;
656	const struct ti_sci_handle *handle;
657	int ret;
658
659	handle = devm_ti_sci_get_handle(dev);
660	if (IS_ERR(handle))
661		return PTR_ERR(handle);
662
663	provider = devm_kzalloc(dev, sizeof(*provider), GFP_KERNEL);
664	if (!provider)
665		return -ENOMEM;
666
667	provider->sci = handle;
668	provider->ops = &handle->ops.clk_ops;
669	provider->dev = dev;
670
671#ifdef CONFIG_TI_SCI_CLK_PROBE_FROM_FW
672	ret = ti_sci_scan_clocks_from_fw(provider);
673	if (ret) {
674		dev_err(dev, "scan clocks from FW failed: %d\n", ret);
675		return ret;
676	}
677#else
678	ret = ti_sci_scan_clocks_from_dt(provider);
679	if (ret) {
680		dev_err(dev, "scan clocks from DT failed: %d\n", ret);
681		return ret;
682	}
683#endif
684
685	ret = ti_sci_init_clocks(provider);
686	if (ret) {
687		pr_err("ti-sci-init-clocks failed.\n");
688		return ret;
689	}
690
691	return of_clk_add_hw_provider(np, sci_clk_get, provider);
692}
693
694/**
695 * ti_sci_clk_remove - Remove TI SCI clock device
696 * @pdev: platform device pointer for the device to be removed
697 *
698 * Removes the TI SCI device. Unregisters the clock provider registered
699 * via common clock framework. Any memory allocated for the device will
700 * be free'd silently via the devm framework. Returns 0 always.
701 */
702static int ti_sci_clk_remove(struct platform_device *pdev)
703{
704	of_clk_del_provider(pdev->dev.of_node);
705
706	return 0;
707}
708
709static struct platform_driver ti_sci_clk_driver = {
710	.probe = ti_sci_clk_probe,
711	.remove = ti_sci_clk_remove,
712	.driver = {
713		.name = "ti-sci-clk",
714		.of_match_table = of_match_ptr(ti_sci_clk_of_match),
715	},
716};
717module_platform_driver(ti_sci_clk_driver);
718
719MODULE_LICENSE("GPL v2");
720MODULE_DESCRIPTION("TI System Control Interface(SCI) Clock driver");
721MODULE_AUTHOR("Tero Kristo");
722MODULE_ALIAS("platform:ti-sci-clk");
723