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