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>
15 #include "sun4i_tcon.h"
16 #include "sun4i_hdmi.h"
20 struct sun4i_hdmi
*hdmi
;
23 static inline struct sun4i_ddc
*hw_to_ddc(struct clk_hw
*hw
)
25 return container_of(hw
, struct sun4i_ddc
, hw
);
28 static unsigned long sun4i_ddc_calc_divider(unsigned long rate
,
29 unsigned long parent_rate
,
32 unsigned long best_rate
= 0;
33 u8 best_m
= 0, best_n
= 0, _m
, _n
;
35 for (_m
= 0; _m
< 8; _m
++) {
36 for (_n
= 0; _n
< 8; _n
++) {
37 unsigned long tmp_rate
;
39 tmp_rate
= (((parent_rate
/ 2) / 10) >> _n
) / (_m
+ 1);
44 if (abs(rate
- tmp_rate
) < abs(rate
- best_rate
)) {
60 static long sun4i_ddc_round_rate(struct clk_hw
*hw
, unsigned long rate
,
63 return sun4i_ddc_calc_divider(rate
, *prate
, NULL
, NULL
);
66 static unsigned long sun4i_ddc_recalc_rate(struct clk_hw
*hw
,
67 unsigned long parent_rate
)
69 struct sun4i_ddc
*ddc
= hw_to_ddc(hw
);
73 reg
= readl(ddc
->hdmi
->base
+ SUN4I_HDMI_DDC_CLK_REG
);
77 return (((parent_rate
/ 2) / 10) >> n
) / (m
+ 1);
80 static int sun4i_ddc_set_rate(struct clk_hw
*hw
, unsigned long rate
,
81 unsigned long parent_rate
)
83 struct sun4i_ddc
*ddc
= hw_to_ddc(hw
);
86 sun4i_ddc_calc_divider(rate
, parent_rate
, &div_m
, &div_n
);
88 writel(SUN4I_HDMI_DDC_CLK_M(div_m
) | SUN4I_HDMI_DDC_CLK_N(div_n
),
89 ddc
->hdmi
->base
+ SUN4I_HDMI_DDC_CLK_REG
);
94 static const struct clk_ops sun4i_ddc_ops
= {
95 .recalc_rate
= sun4i_ddc_recalc_rate
,
96 .round_rate
= sun4i_ddc_round_rate
,
97 .set_rate
= sun4i_ddc_set_rate
,
100 int sun4i_ddc_create(struct sun4i_hdmi
*hdmi
, struct clk
*parent
)
102 struct clk_init_data init
;
103 struct sun4i_ddc
*ddc
;
104 const char *parent_name
;
106 parent_name
= __clk_get_name(parent
);
110 ddc
= devm_kzalloc(hdmi
->dev
, sizeof(*ddc
), GFP_KERNEL
);
114 init
.name
= "hdmi-ddc";
115 init
.ops
= &sun4i_ddc_ops
;
116 init
.parent_names
= &parent_name
;
117 init
.num_parents
= 1;
120 ddc
->hw
.init
= &init
;
122 hdmi
->ddc_clk
= devm_clk_register(hdmi
->dev
, &ddc
->hw
);
123 if (IS_ERR(hdmi
->ddc_clk
))
124 return PTR_ERR(hdmi
->ddc_clk
);