1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2016 Free Electrons
4 * Copyright (C) 2016 NextThing Co
9 #include <linux/clk-provider.h>
10 #include <linux/regmap.h>
12 #include "sun4i_hdmi.h"
16 struct sun4i_hdmi *hdmi;
17 struct regmap_field *reg;
22 static inline struct sun4i_ddc *hw_to_ddc(struct clk_hw *hw)
24 return container_of(hw, struct sun4i_ddc, hw);
27 static unsigned long sun4i_ddc_calc_divider(unsigned long rate,
28 unsigned long parent_rate,
33 unsigned long best_rate = 0;
34 u8 best_m = 0, best_n = 0, _m, _n;
36 for (_m = 0; _m < 16; _m++) {
37 for (_n = 0; _n < 8; _n++) {
38 unsigned long tmp_rate;
40 tmp_rate = (((parent_rate / pre_div) / 10) >> _n) /
46 if (abs(rate - tmp_rate) < abs(rate - best_rate)) {
62 static long sun4i_ddc_round_rate(struct clk_hw *hw, unsigned long rate,
65 struct sun4i_ddc *ddc = hw_to_ddc(hw);
67 return sun4i_ddc_calc_divider(rate, *prate, ddc->pre_div,
68 ddc->m_offset, NULL, NULL);
71 static unsigned long sun4i_ddc_recalc_rate(struct clk_hw *hw,
72 unsigned long parent_rate)
74 struct sun4i_ddc *ddc = hw_to_ddc(hw);
78 regmap_field_read(ddc->reg, ®);
82 return (((parent_rate / ddc->pre_div) / 10) >> n) /
86 static int sun4i_ddc_set_rate(struct clk_hw *hw, unsigned long rate,
87 unsigned long parent_rate)
89 struct sun4i_ddc *ddc = hw_to_ddc(hw);
92 sun4i_ddc_calc_divider(rate, parent_rate, ddc->pre_div,
93 ddc->m_offset, &div_m, &div_n);
95 regmap_field_write(ddc->reg,
96 SUN4I_HDMI_DDC_CLK_M(div_m) |
97 SUN4I_HDMI_DDC_CLK_N(div_n));
102 static const struct clk_ops sun4i_ddc_ops = {
103 .recalc_rate = sun4i_ddc_recalc_rate,
104 .round_rate = sun4i_ddc_round_rate,
105 .set_rate = sun4i_ddc_set_rate,
108 int sun4i_ddc_create(struct sun4i_hdmi *hdmi, struct clk *parent)
110 struct clk_init_data init;
111 struct sun4i_ddc *ddc;
112 const char *parent_name;
114 parent_name = __clk_get_name(parent);
118 ddc = devm_kzalloc(hdmi->dev, sizeof(*ddc), GFP_KERNEL);
122 ddc->reg = devm_regmap_field_alloc(hdmi->dev, hdmi->regmap,
123 hdmi->variant->ddc_clk_reg);
124 if (IS_ERR(ddc->reg))
125 return PTR_ERR(ddc->reg);
127 init.name = "hdmi-ddc";
128 init.ops = &sun4i_ddc_ops;
129 init.parent_names = &parent_name;
130 init.num_parents = 1;
133 ddc->hw.init = &init;
134 ddc->pre_div = hdmi->variant->ddc_clk_pre_divider;
135 ddc->m_offset = hdmi->variant->ddc_clk_m_offset;
137 hdmi->ddc_clk = devm_clk_register(hdmi->dev, &ddc->hw);
138 if (IS_ERR(hdmi->ddc_clk))
139 return PTR_ERR(hdmi->ddc_clk);