GNU Linux-libre 4.14.313-gnu1
[releases.git] / drivers / media / platform / coda / coda-common.c
1 /*
2  * Coda multi-standard codec IP
3  *
4  * Copyright (C) 2012 Vista Silicon S.L.
5  *    Javier Martin, <javier.martin@vista-silicon.com>
6  *    Xavier Duret
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  */
13
14 #include <linux/clk.h>
15 #include <linux/debugfs.h>
16 #include <linux/delay.h>
17 #include <linux/firmware.h>
18 #include <linux/gcd.h>
19 #include <linux/genalloc.h>
20 #include <linux/interrupt.h>
21 #include <linux/io.h>
22 #include <linux/irq.h>
23 #include <linux/kfifo.h>
24 #include <linux/module.h>
25 #include <linux/of_device.h>
26 #include <linux/platform_device.h>
27 #include <linux/pm_runtime.h>
28 #include <linux/slab.h>
29 #include <linux/videodev2.h>
30 #include <linux/of.h>
31 #include <linux/platform_data/media/coda.h>
32 #include <linux/reset.h>
33
34 #include <media/v4l2-ctrls.h>
35 #include <media/v4l2-device.h>
36 #include <media/v4l2-event.h>
37 #include <media/v4l2-ioctl.h>
38 #include <media/v4l2-mem2mem.h>
39 #include <media/videobuf2-v4l2.h>
40 #include <media/videobuf2-dma-contig.h>
41 #include <media/videobuf2-vmalloc.h>
42
43 #include "coda.h"
44 #include "imx-vdoa.h"
45
46 #define CODA_NAME               "coda"
47
48 #define CODADX6_MAX_INSTANCES   4
49 #define CODA_MAX_FORMATS        4
50
51 #define CODA_ISRAM_SIZE (2048 * 2)
52
53 #define MIN_W 176
54 #define MIN_H 144
55
56 #define S_ALIGN         1 /* multiple of 2 */
57 #define W_ALIGN         1 /* multiple of 2 */
58 #define H_ALIGN         1 /* multiple of 2 */
59
60 #define fh_to_ctx(__fh) container_of(__fh, struct coda_ctx, fh)
61
62 int coda_debug;
63 module_param(coda_debug, int, 0644);
64 MODULE_PARM_DESC(coda_debug, "Debug level (0-2)");
65
66 static int disable_tiling;
67 module_param(disable_tiling, int, 0644);
68 MODULE_PARM_DESC(disable_tiling, "Disable tiled frame buffers");
69
70 static int disable_vdoa;
71 module_param(disable_vdoa, int, 0644);
72 MODULE_PARM_DESC(disable_vdoa, "Disable Video Data Order Adapter tiled to raster-scan conversion");
73
74 static int enable_bwb = 0;
75 module_param(enable_bwb, int, 0644);
76 MODULE_PARM_DESC(enable_bwb, "Enable BWB unit for decoding, may crash on certain streams");
77
78 void coda_write(struct coda_dev *dev, u32 data, u32 reg)
79 {
80         v4l2_dbg(2, coda_debug, &dev->v4l2_dev,
81                  "%s: data=0x%x, reg=0x%x\n", __func__, data, reg);
82         writel(data, dev->regs_base + reg);
83 }
84
85 unsigned int coda_read(struct coda_dev *dev, u32 reg)
86 {
87         u32 data;
88
89         data = readl(dev->regs_base + reg);
90         v4l2_dbg(2, coda_debug, &dev->v4l2_dev,
91                  "%s: data=0x%x, reg=0x%x\n", __func__, data, reg);
92         return data;
93 }
94
95 void coda_write_base(struct coda_ctx *ctx, struct coda_q_data *q_data,
96                      struct vb2_v4l2_buffer *buf, unsigned int reg_y)
97 {
98         u32 base_y = vb2_dma_contig_plane_dma_addr(&buf->vb2_buf, 0);
99         u32 base_cb, base_cr;
100
101         switch (q_data->fourcc) {
102         case V4L2_PIX_FMT_YUYV:
103                 /* Fallthrough: IN -H264-> CODA -NV12 MB-> VDOA -YUYV-> OUT */
104         case V4L2_PIX_FMT_NV12:
105         case V4L2_PIX_FMT_YUV420:
106         default:
107                 base_cb = base_y + q_data->bytesperline * q_data->height;
108                 base_cr = base_cb + q_data->bytesperline * q_data->height / 4;
109                 break;
110         case V4L2_PIX_FMT_YVU420:
111                 /* Switch Cb and Cr for YVU420 format */
112                 base_cr = base_y + q_data->bytesperline * q_data->height;
113                 base_cb = base_cr + q_data->bytesperline * q_data->height / 4;
114                 break;
115         case V4L2_PIX_FMT_YUV422P:
116                 base_cb = base_y + q_data->bytesperline * q_data->height;
117                 base_cr = base_cb + q_data->bytesperline * q_data->height / 2;
118         }
119
120         coda_write(ctx->dev, base_y, reg_y);
121         coda_write(ctx->dev, base_cb, reg_y + 4);
122         coda_write(ctx->dev, base_cr, reg_y + 8);
123 }
124
125 #define CODA_CODEC(mode, src_fourcc, dst_fourcc, max_w, max_h) \
126         { mode, src_fourcc, dst_fourcc, max_w, max_h }
127
128 /*
129  * Arrays of codecs supported by each given version of Coda:
130  *  i.MX27 -> codadx6
131  *  i.MX5x -> coda7
132  *  i.MX6  -> coda960
133  * Use V4L2_PIX_FMT_YUV420 as placeholder for all supported YUV 4:2:0 variants
134  */
135 static const struct coda_codec codadx6_codecs[] = {
136         CODA_CODEC(CODADX6_MODE_ENCODE_H264, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_H264,  720, 576),
137         CODA_CODEC(CODADX6_MODE_ENCODE_MP4,  V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_MPEG4, 720, 576),
138 };
139
140 static const struct coda_codec coda7_codecs[] = {
141         CODA_CODEC(CODA7_MODE_ENCODE_H264, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_H264,   1280, 720),
142         CODA_CODEC(CODA7_MODE_ENCODE_MP4,  V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_MPEG4,  1280, 720),
143         CODA_CODEC(CODA7_MODE_ENCODE_MJPG, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_JPEG,   8192, 8192),
144         CODA_CODEC(CODA7_MODE_DECODE_H264, V4L2_PIX_FMT_H264,   V4L2_PIX_FMT_YUV420, 1920, 1088),
145         CODA_CODEC(CODA7_MODE_DECODE_MP2,  V4L2_PIX_FMT_MPEG2,  V4L2_PIX_FMT_YUV420, 1920, 1088),
146         CODA_CODEC(CODA7_MODE_DECODE_MP4,  V4L2_PIX_FMT_MPEG4,  V4L2_PIX_FMT_YUV420, 1920, 1088),
147         CODA_CODEC(CODA7_MODE_DECODE_MJPG, V4L2_PIX_FMT_JPEG,   V4L2_PIX_FMT_YUV420, 8192, 8192),
148 };
149
150 static const struct coda_codec coda9_codecs[] = {
151         CODA_CODEC(CODA9_MODE_ENCODE_H264, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_H264,   1920, 1088),
152         CODA_CODEC(CODA9_MODE_ENCODE_MP4,  V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_MPEG4,  1920, 1088),
153         CODA_CODEC(CODA9_MODE_DECODE_H264, V4L2_PIX_FMT_H264,   V4L2_PIX_FMT_YUV420, 1920, 1088),
154         CODA_CODEC(CODA9_MODE_DECODE_MP2,  V4L2_PIX_FMT_MPEG2,  V4L2_PIX_FMT_YUV420, 1920, 1088),
155         CODA_CODEC(CODA9_MODE_DECODE_MP4,  V4L2_PIX_FMT_MPEG4,  V4L2_PIX_FMT_YUV420, 1920, 1088),
156 };
157
158 struct coda_video_device {
159         const char *name;
160         enum coda_inst_type type;
161         const struct coda_context_ops *ops;
162         bool direct;
163         u32 src_formats[CODA_MAX_FORMATS];
164         u32 dst_formats[CODA_MAX_FORMATS];
165 };
166
167 static const struct coda_video_device coda_bit_encoder = {
168         .name = "coda-encoder",
169         .type = CODA_INST_ENCODER,
170         .ops = &coda_bit_encode_ops,
171         .src_formats = {
172                 V4L2_PIX_FMT_NV12,
173                 V4L2_PIX_FMT_YUV420,
174                 V4L2_PIX_FMT_YVU420,
175         },
176         .dst_formats = {
177                 V4L2_PIX_FMT_H264,
178                 V4L2_PIX_FMT_MPEG4,
179         },
180 };
181
182 static const struct coda_video_device coda_bit_jpeg_encoder = {
183         .name = "coda-jpeg-encoder",
184         .type = CODA_INST_ENCODER,
185         .ops = &coda_bit_encode_ops,
186         .src_formats = {
187                 V4L2_PIX_FMT_NV12,
188                 V4L2_PIX_FMT_YUV420,
189                 V4L2_PIX_FMT_YVU420,
190                 V4L2_PIX_FMT_YUV422P,
191         },
192         .dst_formats = {
193                 V4L2_PIX_FMT_JPEG,
194         },
195 };
196
197 static const struct coda_video_device coda_bit_decoder = {
198         .name = "coda-decoder",
199         .type = CODA_INST_DECODER,
200         .ops = &coda_bit_decode_ops,
201         .src_formats = {
202                 V4L2_PIX_FMT_H264,
203                 V4L2_PIX_FMT_MPEG2,
204                 V4L2_PIX_FMT_MPEG4,
205         },
206         .dst_formats = {
207                 V4L2_PIX_FMT_NV12,
208                 V4L2_PIX_FMT_YUV420,
209                 V4L2_PIX_FMT_YVU420,
210                 /*
211                  * If V4L2_PIX_FMT_YUYV should be default,
212                  * set_default_params() must be adjusted.
213                  */
214                 V4L2_PIX_FMT_YUYV,
215         },
216 };
217
218 static const struct coda_video_device coda_bit_jpeg_decoder = {
219         .name = "coda-jpeg-decoder",
220         .type = CODA_INST_DECODER,
221         .ops = &coda_bit_decode_ops,
222         .src_formats = {
223                 V4L2_PIX_FMT_JPEG,
224         },
225         .dst_formats = {
226                 V4L2_PIX_FMT_NV12,
227                 V4L2_PIX_FMT_YUV420,
228                 V4L2_PIX_FMT_YVU420,
229                 V4L2_PIX_FMT_YUV422P,
230         },
231 };
232
233 static const struct coda_video_device *codadx6_video_devices[] = {
234         &coda_bit_encoder,
235 };
236
237 static const struct coda_video_device *coda7_video_devices[] = {
238         &coda_bit_jpeg_encoder,
239         &coda_bit_jpeg_decoder,
240         &coda_bit_encoder,
241         &coda_bit_decoder,
242 };
243
244 static const struct coda_video_device *coda9_video_devices[] = {
245         &coda_bit_encoder,
246         &coda_bit_decoder,
247 };
248
249 /*
250  * Normalize all supported YUV 4:2:0 formats to the value used in the codec
251  * tables.
252  */
253 static u32 coda_format_normalize_yuv(u32 fourcc)
254 {
255         switch (fourcc) {
256         case V4L2_PIX_FMT_NV12:
257         case V4L2_PIX_FMT_YUV420:
258         case V4L2_PIX_FMT_YVU420:
259         case V4L2_PIX_FMT_YUV422P:
260         case V4L2_PIX_FMT_YUYV:
261                 return V4L2_PIX_FMT_YUV420;
262         default:
263                 return fourcc;
264         }
265 }
266
267 static const struct coda_codec *coda_find_codec(struct coda_dev *dev,
268                                                 int src_fourcc, int dst_fourcc)
269 {
270         const struct coda_codec *codecs = dev->devtype->codecs;
271         int num_codecs = dev->devtype->num_codecs;
272         int k;
273
274         src_fourcc = coda_format_normalize_yuv(src_fourcc);
275         dst_fourcc = coda_format_normalize_yuv(dst_fourcc);
276         if (src_fourcc == dst_fourcc)
277                 return NULL;
278
279         for (k = 0; k < num_codecs; k++) {
280                 if (codecs[k].src_fourcc == src_fourcc &&
281                     codecs[k].dst_fourcc == dst_fourcc)
282                         break;
283         }
284
285         if (k == num_codecs)
286                 return NULL;
287
288         return &codecs[k];
289 }
290
291 static void coda_get_max_dimensions(struct coda_dev *dev,
292                                     const struct coda_codec *codec,
293                                     int *max_w, int *max_h)
294 {
295         const struct coda_codec *codecs = dev->devtype->codecs;
296         int num_codecs = dev->devtype->num_codecs;
297         unsigned int w, h;
298         int k;
299
300         if (codec) {
301                 w = codec->max_w;
302                 h = codec->max_h;
303         } else {
304                 for (k = 0, w = 0, h = 0; k < num_codecs; k++) {
305                         w = max(w, codecs[k].max_w);
306                         h = max(h, codecs[k].max_h);
307                 }
308         }
309
310         if (max_w)
311                 *max_w = w;
312         if (max_h)
313                 *max_h = h;
314 }
315
316 static const struct coda_video_device *to_coda_video_device(struct video_device
317                                                             *vdev)
318 {
319         struct coda_dev *dev = video_get_drvdata(vdev);
320         unsigned int i = vdev - dev->vfd;
321
322         if (i >= dev->devtype->num_vdevs)
323                 return NULL;
324
325         return dev->devtype->vdevs[i];
326 }
327
328 const char *coda_product_name(int product)
329 {
330         static char buf[9];
331
332         switch (product) {
333         case CODA_DX6:
334                 return "CodaDx6";
335         case CODA_7541:
336                 return "CODA7541";
337         case CODA_960:
338                 return "CODA960";
339         default:
340                 snprintf(buf, sizeof(buf), "(0x%04x)", product);
341                 return buf;
342         }
343 }
344
345 static struct vdoa_data *coda_get_vdoa_data(void)
346 {
347         struct device_node *vdoa_node;
348         struct platform_device *vdoa_pdev;
349         struct vdoa_data *vdoa_data = NULL;
350
351         vdoa_node = of_find_compatible_node(NULL, NULL, "fsl,imx6q-vdoa");
352         if (!vdoa_node)
353                 return NULL;
354
355         vdoa_pdev = of_find_device_by_node(vdoa_node);
356         if (!vdoa_pdev)
357                 goto out;
358
359         vdoa_data = platform_get_drvdata(vdoa_pdev);
360         if (!vdoa_data)
361                 vdoa_data = ERR_PTR(-EPROBE_DEFER);
362
363         put_device(&vdoa_pdev->dev);
364 out:
365         if (vdoa_node)
366                 of_node_put(vdoa_node);
367
368         return vdoa_data;
369 }
370
371 /*
372  * V4L2 ioctl() operations.
373  */
374 static int coda_querycap(struct file *file, void *priv,
375                          struct v4l2_capability *cap)
376 {
377         struct coda_ctx *ctx = fh_to_ctx(priv);
378
379         strlcpy(cap->driver, CODA_NAME, sizeof(cap->driver));
380         strlcpy(cap->card, coda_product_name(ctx->dev->devtype->product),
381                 sizeof(cap->card));
382         strlcpy(cap->bus_info, "platform:" CODA_NAME, sizeof(cap->bus_info));
383         cap->device_caps = V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
384         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
385
386         return 0;
387 }
388
389 static int coda_enum_fmt(struct file *file, void *priv,
390                          struct v4l2_fmtdesc *f)
391 {
392         struct video_device *vdev = video_devdata(file);
393         const struct coda_video_device *cvd = to_coda_video_device(vdev);
394         struct coda_ctx *ctx = fh_to_ctx(priv);
395         const u32 *formats;
396
397         if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
398                 formats = cvd->src_formats;
399         else if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
400                 formats = cvd->dst_formats;
401         else
402                 return -EINVAL;
403
404         if (f->index >= CODA_MAX_FORMATS || formats[f->index] == 0)
405                 return -EINVAL;
406
407         /* Skip YUYV if the vdoa is not available */
408         if (!ctx->vdoa && f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
409             formats[f->index] == V4L2_PIX_FMT_YUYV)
410                 return -EINVAL;
411
412         f->pixelformat = formats[f->index];
413
414         return 0;
415 }
416
417 static int coda_g_fmt(struct file *file, void *priv,
418                       struct v4l2_format *f)
419 {
420         struct coda_q_data *q_data;
421         struct coda_ctx *ctx = fh_to_ctx(priv);
422
423         q_data = get_q_data(ctx, f->type);
424         if (!q_data)
425                 return -EINVAL;
426
427         f->fmt.pix.field        = V4L2_FIELD_NONE;
428         f->fmt.pix.pixelformat  = q_data->fourcc;
429         f->fmt.pix.width        = q_data->width;
430         f->fmt.pix.height       = q_data->height;
431         f->fmt.pix.bytesperline = q_data->bytesperline;
432
433         f->fmt.pix.sizeimage    = q_data->sizeimage;
434         f->fmt.pix.colorspace   = ctx->colorspace;
435         f->fmt.pix.xfer_func    = ctx->xfer_func;
436         f->fmt.pix.ycbcr_enc    = ctx->ycbcr_enc;
437         f->fmt.pix.quantization = ctx->quantization;
438
439         return 0;
440 }
441
442 static int coda_try_pixelformat(struct coda_ctx *ctx, struct v4l2_format *f)
443 {
444         struct coda_q_data *q_data;
445         const u32 *formats;
446         int i;
447
448         if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
449                 formats = ctx->cvd->src_formats;
450         else if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
451                 formats = ctx->cvd->dst_formats;
452         else
453                 return -EINVAL;
454
455         for (i = 0; i < CODA_MAX_FORMATS; i++) {
456                 /* Skip YUYV if the vdoa is not available */
457                 if (!ctx->vdoa && f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
458                     formats[i] == V4L2_PIX_FMT_YUYV)
459                         continue;
460
461                 if (formats[i] == f->fmt.pix.pixelformat) {
462                         f->fmt.pix.pixelformat = formats[i];
463                         return 0;
464                 }
465         }
466
467         /* Fall back to currently set pixelformat */
468         q_data = get_q_data(ctx, f->type);
469         f->fmt.pix.pixelformat = q_data->fourcc;
470
471         return 0;
472 }
473
474 static int coda_try_fmt_vdoa(struct coda_ctx *ctx, struct v4l2_format *f,
475                              bool *use_vdoa)
476 {
477         int err;
478
479         if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
480                 return -EINVAL;
481
482         if (!use_vdoa)
483                 return -EINVAL;
484
485         if (!ctx->vdoa) {
486                 *use_vdoa = false;
487                 return 0;
488         }
489
490         err = vdoa_context_configure(NULL, f->fmt.pix.width, f->fmt.pix.height,
491                                      f->fmt.pix.pixelformat);
492         if (err) {
493                 *use_vdoa = false;
494                 return 0;
495         }
496
497         *use_vdoa = true;
498         return 0;
499 }
500
501 static unsigned int coda_estimate_sizeimage(struct coda_ctx *ctx, u32 sizeimage,
502                                             u32 width, u32 height)
503 {
504         /*
505          * This is a rough estimate for sensible compressed buffer
506          * sizes (between 1 and 16 bits per pixel). This could be
507          * improved by better format specific worst case estimates.
508          */
509         return round_up(clamp(sizeimage, width * height / 8,
510                                          width * height * 2), PAGE_SIZE);
511 }
512
513 static int coda_try_fmt(struct coda_ctx *ctx, const struct coda_codec *codec,
514                         struct v4l2_format *f)
515 {
516         struct coda_dev *dev = ctx->dev;
517         unsigned int max_w, max_h;
518         enum v4l2_field field;
519
520         field = f->fmt.pix.field;
521         if (field == V4L2_FIELD_ANY)
522                 field = V4L2_FIELD_NONE;
523         else if (V4L2_FIELD_NONE != field)
524                 return -EINVAL;
525
526         /* V4L2 specification suggests the driver corrects the format struct
527          * if any of the dimensions is unsupported */
528         f->fmt.pix.field = field;
529
530         coda_get_max_dimensions(dev, codec, &max_w, &max_h);
531         v4l_bound_align_image(&f->fmt.pix.width, MIN_W, max_w, W_ALIGN,
532                               &f->fmt.pix.height, MIN_H, max_h, H_ALIGN,
533                               S_ALIGN);
534
535         switch (f->fmt.pix.pixelformat) {
536         case V4L2_PIX_FMT_NV12:
537         case V4L2_PIX_FMT_YUV420:
538         case V4L2_PIX_FMT_YVU420:
539                 /*
540                  * Frame stride must be at least multiple of 8,
541                  * but multiple of 16 for h.264 or JPEG 4:2:x
542                  */
543                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16);
544                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
545                                         f->fmt.pix.height * 3 / 2;
546                 break;
547         case V4L2_PIX_FMT_YUYV:
548                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16) * 2;
549                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
550                                         f->fmt.pix.height;
551                 break;
552         case V4L2_PIX_FMT_YUV422P:
553                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16);
554                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
555                                         f->fmt.pix.height * 2;
556                 break;
557         case V4L2_PIX_FMT_JPEG:
558                 f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
559                 /* fallthrough */
560         case V4L2_PIX_FMT_H264:
561         case V4L2_PIX_FMT_MPEG4:
562         case V4L2_PIX_FMT_MPEG2:
563                 f->fmt.pix.bytesperline = 0;
564                 f->fmt.pix.sizeimage = coda_estimate_sizeimage(ctx,
565                                                         f->fmt.pix.sizeimage,
566                                                         f->fmt.pix.width,
567                                                         f->fmt.pix.height);
568                 break;
569         default:
570                 BUG();
571         }
572
573         return 0;
574 }
575
576 static int coda_try_fmt_vid_cap(struct file *file, void *priv,
577                                 struct v4l2_format *f)
578 {
579         struct coda_ctx *ctx = fh_to_ctx(priv);
580         const struct coda_q_data *q_data_src;
581         const struct coda_codec *codec;
582         struct vb2_queue *src_vq;
583         int ret;
584         bool use_vdoa;
585
586         ret = coda_try_pixelformat(ctx, f);
587         if (ret < 0)
588                 return ret;
589
590         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
591
592         /*
593          * If the source format is already fixed, only allow the same output
594          * resolution
595          */
596         src_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
597         if (vb2_is_streaming(src_vq)) {
598                 f->fmt.pix.width = q_data_src->width;
599                 f->fmt.pix.height = q_data_src->height;
600         }
601
602         f->fmt.pix.colorspace = ctx->colorspace;
603         f->fmt.pix.xfer_func = ctx->xfer_func;
604         f->fmt.pix.ycbcr_enc = ctx->ycbcr_enc;
605         f->fmt.pix.quantization = ctx->quantization;
606
607         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
608         codec = coda_find_codec(ctx->dev, q_data_src->fourcc,
609                                 f->fmt.pix.pixelformat);
610         if (!codec)
611                 return -EINVAL;
612
613         ret = coda_try_fmt(ctx, codec, f);
614         if (ret < 0)
615                 return ret;
616
617         /* The h.264 decoder only returns complete 16x16 macroblocks */
618         if (codec && codec->src_fourcc == V4L2_PIX_FMT_H264) {
619                 f->fmt.pix.height = round_up(f->fmt.pix.height, 16);
620                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16);
621                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
622                                        f->fmt.pix.height * 3 / 2;
623
624                 ret = coda_try_fmt_vdoa(ctx, f, &use_vdoa);
625                 if (ret < 0)
626                         return ret;
627
628                 if (f->fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) {
629                         if (!use_vdoa)
630                                 return -EINVAL;
631
632                         f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16) * 2;
633                         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
634                                 f->fmt.pix.height;
635                 }
636         }
637
638         return 0;
639 }
640
641 static void coda_set_default_colorspace(struct v4l2_pix_format *fmt)
642 {
643         enum v4l2_colorspace colorspace;
644
645         if (fmt->pixelformat == V4L2_PIX_FMT_JPEG)
646                 colorspace = V4L2_COLORSPACE_JPEG;
647         else if (fmt->width <= 720 && fmt->height <= 576)
648                 colorspace = V4L2_COLORSPACE_SMPTE170M;
649         else
650                 colorspace = V4L2_COLORSPACE_REC709;
651
652         fmt->colorspace = colorspace;
653         fmt->xfer_func = V4L2_XFER_FUNC_DEFAULT;
654         fmt->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
655         fmt->quantization = V4L2_QUANTIZATION_DEFAULT;
656 }
657
658 static int coda_try_fmt_vid_out(struct file *file, void *priv,
659                                 struct v4l2_format *f)
660 {
661         struct coda_ctx *ctx = fh_to_ctx(priv);
662         struct coda_dev *dev = ctx->dev;
663         const struct coda_q_data *q_data_dst;
664         const struct coda_codec *codec;
665         int ret;
666
667         ret = coda_try_pixelformat(ctx, f);
668         if (ret < 0)
669                 return ret;
670
671         if (f->fmt.pix.colorspace == V4L2_COLORSPACE_DEFAULT)
672                 coda_set_default_colorspace(&f->fmt.pix);
673
674         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
675         codec = coda_find_codec(dev, f->fmt.pix.pixelformat, q_data_dst->fourcc);
676
677         return coda_try_fmt(ctx, codec, f);
678 }
679
680 static int coda_s_fmt(struct coda_ctx *ctx, struct v4l2_format *f,
681                       struct v4l2_rect *r)
682 {
683         struct coda_q_data *q_data;
684         struct vb2_queue *vq;
685
686         vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type);
687         if (!vq)
688                 return -EINVAL;
689
690         q_data = get_q_data(ctx, f->type);
691         if (!q_data)
692                 return -EINVAL;
693
694         if (vb2_is_busy(vq)) {
695                 v4l2_err(&ctx->dev->v4l2_dev, "%s queue busy\n", __func__);
696                 return -EBUSY;
697         }
698
699         q_data->fourcc = f->fmt.pix.pixelformat;
700         q_data->width = f->fmt.pix.width;
701         q_data->height = f->fmt.pix.height;
702         q_data->bytesperline = f->fmt.pix.bytesperline;
703         q_data->sizeimage = f->fmt.pix.sizeimage;
704         if (r) {
705                 q_data->rect = *r;
706         } else {
707                 q_data->rect.left = 0;
708                 q_data->rect.top = 0;
709                 q_data->rect.width = f->fmt.pix.width;
710                 q_data->rect.height = f->fmt.pix.height;
711         }
712
713         switch (f->fmt.pix.pixelformat) {
714         case V4L2_PIX_FMT_YUYV:
715                 ctx->tiled_map_type = GDI_TILED_FRAME_MB_RASTER_MAP;
716                 break;
717         case V4L2_PIX_FMT_NV12:
718                 if (!disable_tiling) {
719                         ctx->tiled_map_type = GDI_TILED_FRAME_MB_RASTER_MAP;
720                         break;
721                 }
722                 /* else fall through */
723         case V4L2_PIX_FMT_YUV420:
724         case V4L2_PIX_FMT_YVU420:
725                 ctx->tiled_map_type = GDI_LINEAR_FRAME_MAP;
726                 break;
727         default:
728                 break;
729         }
730
731         if (ctx->tiled_map_type == GDI_TILED_FRAME_MB_RASTER_MAP &&
732             !coda_try_fmt_vdoa(ctx, f, &ctx->use_vdoa) &&
733             ctx->use_vdoa)
734                 vdoa_context_configure(ctx->vdoa, f->fmt.pix.width,
735                                        f->fmt.pix.height,
736                                        f->fmt.pix.pixelformat);
737         else
738                 ctx->use_vdoa = false;
739
740         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
741                 "Setting format for type %d, wxh: %dx%d, fmt: %4.4s %c\n",
742                 f->type, q_data->width, q_data->height,
743                 (char *)&q_data->fourcc,
744                 (ctx->tiled_map_type == GDI_LINEAR_FRAME_MAP) ? 'L' : 'T');
745
746         return 0;
747 }
748
749 static int coda_s_fmt_vid_cap(struct file *file, void *priv,
750                               struct v4l2_format *f)
751 {
752         struct coda_ctx *ctx = fh_to_ctx(priv);
753         struct coda_q_data *q_data_src;
754         struct v4l2_rect r;
755         int ret;
756
757         ret = coda_try_fmt_vid_cap(file, priv, f);
758         if (ret)
759                 return ret;
760
761         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
762         r.left = 0;
763         r.top = 0;
764         r.width = q_data_src->width;
765         r.height = q_data_src->height;
766
767         return coda_s_fmt(ctx, f, &r);
768 }
769
770 static int coda_s_fmt_vid_out(struct file *file, void *priv,
771                               struct v4l2_format *f)
772 {
773         struct coda_ctx *ctx = fh_to_ctx(priv);
774         struct coda_q_data *q_data_src;
775         struct v4l2_format f_cap;
776         struct v4l2_rect r;
777         int ret;
778
779         ret = coda_try_fmt_vid_out(file, priv, f);
780         if (ret)
781                 return ret;
782
783         ret = coda_s_fmt(ctx, f, NULL);
784         if (ret)
785                 return ret;
786
787         ctx->colorspace = f->fmt.pix.colorspace;
788         ctx->xfer_func = f->fmt.pix.xfer_func;
789         ctx->ycbcr_enc = f->fmt.pix.ycbcr_enc;
790         ctx->quantization = f->fmt.pix.quantization;
791
792         memset(&f_cap, 0, sizeof(f_cap));
793         f_cap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
794         coda_g_fmt(file, priv, &f_cap);
795         f_cap.fmt.pix.width = f->fmt.pix.width;
796         f_cap.fmt.pix.height = f->fmt.pix.height;
797
798         ret = coda_try_fmt_vid_cap(file, priv, &f_cap);
799         if (ret)
800                 return ret;
801
802         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
803         r.left = 0;
804         r.top = 0;
805         r.width = q_data_src->width;
806         r.height = q_data_src->height;
807
808         return coda_s_fmt(ctx, &f_cap, &r);
809 }
810
811 static int coda_reqbufs(struct file *file, void *priv,
812                         struct v4l2_requestbuffers *rb)
813 {
814         struct coda_ctx *ctx = fh_to_ctx(priv);
815         int ret;
816
817         ret = v4l2_m2m_reqbufs(file, ctx->fh.m2m_ctx, rb);
818         if (ret)
819                 return ret;
820
821         /*
822          * Allow to allocate instance specific per-context buffers, such as
823          * bitstream ringbuffer, slice buffer, work buffer, etc. if needed.
824          */
825         if (rb->type == V4L2_BUF_TYPE_VIDEO_OUTPUT && ctx->ops->reqbufs)
826                 return ctx->ops->reqbufs(ctx, rb);
827
828         return 0;
829 }
830
831 static int coda_qbuf(struct file *file, void *priv,
832                      struct v4l2_buffer *buf)
833 {
834         struct coda_ctx *ctx = fh_to_ctx(priv);
835
836         return v4l2_m2m_qbuf(file, ctx->fh.m2m_ctx, buf);
837 }
838
839 static bool coda_buf_is_end_of_stream(struct coda_ctx *ctx,
840                                       struct vb2_v4l2_buffer *buf)
841 {
842         return ((ctx->bit_stream_param & CODA_BIT_STREAM_END_FLAG) &&
843                 (buf->sequence == (ctx->qsequence - 1)));
844 }
845
846 void coda_m2m_buf_done(struct coda_ctx *ctx, struct vb2_v4l2_buffer *buf,
847                        enum vb2_buffer_state state)
848 {
849         const struct v4l2_event eos_event = {
850                 .type = V4L2_EVENT_EOS
851         };
852
853         if (coda_buf_is_end_of_stream(ctx, buf)) {
854                 buf->flags |= V4L2_BUF_FLAG_LAST;
855
856                 v4l2_event_queue_fh(&ctx->fh, &eos_event);
857         }
858
859         v4l2_m2m_buf_done(buf, state);
860 }
861
862 static int coda_g_selection(struct file *file, void *fh,
863                             struct v4l2_selection *s)
864 {
865         struct coda_ctx *ctx = fh_to_ctx(fh);
866         struct coda_q_data *q_data;
867         struct v4l2_rect r, *rsel;
868
869         q_data = get_q_data(ctx, s->type);
870         if (!q_data)
871                 return -EINVAL;
872
873         r.left = 0;
874         r.top = 0;
875         r.width = q_data->width;
876         r.height = q_data->height;
877         rsel = &q_data->rect;
878
879         switch (s->target) {
880         case V4L2_SEL_TGT_CROP_DEFAULT:
881         case V4L2_SEL_TGT_CROP_BOUNDS:
882                 rsel = &r;
883                 /* fallthrough */
884         case V4L2_SEL_TGT_CROP:
885                 if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
886                         return -EINVAL;
887                 break;
888         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
889         case V4L2_SEL_TGT_COMPOSE_PADDED:
890                 rsel = &r;
891                 /* fallthrough */
892         case V4L2_SEL_TGT_COMPOSE:
893         case V4L2_SEL_TGT_COMPOSE_DEFAULT:
894                 if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
895                         return -EINVAL;
896                 break;
897         default:
898                 return -EINVAL;
899         }
900
901         s->r = *rsel;
902
903         return 0;
904 }
905
906 static int coda_try_encoder_cmd(struct file *file, void *fh,
907                                 struct v4l2_encoder_cmd *ec)
908 {
909         if (ec->cmd != V4L2_ENC_CMD_STOP)
910                 return -EINVAL;
911
912         if (ec->flags & V4L2_ENC_CMD_STOP_AT_GOP_END)
913                 return -EINVAL;
914
915         return 0;
916 }
917
918 static int coda_encoder_cmd(struct file *file, void *fh,
919                             struct v4l2_encoder_cmd *ec)
920 {
921         struct coda_ctx *ctx = fh_to_ctx(fh);
922         struct vb2_queue *dst_vq;
923         int ret;
924
925         ret = coda_try_encoder_cmd(file, fh, ec);
926         if (ret < 0)
927                 return ret;
928
929         /* Ignore encoder stop command silently in decoder context */
930         if (ctx->inst_type != CODA_INST_ENCODER)
931                 return 0;
932
933         /* Set the stream-end flag on this context */
934         ctx->bit_stream_param |= CODA_BIT_STREAM_END_FLAG;
935
936         flush_work(&ctx->pic_run_work);
937
938         /* If there is no buffer in flight, wake up */
939         if (!ctx->streamon_out || ctx->qsequence == ctx->osequence) {
940                 dst_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx,
941                                          V4L2_BUF_TYPE_VIDEO_CAPTURE);
942                 dst_vq->last_buffer_dequeued = true;
943                 wake_up(&dst_vq->done_wq);
944         }
945
946         return 0;
947 }
948
949 static int coda_try_decoder_cmd(struct file *file, void *fh,
950                                 struct v4l2_decoder_cmd *dc)
951 {
952         if (dc->cmd != V4L2_DEC_CMD_STOP)
953                 return -EINVAL;
954
955         if (dc->flags & V4L2_DEC_CMD_STOP_TO_BLACK)
956                 return -EINVAL;
957
958         if (!(dc->flags & V4L2_DEC_CMD_STOP_IMMEDIATELY) && (dc->stop.pts != 0))
959                 return -EINVAL;
960
961         return 0;
962 }
963
964 static int coda_decoder_cmd(struct file *file, void *fh,
965                             struct v4l2_decoder_cmd *dc)
966 {
967         struct coda_ctx *ctx = fh_to_ctx(fh);
968         int ret;
969
970         ret = coda_try_decoder_cmd(file, fh, dc);
971         if (ret < 0)
972                 return ret;
973
974         /* Ignore decoder stop command silently in encoder context */
975         if (ctx->inst_type != CODA_INST_DECODER)
976                 return 0;
977
978         /* Set the stream-end flag on this context */
979         coda_bit_stream_end_flag(ctx);
980         ctx->hold = false;
981         v4l2_m2m_try_schedule(ctx->fh.m2m_ctx);
982
983         return 0;
984 }
985
986 static int coda_g_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
987 {
988         struct coda_ctx *ctx = fh_to_ctx(fh);
989         struct v4l2_fract *tpf;
990
991         if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
992                 return -EINVAL;
993
994         a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
995         tpf = &a->parm.output.timeperframe;
996         tpf->denominator = ctx->params.framerate & CODA_FRATE_RES_MASK;
997         tpf->numerator = 1 + (ctx->params.framerate >>
998                               CODA_FRATE_DIV_OFFSET);
999
1000         return 0;
1001 }
1002
1003 /*
1004  * Approximate timeperframe v4l2_fract with values that can be written
1005  * into the 16-bit CODA_FRATE_DIV and CODA_FRATE_RES fields.
1006  */
1007 static void coda_approximate_timeperframe(struct v4l2_fract *timeperframe)
1008 {
1009         struct v4l2_fract s = *timeperframe;
1010         struct v4l2_fract f0;
1011         struct v4l2_fract f1 = { 1, 0 };
1012         struct v4l2_fract f2 = { 0, 1 };
1013         unsigned int i, div, s_denominator;
1014
1015         /* Lower bound is 1/65535 */
1016         if (s.numerator == 0 || s.denominator / s.numerator > 65535) {
1017                 timeperframe->numerator = 1;
1018                 timeperframe->denominator = 65535;
1019                 return;
1020         }
1021
1022         /* Upper bound is 65536/1, map everything above to infinity */
1023         if (s.denominator == 0 || s.numerator / s.denominator > 65536) {
1024                 timeperframe->numerator = 1;
1025                 timeperframe->denominator = 0;
1026                 return;
1027         }
1028
1029         /* Reduce fraction to lowest terms */
1030         div = gcd(s.numerator, s.denominator);
1031         if (div > 1) {
1032                 s.numerator /= div;
1033                 s.denominator /= div;
1034         }
1035
1036         if (s.numerator <= 65536 && s.denominator < 65536) {
1037                 *timeperframe = s;
1038                 return;
1039         }
1040
1041         /* Find successive convergents from continued fraction expansion */
1042         while (f2.numerator <= 65536 && f2.denominator < 65536) {
1043                 f0 = f1;
1044                 f1 = f2;
1045
1046                 /* Stop when f2 exactly equals timeperframe */
1047                 if (s.numerator == 0)
1048                         break;
1049
1050                 i = s.denominator / s.numerator;
1051
1052                 f2.numerator = f0.numerator + i * f1.numerator;
1053                 f2.denominator = f0.denominator + i * f2.denominator;
1054
1055                 s_denominator = s.numerator;
1056                 s.numerator = s.denominator % s.numerator;
1057                 s.denominator = s_denominator;
1058         }
1059
1060         *timeperframe = f1;
1061 }
1062
1063 static uint32_t coda_timeperframe_to_frate(struct v4l2_fract *timeperframe)
1064 {
1065         return ((timeperframe->numerator - 1) << CODA_FRATE_DIV_OFFSET) |
1066                 timeperframe->denominator;
1067 }
1068
1069 static int coda_s_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1070 {
1071         struct coda_ctx *ctx = fh_to_ctx(fh);
1072         struct v4l2_fract *tpf;
1073
1074         if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
1075                 return -EINVAL;
1076
1077         tpf = &a->parm.output.timeperframe;
1078         coda_approximate_timeperframe(tpf);
1079         ctx->params.framerate = coda_timeperframe_to_frate(tpf);
1080
1081         return 0;
1082 }
1083
1084 static int coda_subscribe_event(struct v4l2_fh *fh,
1085                                 const struct v4l2_event_subscription *sub)
1086 {
1087         switch (sub->type) {
1088         case V4L2_EVENT_EOS:
1089                 return v4l2_event_subscribe(fh, sub, 0, NULL);
1090         default:
1091                 return v4l2_ctrl_subscribe_event(fh, sub);
1092         }
1093 }
1094
1095 static const struct v4l2_ioctl_ops coda_ioctl_ops = {
1096         .vidioc_querycap        = coda_querycap,
1097
1098         .vidioc_enum_fmt_vid_cap = coda_enum_fmt,
1099         .vidioc_g_fmt_vid_cap   = coda_g_fmt,
1100         .vidioc_try_fmt_vid_cap = coda_try_fmt_vid_cap,
1101         .vidioc_s_fmt_vid_cap   = coda_s_fmt_vid_cap,
1102
1103         .vidioc_enum_fmt_vid_out = coda_enum_fmt,
1104         .vidioc_g_fmt_vid_out   = coda_g_fmt,
1105         .vidioc_try_fmt_vid_out = coda_try_fmt_vid_out,
1106         .vidioc_s_fmt_vid_out   = coda_s_fmt_vid_out,
1107
1108         .vidioc_reqbufs         = coda_reqbufs,
1109         .vidioc_querybuf        = v4l2_m2m_ioctl_querybuf,
1110
1111         .vidioc_qbuf            = coda_qbuf,
1112         .vidioc_expbuf          = v4l2_m2m_ioctl_expbuf,
1113         .vidioc_dqbuf           = v4l2_m2m_ioctl_dqbuf,
1114         .vidioc_create_bufs     = v4l2_m2m_ioctl_create_bufs,
1115         .vidioc_prepare_buf     = v4l2_m2m_ioctl_prepare_buf,
1116
1117         .vidioc_streamon        = v4l2_m2m_ioctl_streamon,
1118         .vidioc_streamoff       = v4l2_m2m_ioctl_streamoff,
1119
1120         .vidioc_g_selection     = coda_g_selection,
1121
1122         .vidioc_try_encoder_cmd = coda_try_encoder_cmd,
1123         .vidioc_encoder_cmd     = coda_encoder_cmd,
1124         .vidioc_try_decoder_cmd = coda_try_decoder_cmd,
1125         .vidioc_decoder_cmd     = coda_decoder_cmd,
1126
1127         .vidioc_g_parm          = coda_g_parm,
1128         .vidioc_s_parm          = coda_s_parm,
1129
1130         .vidioc_subscribe_event = coda_subscribe_event,
1131         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1132 };
1133
1134 /*
1135  * Mem-to-mem operations.
1136  */
1137
1138 static void coda_device_run(void *m2m_priv)
1139 {
1140         struct coda_ctx *ctx = m2m_priv;
1141         struct coda_dev *dev = ctx->dev;
1142
1143         queue_work(dev->workqueue, &ctx->pic_run_work);
1144 }
1145
1146 static void coda_pic_run_work(struct work_struct *work)
1147 {
1148         struct coda_ctx *ctx = container_of(work, struct coda_ctx, pic_run_work);
1149         struct coda_dev *dev = ctx->dev;
1150         int ret;
1151
1152         mutex_lock(&ctx->buffer_mutex);
1153         mutex_lock(&dev->coda_mutex);
1154
1155         ret = ctx->ops->prepare_run(ctx);
1156         if (ret < 0 && ctx->inst_type == CODA_INST_DECODER) {
1157                 mutex_unlock(&dev->coda_mutex);
1158                 mutex_unlock(&ctx->buffer_mutex);
1159                 /* job_finish scheduled by prepare_decode */
1160                 return;
1161         }
1162
1163         if (!wait_for_completion_timeout(&ctx->completion,
1164                                          msecs_to_jiffies(1000))) {
1165                 dev_err(&dev->plat_dev->dev, "CODA PIC_RUN timeout\n");
1166
1167                 ctx->hold = true;
1168
1169                 coda_hw_reset(ctx);
1170
1171                 if (ctx->ops->run_timeout)
1172                         ctx->ops->run_timeout(ctx);
1173         } else if (!ctx->aborting) {
1174                 ctx->ops->finish_run(ctx);
1175         }
1176
1177         if ((ctx->aborting || (!ctx->streamon_cap && !ctx->streamon_out)) &&
1178             ctx->ops->seq_end_work)
1179                 queue_work(dev->workqueue, &ctx->seq_end_work);
1180
1181         mutex_unlock(&dev->coda_mutex);
1182         mutex_unlock(&ctx->buffer_mutex);
1183
1184         v4l2_m2m_job_finish(ctx->dev->m2m_dev, ctx->fh.m2m_ctx);
1185 }
1186
1187 static int coda_job_ready(void *m2m_priv)
1188 {
1189         struct coda_ctx *ctx = m2m_priv;
1190         int src_bufs = v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx);
1191
1192         /*
1193          * For both 'P' and 'key' frame cases 1 picture
1194          * and 1 frame are needed. In the decoder case,
1195          * the compressed frame can be in the bitstream.
1196          */
1197         if (!src_bufs && ctx->inst_type != CODA_INST_DECODER) {
1198                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1199                          "not ready: not enough video buffers.\n");
1200                 return 0;
1201         }
1202
1203         if (!v4l2_m2m_num_dst_bufs_ready(ctx->fh.m2m_ctx)) {
1204                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1205                          "not ready: not enough video capture buffers.\n");
1206                 return 0;
1207         }
1208
1209         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit) {
1210                 bool stream_end = ctx->bit_stream_param &
1211                                   CODA_BIT_STREAM_END_FLAG;
1212                 int num_metas = ctx->num_metas;
1213                 unsigned int count;
1214
1215                 count = hweight32(ctx->frm_dis_flg);
1216                 if (ctx->use_vdoa && count >= (ctx->num_internal_frames - 1)) {
1217                         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1218                                  "%d: not ready: all internal buffers in use: %d/%d (0x%x)",
1219                                  ctx->idx, count, ctx->num_internal_frames,
1220                                  ctx->frm_dis_flg);
1221                         return 0;
1222                 }
1223
1224                 if (ctx->hold && !src_bufs) {
1225                         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1226                                  "%d: not ready: on hold for more buffers.\n",
1227                                  ctx->idx);
1228                         return 0;
1229                 }
1230
1231                 if (!stream_end && (num_metas + src_bufs) < 2) {
1232                         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1233                                  "%d: not ready: need 2 buffers available (%d, %d)\n",
1234                                  ctx->idx, num_metas, src_bufs);
1235                         return 0;
1236                 }
1237
1238
1239                 if (!src_bufs && !stream_end &&
1240                     (coda_get_bitstream_payload(ctx) < 512)) {
1241                         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1242                                  "%d: not ready: not enough bitstream data (%d).\n",
1243                                  ctx->idx, coda_get_bitstream_payload(ctx));
1244                         return 0;
1245                 }
1246         }
1247
1248         if (ctx->aborting) {
1249                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1250                          "not ready: aborting\n");
1251                 return 0;
1252         }
1253
1254         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1255                         "job ready\n");
1256
1257         return 1;
1258 }
1259
1260 static void coda_job_abort(void *priv)
1261 {
1262         struct coda_ctx *ctx = priv;
1263
1264         ctx->aborting = 1;
1265
1266         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1267                  "Aborting task\n");
1268 }
1269
1270 static void coda_lock(void *m2m_priv)
1271 {
1272         struct coda_ctx *ctx = m2m_priv;
1273         struct coda_dev *pcdev = ctx->dev;
1274
1275         mutex_lock(&pcdev->dev_mutex);
1276 }
1277
1278 static void coda_unlock(void *m2m_priv)
1279 {
1280         struct coda_ctx *ctx = m2m_priv;
1281         struct coda_dev *pcdev = ctx->dev;
1282
1283         mutex_unlock(&pcdev->dev_mutex);
1284 }
1285
1286 static const struct v4l2_m2m_ops coda_m2m_ops = {
1287         .device_run     = coda_device_run,
1288         .job_ready      = coda_job_ready,
1289         .job_abort      = coda_job_abort,
1290         .lock           = coda_lock,
1291         .unlock         = coda_unlock,
1292 };
1293
1294 static void set_default_params(struct coda_ctx *ctx)
1295 {
1296         unsigned int max_w, max_h, usize, csize;
1297
1298         ctx->codec = coda_find_codec(ctx->dev, ctx->cvd->src_formats[0],
1299                                      ctx->cvd->dst_formats[0]);
1300         max_w = min(ctx->codec->max_w, 1920U);
1301         max_h = min(ctx->codec->max_h, 1088U);
1302         usize = max_w * max_h * 3 / 2;
1303         csize = coda_estimate_sizeimage(ctx, usize, max_w, max_h);
1304
1305         ctx->params.codec_mode = ctx->codec->mode;
1306         if (ctx->cvd->src_formats[0] == V4L2_PIX_FMT_JPEG)
1307                 ctx->colorspace = V4L2_COLORSPACE_JPEG;
1308         else
1309                 ctx->colorspace = V4L2_COLORSPACE_REC709;
1310         ctx->xfer_func = V4L2_XFER_FUNC_DEFAULT;
1311         ctx->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
1312         ctx->quantization = V4L2_QUANTIZATION_DEFAULT;
1313         ctx->params.framerate = 30;
1314
1315         /* Default formats for output and input queues */
1316         ctx->q_data[V4L2_M2M_SRC].fourcc = ctx->cvd->src_formats[0];
1317         ctx->q_data[V4L2_M2M_DST].fourcc = ctx->cvd->dst_formats[0];
1318         ctx->q_data[V4L2_M2M_SRC].width = max_w;
1319         ctx->q_data[V4L2_M2M_SRC].height = max_h;
1320         ctx->q_data[V4L2_M2M_DST].width = max_w;
1321         ctx->q_data[V4L2_M2M_DST].height = max_h;
1322         if (ctx->codec->src_fourcc == V4L2_PIX_FMT_YUV420) {
1323                 ctx->q_data[V4L2_M2M_SRC].bytesperline = max_w;
1324                 ctx->q_data[V4L2_M2M_SRC].sizeimage = usize;
1325                 ctx->q_data[V4L2_M2M_DST].bytesperline = 0;
1326                 ctx->q_data[V4L2_M2M_DST].sizeimage = csize;
1327         } else {
1328                 ctx->q_data[V4L2_M2M_SRC].bytesperline = 0;
1329                 ctx->q_data[V4L2_M2M_SRC].sizeimage = csize;
1330                 ctx->q_data[V4L2_M2M_DST].bytesperline = max_w;
1331                 ctx->q_data[V4L2_M2M_DST].sizeimage = usize;
1332         }
1333         ctx->q_data[V4L2_M2M_SRC].rect.width = max_w;
1334         ctx->q_data[V4L2_M2M_SRC].rect.height = max_h;
1335         ctx->q_data[V4L2_M2M_DST].rect.width = max_w;
1336         ctx->q_data[V4L2_M2M_DST].rect.height = max_h;
1337
1338         /*
1339          * Since the RBC2AXI logic only supports a single chroma plane,
1340          * macroblock tiling only works for to NV12 pixel format.
1341          */
1342         ctx->tiled_map_type = GDI_LINEAR_FRAME_MAP;
1343 }
1344
1345 /*
1346  * Queue operations
1347  */
1348 static int coda_queue_setup(struct vb2_queue *vq,
1349                                 unsigned int *nbuffers, unsigned int *nplanes,
1350                                 unsigned int sizes[], struct device *alloc_devs[])
1351 {
1352         struct coda_ctx *ctx = vb2_get_drv_priv(vq);
1353         struct coda_q_data *q_data;
1354         unsigned int size;
1355
1356         q_data = get_q_data(ctx, vq->type);
1357         size = q_data->sizeimage;
1358
1359         *nplanes = 1;
1360         sizes[0] = size;
1361
1362         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1363                  "get %d buffer(s) of size %d each.\n", *nbuffers, size);
1364
1365         return 0;
1366 }
1367
1368 static int coda_buf_prepare(struct vb2_buffer *vb)
1369 {
1370         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1371         struct coda_q_data *q_data;
1372
1373         q_data = get_q_data(ctx, vb->vb2_queue->type);
1374
1375         if (vb2_plane_size(vb, 0) < q_data->sizeimage) {
1376                 v4l2_warn(&ctx->dev->v4l2_dev,
1377                           "%s data will not fit into plane (%lu < %lu)\n",
1378                           __func__, vb2_plane_size(vb, 0),
1379                           (long)q_data->sizeimage);
1380                 return -EINVAL;
1381         }
1382
1383         return 0;
1384 }
1385
1386 static void coda_buf_queue(struct vb2_buffer *vb)
1387 {
1388         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1389         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1390         struct vb2_queue *vq = vb->vb2_queue;
1391         struct coda_q_data *q_data;
1392
1393         q_data = get_q_data(ctx, vb->vb2_queue->type);
1394
1395         /*
1396          * In the decoder case, immediately try to copy the buffer into the
1397          * bitstream ringbuffer and mark it as ready to be dequeued.
1398          */
1399         if (ctx->bitstream.size && vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1400                 /*
1401                  * For backwards compatibility, queuing an empty buffer marks
1402                  * the stream end
1403                  */
1404                 if (vb2_get_plane_payload(vb, 0) == 0)
1405                         coda_bit_stream_end_flag(ctx);
1406
1407                 if (q_data->fourcc == V4L2_PIX_FMT_H264) {
1408                         /*
1409                          * Unless already done, try to obtain profile_idc and
1410                          * level_idc from the SPS header. This allows to decide
1411                          * whether to enable reordering during sequence
1412                          * initialization.
1413                          */
1414                         if (!ctx->params.h264_profile_idc)
1415                                 coda_sps_parse_profile(ctx, vb);
1416                 }
1417
1418                 mutex_lock(&ctx->bitstream_mutex);
1419                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1420                 if (vb2_is_streaming(vb->vb2_queue))
1421                         /* This set buf->sequence = ctx->qsequence++ */
1422                         coda_fill_bitstream(ctx, NULL);
1423                 mutex_unlock(&ctx->bitstream_mutex);
1424         } else {
1425                 if (ctx->inst_type == CODA_INST_ENCODER &&
1426                     vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1427                         vbuf->sequence = ctx->qsequence++;
1428                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1429         }
1430 }
1431
1432 int coda_alloc_aux_buf(struct coda_dev *dev, struct coda_aux_buf *buf,
1433                        size_t size, const char *name, struct dentry *parent)
1434 {
1435         buf->vaddr = dma_alloc_coherent(&dev->plat_dev->dev, size, &buf->paddr,
1436                                         GFP_KERNEL);
1437         if (!buf->vaddr) {
1438                 v4l2_err(&dev->v4l2_dev,
1439                          "Failed to allocate %s buffer of size %zu\n",
1440                          name, size);
1441                 return -ENOMEM;
1442         }
1443
1444         buf->size = size;
1445
1446         if (name && parent) {
1447                 buf->blob.data = buf->vaddr;
1448                 buf->blob.size = size;
1449                 buf->dentry = debugfs_create_blob(name, 0644, parent,
1450                                                   &buf->blob);
1451                 if (!buf->dentry)
1452                         dev_warn(&dev->plat_dev->dev,
1453                                  "failed to create debugfs entry %s\n", name);
1454         }
1455
1456         return 0;
1457 }
1458
1459 void coda_free_aux_buf(struct coda_dev *dev,
1460                        struct coda_aux_buf *buf)
1461 {
1462         if (buf->vaddr) {
1463                 dma_free_coherent(&dev->plat_dev->dev, buf->size,
1464                                   buf->vaddr, buf->paddr);
1465                 buf->vaddr = NULL;
1466                 buf->size = 0;
1467                 debugfs_remove(buf->dentry);
1468                 buf->dentry = NULL;
1469         }
1470 }
1471
1472 static int coda_start_streaming(struct vb2_queue *q, unsigned int count)
1473 {
1474         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1475         struct v4l2_device *v4l2_dev = &ctx->dev->v4l2_dev;
1476         struct coda_q_data *q_data_src, *q_data_dst;
1477         struct v4l2_m2m_buffer *m2m_buf, *tmp;
1478         struct vb2_v4l2_buffer *buf;
1479         struct list_head list;
1480         int ret = 0;
1481
1482         if (count < 1)
1483                 return -EINVAL;
1484
1485         INIT_LIST_HEAD(&list);
1486
1487         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
1488         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1489                 if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit) {
1490                         /* copy the buffers that were queued before streamon */
1491                         mutex_lock(&ctx->bitstream_mutex);
1492                         coda_fill_bitstream(ctx, &list);
1493                         mutex_unlock(&ctx->bitstream_mutex);
1494
1495                         if (coda_get_bitstream_payload(ctx) < 512) {
1496                                 ret = -EINVAL;
1497                                 goto err;
1498                         }
1499                 }
1500
1501                 ctx->streamon_out = 1;
1502         } else {
1503                 ctx->streamon_cap = 1;
1504         }
1505
1506         /* Don't start the coda unless both queues are on */
1507         if (!(ctx->streamon_out && ctx->streamon_cap))
1508                 goto out;
1509
1510         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1511         if ((q_data_src->width != q_data_dst->width &&
1512              round_up(q_data_src->width, 16) != q_data_dst->width) ||
1513             (q_data_src->height != q_data_dst->height &&
1514              round_up(q_data_src->height, 16) != q_data_dst->height)) {
1515                 v4l2_err(v4l2_dev, "can't convert %dx%d to %dx%d\n",
1516                          q_data_src->width, q_data_src->height,
1517                          q_data_dst->width, q_data_dst->height);
1518                 ret = -EINVAL;
1519                 goto err;
1520         }
1521
1522         /* Allow BIT decoder device_run with no new buffers queued */
1523         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit)
1524                 v4l2_m2m_set_src_buffered(ctx->fh.m2m_ctx, true);
1525
1526         ctx->gopcounter = ctx->params.gop_size - 1;
1527
1528         ctx->codec = coda_find_codec(ctx->dev, q_data_src->fourcc,
1529                                      q_data_dst->fourcc);
1530         if (!ctx->codec) {
1531                 v4l2_err(v4l2_dev, "couldn't tell instance type.\n");
1532                 ret = -EINVAL;
1533                 goto err;
1534         }
1535
1536         if (q_data_dst->fourcc == V4L2_PIX_FMT_JPEG)
1537                 ctx->params.gop_size = 1;
1538         ctx->gopcounter = ctx->params.gop_size - 1;
1539
1540         ret = ctx->ops->start_streaming(ctx);
1541         if (ctx->inst_type == CODA_INST_DECODER) {
1542                 if (ret == -EAGAIN)
1543                         goto out;
1544         }
1545         if (ret < 0)
1546                 goto err;
1547
1548 out:
1549         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1550                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1551                         list_del(&m2m_buf->list);
1552                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_DONE);
1553                 }
1554         }
1555         return 0;
1556
1557 err:
1558         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1559                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1560                         list_del(&m2m_buf->list);
1561                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_QUEUED);
1562                 }
1563                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1564                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1565         } else {
1566                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1567                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1568         }
1569         return ret;
1570 }
1571
1572 static void coda_stop_streaming(struct vb2_queue *q)
1573 {
1574         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1575         struct coda_dev *dev = ctx->dev;
1576         struct vb2_v4l2_buffer *buf;
1577         unsigned long flags;
1578         bool stop;
1579
1580         stop = ctx->streamon_out && ctx->streamon_cap;
1581
1582         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1583                 v4l2_dbg(1, coda_debug, &dev->v4l2_dev,
1584                          "%s: output\n", __func__);
1585                 ctx->streamon_out = 0;
1586
1587                 coda_bit_stream_end_flag(ctx);
1588
1589                 ctx->qsequence = 0;
1590
1591                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1592                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1593         } else {
1594                 v4l2_dbg(1, coda_debug, &dev->v4l2_dev,
1595                          "%s: capture\n", __func__);
1596                 ctx->streamon_cap = 0;
1597
1598                 ctx->osequence = 0;
1599                 ctx->sequence_offset = 0;
1600
1601                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1602                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1603         }
1604
1605         if (stop) {
1606                 struct coda_buffer_meta *meta;
1607
1608                 if (ctx->ops->seq_end_work) {
1609                         queue_work(dev->workqueue, &ctx->seq_end_work);
1610                         flush_work(&ctx->seq_end_work);
1611                 }
1612                 spin_lock_irqsave(&ctx->buffer_meta_lock, flags);
1613                 while (!list_empty(&ctx->buffer_meta_list)) {
1614                         meta = list_first_entry(&ctx->buffer_meta_list,
1615                                                 struct coda_buffer_meta, list);
1616                         list_del(&meta->list);
1617                         kfree(meta);
1618                 }
1619                 ctx->num_metas = 0;
1620                 spin_unlock_irqrestore(&ctx->buffer_meta_lock, flags);
1621                 kfifo_init(&ctx->bitstream_fifo,
1622                         ctx->bitstream.vaddr, ctx->bitstream.size);
1623                 ctx->runcounter = 0;
1624                 ctx->aborting = 0;
1625         }
1626
1627         if (!ctx->streamon_out && !ctx->streamon_cap)
1628                 ctx->bit_stream_param &= ~CODA_BIT_STREAM_END_FLAG;
1629 }
1630
1631 static const struct vb2_ops coda_qops = {
1632         .queue_setup            = coda_queue_setup,
1633         .buf_prepare            = coda_buf_prepare,
1634         .buf_queue              = coda_buf_queue,
1635         .start_streaming        = coda_start_streaming,
1636         .stop_streaming         = coda_stop_streaming,
1637         .wait_prepare           = vb2_ops_wait_prepare,
1638         .wait_finish            = vb2_ops_wait_finish,
1639 };
1640
1641 static int coda_s_ctrl(struct v4l2_ctrl *ctrl)
1642 {
1643         struct coda_ctx *ctx =
1644                         container_of(ctrl->handler, struct coda_ctx, ctrls);
1645
1646         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1647                  "s_ctrl: id = %d, val = %d\n", ctrl->id, ctrl->val);
1648
1649         switch (ctrl->id) {
1650         case V4L2_CID_HFLIP:
1651                 if (ctrl->val)
1652                         ctx->params.rot_mode |= CODA_MIR_HOR;
1653                 else
1654                         ctx->params.rot_mode &= ~CODA_MIR_HOR;
1655                 break;
1656         case V4L2_CID_VFLIP:
1657                 if (ctrl->val)
1658                         ctx->params.rot_mode |= CODA_MIR_VER;
1659                 else
1660                         ctx->params.rot_mode &= ~CODA_MIR_VER;
1661                 break;
1662         case V4L2_CID_MPEG_VIDEO_BITRATE:
1663                 ctx->params.bitrate = ctrl->val / 1000;
1664                 break;
1665         case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
1666                 ctx->params.gop_size = ctrl->val;
1667                 break;
1668         case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
1669                 ctx->params.h264_intra_qp = ctrl->val;
1670                 break;
1671         case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
1672                 ctx->params.h264_inter_qp = ctrl->val;
1673                 break;
1674         case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
1675                 ctx->params.h264_min_qp = ctrl->val;
1676                 break;
1677         case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
1678                 ctx->params.h264_max_qp = ctrl->val;
1679                 break;
1680         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA:
1681                 ctx->params.h264_slice_alpha_c0_offset_div2 = ctrl->val;
1682                 break;
1683         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA:
1684                 ctx->params.h264_slice_beta_offset_div2 = ctrl->val;
1685                 break;
1686         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE:
1687                 ctx->params.h264_disable_deblocking_filter_idc = ctrl->val;
1688                 break;
1689         case V4L2_CID_MPEG_VIDEO_H264_PROFILE:
1690                 /* TODO: switch between baseline and constrained baseline */
1691                 if (ctx->inst_type == CODA_INST_ENCODER)
1692                         ctx->params.h264_profile_idc = 66;
1693                 break;
1694         case V4L2_CID_MPEG_VIDEO_H264_LEVEL:
1695                 /* nothing to do, this is set by the encoder */
1696                 break;
1697         case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
1698                 ctx->params.mpeg4_intra_qp = ctrl->val;
1699                 break;
1700         case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
1701                 ctx->params.mpeg4_inter_qp = ctrl->val;
1702                 break;
1703         case V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE:
1704         case V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL:
1705                 /* nothing to do, these are fixed */
1706                 break;
1707         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
1708                 ctx->params.slice_mode = ctrl->val;
1709                 break;
1710         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
1711                 ctx->params.slice_max_mb = ctrl->val;
1712                 break;
1713         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
1714                 ctx->params.slice_max_bits = ctrl->val * 8;
1715                 break;
1716         case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
1717                 break;
1718         case V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB:
1719                 ctx->params.intra_refresh = ctrl->val;
1720                 break;
1721         case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME:
1722                 ctx->params.force_ipicture = true;
1723                 break;
1724         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
1725                 coda_set_jpeg_compression_quality(ctx, ctrl->val);
1726                 break;
1727         case V4L2_CID_JPEG_RESTART_INTERVAL:
1728                 ctx->params.jpeg_restart_interval = ctrl->val;
1729                 break;
1730         case V4L2_CID_MPEG_VIDEO_VBV_DELAY:
1731                 ctx->params.vbv_delay = ctrl->val;
1732                 break;
1733         case V4L2_CID_MPEG_VIDEO_VBV_SIZE:
1734                 ctx->params.vbv_size = min(ctrl->val * 8192, 0x7fffffff);
1735                 break;
1736         default:
1737                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1738                         "Invalid control, id=%d, val=%d\n",
1739                         ctrl->id, ctrl->val);
1740                 return -EINVAL;
1741         }
1742
1743         return 0;
1744 }
1745
1746 static const struct v4l2_ctrl_ops coda_ctrl_ops = {
1747         .s_ctrl = coda_s_ctrl,
1748 };
1749
1750 static void coda_encode_ctrls(struct coda_ctx *ctx)
1751 {
1752         int max_gop_size = (ctx->dev->devtype->product == CODA_DX6) ? 60 : 99;
1753
1754         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1755                 V4L2_CID_MPEG_VIDEO_BITRATE, 0, 32767000, 1000, 0);
1756         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1757                 V4L2_CID_MPEG_VIDEO_GOP_SIZE, 0, max_gop_size, 1, 16);
1758         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1759                 V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP, 0, 51, 1, 25);
1760         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1761                 V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP, 0, 51, 1, 25);
1762         if (ctx->dev->devtype->product != CODA_960) {
1763                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1764                         V4L2_CID_MPEG_VIDEO_H264_MIN_QP, 0, 51, 1, 12);
1765         }
1766         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1767                 V4L2_CID_MPEG_VIDEO_H264_MAX_QP, 0, 51, 1, 51);
1768         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1769                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA, -6, 6, 1, 0);
1770         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1771                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA, -6, 6, 1, 0);
1772         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1773                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE,
1774                 V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY,
1775                 0x0, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED);
1776         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1777                 V4L2_CID_MPEG_VIDEO_H264_PROFILE,
1778                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE, 0x0,
1779                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE);
1780         if (ctx->dev->devtype->product == CODA_7541) {
1781                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1782                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
1783                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1,
1784                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
1785                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
1786                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1)),
1787                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1);
1788         }
1789         if (ctx->dev->devtype->product == CODA_960) {
1790                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1791                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
1792                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0,
1793                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
1794                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
1795                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1) |
1796                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_2) |
1797                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_4_0)),
1798                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0);
1799         }
1800         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1801                 V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP, 1, 31, 1, 2);
1802         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1803                 V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP, 1, 31, 1, 2);
1804         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1805                 V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE,
1806                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE, 0x0,
1807                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE);
1808         if (ctx->dev->devtype->product == CODA_7541 ||
1809             ctx->dev->devtype->product == CODA_960) {
1810                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1811                         V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL,
1812                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5,
1813                         ~(1 << V4L2_MPEG_VIDEO_MPEG4_LEVEL_5),
1814                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5);
1815         }
1816         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1817                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE,
1818                 V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES, 0x0,
1819                 V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE);
1820         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1821                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB, 1, 0x3fffffff, 1, 1);
1822         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1823                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES, 1, 0x3fffffff, 1,
1824                 500);
1825         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1826                 V4L2_CID_MPEG_VIDEO_HEADER_MODE,
1827                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME,
1828                 (1 << V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE),
1829                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME);
1830         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1831                 V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB, 0,
1832                 1920 * 1088 / 256, 1, 0);
1833         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1834                 V4L2_CID_MPEG_VIDEO_VBV_DELAY, 0, 0x7fff, 1, 0);
1835         /*
1836          * The maximum VBV size value is 0x7fffffff bits,
1837          * one bit less than 262144 KiB
1838          */
1839         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1840                 V4L2_CID_MPEG_VIDEO_VBV_SIZE, 0, 262144, 1, 0);
1841 }
1842
1843 static void coda_jpeg_encode_ctrls(struct coda_ctx *ctx)
1844 {
1845         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1846                 V4L2_CID_JPEG_COMPRESSION_QUALITY, 5, 100, 1, 50);
1847         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1848                 V4L2_CID_JPEG_RESTART_INTERVAL, 0, 100, 1, 0);
1849 }
1850
1851 static int coda_ctrls_setup(struct coda_ctx *ctx)
1852 {
1853         v4l2_ctrl_handler_init(&ctx->ctrls, 2);
1854
1855         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1856                 V4L2_CID_HFLIP, 0, 1, 1, 0);
1857         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1858                 V4L2_CID_VFLIP, 0, 1, 1, 0);
1859         if (ctx->inst_type == CODA_INST_ENCODER) {
1860                 if (ctx->cvd->dst_formats[0] == V4L2_PIX_FMT_JPEG)
1861                         coda_jpeg_encode_ctrls(ctx);
1862                 else
1863                         coda_encode_ctrls(ctx);
1864         }
1865
1866         if (ctx->ctrls.error) {
1867                 v4l2_err(&ctx->dev->v4l2_dev,
1868                         "control initialization error (%d)",
1869                         ctx->ctrls.error);
1870                 return -EINVAL;
1871         }
1872
1873         return v4l2_ctrl_handler_setup(&ctx->ctrls);
1874 }
1875
1876 static int coda_queue_init(struct coda_ctx *ctx, struct vb2_queue *vq)
1877 {
1878         vq->drv_priv = ctx;
1879         vq->ops = &coda_qops;
1880         vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
1881         vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1882         vq->lock = &ctx->dev->dev_mutex;
1883         /* One way to indicate end-of-stream for coda is to set the
1884          * bytesused == 0. However by default videobuf2 handles bytesused
1885          * equal to 0 as a special case and changes its value to the size
1886          * of the buffer. Set the allow_zero_bytesused flag, so
1887          * that videobuf2 will keep the value of bytesused intact.
1888          */
1889         vq->allow_zero_bytesused = 1;
1890         vq->dev = &ctx->dev->plat_dev->dev;
1891
1892         return vb2_queue_init(vq);
1893 }
1894
1895 int coda_encoder_queue_init(void *priv, struct vb2_queue *src_vq,
1896                             struct vb2_queue *dst_vq)
1897 {
1898         int ret;
1899
1900         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
1901         src_vq->io_modes = VB2_DMABUF | VB2_MMAP;
1902         src_vq->mem_ops = &vb2_dma_contig_memops;
1903
1904         ret = coda_queue_init(priv, src_vq);
1905         if (ret)
1906                 return ret;
1907
1908         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1909         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
1910         dst_vq->mem_ops = &vb2_dma_contig_memops;
1911
1912         return coda_queue_init(priv, dst_vq);
1913 }
1914
1915 int coda_decoder_queue_init(void *priv, struct vb2_queue *src_vq,
1916                             struct vb2_queue *dst_vq)
1917 {
1918         int ret;
1919
1920         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
1921         src_vq->io_modes = VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
1922         src_vq->mem_ops = &vb2_vmalloc_memops;
1923
1924         ret = coda_queue_init(priv, src_vq);
1925         if (ret)
1926                 return ret;
1927
1928         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1929         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
1930         dst_vq->mem_ops = &vb2_dma_contig_memops;
1931
1932         return coda_queue_init(priv, dst_vq);
1933 }
1934
1935 static int coda_next_free_instance(struct coda_dev *dev)
1936 {
1937         int idx = ffz(dev->instance_mask);
1938
1939         if ((idx < 0) ||
1940             (dev->devtype->product == CODA_DX6 && idx > CODADX6_MAX_INSTANCES))
1941                 return -EBUSY;
1942
1943         return idx;
1944 }
1945
1946 /*
1947  * File operations
1948  */
1949
1950 static int coda_open(struct file *file)
1951 {
1952         struct video_device *vdev = video_devdata(file);
1953         struct coda_dev *dev = video_get_drvdata(vdev);
1954         struct coda_ctx *ctx = NULL;
1955         char *name;
1956         int ret;
1957         int idx;
1958
1959         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1960         if (!ctx)
1961                 return -ENOMEM;
1962
1963         idx = coda_next_free_instance(dev);
1964         if (idx < 0) {
1965                 ret = idx;
1966                 goto err_coda_max;
1967         }
1968         set_bit(idx, &dev->instance_mask);
1969
1970         name = kasprintf(GFP_KERNEL, "context%d", idx);
1971         if (!name) {
1972                 ret = -ENOMEM;
1973                 goto err_coda_name_init;
1974         }
1975
1976         ctx->debugfs_entry = debugfs_create_dir(name, dev->debugfs_root);
1977         kfree(name);
1978
1979         ctx->cvd = to_coda_video_device(vdev);
1980         ctx->inst_type = ctx->cvd->type;
1981         ctx->ops = ctx->cvd->ops;
1982         ctx->use_bit = !ctx->cvd->direct;
1983         init_completion(&ctx->completion);
1984         INIT_WORK(&ctx->pic_run_work, coda_pic_run_work);
1985         if (ctx->ops->seq_end_work)
1986                 INIT_WORK(&ctx->seq_end_work, ctx->ops->seq_end_work);
1987         v4l2_fh_init(&ctx->fh, video_devdata(file));
1988         file->private_data = &ctx->fh;
1989         v4l2_fh_add(&ctx->fh);
1990         ctx->dev = dev;
1991         ctx->idx = idx;
1992         switch (dev->devtype->product) {
1993         case CODA_960:
1994                 /*
1995                  * Enabling the BWB when decoding can hang the firmware with
1996                  * certain streams. The issue was tracked as ENGR00293425 by
1997                  * Freescale. As a workaround, disable BWB for all decoders.
1998                  * The enable_bwb module parameter allows to override this.
1999                  */
2000                 if (enable_bwb || ctx->inst_type == CODA_INST_ENCODER)
2001                         ctx->frame_mem_ctrl = CODA9_FRAME_ENABLE_BWB;
2002                 /* fallthrough */
2003         case CODA_7541:
2004                 ctx->reg_idx = 0;
2005                 break;
2006         default:
2007                 ctx->reg_idx = idx;
2008         }
2009         if (ctx->dev->vdoa && !disable_vdoa) {
2010                 ctx->vdoa = vdoa_context_create(dev->vdoa);
2011                 if (!ctx->vdoa)
2012                         v4l2_warn(&dev->v4l2_dev,
2013                                   "Failed to create vdoa context: not using vdoa");
2014         }
2015         ctx->use_vdoa = false;
2016
2017         /* Power up and upload firmware if necessary */
2018         ret = pm_runtime_get_sync(&dev->plat_dev->dev);
2019         if (ret < 0) {
2020                 v4l2_err(&dev->v4l2_dev, "failed to power up: %d\n", ret);
2021                 goto err_pm_get;
2022         }
2023
2024         ret = clk_prepare_enable(dev->clk_per);
2025         if (ret)
2026                 goto err_clk_per;
2027
2028         ret = clk_prepare_enable(dev->clk_ahb);
2029         if (ret)
2030                 goto err_clk_ahb;
2031
2032         set_default_params(ctx);
2033         ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx,
2034                                             ctx->ops->queue_init);
2035         if (IS_ERR(ctx->fh.m2m_ctx)) {
2036                 ret = PTR_ERR(ctx->fh.m2m_ctx);
2037
2038                 v4l2_err(&dev->v4l2_dev, "%s return error (%d)\n",
2039                          __func__, ret);
2040                 goto err_ctx_init;
2041         }
2042
2043         ret = coda_ctrls_setup(ctx);
2044         if (ret) {
2045                 v4l2_err(&dev->v4l2_dev, "failed to setup coda controls\n");
2046                 goto err_ctrls_setup;
2047         }
2048
2049         ctx->fh.ctrl_handler = &ctx->ctrls;
2050
2051         mutex_init(&ctx->bitstream_mutex);
2052         mutex_init(&ctx->buffer_mutex);
2053         INIT_LIST_HEAD(&ctx->buffer_meta_list);
2054         spin_lock_init(&ctx->buffer_meta_lock);
2055
2056         coda_lock(ctx);
2057         list_add(&ctx->list, &dev->instances);
2058         coda_unlock(ctx);
2059
2060         v4l2_dbg(1, coda_debug, &dev->v4l2_dev, "Created instance %d (%p)\n",
2061                  ctx->idx, ctx);
2062
2063         return 0;
2064
2065 err_ctrls_setup:
2066         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
2067 err_ctx_init:
2068         clk_disable_unprepare(dev->clk_ahb);
2069 err_clk_ahb:
2070         clk_disable_unprepare(dev->clk_per);
2071 err_clk_per:
2072         pm_runtime_put_sync(&dev->plat_dev->dev);
2073 err_pm_get:
2074         v4l2_fh_del(&ctx->fh);
2075         v4l2_fh_exit(&ctx->fh);
2076         clear_bit(ctx->idx, &dev->instance_mask);
2077 err_coda_name_init:
2078 err_coda_max:
2079         kfree(ctx);
2080         return ret;
2081 }
2082
2083 static int coda_release(struct file *file)
2084 {
2085         struct coda_dev *dev = video_drvdata(file);
2086         struct coda_ctx *ctx = fh_to_ctx(file->private_data);
2087
2088         v4l2_dbg(1, coda_debug, &dev->v4l2_dev, "Releasing instance %p\n",
2089                  ctx);
2090
2091         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit)
2092                 coda_bit_stream_end_flag(ctx);
2093
2094         /* If this instance is running, call .job_abort and wait for it to end */
2095         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
2096
2097         if (ctx->vdoa)
2098                 vdoa_context_destroy(ctx->vdoa);
2099
2100         /* In case the instance was not running, we still need to call SEQ_END */
2101         if (ctx->ops->seq_end_work) {
2102                 queue_work(dev->workqueue, &ctx->seq_end_work);
2103                 flush_work(&ctx->seq_end_work);
2104         }
2105
2106         coda_lock(ctx);
2107         list_del(&ctx->list);
2108         coda_unlock(ctx);
2109
2110         if (ctx->dev->devtype->product == CODA_DX6)
2111                 coda_free_aux_buf(dev, &ctx->workbuf);
2112
2113         v4l2_ctrl_handler_free(&ctx->ctrls);
2114         clk_disable_unprepare(dev->clk_ahb);
2115         clk_disable_unprepare(dev->clk_per);
2116         pm_runtime_put_sync(&dev->plat_dev->dev);
2117         v4l2_fh_del(&ctx->fh);
2118         v4l2_fh_exit(&ctx->fh);
2119         clear_bit(ctx->idx, &dev->instance_mask);
2120         if (ctx->ops->release)
2121                 ctx->ops->release(ctx);
2122         debugfs_remove_recursive(ctx->debugfs_entry);
2123         kfree(ctx);
2124
2125         return 0;
2126 }
2127
2128 static const struct v4l2_file_operations coda_fops = {
2129         .owner          = THIS_MODULE,
2130         .open           = coda_open,
2131         .release        = coda_release,
2132         .poll           = v4l2_m2m_fop_poll,
2133         .unlocked_ioctl = video_ioctl2,
2134         .mmap           = v4l2_m2m_fop_mmap,
2135 };
2136
2137 static int coda_hw_init(struct coda_dev *dev)
2138 {
2139         u32 data;
2140         u16 *p;
2141         int i, ret;
2142
2143         ret = clk_prepare_enable(dev->clk_per);
2144         if (ret)
2145                 goto err_clk_per;
2146
2147         ret = clk_prepare_enable(dev->clk_ahb);
2148         if (ret)
2149                 goto err_clk_ahb;
2150
2151         reset_control_reset(dev->rstc);
2152
2153         /*
2154          * Copy the first CODA_ISRAM_SIZE in the internal SRAM.
2155          * The 16-bit chars in the code buffer are in memory access
2156          * order, re-sort them to CODA order for register download.
2157          * Data in this SRAM survives a reboot.
2158          */
2159         p = (u16 *)dev->codebuf.vaddr;
2160         if (dev->devtype->product == CODA_DX6) {
2161                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++)  {
2162                         data = CODA_DOWN_ADDRESS_SET(i) |
2163                                 CODA_DOWN_DATA_SET(p[i ^ 1]);
2164                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
2165                 }
2166         } else {
2167                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++) {
2168                         data = CODA_DOWN_ADDRESS_SET(i) |
2169                                 CODA_DOWN_DATA_SET(p[round_down(i, 4) +
2170                                                         3 - (i % 4)]);
2171                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
2172                 }
2173         }
2174
2175         /* Clear registers */
2176         for (i = 0; i < 64; i++)
2177                 coda_write(dev, 0, CODA_REG_BIT_CODE_BUF_ADDR + i * 4);
2178
2179         /* Tell the BIT where to find everything it needs */
2180         if (dev->devtype->product == CODA_960 ||
2181             dev->devtype->product == CODA_7541) {
2182                 coda_write(dev, dev->tempbuf.paddr,
2183                                 CODA_REG_BIT_TEMP_BUF_ADDR);
2184                 coda_write(dev, 0, CODA_REG_BIT_BIT_STREAM_PARAM);
2185         } else {
2186                 coda_write(dev, dev->workbuf.paddr,
2187                               CODA_REG_BIT_WORK_BUF_ADDR);
2188         }
2189         coda_write(dev, dev->codebuf.paddr,
2190                       CODA_REG_BIT_CODE_BUF_ADDR);
2191         coda_write(dev, 0, CODA_REG_BIT_CODE_RUN);
2192
2193         /* Set default values */
2194         switch (dev->devtype->product) {
2195         case CODA_DX6:
2196                 coda_write(dev, CODADX6_STREAM_BUF_PIC_FLUSH,
2197                            CODA_REG_BIT_STREAM_CTRL);
2198                 break;
2199         default:
2200                 coda_write(dev, CODA7_STREAM_BUF_PIC_FLUSH,
2201                            CODA_REG_BIT_STREAM_CTRL);
2202         }
2203         if (dev->devtype->product == CODA_960)
2204                 coda_write(dev, CODA9_FRAME_ENABLE_BWB,
2205                                 CODA_REG_BIT_FRAME_MEM_CTRL);
2206         else
2207                 coda_write(dev, 0, CODA_REG_BIT_FRAME_MEM_CTRL);
2208
2209         if (dev->devtype->product != CODA_DX6)
2210                 coda_write(dev, 0, CODA7_REG_BIT_AXI_SRAM_USE);
2211
2212         coda_write(dev, CODA_INT_INTERRUPT_ENABLE,
2213                       CODA_REG_BIT_INT_ENABLE);
2214
2215         /* Reset VPU and start processor */
2216         data = coda_read(dev, CODA_REG_BIT_CODE_RESET);
2217         data |= CODA_REG_RESET_ENABLE;
2218         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
2219         udelay(10);
2220         data &= ~CODA_REG_RESET_ENABLE;
2221         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
2222         coda_write(dev, CODA_REG_RUN_ENABLE, CODA_REG_BIT_CODE_RUN);
2223
2224         clk_disable_unprepare(dev->clk_ahb);
2225         clk_disable_unprepare(dev->clk_per);
2226
2227         return 0;
2228
2229 err_clk_ahb:
2230         clk_disable_unprepare(dev->clk_per);
2231 err_clk_per:
2232         return ret;
2233 }
2234
2235 static int coda_register_device(struct coda_dev *dev, int i)
2236 {
2237         struct video_device *vfd = &dev->vfd[i];
2238
2239         if (i >= dev->devtype->num_vdevs)
2240                 return -EINVAL;
2241
2242         strlcpy(vfd->name, dev->devtype->vdevs[i]->name, sizeof(vfd->name));
2243         vfd->fops       = &coda_fops;
2244         vfd->ioctl_ops  = &coda_ioctl_ops;
2245         vfd->release    = video_device_release_empty,
2246         vfd->lock       = &dev->dev_mutex;
2247         vfd->v4l2_dev   = &dev->v4l2_dev;
2248         vfd->vfl_dir    = VFL_DIR_M2M;
2249         video_set_drvdata(vfd, dev);
2250
2251         /* Not applicable, use the selection API instead */
2252         v4l2_disable_ioctl(vfd, VIDIOC_CROPCAP);
2253         v4l2_disable_ioctl(vfd, VIDIOC_G_CROP);
2254         v4l2_disable_ioctl(vfd, VIDIOC_S_CROP);
2255
2256         return video_register_device(vfd, VFL_TYPE_GRABBER, 0);
2257 }
2258
2259 static void coda_copy_firmware(struct coda_dev *dev, const u8 * const buf,
2260                                size_t size)
2261 {
2262         u32 *src = (u32 *)buf;
2263
2264         /* Check if the firmware has a 16-byte Freescale header, skip it */
2265         if (buf[0] == 'M' && buf[1] == 'X')
2266                 src += 4;
2267         /*
2268          * Check whether the firmware is in native order or pre-reordered for
2269          * memory access. The first instruction opcode always is 0xe40e.
2270          */
2271         if (__le16_to_cpup((__le16 *)src) == 0xe40e) {
2272                 u32 *dst = dev->codebuf.vaddr;
2273                 int i;
2274
2275                 /* Firmware in native order, reorder while copying */
2276                 if (dev->devtype->product == CODA_DX6) {
2277                         for (i = 0; i < (size - 16) / 4; i++)
2278                                 dst[i] = (src[i] << 16) | (src[i] >> 16);
2279                 } else {
2280                         for (i = 0; i < (size - 16) / 4; i += 2) {
2281                                 dst[i] = (src[i + 1] << 16) | (src[i + 1] >> 16);
2282                                 dst[i + 1] = (src[i] << 16) | (src[i] >> 16);
2283                         }
2284                 }
2285         } else {
2286                 /* Copy the already reordered firmware image */
2287                 memcpy(dev->codebuf.vaddr, src, size);
2288         }
2289 }
2290
2291 static void coda_fw_callback(const struct firmware *fw, void *context);
2292
2293 static int coda_firmware_request(struct coda_dev *dev)
2294 {
2295         char *fw;
2296
2297         if (dev->firmware >= ARRAY_SIZE(dev->devtype->firmware))
2298                 return -EINVAL;
2299
2300         fw = dev->devtype->firmware[dev->firmware];
2301
2302         dev_dbg(&dev->plat_dev->dev, "requesting firmware '%s' for %s\n", fw,
2303                 coda_product_name(dev->devtype->product));
2304
2305         return reject_firmware_nowait(THIS_MODULE, true, fw,
2306                                        &dev->plat_dev->dev, GFP_KERNEL, dev,
2307                                        coda_fw_callback);
2308 }
2309
2310 static void coda_fw_callback(const struct firmware *fw, void *context)
2311 {
2312         struct coda_dev *dev = context;
2313         struct platform_device *pdev = dev->plat_dev;
2314         int i, ret;
2315
2316         if (!fw) {
2317                 dev->firmware++;
2318                 ret = coda_firmware_request(dev);
2319                 if (ret < 0) {
2320                         v4l2_err(&dev->v4l2_dev, "firmware request failed\n");
2321                         goto put_pm;
2322                 }
2323                 return;
2324         }
2325         if (dev->firmware > 0) {
2326                 /*
2327                  * Since we can't suppress warnings for failed asynchronous
2328                  * firmware requests, report that the fallback firmware was
2329                  * found.
2330                  */
2331                 dev_info(&pdev->dev, "Using fallback firmware %s\n",
2332                          dev->devtype->firmware[dev->firmware]);
2333         }
2334
2335         /* allocate auxiliary per-device code buffer for the BIT processor */
2336         ret = coda_alloc_aux_buf(dev, &dev->codebuf, fw->size, "codebuf",
2337                                  dev->debugfs_root);
2338         if (ret < 0)
2339                 goto put_pm;
2340
2341         coda_copy_firmware(dev, fw->data, fw->size);
2342         release_firmware(fw);
2343
2344         ret = coda_hw_init(dev);
2345         if (ret < 0) {
2346                 v4l2_err(&dev->v4l2_dev, "HW initialization failed\n");
2347                 goto put_pm;
2348         }
2349
2350         ret = coda_check_firmware(dev);
2351         if (ret < 0)
2352                 goto put_pm;
2353
2354         dev->m2m_dev = v4l2_m2m_init(&coda_m2m_ops);
2355         if (IS_ERR(dev->m2m_dev)) {
2356                 v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n");
2357                 goto put_pm;
2358         }
2359
2360         for (i = 0; i < dev->devtype->num_vdevs; i++) {
2361                 ret = coda_register_device(dev, i);
2362                 if (ret) {
2363                         v4l2_err(&dev->v4l2_dev,
2364                                  "Failed to register %s video device: %d\n",
2365                                  dev->devtype->vdevs[i]->name, ret);
2366                         goto rel_vfd;
2367                 }
2368         }
2369
2370         v4l2_info(&dev->v4l2_dev, "codec registered as /dev/video[%d-%d]\n",
2371                   dev->vfd[0].num, dev->vfd[i - 1].num);
2372
2373         pm_runtime_put_sync(&pdev->dev);
2374         return;
2375
2376 rel_vfd:
2377         while (--i >= 0)
2378                 video_unregister_device(&dev->vfd[i]);
2379         v4l2_m2m_release(dev->m2m_dev);
2380 put_pm:
2381         pm_runtime_put_sync(&pdev->dev);
2382 }
2383
2384 enum coda_platform {
2385         CODA_IMX27,
2386         CODA_IMX53,
2387         CODA_IMX6Q,
2388         CODA_IMX6DL,
2389 };
2390
2391 static const struct coda_devtype coda_devdata[] = {
2392         [CODA_IMX27] = {
2393                 .firmware     = {
2394                         "/*(DEBLOBBED)*/",
2395                         "/*(DEBLOBBED)*/",
2396                         "/*(DEBLOBBED)*/"
2397                 },
2398                 .product      = CODA_DX6,
2399                 .codecs       = codadx6_codecs,
2400                 .num_codecs   = ARRAY_SIZE(codadx6_codecs),
2401                 .vdevs        = codadx6_video_devices,
2402                 .num_vdevs    = ARRAY_SIZE(codadx6_video_devices),
2403                 .workbuf_size = 288 * 1024 + FMO_SLICE_SAVE_BUF_SIZE * 8 * 1024,
2404                 .iram_size    = 0xb000,
2405         },
2406         [CODA_IMX53] = {
2407                 .firmware     = {
2408                         "/*(DEBLOBBED)*/",
2409                         "/*(DEBLOBBED)*/",
2410                         "/*(DEBLOBBED)*/"
2411                 },
2412                 .product      = CODA_7541,
2413                 .codecs       = coda7_codecs,
2414                 .num_codecs   = ARRAY_SIZE(coda7_codecs),
2415                 .vdevs        = coda7_video_devices,
2416                 .num_vdevs    = ARRAY_SIZE(coda7_video_devices),
2417                 .workbuf_size = 128 * 1024,
2418                 .tempbuf_size = 304 * 1024,
2419                 .iram_size    = 0x14000,
2420         },
2421         [CODA_IMX6Q] = {
2422                 .firmware     = {
2423                         "/*(DEBLOBBED)*/",
2424                         "/*(DEBLOBBED)*/",
2425                         "/*(DEBLOBBED)*/"
2426                 },
2427                 .product      = CODA_960,
2428                 .codecs       = coda9_codecs,
2429                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2430                 .vdevs        = coda9_video_devices,
2431                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2432                 .workbuf_size = 80 * 1024,
2433                 .tempbuf_size = 204 * 1024,
2434                 .iram_size    = 0x21000,
2435         },
2436         [CODA_IMX6DL] = {
2437                 .firmware     = {
2438                         "/*(DEBLOBBED)*/",
2439                         "/*(DEBLOBBED)*/",
2440                         "/*(DEBLOBBED)*/"
2441                 },
2442                 .product      = CODA_960,
2443                 .codecs       = coda9_codecs,
2444                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2445                 .vdevs        = coda9_video_devices,
2446                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2447                 .workbuf_size = 80 * 1024,
2448                 .tempbuf_size = 204 * 1024,
2449                 .iram_size    = 0x1f000, /* leave 4k for suspend code */
2450         },
2451 };
2452
2453 static const struct platform_device_id coda_platform_ids[] = {
2454         { .name = "coda-imx27", .driver_data = CODA_IMX27 },
2455         { /* sentinel */ }
2456 };
2457 MODULE_DEVICE_TABLE(platform, coda_platform_ids);
2458
2459 #ifdef CONFIG_OF
2460 static const struct of_device_id coda_dt_ids[] = {
2461         { .compatible = "fsl,imx27-vpu", .data = &coda_devdata[CODA_IMX27] },
2462         { .compatible = "fsl,imx53-vpu", .data = &coda_devdata[CODA_IMX53] },
2463         { .compatible = "fsl,imx6q-vpu", .data = &coda_devdata[CODA_IMX6Q] },
2464         { .compatible = "fsl,imx6dl-vpu", .data = &coda_devdata[CODA_IMX6DL] },
2465         { /* sentinel */ }
2466 };
2467 MODULE_DEVICE_TABLE(of, coda_dt_ids);
2468 #endif
2469
2470 static int coda_probe(struct platform_device *pdev)
2471 {
2472         const struct of_device_id *of_id =
2473                         of_match_device(of_match_ptr(coda_dt_ids), &pdev->dev);
2474         const struct platform_device_id *pdev_id;
2475         struct coda_platform_data *pdata = pdev->dev.platform_data;
2476         struct device_node *np = pdev->dev.of_node;
2477         struct gen_pool *pool;
2478         struct coda_dev *dev;
2479         struct resource *res;
2480         int ret, irq;
2481
2482         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
2483         if (!dev)
2484                 return -ENOMEM;
2485
2486         pdev_id = of_id ? of_id->data : platform_get_device_id(pdev);
2487
2488         if (of_id)
2489                 dev->devtype = of_id->data;
2490         else if (pdev_id)
2491                 dev->devtype = &coda_devdata[pdev_id->driver_data];
2492         else
2493                 return -EINVAL;
2494
2495         spin_lock_init(&dev->irqlock);
2496         INIT_LIST_HEAD(&dev->instances);
2497
2498         dev->plat_dev = pdev;
2499         dev->clk_per = devm_clk_get(&pdev->dev, "per");
2500         if (IS_ERR(dev->clk_per)) {
2501                 dev_err(&pdev->dev, "Could not get per clock\n");
2502                 return PTR_ERR(dev->clk_per);
2503         }
2504
2505         dev->clk_ahb = devm_clk_get(&pdev->dev, "ahb");
2506         if (IS_ERR(dev->clk_ahb)) {
2507                 dev_err(&pdev->dev, "Could not get ahb clock\n");
2508                 return PTR_ERR(dev->clk_ahb);
2509         }
2510
2511         /* Get  memory for physical registers */
2512         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2513         dev->regs_base = devm_ioremap_resource(&pdev->dev, res);
2514         if (IS_ERR(dev->regs_base))
2515                 return PTR_ERR(dev->regs_base);
2516
2517         /* IRQ */
2518         irq = platform_get_irq_byname(pdev, "bit");
2519         if (irq < 0)
2520                 irq = platform_get_irq(pdev, 0);
2521         if (irq < 0) {
2522                 dev_err(&pdev->dev, "failed to get irq resource\n");
2523                 return irq;
2524         }
2525
2526         ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, coda_irq_handler,
2527                         IRQF_ONESHOT, dev_name(&pdev->dev), dev);
2528         if (ret < 0) {
2529                 dev_err(&pdev->dev, "failed to request irq: %d\n", ret);
2530                 return ret;
2531         }
2532
2533         dev->rstc = devm_reset_control_get_optional_exclusive(&pdev->dev,
2534                                                               NULL);
2535         if (IS_ERR(dev->rstc)) {
2536                 ret = PTR_ERR(dev->rstc);
2537                 dev_err(&pdev->dev, "failed get reset control: %d\n", ret);
2538                 return ret;
2539         }
2540
2541         /* Get IRAM pool from device tree or platform data */
2542         pool = of_gen_pool_get(np, "iram", 0);
2543         if (!pool && pdata)
2544                 pool = gen_pool_get(pdata->iram_dev, NULL);
2545         if (!pool) {
2546                 dev_err(&pdev->dev, "iram pool not available\n");
2547                 return -ENOMEM;
2548         }
2549         dev->iram_pool = pool;
2550
2551         /* Get vdoa_data if supported by the platform */
2552         dev->vdoa = coda_get_vdoa_data();
2553         if (PTR_ERR(dev->vdoa) == -EPROBE_DEFER)
2554                 return -EPROBE_DEFER;
2555
2556         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
2557         if (ret)
2558                 return ret;
2559
2560         mutex_init(&dev->dev_mutex);
2561         mutex_init(&dev->coda_mutex);
2562
2563         dev->debugfs_root = debugfs_create_dir("coda", NULL);
2564         if (!dev->debugfs_root)
2565                 dev_warn(&pdev->dev, "failed to create debugfs root\n");
2566
2567         /* allocate auxiliary per-device buffers for the BIT processor */
2568         if (dev->devtype->product == CODA_DX6) {
2569                 ret = coda_alloc_aux_buf(dev, &dev->workbuf,
2570                                          dev->devtype->workbuf_size, "workbuf",
2571                                          dev->debugfs_root);
2572                 if (ret < 0)
2573                         goto err_v4l2_register;
2574         }
2575
2576         if (dev->devtype->tempbuf_size) {
2577                 ret = coda_alloc_aux_buf(dev, &dev->tempbuf,
2578                                          dev->devtype->tempbuf_size, "tempbuf",
2579                                          dev->debugfs_root);
2580                 if (ret < 0)
2581                         goto err_v4l2_register;
2582         }
2583
2584         dev->iram.size = dev->devtype->iram_size;
2585         dev->iram.vaddr = gen_pool_dma_alloc(dev->iram_pool, dev->iram.size,
2586                                              &dev->iram.paddr);
2587         if (!dev->iram.vaddr) {
2588                 dev_warn(&pdev->dev, "unable to alloc iram\n");
2589         } else {
2590                 memset(dev->iram.vaddr, 0, dev->iram.size);
2591                 dev->iram.blob.data = dev->iram.vaddr;
2592                 dev->iram.blob.size = dev->iram.size;
2593                 dev->iram.dentry = debugfs_create_blob("iram", 0644,
2594                                                        dev->debugfs_root,
2595                                                        &dev->iram.blob);
2596         }
2597
2598         dev->workqueue = alloc_workqueue("coda", WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
2599         if (!dev->workqueue) {
2600                 dev_err(&pdev->dev, "unable to alloc workqueue\n");
2601                 ret = -ENOMEM;
2602                 goto err_v4l2_register;
2603         }
2604
2605         platform_set_drvdata(pdev, dev);
2606
2607         /*
2608          * Start activated so we can directly call coda_hw_init in
2609          * coda_fw_callback regardless of whether CONFIG_PM is
2610          * enabled or whether the device is associated with a PM domain.
2611          */
2612         pm_runtime_get_noresume(&pdev->dev);
2613         pm_runtime_set_active(&pdev->dev);
2614         pm_runtime_enable(&pdev->dev);
2615
2616         ret = coda_firmware_request(dev);
2617         if (ret)
2618                 goto err_alloc_workqueue;
2619         return 0;
2620
2621 err_alloc_workqueue:
2622         destroy_workqueue(dev->workqueue);
2623 err_v4l2_register:
2624         v4l2_device_unregister(&dev->v4l2_dev);
2625         return ret;
2626 }
2627
2628 static int coda_remove(struct platform_device *pdev)
2629 {
2630         struct coda_dev *dev = platform_get_drvdata(pdev);
2631         int i;
2632
2633         for (i = 0; i < ARRAY_SIZE(dev->vfd); i++) {
2634                 if (video_get_drvdata(&dev->vfd[i]))
2635                         video_unregister_device(&dev->vfd[i]);
2636         }
2637         if (dev->m2m_dev)
2638                 v4l2_m2m_release(dev->m2m_dev);
2639         pm_runtime_disable(&pdev->dev);
2640         v4l2_device_unregister(&dev->v4l2_dev);
2641         destroy_workqueue(dev->workqueue);
2642         if (dev->iram.vaddr)
2643                 gen_pool_free(dev->iram_pool, (unsigned long)dev->iram.vaddr,
2644                               dev->iram.size);
2645         coda_free_aux_buf(dev, &dev->codebuf);
2646         coda_free_aux_buf(dev, &dev->tempbuf);
2647         coda_free_aux_buf(dev, &dev->workbuf);
2648         debugfs_remove_recursive(dev->debugfs_root);
2649         return 0;
2650 }
2651
2652 #ifdef CONFIG_PM
2653 static int coda_runtime_resume(struct device *dev)
2654 {
2655         struct coda_dev *cdev = dev_get_drvdata(dev);
2656         int ret = 0;
2657
2658         if (dev->pm_domain && cdev->codebuf.vaddr) {
2659                 ret = coda_hw_init(cdev);
2660                 if (ret)
2661                         v4l2_err(&cdev->v4l2_dev, "HW initialization failed\n");
2662         }
2663
2664         return ret;
2665 }
2666 #endif
2667
2668 static const struct dev_pm_ops coda_pm_ops = {
2669         SET_RUNTIME_PM_OPS(NULL, coda_runtime_resume, NULL)
2670 };
2671
2672 static struct platform_driver coda_driver = {
2673         .probe  = coda_probe,
2674         .remove = coda_remove,
2675         .driver = {
2676                 .name   = CODA_NAME,
2677                 .of_match_table = of_match_ptr(coda_dt_ids),
2678                 .pm     = &coda_pm_ops,
2679         },
2680         .id_table = coda_platform_ids,
2681 };
2682
2683 module_platform_driver(coda_driver);
2684
2685 MODULE_LICENSE("GPL");
2686 MODULE_AUTHOR("Javier Martin <javier.martin@vista-silicon.com>");
2687 MODULE_DESCRIPTION("Coda multi-standard codec V4L2 driver");