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