e0a4c8920df8de8ebfc4d179c75f3658541c946a
[sfrench/cifs-2.6.git] / drivers / media / platform / am437x / am437x-vpfe.c
1 /*
2  * TI VPFE capture Driver
3  *
4  * Copyright (C) 2013 - 2014 Texas Instruments, Inc.
5  *
6  * Benoit Parrot <bparrot@ti.com>
7  * Lad, Prabhakar <prabhakar.csengg@gmail.com>
8  *
9  * This program is free software; you may redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; version 2 of the License.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
17  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
18  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  */
22
23 #include <linux/delay.h>
24 #include <linux/err.h>
25 #include <linux/init.h>
26 #include <linux/interrupt.h>
27 #include <linux/io.h>
28 #include <linux/module.h>
29 #include <linux/of_graph.h>
30 #include <linux/pinctrl/consumer.h>
31 #include <linux/platform_device.h>
32 #include <linux/pm_runtime.h>
33 #include <linux/slab.h>
34 #include <linux/uaccess.h>
35 #include <linux/videodev2.h>
36
37 #include <media/v4l2-common.h>
38 #include <media/v4l2-ctrls.h>
39 #include <media/v4l2-event.h>
40 #include <media/v4l2-fwnode.h>
41
42 #include "am437x-vpfe.h"
43
44 #define VPFE_MODULE_NAME        "vpfe"
45 #define VPFE_VERSION            "0.1.0"
46
47 static int debug;
48 module_param(debug, int, 0644);
49 MODULE_PARM_DESC(debug, "Debug level 0-8");
50
51 #define vpfe_dbg(level, dev, fmt, arg...)       \
52                 v4l2_dbg(level, debug, &dev->v4l2_dev, fmt, ##arg)
53 #define vpfe_info(dev, fmt, arg...)     \
54                 v4l2_info(&dev->v4l2_dev, fmt, ##arg)
55 #define vpfe_err(dev, fmt, arg...)      \
56                 v4l2_err(&dev->v4l2_dev, fmt, ##arg)
57
58 /* standard information */
59 struct vpfe_standard {
60         v4l2_std_id std_id;
61         unsigned int width;
62         unsigned int height;
63         struct v4l2_fract pixelaspect;
64         int frame_format;
65 };
66
67 static const struct vpfe_standard vpfe_standards[] = {
68         {V4L2_STD_525_60, 720, 480, {11, 10}, 1},
69         {V4L2_STD_625_50, 720, 576, {54, 59}, 1},
70 };
71
72 struct bus_format {
73         unsigned int width;
74         unsigned int bpp;
75 };
76
77 /*
78  * struct vpfe_fmt - VPFE media bus format information
79  * @code: V4L2 media bus format code
80  * @shifted: V4L2 media bus format code for the same pixel layout but
81  *      shifted to be 8 bits per pixel. =0 if format is not shiftable.
82  * @pixelformat: V4L2 pixel format FCC identifier
83  * @width: Bits per pixel (when transferred over a bus)
84  * @bpp: Bytes per pixel (when stored in memory)
85  * @supported: Indicates format supported by subdev
86  */
87 struct vpfe_fmt {
88         u32 fourcc;
89         u32 code;
90         struct bus_format l;
91         struct bus_format s;
92         bool supported;
93         u32 index;
94 };
95
96 static struct vpfe_fmt formats[] = {
97         {
98                 .fourcc         = V4L2_PIX_FMT_YUYV,
99                 .code           = MEDIA_BUS_FMT_YUYV8_2X8,
100                 .l.width        = 10,
101                 .l.bpp          = 4,
102                 .s.width        = 8,
103                 .s.bpp          = 2,
104                 .supported      = false,
105         }, {
106                 .fourcc         = V4L2_PIX_FMT_UYVY,
107                 .code           = MEDIA_BUS_FMT_UYVY8_2X8,
108                 .l.width        = 10,
109                 .l.bpp          = 4,
110                 .s.width        = 8,
111                 .s.bpp          = 2,
112                 .supported      = false,
113         }, {
114                 .fourcc         = V4L2_PIX_FMT_YVYU,
115                 .code           = MEDIA_BUS_FMT_YVYU8_2X8,
116                 .l.width        = 10,
117                 .l.bpp          = 4,
118                 .s.width        = 8,
119                 .s.bpp          = 2,
120                 .supported      = false,
121         }, {
122                 .fourcc         = V4L2_PIX_FMT_VYUY,
123                 .code           = MEDIA_BUS_FMT_VYUY8_2X8,
124                 .l.width        = 10,
125                 .l.bpp          = 4,
126                 .s.width        = 8,
127                 .s.bpp          = 2,
128                 .supported      = false,
129         }, {
130                 .fourcc         = V4L2_PIX_FMT_SBGGR8,
131                 .code           = MEDIA_BUS_FMT_SBGGR8_1X8,
132                 .l.width        = 10,
133                 .l.bpp          = 2,
134                 .s.width        = 8,
135                 .s.bpp          = 1,
136                 .supported      = false,
137         }, {
138                 .fourcc         = V4L2_PIX_FMT_SGBRG8,
139                 .code           = MEDIA_BUS_FMT_SGBRG8_1X8,
140                 .l.width        = 10,
141                 .l.bpp          = 2,
142                 .s.width        = 8,
143                 .s.bpp          = 1,
144                 .supported      = false,
145         }, {
146                 .fourcc         = V4L2_PIX_FMT_SGRBG8,
147                 .code           = MEDIA_BUS_FMT_SGRBG8_1X8,
148                 .l.width        = 10,
149                 .l.bpp          = 2,
150                 .s.width        = 8,
151                 .s.bpp          = 1,
152                 .supported      = false,
153         }, {
154                 .fourcc         = V4L2_PIX_FMT_SRGGB8,
155                 .code           = MEDIA_BUS_FMT_SRGGB8_1X8,
156                 .l.width        = 10,
157                 .l.bpp          = 2,
158                 .s.width        = 8,
159                 .s.bpp          = 1,
160                 .supported      = false,
161         }, {
162                 .fourcc         = V4L2_PIX_FMT_RGB565,
163                 .code           = MEDIA_BUS_FMT_RGB565_2X8_LE,
164                 .l.width        = 10,
165                 .l.bpp          = 4,
166                 .s.width        = 8,
167                 .s.bpp          = 2,
168                 .supported      = false,
169         }, {
170                 .fourcc         = V4L2_PIX_FMT_RGB565X,
171                 .code           = MEDIA_BUS_FMT_RGB565_2X8_BE,
172                 .l.width        = 10,
173                 .l.bpp          = 4,
174                 .s.width        = 8,
175                 .s.bpp          = 2,
176                 .supported      = false,
177         },
178 };
179
180 static int
181 __vpfe_get_format(struct vpfe_device *vpfe,
182                   struct v4l2_format *format, unsigned int *bpp);
183
184 static struct vpfe_fmt *find_format_by_code(unsigned int code)
185 {
186         struct vpfe_fmt *fmt;
187         unsigned int k;
188
189         for (k = 0; k < ARRAY_SIZE(formats); k++) {
190                 fmt = &formats[k];
191                 if (fmt->code == code)
192                         return fmt;
193         }
194
195         return NULL;
196 }
197
198 static struct vpfe_fmt *find_format_by_pix(unsigned int pixelformat)
199 {
200         struct vpfe_fmt *fmt;
201         unsigned int k;
202
203         for (k = 0; k < ARRAY_SIZE(formats); k++) {
204                 fmt = &formats[k];
205                 if (fmt->fourcc == pixelformat)
206                         return fmt;
207         }
208
209         return NULL;
210 }
211
212 static void
213 mbus_to_pix(struct vpfe_device *vpfe,
214             const struct v4l2_mbus_framefmt *mbus,
215             struct v4l2_pix_format *pix, unsigned int *bpp)
216 {
217         struct vpfe_subdev_info *sdinfo = vpfe->current_subdev;
218         unsigned int bus_width = sdinfo->vpfe_param.bus_width;
219         struct vpfe_fmt *fmt;
220
221         fmt = find_format_by_code(mbus->code);
222         if (WARN_ON(fmt == NULL)) {
223                 pr_err("Invalid mbus code set\n");
224                 *bpp = 1;
225                 return;
226         }
227
228         memset(pix, 0, sizeof(*pix));
229         v4l2_fill_pix_format(pix, mbus);
230         pix->pixelformat = fmt->fourcc;
231         *bpp = (bus_width == 10) ?  fmt->l.bpp : fmt->s.bpp;
232
233         /* pitch should be 32 bytes aligned */
234         pix->bytesperline = ALIGN(pix->width * *bpp, 32);
235         pix->sizeimage = pix->bytesperline * pix->height;
236 }
237
238 static void pix_to_mbus(struct vpfe_device *vpfe,
239                         struct v4l2_pix_format *pix_fmt,
240                         struct v4l2_mbus_framefmt *mbus_fmt)
241 {
242         struct vpfe_fmt *fmt;
243
244         fmt = find_format_by_pix(pix_fmt->pixelformat);
245         if (!fmt) {
246                 /* default to first entry */
247                 vpfe_dbg(3, vpfe, "Invalid pixel code: %x, default used instead\n",
248                         pix_fmt->pixelformat);
249                 fmt = &formats[0];
250         }
251
252         memset(mbus_fmt, 0, sizeof(*mbus_fmt));
253         v4l2_fill_mbus_format(mbus_fmt, pix_fmt, fmt->code);
254 }
255
256 /*  Print Four-character-code (FOURCC) */
257 static char *print_fourcc(u32 fmt)
258 {
259         static char code[5];
260
261         code[0] = (unsigned char)(fmt & 0xff);
262         code[1] = (unsigned char)((fmt >> 8) & 0xff);
263         code[2] = (unsigned char)((fmt >> 16) & 0xff);
264         code[3] = (unsigned char)((fmt >> 24) & 0xff);
265         code[4] = '\0';
266
267         return code;
268 }
269
270 static int
271 cmp_v4l2_format(const struct v4l2_format *lhs, const struct v4l2_format *rhs)
272 {
273         return lhs->type == rhs->type &&
274                 lhs->fmt.pix.width == rhs->fmt.pix.width &&
275                 lhs->fmt.pix.height == rhs->fmt.pix.height &&
276                 lhs->fmt.pix.pixelformat == rhs->fmt.pix.pixelformat &&
277                 lhs->fmt.pix.field == rhs->fmt.pix.field &&
278                 lhs->fmt.pix.colorspace == rhs->fmt.pix.colorspace &&
279                 lhs->fmt.pix.ycbcr_enc == rhs->fmt.pix.ycbcr_enc &&
280                 lhs->fmt.pix.quantization == rhs->fmt.pix.quantization &&
281                 lhs->fmt.pix.xfer_func == rhs->fmt.pix.xfer_func;
282 }
283
284 static inline u32 vpfe_reg_read(struct vpfe_ccdc *ccdc, u32 offset)
285 {
286         return ioread32(ccdc->ccdc_cfg.base_addr + offset);
287 }
288
289 static inline void vpfe_reg_write(struct vpfe_ccdc *ccdc, u32 val, u32 offset)
290 {
291         iowrite32(val, ccdc->ccdc_cfg.base_addr + offset);
292 }
293
294 static inline struct vpfe_device *to_vpfe(struct vpfe_ccdc *ccdc)
295 {
296         return container_of(ccdc, struct vpfe_device, ccdc);
297 }
298
299 static inline
300 struct vpfe_cap_buffer *to_vpfe_buffer(struct vb2_v4l2_buffer *vb)
301 {
302         return container_of(vb, struct vpfe_cap_buffer, vb);
303 }
304
305 static inline void vpfe_pcr_enable(struct vpfe_ccdc *ccdc, int flag)
306 {
307         vpfe_reg_write(ccdc, !!flag, VPFE_PCR);
308 }
309
310 static void vpfe_config_enable(struct vpfe_ccdc *ccdc, int flag)
311 {
312         unsigned int cfg;
313
314         if (!flag) {
315                 cfg = vpfe_reg_read(ccdc, VPFE_CONFIG);
316                 cfg &= ~(VPFE_CONFIG_EN_ENABLE << VPFE_CONFIG_EN_SHIFT);
317         } else {
318                 cfg = VPFE_CONFIG_EN_ENABLE << VPFE_CONFIG_EN_SHIFT;
319         }
320
321         vpfe_reg_write(ccdc, cfg, VPFE_CONFIG);
322 }
323
324 static void vpfe_ccdc_setwin(struct vpfe_ccdc *ccdc,
325                              struct v4l2_rect *image_win,
326                              enum ccdc_frmfmt frm_fmt,
327                              int bpp)
328 {
329         int horz_start, horz_nr_pixels;
330         int vert_start, vert_nr_lines;
331         int val, mid_img;
332
333         /*
334          * ppc - per pixel count. indicates how many pixels per cell
335          * output to SDRAM. example, for ycbcr, it is one y and one c, so 2.
336          * raw capture this is 1
337          */
338         horz_start = image_win->left * bpp;
339         horz_nr_pixels = (image_win->width * bpp) - 1;
340         vpfe_reg_write(ccdc, (horz_start << VPFE_HORZ_INFO_SPH_SHIFT) |
341                                 horz_nr_pixels, VPFE_HORZ_INFO);
342
343         vert_start = image_win->top;
344
345         if (frm_fmt == CCDC_FRMFMT_INTERLACED) {
346                 vert_nr_lines = (image_win->height >> 1) - 1;
347                 vert_start >>= 1;
348                 /* configure VDINT0 */
349                 val = (vert_start << VPFE_VDINT_VDINT0_SHIFT);
350         } else {
351                 vert_nr_lines = image_win->height - 1;
352                 /*
353                  * configure VDINT0 and VDINT1. VDINT1 will be at half
354                  * of image height
355                  */
356                 mid_img = vert_start + (image_win->height / 2);
357                 val = (vert_start << VPFE_VDINT_VDINT0_SHIFT) |
358                                 (mid_img & VPFE_VDINT_VDINT1_MASK);
359         }
360
361         vpfe_reg_write(ccdc, val, VPFE_VDINT);
362
363         vpfe_reg_write(ccdc, (vert_start << VPFE_VERT_START_SLV0_SHIFT) |
364                                 vert_start, VPFE_VERT_START);
365         vpfe_reg_write(ccdc, vert_nr_lines, VPFE_VERT_LINES);
366 }
367
368 static void vpfe_reg_dump(struct vpfe_ccdc *ccdc)
369 {
370         struct vpfe_device *vpfe = to_vpfe(ccdc);
371
372         vpfe_dbg(3, vpfe, "ALAW: 0x%x\n", vpfe_reg_read(ccdc, VPFE_ALAW));
373         vpfe_dbg(3, vpfe, "CLAMP: 0x%x\n", vpfe_reg_read(ccdc, VPFE_CLAMP));
374         vpfe_dbg(3, vpfe, "DCSUB: 0x%x\n", vpfe_reg_read(ccdc, VPFE_DCSUB));
375         vpfe_dbg(3, vpfe, "BLKCMP: 0x%x\n", vpfe_reg_read(ccdc, VPFE_BLKCMP));
376         vpfe_dbg(3, vpfe, "COLPTN: 0x%x\n", vpfe_reg_read(ccdc, VPFE_COLPTN));
377         vpfe_dbg(3, vpfe, "SDOFST: 0x%x\n", vpfe_reg_read(ccdc, VPFE_SDOFST));
378         vpfe_dbg(3, vpfe, "SYN_MODE: 0x%x\n",
379                  vpfe_reg_read(ccdc, VPFE_SYNMODE));
380         vpfe_dbg(3, vpfe, "HSIZE_OFF: 0x%x\n",
381                  vpfe_reg_read(ccdc, VPFE_HSIZE_OFF));
382         vpfe_dbg(3, vpfe, "HORZ_INFO: 0x%x\n",
383                  vpfe_reg_read(ccdc, VPFE_HORZ_INFO));
384         vpfe_dbg(3, vpfe, "VERT_START: 0x%x\n",
385                  vpfe_reg_read(ccdc, VPFE_VERT_START));
386         vpfe_dbg(3, vpfe, "VERT_LINES: 0x%x\n",
387                  vpfe_reg_read(ccdc, VPFE_VERT_LINES));
388 }
389
390 static int
391 vpfe_ccdc_validate_param(struct vpfe_ccdc *ccdc,
392                          struct vpfe_ccdc_config_params_raw *ccdcparam)
393 {
394         struct vpfe_device *vpfe = to_vpfe(ccdc);
395         u8 max_gamma, max_data;
396
397         if (!ccdcparam->alaw.enable)
398                 return 0;
399
400         max_gamma = ccdc_gamma_width_max_bit(ccdcparam->alaw.gamma_wd);
401         max_data = ccdc_data_size_max_bit(ccdcparam->data_sz);
402
403         if (ccdcparam->alaw.gamma_wd > VPFE_CCDC_GAMMA_BITS_09_0 ||
404             ccdcparam->alaw.gamma_wd < VPFE_CCDC_GAMMA_BITS_15_6 ||
405             max_gamma > max_data) {
406                 vpfe_dbg(1, vpfe, "Invalid data line select\n");
407                 return -EINVAL;
408         }
409
410         return 0;
411 }
412
413 static void
414 vpfe_ccdc_update_raw_params(struct vpfe_ccdc *ccdc,
415                             struct vpfe_ccdc_config_params_raw *raw_params)
416 {
417         struct vpfe_ccdc_config_params_raw *config_params =
418                                 &ccdc->ccdc_cfg.bayer.config_params;
419
420         *config_params = *raw_params;
421 }
422
423 /*
424  * vpfe_ccdc_restore_defaults()
425  * This function will write defaults to all CCDC registers
426  */
427 static void vpfe_ccdc_restore_defaults(struct vpfe_ccdc *ccdc)
428 {
429         int i;
430
431         /* Disable CCDC */
432         vpfe_pcr_enable(ccdc, 0);
433
434         /* set all registers to default value */
435         for (i = 4; i <= 0x94; i += 4)
436                 vpfe_reg_write(ccdc, 0,  i);
437
438         vpfe_reg_write(ccdc, VPFE_NO_CULLING, VPFE_CULLING);
439         vpfe_reg_write(ccdc, VPFE_CCDC_GAMMA_BITS_11_2, VPFE_ALAW);
440 }
441
442 static int vpfe_ccdc_close(struct vpfe_ccdc *ccdc, struct device *dev)
443 {
444         struct vpfe_device *vpfe = container_of(ccdc, struct vpfe_device, ccdc);
445         u32 dma_cntl, pcr;
446
447         pcr = vpfe_reg_read(ccdc, VPFE_PCR);
448         if (pcr)
449                 vpfe_dbg(1, vpfe, "VPFE_PCR is still set (%x)", pcr);
450
451         dma_cntl = vpfe_reg_read(ccdc, VPFE_DMA_CNTL);
452         if ((dma_cntl & VPFE_DMA_CNTL_OVERFLOW))
453                 vpfe_dbg(1, vpfe, "VPFE_DMA_CNTL_OVERFLOW is still set (%x)",
454                          dma_cntl);
455
456         /* Disable CCDC by resetting all register to default POR values */
457         vpfe_ccdc_restore_defaults(ccdc);
458
459         /* Disabled the module at the CONFIG level */
460         vpfe_config_enable(ccdc, 0);
461
462         pm_runtime_put_sync(dev);
463         return 0;
464 }
465
466 static int vpfe_ccdc_set_params(struct vpfe_ccdc *ccdc, void __user *params)
467 {
468         struct vpfe_device *vpfe = container_of(ccdc, struct vpfe_device, ccdc);
469         struct vpfe_ccdc_config_params_raw raw_params;
470         int x;
471
472         if (ccdc->ccdc_cfg.if_type != VPFE_RAW_BAYER)
473                 return -EINVAL;
474
475         x = copy_from_user(&raw_params, params, sizeof(raw_params));
476         if (x) {
477                 vpfe_dbg(1, vpfe,
478                         "vpfe_ccdc_set_params: error in copying ccdc params, %d\n",
479                         x);
480                 return -EFAULT;
481         }
482
483         if (!vpfe_ccdc_validate_param(ccdc, &raw_params)) {
484                 vpfe_ccdc_update_raw_params(ccdc, &raw_params);
485                 return 0;
486         }
487
488         return -EINVAL;
489 }
490
491 /*
492  * vpfe_ccdc_config_ycbcr()
493  * This function will configure CCDC for YCbCr video capture
494  */
495 static void vpfe_ccdc_config_ycbcr(struct vpfe_ccdc *ccdc)
496 {
497         struct vpfe_device *vpfe = container_of(ccdc, struct vpfe_device, ccdc);
498         struct ccdc_params_ycbcr *params = &ccdc->ccdc_cfg.ycbcr;
499         u32 syn_mode;
500
501         vpfe_dbg(3, vpfe, "vpfe_ccdc_config_ycbcr:\n");
502         /*
503          * first restore the CCDC registers to default values
504          * This is important since we assume default values to be set in
505          * a lot of registers that we didn't touch
506          */
507         vpfe_ccdc_restore_defaults(ccdc);
508
509         /*
510          * configure pixel format, frame format, configure video frame
511          * format, enable output to SDRAM, enable internal timing generator
512          * and 8bit pack mode
513          */
514         syn_mode = (((params->pix_fmt & VPFE_SYN_MODE_INPMOD_MASK) <<
515                     VPFE_SYN_MODE_INPMOD_SHIFT) |
516                     ((params->frm_fmt & VPFE_SYN_FLDMODE_MASK) <<
517                     VPFE_SYN_FLDMODE_SHIFT) | VPFE_VDHDEN_ENABLE |
518                     VPFE_WEN_ENABLE | VPFE_DATA_PACK_ENABLE);
519
520         /* setup BT.656 sync mode */
521         if (params->bt656_enable) {
522                 vpfe_reg_write(ccdc, VPFE_REC656IF_BT656_EN, VPFE_REC656IF);
523
524                 /*
525                  * configure the FID, VD, HD pin polarity,
526                  * fld,hd pol positive, vd negative, 8-bit data
527                  */
528                 syn_mode |= VPFE_SYN_MODE_VD_POL_NEGATIVE;
529                 if (ccdc->ccdc_cfg.if_type == VPFE_BT656_10BIT)
530                         syn_mode |= VPFE_SYN_MODE_10BITS;
531                 else
532                         syn_mode |= VPFE_SYN_MODE_8BITS;
533         } else {
534                 /* y/c external sync mode */
535                 syn_mode |= (((params->fid_pol & VPFE_FID_POL_MASK) <<
536                              VPFE_FID_POL_SHIFT) |
537                              ((params->hd_pol & VPFE_HD_POL_MASK) <<
538                              VPFE_HD_POL_SHIFT) |
539                              ((params->vd_pol & VPFE_VD_POL_MASK) <<
540                              VPFE_VD_POL_SHIFT));
541         }
542         vpfe_reg_write(ccdc, syn_mode, VPFE_SYNMODE);
543
544         /* configure video window */
545         vpfe_ccdc_setwin(ccdc, &params->win,
546                          params->frm_fmt, params->bytesperpixel);
547
548         /*
549          * configure the order of y cb cr in SDRAM, and disable latch
550          * internal register on vsync
551          */
552         if (ccdc->ccdc_cfg.if_type == VPFE_BT656_10BIT)
553                 vpfe_reg_write(ccdc,
554                                (params->pix_order << VPFE_CCDCFG_Y8POS_SHIFT) |
555                                VPFE_LATCH_ON_VSYNC_DISABLE |
556                                VPFE_CCDCFG_BW656_10BIT, VPFE_CCDCFG);
557         else
558                 vpfe_reg_write(ccdc,
559                                (params->pix_order << VPFE_CCDCFG_Y8POS_SHIFT) |
560                                VPFE_LATCH_ON_VSYNC_DISABLE, VPFE_CCDCFG);
561
562         /*
563          * configure the horizontal line offset. This should be a
564          * on 32 byte boundary. So clear LSB 5 bits
565          */
566         vpfe_reg_write(ccdc, params->bytesperline, VPFE_HSIZE_OFF);
567
568         /* configure the memory line offset */
569         if (params->buf_type == CCDC_BUFTYPE_FLD_INTERLEAVED)
570                 /* two fields are interleaved in memory */
571                 vpfe_reg_write(ccdc, VPFE_SDOFST_FIELD_INTERLEAVED,
572                                VPFE_SDOFST);
573 }
574
575 static void
576 vpfe_ccdc_config_black_clamp(struct vpfe_ccdc *ccdc,
577                              struct vpfe_ccdc_black_clamp *bclamp)
578 {
579         u32 val;
580
581         if (!bclamp->enable) {
582                 /* configure DCSub */
583                 val = (bclamp->dc_sub) & VPFE_BLK_DC_SUB_MASK;
584                 vpfe_reg_write(ccdc, val, VPFE_DCSUB);
585                 vpfe_reg_write(ccdc, VPFE_CLAMP_DEFAULT_VAL, VPFE_CLAMP);
586                 return;
587         }
588         /*
589          * Configure gain,  Start pixel, No of line to be avg,
590          * No of pixel/line to be avg, & Enable the Black clamping
591          */
592         val = ((bclamp->sgain & VPFE_BLK_SGAIN_MASK) |
593                ((bclamp->start_pixel & VPFE_BLK_ST_PXL_MASK) <<
594                 VPFE_BLK_ST_PXL_SHIFT) |
595                ((bclamp->sample_ln & VPFE_BLK_SAMPLE_LINE_MASK) <<
596                 VPFE_BLK_SAMPLE_LINE_SHIFT) |
597                ((bclamp->sample_pixel & VPFE_BLK_SAMPLE_LN_MASK) <<
598                 VPFE_BLK_SAMPLE_LN_SHIFT) | VPFE_BLK_CLAMP_ENABLE);
599         vpfe_reg_write(ccdc, val, VPFE_CLAMP);
600         /* If Black clamping is enable then make dcsub 0 */
601         vpfe_reg_write(ccdc, VPFE_DCSUB_DEFAULT_VAL, VPFE_DCSUB);
602 }
603
604 static void
605 vpfe_ccdc_config_black_compense(struct vpfe_ccdc *ccdc,
606                                 struct vpfe_ccdc_black_compensation *bcomp)
607 {
608         u32 val;
609
610         val = ((bcomp->b & VPFE_BLK_COMP_MASK) |
611               ((bcomp->gb & VPFE_BLK_COMP_MASK) <<
612                VPFE_BLK_COMP_GB_COMP_SHIFT) |
613               ((bcomp->gr & VPFE_BLK_COMP_MASK) <<
614                VPFE_BLK_COMP_GR_COMP_SHIFT) |
615               ((bcomp->r & VPFE_BLK_COMP_MASK) <<
616                VPFE_BLK_COMP_R_COMP_SHIFT));
617         vpfe_reg_write(ccdc, val, VPFE_BLKCMP);
618 }
619
620 /*
621  * vpfe_ccdc_config_raw()
622  * This function will configure CCDC for Raw capture mode
623  */
624 static void vpfe_ccdc_config_raw(struct vpfe_ccdc *ccdc)
625 {
626         struct vpfe_device *vpfe = container_of(ccdc, struct vpfe_device, ccdc);
627         struct vpfe_ccdc_config_params_raw *config_params =
628                                 &ccdc->ccdc_cfg.bayer.config_params;
629         struct ccdc_params_raw *params = &ccdc->ccdc_cfg.bayer;
630         unsigned int syn_mode;
631         unsigned int val;
632
633         vpfe_dbg(3, vpfe, "vpfe_ccdc_config_raw:\n");
634
635         /* Reset CCDC */
636         vpfe_ccdc_restore_defaults(ccdc);
637
638         /* Disable latching function registers on VSYNC  */
639         vpfe_reg_write(ccdc, VPFE_LATCH_ON_VSYNC_DISABLE, VPFE_CCDCFG);
640
641         /*
642          * Configure the vertical sync polarity(SYN_MODE.VDPOL),
643          * horizontal sync polarity (SYN_MODE.HDPOL), frame id polarity
644          * (SYN_MODE.FLDPOL), frame format(progressive or interlace),
645          * data size(SYNMODE.DATSIZ), &pixel format (Input mode), output
646          * SDRAM, enable internal timing generator
647          */
648         syn_mode = (((params->vd_pol & VPFE_VD_POL_MASK) << VPFE_VD_POL_SHIFT) |
649                    ((params->hd_pol & VPFE_HD_POL_MASK) << VPFE_HD_POL_SHIFT) |
650                    ((params->fid_pol & VPFE_FID_POL_MASK) <<
651                    VPFE_FID_POL_SHIFT) | ((params->frm_fmt &
652                    VPFE_FRM_FMT_MASK) << VPFE_FRM_FMT_SHIFT) |
653                    ((config_params->data_sz & VPFE_DATA_SZ_MASK) <<
654                    VPFE_DATA_SZ_SHIFT) | ((params->pix_fmt &
655                    VPFE_PIX_FMT_MASK) << VPFE_PIX_FMT_SHIFT) |
656                    VPFE_WEN_ENABLE | VPFE_VDHDEN_ENABLE);
657
658         /* Enable and configure aLaw register if needed */
659         if (config_params->alaw.enable) {
660                 val = ((config_params->alaw.gamma_wd &
661                       VPFE_ALAW_GAMMA_WD_MASK) | VPFE_ALAW_ENABLE);
662                 vpfe_reg_write(ccdc, val, VPFE_ALAW);
663                 vpfe_dbg(3, vpfe, "\nWriting 0x%x to ALAW...\n", val);
664         }
665
666         /* Configure video window */
667         vpfe_ccdc_setwin(ccdc, &params->win, params->frm_fmt,
668                          params->bytesperpixel);
669
670         /* Configure Black Clamp */
671         vpfe_ccdc_config_black_clamp(ccdc, &config_params->blk_clamp);
672
673         /* Configure Black level compensation */
674         vpfe_ccdc_config_black_compense(ccdc, &config_params->blk_comp);
675
676         /* If data size is 8 bit then pack the data */
677         if ((config_params->data_sz == VPFE_CCDC_DATA_8BITS) ||
678             config_params->alaw.enable)
679                 syn_mode |= VPFE_DATA_PACK_ENABLE;
680
681         /*
682          * Configure Horizontal offset register. If pack 8 is enabled then
683          * 1 pixel will take 1 byte
684          */
685         vpfe_reg_write(ccdc, params->bytesperline, VPFE_HSIZE_OFF);
686
687         vpfe_dbg(3, vpfe, "Writing %d (%x) to HSIZE_OFF\n",
688                 params->bytesperline, params->bytesperline);
689
690         /* Set value for SDOFST */
691         if (params->frm_fmt == CCDC_FRMFMT_INTERLACED) {
692                 if (params->image_invert_enable) {
693                         /* For interlace inverse mode */
694                         vpfe_reg_write(ccdc, VPFE_INTERLACED_IMAGE_INVERT,
695                                    VPFE_SDOFST);
696                 } else {
697                         /* For interlace non inverse mode */
698                         vpfe_reg_write(ccdc, VPFE_INTERLACED_NO_IMAGE_INVERT,
699                                    VPFE_SDOFST);
700                 }
701         } else if (params->frm_fmt == CCDC_FRMFMT_PROGRESSIVE) {
702                 vpfe_reg_write(ccdc, VPFE_PROGRESSIVE_NO_IMAGE_INVERT,
703                            VPFE_SDOFST);
704         }
705
706         vpfe_reg_write(ccdc, syn_mode, VPFE_SYNMODE);
707
708         vpfe_reg_dump(ccdc);
709 }
710
711 static inline int
712 vpfe_ccdc_set_buftype(struct vpfe_ccdc *ccdc,
713                       enum ccdc_buftype buf_type)
714 {
715         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER)
716                 ccdc->ccdc_cfg.bayer.buf_type = buf_type;
717         else
718                 ccdc->ccdc_cfg.ycbcr.buf_type = buf_type;
719
720         return 0;
721 }
722
723 static inline enum ccdc_buftype vpfe_ccdc_get_buftype(struct vpfe_ccdc *ccdc)
724 {
725         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER)
726                 return ccdc->ccdc_cfg.bayer.buf_type;
727
728         return ccdc->ccdc_cfg.ycbcr.buf_type;
729 }
730
731 static int vpfe_ccdc_set_pixel_format(struct vpfe_ccdc *ccdc, u32 pixfmt)
732 {
733         struct vpfe_device *vpfe = container_of(ccdc, struct vpfe_device, ccdc);
734
735         vpfe_dbg(1, vpfe, "vpfe_ccdc_set_pixel_format: if_type: %d, pixfmt:%s\n",
736                  ccdc->ccdc_cfg.if_type, print_fourcc(pixfmt));
737
738         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER) {
739                 ccdc->ccdc_cfg.bayer.pix_fmt = CCDC_PIXFMT_RAW;
740                 /*
741                  * Need to clear it in case it was left on
742                  * after the last capture.
743                  */
744                 ccdc->ccdc_cfg.bayer.config_params.alaw.enable = 0;
745
746                 switch (pixfmt) {
747                 case V4L2_PIX_FMT_SBGGR8:
748                         ccdc->ccdc_cfg.bayer.config_params.alaw.enable = 1;
749                         break;
750
751                 case V4L2_PIX_FMT_YUYV:
752                 case V4L2_PIX_FMT_UYVY:
753                 case V4L2_PIX_FMT_YUV420:
754                 case V4L2_PIX_FMT_NV12:
755                 case V4L2_PIX_FMT_RGB565X:
756                         break;
757
758                 case V4L2_PIX_FMT_SBGGR16:
759                 default:
760                         return -EINVAL;
761                 }
762         } else {
763                 switch (pixfmt) {
764                 case V4L2_PIX_FMT_YUYV:
765                         ccdc->ccdc_cfg.ycbcr.pix_order = CCDC_PIXORDER_YCBYCR;
766                         break;
767
768                 case V4L2_PIX_FMT_UYVY:
769                         ccdc->ccdc_cfg.ycbcr.pix_order = CCDC_PIXORDER_CBYCRY;
770                         break;
771
772                 default:
773                         return -EINVAL;
774                 }
775         }
776
777         return 0;
778 }
779
780 static u32 vpfe_ccdc_get_pixel_format(struct vpfe_ccdc *ccdc)
781 {
782         u32 pixfmt;
783
784         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER) {
785                 pixfmt = V4L2_PIX_FMT_YUYV;
786         } else {
787                 if (ccdc->ccdc_cfg.ycbcr.pix_order == CCDC_PIXORDER_YCBYCR)
788                         pixfmt = V4L2_PIX_FMT_YUYV;
789                 else
790                         pixfmt = V4L2_PIX_FMT_UYVY;
791         }
792
793         return pixfmt;
794 }
795
796 static int
797 vpfe_ccdc_set_image_window(struct vpfe_ccdc *ccdc,
798                            struct v4l2_rect *win, unsigned int bpp)
799 {
800         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER) {
801                 ccdc->ccdc_cfg.bayer.win = *win;
802                 ccdc->ccdc_cfg.bayer.bytesperpixel = bpp;
803                 ccdc->ccdc_cfg.bayer.bytesperline = ALIGN(win->width * bpp, 32);
804         } else {
805                 ccdc->ccdc_cfg.ycbcr.win = *win;
806                 ccdc->ccdc_cfg.ycbcr.bytesperpixel = bpp;
807                 ccdc->ccdc_cfg.ycbcr.bytesperline = ALIGN(win->width * bpp, 32);
808         }
809
810         return 0;
811 }
812
813 static inline void
814 vpfe_ccdc_get_image_window(struct vpfe_ccdc *ccdc,
815                            struct v4l2_rect *win)
816 {
817         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER)
818                 *win = ccdc->ccdc_cfg.bayer.win;
819         else
820                 *win = ccdc->ccdc_cfg.ycbcr.win;
821 }
822
823 static inline unsigned int vpfe_ccdc_get_line_length(struct vpfe_ccdc *ccdc)
824 {
825         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER)
826                 return ccdc->ccdc_cfg.bayer.bytesperline;
827
828         return ccdc->ccdc_cfg.ycbcr.bytesperline;
829 }
830
831 static inline int
832 vpfe_ccdc_set_frame_format(struct vpfe_ccdc *ccdc,
833                            enum ccdc_frmfmt frm_fmt)
834 {
835         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER)
836                 ccdc->ccdc_cfg.bayer.frm_fmt = frm_fmt;
837         else
838                 ccdc->ccdc_cfg.ycbcr.frm_fmt = frm_fmt;
839
840         return 0;
841 }
842
843 static inline enum ccdc_frmfmt
844 vpfe_ccdc_get_frame_format(struct vpfe_ccdc *ccdc)
845 {
846         if (ccdc->ccdc_cfg.if_type == VPFE_RAW_BAYER)
847                 return ccdc->ccdc_cfg.bayer.frm_fmt;
848
849         return ccdc->ccdc_cfg.ycbcr.frm_fmt;
850 }
851
852 static inline int vpfe_ccdc_getfid(struct vpfe_ccdc *ccdc)
853 {
854         return (vpfe_reg_read(ccdc, VPFE_SYNMODE) >> 15) & 1;
855 }
856
857 static inline void vpfe_set_sdr_addr(struct vpfe_ccdc *ccdc, unsigned long addr)
858 {
859         vpfe_reg_write(ccdc, addr & 0xffffffe0, VPFE_SDR_ADDR);
860 }
861
862 static int vpfe_ccdc_set_hw_if_params(struct vpfe_ccdc *ccdc,
863                                       struct vpfe_hw_if_param *params)
864 {
865         struct vpfe_device *vpfe = container_of(ccdc, struct vpfe_device, ccdc);
866
867         ccdc->ccdc_cfg.if_type = params->if_type;
868
869         switch (params->if_type) {
870         case VPFE_BT656:
871         case VPFE_YCBCR_SYNC_16:
872         case VPFE_YCBCR_SYNC_8:
873         case VPFE_BT656_10BIT:
874                 ccdc->ccdc_cfg.ycbcr.vd_pol = params->vdpol;
875                 ccdc->ccdc_cfg.ycbcr.hd_pol = params->hdpol;
876                 break;
877
878         case VPFE_RAW_BAYER:
879                 ccdc->ccdc_cfg.bayer.vd_pol = params->vdpol;
880                 ccdc->ccdc_cfg.bayer.hd_pol = params->hdpol;
881                 if (params->bus_width == 10)
882                         ccdc->ccdc_cfg.bayer.config_params.data_sz =
883                                 VPFE_CCDC_DATA_10BITS;
884                 else
885                         ccdc->ccdc_cfg.bayer.config_params.data_sz =
886                                 VPFE_CCDC_DATA_8BITS;
887                 vpfe_dbg(1, vpfe, "params.bus_width: %d\n",
888                         params->bus_width);
889                 vpfe_dbg(1, vpfe, "config_params.data_sz: %d\n",
890                         ccdc->ccdc_cfg.bayer.config_params.data_sz);
891                 break;
892
893         default:
894                 return -EINVAL;
895         }
896
897         return 0;
898 }
899
900 static void vpfe_clear_intr(struct vpfe_ccdc *ccdc, int vdint)
901 {
902         unsigned int vpfe_int_status;
903
904         vpfe_int_status = vpfe_reg_read(ccdc, VPFE_IRQ_STS);
905
906         switch (vdint) {
907         /* VD0 interrupt */
908         case VPFE_VDINT0:
909                 vpfe_int_status &= ~VPFE_VDINT0;
910                 vpfe_int_status |= VPFE_VDINT0;
911                 break;
912
913         /* VD1 interrupt */
914         case VPFE_VDINT1:
915                 vpfe_int_status &= ~VPFE_VDINT1;
916                 vpfe_int_status |= VPFE_VDINT1;
917                 break;
918
919         /* VD2 interrupt */
920         case VPFE_VDINT2:
921                 vpfe_int_status &= ~VPFE_VDINT2;
922                 vpfe_int_status |= VPFE_VDINT2;
923                 break;
924
925         /* Clear all interrupts */
926         default:
927                 vpfe_int_status &= ~(VPFE_VDINT0 |
928                                 VPFE_VDINT1 |
929                                 VPFE_VDINT2);
930                 vpfe_int_status |= (VPFE_VDINT0 |
931                                 VPFE_VDINT1 |
932                                 VPFE_VDINT2);
933                 break;
934         }
935         /* Clear specific VDINT from the status register */
936         vpfe_reg_write(ccdc, vpfe_int_status, VPFE_IRQ_STS);
937
938         vpfe_int_status = vpfe_reg_read(ccdc, VPFE_IRQ_STS);
939
940         /* Acknowledge that we are done with all interrupts */
941         vpfe_reg_write(ccdc, 1, VPFE_IRQ_EOI);
942 }
943
944 static void vpfe_ccdc_config_defaults(struct vpfe_ccdc *ccdc)
945 {
946         ccdc->ccdc_cfg.if_type = VPFE_RAW_BAYER;
947
948         ccdc->ccdc_cfg.ycbcr.pix_fmt = CCDC_PIXFMT_YCBCR_8BIT;
949         ccdc->ccdc_cfg.ycbcr.frm_fmt = CCDC_FRMFMT_INTERLACED;
950         ccdc->ccdc_cfg.ycbcr.fid_pol = VPFE_PINPOL_POSITIVE;
951         ccdc->ccdc_cfg.ycbcr.vd_pol = VPFE_PINPOL_POSITIVE;
952         ccdc->ccdc_cfg.ycbcr.hd_pol = VPFE_PINPOL_POSITIVE;
953         ccdc->ccdc_cfg.ycbcr.pix_order = CCDC_PIXORDER_CBYCRY;
954         ccdc->ccdc_cfg.ycbcr.buf_type = CCDC_BUFTYPE_FLD_INTERLEAVED;
955
956         ccdc->ccdc_cfg.ycbcr.win.left = 0;
957         ccdc->ccdc_cfg.ycbcr.win.top = 0;
958         ccdc->ccdc_cfg.ycbcr.win.width = 720;
959         ccdc->ccdc_cfg.ycbcr.win.height = 576;
960         ccdc->ccdc_cfg.ycbcr.bt656_enable = 1;
961
962         ccdc->ccdc_cfg.bayer.pix_fmt = CCDC_PIXFMT_RAW;
963         ccdc->ccdc_cfg.bayer.frm_fmt = CCDC_FRMFMT_PROGRESSIVE;
964         ccdc->ccdc_cfg.bayer.fid_pol = VPFE_PINPOL_POSITIVE;
965         ccdc->ccdc_cfg.bayer.vd_pol = VPFE_PINPOL_POSITIVE;
966         ccdc->ccdc_cfg.bayer.hd_pol = VPFE_PINPOL_POSITIVE;
967
968         ccdc->ccdc_cfg.bayer.win.left = 0;
969         ccdc->ccdc_cfg.bayer.win.top = 0;
970         ccdc->ccdc_cfg.bayer.win.width = 800;
971         ccdc->ccdc_cfg.bayer.win.height = 600;
972         ccdc->ccdc_cfg.bayer.config_params.data_sz = VPFE_CCDC_DATA_8BITS;
973         ccdc->ccdc_cfg.bayer.config_params.alaw.gamma_wd =
974                                                 VPFE_CCDC_GAMMA_BITS_09_0;
975 }
976
977 /*
978  * vpfe_get_ccdc_image_format - Get image parameters based on CCDC settings
979  */
980 static int vpfe_get_ccdc_image_format(struct vpfe_device *vpfe,
981                                       struct v4l2_format *f)
982 {
983         struct v4l2_rect image_win;
984         enum ccdc_buftype buf_type;
985         enum ccdc_frmfmt frm_fmt;
986
987         memset(f, 0, sizeof(*f));
988         f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
989         vpfe_ccdc_get_image_window(&vpfe->ccdc, &image_win);
990         f->fmt.pix.width = image_win.width;
991         f->fmt.pix.height = image_win.height;
992         f->fmt.pix.bytesperline = vpfe_ccdc_get_line_length(&vpfe->ccdc);
993         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
994                                 f->fmt.pix.height;
995         buf_type = vpfe_ccdc_get_buftype(&vpfe->ccdc);
996         f->fmt.pix.pixelformat = vpfe_ccdc_get_pixel_format(&vpfe->ccdc);
997         frm_fmt = vpfe_ccdc_get_frame_format(&vpfe->ccdc);
998
999         if (frm_fmt == CCDC_FRMFMT_PROGRESSIVE) {
1000                 f->fmt.pix.field = V4L2_FIELD_NONE;
1001         } else if (frm_fmt == CCDC_FRMFMT_INTERLACED) {
1002                 if (buf_type == CCDC_BUFTYPE_FLD_INTERLEAVED) {
1003                         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1004                  } else if (buf_type == CCDC_BUFTYPE_FLD_SEPARATED) {
1005                         f->fmt.pix.field = V4L2_FIELD_SEQ_TB;
1006                 } else {
1007                         vpfe_err(vpfe, "Invalid buf_type\n");
1008                         return -EINVAL;
1009                 }
1010         } else {
1011                 vpfe_err(vpfe, "Invalid frm_fmt\n");
1012                 return -EINVAL;
1013         }
1014         return 0;
1015 }
1016
1017 static int vpfe_config_ccdc_image_format(struct vpfe_device *vpfe)
1018 {
1019         enum ccdc_frmfmt frm_fmt = CCDC_FRMFMT_INTERLACED;
1020         int ret = 0;
1021
1022         vpfe_dbg(2, vpfe, "vpfe_config_ccdc_image_format\n");
1023
1024         vpfe_dbg(1, vpfe, "pixelformat: %s\n",
1025                 print_fourcc(vpfe->fmt.fmt.pix.pixelformat));
1026
1027         if (vpfe_ccdc_set_pixel_format(&vpfe->ccdc,
1028                         vpfe->fmt.fmt.pix.pixelformat) < 0) {
1029                 vpfe_err(vpfe, "couldn't set pix format in ccdc\n");
1030                 return -EINVAL;
1031         }
1032
1033         /* configure the image window */
1034         vpfe_ccdc_set_image_window(&vpfe->ccdc, &vpfe->crop, vpfe->bpp);
1035
1036         switch (vpfe->fmt.fmt.pix.field) {
1037         case V4L2_FIELD_INTERLACED:
1038                 /* do nothing, since it is default */
1039                 ret = vpfe_ccdc_set_buftype(
1040                                 &vpfe->ccdc,
1041                                 CCDC_BUFTYPE_FLD_INTERLEAVED);
1042                 break;
1043
1044         case V4L2_FIELD_NONE:
1045                 frm_fmt = CCDC_FRMFMT_PROGRESSIVE;
1046                 /* buffer type only applicable for interlaced scan */
1047                 break;
1048
1049         case V4L2_FIELD_SEQ_TB:
1050                 ret = vpfe_ccdc_set_buftype(
1051                                 &vpfe->ccdc,
1052                                 CCDC_BUFTYPE_FLD_SEPARATED);
1053                 break;
1054
1055         default:
1056                 return -EINVAL;
1057         }
1058
1059         if (ret)
1060                 return ret;
1061
1062         return vpfe_ccdc_set_frame_format(&vpfe->ccdc, frm_fmt);
1063 }
1064
1065 /*
1066  * vpfe_config_image_format()
1067  * For a given standard, this functions sets up the default
1068  * pix format & crop values in the vpfe device and ccdc.  It first
1069  * starts with defaults based values from the standard table.
1070  * It then checks if sub device supports get_fmt and then override the
1071  * values based on that.Sets crop values to match with scan resolution
1072  * starting at 0,0. It calls vpfe_config_ccdc_image_format() set the
1073  * values in ccdc
1074  */
1075 static int vpfe_config_image_format(struct vpfe_device *vpfe,
1076                                     v4l2_std_id std_id)
1077 {
1078         struct v4l2_pix_format *pix = &vpfe->fmt.fmt.pix;
1079         int i, ret;
1080
1081         for (i = 0; i < ARRAY_SIZE(vpfe_standards); i++) {
1082                 if (vpfe_standards[i].std_id & std_id) {
1083                         vpfe->std_info.active_pixels =
1084                                         vpfe_standards[i].width;
1085                         vpfe->std_info.active_lines =
1086                                         vpfe_standards[i].height;
1087                         vpfe->std_info.frame_format =
1088                                         vpfe_standards[i].frame_format;
1089                         vpfe->std_index = i;
1090
1091                         break;
1092                 }
1093         }
1094
1095         if (i ==  ARRAY_SIZE(vpfe_standards)) {
1096                 vpfe_err(vpfe, "standard not supported\n");
1097                 return -EINVAL;
1098         }
1099
1100         vpfe->crop.top = vpfe->crop.left = 0;
1101         vpfe->crop.width = vpfe->std_info.active_pixels;
1102         vpfe->crop.height = vpfe->std_info.active_lines;
1103         pix->width = vpfe->crop.width;
1104         pix->height = vpfe->crop.height;
1105         pix->pixelformat = V4L2_PIX_FMT_YUYV;
1106
1107         /* first field and frame format based on standard frame format */
1108         if (vpfe->std_info.frame_format)
1109                 pix->field = V4L2_FIELD_INTERLACED;
1110         else
1111                 pix->field = V4L2_FIELD_NONE;
1112
1113         ret = __vpfe_get_format(vpfe, &vpfe->fmt, &vpfe->bpp);
1114         if (ret)
1115                 return ret;
1116
1117         /* Update the crop window based on found values */
1118         vpfe->crop.width = pix->width;
1119         vpfe->crop.height = pix->height;
1120
1121         return vpfe_config_ccdc_image_format(vpfe);
1122 }
1123
1124 static int vpfe_initialize_device(struct vpfe_device *vpfe)
1125 {
1126         struct vpfe_subdev_info *sdinfo;
1127         int ret;
1128
1129         sdinfo = &vpfe->cfg->sub_devs[0];
1130         sdinfo->sd = vpfe->sd[0];
1131         vpfe->current_input = 0;
1132         vpfe->std_index = 0;
1133         /* Configure the default format information */
1134         ret = vpfe_config_image_format(vpfe,
1135                                        vpfe_standards[vpfe->std_index].std_id);
1136         if (ret)
1137                 return ret;
1138
1139         pm_runtime_get_sync(vpfe->pdev);
1140
1141         vpfe_config_enable(&vpfe->ccdc, 1);
1142
1143         vpfe_ccdc_restore_defaults(&vpfe->ccdc);
1144
1145         /* Clear all VPFE interrupts */
1146         vpfe_clear_intr(&vpfe->ccdc, -1);
1147
1148         return ret;
1149 }
1150
1151 /*
1152  * vpfe_release : This function is based on the vb2_fop_release
1153  * helper function.
1154  * It has been augmented to handle module power management,
1155  * by disabling/enabling h/w module fcntl clock when necessary.
1156  */
1157 static int vpfe_release(struct file *file)
1158 {
1159         struct vpfe_device *vpfe = video_drvdata(file);
1160         bool fh_singular;
1161         int ret;
1162
1163         mutex_lock(&vpfe->lock);
1164
1165         /* Save the singular status before we call the clean-up helper */
1166         fh_singular = v4l2_fh_is_singular_file(file);
1167
1168         /* the release helper will cleanup any on-going streaming */
1169         ret = _vb2_fop_release(file, NULL);
1170
1171         /*
1172          * If this was the last open file.
1173          * Then de-initialize hw module.
1174          */
1175         if (fh_singular)
1176                 vpfe_ccdc_close(&vpfe->ccdc, vpfe->pdev);
1177
1178         mutex_unlock(&vpfe->lock);
1179
1180         return ret;
1181 }
1182
1183 /*
1184  * vpfe_open : This function is based on the v4l2_fh_open helper function.
1185  * It has been augmented to handle module power management,
1186  * by disabling/enabling h/w module fcntl clock when necessary.
1187  */
1188 static int vpfe_open(struct file *file)
1189 {
1190         struct vpfe_device *vpfe = video_drvdata(file);
1191         int ret;
1192
1193         mutex_lock(&vpfe->lock);
1194
1195         ret = v4l2_fh_open(file);
1196         if (ret) {
1197                 vpfe_err(vpfe, "v4l2_fh_open failed\n");
1198                 goto unlock;
1199         }
1200
1201         if (!v4l2_fh_is_singular_file(file))
1202                 goto unlock;
1203
1204         if (vpfe_initialize_device(vpfe)) {
1205                 v4l2_fh_release(file);
1206                 ret = -ENODEV;
1207         }
1208
1209 unlock:
1210         mutex_unlock(&vpfe->lock);
1211         return ret;
1212 }
1213
1214 /**
1215  * vpfe_schedule_next_buffer: set next buffer address for capture
1216  * @vpfe : ptr to vpfe device
1217  *
1218  * This function will get next buffer from the dma queue and
1219  * set the buffer address in the vpfe register for capture.
1220  * the buffer is marked active
1221  */
1222 static void vpfe_schedule_next_buffer(struct vpfe_device *vpfe)
1223 {
1224         dma_addr_t addr;
1225
1226         spin_lock(&vpfe->dma_queue_lock);
1227         if (list_empty(&vpfe->dma_queue)) {
1228                 spin_unlock(&vpfe->dma_queue_lock);
1229                 return;
1230         }
1231
1232         vpfe->next_frm = list_entry(vpfe->dma_queue.next,
1233                                     struct vpfe_cap_buffer, list);
1234         list_del(&vpfe->next_frm->list);
1235         spin_unlock(&vpfe->dma_queue_lock);
1236
1237         addr = vb2_dma_contig_plane_dma_addr(&vpfe->next_frm->vb.vb2_buf, 0);
1238         vpfe_set_sdr_addr(&vpfe->ccdc, addr);
1239 }
1240
1241 static inline void vpfe_schedule_bottom_field(struct vpfe_device *vpfe)
1242 {
1243         dma_addr_t addr;
1244
1245         addr = vb2_dma_contig_plane_dma_addr(&vpfe->next_frm->vb.vb2_buf, 0) +
1246                                         vpfe->field_off;
1247
1248         vpfe_set_sdr_addr(&vpfe->ccdc, addr);
1249 }
1250
1251 /*
1252  * vpfe_process_buffer_complete: process a completed buffer
1253  * @vpfe : ptr to vpfe device
1254  *
1255  * This function time stamp the buffer and mark it as DONE. It also
1256  * wake up any process waiting on the QUEUE and set the next buffer
1257  * as current
1258  */
1259 static inline void vpfe_process_buffer_complete(struct vpfe_device *vpfe)
1260 {
1261         vpfe->cur_frm->vb.vb2_buf.timestamp = ktime_get_ns();
1262         vpfe->cur_frm->vb.field = vpfe->fmt.fmt.pix.field;
1263         vpfe->cur_frm->vb.sequence = vpfe->sequence++;
1264         vb2_buffer_done(&vpfe->cur_frm->vb.vb2_buf, VB2_BUF_STATE_DONE);
1265         vpfe->cur_frm = vpfe->next_frm;
1266 }
1267
1268 static void vpfe_handle_interlaced_irq(struct vpfe_device *vpfe,
1269                                        enum v4l2_field field)
1270 {
1271         int fid;
1272
1273         /* interlaced or TB capture check which field
1274          * we are in hardware
1275          */
1276         fid = vpfe_ccdc_getfid(&vpfe->ccdc);
1277
1278         /* switch the software maintained field id */
1279         vpfe->field ^= 1;
1280         if (fid == vpfe->field) {
1281                 /* we are in-sync here,continue */
1282                 if (fid == 0) {
1283                         /*
1284                          * One frame is just being captured. If the
1285                          * next frame is available, release the
1286                          * current frame and move on
1287                          */
1288                         if (vpfe->cur_frm != vpfe->next_frm)
1289                                 vpfe_process_buffer_complete(vpfe);
1290
1291                         if (vpfe->stopping)
1292                                 return;
1293
1294                         /*
1295                          * based on whether the two fields are stored
1296                          * interleave or separately in memory,
1297                          * reconfigure the CCDC memory address
1298                          */
1299                         if (field == V4L2_FIELD_SEQ_TB)
1300                                 vpfe_schedule_bottom_field(vpfe);
1301                 } else {
1302                         /*
1303                          * if one field is just being captured configure
1304                          * the next frame get the next frame from the empty
1305                          * queue if no frame is available hold on to the
1306                          * current buffer
1307                          */
1308                         if (vpfe->cur_frm == vpfe->next_frm)
1309                                 vpfe_schedule_next_buffer(vpfe);
1310                 }
1311         } else if (fid == 0) {
1312                 /*
1313                  * out of sync. Recover from any hardware out-of-sync.
1314                  * May loose one frame
1315                  */
1316                 vpfe->field = fid;
1317         }
1318 }
1319
1320 /*
1321  * vpfe_isr : ISR handler for vpfe capture (VINT0)
1322  * @irq: irq number
1323  * @dev_id: dev_id ptr
1324  *
1325  * It changes status of the captured buffer, takes next buffer from the queue
1326  * and sets its address in VPFE registers
1327  */
1328 static irqreturn_t vpfe_isr(int irq, void *dev)
1329 {
1330         struct vpfe_device *vpfe = (struct vpfe_device *)dev;
1331         enum v4l2_field field = vpfe->fmt.fmt.pix.field;
1332         int intr_status, stopping = vpfe->stopping;
1333
1334         intr_status = vpfe_reg_read(&vpfe->ccdc, VPFE_IRQ_STS);
1335
1336         if (intr_status & VPFE_VDINT0) {
1337                 if (field == V4L2_FIELD_NONE) {
1338                         if (vpfe->cur_frm != vpfe->next_frm)
1339                                 vpfe_process_buffer_complete(vpfe);
1340                 } else {
1341                         vpfe_handle_interlaced_irq(vpfe, field);
1342                 }
1343                 if (stopping) {
1344                         vpfe->stopping = false;
1345                         complete(&vpfe->capture_stop);
1346                 }
1347         }
1348
1349         if (intr_status & VPFE_VDINT1 && !stopping) {
1350                 if (field == V4L2_FIELD_NONE &&
1351                     vpfe->cur_frm == vpfe->next_frm)
1352                         vpfe_schedule_next_buffer(vpfe);
1353         }
1354
1355         vpfe_clear_intr(&vpfe->ccdc, intr_status);
1356
1357         return IRQ_HANDLED;
1358 }
1359
1360 static inline void vpfe_detach_irq(struct vpfe_device *vpfe)
1361 {
1362         unsigned int intr = VPFE_VDINT0;
1363         enum ccdc_frmfmt frame_format;
1364
1365         frame_format = vpfe_ccdc_get_frame_format(&vpfe->ccdc);
1366         if (frame_format == CCDC_FRMFMT_PROGRESSIVE)
1367                 intr |= VPFE_VDINT1;
1368
1369         vpfe_reg_write(&vpfe->ccdc, intr, VPFE_IRQ_EN_CLR);
1370 }
1371
1372 static inline void vpfe_attach_irq(struct vpfe_device *vpfe)
1373 {
1374         unsigned int intr = VPFE_VDINT0;
1375         enum ccdc_frmfmt frame_format;
1376
1377         frame_format = vpfe_ccdc_get_frame_format(&vpfe->ccdc);
1378         if (frame_format == CCDC_FRMFMT_PROGRESSIVE)
1379                 intr |= VPFE_VDINT1;
1380
1381         vpfe_reg_write(&vpfe->ccdc, intr, VPFE_IRQ_EN_SET);
1382 }
1383
1384 static int vpfe_querycap(struct file *file, void  *priv,
1385                          struct v4l2_capability *cap)
1386 {
1387         struct vpfe_device *vpfe = video_drvdata(file);
1388
1389         vpfe_dbg(2, vpfe, "vpfe_querycap\n");
1390
1391         strscpy(cap->driver, VPFE_MODULE_NAME, sizeof(cap->driver));
1392         strscpy(cap->card, "TI AM437x VPFE", sizeof(cap->card));
1393         snprintf(cap->bus_info, sizeof(cap->bus_info),
1394                         "platform:%s", vpfe->v4l2_dev.name);
1395         return 0;
1396 }
1397
1398 /* get the format set at output pad of the adjacent subdev */
1399 static int __vpfe_get_format(struct vpfe_device *vpfe,
1400                              struct v4l2_format *format, unsigned int *bpp)
1401 {
1402         struct v4l2_mbus_framefmt mbus_fmt;
1403         struct vpfe_subdev_info *sdinfo;
1404         struct v4l2_subdev_format fmt;
1405         int ret;
1406
1407         sdinfo = vpfe->current_subdev;
1408         if (!sdinfo->sd)
1409                 return -EINVAL;
1410
1411         fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1412         fmt.pad = 0;
1413
1414         ret = v4l2_subdev_call(sdinfo->sd, pad, get_fmt, NULL, &fmt);
1415         if (ret && ret != -ENOIOCTLCMD && ret != -ENODEV)
1416                 return ret;
1417
1418         if (!ret) {
1419                 v4l2_fill_pix_format(&format->fmt.pix, &fmt.format);
1420                 mbus_to_pix(vpfe, &fmt.format, &format->fmt.pix, bpp);
1421         } else {
1422                 ret = v4l2_device_call_until_err(&vpfe->v4l2_dev,
1423                                                  sdinfo->grp_id,
1424                                                  pad, get_fmt,
1425                                                  NULL, &fmt);
1426                 if (ret && ret != -ENOIOCTLCMD && ret != -ENODEV)
1427                         return ret;
1428                 v4l2_fill_pix_format(&format->fmt.pix, &mbus_fmt);
1429                 mbus_to_pix(vpfe, &mbus_fmt, &format->fmt.pix, bpp);
1430         }
1431
1432         format->type = vpfe->fmt.type;
1433
1434         vpfe_dbg(1, vpfe,
1435                  "%s size %dx%d (%s) bytesperline = %d, size = %d, bpp = %d\n",
1436                  __func__, format->fmt.pix.width, format->fmt.pix.height,
1437                  print_fourcc(format->fmt.pix.pixelformat),
1438                  format->fmt.pix.bytesperline, format->fmt.pix.sizeimage, *bpp);
1439
1440         return 0;
1441 }
1442
1443 /* set the format at output pad of the adjacent subdev */
1444 static int __vpfe_set_format(struct vpfe_device *vpfe,
1445                              struct v4l2_format *format, unsigned int *bpp)
1446 {
1447         struct vpfe_subdev_info *sdinfo;
1448         struct v4l2_subdev_format fmt;
1449         int ret;
1450
1451         vpfe_dbg(2, vpfe, "__vpfe_set_format\n");
1452
1453         sdinfo = vpfe->current_subdev;
1454         if (!sdinfo->sd)
1455                 return -EINVAL;
1456
1457         fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1458         fmt.pad = 0;
1459
1460         pix_to_mbus(vpfe, &format->fmt.pix, &fmt.format);
1461
1462         ret = v4l2_subdev_call(sdinfo->sd, pad, set_fmt, NULL, &fmt);
1463         if (ret)
1464                 return ret;
1465
1466         v4l2_fill_pix_format(&format->fmt.pix, &fmt.format);
1467         mbus_to_pix(vpfe, &fmt.format, &format->fmt.pix, bpp);
1468
1469         format->type = vpfe->fmt.type;
1470
1471         vpfe_dbg(1, vpfe,
1472                  "%s size %dx%d (%s) bytesperline = %d, size = %d, bpp = %d\n",
1473                  __func__,  format->fmt.pix.width, format->fmt.pix.height,
1474                  print_fourcc(format->fmt.pix.pixelformat),
1475                  format->fmt.pix.bytesperline, format->fmt.pix.sizeimage, *bpp);
1476
1477         return 0;
1478 }
1479
1480 static int vpfe_g_fmt(struct file *file, void *priv,
1481                       struct v4l2_format *fmt)
1482 {
1483         struct vpfe_device *vpfe = video_drvdata(file);
1484
1485         vpfe_dbg(2, vpfe, "vpfe_g_fmt\n");
1486
1487         *fmt = vpfe->fmt;
1488
1489         return 0;
1490 }
1491
1492 static int vpfe_enum_fmt(struct file *file, void  *priv,
1493                          struct v4l2_fmtdesc *f)
1494 {
1495         struct vpfe_device *vpfe = video_drvdata(file);
1496         struct vpfe_subdev_info *sdinfo;
1497         struct vpfe_fmt *fmt = NULL;
1498         unsigned int k;
1499
1500         vpfe_dbg(2, vpfe, "vpfe_enum_format index:%d\n",
1501                 f->index);
1502
1503         sdinfo = vpfe->current_subdev;
1504         if (!sdinfo->sd)
1505                 return -EINVAL;
1506
1507         if (f->index > ARRAY_SIZE(formats))
1508                 return -EINVAL;
1509
1510         for (k = 0; k < ARRAY_SIZE(formats); k++) {
1511                 if (formats[k].index == f->index) {
1512                         fmt = &formats[k];
1513                         break;
1514                 }
1515         }
1516         if (!fmt)
1517                 return -EINVAL;
1518
1519         f->pixelformat = fmt->fourcc;
1520
1521         vpfe_dbg(1, vpfe, "vpfe_enum_format: mbus index: %d code: %x pixelformat: %s\n",
1522                  f->index, fmt->code, print_fourcc(fmt->fourcc));
1523
1524         return 0;
1525 }
1526
1527 static int vpfe_try_fmt(struct file *file, void *priv,
1528                         struct v4l2_format *fmt)
1529 {
1530         struct vpfe_device *vpfe = video_drvdata(file);
1531         unsigned int bpp;
1532
1533         vpfe_dbg(2, vpfe, "vpfe_try_fmt\n");
1534
1535         return __vpfe_get_format(vpfe, fmt, &bpp);
1536 }
1537
1538 static int vpfe_s_fmt(struct file *file, void *priv,
1539                       struct v4l2_format *fmt)
1540 {
1541         struct vpfe_device *vpfe = video_drvdata(file);
1542         struct v4l2_format format;
1543         unsigned int bpp;
1544         int ret;
1545
1546         vpfe_dbg(2, vpfe, "vpfe_s_fmt\n");
1547
1548         /* If streaming is started, return error */
1549         if (vb2_is_busy(&vpfe->buffer_queue)) {
1550                 vpfe_err(vpfe, "%s device busy\n", __func__);
1551                 return -EBUSY;
1552         }
1553
1554         ret = __vpfe_get_format(vpfe, &format, &bpp);
1555         if (ret)
1556                 return ret;
1557
1558
1559         if (!cmp_v4l2_format(fmt, &format)) {
1560                 /* Sensor format is different from the requested format
1561                  * so we need to change it
1562                  */
1563                 ret = __vpfe_set_format(vpfe, fmt, &bpp);
1564                 if (ret)
1565                         return ret;
1566         } else /* Just make sure all of the fields are consistent */
1567                 *fmt = format;
1568
1569         /* First detach any IRQ if currently attached */
1570         vpfe_detach_irq(vpfe);
1571         vpfe->fmt = *fmt;
1572         vpfe->bpp = bpp;
1573
1574         /* Update the crop window based on found values */
1575         vpfe->crop.width = fmt->fmt.pix.width;
1576         vpfe->crop.height = fmt->fmt.pix.height;
1577
1578         /* set image capture parameters in the ccdc */
1579         return vpfe_config_ccdc_image_format(vpfe);
1580 }
1581
1582 static int vpfe_enum_size(struct file *file, void  *priv,
1583                           struct v4l2_frmsizeenum *fsize)
1584 {
1585         struct vpfe_device *vpfe = video_drvdata(file);
1586         struct v4l2_subdev_frame_size_enum fse;
1587         struct vpfe_subdev_info *sdinfo;
1588         struct v4l2_mbus_framefmt mbus;
1589         struct v4l2_pix_format pix;
1590         struct vpfe_fmt *fmt;
1591         int ret;
1592
1593         vpfe_dbg(2, vpfe, "vpfe_enum_size\n");
1594
1595         /* check for valid format */
1596         fmt = find_format_by_pix(fsize->pixel_format);
1597         if (!fmt) {
1598                 vpfe_dbg(3, vpfe, "Invalid pixel code: %x, default used instead\n",
1599                         fsize->pixel_format);
1600                 return -EINVAL;
1601         }
1602
1603         memset(fsize->reserved, 0x0, sizeof(fsize->reserved));
1604
1605         sdinfo = vpfe->current_subdev;
1606         if (!sdinfo->sd)
1607                 return -EINVAL;
1608
1609         memset(&pix, 0x0, sizeof(pix));
1610         /* Construct pix from parameter and use default for the rest */
1611         pix.pixelformat = fsize->pixel_format;
1612         pix.width = 640;
1613         pix.height = 480;
1614         pix.colorspace = V4L2_COLORSPACE_SRGB;
1615         pix.field = V4L2_FIELD_NONE;
1616         pix_to_mbus(vpfe, &pix, &mbus);
1617
1618         memset(&fse, 0x0, sizeof(fse));
1619         fse.index = fsize->index;
1620         fse.pad = 0;
1621         fse.code = mbus.code;
1622         fse.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1623         ret = v4l2_subdev_call(sdinfo->sd, pad, enum_frame_size, NULL, &fse);
1624         if (ret)
1625                 return -EINVAL;
1626
1627         vpfe_dbg(1, vpfe, "vpfe_enum_size: index: %d code: %x W:[%d,%d] H:[%d,%d]\n",
1628                 fse.index, fse.code, fse.min_width, fse.max_width,
1629                 fse.min_height, fse.max_height);
1630
1631         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1632         fsize->discrete.width = fse.max_width;
1633         fsize->discrete.height = fse.max_height;
1634
1635         vpfe_dbg(1, vpfe, "vpfe_enum_size: index: %d pixformat: %s size: %dx%d\n",
1636                 fsize->index, print_fourcc(fsize->pixel_format),
1637                 fsize->discrete.width, fsize->discrete.height);
1638
1639         return 0;
1640 }
1641
1642 /*
1643  * vpfe_get_subdev_input_index - Get subdev index and subdev input index for a
1644  * given app input index
1645  */
1646 static int
1647 vpfe_get_subdev_input_index(struct vpfe_device *vpfe,
1648                             int *subdev_index,
1649                             int *subdev_input_index,
1650                             int app_input_index)
1651 {
1652         int i, j = 0;
1653
1654         for (i = 0; i < ARRAY_SIZE(vpfe->cfg->asd); i++) {
1655                 if (app_input_index < (j + 1)) {
1656                         *subdev_index = i;
1657                         *subdev_input_index = app_input_index - j;
1658                         return 0;
1659                 }
1660                 j++;
1661         }
1662         return -EINVAL;
1663 }
1664
1665 /*
1666  * vpfe_get_app_input - Get app input index for a given subdev input index
1667  * driver stores the input index of the current sub device and translate it
1668  * when application request the current input
1669  */
1670 static int vpfe_get_app_input_index(struct vpfe_device *vpfe,
1671                                     int *app_input_index)
1672 {
1673         struct vpfe_config *cfg = vpfe->cfg;
1674         struct vpfe_subdev_info *sdinfo;
1675         struct i2c_client *client;
1676         struct i2c_client *curr_client;
1677         int i, j = 0;
1678
1679         curr_client = v4l2_get_subdevdata(vpfe->current_subdev->sd);
1680         for (i = 0; i < ARRAY_SIZE(vpfe->cfg->asd); i++) {
1681                 sdinfo = &cfg->sub_devs[i];
1682                 client = v4l2_get_subdevdata(sdinfo->sd);
1683                 if (client->addr == curr_client->addr &&
1684                     client->adapter->nr == curr_client->adapter->nr) {
1685                         if (vpfe->current_input >= 1)
1686                                 return -1;
1687                         *app_input_index = j + vpfe->current_input;
1688                         return 0;
1689                 }
1690                 j++;
1691         }
1692         return -EINVAL;
1693 }
1694
1695 static int vpfe_enum_input(struct file *file, void *priv,
1696                            struct v4l2_input *inp)
1697 {
1698         struct vpfe_device *vpfe = video_drvdata(file);
1699         struct vpfe_subdev_info *sdinfo;
1700         int subdev, index;
1701
1702         vpfe_dbg(2, vpfe, "vpfe_enum_input\n");
1703
1704         if (vpfe_get_subdev_input_index(vpfe, &subdev, &index,
1705                                         inp->index) < 0) {
1706                 vpfe_dbg(1, vpfe,
1707                         "input information not found for the subdev\n");
1708                 return -EINVAL;
1709         }
1710         sdinfo = &vpfe->cfg->sub_devs[subdev];
1711         *inp = sdinfo->inputs[index];
1712
1713         return 0;
1714 }
1715
1716 static int vpfe_g_input(struct file *file, void *priv, unsigned int *index)
1717 {
1718         struct vpfe_device *vpfe = video_drvdata(file);
1719
1720         vpfe_dbg(2, vpfe, "vpfe_g_input\n");
1721
1722         return vpfe_get_app_input_index(vpfe, index);
1723 }
1724
1725 /* Assumes caller is holding vpfe_dev->lock */
1726 static int vpfe_set_input(struct vpfe_device *vpfe, unsigned int index)
1727 {
1728         int subdev_index = 0, inp_index = 0;
1729         struct vpfe_subdev_info *sdinfo;
1730         struct vpfe_route *route;
1731         u32 input, output;
1732         int ret;
1733
1734         vpfe_dbg(2, vpfe, "vpfe_set_input: index: %d\n", index);
1735
1736         /* If streaming is started, return error */
1737         if (vb2_is_busy(&vpfe->buffer_queue)) {
1738                 vpfe_err(vpfe, "%s device busy\n", __func__);
1739                 return -EBUSY;
1740         }
1741         ret = vpfe_get_subdev_input_index(vpfe,
1742                                           &subdev_index,
1743                                           &inp_index,
1744                                           index);
1745         if (ret < 0) {
1746                 vpfe_err(vpfe, "invalid input index: %d\n", index);
1747                 goto get_out;
1748         }
1749
1750         sdinfo = &vpfe->cfg->sub_devs[subdev_index];
1751         sdinfo->sd = vpfe->sd[subdev_index];
1752         route = &sdinfo->routes[inp_index];
1753         if (route && sdinfo->can_route) {
1754                 input = route->input;
1755                 output = route->output;
1756                 if (sdinfo->sd) {
1757                         ret = v4l2_subdev_call(sdinfo->sd, video,
1758                                         s_routing, input, output, 0);
1759                         if (ret) {
1760                                 vpfe_err(vpfe, "s_routing failed\n");
1761                                 ret = -EINVAL;
1762                                 goto get_out;
1763                         }
1764                 }
1765
1766         }
1767
1768         vpfe->current_subdev = sdinfo;
1769         if (sdinfo->sd)
1770                 vpfe->v4l2_dev.ctrl_handler = sdinfo->sd->ctrl_handler;
1771         vpfe->current_input = index;
1772         vpfe->std_index = 0;
1773
1774         /* set the bus/interface parameter for the sub device in ccdc */
1775         ret = vpfe_ccdc_set_hw_if_params(&vpfe->ccdc, &sdinfo->vpfe_param);
1776         if (ret)
1777                 return ret;
1778
1779         /* set the default image parameters in the device */
1780         return vpfe_config_image_format(vpfe,
1781                                         vpfe_standards[vpfe->std_index].std_id);
1782
1783 get_out:
1784         return ret;
1785 }
1786
1787 static int vpfe_s_input(struct file *file, void *priv, unsigned int index)
1788 {
1789         struct vpfe_device *vpfe = video_drvdata(file);
1790
1791         vpfe_dbg(2, vpfe,
1792                 "vpfe_s_input: index: %d\n", index);
1793
1794         return vpfe_set_input(vpfe, index);
1795 }
1796
1797 static int vpfe_querystd(struct file *file, void *priv, v4l2_std_id *std_id)
1798 {
1799         struct vpfe_device *vpfe = video_drvdata(file);
1800         struct vpfe_subdev_info *sdinfo;
1801
1802         vpfe_dbg(2, vpfe, "vpfe_querystd\n");
1803
1804         sdinfo = vpfe->current_subdev;
1805         if (!(sdinfo->inputs[0].capabilities & V4L2_IN_CAP_STD))
1806                 return -ENODATA;
1807
1808         /* Call querystd function of decoder device */
1809         return v4l2_device_call_until_err(&vpfe->v4l2_dev, sdinfo->grp_id,
1810                                          video, querystd, std_id);
1811 }
1812
1813 static int vpfe_s_std(struct file *file, void *priv, v4l2_std_id std_id)
1814 {
1815         struct vpfe_device *vpfe = video_drvdata(file);
1816         struct vpfe_subdev_info *sdinfo;
1817         int ret;
1818
1819         vpfe_dbg(2, vpfe, "vpfe_s_std\n");
1820
1821         sdinfo = vpfe->current_subdev;
1822         if (!(sdinfo->inputs[0].capabilities & V4L2_IN_CAP_STD))
1823                 return -ENODATA;
1824
1825         /* If streaming is started, return error */
1826         if (vb2_is_busy(&vpfe->buffer_queue)) {
1827                 vpfe_err(vpfe, "%s device busy\n", __func__);
1828                 ret = -EBUSY;
1829                 return ret;
1830         }
1831
1832         ret = v4l2_device_call_until_err(&vpfe->v4l2_dev, sdinfo->grp_id,
1833                                          video, s_std, std_id);
1834         if (ret < 0) {
1835                 vpfe_err(vpfe, "Failed to set standard\n");
1836                 return ret;
1837         }
1838         ret = vpfe_config_image_format(vpfe, std_id);
1839
1840         return ret;
1841 }
1842
1843 static int vpfe_g_std(struct file *file, void *priv, v4l2_std_id *std_id)
1844 {
1845         struct vpfe_device *vpfe = video_drvdata(file);
1846         struct vpfe_subdev_info *sdinfo;
1847
1848         vpfe_dbg(2, vpfe, "vpfe_g_std\n");
1849
1850         sdinfo = vpfe->current_subdev;
1851         if (sdinfo->inputs[0].capabilities != V4L2_IN_CAP_STD)
1852                 return -ENODATA;
1853
1854         *std_id = vpfe_standards[vpfe->std_index].std_id;
1855
1856         return 0;
1857 }
1858
1859 /*
1860  * vpfe_calculate_offsets : This function calculates buffers offset
1861  * for top and bottom field
1862  */
1863 static void vpfe_calculate_offsets(struct vpfe_device *vpfe)
1864 {
1865         struct v4l2_rect image_win;
1866
1867         vpfe_dbg(2, vpfe, "vpfe_calculate_offsets\n");
1868
1869         vpfe_ccdc_get_image_window(&vpfe->ccdc, &image_win);
1870         vpfe->field_off = image_win.height * image_win.width;
1871 }
1872
1873 /*
1874  * vpfe_queue_setup - Callback function for buffer setup.
1875  * @vq: vb2_queue ptr
1876  * @nbuffers: ptr to number of buffers requested by application
1877  * @nplanes:: contains number of distinct video planes needed to hold a frame
1878  * @sizes[]: contains the size (in bytes) of each plane.
1879  * @alloc_devs: ptr to allocation context
1880  *
1881  * This callback function is called when reqbuf() is called to adjust
1882  * the buffer count and buffer size
1883  */
1884 static int vpfe_queue_setup(struct vb2_queue *vq,
1885                             unsigned int *nbuffers, unsigned int *nplanes,
1886                             unsigned int sizes[], struct device *alloc_devs[])
1887 {
1888         struct vpfe_device *vpfe = vb2_get_drv_priv(vq);
1889         unsigned size = vpfe->fmt.fmt.pix.sizeimage;
1890
1891         if (vq->num_buffers + *nbuffers < 3)
1892                 *nbuffers = 3 - vq->num_buffers;
1893
1894         if (*nplanes) {
1895                 if (sizes[0] < size)
1896                         return -EINVAL;
1897                 size = sizes[0];
1898         }
1899
1900         *nplanes = 1;
1901         sizes[0] = size;
1902
1903         vpfe_dbg(1, vpfe,
1904                 "nbuffers=%d, size=%u\n", *nbuffers, sizes[0]);
1905
1906         /* Calculate field offset */
1907         vpfe_calculate_offsets(vpfe);
1908
1909         return 0;
1910 }
1911
1912 /*
1913  * vpfe_buffer_prepare :  callback function for buffer prepare
1914  * @vb: ptr to vb2_buffer
1915  *
1916  * This is the callback function for buffer prepare when vb2_qbuf()
1917  * function is called. The buffer is prepared and user space virtual address
1918  * or user address is converted into  physical address
1919  */
1920 static int vpfe_buffer_prepare(struct vb2_buffer *vb)
1921 {
1922         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1923         struct vpfe_device *vpfe = vb2_get_drv_priv(vb->vb2_queue);
1924
1925         vb2_set_plane_payload(vb, 0, vpfe->fmt.fmt.pix.sizeimage);
1926
1927         if (vb2_get_plane_payload(vb, 0) > vb2_plane_size(vb, 0))
1928                 return -EINVAL;
1929
1930         vbuf->field = vpfe->fmt.fmt.pix.field;
1931
1932         return 0;
1933 }
1934
1935 /*
1936  * vpfe_buffer_queue : Callback function to add buffer to DMA queue
1937  * @vb: ptr to vb2_buffer
1938  */
1939 static void vpfe_buffer_queue(struct vb2_buffer *vb)
1940 {
1941         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1942         struct vpfe_device *vpfe = vb2_get_drv_priv(vb->vb2_queue);
1943         struct vpfe_cap_buffer *buf = to_vpfe_buffer(vbuf);
1944         unsigned long flags = 0;
1945
1946         /* add the buffer to the DMA queue */
1947         spin_lock_irqsave(&vpfe->dma_queue_lock, flags);
1948         list_add_tail(&buf->list, &vpfe->dma_queue);
1949         spin_unlock_irqrestore(&vpfe->dma_queue_lock, flags);
1950 }
1951
1952 /*
1953  * vpfe_start_streaming : Starts the DMA engine for streaming
1954  * @vb: ptr to vb2_buffer
1955  * @count: number of buffers
1956  */
1957 static int vpfe_start_streaming(struct vb2_queue *vq, unsigned int count)
1958 {
1959         struct vpfe_device *vpfe = vb2_get_drv_priv(vq);
1960         struct vpfe_cap_buffer *buf, *tmp;
1961         struct vpfe_subdev_info *sdinfo;
1962         unsigned long flags;
1963         unsigned long addr;
1964         int ret;
1965
1966         spin_lock_irqsave(&vpfe->dma_queue_lock, flags);
1967
1968         vpfe->field = 0;
1969         vpfe->sequence = 0;
1970
1971         sdinfo = vpfe->current_subdev;
1972
1973         vpfe_attach_irq(vpfe);
1974
1975         vpfe->stopping = false;
1976         init_completion(&vpfe->capture_stop);
1977
1978         if (vpfe->ccdc.ccdc_cfg.if_type == VPFE_RAW_BAYER)
1979                 vpfe_ccdc_config_raw(&vpfe->ccdc);
1980         else
1981                 vpfe_ccdc_config_ycbcr(&vpfe->ccdc);
1982
1983         /* Get the next frame from the buffer queue */
1984         vpfe->next_frm = list_entry(vpfe->dma_queue.next,
1985                                     struct vpfe_cap_buffer, list);
1986         vpfe->cur_frm = vpfe->next_frm;
1987         /* Remove buffer from the buffer queue */
1988         list_del(&vpfe->cur_frm->list);
1989         spin_unlock_irqrestore(&vpfe->dma_queue_lock, flags);
1990
1991         addr = vb2_dma_contig_plane_dma_addr(&vpfe->cur_frm->vb.vb2_buf, 0);
1992
1993         vpfe_set_sdr_addr(&vpfe->ccdc, (unsigned long)(addr));
1994
1995         vpfe_pcr_enable(&vpfe->ccdc, 1);
1996
1997         ret = v4l2_subdev_call(sdinfo->sd, video, s_stream, 1);
1998         if (ret < 0) {
1999                 vpfe_err(vpfe, "Error in attaching interrupt handle\n");
2000                 goto err;
2001         }
2002
2003         return 0;
2004
2005 err:
2006         list_for_each_entry_safe(buf, tmp, &vpfe->dma_queue, list) {
2007                 list_del(&buf->list);
2008                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
2009         }
2010
2011         vpfe_pcr_enable(&vpfe->ccdc, 0);
2012         return ret;
2013 }
2014
2015 /*
2016  * vpfe_stop_streaming : Stop the DMA engine
2017  * @vq: ptr to vb2_queue
2018  *
2019  * This callback stops the DMA engine and any remaining buffers
2020  * in the DMA queue are released.
2021  */
2022 static void vpfe_stop_streaming(struct vb2_queue *vq)
2023 {
2024         struct vpfe_device *vpfe = vb2_get_drv_priv(vq);
2025         struct vpfe_subdev_info *sdinfo;
2026         unsigned long flags;
2027         int ret;
2028
2029         vpfe_pcr_enable(&vpfe->ccdc, 0);
2030
2031         /* Wait for the last frame to be captured */
2032         vpfe->stopping = true;
2033         wait_for_completion_timeout(&vpfe->capture_stop,
2034                                     msecs_to_jiffies(250));
2035
2036         vpfe_detach_irq(vpfe);
2037
2038         sdinfo = vpfe->current_subdev;
2039         ret = v4l2_subdev_call(sdinfo->sd, video, s_stream, 0);
2040         if (ret && ret != -ENOIOCTLCMD && ret != -ENODEV)
2041                 vpfe_dbg(1, vpfe, "stream off failed in subdev\n");
2042
2043         /* release all active buffers */
2044         spin_lock_irqsave(&vpfe->dma_queue_lock, flags);
2045         if (vpfe->cur_frm == vpfe->next_frm) {
2046                 vb2_buffer_done(&vpfe->cur_frm->vb.vb2_buf,
2047                                 VB2_BUF_STATE_ERROR);
2048         } else {
2049                 if (vpfe->cur_frm != NULL)
2050                         vb2_buffer_done(&vpfe->cur_frm->vb.vb2_buf,
2051                                         VB2_BUF_STATE_ERROR);
2052                 if (vpfe->next_frm != NULL)
2053                         vb2_buffer_done(&vpfe->next_frm->vb.vb2_buf,
2054                                         VB2_BUF_STATE_ERROR);
2055         }
2056
2057         while (!list_empty(&vpfe->dma_queue)) {
2058                 vpfe->next_frm = list_entry(vpfe->dma_queue.next,
2059                                                 struct vpfe_cap_buffer, list);
2060                 list_del(&vpfe->next_frm->list);
2061                 vb2_buffer_done(&vpfe->next_frm->vb.vb2_buf,
2062                                 VB2_BUF_STATE_ERROR);
2063         }
2064         spin_unlock_irqrestore(&vpfe->dma_queue_lock, flags);
2065 }
2066
2067 static int vpfe_g_pixelaspect(struct file *file, void *priv,
2068                               int type, struct v4l2_fract *f)
2069 {
2070         struct vpfe_device *vpfe = video_drvdata(file);
2071
2072         vpfe_dbg(2, vpfe, "vpfe_g_pixelaspect\n");
2073
2074         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2075             vpfe->std_index >= ARRAY_SIZE(vpfe_standards))
2076                 return -EINVAL;
2077
2078         *f = vpfe_standards[vpfe->std_index].pixelaspect;
2079
2080         return 0;
2081 }
2082
2083 static int
2084 vpfe_g_selection(struct file *file, void *fh, struct v4l2_selection *s)
2085 {
2086         struct vpfe_device *vpfe = video_drvdata(file);
2087
2088         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2089             vpfe->std_index >= ARRAY_SIZE(vpfe_standards))
2090                 return -EINVAL;
2091
2092         switch (s->target) {
2093         case V4L2_SEL_TGT_CROP_BOUNDS:
2094         case V4L2_SEL_TGT_CROP_DEFAULT:
2095                 s->r.left = 0;
2096                 s->r.top = 0;
2097                 s->r.width = vpfe_standards[vpfe->std_index].width;
2098                 s->r.height = vpfe_standards[vpfe->std_index].height;
2099                 break;
2100
2101         case V4L2_SEL_TGT_CROP:
2102                 s->r = vpfe->crop;
2103                 break;
2104
2105         default:
2106                 return -EINVAL;
2107         }
2108
2109         return 0;
2110 }
2111
2112 static int enclosed_rectangle(struct v4l2_rect *a, struct v4l2_rect *b)
2113 {
2114         if (a->left < b->left || a->top < b->top)
2115                 return 0;
2116
2117         if (a->left + a->width > b->left + b->width)
2118                 return 0;
2119
2120         if (a->top + a->height > b->top + b->height)
2121                 return 0;
2122
2123         return 1;
2124 }
2125
2126 static int
2127 vpfe_s_selection(struct file *file, void *fh, struct v4l2_selection *s)
2128 {
2129         struct vpfe_device *vpfe = video_drvdata(file);
2130         struct v4l2_rect cr = vpfe->crop;
2131         struct v4l2_rect r = s->r;
2132
2133         /* If streaming is started, return error */
2134         if (vb2_is_busy(&vpfe->buffer_queue)) {
2135                 vpfe_err(vpfe, "%s device busy\n", __func__);
2136                 return -EBUSY;
2137         }
2138
2139         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2140                         s->target != V4L2_SEL_TGT_CROP)
2141                 return -EINVAL;
2142
2143         v4l_bound_align_image(&r.width, 0, cr.width, 0,
2144                               &r.height, 0, cr.height, 0, 0);
2145
2146         r.left = clamp_t(unsigned int, r.left, 0, cr.width - r.width);
2147         r.top  = clamp_t(unsigned int, r.top, 0, cr.height - r.height);
2148
2149         if (s->flags & V4L2_SEL_FLAG_LE && !enclosed_rectangle(&r, &s->r))
2150                 return -ERANGE;
2151
2152         if (s->flags & V4L2_SEL_FLAG_GE && !enclosed_rectangle(&s->r, &r))
2153                 return -ERANGE;
2154
2155         s->r = vpfe->crop = r;
2156
2157         vpfe_ccdc_set_image_window(&vpfe->ccdc, &r, vpfe->bpp);
2158         vpfe->fmt.fmt.pix.width = r.width;
2159         vpfe->fmt.fmt.pix.height = r.height;
2160         vpfe->fmt.fmt.pix.bytesperline = vpfe_ccdc_get_line_length(&vpfe->ccdc);
2161         vpfe->fmt.fmt.pix.sizeimage = vpfe->fmt.fmt.pix.bytesperline *
2162                                                 vpfe->fmt.fmt.pix.height;
2163
2164         vpfe_dbg(1, vpfe, "cropped (%d,%d)/%dx%d of %dx%d\n",
2165                  r.left, r.top, r.width, r.height, cr.width, cr.height);
2166
2167         return 0;
2168 }
2169
2170 static long vpfe_ioctl_default(struct file *file, void *priv,
2171                                bool valid_prio, unsigned int cmd, void *param)
2172 {
2173         struct vpfe_device *vpfe = video_drvdata(file);
2174         int ret;
2175
2176         vpfe_dbg(2, vpfe, "vpfe_ioctl_default\n");
2177
2178         if (!valid_prio) {
2179                 vpfe_err(vpfe, "%s device busy\n", __func__);
2180                 return -EBUSY;
2181         }
2182
2183         /* If streaming is started, return error */
2184         if (vb2_is_busy(&vpfe->buffer_queue)) {
2185                 vpfe_err(vpfe, "%s device busy\n", __func__);
2186                 return -EBUSY;
2187         }
2188
2189         switch (cmd) {
2190         case VIDIOC_AM437X_CCDC_CFG:
2191                 ret = vpfe_ccdc_set_params(&vpfe->ccdc, (void __user *)param);
2192                 if (ret) {
2193                         vpfe_dbg(2, vpfe,
2194                                 "Error setting parameters in CCDC\n");
2195                         return ret;
2196                 }
2197                 ret = vpfe_get_ccdc_image_format(vpfe,
2198                                                  &vpfe->fmt);
2199                 if (ret < 0) {
2200                         vpfe_dbg(2, vpfe,
2201                                 "Invalid image format at CCDC\n");
2202                         return ret;
2203                 }
2204                 break;
2205
2206         default:
2207                 ret = -ENOTTY;
2208                 break;
2209         }
2210
2211         return ret;
2212 }
2213
2214 static const struct vb2_ops vpfe_video_qops = {
2215         .wait_prepare           = vb2_ops_wait_prepare,
2216         .wait_finish            = vb2_ops_wait_finish,
2217         .queue_setup            = vpfe_queue_setup,
2218         .buf_prepare            = vpfe_buffer_prepare,
2219         .buf_queue              = vpfe_buffer_queue,
2220         .start_streaming        = vpfe_start_streaming,
2221         .stop_streaming         = vpfe_stop_streaming,
2222 };
2223
2224 /* vpfe capture driver file operations */
2225 static const struct v4l2_file_operations vpfe_fops = {
2226         .owner          = THIS_MODULE,
2227         .open           = vpfe_open,
2228         .release        = vpfe_release,
2229         .read           = vb2_fop_read,
2230         .poll           = vb2_fop_poll,
2231         .unlocked_ioctl = video_ioctl2,
2232         .mmap           = vb2_fop_mmap,
2233 };
2234
2235 /* vpfe capture ioctl operations */
2236 static const struct v4l2_ioctl_ops vpfe_ioctl_ops = {
2237         .vidioc_querycap                = vpfe_querycap,
2238         .vidioc_enum_fmt_vid_cap        = vpfe_enum_fmt,
2239         .vidioc_g_fmt_vid_cap           = vpfe_g_fmt,
2240         .vidioc_s_fmt_vid_cap           = vpfe_s_fmt,
2241         .vidioc_try_fmt_vid_cap         = vpfe_try_fmt,
2242
2243         .vidioc_enum_framesizes         = vpfe_enum_size,
2244
2245         .vidioc_enum_input              = vpfe_enum_input,
2246         .vidioc_g_input                 = vpfe_g_input,
2247         .vidioc_s_input                 = vpfe_s_input,
2248
2249         .vidioc_querystd                = vpfe_querystd,
2250         .vidioc_s_std                   = vpfe_s_std,
2251         .vidioc_g_std                   = vpfe_g_std,
2252
2253         .vidioc_reqbufs                 = vb2_ioctl_reqbufs,
2254         .vidioc_create_bufs             = vb2_ioctl_create_bufs,
2255         .vidioc_prepare_buf             = vb2_ioctl_prepare_buf,
2256         .vidioc_querybuf                = vb2_ioctl_querybuf,
2257         .vidioc_qbuf                    = vb2_ioctl_qbuf,
2258         .vidioc_dqbuf                   = vb2_ioctl_dqbuf,
2259         .vidioc_expbuf                  = vb2_ioctl_expbuf,
2260         .vidioc_streamon                = vb2_ioctl_streamon,
2261         .vidioc_streamoff               = vb2_ioctl_streamoff,
2262
2263         .vidioc_log_status              = v4l2_ctrl_log_status,
2264         .vidioc_subscribe_event         = v4l2_ctrl_subscribe_event,
2265         .vidioc_unsubscribe_event       = v4l2_event_unsubscribe,
2266
2267         .vidioc_g_pixelaspect           = vpfe_g_pixelaspect,
2268         .vidioc_g_selection             = vpfe_g_selection,
2269         .vidioc_s_selection             = vpfe_s_selection,
2270
2271         .vidioc_default                 = vpfe_ioctl_default,
2272 };
2273
2274 static int
2275 vpfe_async_bound(struct v4l2_async_notifier *notifier,
2276                  struct v4l2_subdev *subdev,
2277                  struct v4l2_async_subdev *asd)
2278 {
2279         struct vpfe_device *vpfe = container_of(notifier->v4l2_dev,
2280                                                struct vpfe_device, v4l2_dev);
2281         struct v4l2_subdev_mbus_code_enum mbus_code;
2282         struct vpfe_subdev_info *sdinfo;
2283         bool found = false;
2284         int i, j;
2285
2286         vpfe_dbg(1, vpfe, "vpfe_async_bound\n");
2287
2288         for (i = 0; i < ARRAY_SIZE(vpfe->cfg->asd); i++) {
2289                 if (vpfe->cfg->asd[i]->match.fwnode ==
2290                     asd[i].match.fwnode) {
2291                         sdinfo = &vpfe->cfg->sub_devs[i];
2292                         vpfe->sd[i] = subdev;
2293                         vpfe->sd[i]->grp_id = sdinfo->grp_id;
2294                         found = true;
2295                         break;
2296                 }
2297         }
2298
2299         if (!found) {
2300                 vpfe_info(vpfe, "sub device (%s) not matched\n", subdev->name);
2301                 return -EINVAL;
2302         }
2303
2304         vpfe->video_dev.tvnorms |= sdinfo->inputs[0].std;
2305
2306         /* setup the supported formats & indexes */
2307         for (j = 0, i = 0; ; ++j) {
2308                 struct vpfe_fmt *fmt;
2309                 int ret;
2310
2311                 memset(&mbus_code, 0, sizeof(mbus_code));
2312                 mbus_code.index = j;
2313                 mbus_code.which = V4L2_SUBDEV_FORMAT_ACTIVE;
2314                 ret = v4l2_subdev_call(subdev, pad, enum_mbus_code,
2315                                NULL, &mbus_code);
2316                 if (ret)
2317                         break;
2318
2319                 fmt = find_format_by_code(mbus_code.code);
2320                 if (!fmt)
2321                         continue;
2322
2323                 fmt->supported = true;
2324                 fmt->index = i++;
2325         }
2326
2327         return 0;
2328 }
2329
2330 static int vpfe_probe_complete(struct vpfe_device *vpfe)
2331 {
2332         struct video_device *vdev;
2333         struct vb2_queue *q;
2334         int err;
2335
2336         spin_lock_init(&vpfe->dma_queue_lock);
2337         mutex_init(&vpfe->lock);
2338
2339         vpfe->fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2340
2341         /* set first sub device as current one */
2342         vpfe->current_subdev = &vpfe->cfg->sub_devs[0];
2343         vpfe->v4l2_dev.ctrl_handler = vpfe->sd[0]->ctrl_handler;
2344
2345         err = vpfe_set_input(vpfe, 0);
2346         if (err)
2347                 goto probe_out;
2348
2349         /* Initialize videobuf2 queue as per the buffer type */
2350         q = &vpfe->buffer_queue;
2351         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2352         q->io_modes = VB2_MMAP | VB2_DMABUF | VB2_READ;
2353         q->drv_priv = vpfe;
2354         q->ops = &vpfe_video_qops;
2355         q->mem_ops = &vb2_dma_contig_memops;
2356         q->buf_struct_size = sizeof(struct vpfe_cap_buffer);
2357         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
2358         q->lock = &vpfe->lock;
2359         q->min_buffers_needed = 1;
2360         q->dev = vpfe->pdev;
2361
2362         err = vb2_queue_init(q);
2363         if (err) {
2364                 vpfe_err(vpfe, "vb2_queue_init() failed\n");
2365                 goto probe_out;
2366         }
2367
2368         INIT_LIST_HEAD(&vpfe->dma_queue);
2369
2370         vdev = &vpfe->video_dev;
2371         strscpy(vdev->name, VPFE_MODULE_NAME, sizeof(vdev->name));
2372         vdev->release = video_device_release_empty;
2373         vdev->fops = &vpfe_fops;
2374         vdev->ioctl_ops = &vpfe_ioctl_ops;
2375         vdev->v4l2_dev = &vpfe->v4l2_dev;
2376         vdev->vfl_dir = VFL_DIR_RX;
2377         vdev->queue = q;
2378         vdev->lock = &vpfe->lock;
2379         vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
2380                             V4L2_CAP_READWRITE;
2381         video_set_drvdata(vdev, vpfe);
2382         err = video_register_device(&vpfe->video_dev, VFL_TYPE_GRABBER, -1);
2383         if (err) {
2384                 vpfe_err(vpfe,
2385                         "Unable to register video device.\n");
2386                 goto probe_out;
2387         }
2388
2389         return 0;
2390
2391 probe_out:
2392         v4l2_device_unregister(&vpfe->v4l2_dev);
2393         return err;
2394 }
2395
2396 static int vpfe_async_complete(struct v4l2_async_notifier *notifier)
2397 {
2398         struct vpfe_device *vpfe = container_of(notifier->v4l2_dev,
2399                                         struct vpfe_device, v4l2_dev);
2400
2401         return vpfe_probe_complete(vpfe);
2402 }
2403
2404 static const struct v4l2_async_notifier_operations vpfe_async_ops = {
2405         .bound = vpfe_async_bound,
2406         .complete = vpfe_async_complete,
2407 };
2408
2409 static struct vpfe_config *
2410 vpfe_get_pdata(struct vpfe_device *vpfe)
2411 {
2412         struct device_node *endpoint = NULL;
2413         struct device *dev = vpfe->pdev;
2414         struct vpfe_subdev_info *sdinfo;
2415         struct vpfe_config *pdata;
2416         unsigned int flags;
2417         unsigned int i;
2418         int err;
2419
2420         dev_dbg(dev, "vpfe_get_pdata\n");
2421
2422         v4l2_async_notifier_init(&vpfe->notifier);
2423
2424         if (!IS_ENABLED(CONFIG_OF) || !dev->of_node)
2425                 return dev->platform_data;
2426
2427         pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
2428         if (!pdata)
2429                 return NULL;
2430
2431         for (i = 0; ; i++) {
2432                 struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = 0 };
2433                 struct device_node *rem;
2434
2435                 endpoint = of_graph_get_next_endpoint(dev->of_node, endpoint);
2436                 if (!endpoint)
2437                         break;
2438
2439                 sdinfo = &pdata->sub_devs[i];
2440                 sdinfo->grp_id = 0;
2441
2442                 /* we only support camera */
2443                 sdinfo->inputs[0].index = i;
2444                 strscpy(sdinfo->inputs[0].name, "Camera",
2445                         sizeof(sdinfo->inputs[0].name));
2446                 sdinfo->inputs[0].type = V4L2_INPUT_TYPE_CAMERA;
2447                 sdinfo->inputs[0].std = V4L2_STD_ALL;
2448                 sdinfo->inputs[0].capabilities = V4L2_IN_CAP_STD;
2449
2450                 sdinfo->can_route = 0;
2451                 sdinfo->routes = NULL;
2452
2453                 of_property_read_u32(endpoint, "ti,am437x-vpfe-interface",
2454                                      &sdinfo->vpfe_param.if_type);
2455                 if (sdinfo->vpfe_param.if_type < 0 ||
2456                         sdinfo->vpfe_param.if_type > 4) {
2457                         sdinfo->vpfe_param.if_type = VPFE_RAW_BAYER;
2458                 }
2459
2460                 err = v4l2_fwnode_endpoint_parse(of_fwnode_handle(endpoint),
2461                                                  &bus_cfg);
2462                 if (err) {
2463                         dev_err(dev, "Could not parse the endpoint\n");
2464                         goto cleanup;
2465                 }
2466
2467                 sdinfo->vpfe_param.bus_width = bus_cfg.bus.parallel.bus_width;
2468
2469                 if (sdinfo->vpfe_param.bus_width < 8 ||
2470                         sdinfo->vpfe_param.bus_width > 16) {
2471                         dev_err(dev, "Invalid bus width.\n");
2472                         goto cleanup;
2473                 }
2474
2475                 flags = bus_cfg.bus.parallel.flags;
2476
2477                 if (flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH)
2478                         sdinfo->vpfe_param.hdpol = 1;
2479
2480                 if (flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH)
2481                         sdinfo->vpfe_param.vdpol = 1;
2482
2483                 rem = of_graph_get_remote_port_parent(endpoint);
2484                 if (!rem) {
2485                         dev_err(dev, "Remote device at %pOF not found\n",
2486                                 endpoint);
2487                         goto cleanup;
2488                 }
2489
2490                 pdata->asd[i] = v4l2_async_notifier_add_fwnode_subdev(
2491                         &vpfe->notifier, of_fwnode_handle(rem),
2492                         sizeof(struct v4l2_async_subdev));
2493                 of_node_put(rem);
2494                 if (IS_ERR(pdata->asd[i]))
2495                         goto cleanup;
2496         }
2497
2498         of_node_put(endpoint);
2499         return pdata;
2500
2501 cleanup:
2502         v4l2_async_notifier_cleanup(&vpfe->notifier);
2503         of_node_put(endpoint);
2504         return NULL;
2505 }
2506
2507 /*
2508  * vpfe_probe : This function creates device entries by register
2509  * itself to the V4L2 driver and initializes fields of each
2510  * device objects
2511  */
2512 static int vpfe_probe(struct platform_device *pdev)
2513 {
2514         struct vpfe_config *vpfe_cfg;
2515         struct vpfe_device *vpfe;
2516         struct vpfe_ccdc *ccdc;
2517         struct resource *res;
2518         int ret;
2519
2520         vpfe = devm_kzalloc(&pdev->dev, sizeof(*vpfe), GFP_KERNEL);
2521         if (!vpfe)
2522                 return -ENOMEM;
2523
2524         vpfe->pdev = &pdev->dev;
2525
2526         vpfe_cfg = vpfe_get_pdata(vpfe);
2527         if (!vpfe_cfg) {
2528                 dev_err(&pdev->dev, "No platform data\n");
2529                 return -EINVAL;
2530         }
2531
2532         vpfe->cfg = vpfe_cfg;
2533         ccdc = &vpfe->ccdc;
2534
2535         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2536         ccdc->ccdc_cfg.base_addr = devm_ioremap_resource(&pdev->dev, res);
2537         if (IS_ERR(ccdc->ccdc_cfg.base_addr)) {
2538                 ret = PTR_ERR(ccdc->ccdc_cfg.base_addr);
2539                 goto probe_out_cleanup;
2540         }
2541
2542         ret = platform_get_irq(pdev, 0);
2543         if (ret <= 0) {
2544                 ret = -ENODEV;
2545                 goto probe_out_cleanup;
2546         }
2547         vpfe->irq = ret;
2548
2549         ret = devm_request_irq(vpfe->pdev, vpfe->irq, vpfe_isr, 0,
2550                                "vpfe_capture0", vpfe);
2551         if (ret) {
2552                 dev_err(&pdev->dev, "Unable to request interrupt\n");
2553                 ret = -EINVAL;
2554                 goto probe_out_cleanup;
2555         }
2556
2557         ret = v4l2_device_register(&pdev->dev, &vpfe->v4l2_dev);
2558         if (ret) {
2559                 vpfe_err(vpfe,
2560                         "Unable to register v4l2 device.\n");
2561                 goto probe_out_cleanup;
2562         }
2563
2564         /* set the driver data in platform device */
2565         platform_set_drvdata(pdev, vpfe);
2566         /* Enabling module functional clock */
2567         pm_runtime_enable(&pdev->dev);
2568
2569         /* for now just enable it here instead of waiting for the open */
2570         pm_runtime_get_sync(&pdev->dev);
2571
2572         vpfe_ccdc_config_defaults(ccdc);
2573
2574         pm_runtime_put_sync(&pdev->dev);
2575
2576         vpfe->sd = devm_kcalloc(&pdev->dev,
2577                                 ARRAY_SIZE(vpfe->cfg->asd),
2578                                 sizeof(struct v4l2_subdev *),
2579                                 GFP_KERNEL);
2580         if (!vpfe->sd) {
2581                 ret = -ENOMEM;
2582                 goto probe_out_v4l2_unregister;
2583         }
2584
2585         vpfe->notifier.ops = &vpfe_async_ops;
2586         ret = v4l2_async_notifier_register(&vpfe->v4l2_dev, &vpfe->notifier);
2587         if (ret) {
2588                 vpfe_err(vpfe, "Error registering async notifier\n");
2589                 ret = -EINVAL;
2590                 goto probe_out_v4l2_unregister;
2591         }
2592
2593         return 0;
2594
2595 probe_out_v4l2_unregister:
2596         v4l2_device_unregister(&vpfe->v4l2_dev);
2597 probe_out_cleanup:
2598         v4l2_async_notifier_cleanup(&vpfe->notifier);
2599         return ret;
2600 }
2601
2602 /*
2603  * vpfe_remove : It un-register device from V4L2 driver
2604  */
2605 static int vpfe_remove(struct platform_device *pdev)
2606 {
2607         struct vpfe_device *vpfe = platform_get_drvdata(pdev);
2608
2609         vpfe_dbg(2, vpfe, "vpfe_remove\n");
2610
2611         pm_runtime_disable(&pdev->dev);
2612
2613         v4l2_async_notifier_unregister(&vpfe->notifier);
2614         v4l2_async_notifier_cleanup(&vpfe->notifier);
2615         v4l2_device_unregister(&vpfe->v4l2_dev);
2616         video_unregister_device(&vpfe->video_dev);
2617
2618         return 0;
2619 }
2620
2621 #ifdef CONFIG_PM_SLEEP
2622
2623 static void vpfe_save_context(struct vpfe_ccdc *ccdc)
2624 {
2625         ccdc->ccdc_ctx[VPFE_PCR >> 2] = vpfe_reg_read(ccdc, VPFE_PCR);
2626         ccdc->ccdc_ctx[VPFE_SYNMODE >> 2] = vpfe_reg_read(ccdc, VPFE_SYNMODE);
2627         ccdc->ccdc_ctx[VPFE_SDOFST >> 2] = vpfe_reg_read(ccdc, VPFE_SDOFST);
2628         ccdc->ccdc_ctx[VPFE_SDR_ADDR >> 2] = vpfe_reg_read(ccdc, VPFE_SDR_ADDR);
2629         ccdc->ccdc_ctx[VPFE_CLAMP >> 2] = vpfe_reg_read(ccdc, VPFE_CLAMP);
2630         ccdc->ccdc_ctx[VPFE_DCSUB >> 2] = vpfe_reg_read(ccdc, VPFE_DCSUB);
2631         ccdc->ccdc_ctx[VPFE_COLPTN >> 2] = vpfe_reg_read(ccdc, VPFE_COLPTN);
2632         ccdc->ccdc_ctx[VPFE_BLKCMP >> 2] = vpfe_reg_read(ccdc, VPFE_BLKCMP);
2633         ccdc->ccdc_ctx[VPFE_VDINT >> 2] = vpfe_reg_read(ccdc, VPFE_VDINT);
2634         ccdc->ccdc_ctx[VPFE_ALAW >> 2] = vpfe_reg_read(ccdc, VPFE_ALAW);
2635         ccdc->ccdc_ctx[VPFE_REC656IF >> 2] = vpfe_reg_read(ccdc, VPFE_REC656IF);
2636         ccdc->ccdc_ctx[VPFE_CCDCFG >> 2] = vpfe_reg_read(ccdc, VPFE_CCDCFG);
2637         ccdc->ccdc_ctx[VPFE_CULLING >> 2] = vpfe_reg_read(ccdc, VPFE_CULLING);
2638         ccdc->ccdc_ctx[VPFE_HD_VD_WID >> 2] = vpfe_reg_read(ccdc,
2639                                                             VPFE_HD_VD_WID);
2640         ccdc->ccdc_ctx[VPFE_PIX_LINES >> 2] = vpfe_reg_read(ccdc,
2641                                                             VPFE_PIX_LINES);
2642         ccdc->ccdc_ctx[VPFE_HORZ_INFO >> 2] = vpfe_reg_read(ccdc,
2643                                                             VPFE_HORZ_INFO);
2644         ccdc->ccdc_ctx[VPFE_VERT_START >> 2] = vpfe_reg_read(ccdc,
2645                                                              VPFE_VERT_START);
2646         ccdc->ccdc_ctx[VPFE_VERT_LINES >> 2] = vpfe_reg_read(ccdc,
2647                                                              VPFE_VERT_LINES);
2648         ccdc->ccdc_ctx[VPFE_HSIZE_OFF >> 2] = vpfe_reg_read(ccdc,
2649                                                             VPFE_HSIZE_OFF);
2650 }
2651
2652 static int vpfe_suspend(struct device *dev)
2653 {
2654         struct vpfe_device *vpfe = dev_get_drvdata(dev);
2655         struct vpfe_ccdc *ccdc = &vpfe->ccdc;
2656
2657         /* only do full suspend if streaming has started */
2658         if (vb2_start_streaming_called(&vpfe->buffer_queue)) {
2659                 pm_runtime_get_sync(dev);
2660                 vpfe_config_enable(ccdc, 1);
2661
2662                 /* Save VPFE context */
2663                 vpfe_save_context(ccdc);
2664
2665                 /* Disable CCDC */
2666                 vpfe_pcr_enable(ccdc, 0);
2667                 vpfe_config_enable(ccdc, 0);
2668
2669                 /* Disable both master and slave clock */
2670                 pm_runtime_put_sync(dev);
2671         }
2672
2673         /* Select sleep pin state */
2674         pinctrl_pm_select_sleep_state(dev);
2675
2676         return 0;
2677 }
2678
2679 static void vpfe_restore_context(struct vpfe_ccdc *ccdc)
2680 {
2681         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_SYNMODE >> 2], VPFE_SYNMODE);
2682         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_CULLING >> 2], VPFE_CULLING);
2683         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_SDOFST >> 2], VPFE_SDOFST);
2684         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_SDR_ADDR >> 2], VPFE_SDR_ADDR);
2685         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_CLAMP >> 2], VPFE_CLAMP);
2686         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_DCSUB >> 2], VPFE_DCSUB);
2687         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_COLPTN >> 2], VPFE_COLPTN);
2688         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_BLKCMP >> 2], VPFE_BLKCMP);
2689         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_VDINT >> 2], VPFE_VDINT);
2690         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_ALAW >> 2], VPFE_ALAW);
2691         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_REC656IF >> 2], VPFE_REC656IF);
2692         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_CCDCFG >> 2], VPFE_CCDCFG);
2693         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_PCR >> 2], VPFE_PCR);
2694         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_HD_VD_WID >> 2],
2695                                                 VPFE_HD_VD_WID);
2696         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_PIX_LINES >> 2],
2697                                                 VPFE_PIX_LINES);
2698         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_HORZ_INFO >> 2],
2699                                                 VPFE_HORZ_INFO);
2700         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_VERT_START >> 2],
2701                                                 VPFE_VERT_START);
2702         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_VERT_LINES >> 2],
2703                                                 VPFE_VERT_LINES);
2704         vpfe_reg_write(ccdc, ccdc->ccdc_ctx[VPFE_HSIZE_OFF >> 2],
2705                                                 VPFE_HSIZE_OFF);
2706 }
2707
2708 static int vpfe_resume(struct device *dev)
2709 {
2710         struct vpfe_device *vpfe = dev_get_drvdata(dev);
2711         struct vpfe_ccdc *ccdc = &vpfe->ccdc;
2712
2713         /* only do full resume if streaming has started */
2714         if (vb2_start_streaming_called(&vpfe->buffer_queue)) {
2715                 /* Enable both master and slave clock */
2716                 pm_runtime_get_sync(dev);
2717                 vpfe_config_enable(ccdc, 1);
2718
2719                 /* Restore VPFE context */
2720                 vpfe_restore_context(ccdc);
2721
2722                 vpfe_config_enable(ccdc, 0);
2723                 pm_runtime_put_sync(dev);
2724         }
2725
2726         /* Select default pin state */
2727         pinctrl_pm_select_default_state(dev);
2728
2729         return 0;
2730 }
2731
2732 #endif
2733
2734 static SIMPLE_DEV_PM_OPS(vpfe_pm_ops, vpfe_suspend, vpfe_resume);
2735
2736 static const struct of_device_id vpfe_of_match[] = {
2737         { .compatible = "ti,am437x-vpfe", },
2738         { /* sentinel */ },
2739 };
2740 MODULE_DEVICE_TABLE(of, vpfe_of_match);
2741
2742 static struct platform_driver vpfe_driver = {
2743         .probe          = vpfe_probe,
2744         .remove         = vpfe_remove,
2745         .driver = {
2746                 .name   = VPFE_MODULE_NAME,
2747                 .pm     = &vpfe_pm_ops,
2748                 .of_match_table = of_match_ptr(vpfe_of_match),
2749         },
2750 };
2751
2752 module_platform_driver(vpfe_driver);
2753
2754 MODULE_AUTHOR("Texas Instruments");
2755 MODULE_DESCRIPTION("TI AM437x VPFE driver");
2756 MODULE_LICENSE("GPL");
2757 MODULE_VERSION(VPFE_VERSION);