Merge tag 'kconfig-v5.2' of git://git.kernel.org/pub/scm/linux/kernel/git/masahiroy...
[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(2, coda_debug, &dev->v4l2_dev,
82                  "%s: data=0x%x, reg=0x%x\n", __func__, data, reg);
83         writel(data, dev->regs_base + reg);
84 }
85
86 unsigned int coda_read(struct coda_dev *dev, u32 reg)
87 {
88         u32 data;
89
90         data = readl(dev->regs_base + reg);
91         v4l2_dbg(2, coda_debug, &dev->v4l2_dev,
92                  "%s: data=0x%x, reg=0x%x\n", __func__, data, reg);
93         return data;
94 }
95
96 void coda_write_base(struct coda_ctx *ctx, struct coda_q_data *q_data,
97                      struct vb2_v4l2_buffer *buf, unsigned int reg_y)
98 {
99         u32 base_y = vb2_dma_contig_plane_dma_addr(&buf->vb2_buf, 0);
100         u32 base_cb, base_cr;
101
102         switch (q_data->fourcc) {
103         case V4L2_PIX_FMT_YUYV:
104                 /* Fallthrough: IN -H264-> CODA -NV12 MB-> VDOA -YUYV-> OUT */
105         case V4L2_PIX_FMT_NV12:
106         case V4L2_PIX_FMT_YUV420:
107         default:
108                 base_cb = base_y + q_data->bytesperline * q_data->height;
109                 base_cr = base_cb + q_data->bytesperline * q_data->height / 4;
110                 break;
111         case V4L2_PIX_FMT_YVU420:
112                 /* Switch Cb and Cr for YVU420 format */
113                 base_cr = base_y + q_data->bytesperline * q_data->height;
114                 base_cb = base_cr + q_data->bytesperline * q_data->height / 4;
115                 break;
116         case V4L2_PIX_FMT_YUV422P:
117                 base_cb = base_y + q_data->bytesperline * q_data->height;
118                 base_cr = base_cb + q_data->bytesperline * q_data->height / 2;
119         }
120
121         coda_write(ctx->dev, base_y, reg_y);
122         coda_write(ctx->dev, base_cb, reg_y + 4);
123         coda_write(ctx->dev, base_cr, reg_y + 8);
124 }
125
126 #define CODA_CODEC(mode, src_fourcc, dst_fourcc, max_w, max_h) \
127         { mode, src_fourcc, dst_fourcc, max_w, max_h }
128
129 /*
130  * Arrays of codecs supported by each given version of Coda:
131  *  i.MX27 -> codadx6
132  *  i.MX51 -> codahx4
133  *  i.MX53 -> coda7
134  *  i.MX6  -> coda960
135  * Use V4L2_PIX_FMT_YUV420 as placeholder for all supported YUV 4:2:0 variants
136  */
137 static const struct coda_codec codadx6_codecs[] = {
138         CODA_CODEC(CODADX6_MODE_ENCODE_H264, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_H264,  720, 576),
139         CODA_CODEC(CODADX6_MODE_ENCODE_MP4,  V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_MPEG4, 720, 576),
140 };
141
142 static const struct coda_codec codahx4_codecs[] = {
143         CODA_CODEC(CODA7_MODE_ENCODE_H264, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_H264,   720, 576),
144         CODA_CODEC(CODA7_MODE_DECODE_H264, V4L2_PIX_FMT_H264,   V4L2_PIX_FMT_YUV420, 1920, 1088),
145         CODA_CODEC(CODA7_MODE_DECODE_MP2,  V4L2_PIX_FMT_MPEG2,  V4L2_PIX_FMT_YUV420, 1920, 1088),
146         CODA_CODEC(CODA7_MODE_DECODE_MP4,  V4L2_PIX_FMT_MPEG4,  V4L2_PIX_FMT_YUV420, 1280, 720),
147 };
148
149 static const struct coda_codec coda7_codecs[] = {
150         CODA_CODEC(CODA7_MODE_ENCODE_H264, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_H264,   1280, 720),
151         CODA_CODEC(CODA7_MODE_ENCODE_MP4,  V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_MPEG4,  1280, 720),
152         CODA_CODEC(CODA7_MODE_ENCODE_MJPG, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_JPEG,   8192, 8192),
153         CODA_CODEC(CODA7_MODE_DECODE_H264, V4L2_PIX_FMT_H264,   V4L2_PIX_FMT_YUV420, 1920, 1088),
154         CODA_CODEC(CODA7_MODE_DECODE_MP2,  V4L2_PIX_FMT_MPEG2,  V4L2_PIX_FMT_YUV420, 1920, 1088),
155         CODA_CODEC(CODA7_MODE_DECODE_MP4,  V4L2_PIX_FMT_MPEG4,  V4L2_PIX_FMT_YUV420, 1920, 1088),
156         CODA_CODEC(CODA7_MODE_DECODE_MJPG, V4L2_PIX_FMT_JPEG,   V4L2_PIX_FMT_YUV420, 8192, 8192),
157 };
158
159 static const struct coda_codec coda9_codecs[] = {
160         CODA_CODEC(CODA9_MODE_ENCODE_H264, V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_H264,   1920, 1088),
161         CODA_CODEC(CODA9_MODE_ENCODE_MP4,  V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_MPEG4,  1920, 1088),
162         CODA_CODEC(CODA9_MODE_DECODE_H264, V4L2_PIX_FMT_H264,   V4L2_PIX_FMT_YUV420, 1920, 1088),
163         CODA_CODEC(CODA9_MODE_DECODE_MP2,  V4L2_PIX_FMT_MPEG2,  V4L2_PIX_FMT_YUV420, 1920, 1088),
164         CODA_CODEC(CODA9_MODE_DECODE_MP4,  V4L2_PIX_FMT_MPEG4,  V4L2_PIX_FMT_YUV420, 1920, 1088),
165 };
166
167 struct coda_video_device {
168         const char *name;
169         enum coda_inst_type type;
170         const struct coda_context_ops *ops;
171         bool direct;
172         u32 src_formats[CODA_MAX_FORMATS];
173         u32 dst_formats[CODA_MAX_FORMATS];
174 };
175
176 static const struct coda_video_device coda_bit_encoder = {
177         .name = "coda-encoder",
178         .type = CODA_INST_ENCODER,
179         .ops = &coda_bit_encode_ops,
180         .src_formats = {
181                 V4L2_PIX_FMT_NV12,
182                 V4L2_PIX_FMT_YUV420,
183                 V4L2_PIX_FMT_YVU420,
184         },
185         .dst_formats = {
186                 V4L2_PIX_FMT_H264,
187                 V4L2_PIX_FMT_MPEG4,
188         },
189 };
190
191 static const struct coda_video_device coda_bit_jpeg_encoder = {
192         .name = "coda-jpeg-encoder",
193         .type = CODA_INST_ENCODER,
194         .ops = &coda_bit_encode_ops,
195         .src_formats = {
196                 V4L2_PIX_FMT_NV12,
197                 V4L2_PIX_FMT_YUV420,
198                 V4L2_PIX_FMT_YVU420,
199                 V4L2_PIX_FMT_YUV422P,
200         },
201         .dst_formats = {
202                 V4L2_PIX_FMT_JPEG,
203         },
204 };
205
206 static const struct coda_video_device coda_bit_decoder = {
207         .name = "coda-decoder",
208         .type = CODA_INST_DECODER,
209         .ops = &coda_bit_decode_ops,
210         .src_formats = {
211                 V4L2_PIX_FMT_H264,
212                 V4L2_PIX_FMT_MPEG2,
213                 V4L2_PIX_FMT_MPEG4,
214         },
215         .dst_formats = {
216                 V4L2_PIX_FMT_NV12,
217                 V4L2_PIX_FMT_YUV420,
218                 V4L2_PIX_FMT_YVU420,
219                 /*
220                  * If V4L2_PIX_FMT_YUYV should be default,
221                  * set_default_params() must be adjusted.
222                  */
223                 V4L2_PIX_FMT_YUYV,
224         },
225 };
226
227 static const struct coda_video_device coda_bit_jpeg_decoder = {
228         .name = "coda-jpeg-decoder",
229         .type = CODA_INST_DECODER,
230         .ops = &coda_bit_decode_ops,
231         .src_formats = {
232                 V4L2_PIX_FMT_JPEG,
233         },
234         .dst_formats = {
235                 V4L2_PIX_FMT_NV12,
236                 V4L2_PIX_FMT_YUV420,
237                 V4L2_PIX_FMT_YVU420,
238                 V4L2_PIX_FMT_YUV422P,
239         },
240 };
241
242 static const struct coda_video_device *codadx6_video_devices[] = {
243         &coda_bit_encoder,
244 };
245
246 static const struct coda_video_device *codahx4_video_devices[] = {
247         &coda_bit_encoder,
248         &coda_bit_decoder,
249 };
250
251 static const struct coda_video_device *coda7_video_devices[] = {
252         &coda_bit_jpeg_encoder,
253         &coda_bit_jpeg_decoder,
254         &coda_bit_encoder,
255         &coda_bit_decoder,
256 };
257
258 static const struct coda_video_device *coda9_video_devices[] = {
259         &coda_bit_encoder,
260         &coda_bit_decoder,
261 };
262
263 /*
264  * Normalize all supported YUV 4:2:0 formats to the value used in the codec
265  * tables.
266  */
267 static u32 coda_format_normalize_yuv(u32 fourcc)
268 {
269         switch (fourcc) {
270         case V4L2_PIX_FMT_NV12:
271         case V4L2_PIX_FMT_YUV420:
272         case V4L2_PIX_FMT_YVU420:
273         case V4L2_PIX_FMT_YUV422P:
274         case V4L2_PIX_FMT_YUYV:
275                 return V4L2_PIX_FMT_YUV420;
276         default:
277                 return fourcc;
278         }
279 }
280
281 static const struct coda_codec *coda_find_codec(struct coda_dev *dev,
282                                                 int src_fourcc, int dst_fourcc)
283 {
284         const struct coda_codec *codecs = dev->devtype->codecs;
285         int num_codecs = dev->devtype->num_codecs;
286         int k;
287
288         src_fourcc = coda_format_normalize_yuv(src_fourcc);
289         dst_fourcc = coda_format_normalize_yuv(dst_fourcc);
290         if (src_fourcc == dst_fourcc)
291                 return NULL;
292
293         for (k = 0; k < num_codecs; k++) {
294                 if (codecs[k].src_fourcc == src_fourcc &&
295                     codecs[k].dst_fourcc == dst_fourcc)
296                         break;
297         }
298
299         if (k == num_codecs)
300                 return NULL;
301
302         return &codecs[k];
303 }
304
305 static void coda_get_max_dimensions(struct coda_dev *dev,
306                                     const struct coda_codec *codec,
307                                     int *max_w, int *max_h)
308 {
309         const struct coda_codec *codecs = dev->devtype->codecs;
310         int num_codecs = dev->devtype->num_codecs;
311         unsigned int w, h;
312         int k;
313
314         if (codec) {
315                 w = codec->max_w;
316                 h = codec->max_h;
317         } else {
318                 for (k = 0, w = 0, h = 0; k < num_codecs; k++) {
319                         w = max(w, codecs[k].max_w);
320                         h = max(h, codecs[k].max_h);
321                 }
322         }
323
324         if (max_w)
325                 *max_w = w;
326         if (max_h)
327                 *max_h = h;
328 }
329
330 static const struct coda_video_device *to_coda_video_device(struct video_device
331                                                             *vdev)
332 {
333         struct coda_dev *dev = video_get_drvdata(vdev);
334         unsigned int i = vdev - dev->vfd;
335
336         if (i >= dev->devtype->num_vdevs)
337                 return NULL;
338
339         return dev->devtype->vdevs[i];
340 }
341
342 const char *coda_product_name(int product)
343 {
344         static char buf[9];
345
346         switch (product) {
347         case CODA_DX6:
348                 return "CodaDx6";
349         case CODA_HX4:
350                 return "CodaHx4";
351         case CODA_7541:
352                 return "CODA7541";
353         case CODA_960:
354                 return "CODA960";
355         default:
356                 snprintf(buf, sizeof(buf), "(0x%04x)", product);
357                 return buf;
358         }
359 }
360
361 static struct vdoa_data *coda_get_vdoa_data(void)
362 {
363         struct device_node *vdoa_node;
364         struct platform_device *vdoa_pdev;
365         struct vdoa_data *vdoa_data = NULL;
366
367         vdoa_node = of_find_compatible_node(NULL, NULL, "fsl,imx6q-vdoa");
368         if (!vdoa_node)
369                 return NULL;
370
371         vdoa_pdev = of_find_device_by_node(vdoa_node);
372         if (!vdoa_pdev)
373                 goto out;
374
375         vdoa_data = platform_get_drvdata(vdoa_pdev);
376         if (!vdoa_data)
377                 vdoa_data = ERR_PTR(-EPROBE_DEFER);
378
379 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(1, 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 coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1519         struct coda_q_data *q_data;
1520
1521         q_data = get_q_data(ctx, vb->vb2_queue->type);
1522
1523         if (vb2_plane_size(vb, 0) < q_data->sizeimage) {
1524                 v4l2_warn(&ctx->dev->v4l2_dev,
1525                           "%s data will not fit into plane (%lu < %lu)\n",
1526                           __func__, vb2_plane_size(vb, 0),
1527                           (long)q_data->sizeimage);
1528                 return -EINVAL;
1529         }
1530
1531         return 0;
1532 }
1533
1534 static void coda_update_menu_ctrl(struct v4l2_ctrl *ctrl, int value)
1535 {
1536         if (!ctrl)
1537                 return;
1538
1539         v4l2_ctrl_lock(ctrl);
1540
1541         /*
1542          * Extend the control range if the parsed stream contains a known but
1543          * unsupported value or level.
1544          */
1545         if (value > ctrl->maximum) {
1546                 __v4l2_ctrl_modify_range(ctrl, ctrl->minimum, value,
1547                         ctrl->menu_skip_mask & ~(1 << value),
1548                         ctrl->default_value);
1549         } else if (value < ctrl->minimum) {
1550                 __v4l2_ctrl_modify_range(ctrl, value, ctrl->maximum,
1551                         ctrl->menu_skip_mask & ~(1 << value),
1552                         ctrl->default_value);
1553         }
1554
1555         __v4l2_ctrl_s_ctrl(ctrl, value);
1556
1557         v4l2_ctrl_unlock(ctrl);
1558 }
1559
1560 static void coda_update_h264_profile_ctrl(struct coda_ctx *ctx)
1561 {
1562         const char * const *profile_names;
1563         int profile;
1564
1565         profile = coda_h264_profile(ctx->params.h264_profile_idc);
1566         if (profile < 0) {
1567                 v4l2_warn(&ctx->dev->v4l2_dev, "Invalid H264 Profile: %u\n",
1568                           ctx->params.h264_profile_idc);
1569                 return;
1570         }
1571
1572         coda_update_menu_ctrl(ctx->h264_profile_ctrl, profile);
1573
1574         profile_names = v4l2_ctrl_get_menu(V4L2_CID_MPEG_VIDEO_H264_PROFILE);
1575
1576         coda_dbg(1, ctx, "Parsed H264 Profile: %s\n", profile_names[profile]);
1577 }
1578
1579 static void coda_update_h264_level_ctrl(struct coda_ctx *ctx)
1580 {
1581         const char * const *level_names;
1582         int level;
1583
1584         level = coda_h264_level(ctx->params.h264_level_idc);
1585         if (level < 0) {
1586                 v4l2_warn(&ctx->dev->v4l2_dev, "Invalid H264 Level: %u\n",
1587                           ctx->params.h264_level_idc);
1588                 return;
1589         }
1590
1591         coda_update_menu_ctrl(ctx->h264_level_ctrl, level);
1592
1593         level_names = v4l2_ctrl_get_menu(V4L2_CID_MPEG_VIDEO_H264_LEVEL);
1594
1595         coda_dbg(1, ctx, "Parsed H264 Level: %s\n", level_names[level]);
1596 }
1597
1598 static void coda_buf_queue(struct vb2_buffer *vb)
1599 {
1600         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1601         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1602         struct vb2_queue *vq = vb->vb2_queue;
1603         struct coda_q_data *q_data;
1604
1605         q_data = get_q_data(ctx, vb->vb2_queue->type);
1606
1607         /*
1608          * In the decoder case, immediately try to copy the buffer into the
1609          * bitstream ringbuffer and mark it as ready to be dequeued.
1610          */
1611         if (ctx->bitstream.size && vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1612                 /*
1613                  * For backwards compatibility, queuing an empty buffer marks
1614                  * the stream end
1615                  */
1616                 if (vb2_get_plane_payload(vb, 0) == 0)
1617                         coda_bit_stream_end_flag(ctx);
1618
1619                 if (q_data->fourcc == V4L2_PIX_FMT_H264) {
1620                         /*
1621                          * Unless already done, try to obtain profile_idc and
1622                          * level_idc from the SPS header. This allows to decide
1623                          * whether to enable reordering during sequence
1624                          * initialization.
1625                          */
1626                         if (!ctx->params.h264_profile_idc) {
1627                                 coda_sps_parse_profile(ctx, vb);
1628                                 coda_update_h264_profile_ctrl(ctx);
1629                                 coda_update_h264_level_ctrl(ctx);
1630                         }
1631                 }
1632
1633                 mutex_lock(&ctx->bitstream_mutex);
1634                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1635                 if (vb2_is_streaming(vb->vb2_queue))
1636                         /* This set buf->sequence = ctx->qsequence++ */
1637                         coda_fill_bitstream(ctx, NULL);
1638                 mutex_unlock(&ctx->bitstream_mutex);
1639         } else {
1640                 if (ctx->inst_type == CODA_INST_ENCODER &&
1641                     vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1642                         vbuf->sequence = ctx->qsequence++;
1643                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1644         }
1645 }
1646
1647 int coda_alloc_aux_buf(struct coda_dev *dev, struct coda_aux_buf *buf,
1648                        size_t size, const char *name, struct dentry *parent)
1649 {
1650         buf->vaddr = dma_alloc_coherent(&dev->plat_dev->dev, size, &buf->paddr,
1651                                         GFP_KERNEL);
1652         if (!buf->vaddr) {
1653                 v4l2_err(&dev->v4l2_dev,
1654                          "Failed to allocate %s buffer of size %zu\n",
1655                          name, size);
1656                 return -ENOMEM;
1657         }
1658
1659         buf->size = size;
1660
1661         if (name && parent) {
1662                 buf->blob.data = buf->vaddr;
1663                 buf->blob.size = size;
1664                 buf->dentry = debugfs_create_blob(name, 0644, parent,
1665                                                   &buf->blob);
1666                 if (!buf->dentry)
1667                         dev_warn(&dev->plat_dev->dev,
1668                                  "failed to create debugfs entry %s\n", name);
1669         }
1670
1671         return 0;
1672 }
1673
1674 void coda_free_aux_buf(struct coda_dev *dev,
1675                        struct coda_aux_buf *buf)
1676 {
1677         if (buf->vaddr) {
1678                 dma_free_coherent(&dev->plat_dev->dev, buf->size,
1679                                   buf->vaddr, buf->paddr);
1680                 buf->vaddr = NULL;
1681                 buf->size = 0;
1682                 debugfs_remove(buf->dentry);
1683                 buf->dentry = NULL;
1684         }
1685 }
1686
1687 static int coda_start_streaming(struct vb2_queue *q, unsigned int count)
1688 {
1689         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1690         struct v4l2_device *v4l2_dev = &ctx->dev->v4l2_dev;
1691         struct coda_q_data *q_data_src, *q_data_dst;
1692         struct v4l2_m2m_buffer *m2m_buf, *tmp;
1693         struct vb2_v4l2_buffer *buf;
1694         struct list_head list;
1695         int ret = 0;
1696
1697         if (count < 1)
1698                 return -EINVAL;
1699
1700         coda_dbg(1, ctx, "start streaming %s\n", v4l2_type_names[q->type]);
1701
1702         INIT_LIST_HEAD(&list);
1703
1704         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
1705         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1706                 if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit) {
1707                         /* copy the buffers that were queued before streamon */
1708                         mutex_lock(&ctx->bitstream_mutex);
1709                         coda_fill_bitstream(ctx, &list);
1710                         mutex_unlock(&ctx->bitstream_mutex);
1711
1712                         if (coda_get_bitstream_payload(ctx) < 512) {
1713                                 ret = -EINVAL;
1714                                 goto err;
1715                         }
1716                 }
1717
1718                 ctx->streamon_out = 1;
1719         } else {
1720                 ctx->streamon_cap = 1;
1721         }
1722
1723         /* Don't start the coda unless both queues are on */
1724         if (!(ctx->streamon_out && ctx->streamon_cap))
1725                 goto out;
1726
1727         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1728         if ((q_data_src->rect.width != q_data_dst->width &&
1729              round_up(q_data_src->rect.width, 16) != q_data_dst->width) ||
1730             (q_data_src->rect.height != q_data_dst->height &&
1731              round_up(q_data_src->rect.height, 16) != q_data_dst->height)) {
1732                 v4l2_err(v4l2_dev, "can't convert %dx%d to %dx%d\n",
1733                          q_data_src->rect.width, q_data_src->rect.height,
1734                          q_data_dst->width, q_data_dst->height);
1735                 ret = -EINVAL;
1736                 goto err;
1737         }
1738
1739         /* Allow BIT decoder device_run with no new buffers queued */
1740         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit)
1741                 v4l2_m2m_set_src_buffered(ctx->fh.m2m_ctx, true);
1742
1743         ctx->gopcounter = ctx->params.gop_size - 1;
1744
1745         if (q_data_dst->fourcc == V4L2_PIX_FMT_JPEG)
1746                 ctx->params.gop_size = 1;
1747         ctx->gopcounter = ctx->params.gop_size - 1;
1748
1749         ret = ctx->ops->start_streaming(ctx);
1750         if (ctx->inst_type == CODA_INST_DECODER) {
1751                 if (ret == -EAGAIN)
1752                         goto out;
1753         }
1754         if (ret < 0)
1755                 goto err;
1756
1757 out:
1758         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1759                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1760                         list_del(&m2m_buf->list);
1761                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_DONE);
1762                 }
1763         }
1764         return 0;
1765
1766 err:
1767         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1768                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1769                         list_del(&m2m_buf->list);
1770                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_QUEUED);
1771                 }
1772                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1773                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1774         } else {
1775                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1776                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1777         }
1778         return ret;
1779 }
1780
1781 static void coda_stop_streaming(struct vb2_queue *q)
1782 {
1783         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1784         struct coda_dev *dev = ctx->dev;
1785         struct vb2_v4l2_buffer *buf;
1786         bool stop;
1787
1788         stop = ctx->streamon_out && ctx->streamon_cap;
1789
1790         coda_dbg(1, ctx, "stop streaming %s\n", v4l2_type_names[q->type]);
1791
1792         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1793                 ctx->streamon_out = 0;
1794
1795                 coda_bit_stream_end_flag(ctx);
1796
1797                 ctx->qsequence = 0;
1798
1799                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1800                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1801         } else {
1802                 ctx->streamon_cap = 0;
1803
1804                 ctx->osequence = 0;
1805                 ctx->sequence_offset = 0;
1806
1807                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1808                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1809         }
1810
1811         if (stop) {
1812                 struct coda_buffer_meta *meta;
1813
1814                 if (ctx->ops->seq_end_work) {
1815                         queue_work(dev->workqueue, &ctx->seq_end_work);
1816                         flush_work(&ctx->seq_end_work);
1817                 }
1818                 spin_lock(&ctx->buffer_meta_lock);
1819                 while (!list_empty(&ctx->buffer_meta_list)) {
1820                         meta = list_first_entry(&ctx->buffer_meta_list,
1821                                                 struct coda_buffer_meta, list);
1822                         list_del(&meta->list);
1823                         kfree(meta);
1824                 }
1825                 ctx->num_metas = 0;
1826                 spin_unlock(&ctx->buffer_meta_lock);
1827                 kfifo_init(&ctx->bitstream_fifo,
1828                         ctx->bitstream.vaddr, ctx->bitstream.size);
1829                 ctx->runcounter = 0;
1830                 ctx->aborting = 0;
1831                 ctx->hold = false;
1832         }
1833
1834         if (!ctx->streamon_out && !ctx->streamon_cap)
1835                 ctx->bit_stream_param &= ~CODA_BIT_STREAM_END_FLAG;
1836 }
1837
1838 static const struct vb2_ops coda_qops = {
1839         .queue_setup            = coda_queue_setup,
1840         .buf_prepare            = coda_buf_prepare,
1841         .buf_queue              = coda_buf_queue,
1842         .start_streaming        = coda_start_streaming,
1843         .stop_streaming         = coda_stop_streaming,
1844         .wait_prepare           = vb2_ops_wait_prepare,
1845         .wait_finish            = vb2_ops_wait_finish,
1846 };
1847
1848 static int coda_s_ctrl(struct v4l2_ctrl *ctrl)
1849 {
1850         struct coda_ctx *ctx =
1851                         container_of(ctrl->handler, struct coda_ctx, ctrls);
1852
1853         coda_dbg(1, ctx, "s_ctrl: id = 0x%x, name = \"%s\", val = %d\n",
1854                  ctrl->id, ctrl->name, ctrl->val);
1855
1856         switch (ctrl->id) {
1857         case V4L2_CID_HFLIP:
1858                 if (ctrl->val)
1859                         ctx->params.rot_mode |= CODA_MIR_HOR;
1860                 else
1861                         ctx->params.rot_mode &= ~CODA_MIR_HOR;
1862                 break;
1863         case V4L2_CID_VFLIP:
1864                 if (ctrl->val)
1865                         ctx->params.rot_mode |= CODA_MIR_VER;
1866                 else
1867                         ctx->params.rot_mode &= ~CODA_MIR_VER;
1868                 break;
1869         case V4L2_CID_MPEG_VIDEO_BITRATE:
1870                 ctx->params.bitrate = ctrl->val / 1000;
1871                 break;
1872         case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
1873                 ctx->params.gop_size = ctrl->val;
1874                 break;
1875         case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
1876                 ctx->params.h264_intra_qp = ctrl->val;
1877                 break;
1878         case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
1879                 ctx->params.h264_inter_qp = ctrl->val;
1880                 break;
1881         case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
1882                 ctx->params.h264_min_qp = ctrl->val;
1883                 break;
1884         case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
1885                 ctx->params.h264_max_qp = ctrl->val;
1886                 break;
1887         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA:
1888                 ctx->params.h264_slice_alpha_c0_offset_div2 = ctrl->val;
1889                 break;
1890         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA:
1891                 ctx->params.h264_slice_beta_offset_div2 = ctrl->val;
1892                 break;
1893         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE:
1894                 ctx->params.h264_disable_deblocking_filter_idc = ctrl->val;
1895                 break;
1896         case V4L2_CID_MPEG_VIDEO_H264_CONSTRAINED_INTRA_PREDICTION:
1897                 ctx->params.h264_constrained_intra_pred_flag = ctrl->val;
1898                 break;
1899         case V4L2_CID_MPEG_VIDEO_H264_CHROMA_QP_INDEX_OFFSET:
1900                 ctx->params.h264_chroma_qp_index_offset = ctrl->val;
1901                 break;
1902         case V4L2_CID_MPEG_VIDEO_H264_PROFILE:
1903                 /* TODO: switch between baseline and constrained baseline */
1904                 if (ctx->inst_type == CODA_INST_ENCODER)
1905                         ctx->params.h264_profile_idc = 66;
1906                 break;
1907         case V4L2_CID_MPEG_VIDEO_H264_LEVEL:
1908                 /* nothing to do, this is set by the encoder */
1909                 break;
1910         case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
1911                 ctx->params.mpeg4_intra_qp = ctrl->val;
1912                 break;
1913         case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
1914                 ctx->params.mpeg4_inter_qp = ctrl->val;
1915                 break;
1916         case V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE:
1917         case V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL:
1918                 /* nothing to do, these are fixed */
1919                 break;
1920         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
1921                 ctx->params.slice_mode = ctrl->val;
1922                 break;
1923         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
1924                 ctx->params.slice_max_mb = ctrl->val;
1925                 break;
1926         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
1927                 ctx->params.slice_max_bits = ctrl->val * 8;
1928                 break;
1929         case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
1930                 break;
1931         case V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB:
1932                 ctx->params.intra_refresh = ctrl->val;
1933                 break;
1934         case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME:
1935                 ctx->params.force_ipicture = true;
1936                 break;
1937         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
1938                 coda_set_jpeg_compression_quality(ctx, ctrl->val);
1939                 break;
1940         case V4L2_CID_JPEG_RESTART_INTERVAL:
1941                 ctx->params.jpeg_restart_interval = ctrl->val;
1942                 break;
1943         case V4L2_CID_MPEG_VIDEO_VBV_DELAY:
1944                 ctx->params.vbv_delay = ctrl->val;
1945                 break;
1946         case V4L2_CID_MPEG_VIDEO_VBV_SIZE:
1947                 ctx->params.vbv_size = min(ctrl->val * 8192, 0x7fffffff);
1948                 break;
1949         default:
1950                 coda_dbg(1, ctx, "Invalid control, id=%d, val=%d\n",
1951                          ctrl->id, ctrl->val);
1952                 return -EINVAL;
1953         }
1954
1955         return 0;
1956 }
1957
1958 static const struct v4l2_ctrl_ops coda_ctrl_ops = {
1959         .s_ctrl = coda_s_ctrl,
1960 };
1961
1962 static void coda_encode_ctrls(struct coda_ctx *ctx)
1963 {
1964         int max_gop_size = (ctx->dev->devtype->product == CODA_DX6) ? 60 : 99;
1965
1966         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1967                 V4L2_CID_MPEG_VIDEO_BITRATE, 0, 32767000, 1000, 0);
1968         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1969                 V4L2_CID_MPEG_VIDEO_GOP_SIZE, 0, max_gop_size, 1, 16);
1970         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1971                 V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP, 0, 51, 1, 25);
1972         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1973                 V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP, 0, 51, 1, 25);
1974         if (ctx->dev->devtype->product != CODA_960) {
1975                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1976                         V4L2_CID_MPEG_VIDEO_H264_MIN_QP, 0, 51, 1, 12);
1977         }
1978         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1979                 V4L2_CID_MPEG_VIDEO_H264_MAX_QP, 0, 51, 1, 51);
1980         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1981                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA, -6, 6, 1, 0);
1982         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1983                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA, -6, 6, 1, 0);
1984         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1985                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE,
1986                 V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY,
1987                 0x0, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED);
1988         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1989                 V4L2_CID_MPEG_VIDEO_H264_CONSTRAINED_INTRA_PREDICTION, 0, 1, 1,
1990                 0);
1991         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1992                 V4L2_CID_MPEG_VIDEO_H264_CHROMA_QP_INDEX_OFFSET, -12, 12, 1, 0);
1993         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1994                 V4L2_CID_MPEG_VIDEO_H264_PROFILE,
1995                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE, 0x0,
1996                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE);
1997         if (ctx->dev->devtype->product == CODA_HX4 ||
1998             ctx->dev->devtype->product == CODA_7541) {
1999                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2000                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
2001                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1,
2002                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
2003                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
2004                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1)),
2005                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1);
2006         }
2007         if (ctx->dev->devtype->product == CODA_960) {
2008                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2009                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
2010                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0,
2011                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
2012                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
2013                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1) |
2014                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_2) |
2015                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_4_0)),
2016                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0);
2017         }
2018         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2019                 V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP, 1, 31, 1, 2);
2020         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2021                 V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP, 1, 31, 1, 2);
2022         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2023                 V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE,
2024                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE, 0x0,
2025                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE);
2026         if (ctx->dev->devtype->product == CODA_HX4 ||
2027             ctx->dev->devtype->product == CODA_7541 ||
2028             ctx->dev->devtype->product == CODA_960) {
2029                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2030                         V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL,
2031                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5,
2032                         ~(1 << V4L2_MPEG_VIDEO_MPEG4_LEVEL_5),
2033                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5);
2034         }
2035         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2036                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE,
2037                 V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES, 0x0,
2038                 V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE);
2039         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2040                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB, 1, 0x3fffffff, 1, 1);
2041         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2042                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES, 1, 0x3fffffff, 1,
2043                 500);
2044         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2045                 V4L2_CID_MPEG_VIDEO_HEADER_MODE,
2046                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME,
2047                 (1 << V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE),
2048                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME);
2049         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2050                 V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB, 0,
2051                 1920 * 1088 / 256, 1, 0);
2052         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2053                 V4L2_CID_MPEG_VIDEO_VBV_DELAY, 0, 0x7fff, 1, 0);
2054         /*
2055          * The maximum VBV size value is 0x7fffffff bits,
2056          * one bit less than 262144 KiB
2057          */
2058         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2059                 V4L2_CID_MPEG_VIDEO_VBV_SIZE, 0, 262144, 1, 0);
2060 }
2061
2062 static void coda_jpeg_encode_ctrls(struct coda_ctx *ctx)
2063 {
2064         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2065                 V4L2_CID_JPEG_COMPRESSION_QUALITY, 5, 100, 1, 50);
2066         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2067                 V4L2_CID_JPEG_RESTART_INTERVAL, 0, 100, 1, 0);
2068 }
2069
2070 static void coda_decode_ctrls(struct coda_ctx *ctx)
2071 {
2072         u8 max;
2073
2074         ctx->h264_profile_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2075                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_H264_PROFILE,
2076                 V4L2_MPEG_VIDEO_H264_PROFILE_HIGH,
2077                 ~((1 << V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE) |
2078                   (1 << V4L2_MPEG_VIDEO_H264_PROFILE_MAIN) |
2079                   (1 << V4L2_MPEG_VIDEO_H264_PROFILE_HIGH)),
2080                 V4L2_MPEG_VIDEO_H264_PROFILE_HIGH);
2081         if (ctx->h264_profile_ctrl)
2082                 ctx->h264_profile_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2083
2084         if (ctx->dev->devtype->product == CODA_HX4 ||
2085             ctx->dev->devtype->product == CODA_7541)
2086                 max = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
2087         else if (ctx->dev->devtype->product == CODA_960)
2088                 max = V4L2_MPEG_VIDEO_H264_LEVEL_4_1;
2089         else
2090                 return;
2091         ctx->h264_level_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2092                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_H264_LEVEL, max, 0, max);
2093         if (ctx->h264_level_ctrl)
2094                 ctx->h264_level_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2095 }
2096
2097 static int coda_ctrls_setup(struct coda_ctx *ctx)
2098 {
2099         v4l2_ctrl_handler_init(&ctx->ctrls, 2);
2100
2101         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2102                 V4L2_CID_HFLIP, 0, 1, 1, 0);
2103         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2104                 V4L2_CID_VFLIP, 0, 1, 1, 0);
2105         if (ctx->inst_type == CODA_INST_ENCODER) {
2106                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2107                                   V4L2_CID_MIN_BUFFERS_FOR_OUTPUT,
2108                                   1, 1, 1, 1);
2109                 if (ctx->cvd->dst_formats[0] == V4L2_PIX_FMT_JPEG)
2110                         coda_jpeg_encode_ctrls(ctx);
2111                 else
2112                         coda_encode_ctrls(ctx);
2113         } else {
2114                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2115                                   V4L2_CID_MIN_BUFFERS_FOR_CAPTURE,
2116                                   1, 1, 1, 1);
2117                 if (ctx->cvd->src_formats[0] == V4L2_PIX_FMT_H264)
2118                         coda_decode_ctrls(ctx);
2119         }
2120
2121         if (ctx->ctrls.error) {
2122                 v4l2_err(&ctx->dev->v4l2_dev,
2123                         "control initialization error (%d)",
2124                         ctx->ctrls.error);
2125                 return -EINVAL;
2126         }
2127
2128         return v4l2_ctrl_handler_setup(&ctx->ctrls);
2129 }
2130
2131 static int coda_queue_init(struct coda_ctx *ctx, struct vb2_queue *vq)
2132 {
2133         vq->drv_priv = ctx;
2134         vq->ops = &coda_qops;
2135         vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
2136         vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
2137         vq->lock = &ctx->dev->dev_mutex;
2138         /* One way to indicate end-of-stream for coda is to set the
2139          * bytesused == 0. However by default videobuf2 handles bytesused
2140          * equal to 0 as a special case and changes its value to the size
2141          * of the buffer. Set the allow_zero_bytesused flag, so
2142          * that videobuf2 will keep the value of bytesused intact.
2143          */
2144         vq->allow_zero_bytesused = 1;
2145         /*
2146          * We might be fine with no buffers on some of the queues, but that
2147          * would need to be reflected in job_ready(). Currently we expect all
2148          * queues to have at least one buffer queued.
2149          */
2150         vq->min_buffers_needed = 1;
2151         vq->dev = &ctx->dev->plat_dev->dev;
2152
2153         return vb2_queue_init(vq);
2154 }
2155
2156 int coda_encoder_queue_init(void *priv, struct vb2_queue *src_vq,
2157                             struct vb2_queue *dst_vq)
2158 {
2159         int ret;
2160
2161         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
2162         src_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2163         src_vq->mem_ops = &vb2_dma_contig_memops;
2164
2165         ret = coda_queue_init(priv, src_vq);
2166         if (ret)
2167                 return ret;
2168
2169         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2170         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2171         dst_vq->mem_ops = &vb2_dma_contig_memops;
2172
2173         return coda_queue_init(priv, dst_vq);
2174 }
2175
2176 int coda_decoder_queue_init(void *priv, struct vb2_queue *src_vq,
2177                             struct vb2_queue *dst_vq)
2178 {
2179         int ret;
2180
2181         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
2182         src_vq->io_modes = VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
2183         src_vq->mem_ops = &vb2_vmalloc_memops;
2184
2185         ret = coda_queue_init(priv, src_vq);
2186         if (ret)
2187                 return ret;
2188
2189         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2190         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2191         dst_vq->mem_ops = &vb2_dma_contig_memops;
2192
2193         return coda_queue_init(priv, dst_vq);
2194 }
2195
2196 /*
2197  * File operations
2198  */
2199
2200 static int coda_open(struct file *file)
2201 {
2202         struct video_device *vdev = video_devdata(file);
2203         struct coda_dev *dev = video_get_drvdata(vdev);
2204         struct coda_ctx *ctx;
2205         unsigned int max = ~0;
2206         char *name;
2207         int ret;
2208         int idx;
2209
2210         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
2211         if (!ctx)
2212                 return -ENOMEM;
2213
2214         if (dev->devtype->product == CODA_DX6)
2215                 max = CODADX6_MAX_INSTANCES - 1;
2216         idx = ida_alloc_max(&dev->ida, max, GFP_KERNEL);
2217         if (idx < 0) {
2218                 ret = idx;
2219                 goto err_coda_max;
2220         }
2221
2222         name = kasprintf(GFP_KERNEL, "context%d", idx);
2223         if (!name) {
2224                 ret = -ENOMEM;
2225                 goto err_coda_name_init;
2226         }
2227
2228         ctx->debugfs_entry = debugfs_create_dir(name, dev->debugfs_root);
2229         kfree(name);
2230
2231         ctx->cvd = to_coda_video_device(vdev);
2232         ctx->inst_type = ctx->cvd->type;
2233         ctx->ops = ctx->cvd->ops;
2234         ctx->use_bit = !ctx->cvd->direct;
2235         init_completion(&ctx->completion);
2236         INIT_WORK(&ctx->pic_run_work, coda_pic_run_work);
2237         if (ctx->ops->seq_end_work)
2238                 INIT_WORK(&ctx->seq_end_work, ctx->ops->seq_end_work);
2239         v4l2_fh_init(&ctx->fh, video_devdata(file));
2240         file->private_data = &ctx->fh;
2241         v4l2_fh_add(&ctx->fh);
2242         ctx->dev = dev;
2243         ctx->idx = idx;
2244
2245         coda_dbg(1, ctx, "open instance (%p)\n", ctx);
2246
2247         switch (dev->devtype->product) {
2248         case CODA_960:
2249                 /*
2250                  * Enabling the BWB when decoding can hang the firmware with
2251                  * certain streams. The issue was tracked as ENGR00293425 by
2252                  * Freescale. As a workaround, disable BWB for all decoders.
2253                  * The enable_bwb module parameter allows to override this.
2254                  */
2255                 if (enable_bwb || ctx->inst_type == CODA_INST_ENCODER)
2256                         ctx->frame_mem_ctrl = CODA9_FRAME_ENABLE_BWB;
2257                 /* fallthrough */
2258         case CODA_HX4:
2259         case CODA_7541:
2260                 ctx->reg_idx = 0;
2261                 break;
2262         default:
2263                 ctx->reg_idx = idx;
2264         }
2265         if (ctx->dev->vdoa && !disable_vdoa) {
2266                 ctx->vdoa = vdoa_context_create(dev->vdoa);
2267                 if (!ctx->vdoa)
2268                         v4l2_warn(&dev->v4l2_dev,
2269                                   "Failed to create vdoa context: not using vdoa");
2270         }
2271         ctx->use_vdoa = false;
2272
2273         /* Power up and upload firmware if necessary */
2274         ret = pm_runtime_get_sync(&dev->plat_dev->dev);
2275         if (ret < 0) {
2276                 v4l2_err(&dev->v4l2_dev, "failed to power up: %d\n", ret);
2277                 goto err_pm_get;
2278         }
2279
2280         ret = clk_prepare_enable(dev->clk_per);
2281         if (ret)
2282                 goto err_clk_per;
2283
2284         ret = clk_prepare_enable(dev->clk_ahb);
2285         if (ret)
2286                 goto err_clk_ahb;
2287
2288         set_default_params(ctx);
2289         ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx,
2290                                             ctx->ops->queue_init);
2291         if (IS_ERR(ctx->fh.m2m_ctx)) {
2292                 ret = PTR_ERR(ctx->fh.m2m_ctx);
2293
2294                 v4l2_err(&dev->v4l2_dev, "%s return error (%d)\n",
2295                          __func__, ret);
2296                 goto err_ctx_init;
2297         }
2298
2299         ret = coda_ctrls_setup(ctx);
2300         if (ret) {
2301                 v4l2_err(&dev->v4l2_dev, "failed to setup coda controls\n");
2302                 goto err_ctrls_setup;
2303         }
2304
2305         ctx->fh.ctrl_handler = &ctx->ctrls;
2306
2307         mutex_init(&ctx->bitstream_mutex);
2308         mutex_init(&ctx->buffer_mutex);
2309         INIT_LIST_HEAD(&ctx->buffer_meta_list);
2310         spin_lock_init(&ctx->buffer_meta_lock);
2311
2312         return 0;
2313
2314 err_ctrls_setup:
2315         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
2316 err_ctx_init:
2317         clk_disable_unprepare(dev->clk_ahb);
2318 err_clk_ahb:
2319         clk_disable_unprepare(dev->clk_per);
2320 err_clk_per:
2321         pm_runtime_put_sync(&dev->plat_dev->dev);
2322 err_pm_get:
2323         v4l2_fh_del(&ctx->fh);
2324         v4l2_fh_exit(&ctx->fh);
2325 err_coda_name_init:
2326         ida_free(&dev->ida, ctx->idx);
2327 err_coda_max:
2328         kfree(ctx);
2329         return ret;
2330 }
2331
2332 static int coda_release(struct file *file)
2333 {
2334         struct coda_dev *dev = video_drvdata(file);
2335         struct coda_ctx *ctx = fh_to_ctx(file->private_data);
2336
2337         coda_dbg(1, ctx, "release instance (%p)\n", ctx);
2338
2339         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit)
2340                 coda_bit_stream_end_flag(ctx);
2341
2342         /* If this instance is running, call .job_abort and wait for it to end */
2343         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
2344
2345         if (ctx->vdoa)
2346                 vdoa_context_destroy(ctx->vdoa);
2347
2348         /* In case the instance was not running, we still need to call SEQ_END */
2349         if (ctx->ops->seq_end_work) {
2350                 queue_work(dev->workqueue, &ctx->seq_end_work);
2351                 flush_work(&ctx->seq_end_work);
2352         }
2353
2354         if (ctx->dev->devtype->product == CODA_DX6)
2355                 coda_free_aux_buf(dev, &ctx->workbuf);
2356
2357         v4l2_ctrl_handler_free(&ctx->ctrls);
2358         clk_disable_unprepare(dev->clk_ahb);
2359         clk_disable_unprepare(dev->clk_per);
2360         pm_runtime_put_sync(&dev->plat_dev->dev);
2361         v4l2_fh_del(&ctx->fh);
2362         v4l2_fh_exit(&ctx->fh);
2363         ida_free(&dev->ida, ctx->idx);
2364         if (ctx->ops->release)
2365                 ctx->ops->release(ctx);
2366         debugfs_remove_recursive(ctx->debugfs_entry);
2367         kfree(ctx);
2368
2369         return 0;
2370 }
2371
2372 static const struct v4l2_file_operations coda_fops = {
2373         .owner          = THIS_MODULE,
2374         .open           = coda_open,
2375         .release        = coda_release,
2376         .poll           = v4l2_m2m_fop_poll,
2377         .unlocked_ioctl = video_ioctl2,
2378         .mmap           = v4l2_m2m_fop_mmap,
2379 };
2380
2381 static int coda_hw_init(struct coda_dev *dev)
2382 {
2383         u32 data;
2384         u16 *p;
2385         int i, ret;
2386
2387         ret = clk_prepare_enable(dev->clk_per);
2388         if (ret)
2389                 goto err_clk_per;
2390
2391         ret = clk_prepare_enable(dev->clk_ahb);
2392         if (ret)
2393                 goto err_clk_ahb;
2394
2395         reset_control_reset(dev->rstc);
2396
2397         /*
2398          * Copy the first CODA_ISRAM_SIZE in the internal SRAM.
2399          * The 16-bit chars in the code buffer are in memory access
2400          * order, re-sort them to CODA order for register download.
2401          * Data in this SRAM survives a reboot.
2402          */
2403         p = (u16 *)dev->codebuf.vaddr;
2404         if (dev->devtype->product == CODA_DX6) {
2405                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++)  {
2406                         data = CODA_DOWN_ADDRESS_SET(i) |
2407                                 CODA_DOWN_DATA_SET(p[i ^ 1]);
2408                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
2409                 }
2410         } else {
2411                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++) {
2412                         data = CODA_DOWN_ADDRESS_SET(i) |
2413                                 CODA_DOWN_DATA_SET(p[round_down(i, 4) +
2414                                                         3 - (i % 4)]);
2415                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
2416                 }
2417         }
2418
2419         /* Clear registers */
2420         for (i = 0; i < 64; i++)
2421                 coda_write(dev, 0, CODA_REG_BIT_CODE_BUF_ADDR + i * 4);
2422
2423         /* Tell the BIT where to find everything it needs */
2424         if (dev->devtype->product == CODA_960 ||
2425             dev->devtype->product == CODA_7541 ||
2426             dev->devtype->product == CODA_HX4) {
2427                 coda_write(dev, dev->tempbuf.paddr,
2428                                 CODA_REG_BIT_TEMP_BUF_ADDR);
2429                 coda_write(dev, 0, CODA_REG_BIT_BIT_STREAM_PARAM);
2430         } else {
2431                 coda_write(dev, dev->workbuf.paddr,
2432                               CODA_REG_BIT_WORK_BUF_ADDR);
2433         }
2434         coda_write(dev, dev->codebuf.paddr,
2435                       CODA_REG_BIT_CODE_BUF_ADDR);
2436         coda_write(dev, 0, CODA_REG_BIT_CODE_RUN);
2437
2438         /* Set default values */
2439         switch (dev->devtype->product) {
2440         case CODA_DX6:
2441                 coda_write(dev, CODADX6_STREAM_BUF_PIC_FLUSH,
2442                            CODA_REG_BIT_STREAM_CTRL);
2443                 break;
2444         default:
2445                 coda_write(dev, CODA7_STREAM_BUF_PIC_FLUSH,
2446                            CODA_REG_BIT_STREAM_CTRL);
2447         }
2448         if (dev->devtype->product == CODA_960)
2449                 coda_write(dev, CODA9_FRAME_ENABLE_BWB,
2450                                 CODA_REG_BIT_FRAME_MEM_CTRL);
2451         else
2452                 coda_write(dev, 0, CODA_REG_BIT_FRAME_MEM_CTRL);
2453
2454         if (dev->devtype->product != CODA_DX6)
2455                 coda_write(dev, 0, CODA7_REG_BIT_AXI_SRAM_USE);
2456
2457         coda_write(dev, CODA_INT_INTERRUPT_ENABLE,
2458                       CODA_REG_BIT_INT_ENABLE);
2459
2460         /* Reset VPU and start processor */
2461         data = coda_read(dev, CODA_REG_BIT_CODE_RESET);
2462         data |= CODA_REG_RESET_ENABLE;
2463         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
2464         udelay(10);
2465         data &= ~CODA_REG_RESET_ENABLE;
2466         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
2467         coda_write(dev, CODA_REG_RUN_ENABLE, CODA_REG_BIT_CODE_RUN);
2468
2469         clk_disable_unprepare(dev->clk_ahb);
2470         clk_disable_unprepare(dev->clk_per);
2471
2472         return 0;
2473
2474 err_clk_ahb:
2475         clk_disable_unprepare(dev->clk_per);
2476 err_clk_per:
2477         return ret;
2478 }
2479
2480 static int coda_register_device(struct coda_dev *dev, int i)
2481 {
2482         struct video_device *vfd = &dev->vfd[i];
2483
2484         if (i >= dev->devtype->num_vdevs)
2485                 return -EINVAL;
2486
2487         strscpy(vfd->name, dev->devtype->vdevs[i]->name, sizeof(vfd->name));
2488         vfd->fops       = &coda_fops;
2489         vfd->ioctl_ops  = &coda_ioctl_ops;
2490         vfd->release    = video_device_release_empty,
2491         vfd->lock       = &dev->dev_mutex;
2492         vfd->v4l2_dev   = &dev->v4l2_dev;
2493         vfd->vfl_dir    = VFL_DIR_M2M;
2494         video_set_drvdata(vfd, dev);
2495
2496         /* Not applicable, use the selection API instead */
2497         v4l2_disable_ioctl(vfd, VIDIOC_CROPCAP);
2498         v4l2_disable_ioctl(vfd, VIDIOC_G_CROP);
2499         v4l2_disable_ioctl(vfd, VIDIOC_S_CROP);
2500
2501         return video_register_device(vfd, VFL_TYPE_GRABBER, 0);
2502 }
2503
2504 static void coda_copy_firmware(struct coda_dev *dev, const u8 * const buf,
2505                                size_t size)
2506 {
2507         u32 *src = (u32 *)buf;
2508
2509         /* Check if the firmware has a 16-byte Freescale header, skip it */
2510         if (buf[0] == 'M' && buf[1] == 'X')
2511                 src += 4;
2512         /*
2513          * Check whether the firmware is in native order or pre-reordered for
2514          * memory access. The first instruction opcode always is 0xe40e.
2515          */
2516         if (__le16_to_cpup((__le16 *)src) == 0xe40e) {
2517                 u32 *dst = dev->codebuf.vaddr;
2518                 int i;
2519
2520                 /* Firmware in native order, reorder while copying */
2521                 if (dev->devtype->product == CODA_DX6) {
2522                         for (i = 0; i < (size - 16) / 4; i++)
2523                                 dst[i] = (src[i] << 16) | (src[i] >> 16);
2524                 } else {
2525                         for (i = 0; i < (size - 16) / 4; i += 2) {
2526                                 dst[i] = (src[i + 1] << 16) | (src[i + 1] >> 16);
2527                                 dst[i + 1] = (src[i] << 16) | (src[i] >> 16);
2528                         }
2529                 }
2530         } else {
2531                 /* Copy the already reordered firmware image */
2532                 memcpy(dev->codebuf.vaddr, src, size);
2533         }
2534 }
2535
2536 static void coda_fw_callback(const struct firmware *fw, void *context);
2537
2538 static int coda_firmware_request(struct coda_dev *dev)
2539 {
2540         char *fw;
2541
2542         if (dev->firmware >= ARRAY_SIZE(dev->devtype->firmware))
2543                 return -EINVAL;
2544
2545         fw = dev->devtype->firmware[dev->firmware];
2546
2547         dev_dbg(&dev->plat_dev->dev, "requesting firmware '%s' for %s\n", fw,
2548                 coda_product_name(dev->devtype->product));
2549
2550         return request_firmware_nowait(THIS_MODULE, true, fw,
2551                                        &dev->plat_dev->dev, GFP_KERNEL, dev,
2552                                        coda_fw_callback);
2553 }
2554
2555 static void coda_fw_callback(const struct firmware *fw, void *context)
2556 {
2557         struct coda_dev *dev = context;
2558         struct platform_device *pdev = dev->plat_dev;
2559         int i, ret;
2560
2561         if (!fw) {
2562                 dev->firmware++;
2563                 ret = coda_firmware_request(dev);
2564                 if (ret < 0) {
2565                         v4l2_err(&dev->v4l2_dev, "firmware request failed\n");
2566                         goto put_pm;
2567                 }
2568                 return;
2569         }
2570         if (dev->firmware > 0) {
2571                 /*
2572                  * Since we can't suppress warnings for failed asynchronous
2573                  * firmware requests, report that the fallback firmware was
2574                  * found.
2575                  */
2576                 dev_info(&pdev->dev, "Using fallback firmware %s\n",
2577                          dev->devtype->firmware[dev->firmware]);
2578         }
2579
2580         /* allocate auxiliary per-device code buffer for the BIT processor */
2581         ret = coda_alloc_aux_buf(dev, &dev->codebuf, fw->size, "codebuf",
2582                                  dev->debugfs_root);
2583         if (ret < 0)
2584                 goto put_pm;
2585
2586         coda_copy_firmware(dev, fw->data, fw->size);
2587         release_firmware(fw);
2588
2589         ret = coda_hw_init(dev);
2590         if (ret < 0) {
2591                 v4l2_err(&dev->v4l2_dev, "HW initialization failed\n");
2592                 goto put_pm;
2593         }
2594
2595         ret = coda_check_firmware(dev);
2596         if (ret < 0)
2597                 goto put_pm;
2598
2599         dev->m2m_dev = v4l2_m2m_init(&coda_m2m_ops);
2600         if (IS_ERR(dev->m2m_dev)) {
2601                 v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n");
2602                 goto put_pm;
2603         }
2604
2605         for (i = 0; i < dev->devtype->num_vdevs; i++) {
2606                 ret = coda_register_device(dev, i);
2607                 if (ret) {
2608                         v4l2_err(&dev->v4l2_dev,
2609                                  "Failed to register %s video device: %d\n",
2610                                  dev->devtype->vdevs[i]->name, ret);
2611                         goto rel_vfd;
2612                 }
2613         }
2614
2615         v4l2_info(&dev->v4l2_dev, "codec registered as /dev/video[%d-%d]\n",
2616                   dev->vfd[0].num, dev->vfd[i - 1].num);
2617
2618         pm_runtime_put_sync(&pdev->dev);
2619         return;
2620
2621 rel_vfd:
2622         while (--i >= 0)
2623                 video_unregister_device(&dev->vfd[i]);
2624         v4l2_m2m_release(dev->m2m_dev);
2625 put_pm:
2626         pm_runtime_put_sync(&pdev->dev);
2627 }
2628
2629 enum coda_platform {
2630         CODA_IMX27,
2631         CODA_IMX51,
2632         CODA_IMX53,
2633         CODA_IMX6Q,
2634         CODA_IMX6DL,
2635 };
2636
2637 static const struct coda_devtype coda_devdata[] = {
2638         [CODA_IMX27] = {
2639                 .firmware     = {
2640                         "vpu_fw_imx27_TO2.bin",
2641                         "vpu/vpu_fw_imx27_TO2.bin",
2642                         "v4l-codadx6-imx27.bin"
2643                 },
2644                 .product      = CODA_DX6,
2645                 .codecs       = codadx6_codecs,
2646                 .num_codecs   = ARRAY_SIZE(codadx6_codecs),
2647                 .vdevs        = codadx6_video_devices,
2648                 .num_vdevs    = ARRAY_SIZE(codadx6_video_devices),
2649                 .workbuf_size = 288 * 1024 + FMO_SLICE_SAVE_BUF_SIZE * 8 * 1024,
2650                 .iram_size    = 0xb000,
2651         },
2652         [CODA_IMX51] = {
2653                 .firmware     = {
2654                         "vpu_fw_imx51.bin",
2655                         "vpu/vpu_fw_imx51.bin",
2656                         "v4l-codahx4-imx51.bin"
2657                 },
2658                 .product      = CODA_HX4,
2659                 .codecs       = codahx4_codecs,
2660                 .num_codecs   = ARRAY_SIZE(codahx4_codecs),
2661                 .vdevs        = codahx4_video_devices,
2662                 .num_vdevs    = ARRAY_SIZE(codahx4_video_devices),
2663                 .workbuf_size = 128 * 1024,
2664                 .tempbuf_size = 304 * 1024,
2665                 .iram_size    = 0x14000,
2666         },
2667         [CODA_IMX53] = {
2668                 .firmware     = {
2669                         "vpu_fw_imx53.bin",
2670                         "vpu/vpu_fw_imx53.bin",
2671                         "v4l-coda7541-imx53.bin"
2672                 },
2673                 .product      = CODA_7541,
2674                 .codecs       = coda7_codecs,
2675                 .num_codecs   = ARRAY_SIZE(coda7_codecs),
2676                 .vdevs        = coda7_video_devices,
2677                 .num_vdevs    = ARRAY_SIZE(coda7_video_devices),
2678                 .workbuf_size = 128 * 1024,
2679                 .tempbuf_size = 304 * 1024,
2680                 .iram_size    = 0x14000,
2681         },
2682         [CODA_IMX6Q] = {
2683                 .firmware     = {
2684                         "vpu_fw_imx6q.bin",
2685                         "vpu/vpu_fw_imx6q.bin",
2686                         "v4l-coda960-imx6q.bin"
2687                 },
2688                 .product      = CODA_960,
2689                 .codecs       = coda9_codecs,
2690                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2691                 .vdevs        = coda9_video_devices,
2692                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2693                 .workbuf_size = 80 * 1024,
2694                 .tempbuf_size = 204 * 1024,
2695                 .iram_size    = 0x21000,
2696         },
2697         [CODA_IMX6DL] = {
2698                 .firmware     = {
2699                         "vpu_fw_imx6d.bin",
2700                         "vpu/vpu_fw_imx6d.bin",
2701                         "v4l-coda960-imx6dl.bin"
2702                 },
2703                 .product      = CODA_960,
2704                 .codecs       = coda9_codecs,
2705                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2706                 .vdevs        = coda9_video_devices,
2707                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2708                 .workbuf_size = 80 * 1024,
2709                 .tempbuf_size = 204 * 1024,
2710                 .iram_size    = 0x1f000, /* leave 4k for suspend code */
2711         },
2712 };
2713
2714 static const struct platform_device_id coda_platform_ids[] = {
2715         { .name = "coda-imx27", .driver_data = CODA_IMX27 },
2716         { /* sentinel */ }
2717 };
2718 MODULE_DEVICE_TABLE(platform, coda_platform_ids);
2719
2720 #ifdef CONFIG_OF
2721 static const struct of_device_id coda_dt_ids[] = {
2722         { .compatible = "fsl,imx27-vpu", .data = &coda_devdata[CODA_IMX27] },
2723         { .compatible = "fsl,imx51-vpu", .data = &coda_devdata[CODA_IMX51] },
2724         { .compatible = "fsl,imx53-vpu", .data = &coda_devdata[CODA_IMX53] },
2725         { .compatible = "fsl,imx6q-vpu", .data = &coda_devdata[CODA_IMX6Q] },
2726         { .compatible = "fsl,imx6dl-vpu", .data = &coda_devdata[CODA_IMX6DL] },
2727         { /* sentinel */ }
2728 };
2729 MODULE_DEVICE_TABLE(of, coda_dt_ids);
2730 #endif
2731
2732 static int coda_probe(struct platform_device *pdev)
2733 {
2734         const struct of_device_id *of_id =
2735                         of_match_device(of_match_ptr(coda_dt_ids), &pdev->dev);
2736         const struct platform_device_id *pdev_id;
2737         struct coda_platform_data *pdata = pdev->dev.platform_data;
2738         struct device_node *np = pdev->dev.of_node;
2739         struct gen_pool *pool;
2740         struct coda_dev *dev;
2741         struct resource *res;
2742         int ret, irq;
2743
2744         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
2745         if (!dev)
2746                 return -ENOMEM;
2747
2748         pdev_id = of_id ? of_id->data : platform_get_device_id(pdev);
2749
2750         if (of_id)
2751                 dev->devtype = of_id->data;
2752         else if (pdev_id)
2753                 dev->devtype = &coda_devdata[pdev_id->driver_data];
2754         else
2755                 return -EINVAL;
2756
2757         spin_lock_init(&dev->irqlock);
2758
2759         dev->plat_dev = pdev;
2760         dev->clk_per = devm_clk_get(&pdev->dev, "per");
2761         if (IS_ERR(dev->clk_per)) {
2762                 dev_err(&pdev->dev, "Could not get per clock\n");
2763                 return PTR_ERR(dev->clk_per);
2764         }
2765
2766         dev->clk_ahb = devm_clk_get(&pdev->dev, "ahb");
2767         if (IS_ERR(dev->clk_ahb)) {
2768                 dev_err(&pdev->dev, "Could not get ahb clock\n");
2769                 return PTR_ERR(dev->clk_ahb);
2770         }
2771
2772         /* Get  memory for physical registers */
2773         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2774         dev->regs_base = devm_ioremap_resource(&pdev->dev, res);
2775         if (IS_ERR(dev->regs_base))
2776                 return PTR_ERR(dev->regs_base);
2777
2778         /* IRQ */
2779         irq = platform_get_irq_byname(pdev, "bit");
2780         if (irq < 0)
2781                 irq = platform_get_irq(pdev, 0);
2782         if (irq < 0) {
2783                 dev_err(&pdev->dev, "failed to get irq resource\n");
2784                 return irq;
2785         }
2786
2787         ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, coda_irq_handler,
2788                         IRQF_ONESHOT, dev_name(&pdev->dev), dev);
2789         if (ret < 0) {
2790                 dev_err(&pdev->dev, "failed to request irq: %d\n", ret);
2791                 return ret;
2792         }
2793
2794         dev->rstc = devm_reset_control_get_optional_exclusive(&pdev->dev,
2795                                                               NULL);
2796         if (IS_ERR(dev->rstc)) {
2797                 ret = PTR_ERR(dev->rstc);
2798                 dev_err(&pdev->dev, "failed get reset control: %d\n", ret);
2799                 return ret;
2800         }
2801
2802         /* Get IRAM pool from device tree or platform data */
2803         pool = of_gen_pool_get(np, "iram", 0);
2804         if (!pool && pdata)
2805                 pool = gen_pool_get(pdata->iram_dev, NULL);
2806         if (!pool) {
2807                 dev_err(&pdev->dev, "iram pool not available\n");
2808                 return -ENOMEM;
2809         }
2810         dev->iram_pool = pool;
2811
2812         /* Get vdoa_data if supported by the platform */
2813         dev->vdoa = coda_get_vdoa_data();
2814         if (PTR_ERR(dev->vdoa) == -EPROBE_DEFER)
2815                 return -EPROBE_DEFER;
2816
2817         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
2818         if (ret)
2819                 return ret;
2820
2821         mutex_init(&dev->dev_mutex);
2822         mutex_init(&dev->coda_mutex);
2823         ida_init(&dev->ida);
2824
2825         dev->debugfs_root = debugfs_create_dir("coda", NULL);
2826         if (!dev->debugfs_root)
2827                 dev_warn(&pdev->dev, "failed to create debugfs root\n");
2828
2829         /* allocate auxiliary per-device buffers for the BIT processor */
2830         if (dev->devtype->product == CODA_DX6) {
2831                 ret = coda_alloc_aux_buf(dev, &dev->workbuf,
2832                                          dev->devtype->workbuf_size, "workbuf",
2833                                          dev->debugfs_root);
2834                 if (ret < 0)
2835                         goto err_v4l2_register;
2836         }
2837
2838         if (dev->devtype->tempbuf_size) {
2839                 ret = coda_alloc_aux_buf(dev, &dev->tempbuf,
2840                                          dev->devtype->tempbuf_size, "tempbuf",
2841                                          dev->debugfs_root);
2842                 if (ret < 0)
2843                         goto err_v4l2_register;
2844         }
2845
2846         dev->iram.size = dev->devtype->iram_size;
2847         dev->iram.vaddr = gen_pool_dma_alloc(dev->iram_pool, dev->iram.size,
2848                                              &dev->iram.paddr);
2849         if (!dev->iram.vaddr) {
2850                 dev_warn(&pdev->dev, "unable to alloc iram\n");
2851         } else {
2852                 memset(dev->iram.vaddr, 0, dev->iram.size);
2853                 dev->iram.blob.data = dev->iram.vaddr;
2854                 dev->iram.blob.size = dev->iram.size;
2855                 dev->iram.dentry = debugfs_create_blob("iram", 0644,
2856                                                        dev->debugfs_root,
2857                                                        &dev->iram.blob);
2858         }
2859
2860         dev->workqueue = alloc_workqueue("coda", WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
2861         if (!dev->workqueue) {
2862                 dev_err(&pdev->dev, "unable to alloc workqueue\n");
2863                 ret = -ENOMEM;
2864                 goto err_v4l2_register;
2865         }
2866
2867         platform_set_drvdata(pdev, dev);
2868
2869         /*
2870          * Start activated so we can directly call coda_hw_init in
2871          * coda_fw_callback regardless of whether CONFIG_PM is
2872          * enabled or whether the device is associated with a PM domain.
2873          */
2874         pm_runtime_get_noresume(&pdev->dev);
2875         pm_runtime_set_active(&pdev->dev);
2876         pm_runtime_enable(&pdev->dev);
2877
2878         ret = coda_firmware_request(dev);
2879         if (ret)
2880                 goto err_alloc_workqueue;
2881         return 0;
2882
2883 err_alloc_workqueue:
2884         destroy_workqueue(dev->workqueue);
2885 err_v4l2_register:
2886         v4l2_device_unregister(&dev->v4l2_dev);
2887         return ret;
2888 }
2889
2890 static int coda_remove(struct platform_device *pdev)
2891 {
2892         struct coda_dev *dev = platform_get_drvdata(pdev);
2893         int i;
2894
2895         for (i = 0; i < ARRAY_SIZE(dev->vfd); i++) {
2896                 if (video_get_drvdata(&dev->vfd[i]))
2897                         video_unregister_device(&dev->vfd[i]);
2898         }
2899         if (dev->m2m_dev)
2900                 v4l2_m2m_release(dev->m2m_dev);
2901         pm_runtime_disable(&pdev->dev);
2902         v4l2_device_unregister(&dev->v4l2_dev);
2903         destroy_workqueue(dev->workqueue);
2904         if (dev->iram.vaddr)
2905                 gen_pool_free(dev->iram_pool, (unsigned long)dev->iram.vaddr,
2906                               dev->iram.size);
2907         coda_free_aux_buf(dev, &dev->codebuf);
2908         coda_free_aux_buf(dev, &dev->tempbuf);
2909         coda_free_aux_buf(dev, &dev->workbuf);
2910         debugfs_remove_recursive(dev->debugfs_root);
2911         ida_destroy(&dev->ida);
2912         return 0;
2913 }
2914
2915 #ifdef CONFIG_PM
2916 static int coda_runtime_resume(struct device *dev)
2917 {
2918         struct coda_dev *cdev = dev_get_drvdata(dev);
2919         int ret = 0;
2920
2921         if (dev->pm_domain && cdev->codebuf.vaddr) {
2922                 ret = coda_hw_init(cdev);
2923                 if (ret)
2924                         v4l2_err(&cdev->v4l2_dev, "HW initialization failed\n");
2925         }
2926
2927         return ret;
2928 }
2929 #endif
2930
2931 static const struct dev_pm_ops coda_pm_ops = {
2932         SET_RUNTIME_PM_OPS(NULL, coda_runtime_resume, NULL)
2933 };
2934
2935 static struct platform_driver coda_driver = {
2936         .probe  = coda_probe,
2937         .remove = coda_remove,
2938         .driver = {
2939                 .name   = CODA_NAME,
2940                 .of_match_table = of_match_ptr(coda_dt_ids),
2941                 .pm     = &coda_pm_ops,
2942         },
2943         .id_table = coda_platform_ids,
2944 };
2945
2946 module_platform_driver(coda_driver);
2947
2948 MODULE_LICENSE("GPL");
2949 MODULE_AUTHOR("Javier Martin <javier.martin@vista-silicon.com>");
2950 MODULE_DESCRIPTION("Coda multi-standard codec V4L2 driver");