2 * Copyright (C) 2016 Free Electrons
3 * Copyright (C) 2016 NextThing Co
5 * Maxime Ripard <maxime.ripard@free-electrons.com>
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation; either version 2 of
10 * the License, or (at your option) any later version.
13 #include <linux/clk-provider.h>
14 #include <linux/regmap.h>
16 #include "sun4i_hdmi.h"
20 struct sun4i_hdmi
*hdmi
;
21 struct regmap_field
*reg
;
26 static inline struct sun4i_ddc
*hw_to_ddc(struct clk_hw
*hw
)
28 return container_of(hw
, struct sun4i_ddc
, hw
);
31 static unsigned long sun4i_ddc_calc_divider(unsigned long rate
,
32 unsigned long parent_rate
,
37 unsigned long best_rate
= 0;
38 u8 best_m
= 0, best_n
= 0, _m
, _n
;
40 for (_m
= 0; _m
< 8; _m
++) {
41 for (_n
= 0; _n
< 8; _n
++) {
42 unsigned long tmp_rate
;
44 tmp_rate
= (((parent_rate
/ pre_div
) / 10) >> _n
) /
50 if (abs(rate
- tmp_rate
) < abs(rate
- best_rate
)) {
66 static long sun4i_ddc_round_rate(struct clk_hw
*hw
, unsigned long rate
,
69 struct sun4i_ddc
*ddc
= hw_to_ddc(hw
);
71 return sun4i_ddc_calc_divider(rate
, *prate
, ddc
->pre_div
,
72 ddc
->m_offset
, NULL
, NULL
);
75 static unsigned long sun4i_ddc_recalc_rate(struct clk_hw
*hw
,
76 unsigned long parent_rate
)
78 struct sun4i_ddc
*ddc
= hw_to_ddc(hw
);
82 regmap_field_read(ddc
->reg
, ®
);
86 return (((parent_rate
/ ddc
->pre_div
) / 10) >> n
) /
90 static int sun4i_ddc_set_rate(struct clk_hw
*hw
, unsigned long rate
,
91 unsigned long parent_rate
)
93 struct sun4i_ddc
*ddc
= hw_to_ddc(hw
);
96 sun4i_ddc_calc_divider(rate
, parent_rate
, ddc
->pre_div
,
97 ddc
->m_offset
, &div_m
, &div_n
);
99 regmap_field_write(ddc
->reg
,
100 SUN4I_HDMI_DDC_CLK_M(div_m
) |
101 SUN4I_HDMI_DDC_CLK_N(div_n
));
106 static const struct clk_ops sun4i_ddc_ops
= {
107 .recalc_rate
= sun4i_ddc_recalc_rate
,
108 .round_rate
= sun4i_ddc_round_rate
,
109 .set_rate
= sun4i_ddc_set_rate
,
112 int sun4i_ddc_create(struct sun4i_hdmi
*hdmi
, struct clk
*parent
)
114 struct clk_init_data init
;
115 struct sun4i_ddc
*ddc
;
116 const char *parent_name
;
118 parent_name
= __clk_get_name(parent
);
122 ddc
= devm_kzalloc(hdmi
->dev
, sizeof(*ddc
), GFP_KERNEL
);
126 ddc
->reg
= devm_regmap_field_alloc(hdmi
->dev
, hdmi
->regmap
,
127 hdmi
->variant
->ddc_clk_reg
);
128 if (IS_ERR(ddc
->reg
))
129 return PTR_ERR(ddc
->reg
);
131 init
.name
= "hdmi-ddc";
132 init
.ops
= &sun4i_ddc_ops
;
133 init
.parent_names
= &parent_name
;
134 init
.num_parents
= 1;
137 ddc
->hw
.init
= &init
;
138 ddc
->pre_div
= hdmi
->variant
->ddc_clk_pre_divider
;
139 ddc
->m_offset
= hdmi
->variant
->ddc_clk_m_offset
;
141 hdmi
->ddc_clk
= devm_clk_register(hdmi
->dev
, &ddc
->hw
);
142 if (IS_ERR(hdmi
->ddc_clk
))
143 return PTR_ERR(hdmi
->ddc_clk
);