xref: /openbmc/linux/drivers/media/i2c/ov772x.c (revision 4bf3bd0f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * ov772x Camera Driver
4  *
5  * Copyright (C) 2017 Jacopo Mondi <jacopo+renesas@jmondi.org>
6  *
7  * Copyright (C) 2008 Renesas Solutions Corp.
8  * Kuninori Morimoto <morimoto.kuninori@renesas.com>
9  *
10  * Based on ov7670 and soc_camera_platform driver,
11  *
12  * Copyright 2006-7 Jonathan Corbet <corbet@lwn.net>
13  * Copyright (C) 2008 Magnus Damm
14  * Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de>
15  */
16 
17 #include <linux/clk.h>
18 #include <linux/delay.h>
19 #include <linux/gpio/consumer.h>
20 #include <linux/i2c.h>
21 #include <linux/init.h>
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/regmap.h>
25 #include <linux/slab.h>
26 #include <linux/v4l2-mediabus.h>
27 #include <linux/videodev2.h>
28 
29 #include <media/i2c/ov772x.h>
30 
31 #include <media/v4l2-ctrls.h>
32 #include <media/v4l2-device.h>
33 #include <media/v4l2-image-sizes.h>
34 #include <media/v4l2-subdev.h>
35 
36 /*
37  * register offset
38  */
39 #define GAIN        0x00 /* AGC - Gain control gain setting */
40 #define BLUE        0x01 /* AWB - Blue channel gain setting */
41 #define RED         0x02 /* AWB - Red   channel gain setting */
42 #define GREEN       0x03 /* AWB - Green channel gain setting */
43 #define COM1        0x04 /* Common control 1 */
44 #define BAVG        0x05 /* U/B Average Level */
45 #define GAVG        0x06 /* Y/Gb Average Level */
46 #define RAVG        0x07 /* V/R Average Level */
47 #define AECH        0x08 /* Exposure Value - AEC MSBs */
48 #define COM2        0x09 /* Common control 2 */
49 #define PID         0x0A /* Product ID Number MSB */
50 #define VER         0x0B /* Product ID Number LSB */
51 #define COM3        0x0C /* Common control 3 */
52 #define COM4        0x0D /* Common control 4 */
53 #define COM5        0x0E /* Common control 5 */
54 #define COM6        0x0F /* Common control 6 */
55 #define AEC         0x10 /* Exposure Value */
56 #define CLKRC       0x11 /* Internal clock */
57 #define COM7        0x12 /* Common control 7 */
58 #define COM8        0x13 /* Common control 8 */
59 #define COM9        0x14 /* Common control 9 */
60 #define COM10       0x15 /* Common control 10 */
61 #define REG16       0x16 /* Register 16 */
62 #define HSTART      0x17 /* Horizontal sensor size */
63 #define HSIZE       0x18 /* Horizontal frame (HREF column) end high 8-bit */
64 #define VSTART      0x19 /* Vertical frame (row) start high 8-bit */
65 #define VSIZE       0x1A /* Vertical sensor size */
66 #define PSHFT       0x1B /* Data format - pixel delay select */
67 #define MIDH        0x1C /* Manufacturer ID byte - high */
68 #define MIDL        0x1D /* Manufacturer ID byte - low  */
69 #define LAEC        0x1F /* Fine AEC value */
70 #define COM11       0x20 /* Common control 11 */
71 #define BDBASE      0x22 /* Banding filter Minimum AEC value */
72 #define DBSTEP      0x23 /* Banding filter Maximum Setp */
73 #define AEW         0x24 /* AGC/AEC - Stable operating region (upper limit) */
74 #define AEB         0x25 /* AGC/AEC - Stable operating region (lower limit) */
75 #define VPT         0x26 /* AGC/AEC Fast mode operating region */
76 #define REG28       0x28 /* Register 28 */
77 #define HOUTSIZE    0x29 /* Horizontal data output size MSBs */
78 #define EXHCH       0x2A /* Dummy pixel insert MSB */
79 #define EXHCL       0x2B /* Dummy pixel insert LSB */
80 #define VOUTSIZE    0x2C /* Vertical data output size MSBs */
81 #define ADVFL       0x2D /* LSB of insert dummy lines in Vertical direction */
82 #define ADVFH       0x2E /* MSG of insert dummy lines in Vertical direction */
83 #define YAVE        0x2F /* Y/G Channel Average value */
84 #define LUMHTH      0x30 /* Histogram AEC/AGC Luminance high level threshold */
85 #define LUMLTH      0x31 /* Histogram AEC/AGC Luminance low  level threshold */
86 #define HREF        0x32 /* Image start and size control */
87 #define DM_LNL      0x33 /* Dummy line low  8 bits */
88 #define DM_LNH      0x34 /* Dummy line high 8 bits */
89 #define ADOFF_B     0x35 /* AD offset compensation value for B  channel */
90 #define ADOFF_R     0x36 /* AD offset compensation value for R  channel */
91 #define ADOFF_GB    0x37 /* AD offset compensation value for Gb channel */
92 #define ADOFF_GR    0x38 /* AD offset compensation value for Gr channel */
93 #define OFF_B       0x39 /* Analog process B  channel offset value */
94 #define OFF_R       0x3A /* Analog process R  channel offset value */
95 #define OFF_GB      0x3B /* Analog process Gb channel offset value */
96 #define OFF_GR      0x3C /* Analog process Gr channel offset value */
97 #define COM12       0x3D /* Common control 12 */
98 #define COM13       0x3E /* Common control 13 */
99 #define COM14       0x3F /* Common control 14 */
100 #define COM15       0x40 /* Common control 15*/
101 #define COM16       0x41 /* Common control 16 */
102 #define TGT_B       0x42 /* BLC blue channel target value */
103 #define TGT_R       0x43 /* BLC red  channel target value */
104 #define TGT_GB      0x44 /* BLC Gb   channel target value */
105 #define TGT_GR      0x45 /* BLC Gr   channel target value */
106 /* for ov7720 */
107 #define LCC0        0x46 /* Lens correction control 0 */
108 #define LCC1        0x47 /* Lens correction option 1 - X coordinate */
109 #define LCC2        0x48 /* Lens correction option 2 - Y coordinate */
110 #define LCC3        0x49 /* Lens correction option 3 */
111 #define LCC4        0x4A /* Lens correction option 4 - radius of the circular */
112 #define LCC5        0x4B /* Lens correction option 5 */
113 #define LCC6        0x4C /* Lens correction option 6 */
114 /* for ov7725 */
115 #define LC_CTR      0x46 /* Lens correction control */
116 #define LC_XC       0x47 /* X coordinate of lens correction center relative */
117 #define LC_YC       0x48 /* Y coordinate of lens correction center relative */
118 #define LC_COEF     0x49 /* Lens correction coefficient */
119 #define LC_RADI     0x4A /* Lens correction radius */
120 #define LC_COEFB    0x4B /* Lens B channel compensation coefficient */
121 #define LC_COEFR    0x4C /* Lens R channel compensation coefficient */
122 
123 #define FIXGAIN     0x4D /* Analog fix gain amplifer */
124 #define AREF0       0x4E /* Sensor reference control */
125 #define AREF1       0x4F /* Sensor reference current control */
126 #define AREF2       0x50 /* Analog reference control */
127 #define AREF3       0x51 /* ADC    reference control */
128 #define AREF4       0x52 /* ADC    reference control */
129 #define AREF5       0x53 /* ADC    reference control */
130 #define AREF6       0x54 /* Analog reference control */
131 #define AREF7       0x55 /* Analog reference control */
132 #define UFIX        0x60 /* U channel fixed value output */
133 #define VFIX        0x61 /* V channel fixed value output */
134 #define AWBB_BLK    0x62 /* AWB option for advanced AWB */
135 #define AWB_CTRL0   0x63 /* AWB control byte 0 */
136 #define DSP_CTRL1   0x64 /* DSP control byte 1 */
137 #define DSP_CTRL2   0x65 /* DSP control byte 2 */
138 #define DSP_CTRL3   0x66 /* DSP control byte 3 */
139 #define DSP_CTRL4   0x67 /* DSP control byte 4 */
140 #define AWB_BIAS    0x68 /* AWB BLC level clip */
141 #define AWB_CTRL1   0x69 /* AWB control  1 */
142 #define AWB_CTRL2   0x6A /* AWB control  2 */
143 #define AWB_CTRL3   0x6B /* AWB control  3 */
144 #define AWB_CTRL4   0x6C /* AWB control  4 */
145 #define AWB_CTRL5   0x6D /* AWB control  5 */
146 #define AWB_CTRL6   0x6E /* AWB control  6 */
147 #define AWB_CTRL7   0x6F /* AWB control  7 */
148 #define AWB_CTRL8   0x70 /* AWB control  8 */
149 #define AWB_CTRL9   0x71 /* AWB control  9 */
150 #define AWB_CTRL10  0x72 /* AWB control 10 */
151 #define AWB_CTRL11  0x73 /* AWB control 11 */
152 #define AWB_CTRL12  0x74 /* AWB control 12 */
153 #define AWB_CTRL13  0x75 /* AWB control 13 */
154 #define AWB_CTRL14  0x76 /* AWB control 14 */
155 #define AWB_CTRL15  0x77 /* AWB control 15 */
156 #define AWB_CTRL16  0x78 /* AWB control 16 */
157 #define AWB_CTRL17  0x79 /* AWB control 17 */
158 #define AWB_CTRL18  0x7A /* AWB control 18 */
159 #define AWB_CTRL19  0x7B /* AWB control 19 */
160 #define AWB_CTRL20  0x7C /* AWB control 20 */
161 #define AWB_CTRL21  0x7D /* AWB control 21 */
162 #define GAM1        0x7E /* Gamma Curve  1st segment input end point */
163 #define GAM2        0x7F /* Gamma Curve  2nd segment input end point */
164 #define GAM3        0x80 /* Gamma Curve  3rd segment input end point */
165 #define GAM4        0x81 /* Gamma Curve  4th segment input end point */
166 #define GAM5        0x82 /* Gamma Curve  5th segment input end point */
167 #define GAM6        0x83 /* Gamma Curve  6th segment input end point */
168 #define GAM7        0x84 /* Gamma Curve  7th segment input end point */
169 #define GAM8        0x85 /* Gamma Curve  8th segment input end point */
170 #define GAM9        0x86 /* Gamma Curve  9th segment input end point */
171 #define GAM10       0x87 /* Gamma Curve 10th segment input end point */
172 #define GAM11       0x88 /* Gamma Curve 11th segment input end point */
173 #define GAM12       0x89 /* Gamma Curve 12th segment input end point */
174 #define GAM13       0x8A /* Gamma Curve 13th segment input end point */
175 #define GAM14       0x8B /* Gamma Curve 14th segment input end point */
176 #define GAM15       0x8C /* Gamma Curve 15th segment input end point */
177 #define SLOP        0x8D /* Gamma curve highest segment slope */
178 #define DNSTH       0x8E /* De-noise threshold */
179 #define EDGE_STRNGT 0x8F /* Edge strength  control when manual mode */
180 #define EDGE_TRSHLD 0x90 /* Edge threshold control when manual mode */
181 #define DNSOFF      0x91 /* Auto De-noise threshold control */
182 #define EDGE_UPPER  0x92 /* Edge strength upper limit when Auto mode */
183 #define EDGE_LOWER  0x93 /* Edge strength lower limit when Auto mode */
184 #define MTX1        0x94 /* Matrix coefficient 1 */
185 #define MTX2        0x95 /* Matrix coefficient 2 */
186 #define MTX3        0x96 /* Matrix coefficient 3 */
187 #define MTX4        0x97 /* Matrix coefficient 4 */
188 #define MTX5        0x98 /* Matrix coefficient 5 */
189 #define MTX6        0x99 /* Matrix coefficient 6 */
190 #define MTX_CTRL    0x9A /* Matrix control */
191 #define BRIGHT      0x9B /* Brightness control */
192 #define CNTRST      0x9C /* Contrast contrast */
193 #define CNTRST_CTRL 0x9D /* Contrast contrast center */
194 #define UVAD_J0     0x9E /* Auto UV adjust contrast 0 */
195 #define UVAD_J1     0x9F /* Auto UV adjust contrast 1 */
196 #define SCAL0       0xA0 /* Scaling control 0 */
197 #define SCAL1       0xA1 /* Scaling control 1 */
198 #define SCAL2       0xA2 /* Scaling control 2 */
199 #define FIFODLYM    0xA3 /* FIFO manual mode delay control */
200 #define FIFODLYA    0xA4 /* FIFO auto   mode delay control */
201 #define SDE         0xA6 /* Special digital effect control */
202 #define USAT        0xA7 /* U component saturation control */
203 #define VSAT        0xA8 /* V component saturation control */
204 /* for ov7720 */
205 #define HUE0        0xA9 /* Hue control 0 */
206 #define HUE1        0xAA /* Hue control 1 */
207 /* for ov7725 */
208 #define HUECOS      0xA9 /* Cosine value */
209 #define HUESIN      0xAA /* Sine value */
210 
211 #define SIGN        0xAB /* Sign bit for Hue and contrast */
212 #define DSPAUTO     0xAC /* DSP auto function ON/OFF control */
213 
214 /*
215  * register detail
216  */
217 
218 /* COM2 */
219 #define SOFT_SLEEP_MODE 0x10	/* Soft sleep mode */
220 				/* Output drive capability */
221 #define OCAP_1x         0x00	/* 1x */
222 #define OCAP_2x         0x01	/* 2x */
223 #define OCAP_3x         0x02	/* 3x */
224 #define OCAP_4x         0x03	/* 4x */
225 
226 /* COM3 */
227 #define SWAP_MASK       (SWAP_RGB | SWAP_YUV | SWAP_ML)
228 #define IMG_MASK        (VFLIP_IMG | HFLIP_IMG)
229 
230 #define VFLIP_IMG       0x80	/* Vertical flip image ON/OFF selection */
231 #define HFLIP_IMG       0x40	/* Horizontal mirror image ON/OFF selection */
232 #define SWAP_RGB        0x20	/* Swap B/R  output sequence in RGB mode */
233 #define SWAP_YUV        0x10	/* Swap Y/UV output sequence in YUV mode */
234 #define SWAP_ML         0x08	/* Swap output MSB/LSB */
235 				/* Tri-state option for output clock */
236 #define NOTRI_CLOCK     0x04	/*   0: Tri-state    at this period */
237 				/*   1: No tri-state at this period */
238 				/* Tri-state option for output data */
239 #define NOTRI_DATA      0x02	/*   0: Tri-state    at this period */
240 				/*   1: No tri-state at this period */
241 #define SCOLOR_TEST     0x01	/* Sensor color bar test pattern */
242 
243 /* COM4 */
244 				/* PLL frequency control */
245 #define PLL_BYPASS      0x00	/*  00: Bypass PLL */
246 #define PLL_4x          0x40	/*  01: PLL 4x */
247 #define PLL_6x          0x80	/*  10: PLL 6x */
248 #define PLL_8x          0xc0	/*  11: PLL 8x */
249 				/* AEC evaluate window */
250 #define AEC_FULL        0x00	/*  00: Full window */
251 #define AEC_1p2         0x10	/*  01: 1/2  window */
252 #define AEC_1p4         0x20	/*  10: 1/4  window */
253 #define AEC_2p3         0x30	/*  11: Low 2/3 window */
254 #define COM4_RESERVED   0x01	/* Reserved bit */
255 
256 /* COM5 */
257 #define AFR_ON_OFF      0x80	/* Auto frame rate control ON/OFF selection */
258 #define AFR_SPPED       0x40	/* Auto frame rate control speed selection */
259 				/* Auto frame rate max rate control */
260 #define AFR_NO_RATE     0x00	/*     No  reduction of frame rate */
261 #define AFR_1p2         0x10	/*     Max reduction to 1/2 frame rate */
262 #define AFR_1p4         0x20	/*     Max reduction to 1/4 frame rate */
263 #define AFR_1p8         0x30	/* Max reduction to 1/8 frame rate */
264 				/* Auto frame rate active point control */
265 #define AF_2x           0x00	/*     Add frame when AGC reaches  2x gain */
266 #define AF_4x           0x04	/*     Add frame when AGC reaches  4x gain */
267 #define AF_8x           0x08	/*     Add frame when AGC reaches  8x gain */
268 #define AF_16x          0x0c	/* Add frame when AGC reaches 16x gain */
269 				/* AEC max step control */
270 #define AEC_NO_LIMIT    0x01	/*   0 : AEC incease step has limit */
271 				/*   1 : No limit to AEC increase step */
272 /* CLKRC */
273 				/* Input clock divider register */
274 #define CLKRC_RESERVED  0x80	/* Reserved bit */
275 #define CLKRC_DIV(n)    ((n) - 1)
276 
277 /* COM7 */
278 				/* SCCB Register Reset */
279 #define SCCB_RESET      0x80	/*   0 : No change */
280 				/*   1 : Resets all registers to default */
281 				/* Resolution selection */
282 #define SLCT_MASK       0x40	/*   Mask of VGA or QVGA */
283 #define SLCT_VGA        0x00	/*   0 : VGA */
284 #define SLCT_QVGA       0x40	/*   1 : QVGA */
285 #define ITU656_ON_OFF   0x20	/* ITU656 protocol ON/OFF selection */
286 #define SENSOR_RAW	0x10	/* Sensor RAW */
287 				/* RGB output format control */
288 #define FMT_MASK        0x0c	/*      Mask of color format */
289 #define FMT_GBR422      0x00	/*      00 : GBR 4:2:2 */
290 #define FMT_RGB565      0x04	/*      01 : RGB 565 */
291 #define FMT_RGB555      0x08	/*      10 : RGB 555 */
292 #define FMT_RGB444      0x0c	/* 11 : RGB 444 */
293 				/* Output format control */
294 #define OFMT_MASK       0x03    /*      Mask of output format */
295 #define OFMT_YUV        0x00	/*      00 : YUV */
296 #define OFMT_P_BRAW     0x01	/*      01 : Processed Bayer RAW */
297 #define OFMT_RGB        0x02	/*      10 : RGB */
298 #define OFMT_BRAW       0x03	/* 11 : Bayer RAW */
299 
300 /* COM8 */
301 #define FAST_ALGO       0x80	/* Enable fast AGC/AEC algorithm */
302 				/* AEC Setp size limit */
303 #define UNLMT_STEP      0x40	/*   0 : Step size is limited */
304 				/*   1 : Unlimited step size */
305 #define BNDF_ON_OFF     0x20	/* Banding filter ON/OFF */
306 #define AEC_BND         0x10	/* Enable AEC below banding value */
307 #define AEC_ON_OFF      0x08	/* Fine AEC ON/OFF control */
308 #define AGC_ON          0x04	/* AGC Enable */
309 #define AWB_ON          0x02	/* AWB Enable */
310 #define AEC_ON          0x01	/* AEC Enable */
311 
312 /* COM9 */
313 #define BASE_AECAGC     0x80	/* Histogram or average based AEC/AGC */
314 				/* Automatic gain ceiling - maximum AGC value */
315 #define GAIN_2x         0x00	/*    000 :   2x */
316 #define GAIN_4x         0x10	/*    001 :   4x */
317 #define GAIN_8x         0x20	/*    010 :   8x */
318 #define GAIN_16x        0x30	/*    011 :  16x */
319 #define GAIN_32x        0x40	/*    100 :  32x */
320 #define GAIN_64x        0x50	/* 101 :  64x */
321 #define GAIN_128x       0x60	/* 110 : 128x */
322 #define DROP_VSYNC      0x04	/* Drop VSYNC output of corrupt frame */
323 #define DROP_HREF       0x02	/* Drop HREF  output of corrupt frame */
324 
325 /* COM11 */
326 #define SGLF_ON_OFF     0x02	/* Single frame ON/OFF selection */
327 #define SGLF_TRIG       0x01	/* Single frame transfer trigger */
328 
329 /* HREF */
330 #define HREF_VSTART_SHIFT	6	/* VSTART LSB */
331 #define HREF_HSTART_SHIFT	4	/* HSTART 2 LSBs */
332 #define HREF_VSIZE_SHIFT	2	/* VSIZE LSB */
333 #define HREF_HSIZE_SHIFT	0	/* HSIZE 2 LSBs */
334 
335 /* EXHCH */
336 #define EXHCH_VSIZE_SHIFT	2	/* VOUTSIZE LSB */
337 #define EXHCH_HSIZE_SHIFT	0	/* HOUTSIZE 2 LSBs */
338 
339 /* DSP_CTRL1 */
340 #define FIFO_ON         0x80	/* FIFO enable/disable selection */
341 #define UV_ON_OFF       0x40	/* UV adjust function ON/OFF selection */
342 #define YUV444_2_422    0x20	/* YUV444 to 422 UV channel option selection */
343 #define CLR_MTRX_ON_OFF 0x10	/* Color matrix ON/OFF selection */
344 #define INTPLT_ON_OFF   0x08	/* Interpolation ON/OFF selection */
345 #define GMM_ON_OFF      0x04	/* Gamma function ON/OFF selection */
346 #define AUTO_BLK_ON_OFF 0x02	/* Black defect auto correction ON/OFF */
347 #define AUTO_WHT_ON_OFF 0x01	/* White define auto correction ON/OFF */
348 
349 /* DSP_CTRL3 */
350 #define UV_MASK         0x80	/* UV output sequence option */
351 #define UV_ON           0x80	/*   ON */
352 #define UV_OFF          0x00	/*   OFF */
353 #define CBAR_MASK       0x20	/* DSP Color bar mask */
354 #define CBAR_ON         0x20	/*   ON */
355 #define CBAR_OFF        0x00	/*   OFF */
356 
357 /* DSP_CTRL4 */
358 #define DSP_OFMT_YUV	0x00
359 #define DSP_OFMT_RGB	0x00
360 #define DSP_OFMT_RAW8	0x02
361 #define DSP_OFMT_RAW10	0x03
362 
363 /* DSPAUTO (DSP Auto Function ON/OFF Control) */
364 #define AWB_ACTRL       0x80 /* AWB auto threshold control */
365 #define DENOISE_ACTRL   0x40 /* De-noise auto threshold control */
366 #define EDGE_ACTRL      0x20 /* Edge enhancement auto strength control */
367 #define UV_ACTRL        0x10 /* UV adjust auto slope control */
368 #define SCAL0_ACTRL     0x08 /* Auto scaling factor control */
369 #define SCAL1_2_ACTRL   0x04 /* Auto scaling factor control */
370 
371 #define OV772X_MAX_WIDTH	VGA_WIDTH
372 #define OV772X_MAX_HEIGHT	VGA_HEIGHT
373 
374 /*
375  * ID
376  */
377 #define OV7720  0x7720
378 #define OV7725  0x7721
379 #define VERSION(pid, ver) ((pid << 8) | (ver & 0xFF))
380 
381 /*
382  * PLL multipliers
383  */
384 static struct {
385 	unsigned int mult;
386 	u8 com4;
387 } ov772x_pll[] = {
388 	{ 1, PLL_BYPASS, },
389 	{ 4, PLL_4x, },
390 	{ 6, PLL_6x, },
391 	{ 8, PLL_8x, },
392 };
393 
394 /*
395  * struct
396  */
397 
398 struct ov772x_color_format {
399 	u32 code;
400 	enum v4l2_colorspace colorspace;
401 	u8 dsp3;
402 	u8 dsp4;
403 	u8 com3;
404 	u8 com7;
405 };
406 
407 struct ov772x_win_size {
408 	char                     *name;
409 	unsigned char             com7_bit;
410 	unsigned int		  sizeimage;
411 	struct v4l2_rect	  rect;
412 };
413 
414 struct ov772x_priv {
415 	struct v4l2_subdev                subdev;
416 	struct v4l2_ctrl_handler	  hdl;
417 	struct clk			 *clk;
418 	struct regmap			 *regmap;
419 	struct ov772x_camera_info        *info;
420 	struct gpio_desc		 *pwdn_gpio;
421 	struct gpio_desc		 *rstb_gpio;
422 	const struct ov772x_color_format *cfmt;
423 	const struct ov772x_win_size     *win;
424 	struct v4l2_ctrl		 *vflip_ctrl;
425 	struct v4l2_ctrl		 *hflip_ctrl;
426 	/* band_filter = COM8[5] ? 256 - BDBASE : 0 */
427 	struct v4l2_ctrl		 *band_filter_ctrl;
428 	unsigned int			  fps;
429 	/* lock to protect power_count and streaming */
430 	struct mutex			  lock;
431 	int				  power_count;
432 	int				  streaming;
433 #ifdef CONFIG_MEDIA_CONTROLLER
434 	struct media_pad pad;
435 #endif
436 };
437 
438 /*
439  * supported color format list
440  */
441 static const struct ov772x_color_format ov772x_cfmts[] = {
442 	{
443 		.code		= MEDIA_BUS_FMT_YUYV8_2X8,
444 		.colorspace	= V4L2_COLORSPACE_SRGB,
445 		.dsp3		= 0x0,
446 		.dsp4		= DSP_OFMT_YUV,
447 		.com3		= SWAP_YUV,
448 		.com7		= OFMT_YUV,
449 	},
450 	{
451 		.code		= MEDIA_BUS_FMT_YVYU8_2X8,
452 		.colorspace	= V4L2_COLORSPACE_SRGB,
453 		.dsp3		= UV_ON,
454 		.dsp4		= DSP_OFMT_YUV,
455 		.com3		= SWAP_YUV,
456 		.com7		= OFMT_YUV,
457 	},
458 	{
459 		.code		= MEDIA_BUS_FMT_UYVY8_2X8,
460 		.colorspace	= V4L2_COLORSPACE_SRGB,
461 		.dsp3		= 0x0,
462 		.dsp4		= DSP_OFMT_YUV,
463 		.com3		= 0x0,
464 		.com7		= OFMT_YUV,
465 	},
466 	{
467 		.code		= MEDIA_BUS_FMT_RGB555_2X8_PADHI_LE,
468 		.colorspace	= V4L2_COLORSPACE_SRGB,
469 		.dsp3		= 0x0,
470 		.dsp4		= DSP_OFMT_YUV,
471 		.com3		= SWAP_RGB,
472 		.com7		= FMT_RGB555 | OFMT_RGB,
473 	},
474 	{
475 		.code		= MEDIA_BUS_FMT_RGB555_2X8_PADHI_BE,
476 		.colorspace	= V4L2_COLORSPACE_SRGB,
477 		.dsp3		= 0x0,
478 		.dsp4		= DSP_OFMT_YUV,
479 		.com3		= 0x0,
480 		.com7		= FMT_RGB555 | OFMT_RGB,
481 	},
482 	{
483 		.code		= MEDIA_BUS_FMT_RGB565_2X8_LE,
484 		.colorspace	= V4L2_COLORSPACE_SRGB,
485 		.dsp3		= 0x0,
486 		.dsp4		= DSP_OFMT_YUV,
487 		.com3		= SWAP_RGB,
488 		.com7		= FMT_RGB565 | OFMT_RGB,
489 	},
490 	{
491 		.code		= MEDIA_BUS_FMT_RGB565_2X8_BE,
492 		.colorspace	= V4L2_COLORSPACE_SRGB,
493 		.dsp3		= 0x0,
494 		.dsp4		= DSP_OFMT_YUV,
495 		.com3		= 0x0,
496 		.com7		= FMT_RGB565 | OFMT_RGB,
497 	},
498 	{
499 		/* Setting DSP4 to DSP_OFMT_RAW8 still gives 10-bit output,
500 		 * regardless of the COM7 value. We can thus only support 10-bit
501 		 * Bayer until someone figures it out.
502 		 */
503 		.code		= MEDIA_BUS_FMT_SBGGR10_1X10,
504 		.colorspace	= V4L2_COLORSPACE_SRGB,
505 		.dsp3		= 0x0,
506 		.dsp4		= DSP_OFMT_RAW10,
507 		.com3		= 0x0,
508 		.com7		= SENSOR_RAW | OFMT_BRAW,
509 	},
510 };
511 
512 /*
513  * window size list
514  */
515 
516 static const struct ov772x_win_size ov772x_win_sizes[] = {
517 	{
518 		.name		= "VGA",
519 		.com7_bit	= SLCT_VGA,
520 		.sizeimage	= 510 * 748,
521 		.rect = {
522 			.left	= 140,
523 			.top	= 14,
524 			.width	= VGA_WIDTH,
525 			.height	= VGA_HEIGHT,
526 		},
527 	}, {
528 		.name		= "QVGA",
529 		.com7_bit	= SLCT_QVGA,
530 		.sizeimage	= 278 * 576,
531 		.rect = {
532 			.left	= 252,
533 			.top	= 6,
534 			.width	= QVGA_WIDTH,
535 			.height	= QVGA_HEIGHT,
536 		},
537 	},
538 };
539 
540 /*
541  * frame rate settings lists
542  */
543 static const unsigned int ov772x_frame_intervals[] = { 5, 10, 15, 20, 30, 60 };
544 
545 /*
546  * general function
547  */
548 
549 static struct ov772x_priv *to_ov772x(struct v4l2_subdev *sd)
550 {
551 	return container_of(sd, struct ov772x_priv, subdev);
552 }
553 
554 static int ov772x_reset(struct ov772x_priv *priv)
555 {
556 	int ret;
557 
558 	ret = regmap_write(priv->regmap, COM7, SCCB_RESET);
559 	if (ret < 0)
560 		return ret;
561 
562 	usleep_range(1000, 5000);
563 
564 	return regmap_update_bits(priv->regmap, COM2, SOFT_SLEEP_MODE,
565 				  SOFT_SLEEP_MODE);
566 }
567 
568 /*
569  * subdev ops
570  */
571 
572 static int ov772x_s_stream(struct v4l2_subdev *sd, int enable)
573 {
574 	struct i2c_client *client = v4l2_get_subdevdata(sd);
575 	struct ov772x_priv *priv = to_ov772x(sd);
576 	int ret = 0;
577 
578 	mutex_lock(&priv->lock);
579 
580 	if (priv->streaming == enable)
581 		goto done;
582 
583 	ret = regmap_update_bits(priv->regmap, COM2, SOFT_SLEEP_MODE,
584 				 enable ? 0 : SOFT_SLEEP_MODE);
585 	if (ret)
586 		goto done;
587 
588 	if (enable) {
589 		dev_dbg(&client->dev, "format %d, win %s\n",
590 			priv->cfmt->code, priv->win->name);
591 	}
592 	priv->streaming = enable;
593 
594 done:
595 	mutex_unlock(&priv->lock);
596 
597 	return ret;
598 }
599 
600 static unsigned int ov772x_select_fps(struct ov772x_priv *priv,
601 				      struct v4l2_fract *tpf)
602 {
603 	unsigned int fps = tpf->numerator ?
604 			   tpf->denominator / tpf->numerator :
605 			   tpf->denominator;
606 	unsigned int best_diff;
607 	unsigned int diff;
608 	unsigned int idx;
609 	unsigned int i;
610 
611 	/* Approximate to the closest supported frame interval. */
612 	best_diff = ~0L;
613 	for (i = 0, idx = 0; i < ARRAY_SIZE(ov772x_frame_intervals); i++) {
614 		diff = abs(fps - ov772x_frame_intervals[i]);
615 		if (diff < best_diff) {
616 			idx = i;
617 			best_diff = diff;
618 		}
619 	}
620 
621 	return ov772x_frame_intervals[idx];
622 }
623 
624 static int ov772x_set_frame_rate(struct ov772x_priv *priv,
625 				 unsigned int fps,
626 				 const struct ov772x_color_format *cfmt,
627 				 const struct ov772x_win_size *win)
628 {
629 	unsigned long fin = clk_get_rate(priv->clk);
630 	unsigned int best_diff;
631 	unsigned int fsize;
632 	unsigned int pclk;
633 	unsigned int diff;
634 	unsigned int i;
635 	u8 clkrc = 0;
636 	u8 com4 = 0;
637 	int ret;
638 
639 	/* Use image size (with blankings) to calculate desired pixel clock. */
640 	switch (cfmt->com7 & OFMT_MASK) {
641 	case OFMT_BRAW:
642 		fsize = win->sizeimage;
643 		break;
644 	case OFMT_RGB:
645 	case OFMT_YUV:
646 	default:
647 		fsize = win->sizeimage * 2;
648 		break;
649 	}
650 
651 	pclk = fps * fsize;
652 
653 	/*
654 	 * Pixel clock generation circuit is pretty simple:
655 	 *
656 	 * Fin -> [ / CLKRC_div] -> [ * PLL_mult] -> pclk
657 	 *
658 	 * Try to approximate the desired pixel clock testing all available
659 	 * PLL multipliers (1x, 4x, 6x, 8x) and calculate corresponding
660 	 * divisor with:
661 	 *
662 	 * div = PLL_mult * Fin / pclk
663 	 *
664 	 * and re-calculate the pixel clock using it:
665 	 *
666 	 * pclk = Fin * PLL_mult / CLKRC_div
667 	 *
668 	 * Choose the PLL_mult and CLKRC_div pair that gives a pixel clock
669 	 * closer to the desired one.
670 	 *
671 	 * The desired pixel clock is calculated using a known frame size
672 	 * (blanking included) and FPS.
673 	 */
674 	best_diff = ~0L;
675 	for (i = 0; i < ARRAY_SIZE(ov772x_pll); i++) {
676 		unsigned int pll_mult = ov772x_pll[i].mult;
677 		unsigned int pll_out = pll_mult * fin;
678 		unsigned int t_pclk;
679 		unsigned int div;
680 
681 		if (pll_out < pclk)
682 			continue;
683 
684 		div = DIV_ROUND_CLOSEST(pll_out, pclk);
685 		t_pclk = DIV_ROUND_CLOSEST(fin * pll_mult, div);
686 		diff = abs(pclk - t_pclk);
687 		if (diff < best_diff) {
688 			best_diff = diff;
689 			clkrc = CLKRC_DIV(div);
690 			com4 = ov772x_pll[i].com4;
691 		}
692 	}
693 
694 	ret = regmap_write(priv->regmap, COM4, com4 | COM4_RESERVED);
695 	if (ret < 0)
696 		return ret;
697 
698 	ret = regmap_write(priv->regmap, CLKRC, clkrc | CLKRC_RESERVED);
699 	if (ret < 0)
700 		return ret;
701 
702 	return 0;
703 }
704 
705 static int ov772x_g_frame_interval(struct v4l2_subdev *sd,
706 				   struct v4l2_subdev_frame_interval *ival)
707 {
708 	struct ov772x_priv *priv = to_ov772x(sd);
709 	struct v4l2_fract *tpf = &ival->interval;
710 
711 	tpf->numerator = 1;
712 	tpf->denominator = priv->fps;
713 
714 	return 0;
715 }
716 
717 static int ov772x_s_frame_interval(struct v4l2_subdev *sd,
718 				   struct v4l2_subdev_frame_interval *ival)
719 {
720 	struct ov772x_priv *priv = to_ov772x(sd);
721 	struct v4l2_fract *tpf = &ival->interval;
722 	unsigned int fps;
723 	int ret = 0;
724 
725 	mutex_lock(&priv->lock);
726 
727 	if (priv->streaming) {
728 		ret = -EBUSY;
729 		goto error;
730 	}
731 
732 	fps = ov772x_select_fps(priv, tpf);
733 
734 	/*
735 	 * If the device is not powered up by the host driver do
736 	 * not apply any changes to H/W at this time. Instead
737 	 * the frame rate will be restored right after power-up.
738 	 */
739 	if (priv->power_count > 0) {
740 		ret = ov772x_set_frame_rate(priv, fps, priv->cfmt, priv->win);
741 		if (ret)
742 			goto error;
743 	}
744 
745 	tpf->numerator = 1;
746 	tpf->denominator = fps;
747 	priv->fps = fps;
748 
749 error:
750 	mutex_unlock(&priv->lock);
751 
752 	return ret;
753 }
754 
755 static int ov772x_s_ctrl(struct v4l2_ctrl *ctrl)
756 {
757 	struct ov772x_priv *priv = container_of(ctrl->handler,
758 						struct ov772x_priv, hdl);
759 	struct regmap *regmap = priv->regmap;
760 	int ret = 0;
761 	u8 val;
762 
763 	/* v4l2_ctrl_lock() locks our own mutex */
764 
765 	/*
766 	 * If the device is not powered up by the host driver do
767 	 * not apply any controls to H/W at this time. Instead
768 	 * the controls will be restored right after power-up.
769 	 */
770 	if (priv->power_count == 0)
771 		return 0;
772 
773 	switch (ctrl->id) {
774 	case V4L2_CID_VFLIP:
775 		val = ctrl->val ? VFLIP_IMG : 0x00;
776 		if (priv->info && (priv->info->flags & OV772X_FLAG_VFLIP))
777 			val ^= VFLIP_IMG;
778 		return regmap_update_bits(regmap, COM3, VFLIP_IMG, val);
779 	case V4L2_CID_HFLIP:
780 		val = ctrl->val ? HFLIP_IMG : 0x00;
781 		if (priv->info && (priv->info->flags & OV772X_FLAG_HFLIP))
782 			val ^= HFLIP_IMG;
783 		return regmap_update_bits(regmap, COM3, HFLIP_IMG, val);
784 	case V4L2_CID_BAND_STOP_FILTER:
785 		if (!ctrl->val) {
786 			/* Switch the filter off, it is on now */
787 			ret = regmap_update_bits(regmap, BDBASE, 0xff, 0xff);
788 			if (!ret)
789 				ret = regmap_update_bits(regmap, COM8,
790 							 BNDF_ON_OFF, 0);
791 		} else {
792 			/* Switch the filter on, set AEC low limit */
793 			val = 256 - ctrl->val;
794 			ret = regmap_update_bits(regmap, COM8,
795 						 BNDF_ON_OFF, BNDF_ON_OFF);
796 			if (!ret)
797 				ret = regmap_update_bits(regmap, BDBASE,
798 							 0xff, val);
799 		}
800 
801 		return ret;
802 	}
803 
804 	return -EINVAL;
805 }
806 
807 #ifdef CONFIG_VIDEO_ADV_DEBUG
808 static int ov772x_g_register(struct v4l2_subdev *sd,
809 			     struct v4l2_dbg_register *reg)
810 {
811 	struct ov772x_priv *priv = to_ov772x(sd);
812 	int ret;
813 	unsigned int val;
814 
815 	reg->size = 1;
816 	if (reg->reg > 0xff)
817 		return -EINVAL;
818 
819 	ret = regmap_read(priv->regmap, reg->reg, &val);
820 	if (ret < 0)
821 		return ret;
822 
823 	reg->val = (__u64)val;
824 
825 	return 0;
826 }
827 
828 static int ov772x_s_register(struct v4l2_subdev *sd,
829 			     const struct v4l2_dbg_register *reg)
830 {
831 	struct ov772x_priv *priv = to_ov772x(sd);
832 
833 	if (reg->reg > 0xff ||
834 	    reg->val > 0xff)
835 		return -EINVAL;
836 
837 	return regmap_write(priv->regmap, reg->reg, reg->val);
838 }
839 #endif
840 
841 static int ov772x_power_on(struct ov772x_priv *priv)
842 {
843 	struct i2c_client *client = v4l2_get_subdevdata(&priv->subdev);
844 	int ret;
845 
846 	if (priv->clk) {
847 		ret = clk_prepare_enable(priv->clk);
848 		if (ret)
849 			return ret;
850 	}
851 
852 	if (priv->pwdn_gpio) {
853 		gpiod_set_value(priv->pwdn_gpio, 1);
854 		usleep_range(500, 1000);
855 	}
856 
857 	/*
858 	 * FIXME: The reset signal is connected to a shared GPIO on some
859 	 * platforms (namely the SuperH Migo-R). Until a framework becomes
860 	 * available to handle this cleanly, request the GPIO temporarily
861 	 * to avoid conflicts.
862 	 */
863 	priv->rstb_gpio = gpiod_get_optional(&client->dev, "reset",
864 					     GPIOD_OUT_LOW);
865 	if (IS_ERR(priv->rstb_gpio)) {
866 		dev_info(&client->dev, "Unable to get GPIO \"reset\"");
867 		clk_disable_unprepare(priv->clk);
868 		return PTR_ERR(priv->rstb_gpio);
869 	}
870 
871 	if (priv->rstb_gpio) {
872 		gpiod_set_value(priv->rstb_gpio, 1);
873 		usleep_range(500, 1000);
874 		gpiod_set_value(priv->rstb_gpio, 0);
875 		usleep_range(500, 1000);
876 
877 		gpiod_put(priv->rstb_gpio);
878 	}
879 
880 	return 0;
881 }
882 
883 static int ov772x_power_off(struct ov772x_priv *priv)
884 {
885 	clk_disable_unprepare(priv->clk);
886 
887 	if (priv->pwdn_gpio) {
888 		gpiod_set_value(priv->pwdn_gpio, 0);
889 		usleep_range(500, 1000);
890 	}
891 
892 	return 0;
893 }
894 
895 static int ov772x_set_params(struct ov772x_priv *priv,
896 			     const struct ov772x_color_format *cfmt,
897 			     const struct ov772x_win_size *win);
898 
899 static int ov772x_s_power(struct v4l2_subdev *sd, int on)
900 {
901 	struct ov772x_priv *priv = to_ov772x(sd);
902 	int ret = 0;
903 
904 	mutex_lock(&priv->lock);
905 
906 	/* If the power count is modified from 0 to != 0 or from != 0 to 0,
907 	 * update the power state.
908 	 */
909 	if (priv->power_count == !on) {
910 		if (on) {
911 			ret = ov772x_power_on(priv);
912 			/*
913 			 * Restore the format, the frame rate, and
914 			 * the controls
915 			 */
916 			if (!ret)
917 				ret = ov772x_set_params(priv, priv->cfmt,
918 							priv->win);
919 		} else {
920 			ret = ov772x_power_off(priv);
921 		}
922 	}
923 
924 	if (!ret) {
925 		/* Update the power count. */
926 		priv->power_count += on ? 1 : -1;
927 		WARN(priv->power_count < 0, "Unbalanced power count\n");
928 		WARN(priv->power_count > 1, "Duplicated s_power call\n");
929 	}
930 
931 	mutex_unlock(&priv->lock);
932 
933 	return ret;
934 }
935 
936 static const struct ov772x_win_size *ov772x_select_win(u32 width, u32 height)
937 {
938 	const struct ov772x_win_size *win = &ov772x_win_sizes[0];
939 	u32 best_diff = UINT_MAX;
940 	unsigned int i;
941 
942 	for (i = 0; i < ARRAY_SIZE(ov772x_win_sizes); ++i) {
943 		u32 diff = abs(width - ov772x_win_sizes[i].rect.width)
944 			 + abs(height - ov772x_win_sizes[i].rect.height);
945 		if (diff < best_diff) {
946 			best_diff = diff;
947 			win = &ov772x_win_sizes[i];
948 		}
949 	}
950 
951 	return win;
952 }
953 
954 static void ov772x_select_params(const struct v4l2_mbus_framefmt *mf,
955 				 const struct ov772x_color_format **cfmt,
956 				 const struct ov772x_win_size **win)
957 {
958 	unsigned int i;
959 
960 	/* Select a format. */
961 	*cfmt = &ov772x_cfmts[0];
962 
963 	for (i = 0; i < ARRAY_SIZE(ov772x_cfmts); i++) {
964 		if (mf->code == ov772x_cfmts[i].code) {
965 			*cfmt = &ov772x_cfmts[i];
966 			break;
967 		}
968 	}
969 
970 	/* Select a window size. */
971 	*win = ov772x_select_win(mf->width, mf->height);
972 }
973 
974 static int ov772x_edgectrl(struct ov772x_priv *priv)
975 {
976 	struct regmap *regmap = priv->regmap;
977 	int ret;
978 
979 	if (!priv->info)
980 		return 0;
981 
982 	if (priv->info->edgectrl.strength & OV772X_MANUAL_EDGE_CTRL) {
983 		/*
984 		 * Manual Edge Control Mode.
985 		 *
986 		 * Edge auto strength bit is set by default.
987 		 * Remove it when manual mode.
988 		 */
989 
990 		ret = regmap_update_bits(regmap, DSPAUTO, EDGE_ACTRL, 0x00);
991 		if (ret < 0)
992 			return ret;
993 
994 		ret = regmap_update_bits(regmap, EDGE_TRSHLD,
995 					 OV772X_EDGE_THRESHOLD_MASK,
996 					 priv->info->edgectrl.threshold);
997 		if (ret < 0)
998 			return ret;
999 
1000 		ret = regmap_update_bits(regmap, EDGE_STRNGT,
1001 					 OV772X_EDGE_STRENGTH_MASK,
1002 					 priv->info->edgectrl.strength);
1003 		if (ret < 0)
1004 			return ret;
1005 
1006 	} else if (priv->info->edgectrl.upper > priv->info->edgectrl.lower) {
1007 		/*
1008 		 * Auto Edge Control Mode.
1009 		 *
1010 		 * Set upper and lower limit.
1011 		 */
1012 		ret = regmap_update_bits(regmap, EDGE_UPPER,
1013 					 OV772X_EDGE_UPPER_MASK,
1014 					 priv->info->edgectrl.upper);
1015 		if (ret < 0)
1016 			return ret;
1017 
1018 		ret = regmap_update_bits(regmap, EDGE_LOWER,
1019 					 OV772X_EDGE_LOWER_MASK,
1020 					 priv->info->edgectrl.lower);
1021 		if (ret < 0)
1022 			return ret;
1023 	}
1024 
1025 	return 0;
1026 }
1027 
1028 static int ov772x_set_params(struct ov772x_priv *priv,
1029 			     const struct ov772x_color_format *cfmt,
1030 			     const struct ov772x_win_size *win)
1031 {
1032 	int ret;
1033 	u8  val;
1034 
1035 	/* Reset hardware. */
1036 	ov772x_reset(priv);
1037 
1038 	/* Edge Ctrl. */
1039 	ret = ov772x_edgectrl(priv);
1040 	if (ret < 0)
1041 		return ret;
1042 
1043 	/* Format and window size. */
1044 	ret = regmap_write(priv->regmap, HSTART, win->rect.left >> 2);
1045 	if (ret < 0)
1046 		goto ov772x_set_fmt_error;
1047 	ret = regmap_write(priv->regmap, HSIZE, win->rect.width >> 2);
1048 	if (ret < 0)
1049 		goto ov772x_set_fmt_error;
1050 	ret = regmap_write(priv->regmap, VSTART, win->rect.top >> 1);
1051 	if (ret < 0)
1052 		goto ov772x_set_fmt_error;
1053 	ret = regmap_write(priv->regmap, VSIZE, win->rect.height >> 1);
1054 	if (ret < 0)
1055 		goto ov772x_set_fmt_error;
1056 	ret = regmap_write(priv->regmap, HOUTSIZE, win->rect.width >> 2);
1057 	if (ret < 0)
1058 		goto ov772x_set_fmt_error;
1059 	ret = regmap_write(priv->regmap, VOUTSIZE, win->rect.height >> 1);
1060 	if (ret < 0)
1061 		goto ov772x_set_fmt_error;
1062 	ret = regmap_write(priv->regmap, HREF,
1063 			   ((win->rect.top & 1) << HREF_VSTART_SHIFT) |
1064 			   ((win->rect.left & 3) << HREF_HSTART_SHIFT) |
1065 			   ((win->rect.height & 1) << HREF_VSIZE_SHIFT) |
1066 			   ((win->rect.width & 3) << HREF_HSIZE_SHIFT));
1067 	if (ret < 0)
1068 		goto ov772x_set_fmt_error;
1069 	ret = regmap_write(priv->regmap, EXHCH,
1070 			   ((win->rect.height & 1) << EXHCH_VSIZE_SHIFT) |
1071 			   ((win->rect.width & 3) << EXHCH_HSIZE_SHIFT));
1072 	if (ret < 0)
1073 		goto ov772x_set_fmt_error;
1074 
1075 	/* Set DSP_CTRL3. */
1076 	val = cfmt->dsp3;
1077 	if (val) {
1078 		ret = regmap_update_bits(priv->regmap, DSP_CTRL3, UV_MASK, val);
1079 		if (ret < 0)
1080 			goto ov772x_set_fmt_error;
1081 	}
1082 
1083 	/* DSP_CTRL4: AEC reference point and DSP output format. */
1084 	if (cfmt->dsp4) {
1085 		ret = regmap_write(priv->regmap, DSP_CTRL4, cfmt->dsp4);
1086 		if (ret < 0)
1087 			goto ov772x_set_fmt_error;
1088 	}
1089 
1090 	/* Set COM3. */
1091 	val = cfmt->com3;
1092 	if (priv->info && (priv->info->flags & OV772X_FLAG_VFLIP))
1093 		val |= VFLIP_IMG;
1094 	if (priv->info && (priv->info->flags & OV772X_FLAG_HFLIP))
1095 		val |= HFLIP_IMG;
1096 	if (priv->vflip_ctrl->val)
1097 		val ^= VFLIP_IMG;
1098 	if (priv->hflip_ctrl->val)
1099 		val ^= HFLIP_IMG;
1100 
1101 	ret = regmap_update_bits(priv->regmap, COM3, SWAP_MASK | IMG_MASK, val);
1102 	if (ret < 0)
1103 		goto ov772x_set_fmt_error;
1104 
1105 	/* COM7: Sensor resolution and output format control. */
1106 	ret = regmap_write(priv->regmap, COM7, win->com7_bit | cfmt->com7);
1107 	if (ret < 0)
1108 		goto ov772x_set_fmt_error;
1109 
1110 	/* COM4, CLKRC: Set pixel clock and framerate. */
1111 	ret = ov772x_set_frame_rate(priv, priv->fps, cfmt, win);
1112 	if (ret < 0)
1113 		goto ov772x_set_fmt_error;
1114 
1115 	/* Set COM8. */
1116 	if (priv->band_filter_ctrl->val) {
1117 		unsigned short band_filter = priv->band_filter_ctrl->val;
1118 
1119 		ret = regmap_update_bits(priv->regmap, COM8,
1120 					 BNDF_ON_OFF, BNDF_ON_OFF);
1121 		if (!ret)
1122 			ret = regmap_update_bits(priv->regmap, BDBASE,
1123 						 0xff, 256 - band_filter);
1124 		if (ret < 0)
1125 			goto ov772x_set_fmt_error;
1126 	}
1127 
1128 	return ret;
1129 
1130 ov772x_set_fmt_error:
1131 
1132 	ov772x_reset(priv);
1133 
1134 	return ret;
1135 }
1136 
1137 static int ov772x_get_selection(struct v4l2_subdev *sd,
1138 				struct v4l2_subdev_pad_config *cfg,
1139 				struct v4l2_subdev_selection *sel)
1140 {
1141 	struct ov772x_priv *priv = to_ov772x(sd);
1142 
1143 	if (sel->which != V4L2_SUBDEV_FORMAT_ACTIVE)
1144 		return -EINVAL;
1145 
1146 	sel->r.left = 0;
1147 	sel->r.top = 0;
1148 	switch (sel->target) {
1149 	case V4L2_SEL_TGT_CROP_BOUNDS:
1150 	case V4L2_SEL_TGT_CROP:
1151 		sel->r.width = priv->win->rect.width;
1152 		sel->r.height = priv->win->rect.height;
1153 		return 0;
1154 	default:
1155 		return -EINVAL;
1156 	}
1157 }
1158 
1159 static int ov772x_get_fmt(struct v4l2_subdev *sd,
1160 			  struct v4l2_subdev_pad_config *cfg,
1161 			  struct v4l2_subdev_format *format)
1162 {
1163 	struct v4l2_mbus_framefmt *mf = &format->format;
1164 	struct ov772x_priv *priv = to_ov772x(sd);
1165 
1166 	if (format->pad)
1167 		return -EINVAL;
1168 
1169 	mf->width	= priv->win->rect.width;
1170 	mf->height	= priv->win->rect.height;
1171 	mf->code	= priv->cfmt->code;
1172 	mf->colorspace	= priv->cfmt->colorspace;
1173 	mf->field	= V4L2_FIELD_NONE;
1174 
1175 	return 0;
1176 }
1177 
1178 static int ov772x_set_fmt(struct v4l2_subdev *sd,
1179 			  struct v4l2_subdev_pad_config *cfg,
1180 			  struct v4l2_subdev_format *format)
1181 {
1182 	struct ov772x_priv *priv = to_ov772x(sd);
1183 	struct v4l2_mbus_framefmt *mf = &format->format;
1184 	const struct ov772x_color_format *cfmt;
1185 	const struct ov772x_win_size *win;
1186 	int ret = 0;
1187 
1188 	if (format->pad)
1189 		return -EINVAL;
1190 
1191 	ov772x_select_params(mf, &cfmt, &win);
1192 
1193 	mf->code = cfmt->code;
1194 	mf->width = win->rect.width;
1195 	mf->height = win->rect.height;
1196 	mf->field = V4L2_FIELD_NONE;
1197 	mf->colorspace = cfmt->colorspace;
1198 	mf->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
1199 	mf->quantization = V4L2_QUANTIZATION_DEFAULT;
1200 	mf->xfer_func = V4L2_XFER_FUNC_DEFAULT;
1201 
1202 	if (format->which == V4L2_SUBDEV_FORMAT_TRY) {
1203 		cfg->try_fmt = *mf;
1204 		return 0;
1205 	}
1206 
1207 	mutex_lock(&priv->lock);
1208 
1209 	if (priv->streaming) {
1210 		ret = -EBUSY;
1211 		goto error;
1212 	}
1213 
1214 	/*
1215 	 * If the device is not powered up by the host driver do
1216 	 * not apply any changes to H/W at this time. Instead
1217 	 * the format will be restored right after power-up.
1218 	 */
1219 	if (priv->power_count > 0) {
1220 		ret = ov772x_set_params(priv, cfmt, win);
1221 		if (ret < 0)
1222 			goto error;
1223 	}
1224 	priv->win = win;
1225 	priv->cfmt = cfmt;
1226 
1227 error:
1228 	mutex_unlock(&priv->lock);
1229 
1230 	return ret;
1231 }
1232 
1233 static int ov772x_video_probe(struct ov772x_priv *priv)
1234 {
1235 	struct i2c_client  *client = v4l2_get_subdevdata(&priv->subdev);
1236 	int		    pid, ver, midh, midl;
1237 	const char         *devname;
1238 	int		    ret;
1239 
1240 	ret = ov772x_power_on(priv);
1241 	if (ret < 0)
1242 		return ret;
1243 
1244 	/* Check and show product ID and manufacturer ID. */
1245 	ret = regmap_read(priv->regmap, PID, &pid);
1246 	if (ret < 0)
1247 		return ret;
1248 	ret = regmap_read(priv->regmap, VER, &ver);
1249 	if (ret < 0)
1250 		return ret;
1251 
1252 	switch (VERSION(pid, ver)) {
1253 	case OV7720:
1254 		devname     = "ov7720";
1255 		break;
1256 	case OV7725:
1257 		devname     = "ov7725";
1258 		break;
1259 	default:
1260 		dev_err(&client->dev,
1261 			"Product ID error %x:%x\n", pid, ver);
1262 		ret = -ENODEV;
1263 		goto done;
1264 	}
1265 
1266 	ret = regmap_read(priv->regmap, MIDH, &midh);
1267 	if (ret < 0)
1268 		return ret;
1269 	ret = regmap_read(priv->regmap, MIDL, &midl);
1270 	if (ret < 0)
1271 		return ret;
1272 
1273 	dev_info(&client->dev,
1274 		 "%s Product ID %0x:%0x Manufacturer ID %x:%x\n",
1275 		 devname, pid, ver, midh, midl);
1276 
1277 	ret = v4l2_ctrl_handler_setup(&priv->hdl);
1278 
1279 done:
1280 	ov772x_power_off(priv);
1281 
1282 	return ret;
1283 }
1284 
1285 static const struct v4l2_ctrl_ops ov772x_ctrl_ops = {
1286 	.s_ctrl = ov772x_s_ctrl,
1287 };
1288 
1289 static const struct v4l2_subdev_core_ops ov772x_subdev_core_ops = {
1290 #ifdef CONFIG_VIDEO_ADV_DEBUG
1291 	.g_register	= ov772x_g_register,
1292 	.s_register	= ov772x_s_register,
1293 #endif
1294 	.s_power	= ov772x_s_power,
1295 };
1296 
1297 static int ov772x_enum_frame_interval(struct v4l2_subdev *sd,
1298 				      struct v4l2_subdev_pad_config *cfg,
1299 				      struct v4l2_subdev_frame_interval_enum *fie)
1300 {
1301 	if (fie->pad || fie->index >= ARRAY_SIZE(ov772x_frame_intervals))
1302 		return -EINVAL;
1303 
1304 	if (fie->width != VGA_WIDTH && fie->width != QVGA_WIDTH)
1305 		return -EINVAL;
1306 	if (fie->height != VGA_HEIGHT && fie->height != QVGA_HEIGHT)
1307 		return -EINVAL;
1308 
1309 	fie->interval.numerator = 1;
1310 	fie->interval.denominator = ov772x_frame_intervals[fie->index];
1311 
1312 	return 0;
1313 }
1314 
1315 static int ov772x_enum_mbus_code(struct v4l2_subdev *sd,
1316 				 struct v4l2_subdev_pad_config *cfg,
1317 				 struct v4l2_subdev_mbus_code_enum *code)
1318 {
1319 	if (code->pad || code->index >= ARRAY_SIZE(ov772x_cfmts))
1320 		return -EINVAL;
1321 
1322 	code->code = ov772x_cfmts[code->index].code;
1323 
1324 	return 0;
1325 }
1326 
1327 static const struct v4l2_subdev_video_ops ov772x_subdev_video_ops = {
1328 	.s_stream		= ov772x_s_stream,
1329 	.s_frame_interval	= ov772x_s_frame_interval,
1330 	.g_frame_interval	= ov772x_g_frame_interval,
1331 };
1332 
1333 static const struct v4l2_subdev_pad_ops ov772x_subdev_pad_ops = {
1334 	.enum_frame_interval	= ov772x_enum_frame_interval,
1335 	.enum_mbus_code		= ov772x_enum_mbus_code,
1336 	.get_selection		= ov772x_get_selection,
1337 	.get_fmt		= ov772x_get_fmt,
1338 	.set_fmt		= ov772x_set_fmt,
1339 };
1340 
1341 static const struct v4l2_subdev_ops ov772x_subdev_ops = {
1342 	.core	= &ov772x_subdev_core_ops,
1343 	.video	= &ov772x_subdev_video_ops,
1344 	.pad	= &ov772x_subdev_pad_ops,
1345 };
1346 
1347 /*
1348  * i2c_driver function
1349  */
1350 
1351 static int ov772x_probe(struct i2c_client *client,
1352 			const struct i2c_device_id *did)
1353 {
1354 	struct ov772x_priv	*priv;
1355 	int			ret;
1356 	static const struct regmap_config ov772x_regmap_config = {
1357 		.reg_bits = 8,
1358 		.val_bits = 8,
1359 		.max_register = DSPAUTO,
1360 	};
1361 
1362 	if (!client->dev.of_node && !client->dev.platform_data) {
1363 		dev_err(&client->dev,
1364 			"Missing ov772x platform data for non-DT device\n");
1365 		return -EINVAL;
1366 	}
1367 
1368 	priv = devm_kzalloc(&client->dev, sizeof(*priv), GFP_KERNEL);
1369 	if (!priv)
1370 		return -ENOMEM;
1371 
1372 	priv->regmap = devm_regmap_init_sccb(client, &ov772x_regmap_config);
1373 	if (IS_ERR(priv->regmap)) {
1374 		dev_err(&client->dev, "Failed to allocate register map\n");
1375 		return PTR_ERR(priv->regmap);
1376 	}
1377 
1378 	priv->info = client->dev.platform_data;
1379 	mutex_init(&priv->lock);
1380 
1381 	v4l2_i2c_subdev_init(&priv->subdev, client, &ov772x_subdev_ops);
1382 	priv->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
1383 	v4l2_ctrl_handler_init(&priv->hdl, 3);
1384 	/* Use our mutex for the controls */
1385 	priv->hdl.lock = &priv->lock;
1386 	priv->vflip_ctrl = v4l2_ctrl_new_std(&priv->hdl, &ov772x_ctrl_ops,
1387 					     V4L2_CID_VFLIP, 0, 1, 1, 0);
1388 	priv->hflip_ctrl = v4l2_ctrl_new_std(&priv->hdl, &ov772x_ctrl_ops,
1389 					     V4L2_CID_HFLIP, 0, 1, 1, 0);
1390 	priv->band_filter_ctrl = v4l2_ctrl_new_std(&priv->hdl, &ov772x_ctrl_ops,
1391 						   V4L2_CID_BAND_STOP_FILTER,
1392 						   0, 256, 1, 0);
1393 	priv->subdev.ctrl_handler = &priv->hdl;
1394 	if (priv->hdl.error) {
1395 		ret = priv->hdl.error;
1396 		goto error_mutex_destroy;
1397 	}
1398 
1399 	priv->clk = clk_get(&client->dev, NULL);
1400 	if (IS_ERR(priv->clk)) {
1401 		dev_err(&client->dev, "Unable to get xclk clock\n");
1402 		ret = PTR_ERR(priv->clk);
1403 		goto error_ctrl_free;
1404 	}
1405 
1406 	priv->pwdn_gpio = gpiod_get_optional(&client->dev, "powerdown",
1407 					     GPIOD_OUT_LOW);
1408 	if (IS_ERR(priv->pwdn_gpio)) {
1409 		dev_info(&client->dev, "Unable to get GPIO \"powerdown\"");
1410 		ret = PTR_ERR(priv->pwdn_gpio);
1411 		goto error_clk_put;
1412 	}
1413 
1414 	ret = ov772x_video_probe(priv);
1415 	if (ret < 0)
1416 		goto error_gpio_put;
1417 
1418 #ifdef CONFIG_MEDIA_CONTROLLER
1419 	priv->pad.flags = MEDIA_PAD_FL_SOURCE;
1420 	priv->subdev.entity.function = MEDIA_ENT_F_CAM_SENSOR;
1421 	ret = media_entity_pads_init(&priv->subdev.entity, 1, &priv->pad);
1422 	if (ret < 0)
1423 		goto error_gpio_put;
1424 #endif
1425 
1426 	priv->cfmt = &ov772x_cfmts[0];
1427 	priv->win = &ov772x_win_sizes[0];
1428 	priv->fps = 15;
1429 
1430 	ret = v4l2_async_register_subdev(&priv->subdev);
1431 	if (ret)
1432 		goto error_entity_cleanup;
1433 
1434 	return 0;
1435 
1436 error_entity_cleanup:
1437 	media_entity_cleanup(&priv->subdev.entity);
1438 error_gpio_put:
1439 	if (priv->pwdn_gpio)
1440 		gpiod_put(priv->pwdn_gpio);
1441 error_clk_put:
1442 	clk_put(priv->clk);
1443 error_ctrl_free:
1444 	v4l2_ctrl_handler_free(&priv->hdl);
1445 error_mutex_destroy:
1446 	mutex_destroy(&priv->lock);
1447 
1448 	return ret;
1449 }
1450 
1451 static int ov772x_remove(struct i2c_client *client)
1452 {
1453 	struct ov772x_priv *priv = to_ov772x(i2c_get_clientdata(client));
1454 
1455 	media_entity_cleanup(&priv->subdev.entity);
1456 	clk_put(priv->clk);
1457 	if (priv->pwdn_gpio)
1458 		gpiod_put(priv->pwdn_gpio);
1459 	v4l2_async_unregister_subdev(&priv->subdev);
1460 	v4l2_ctrl_handler_free(&priv->hdl);
1461 	mutex_destroy(&priv->lock);
1462 
1463 	return 0;
1464 }
1465 
1466 static const struct i2c_device_id ov772x_id[] = {
1467 	{ "ov772x", 0 },
1468 	{ }
1469 };
1470 MODULE_DEVICE_TABLE(i2c, ov772x_id);
1471 
1472 static const struct of_device_id ov772x_of_match[] = {
1473 	{ .compatible = "ovti,ov7725", },
1474 	{ .compatible = "ovti,ov7720", },
1475 	{ /* sentinel */ },
1476 };
1477 MODULE_DEVICE_TABLE(of, ov772x_of_match);
1478 
1479 static struct i2c_driver ov772x_i2c_driver = {
1480 	.driver = {
1481 		.name = "ov772x",
1482 		.of_match_table = ov772x_of_match,
1483 	},
1484 	.probe    = ov772x_probe,
1485 	.remove   = ov772x_remove,
1486 	.id_table = ov772x_id,
1487 };
1488 
1489 module_i2c_driver(ov772x_i2c_driver);
1490 
1491 MODULE_DESCRIPTION("V4L2 driver for OV772x image sensor");
1492 MODULE_AUTHOR("Kuninori Morimoto");
1493 MODULE_LICENSE("GPL v2");
1494