GNU Linux-libre 6.1.86-gnu
[releases.git] / drivers / media / i2c / ov5640.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2011-2013 Freescale Semiconductor, Inc. All Rights Reserved.
4  * Copyright (C) 2014-2017 Mentor Graphics Inc.
5  */
6
7 #include <linux/clk.h>
8 #include <linux/clk-provider.h>
9 #include <linux/clkdev.h>
10 #include <linux/ctype.h>
11 #include <linux/delay.h>
12 #include <linux/device.h>
13 #include <linux/gpio/consumer.h>
14 #include <linux/i2c.h>
15 #include <linux/init.h>
16 #include <linux/module.h>
17 #include <linux/of_device.h>
18 #include <linux/pm_runtime.h>
19 #include <linux/regulator/consumer.h>
20 #include <linux/slab.h>
21 #include <linux/types.h>
22 #include <media/v4l2-async.h>
23 #include <media/v4l2-ctrls.h>
24 #include <media/v4l2-device.h>
25 #include <media/v4l2-event.h>
26 #include <media/v4l2-fwnode.h>
27 #include <media/v4l2-subdev.h>
28
29 /* min/typical/max system clock (xclk) frequencies */
30 #define OV5640_XCLK_MIN  6000000
31 #define OV5640_XCLK_MAX 54000000
32
33 #define OV5640_NATIVE_WIDTH             2624
34 #define OV5640_NATIVE_HEIGHT            1964
35 #define OV5640_PIXEL_ARRAY_TOP          14
36 #define OV5640_PIXEL_ARRAY_LEFT         16
37 #define OV5640_PIXEL_ARRAY_WIDTH        2592
38 #define OV5640_PIXEL_ARRAY_HEIGHT       1944
39
40 /* FIXME: not documented. */
41 #define OV5640_MIN_VBLANK       24
42 #define OV5640_MAX_VTS          3375
43
44 #define OV5640_DEFAULT_SLAVE_ID 0x3c
45
46 #define OV5640_LINK_RATE_MAX            490000000U
47
48 #define OV5640_REG_SYS_RESET02          0x3002
49 #define OV5640_REG_SYS_CLOCK_ENABLE02   0x3006
50 #define OV5640_REG_SYS_CTRL0            0x3008
51 #define OV5640_REG_SYS_CTRL0_SW_PWDN    0x42
52 #define OV5640_REG_SYS_CTRL0_SW_PWUP    0x02
53 #define OV5640_REG_SYS_CTRL0_SW_RST     0x82
54 #define OV5640_REG_CHIP_ID              0x300a
55 #define OV5640_REG_IO_MIPI_CTRL00       0x300e
56 #define OV5640_REG_PAD_OUTPUT_ENABLE01  0x3017
57 #define OV5640_REG_PAD_OUTPUT_ENABLE02  0x3018
58 #define OV5640_REG_PAD_OUTPUT00         0x3019
59 #define OV5640_REG_SYSTEM_CONTROL1      0x302e
60 #define OV5640_REG_SC_PLL_CTRL0         0x3034
61 #define OV5640_REG_SC_PLL_CTRL1         0x3035
62 #define OV5640_REG_SC_PLL_CTRL2         0x3036
63 #define OV5640_REG_SC_PLL_CTRL3         0x3037
64 #define OV5640_REG_SLAVE_ID             0x3100
65 #define OV5640_REG_SCCB_SYS_CTRL1       0x3103
66 #define OV5640_REG_SYS_ROOT_DIVIDER     0x3108
67 #define OV5640_REG_AWB_R_GAIN           0x3400
68 #define OV5640_REG_AWB_G_GAIN           0x3402
69 #define OV5640_REG_AWB_B_GAIN           0x3404
70 #define OV5640_REG_AWB_MANUAL_CTRL      0x3406
71 #define OV5640_REG_AEC_PK_EXPOSURE_HI   0x3500
72 #define OV5640_REG_AEC_PK_EXPOSURE_MED  0x3501
73 #define OV5640_REG_AEC_PK_EXPOSURE_LO   0x3502
74 #define OV5640_REG_AEC_PK_MANUAL        0x3503
75 #define OV5640_REG_AEC_PK_REAL_GAIN     0x350a
76 #define OV5640_REG_AEC_PK_VTS           0x350c
77 #define OV5640_REG_TIMING_HS            0x3800
78 #define OV5640_REG_TIMING_VS            0x3802
79 #define OV5640_REG_TIMING_HW            0x3804
80 #define OV5640_REG_TIMING_VH            0x3806
81 #define OV5640_REG_TIMING_DVPHO         0x3808
82 #define OV5640_REG_TIMING_DVPVO         0x380a
83 #define OV5640_REG_TIMING_HTS           0x380c
84 #define OV5640_REG_TIMING_VTS           0x380e
85 #define OV5640_REG_TIMING_HOFFS         0x3810
86 #define OV5640_REG_TIMING_VOFFS         0x3812
87 #define OV5640_REG_TIMING_TC_REG20      0x3820
88 #define OV5640_REG_TIMING_TC_REG21      0x3821
89 #define OV5640_REG_AEC_CTRL00           0x3a00
90 #define OV5640_REG_AEC_B50_STEP         0x3a08
91 #define OV5640_REG_AEC_B60_STEP         0x3a0a
92 #define OV5640_REG_AEC_CTRL0D           0x3a0d
93 #define OV5640_REG_AEC_CTRL0E           0x3a0e
94 #define OV5640_REG_AEC_CTRL0F           0x3a0f
95 #define OV5640_REG_AEC_CTRL10           0x3a10
96 #define OV5640_REG_AEC_CTRL11           0x3a11
97 #define OV5640_REG_AEC_CTRL1B           0x3a1b
98 #define OV5640_REG_AEC_CTRL1E           0x3a1e
99 #define OV5640_REG_AEC_CTRL1F           0x3a1f
100 #define OV5640_REG_HZ5060_CTRL00        0x3c00
101 #define OV5640_REG_HZ5060_CTRL01        0x3c01
102 #define OV5640_REG_SIGMADELTA_CTRL0C    0x3c0c
103 #define OV5640_REG_FRAME_CTRL01         0x4202
104 #define OV5640_REG_FORMAT_CONTROL00     0x4300
105 #define OV5640_REG_VFIFO_HSIZE          0x4602
106 #define OV5640_REG_VFIFO_VSIZE          0x4604
107 #define OV5640_REG_JPG_MODE_SELECT      0x4713
108 #define OV5640_REG_CCIR656_CTRL00       0x4730
109 #define OV5640_REG_POLARITY_CTRL00      0x4740
110 #define OV5640_REG_MIPI_CTRL00          0x4800
111 #define OV5640_REG_DEBUG_MODE           0x4814
112 #define OV5640_REG_PCLK_PERIOD          0x4837
113 #define OV5640_REG_ISP_FORMAT_MUX_CTRL  0x501f
114 #define OV5640_REG_PRE_ISP_TEST_SET1    0x503d
115 #define OV5640_REG_SDE_CTRL0            0x5580
116 #define OV5640_REG_SDE_CTRL1            0x5581
117 #define OV5640_REG_SDE_CTRL3            0x5583
118 #define OV5640_REG_SDE_CTRL4            0x5584
119 #define OV5640_REG_SDE_CTRL5            0x5585
120 #define OV5640_REG_AVG_READOUT          0x56a1
121
122 enum ov5640_mode_id {
123         OV5640_MODE_QQVGA_160_120 = 0,
124         OV5640_MODE_QCIF_176_144,
125         OV5640_MODE_QVGA_320_240,
126         OV5640_MODE_VGA_640_480,
127         OV5640_MODE_NTSC_720_480,
128         OV5640_MODE_PAL_720_576,
129         OV5640_MODE_XGA_1024_768,
130         OV5640_MODE_720P_1280_720,
131         OV5640_MODE_1080P_1920_1080,
132         OV5640_MODE_QSXGA_2592_1944,
133         OV5640_NUM_MODES,
134 };
135
136 enum ov5640_frame_rate {
137         OV5640_15_FPS = 0,
138         OV5640_30_FPS,
139         OV5640_60_FPS,
140         OV5640_NUM_FRAMERATES,
141 };
142
143 enum ov5640_pixel_rate_id {
144         OV5640_PIXEL_RATE_168M,
145         OV5640_PIXEL_RATE_148M,
146         OV5640_PIXEL_RATE_124M,
147         OV5640_PIXEL_RATE_96M,
148         OV5640_PIXEL_RATE_48M,
149         OV5640_NUM_PIXEL_RATES,
150 };
151
152 /*
153  * The chip manual suggests 24/48/96/192 MHz pixel clocks.
154  *
155  * 192MHz exceeds the sysclk limits; use 168MHz as maximum pixel rate for
156  * full resolution mode @15 FPS.
157  */
158 static const u32 ov5640_pixel_rates[] = {
159         [OV5640_PIXEL_RATE_168M] = 168000000,
160         [OV5640_PIXEL_RATE_148M] = 148000000,
161         [OV5640_PIXEL_RATE_124M] = 124000000,
162         [OV5640_PIXEL_RATE_96M] = 96000000,
163         [OV5640_PIXEL_RATE_48M] = 48000000,
164 };
165
166 /*
167  * MIPI CSI-2 link frequencies.
168  *
169  * Derived from the above defined pixel rate for bpp = (8, 16, 24) and
170  * data_lanes = (1, 2)
171  *
172  * link_freq = (pixel_rate * bpp) / (2 * data_lanes)
173  */
174 static const s64 ov5640_csi2_link_freqs[] = {
175         992000000, 888000000, 768000000, 744000000, 672000000, 672000000,
176         592000000, 592000000, 576000000, 576000000, 496000000, 496000000,
177         384000000, 384000000, 384000000, 336000000, 296000000, 288000000,
178         248000000, 192000000, 192000000, 192000000, 96000000,
179 };
180
181 /* Link freq for default mode: UYVY 16 bpp, 2 data lanes. */
182 #define OV5640_DEFAULT_LINK_FREQ        13
183
184 enum ov5640_format_mux {
185         OV5640_FMT_MUX_YUV422 = 0,
186         OV5640_FMT_MUX_RGB,
187         OV5640_FMT_MUX_DITHER,
188         OV5640_FMT_MUX_RAW_DPC,
189         OV5640_FMT_MUX_SNR_RAW,
190         OV5640_FMT_MUX_RAW_CIP,
191 };
192
193 struct ov5640_pixfmt {
194         u32 code;
195         u32 colorspace;
196         u8 bpp;
197         u8 ctrl00;
198         enum ov5640_format_mux mux;
199 };
200
201 static const struct ov5640_pixfmt ov5640_dvp_formats[] = {
202         {
203                 /* YUV422, YUYV */
204                 .code           = MEDIA_BUS_FMT_JPEG_1X8,
205                 .colorspace     = V4L2_COLORSPACE_JPEG,
206                 .bpp            = 16,
207                 .ctrl00         = 0x30,
208                 .mux            = OV5640_FMT_MUX_YUV422,
209         }, {
210                 /* YUV422, UYVY */
211                 .code           = MEDIA_BUS_FMT_UYVY8_2X8,
212                 .colorspace     = V4L2_COLORSPACE_SRGB,
213                 .bpp            = 16,
214                 .ctrl00         = 0x3f,
215                 .mux            = OV5640_FMT_MUX_YUV422,
216         }, {
217                 /* YUV422, YUYV */
218                 .code           = MEDIA_BUS_FMT_YUYV8_2X8,
219                 .colorspace     = V4L2_COLORSPACE_SRGB,
220                 .bpp            = 16,
221                 .ctrl00         = 0x30,
222                 .mux            = OV5640_FMT_MUX_YUV422,
223         }, {
224                 /* RGB565 {g[2:0],b[4:0]},{r[4:0],g[5:3]} */
225                 .code           = MEDIA_BUS_FMT_RGB565_2X8_LE,
226                 .colorspace     = V4L2_COLORSPACE_SRGB,
227                 .bpp            = 16,
228                 .ctrl00         = 0x6f,
229                 .mux            = OV5640_FMT_MUX_RGB,
230         }, {
231                 /* RGB565 {r[4:0],g[5:3]},{g[2:0],b[4:0]} */
232                 .code           = MEDIA_BUS_FMT_RGB565_2X8_BE,
233                 .colorspace     = V4L2_COLORSPACE_SRGB,
234                 .bpp            = 16,
235                 .ctrl00         = 0x61,
236                 .mux            = OV5640_FMT_MUX_RGB,
237         }, {
238                 /* Raw, BGBG... / GRGR... */
239                 .code           = MEDIA_BUS_FMT_SBGGR8_1X8,
240                 .colorspace     = V4L2_COLORSPACE_SRGB,
241                 .bpp            = 8,
242                 .ctrl00         = 0x00,
243                 .mux            = OV5640_FMT_MUX_RAW_DPC,
244         }, {
245                 /* Raw bayer, GBGB... / RGRG... */
246                 .code           = MEDIA_BUS_FMT_SGBRG8_1X8,
247                 .colorspace     = V4L2_COLORSPACE_SRGB,
248                 .bpp            = 8,
249                 .ctrl00         = 0x01,
250                 .mux            = OV5640_FMT_MUX_RAW_DPC,
251         }, {
252                 /* Raw bayer, GRGR... / BGBG... */
253                 .code           = MEDIA_BUS_FMT_SGRBG8_1X8,
254                 .colorspace     = V4L2_COLORSPACE_SRGB,
255                 .bpp            = 8,
256                 .ctrl00         = 0x02,
257                 .mux            = OV5640_FMT_MUX_RAW_DPC,
258         }, {
259                 /* Raw bayer, RGRG... / GBGB... */
260                 .code           = MEDIA_BUS_FMT_SRGGB8_1X8,
261                 .colorspace     = V4L2_COLORSPACE_SRGB,
262                 .bpp            = 8,
263                 .ctrl00         = 0x03,
264                 .mux            = OV5640_FMT_MUX_RAW_DPC,
265         },
266         { /* sentinel */ }
267 };
268
269 static const struct ov5640_pixfmt ov5640_csi2_formats[] = {
270         {
271                 /* YUV422, YUYV */
272                 .code           = MEDIA_BUS_FMT_JPEG_1X8,
273                 .colorspace     = V4L2_COLORSPACE_JPEG,
274                 .bpp            = 16,
275                 .ctrl00         = 0x30,
276                 .mux            = OV5640_FMT_MUX_YUV422,
277         }, {
278                 /* YUV422, UYVY */
279                 .code           = MEDIA_BUS_FMT_UYVY8_1X16,
280                 .colorspace     = V4L2_COLORSPACE_SRGB,
281                 .bpp            = 16,
282                 .ctrl00         = 0x3f,
283                 .mux            = OV5640_FMT_MUX_YUV422,
284         }, {
285                 /* YUV422, YUYV */
286                 .code           = MEDIA_BUS_FMT_YUYV8_1X16,
287                 .colorspace     = V4L2_COLORSPACE_SRGB,
288                 .bpp            = 16,
289                 .ctrl00         = 0x30,
290                 .mux            = OV5640_FMT_MUX_YUV422,
291         }, {
292                 /* RGB565 {g[2:0],b[4:0]},{r[4:0],g[5:3]} */
293                 .code           = MEDIA_BUS_FMT_RGB565_1X16,
294                 .colorspace     = V4L2_COLORSPACE_SRGB,
295                 .bpp            = 16,
296                 .ctrl00         = 0x6f,
297                 .mux            = OV5640_FMT_MUX_RGB,
298         }, {
299                 /* BGR888: RGB */
300                 .code           = MEDIA_BUS_FMT_BGR888_1X24,
301                 .colorspace     = V4L2_COLORSPACE_SRGB,
302                 .bpp            = 24,
303                 .ctrl00         = 0x23,
304                 .mux            = OV5640_FMT_MUX_RGB,
305         }, {
306                 /* Raw, BGBG... / GRGR... */
307                 .code           = MEDIA_BUS_FMT_SBGGR8_1X8,
308                 .colorspace     = V4L2_COLORSPACE_SRGB,
309                 .bpp            = 8,
310                 .ctrl00         = 0x00,
311                 .mux            = OV5640_FMT_MUX_RAW_DPC,
312         }, {
313                 /* Raw bayer, GBGB... / RGRG... */
314                 .code           = MEDIA_BUS_FMT_SGBRG8_1X8,
315                 .colorspace     = V4L2_COLORSPACE_SRGB,
316                 .bpp            = 8,
317                 .ctrl00         = 0x01,
318                 .mux            = OV5640_FMT_MUX_RAW_DPC,
319         }, {
320                 /* Raw bayer, GRGR... / BGBG... */
321                 .code           = MEDIA_BUS_FMT_SGRBG8_1X8,
322                 .colorspace     = V4L2_COLORSPACE_SRGB,
323                 .bpp            = 8,
324                 .ctrl00         = 0x02,
325                 .mux            = OV5640_FMT_MUX_RAW_DPC,
326         }, {
327                 /* Raw bayer, RGRG... / GBGB... */
328                 .code           = MEDIA_BUS_FMT_SRGGB8_1X8,
329                 .colorspace     = V4L2_COLORSPACE_SRGB,
330                 .bpp            = 8,
331                 .ctrl00         = 0x03,
332                 .mux            = OV5640_FMT_MUX_RAW_DPC,
333         },
334         { /* sentinel */ }
335 };
336
337 /*
338  * FIXME: remove this when a subdev API becomes available
339  * to set the MIPI CSI-2 virtual channel.
340  */
341 static unsigned int virtual_channel;
342 module_param(virtual_channel, uint, 0444);
343 MODULE_PARM_DESC(virtual_channel,
344                  "MIPI CSI-2 virtual channel (0..3), default 0");
345
346 static const int ov5640_framerates[] = {
347         [OV5640_15_FPS] = 15,
348         [OV5640_30_FPS] = 30,
349         [OV5640_60_FPS] = 60,
350 };
351
352 /* regulator supplies */
353 static const char * const ov5640_supply_name[] = {
354         "DOVDD", /* Digital I/O (1.8V) supply */
355         "AVDD",  /* Analog (2.8V) supply */
356         "DVDD",  /* Digital Core (1.5V) supply */
357 };
358
359 #define OV5640_NUM_SUPPLIES ARRAY_SIZE(ov5640_supply_name)
360
361 /*
362  * Image size under 1280 * 960 are SUBSAMPLING
363  * Image size upper 1280 * 960 are SCALING
364  */
365 enum ov5640_downsize_mode {
366         SUBSAMPLING,
367         SCALING,
368 };
369
370 struct reg_value {
371         u16 reg_addr;
372         u8 val;
373         u8 mask;
374         u32 delay_ms;
375 };
376
377 struct ov5640_timings {
378         /* Analog crop rectangle. */
379         struct v4l2_rect analog_crop;
380         /* Visibile crop: from analog crop top-left corner. */
381         struct v4l2_rect crop;
382         /* Total pixels per line: width + fixed hblank. */
383         u32 htot;
384         /* Default vertical blanking: frame height = height + vblank. */
385         u32 vblank_def;
386 };
387
388 struct ov5640_mode_info {
389         enum ov5640_mode_id id;
390         enum ov5640_downsize_mode dn_mode;
391         enum ov5640_pixel_rate_id pixel_rate;
392
393         unsigned int width;
394         unsigned int height;
395
396         struct ov5640_timings dvp_timings;
397         struct ov5640_timings csi2_timings;
398
399         const struct reg_value *reg_data;
400         u32 reg_data_size;
401
402         /* Used by s_frame_interval only. */
403         u32 max_fps;
404         u32 def_fps;
405 };
406
407 struct ov5640_ctrls {
408         struct v4l2_ctrl_handler handler;
409         struct v4l2_ctrl *pixel_rate;
410         struct v4l2_ctrl *link_freq;
411         struct v4l2_ctrl *hblank;
412         struct v4l2_ctrl *vblank;
413         struct {
414                 struct v4l2_ctrl *auto_exp;
415                 struct v4l2_ctrl *exposure;
416         };
417         struct {
418                 struct v4l2_ctrl *auto_wb;
419                 struct v4l2_ctrl *blue_balance;
420                 struct v4l2_ctrl *red_balance;
421         };
422         struct {
423                 struct v4l2_ctrl *auto_gain;
424                 struct v4l2_ctrl *gain;
425         };
426         struct v4l2_ctrl *brightness;
427         struct v4l2_ctrl *light_freq;
428         struct v4l2_ctrl *saturation;
429         struct v4l2_ctrl *contrast;
430         struct v4l2_ctrl *hue;
431         struct v4l2_ctrl *test_pattern;
432         struct v4l2_ctrl *hflip;
433         struct v4l2_ctrl *vflip;
434 };
435
436 struct ov5640_dev {
437         struct i2c_client *i2c_client;
438         struct v4l2_subdev sd;
439         struct media_pad pad;
440         struct v4l2_fwnode_endpoint ep; /* the parsed DT endpoint info */
441         struct clk *xclk; /* system clock to OV5640 */
442         u32 xclk_freq;
443
444         struct regulator_bulk_data supplies[OV5640_NUM_SUPPLIES];
445         struct gpio_desc *reset_gpio;
446         struct gpio_desc *pwdn_gpio;
447         bool   upside_down;
448
449         /* lock to protect all members below */
450         struct mutex lock;
451
452         struct v4l2_mbus_framefmt fmt;
453         bool pending_fmt_change;
454
455         const struct ov5640_mode_info *current_mode;
456         const struct ov5640_mode_info *last_mode;
457         enum ov5640_frame_rate current_fr;
458         struct v4l2_fract frame_interval;
459         s64 current_link_freq;
460
461         struct ov5640_ctrls ctrls;
462
463         u32 prev_sysclk, prev_hts;
464         u32 ae_low, ae_high, ae_target;
465
466         bool pending_mode_change;
467         bool streaming;
468 };
469
470 static inline struct ov5640_dev *to_ov5640_dev(struct v4l2_subdev *sd)
471 {
472         return container_of(sd, struct ov5640_dev, sd);
473 }
474
475 static inline struct v4l2_subdev *ctrl_to_sd(struct v4l2_ctrl *ctrl)
476 {
477         return &container_of(ctrl->handler, struct ov5640_dev,
478                              ctrls.handler)->sd;
479 }
480
481 static inline bool ov5640_is_csi2(const struct ov5640_dev *sensor)
482 {
483         return sensor->ep.bus_type == V4L2_MBUS_CSI2_DPHY;
484 }
485
486 static inline const struct ov5640_pixfmt *
487 ov5640_formats(struct ov5640_dev *sensor)
488 {
489         return ov5640_is_csi2(sensor) ? ov5640_csi2_formats
490                                       : ov5640_dvp_formats;
491 }
492
493 static const struct ov5640_pixfmt *
494 ov5640_code_to_pixfmt(struct ov5640_dev *sensor, u32 code)
495 {
496         const struct ov5640_pixfmt *formats = ov5640_formats(sensor);
497         unsigned int i;
498
499         for (i = 0; formats[i].code; ++i) {
500                 if (formats[i].code == code)
501                         return &formats[i];
502         }
503
504         return &formats[0];
505 }
506
507 static u32 ov5640_code_to_bpp(struct ov5640_dev *sensor, u32 code)
508 {
509         const struct ov5640_pixfmt *format = ov5640_code_to_pixfmt(sensor,
510                                                                    code);
511
512         return format->bpp;
513 }
514
515 /*
516  * FIXME: all of these register tables are likely filled with
517  * entries that set the register to their power-on default values,
518  * and which are otherwise not touched by this driver. Those entries
519  * should be identified and removed to speed register load time
520  * over i2c.
521  */
522 /* YUV422 UYVY VGA@30fps */
523
524 static const struct v4l2_mbus_framefmt ov5640_default_fmt = {
525         .code = MEDIA_BUS_FMT_UYVY8_2X8,
526         .width = 640,
527         .height = 480,
528         .colorspace = V4L2_COLORSPACE_SRGB,
529         .ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(V4L2_COLORSPACE_SRGB),
530         .quantization = V4L2_QUANTIZATION_FULL_RANGE,
531         .xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(V4L2_COLORSPACE_SRGB),
532         .field = V4L2_FIELD_NONE,
533 };
534
535 static const struct reg_value ov5640_init_setting[] = {
536         {0x3103, 0x11, 0, 0},
537         {0x3103, 0x03, 0, 0}, {0x3630, 0x36, 0, 0},
538         {0x3631, 0x0e, 0, 0}, {0x3632, 0xe2, 0, 0}, {0x3633, 0x12, 0, 0},
539         {0x3621, 0xe0, 0, 0}, {0x3704, 0xa0, 0, 0}, {0x3703, 0x5a, 0, 0},
540         {0x3715, 0x78, 0, 0}, {0x3717, 0x01, 0, 0}, {0x370b, 0x60, 0, 0},
541         {0x3705, 0x1a, 0, 0}, {0x3905, 0x02, 0, 0}, {0x3906, 0x10, 0, 0},
542         {0x3901, 0x0a, 0, 0}, {0x3731, 0x12, 0, 0}, {0x3600, 0x08, 0, 0},
543         {0x3601, 0x33, 0, 0}, {0x302d, 0x60, 0, 0}, {0x3620, 0x52, 0, 0},
544         {0x371b, 0x20, 0, 0}, {0x471c, 0x50, 0, 0}, {0x3a13, 0x43, 0, 0},
545         {0x3a18, 0x00, 0, 0}, {0x3a19, 0xf8, 0, 0}, {0x3635, 0x13, 0, 0},
546         {0x3636, 0x03, 0, 0}, {0x3634, 0x40, 0, 0}, {0x3622, 0x01, 0, 0},
547         {0x3c01, 0xa4, 0, 0}, {0x3c04, 0x28, 0, 0}, {0x3c05, 0x98, 0, 0},
548         {0x3c06, 0x00, 0, 0}, {0x3c07, 0x08, 0, 0}, {0x3c08, 0x00, 0, 0},
549         {0x3c09, 0x1c, 0, 0}, {0x3c0a, 0x9c, 0, 0}, {0x3c0b, 0x40, 0, 0},
550         {0x3820, 0x41, 0, 0}, {0x3821, 0x07, 0, 0}, {0x3814, 0x31, 0, 0},
551         {0x3815, 0x31, 0, 0},
552         {0x3618, 0x00, 0, 0}, {0x3612, 0x29, 0, 0}, {0x3708, 0x64, 0, 0},
553         {0x3709, 0x52, 0, 0}, {0x370c, 0x03, 0, 0}, {0x3a02, 0x03, 0, 0},
554         {0x3a03, 0xd8, 0, 0}, {0x3a08, 0x01, 0, 0}, {0x3a09, 0x27, 0, 0},
555         {0x3a0a, 0x00, 0, 0}, {0x3a0b, 0xf6, 0, 0}, {0x3a0e, 0x03, 0, 0},
556         {0x3a0d, 0x04, 0, 0}, {0x3a14, 0x03, 0, 0}, {0x3a15, 0xd8, 0, 0},
557         {0x4001, 0x02, 0, 0}, {0x4004, 0x02, 0, 0}, {0x3000, 0x00, 0, 0},
558         {0x3002, 0x1c, 0, 0}, {0x3004, 0xff, 0, 0}, {0x3006, 0xc3, 0, 0},
559         {0x302e, 0x08, 0, 0}, {0x4300, 0x3f, 0, 0},
560         {0x501f, 0x00, 0, 0}, {0x440e, 0x00, 0, 0}, {0x4837, 0x0a, 0, 0},
561         {0x5000, 0xa7, 0, 0}, {0x5001, 0xa3, 0, 0}, {0x5180, 0xff, 0, 0},
562         {0x5181, 0xf2, 0, 0}, {0x5182, 0x00, 0, 0}, {0x5183, 0x14, 0, 0},
563         {0x5184, 0x25, 0, 0}, {0x5185, 0x24, 0, 0}, {0x5186, 0x09, 0, 0},
564         {0x5187, 0x09, 0, 0}, {0x5188, 0x09, 0, 0}, {0x5189, 0x88, 0, 0},
565         {0x518a, 0x54, 0, 0}, {0x518b, 0xee, 0, 0}, {0x518c, 0xb2, 0, 0},
566         {0x518d, 0x50, 0, 0}, {0x518e, 0x34, 0, 0}, {0x518f, 0x6b, 0, 0},
567         {0x5190, 0x46, 0, 0}, {0x5191, 0xf8, 0, 0}, {0x5192, 0x04, 0, 0},
568         {0x5193, 0x70, 0, 0}, {0x5194, 0xf0, 0, 0}, {0x5195, 0xf0, 0, 0},
569         {0x5196, 0x03, 0, 0}, {0x5197, 0x01, 0, 0}, {0x5198, 0x04, 0, 0},
570         {0x5199, 0x6c, 0, 0}, {0x519a, 0x04, 0, 0}, {0x519b, 0x00, 0, 0},
571         {0x519c, 0x09, 0, 0}, {0x519d, 0x2b, 0, 0}, {0x519e, 0x38, 0, 0},
572         {0x5381, 0x1e, 0, 0}, {0x5382, 0x5b, 0, 0}, {0x5383, 0x08, 0, 0},
573         {0x5384, 0x0a, 0, 0}, {0x5385, 0x7e, 0, 0}, {0x5386, 0x88, 0, 0},
574         {0x5387, 0x7c, 0, 0}, {0x5388, 0x6c, 0, 0}, {0x5389, 0x10, 0, 0},
575         {0x538a, 0x01, 0, 0}, {0x538b, 0x98, 0, 0}, {0x5300, 0x08, 0, 0},
576         {0x5301, 0x30, 0, 0}, {0x5302, 0x10, 0, 0}, {0x5303, 0x00, 0, 0},
577         {0x5304, 0x08, 0, 0}, {0x5305, 0x30, 0, 0}, {0x5306, 0x08, 0, 0},
578         {0x5307, 0x16, 0, 0}, {0x5309, 0x08, 0, 0}, {0x530a, 0x30, 0, 0},
579         {0x530b, 0x04, 0, 0}, {0x530c, 0x06, 0, 0}, {0x5480, 0x01, 0, 0},
580         {0x5481, 0x08, 0, 0}, {0x5482, 0x14, 0, 0}, {0x5483, 0x28, 0, 0},
581         {0x5484, 0x51, 0, 0}, {0x5485, 0x65, 0, 0}, {0x5486, 0x71, 0, 0},
582         {0x5487, 0x7d, 0, 0}, {0x5488, 0x87, 0, 0}, {0x5489, 0x91, 0, 0},
583         {0x548a, 0x9a, 0, 0}, {0x548b, 0xaa, 0, 0}, {0x548c, 0xb8, 0, 0},
584         {0x548d, 0xcd, 0, 0}, {0x548e, 0xdd, 0, 0}, {0x548f, 0xea, 0, 0},
585         {0x5490, 0x1d, 0, 0}, {0x5580, 0x02, 0, 0}, {0x5583, 0x40, 0, 0},
586         {0x5584, 0x10, 0, 0}, {0x5589, 0x10, 0, 0}, {0x558a, 0x00, 0, 0},
587         {0x558b, 0xf8, 0, 0}, {0x5800, 0x23, 0, 0}, {0x5801, 0x14, 0, 0},
588         {0x5802, 0x0f, 0, 0}, {0x5803, 0x0f, 0, 0}, {0x5804, 0x12, 0, 0},
589         {0x5805, 0x26, 0, 0}, {0x5806, 0x0c, 0, 0}, {0x5807, 0x08, 0, 0},
590         {0x5808, 0x05, 0, 0}, {0x5809, 0x05, 0, 0}, {0x580a, 0x08, 0, 0},
591         {0x580b, 0x0d, 0, 0}, {0x580c, 0x08, 0, 0}, {0x580d, 0x03, 0, 0},
592         {0x580e, 0x00, 0, 0}, {0x580f, 0x00, 0, 0}, {0x5810, 0x03, 0, 0},
593         {0x5811, 0x09, 0, 0}, {0x5812, 0x07, 0, 0}, {0x5813, 0x03, 0, 0},
594         {0x5814, 0x00, 0, 0}, {0x5815, 0x01, 0, 0}, {0x5816, 0x03, 0, 0},
595         {0x5817, 0x08, 0, 0}, {0x5818, 0x0d, 0, 0}, {0x5819, 0x08, 0, 0},
596         {0x581a, 0x05, 0, 0}, {0x581b, 0x06, 0, 0}, {0x581c, 0x08, 0, 0},
597         {0x581d, 0x0e, 0, 0}, {0x581e, 0x29, 0, 0}, {0x581f, 0x17, 0, 0},
598         {0x5820, 0x11, 0, 0}, {0x5821, 0x11, 0, 0}, {0x5822, 0x15, 0, 0},
599         {0x5823, 0x28, 0, 0}, {0x5824, 0x46, 0, 0}, {0x5825, 0x26, 0, 0},
600         {0x5826, 0x08, 0, 0}, {0x5827, 0x26, 0, 0}, {0x5828, 0x64, 0, 0},
601         {0x5829, 0x26, 0, 0}, {0x582a, 0x24, 0, 0}, {0x582b, 0x22, 0, 0},
602         {0x582c, 0x24, 0, 0}, {0x582d, 0x24, 0, 0}, {0x582e, 0x06, 0, 0},
603         {0x582f, 0x22, 0, 0}, {0x5830, 0x40, 0, 0}, {0x5831, 0x42, 0, 0},
604         {0x5832, 0x24, 0, 0}, {0x5833, 0x26, 0, 0}, {0x5834, 0x24, 0, 0},
605         {0x5835, 0x22, 0, 0}, {0x5836, 0x22, 0, 0}, {0x5837, 0x26, 0, 0},
606         {0x5838, 0x44, 0, 0}, {0x5839, 0x24, 0, 0}, {0x583a, 0x26, 0, 0},
607         {0x583b, 0x28, 0, 0}, {0x583c, 0x42, 0, 0}, {0x583d, 0xce, 0, 0},
608         {0x5025, 0x00, 0, 0}, {0x3a0f, 0x30, 0, 0}, {0x3a10, 0x28, 0, 0},
609         {0x3a1b, 0x30, 0, 0}, {0x3a1e, 0x26, 0, 0}, {0x3a11, 0x60, 0, 0},
610         {0x3a1f, 0x14, 0, 0}, {0x3008, 0x02, 0, 0}, {0x3c00, 0x04, 0, 300},
611 };
612
613 static const struct reg_value ov5640_setting_low_res[] = {
614         {0x3c07, 0x08, 0, 0},
615         {0x3c09, 0x1c, 0, 0}, {0x3c0a, 0x9c, 0, 0}, {0x3c0b, 0x40, 0, 0},
616         {0x3814, 0x31, 0, 0},
617         {0x3815, 0x31, 0, 0},
618         {0x3618, 0x00, 0, 0}, {0x3612, 0x29, 0, 0}, {0x3708, 0x64, 0, 0},
619         {0x3709, 0x52, 0, 0}, {0x370c, 0x03, 0, 0}, {0x3a02, 0x03, 0, 0},
620         {0x3a03, 0xd8, 0, 0}, {0x3a08, 0x01, 0, 0}, {0x3a09, 0x27, 0, 0},
621         {0x3a0a, 0x00, 0, 0}, {0x3a0b, 0xf6, 0, 0}, {0x3a0e, 0x03, 0, 0},
622         {0x3a0d, 0x04, 0, 0}, {0x3a14, 0x03, 0, 0}, {0x3a15, 0xd8, 0, 0},
623         {0x4001, 0x02, 0, 0}, {0x4004, 0x02, 0, 0},
624         {0x4407, 0x04, 0, 0}, {0x460b, 0x35, 0, 0}, {0x460c, 0x22, 0, 0},
625         {0x3824, 0x02, 0, 0}, {0x5001, 0xa3, 0, 0},
626 };
627
628 static const struct reg_value ov5640_setting_720P_1280_720[] = {
629         {0x3c07, 0x07, 0, 0},
630         {0x3c09, 0x1c, 0, 0}, {0x3c0a, 0x9c, 0, 0}, {0x3c0b, 0x40, 0, 0},
631         {0x3814, 0x31, 0, 0},
632         {0x3815, 0x31, 0, 0},
633         {0x3618, 0x00, 0, 0}, {0x3612, 0x29, 0, 0}, {0x3708, 0x64, 0, 0},
634         {0x3709, 0x52, 0, 0}, {0x370c, 0x03, 0, 0}, {0x3a02, 0x02, 0, 0},
635         {0x3a03, 0xe4, 0, 0}, {0x3a08, 0x01, 0, 0}, {0x3a09, 0xbc, 0, 0},
636         {0x3a0a, 0x01, 0, 0}, {0x3a0b, 0x72, 0, 0}, {0x3a0e, 0x01, 0, 0},
637         {0x3a0d, 0x02, 0, 0}, {0x3a14, 0x02, 0, 0}, {0x3a15, 0xe4, 0, 0},
638         {0x4001, 0x02, 0, 0}, {0x4004, 0x02, 0, 0},
639         {0x4407, 0x04, 0, 0}, {0x460b, 0x37, 0, 0}, {0x460c, 0x20, 0, 0},
640         {0x3824, 0x04, 0, 0}, {0x5001, 0x83, 0, 0},
641 };
642
643 static const struct reg_value ov5640_setting_1080P_1920_1080[] = {
644         {0x3c07, 0x08, 0, 0},
645         {0x3c09, 0x1c, 0, 0}, {0x3c0a, 0x9c, 0, 0}, {0x3c0b, 0x40, 0, 0},
646         {0x3814, 0x11, 0, 0},
647         {0x3815, 0x11, 0, 0},
648         {0x3618, 0x04, 0, 0}, {0x3612, 0x29, 0, 0}, {0x3708, 0x21, 0, 0},
649         {0x3709, 0x12, 0, 0}, {0x370c, 0x00, 0, 0}, {0x3a02, 0x03, 0, 0},
650         {0x3a03, 0xd8, 0, 0}, {0x3a08, 0x01, 0, 0}, {0x3a09, 0x27, 0, 0},
651         {0x3a0a, 0x00, 0, 0}, {0x3a0b, 0xf6, 0, 0}, {0x3a0e, 0x03, 0, 0},
652         {0x3a0d, 0x04, 0, 0}, {0x3a14, 0x03, 0, 0}, {0x3a15, 0xd8, 0, 0},
653         {0x4001, 0x02, 0, 0}, {0x4004, 0x06, 0, 0},
654         {0x4407, 0x04, 0, 0}, {0x460b, 0x35, 0, 0}, {0x460c, 0x22, 0, 0},
655         {0x3824, 0x02, 0, 0}, {0x5001, 0x83, 0, 0},
656         {0x3c07, 0x07, 0, 0}, {0x3c08, 0x00, 0, 0},
657         {0x3c09, 0x1c, 0, 0}, {0x3c0a, 0x9c, 0, 0}, {0x3c0b, 0x40, 0, 0},
658         {0x3612, 0x2b, 0, 0}, {0x3708, 0x64, 0, 0},
659         {0x3a02, 0x04, 0, 0}, {0x3a03, 0x60, 0, 0}, {0x3a08, 0x01, 0, 0},
660         {0x3a09, 0x50, 0, 0}, {0x3a0a, 0x01, 0, 0}, {0x3a0b, 0x18, 0, 0},
661         {0x3a0e, 0x03, 0, 0}, {0x3a0d, 0x04, 0, 0}, {0x3a14, 0x04, 0, 0},
662         {0x3a15, 0x60, 0, 0}, {0x4407, 0x04, 0, 0},
663         {0x460b, 0x37, 0, 0}, {0x460c, 0x20, 0, 0}, {0x3824, 0x04, 0, 0},
664         {0x4005, 0x1a, 0, 0},
665 };
666
667 static const struct reg_value ov5640_setting_QSXGA_2592_1944[] = {
668         {0x3c07, 0x08, 0, 0},
669         {0x3c09, 0x1c, 0, 0}, {0x3c0a, 0x9c, 0, 0}, {0x3c0b, 0x40, 0, 0},
670         {0x3814, 0x11, 0, 0},
671         {0x3815, 0x11, 0, 0},
672         {0x3618, 0x04, 0, 0}, {0x3612, 0x29, 0, 0}, {0x3708, 0x21, 0, 0},
673         {0x3709, 0x12, 0, 0}, {0x370c, 0x00, 0, 0}, {0x3a02, 0x03, 0, 0},
674         {0x3a03, 0xd8, 0, 0}, {0x3a08, 0x01, 0, 0}, {0x3a09, 0x27, 0, 0},
675         {0x3a0a, 0x00, 0, 0}, {0x3a0b, 0xf6, 0, 0}, {0x3a0e, 0x03, 0, 0},
676         {0x3a0d, 0x04, 0, 0}, {0x3a14, 0x03, 0, 0}, {0x3a15, 0xd8, 0, 0},
677         {0x4001, 0x02, 0, 0}, {0x4004, 0x06, 0, 0},
678         {0x4407, 0x04, 0, 0}, {0x460b, 0x35, 0, 0}, {0x460c, 0x22, 0, 0},
679         {0x3824, 0x02, 0, 0}, {0x5001, 0x83, 0, 70},
680 };
681
682 static const struct ov5640_mode_info ov5640_mode_data[OV5640_NUM_MODES] = {
683         {
684                 /* 160x120 */
685                 .id             = OV5640_MODE_QQVGA_160_120,
686                 .dn_mode        = SUBSAMPLING,
687                 .pixel_rate     = OV5640_PIXEL_RATE_48M,
688                 .width          = 160,
689                 .height         = 120,
690                 .dvp_timings = {
691                         .analog_crop = {
692                                 .left   = 0,
693                                 .top    = 4,
694                                 .width  = 2624,
695                                 .height = 1944,
696                         },
697                         .crop = {
698                                 .left   = 16,
699                                 .top    = 6,
700                                 .width  = 160,
701                                 .height = 120,
702                         },
703                         .htot           = 1896,
704                         .vblank_def     = 864,
705                 },
706                 .csi2_timings = {
707                         /* Feed the full valid pixel array to the ISP. */
708                         .analog_crop = {
709                                 .left   = OV5640_PIXEL_ARRAY_LEFT,
710                                 .top    = OV5640_PIXEL_ARRAY_TOP,
711                                 .width  = OV5640_PIXEL_ARRAY_WIDTH,
712                                 .height = OV5640_PIXEL_ARRAY_HEIGHT,
713                         },
714                         /* Maintain a minimum processing margin. */
715                         .crop = {
716                                 .left   = 2,
717                                 .top    = 4,
718                                 .width  = 160,
719                                 .height = 120,
720                         },
721                         .htot           = 1600,
722                         .vblank_def     = 878,
723                 },
724                 .reg_data       = ov5640_setting_low_res,
725                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_low_res),
726                 .max_fps        = OV5640_30_FPS,
727                 .def_fps        = OV5640_30_FPS
728         }, {
729                 /* 176x144 */
730                 .id             = OV5640_MODE_QCIF_176_144,
731                 .dn_mode        = SUBSAMPLING,
732                 .pixel_rate     = OV5640_PIXEL_RATE_48M,
733                 .width          = 176,
734                 .height         = 144,
735                 .dvp_timings = {
736                         .analog_crop = {
737                                 .left   = 0,
738                                 .top    = 4,
739                                 .width  = 2624,
740                                 .height = 1944,
741                         },
742                         .crop = {
743                                 .left   = 16,
744                                 .top    = 6,
745                                 .width  = 176,
746                                 .height = 144,
747                         },
748                         .htot           = 1896,
749                         .vblank_def     = 840,
750                 },
751                 .csi2_timings = {
752                         /* Feed the full valid pixel array to the ISP. */
753                         .analog_crop = {
754                                 .left   = OV5640_PIXEL_ARRAY_LEFT,
755                                 .top    = OV5640_PIXEL_ARRAY_TOP,
756                                 .width  = OV5640_PIXEL_ARRAY_WIDTH,
757                                 .height = OV5640_PIXEL_ARRAY_HEIGHT,
758                         },
759                         /* Maintain a minimum processing margin. */
760                         .crop = {
761                                 .left   = 2,
762                                 .top    = 4,
763                                 .width  = 176,
764                                 .height = 144,
765                         },
766                         .htot           = 1600,
767                         .vblank_def     = 854,
768                 },
769                 .reg_data       = ov5640_setting_low_res,
770                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_low_res),
771                 .max_fps        = OV5640_30_FPS,
772                 .def_fps        = OV5640_30_FPS
773         }, {
774                 /* 320x240 */
775                 .id             = OV5640_MODE_QVGA_320_240,
776                 .dn_mode        = SUBSAMPLING,
777                 .width          = 320,
778                 .height         = 240,
779                 .pixel_rate     = OV5640_PIXEL_RATE_48M,
780                 .dvp_timings = {
781                         .analog_crop = {
782                                 .left   = 0,
783                                 .top    = 4,
784                                 .width  = 2624,
785                                 .height = 1944,
786                         },
787                         .crop = {
788                                 .left   = 16,
789                                 .top    = 6,
790                                 .width  = 320,
791                                 .height = 240,
792                         },
793                         .htot           = 1896,
794                         .vblank_def     = 744,
795                 },
796                 .csi2_timings = {
797                         /* Feed the full valid pixel array to the ISP. */
798                         .analog_crop = {
799                                 .left   = OV5640_PIXEL_ARRAY_LEFT,
800                                 .top    = OV5640_PIXEL_ARRAY_TOP,
801                                 .width  = OV5640_PIXEL_ARRAY_WIDTH,
802                                 .height = OV5640_PIXEL_ARRAY_HEIGHT,
803                         },
804                         /* Maintain a minimum processing margin. */
805                         .crop = {
806                                 .left   = 2,
807                                 .top    = 4,
808                                 .width  = 320,
809                                 .height = 240,
810                         },
811                         .htot           = 1600,
812                         .vblank_def     = 760,
813                 },
814                 .reg_data       = ov5640_setting_low_res,
815                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_low_res),
816                 .max_fps        = OV5640_30_FPS,
817                 .def_fps        = OV5640_30_FPS
818         }, {
819                 /* 640x480 */
820                 .id             = OV5640_MODE_VGA_640_480,
821                 .dn_mode        = SUBSAMPLING,
822                 .pixel_rate     = OV5640_PIXEL_RATE_48M,
823                 .width          = 640,
824                 .height         = 480,
825                 .dvp_timings = {
826                         .analog_crop = {
827                                 .left   = 0,
828                                 .top    = 4,
829                                 .width  = 2624,
830                                 .height = 1944,
831                         },
832                         .crop = {
833                                 .left   = 16,
834                                 .top    = 6,
835                                 .width  = 640,
836                                 .height = 480,
837                         },
838                         .htot           = 1896,
839                         .vblank_def     = 600,
840                 },
841                 .csi2_timings = {
842                         /* Feed the full valid pixel array to the ISP. */
843                         .analog_crop = {
844                                 .left   = OV5640_PIXEL_ARRAY_LEFT,
845                                 .top    = OV5640_PIXEL_ARRAY_TOP,
846                                 .width  = OV5640_PIXEL_ARRAY_WIDTH,
847                                 .height = OV5640_PIXEL_ARRAY_HEIGHT,
848                         },
849                         /* Maintain a minimum processing margin. */
850                         .crop = {
851                                 .left   = 2,
852                                 .top    = 4,
853                                 .width  = 640,
854                                 .height = 480,
855                         },
856                         .htot           = 1600,
857                         .vblank_def     = 520,
858                 },
859                 .reg_data       = ov5640_setting_low_res,
860                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_low_res),
861                 .max_fps        = OV5640_60_FPS,
862                 .def_fps        = OV5640_30_FPS
863         }, {
864                 /* 720x480 */
865                 .id             = OV5640_MODE_NTSC_720_480,
866                 .dn_mode        = SUBSAMPLING,
867                 .width          = 720,
868                 .height         = 480,
869                 .pixel_rate     = OV5640_PIXEL_RATE_96M,
870                 .dvp_timings = {
871                         .analog_crop = {
872                                 .left   = 0,
873                                 .top    = 4,
874                                 .width  = 2624,
875                                 .height = 1944,
876                         },
877                         .crop = {
878                                 .left   = 56,
879                                 .top    = 60,
880                                 .width  = 720,
881                                 .height = 480,
882                         },
883                         .htot           = 1896,
884                         .vblank_def     = 504,
885                 },
886                 .csi2_timings = {
887                         /* Feed the full valid pixel array to the ISP. */
888                         .analog_crop = {
889                                 .left   = OV5640_PIXEL_ARRAY_LEFT,
890                                 .top    = OV5640_PIXEL_ARRAY_TOP,
891                                 .width  = OV5640_PIXEL_ARRAY_WIDTH,
892                                 .height = OV5640_PIXEL_ARRAY_HEIGHT,
893                         },
894                         .crop = {
895                                 .left   = 56,
896                                 .top    = 60,
897                                 .width  = 720,
898                                 .height = 480,
899                         },
900                         .htot           = 1896,
901                         .vblank_def     = 1206,
902                 },
903                 .reg_data       = ov5640_setting_low_res,
904                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_low_res),
905                 .max_fps        = OV5640_30_FPS,
906                 .def_fps        = OV5640_30_FPS
907         }, {
908                 /* 720x576 */
909                 .id             = OV5640_MODE_PAL_720_576,
910                 .dn_mode        = SUBSAMPLING,
911                 .width          = 720,
912                 .height         = 576,
913                 .pixel_rate     = OV5640_PIXEL_RATE_96M,
914                 .dvp_timings = {
915                         .analog_crop = {
916                                 .left   = 0,
917                                 .top    = 4,
918                                 .width  = 2624,
919                                 .height = 1944,
920                         },
921                         .crop = {
922                                 .left   = 56,
923                                 .top    = 6,
924                                 .width  = 720,
925                                 .height = 576,
926                         },
927                         .htot           = 1896,
928                         .vblank_def     = 408,
929                 },
930                 .csi2_timings = {
931                         /* Feed the full valid pixel array to the ISP. */
932                         .analog_crop = {
933                                 .left   = OV5640_PIXEL_ARRAY_LEFT,
934                                 .top    = OV5640_PIXEL_ARRAY_TOP,
935                                 .width  = OV5640_PIXEL_ARRAY_WIDTH,
936                                 .height = OV5640_PIXEL_ARRAY_HEIGHT,
937                         },
938                         .crop = {
939                                 .left   = 56,
940                                 .top    = 6,
941                                 .width  = 720,
942                                 .height = 576,
943                         },
944                         .htot           = 1896,
945                         .vblank_def     = 1110,
946                 },
947                 .reg_data       = ov5640_setting_low_res,
948                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_low_res),
949                 .max_fps        = OV5640_30_FPS,
950                 .def_fps        = OV5640_30_FPS
951         }, {
952                 /* 1024x768 */
953                 .id             = OV5640_MODE_XGA_1024_768,
954                 .dn_mode        = SUBSAMPLING,
955                 .pixel_rate     = OV5640_PIXEL_RATE_96M,
956                 .width          = 1024,
957                 .height         = 768,
958                 .dvp_timings = {
959                         .analog_crop = {
960                                 .left   = 0,
961                                 .top    = 4,
962                                 .width  = 2624,
963                                 .height = 1944,
964                         },
965                         .crop = {
966                                 .left   = 16,
967                                 .top    = 6,
968                                 .width  = 1024,
969                                 .height = 768,
970                         },
971                         .htot           = 1896,
972                         .vblank_def     = 312,
973                 },
974                 .csi2_timings = {
975                         .analog_crop = {
976                                 .left   = 0,
977                                 .top    = 4,
978                                 .width  = OV5640_NATIVE_WIDTH,
979                                 .height = OV5640_PIXEL_ARRAY_HEIGHT,
980                         },
981                         .crop = {
982                                 .left   = 16,
983                                 .top    = 6,
984                                 .width  = 1024,
985                                 .height = 768,
986                         },
987                         .htot           = 1896,
988                         .vblank_def     = 918,
989                 },
990                 .reg_data       = ov5640_setting_low_res,
991                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_low_res),
992                 .max_fps        = OV5640_30_FPS,
993                 .def_fps        = OV5640_30_FPS
994         }, {
995                 /* 1280x720 */
996                 .id             = OV5640_MODE_720P_1280_720,
997                 .dn_mode        = SUBSAMPLING,
998                 .pixel_rate     = OV5640_PIXEL_RATE_124M,
999                 .width          = 1280,
1000                 .height         = 720,
1001                 .dvp_timings = {
1002                         .analog_crop = {
1003                                 .left   = 0,
1004                                 .top    = 250,
1005                                 .width  = 2624,
1006                                 .height = 1456,
1007                         },
1008                         .crop = {
1009                                 .left   = 16,
1010                                 .top    = 4,
1011                                 .width  = 1280,
1012                                 .height = 720,
1013                         },
1014                         .htot           = 1892,
1015                         .vblank_def     = 20,
1016                 },
1017                 .csi2_timings = {
1018                         .analog_crop = {
1019                                 .left   = 0,
1020                                 .top    = 250,
1021                                 .width  = 2624,
1022                                 .height = 1456,
1023                         },
1024                         .crop = {
1025                                 .left   = 16,
1026                                 .top    = 4,
1027                                 .width  = 1280,
1028                                 .height = 720,
1029                         },
1030                         .htot           = 1600,
1031                         .vblank_def     = 560,
1032                 },
1033                 .reg_data       = ov5640_setting_720P_1280_720,
1034                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_720P_1280_720),
1035                 .max_fps        = OV5640_30_FPS,
1036                 .def_fps        = OV5640_30_FPS
1037         }, {
1038                 /* 1920x1080 */
1039                 .id             = OV5640_MODE_1080P_1920_1080,
1040                 .dn_mode        = SCALING,
1041                 .pixel_rate     = OV5640_PIXEL_RATE_148M,
1042                 .width          = 1920,
1043                 .height         = 1080,
1044                 .dvp_timings = {
1045                         .analog_crop = {
1046                                 .left   = 336,
1047                                 .top    = 434,
1048                                 .width  = 1952,
1049                                 .height = 1088,
1050                         },
1051                         .crop = {
1052                                 .left   = 16,
1053                                 .top    = 4,
1054                                 .width  = 1920,
1055                                 .height = 1080,
1056                         },
1057                         .htot           = 2500,
1058                         .vblank_def     = 40,
1059                 },
1060                 .csi2_timings = {
1061                         /* Crop the full valid pixel array in the center. */
1062                         .analog_crop = {
1063                                 .left   = 336,
1064                                 .top    = 434,
1065                                 .width  = 1952,
1066                                 .height = 1088,
1067                         },
1068                         /* Maintain a larger processing margins. */
1069                         .crop = {
1070                                 .left   = 16,
1071                                 .top    = 4,
1072                                 .width  = 1920,
1073                                 .height = 1080,
1074                         },
1075                         .htot           = 2234,
1076                         .vblank_def     = 24,
1077                 },
1078                 .reg_data       = ov5640_setting_1080P_1920_1080,
1079                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_1080P_1920_1080),
1080                 .max_fps        = OV5640_30_FPS,
1081                 .def_fps        = OV5640_30_FPS
1082         }, {
1083                 /* 2592x1944 */
1084                 .id             = OV5640_MODE_QSXGA_2592_1944,
1085                 .dn_mode        = SCALING,
1086                 .pixel_rate     = OV5640_PIXEL_RATE_168M,
1087                 .width          = OV5640_PIXEL_ARRAY_WIDTH,
1088                 .height         = OV5640_PIXEL_ARRAY_HEIGHT,
1089                 .dvp_timings = {
1090                         .analog_crop = {
1091                                 .left   = 0,
1092                                 .top    = 0,
1093                                 .width  = 2624,
1094                                 .height = 1952,
1095                         },
1096                         .crop = {
1097                                 .left   = 16,
1098                                 .top    = 4,
1099                                 .width  = 2592,
1100                                 .height = 1944,
1101                         },
1102                         .htot           = 2844,
1103                         .vblank_def     = 24,
1104                 },
1105                 .csi2_timings = {
1106                         /* Give more processing margin to full resolution. */
1107                         .analog_crop = {
1108                                 .left   = 0,
1109                                 .top    = 0,
1110                                 .width  = OV5640_NATIVE_WIDTH,
1111                                 .height = 1952,
1112                         },
1113                         .crop = {
1114                                 .left   = 16,
1115                                 .top    = 4,
1116                                 .width  = 2592,
1117                                 .height = 1944,
1118                         },
1119                         .htot           = 2844,
1120                         .vblank_def     = 24,
1121                 },
1122                 .reg_data       = ov5640_setting_QSXGA_2592_1944,
1123                 .reg_data_size  = ARRAY_SIZE(ov5640_setting_QSXGA_2592_1944),
1124                 .max_fps        = OV5640_15_FPS,
1125                 .def_fps        = OV5640_15_FPS
1126         },
1127 };
1128
1129 static const struct ov5640_timings *
1130 ov5640_timings(const struct ov5640_dev *sensor,
1131                const struct ov5640_mode_info *mode)
1132 {
1133         if (ov5640_is_csi2(sensor))
1134                 return &mode->csi2_timings;
1135
1136         return &mode->dvp_timings;
1137 }
1138
1139 static int ov5640_init_slave_id(struct ov5640_dev *sensor)
1140 {
1141         struct i2c_client *client = sensor->i2c_client;
1142         struct i2c_msg msg;
1143         u8 buf[3];
1144         int ret;
1145
1146         if (client->addr == OV5640_DEFAULT_SLAVE_ID)
1147                 return 0;
1148
1149         buf[0] = OV5640_REG_SLAVE_ID >> 8;
1150         buf[1] = OV5640_REG_SLAVE_ID & 0xff;
1151         buf[2] = client->addr << 1;
1152
1153         msg.addr = OV5640_DEFAULT_SLAVE_ID;
1154         msg.flags = 0;
1155         msg.buf = buf;
1156         msg.len = sizeof(buf);
1157
1158         ret = i2c_transfer(client->adapter, &msg, 1);
1159         if (ret < 0) {
1160                 dev_err(&client->dev, "%s: failed with %d\n", __func__, ret);
1161                 return ret;
1162         }
1163
1164         return 0;
1165 }
1166
1167 static int ov5640_write_reg(struct ov5640_dev *sensor, u16 reg, u8 val)
1168 {
1169         struct i2c_client *client = sensor->i2c_client;
1170         struct i2c_msg msg;
1171         u8 buf[3];
1172         int ret;
1173
1174         buf[0] = reg >> 8;
1175         buf[1] = reg & 0xff;
1176         buf[2] = val;
1177
1178         msg.addr = client->addr;
1179         msg.flags = client->flags;
1180         msg.buf = buf;
1181         msg.len = sizeof(buf);
1182
1183         ret = i2c_transfer(client->adapter, &msg, 1);
1184         if (ret < 0) {
1185                 dev_err(&client->dev, "%s: error: reg=%x, val=%x\n",
1186                         __func__, reg, val);
1187                 return ret;
1188         }
1189
1190         return 0;
1191 }
1192
1193 static int ov5640_read_reg(struct ov5640_dev *sensor, u16 reg, u8 *val)
1194 {
1195         struct i2c_client *client = sensor->i2c_client;
1196         struct i2c_msg msg[2];
1197         u8 buf[2];
1198         int ret;
1199
1200         buf[0] = reg >> 8;
1201         buf[1] = reg & 0xff;
1202
1203         msg[0].addr = client->addr;
1204         msg[0].flags = client->flags;
1205         msg[0].buf = buf;
1206         msg[0].len = sizeof(buf);
1207
1208         msg[1].addr = client->addr;
1209         msg[1].flags = client->flags | I2C_M_RD;
1210         msg[1].buf = buf;
1211         msg[1].len = 1;
1212
1213         ret = i2c_transfer(client->adapter, msg, 2);
1214         if (ret < 0) {
1215                 dev_err(&client->dev, "%s: error: reg=%x\n",
1216                         __func__, reg);
1217                 return ret;
1218         }
1219
1220         *val = buf[0];
1221         return 0;
1222 }
1223
1224 static int ov5640_read_reg16(struct ov5640_dev *sensor, u16 reg, u16 *val)
1225 {
1226         u8 hi, lo;
1227         int ret;
1228
1229         ret = ov5640_read_reg(sensor, reg, &hi);
1230         if (ret)
1231                 return ret;
1232         ret = ov5640_read_reg(sensor, reg + 1, &lo);
1233         if (ret)
1234                 return ret;
1235
1236         *val = ((u16)hi << 8) | (u16)lo;
1237         return 0;
1238 }
1239
1240 static int ov5640_write_reg16(struct ov5640_dev *sensor, u16 reg, u16 val)
1241 {
1242         int ret;
1243
1244         ret = ov5640_write_reg(sensor, reg, val >> 8);
1245         if (ret)
1246                 return ret;
1247
1248         return ov5640_write_reg(sensor, reg + 1, val & 0xff);
1249 }
1250
1251 static int ov5640_mod_reg(struct ov5640_dev *sensor, u16 reg,
1252                           u8 mask, u8 val)
1253 {
1254         u8 readval;
1255         int ret;
1256
1257         ret = ov5640_read_reg(sensor, reg, &readval);
1258         if (ret)
1259                 return ret;
1260
1261         readval &= ~mask;
1262         val &= mask;
1263         val |= readval;
1264
1265         return ov5640_write_reg(sensor, reg, val);
1266 }
1267
1268 /*
1269  * After trying the various combinations, reading various
1270  * documentations spread around the net, and from the various
1271  * feedback, the clock tree is probably as follows:
1272  *
1273  *   +--------------+
1274  *   |  Ext. Clock  |
1275  *   +-+------------+
1276  *     |  +----------+
1277  *     +->|   PLL1   | - reg 0x3036, for the multiplier
1278  *        +-+--------+ - reg 0x3037, bits 0-3 for the pre-divider
1279  *          |  +--------------+
1280  *          +->| System Clock |  - reg 0x3035, bits 4-7
1281  *             +-+------------+
1282  *               |  +--------------+
1283  *               +->| MIPI Divider | - reg 0x3035, bits 0-3
1284  *               |  +-+------------+
1285  *               |    +----------------> MIPI SCLK
1286  *               |    +  +-----+
1287  *               |    +->| / 2 |-------> MIPI BIT CLK
1288  *               |       +-----+
1289  *               |  +--------------+
1290  *               +->| PLL Root Div | - reg 0x3037, bit 4
1291  *                  +-+------------+
1292  *                    |  +---------+
1293  *                    +->| Bit Div | - reg 0x3034, bits 0-3
1294  *                       +-+-------+
1295  *                         |  +-------------+
1296  *                         +->| SCLK Div    | - reg 0x3108, bits 0-1
1297  *                         |  +-+-----------+
1298  *                         |    +---------------> SCLK
1299  *                         |  +-------------+
1300  *                         +->| SCLK 2X Div | - reg 0x3108, bits 2-3
1301  *                         |  +-+-----------+
1302  *                         |    +---------------> SCLK 2X
1303  *                         |  +-------------+
1304  *                         +->| PCLK Div    | - reg 0x3108, bits 4-5
1305  *                            ++------------+
1306  *                             +  +-----------+
1307  *                             +->|   P_DIV   | - reg 0x3035, bits 0-3
1308  *                                +-----+-----+
1309  *                                       +------------> PCLK
1310  *
1311  * There seems to be also constraints:
1312  *  - the PLL pre-divider output rate should be in the 4-27MHz range
1313  *  - the PLL multiplier output rate should be in the 500-1000MHz range
1314  *  - PCLK >= SCLK * 2 in YUV, >= SCLK in Raw or JPEG
1315  */
1316
1317 /*
1318  * This is supposed to be ranging from 1 to 8, but the value is always
1319  * set to 3 in the vendor kernels.
1320  */
1321 #define OV5640_PLL_PREDIV       3
1322
1323 #define OV5640_PLL_MULT_MIN     4
1324 #define OV5640_PLL_MULT_MAX     252
1325
1326 /*
1327  * This is supposed to be ranging from 1 to 16, but the value is
1328  * always set to either 1 or 2 in the vendor kernels.
1329  */
1330 #define OV5640_SYSDIV_MIN       1
1331 #define OV5640_SYSDIV_MAX       16
1332
1333 /*
1334  * This is supposed to be ranging from 1 to 2, but the value is always
1335  * set to 2 in the vendor kernels.
1336  */
1337 #define OV5640_PLL_ROOT_DIV                     2
1338 #define OV5640_PLL_CTRL3_PLL_ROOT_DIV_2         BIT(4)
1339
1340 /*
1341  * We only supports 8-bit formats at the moment
1342  */
1343 #define OV5640_BIT_DIV                          2
1344 #define OV5640_PLL_CTRL0_MIPI_MODE_8BIT         0x08
1345
1346 /*
1347  * This is supposed to be ranging from 1 to 8, but the value is always
1348  * set to 2 in the vendor kernels.
1349  */
1350 #define OV5640_SCLK_ROOT_DIV    2
1351
1352 /*
1353  * This is hardcoded so that the consistency is maintained between SCLK and
1354  * SCLK 2x.
1355  */
1356 #define OV5640_SCLK2X_ROOT_DIV (OV5640_SCLK_ROOT_DIV / 2)
1357
1358 /*
1359  * This is supposed to be ranging from 1 to 8, but the value is always
1360  * set to 1 in the vendor kernels.
1361  */
1362 #define OV5640_PCLK_ROOT_DIV                    1
1363 #define OV5640_PLL_SYS_ROOT_DIVIDER_BYPASS      0x00
1364
1365 static unsigned long ov5640_compute_sys_clk(struct ov5640_dev *sensor,
1366                                             u8 pll_prediv, u8 pll_mult,
1367                                             u8 sysdiv)
1368 {
1369         unsigned long sysclk = sensor->xclk_freq / pll_prediv * pll_mult;
1370
1371         /* PLL1 output cannot exceed 1GHz. */
1372         if (sysclk / 1000000 > 1000)
1373                 return 0;
1374
1375         return sysclk / sysdiv;
1376 }
1377
1378 static unsigned long ov5640_calc_sys_clk(struct ov5640_dev *sensor,
1379                                          unsigned long rate,
1380                                          u8 *pll_prediv, u8 *pll_mult,
1381                                          u8 *sysdiv)
1382 {
1383         unsigned long best = ~0;
1384         u8 best_sysdiv = 1, best_mult = 1;
1385         u8 _sysdiv, _pll_mult;
1386
1387         for (_sysdiv = OV5640_SYSDIV_MIN;
1388              _sysdiv <= OV5640_SYSDIV_MAX;
1389              _sysdiv++) {
1390                 for (_pll_mult = OV5640_PLL_MULT_MIN;
1391                      _pll_mult <= OV5640_PLL_MULT_MAX;
1392                      _pll_mult++) {
1393                         unsigned long _rate;
1394
1395                         /*
1396                          * The PLL multiplier cannot be odd if above
1397                          * 127.
1398                          */
1399                         if (_pll_mult > 127 && (_pll_mult % 2))
1400                                 continue;
1401
1402                         _rate = ov5640_compute_sys_clk(sensor,
1403                                                        OV5640_PLL_PREDIV,
1404                                                        _pll_mult, _sysdiv);
1405
1406                         /*
1407                          * We have reached the maximum allowed PLL1 output,
1408                          * increase sysdiv.
1409                          */
1410                         if (!_rate)
1411                                 break;
1412
1413                         /*
1414                          * Prefer rates above the expected clock rate than
1415                          * below, even if that means being less precise.
1416                          */
1417                         if (_rate < rate)
1418                                 continue;
1419
1420                         if (abs(rate - _rate) < abs(rate - best)) {
1421                                 best = _rate;
1422                                 best_sysdiv = _sysdiv;
1423                                 best_mult = _pll_mult;
1424                         }
1425
1426                         if (_rate == rate)
1427                                 goto out;
1428                 }
1429         }
1430
1431 out:
1432         *sysdiv = best_sysdiv;
1433         *pll_prediv = OV5640_PLL_PREDIV;
1434         *pll_mult = best_mult;
1435
1436         return best;
1437 }
1438
1439 /*
1440  * ov5640_set_mipi_pclk() - Calculate the clock tree configuration values
1441  *                          for the MIPI CSI-2 output.
1442  */
1443 static int ov5640_set_mipi_pclk(struct ov5640_dev *sensor)
1444 {
1445         u8 bit_div, mipi_div, pclk_div, sclk_div, sclk2x_div, root_div;
1446         u8 prediv, mult, sysdiv;
1447         unsigned long link_freq;
1448         unsigned long sysclk;
1449         u8 pclk_period;
1450         u32 sample_rate;
1451         u32 num_lanes;
1452         int ret;
1453
1454         /* Use the link freq computed at ov5640_update_pixel_rate() time. */
1455         link_freq = sensor->current_link_freq;
1456
1457         /*
1458          * - mipi_div - Additional divider for the MIPI lane clock.
1459          *
1460          * Higher link frequencies would make sysclk > 1GHz.
1461          * Keep the sysclk low and do not divide in the MIPI domain.
1462          */
1463         if (link_freq > OV5640_LINK_RATE_MAX)
1464                 mipi_div = 1;
1465         else
1466                 mipi_div = 2;
1467
1468         sysclk = link_freq * mipi_div;
1469         ov5640_calc_sys_clk(sensor, sysclk, &prediv, &mult, &sysdiv);
1470
1471         /*
1472          * Adjust PLL parameters to maintain the MIPI_SCLK-to-PCLK ratio.
1473          *
1474          * - root_div = 2 (fixed)
1475          * - bit_div : MIPI 8-bit = 2; MIPI 10-bit = 2.5
1476          * - pclk_div = 1 (fixed)
1477          * - p_div  = (2 lanes ? mipi_div : 2 * mipi_div)
1478          *
1479          * This results in the following MIPI_SCLK depending on the number
1480          * of lanes:
1481          *
1482          * - 2 lanes: MIPI_SCLK = (4 or 5) * PCLK
1483          * - 1 lanes: MIPI_SCLK = (8 or 10) * PCLK
1484          */
1485         root_div = OV5640_PLL_CTRL3_PLL_ROOT_DIV_2;
1486         bit_div =  OV5640_PLL_CTRL0_MIPI_MODE_8BIT;
1487         pclk_div = ilog2(OV5640_PCLK_ROOT_DIV);
1488
1489         /*
1490          * Scaler clock:
1491          * - YUV: PCLK >= 2 * SCLK
1492          * - RAW or JPEG: PCLK >= SCLK
1493          * - sclk2x_div = sclk_div / 2
1494          */
1495         sclk_div = ilog2(OV5640_SCLK_ROOT_DIV);
1496         sclk2x_div = ilog2(OV5640_SCLK2X_ROOT_DIV);
1497
1498         /*
1499          * Set the pixel clock period expressed in ns with 1-bit decimal
1500          * (0x01=0.5ns).
1501          *
1502          * The register is very briefly documented. In the OV5645 datasheet it
1503          * is described as (2 * pclk period), and from testing it seems the
1504          * actual definition is 2 * 8-bit sample period.
1505          *
1506          * 2 * sample_period = (mipi_clk * 2 * num_lanes / bpp) * (bpp / 8) / 2
1507          */
1508         num_lanes = sensor->ep.bus.mipi_csi2.num_data_lanes;
1509         sample_rate = (link_freq * mipi_div * num_lanes * 2) / 16;
1510         pclk_period = 2000000000UL / sample_rate;
1511
1512         /* Program the clock tree registers. */
1513         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL0, 0x0f, bit_div);
1514         if (ret)
1515                 return ret;
1516
1517         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL1, 0xff,
1518                              (sysdiv << 4) | mipi_div);
1519         if (ret)
1520                 return ret;
1521
1522         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL2, 0xff, mult);
1523         if (ret)
1524                 return ret;
1525
1526         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL3, 0x1f,
1527                              root_div | prediv);
1528         if (ret)
1529                 return ret;
1530
1531         ret = ov5640_mod_reg(sensor, OV5640_REG_SYS_ROOT_DIVIDER, 0x3f,
1532                              (pclk_div << 4) | (sclk2x_div << 2) | sclk_div);
1533         if (ret)
1534                 return ret;
1535
1536         return ov5640_write_reg(sensor, OV5640_REG_PCLK_PERIOD, pclk_period);
1537 }
1538
1539 static u32 ov5640_calc_pixel_rate(struct ov5640_dev *sensor)
1540 {
1541         const struct ov5640_mode_info *mode = sensor->current_mode;
1542         const struct ov5640_timings *timings = &mode->dvp_timings;
1543         u32 rate;
1544
1545         rate = timings->htot * (timings->crop.height + timings->vblank_def);
1546         rate *= ov5640_framerates[sensor->current_fr];
1547
1548         return rate;
1549 }
1550
1551 static unsigned long ov5640_calc_pclk(struct ov5640_dev *sensor,
1552                                       unsigned long rate,
1553                                       u8 *pll_prediv, u8 *pll_mult, u8 *sysdiv,
1554                                       u8 *pll_rdiv, u8 *bit_div, u8 *pclk_div)
1555 {
1556         unsigned long _rate = rate * OV5640_PLL_ROOT_DIV * OV5640_BIT_DIV *
1557                                 OV5640_PCLK_ROOT_DIV;
1558
1559         _rate = ov5640_calc_sys_clk(sensor, _rate, pll_prediv, pll_mult,
1560                                     sysdiv);
1561         *pll_rdiv = OV5640_PLL_ROOT_DIV;
1562         *bit_div = OV5640_BIT_DIV;
1563         *pclk_div = OV5640_PCLK_ROOT_DIV;
1564
1565         return _rate / *pll_rdiv / *bit_div / *pclk_div;
1566 }
1567
1568 static int ov5640_set_dvp_pclk(struct ov5640_dev *sensor)
1569 {
1570         u8 prediv, mult, sysdiv, pll_rdiv, bit_div, pclk_div;
1571         u32 rate;
1572         int ret;
1573
1574         rate = ov5640_calc_pixel_rate(sensor);
1575         rate *= ov5640_code_to_bpp(sensor, sensor->fmt.code);
1576         rate /= sensor->ep.bus.parallel.bus_width;
1577
1578         ov5640_calc_pclk(sensor, rate, &prediv, &mult, &sysdiv, &pll_rdiv,
1579                          &bit_div, &pclk_div);
1580
1581         if (bit_div == 2)
1582                 bit_div = 8;
1583
1584         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL0,
1585                              0x0f, bit_div);
1586         if (ret)
1587                 return ret;
1588
1589         /*
1590          * We need to set sysdiv according to the clock, and to clear
1591          * the MIPI divider.
1592          */
1593         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL1,
1594                              0xff, sysdiv << 4);
1595         if (ret)
1596                 return ret;
1597
1598         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL2,
1599                              0xff, mult);
1600         if (ret)
1601                 return ret;
1602
1603         ret = ov5640_mod_reg(sensor, OV5640_REG_SC_PLL_CTRL3,
1604                              0x1f, prediv | ((pll_rdiv - 1) << 4));
1605         if (ret)
1606                 return ret;
1607
1608         return ov5640_mod_reg(sensor, OV5640_REG_SYS_ROOT_DIVIDER, 0x30,
1609                               (ilog2(pclk_div) << 4));
1610 }
1611
1612 /* set JPEG framing sizes */
1613 static int ov5640_set_jpeg_timings(struct ov5640_dev *sensor,
1614                                    const struct ov5640_mode_info *mode)
1615 {
1616         int ret;
1617
1618         /*
1619          * compression mode 3 timing
1620          *
1621          * Data is transmitted with programmable width (VFIFO_HSIZE).
1622          * No padding done. Last line may have less data. Varying
1623          * number of lines per frame, depending on amount of data.
1624          */
1625         ret = ov5640_mod_reg(sensor, OV5640_REG_JPG_MODE_SELECT, 0x7, 0x3);
1626         if (ret < 0)
1627                 return ret;
1628
1629         ret = ov5640_write_reg16(sensor, OV5640_REG_VFIFO_HSIZE, mode->width);
1630         if (ret < 0)
1631                 return ret;
1632
1633         return ov5640_write_reg16(sensor, OV5640_REG_VFIFO_VSIZE, mode->height);
1634 }
1635
1636 /* download ov5640 settings to sensor through i2c */
1637 static int ov5640_set_timings(struct ov5640_dev *sensor,
1638                               const struct ov5640_mode_info *mode)
1639 {
1640         const struct ov5640_timings *timings;
1641         const struct v4l2_rect *analog_crop;
1642         const struct v4l2_rect *crop;
1643         int ret;
1644
1645         if (sensor->fmt.code == MEDIA_BUS_FMT_JPEG_1X8) {
1646                 ret = ov5640_set_jpeg_timings(sensor, mode);
1647                 if (ret < 0)
1648                         return ret;
1649         }
1650
1651         timings = ov5640_timings(sensor, mode);
1652         analog_crop = &timings->analog_crop;
1653         crop = &timings->crop;
1654
1655         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_HS,
1656                                  analog_crop->left);
1657         if (ret < 0)
1658                 return ret;
1659
1660         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_VS,
1661                                  analog_crop->top);
1662         if (ret < 0)
1663                 return ret;
1664
1665         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_HW,
1666                                  analog_crop->left + analog_crop->width - 1);
1667         if (ret < 0)
1668                 return ret;
1669
1670         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_VH,
1671                                  analog_crop->top + analog_crop->height - 1);
1672         if (ret < 0)
1673                 return ret;
1674
1675         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_HOFFS, crop->left);
1676         if (ret < 0)
1677                 return ret;
1678
1679         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_VOFFS, crop->top);
1680         if (ret < 0)
1681                 return ret;
1682
1683         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_DVPHO, mode->width);
1684         if (ret < 0)
1685                 return ret;
1686
1687         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_DVPVO, mode->height);
1688         if (ret < 0)
1689                 return ret;
1690
1691         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_HTS, timings->htot);
1692         if (ret < 0)
1693                 return ret;
1694
1695         ret = ov5640_write_reg16(sensor, OV5640_REG_TIMING_VTS,
1696                                  mode->height + timings->vblank_def);
1697         if (ret < 0)
1698                 return ret;
1699
1700         return 0;
1701 }
1702
1703 static void ov5640_load_regs(struct ov5640_dev *sensor,
1704                              const struct reg_value *regs, unsigned int regnum)
1705 {
1706         unsigned int i;
1707         u32 delay_ms;
1708         u16 reg_addr;
1709         u8 mask, val;
1710         int ret = 0;
1711
1712         for (i = 0; i < regnum; ++i, ++regs) {
1713                 delay_ms = regs->delay_ms;
1714                 reg_addr = regs->reg_addr;
1715                 val = regs->val;
1716                 mask = regs->mask;
1717
1718                 /* remain in power down mode for DVP */
1719                 if (regs->reg_addr == OV5640_REG_SYS_CTRL0 &&
1720                     val == OV5640_REG_SYS_CTRL0_SW_PWUP &&
1721                     !ov5640_is_csi2(sensor))
1722                         continue;
1723
1724                 if (mask)
1725                         ret = ov5640_mod_reg(sensor, reg_addr, mask, val);
1726                 else
1727                         ret = ov5640_write_reg(sensor, reg_addr, val);
1728                 if (ret)
1729                         break;
1730
1731                 if (delay_ms)
1732                         usleep_range(1000 * delay_ms, 1000 * delay_ms + 100);
1733         }
1734 }
1735
1736 static int ov5640_set_autoexposure(struct ov5640_dev *sensor, bool on)
1737 {
1738         return ov5640_mod_reg(sensor, OV5640_REG_AEC_PK_MANUAL,
1739                               BIT(0), on ? 0 : BIT(0));
1740 }
1741
1742 /* read exposure, in number of line periods */
1743 static int ov5640_get_exposure(struct ov5640_dev *sensor)
1744 {
1745         int exp, ret;
1746         u8 temp;
1747
1748         ret = ov5640_read_reg(sensor, OV5640_REG_AEC_PK_EXPOSURE_HI, &temp);
1749         if (ret)
1750                 return ret;
1751         exp = ((int)temp & 0x0f) << 16;
1752         ret = ov5640_read_reg(sensor, OV5640_REG_AEC_PK_EXPOSURE_MED, &temp);
1753         if (ret)
1754                 return ret;
1755         exp |= ((int)temp << 8);
1756         ret = ov5640_read_reg(sensor, OV5640_REG_AEC_PK_EXPOSURE_LO, &temp);
1757         if (ret)
1758                 return ret;
1759         exp |= (int)temp;
1760
1761         return exp >> 4;
1762 }
1763
1764 /* write exposure, given number of line periods */
1765 static int ov5640_set_exposure(struct ov5640_dev *sensor, u32 exposure)
1766 {
1767         int ret;
1768
1769         exposure <<= 4;
1770
1771         ret = ov5640_write_reg(sensor,
1772                                OV5640_REG_AEC_PK_EXPOSURE_LO,
1773                                exposure & 0xff);
1774         if (ret)
1775                 return ret;
1776         ret = ov5640_write_reg(sensor,
1777                                OV5640_REG_AEC_PK_EXPOSURE_MED,
1778                                (exposure >> 8) & 0xff);
1779         if (ret)
1780                 return ret;
1781         return ov5640_write_reg(sensor,
1782                                 OV5640_REG_AEC_PK_EXPOSURE_HI,
1783                                 (exposure >> 16) & 0x0f);
1784 }
1785
1786 static int ov5640_get_gain(struct ov5640_dev *sensor)
1787 {
1788         u16 gain;
1789         int ret;
1790
1791         ret = ov5640_read_reg16(sensor, OV5640_REG_AEC_PK_REAL_GAIN, &gain);
1792         if (ret)
1793                 return ret;
1794
1795         return gain & 0x3ff;
1796 }
1797
1798 static int ov5640_set_gain(struct ov5640_dev *sensor, int gain)
1799 {
1800         return ov5640_write_reg16(sensor, OV5640_REG_AEC_PK_REAL_GAIN,
1801                                   (u16)gain & 0x3ff);
1802 }
1803
1804 static int ov5640_set_autogain(struct ov5640_dev *sensor, bool on)
1805 {
1806         return ov5640_mod_reg(sensor, OV5640_REG_AEC_PK_MANUAL,
1807                               BIT(1), on ? 0 : BIT(1));
1808 }
1809
1810 static int ov5640_set_stream_dvp(struct ov5640_dev *sensor, bool on)
1811 {
1812         return ov5640_write_reg(sensor, OV5640_REG_SYS_CTRL0, on ?
1813                                 OV5640_REG_SYS_CTRL0_SW_PWUP :
1814                                 OV5640_REG_SYS_CTRL0_SW_PWDN);
1815 }
1816
1817 static int ov5640_set_stream_mipi(struct ov5640_dev *sensor, bool on)
1818 {
1819         int ret;
1820
1821         /*
1822          * Enable/disable the MIPI interface
1823          *
1824          * 0x300e = on ? 0x45 : 0x40
1825          *
1826          * FIXME: the sensor manual (version 2.03) reports
1827          * [7:5] = 000  : 1 data lane mode
1828          * [7:5] = 001  : 2 data lanes mode
1829          * But this settings do not work, while the following ones
1830          * have been validated for 2 data lanes mode.
1831          *
1832          * [7:5] = 010  : 2 data lanes mode
1833          * [4] = 0      : Power up MIPI HS Tx
1834          * [3] = 0      : Power up MIPI LS Rx
1835          * [2] = 1/0    : MIPI interface enable/disable
1836          * [1:0] = 01/00: FIXME: 'debug'
1837          */
1838         ret = ov5640_write_reg(sensor, OV5640_REG_IO_MIPI_CTRL00,
1839                                on ? 0x45 : 0x40);
1840         if (ret)
1841                 return ret;
1842
1843         return ov5640_write_reg(sensor, OV5640_REG_FRAME_CTRL01,
1844                                 on ? 0x00 : 0x0f);
1845 }
1846
1847 static int ov5640_get_sysclk(struct ov5640_dev *sensor)
1848 {
1849          /* calculate sysclk */
1850         u32 xvclk = sensor->xclk_freq / 10000;
1851         u32 multiplier, prediv, VCO, sysdiv, pll_rdiv;
1852         u32 sclk_rdiv_map[] = {1, 2, 4, 8};
1853         u32 bit_div2x = 1, sclk_rdiv, sysclk;
1854         u8 temp1, temp2;
1855         int ret;
1856
1857         ret = ov5640_read_reg(sensor, OV5640_REG_SC_PLL_CTRL0, &temp1);
1858         if (ret)
1859                 return ret;
1860         temp2 = temp1 & 0x0f;
1861         if (temp2 == 8 || temp2 == 10)
1862                 bit_div2x = temp2 / 2;
1863
1864         ret = ov5640_read_reg(sensor, OV5640_REG_SC_PLL_CTRL1, &temp1);
1865         if (ret)
1866                 return ret;
1867         sysdiv = temp1 >> 4;
1868         if (sysdiv == 0)
1869                 sysdiv = 16;
1870
1871         ret = ov5640_read_reg(sensor, OV5640_REG_SC_PLL_CTRL2, &temp1);
1872         if (ret)
1873                 return ret;
1874         multiplier = temp1;
1875
1876         ret = ov5640_read_reg(sensor, OV5640_REG_SC_PLL_CTRL3, &temp1);
1877         if (ret)
1878                 return ret;
1879         prediv = temp1 & 0x0f;
1880         pll_rdiv = ((temp1 >> 4) & 0x01) + 1;
1881
1882         ret = ov5640_read_reg(sensor, OV5640_REG_SYS_ROOT_DIVIDER, &temp1);
1883         if (ret)
1884                 return ret;
1885         temp2 = temp1 & 0x03;
1886         sclk_rdiv = sclk_rdiv_map[temp2];
1887
1888         if (!prediv || !sysdiv || !pll_rdiv || !bit_div2x)
1889                 return -EINVAL;
1890
1891         VCO = xvclk * multiplier / prediv;
1892
1893         sysclk = VCO / sysdiv / pll_rdiv * 2 / bit_div2x / sclk_rdiv;
1894
1895         return sysclk;
1896 }
1897
1898 static int ov5640_set_night_mode(struct ov5640_dev *sensor)
1899 {
1900          /* read HTS from register settings */
1901         u8 mode;
1902         int ret;
1903
1904         ret = ov5640_read_reg(sensor, OV5640_REG_AEC_CTRL00, &mode);
1905         if (ret)
1906                 return ret;
1907         mode &= 0xfb;
1908         return ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL00, mode);
1909 }
1910
1911 static int ov5640_get_hts(struct ov5640_dev *sensor)
1912 {
1913         /* read HTS from register settings */
1914         u16 hts;
1915         int ret;
1916
1917         ret = ov5640_read_reg16(sensor, OV5640_REG_TIMING_HTS, &hts);
1918         if (ret)
1919                 return ret;
1920         return hts;
1921 }
1922
1923 static int ov5640_get_vts(struct ov5640_dev *sensor)
1924 {
1925         u16 vts;
1926         int ret;
1927
1928         ret = ov5640_read_reg16(sensor, OV5640_REG_TIMING_VTS, &vts);
1929         if (ret)
1930                 return ret;
1931         return vts;
1932 }
1933
1934 static int ov5640_set_vts(struct ov5640_dev *sensor, int vts)
1935 {
1936         return ov5640_write_reg16(sensor, OV5640_REG_TIMING_VTS, vts);
1937 }
1938
1939 static int ov5640_get_light_freq(struct ov5640_dev *sensor)
1940 {
1941         /* get banding filter value */
1942         int ret, light_freq = 0;
1943         u8 temp, temp1;
1944
1945         ret = ov5640_read_reg(sensor, OV5640_REG_HZ5060_CTRL01, &temp);
1946         if (ret)
1947                 return ret;
1948
1949         if (temp & 0x80) {
1950                 /* manual */
1951                 ret = ov5640_read_reg(sensor, OV5640_REG_HZ5060_CTRL00,
1952                                       &temp1);
1953                 if (ret)
1954                         return ret;
1955                 if (temp1 & 0x04) {
1956                         /* 50Hz */
1957                         light_freq = 50;
1958                 } else {
1959                         /* 60Hz */
1960                         light_freq = 60;
1961                 }
1962         } else {
1963                 /* auto */
1964                 ret = ov5640_read_reg(sensor, OV5640_REG_SIGMADELTA_CTRL0C,
1965                                       &temp1);
1966                 if (ret)
1967                         return ret;
1968
1969                 if (temp1 & 0x01) {
1970                         /* 50Hz */
1971                         light_freq = 50;
1972                 } else {
1973                         /* 60Hz */
1974                 }
1975         }
1976
1977         return light_freq;
1978 }
1979
1980 static int ov5640_set_bandingfilter(struct ov5640_dev *sensor)
1981 {
1982         u32 band_step60, max_band60, band_step50, max_band50, prev_vts;
1983         int ret;
1984
1985         /* read preview PCLK */
1986         ret = ov5640_get_sysclk(sensor);
1987         if (ret < 0)
1988                 return ret;
1989         if (ret == 0)
1990                 return -EINVAL;
1991         sensor->prev_sysclk = ret;
1992         /* read preview HTS */
1993         ret = ov5640_get_hts(sensor);
1994         if (ret < 0)
1995                 return ret;
1996         if (ret == 0)
1997                 return -EINVAL;
1998         sensor->prev_hts = ret;
1999
2000         /* read preview VTS */
2001         ret = ov5640_get_vts(sensor);
2002         if (ret < 0)
2003                 return ret;
2004         prev_vts = ret;
2005
2006         /* calculate banding filter */
2007         /* 60Hz */
2008         band_step60 = sensor->prev_sysclk * 100 / sensor->prev_hts * 100 / 120;
2009         ret = ov5640_write_reg16(sensor, OV5640_REG_AEC_B60_STEP, band_step60);
2010         if (ret)
2011                 return ret;
2012         if (!band_step60)
2013                 return -EINVAL;
2014         max_band60 = (int)((prev_vts - 4) / band_step60);
2015         ret = ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL0D, max_band60);
2016         if (ret)
2017                 return ret;
2018
2019         /* 50Hz */
2020         band_step50 = sensor->prev_sysclk * 100 / sensor->prev_hts;
2021         ret = ov5640_write_reg16(sensor, OV5640_REG_AEC_B50_STEP, band_step50);
2022         if (ret)
2023                 return ret;
2024         if (!band_step50)
2025                 return -EINVAL;
2026         max_band50 = (int)((prev_vts - 4) / band_step50);
2027         return ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL0E, max_band50);
2028 }
2029
2030 static int ov5640_set_ae_target(struct ov5640_dev *sensor, int target)
2031 {
2032         /* stable in high */
2033         u32 fast_high, fast_low;
2034         int ret;
2035
2036         sensor->ae_low = target * 23 / 25;      /* 0.92 */
2037         sensor->ae_high = target * 27 / 25;     /* 1.08 */
2038
2039         fast_high = sensor->ae_high << 1;
2040         if (fast_high > 255)
2041                 fast_high = 255;
2042
2043         fast_low = sensor->ae_low >> 1;
2044
2045         ret = ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL0F, sensor->ae_high);
2046         if (ret)
2047                 return ret;
2048         ret = ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL10, sensor->ae_low);
2049         if (ret)
2050                 return ret;
2051         ret = ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL1B, sensor->ae_high);
2052         if (ret)
2053                 return ret;
2054         ret = ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL1E, sensor->ae_low);
2055         if (ret)
2056                 return ret;
2057         ret = ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL11, fast_high);
2058         if (ret)
2059                 return ret;
2060         return ov5640_write_reg(sensor, OV5640_REG_AEC_CTRL1F, fast_low);
2061 }
2062
2063 static int ov5640_get_binning(struct ov5640_dev *sensor)
2064 {
2065         u8 temp;
2066         int ret;
2067
2068         ret = ov5640_read_reg(sensor, OV5640_REG_TIMING_TC_REG21, &temp);
2069         if (ret)
2070                 return ret;
2071
2072         return temp & BIT(0);
2073 }
2074
2075 static int ov5640_set_binning(struct ov5640_dev *sensor, bool enable)
2076 {
2077         int ret;
2078
2079         /*
2080          * TIMING TC REG21:
2081          * - [0]:       Horizontal binning enable
2082          */
2083         ret = ov5640_mod_reg(sensor, OV5640_REG_TIMING_TC_REG21,
2084                              BIT(0), enable ? BIT(0) : 0);
2085         if (ret)
2086                 return ret;
2087         /*
2088          * TIMING TC REG20:
2089          * - [0]:       Undocumented, but hardcoded init sequences
2090          *              are always setting REG21/REG20 bit 0 to same value...
2091          */
2092         return ov5640_mod_reg(sensor, OV5640_REG_TIMING_TC_REG20,
2093                               BIT(0), enable ? BIT(0) : 0);
2094 }
2095
2096 static int ov5640_set_virtual_channel(struct ov5640_dev *sensor)
2097 {
2098         struct i2c_client *client = sensor->i2c_client;
2099         u8 temp, channel = virtual_channel;
2100         int ret;
2101
2102         if (channel > 3) {
2103                 dev_err(&client->dev,
2104                         "%s: wrong virtual_channel parameter, expected (0..3), got %d\n",
2105                         __func__, channel);
2106                 return -EINVAL;
2107         }
2108
2109         ret = ov5640_read_reg(sensor, OV5640_REG_DEBUG_MODE, &temp);
2110         if (ret)
2111                 return ret;
2112         temp &= ~(3 << 6);
2113         temp |= (channel << 6);
2114         return ov5640_write_reg(sensor, OV5640_REG_DEBUG_MODE, temp);
2115 }
2116
2117 static const struct ov5640_mode_info *
2118 ov5640_find_mode(struct ov5640_dev *sensor, int width, int height, bool nearest)
2119 {
2120         const struct ov5640_mode_info *mode;
2121
2122         mode = v4l2_find_nearest_size(ov5640_mode_data,
2123                                       ARRAY_SIZE(ov5640_mode_data),
2124                                       width, height, width, height);
2125
2126         if (!mode ||
2127             (!nearest &&
2128              (mode->width != width || mode->height != height)))
2129                 return NULL;
2130
2131         return mode;
2132 }
2133
2134 /*
2135  * sensor changes between scaling and subsampling, go through
2136  * exposure calculation
2137  */
2138 static int ov5640_set_mode_exposure_calc(struct ov5640_dev *sensor,
2139                                          const struct ov5640_mode_info *mode)
2140 {
2141         u32 prev_shutter, prev_gain16;
2142         u32 cap_shutter, cap_gain16;
2143         u32 cap_sysclk, cap_hts, cap_vts;
2144         u32 light_freq, cap_bandfilt, cap_maxband;
2145         u32 cap_gain16_shutter;
2146         u8 average;
2147         int ret;
2148
2149         if (!mode->reg_data)
2150                 return -EINVAL;
2151
2152         /* read preview shutter */
2153         ret = ov5640_get_exposure(sensor);
2154         if (ret < 0)
2155                 return ret;
2156         prev_shutter = ret;
2157         ret = ov5640_get_binning(sensor);
2158         if (ret < 0)
2159                 return ret;
2160         if (ret && mode->id != OV5640_MODE_720P_1280_720 &&
2161             mode->id != OV5640_MODE_1080P_1920_1080)
2162                 prev_shutter *= 2;
2163
2164         /* read preview gain */
2165         ret = ov5640_get_gain(sensor);
2166         if (ret < 0)
2167                 return ret;
2168         prev_gain16 = ret;
2169
2170         /* get average */
2171         ret = ov5640_read_reg(sensor, OV5640_REG_AVG_READOUT, &average);
2172         if (ret)
2173                 return ret;
2174
2175         /* turn off night mode for capture */
2176         ret = ov5640_set_night_mode(sensor);
2177         if (ret < 0)
2178                 return ret;
2179
2180         /* Write capture setting */
2181         ov5640_load_regs(sensor, mode->reg_data, mode->reg_data_size);
2182         ret = ov5640_set_timings(sensor, mode);
2183         if (ret < 0)
2184                 return ret;
2185
2186         /* read capture VTS */
2187         ret = ov5640_get_vts(sensor);
2188         if (ret < 0)
2189                 return ret;
2190         cap_vts = ret;
2191         ret = ov5640_get_hts(sensor);
2192         if (ret < 0)
2193                 return ret;
2194         if (ret == 0)
2195                 return -EINVAL;
2196         cap_hts = ret;
2197
2198         ret = ov5640_get_sysclk(sensor);
2199         if (ret < 0)
2200                 return ret;
2201         if (ret == 0)
2202                 return -EINVAL;
2203         cap_sysclk = ret;
2204
2205         /* calculate capture banding filter */
2206         ret = ov5640_get_light_freq(sensor);
2207         if (ret < 0)
2208                 return ret;
2209         light_freq = ret;
2210
2211         if (light_freq == 60) {
2212                 /* 60Hz */
2213                 cap_bandfilt = cap_sysclk * 100 / cap_hts * 100 / 120;
2214         } else {
2215                 /* 50Hz */
2216                 cap_bandfilt = cap_sysclk * 100 / cap_hts;
2217         }
2218
2219         if (!sensor->prev_sysclk) {
2220                 ret = ov5640_get_sysclk(sensor);
2221                 if (ret < 0)
2222                         return ret;
2223                 if (ret == 0)
2224                         return -EINVAL;
2225                 sensor->prev_sysclk = ret;
2226         }
2227
2228         if (!cap_bandfilt)
2229                 return -EINVAL;
2230
2231         cap_maxband = (int)((cap_vts - 4) / cap_bandfilt);
2232
2233         /* calculate capture shutter/gain16 */
2234         if (average > sensor->ae_low && average < sensor->ae_high) {
2235                 /* in stable range */
2236                 cap_gain16_shutter =
2237                         prev_gain16 * prev_shutter *
2238                         cap_sysclk / sensor->prev_sysclk *
2239                         sensor->prev_hts / cap_hts *
2240                         sensor->ae_target / average;
2241         } else {
2242                 cap_gain16_shutter =
2243                         prev_gain16 * prev_shutter *
2244                         cap_sysclk / sensor->prev_sysclk *
2245                         sensor->prev_hts / cap_hts;
2246         }
2247
2248         /* gain to shutter */
2249         if (cap_gain16_shutter < (cap_bandfilt * 16)) {
2250                 /* shutter < 1/100 */
2251                 cap_shutter = cap_gain16_shutter / 16;
2252                 if (cap_shutter < 1)
2253                         cap_shutter = 1;
2254
2255                 cap_gain16 = cap_gain16_shutter / cap_shutter;
2256                 if (cap_gain16 < 16)
2257                         cap_gain16 = 16;
2258         } else {
2259                 if (cap_gain16_shutter > (cap_bandfilt * cap_maxband * 16)) {
2260                         /* exposure reach max */
2261                         cap_shutter = cap_bandfilt * cap_maxband;
2262                         if (!cap_shutter)
2263                                 return -EINVAL;
2264
2265                         cap_gain16 = cap_gain16_shutter / cap_shutter;
2266                 } else {
2267                         /* 1/100 < (cap_shutter = n/100) =< max */
2268                         cap_shutter =
2269                                 ((int)(cap_gain16_shutter / 16 / cap_bandfilt))
2270                                 * cap_bandfilt;
2271                         if (!cap_shutter)
2272                                 return -EINVAL;
2273
2274                         cap_gain16 = cap_gain16_shutter / cap_shutter;
2275                 }
2276         }
2277
2278         /* set capture gain */
2279         ret = ov5640_set_gain(sensor, cap_gain16);
2280         if (ret)
2281                 return ret;
2282
2283         /* write capture shutter */
2284         if (cap_shutter > (cap_vts - 4)) {
2285                 cap_vts = cap_shutter + 4;
2286                 ret = ov5640_set_vts(sensor, cap_vts);
2287                 if (ret < 0)
2288                         return ret;
2289         }
2290
2291         /* set exposure */
2292         return ov5640_set_exposure(sensor, cap_shutter);
2293 }
2294
2295 /*
2296  * if sensor changes inside scaling or subsampling
2297  * change mode directly
2298  */
2299 static int ov5640_set_mode_direct(struct ov5640_dev *sensor,
2300                                   const struct ov5640_mode_info *mode)
2301 {
2302         if (!mode->reg_data)
2303                 return -EINVAL;
2304
2305         /* Write capture setting */
2306         ov5640_load_regs(sensor, mode->reg_data, mode->reg_data_size);
2307         return ov5640_set_timings(sensor, mode);
2308 }
2309
2310 static int ov5640_set_mode(struct ov5640_dev *sensor)
2311 {
2312         const struct ov5640_mode_info *mode = sensor->current_mode;
2313         const struct ov5640_mode_info *orig_mode = sensor->last_mode;
2314         enum ov5640_downsize_mode dn_mode, orig_dn_mode;
2315         bool auto_gain = sensor->ctrls.auto_gain->val == 1;
2316         bool auto_exp =  sensor->ctrls.auto_exp->val == V4L2_EXPOSURE_AUTO;
2317         int ret;
2318
2319         dn_mode = mode->dn_mode;
2320         orig_dn_mode = orig_mode->dn_mode;
2321
2322         /* auto gain and exposure must be turned off when changing modes */
2323         if (auto_gain) {
2324                 ret = ov5640_set_autogain(sensor, false);
2325                 if (ret)
2326                         return ret;
2327         }
2328
2329         if (auto_exp) {
2330                 ret = ov5640_set_autoexposure(sensor, false);
2331                 if (ret)
2332                         goto restore_auto_gain;
2333         }
2334
2335         if (ov5640_is_csi2(sensor))
2336                 ret = ov5640_set_mipi_pclk(sensor);
2337         else
2338                 ret = ov5640_set_dvp_pclk(sensor);
2339         if (ret < 0)
2340                 return 0;
2341
2342         if ((dn_mode == SUBSAMPLING && orig_dn_mode == SCALING) ||
2343             (dn_mode == SCALING && orig_dn_mode == SUBSAMPLING)) {
2344                 /*
2345                  * change between subsampling and scaling
2346                  * go through exposure calculation
2347                  */
2348                 ret = ov5640_set_mode_exposure_calc(sensor, mode);
2349         } else {
2350                 /*
2351                  * change inside subsampling or scaling
2352                  * download firmware directly
2353                  */
2354                 ret = ov5640_set_mode_direct(sensor, mode);
2355         }
2356         if (ret < 0)
2357                 goto restore_auto_exp_gain;
2358
2359         /* restore auto gain and exposure */
2360         if (auto_gain)
2361                 ov5640_set_autogain(sensor, true);
2362         if (auto_exp)
2363                 ov5640_set_autoexposure(sensor, true);
2364
2365         ret = ov5640_set_binning(sensor, dn_mode != SCALING);
2366         if (ret < 0)
2367                 return ret;
2368         ret = ov5640_set_ae_target(sensor, sensor->ae_target);
2369         if (ret < 0)
2370                 return ret;
2371         ret = ov5640_get_light_freq(sensor);
2372         if (ret < 0)
2373                 return ret;
2374         ret = ov5640_set_bandingfilter(sensor);
2375         if (ret < 0)
2376                 return ret;
2377         ret = ov5640_set_virtual_channel(sensor);
2378         if (ret < 0)
2379                 return ret;
2380
2381         sensor->pending_mode_change = false;
2382         sensor->last_mode = mode;
2383
2384         return 0;
2385
2386 restore_auto_exp_gain:
2387         if (auto_exp)
2388                 ov5640_set_autoexposure(sensor, true);
2389 restore_auto_gain:
2390         if (auto_gain)
2391                 ov5640_set_autogain(sensor, true);
2392
2393         return ret;
2394 }
2395
2396 static int ov5640_set_framefmt(struct ov5640_dev *sensor,
2397                                struct v4l2_mbus_framefmt *format);
2398
2399 /* restore the last set video mode after chip power-on */
2400 static int ov5640_restore_mode(struct ov5640_dev *sensor)
2401 {
2402         int ret;
2403
2404         /* first load the initial register values */
2405         ov5640_load_regs(sensor, ov5640_init_setting,
2406                          ARRAY_SIZE(ov5640_init_setting));
2407
2408         ret = ov5640_mod_reg(sensor, OV5640_REG_SYS_ROOT_DIVIDER, 0x3f,
2409                              (ilog2(OV5640_SCLK2X_ROOT_DIV) << 2) |
2410                              ilog2(OV5640_SCLK_ROOT_DIV));
2411         if (ret)
2412                 return ret;
2413
2414         /* now restore the last capture mode */
2415         ret = ov5640_set_mode(sensor);
2416         if (ret < 0)
2417                 return ret;
2418
2419         return ov5640_set_framefmt(sensor, &sensor->fmt);
2420 }
2421
2422 static void ov5640_power(struct ov5640_dev *sensor, bool enable)
2423 {
2424         gpiod_set_value_cansleep(sensor->pwdn_gpio, enable ? 0 : 1);
2425 }
2426
2427 /*
2428  * From section 2.7 power up sequence:
2429  * t0 + t1 + t2 >= 5ms  Delay from DOVDD stable to PWDN pull down
2430  * t3 >= 1ms            Delay from PWDN pull down to RESETB pull up
2431  * t4 >= 20ms           Delay from RESETB pull up to SCCB (i2c) stable
2432  *
2433  * Some modules don't expose RESETB/PWDN pins directly, instead providing a
2434  * "PWUP" GPIO which is wired through appropriate delays and inverters to the
2435  * pins.
2436  *
2437  * In such cases, this gpio should be mapped to pwdn_gpio in the driver, and we
2438  * should still toggle the pwdn_gpio below with the appropriate delays, while
2439  * the calls to reset_gpio will be ignored.
2440  */
2441 static void ov5640_powerup_sequence(struct ov5640_dev *sensor)
2442 {
2443         if (sensor->pwdn_gpio) {
2444                 gpiod_set_value_cansleep(sensor->reset_gpio, 1);
2445
2446                 /* camera power cycle */
2447                 ov5640_power(sensor, false);
2448                 usleep_range(5000, 10000);      /* t2 */
2449                 ov5640_power(sensor, true);
2450                 usleep_range(1000, 2000);       /* t3 */
2451
2452                 gpiod_set_value_cansleep(sensor->reset_gpio, 0);
2453         } else {
2454                 /* software reset */
2455                 ov5640_write_reg(sensor, OV5640_REG_SYS_CTRL0,
2456                                  OV5640_REG_SYS_CTRL0_SW_RST);
2457         }
2458         usleep_range(20000, 25000);     /* t4 */
2459
2460         /*
2461          * software standby: allows registers programming;
2462          * exit at restore_mode() for CSI, s_stream(1) for DVP
2463          */
2464         ov5640_write_reg(sensor, OV5640_REG_SYS_CTRL0,
2465                          OV5640_REG_SYS_CTRL0_SW_PWDN);
2466 }
2467
2468 static int ov5640_set_power_on(struct ov5640_dev *sensor)
2469 {
2470         struct i2c_client *client = sensor->i2c_client;
2471         int ret;
2472
2473         ret = clk_prepare_enable(sensor->xclk);
2474         if (ret) {
2475                 dev_err(&client->dev, "%s: failed to enable clock\n",
2476                         __func__);
2477                 return ret;
2478         }
2479
2480         ret = regulator_bulk_enable(OV5640_NUM_SUPPLIES,
2481                                     sensor->supplies);
2482         if (ret) {
2483                 dev_err(&client->dev, "%s: failed to enable regulators\n",
2484                         __func__);
2485                 goto xclk_off;
2486         }
2487
2488         ov5640_powerup_sequence(sensor);
2489
2490         ret = ov5640_init_slave_id(sensor);
2491         if (ret)
2492                 goto power_off;
2493
2494         return 0;
2495
2496 power_off:
2497         ov5640_power(sensor, false);
2498         regulator_bulk_disable(OV5640_NUM_SUPPLIES, sensor->supplies);
2499 xclk_off:
2500         clk_disable_unprepare(sensor->xclk);
2501         return ret;
2502 }
2503
2504 static void ov5640_set_power_off(struct ov5640_dev *sensor)
2505 {
2506         ov5640_power(sensor, false);
2507         regulator_bulk_disable(OV5640_NUM_SUPPLIES, sensor->supplies);
2508         clk_disable_unprepare(sensor->xclk);
2509 }
2510
2511 static int ov5640_set_power_mipi(struct ov5640_dev *sensor, bool on)
2512 {
2513         int ret;
2514
2515         if (!on) {
2516                 /* Reset MIPI bus settings to their default values. */
2517                 ov5640_write_reg(sensor, OV5640_REG_IO_MIPI_CTRL00, 0x58);
2518                 ov5640_write_reg(sensor, OV5640_REG_MIPI_CTRL00, 0x04);
2519                 ov5640_write_reg(sensor, OV5640_REG_PAD_OUTPUT00, 0x00);
2520                 return 0;
2521         }
2522
2523         /*
2524          * Power up MIPI HS Tx and LS Rx; 2 data lanes mode
2525          *
2526          * 0x300e = 0x40
2527          * [7:5] = 010  : 2 data lanes mode (see FIXME note in
2528          *                "ov5640_set_stream_mipi()")
2529          * [4] = 0      : Power up MIPI HS Tx
2530          * [3] = 0      : Power up MIPI LS Rx
2531          * [2] = 1      : MIPI interface enabled
2532          */
2533         ret = ov5640_write_reg(sensor, OV5640_REG_IO_MIPI_CTRL00, 0x44);
2534         if (ret)
2535                 return ret;
2536
2537         /*
2538          * Gate clock and set LP11 in 'no packets mode' (idle)
2539          *
2540          * 0x4800 = 0x24
2541          * [5] = 1      : Gate clock when 'no packets'
2542          * [2] = 1      : MIPI bus in LP11 when 'no packets'
2543          */
2544         ret = ov5640_write_reg(sensor, OV5640_REG_MIPI_CTRL00, 0x24);
2545         if (ret)
2546                 return ret;
2547
2548         /*
2549          * Set data lanes and clock in LP11 when 'sleeping'
2550          *
2551          * 0x3019 = 0x70
2552          * [6] = 1      : MIPI data lane 2 in LP11 when 'sleeping'
2553          * [5] = 1      : MIPI data lane 1 in LP11 when 'sleeping'
2554          * [4] = 1      : MIPI clock lane in LP11 when 'sleeping'
2555          */
2556         ret = ov5640_write_reg(sensor, OV5640_REG_PAD_OUTPUT00, 0x70);
2557         if (ret)
2558                 return ret;
2559
2560         /* Give lanes some time to coax into LP11 state. */
2561         usleep_range(500, 1000);
2562
2563         return 0;
2564 }
2565
2566 static int ov5640_set_power_dvp(struct ov5640_dev *sensor, bool on)
2567 {
2568         unsigned int flags = sensor->ep.bus.parallel.flags;
2569         bool bt656 = sensor->ep.bus_type == V4L2_MBUS_BT656;
2570         u8 polarities = 0;
2571         int ret;
2572
2573         if (!on) {
2574                 /* Reset settings to their default values. */
2575                 ov5640_write_reg(sensor, OV5640_REG_CCIR656_CTRL00, 0x00);
2576                 ov5640_write_reg(sensor, OV5640_REG_IO_MIPI_CTRL00, 0x58);
2577                 ov5640_write_reg(sensor, OV5640_REG_POLARITY_CTRL00, 0x20);
2578                 ov5640_write_reg(sensor, OV5640_REG_PAD_OUTPUT_ENABLE01, 0x00);
2579                 ov5640_write_reg(sensor, OV5640_REG_PAD_OUTPUT_ENABLE02, 0x00);
2580                 return 0;
2581         }
2582
2583         /*
2584          * Note about parallel port configuration.
2585          *
2586          * When configured in parallel mode, the OV5640 will
2587          * output 10 bits data on DVP data lines [9:0].
2588          * If only 8 bits data are wanted, the 8 bits data lines
2589          * of the camera interface must be physically connected
2590          * on the DVP data lines [9:2].
2591          *
2592          * Control lines polarity can be configured through
2593          * devicetree endpoint control lines properties.
2594          * If no endpoint control lines properties are set,
2595          * polarity will be as below:
2596          * - VSYNC:     active high
2597          * - HREF:      active low
2598          * - PCLK:      active low
2599          *
2600          * VSYNC & HREF are not configured if BT656 bus mode is selected
2601          */
2602
2603         /*
2604          * BT656 embedded synchronization configuration
2605          *
2606          * CCIR656 CTRL00
2607          * - [7]:       SYNC code selection (0: auto generate sync code,
2608          *              1: sync code from regs 0x4732-0x4735)
2609          * - [6]:       f value in CCIR656 SYNC code when fixed f value
2610          * - [5]:       Fixed f value
2611          * - [4:3]:     Blank toggle data options (00: data=1'h040/1'h200,
2612          *              01: data from regs 0x4736-0x4738, 10: always keep 0)
2613          * - [1]:       Clip data disable
2614          * - [0]:       CCIR656 mode enable
2615          *
2616          * Default CCIR656 SAV/EAV mode with default codes
2617          * SAV=0xff000080 & EAV=0xff00009d is enabled here with settings:
2618          * - CCIR656 mode enable
2619          * - auto generation of sync codes
2620          * - blank toggle data 1'h040/1'h200
2621          * - clip reserved data (0x00 & 0xff changed to 0x01 & 0xfe)
2622          */
2623         ret = ov5640_write_reg(sensor, OV5640_REG_CCIR656_CTRL00,
2624                                bt656 ? 0x01 : 0x00);
2625         if (ret)
2626                 return ret;
2627
2628         /*
2629          * configure parallel port control lines polarity
2630          *
2631          * POLARITY CTRL0
2632          * - [5]:       PCLK polarity (0: active low, 1: active high)
2633          * - [1]:       HREF polarity (0: active low, 1: active high)
2634          * - [0]:       VSYNC polarity (mismatch here between
2635          *              datasheet and hardware, 0 is active high
2636          *              and 1 is active low...)
2637          */
2638         if (!bt656) {
2639                 if (flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH)
2640                         polarities |= BIT(1);
2641                 if (flags & V4L2_MBUS_VSYNC_ACTIVE_LOW)
2642                         polarities |= BIT(0);
2643         }
2644         if (flags & V4L2_MBUS_PCLK_SAMPLE_RISING)
2645                 polarities |= BIT(5);
2646
2647         ret = ov5640_write_reg(sensor, OV5640_REG_POLARITY_CTRL00, polarities);
2648         if (ret)
2649                 return ret;
2650
2651         /*
2652          * powerdown MIPI TX/RX PHY & enable DVP
2653          *
2654          * MIPI CONTROL 00
2655          * [4] = 1      : Power down MIPI HS Tx
2656          * [3] = 1      : Power down MIPI LS Rx
2657          * [2] = 0      : DVP enable (MIPI disable)
2658          */
2659         ret = ov5640_write_reg(sensor, OV5640_REG_IO_MIPI_CTRL00, 0x18);
2660         if (ret)
2661                 return ret;
2662
2663         /*
2664          * enable VSYNC/HREF/PCLK DVP control lines
2665          * & D[9:6] DVP data lines
2666          *
2667          * PAD OUTPUT ENABLE 01
2668          * - 6:         VSYNC output enable
2669          * - 5:         HREF output enable
2670          * - 4:         PCLK output enable
2671          * - [3:0]:     D[9:6] output enable
2672          */
2673         ret = ov5640_write_reg(sensor, OV5640_REG_PAD_OUTPUT_ENABLE01,
2674                                bt656 ? 0x1f : 0x7f);
2675         if (ret)
2676                 return ret;
2677
2678         /*
2679          * enable D[5:0] DVP data lines
2680          *
2681          * PAD OUTPUT ENABLE 02
2682          * - [7:2]:     D[5:0] output enable
2683          */
2684         return ov5640_write_reg(sensor, OV5640_REG_PAD_OUTPUT_ENABLE02, 0xfc);
2685 }
2686
2687 static int ov5640_set_power(struct ov5640_dev *sensor, bool on)
2688 {
2689         int ret = 0;
2690
2691         if (on) {
2692                 ret = ov5640_set_power_on(sensor);
2693                 if (ret)
2694                         return ret;
2695
2696                 ret = ov5640_restore_mode(sensor);
2697                 if (ret)
2698                         goto power_off;
2699         }
2700
2701         if (sensor->ep.bus_type == V4L2_MBUS_CSI2_DPHY)
2702                 ret = ov5640_set_power_mipi(sensor, on);
2703         else
2704                 ret = ov5640_set_power_dvp(sensor, on);
2705         if (ret)
2706                 goto power_off;
2707
2708         if (!on)
2709                 ov5640_set_power_off(sensor);
2710
2711         return 0;
2712
2713 power_off:
2714         ov5640_set_power_off(sensor);
2715         return ret;
2716 }
2717
2718 static int ov5640_sensor_suspend(struct device *dev)
2719 {
2720         struct v4l2_subdev *sd = dev_get_drvdata(dev);
2721         struct ov5640_dev *ov5640 = to_ov5640_dev(sd);
2722
2723         return ov5640_set_power(ov5640, false);
2724 }
2725
2726 static int ov5640_sensor_resume(struct device *dev)
2727 {
2728         struct v4l2_subdev *sd = dev_get_drvdata(dev);
2729         struct ov5640_dev *ov5640 = to_ov5640_dev(sd);
2730
2731         return ov5640_set_power(ov5640, true);
2732 }
2733
2734 /* --------------- Subdev Operations --------------- */
2735
2736 static int ov5640_try_frame_interval(struct ov5640_dev *sensor,
2737                                      struct v4l2_fract *fi,
2738                                      u32 width, u32 height)
2739 {
2740         const struct ov5640_mode_info *mode;
2741         enum ov5640_frame_rate rate = OV5640_15_FPS;
2742         int minfps, maxfps, best_fps, fps;
2743         int i;
2744
2745         minfps = ov5640_framerates[OV5640_15_FPS];
2746         maxfps = ov5640_framerates[OV5640_60_FPS];
2747
2748         if (fi->numerator == 0) {
2749                 fi->denominator = maxfps;
2750                 fi->numerator = 1;
2751                 rate = OV5640_60_FPS;
2752                 goto find_mode;
2753         }
2754
2755         fps = clamp_val(DIV_ROUND_CLOSEST(fi->denominator, fi->numerator),
2756                         minfps, maxfps);
2757
2758         best_fps = minfps;
2759         for (i = 0; i < ARRAY_SIZE(ov5640_framerates); i++) {
2760                 int curr_fps = ov5640_framerates[i];
2761
2762                 if (abs(curr_fps - fps) < abs(best_fps - fps)) {
2763                         best_fps = curr_fps;
2764                         rate = i;
2765                 }
2766         }
2767
2768         fi->numerator = 1;
2769         fi->denominator = best_fps;
2770
2771 find_mode:
2772         mode = ov5640_find_mode(sensor, width, height, false);
2773         return mode ? rate : -EINVAL;
2774 }
2775
2776 static int ov5640_get_fmt(struct v4l2_subdev *sd,
2777                           struct v4l2_subdev_state *sd_state,
2778                           struct v4l2_subdev_format *format)
2779 {
2780         struct ov5640_dev *sensor = to_ov5640_dev(sd);
2781         struct v4l2_mbus_framefmt *fmt;
2782
2783         if (format->pad != 0)
2784                 return -EINVAL;
2785
2786         mutex_lock(&sensor->lock);
2787
2788         if (format->which == V4L2_SUBDEV_FORMAT_TRY)
2789                 fmt = v4l2_subdev_get_try_format(&sensor->sd, sd_state,
2790                                                  format->pad);
2791         else
2792                 fmt = &sensor->fmt;
2793
2794         format->format = *fmt;
2795
2796         mutex_unlock(&sensor->lock);
2797
2798         return 0;
2799 }
2800
2801 static int ov5640_try_fmt_internal(struct v4l2_subdev *sd,
2802                                    struct v4l2_mbus_framefmt *fmt,
2803                                    enum ov5640_frame_rate fr,
2804                                    const struct ov5640_mode_info **new_mode)
2805 {
2806         struct ov5640_dev *sensor = to_ov5640_dev(sd);
2807         const struct ov5640_mode_info *mode;
2808         const struct ov5640_pixfmt *pixfmt;
2809         unsigned int bpp;
2810
2811         mode = ov5640_find_mode(sensor, fmt->width, fmt->height, true);
2812         if (!mode)
2813                 return -EINVAL;
2814
2815         pixfmt = ov5640_code_to_pixfmt(sensor, fmt->code);
2816         bpp = pixfmt->bpp;
2817
2818         /*
2819          * Adjust mode according to bpp:
2820          * - 8bpp modes work for resolution >= 1280x720
2821          * - 24bpp modes work resolution < 1280x720
2822          */
2823         if (bpp == 8 && mode->width < 1280)
2824                 mode = &ov5640_mode_data[OV5640_MODE_720P_1280_720];
2825         else if (bpp == 24 && mode->width > 1024)
2826                 mode = &ov5640_mode_data[OV5640_MODE_XGA_1024_768];
2827
2828         fmt->width = mode->width;
2829         fmt->height = mode->height;
2830
2831         if (new_mode)
2832                 *new_mode = mode;
2833
2834         fmt->code = pixfmt->code;
2835         fmt->colorspace = pixfmt->colorspace;
2836         fmt->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(fmt->colorspace);
2837         fmt->quantization = V4L2_QUANTIZATION_FULL_RANGE;
2838         fmt->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(fmt->colorspace);
2839
2840         return 0;
2841 }
2842
2843 static void __v4l2_ctrl_vblank_update(struct ov5640_dev *sensor, u32 vblank)
2844 {
2845         const struct ov5640_mode_info *mode = sensor->current_mode;
2846
2847         __v4l2_ctrl_modify_range(sensor->ctrls.vblank, OV5640_MIN_VBLANK,
2848                                  OV5640_MAX_VTS - mode->height, 1, vblank);
2849
2850         __v4l2_ctrl_s_ctrl(sensor->ctrls.vblank, vblank);
2851 }
2852
2853 static int ov5640_update_pixel_rate(struct ov5640_dev *sensor)
2854 {
2855         const struct ov5640_mode_info *mode = sensor->current_mode;
2856         enum ov5640_pixel_rate_id pixel_rate_id = mode->pixel_rate;
2857         struct v4l2_mbus_framefmt *fmt = &sensor->fmt;
2858         const struct ov5640_timings *timings = ov5640_timings(sensor, mode);
2859         s32 exposure_val, exposure_max;
2860         unsigned int hblank;
2861         unsigned int i = 0;
2862         u32 pixel_rate;
2863         s64 link_freq;
2864         u32 num_lanes;
2865         u32 vblank;
2866         u32 bpp;
2867
2868         /*
2869          * Update the pixel rate control value.
2870          *
2871          * For DVP mode, maintain the pixel rate calculation using fixed FPS.
2872          */
2873         if (!ov5640_is_csi2(sensor)) {
2874                 __v4l2_ctrl_s_ctrl_int64(sensor->ctrls.pixel_rate,
2875                                          ov5640_calc_pixel_rate(sensor));
2876
2877                 __v4l2_ctrl_vblank_update(sensor, timings->vblank_def);
2878
2879                 return 0;
2880         }
2881
2882         /*
2883          * The MIPI CSI-2 link frequency should comply with the CSI-2
2884          * specification and be lower than 1GHz.
2885          *
2886          * Start from the suggested pixel_rate for the current mode and
2887          * progressively slow it down if it exceeds 1GHz.
2888          */
2889         num_lanes = sensor->ep.bus.mipi_csi2.num_data_lanes;
2890         bpp = ov5640_code_to_bpp(sensor, fmt->code);
2891         do {
2892                 pixel_rate = ov5640_pixel_rates[pixel_rate_id];
2893                 link_freq = pixel_rate * bpp / (2 * num_lanes);
2894         } while (link_freq >= 1000000000U &&
2895                  ++pixel_rate_id < OV5640_NUM_PIXEL_RATES);
2896
2897         sensor->current_link_freq = link_freq;
2898
2899         /*
2900          * Higher link rates require the clock tree to be programmed with
2901          * 'mipi_div' = 1; this has the effect of halving the actual output
2902          * pixel rate in the MIPI domain.
2903          *
2904          * Adjust the pixel rate and link frequency control value to report it
2905          * correctly to userspace.
2906          */
2907         if (link_freq > OV5640_LINK_RATE_MAX) {
2908                 pixel_rate /= 2;
2909                 link_freq /= 2;
2910         }
2911
2912         for (i = 0; i < ARRAY_SIZE(ov5640_csi2_link_freqs); ++i) {
2913                 if (ov5640_csi2_link_freqs[i] == link_freq)
2914                         break;
2915         }
2916         WARN_ON(i == ARRAY_SIZE(ov5640_csi2_link_freqs));
2917
2918         __v4l2_ctrl_s_ctrl_int64(sensor->ctrls.pixel_rate, pixel_rate);
2919         __v4l2_ctrl_s_ctrl(sensor->ctrls.link_freq, i);
2920
2921         hblank = timings->htot - mode->width;
2922         __v4l2_ctrl_modify_range(sensor->ctrls.hblank,
2923                                  hblank, hblank, 1, hblank);
2924
2925         vblank = timings->vblank_def;
2926         __v4l2_ctrl_vblank_update(sensor, vblank);
2927
2928         exposure_max = timings->crop.height + vblank - 4;
2929         exposure_val = clamp_t(s32, sensor->ctrls.exposure->val,
2930                                sensor->ctrls.exposure->minimum,
2931                                exposure_max);
2932
2933         __v4l2_ctrl_modify_range(sensor->ctrls.exposure,
2934                                  sensor->ctrls.exposure->minimum,
2935                                  exposure_max, 1, exposure_val);
2936
2937         return 0;
2938 }
2939
2940 static int ov5640_set_fmt(struct v4l2_subdev *sd,
2941                           struct v4l2_subdev_state *sd_state,
2942                           struct v4l2_subdev_format *format)
2943 {
2944         struct ov5640_dev *sensor = to_ov5640_dev(sd);
2945         const struct ov5640_mode_info *new_mode;
2946         struct v4l2_mbus_framefmt *mbus_fmt = &format->format;
2947         int ret;
2948
2949         if (format->pad != 0)
2950                 return -EINVAL;
2951
2952         mutex_lock(&sensor->lock);
2953
2954         if (sensor->streaming) {
2955                 ret = -EBUSY;
2956                 goto out;
2957         }
2958
2959         ret = ov5640_try_fmt_internal(sd, mbus_fmt,
2960                                       sensor->current_fr, &new_mode);
2961         if (ret)
2962                 goto out;
2963
2964         if (format->which == V4L2_SUBDEV_FORMAT_TRY) {
2965                 *v4l2_subdev_get_try_format(sd, sd_state, 0) = *mbus_fmt;
2966                 goto out;
2967         }
2968
2969         if (new_mode != sensor->current_mode) {
2970                 sensor->current_fr = new_mode->def_fps;
2971                 sensor->current_mode = new_mode;
2972                 sensor->pending_mode_change = true;
2973         }
2974         if (mbus_fmt->code != sensor->fmt.code)
2975                 sensor->pending_fmt_change = true;
2976
2977         /* update format even if code is unchanged, resolution might change */
2978         sensor->fmt = *mbus_fmt;
2979
2980         ov5640_update_pixel_rate(sensor);
2981
2982 out:
2983         mutex_unlock(&sensor->lock);
2984         return ret;
2985 }
2986
2987 static int ov5640_get_selection(struct v4l2_subdev *sd,
2988                                 struct v4l2_subdev_state *sd_state,
2989                                 struct v4l2_subdev_selection *sel)
2990 {
2991         struct ov5640_dev *sensor = to_ov5640_dev(sd);
2992         const struct ov5640_mode_info *mode = sensor->current_mode;
2993         const struct ov5640_timings *timings;
2994
2995         switch (sel->target) {
2996         case V4L2_SEL_TGT_CROP: {
2997                 mutex_lock(&sensor->lock);
2998                 timings = ov5640_timings(sensor, mode);
2999                 sel->r = timings->analog_crop;
3000                 mutex_unlock(&sensor->lock);
3001
3002                 return 0;
3003         }
3004
3005         case V4L2_SEL_TGT_NATIVE_SIZE:
3006         case V4L2_SEL_TGT_CROP_BOUNDS:
3007                 sel->r.top = 0;
3008                 sel->r.left = 0;
3009                 sel->r.width = OV5640_NATIVE_WIDTH;
3010                 sel->r.height = OV5640_NATIVE_HEIGHT;
3011
3012                 return 0;
3013
3014         case V4L2_SEL_TGT_CROP_DEFAULT:
3015                 sel->r.top = OV5640_PIXEL_ARRAY_TOP;
3016                 sel->r.left = OV5640_PIXEL_ARRAY_LEFT;
3017                 sel->r.width = OV5640_PIXEL_ARRAY_WIDTH;
3018                 sel->r.height = OV5640_PIXEL_ARRAY_HEIGHT;
3019
3020                 return 0;
3021         }
3022
3023         return -EINVAL;
3024 }
3025
3026 static int ov5640_set_framefmt(struct ov5640_dev *sensor,
3027                                struct v4l2_mbus_framefmt *format)
3028 {
3029         bool is_jpeg = format->code == MEDIA_BUS_FMT_JPEG_1X8;
3030         const struct ov5640_pixfmt *pixfmt;
3031         int ret = 0;
3032
3033         pixfmt = ov5640_code_to_pixfmt(sensor, format->code);
3034
3035         /* FORMAT CONTROL00: YUV and RGB formatting */
3036         ret = ov5640_write_reg(sensor, OV5640_REG_FORMAT_CONTROL00,
3037                                pixfmt->ctrl00);
3038         if (ret)
3039                 return ret;
3040
3041         /* FORMAT MUX CONTROL: ISP YUV or RGB */
3042         ret = ov5640_write_reg(sensor, OV5640_REG_ISP_FORMAT_MUX_CTRL,
3043                                pixfmt->mux);
3044         if (ret)
3045                 return ret;
3046
3047         /*
3048          * TIMING TC REG21:
3049          * - [5]:       JPEG enable
3050          */
3051         ret = ov5640_mod_reg(sensor, OV5640_REG_TIMING_TC_REG21,
3052                              BIT(5), is_jpeg ? BIT(5) : 0);
3053         if (ret)
3054                 return ret;
3055
3056         /*
3057          * SYSTEM RESET02:
3058          * - [4]:       Reset JFIFO
3059          * - [3]:       Reset SFIFO
3060          * - [2]:       Reset JPEG
3061          */
3062         ret = ov5640_mod_reg(sensor, OV5640_REG_SYS_RESET02,
3063                              BIT(4) | BIT(3) | BIT(2),
3064                              is_jpeg ? 0 : (BIT(4) | BIT(3) | BIT(2)));
3065         if (ret)
3066                 return ret;
3067
3068         /*
3069          * CLOCK ENABLE02:
3070          * - [5]:       Enable JPEG 2x clock
3071          * - [3]:       Enable JPEG clock
3072          */
3073         return ov5640_mod_reg(sensor, OV5640_REG_SYS_CLOCK_ENABLE02,
3074                               BIT(5) | BIT(3),
3075                               is_jpeg ? (BIT(5) | BIT(3)) : 0);
3076 }
3077
3078 /*
3079  * Sensor Controls.
3080  */
3081
3082 static int ov5640_set_ctrl_hue(struct ov5640_dev *sensor, int value)
3083 {
3084         int ret;
3085
3086         if (value) {
3087                 ret = ov5640_mod_reg(sensor, OV5640_REG_SDE_CTRL0,
3088                                      BIT(0), BIT(0));
3089                 if (ret)
3090                         return ret;
3091                 ret = ov5640_write_reg16(sensor, OV5640_REG_SDE_CTRL1, value);
3092         } else {
3093                 ret = ov5640_mod_reg(sensor, OV5640_REG_SDE_CTRL0, BIT(0), 0);
3094         }
3095
3096         return ret;
3097 }
3098
3099 static int ov5640_set_ctrl_contrast(struct ov5640_dev *sensor, int value)
3100 {
3101         int ret;
3102
3103         if (value) {
3104                 ret = ov5640_mod_reg(sensor, OV5640_REG_SDE_CTRL0,
3105                                      BIT(2), BIT(2));
3106                 if (ret)
3107                         return ret;
3108                 ret = ov5640_write_reg(sensor, OV5640_REG_SDE_CTRL5,
3109                                        value & 0xff);
3110         } else {
3111                 ret = ov5640_mod_reg(sensor, OV5640_REG_SDE_CTRL0, BIT(2), 0);
3112         }
3113
3114         return ret;
3115 }
3116
3117 static int ov5640_set_ctrl_saturation(struct ov5640_dev *sensor, int value)
3118 {
3119         int ret;
3120
3121         if (value) {
3122                 ret = ov5640_mod_reg(sensor, OV5640_REG_SDE_CTRL0,
3123                                      BIT(1), BIT(1));
3124                 if (ret)
3125                         return ret;
3126                 ret = ov5640_write_reg(sensor, OV5640_REG_SDE_CTRL3,
3127                                        value & 0xff);
3128                 if (ret)
3129                         return ret;
3130                 ret = ov5640_write_reg(sensor, OV5640_REG_SDE_CTRL4,
3131                                        value & 0xff);
3132         } else {
3133                 ret = ov5640_mod_reg(sensor, OV5640_REG_SDE_CTRL0, BIT(1), 0);
3134         }
3135
3136         return ret;
3137 }
3138
3139 static int ov5640_set_ctrl_white_balance(struct ov5640_dev *sensor, int awb)
3140 {
3141         int ret;
3142
3143         ret = ov5640_mod_reg(sensor, OV5640_REG_AWB_MANUAL_CTRL,
3144                              BIT(0), awb ? 0 : 1);
3145         if (ret)
3146                 return ret;
3147
3148         if (!awb) {
3149                 u16 red = (u16)sensor->ctrls.red_balance->val;
3150                 u16 blue = (u16)sensor->ctrls.blue_balance->val;
3151
3152                 ret = ov5640_write_reg16(sensor, OV5640_REG_AWB_R_GAIN, red);
3153                 if (ret)
3154                         return ret;
3155                 ret = ov5640_write_reg16(sensor, OV5640_REG_AWB_B_GAIN, blue);
3156         }
3157
3158         return ret;
3159 }
3160
3161 static int ov5640_set_ctrl_exposure(struct ov5640_dev *sensor,
3162                                     enum v4l2_exposure_auto_type auto_exposure)
3163 {
3164         struct ov5640_ctrls *ctrls = &sensor->ctrls;
3165         bool auto_exp = (auto_exposure == V4L2_EXPOSURE_AUTO);
3166         int ret = 0;
3167
3168         if (ctrls->auto_exp->is_new) {
3169                 ret = ov5640_set_autoexposure(sensor, auto_exp);
3170                 if (ret)
3171                         return ret;
3172         }
3173
3174         if (!auto_exp && ctrls->exposure->is_new) {
3175                 u16 max_exp;
3176
3177                 ret = ov5640_read_reg16(sensor, OV5640_REG_AEC_PK_VTS,
3178                                         &max_exp);
3179                 if (ret)
3180                         return ret;
3181                 ret = ov5640_get_vts(sensor);
3182                 if (ret < 0)
3183                         return ret;
3184                 max_exp += ret;
3185                 ret = 0;
3186
3187                 if (ctrls->exposure->val < max_exp)
3188                         ret = ov5640_set_exposure(sensor, ctrls->exposure->val);
3189         }
3190
3191         return ret;
3192 }
3193
3194 static int ov5640_set_ctrl_gain(struct ov5640_dev *sensor, bool auto_gain)
3195 {
3196         struct ov5640_ctrls *ctrls = &sensor->ctrls;
3197         int ret = 0;
3198
3199         if (ctrls->auto_gain->is_new) {
3200                 ret = ov5640_set_autogain(sensor, auto_gain);
3201                 if (ret)
3202                         return ret;
3203         }
3204
3205         if (!auto_gain && ctrls->gain->is_new)
3206                 ret = ov5640_set_gain(sensor, ctrls->gain->val);
3207
3208         return ret;
3209 }
3210
3211 static const char * const test_pattern_menu[] = {
3212         "Disabled",
3213         "Color bars",
3214         "Color bars w/ rolling bar",
3215         "Color squares",
3216         "Color squares w/ rolling bar",
3217 };
3218
3219 #define OV5640_TEST_ENABLE              BIT(7)
3220 #define OV5640_TEST_ROLLING             BIT(6)  /* rolling horizontal bar */
3221 #define OV5640_TEST_TRANSPARENT         BIT(5)
3222 #define OV5640_TEST_SQUARE_BW           BIT(4)  /* black & white squares */
3223 #define OV5640_TEST_BAR_STANDARD        (0 << 2)
3224 #define OV5640_TEST_BAR_VERT_CHANGE_1   (1 << 2)
3225 #define OV5640_TEST_BAR_HOR_CHANGE      (2 << 2)
3226 #define OV5640_TEST_BAR_VERT_CHANGE_2   (3 << 2)
3227 #define OV5640_TEST_BAR                 (0 << 0)
3228 #define OV5640_TEST_RANDOM              (1 << 0)
3229 #define OV5640_TEST_SQUARE              (2 << 0)
3230 #define OV5640_TEST_BLACK               (3 << 0)
3231
3232 static const u8 test_pattern_val[] = {
3233         0,
3234         OV5640_TEST_ENABLE | OV5640_TEST_BAR_VERT_CHANGE_1 |
3235                 OV5640_TEST_BAR,
3236         OV5640_TEST_ENABLE | OV5640_TEST_ROLLING |
3237                 OV5640_TEST_BAR_VERT_CHANGE_1 | OV5640_TEST_BAR,
3238         OV5640_TEST_ENABLE | OV5640_TEST_SQUARE,
3239         OV5640_TEST_ENABLE | OV5640_TEST_ROLLING | OV5640_TEST_SQUARE,
3240 };
3241
3242 static int ov5640_set_ctrl_test_pattern(struct ov5640_dev *sensor, int value)
3243 {
3244         return ov5640_write_reg(sensor, OV5640_REG_PRE_ISP_TEST_SET1,
3245                                 test_pattern_val[value]);
3246 }
3247
3248 static int ov5640_set_ctrl_light_freq(struct ov5640_dev *sensor, int value)
3249 {
3250         int ret;
3251
3252         ret = ov5640_mod_reg(sensor, OV5640_REG_HZ5060_CTRL01, BIT(7),
3253                              (value == V4L2_CID_POWER_LINE_FREQUENCY_AUTO) ?
3254                              0 : BIT(7));
3255         if (ret)
3256                 return ret;
3257
3258         return ov5640_mod_reg(sensor, OV5640_REG_HZ5060_CTRL00, BIT(2),
3259                               (value == V4L2_CID_POWER_LINE_FREQUENCY_50HZ) ?
3260                               BIT(2) : 0);
3261 }
3262
3263 static int ov5640_set_ctrl_hflip(struct ov5640_dev *sensor, int value)
3264 {
3265         /*
3266          * If sensor is mounted upside down, mirror logic is inversed.
3267          *
3268          * Sensor is a BSI (Back Side Illuminated) one,
3269          * so image captured is physically mirrored.
3270          * This is why mirror logic is inversed in
3271          * order to cancel this mirror effect.
3272          */
3273
3274         /*
3275          * TIMING TC REG21:
3276          * - [2]:       ISP mirror
3277          * - [1]:       Sensor mirror
3278          */
3279         return ov5640_mod_reg(sensor, OV5640_REG_TIMING_TC_REG21,
3280                               BIT(2) | BIT(1),
3281                               (!(value ^ sensor->upside_down)) ?
3282                               (BIT(2) | BIT(1)) : 0);
3283 }
3284
3285 static int ov5640_set_ctrl_vflip(struct ov5640_dev *sensor, int value)
3286 {
3287         /* If sensor is mounted upside down, flip logic is inversed */
3288
3289         /*
3290          * TIMING TC REG20:
3291          * - [2]:       ISP vflip
3292          * - [1]:       Sensor vflip
3293          */
3294         return ov5640_mod_reg(sensor, OV5640_REG_TIMING_TC_REG20,
3295                               BIT(2) | BIT(1),
3296                               (value ^ sensor->upside_down) ?
3297                               (BIT(2) | BIT(1)) : 0);
3298 }
3299
3300 static int ov5640_set_ctrl_vblank(struct ov5640_dev *sensor, int value)
3301 {
3302         const struct ov5640_mode_info *mode = sensor->current_mode;
3303
3304         /* Update the VTOT timing register value. */
3305         return ov5640_write_reg16(sensor, OV5640_REG_TIMING_VTS,
3306                                   mode->height + value);
3307 }
3308
3309 static int ov5640_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
3310 {
3311         struct v4l2_subdev *sd = ctrl_to_sd(ctrl);
3312         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3313         int val;
3314
3315         /* v4l2_ctrl_lock() locks our own mutex */
3316
3317         if (!pm_runtime_get_if_in_use(&sensor->i2c_client->dev))
3318                 return 0;
3319
3320         switch (ctrl->id) {
3321         case V4L2_CID_AUTOGAIN:
3322                 val = ov5640_get_gain(sensor);
3323                 if (val < 0)
3324                         return val;
3325                 sensor->ctrls.gain->val = val;
3326                 break;
3327         case V4L2_CID_EXPOSURE_AUTO:
3328                 val = ov5640_get_exposure(sensor);
3329                 if (val < 0)
3330                         return val;
3331                 sensor->ctrls.exposure->val = val;
3332                 break;
3333         }
3334
3335         pm_runtime_put_autosuspend(&sensor->i2c_client->dev);
3336
3337         return 0;
3338 }
3339
3340 static int ov5640_s_ctrl(struct v4l2_ctrl *ctrl)
3341 {
3342         struct v4l2_subdev *sd = ctrl_to_sd(ctrl);
3343         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3344         const struct ov5640_mode_info *mode = sensor->current_mode;
3345         const struct ov5640_timings *timings;
3346         unsigned int exp_max;
3347         int ret;
3348
3349         /* v4l2_ctrl_lock() locks our own mutex */
3350
3351         switch (ctrl->id) {
3352         case V4L2_CID_VBLANK:
3353                 /* Update the exposure range to the newly programmed vblank. */
3354                 timings = ov5640_timings(sensor, mode);
3355                 exp_max = mode->height + ctrl->val - 4;
3356                 __v4l2_ctrl_modify_range(sensor->ctrls.exposure,
3357                                          sensor->ctrls.exposure->minimum,
3358                                          exp_max, sensor->ctrls.exposure->step,
3359                                          timings->vblank_def);
3360                 break;
3361         }
3362
3363         /*
3364          * If the device is not powered up by the host driver do
3365          * not apply any controls to H/W at this time. Instead
3366          * the controls will be restored at start streaming time.
3367          */
3368         if (!pm_runtime_get_if_in_use(&sensor->i2c_client->dev))
3369                 return 0;
3370
3371         switch (ctrl->id) {
3372         case V4L2_CID_AUTOGAIN:
3373                 ret = ov5640_set_ctrl_gain(sensor, ctrl->val);
3374                 break;
3375         case V4L2_CID_EXPOSURE_AUTO:
3376                 ret = ov5640_set_ctrl_exposure(sensor, ctrl->val);
3377                 break;
3378         case V4L2_CID_AUTO_WHITE_BALANCE:
3379                 ret = ov5640_set_ctrl_white_balance(sensor, ctrl->val);
3380                 break;
3381         case V4L2_CID_HUE:
3382                 ret = ov5640_set_ctrl_hue(sensor, ctrl->val);
3383                 break;
3384         case V4L2_CID_CONTRAST:
3385                 ret = ov5640_set_ctrl_contrast(sensor, ctrl->val);
3386                 break;
3387         case V4L2_CID_SATURATION:
3388                 ret = ov5640_set_ctrl_saturation(sensor, ctrl->val);
3389                 break;
3390         case V4L2_CID_TEST_PATTERN:
3391                 ret = ov5640_set_ctrl_test_pattern(sensor, ctrl->val);
3392                 break;
3393         case V4L2_CID_POWER_LINE_FREQUENCY:
3394                 ret = ov5640_set_ctrl_light_freq(sensor, ctrl->val);
3395                 break;
3396         case V4L2_CID_HFLIP:
3397                 ret = ov5640_set_ctrl_hflip(sensor, ctrl->val);
3398                 break;
3399         case V4L2_CID_VFLIP:
3400                 ret = ov5640_set_ctrl_vflip(sensor, ctrl->val);
3401                 break;
3402         case V4L2_CID_VBLANK:
3403                 ret = ov5640_set_ctrl_vblank(sensor, ctrl->val);
3404                 break;
3405         default:
3406                 ret = -EINVAL;
3407                 break;
3408         }
3409
3410         pm_runtime_put_autosuspend(&sensor->i2c_client->dev);
3411
3412         return ret;
3413 }
3414
3415 static const struct v4l2_ctrl_ops ov5640_ctrl_ops = {
3416         .g_volatile_ctrl = ov5640_g_volatile_ctrl,
3417         .s_ctrl = ov5640_s_ctrl,
3418 };
3419
3420 static int ov5640_init_controls(struct ov5640_dev *sensor)
3421 {
3422         const struct ov5640_mode_info *mode = sensor->current_mode;
3423         const struct v4l2_ctrl_ops *ops = &ov5640_ctrl_ops;
3424         struct ov5640_ctrls *ctrls = &sensor->ctrls;
3425         struct v4l2_ctrl_handler *hdl = &ctrls->handler;
3426         struct v4l2_fwnode_device_properties props;
3427         const struct ov5640_timings *timings;
3428         unsigned int max_vblank;
3429         unsigned int hblank;
3430         int ret;
3431
3432         v4l2_ctrl_handler_init(hdl, 32);
3433
3434         /* we can use our own mutex for the ctrl lock */
3435         hdl->lock = &sensor->lock;
3436
3437         /* Clock related controls */
3438         ctrls->pixel_rate = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_PIXEL_RATE,
3439                               ov5640_pixel_rates[OV5640_NUM_PIXEL_RATES - 1],
3440                               ov5640_pixel_rates[0], 1,
3441                               ov5640_pixel_rates[mode->pixel_rate]);
3442
3443         ctrls->link_freq = v4l2_ctrl_new_int_menu(hdl, ops,
3444                                         V4L2_CID_LINK_FREQ,
3445                                         ARRAY_SIZE(ov5640_csi2_link_freqs) - 1,
3446                                         OV5640_DEFAULT_LINK_FREQ,
3447                                         ov5640_csi2_link_freqs);
3448
3449         timings = ov5640_timings(sensor, mode);
3450         hblank = timings->htot - mode->width;
3451         ctrls->hblank = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_HBLANK, hblank,
3452                                           hblank, 1, hblank);
3453
3454         max_vblank = OV5640_MAX_VTS - mode->height;
3455         ctrls->vblank = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_VBLANK,
3456                                           OV5640_MIN_VBLANK, max_vblank,
3457                                           1, timings->vblank_def);
3458
3459         /* Auto/manual white balance */
3460         ctrls->auto_wb = v4l2_ctrl_new_std(hdl, ops,
3461                                            V4L2_CID_AUTO_WHITE_BALANCE,
3462                                            0, 1, 1, 1);
3463         ctrls->blue_balance = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BLUE_BALANCE,
3464                                                 0, 4095, 1, 0);
3465         ctrls->red_balance = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_RED_BALANCE,
3466                                                0, 4095, 1, 0);
3467         /* Auto/manual exposure */
3468         ctrls->auto_exp = v4l2_ctrl_new_std_menu(hdl, ops,
3469                                                  V4L2_CID_EXPOSURE_AUTO,
3470                                                  V4L2_EXPOSURE_MANUAL, 0,
3471                                                  V4L2_EXPOSURE_AUTO);
3472         ctrls->exposure = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_EXPOSURE,
3473                                             0, 65535, 1, 0);
3474         /* Auto/manual gain */
3475         ctrls->auto_gain = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_AUTOGAIN,
3476                                              0, 1, 1, 1);
3477         ctrls->gain = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_ANALOGUE_GAIN,
3478                                         0, 1023, 1, 0);
3479
3480         ctrls->saturation = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SATURATION,
3481                                               0, 255, 1, 64);
3482         ctrls->hue = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_HUE,
3483                                        0, 359, 1, 0);
3484         ctrls->contrast = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_CONTRAST,
3485                                             0, 255, 1, 0);
3486         ctrls->test_pattern =
3487                 v4l2_ctrl_new_std_menu_items(hdl, ops, V4L2_CID_TEST_PATTERN,
3488                                              ARRAY_SIZE(test_pattern_menu) - 1,
3489                                              0, 0, test_pattern_menu);
3490         ctrls->hflip = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_HFLIP,
3491                                          0, 1, 1, 0);
3492         ctrls->vflip = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_VFLIP,
3493                                          0, 1, 1, 0);
3494
3495         ctrls->light_freq =
3496                 v4l2_ctrl_new_std_menu(hdl, ops,
3497                                        V4L2_CID_POWER_LINE_FREQUENCY,
3498                                        V4L2_CID_POWER_LINE_FREQUENCY_AUTO, 0,
3499                                        V4L2_CID_POWER_LINE_FREQUENCY_50HZ);
3500
3501         if (hdl->error) {
3502                 ret = hdl->error;
3503                 goto free_ctrls;
3504         }
3505
3506         ret = v4l2_fwnode_device_parse(&sensor->i2c_client->dev, &props);
3507         if (ret)
3508                 goto free_ctrls;
3509
3510         if (props.rotation == 180)
3511                 sensor->upside_down = true;
3512
3513         ret = v4l2_ctrl_new_fwnode_properties(hdl, ops, &props);
3514         if (ret)
3515                 goto free_ctrls;
3516
3517         ctrls->pixel_rate->flags |= V4L2_CTRL_FLAG_READ_ONLY;
3518         ctrls->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY;
3519         ctrls->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY;
3520         ctrls->gain->flags |= V4L2_CTRL_FLAG_VOLATILE;
3521         ctrls->exposure->flags |= V4L2_CTRL_FLAG_VOLATILE;
3522
3523         v4l2_ctrl_auto_cluster(3, &ctrls->auto_wb, 0, false);
3524         v4l2_ctrl_auto_cluster(2, &ctrls->auto_gain, 0, true);
3525         v4l2_ctrl_auto_cluster(2, &ctrls->auto_exp, 1, true);
3526
3527         sensor->sd.ctrl_handler = hdl;
3528         return 0;
3529
3530 free_ctrls:
3531         v4l2_ctrl_handler_free(hdl);
3532         return ret;
3533 }
3534
3535 static int ov5640_enum_frame_size(struct v4l2_subdev *sd,
3536                                   struct v4l2_subdev_state *sd_state,
3537                                   struct v4l2_subdev_frame_size_enum *fse)
3538 {
3539         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3540         u32 bpp = ov5640_code_to_bpp(sensor, fse->code);
3541         unsigned int index = fse->index;
3542
3543         if (fse->pad != 0)
3544                 return -EINVAL;
3545         if (!bpp)
3546                 return -EINVAL;
3547
3548         /* Only low-resolution modes are supported for 24bpp formats. */
3549         if (bpp == 24 && index >= OV5640_MODE_720P_1280_720)
3550                 return -EINVAL;
3551
3552         /* FIXME: Low resolution modes don't work in 8bpp formats. */
3553         if (bpp == 8)
3554                 index += OV5640_MODE_720P_1280_720;
3555
3556         if (index >= OV5640_NUM_MODES)
3557                 return -EINVAL;
3558
3559         fse->min_width = ov5640_mode_data[index].width;
3560         fse->max_width = fse->min_width;
3561         fse->min_height = ov5640_mode_data[index].height;
3562         fse->max_height = fse->min_height;
3563
3564         return 0;
3565 }
3566
3567 static int ov5640_enum_frame_interval(
3568         struct v4l2_subdev *sd,
3569         struct v4l2_subdev_state *sd_state,
3570         struct v4l2_subdev_frame_interval_enum *fie)
3571 {
3572         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3573         struct v4l2_fract tpf;
3574         int ret;
3575
3576         if (fie->pad != 0)
3577                 return -EINVAL;
3578         if (fie->index >= OV5640_NUM_FRAMERATES)
3579                 return -EINVAL;
3580
3581         tpf.numerator = 1;
3582         tpf.denominator = ov5640_framerates[fie->index];
3583
3584         ret = ov5640_try_frame_interval(sensor, &tpf,
3585                                         fie->width, fie->height);
3586         if (ret < 0)
3587                 return -EINVAL;
3588
3589         fie->interval = tpf;
3590         return 0;
3591 }
3592
3593 static int ov5640_g_frame_interval(struct v4l2_subdev *sd,
3594                                    struct v4l2_subdev_frame_interval *fi)
3595 {
3596         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3597
3598         mutex_lock(&sensor->lock);
3599         fi->interval = sensor->frame_interval;
3600         mutex_unlock(&sensor->lock);
3601
3602         return 0;
3603 }
3604
3605 static int ov5640_s_frame_interval(struct v4l2_subdev *sd,
3606                                    struct v4l2_subdev_frame_interval *fi)
3607 {
3608         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3609         const struct ov5640_mode_info *mode;
3610         int frame_rate, ret = 0;
3611
3612         if (fi->pad != 0)
3613                 return -EINVAL;
3614
3615         mutex_lock(&sensor->lock);
3616
3617         if (sensor->streaming) {
3618                 ret = -EBUSY;
3619                 goto out;
3620         }
3621
3622         mode = sensor->current_mode;
3623
3624         frame_rate = ov5640_try_frame_interval(sensor, &fi->interval,
3625                                                mode->width,
3626                                                mode->height);
3627         if (frame_rate < 0) {
3628                 /* Always return a valid frame interval value */
3629                 fi->interval = sensor->frame_interval;
3630                 goto out;
3631         }
3632
3633         mode = ov5640_find_mode(sensor, mode->width, mode->height, true);
3634         if (!mode) {
3635                 ret = -EINVAL;
3636                 goto out;
3637         }
3638
3639         if (ov5640_framerates[frame_rate] > ov5640_framerates[mode->max_fps]) {
3640                 ret = -EINVAL;
3641                 goto out;
3642         }
3643
3644         if (mode != sensor->current_mode ||
3645             frame_rate != sensor->current_fr) {
3646                 sensor->current_fr = frame_rate;
3647                 sensor->frame_interval = fi->interval;
3648                 sensor->current_mode = mode;
3649                 sensor->pending_mode_change = true;
3650
3651                 ov5640_update_pixel_rate(sensor);
3652         }
3653 out:
3654         mutex_unlock(&sensor->lock);
3655         return ret;
3656 }
3657
3658 static int ov5640_enum_mbus_code(struct v4l2_subdev *sd,
3659                                  struct v4l2_subdev_state *sd_state,
3660                                  struct v4l2_subdev_mbus_code_enum *code)
3661 {
3662         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3663         const struct ov5640_pixfmt *formats;
3664         unsigned int num_formats;
3665
3666         if (ov5640_is_csi2(sensor)) {
3667                 formats = ov5640_csi2_formats;
3668                 num_formats = ARRAY_SIZE(ov5640_csi2_formats) - 1;
3669         } else {
3670                 formats = ov5640_dvp_formats;
3671                 num_formats = ARRAY_SIZE(ov5640_dvp_formats) - 1;
3672         }
3673
3674         if (code->index >= num_formats)
3675                 return -EINVAL;
3676
3677         code->code = formats[code->index].code;
3678
3679         return 0;
3680 }
3681
3682 static int ov5640_s_stream(struct v4l2_subdev *sd, int enable)
3683 {
3684         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3685         int ret = 0;
3686
3687         if (enable) {
3688                 ret = pm_runtime_resume_and_get(&sensor->i2c_client->dev);
3689                 if (ret < 0)
3690                         return ret;
3691
3692                 ret = v4l2_ctrl_handler_setup(&sensor->ctrls.handler);
3693                 if (ret) {
3694                         pm_runtime_put(&sensor->i2c_client->dev);
3695                         return ret;
3696                 }
3697         }
3698
3699         mutex_lock(&sensor->lock);
3700
3701         if (sensor->streaming == !enable) {
3702                 if (enable && sensor->pending_mode_change) {
3703                         ret = ov5640_set_mode(sensor);
3704                         if (ret)
3705                                 goto out;
3706                 }
3707
3708                 if (enable && sensor->pending_fmt_change) {
3709                         ret = ov5640_set_framefmt(sensor, &sensor->fmt);
3710                         if (ret)
3711                                 goto out;
3712                         sensor->pending_fmt_change = false;
3713                 }
3714
3715                 if (ov5640_is_csi2(sensor))
3716                         ret = ov5640_set_stream_mipi(sensor, enable);
3717                 else
3718                         ret = ov5640_set_stream_dvp(sensor, enable);
3719
3720                 if (!ret)
3721                         sensor->streaming = enable;
3722         }
3723
3724 out:
3725         mutex_unlock(&sensor->lock);
3726
3727         if (!enable || ret)
3728                 pm_runtime_put_autosuspend(&sensor->i2c_client->dev);
3729
3730         return ret;
3731 }
3732
3733 static int ov5640_init_cfg(struct v4l2_subdev *sd,
3734                            struct v4l2_subdev_state *state)
3735 {
3736         struct v4l2_mbus_framefmt *fmt =
3737                                 v4l2_subdev_get_try_format(sd, state, 0);
3738         struct v4l2_rect *crop = v4l2_subdev_get_try_crop(sd, state, 0);
3739
3740         *fmt = ov5640_default_fmt;
3741
3742         crop->left = OV5640_PIXEL_ARRAY_LEFT;
3743         crop->top = OV5640_PIXEL_ARRAY_TOP;
3744         crop->width = OV5640_PIXEL_ARRAY_WIDTH;
3745         crop->height = OV5640_PIXEL_ARRAY_HEIGHT;
3746
3747         return 0;
3748 }
3749
3750 static const struct v4l2_subdev_core_ops ov5640_core_ops = {
3751         .log_status = v4l2_ctrl_subdev_log_status,
3752         .subscribe_event = v4l2_ctrl_subdev_subscribe_event,
3753         .unsubscribe_event = v4l2_event_subdev_unsubscribe,
3754 };
3755
3756 static const struct v4l2_subdev_video_ops ov5640_video_ops = {
3757         .g_frame_interval = ov5640_g_frame_interval,
3758         .s_frame_interval = ov5640_s_frame_interval,
3759         .s_stream = ov5640_s_stream,
3760 };
3761
3762 static const struct v4l2_subdev_pad_ops ov5640_pad_ops = {
3763         .init_cfg = ov5640_init_cfg,
3764         .enum_mbus_code = ov5640_enum_mbus_code,
3765         .get_fmt = ov5640_get_fmt,
3766         .set_fmt = ov5640_set_fmt,
3767         .get_selection = ov5640_get_selection,
3768         .enum_frame_size = ov5640_enum_frame_size,
3769         .enum_frame_interval = ov5640_enum_frame_interval,
3770 };
3771
3772 static const struct v4l2_subdev_ops ov5640_subdev_ops = {
3773         .core = &ov5640_core_ops,
3774         .video = &ov5640_video_ops,
3775         .pad = &ov5640_pad_ops,
3776 };
3777
3778 static int ov5640_get_regulators(struct ov5640_dev *sensor)
3779 {
3780         int i;
3781
3782         for (i = 0; i < OV5640_NUM_SUPPLIES; i++)
3783                 sensor->supplies[i].supply = ov5640_supply_name[i];
3784
3785         return devm_regulator_bulk_get(&sensor->i2c_client->dev,
3786                                        OV5640_NUM_SUPPLIES,
3787                                        sensor->supplies);
3788 }
3789
3790 static int ov5640_check_chip_id(struct ov5640_dev *sensor)
3791 {
3792         struct i2c_client *client = sensor->i2c_client;
3793         int ret = 0;
3794         u16 chip_id;
3795
3796         ret = ov5640_read_reg16(sensor, OV5640_REG_CHIP_ID, &chip_id);
3797         if (ret) {
3798                 dev_err(&client->dev, "%s: failed to read chip identifier\n",
3799                         __func__);
3800                 return ret;
3801         }
3802
3803         if (chip_id != 0x5640) {
3804                 dev_err(&client->dev, "%s: wrong chip identifier, expected 0x5640, got 0x%x\n",
3805                         __func__, chip_id);
3806                 return -ENXIO;
3807         }
3808
3809         return 0;
3810 }
3811
3812 static int ov5640_probe(struct i2c_client *client)
3813 {
3814         struct device *dev = &client->dev;
3815         struct fwnode_handle *endpoint;
3816         struct ov5640_dev *sensor;
3817         int ret;
3818
3819         sensor = devm_kzalloc(dev, sizeof(*sensor), GFP_KERNEL);
3820         if (!sensor)
3821                 return -ENOMEM;
3822
3823         sensor->i2c_client = client;
3824
3825         /*
3826          * default init sequence initialize sensor to
3827          * YUV422 UYVY VGA@30fps
3828          */
3829         sensor->fmt = ov5640_default_fmt;
3830         sensor->frame_interval.numerator = 1;
3831         sensor->frame_interval.denominator = ov5640_framerates[OV5640_30_FPS];
3832         sensor->current_fr = OV5640_30_FPS;
3833         sensor->current_mode =
3834                 &ov5640_mode_data[OV5640_MODE_VGA_640_480];
3835         sensor->last_mode = sensor->current_mode;
3836         sensor->current_link_freq =
3837                 ov5640_csi2_link_freqs[OV5640_DEFAULT_LINK_FREQ];
3838
3839         sensor->ae_target = 52;
3840
3841         endpoint = fwnode_graph_get_next_endpoint(dev_fwnode(&client->dev),
3842                                                   NULL);
3843         if (!endpoint) {
3844                 dev_err(dev, "endpoint node not found\n");
3845                 return -EINVAL;
3846         }
3847
3848         ret = v4l2_fwnode_endpoint_parse(endpoint, &sensor->ep);
3849         fwnode_handle_put(endpoint);
3850         if (ret) {
3851                 dev_err(dev, "Could not parse endpoint\n");
3852                 return ret;
3853         }
3854
3855         if (sensor->ep.bus_type != V4L2_MBUS_PARALLEL &&
3856             sensor->ep.bus_type != V4L2_MBUS_CSI2_DPHY &&
3857             sensor->ep.bus_type != V4L2_MBUS_BT656) {
3858                 dev_err(dev, "Unsupported bus type %d\n", sensor->ep.bus_type);
3859                 return -EINVAL;
3860         }
3861
3862         /* get system clock (xclk) */
3863         sensor->xclk = devm_clk_get(dev, "xclk");
3864         if (IS_ERR(sensor->xclk)) {
3865                 dev_err(dev, "failed to get xclk\n");
3866                 return PTR_ERR(sensor->xclk);
3867         }
3868
3869         sensor->xclk_freq = clk_get_rate(sensor->xclk);
3870         if (sensor->xclk_freq < OV5640_XCLK_MIN ||
3871             sensor->xclk_freq > OV5640_XCLK_MAX) {
3872                 dev_err(dev, "xclk frequency out of range: %d Hz\n",
3873                         sensor->xclk_freq);
3874                 return -EINVAL;
3875         }
3876
3877         /* request optional power down pin */
3878         sensor->pwdn_gpio = devm_gpiod_get_optional(dev, "powerdown",
3879                                                     GPIOD_OUT_HIGH);
3880         if (IS_ERR(sensor->pwdn_gpio))
3881                 return PTR_ERR(sensor->pwdn_gpio);
3882
3883         /* request optional reset pin */
3884         sensor->reset_gpio = devm_gpiod_get_optional(dev, "reset",
3885                                                      GPIOD_OUT_HIGH);
3886         if (IS_ERR(sensor->reset_gpio))
3887                 return PTR_ERR(sensor->reset_gpio);
3888
3889         v4l2_i2c_subdev_init(&sensor->sd, client, &ov5640_subdev_ops);
3890
3891         sensor->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE |
3892                             V4L2_SUBDEV_FL_HAS_EVENTS;
3893         sensor->pad.flags = MEDIA_PAD_FL_SOURCE;
3894         sensor->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR;
3895         ret = media_entity_pads_init(&sensor->sd.entity, 1, &sensor->pad);
3896         if (ret)
3897                 return ret;
3898
3899         ret = ov5640_get_regulators(sensor);
3900         if (ret)
3901                 goto entity_cleanup;
3902
3903         mutex_init(&sensor->lock);
3904
3905         ret = ov5640_init_controls(sensor);
3906         if (ret)
3907                 goto entity_cleanup;
3908
3909         ret = ov5640_sensor_resume(dev);
3910         if (ret) {
3911                 dev_err(dev, "failed to power on\n");
3912                 goto free_ctrls;
3913         }
3914
3915         pm_runtime_set_active(dev);
3916         pm_runtime_get_noresume(dev);
3917         pm_runtime_enable(dev);
3918
3919         ret = ov5640_check_chip_id(sensor);
3920         if (ret)
3921                 goto err_pm_runtime;
3922
3923         ret = v4l2_async_register_subdev_sensor(&sensor->sd);
3924         if (ret)
3925                 goto err_pm_runtime;
3926
3927         pm_runtime_set_autosuspend_delay(dev, 1000);
3928         pm_runtime_use_autosuspend(dev);
3929         pm_runtime_put_autosuspend(dev);
3930
3931         return 0;
3932
3933 err_pm_runtime:
3934         pm_runtime_put_noidle(dev);
3935         pm_runtime_disable(dev);
3936         ov5640_sensor_suspend(dev);
3937 free_ctrls:
3938         v4l2_ctrl_handler_free(&sensor->ctrls.handler);
3939 entity_cleanup:
3940         media_entity_cleanup(&sensor->sd.entity);
3941         mutex_destroy(&sensor->lock);
3942         return ret;
3943 }
3944
3945 static void ov5640_remove(struct i2c_client *client)
3946 {
3947         struct v4l2_subdev *sd = i2c_get_clientdata(client);
3948         struct ov5640_dev *sensor = to_ov5640_dev(sd);
3949         struct device *dev = &client->dev;
3950
3951         pm_runtime_disable(dev);
3952         if (!pm_runtime_status_suspended(dev))
3953                 ov5640_sensor_suspend(dev);
3954         pm_runtime_set_suspended(dev);
3955
3956         v4l2_async_unregister_subdev(&sensor->sd);
3957         media_entity_cleanup(&sensor->sd.entity);
3958         v4l2_ctrl_handler_free(&sensor->ctrls.handler);
3959         mutex_destroy(&sensor->lock);
3960 }
3961
3962 static const struct dev_pm_ops ov5640_pm_ops = {
3963         SET_RUNTIME_PM_OPS(ov5640_sensor_suspend, ov5640_sensor_resume, NULL)
3964 };
3965
3966 static const struct i2c_device_id ov5640_id[] = {
3967         {"ov5640", 0},
3968         {},
3969 };
3970 MODULE_DEVICE_TABLE(i2c, ov5640_id);
3971
3972 static const struct of_device_id ov5640_dt_ids[] = {
3973         { .compatible = "ovti,ov5640" },
3974         { /* sentinel */ }
3975 };
3976 MODULE_DEVICE_TABLE(of, ov5640_dt_ids);
3977
3978 static struct i2c_driver ov5640_i2c_driver = {
3979         .driver = {
3980                 .name  = "ov5640",
3981                 .of_match_table = ov5640_dt_ids,
3982                 .pm = &ov5640_pm_ops,
3983         },
3984         .id_table = ov5640_id,
3985         .probe_new = ov5640_probe,
3986         .remove   = ov5640_remove,
3987 };
3988
3989 module_i2c_driver(ov5640_i2c_driver);
3990
3991 MODULE_DESCRIPTION("OV5640 MIPI Camera Subdev Driver");
3992 MODULE_LICENSE("GPL");