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