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