1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Copyright (c) 2015 Linaro Ltd.
4 * Author: Pi-Cheng Chen <pi-cheng.chen@linaro.org>
5 */
6
7#include <linux/clk-provider.h>
8#include <linux/mfd/syscon.h>
9#include <linux/slab.h>
10
11#include "clk-mtk.h"
12#include "clk-cpumux.h"
13
14static inline struct mtk_clk_cpumux *to_mtk_clk_cpumux(struct clk_hw *_hw)
15{
16	return container_of(_hw, struct mtk_clk_cpumux, hw);
17}
18
19static u8 clk_cpumux_get_parent(struct clk_hw *hw)
20{
21	struct mtk_clk_cpumux *mux = to_mtk_clk_cpumux(hw);
22	unsigned int val;
23
24	regmap_read(mux->regmap, mux->reg, &val);
25
26	val >>= mux->shift;
27	val &= mux->mask;
28
29	return val;
30}
31
32static int clk_cpumux_set_parent(struct clk_hw *hw, u8 index)
33{
34	struct mtk_clk_cpumux *mux = to_mtk_clk_cpumux(hw);
35	u32 mask, val;
36
37	val = index << mux->shift;
38	mask = mux->mask << mux->shift;
39
40	return regmap_update_bits(mux->regmap, mux->reg, mask, val);
41}
42
43static const struct clk_ops clk_cpumux_ops = {
44	.get_parent = clk_cpumux_get_parent,
45	.set_parent = clk_cpumux_set_parent,
46};
47
48static struct clk *
49mtk_clk_register_cpumux(const struct mtk_composite *mux,
50			struct regmap *regmap)
51{
52	struct mtk_clk_cpumux *cpumux;
53	struct clk *clk;
54	struct clk_init_data init;
55
56	cpumux = kzalloc(sizeof(*cpumux), GFP_KERNEL);
57	if (!cpumux)
58		return ERR_PTR(-ENOMEM);
59
60	init.name = mux->name;
61	init.ops = &clk_cpumux_ops;
62	init.parent_names = mux->parent_names;
63	init.num_parents = mux->num_parents;
64	init.flags = mux->flags;
65
66	cpumux->reg = mux->mux_reg;
67	cpumux->shift = mux->mux_shift;
68	cpumux->mask = BIT(mux->mux_width) - 1;
69	cpumux->regmap = regmap;
70	cpumux->hw.init = &init;
71
72	clk = clk_register(NULL, &cpumux->hw);
73	if (IS_ERR(clk))
74		kfree(cpumux);
75
76	return clk;
77}
78
79int mtk_clk_register_cpumuxes(struct device_node *node,
80			      const struct mtk_composite *clks, int num,
81			      struct clk_onecell_data *clk_data)
82{
83	int i;
84	struct clk *clk;
85	struct regmap *regmap;
86
87	regmap = syscon_node_to_regmap(node);
88	if (IS_ERR(regmap)) {
89		pr_err("Cannot find regmap for %pOF: %ld\n", node,
90		       PTR_ERR(regmap));
91		return PTR_ERR(regmap);
92	}
93
94	for (i = 0; i < num; i++) {
95		const struct mtk_composite *mux = &clks[i];
96
97		clk = mtk_clk_register_cpumux(mux, regmap);
98		if (IS_ERR(clk)) {
99			pr_err("Failed to register clk %s: %ld\n",
100			       mux->name, PTR_ERR(clk));
101			continue;
102		}
103
104		clk_data->clks[mux->id] = clk;
105	}
106
107	return 0;
108}
109