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