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