1 /*
2  * Copyright (C) 2014 Free Electrons
3  *
4  * License Terms: GNU General Public License v2
5  * Author: Boris BREZILLON <boris.brezillon@free-electrons.com>
6  *
7  * Allwinner A31 APB0 clock gates driver
8  *
9  */
10 
11 #include <linux/clk-provider.h>
12 #include <linux/module.h>
13 #include <linux/of.h>
14 #include <linux/platform_device.h>
15 
16 #define SUN6I_APB0_GATES_MAX_SIZE	32
17 
18 static int sun6i_a31_apb0_gates_clk_probe(struct platform_device *pdev)
19 {
20 	struct device_node *np = pdev->dev.of_node;
21 	struct clk_onecell_data *clk_data;
22 	const char *clk_parent;
23 	const char *clk_name;
24 	struct resource *r;
25 	void __iomem *reg;
26 	int gate_id;
27 	int ngates;
28 	int i;
29 
30 	r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
31 	reg = devm_ioremap_resource(&pdev->dev, r);
32 	if (IS_ERR(reg))
33 		return PTR_ERR(reg);
34 
35 	clk_parent = of_clk_get_parent_name(np, 0);
36 	if (!clk_parent)
37 		return -EINVAL;
38 
39 	ngates = of_property_count_strings(np, "clock-output-names");
40 	if (ngates < 0)
41 		return ngates;
42 
43 	if (!ngates || ngates > SUN6I_APB0_GATES_MAX_SIZE)
44 		return -EINVAL;
45 
46 	clk_data = devm_kzalloc(&pdev->dev, sizeof(struct clk_onecell_data),
47 				GFP_KERNEL);
48 	if (!clk_data)
49 		return -ENOMEM;
50 
51 	clk_data->clks = devm_kzalloc(&pdev->dev,
52 				      SUN6I_APB0_GATES_MAX_SIZE *
53 				      sizeof(struct clk *),
54 				      GFP_KERNEL);
55 	if (!clk_data->clks)
56 		return -ENOMEM;
57 
58 	for (i = 0; i < ngates; i++) {
59 		of_property_read_string_index(np, "clock-output-names",
60 					      i, &clk_name);
61 
62 		gate_id = i;
63 		of_property_read_u32_index(np, "clock-indices", i, &gate_id);
64 
65 		WARN_ON(gate_id >= SUN6I_APB0_GATES_MAX_SIZE);
66 		if (gate_id >= SUN6I_APB0_GATES_MAX_SIZE)
67 			continue;
68 
69 		clk_data->clks[gate_id] = clk_register_gate(&pdev->dev,
70 							    clk_name,
71 							    clk_parent, 0,
72 							    reg, gate_id,
73 							    0, NULL);
74 		WARN_ON(IS_ERR(clk_data->clks[gate_id]));
75 	}
76 
77 	clk_data->clk_num = ngates;
78 
79 	return of_clk_add_provider(np, of_clk_src_onecell_get, clk_data);
80 }
81 
82 const struct of_device_id sun6i_a31_apb0_gates_clk_dt_ids[] = {
83 	{ .compatible = "allwinner,sun6i-a31-apb0-gates-clk" },
84 	{ /* sentinel */ }
85 };
86 
87 static struct platform_driver sun6i_a31_apb0_gates_clk_driver = {
88 	.driver = {
89 		.name = "sun6i-a31-apb0-gates-clk",
90 		.owner = THIS_MODULE,
91 		.of_match_table = sun6i_a31_apb0_gates_clk_dt_ids,
92 	},
93 	.probe = sun6i_a31_apb0_gates_clk_probe,
94 };
95 module_platform_driver(sun6i_a31_apb0_gates_clk_driver);
96 
97 MODULE_AUTHOR("Boris BREZILLON <boris.brezillon@free-electrons.com>");
98 MODULE_DESCRIPTION("Allwinner A31 APB0 gate clocks driver");
99 MODULE_LICENSE("GPL v2");
100