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