1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2014 Free Electrons
4  *
5  * Author: Boris BREZILLON <boris.brezillon@free-electrons.com>
6  *
7  * Allwinner A31 APB0 clock gates driver
8  */
9 
10 #include <linux/clk-provider.h>
11 #include <linux/init.h>
12 #include <linux/of.h>
13 #include <linux/platform_device.h>
14 
15 #define SUN6I_APB0_GATES_MAX_SIZE	32
16 
17 struct gates_data {
18 	DECLARE_BITMAP(mask, SUN6I_APB0_GATES_MAX_SIZE);
19 };
20 
21 static const struct gates_data sun6i_a31_apb0_gates __initconst = {
22 	.mask = {0x7F},
23 };
24 
25 static const struct gates_data sun8i_a23_apb0_gates __initconst = {
26 	.mask = {0x5D},
27 };
28 
29 static const struct of_device_id sun6i_a31_apb0_gates_clk_dt_ids[] = {
30 	{ .compatible = "allwinner,sun6i-a31-apb0-gates-clk", .data = &sun6i_a31_apb0_gates },
31 	{ .compatible = "allwinner,sun8i-a23-apb0-gates-clk", .data = &sun8i_a23_apb0_gates },
32 	{ /* sentinel */ }
33 };
34 
sun6i_a31_apb0_gates_clk_probe(struct platform_device * pdev)35 static int sun6i_a31_apb0_gates_clk_probe(struct platform_device *pdev)
36 {
37 	struct device_node *np = pdev->dev.of_node;
38 	struct clk_onecell_data *clk_data;
39 	const struct gates_data *data;
40 	const char *clk_parent;
41 	const char *clk_name;
42 	void __iomem *reg;
43 	int ngates;
44 	int i;
45 	int j = 0;
46 
47 	if (!np)
48 		return -ENODEV;
49 
50 	data = of_device_get_match_data(&pdev->dev);
51 	if (!data)
52 		return -ENODEV;
53 
54 	reg = devm_platform_ioremap_resource(pdev, 0);
55 	if (IS_ERR(reg))
56 		return PTR_ERR(reg);
57 
58 	clk_parent = of_clk_get_parent_name(np, 0);
59 	if (!clk_parent)
60 		return -EINVAL;
61 
62 	clk_data = devm_kzalloc(&pdev->dev, sizeof(struct clk_onecell_data),
63 				GFP_KERNEL);
64 	if (!clk_data)
65 		return -ENOMEM;
66 
67 	/* Worst-case size approximation and memory allocation */
68 	ngates = find_last_bit(data->mask, SUN6I_APB0_GATES_MAX_SIZE);
69 	clk_data->clks = devm_kcalloc(&pdev->dev, (ngates + 1),
70 				      sizeof(struct clk *), GFP_KERNEL);
71 	if (!clk_data->clks)
72 		return -ENOMEM;
73 
74 	for_each_set_bit(i, data->mask, SUN6I_APB0_GATES_MAX_SIZE) {
75 		of_property_read_string_index(np, "clock-output-names",
76 					      j, &clk_name);
77 
78 		clk_data->clks[i] = clk_register_gate(&pdev->dev, clk_name,
79 						      clk_parent, 0, reg, i,
80 						      0, NULL);
81 		WARN_ON(IS_ERR(clk_data->clks[i]));
82 
83 		j++;
84 	}
85 
86 	clk_data->clk_num = ngates + 1;
87 
88 	return of_clk_add_provider(np, of_clk_src_onecell_get, clk_data);
89 }
90 
91 static struct platform_driver sun6i_a31_apb0_gates_clk_driver = {
92 	.driver = {
93 		.name = "sun6i-a31-apb0-gates-clk",
94 		.of_match_table = sun6i_a31_apb0_gates_clk_dt_ids,
95 	},
96 	.probe = sun6i_a31_apb0_gates_clk_probe,
97 };
98 builtin_platform_driver(sun6i_a31_apb0_gates_clk_driver);
99