]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/media/platform/ti-vpe/vpe.c
0e9cb0319a92540fc39b7f64eb00f5d270f72de7
[linux.git] / drivers / media / platform / ti-vpe / vpe.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * TI VPE mem2mem driver, based on the virtual v4l2-mem2mem example driver
4  *
5  * Copyright (c) 2013 Texas Instruments Inc.
6  * David Griego, <dagriego@biglakesoftware.com>
7  * Dale Farnsworth, <dale@farnsworth.org>
8  * Archit Taneja, <archit@ti.com>
9  *
10  * Copyright (c) 2009-2010 Samsung Electronics Co., Ltd.
11  * Pawel Osciak, <pawel@osciak.com>
12  * Marek Szyprowski, <m.szyprowski@samsung.com>
13  *
14  * Based on the virtual v4l2-mem2mem example device
15  */
16
17 #include <linux/delay.h>
18 #include <linux/dma-mapping.h>
19 #include <linux/err.h>
20 #include <linux/fs.h>
21 #include <linux/interrupt.h>
22 #include <linux/io.h>
23 #include <linux/ioctl.h>
24 #include <linux/module.h>
25 #include <linux/of.h>
26 #include <linux/platform_device.h>
27 #include <linux/pm_runtime.h>
28 #include <linux/sched.h>
29 #include <linux/slab.h>
30 #include <linux/videodev2.h>
31 #include <linux/log2.h>
32 #include <linux/sizes.h>
33
34 #include <media/v4l2-common.h>
35 #include <media/v4l2-ctrls.h>
36 #include <media/v4l2-device.h>
37 #include <media/v4l2-event.h>
38 #include <media/v4l2-ioctl.h>
39 #include <media/v4l2-mem2mem.h>
40 #include <media/videobuf2-v4l2.h>
41 #include <media/videobuf2-dma-contig.h>
42
43 #include "vpdma.h"
44 #include "vpdma_priv.h"
45 #include "vpe_regs.h"
46 #include "sc.h"
47 #include "csc.h"
48
49 #define VPE_MODULE_NAME "vpe"
50
51 /* minimum and maximum frame sizes */
52 #define MIN_W           32
53 #define MIN_H           32
54 #define MAX_W           2048
55 #define MAX_H           1184
56
57 /* required alignments */
58 #define S_ALIGN         0       /* multiple of 1 */
59 #define H_ALIGN         1       /* multiple of 2 */
60
61 /* flags that indicate a format can be used for capture/output */
62 #define VPE_FMT_TYPE_CAPTURE    (1 << 0)
63 #define VPE_FMT_TYPE_OUTPUT     (1 << 1)
64
65 /* used as plane indices */
66 #define VPE_MAX_PLANES  2
67 #define VPE_LUMA        0
68 #define VPE_CHROMA      1
69
70 /* per m2m context info */
71 #define VPE_MAX_SRC_BUFS        3       /* need 3 src fields to de-interlace */
72
73 #define VPE_DEF_BUFS_PER_JOB    1       /* default one buffer per batch job */
74
75 /*
76  * each VPE context can need up to 3 config descriptors, 7 input descriptors,
77  * 3 output descriptors, and 10 control descriptors
78  */
79 #define VPE_DESC_LIST_SIZE      (10 * VPDMA_DTD_DESC_SIZE +     \
80                                         13 * VPDMA_CFD_CTD_DESC_SIZE)
81
82 #define vpe_dbg(vpedev, fmt, arg...)    \
83                 dev_dbg((vpedev)->v4l2_dev.dev, fmt, ##arg)
84 #define vpe_err(vpedev, fmt, arg...)    \
85                 dev_err((vpedev)->v4l2_dev.dev, fmt, ##arg)
86
87 struct vpe_us_coeffs {
88         unsigned short  anchor_fid0_c0;
89         unsigned short  anchor_fid0_c1;
90         unsigned short  anchor_fid0_c2;
91         unsigned short  anchor_fid0_c3;
92         unsigned short  interp_fid0_c0;
93         unsigned short  interp_fid0_c1;
94         unsigned short  interp_fid0_c2;
95         unsigned short  interp_fid0_c3;
96         unsigned short  anchor_fid1_c0;
97         unsigned short  anchor_fid1_c1;
98         unsigned short  anchor_fid1_c2;
99         unsigned short  anchor_fid1_c3;
100         unsigned short  interp_fid1_c0;
101         unsigned short  interp_fid1_c1;
102         unsigned short  interp_fid1_c2;
103         unsigned short  interp_fid1_c3;
104 };
105
106 /*
107  * Default upsampler coefficients
108  */
109 static const struct vpe_us_coeffs us_coeffs[] = {
110         {
111                 /* Coefficients for progressive input */
112                 0x00C8, 0x0348, 0x0018, 0x3FD8, 0x3FB8, 0x0378, 0x00E8, 0x3FE8,
113                 0x00C8, 0x0348, 0x0018, 0x3FD8, 0x3FB8, 0x0378, 0x00E8, 0x3FE8,
114         },
115         {
116                 /* Coefficients for Top Field Interlaced input */
117                 0x0051, 0x03D5, 0x3FE3, 0x3FF7, 0x3FB5, 0x02E9, 0x018F, 0x3FD3,
118                 /* Coefficients for Bottom Field Interlaced input */
119                 0x016B, 0x0247, 0x00B1, 0x3F9D, 0x3FCF, 0x03DB, 0x005D, 0x3FF9,
120         },
121 };
122
123 /*
124  * the following registers are for configuring some of the parameters of the
125  * motion and edge detection blocks inside DEI, these generally remain the same,
126  * these could be passed later via userspace if some one needs to tweak these.
127  */
128 struct vpe_dei_regs {
129         unsigned long mdt_spacial_freq_thr_reg;         /* VPE_DEI_REG2 */
130         unsigned long edi_config_reg;                   /* VPE_DEI_REG3 */
131         unsigned long edi_lut_reg0;                     /* VPE_DEI_REG4 */
132         unsigned long edi_lut_reg1;                     /* VPE_DEI_REG5 */
133         unsigned long edi_lut_reg2;                     /* VPE_DEI_REG6 */
134         unsigned long edi_lut_reg3;                     /* VPE_DEI_REG7 */
135 };
136
137 /*
138  * default expert DEI register values, unlikely to be modified.
139  */
140 static const struct vpe_dei_regs dei_regs = {
141         .mdt_spacial_freq_thr_reg = 0x020C0804u,
142         .edi_config_reg = 0x0118100Cu,
143         .edi_lut_reg0 = 0x08040200u,
144         .edi_lut_reg1 = 0x1010100Cu,
145         .edi_lut_reg2 = 0x10101010u,
146         .edi_lut_reg3 = 0x10101010u,
147 };
148
149 /*
150  * The port_data structure contains per-port data.
151  */
152 struct vpe_port_data {
153         enum vpdma_channel channel;     /* VPDMA channel */
154         u8      vb_index;               /* input frame f, f-1, f-2 index */
155         u8      vb_part;                /* plane index for co-panar formats */
156 };
157
158 /*
159  * Define indices into the port_data tables
160  */
161 #define VPE_PORT_LUMA1_IN       0
162 #define VPE_PORT_CHROMA1_IN     1
163 #define VPE_PORT_LUMA2_IN       2
164 #define VPE_PORT_CHROMA2_IN     3
165 #define VPE_PORT_LUMA3_IN       4
166 #define VPE_PORT_CHROMA3_IN     5
167 #define VPE_PORT_MV_IN          6
168 #define VPE_PORT_MV_OUT         7
169 #define VPE_PORT_LUMA_OUT       8
170 #define VPE_PORT_CHROMA_OUT     9
171 #define VPE_PORT_RGB_OUT        10
172
173 static const struct vpe_port_data port_data[11] = {
174         [VPE_PORT_LUMA1_IN] = {
175                 .channel        = VPE_CHAN_LUMA1_IN,
176                 .vb_index       = 0,
177                 .vb_part        = VPE_LUMA,
178         },
179         [VPE_PORT_CHROMA1_IN] = {
180                 .channel        = VPE_CHAN_CHROMA1_IN,
181                 .vb_index       = 0,
182                 .vb_part        = VPE_CHROMA,
183         },
184         [VPE_PORT_LUMA2_IN] = {
185                 .channel        = VPE_CHAN_LUMA2_IN,
186                 .vb_index       = 1,
187                 .vb_part        = VPE_LUMA,
188         },
189         [VPE_PORT_CHROMA2_IN] = {
190                 .channel        = VPE_CHAN_CHROMA2_IN,
191                 .vb_index       = 1,
192                 .vb_part        = VPE_CHROMA,
193         },
194         [VPE_PORT_LUMA3_IN] = {
195                 .channel        = VPE_CHAN_LUMA3_IN,
196                 .vb_index       = 2,
197                 .vb_part        = VPE_LUMA,
198         },
199         [VPE_PORT_CHROMA3_IN] = {
200                 .channel        = VPE_CHAN_CHROMA3_IN,
201                 .vb_index       = 2,
202                 .vb_part        = VPE_CHROMA,
203         },
204         [VPE_PORT_MV_IN] = {
205                 .channel        = VPE_CHAN_MV_IN,
206         },
207         [VPE_PORT_MV_OUT] = {
208                 .channel        = VPE_CHAN_MV_OUT,
209         },
210         [VPE_PORT_LUMA_OUT] = {
211                 .channel        = VPE_CHAN_LUMA_OUT,
212                 .vb_part        = VPE_LUMA,
213         },
214         [VPE_PORT_CHROMA_OUT] = {
215                 .channel        = VPE_CHAN_CHROMA_OUT,
216                 .vb_part        = VPE_CHROMA,
217         },
218         [VPE_PORT_RGB_OUT] = {
219                 .channel        = VPE_CHAN_RGB_OUT,
220                 .vb_part        = VPE_LUMA,
221         },
222 };
223
224
225 /* driver info for each of the supported video formats */
226 struct vpe_fmt {
227         u32     fourcc;                 /* standard format identifier */
228         u8      types;                  /* CAPTURE and/or OUTPUT */
229         u8      coplanar;               /* set for unpacked Luma and Chroma */
230         /* vpdma format info for each plane */
231         struct vpdma_data_format const *vpdma_fmt[VPE_MAX_PLANES];
232 };
233
234 static struct vpe_fmt vpe_formats[] = {
235         {
236                 .fourcc         = V4L2_PIX_FMT_NV16,
237                 .types          = VPE_FMT_TYPE_CAPTURE | VPE_FMT_TYPE_OUTPUT,
238                 .coplanar       = 1,
239                 .vpdma_fmt      = { &vpdma_yuv_fmts[VPDMA_DATA_FMT_Y444],
240                                     &vpdma_yuv_fmts[VPDMA_DATA_FMT_C444],
241                                   },
242         },
243         {
244                 .fourcc         = V4L2_PIX_FMT_NV12,
245                 .types          = VPE_FMT_TYPE_CAPTURE | VPE_FMT_TYPE_OUTPUT,
246                 .coplanar       = 1,
247                 .vpdma_fmt      = { &vpdma_yuv_fmts[VPDMA_DATA_FMT_Y420],
248                                     &vpdma_yuv_fmts[VPDMA_DATA_FMT_C420],
249                                   },
250         },
251         {
252                 .fourcc         = V4L2_PIX_FMT_YUYV,
253                 .types          = VPE_FMT_TYPE_CAPTURE | VPE_FMT_TYPE_OUTPUT,
254                 .coplanar       = 0,
255                 .vpdma_fmt      = { &vpdma_yuv_fmts[VPDMA_DATA_FMT_YCB422],
256                                   },
257         },
258         {
259                 .fourcc         = V4L2_PIX_FMT_UYVY,
260                 .types          = VPE_FMT_TYPE_CAPTURE | VPE_FMT_TYPE_OUTPUT,
261                 .coplanar       = 0,
262                 .vpdma_fmt      = { &vpdma_yuv_fmts[VPDMA_DATA_FMT_CBY422],
263                                   },
264         },
265         {
266                 .fourcc         = V4L2_PIX_FMT_RGB24,
267                 .types          = VPE_FMT_TYPE_CAPTURE,
268                 .coplanar       = 0,
269                 .vpdma_fmt      = { &vpdma_rgb_fmts[VPDMA_DATA_FMT_RGB24],
270                                   },
271         },
272         {
273                 .fourcc         = V4L2_PIX_FMT_RGB32,
274                 .types          = VPE_FMT_TYPE_CAPTURE,
275                 .coplanar       = 0,
276                 .vpdma_fmt      = { &vpdma_rgb_fmts[VPDMA_DATA_FMT_ARGB32],
277                                   },
278         },
279         {
280                 .fourcc         = V4L2_PIX_FMT_BGR24,
281                 .types          = VPE_FMT_TYPE_CAPTURE,
282                 .coplanar       = 0,
283                 .vpdma_fmt      = { &vpdma_rgb_fmts[VPDMA_DATA_FMT_BGR24],
284                                   },
285         },
286         {
287                 .fourcc         = V4L2_PIX_FMT_BGR32,
288                 .types          = VPE_FMT_TYPE_CAPTURE,
289                 .coplanar       = 0,
290                 .vpdma_fmt      = { &vpdma_rgb_fmts[VPDMA_DATA_FMT_ABGR32],
291                                   },
292         },
293         {
294                 .fourcc         = V4L2_PIX_FMT_RGB565,
295                 .types          = VPE_FMT_TYPE_CAPTURE,
296                 .coplanar       = 0,
297                 .vpdma_fmt      = { &vpdma_rgb_fmts[VPDMA_DATA_FMT_RGB565],
298                                   },
299         },
300         {
301                 .fourcc         = V4L2_PIX_FMT_RGB555,
302                 .types          = VPE_FMT_TYPE_CAPTURE,
303                 .coplanar       = 0,
304                 .vpdma_fmt      = { &vpdma_rgb_fmts[VPDMA_DATA_FMT_RGBA16_5551],
305                                   },
306         },
307 };
308
309 /*
310  * per-queue, driver-specific private data.
311  * there is one source queue and one destination queue for each m2m context.
312  */
313 struct vpe_q_data {
314         unsigned int            width;                          /* frame width */
315         unsigned int            height;                         /* frame height */
316         unsigned int            nplanes;                        /* Current number of planes */
317         unsigned int            bytesperline[VPE_MAX_PLANES];   /* bytes per line in memory */
318         enum v4l2_colorspace    colorspace;
319         enum v4l2_field         field;                          /* supported field value */
320         unsigned int            flags;
321         unsigned int            sizeimage[VPE_MAX_PLANES];      /* image size in memory */
322         struct v4l2_rect        c_rect;                         /* crop/compose rectangle */
323         struct vpe_fmt          *fmt;                           /* format info */
324 };
325
326 /* vpe_q_data flag bits */
327 #define Q_DATA_FRAME_1D                 BIT(0)
328 #define Q_DATA_MODE_TILED               BIT(1)
329 #define Q_DATA_INTERLACED_ALTERNATE     BIT(2)
330 #define Q_DATA_INTERLACED_SEQ_TB        BIT(3)
331
332 #define Q_IS_INTERLACED         (Q_DATA_INTERLACED_ALTERNATE | \
333                                 Q_DATA_INTERLACED_SEQ_TB)
334
335 enum {
336         Q_DATA_SRC = 0,
337         Q_DATA_DST = 1,
338 };
339
340 /* find our format description corresponding to the passed v4l2_format */
341 static struct vpe_fmt *find_format(struct v4l2_format *f)
342 {
343         struct vpe_fmt *fmt;
344         unsigned int k;
345
346         for (k = 0; k < ARRAY_SIZE(vpe_formats); k++) {
347                 fmt = &vpe_formats[k];
348                 if (fmt->fourcc == f->fmt.pix.pixelformat)
349                         return fmt;
350         }
351
352         return NULL;
353 }
354
355 /*
356  * there is one vpe_dev structure in the driver, it is shared by
357  * all instances.
358  */
359 struct vpe_dev {
360         struct v4l2_device      v4l2_dev;
361         struct video_device     vfd;
362         struct v4l2_m2m_dev     *m2m_dev;
363
364         atomic_t                num_instances;  /* count of driver instances */
365         dma_addr_t              loaded_mmrs;    /* shadow mmrs in device */
366         struct mutex            dev_mutex;
367         spinlock_t              lock;
368
369         int                     irq;
370         void __iomem            *base;
371         struct resource         *res;
372
373         struct vpdma_data       vpdma_data;
374         struct vpdma_data       *vpdma;         /* vpdma data handle */
375         struct sc_data          *sc;            /* scaler data handle */
376         struct csc_data         *csc;           /* csc data handle */
377 };
378
379 /*
380  * There is one vpe_ctx structure for each m2m context.
381  */
382 struct vpe_ctx {
383         struct v4l2_fh          fh;
384         struct vpe_dev          *dev;
385         struct v4l2_ctrl_handler hdl;
386
387         unsigned int            field;                  /* current field */
388         unsigned int            sequence;               /* current frame/field seq */
389         unsigned int            aborting;               /* abort after next irq */
390
391         unsigned int            bufs_per_job;           /* input buffers per batch */
392         unsigned int            bufs_completed;         /* bufs done in this batch */
393
394         struct vpe_q_data       q_data[2];              /* src & dst queue data */
395         struct vb2_v4l2_buffer  *src_vbs[VPE_MAX_SRC_BUFS];
396         struct vb2_v4l2_buffer  *dst_vb;
397
398         dma_addr_t              mv_buf_dma[2];          /* dma addrs of motion vector in/out bufs */
399         void                    *mv_buf[2];             /* virtual addrs of motion vector bufs */
400         size_t                  mv_buf_size;            /* current motion vector buffer size */
401         struct vpdma_buf        mmr_adb;                /* shadow reg addr/data block */
402         struct vpdma_buf        sc_coeff_h;             /* h coeff buffer */
403         struct vpdma_buf        sc_coeff_v;             /* v coeff buffer */
404         struct vpdma_desc_list  desc_list;              /* DMA descriptor list */
405
406         bool                    deinterlacing;          /* using de-interlacer */
407         bool                    load_mmrs;              /* have new shadow reg values */
408
409         unsigned int            src_mv_buf_selector;
410 };
411
412
413 /*
414  * M2M devices get 2 queues.
415  * Return the queue given the type.
416  */
417 static struct vpe_q_data *get_q_data(struct vpe_ctx *ctx,
418                                      enum v4l2_buf_type type)
419 {
420         switch (type) {
421         case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
422         case V4L2_BUF_TYPE_VIDEO_OUTPUT:
423                 return &ctx->q_data[Q_DATA_SRC];
424         case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
425         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
426                 return &ctx->q_data[Q_DATA_DST];
427         default:
428                 return NULL;
429         }
430         return NULL;
431 }
432
433 static u32 read_reg(struct vpe_dev *dev, int offset)
434 {
435         return ioread32(dev->base + offset);
436 }
437
438 static void write_reg(struct vpe_dev *dev, int offset, u32 value)
439 {
440         iowrite32(value, dev->base + offset);
441 }
442
443 /* register field read/write helpers */
444 static int get_field(u32 value, u32 mask, int shift)
445 {
446         return (value & (mask << shift)) >> shift;
447 }
448
449 static int read_field_reg(struct vpe_dev *dev, int offset, u32 mask, int shift)
450 {
451         return get_field(read_reg(dev, offset), mask, shift);
452 }
453
454 static void write_field(u32 *valp, u32 field, u32 mask, int shift)
455 {
456         u32 val = *valp;
457
458         val &= ~(mask << shift);
459         val |= (field & mask) << shift;
460         *valp = val;
461 }
462
463 static void write_field_reg(struct vpe_dev *dev, int offset, u32 field,
464                 u32 mask, int shift)
465 {
466         u32 val = read_reg(dev, offset);
467
468         write_field(&val, field, mask, shift);
469
470         write_reg(dev, offset, val);
471 }
472
473 /*
474  * DMA address/data block for the shadow registers
475  */
476 struct vpe_mmr_adb {
477         struct vpdma_adb_hdr    out_fmt_hdr;
478         u32                     out_fmt_reg[1];
479         u32                     out_fmt_pad[3];
480         struct vpdma_adb_hdr    us1_hdr;
481         u32                     us1_regs[8];
482         struct vpdma_adb_hdr    us2_hdr;
483         u32                     us2_regs[8];
484         struct vpdma_adb_hdr    us3_hdr;
485         u32                     us3_regs[8];
486         struct vpdma_adb_hdr    dei_hdr;
487         u32                     dei_regs[8];
488         struct vpdma_adb_hdr    sc_hdr0;
489         u32                     sc_regs0[7];
490         u32                     sc_pad0[1];
491         struct vpdma_adb_hdr    sc_hdr8;
492         u32                     sc_regs8[6];
493         u32                     sc_pad8[2];
494         struct vpdma_adb_hdr    sc_hdr17;
495         u32                     sc_regs17[9];
496         u32                     sc_pad17[3];
497         struct vpdma_adb_hdr    csc_hdr;
498         u32                     csc_regs[6];
499         u32                     csc_pad[2];
500 };
501
502 #define GET_OFFSET_TOP(ctx, obj, reg)   \
503         ((obj)->res->start - ctx->dev->res->start + reg)
504
505 #define VPE_SET_MMR_ADB_HDR(ctx, hdr, regs, offset_a)   \
506         VPDMA_SET_MMR_ADB_HDR(ctx->mmr_adb, vpe_mmr_adb, hdr, regs, offset_a)
507 /*
508  * Set the headers for all of the address/data block structures.
509  */
510 static void init_adb_hdrs(struct vpe_ctx *ctx)
511 {
512         VPE_SET_MMR_ADB_HDR(ctx, out_fmt_hdr, out_fmt_reg, VPE_CLK_FORMAT_SELECT);
513         VPE_SET_MMR_ADB_HDR(ctx, us1_hdr, us1_regs, VPE_US1_R0);
514         VPE_SET_MMR_ADB_HDR(ctx, us2_hdr, us2_regs, VPE_US2_R0);
515         VPE_SET_MMR_ADB_HDR(ctx, us3_hdr, us3_regs, VPE_US3_R0);
516         VPE_SET_MMR_ADB_HDR(ctx, dei_hdr, dei_regs, VPE_DEI_FRAME_SIZE);
517         VPE_SET_MMR_ADB_HDR(ctx, sc_hdr0, sc_regs0,
518                 GET_OFFSET_TOP(ctx, ctx->dev->sc, CFG_SC0));
519         VPE_SET_MMR_ADB_HDR(ctx, sc_hdr8, sc_regs8,
520                 GET_OFFSET_TOP(ctx, ctx->dev->sc, CFG_SC8));
521         VPE_SET_MMR_ADB_HDR(ctx, sc_hdr17, sc_regs17,
522                 GET_OFFSET_TOP(ctx, ctx->dev->sc, CFG_SC17));
523         VPE_SET_MMR_ADB_HDR(ctx, csc_hdr, csc_regs,
524                 GET_OFFSET_TOP(ctx, ctx->dev->csc, CSC_CSC00));
525 };
526
527 /*
528  * Allocate or re-allocate the motion vector DMA buffers
529  * There are two buffers, one for input and one for output.
530  * However, the roles are reversed after each field is processed.
531  * In other words, after each field is processed, the previous
532  * output (dst) MV buffer becomes the new input (src) MV buffer.
533  */
534 static int realloc_mv_buffers(struct vpe_ctx *ctx, size_t size)
535 {
536         struct device *dev = ctx->dev->v4l2_dev.dev;
537
538         if (ctx->mv_buf_size == size)
539                 return 0;
540
541         if (ctx->mv_buf[0])
542                 dma_free_coherent(dev, ctx->mv_buf_size, ctx->mv_buf[0],
543                         ctx->mv_buf_dma[0]);
544
545         if (ctx->mv_buf[1])
546                 dma_free_coherent(dev, ctx->mv_buf_size, ctx->mv_buf[1],
547                         ctx->mv_buf_dma[1]);
548
549         if (size == 0)
550                 return 0;
551
552         ctx->mv_buf[0] = dma_alloc_coherent(dev, size, &ctx->mv_buf_dma[0],
553                                 GFP_KERNEL);
554         if (!ctx->mv_buf[0]) {
555                 vpe_err(ctx->dev, "failed to allocate motion vector buffer\n");
556                 return -ENOMEM;
557         }
558
559         ctx->mv_buf[1] = dma_alloc_coherent(dev, size, &ctx->mv_buf_dma[1],
560                                 GFP_KERNEL);
561         if (!ctx->mv_buf[1]) {
562                 vpe_err(ctx->dev, "failed to allocate motion vector buffer\n");
563                 dma_free_coherent(dev, size, ctx->mv_buf[0],
564                         ctx->mv_buf_dma[0]);
565
566                 return -ENOMEM;
567         }
568
569         ctx->mv_buf_size = size;
570         ctx->src_mv_buf_selector = 0;
571
572         return 0;
573 }
574
575 static void free_mv_buffers(struct vpe_ctx *ctx)
576 {
577         realloc_mv_buffers(ctx, 0);
578 }
579
580 /*
581  * While de-interlacing, we keep the two most recent input buffers
582  * around.  This function frees those two buffers when we have
583  * finished processing the current stream.
584  */
585 static void free_vbs(struct vpe_ctx *ctx)
586 {
587         struct vpe_dev *dev = ctx->dev;
588         unsigned long flags;
589
590         if (ctx->src_vbs[2] == NULL)
591                 return;
592
593         spin_lock_irqsave(&dev->lock, flags);
594         if (ctx->src_vbs[2]) {
595                 v4l2_m2m_buf_done(ctx->src_vbs[2], VB2_BUF_STATE_DONE);
596                 if (ctx->src_vbs[1] && (ctx->src_vbs[1] != ctx->src_vbs[2]))
597                         v4l2_m2m_buf_done(ctx->src_vbs[1], VB2_BUF_STATE_DONE);
598                 ctx->src_vbs[2] = NULL;
599                 ctx->src_vbs[1] = NULL;
600         }
601         spin_unlock_irqrestore(&dev->lock, flags);
602 }
603
604 /*
605  * Enable or disable the VPE clocks
606  */
607 static void vpe_set_clock_enable(struct vpe_dev *dev, bool on)
608 {
609         u32 val = 0;
610
611         if (on)
612                 val = VPE_DATA_PATH_CLK_ENABLE | VPE_VPEDMA_CLK_ENABLE;
613         write_reg(dev, VPE_CLK_ENABLE, val);
614 }
615
616 static void vpe_top_reset(struct vpe_dev *dev)
617 {
618
619         write_field_reg(dev, VPE_CLK_RESET, 1, VPE_DATA_PATH_CLK_RESET_MASK,
620                 VPE_DATA_PATH_CLK_RESET_SHIFT);
621
622         usleep_range(100, 150);
623
624         write_field_reg(dev, VPE_CLK_RESET, 0, VPE_DATA_PATH_CLK_RESET_MASK,
625                 VPE_DATA_PATH_CLK_RESET_SHIFT);
626 }
627
628 static void vpe_top_vpdma_reset(struct vpe_dev *dev)
629 {
630         write_field_reg(dev, VPE_CLK_RESET, 1, VPE_VPDMA_CLK_RESET_MASK,
631                 VPE_VPDMA_CLK_RESET_SHIFT);
632
633         usleep_range(100, 150);
634
635         write_field_reg(dev, VPE_CLK_RESET, 0, VPE_VPDMA_CLK_RESET_MASK,
636                 VPE_VPDMA_CLK_RESET_SHIFT);
637 }
638
639 /*
640  * Load the correct of upsampler coefficients into the shadow MMRs
641  */
642 static void set_us_coefficients(struct vpe_ctx *ctx)
643 {
644         struct vpe_mmr_adb *mmr_adb = ctx->mmr_adb.addr;
645         struct vpe_q_data *s_q_data = &ctx->q_data[Q_DATA_SRC];
646         u32 *us1_reg = &mmr_adb->us1_regs[0];
647         u32 *us2_reg = &mmr_adb->us2_regs[0];
648         u32 *us3_reg = &mmr_adb->us3_regs[0];
649         const unsigned short *cp, *end_cp;
650
651         cp = &us_coeffs[0].anchor_fid0_c0;
652
653         if (s_q_data->flags & Q_IS_INTERLACED)          /* interlaced */
654                 cp += sizeof(us_coeffs[0]) / sizeof(*cp);
655
656         end_cp = cp + sizeof(us_coeffs[0]) / sizeof(*cp);
657
658         while (cp < end_cp) {
659                 write_field(us1_reg, *cp++, VPE_US_C0_MASK, VPE_US_C0_SHIFT);
660                 write_field(us1_reg, *cp++, VPE_US_C1_MASK, VPE_US_C1_SHIFT);
661                 *us2_reg++ = *us1_reg;
662                 *us3_reg++ = *us1_reg++;
663         }
664         ctx->load_mmrs = true;
665 }
666
667 /*
668  * Set the upsampler config mode and the VPDMA line mode in the shadow MMRs.
669  */
670 static void set_cfg_modes(struct vpe_ctx *ctx)
671 {
672         struct vpe_fmt *fmt = ctx->q_data[Q_DATA_SRC].fmt;
673         struct vpe_mmr_adb *mmr_adb = ctx->mmr_adb.addr;
674         u32 *us1_reg0 = &mmr_adb->us1_regs[0];
675         u32 *us2_reg0 = &mmr_adb->us2_regs[0];
676         u32 *us3_reg0 = &mmr_adb->us3_regs[0];
677         int cfg_mode = 1;
678
679         /*
680          * Cfg Mode 0: YUV420 source, enable upsampler, DEI is de-interlacing.
681          * Cfg Mode 1: YUV422 source, disable upsampler, DEI is de-interlacing.
682          */
683
684         if (fmt->fourcc == V4L2_PIX_FMT_NV12)
685                 cfg_mode = 0;
686
687         write_field(us1_reg0, cfg_mode, VPE_US_MODE_MASK, VPE_US_MODE_SHIFT);
688         write_field(us2_reg0, cfg_mode, VPE_US_MODE_MASK, VPE_US_MODE_SHIFT);
689         write_field(us3_reg0, cfg_mode, VPE_US_MODE_MASK, VPE_US_MODE_SHIFT);
690
691         ctx->load_mmrs = true;
692 }
693
694 static void set_line_modes(struct vpe_ctx *ctx)
695 {
696         struct vpe_fmt *fmt = ctx->q_data[Q_DATA_SRC].fmt;
697         int line_mode = 1;
698
699         if (fmt->fourcc == V4L2_PIX_FMT_NV12)
700                 line_mode = 0;          /* double lines to line buffer */
701
702         /* regs for now */
703         vpdma_set_line_mode(ctx->dev->vpdma, line_mode, VPE_CHAN_CHROMA1_IN);
704         vpdma_set_line_mode(ctx->dev->vpdma, line_mode, VPE_CHAN_CHROMA2_IN);
705         vpdma_set_line_mode(ctx->dev->vpdma, line_mode, VPE_CHAN_CHROMA3_IN);
706
707         /* frame start for input luma */
708         vpdma_set_frame_start_event(ctx->dev->vpdma, VPDMA_FSEVENT_CHANNEL_ACTIVE,
709                 VPE_CHAN_LUMA1_IN);
710         vpdma_set_frame_start_event(ctx->dev->vpdma, VPDMA_FSEVENT_CHANNEL_ACTIVE,
711                 VPE_CHAN_LUMA2_IN);
712         vpdma_set_frame_start_event(ctx->dev->vpdma, VPDMA_FSEVENT_CHANNEL_ACTIVE,
713                 VPE_CHAN_LUMA3_IN);
714
715         /* frame start for input chroma */
716         vpdma_set_frame_start_event(ctx->dev->vpdma, VPDMA_FSEVENT_CHANNEL_ACTIVE,
717                 VPE_CHAN_CHROMA1_IN);
718         vpdma_set_frame_start_event(ctx->dev->vpdma, VPDMA_FSEVENT_CHANNEL_ACTIVE,
719                 VPE_CHAN_CHROMA2_IN);
720         vpdma_set_frame_start_event(ctx->dev->vpdma, VPDMA_FSEVENT_CHANNEL_ACTIVE,
721                 VPE_CHAN_CHROMA3_IN);
722
723         /* frame start for MV in client */
724         vpdma_set_frame_start_event(ctx->dev->vpdma, VPDMA_FSEVENT_CHANNEL_ACTIVE,
725                 VPE_CHAN_MV_IN);
726 }
727
728 /*
729  * Set the shadow registers that are modified when the source
730  * format changes.
731  */
732 static void set_src_registers(struct vpe_ctx *ctx)
733 {
734         set_us_coefficients(ctx);
735 }
736
737 /*
738  * Set the shadow registers that are modified when the destination
739  * format changes.
740  */
741 static void set_dst_registers(struct vpe_ctx *ctx)
742 {
743         struct vpe_mmr_adb *mmr_adb = ctx->mmr_adb.addr;
744         enum v4l2_colorspace clrspc = ctx->q_data[Q_DATA_DST].colorspace;
745         struct vpe_fmt *fmt = ctx->q_data[Q_DATA_DST].fmt;
746         u32 val = 0;
747
748         if (clrspc == V4L2_COLORSPACE_SRGB) {
749                 val |= VPE_RGB_OUT_SELECT;
750                 vpdma_set_bg_color(ctx->dev->vpdma,
751                         (struct vpdma_data_format *)fmt->vpdma_fmt[0], 0xff);
752         } else if (fmt->fourcc == V4L2_PIX_FMT_NV16)
753                 val |= VPE_COLOR_SEPARATE_422;
754
755         /*
756          * the source of CHR_DS and CSC is always the scaler, irrespective of
757          * whether it's used or not
758          */
759         val |= VPE_DS_SRC_DEI_SCALER | VPE_CSC_SRC_DEI_SCALER;
760
761         if (fmt->fourcc != V4L2_PIX_FMT_NV12)
762                 val |= VPE_DS_BYPASS;
763
764         mmr_adb->out_fmt_reg[0] = val;
765
766         ctx->load_mmrs = true;
767 }
768
769 /*
770  * Set the de-interlacer shadow register values
771  */
772 static void set_dei_regs(struct vpe_ctx *ctx)
773 {
774         struct vpe_mmr_adb *mmr_adb = ctx->mmr_adb.addr;
775         struct vpe_q_data *s_q_data = &ctx->q_data[Q_DATA_SRC];
776         unsigned int src_h = s_q_data->c_rect.height;
777         unsigned int src_w = s_q_data->c_rect.width;
778         u32 *dei_mmr0 = &mmr_adb->dei_regs[0];
779         bool deinterlace = true;
780         u32 val = 0;
781
782         /*
783          * according to TRM, we should set DEI in progressive bypass mode when
784          * the input content is progressive, however, DEI is bypassed correctly
785          * for both progressive and interlace content in interlace bypass mode.
786          * It has been recommended not to use progressive bypass mode.
787          */
788         if (!(s_q_data->flags & Q_IS_INTERLACED) || !ctx->deinterlacing) {
789                 deinterlace = false;
790                 val = VPE_DEI_INTERLACE_BYPASS;
791         }
792
793         src_h = deinterlace ? src_h * 2 : src_h;
794
795         val |= (src_h << VPE_DEI_HEIGHT_SHIFT) |
796                 (src_w << VPE_DEI_WIDTH_SHIFT) |
797                 VPE_DEI_FIELD_FLUSH;
798
799         *dei_mmr0 = val;
800
801         ctx->load_mmrs = true;
802 }
803
804 static void set_dei_shadow_registers(struct vpe_ctx *ctx)
805 {
806         struct vpe_mmr_adb *mmr_adb = ctx->mmr_adb.addr;
807         u32 *dei_mmr = &mmr_adb->dei_regs[0];
808         const struct vpe_dei_regs *cur = &dei_regs;
809
810         dei_mmr[2]  = cur->mdt_spacial_freq_thr_reg;
811         dei_mmr[3]  = cur->edi_config_reg;
812         dei_mmr[4]  = cur->edi_lut_reg0;
813         dei_mmr[5]  = cur->edi_lut_reg1;
814         dei_mmr[6]  = cur->edi_lut_reg2;
815         dei_mmr[7]  = cur->edi_lut_reg3;
816
817         ctx->load_mmrs = true;
818 }
819
820 static void config_edi_input_mode(struct vpe_ctx *ctx, int mode)
821 {
822         struct vpe_mmr_adb *mmr_adb = ctx->mmr_adb.addr;
823         u32 *edi_config_reg = &mmr_adb->dei_regs[3];
824
825         if (mode & 0x2)
826                 write_field(edi_config_reg, 1, 1, 2);   /* EDI_ENABLE_3D */
827
828         if (mode & 0x3)
829                 write_field(edi_config_reg, 1, 1, 3);   /* EDI_CHROMA_3D  */
830
831         write_field(edi_config_reg, mode, VPE_EDI_INP_MODE_MASK,
832                 VPE_EDI_INP_MODE_SHIFT);
833
834         ctx->load_mmrs = true;
835 }
836
837 /*
838  * Set the shadow registers whose values are modified when either the
839  * source or destination format is changed.
840  */
841 static int set_srcdst_params(struct vpe_ctx *ctx)
842 {
843         struct vpe_q_data *s_q_data =  &ctx->q_data[Q_DATA_SRC];
844         struct vpe_q_data *d_q_data =  &ctx->q_data[Q_DATA_DST];
845         struct vpe_mmr_adb *mmr_adb = ctx->mmr_adb.addr;
846         unsigned int src_w = s_q_data->c_rect.width;
847         unsigned int src_h = s_q_data->c_rect.height;
848         unsigned int dst_w = d_q_data->c_rect.width;
849         unsigned int dst_h = d_q_data->c_rect.height;
850         size_t mv_buf_size;
851         int ret;
852
853         ctx->sequence = 0;
854         ctx->field = V4L2_FIELD_TOP;
855
856         if ((s_q_data->flags & Q_IS_INTERLACED) &&
857                         !(d_q_data->flags & Q_IS_INTERLACED)) {
858                 int bytes_per_line;
859                 const struct vpdma_data_format *mv =
860                         &vpdma_misc_fmts[VPDMA_DATA_FMT_MV];
861
862                 /*
863                  * we make sure that the source image has a 16 byte aligned
864                  * stride, we need to do the same for the motion vector buffer
865                  * by aligning it's stride to the next 16 byte boundary. this
866                  * extra space will not be used by the de-interlacer, but will
867                  * ensure that vpdma operates correctly
868                  */
869                 bytes_per_line = ALIGN((s_q_data->width * mv->depth) >> 3,
870                                         VPDMA_STRIDE_ALIGN);
871                 mv_buf_size = bytes_per_line * s_q_data->height;
872
873                 ctx->deinterlacing = true;
874                 src_h <<= 1;
875         } else {
876                 ctx->deinterlacing = false;
877                 mv_buf_size = 0;
878         }
879
880         free_vbs(ctx);
881         ctx->src_vbs[2] = ctx->src_vbs[1] = ctx->src_vbs[0] = NULL;
882
883         ret = realloc_mv_buffers(ctx, mv_buf_size);
884         if (ret)
885                 return ret;
886
887         set_cfg_modes(ctx);
888         set_dei_regs(ctx);
889
890         csc_set_coeff(ctx->dev->csc, &mmr_adb->csc_regs[0],
891                 s_q_data->colorspace, d_q_data->colorspace);
892
893         sc_set_hs_coeffs(ctx->dev->sc, ctx->sc_coeff_h.addr, src_w, dst_w);
894         sc_set_vs_coeffs(ctx->dev->sc, ctx->sc_coeff_v.addr, src_h, dst_h);
895
896         sc_config_scaler(ctx->dev->sc, &mmr_adb->sc_regs0[0],
897                 &mmr_adb->sc_regs8[0], &mmr_adb->sc_regs17[0],
898                 src_w, src_h, dst_w, dst_h);
899
900         return 0;
901 }
902
903 /*
904  * mem2mem callbacks
905  */
906
907 /*
908  * job_ready() - check whether an instance is ready to be scheduled to run
909  */
910 static int job_ready(void *priv)
911 {
912         struct vpe_ctx *ctx = priv;
913
914         /*
915          * This check is needed as this might be called directly from driver
916          * When called by m2m framework, this will always satisfy, but when
917          * called from vpe_irq, this might fail. (src stream with zero buffers)
918          */
919         if (v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx) <= 0 ||
920                 v4l2_m2m_num_dst_bufs_ready(ctx->fh.m2m_ctx) <= 0)
921                 return 0;
922
923         return 1;
924 }
925
926 static void job_abort(void *priv)
927 {
928         struct vpe_ctx *ctx = priv;
929
930         /* Will cancel the transaction in the next interrupt handler */
931         ctx->aborting = 1;
932 }
933
934 static void vpe_dump_regs(struct vpe_dev *dev)
935 {
936 #define DUMPREG(r) vpe_dbg(dev, "%-35s %08x\n", #r, read_reg(dev, VPE_##r))
937
938         vpe_dbg(dev, "VPE Registers:\n");
939
940         DUMPREG(PID);
941         DUMPREG(SYSCONFIG);
942         DUMPREG(INT0_STATUS0_RAW);
943         DUMPREG(INT0_STATUS0);
944         DUMPREG(INT0_ENABLE0);
945         DUMPREG(INT0_STATUS1_RAW);
946         DUMPREG(INT0_STATUS1);
947         DUMPREG(INT0_ENABLE1);
948         DUMPREG(CLK_ENABLE);
949         DUMPREG(CLK_RESET);
950         DUMPREG(CLK_FORMAT_SELECT);
951         DUMPREG(CLK_RANGE_MAP);
952         DUMPREG(US1_R0);
953         DUMPREG(US1_R1);
954         DUMPREG(US1_R2);
955         DUMPREG(US1_R3);
956         DUMPREG(US1_R4);
957         DUMPREG(US1_R5);
958         DUMPREG(US1_R6);
959         DUMPREG(US1_R7);
960         DUMPREG(US2_R0);
961         DUMPREG(US2_R1);
962         DUMPREG(US2_R2);
963         DUMPREG(US2_R3);
964         DUMPREG(US2_R4);
965         DUMPREG(US2_R5);
966         DUMPREG(US2_R6);
967         DUMPREG(US2_R7);
968         DUMPREG(US3_R0);
969         DUMPREG(US3_R1);
970         DUMPREG(US3_R2);
971         DUMPREG(US3_R3);
972         DUMPREG(US3_R4);
973         DUMPREG(US3_R5);
974         DUMPREG(US3_R6);
975         DUMPREG(US3_R7);
976         DUMPREG(DEI_FRAME_SIZE);
977         DUMPREG(MDT_BYPASS);
978         DUMPREG(MDT_SF_THRESHOLD);
979         DUMPREG(EDI_CONFIG);
980         DUMPREG(DEI_EDI_LUT_R0);
981         DUMPREG(DEI_EDI_LUT_R1);
982         DUMPREG(DEI_EDI_LUT_R2);
983         DUMPREG(DEI_EDI_LUT_R3);
984         DUMPREG(DEI_FMD_WINDOW_R0);
985         DUMPREG(DEI_FMD_WINDOW_R1);
986         DUMPREG(DEI_FMD_CONTROL_R0);
987         DUMPREG(DEI_FMD_CONTROL_R1);
988         DUMPREG(DEI_FMD_STATUS_R0);
989         DUMPREG(DEI_FMD_STATUS_R1);
990         DUMPREG(DEI_FMD_STATUS_R2);
991 #undef DUMPREG
992
993         sc_dump_regs(dev->sc);
994         csc_dump_regs(dev->csc);
995 }
996
997 static void add_out_dtd(struct vpe_ctx *ctx, int port)
998 {
999         struct vpe_q_data *q_data = &ctx->q_data[Q_DATA_DST];
1000         const struct vpe_port_data *p_data = &port_data[port];
1001         struct vb2_buffer *vb = &ctx->dst_vb->vb2_buf;
1002         struct vpe_fmt *fmt = q_data->fmt;
1003         const struct vpdma_data_format *vpdma_fmt;
1004         int mv_buf_selector = !ctx->src_mv_buf_selector;
1005         dma_addr_t dma_addr;
1006         u32 flags = 0;
1007         u32 offset = 0;
1008         u32 stride;
1009
1010         if (port == VPE_PORT_MV_OUT) {
1011                 vpdma_fmt = &vpdma_misc_fmts[VPDMA_DATA_FMT_MV];
1012                 dma_addr = ctx->mv_buf_dma[mv_buf_selector];
1013                 q_data = &ctx->q_data[Q_DATA_SRC];
1014                 stride = ALIGN((q_data->width * vpdma_fmt->depth) >> 3,
1015                                VPDMA_STRIDE_ALIGN);
1016         } else {
1017                 /* to incorporate interleaved formats */
1018                 int plane = fmt->coplanar ? p_data->vb_part : 0;
1019
1020                 vpdma_fmt = fmt->vpdma_fmt[plane];
1021                 /*
1022                  * If we are using a single plane buffer and
1023                  * we need to set a separate vpdma chroma channel.
1024                  */
1025                 if (q_data->nplanes == 1 && plane) {
1026                         dma_addr = vb2_dma_contig_plane_dma_addr(vb, 0);
1027                         /* Compute required offset */
1028                         offset = q_data->bytesperline[0] * q_data->height;
1029                 } else {
1030                         dma_addr = vb2_dma_contig_plane_dma_addr(vb, plane);
1031                         /* Use address as is, no offset */
1032                         offset = 0;
1033                 }
1034                 if (!dma_addr) {
1035                         vpe_err(ctx->dev,
1036                                 "acquiring output buffer(%d) dma_addr failed\n",
1037                                 port);
1038                         return;
1039                 }
1040                 /* Apply the offset */
1041                 dma_addr += offset;
1042                 stride = q_data->bytesperline[VPE_LUMA];
1043         }
1044
1045         if (q_data->flags & Q_DATA_FRAME_1D)
1046                 flags |= VPDMA_DATA_FRAME_1D;
1047         if (q_data->flags & Q_DATA_MODE_TILED)
1048                 flags |= VPDMA_DATA_MODE_TILED;
1049
1050         vpdma_set_max_size(ctx->dev->vpdma, VPDMA_MAX_SIZE1,
1051                            MAX_W, MAX_H);
1052
1053         vpdma_add_out_dtd(&ctx->desc_list, q_data->width,
1054                           stride, &q_data->c_rect,
1055                           vpdma_fmt, dma_addr, MAX_OUT_WIDTH_REG1,
1056                           MAX_OUT_HEIGHT_REG1, p_data->channel, flags);
1057 }
1058
1059 static void add_in_dtd(struct vpe_ctx *ctx, int port)
1060 {
1061         struct vpe_q_data *q_data = &ctx->q_data[Q_DATA_SRC];
1062         const struct vpe_port_data *p_data = &port_data[port];
1063         struct vb2_buffer *vb = &ctx->src_vbs[p_data->vb_index]->vb2_buf;
1064         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1065         struct vpe_fmt *fmt = q_data->fmt;
1066         const struct vpdma_data_format *vpdma_fmt;
1067         int mv_buf_selector = ctx->src_mv_buf_selector;
1068         int field = vbuf->field == V4L2_FIELD_BOTTOM;
1069         int frame_width, frame_height;
1070         dma_addr_t dma_addr;
1071         u32 flags = 0;
1072         u32 offset = 0;
1073         u32 stride;
1074
1075         if (port == VPE_PORT_MV_IN) {
1076                 vpdma_fmt = &vpdma_misc_fmts[VPDMA_DATA_FMT_MV];
1077                 dma_addr = ctx->mv_buf_dma[mv_buf_selector];
1078                 stride = ALIGN((q_data->width * vpdma_fmt->depth) >> 3,
1079                                VPDMA_STRIDE_ALIGN);
1080         } else {
1081                 /* to incorporate interleaved formats */
1082                 int plane = fmt->coplanar ? p_data->vb_part : 0;
1083
1084                 vpdma_fmt = fmt->vpdma_fmt[plane];
1085                 /*
1086                  * If we are using a single plane buffer and
1087                  * we need to set a separate vpdma chroma channel.
1088                  */
1089                 if (q_data->nplanes == 1 && plane) {
1090                         dma_addr = vb2_dma_contig_plane_dma_addr(vb, 0);
1091                         /* Compute required offset */
1092                         offset = q_data->bytesperline[0] * q_data->height;
1093                 } else {
1094                         dma_addr = vb2_dma_contig_plane_dma_addr(vb, plane);
1095                         /* Use address as is, no offset */
1096                         offset = 0;
1097                 }
1098                 if (!dma_addr) {
1099                         vpe_err(ctx->dev,
1100                                 "acquiring output buffer(%d) dma_addr failed\n",
1101                                 port);
1102                         return;
1103                 }
1104                 /* Apply the offset */
1105                 dma_addr += offset;
1106                 stride = q_data->bytesperline[VPE_LUMA];
1107
1108                 if (q_data->flags & Q_DATA_INTERLACED_SEQ_TB) {
1109                         /*
1110                          * Use top or bottom field from same vb alternately
1111                          * f,f-1,f-2 = TBT when seq is even
1112                          * f,f-1,f-2 = BTB when seq is odd
1113                          */
1114                         field = (p_data->vb_index + (ctx->sequence % 2)) % 2;
1115
1116                         if (field) {
1117                                 /*
1118                                  * bottom field of a SEQ_TB buffer
1119                                  * Skip the top field data by
1120                                  */
1121                                 int height = q_data->height / 2;
1122                                 int bpp = fmt->fourcc == V4L2_PIX_FMT_NV12 ?
1123                                                 1 : (vpdma_fmt->depth >> 3);
1124                                 if (plane)
1125                                         height /= 2;
1126                                 dma_addr += q_data->width * height * bpp;
1127                         }
1128                 }
1129         }
1130
1131         if (q_data->flags & Q_DATA_FRAME_1D)
1132                 flags |= VPDMA_DATA_FRAME_1D;
1133         if (q_data->flags & Q_DATA_MODE_TILED)
1134                 flags |= VPDMA_DATA_MODE_TILED;
1135
1136         frame_width = q_data->c_rect.width;
1137         frame_height = q_data->c_rect.height;
1138
1139         if (p_data->vb_part && fmt->fourcc == V4L2_PIX_FMT_NV12)
1140                 frame_height /= 2;
1141
1142         vpdma_add_in_dtd(&ctx->desc_list, q_data->width, stride,
1143                          &q_data->c_rect, vpdma_fmt, dma_addr,
1144                          p_data->channel, field, flags, frame_width,
1145                          frame_height, 0, 0);
1146 }
1147
1148 /*
1149  * Enable the expected IRQ sources
1150  */
1151 static void enable_irqs(struct vpe_ctx *ctx)
1152 {
1153         write_reg(ctx->dev, VPE_INT0_ENABLE0_SET, VPE_INT0_LIST0_COMPLETE);
1154         write_reg(ctx->dev, VPE_INT0_ENABLE1_SET, VPE_DEI_ERROR_INT |
1155                                 VPE_DS1_UV_ERROR_INT);
1156
1157         vpdma_enable_list_complete_irq(ctx->dev->vpdma, 0, 0, true);
1158 }
1159
1160 static void disable_irqs(struct vpe_ctx *ctx)
1161 {
1162         write_reg(ctx->dev, VPE_INT0_ENABLE0_CLR, 0xffffffff);
1163         write_reg(ctx->dev, VPE_INT0_ENABLE1_CLR, 0xffffffff);
1164
1165         vpdma_enable_list_complete_irq(ctx->dev->vpdma, 0, 0, false);
1166 }
1167
1168 /* device_run() - prepares and starts the device
1169  *
1170  * This function is only called when both the source and destination
1171  * buffers are in place.
1172  */
1173 static void device_run(void *priv)
1174 {
1175         struct vpe_ctx *ctx = priv;
1176         struct sc_data *sc = ctx->dev->sc;
1177         struct vpe_q_data *d_q_data = &ctx->q_data[Q_DATA_DST];
1178         struct vpe_q_data *s_q_data = &ctx->q_data[Q_DATA_SRC];
1179
1180         if (ctx->deinterlacing && s_q_data->flags & Q_DATA_INTERLACED_SEQ_TB &&
1181                 ctx->sequence % 2 == 0) {
1182                 /* When using SEQ_TB buffers, When using it first time,
1183                  * No need to remove the buffer as the next field is present
1184                  * in the same buffer. (so that job_ready won't fail)
1185                  * It will be removed when using bottom field
1186                  */
1187                 ctx->src_vbs[0] = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx);
1188                 WARN_ON(ctx->src_vbs[0] == NULL);
1189         } else {
1190                 ctx->src_vbs[0] = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx);
1191                 WARN_ON(ctx->src_vbs[0] == NULL);
1192         }
1193
1194         ctx->dst_vb = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx);
1195         WARN_ON(ctx->dst_vb == NULL);
1196
1197         if (ctx->deinterlacing) {
1198
1199                 if (ctx->src_vbs[2] == NULL) {
1200                         ctx->src_vbs[2] = ctx->src_vbs[0];
1201                         WARN_ON(ctx->src_vbs[2] == NULL);
1202                         ctx->src_vbs[1] = ctx->src_vbs[0];
1203                         WARN_ON(ctx->src_vbs[1] == NULL);
1204                 }
1205
1206                 /*
1207                  * we have output the first 2 frames through line average, we
1208                  * now switch to EDI de-interlacer
1209                  */
1210                 if (ctx->sequence == 2)
1211                         config_edi_input_mode(ctx, 0x3); /* EDI (Y + UV) */
1212         }
1213
1214         /* config descriptors */
1215         if (ctx->dev->loaded_mmrs != ctx->mmr_adb.dma_addr || ctx->load_mmrs) {
1216                 vpdma_map_desc_buf(ctx->dev->vpdma, &ctx->mmr_adb);
1217                 vpdma_add_cfd_adb(&ctx->desc_list, CFD_MMR_CLIENT, &ctx->mmr_adb);
1218
1219                 set_line_modes(ctx);
1220
1221                 ctx->dev->loaded_mmrs = ctx->mmr_adb.dma_addr;
1222                 ctx->load_mmrs = false;
1223         }
1224
1225         if (sc->loaded_coeff_h != ctx->sc_coeff_h.dma_addr ||
1226                         sc->load_coeff_h) {
1227                 vpdma_map_desc_buf(ctx->dev->vpdma, &ctx->sc_coeff_h);
1228                 vpdma_add_cfd_block(&ctx->desc_list, CFD_SC_CLIENT,
1229                         &ctx->sc_coeff_h, 0);
1230
1231                 sc->loaded_coeff_h = ctx->sc_coeff_h.dma_addr;
1232                 sc->load_coeff_h = false;
1233         }
1234
1235         if (sc->loaded_coeff_v != ctx->sc_coeff_v.dma_addr ||
1236                         sc->load_coeff_v) {
1237                 vpdma_map_desc_buf(ctx->dev->vpdma, &ctx->sc_coeff_v);
1238                 vpdma_add_cfd_block(&ctx->desc_list, CFD_SC_CLIENT,
1239                         &ctx->sc_coeff_v, SC_COEF_SRAM_SIZE >> 4);
1240
1241                 sc->loaded_coeff_v = ctx->sc_coeff_v.dma_addr;
1242                 sc->load_coeff_v = false;
1243         }
1244
1245         /* output data descriptors */
1246         if (ctx->deinterlacing)
1247                 add_out_dtd(ctx, VPE_PORT_MV_OUT);
1248
1249         if (d_q_data->colorspace == V4L2_COLORSPACE_SRGB) {
1250                 add_out_dtd(ctx, VPE_PORT_RGB_OUT);
1251         } else {
1252                 add_out_dtd(ctx, VPE_PORT_LUMA_OUT);
1253                 if (d_q_data->fmt->coplanar)
1254                         add_out_dtd(ctx, VPE_PORT_CHROMA_OUT);
1255         }
1256
1257         /* input data descriptors */
1258         if (ctx->deinterlacing) {
1259                 add_in_dtd(ctx, VPE_PORT_LUMA3_IN);
1260                 add_in_dtd(ctx, VPE_PORT_CHROMA3_IN);
1261
1262                 add_in_dtd(ctx, VPE_PORT_LUMA2_IN);
1263                 add_in_dtd(ctx, VPE_PORT_CHROMA2_IN);
1264         }
1265
1266         add_in_dtd(ctx, VPE_PORT_LUMA1_IN);
1267         add_in_dtd(ctx, VPE_PORT_CHROMA1_IN);
1268
1269         if (ctx->deinterlacing)
1270                 add_in_dtd(ctx, VPE_PORT_MV_IN);
1271
1272         /* sync on channel control descriptors for input ports */
1273         vpdma_add_sync_on_channel_ctd(&ctx->desc_list, VPE_CHAN_LUMA1_IN);
1274         vpdma_add_sync_on_channel_ctd(&ctx->desc_list, VPE_CHAN_CHROMA1_IN);
1275
1276         if (ctx->deinterlacing) {
1277                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list,
1278                         VPE_CHAN_LUMA2_IN);
1279                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list,
1280                         VPE_CHAN_CHROMA2_IN);
1281
1282                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list,
1283                         VPE_CHAN_LUMA3_IN);
1284                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list,
1285                         VPE_CHAN_CHROMA3_IN);
1286
1287                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list, VPE_CHAN_MV_IN);
1288         }
1289
1290         /* sync on channel control descriptors for output ports */
1291         if (d_q_data->colorspace == V4L2_COLORSPACE_SRGB) {
1292                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list,
1293                         VPE_CHAN_RGB_OUT);
1294         } else {
1295                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list,
1296                         VPE_CHAN_LUMA_OUT);
1297                 if (d_q_data->fmt->coplanar)
1298                         vpdma_add_sync_on_channel_ctd(&ctx->desc_list,
1299                                 VPE_CHAN_CHROMA_OUT);
1300         }
1301
1302         if (ctx->deinterlacing)
1303                 vpdma_add_sync_on_channel_ctd(&ctx->desc_list, VPE_CHAN_MV_OUT);
1304
1305         enable_irqs(ctx);
1306
1307         vpdma_map_desc_buf(ctx->dev->vpdma, &ctx->desc_list.buf);
1308         vpdma_submit_descs(ctx->dev->vpdma, &ctx->desc_list, 0);
1309 }
1310
1311 static void dei_error(struct vpe_ctx *ctx)
1312 {
1313         dev_warn(ctx->dev->v4l2_dev.dev,
1314                 "received DEI error interrupt\n");
1315 }
1316
1317 static void ds1_uv_error(struct vpe_ctx *ctx)
1318 {
1319         dev_warn(ctx->dev->v4l2_dev.dev,
1320                 "received downsampler error interrupt\n");
1321 }
1322
1323 static irqreturn_t vpe_irq(int irq_vpe, void *data)
1324 {
1325         struct vpe_dev *dev = (struct vpe_dev *)data;
1326         struct vpe_ctx *ctx;
1327         struct vpe_q_data *d_q_data;
1328         struct vb2_v4l2_buffer *s_vb, *d_vb;
1329         unsigned long flags;
1330         u32 irqst0, irqst1;
1331         bool list_complete = false;
1332
1333         irqst0 = read_reg(dev, VPE_INT0_STATUS0);
1334         if (irqst0) {
1335                 write_reg(dev, VPE_INT0_STATUS0_CLR, irqst0);
1336                 vpe_dbg(dev, "INT0_STATUS0 = 0x%08x\n", irqst0);
1337         }
1338
1339         irqst1 = read_reg(dev, VPE_INT0_STATUS1);
1340         if (irqst1) {
1341                 write_reg(dev, VPE_INT0_STATUS1_CLR, irqst1);
1342                 vpe_dbg(dev, "INT0_STATUS1 = 0x%08x\n", irqst1);
1343         }
1344
1345         ctx = v4l2_m2m_get_curr_priv(dev->m2m_dev);
1346         if (!ctx) {
1347                 vpe_err(dev, "instance released before end of transaction\n");
1348                 goto handled;
1349         }
1350
1351         if (irqst1) {
1352                 if (irqst1 & VPE_DEI_ERROR_INT) {
1353                         irqst1 &= ~VPE_DEI_ERROR_INT;
1354                         dei_error(ctx);
1355                 }
1356                 if (irqst1 & VPE_DS1_UV_ERROR_INT) {
1357                         irqst1 &= ~VPE_DS1_UV_ERROR_INT;
1358                         ds1_uv_error(ctx);
1359                 }
1360         }
1361
1362         if (irqst0) {
1363                 if (irqst0 & VPE_INT0_LIST0_COMPLETE)
1364                         vpdma_clear_list_stat(ctx->dev->vpdma, 0, 0);
1365
1366                 irqst0 &= ~(VPE_INT0_LIST0_COMPLETE);
1367                 list_complete = true;
1368         }
1369
1370         if (irqst0 | irqst1) {
1371                 dev_warn(dev->v4l2_dev.dev, "Unexpected interrupt: INT0_STATUS0 = 0x%08x, INT0_STATUS1 = 0x%08x\n",
1372                         irqst0, irqst1);
1373         }
1374
1375         /*
1376          * Setup next operation only when list complete IRQ occurs
1377          * otherwise, skip the following code
1378          */
1379         if (!list_complete)
1380                 goto handled;
1381
1382         disable_irqs(ctx);
1383
1384         vpdma_unmap_desc_buf(dev->vpdma, &ctx->desc_list.buf);
1385         vpdma_unmap_desc_buf(dev->vpdma, &ctx->mmr_adb);
1386         vpdma_unmap_desc_buf(dev->vpdma, &ctx->sc_coeff_h);
1387         vpdma_unmap_desc_buf(dev->vpdma, &ctx->sc_coeff_v);
1388
1389         vpdma_reset_desc_list(&ctx->desc_list);
1390
1391          /* the previous dst mv buffer becomes the next src mv buffer */
1392         ctx->src_mv_buf_selector = !ctx->src_mv_buf_selector;
1393
1394         if (ctx->aborting)
1395                 goto finished;
1396
1397         s_vb = ctx->src_vbs[0];
1398         d_vb = ctx->dst_vb;
1399
1400         d_vb->flags = s_vb->flags;
1401         d_vb->vb2_buf.timestamp = s_vb->vb2_buf.timestamp;
1402
1403         if (s_vb->flags & V4L2_BUF_FLAG_TIMECODE)
1404                 d_vb->timecode = s_vb->timecode;
1405
1406         d_vb->sequence = ctx->sequence;
1407
1408         d_q_data = &ctx->q_data[Q_DATA_DST];
1409         if (d_q_data->flags & Q_IS_INTERLACED) {
1410                 d_vb->field = ctx->field;
1411                 if (ctx->field == V4L2_FIELD_BOTTOM) {
1412                         ctx->sequence++;
1413                         ctx->field = V4L2_FIELD_TOP;
1414                 } else {
1415                         WARN_ON(ctx->field != V4L2_FIELD_TOP);
1416                         ctx->field = V4L2_FIELD_BOTTOM;
1417                 }
1418         } else {
1419                 d_vb->field = V4L2_FIELD_NONE;
1420                 ctx->sequence++;
1421         }
1422
1423         if (ctx->deinterlacing) {
1424                 /*
1425                  * Allow source buffer to be dequeued only if it won't be used
1426                  * in the next iteration. All vbs are initialized to first
1427                  * buffer and we are shifting buffers every iteration, for the
1428                  * first two iterations, no buffer will be dequeued.
1429                  * This ensures that driver will keep (n-2)th (n-1)th and (n)th
1430                  * field when deinterlacing is enabled
1431                  */
1432                 if (ctx->src_vbs[2] != ctx->src_vbs[1])
1433                         s_vb = ctx->src_vbs[2];
1434                 else
1435                         s_vb = NULL;
1436         }
1437
1438         spin_lock_irqsave(&dev->lock, flags);
1439
1440         if (s_vb)
1441                 v4l2_m2m_buf_done(s_vb, VB2_BUF_STATE_DONE);
1442
1443         v4l2_m2m_buf_done(d_vb, VB2_BUF_STATE_DONE);
1444
1445         spin_unlock_irqrestore(&dev->lock, flags);
1446
1447         if (ctx->deinterlacing) {
1448                 ctx->src_vbs[2] = ctx->src_vbs[1];
1449                 ctx->src_vbs[1] = ctx->src_vbs[0];
1450         }
1451
1452         /*
1453          * Since the vb2_buf_done has already been called fir therse
1454          * buffer we can now NULL them out so that we won't try
1455          * to clean out stray pointer later on.
1456         */
1457         ctx->src_vbs[0] = NULL;
1458         ctx->dst_vb = NULL;
1459
1460         ctx->bufs_completed++;
1461         if (ctx->bufs_completed < ctx->bufs_per_job && job_ready(ctx)) {
1462                 device_run(ctx);
1463                 goto handled;
1464         }
1465
1466 finished:
1467         vpe_dbg(ctx->dev, "finishing transaction\n");
1468         ctx->bufs_completed = 0;
1469         v4l2_m2m_job_finish(dev->m2m_dev, ctx->fh.m2m_ctx);
1470 handled:
1471         return IRQ_HANDLED;
1472 }
1473
1474 /*
1475  * video ioctls
1476  */
1477 static int vpe_querycap(struct file *file, void *priv,
1478                         struct v4l2_capability *cap)
1479 {
1480         strscpy(cap->driver, VPE_MODULE_NAME, sizeof(cap->driver));
1481         strscpy(cap->card, VPE_MODULE_NAME, sizeof(cap->card));
1482         snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s",
1483                 VPE_MODULE_NAME);
1484         return 0;
1485 }
1486
1487 static int __enum_fmt(struct v4l2_fmtdesc *f, u32 type)
1488 {
1489         int i, index;
1490         struct vpe_fmt *fmt = NULL;
1491
1492         index = 0;
1493         for (i = 0; i < ARRAY_SIZE(vpe_formats); ++i) {
1494                 if (vpe_formats[i].types & type) {
1495                         if (index == f->index) {
1496                                 fmt = &vpe_formats[i];
1497                                 break;
1498                         }
1499                         index++;
1500                 }
1501         }
1502
1503         if (!fmt)
1504                 return -EINVAL;
1505
1506         f->pixelformat = fmt->fourcc;
1507         return 0;
1508 }
1509
1510 static int vpe_enum_fmt(struct file *file, void *priv,
1511                                 struct v4l2_fmtdesc *f)
1512 {
1513         if (V4L2_TYPE_IS_OUTPUT(f->type))
1514                 return __enum_fmt(f, VPE_FMT_TYPE_OUTPUT);
1515
1516         return __enum_fmt(f, VPE_FMT_TYPE_CAPTURE);
1517 }
1518
1519 static int vpe_g_fmt(struct file *file, void *priv, struct v4l2_format *f)
1520 {
1521         struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
1522         struct vpe_ctx *ctx = file->private_data;
1523         struct vb2_queue *vq;
1524         struct vpe_q_data *q_data;
1525         int i;
1526
1527         vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type);
1528         if (!vq)
1529                 return -EINVAL;
1530
1531         q_data = get_q_data(ctx, f->type);
1532         if (!q_data)
1533                 return -EINVAL;
1534
1535         pix->width = q_data->width;
1536         pix->height = q_data->height;
1537         pix->pixelformat = q_data->fmt->fourcc;
1538         pix->field = q_data->field;
1539
1540         if (V4L2_TYPE_IS_OUTPUT(f->type)) {
1541                 pix->colorspace = q_data->colorspace;
1542         } else {
1543                 struct vpe_q_data *s_q_data;
1544
1545                 /* get colorspace from the source queue */
1546                 s_q_data = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE);
1547
1548                 pix->colorspace = s_q_data->colorspace;
1549         }
1550
1551         pix->num_planes = q_data->nplanes;
1552
1553         for (i = 0; i < pix->num_planes; i++) {
1554                 pix->plane_fmt[i].bytesperline = q_data->bytesperline[i];
1555                 pix->plane_fmt[i].sizeimage = q_data->sizeimage[i];
1556         }
1557
1558         return 0;
1559 }
1560
1561 static int __vpe_try_fmt(struct vpe_ctx *ctx, struct v4l2_format *f,
1562                        struct vpe_fmt *fmt, int type)
1563 {
1564         struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
1565         struct v4l2_plane_pix_format *plane_fmt;
1566         unsigned int w_align;
1567         int i, depth, depth_bytes, height;
1568         unsigned int stride = 0;
1569
1570         if (!fmt || !(fmt->types & type)) {
1571                 vpe_err(ctx->dev, "Fourcc format (0x%08x) invalid.\n",
1572                         pix->pixelformat);
1573                 return -EINVAL;
1574         }
1575
1576         if (pix->field != V4L2_FIELD_NONE && pix->field != V4L2_FIELD_ALTERNATE
1577                         && pix->field != V4L2_FIELD_SEQ_TB)
1578                 pix->field = V4L2_FIELD_NONE;
1579
1580         depth = fmt->vpdma_fmt[VPE_LUMA]->depth;
1581
1582         /*
1583          * the line stride should 16 byte aligned for VPDMA to work, based on
1584          * the bytes per pixel, figure out how much the width should be aligned
1585          * to make sure line stride is 16 byte aligned
1586          */
1587         depth_bytes = depth >> 3;
1588
1589         if (depth_bytes == 3) {
1590                 /*
1591                  * if bpp is 3(as in some RGB formats), the pixel width doesn't
1592                  * really help in ensuring line stride is 16 byte aligned
1593                  */
1594                 w_align = 4;
1595         } else {
1596                 /*
1597                  * for the remainder bpp(4, 2 and 1), the pixel width alignment
1598                  * can ensure a line stride alignment of 16 bytes. For example,
1599                  * if bpp is 2, then the line stride can be 16 byte aligned if
1600                  * the width is 8 byte aligned
1601                  */
1602
1603                 /*
1604                  * HACK: using order_base_2() here causes lots of asm output
1605                  * errors with smatch, on i386:
1606                  * ./arch/x86/include/asm/bitops.h:457:22:
1607                  *               warning: asm output is not an lvalue
1608                  * Perhaps some gcc optimization is doing the wrong thing
1609                  * there.
1610                  * Let's get rid of them by doing the calculus on two steps
1611                  */
1612                 w_align = roundup_pow_of_two(VPDMA_DESC_ALIGN / depth_bytes);
1613                 w_align = ilog2(w_align);
1614         }
1615
1616         v4l_bound_align_image(&pix->width, MIN_W, MAX_W, w_align,
1617                               &pix->height, MIN_H, MAX_H, H_ALIGN,
1618                               S_ALIGN);
1619
1620         if (!pix->num_planes)
1621                 pix->num_planes = fmt->coplanar ? 2 : 1;
1622         else if (pix->num_planes > 1 && !fmt->coplanar)
1623                 pix->num_planes = 1;
1624
1625         pix->pixelformat = fmt->fourcc;
1626
1627         /*
1628          * For the actual image parameters, we need to consider the field
1629          * height of the image for SEQ_TB buffers.
1630          */
1631         if (pix->field == V4L2_FIELD_SEQ_TB)
1632                 height = pix->height / 2;
1633         else
1634                 height = pix->height;
1635
1636         if (!pix->colorspace) {
1637                 if (fmt->fourcc == V4L2_PIX_FMT_RGB24 ||
1638                                 fmt->fourcc == V4L2_PIX_FMT_BGR24 ||
1639                                 fmt->fourcc == V4L2_PIX_FMT_RGB32 ||
1640                                 fmt->fourcc == V4L2_PIX_FMT_BGR32) {
1641                         pix->colorspace = V4L2_COLORSPACE_SRGB;
1642                 } else {
1643                         if (height > 1280)      /* HD */
1644                                 pix->colorspace = V4L2_COLORSPACE_REC709;
1645                         else                    /* SD */
1646                                 pix->colorspace = V4L2_COLORSPACE_SMPTE170M;
1647                 }
1648         }
1649
1650         memset(pix->reserved, 0, sizeof(pix->reserved));
1651         for (i = 0; i < pix->num_planes; i++) {
1652                 plane_fmt = &pix->plane_fmt[i];
1653                 depth = fmt->vpdma_fmt[i]->depth;
1654
1655                 stride = (pix->width * fmt->vpdma_fmt[VPE_LUMA]->depth) >> 3;
1656                 if (stride > plane_fmt->bytesperline)
1657                         plane_fmt->bytesperline = stride;
1658
1659                 plane_fmt->bytesperline = ALIGN(plane_fmt->bytesperline,
1660                                                 VPDMA_STRIDE_ALIGN);
1661
1662                 if (i == VPE_LUMA) {
1663                         plane_fmt->sizeimage = pix->height *
1664                                                plane_fmt->bytesperline;
1665
1666                         if (pix->num_planes == 1 && fmt->coplanar)
1667                                 plane_fmt->sizeimage += pix->height *
1668                                         plane_fmt->bytesperline *
1669                                         fmt->vpdma_fmt[VPE_CHROMA]->depth >> 3;
1670
1671                 } else { /* i == VIP_CHROMA */
1672                         plane_fmt->sizeimage = (pix->height *
1673                                                plane_fmt->bytesperline *
1674                                                depth) >> 3;
1675                 }
1676                 memset(plane_fmt->reserved, 0, sizeof(plane_fmt->reserved));
1677         }
1678
1679         return 0;
1680 }
1681
1682 static int vpe_try_fmt(struct file *file, void *priv, struct v4l2_format *f)
1683 {
1684         struct vpe_ctx *ctx = file->private_data;
1685         struct vpe_fmt *fmt = find_format(f);
1686
1687         if (V4L2_TYPE_IS_OUTPUT(f->type))
1688                 return __vpe_try_fmt(ctx, f, fmt, VPE_FMT_TYPE_OUTPUT);
1689         else
1690                 return __vpe_try_fmt(ctx, f, fmt, VPE_FMT_TYPE_CAPTURE);
1691 }
1692
1693 static int __vpe_s_fmt(struct vpe_ctx *ctx, struct v4l2_format *f)
1694 {
1695         struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
1696         struct v4l2_plane_pix_format *plane_fmt;
1697         struct vpe_q_data *q_data;
1698         struct vb2_queue *vq;
1699         int i;
1700
1701         vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type);
1702         if (!vq)
1703                 return -EINVAL;
1704
1705         if (vb2_is_busy(vq)) {
1706                 vpe_err(ctx->dev, "queue busy\n");
1707                 return -EBUSY;
1708         }
1709
1710         q_data = get_q_data(ctx, f->type);
1711         if (!q_data)
1712                 return -EINVAL;
1713
1714         q_data->fmt             = find_format(f);
1715         q_data->width           = pix->width;
1716         q_data->height          = pix->height;
1717         q_data->colorspace      = pix->colorspace;
1718         q_data->field           = pix->field;
1719         q_data->nplanes         = pix->num_planes;
1720
1721         for (i = 0; i < pix->num_planes; i++) {
1722                 plane_fmt = &pix->plane_fmt[i];
1723
1724                 q_data->bytesperline[i] = plane_fmt->bytesperline;
1725                 q_data->sizeimage[i]    = plane_fmt->sizeimage;
1726         }
1727
1728         q_data->c_rect.left     = 0;
1729         q_data->c_rect.top      = 0;
1730         q_data->c_rect.width    = q_data->width;
1731         q_data->c_rect.height   = q_data->height;
1732
1733         if (q_data->field == V4L2_FIELD_ALTERNATE)
1734                 q_data->flags |= Q_DATA_INTERLACED_ALTERNATE;
1735         else if (q_data->field == V4L2_FIELD_SEQ_TB)
1736                 q_data->flags |= Q_DATA_INTERLACED_SEQ_TB;
1737         else
1738                 q_data->flags &= ~Q_IS_INTERLACED;
1739
1740         /* the crop height is halved for the case of SEQ_TB buffers */
1741         if (q_data->flags & Q_DATA_INTERLACED_SEQ_TB)
1742                 q_data->c_rect.height /= 2;
1743
1744         vpe_dbg(ctx->dev, "Setting format for type %d, wxh: %dx%d, fmt: %d bpl_y %d",
1745                 f->type, q_data->width, q_data->height, q_data->fmt->fourcc,
1746                 q_data->bytesperline[VPE_LUMA]);
1747         if (q_data->nplanes == 2)
1748                 vpe_dbg(ctx->dev, " bpl_uv %d\n",
1749                         q_data->bytesperline[VPE_CHROMA]);
1750
1751         return 0;
1752 }
1753
1754 static int vpe_s_fmt(struct file *file, void *priv, struct v4l2_format *f)
1755 {
1756         int ret;
1757         struct vpe_ctx *ctx = file->private_data;
1758
1759         ret = vpe_try_fmt(file, priv, f);
1760         if (ret)
1761                 return ret;
1762
1763         ret = __vpe_s_fmt(ctx, f);
1764         if (ret)
1765                 return ret;
1766
1767         if (V4L2_TYPE_IS_OUTPUT(f->type))
1768                 set_src_registers(ctx);
1769         else
1770                 set_dst_registers(ctx);
1771
1772         return set_srcdst_params(ctx);
1773 }
1774
1775 static int __vpe_try_selection(struct vpe_ctx *ctx, struct v4l2_selection *s)
1776 {
1777         struct vpe_q_data *q_data;
1778         int height;
1779
1780         if ((s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
1781             (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT))
1782                 return -EINVAL;
1783
1784         q_data = get_q_data(ctx, s->type);
1785         if (!q_data)
1786                 return -EINVAL;
1787
1788         switch (s->target) {
1789         case V4L2_SEL_TGT_COMPOSE:
1790                 /*
1791                  * COMPOSE target is only valid for capture buffer type, return
1792                  * error for output buffer type
1793                  */
1794                 if (s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1795                         return -EINVAL;
1796                 break;
1797         case V4L2_SEL_TGT_CROP:
1798                 /*
1799                  * CROP target is only valid for output buffer type, return
1800                  * error for capture buffer type
1801                  */
1802                 if (s->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1803                         return -EINVAL;
1804                 break;
1805         /*
1806          * bound and default crop/compose targets are invalid targets to
1807          * try/set
1808          */
1809         default:
1810                 return -EINVAL;
1811         }
1812
1813         /*
1814          * For SEQ_TB buffers, crop height should be less than the height of
1815          * the field height, not the buffer height
1816          */
1817         if (q_data->flags & Q_DATA_INTERLACED_SEQ_TB)
1818                 height = q_data->height / 2;
1819         else
1820                 height = q_data->height;
1821
1822         if (s->r.top < 0 || s->r.left < 0) {
1823                 vpe_err(ctx->dev, "negative values for top and left\n");
1824                 s->r.top = s->r.left = 0;
1825         }
1826
1827         v4l_bound_align_image(&s->r.width, MIN_W, q_data->width, 1,
1828                 &s->r.height, MIN_H, height, H_ALIGN, S_ALIGN);
1829
1830         /* adjust left/top if cropping rectangle is out of bounds */
1831         if (s->r.left + s->r.width > q_data->width)
1832                 s->r.left = q_data->width - s->r.width;
1833         if (s->r.top + s->r.height > q_data->height)
1834                 s->r.top = q_data->height - s->r.height;
1835
1836         return 0;
1837 }
1838
1839 static int vpe_g_selection(struct file *file, void *fh,
1840                 struct v4l2_selection *s)
1841 {
1842         struct vpe_ctx *ctx = file->private_data;
1843         struct vpe_q_data *q_data;
1844         bool use_c_rect = false;
1845
1846         if ((s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
1847             (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT))
1848                 return -EINVAL;
1849
1850         q_data = get_q_data(ctx, s->type);
1851         if (!q_data)
1852                 return -EINVAL;
1853
1854         switch (s->target) {
1855         case V4L2_SEL_TGT_COMPOSE_DEFAULT:
1856         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1857                 if (s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1858                         return -EINVAL;
1859                 break;
1860         case V4L2_SEL_TGT_CROP_BOUNDS:
1861         case V4L2_SEL_TGT_CROP_DEFAULT:
1862                 if (s->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1863                         return -EINVAL;
1864                 break;
1865         case V4L2_SEL_TGT_COMPOSE:
1866                 if (s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1867                         return -EINVAL;
1868                 use_c_rect = true;
1869                 break;
1870         case V4L2_SEL_TGT_CROP:
1871                 if (s->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1872                         return -EINVAL;
1873                 use_c_rect = true;
1874                 break;
1875         default:
1876                 return -EINVAL;
1877         }
1878
1879         if (use_c_rect) {
1880                 /*
1881                  * for CROP/COMPOSE target type, return c_rect params from the
1882                  * respective buffer type
1883                  */
1884                 s->r = q_data->c_rect;
1885         } else {
1886                 /*
1887                  * for DEFAULT/BOUNDS target type, return width and height from
1888                  * S_FMT of the respective buffer type
1889                  */
1890                 s->r.left = 0;
1891                 s->r.top = 0;
1892                 s->r.width = q_data->width;
1893                 s->r.height = q_data->height;
1894         }
1895
1896         return 0;
1897 }
1898
1899
1900 static int vpe_s_selection(struct file *file, void *fh,
1901                 struct v4l2_selection *s)
1902 {
1903         struct vpe_ctx *ctx = file->private_data;
1904         struct vpe_q_data *q_data;
1905         struct v4l2_selection sel = *s;
1906         int ret;
1907
1908         ret = __vpe_try_selection(ctx, &sel);
1909         if (ret)
1910                 return ret;
1911
1912         q_data = get_q_data(ctx, sel.type);
1913         if (!q_data)
1914                 return -EINVAL;
1915
1916         if ((q_data->c_rect.left == sel.r.left) &&
1917                         (q_data->c_rect.top == sel.r.top) &&
1918                         (q_data->c_rect.width == sel.r.width) &&
1919                         (q_data->c_rect.height == sel.r.height)) {
1920                 vpe_dbg(ctx->dev,
1921                         "requested crop/compose values are already set\n");
1922                 return 0;
1923         }
1924
1925         q_data->c_rect = sel.r;
1926
1927         return set_srcdst_params(ctx);
1928 }
1929
1930 /*
1931  * defines number of buffers/frames a context can process with VPE before
1932  * switching to a different context. default value is 1 buffer per context
1933  */
1934 #define V4L2_CID_VPE_BUFS_PER_JOB               (V4L2_CID_USER_TI_VPE_BASE + 0)
1935
1936 static int vpe_s_ctrl(struct v4l2_ctrl *ctrl)
1937 {
1938         struct vpe_ctx *ctx =
1939                 container_of(ctrl->handler, struct vpe_ctx, hdl);
1940
1941         switch (ctrl->id) {
1942         case V4L2_CID_VPE_BUFS_PER_JOB:
1943                 ctx->bufs_per_job = ctrl->val;
1944                 break;
1945
1946         default:
1947                 vpe_err(ctx->dev, "Invalid control\n");
1948                 return -EINVAL;
1949         }
1950
1951         return 0;
1952 }
1953
1954 static const struct v4l2_ctrl_ops vpe_ctrl_ops = {
1955         .s_ctrl = vpe_s_ctrl,
1956 };
1957
1958 static const struct v4l2_ioctl_ops vpe_ioctl_ops = {
1959         .vidioc_querycap                = vpe_querycap,
1960
1961         .vidioc_enum_fmt_vid_cap        = vpe_enum_fmt,
1962         .vidioc_g_fmt_vid_cap_mplane    = vpe_g_fmt,
1963         .vidioc_try_fmt_vid_cap_mplane  = vpe_try_fmt,
1964         .vidioc_s_fmt_vid_cap_mplane    = vpe_s_fmt,
1965
1966         .vidioc_enum_fmt_vid_out        = vpe_enum_fmt,
1967         .vidioc_g_fmt_vid_out_mplane    = vpe_g_fmt,
1968         .vidioc_try_fmt_vid_out_mplane  = vpe_try_fmt,
1969         .vidioc_s_fmt_vid_out_mplane    = vpe_s_fmt,
1970
1971         .vidioc_g_selection             = vpe_g_selection,
1972         .vidioc_s_selection             = vpe_s_selection,
1973
1974         .vidioc_reqbufs                 = v4l2_m2m_ioctl_reqbufs,
1975         .vidioc_querybuf                = v4l2_m2m_ioctl_querybuf,
1976         .vidioc_qbuf                    = v4l2_m2m_ioctl_qbuf,
1977         .vidioc_dqbuf                   = v4l2_m2m_ioctl_dqbuf,
1978         .vidioc_expbuf                  = v4l2_m2m_ioctl_expbuf,
1979         .vidioc_streamon                = v4l2_m2m_ioctl_streamon,
1980         .vidioc_streamoff               = v4l2_m2m_ioctl_streamoff,
1981
1982         .vidioc_subscribe_event         = v4l2_ctrl_subscribe_event,
1983         .vidioc_unsubscribe_event       = v4l2_event_unsubscribe,
1984 };
1985
1986 /*
1987  * Queue operations
1988  */
1989 static int vpe_queue_setup(struct vb2_queue *vq,
1990                            unsigned int *nbuffers, unsigned int *nplanes,
1991                            unsigned int sizes[], struct device *alloc_devs[])
1992 {
1993         int i;
1994         struct vpe_ctx *ctx = vb2_get_drv_priv(vq);
1995         struct vpe_q_data *q_data;
1996
1997         q_data = get_q_data(ctx, vq->type);
1998         if (!q_data)
1999                 return -EINVAL;
2000
2001         *nplanes = q_data->nplanes;
2002
2003         for (i = 0; i < *nplanes; i++)
2004                 sizes[i] = q_data->sizeimage[i];
2005
2006         vpe_dbg(ctx->dev, "get %d buffer(s) of size %d", *nbuffers,
2007                 sizes[VPE_LUMA]);
2008         if (q_data->nplanes == 2)
2009                 vpe_dbg(ctx->dev, " and %d\n", sizes[VPE_CHROMA]);
2010
2011         return 0;
2012 }
2013
2014 static int vpe_buf_prepare(struct vb2_buffer *vb)
2015 {
2016         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
2017         struct vpe_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
2018         struct vpe_q_data *q_data;
2019         int i, num_planes;
2020
2021         vpe_dbg(ctx->dev, "type: %d\n", vb->vb2_queue->type);
2022
2023         q_data = get_q_data(ctx, vb->vb2_queue->type);
2024         if (!q_data)
2025                 return -EINVAL;
2026         num_planes = q_data->nplanes;
2027
2028         if (vb->vb2_queue->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
2029                 if (!(q_data->flags & Q_IS_INTERLACED)) {
2030                         vbuf->field = V4L2_FIELD_NONE;
2031                 } else {
2032                         if (vbuf->field != V4L2_FIELD_TOP &&
2033                             vbuf->field != V4L2_FIELD_BOTTOM &&
2034                             vbuf->field != V4L2_FIELD_SEQ_TB)
2035                                 return -EINVAL;
2036                 }
2037         }
2038
2039         for (i = 0; i < num_planes; i++) {
2040                 if (vb2_plane_size(vb, i) < q_data->sizeimage[i]) {
2041                         vpe_err(ctx->dev,
2042                                 "data will not fit into plane (%lu < %lu)\n",
2043                                 vb2_plane_size(vb, i),
2044                                 (long) q_data->sizeimage[i]);
2045                         return -EINVAL;
2046                 }
2047         }
2048
2049         for (i = 0; i < num_planes; i++)
2050                 vb2_set_plane_payload(vb, i, q_data->sizeimage[i]);
2051
2052         return 0;
2053 }
2054
2055 static void vpe_buf_queue(struct vb2_buffer *vb)
2056 {
2057         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
2058         struct vpe_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
2059
2060         v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
2061 }
2062
2063 static int check_srcdst_sizes(struct vpe_ctx *ctx)
2064 {
2065         struct vpe_q_data *s_q_data =  &ctx->q_data[Q_DATA_SRC];
2066         struct vpe_q_data *d_q_data =  &ctx->q_data[Q_DATA_DST];
2067         unsigned int src_w = s_q_data->c_rect.width;
2068         unsigned int src_h = s_q_data->c_rect.height;
2069         unsigned int dst_w = d_q_data->c_rect.width;
2070         unsigned int dst_h = d_q_data->c_rect.height;
2071
2072         if (src_w == dst_w && src_h == dst_h)
2073                 return 0;
2074
2075         if (src_h <= SC_MAX_PIXEL_HEIGHT &&
2076             src_w <= SC_MAX_PIXEL_WIDTH &&
2077             dst_h <= SC_MAX_PIXEL_HEIGHT &&
2078             dst_w <= SC_MAX_PIXEL_WIDTH)
2079                 return 0;
2080
2081         return -1;
2082 }
2083
2084 static void vpe_return_all_buffers(struct vpe_ctx *ctx,  struct vb2_queue *q,
2085                                    enum vb2_buffer_state state)
2086 {
2087         struct vb2_v4l2_buffer *vb;
2088         unsigned long flags;
2089
2090         for (;;) {
2091                 if (V4L2_TYPE_IS_OUTPUT(q->type))
2092                         vb = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx);
2093                 else
2094                         vb = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx);
2095                 if (!vb)
2096                         break;
2097                 spin_lock_irqsave(&ctx->dev->lock, flags);
2098                 v4l2_m2m_buf_done(vb, state);
2099                 spin_unlock_irqrestore(&ctx->dev->lock, flags);
2100         }
2101
2102         /*
2103          * Cleanup the in-transit vb2 buffers that have been
2104          * removed from their respective queue already but for
2105          * which procecessing has not been completed yet.
2106          */
2107         if (V4L2_TYPE_IS_OUTPUT(q->type)) {
2108                 spin_lock_irqsave(&ctx->dev->lock, flags);
2109
2110                 if (ctx->src_vbs[2])
2111                         v4l2_m2m_buf_done(ctx->src_vbs[2], state);
2112
2113                 if (ctx->src_vbs[1] && (ctx->src_vbs[1] != ctx->src_vbs[2]))
2114                         v4l2_m2m_buf_done(ctx->src_vbs[1], state);
2115
2116                 if (ctx->src_vbs[0] &&
2117                     (ctx->src_vbs[0] != ctx->src_vbs[1]) &&
2118                     (ctx->src_vbs[0] != ctx->src_vbs[2]))
2119                         v4l2_m2m_buf_done(ctx->src_vbs[0], state);
2120
2121                 ctx->src_vbs[2] = NULL;
2122                 ctx->src_vbs[1] = NULL;
2123                 ctx->src_vbs[0] = NULL;
2124
2125                 spin_unlock_irqrestore(&ctx->dev->lock, flags);
2126         } else {
2127                 if (ctx->dst_vb) {
2128                         spin_lock_irqsave(&ctx->dev->lock, flags);
2129
2130                         v4l2_m2m_buf_done(ctx->dst_vb, state);
2131                         ctx->dst_vb = NULL;
2132                         spin_unlock_irqrestore(&ctx->dev->lock, flags);
2133                 }
2134         }
2135 }
2136
2137 static int vpe_start_streaming(struct vb2_queue *q, unsigned int count)
2138 {
2139         struct vpe_ctx *ctx = vb2_get_drv_priv(q);
2140
2141         /* Check any of the size exceed maximum scaling sizes */
2142         if (check_srcdst_sizes(ctx)) {
2143                 vpe_err(ctx->dev,
2144                         "Conversion setup failed, check source and destination parameters\n"
2145                         );
2146                 vpe_return_all_buffers(ctx, q, VB2_BUF_STATE_QUEUED);
2147                 return -EINVAL;
2148         }
2149
2150         if (ctx->deinterlacing)
2151                 config_edi_input_mode(ctx, 0x0);
2152
2153         if (ctx->sequence != 0)
2154                 set_srcdst_params(ctx);
2155
2156         return 0;
2157 }
2158
2159 static void vpe_stop_streaming(struct vb2_queue *q)
2160 {
2161         struct vpe_ctx *ctx = vb2_get_drv_priv(q);
2162
2163         vpe_dump_regs(ctx->dev);
2164         vpdma_dump_regs(ctx->dev->vpdma);
2165
2166         vpe_return_all_buffers(ctx, q, VB2_BUF_STATE_ERROR);
2167 }
2168
2169 static const struct vb2_ops vpe_qops = {
2170         .queue_setup     = vpe_queue_setup,
2171         .buf_prepare     = vpe_buf_prepare,
2172         .buf_queue       = vpe_buf_queue,
2173         .wait_prepare    = vb2_ops_wait_prepare,
2174         .wait_finish     = vb2_ops_wait_finish,
2175         .start_streaming = vpe_start_streaming,
2176         .stop_streaming  = vpe_stop_streaming,
2177 };
2178
2179 static int queue_init(void *priv, struct vb2_queue *src_vq,
2180                       struct vb2_queue *dst_vq)
2181 {
2182         struct vpe_ctx *ctx = priv;
2183         struct vpe_dev *dev = ctx->dev;
2184         int ret;
2185
2186         memset(src_vq, 0, sizeof(*src_vq));
2187         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
2188         src_vq->io_modes = VB2_MMAP | VB2_DMABUF;
2189         src_vq->drv_priv = ctx;
2190         src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
2191         src_vq->ops = &vpe_qops;
2192         src_vq->mem_ops = &vb2_dma_contig_memops;
2193         src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
2194         src_vq->lock = &dev->dev_mutex;
2195         src_vq->dev = dev->v4l2_dev.dev;
2196
2197         ret = vb2_queue_init(src_vq);
2198         if (ret)
2199                 return ret;
2200
2201         memset(dst_vq, 0, sizeof(*dst_vq));
2202         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
2203         dst_vq->io_modes = VB2_MMAP | VB2_DMABUF;
2204         dst_vq->drv_priv = ctx;
2205         dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
2206         dst_vq->ops = &vpe_qops;
2207         dst_vq->mem_ops = &vb2_dma_contig_memops;
2208         dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
2209         dst_vq->lock = &dev->dev_mutex;
2210         dst_vq->dev = dev->v4l2_dev.dev;
2211
2212         return vb2_queue_init(dst_vq);
2213 }
2214
2215 static const struct v4l2_ctrl_config vpe_bufs_per_job = {
2216         .ops = &vpe_ctrl_ops,
2217         .id = V4L2_CID_VPE_BUFS_PER_JOB,
2218         .name = "Buffers Per Transaction",
2219         .type = V4L2_CTRL_TYPE_INTEGER,
2220         .def = VPE_DEF_BUFS_PER_JOB,
2221         .min = 1,
2222         .max = VIDEO_MAX_FRAME,
2223         .step = 1,
2224 };
2225
2226 /*
2227  * File operations
2228  */
2229 static int vpe_open(struct file *file)
2230 {
2231         struct vpe_dev *dev = video_drvdata(file);
2232         struct vpe_q_data *s_q_data;
2233         struct v4l2_ctrl_handler *hdl;
2234         struct vpe_ctx *ctx;
2235         int ret;
2236
2237         vpe_dbg(dev, "vpe_open\n");
2238
2239         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
2240         if (!ctx)
2241                 return -ENOMEM;
2242
2243         ctx->dev = dev;
2244
2245         if (mutex_lock_interruptible(&dev->dev_mutex)) {
2246                 ret = -ERESTARTSYS;
2247                 goto free_ctx;
2248         }
2249
2250         ret = vpdma_create_desc_list(&ctx->desc_list, VPE_DESC_LIST_SIZE,
2251                         VPDMA_LIST_TYPE_NORMAL);
2252         if (ret != 0)
2253                 goto unlock;
2254
2255         ret = vpdma_alloc_desc_buf(&ctx->mmr_adb, sizeof(struct vpe_mmr_adb));
2256         if (ret != 0)
2257                 goto free_desc_list;
2258
2259         ret = vpdma_alloc_desc_buf(&ctx->sc_coeff_h, SC_COEF_SRAM_SIZE);
2260         if (ret != 0)
2261                 goto free_mmr_adb;
2262
2263         ret = vpdma_alloc_desc_buf(&ctx->sc_coeff_v, SC_COEF_SRAM_SIZE);
2264         if (ret != 0)
2265                 goto free_sc_h;
2266
2267         init_adb_hdrs(ctx);
2268
2269         v4l2_fh_init(&ctx->fh, video_devdata(file));
2270         file->private_data = ctx;
2271
2272         hdl = &ctx->hdl;
2273         v4l2_ctrl_handler_init(hdl, 1);
2274         v4l2_ctrl_new_custom(hdl, &vpe_bufs_per_job, NULL);
2275         if (hdl->error) {
2276                 ret = hdl->error;
2277                 goto exit_fh;
2278         }
2279         ctx->fh.ctrl_handler = hdl;
2280         v4l2_ctrl_handler_setup(hdl);
2281
2282         s_q_data = &ctx->q_data[Q_DATA_SRC];
2283         s_q_data->fmt = &vpe_formats[2];
2284         s_q_data->width = 1920;
2285         s_q_data->height = 1080;
2286         s_q_data->nplanes = 1;
2287         s_q_data->bytesperline[VPE_LUMA] = (s_q_data->width *
2288                         s_q_data->fmt->vpdma_fmt[VPE_LUMA]->depth) >> 3;
2289         s_q_data->sizeimage[VPE_LUMA] = (s_q_data->bytesperline[VPE_LUMA] *
2290                         s_q_data->height);
2291         s_q_data->colorspace = V4L2_COLORSPACE_REC709;
2292         s_q_data->field = V4L2_FIELD_NONE;
2293         s_q_data->c_rect.left = 0;
2294         s_q_data->c_rect.top = 0;
2295         s_q_data->c_rect.width = s_q_data->width;
2296         s_q_data->c_rect.height = s_q_data->height;
2297         s_q_data->flags = 0;
2298
2299         ctx->q_data[Q_DATA_DST] = *s_q_data;
2300
2301         set_dei_shadow_registers(ctx);
2302         set_src_registers(ctx);
2303         set_dst_registers(ctx);
2304         ret = set_srcdst_params(ctx);
2305         if (ret)
2306                 goto exit_fh;
2307
2308         ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx, &queue_init);
2309
2310         if (IS_ERR(ctx->fh.m2m_ctx)) {
2311                 ret = PTR_ERR(ctx->fh.m2m_ctx);
2312                 goto exit_fh;
2313         }
2314
2315         v4l2_fh_add(&ctx->fh);
2316
2317         /*
2318          * for now, just report the creation of the first instance, we can later
2319          * optimize the driver to enable or disable clocks when the first
2320          * instance is created or the last instance released
2321          */
2322         if (atomic_inc_return(&dev->num_instances) == 1)
2323                 vpe_dbg(dev, "first instance created\n");
2324
2325         ctx->bufs_per_job = VPE_DEF_BUFS_PER_JOB;
2326
2327         ctx->load_mmrs = true;
2328
2329         vpe_dbg(dev, "created instance %p, m2m_ctx: %p\n",
2330                 ctx, ctx->fh.m2m_ctx);
2331
2332         mutex_unlock(&dev->dev_mutex);
2333
2334         return 0;
2335 exit_fh:
2336         v4l2_ctrl_handler_free(hdl);
2337         v4l2_fh_exit(&ctx->fh);
2338         vpdma_free_desc_buf(&ctx->sc_coeff_v);
2339 free_sc_h:
2340         vpdma_free_desc_buf(&ctx->sc_coeff_h);
2341 free_mmr_adb:
2342         vpdma_free_desc_buf(&ctx->mmr_adb);
2343 free_desc_list:
2344         vpdma_free_desc_list(&ctx->desc_list);
2345 unlock:
2346         mutex_unlock(&dev->dev_mutex);
2347 free_ctx:
2348         kfree(ctx);
2349         return ret;
2350 }
2351
2352 static int vpe_release(struct file *file)
2353 {
2354         struct vpe_dev *dev = video_drvdata(file);
2355         struct vpe_ctx *ctx = file->private_data;
2356
2357         vpe_dbg(dev, "releasing instance %p\n", ctx);
2358
2359         mutex_lock(&dev->dev_mutex);
2360         free_mv_buffers(ctx);
2361         vpdma_free_desc_list(&ctx->desc_list);
2362         vpdma_free_desc_buf(&ctx->mmr_adb);
2363
2364         vpdma_free_desc_buf(&ctx->sc_coeff_v);
2365         vpdma_free_desc_buf(&ctx->sc_coeff_h);
2366
2367         v4l2_fh_del(&ctx->fh);
2368         v4l2_fh_exit(&ctx->fh);
2369         v4l2_ctrl_handler_free(&ctx->hdl);
2370         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
2371
2372         kfree(ctx);
2373
2374         /*
2375          * for now, just report the release of the last instance, we can later
2376          * optimize the driver to enable or disable clocks when the first
2377          * instance is created or the last instance released
2378          */
2379         if (atomic_dec_return(&dev->num_instances) == 0)
2380                 vpe_dbg(dev, "last instance released\n");
2381
2382         mutex_unlock(&dev->dev_mutex);
2383
2384         return 0;
2385 }
2386
2387 static const struct v4l2_file_operations vpe_fops = {
2388         .owner          = THIS_MODULE,
2389         .open           = vpe_open,
2390         .release        = vpe_release,
2391         .poll           = v4l2_m2m_fop_poll,
2392         .unlocked_ioctl = video_ioctl2,
2393         .mmap           = v4l2_m2m_fop_mmap,
2394 };
2395
2396 static const struct video_device vpe_videodev = {
2397         .name           = VPE_MODULE_NAME,
2398         .fops           = &vpe_fops,
2399         .ioctl_ops      = &vpe_ioctl_ops,
2400         .minor          = -1,
2401         .release        = video_device_release_empty,
2402         .vfl_dir        = VFL_DIR_M2M,
2403         .device_caps    = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING,
2404 };
2405
2406 static const struct v4l2_m2m_ops m2m_ops = {
2407         .device_run     = device_run,
2408         .job_ready      = job_ready,
2409         .job_abort      = job_abort,
2410 };
2411
2412 static int vpe_runtime_get(struct platform_device *pdev)
2413 {
2414         int r;
2415
2416         dev_dbg(&pdev->dev, "vpe_runtime_get\n");
2417
2418         r = pm_runtime_get_sync(&pdev->dev);
2419         WARN_ON(r < 0);
2420         return r < 0 ? r : 0;
2421 }
2422
2423 static void vpe_runtime_put(struct platform_device *pdev)
2424 {
2425
2426         int r;
2427
2428         dev_dbg(&pdev->dev, "vpe_runtime_put\n");
2429
2430         r = pm_runtime_put_sync(&pdev->dev);
2431         WARN_ON(r < 0 && r != -ENOSYS);
2432 }
2433
2434 static void vpe_fw_cb(struct platform_device *pdev)
2435 {
2436         struct vpe_dev *dev = platform_get_drvdata(pdev);
2437         struct video_device *vfd;
2438         int ret;
2439
2440         vfd = &dev->vfd;
2441         *vfd = vpe_videodev;
2442         vfd->lock = &dev->dev_mutex;
2443         vfd->v4l2_dev = &dev->v4l2_dev;
2444
2445         ret = video_register_device(vfd, VFL_TYPE_GRABBER, 0);
2446         if (ret) {
2447                 vpe_err(dev, "Failed to register video device\n");
2448
2449                 vpe_set_clock_enable(dev, 0);
2450                 vpe_runtime_put(pdev);
2451                 pm_runtime_disable(&pdev->dev);
2452                 v4l2_m2m_release(dev->m2m_dev);
2453                 v4l2_device_unregister(&dev->v4l2_dev);
2454
2455                 return;
2456         }
2457
2458         video_set_drvdata(vfd, dev);
2459         dev_info(dev->v4l2_dev.dev, "Device registered as /dev/video%d\n",
2460                 vfd->num);
2461 }
2462
2463 static int vpe_probe(struct platform_device *pdev)
2464 {
2465         struct vpe_dev *dev;
2466         int ret, irq, func;
2467
2468         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
2469         if (!dev)
2470                 return -ENOMEM;
2471
2472         spin_lock_init(&dev->lock);
2473
2474         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
2475         if (ret)
2476                 return ret;
2477
2478         atomic_set(&dev->num_instances, 0);
2479         mutex_init(&dev->dev_mutex);
2480
2481         dev->res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
2482                                                 "vpe_top");
2483         if (!dev->res) {
2484                 dev_err(&pdev->dev, "missing 'vpe_top' resources data\n");
2485                 return -ENODEV;
2486         }
2487
2488         /*
2489          * HACK: we get resource info from device tree in the form of a list of
2490          * VPE sub blocks, the driver currently uses only the base of vpe_top
2491          * for register access, the driver should be changed later to access
2492          * registers based on the sub block base addresses
2493          */
2494         dev->base = devm_ioremap(&pdev->dev, dev->res->start, SZ_32K);
2495         if (!dev->base) {
2496                 ret = -ENOMEM;
2497                 goto v4l2_dev_unreg;
2498         }
2499
2500         irq = platform_get_irq(pdev, 0);
2501         ret = devm_request_irq(&pdev->dev, irq, vpe_irq, 0, VPE_MODULE_NAME,
2502                         dev);
2503         if (ret)
2504                 goto v4l2_dev_unreg;
2505
2506         platform_set_drvdata(pdev, dev);
2507
2508         dev->m2m_dev = v4l2_m2m_init(&m2m_ops);
2509         if (IS_ERR(dev->m2m_dev)) {
2510                 vpe_err(dev, "Failed to init mem2mem device\n");
2511                 ret = PTR_ERR(dev->m2m_dev);
2512                 goto v4l2_dev_unreg;
2513         }
2514
2515         pm_runtime_enable(&pdev->dev);
2516
2517         ret = vpe_runtime_get(pdev);
2518         if (ret)
2519                 goto rel_m2m;
2520
2521         /* Perform clk enable followed by reset */
2522         vpe_set_clock_enable(dev, 1);
2523
2524         vpe_top_reset(dev);
2525
2526         func = read_field_reg(dev, VPE_PID, VPE_PID_FUNC_MASK,
2527                 VPE_PID_FUNC_SHIFT);
2528         vpe_dbg(dev, "VPE PID function %x\n", func);
2529
2530         vpe_top_vpdma_reset(dev);
2531
2532         dev->sc = sc_create(pdev, "sc");
2533         if (IS_ERR(dev->sc)) {
2534                 ret = PTR_ERR(dev->sc);
2535                 goto runtime_put;
2536         }
2537
2538         dev->csc = csc_create(pdev, "csc");
2539         if (IS_ERR(dev->csc)) {
2540                 ret = PTR_ERR(dev->csc);
2541                 goto runtime_put;
2542         }
2543
2544         dev->vpdma = &dev->vpdma_data;
2545         ret = vpdma_create(pdev, dev->vpdma, vpe_fw_cb);
2546         if (ret)
2547                 goto runtime_put;
2548
2549         return 0;
2550
2551 runtime_put:
2552         vpe_runtime_put(pdev);
2553 rel_m2m:
2554         pm_runtime_disable(&pdev->dev);
2555         v4l2_m2m_release(dev->m2m_dev);
2556 v4l2_dev_unreg:
2557         v4l2_device_unregister(&dev->v4l2_dev);
2558
2559         return ret;
2560 }
2561
2562 static int vpe_remove(struct platform_device *pdev)
2563 {
2564         struct vpe_dev *dev = platform_get_drvdata(pdev);
2565
2566         v4l2_info(&dev->v4l2_dev, "Removing " VPE_MODULE_NAME);
2567
2568         v4l2_m2m_release(dev->m2m_dev);
2569         video_unregister_device(&dev->vfd);
2570         v4l2_device_unregister(&dev->v4l2_dev);
2571
2572         vpe_set_clock_enable(dev, 0);
2573         vpe_runtime_put(pdev);
2574         pm_runtime_disable(&pdev->dev);
2575
2576         return 0;
2577 }
2578
2579 #if defined(CONFIG_OF)
2580 static const struct of_device_id vpe_of_match[] = {
2581         {
2582                 .compatible = "ti,vpe",
2583         },
2584         {},
2585 };
2586 MODULE_DEVICE_TABLE(of, vpe_of_match);
2587 #endif
2588
2589 static struct platform_driver vpe_pdrv = {
2590         .probe          = vpe_probe,
2591         .remove         = vpe_remove,
2592         .driver         = {
2593                 .name   = VPE_MODULE_NAME,
2594                 .of_match_table = of_match_ptr(vpe_of_match),
2595         },
2596 };
2597
2598 module_platform_driver(vpe_pdrv);
2599
2600 MODULE_DESCRIPTION("TI VPE driver");
2601 MODULE_AUTHOR("Dale Farnsworth, <dale@farnsworth.org>");
2602 MODULE_LICENSE("GPL");