Merge tag 'media/v5.5-1' of git://git.kernel.org/pub/scm/linux/kernel/git/mchehab...
[sfrench/cifs-2.6.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                     ctx->inst_type == CODA_INST_DECODER)
938                         return -EINVAL;
939                 break;
940         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
941         case V4L2_SEL_TGT_COMPOSE_PADDED:
942                 rsel = &r;
943                 /* fallthrough */
944         case V4L2_SEL_TGT_COMPOSE:
945         case V4L2_SEL_TGT_COMPOSE_DEFAULT:
946                 if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
947                     ctx->inst_type == CODA_INST_ENCODER)
948                         return -EINVAL;
949                 break;
950         default:
951                 return -EINVAL;
952         }
953
954         s->r = *rsel;
955
956         return 0;
957 }
958
959 static int coda_s_selection(struct file *file, void *fh,
960                             struct v4l2_selection *s)
961 {
962         struct coda_ctx *ctx = fh_to_ctx(fh);
963         struct coda_q_data *q_data;
964
965         switch (s->target) {
966         case V4L2_SEL_TGT_CROP:
967                 if (ctx->inst_type == CODA_INST_ENCODER &&
968                     s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
969                         q_data = get_q_data(ctx, s->type);
970                         if (!q_data)
971                                 return -EINVAL;
972
973                         s->r.left = 0;
974                         s->r.top = 0;
975                         s->r.width = clamp(s->r.width, 2U, q_data->width);
976                         s->r.height = clamp(s->r.height, 2U, q_data->height);
977
978                         if (s->flags & V4L2_SEL_FLAG_LE) {
979                                 s->r.width = round_up(s->r.width, 2);
980                                 s->r.height = round_up(s->r.height, 2);
981                         } else {
982                                 s->r.width = round_down(s->r.width, 2);
983                                 s->r.height = round_down(s->r.height, 2);
984                         }
985
986                         q_data->rect = s->r;
987
988                         coda_dbg(1, ctx, "Setting crop rectangle: %dx%d\n",
989                                  s->r.width, s->r.height);
990
991                         return 0;
992                 }
993                 /* else fall through */
994         case V4L2_SEL_TGT_NATIVE_SIZE:
995         case V4L2_SEL_TGT_COMPOSE:
996                 return coda_g_selection(file, fh, s);
997         default:
998                 /* v4l2-compliance expects this to fail for read-only targets */
999                 return -EINVAL;
1000         }
1001 }
1002
1003 static int coda_try_encoder_cmd(struct file *file, void *fh,
1004                                 struct v4l2_encoder_cmd *ec)
1005 {
1006         struct coda_ctx *ctx = fh_to_ctx(fh);
1007
1008         if (ctx->inst_type != CODA_INST_ENCODER)
1009                 return -ENOTTY;
1010
1011         return v4l2_m2m_ioctl_try_encoder_cmd(file, fh, ec);
1012 }
1013
1014 static void coda_wake_up_capture_queue(struct coda_ctx *ctx)
1015 {
1016         struct vb2_queue *dst_vq;
1017
1018         coda_dbg(1, ctx, "waking up capture queue\n");
1019
1020         dst_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1021         dst_vq->last_buffer_dequeued = true;
1022         wake_up(&dst_vq->done_wq);
1023 }
1024
1025 static int coda_encoder_cmd(struct file *file, void *fh,
1026                             struct v4l2_encoder_cmd *ec)
1027 {
1028         struct coda_ctx *ctx = fh_to_ctx(fh);
1029         struct vb2_v4l2_buffer *buf;
1030         int ret;
1031
1032         ret = coda_try_encoder_cmd(file, fh, ec);
1033         if (ret < 0)
1034                 return ret;
1035
1036         mutex_lock(&ctx->wakeup_mutex);
1037         buf = v4l2_m2m_last_src_buf(ctx->fh.m2m_ctx);
1038         if (buf) {
1039                 /*
1040                  * If the last output buffer is still on the queue, make sure
1041                  * that decoder finish_run will see the last flag and report it
1042                  * to userspace.
1043                  */
1044                 buf->flags |= V4L2_BUF_FLAG_LAST;
1045         } else {
1046                 /* Set the stream-end flag on this context */
1047                 ctx->bit_stream_param |= CODA_BIT_STREAM_END_FLAG;
1048
1049                 /*
1050                  * If the last output buffer has already been taken from the
1051                  * queue, wake up the capture queue and signal end of stream
1052                  * via the -EPIPE mechanism.
1053                  */
1054                 coda_wake_up_capture_queue(ctx);
1055         }
1056         mutex_unlock(&ctx->wakeup_mutex);
1057
1058         return 0;
1059 }
1060
1061 static int coda_try_decoder_cmd(struct file *file, void *fh,
1062                                 struct v4l2_decoder_cmd *dc)
1063 {
1064         struct coda_ctx *ctx = fh_to_ctx(fh);
1065
1066         if (ctx->inst_type != CODA_INST_DECODER)
1067                 return -ENOTTY;
1068
1069         return v4l2_m2m_ioctl_try_decoder_cmd(file, fh, dc);
1070 }
1071
1072 static int coda_decoder_cmd(struct file *file, void *fh,
1073                             struct v4l2_decoder_cmd *dc)
1074 {
1075         struct coda_ctx *ctx = fh_to_ctx(fh);
1076         struct coda_dev *dev = ctx->dev;
1077         struct vb2_v4l2_buffer *buf;
1078         struct vb2_queue *dst_vq;
1079         bool stream_end;
1080         bool wakeup;
1081         int ret;
1082
1083         ret = coda_try_decoder_cmd(file, fh, dc);
1084         if (ret < 0)
1085                 return ret;
1086
1087         switch (dc->cmd) {
1088         case V4L2_DEC_CMD_START:
1089                 mutex_lock(&dev->coda_mutex);
1090                 mutex_lock(&ctx->bitstream_mutex);
1091                 coda_bitstream_flush(ctx);
1092                 dst_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx,
1093                                          V4L2_BUF_TYPE_VIDEO_CAPTURE);
1094                 vb2_clear_last_buffer_dequeued(dst_vq);
1095                 ctx->bit_stream_param &= ~CODA_BIT_STREAM_END_FLAG;
1096                 coda_fill_bitstream(ctx, NULL);
1097                 mutex_unlock(&ctx->bitstream_mutex);
1098                 mutex_unlock(&dev->coda_mutex);
1099                 break;
1100         case V4L2_DEC_CMD_STOP:
1101                 stream_end = false;
1102                 wakeup = false;
1103
1104                 buf = v4l2_m2m_last_src_buf(ctx->fh.m2m_ctx);
1105                 if (buf) {
1106                         coda_dbg(1, ctx, "marking last pending buffer\n");
1107
1108                         /* Mark last buffer */
1109                         buf->flags |= V4L2_BUF_FLAG_LAST;
1110
1111                         if (v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx) == 0) {
1112                                 coda_dbg(1, ctx, "all remaining buffers queued\n");
1113                                 stream_end = true;
1114                         }
1115                 } else {
1116                         coda_dbg(1, ctx, "marking last meta\n");
1117
1118                         /* Mark last meta */
1119                         spin_lock(&ctx->buffer_meta_lock);
1120                         if (!list_empty(&ctx->buffer_meta_list)) {
1121                                 struct coda_buffer_meta *meta;
1122
1123                                 meta = list_last_entry(&ctx->buffer_meta_list,
1124                                                        struct coda_buffer_meta,
1125                                                        list);
1126                                 meta->last = true;
1127                                 stream_end = true;
1128                         } else {
1129                                 wakeup = true;
1130                         }
1131                         spin_unlock(&ctx->buffer_meta_lock);
1132                 }
1133
1134                 if (stream_end) {
1135                         coda_dbg(1, ctx, "all remaining buffers queued\n");
1136
1137                         /* Set the stream-end flag on this context */
1138                         coda_bit_stream_end_flag(ctx);
1139                         ctx->hold = false;
1140                         v4l2_m2m_try_schedule(ctx->fh.m2m_ctx);
1141                 }
1142
1143                 if (wakeup) {
1144                         /* If there is no buffer in flight, wake up */
1145                         coda_wake_up_capture_queue(ctx);
1146                 }
1147
1148                 break;
1149         default:
1150                 return -EINVAL;
1151         }
1152
1153         return 0;
1154 }
1155
1156 static int coda_enum_framesizes(struct file *file, void *fh,
1157                                 struct v4l2_frmsizeenum *fsize)
1158 {
1159         struct coda_ctx *ctx = fh_to_ctx(fh);
1160         struct coda_q_data *q_data_dst;
1161         const struct coda_codec *codec;
1162
1163         if (ctx->inst_type != CODA_INST_ENCODER)
1164                 return -ENOTTY;
1165
1166         if (fsize->index)
1167                 return -EINVAL;
1168
1169         if (coda_format_normalize_yuv(fsize->pixel_format) ==
1170             V4L2_PIX_FMT_YUV420) {
1171                 q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1172                 codec = coda_find_codec(ctx->dev, fsize->pixel_format,
1173                                         q_data_dst->fourcc);
1174         } else {
1175                 codec = coda_find_codec(ctx->dev, V4L2_PIX_FMT_YUV420,
1176                                         fsize->pixel_format);
1177         }
1178         if (!codec)
1179                 return -EINVAL;
1180
1181         fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
1182         fsize->stepwise.min_width = MIN_W;
1183         fsize->stepwise.max_width = codec->max_w;
1184         fsize->stepwise.step_width = 1;
1185         fsize->stepwise.min_height = MIN_H;
1186         fsize->stepwise.max_height = codec->max_h;
1187         fsize->stepwise.step_height = 1;
1188
1189         return 0;
1190 }
1191
1192 static int coda_enum_frameintervals(struct file *file, void *fh,
1193                                     struct v4l2_frmivalenum *f)
1194 {
1195         struct coda_ctx *ctx = fh_to_ctx(fh);
1196         int i;
1197
1198         if (f->index)
1199                 return -EINVAL;
1200
1201         /* Disallow YUYV if the vdoa is not available */
1202         if (!ctx->vdoa && f->pixel_format == V4L2_PIX_FMT_YUYV)
1203                 return -EINVAL;
1204
1205         for (i = 0; i < CODA_MAX_FORMATS; i++) {
1206                 if (f->pixel_format == ctx->cvd->src_formats[i] ||
1207                     f->pixel_format == ctx->cvd->dst_formats[i])
1208                         break;
1209         }
1210         if (i == CODA_MAX_FORMATS)
1211                 return -EINVAL;
1212
1213         f->type = V4L2_FRMIVAL_TYPE_CONTINUOUS;
1214         f->stepwise.min.numerator = 1;
1215         f->stepwise.min.denominator = 65535;
1216         f->stepwise.max.numerator = 65536;
1217         f->stepwise.max.denominator = 1;
1218         f->stepwise.step.numerator = 1;
1219         f->stepwise.step.denominator = 1;
1220
1221         return 0;
1222 }
1223
1224 static int coda_g_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1225 {
1226         struct coda_ctx *ctx = fh_to_ctx(fh);
1227         struct v4l2_fract *tpf;
1228
1229         if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
1230                 return -EINVAL;
1231
1232         a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
1233         tpf = &a->parm.output.timeperframe;
1234         tpf->denominator = ctx->params.framerate & CODA_FRATE_RES_MASK;
1235         tpf->numerator = 1 + (ctx->params.framerate >>
1236                               CODA_FRATE_DIV_OFFSET);
1237
1238         return 0;
1239 }
1240
1241 /*
1242  * Approximate timeperframe v4l2_fract with values that can be written
1243  * into the 16-bit CODA_FRATE_DIV and CODA_FRATE_RES fields.
1244  */
1245 static void coda_approximate_timeperframe(struct v4l2_fract *timeperframe)
1246 {
1247         struct v4l2_fract s = *timeperframe;
1248         struct v4l2_fract f0;
1249         struct v4l2_fract f1 = { 1, 0 };
1250         struct v4l2_fract f2 = { 0, 1 };
1251         unsigned int i, div, s_denominator;
1252
1253         /* Lower bound is 1/65535 */
1254         if (s.numerator == 0 || s.denominator / s.numerator > 65535) {
1255                 timeperframe->numerator = 1;
1256                 timeperframe->denominator = 65535;
1257                 return;
1258         }
1259
1260         /* Upper bound is 65536/1 */
1261         if (s.denominator == 0 || s.numerator / s.denominator > 65536) {
1262                 timeperframe->numerator = 65536;
1263                 timeperframe->denominator = 1;
1264                 return;
1265         }
1266
1267         /* Reduce fraction to lowest terms */
1268         div = gcd(s.numerator, s.denominator);
1269         if (div > 1) {
1270                 s.numerator /= div;
1271                 s.denominator /= div;
1272         }
1273
1274         if (s.numerator <= 65536 && s.denominator < 65536) {
1275                 *timeperframe = s;
1276                 return;
1277         }
1278
1279         /* Find successive convergents from continued fraction expansion */
1280         while (f2.numerator <= 65536 && f2.denominator < 65536) {
1281                 f0 = f1;
1282                 f1 = f2;
1283
1284                 /* Stop when f2 exactly equals timeperframe */
1285                 if (s.numerator == 0)
1286                         break;
1287
1288                 i = s.denominator / s.numerator;
1289
1290                 f2.numerator = f0.numerator + i * f1.numerator;
1291                 f2.denominator = f0.denominator + i * f2.denominator;
1292
1293                 s_denominator = s.numerator;
1294                 s.numerator = s.denominator % s.numerator;
1295                 s.denominator = s_denominator;
1296         }
1297
1298         *timeperframe = f1;
1299 }
1300
1301 static uint32_t coda_timeperframe_to_frate(struct v4l2_fract *timeperframe)
1302 {
1303         return ((timeperframe->numerator - 1) << CODA_FRATE_DIV_OFFSET) |
1304                 timeperframe->denominator;
1305 }
1306
1307 static int coda_s_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1308 {
1309         struct coda_ctx *ctx = fh_to_ctx(fh);
1310         struct v4l2_fract *tpf;
1311
1312         if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
1313                 return -EINVAL;
1314
1315         a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
1316         tpf = &a->parm.output.timeperframe;
1317         coda_approximate_timeperframe(tpf);
1318         ctx->params.framerate = coda_timeperframe_to_frate(tpf);
1319         ctx->params.framerate_changed = true;
1320
1321         return 0;
1322 }
1323
1324 static int coda_subscribe_event(struct v4l2_fh *fh,
1325                                 const struct v4l2_event_subscription *sub)
1326 {
1327         struct coda_ctx *ctx = fh_to_ctx(fh);
1328
1329         switch (sub->type) {
1330         case V4L2_EVENT_EOS:
1331                 return v4l2_event_subscribe(fh, sub, 0, NULL);
1332         case V4L2_EVENT_SOURCE_CHANGE:
1333                 if (ctx->inst_type == CODA_INST_DECODER)
1334                         return v4l2_event_subscribe(fh, sub, 0, NULL);
1335                 else
1336                         return -EINVAL;
1337         default:
1338                 return v4l2_ctrl_subscribe_event(fh, sub);
1339         }
1340 }
1341
1342 static const struct v4l2_ioctl_ops coda_ioctl_ops = {
1343         .vidioc_querycap        = coda_querycap,
1344
1345         .vidioc_enum_fmt_vid_cap = coda_enum_fmt,
1346         .vidioc_g_fmt_vid_cap   = coda_g_fmt,
1347         .vidioc_try_fmt_vid_cap = coda_try_fmt_vid_cap,
1348         .vidioc_s_fmt_vid_cap   = coda_s_fmt_vid_cap,
1349
1350         .vidioc_enum_fmt_vid_out = coda_enum_fmt,
1351         .vidioc_g_fmt_vid_out   = coda_g_fmt,
1352         .vidioc_try_fmt_vid_out = coda_try_fmt_vid_out,
1353         .vidioc_s_fmt_vid_out   = coda_s_fmt_vid_out,
1354
1355         .vidioc_reqbufs         = coda_reqbufs,
1356         .vidioc_querybuf        = v4l2_m2m_ioctl_querybuf,
1357
1358         .vidioc_qbuf            = coda_qbuf,
1359         .vidioc_expbuf          = v4l2_m2m_ioctl_expbuf,
1360         .vidioc_dqbuf           = coda_dqbuf,
1361         .vidioc_create_bufs     = v4l2_m2m_ioctl_create_bufs,
1362         .vidioc_prepare_buf     = v4l2_m2m_ioctl_prepare_buf,
1363
1364         .vidioc_streamon        = v4l2_m2m_ioctl_streamon,
1365         .vidioc_streamoff       = v4l2_m2m_ioctl_streamoff,
1366
1367         .vidioc_g_selection     = coda_g_selection,
1368         .vidioc_s_selection     = coda_s_selection,
1369
1370         .vidioc_try_encoder_cmd = coda_try_encoder_cmd,
1371         .vidioc_encoder_cmd     = coda_encoder_cmd,
1372         .vidioc_try_decoder_cmd = coda_try_decoder_cmd,
1373         .vidioc_decoder_cmd     = coda_decoder_cmd,
1374
1375         .vidioc_g_parm          = coda_g_parm,
1376         .vidioc_s_parm          = coda_s_parm,
1377
1378         .vidioc_enum_framesizes = coda_enum_framesizes,
1379         .vidioc_enum_frameintervals = coda_enum_frameintervals,
1380
1381         .vidioc_subscribe_event = coda_subscribe_event,
1382         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1383 };
1384
1385 /*
1386  * Mem-to-mem operations.
1387  */
1388
1389 static void coda_device_run(void *m2m_priv)
1390 {
1391         struct coda_ctx *ctx = m2m_priv;
1392         struct coda_dev *dev = ctx->dev;
1393
1394         queue_work(dev->workqueue, &ctx->pic_run_work);
1395 }
1396
1397 static void coda_pic_run_work(struct work_struct *work)
1398 {
1399         struct coda_ctx *ctx = container_of(work, struct coda_ctx, pic_run_work);
1400         struct coda_dev *dev = ctx->dev;
1401         int ret;
1402
1403         mutex_lock(&ctx->buffer_mutex);
1404         mutex_lock(&dev->coda_mutex);
1405
1406         ret = ctx->ops->prepare_run(ctx);
1407         if (ret < 0 && ctx->inst_type == CODA_INST_DECODER) {
1408                 mutex_unlock(&dev->coda_mutex);
1409                 mutex_unlock(&ctx->buffer_mutex);
1410                 /* job_finish scheduled by prepare_decode */
1411                 return;
1412         }
1413
1414         if (!wait_for_completion_timeout(&ctx->completion,
1415                                          msecs_to_jiffies(1000))) {
1416                 dev_err(dev->dev, "CODA PIC_RUN timeout\n");
1417
1418                 ctx->hold = true;
1419
1420                 coda_hw_reset(ctx);
1421
1422                 if (ctx->ops->run_timeout)
1423                         ctx->ops->run_timeout(ctx);
1424         } else if (!ctx->aborting) {
1425                 ctx->ops->finish_run(ctx);
1426         }
1427
1428         if ((ctx->aborting || (!ctx->streamon_cap && !ctx->streamon_out)) &&
1429             ctx->ops->seq_end_work)
1430                 queue_work(dev->workqueue, &ctx->seq_end_work);
1431
1432         mutex_unlock(&dev->coda_mutex);
1433         mutex_unlock(&ctx->buffer_mutex);
1434
1435         v4l2_m2m_job_finish(ctx->dev->m2m_dev, ctx->fh.m2m_ctx);
1436 }
1437
1438 static int coda_job_ready(void *m2m_priv)
1439 {
1440         struct coda_ctx *ctx = m2m_priv;
1441         int src_bufs = v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx);
1442
1443         /*
1444          * For both 'P' and 'key' frame cases 1 picture
1445          * and 1 frame are needed. In the decoder case,
1446          * the compressed frame can be in the bitstream.
1447          */
1448         if (!src_bufs && ctx->inst_type != CODA_INST_DECODER) {
1449                 coda_dbg(1, ctx, "not ready: not enough vid-out buffers.\n");
1450                 return 0;
1451         }
1452
1453         if (!v4l2_m2m_num_dst_bufs_ready(ctx->fh.m2m_ctx)) {
1454                 coda_dbg(1, ctx, "not ready: not enough vid-cap buffers.\n");
1455                 return 0;
1456         }
1457
1458         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit) {
1459                 bool stream_end = ctx->bit_stream_param &
1460                                   CODA_BIT_STREAM_END_FLAG;
1461                 int num_metas = ctx->num_metas;
1462                 struct coda_buffer_meta *meta;
1463                 unsigned int count;
1464
1465                 count = hweight32(ctx->frm_dis_flg);
1466                 if (ctx->use_vdoa && count >= (ctx->num_internal_frames - 1)) {
1467                         coda_dbg(1, ctx,
1468                                  "not ready: all internal buffers in use: %d/%d (0x%x)",
1469                                  count, ctx->num_internal_frames,
1470                                  ctx->frm_dis_flg);
1471                         return 0;
1472                 }
1473
1474                 if (ctx->hold && !src_bufs) {
1475                         coda_dbg(1, ctx,
1476                                  "not ready: on hold for more buffers.\n");
1477                         return 0;
1478                 }
1479
1480                 if (!stream_end && (num_metas + src_bufs) < 2) {
1481                         coda_dbg(1, ctx,
1482                                  "not ready: need 2 buffers available (queue:%d + bitstream:%d)\n",
1483                                  num_metas, src_bufs);
1484                         return 0;
1485                 }
1486
1487                 meta = list_first_entry(&ctx->buffer_meta_list,
1488                                         struct coda_buffer_meta, list);
1489                 if (!coda_bitstream_can_fetch_past(ctx, meta->end) &&
1490                     !stream_end) {
1491                         coda_dbg(1, ctx,
1492                                  "not ready: not enough bitstream data to read past %u (%u)\n",
1493                                  meta->end, ctx->bitstream_fifo.kfifo.in);
1494                         return 0;
1495                 }
1496         }
1497
1498         if (ctx->aborting) {
1499                 coda_dbg(1, ctx, "not ready: aborting\n");
1500                 return 0;
1501         }
1502
1503         coda_dbg(2, ctx, "job ready\n");
1504
1505         return 1;
1506 }
1507
1508 static void coda_job_abort(void *priv)
1509 {
1510         struct coda_ctx *ctx = priv;
1511
1512         ctx->aborting = 1;
1513
1514         coda_dbg(1, ctx, "job abort\n");
1515 }
1516
1517 static const struct v4l2_m2m_ops coda_m2m_ops = {
1518         .device_run     = coda_device_run,
1519         .job_ready      = coda_job_ready,
1520         .job_abort      = coda_job_abort,
1521 };
1522
1523 static void set_default_params(struct coda_ctx *ctx)
1524 {
1525         unsigned int max_w, max_h, usize, csize;
1526
1527         ctx->codec = coda_find_codec(ctx->dev, ctx->cvd->src_formats[0],
1528                                      ctx->cvd->dst_formats[0]);
1529         max_w = min(ctx->codec->max_w, 1920U);
1530         max_h = min(ctx->codec->max_h, 1088U);
1531         usize = max_w * max_h * 3 / 2;
1532         csize = coda_estimate_sizeimage(ctx, usize, max_w, max_h);
1533
1534         ctx->params.codec_mode = ctx->codec->mode;
1535         if (ctx->cvd->src_formats[0] == V4L2_PIX_FMT_JPEG)
1536                 ctx->colorspace = V4L2_COLORSPACE_JPEG;
1537         else
1538                 ctx->colorspace = V4L2_COLORSPACE_REC709;
1539         ctx->xfer_func = V4L2_XFER_FUNC_DEFAULT;
1540         ctx->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
1541         ctx->quantization = V4L2_QUANTIZATION_DEFAULT;
1542         ctx->params.framerate = 30;
1543
1544         /* Default formats for output and input queues */
1545         ctx->q_data[V4L2_M2M_SRC].fourcc = ctx->cvd->src_formats[0];
1546         ctx->q_data[V4L2_M2M_DST].fourcc = ctx->cvd->dst_formats[0];
1547         ctx->q_data[V4L2_M2M_SRC].width = max_w;
1548         ctx->q_data[V4L2_M2M_SRC].height = max_h;
1549         ctx->q_data[V4L2_M2M_DST].width = max_w;
1550         ctx->q_data[V4L2_M2M_DST].height = max_h;
1551         if (ctx->codec->src_fourcc == V4L2_PIX_FMT_YUV420) {
1552                 ctx->q_data[V4L2_M2M_SRC].bytesperline = max_w;
1553                 ctx->q_data[V4L2_M2M_SRC].sizeimage = usize;
1554                 ctx->q_data[V4L2_M2M_DST].bytesperline = 0;
1555                 ctx->q_data[V4L2_M2M_DST].sizeimage = csize;
1556         } else {
1557                 ctx->q_data[V4L2_M2M_SRC].bytesperline = 0;
1558                 ctx->q_data[V4L2_M2M_SRC].sizeimage = csize;
1559                 ctx->q_data[V4L2_M2M_DST].bytesperline = max_w;
1560                 ctx->q_data[V4L2_M2M_DST].sizeimage = usize;
1561         }
1562         ctx->q_data[V4L2_M2M_SRC].rect.width = max_w;
1563         ctx->q_data[V4L2_M2M_SRC].rect.height = max_h;
1564         ctx->q_data[V4L2_M2M_DST].rect.width = max_w;
1565         ctx->q_data[V4L2_M2M_DST].rect.height = max_h;
1566
1567         /*
1568          * Since the RBC2AXI logic only supports a single chroma plane,
1569          * macroblock tiling only works for to NV12 pixel format.
1570          */
1571         ctx->tiled_map_type = GDI_LINEAR_FRAME_MAP;
1572 }
1573
1574 /*
1575  * Queue operations
1576  */
1577 static int coda_queue_setup(struct vb2_queue *vq,
1578                                 unsigned int *nbuffers, unsigned int *nplanes,
1579                                 unsigned int sizes[], struct device *alloc_devs[])
1580 {
1581         struct coda_ctx *ctx = vb2_get_drv_priv(vq);
1582         struct coda_q_data *q_data;
1583         unsigned int size;
1584
1585         q_data = get_q_data(ctx, vq->type);
1586         size = q_data->sizeimage;
1587
1588         if (*nplanes)
1589                 return sizes[0] < size ? -EINVAL : 0;
1590
1591         *nplanes = 1;
1592         sizes[0] = size;
1593
1594         coda_dbg(1, ctx, "get %d buffer(s) of size %d each.\n", *nbuffers,
1595                  size);
1596
1597         return 0;
1598 }
1599
1600 static int coda_buf_prepare(struct vb2_buffer *vb)
1601 {
1602         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1603         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1604         struct coda_q_data *q_data;
1605
1606         q_data = get_q_data(ctx, vb->vb2_queue->type);
1607         if (V4L2_TYPE_IS_OUTPUT(vb->vb2_queue->type)) {
1608                 if (vbuf->field == V4L2_FIELD_ANY)
1609                         vbuf->field = V4L2_FIELD_NONE;
1610                 if (vbuf->field != V4L2_FIELD_NONE) {
1611                         v4l2_warn(&ctx->dev->v4l2_dev,
1612                                   "%s field isn't supported\n", __func__);
1613                         return -EINVAL;
1614                 }
1615         }
1616
1617         if (vb2_plane_size(vb, 0) < q_data->sizeimage) {
1618                 v4l2_warn(&ctx->dev->v4l2_dev,
1619                           "%s data will not fit into plane (%lu < %lu)\n",
1620                           __func__, vb2_plane_size(vb, 0),
1621                           (long)q_data->sizeimage);
1622                 return -EINVAL;
1623         }
1624
1625         return 0;
1626 }
1627
1628 static void coda_update_menu_ctrl(struct v4l2_ctrl *ctrl, int value)
1629 {
1630         if (!ctrl)
1631                 return;
1632
1633         v4l2_ctrl_lock(ctrl);
1634
1635         /*
1636          * Extend the control range if the parsed stream contains a known but
1637          * unsupported value or level.
1638          */
1639         if (value > ctrl->maximum) {
1640                 __v4l2_ctrl_modify_range(ctrl, ctrl->minimum, value,
1641                         ctrl->menu_skip_mask & ~(1 << value),
1642                         ctrl->default_value);
1643         } else if (value < ctrl->minimum) {
1644                 __v4l2_ctrl_modify_range(ctrl, value, ctrl->maximum,
1645                         ctrl->menu_skip_mask & ~(1 << value),
1646                         ctrl->default_value);
1647         }
1648
1649         __v4l2_ctrl_s_ctrl(ctrl, value);
1650
1651         v4l2_ctrl_unlock(ctrl);
1652 }
1653
1654 void coda_update_profile_level_ctrls(struct coda_ctx *ctx, u8 profile_idc,
1655                                      u8 level_idc)
1656 {
1657         const char * const *profile_names;
1658         const char * const *level_names;
1659         struct v4l2_ctrl *profile_ctrl;
1660         struct v4l2_ctrl *level_ctrl;
1661         const char *codec_name;
1662         u32 profile_cid;
1663         u32 level_cid;
1664         int profile;
1665         int level;
1666
1667         switch (ctx->codec->src_fourcc) {
1668         case V4L2_PIX_FMT_H264:
1669                 codec_name = "H264";
1670                 profile_cid = V4L2_CID_MPEG_VIDEO_H264_PROFILE;
1671                 level_cid = V4L2_CID_MPEG_VIDEO_H264_LEVEL;
1672                 profile_ctrl = ctx->h264_profile_ctrl;
1673                 level_ctrl = ctx->h264_level_ctrl;
1674                 profile = coda_h264_profile(profile_idc);
1675                 level = coda_h264_level(level_idc);
1676                 break;
1677         case V4L2_PIX_FMT_MPEG2:
1678                 codec_name = "MPEG-2";
1679                 profile_cid = V4L2_CID_MPEG_VIDEO_MPEG2_PROFILE;
1680                 level_cid = V4L2_CID_MPEG_VIDEO_MPEG2_LEVEL;
1681                 profile_ctrl = ctx->mpeg2_profile_ctrl;
1682                 level_ctrl = ctx->mpeg2_level_ctrl;
1683                 profile = coda_mpeg2_profile(profile_idc);
1684                 level = coda_mpeg2_level(level_idc);
1685                 break;
1686         case V4L2_PIX_FMT_MPEG4:
1687                 codec_name = "MPEG-4";
1688                 profile_cid = V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE;
1689                 level_cid = V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL;
1690                 profile_ctrl = ctx->mpeg4_profile_ctrl;
1691                 level_ctrl = ctx->mpeg4_level_ctrl;
1692                 profile = coda_mpeg4_profile(profile_idc);
1693                 level = coda_mpeg4_level(level_idc);
1694                 break;
1695         default:
1696                 return;
1697         }
1698
1699         profile_names = v4l2_ctrl_get_menu(profile_cid);
1700         level_names = v4l2_ctrl_get_menu(level_cid);
1701
1702         if (profile < 0) {
1703                 v4l2_warn(&ctx->dev->v4l2_dev, "Invalid %s profile: %u\n",
1704                           codec_name, profile_idc);
1705         } else {
1706                 coda_dbg(1, ctx, "Parsed %s profile: %s\n", codec_name,
1707                          profile_names[profile]);
1708                 coda_update_menu_ctrl(profile_ctrl, profile);
1709         }
1710
1711         if (level < 0) {
1712                 v4l2_warn(&ctx->dev->v4l2_dev, "Invalid %s level: %u\n",
1713                           codec_name, level_idc);
1714         } else {
1715                 coda_dbg(1, ctx, "Parsed %s level: %s\n", codec_name,
1716                          level_names[level]);
1717                 coda_update_menu_ctrl(level_ctrl, level);
1718         }
1719 }
1720
1721 static void coda_queue_source_change_event(struct coda_ctx *ctx)
1722 {
1723         static const struct v4l2_event source_change_event = {
1724                 .type = V4L2_EVENT_SOURCE_CHANGE,
1725                 .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION,
1726         };
1727
1728         v4l2_event_queue_fh(&ctx->fh, &source_change_event);
1729 }
1730
1731 static void coda_buf_queue(struct vb2_buffer *vb)
1732 {
1733         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1734         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1735         struct vb2_queue *vq = vb->vb2_queue;
1736         struct coda_q_data *q_data;
1737
1738         q_data = get_q_data(ctx, vb->vb2_queue->type);
1739
1740         /*
1741          * In the decoder case, immediately try to copy the buffer into the
1742          * bitstream ringbuffer and mark it as ready to be dequeued.
1743          */
1744         if (ctx->bitstream.size && vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1745                 /*
1746                  * For backwards compatibility, queuing an empty buffer marks
1747                  * the stream end
1748                  */
1749                 if (vb2_get_plane_payload(vb, 0) == 0)
1750                         coda_bit_stream_end_flag(ctx);
1751
1752                 if (q_data->fourcc == V4L2_PIX_FMT_H264) {
1753                         /*
1754                          * Unless already done, try to obtain profile_idc and
1755                          * level_idc from the SPS header. This allows to decide
1756                          * whether to enable reordering during sequence
1757                          * initialization.
1758                          */
1759                         if (!ctx->params.h264_profile_idc) {
1760                                 coda_sps_parse_profile(ctx, vb);
1761                                 coda_update_profile_level_ctrls(ctx,
1762                                                 ctx->params.h264_profile_idc,
1763                                                 ctx->params.h264_level_idc);
1764                         }
1765                 }
1766
1767                 mutex_lock(&ctx->bitstream_mutex);
1768                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1769                 if (vb2_is_streaming(vb->vb2_queue))
1770                         /* This set buf->sequence = ctx->qsequence++ */
1771                         coda_fill_bitstream(ctx, NULL);
1772                 mutex_unlock(&ctx->bitstream_mutex);
1773
1774                 if (!ctx->initialized) {
1775                         /*
1776                          * Run sequence initialization in case the queued
1777                          * buffer contained headers.
1778                          */
1779                         if (vb2_is_streaming(vb->vb2_queue) &&
1780                             ctx->ops->seq_init_work) {
1781                                 queue_work(ctx->dev->workqueue,
1782                                            &ctx->seq_init_work);
1783                                 flush_work(&ctx->seq_init_work);
1784                         }
1785
1786                         if (ctx->initialized)
1787                                 coda_queue_source_change_event(ctx);
1788                 }
1789         } else {
1790                 if (ctx->inst_type == CODA_INST_ENCODER &&
1791                     vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1792                         vbuf->sequence = ctx->qsequence++;
1793                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1794         }
1795 }
1796
1797 int coda_alloc_aux_buf(struct coda_dev *dev, struct coda_aux_buf *buf,
1798                        size_t size, const char *name, struct dentry *parent)
1799 {
1800         buf->vaddr = dma_alloc_coherent(dev->dev, size, &buf->paddr,
1801                                         GFP_KERNEL);
1802         if (!buf->vaddr) {
1803                 v4l2_err(&dev->v4l2_dev,
1804                          "Failed to allocate %s buffer of size %zu\n",
1805                          name, size);
1806                 return -ENOMEM;
1807         }
1808
1809         buf->size = size;
1810
1811         if (name && parent) {
1812                 buf->blob.data = buf->vaddr;
1813                 buf->blob.size = size;
1814                 buf->dentry = debugfs_create_blob(name, 0644, parent,
1815                                                   &buf->blob);
1816                 if (!buf->dentry)
1817                         dev_warn(dev->dev,
1818                                  "failed to create debugfs entry %s\n", name);
1819         }
1820
1821         return 0;
1822 }
1823
1824 void coda_free_aux_buf(struct coda_dev *dev,
1825                        struct coda_aux_buf *buf)
1826 {
1827         if (buf->vaddr) {
1828                 dma_free_coherent(dev->dev, buf->size, buf->vaddr, buf->paddr);
1829                 buf->vaddr = NULL;
1830                 buf->size = 0;
1831                 debugfs_remove(buf->dentry);
1832                 buf->dentry = NULL;
1833         }
1834 }
1835
1836 static int coda_start_streaming(struct vb2_queue *q, unsigned int count)
1837 {
1838         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1839         struct v4l2_device *v4l2_dev = &ctx->dev->v4l2_dev;
1840         struct coda_q_data *q_data_src, *q_data_dst;
1841         struct v4l2_m2m_buffer *m2m_buf, *tmp;
1842         struct vb2_v4l2_buffer *buf;
1843         struct list_head list;
1844         int ret = 0;
1845
1846         if (count < 1)
1847                 return -EINVAL;
1848
1849         coda_dbg(1, ctx, "start streaming %s\n", v4l2_type_names[q->type]);
1850
1851         INIT_LIST_HEAD(&list);
1852
1853         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
1854         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1855                 if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit) {
1856                         /* copy the buffers that were queued before streamon */
1857                         mutex_lock(&ctx->bitstream_mutex);
1858                         coda_fill_bitstream(ctx, &list);
1859                         mutex_unlock(&ctx->bitstream_mutex);
1860
1861                         if (ctx->dev->devtype->product != CODA_960 &&
1862                             coda_get_bitstream_payload(ctx) < 512) {
1863                                 v4l2_err(v4l2_dev, "start payload < 512\n");
1864                                 ret = -EINVAL;
1865                                 goto err;
1866                         }
1867
1868                         if (!ctx->initialized) {
1869                                 /* Run sequence initialization */
1870                                 if (ctx->ops->seq_init_work) {
1871                                         queue_work(ctx->dev->workqueue,
1872                                                    &ctx->seq_init_work);
1873                                         flush_work(&ctx->seq_init_work);
1874                                 }
1875                         }
1876                 }
1877
1878                 ctx->streamon_out = 1;
1879         } else {
1880                 ctx->streamon_cap = 1;
1881         }
1882
1883         /* Don't start the coda unless both queues are on */
1884         if (!(ctx->streamon_out && ctx->streamon_cap))
1885                 goto out;
1886
1887         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1888         if ((q_data_src->rect.width != q_data_dst->width &&
1889              round_up(q_data_src->rect.width, 16) != q_data_dst->width) ||
1890             (q_data_src->rect.height != q_data_dst->height &&
1891              round_up(q_data_src->rect.height, 16) != q_data_dst->height)) {
1892                 v4l2_err(v4l2_dev, "can't convert %dx%d to %dx%d\n",
1893                          q_data_src->rect.width, q_data_src->rect.height,
1894                          q_data_dst->width, q_data_dst->height);
1895                 ret = -EINVAL;
1896                 goto err;
1897         }
1898
1899         /* Allow BIT decoder device_run with no new buffers queued */
1900         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit)
1901                 v4l2_m2m_set_src_buffered(ctx->fh.m2m_ctx, true);
1902
1903         ctx->gopcounter = ctx->params.gop_size - 1;
1904
1905         if (q_data_dst->fourcc == V4L2_PIX_FMT_JPEG)
1906                 ctx->params.gop_size = 1;
1907         ctx->gopcounter = ctx->params.gop_size - 1;
1908
1909         ret = ctx->ops->start_streaming(ctx);
1910         if (ctx->inst_type == CODA_INST_DECODER) {
1911                 if (ret == -EAGAIN)
1912                         goto out;
1913         }
1914         if (ret < 0)
1915                 goto err;
1916
1917 out:
1918         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1919                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1920                         list_del(&m2m_buf->list);
1921                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_DONE);
1922                 }
1923         }
1924         return 0;
1925
1926 err:
1927         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1928                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1929                         list_del(&m2m_buf->list);
1930                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_QUEUED);
1931                 }
1932                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1933                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1934         } else {
1935                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1936                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1937         }
1938         return ret;
1939 }
1940
1941 static void coda_stop_streaming(struct vb2_queue *q)
1942 {
1943         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1944         struct coda_dev *dev = ctx->dev;
1945         struct vb2_v4l2_buffer *buf;
1946         bool stop;
1947
1948         stop = ctx->streamon_out && ctx->streamon_cap;
1949
1950         coda_dbg(1, ctx, "stop streaming %s\n", v4l2_type_names[q->type]);
1951
1952         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1953                 ctx->streamon_out = 0;
1954
1955                 coda_bit_stream_end_flag(ctx);
1956
1957                 ctx->qsequence = 0;
1958
1959                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1960                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1961         } else {
1962                 ctx->streamon_cap = 0;
1963
1964                 ctx->osequence = 0;
1965                 ctx->sequence_offset = 0;
1966
1967                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1968                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1969         }
1970
1971         if (stop) {
1972                 struct coda_buffer_meta *meta;
1973
1974                 if (ctx->ops->seq_end_work) {
1975                         queue_work(dev->workqueue, &ctx->seq_end_work);
1976                         flush_work(&ctx->seq_end_work);
1977                 }
1978                 spin_lock(&ctx->buffer_meta_lock);
1979                 while (!list_empty(&ctx->buffer_meta_list)) {
1980                         meta = list_first_entry(&ctx->buffer_meta_list,
1981                                                 struct coda_buffer_meta, list);
1982                         list_del(&meta->list);
1983                         kfree(meta);
1984                 }
1985                 ctx->num_metas = 0;
1986                 spin_unlock(&ctx->buffer_meta_lock);
1987                 kfifo_init(&ctx->bitstream_fifo,
1988                         ctx->bitstream.vaddr, ctx->bitstream.size);
1989                 ctx->runcounter = 0;
1990                 ctx->aborting = 0;
1991                 ctx->hold = false;
1992         }
1993
1994         if (!ctx->streamon_out && !ctx->streamon_cap)
1995                 ctx->bit_stream_param &= ~CODA_BIT_STREAM_END_FLAG;
1996 }
1997
1998 static const struct vb2_ops coda_qops = {
1999         .queue_setup            = coda_queue_setup,
2000         .buf_prepare            = coda_buf_prepare,
2001         .buf_queue              = coda_buf_queue,
2002         .start_streaming        = coda_start_streaming,
2003         .stop_streaming         = coda_stop_streaming,
2004         .wait_prepare           = vb2_ops_wait_prepare,
2005         .wait_finish            = vb2_ops_wait_finish,
2006 };
2007
2008 static int coda_s_ctrl(struct v4l2_ctrl *ctrl)
2009 {
2010         const char * const *val_names = v4l2_ctrl_get_menu(ctrl->id);
2011         struct coda_ctx *ctx =
2012                         container_of(ctrl->handler, struct coda_ctx, ctrls);
2013
2014         if (val_names)
2015                 coda_dbg(2, ctx, "s_ctrl: id = 0x%x, name = \"%s\", val = %d (\"%s\")\n",
2016                          ctrl->id, ctrl->name, ctrl->val, val_names[ctrl->val]);
2017         else
2018                 coda_dbg(2, ctx, "s_ctrl: id = 0x%x, name = \"%s\", val = %d\n",
2019                          ctrl->id, ctrl->name, ctrl->val);
2020
2021         switch (ctrl->id) {
2022         case V4L2_CID_HFLIP:
2023                 if (ctrl->val)
2024                         ctx->params.rot_mode |= CODA_MIR_HOR;
2025                 else
2026                         ctx->params.rot_mode &= ~CODA_MIR_HOR;
2027                 break;
2028         case V4L2_CID_VFLIP:
2029                 if (ctrl->val)
2030                         ctx->params.rot_mode |= CODA_MIR_VER;
2031                 else
2032                         ctx->params.rot_mode &= ~CODA_MIR_VER;
2033                 break;
2034         case V4L2_CID_MPEG_VIDEO_BITRATE:
2035                 ctx->params.bitrate = ctrl->val / 1000;
2036                 ctx->params.bitrate_changed = true;
2037                 break;
2038         case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
2039                 ctx->params.gop_size = ctrl->val;
2040                 break;
2041         case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
2042                 ctx->params.h264_intra_qp = ctrl->val;
2043                 ctx->params.h264_intra_qp_changed = true;
2044                 break;
2045         case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
2046                 ctx->params.h264_inter_qp = ctrl->val;
2047                 break;
2048         case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
2049                 ctx->params.h264_min_qp = ctrl->val;
2050                 break;
2051         case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
2052                 ctx->params.h264_max_qp = ctrl->val;
2053                 break;
2054         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA:
2055                 ctx->params.h264_slice_alpha_c0_offset_div2 = ctrl->val;
2056                 break;
2057         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA:
2058                 ctx->params.h264_slice_beta_offset_div2 = ctrl->val;
2059                 break;
2060         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE:
2061                 ctx->params.h264_disable_deblocking_filter_idc = ctrl->val;
2062                 break;
2063         case V4L2_CID_MPEG_VIDEO_H264_CONSTRAINED_INTRA_PREDICTION:
2064                 ctx->params.h264_constrained_intra_pred_flag = ctrl->val;
2065                 break;
2066         case V4L2_CID_MPEG_VIDEO_H264_CHROMA_QP_INDEX_OFFSET:
2067                 ctx->params.h264_chroma_qp_index_offset = ctrl->val;
2068                 break;
2069         case V4L2_CID_MPEG_VIDEO_H264_PROFILE:
2070                 /* TODO: switch between baseline and constrained baseline */
2071                 if (ctx->inst_type == CODA_INST_ENCODER)
2072                         ctx->params.h264_profile_idc = 66;
2073                 break;
2074         case V4L2_CID_MPEG_VIDEO_H264_LEVEL:
2075                 /* nothing to do, this is set by the encoder */
2076                 break;
2077         case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
2078                 ctx->params.mpeg4_intra_qp = ctrl->val;
2079                 break;
2080         case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
2081                 ctx->params.mpeg4_inter_qp = ctrl->val;
2082                 break;
2083         case V4L2_CID_MPEG_VIDEO_MPEG2_PROFILE:
2084         case V4L2_CID_MPEG_VIDEO_MPEG2_LEVEL:
2085         case V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE:
2086         case V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL:
2087                 /* nothing to do, these are fixed */
2088                 break;
2089         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
2090                 ctx->params.slice_mode = ctrl->val;
2091                 ctx->params.slice_mode_changed = true;
2092                 break;
2093         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
2094                 ctx->params.slice_max_mb = ctrl->val;
2095                 ctx->params.slice_mode_changed = true;
2096                 break;
2097         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
2098                 ctx->params.slice_max_bits = ctrl->val * 8;
2099                 ctx->params.slice_mode_changed = true;
2100                 break;
2101         case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
2102                 break;
2103         case V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB:
2104                 ctx->params.intra_refresh = ctrl->val;
2105                 ctx->params.intra_refresh_changed = true;
2106                 break;
2107         case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME:
2108                 ctx->params.force_ipicture = true;
2109                 break;
2110         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
2111                 coda_set_jpeg_compression_quality(ctx, ctrl->val);
2112                 break;
2113         case V4L2_CID_JPEG_RESTART_INTERVAL:
2114                 ctx->params.jpeg_restart_interval = ctrl->val;
2115                 break;
2116         case V4L2_CID_MPEG_VIDEO_VBV_DELAY:
2117                 ctx->params.vbv_delay = ctrl->val;
2118                 break;
2119         case V4L2_CID_MPEG_VIDEO_VBV_SIZE:
2120                 ctx->params.vbv_size = min(ctrl->val * 8192, 0x7fffffff);
2121                 break;
2122         default:
2123                 coda_dbg(1, ctx, "Invalid control, id=%d, val=%d\n",
2124                          ctrl->id, ctrl->val);
2125                 return -EINVAL;
2126         }
2127
2128         return 0;
2129 }
2130
2131 static const struct v4l2_ctrl_ops coda_ctrl_ops = {
2132         .s_ctrl = coda_s_ctrl,
2133 };
2134
2135 static void coda_encode_ctrls(struct coda_ctx *ctx)
2136 {
2137         int max_gop_size = (ctx->dev->devtype->product == CODA_DX6) ? 60 : 99;
2138
2139         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2140                 V4L2_CID_MPEG_VIDEO_BITRATE, 0, 32767000, 1000, 0);
2141         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2142                 V4L2_CID_MPEG_VIDEO_GOP_SIZE, 0, max_gop_size, 1, 16);
2143         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2144                 V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP, 0, 51, 1, 25);
2145         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2146                 V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP, 0, 51, 1, 25);
2147         if (ctx->dev->devtype->product != CODA_960) {
2148                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2149                         V4L2_CID_MPEG_VIDEO_H264_MIN_QP, 0, 51, 1, 12);
2150         }
2151         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2152                 V4L2_CID_MPEG_VIDEO_H264_MAX_QP, 0, 51, 1, 51);
2153         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2154                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA, -6, 6, 1, 0);
2155         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2156                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA, -6, 6, 1, 0);
2157         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2158                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE,
2159                 V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY,
2160                 0x0, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED);
2161         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2162                 V4L2_CID_MPEG_VIDEO_H264_CONSTRAINED_INTRA_PREDICTION, 0, 1, 1,
2163                 0);
2164         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2165                 V4L2_CID_MPEG_VIDEO_H264_CHROMA_QP_INDEX_OFFSET, -12, 12, 1, 0);
2166         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2167                 V4L2_CID_MPEG_VIDEO_H264_PROFILE,
2168                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE, 0x0,
2169                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE);
2170         if (ctx->dev->devtype->product == CODA_HX4 ||
2171             ctx->dev->devtype->product == CODA_7541) {
2172                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2173                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
2174                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1,
2175                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
2176                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
2177                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1)),
2178                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1);
2179         }
2180         if (ctx->dev->devtype->product == CODA_960) {
2181                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2182                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
2183                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0,
2184                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
2185                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
2186                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1) |
2187                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_2) |
2188                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_4_0)),
2189                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0);
2190         }
2191         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2192                 V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP, 1, 31, 1, 2);
2193         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2194                 V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP, 1, 31, 1, 2);
2195         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2196                 V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE,
2197                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE, 0x0,
2198                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE);
2199         if (ctx->dev->devtype->product == CODA_HX4 ||
2200             ctx->dev->devtype->product == CODA_7541 ||
2201             ctx->dev->devtype->product == CODA_960) {
2202                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2203                         V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL,
2204                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5,
2205                         ~(1 << V4L2_MPEG_VIDEO_MPEG4_LEVEL_5),
2206                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5);
2207         }
2208         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2209                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE,
2210                 V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_MAX_BYTES, 0x0,
2211                 V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE);
2212         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2213                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB, 1, 0x3fffffff, 1, 1);
2214         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2215                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES, 1, 0x3fffffff, 1,
2216                 500);
2217         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2218                 V4L2_CID_MPEG_VIDEO_HEADER_MODE,
2219                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME,
2220                 (1 << V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE),
2221                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME);
2222         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2223                 V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB, 0,
2224                 1920 * 1088 / 256, 1, 0);
2225         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2226                 V4L2_CID_MPEG_VIDEO_VBV_DELAY, 0, 0x7fff, 1, 0);
2227         /*
2228          * The maximum VBV size value is 0x7fffffff bits,
2229          * one bit less than 262144 KiB
2230          */
2231         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2232                 V4L2_CID_MPEG_VIDEO_VBV_SIZE, 0, 262144, 1, 0);
2233 }
2234
2235 static void coda_jpeg_encode_ctrls(struct coda_ctx *ctx)
2236 {
2237         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2238                 V4L2_CID_JPEG_COMPRESSION_QUALITY, 5, 100, 1, 50);
2239         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2240                 V4L2_CID_JPEG_RESTART_INTERVAL, 0, 100, 1, 0);
2241 }
2242
2243 static void coda_decode_ctrls(struct coda_ctx *ctx)
2244 {
2245         u8 max;
2246
2247         ctx->h264_profile_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2248                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_H264_PROFILE,
2249                 V4L2_MPEG_VIDEO_H264_PROFILE_HIGH,
2250                 ~((1 << V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE) |
2251                   (1 << V4L2_MPEG_VIDEO_H264_PROFILE_MAIN) |
2252                   (1 << V4L2_MPEG_VIDEO_H264_PROFILE_HIGH)),
2253                 V4L2_MPEG_VIDEO_H264_PROFILE_HIGH);
2254         if (ctx->h264_profile_ctrl)
2255                 ctx->h264_profile_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2256
2257         if (ctx->dev->devtype->product == CODA_HX4 ||
2258             ctx->dev->devtype->product == CODA_7541)
2259                 max = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
2260         else if (ctx->dev->devtype->product == CODA_960)
2261                 max = V4L2_MPEG_VIDEO_H264_LEVEL_4_1;
2262         else
2263                 return;
2264         ctx->h264_level_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2265                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_H264_LEVEL, max, 0, max);
2266         if (ctx->h264_level_ctrl)
2267                 ctx->h264_level_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2268
2269         ctx->mpeg2_profile_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2270                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG2_PROFILE,
2271                 V4L2_MPEG_VIDEO_MPEG2_PROFILE_HIGH, 0,
2272                 V4L2_MPEG_VIDEO_MPEG2_PROFILE_HIGH);
2273         if (ctx->mpeg2_profile_ctrl)
2274                 ctx->mpeg2_profile_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2275
2276         ctx->mpeg2_level_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2277                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG2_LEVEL,
2278                 V4L2_MPEG_VIDEO_MPEG2_LEVEL_HIGH, 0,
2279                 V4L2_MPEG_VIDEO_MPEG2_LEVEL_HIGH);
2280         if (ctx->mpeg2_level_ctrl)
2281                 ctx->mpeg2_level_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2282
2283         ctx->mpeg4_profile_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2284                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE,
2285                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY, 0,
2286                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY);
2287         if (ctx->mpeg4_profile_ctrl)
2288                 ctx->mpeg4_profile_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2289
2290         ctx->mpeg4_level_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2291                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL,
2292                 V4L2_MPEG_VIDEO_MPEG4_LEVEL_5, 0,
2293                 V4L2_MPEG_VIDEO_MPEG4_LEVEL_5);
2294         if (ctx->mpeg4_level_ctrl)
2295                 ctx->mpeg4_level_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2296 }
2297
2298 static int coda_ctrls_setup(struct coda_ctx *ctx)
2299 {
2300         v4l2_ctrl_handler_init(&ctx->ctrls, 2);
2301
2302         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2303                 V4L2_CID_HFLIP, 0, 1, 1, 0);
2304         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2305                 V4L2_CID_VFLIP, 0, 1, 1, 0);
2306         if (ctx->inst_type == CODA_INST_ENCODER) {
2307                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2308                                   V4L2_CID_MIN_BUFFERS_FOR_OUTPUT,
2309                                   1, 1, 1, 1);
2310                 if (ctx->cvd->dst_formats[0] == V4L2_PIX_FMT_JPEG)
2311                         coda_jpeg_encode_ctrls(ctx);
2312                 else
2313                         coda_encode_ctrls(ctx);
2314         } else {
2315                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2316                                   V4L2_CID_MIN_BUFFERS_FOR_CAPTURE,
2317                                   1, 1, 1, 1);
2318                 if (ctx->cvd->src_formats[0] == V4L2_PIX_FMT_H264)
2319                         coda_decode_ctrls(ctx);
2320         }
2321
2322         if (ctx->ctrls.error) {
2323                 v4l2_err(&ctx->dev->v4l2_dev,
2324                         "control initialization error (%d)",
2325                         ctx->ctrls.error);
2326                 return -EINVAL;
2327         }
2328
2329         return v4l2_ctrl_handler_setup(&ctx->ctrls);
2330 }
2331
2332 static int coda_queue_init(struct coda_ctx *ctx, struct vb2_queue *vq)
2333 {
2334         vq->drv_priv = ctx;
2335         vq->ops = &coda_qops;
2336         vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
2337         vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
2338         vq->lock = &ctx->dev->dev_mutex;
2339         /* One way to indicate end-of-stream for coda is to set the
2340          * bytesused == 0. However by default videobuf2 handles bytesused
2341          * equal to 0 as a special case and changes its value to the size
2342          * of the buffer. Set the allow_zero_bytesused flag, so
2343          * that videobuf2 will keep the value of bytesused intact.
2344          */
2345         vq->allow_zero_bytesused = 1;
2346         /*
2347          * We might be fine with no buffers on some of the queues, but that
2348          * would need to be reflected in job_ready(). Currently we expect all
2349          * queues to have at least one buffer queued.
2350          */
2351         vq->min_buffers_needed = 1;
2352         vq->dev = ctx->dev->dev;
2353
2354         return vb2_queue_init(vq);
2355 }
2356
2357 int coda_encoder_queue_init(void *priv, struct vb2_queue *src_vq,
2358                             struct vb2_queue *dst_vq)
2359 {
2360         int ret;
2361
2362         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
2363         src_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2364         src_vq->mem_ops = &vb2_dma_contig_memops;
2365
2366         ret = coda_queue_init(priv, src_vq);
2367         if (ret)
2368                 return ret;
2369
2370         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2371         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2372         dst_vq->mem_ops = &vb2_dma_contig_memops;
2373
2374         return coda_queue_init(priv, dst_vq);
2375 }
2376
2377 int coda_decoder_queue_init(void *priv, struct vb2_queue *src_vq,
2378                             struct vb2_queue *dst_vq)
2379 {
2380         int ret;
2381
2382         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
2383         src_vq->io_modes = VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
2384         src_vq->mem_ops = &vb2_vmalloc_memops;
2385
2386         ret = coda_queue_init(priv, src_vq);
2387         if (ret)
2388                 return ret;
2389
2390         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2391         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2392         dst_vq->dma_attrs = DMA_ATTR_NO_KERNEL_MAPPING;
2393         dst_vq->mem_ops = &vb2_dma_contig_memops;
2394
2395         return coda_queue_init(priv, dst_vq);
2396 }
2397
2398 /*
2399  * File operations
2400  */
2401
2402 static int coda_open(struct file *file)
2403 {
2404         struct video_device *vdev = video_devdata(file);
2405         struct coda_dev *dev = video_get_drvdata(vdev);
2406         struct coda_ctx *ctx;
2407         unsigned int max = ~0;
2408         char *name;
2409         int ret;
2410         int idx;
2411
2412         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
2413         if (!ctx)
2414                 return -ENOMEM;
2415
2416         if (dev->devtype->product == CODA_DX6)
2417                 max = CODADX6_MAX_INSTANCES - 1;
2418         idx = ida_alloc_max(&dev->ida, max, GFP_KERNEL);
2419         if (idx < 0) {
2420                 ret = idx;
2421                 goto err_coda_max;
2422         }
2423
2424         name = kasprintf(GFP_KERNEL, "context%d", idx);
2425         if (!name) {
2426                 ret = -ENOMEM;
2427                 goto err_coda_name_init;
2428         }
2429
2430         ctx->debugfs_entry = debugfs_create_dir(name, dev->debugfs_root);
2431         kfree(name);
2432
2433         ctx->cvd = to_coda_video_device(vdev);
2434         ctx->inst_type = ctx->cvd->type;
2435         ctx->ops = ctx->cvd->ops;
2436         ctx->use_bit = !ctx->cvd->direct;
2437         init_completion(&ctx->completion);
2438         INIT_WORK(&ctx->pic_run_work, coda_pic_run_work);
2439         if (ctx->ops->seq_init_work)
2440                 INIT_WORK(&ctx->seq_init_work, ctx->ops->seq_init_work);
2441         if (ctx->ops->seq_end_work)
2442                 INIT_WORK(&ctx->seq_end_work, ctx->ops->seq_end_work);
2443         v4l2_fh_init(&ctx->fh, video_devdata(file));
2444         file->private_data = &ctx->fh;
2445         v4l2_fh_add(&ctx->fh);
2446         ctx->dev = dev;
2447         ctx->idx = idx;
2448
2449         coda_dbg(1, ctx, "open instance (%p)\n", ctx);
2450
2451         switch (dev->devtype->product) {
2452         case CODA_960:
2453                 /*
2454                  * Enabling the BWB when decoding can hang the firmware with
2455                  * certain streams. The issue was tracked as ENGR00293425 by
2456                  * Freescale. As a workaround, disable BWB for all decoders.
2457                  * The enable_bwb module parameter allows to override this.
2458                  */
2459                 if (enable_bwb || ctx->inst_type == CODA_INST_ENCODER)
2460                         ctx->frame_mem_ctrl = CODA9_FRAME_ENABLE_BWB;
2461                 /* fallthrough */
2462         case CODA_HX4:
2463         case CODA_7541:
2464                 ctx->reg_idx = 0;
2465                 break;
2466         default:
2467                 ctx->reg_idx = idx;
2468         }
2469         if (ctx->dev->vdoa && !disable_vdoa) {
2470                 ctx->vdoa = vdoa_context_create(dev->vdoa);
2471                 if (!ctx->vdoa)
2472                         v4l2_warn(&dev->v4l2_dev,
2473                                   "Failed to create vdoa context: not using vdoa");
2474         }
2475         ctx->use_vdoa = false;
2476
2477         /* Power up and upload firmware if necessary */
2478         ret = pm_runtime_get_sync(dev->dev);
2479         if (ret < 0) {
2480                 v4l2_err(&dev->v4l2_dev, "failed to power up: %d\n", ret);
2481                 goto err_pm_get;
2482         }
2483
2484         ret = clk_prepare_enable(dev->clk_per);
2485         if (ret)
2486                 goto err_clk_per;
2487
2488         ret = clk_prepare_enable(dev->clk_ahb);
2489         if (ret)
2490                 goto err_clk_ahb;
2491
2492         set_default_params(ctx);
2493         ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx,
2494                                             ctx->ops->queue_init);
2495         if (IS_ERR(ctx->fh.m2m_ctx)) {
2496                 ret = PTR_ERR(ctx->fh.m2m_ctx);
2497
2498                 v4l2_err(&dev->v4l2_dev, "%s return error (%d)\n",
2499                          __func__, ret);
2500                 goto err_ctx_init;
2501         }
2502
2503         ret = coda_ctrls_setup(ctx);
2504         if (ret) {
2505                 v4l2_err(&dev->v4l2_dev, "failed to setup coda controls\n");
2506                 goto err_ctrls_setup;
2507         }
2508
2509         ctx->fh.ctrl_handler = &ctx->ctrls;
2510
2511         mutex_init(&ctx->bitstream_mutex);
2512         mutex_init(&ctx->buffer_mutex);
2513         mutex_init(&ctx->wakeup_mutex);
2514         INIT_LIST_HEAD(&ctx->buffer_meta_list);
2515         spin_lock_init(&ctx->buffer_meta_lock);
2516
2517         return 0;
2518
2519 err_ctrls_setup:
2520         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
2521 err_ctx_init:
2522         clk_disable_unprepare(dev->clk_ahb);
2523 err_clk_ahb:
2524         clk_disable_unprepare(dev->clk_per);
2525 err_clk_per:
2526         pm_runtime_put_sync(dev->dev);
2527 err_pm_get:
2528         v4l2_fh_del(&ctx->fh);
2529         v4l2_fh_exit(&ctx->fh);
2530 err_coda_name_init:
2531         ida_free(&dev->ida, ctx->idx);
2532 err_coda_max:
2533         kfree(ctx);
2534         return ret;
2535 }
2536
2537 static int coda_release(struct file *file)
2538 {
2539         struct coda_dev *dev = video_drvdata(file);
2540         struct coda_ctx *ctx = fh_to_ctx(file->private_data);
2541
2542         coda_dbg(1, ctx, "release instance (%p)\n", ctx);
2543
2544         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit)
2545                 coda_bit_stream_end_flag(ctx);
2546
2547         /* If this instance is running, call .job_abort and wait for it to end */
2548         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
2549
2550         if (ctx->vdoa)
2551                 vdoa_context_destroy(ctx->vdoa);
2552
2553         /* In case the instance was not running, we still need to call SEQ_END */
2554         if (ctx->ops->seq_end_work) {
2555                 queue_work(dev->workqueue, &ctx->seq_end_work);
2556                 flush_work(&ctx->seq_end_work);
2557         }
2558
2559         if (ctx->dev->devtype->product == CODA_DX6)
2560                 coda_free_aux_buf(dev, &ctx->workbuf);
2561
2562         v4l2_ctrl_handler_free(&ctx->ctrls);
2563         clk_disable_unprepare(dev->clk_ahb);
2564         clk_disable_unprepare(dev->clk_per);
2565         pm_runtime_put_sync(dev->dev);
2566         v4l2_fh_del(&ctx->fh);
2567         v4l2_fh_exit(&ctx->fh);
2568         ida_free(&dev->ida, ctx->idx);
2569         if (ctx->ops->release)
2570                 ctx->ops->release(ctx);
2571         debugfs_remove_recursive(ctx->debugfs_entry);
2572         kfree(ctx);
2573
2574         return 0;
2575 }
2576
2577 static const struct v4l2_file_operations coda_fops = {
2578         .owner          = THIS_MODULE,
2579         .open           = coda_open,
2580         .release        = coda_release,
2581         .poll           = v4l2_m2m_fop_poll,
2582         .unlocked_ioctl = video_ioctl2,
2583         .mmap           = v4l2_m2m_fop_mmap,
2584 };
2585
2586 static int coda_hw_init(struct coda_dev *dev)
2587 {
2588         u32 data;
2589         u16 *p;
2590         int i, ret;
2591
2592         ret = clk_prepare_enable(dev->clk_per);
2593         if (ret)
2594                 goto err_clk_per;
2595
2596         ret = clk_prepare_enable(dev->clk_ahb);
2597         if (ret)
2598                 goto err_clk_ahb;
2599
2600         reset_control_reset(dev->rstc);
2601
2602         /*
2603          * Copy the first CODA_ISRAM_SIZE in the internal SRAM.
2604          * The 16-bit chars in the code buffer are in memory access
2605          * order, re-sort them to CODA order for register download.
2606          * Data in this SRAM survives a reboot.
2607          */
2608         p = (u16 *)dev->codebuf.vaddr;
2609         if (dev->devtype->product == CODA_DX6) {
2610                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++)  {
2611                         data = CODA_DOWN_ADDRESS_SET(i) |
2612                                 CODA_DOWN_DATA_SET(p[i ^ 1]);
2613                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
2614                 }
2615         } else {
2616                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++) {
2617                         data = CODA_DOWN_ADDRESS_SET(i) |
2618                                 CODA_DOWN_DATA_SET(p[round_down(i, 4) +
2619                                                         3 - (i % 4)]);
2620                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
2621                 }
2622         }
2623
2624         /* Clear registers */
2625         for (i = 0; i < 64; i++)
2626                 coda_write(dev, 0, CODA_REG_BIT_CODE_BUF_ADDR + i * 4);
2627
2628         /* Tell the BIT where to find everything it needs */
2629         if (dev->devtype->product == CODA_960 ||
2630             dev->devtype->product == CODA_7541 ||
2631             dev->devtype->product == CODA_HX4) {
2632                 coda_write(dev, dev->tempbuf.paddr,
2633                                 CODA_REG_BIT_TEMP_BUF_ADDR);
2634                 coda_write(dev, 0, CODA_REG_BIT_BIT_STREAM_PARAM);
2635         } else {
2636                 coda_write(dev, dev->workbuf.paddr,
2637                               CODA_REG_BIT_WORK_BUF_ADDR);
2638         }
2639         coda_write(dev, dev->codebuf.paddr,
2640                       CODA_REG_BIT_CODE_BUF_ADDR);
2641         coda_write(dev, 0, CODA_REG_BIT_CODE_RUN);
2642
2643         /* Set default values */
2644         switch (dev->devtype->product) {
2645         case CODA_DX6:
2646                 coda_write(dev, CODADX6_STREAM_BUF_PIC_FLUSH,
2647                            CODA_REG_BIT_STREAM_CTRL);
2648                 break;
2649         default:
2650                 coda_write(dev, CODA7_STREAM_BUF_PIC_FLUSH,
2651                            CODA_REG_BIT_STREAM_CTRL);
2652         }
2653         if (dev->devtype->product == CODA_960)
2654                 coda_write(dev, CODA9_FRAME_ENABLE_BWB,
2655                                 CODA_REG_BIT_FRAME_MEM_CTRL);
2656         else
2657                 coda_write(dev, 0, CODA_REG_BIT_FRAME_MEM_CTRL);
2658
2659         if (dev->devtype->product != CODA_DX6)
2660                 coda_write(dev, 0, CODA7_REG_BIT_AXI_SRAM_USE);
2661
2662         coda_write(dev, CODA_INT_INTERRUPT_ENABLE,
2663                       CODA_REG_BIT_INT_ENABLE);
2664
2665         /* Reset VPU and start processor */
2666         data = coda_read(dev, CODA_REG_BIT_CODE_RESET);
2667         data |= CODA_REG_RESET_ENABLE;
2668         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
2669         udelay(10);
2670         data &= ~CODA_REG_RESET_ENABLE;
2671         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
2672         coda_write(dev, CODA_REG_RUN_ENABLE, CODA_REG_BIT_CODE_RUN);
2673
2674         clk_disable_unprepare(dev->clk_ahb);
2675         clk_disable_unprepare(dev->clk_per);
2676
2677         return 0;
2678
2679 err_clk_ahb:
2680         clk_disable_unprepare(dev->clk_per);
2681 err_clk_per:
2682         return ret;
2683 }
2684
2685 static int coda_register_device(struct coda_dev *dev, int i)
2686 {
2687         struct video_device *vfd = &dev->vfd[i];
2688         enum coda_inst_type type;
2689         int ret;
2690
2691         if (i >= dev->devtype->num_vdevs)
2692                 return -EINVAL;
2693         type = dev->devtype->vdevs[i]->type;
2694
2695         strscpy(vfd->name, dev->devtype->vdevs[i]->name, sizeof(vfd->name));
2696         vfd->fops       = &coda_fops;
2697         vfd->ioctl_ops  = &coda_ioctl_ops;
2698         vfd->release    = video_device_release_empty,
2699         vfd->lock       = &dev->dev_mutex;
2700         vfd->v4l2_dev   = &dev->v4l2_dev;
2701         vfd->vfl_dir    = VFL_DIR_M2M;
2702         vfd->device_caps = V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
2703         video_set_drvdata(vfd, dev);
2704
2705         /* Not applicable, use the selection API instead */
2706         v4l2_disable_ioctl(vfd, VIDIOC_CROPCAP);
2707         v4l2_disable_ioctl(vfd, VIDIOC_G_CROP);
2708         v4l2_disable_ioctl(vfd, VIDIOC_S_CROP);
2709
2710         ret = video_register_device(vfd, VFL_TYPE_GRABBER, 0);
2711         if (!ret)
2712                 v4l2_info(&dev->v4l2_dev, "%s registered as %s\n",
2713                           type == CODA_INST_ENCODER ? "encoder" : "decoder",
2714                           video_device_node_name(vfd));
2715         return ret;
2716 }
2717
2718 static void coda_copy_firmware(struct coda_dev *dev, const u8 * const buf,
2719                                size_t size)
2720 {
2721         u32 *src = (u32 *)buf;
2722
2723         /* Check if the firmware has a 16-byte Freescale header, skip it */
2724         if (buf[0] == 'M' && buf[1] == 'X')
2725                 src += 4;
2726         /*
2727          * Check whether the firmware is in native order or pre-reordered for
2728          * memory access. The first instruction opcode always is 0xe40e.
2729          */
2730         if (__le16_to_cpup((__le16 *)src) == 0xe40e) {
2731                 u32 *dst = dev->codebuf.vaddr;
2732                 int i;
2733
2734                 /* Firmware in native order, reorder while copying */
2735                 if (dev->devtype->product == CODA_DX6) {
2736                         for (i = 0; i < (size - 16) / 4; i++)
2737                                 dst[i] = (src[i] << 16) | (src[i] >> 16);
2738                 } else {
2739                         for (i = 0; i < (size - 16) / 4; i += 2) {
2740                                 dst[i] = (src[i + 1] << 16) | (src[i + 1] >> 16);
2741                                 dst[i + 1] = (src[i] << 16) | (src[i] >> 16);
2742                         }
2743                 }
2744         } else {
2745                 /* Copy the already reordered firmware image */
2746                 memcpy(dev->codebuf.vaddr, src, size);
2747         }
2748 }
2749
2750 static void coda_fw_callback(const struct firmware *fw, void *context);
2751
2752 static int coda_firmware_request(struct coda_dev *dev)
2753 {
2754         char *fw;
2755
2756         if (dev->firmware >= ARRAY_SIZE(dev->devtype->firmware))
2757                 return -EINVAL;
2758
2759         fw = dev->devtype->firmware[dev->firmware];
2760
2761         dev_dbg(dev->dev, "requesting firmware '%s' for %s\n", fw,
2762                 coda_product_name(dev->devtype->product));
2763
2764         return request_firmware_nowait(THIS_MODULE, true, fw, dev->dev,
2765                                        GFP_KERNEL, dev, coda_fw_callback);
2766 }
2767
2768 static void coda_fw_callback(const struct firmware *fw, void *context)
2769 {
2770         struct coda_dev *dev = context;
2771         int i, ret;
2772
2773         if (!fw) {
2774                 dev->firmware++;
2775                 ret = coda_firmware_request(dev);
2776                 if (ret < 0) {
2777                         v4l2_err(&dev->v4l2_dev, "firmware request failed\n");
2778                         goto put_pm;
2779                 }
2780                 return;
2781         }
2782         if (dev->firmware > 0) {
2783                 /*
2784                  * Since we can't suppress warnings for failed asynchronous
2785                  * firmware requests, report that the fallback firmware was
2786                  * found.
2787                  */
2788                 dev_info(dev->dev, "Using fallback firmware %s\n",
2789                          dev->devtype->firmware[dev->firmware]);
2790         }
2791
2792         /* allocate auxiliary per-device code buffer for the BIT processor */
2793         ret = coda_alloc_aux_buf(dev, &dev->codebuf, fw->size, "codebuf",
2794                                  dev->debugfs_root);
2795         if (ret < 0)
2796                 goto put_pm;
2797
2798         coda_copy_firmware(dev, fw->data, fw->size);
2799         release_firmware(fw);
2800
2801         ret = coda_hw_init(dev);
2802         if (ret < 0) {
2803                 v4l2_err(&dev->v4l2_dev, "HW initialization failed\n");
2804                 goto put_pm;
2805         }
2806
2807         ret = coda_check_firmware(dev);
2808         if (ret < 0)
2809                 goto put_pm;
2810
2811         dev->m2m_dev = v4l2_m2m_init(&coda_m2m_ops);
2812         if (IS_ERR(dev->m2m_dev)) {
2813                 v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n");
2814                 goto put_pm;
2815         }
2816
2817         for (i = 0; i < dev->devtype->num_vdevs; i++) {
2818                 ret = coda_register_device(dev, i);
2819                 if (ret) {
2820                         v4l2_err(&dev->v4l2_dev,
2821                                  "Failed to register %s video device: %d\n",
2822                                  dev->devtype->vdevs[i]->name, ret);
2823                         goto rel_vfd;
2824                 }
2825         }
2826
2827         pm_runtime_put_sync(dev->dev);
2828         return;
2829
2830 rel_vfd:
2831         while (--i >= 0)
2832                 video_unregister_device(&dev->vfd[i]);
2833         v4l2_m2m_release(dev->m2m_dev);
2834 put_pm:
2835         pm_runtime_put_sync(dev->dev);
2836 }
2837
2838 enum coda_platform {
2839         CODA_IMX27,
2840         CODA_IMX51,
2841         CODA_IMX53,
2842         CODA_IMX6Q,
2843         CODA_IMX6DL,
2844 };
2845
2846 static const struct coda_devtype coda_devdata[] = {
2847         [CODA_IMX27] = {
2848                 .firmware     = {
2849                         "vpu_fw_imx27_TO2.bin",
2850                         "vpu/vpu_fw_imx27_TO2.bin",
2851                         "v4l-codadx6-imx27.bin"
2852                 },
2853                 .product      = CODA_DX6,
2854                 .codecs       = codadx6_codecs,
2855                 .num_codecs   = ARRAY_SIZE(codadx6_codecs),
2856                 .vdevs        = codadx6_video_devices,
2857                 .num_vdevs    = ARRAY_SIZE(codadx6_video_devices),
2858                 .workbuf_size = 288 * 1024 + FMO_SLICE_SAVE_BUF_SIZE * 8 * 1024,
2859                 .iram_size    = 0xb000,
2860         },
2861         [CODA_IMX51] = {
2862                 .firmware     = {
2863                         "vpu_fw_imx51.bin",
2864                         "vpu/vpu_fw_imx51.bin",
2865                         "v4l-codahx4-imx51.bin"
2866                 },
2867                 .product      = CODA_HX4,
2868                 .codecs       = codahx4_codecs,
2869                 .num_codecs   = ARRAY_SIZE(codahx4_codecs),
2870                 .vdevs        = codahx4_video_devices,
2871                 .num_vdevs    = ARRAY_SIZE(codahx4_video_devices),
2872                 .workbuf_size = 128 * 1024,
2873                 .tempbuf_size = 304 * 1024,
2874                 .iram_size    = 0x14000,
2875         },
2876         [CODA_IMX53] = {
2877                 .firmware     = {
2878                         "vpu_fw_imx53.bin",
2879                         "vpu/vpu_fw_imx53.bin",
2880                         "v4l-coda7541-imx53.bin"
2881                 },
2882                 .product      = CODA_7541,
2883                 .codecs       = coda7_codecs,
2884                 .num_codecs   = ARRAY_SIZE(coda7_codecs),
2885                 .vdevs        = coda7_video_devices,
2886                 .num_vdevs    = ARRAY_SIZE(coda7_video_devices),
2887                 .workbuf_size = 128 * 1024,
2888                 .tempbuf_size = 304 * 1024,
2889                 .iram_size    = 0x14000,
2890         },
2891         [CODA_IMX6Q] = {
2892                 .firmware     = {
2893                         "vpu_fw_imx6q.bin",
2894                         "vpu/vpu_fw_imx6q.bin",
2895                         "v4l-coda960-imx6q.bin"
2896                 },
2897                 .product      = CODA_960,
2898                 .codecs       = coda9_codecs,
2899                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2900                 .vdevs        = coda9_video_devices,
2901                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2902                 .workbuf_size = 80 * 1024,
2903                 .tempbuf_size = 204 * 1024,
2904                 .iram_size    = 0x21000,
2905         },
2906         [CODA_IMX6DL] = {
2907                 .firmware     = {
2908                         "vpu_fw_imx6d.bin",
2909                         "vpu/vpu_fw_imx6d.bin",
2910                         "v4l-coda960-imx6dl.bin"
2911                 },
2912                 .product      = CODA_960,
2913                 .codecs       = coda9_codecs,
2914                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2915                 .vdevs        = coda9_video_devices,
2916                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2917                 .workbuf_size = 80 * 1024,
2918                 .tempbuf_size = 204 * 1024,
2919                 .iram_size    = 0x1f000, /* leave 4k for suspend code */
2920         },
2921 };
2922
2923 static const struct platform_device_id coda_platform_ids[] = {
2924         { .name = "coda-imx27", .driver_data = CODA_IMX27 },
2925         { /* sentinel */ }
2926 };
2927 MODULE_DEVICE_TABLE(platform, coda_platform_ids);
2928
2929 #ifdef CONFIG_OF
2930 static const struct of_device_id coda_dt_ids[] = {
2931         { .compatible = "fsl,imx27-vpu", .data = &coda_devdata[CODA_IMX27] },
2932         { .compatible = "fsl,imx51-vpu", .data = &coda_devdata[CODA_IMX51] },
2933         { .compatible = "fsl,imx53-vpu", .data = &coda_devdata[CODA_IMX53] },
2934         { .compatible = "fsl,imx6q-vpu", .data = &coda_devdata[CODA_IMX6Q] },
2935         { .compatible = "fsl,imx6dl-vpu", .data = &coda_devdata[CODA_IMX6DL] },
2936         { /* sentinel */ }
2937 };
2938 MODULE_DEVICE_TABLE(of, coda_dt_ids);
2939 #endif
2940
2941 static int coda_probe(struct platform_device *pdev)
2942 {
2943         const struct of_device_id *of_id =
2944                         of_match_device(of_match_ptr(coda_dt_ids), &pdev->dev);
2945         const struct platform_device_id *pdev_id;
2946         struct coda_platform_data *pdata = pdev->dev.platform_data;
2947         struct device_node *np = pdev->dev.of_node;
2948         struct gen_pool *pool;
2949         struct coda_dev *dev;
2950         int ret, irq;
2951
2952         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
2953         if (!dev)
2954                 return -ENOMEM;
2955
2956         pdev_id = of_id ? of_id->data : platform_get_device_id(pdev);
2957
2958         if (of_id)
2959                 dev->devtype = of_id->data;
2960         else if (pdev_id)
2961                 dev->devtype = &coda_devdata[pdev_id->driver_data];
2962         else
2963                 return -EINVAL;
2964
2965         dev->dev = &pdev->dev;
2966         dev->clk_per = devm_clk_get(&pdev->dev, "per");
2967         if (IS_ERR(dev->clk_per)) {
2968                 dev_err(&pdev->dev, "Could not get per clock\n");
2969                 return PTR_ERR(dev->clk_per);
2970         }
2971
2972         dev->clk_ahb = devm_clk_get(&pdev->dev, "ahb");
2973         if (IS_ERR(dev->clk_ahb)) {
2974                 dev_err(&pdev->dev, "Could not get ahb clock\n");
2975                 return PTR_ERR(dev->clk_ahb);
2976         }
2977
2978         /* Get  memory for physical registers */
2979         dev->regs_base = devm_platform_ioremap_resource(pdev, 0);
2980         if (IS_ERR(dev->regs_base))
2981                 return PTR_ERR(dev->regs_base);
2982
2983         /* IRQ */
2984         irq = platform_get_irq_byname(pdev, "bit");
2985         if (irq < 0)
2986                 irq = platform_get_irq(pdev, 0);
2987         if (irq < 0) {
2988                 dev_err(&pdev->dev, "failed to get irq resource\n");
2989                 return irq;
2990         }
2991
2992         ret = devm_request_irq(&pdev->dev, irq, coda_irq_handler, 0,
2993                                dev_name(&pdev->dev), dev);
2994         if (ret < 0) {
2995                 dev_err(&pdev->dev, "failed to request irq: %d\n", ret);
2996                 return ret;
2997         }
2998
2999         dev->rstc = devm_reset_control_get_optional_exclusive(&pdev->dev,
3000                                                               NULL);
3001         if (IS_ERR(dev->rstc)) {
3002                 ret = PTR_ERR(dev->rstc);
3003                 dev_err(&pdev->dev, "failed get reset control: %d\n", ret);
3004                 return ret;
3005         }
3006
3007         /* Get IRAM pool from device tree or platform data */
3008         pool = of_gen_pool_get(np, "iram", 0);
3009         if (!pool && pdata)
3010                 pool = gen_pool_get(pdata->iram_dev, NULL);
3011         if (!pool) {
3012                 dev_err(&pdev->dev, "iram pool not available\n");
3013                 return -ENOMEM;
3014         }
3015         dev->iram_pool = pool;
3016
3017         /* Get vdoa_data if supported by the platform */
3018         dev->vdoa = coda_get_vdoa_data();
3019         if (PTR_ERR(dev->vdoa) == -EPROBE_DEFER)
3020                 return -EPROBE_DEFER;
3021
3022         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
3023         if (ret)
3024                 return ret;
3025
3026         mutex_init(&dev->dev_mutex);
3027         mutex_init(&dev->coda_mutex);
3028         ida_init(&dev->ida);
3029
3030         dev->debugfs_root = debugfs_create_dir("coda", NULL);
3031         if (!dev->debugfs_root)
3032                 dev_warn(&pdev->dev, "failed to create debugfs root\n");
3033
3034         /* allocate auxiliary per-device buffers for the BIT processor */
3035         if (dev->devtype->product == CODA_DX6) {
3036                 ret = coda_alloc_aux_buf(dev, &dev->workbuf,
3037                                          dev->devtype->workbuf_size, "workbuf",
3038                                          dev->debugfs_root);
3039                 if (ret < 0)
3040                         goto err_v4l2_register;
3041         }
3042
3043         if (dev->devtype->tempbuf_size) {
3044                 ret = coda_alloc_aux_buf(dev, &dev->tempbuf,
3045                                          dev->devtype->tempbuf_size, "tempbuf",
3046                                          dev->debugfs_root);
3047                 if (ret < 0)
3048                         goto err_v4l2_register;
3049         }
3050
3051         dev->iram.size = dev->devtype->iram_size;
3052         dev->iram.vaddr = gen_pool_dma_alloc(dev->iram_pool, dev->iram.size,
3053                                              &dev->iram.paddr);
3054         if (!dev->iram.vaddr) {
3055                 dev_warn(&pdev->dev, "unable to alloc iram\n");
3056         } else {
3057                 memset(dev->iram.vaddr, 0, dev->iram.size);
3058                 dev->iram.blob.data = dev->iram.vaddr;
3059                 dev->iram.blob.size = dev->iram.size;
3060                 dev->iram.dentry = debugfs_create_blob("iram", 0644,
3061                                                        dev->debugfs_root,
3062                                                        &dev->iram.blob);
3063         }
3064
3065         dev->workqueue = alloc_workqueue("coda", WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
3066         if (!dev->workqueue) {
3067                 dev_err(&pdev->dev, "unable to alloc workqueue\n");
3068                 ret = -ENOMEM;
3069                 goto err_v4l2_register;
3070         }
3071
3072         platform_set_drvdata(pdev, dev);
3073
3074         /*
3075          * Start activated so we can directly call coda_hw_init in
3076          * coda_fw_callback regardless of whether CONFIG_PM is
3077          * enabled or whether the device is associated with a PM domain.
3078          */
3079         pm_runtime_get_noresume(&pdev->dev);
3080         pm_runtime_set_active(&pdev->dev);
3081         pm_runtime_enable(&pdev->dev);
3082
3083         ret = coda_firmware_request(dev);
3084         if (ret)
3085                 goto err_alloc_workqueue;
3086         return 0;
3087
3088 err_alloc_workqueue:
3089         destroy_workqueue(dev->workqueue);
3090 err_v4l2_register:
3091         v4l2_device_unregister(&dev->v4l2_dev);
3092         return ret;
3093 }
3094
3095 static int coda_remove(struct platform_device *pdev)
3096 {
3097         struct coda_dev *dev = platform_get_drvdata(pdev);
3098         int i;
3099
3100         for (i = 0; i < ARRAY_SIZE(dev->vfd); i++) {
3101                 if (video_get_drvdata(&dev->vfd[i]))
3102                         video_unregister_device(&dev->vfd[i]);
3103         }
3104         if (dev->m2m_dev)
3105                 v4l2_m2m_release(dev->m2m_dev);
3106         pm_runtime_disable(&pdev->dev);
3107         v4l2_device_unregister(&dev->v4l2_dev);
3108         destroy_workqueue(dev->workqueue);
3109         if (dev->iram.vaddr)
3110                 gen_pool_free(dev->iram_pool, (unsigned long)dev->iram.vaddr,
3111                               dev->iram.size);
3112         coda_free_aux_buf(dev, &dev->codebuf);
3113         coda_free_aux_buf(dev, &dev->tempbuf);
3114         coda_free_aux_buf(dev, &dev->workbuf);
3115         debugfs_remove_recursive(dev->debugfs_root);
3116         ida_destroy(&dev->ida);
3117         return 0;
3118 }
3119
3120 #ifdef CONFIG_PM
3121 static int coda_runtime_resume(struct device *dev)
3122 {
3123         struct coda_dev *cdev = dev_get_drvdata(dev);
3124         int ret = 0;
3125
3126         if (dev->pm_domain && cdev->codebuf.vaddr) {
3127                 ret = coda_hw_init(cdev);
3128                 if (ret)
3129                         v4l2_err(&cdev->v4l2_dev, "HW initialization failed\n");
3130         }
3131
3132         return ret;
3133 }
3134 #endif
3135
3136 static const struct dev_pm_ops coda_pm_ops = {
3137         SET_RUNTIME_PM_OPS(NULL, coda_runtime_resume, NULL)
3138 };
3139
3140 static struct platform_driver coda_driver = {
3141         .probe  = coda_probe,
3142         .remove = coda_remove,
3143         .driver = {
3144                 .name   = CODA_NAME,
3145                 .of_match_table = of_match_ptr(coda_dt_ids),
3146                 .pm     = &coda_pm_ops,
3147         },
3148         .id_table = coda_platform_ids,
3149 };
3150
3151 module_platform_driver(coda_driver);
3152
3153 MODULE_LICENSE("GPL");
3154 MODULE_AUTHOR("Javier Martin <javier.martin@vista-silicon.com>");
3155 MODULE_DESCRIPTION("Coda multi-standard codec V4L2 driver");