Linux-libre 5.3.12-gnu
[librecmc/linux-libre.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         cap->device_caps = V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
394         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
395
396         return 0;
397 }
398
399 static int coda_enum_fmt(struct file *file, void *priv,
400                          struct v4l2_fmtdesc *f)
401 {
402         struct video_device *vdev = video_devdata(file);
403         const struct coda_video_device *cvd = to_coda_video_device(vdev);
404         struct coda_ctx *ctx = fh_to_ctx(priv);
405         const u32 *formats;
406
407         if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
408                 formats = cvd->src_formats;
409         else if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
410                 formats = cvd->dst_formats;
411         else
412                 return -EINVAL;
413
414         if (f->index >= CODA_MAX_FORMATS || formats[f->index] == 0)
415                 return -EINVAL;
416
417         /* Skip YUYV if the vdoa is not available */
418         if (!ctx->vdoa && f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
419             formats[f->index] == V4L2_PIX_FMT_YUYV)
420                 return -EINVAL;
421
422         f->pixelformat = formats[f->index];
423
424         return 0;
425 }
426
427 static int coda_g_fmt(struct file *file, void *priv,
428                       struct v4l2_format *f)
429 {
430         struct coda_q_data *q_data;
431         struct coda_ctx *ctx = fh_to_ctx(priv);
432
433         q_data = get_q_data(ctx, f->type);
434         if (!q_data)
435                 return -EINVAL;
436
437         f->fmt.pix.field        = V4L2_FIELD_NONE;
438         f->fmt.pix.pixelformat  = q_data->fourcc;
439         f->fmt.pix.width        = q_data->width;
440         f->fmt.pix.height       = q_data->height;
441         f->fmt.pix.bytesperline = q_data->bytesperline;
442
443         f->fmt.pix.sizeimage    = q_data->sizeimage;
444         f->fmt.pix.colorspace   = ctx->colorspace;
445         f->fmt.pix.xfer_func    = ctx->xfer_func;
446         f->fmt.pix.ycbcr_enc    = ctx->ycbcr_enc;
447         f->fmt.pix.quantization = ctx->quantization;
448
449         return 0;
450 }
451
452 static int coda_try_pixelformat(struct coda_ctx *ctx, struct v4l2_format *f)
453 {
454         struct coda_q_data *q_data;
455         const u32 *formats;
456         int i;
457
458         if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
459                 formats = ctx->cvd->src_formats;
460         else if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
461                 formats = ctx->cvd->dst_formats;
462         else
463                 return -EINVAL;
464
465         for (i = 0; i < CODA_MAX_FORMATS; i++) {
466                 /* Skip YUYV if the vdoa is not available */
467                 if (!ctx->vdoa && f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
468                     formats[i] == V4L2_PIX_FMT_YUYV)
469                         continue;
470
471                 if (formats[i] == f->fmt.pix.pixelformat) {
472                         f->fmt.pix.pixelformat = formats[i];
473                         return 0;
474                 }
475         }
476
477         /* Fall back to currently set pixelformat */
478         q_data = get_q_data(ctx, f->type);
479         f->fmt.pix.pixelformat = q_data->fourcc;
480
481         return 0;
482 }
483
484 static int coda_try_fmt_vdoa(struct coda_ctx *ctx, struct v4l2_format *f,
485                              bool *use_vdoa)
486 {
487         int err;
488
489         if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
490                 return -EINVAL;
491
492         if (!use_vdoa)
493                 return -EINVAL;
494
495         if (!ctx->vdoa) {
496                 *use_vdoa = false;
497                 return 0;
498         }
499
500         err = vdoa_context_configure(NULL, round_up(f->fmt.pix.width, 16),
501                                      f->fmt.pix.height, f->fmt.pix.pixelformat);
502         if (err) {
503                 *use_vdoa = false;
504                 return 0;
505         }
506
507         *use_vdoa = true;
508         return 0;
509 }
510
511 static unsigned int coda_estimate_sizeimage(struct coda_ctx *ctx, u32 sizeimage,
512                                             u32 width, u32 height)
513 {
514         /*
515          * This is a rough estimate for sensible compressed buffer
516          * sizes (between 1 and 16 bits per pixel). This could be
517          * improved by better format specific worst case estimates.
518          */
519         return round_up(clamp(sizeimage, width * height / 8,
520                                          width * height * 2), PAGE_SIZE);
521 }
522
523 static int coda_try_fmt(struct coda_ctx *ctx, const struct coda_codec *codec,
524                         struct v4l2_format *f)
525 {
526         struct coda_dev *dev = ctx->dev;
527         unsigned int max_w, max_h;
528         enum v4l2_field field;
529
530         field = f->fmt.pix.field;
531         if (field == V4L2_FIELD_ANY)
532                 field = V4L2_FIELD_NONE;
533         else if (V4L2_FIELD_NONE != field)
534                 return -EINVAL;
535
536         /* V4L2 specification suggests the driver corrects the format struct
537          * if any of the dimensions is unsupported */
538         f->fmt.pix.field = field;
539
540         coda_get_max_dimensions(dev, codec, &max_w, &max_h);
541         v4l_bound_align_image(&f->fmt.pix.width, MIN_W, max_w, W_ALIGN,
542                               &f->fmt.pix.height, MIN_H, max_h, H_ALIGN,
543                               S_ALIGN);
544
545         switch (f->fmt.pix.pixelformat) {
546         case V4L2_PIX_FMT_NV12:
547         case V4L2_PIX_FMT_YUV420:
548         case V4L2_PIX_FMT_YVU420:
549                 /*
550                  * Frame stride must be at least multiple of 8,
551                  * but multiple of 16 for h.264 or JPEG 4:2:x
552                  */
553                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16);
554                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
555                                         f->fmt.pix.height * 3 / 2;
556                 break;
557         case V4L2_PIX_FMT_YUYV:
558                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16) * 2;
559                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
560                                         f->fmt.pix.height;
561                 break;
562         case V4L2_PIX_FMT_YUV422P:
563                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16);
564                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
565                                         f->fmt.pix.height * 2;
566                 break;
567         case V4L2_PIX_FMT_JPEG:
568         case V4L2_PIX_FMT_H264:
569         case V4L2_PIX_FMT_MPEG4:
570         case V4L2_PIX_FMT_MPEG2:
571                 f->fmt.pix.bytesperline = 0;
572                 f->fmt.pix.sizeimage = coda_estimate_sizeimage(ctx,
573                                                         f->fmt.pix.sizeimage,
574                                                         f->fmt.pix.width,
575                                                         f->fmt.pix.height);
576                 break;
577         default:
578                 BUG();
579         }
580
581         return 0;
582 }
583
584 static int coda_try_fmt_vid_cap(struct file *file, void *priv,
585                                 struct v4l2_format *f)
586 {
587         struct coda_ctx *ctx = fh_to_ctx(priv);
588         const struct coda_q_data *q_data_src;
589         const struct coda_codec *codec;
590         struct vb2_queue *src_vq;
591         int ret;
592         bool use_vdoa;
593
594         ret = coda_try_pixelformat(ctx, f);
595         if (ret < 0)
596                 return ret;
597
598         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
599
600         /*
601          * If the source format is already fixed, only allow the same output
602          * resolution
603          */
604         src_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
605         if (vb2_is_streaming(src_vq)) {
606                 f->fmt.pix.width = q_data_src->width;
607                 f->fmt.pix.height = q_data_src->height;
608         }
609
610         f->fmt.pix.colorspace = ctx->colorspace;
611         f->fmt.pix.xfer_func = ctx->xfer_func;
612         f->fmt.pix.ycbcr_enc = ctx->ycbcr_enc;
613         f->fmt.pix.quantization = ctx->quantization;
614
615         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
616         codec = coda_find_codec(ctx->dev, q_data_src->fourcc,
617                                 f->fmt.pix.pixelformat);
618         if (!codec)
619                 return -EINVAL;
620
621         ret = coda_try_fmt(ctx, codec, f);
622         if (ret < 0)
623                 return ret;
624
625         /* The h.264 decoder only returns complete 16x16 macroblocks */
626         if (codec && codec->src_fourcc == V4L2_PIX_FMT_H264) {
627                 f->fmt.pix.height = round_up(f->fmt.pix.height, 16);
628                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16);
629                 f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
630                                        f->fmt.pix.height * 3 / 2;
631
632                 ret = coda_try_fmt_vdoa(ctx, f, &use_vdoa);
633                 if (ret < 0)
634                         return ret;
635
636                 if (f->fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) {
637                         if (!use_vdoa)
638                                 return -EINVAL;
639
640                         f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 16) * 2;
641                         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline *
642                                 f->fmt.pix.height;
643                 }
644         }
645
646         return 0;
647 }
648
649 static void coda_set_default_colorspace(struct v4l2_pix_format *fmt)
650 {
651         enum v4l2_colorspace colorspace;
652
653         if (fmt->pixelformat == V4L2_PIX_FMT_JPEG)
654                 colorspace = V4L2_COLORSPACE_JPEG;
655         else if (fmt->width <= 720 && fmt->height <= 576)
656                 colorspace = V4L2_COLORSPACE_SMPTE170M;
657         else
658                 colorspace = V4L2_COLORSPACE_REC709;
659
660         fmt->colorspace = colorspace;
661         fmt->xfer_func = V4L2_XFER_FUNC_DEFAULT;
662         fmt->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
663         fmt->quantization = V4L2_QUANTIZATION_DEFAULT;
664 }
665
666 static int coda_try_fmt_vid_out(struct file *file, void *priv,
667                                 struct v4l2_format *f)
668 {
669         struct coda_ctx *ctx = fh_to_ctx(priv);
670         struct coda_dev *dev = ctx->dev;
671         const struct coda_q_data *q_data_dst;
672         const struct coda_codec *codec;
673         int ret;
674
675         ret = coda_try_pixelformat(ctx, f);
676         if (ret < 0)
677                 return ret;
678
679         if (f->fmt.pix.colorspace == V4L2_COLORSPACE_DEFAULT)
680                 coda_set_default_colorspace(&f->fmt.pix);
681
682         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
683         codec = coda_find_codec(dev, f->fmt.pix.pixelformat, q_data_dst->fourcc);
684
685         return coda_try_fmt(ctx, codec, f);
686 }
687
688 static int coda_s_fmt(struct coda_ctx *ctx, struct v4l2_format *f,
689                       struct v4l2_rect *r)
690 {
691         struct coda_q_data *q_data;
692         struct vb2_queue *vq;
693
694         vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type);
695         if (!vq)
696                 return -EINVAL;
697
698         q_data = get_q_data(ctx, f->type);
699         if (!q_data)
700                 return -EINVAL;
701
702         if (vb2_is_busy(vq)) {
703                 v4l2_err(&ctx->dev->v4l2_dev, "%s: %s queue busy: %d\n",
704                          __func__, v4l2_type_names[f->type], vq->num_buffers);
705                 return -EBUSY;
706         }
707
708         q_data->fourcc = f->fmt.pix.pixelformat;
709         q_data->width = f->fmt.pix.width;
710         q_data->height = f->fmt.pix.height;
711         q_data->bytesperline = f->fmt.pix.bytesperline;
712         q_data->sizeimage = f->fmt.pix.sizeimage;
713         if (r) {
714                 q_data->rect = *r;
715         } else {
716                 q_data->rect.left = 0;
717                 q_data->rect.top = 0;
718                 q_data->rect.width = f->fmt.pix.width;
719                 q_data->rect.height = f->fmt.pix.height;
720         }
721
722         switch (f->fmt.pix.pixelformat) {
723         case V4L2_PIX_FMT_YUYV:
724                 ctx->tiled_map_type = GDI_TILED_FRAME_MB_RASTER_MAP;
725                 break;
726         case V4L2_PIX_FMT_NV12:
727                 if (!disable_tiling && ctx->dev->devtype->product == CODA_960) {
728                         ctx->tiled_map_type = GDI_TILED_FRAME_MB_RASTER_MAP;
729                         break;
730                 }
731                 /* else fall through */
732         case V4L2_PIX_FMT_YUV420:
733         case V4L2_PIX_FMT_YVU420:
734                 ctx->tiled_map_type = GDI_LINEAR_FRAME_MAP;
735                 break;
736         default:
737                 break;
738         }
739
740         if (ctx->tiled_map_type == GDI_TILED_FRAME_MB_RASTER_MAP &&
741             !coda_try_fmt_vdoa(ctx, f, &ctx->use_vdoa) &&
742             ctx->use_vdoa)
743                 vdoa_context_configure(ctx->vdoa,
744                                        round_up(f->fmt.pix.width, 16),
745                                        f->fmt.pix.height,
746                                        f->fmt.pix.pixelformat);
747         else
748                 ctx->use_vdoa = false;
749
750         coda_dbg(1, ctx, "Setting %s format, wxh: %dx%d, fmt: %4.4s %c\n",
751                  v4l2_type_names[f->type], q_data->width, q_data->height,
752                  (char *)&q_data->fourcc,
753                  (ctx->tiled_map_type == GDI_LINEAR_FRAME_MAP) ? 'L' : 'T');
754
755         return 0;
756 }
757
758 static int coda_s_fmt_vid_cap(struct file *file, void *priv,
759                               struct v4l2_format *f)
760 {
761         struct coda_ctx *ctx = fh_to_ctx(priv);
762         struct coda_q_data *q_data_src;
763         const struct coda_codec *codec;
764         struct v4l2_rect r;
765         int ret;
766
767         ret = coda_try_fmt_vid_cap(file, priv, f);
768         if (ret)
769                 return ret;
770
771         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
772         r.left = 0;
773         r.top = 0;
774         r.width = q_data_src->width;
775         r.height = q_data_src->height;
776
777         ret = coda_s_fmt(ctx, f, &r);
778         if (ret)
779                 return ret;
780
781         if (ctx->inst_type != CODA_INST_ENCODER)
782                 return 0;
783
784         /* Setting the coded format determines the selected codec */
785         codec = coda_find_codec(ctx->dev, q_data_src->fourcc,
786                                 f->fmt.pix.pixelformat);
787         if (!codec) {
788                 v4l2_err(&ctx->dev->v4l2_dev, "failed to determine codec\n");
789                 return -EINVAL;
790         }
791         ctx->codec = codec;
792
793         ctx->colorspace = f->fmt.pix.colorspace;
794         ctx->xfer_func = f->fmt.pix.xfer_func;
795         ctx->ycbcr_enc = f->fmt.pix.ycbcr_enc;
796         ctx->quantization = f->fmt.pix.quantization;
797
798         return 0;
799 }
800
801 static int coda_s_fmt_vid_out(struct file *file, void *priv,
802                               struct v4l2_format *f)
803 {
804         struct coda_ctx *ctx = fh_to_ctx(priv);
805         const struct coda_codec *codec;
806         struct v4l2_format f_cap;
807         struct vb2_queue *dst_vq;
808         int ret;
809
810         ret = coda_try_fmt_vid_out(file, priv, f);
811         if (ret)
812                 return ret;
813
814         ret = coda_s_fmt(ctx, f, NULL);
815         if (ret)
816                 return ret;
817
818         ctx->colorspace = f->fmt.pix.colorspace;
819         ctx->xfer_func = f->fmt.pix.xfer_func;
820         ctx->ycbcr_enc = f->fmt.pix.ycbcr_enc;
821         ctx->quantization = f->fmt.pix.quantization;
822
823         if (ctx->inst_type != CODA_INST_DECODER)
824                 return 0;
825
826         /* Setting the coded format determines the selected codec */
827         codec = coda_find_codec(ctx->dev, f->fmt.pix.pixelformat,
828                                 V4L2_PIX_FMT_YUV420);
829         if (!codec) {
830                 v4l2_err(&ctx->dev->v4l2_dev, "failed to determine codec\n");
831                 return -EINVAL;
832         }
833         ctx->codec = codec;
834
835         dst_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
836         if (!dst_vq)
837                 return -EINVAL;
838
839         /*
840          * Setting the capture queue format is not possible while the capture
841          * queue is still busy. This is not an error, but the user will have to
842          * make sure themselves that the capture format is set correctly before
843          * starting the output queue again.
844          */
845         if (vb2_is_busy(dst_vq))
846                 return 0;
847
848         memset(&f_cap, 0, sizeof(f_cap));
849         f_cap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
850         coda_g_fmt(file, priv, &f_cap);
851         f_cap.fmt.pix.width = f->fmt.pix.width;
852         f_cap.fmt.pix.height = f->fmt.pix.height;
853
854         return coda_s_fmt_vid_cap(file, priv, &f_cap);
855 }
856
857 static int coda_reqbufs(struct file *file, void *priv,
858                         struct v4l2_requestbuffers *rb)
859 {
860         struct coda_ctx *ctx = fh_to_ctx(priv);
861         int ret;
862
863         ret = v4l2_m2m_reqbufs(file, ctx->fh.m2m_ctx, rb);
864         if (ret)
865                 return ret;
866
867         /*
868          * Allow to allocate instance specific per-context buffers, such as
869          * bitstream ringbuffer, slice buffer, work buffer, etc. if needed.
870          */
871         if (rb->type == V4L2_BUF_TYPE_VIDEO_OUTPUT && ctx->ops->reqbufs)
872                 return ctx->ops->reqbufs(ctx, rb);
873
874         return 0;
875 }
876
877 static int coda_qbuf(struct file *file, void *priv,
878                      struct v4l2_buffer *buf)
879 {
880         struct coda_ctx *ctx = fh_to_ctx(priv);
881
882         if (ctx->inst_type == CODA_INST_DECODER &&
883             buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
884                 buf->flags &= ~V4L2_BUF_FLAG_LAST;
885
886         return v4l2_m2m_qbuf(file, ctx->fh.m2m_ctx, buf);
887 }
888
889 static int coda_dqbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
890 {
891         struct coda_ctx *ctx = fh_to_ctx(priv);
892         int ret;
893
894         ret = v4l2_m2m_dqbuf(file, ctx->fh.m2m_ctx, buf);
895
896         if (ctx->inst_type == CODA_INST_DECODER &&
897             buf->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
898                 buf->flags &= ~V4L2_BUF_FLAG_LAST;
899
900         return ret;
901 }
902
903 void coda_m2m_buf_done(struct coda_ctx *ctx, struct vb2_v4l2_buffer *buf,
904                        enum vb2_buffer_state state)
905 {
906         const struct v4l2_event eos_event = {
907                 .type = V4L2_EVENT_EOS
908         };
909
910         if (buf->flags & V4L2_BUF_FLAG_LAST)
911                 v4l2_event_queue_fh(&ctx->fh, &eos_event);
912
913         v4l2_m2m_buf_done(buf, state);
914 }
915
916 static int coda_g_selection(struct file *file, void *fh,
917                             struct v4l2_selection *s)
918 {
919         struct coda_ctx *ctx = fh_to_ctx(fh);
920         struct coda_q_data *q_data;
921         struct v4l2_rect r, *rsel;
922
923         q_data = get_q_data(ctx, s->type);
924         if (!q_data)
925                 return -EINVAL;
926
927         r.left = 0;
928         r.top = 0;
929         r.width = q_data->width;
930         r.height = q_data->height;
931         rsel = &q_data->rect;
932
933         switch (s->target) {
934         case V4L2_SEL_TGT_CROP_DEFAULT:
935         case V4L2_SEL_TGT_CROP_BOUNDS:
936                 rsel = &r;
937                 /* fallthrough */
938         case V4L2_SEL_TGT_CROP:
939                 if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
940                         return -EINVAL;
941                 break;
942         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
943         case V4L2_SEL_TGT_COMPOSE_PADDED:
944                 rsel = &r;
945                 /* fallthrough */
946         case V4L2_SEL_TGT_COMPOSE:
947         case V4L2_SEL_TGT_COMPOSE_DEFAULT:
948                 if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
949                         return -EINVAL;
950                 break;
951         default:
952                 return -EINVAL;
953         }
954
955         s->r = *rsel;
956
957         return 0;
958 }
959
960 static int coda_s_selection(struct file *file, void *fh,
961                             struct v4l2_selection *s)
962 {
963         struct coda_ctx *ctx = fh_to_ctx(fh);
964         struct coda_q_data *q_data;
965
966         switch (s->target) {
967         case V4L2_SEL_TGT_CROP:
968                 if (ctx->inst_type == CODA_INST_ENCODER &&
969                     s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
970                         q_data = get_q_data(ctx, s->type);
971                         if (!q_data)
972                                 return -EINVAL;
973
974                         s->r.left = 0;
975                         s->r.top = 0;
976                         s->r.width = clamp(s->r.width, 2U, q_data->width);
977                         s->r.height = clamp(s->r.height, 2U, q_data->height);
978
979                         if (s->flags & V4L2_SEL_FLAG_LE) {
980                                 s->r.width = round_up(s->r.width, 2);
981                                 s->r.height = round_up(s->r.height, 2);
982                         } else {
983                                 s->r.width = round_down(s->r.width, 2);
984                                 s->r.height = round_down(s->r.height, 2);
985                         }
986
987                         q_data->rect = s->r;
988
989                         coda_dbg(1, ctx, "Setting crop rectangle: %dx%d\n",
990                                  s->r.width, s->r.height);
991
992                         return 0;
993                 }
994                 /* else fall through */
995         case V4L2_SEL_TGT_NATIVE_SIZE:
996         case V4L2_SEL_TGT_COMPOSE:
997                 return coda_g_selection(file, fh, s);
998         default:
999                 /* v4l2-compliance expects this to fail for read-only targets */
1000                 return -EINVAL;
1001         }
1002 }
1003
1004 static int coda_try_encoder_cmd(struct file *file, void *fh,
1005                                 struct v4l2_encoder_cmd *ec)
1006 {
1007         struct coda_ctx *ctx = fh_to_ctx(fh);
1008
1009         if (ctx->inst_type != CODA_INST_ENCODER)
1010                 return -ENOTTY;
1011
1012         return v4l2_m2m_ioctl_try_encoder_cmd(file, fh, ec);
1013 }
1014
1015 static void coda_wake_up_capture_queue(struct coda_ctx *ctx)
1016 {
1017         struct vb2_queue *dst_vq;
1018
1019         coda_dbg(1, ctx, "waking up capture queue\n");
1020
1021         dst_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1022         dst_vq->last_buffer_dequeued = true;
1023         wake_up(&dst_vq->done_wq);
1024 }
1025
1026 static int coda_encoder_cmd(struct file *file, void *fh,
1027                             struct v4l2_encoder_cmd *ec)
1028 {
1029         struct coda_ctx *ctx = fh_to_ctx(fh);
1030         struct vb2_v4l2_buffer *buf;
1031         int ret;
1032
1033         ret = coda_try_encoder_cmd(file, fh, ec);
1034         if (ret < 0)
1035                 return ret;
1036
1037         mutex_lock(&ctx->wakeup_mutex);
1038         buf = v4l2_m2m_last_src_buf(ctx->fh.m2m_ctx);
1039         if (buf) {
1040                 /*
1041                  * If the last output buffer is still on the queue, make sure
1042                  * that decoder finish_run will see the last flag and report it
1043                  * to userspace.
1044                  */
1045                 buf->flags |= V4L2_BUF_FLAG_LAST;
1046         } else {
1047                 /* Set the stream-end flag on this context */
1048                 ctx->bit_stream_param |= CODA_BIT_STREAM_END_FLAG;
1049
1050                 /*
1051                  * If the last output buffer has already been taken from the
1052                  * queue, wake up the capture queue and signal end of stream
1053                  * via the -EPIPE mechanism.
1054                  */
1055                 coda_wake_up_capture_queue(ctx);
1056         }
1057         mutex_unlock(&ctx->wakeup_mutex);
1058
1059         return 0;
1060 }
1061
1062 static int coda_try_decoder_cmd(struct file *file, void *fh,
1063                                 struct v4l2_decoder_cmd *dc)
1064 {
1065         struct coda_ctx *ctx = fh_to_ctx(fh);
1066
1067         if (ctx->inst_type != CODA_INST_DECODER)
1068                 return -ENOTTY;
1069
1070         return v4l2_m2m_ioctl_try_decoder_cmd(file, fh, dc);
1071 }
1072
1073 static int coda_decoder_cmd(struct file *file, void *fh,
1074                             struct v4l2_decoder_cmd *dc)
1075 {
1076         struct coda_ctx *ctx = fh_to_ctx(fh);
1077         struct coda_dev *dev = ctx->dev;
1078         struct vb2_v4l2_buffer *buf;
1079         struct vb2_queue *dst_vq;
1080         bool stream_end;
1081         bool wakeup;
1082         int ret;
1083
1084         ret = coda_try_decoder_cmd(file, fh, dc);
1085         if (ret < 0)
1086                 return ret;
1087
1088         switch (dc->cmd) {
1089         case V4L2_DEC_CMD_START:
1090                 mutex_lock(&ctx->bitstream_mutex);
1091                 mutex_lock(&dev->coda_mutex);
1092                 coda_bitstream_flush(ctx);
1093                 mutex_unlock(&dev->coda_mutex);
1094                 dst_vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx,
1095                                          V4L2_BUF_TYPE_VIDEO_CAPTURE);
1096                 vb2_clear_last_buffer_dequeued(dst_vq);
1097                 ctx->bit_stream_param &= ~CODA_BIT_STREAM_END_FLAG;
1098                 coda_fill_bitstream(ctx, NULL);
1099                 mutex_unlock(&ctx->bitstream_mutex);
1100                 break;
1101         case V4L2_DEC_CMD_STOP:
1102                 stream_end = false;
1103                 wakeup = false;
1104
1105                 buf = v4l2_m2m_last_src_buf(ctx->fh.m2m_ctx);
1106                 if (buf) {
1107                         coda_dbg(1, ctx, "marking last pending buffer\n");
1108
1109                         /* Mark last buffer */
1110                         buf->flags |= V4L2_BUF_FLAG_LAST;
1111
1112                         if (v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx) == 0) {
1113                                 coda_dbg(1, ctx, "all remaining buffers queued\n");
1114                                 stream_end = true;
1115                         }
1116                 } else {
1117                         coda_dbg(1, ctx, "marking last meta\n");
1118
1119                         /* Mark last meta */
1120                         spin_lock(&ctx->buffer_meta_lock);
1121                         if (!list_empty(&ctx->buffer_meta_list)) {
1122                                 struct coda_buffer_meta *meta;
1123
1124                                 meta = list_last_entry(&ctx->buffer_meta_list,
1125                                                        struct coda_buffer_meta,
1126                                                        list);
1127                                 meta->last = true;
1128                                 stream_end = true;
1129                         } else {
1130                                 wakeup = true;
1131                         }
1132                         spin_unlock(&ctx->buffer_meta_lock);
1133                 }
1134
1135                 if (stream_end) {
1136                         coda_dbg(1, ctx, "all remaining buffers queued\n");
1137
1138                         /* Set the stream-end flag on this context */
1139                         coda_bit_stream_end_flag(ctx);
1140                         ctx->hold = false;
1141                         v4l2_m2m_try_schedule(ctx->fh.m2m_ctx);
1142                 }
1143
1144                 if (wakeup) {
1145                         /* If there is no buffer in flight, wake up */
1146                         coda_wake_up_capture_queue(ctx);
1147                 }
1148
1149                 break;
1150         default:
1151                 return -EINVAL;
1152         }
1153
1154         return 0;
1155 }
1156
1157 static int coda_enum_framesizes(struct file *file, void *fh,
1158                                 struct v4l2_frmsizeenum *fsize)
1159 {
1160         struct coda_ctx *ctx = fh_to_ctx(fh);
1161         struct coda_q_data *q_data_dst;
1162         const struct coda_codec *codec;
1163
1164         if (ctx->inst_type != CODA_INST_ENCODER)
1165                 return -ENOTTY;
1166
1167         if (fsize->index)
1168                 return -EINVAL;
1169
1170         if (coda_format_normalize_yuv(fsize->pixel_format) ==
1171             V4L2_PIX_FMT_YUV420) {
1172                 q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1173                 codec = coda_find_codec(ctx->dev, fsize->pixel_format,
1174                                         q_data_dst->fourcc);
1175         } else {
1176                 codec = coda_find_codec(ctx->dev, V4L2_PIX_FMT_YUV420,
1177                                         fsize->pixel_format);
1178         }
1179         if (!codec)
1180                 return -EINVAL;
1181
1182         fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
1183         fsize->stepwise.min_width = MIN_W;
1184         fsize->stepwise.max_width = codec->max_w;
1185         fsize->stepwise.step_width = 1;
1186         fsize->stepwise.min_height = MIN_H;
1187         fsize->stepwise.max_height = codec->max_h;
1188         fsize->stepwise.step_height = 1;
1189
1190         return 0;
1191 }
1192
1193 static int coda_enum_frameintervals(struct file *file, void *fh,
1194                                     struct v4l2_frmivalenum *f)
1195 {
1196         struct coda_ctx *ctx = fh_to_ctx(fh);
1197         int i;
1198
1199         if (f->index)
1200                 return -EINVAL;
1201
1202         /* Disallow YUYV if the vdoa is not available */
1203         if (!ctx->vdoa && f->pixel_format == V4L2_PIX_FMT_YUYV)
1204                 return -EINVAL;
1205
1206         for (i = 0; i < CODA_MAX_FORMATS; i++) {
1207                 if (f->pixel_format == ctx->cvd->src_formats[i] ||
1208                     f->pixel_format == ctx->cvd->dst_formats[i])
1209                         break;
1210         }
1211         if (i == CODA_MAX_FORMATS)
1212                 return -EINVAL;
1213
1214         f->type = V4L2_FRMIVAL_TYPE_CONTINUOUS;
1215         f->stepwise.min.numerator = 1;
1216         f->stepwise.min.denominator = 65535;
1217         f->stepwise.max.numerator = 65536;
1218         f->stepwise.max.denominator = 1;
1219         f->stepwise.step.numerator = 1;
1220         f->stepwise.step.denominator = 1;
1221
1222         return 0;
1223 }
1224
1225 static int coda_g_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1226 {
1227         struct coda_ctx *ctx = fh_to_ctx(fh);
1228         struct v4l2_fract *tpf;
1229
1230         if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
1231                 return -EINVAL;
1232
1233         a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
1234         tpf = &a->parm.output.timeperframe;
1235         tpf->denominator = ctx->params.framerate & CODA_FRATE_RES_MASK;
1236         tpf->numerator = 1 + (ctx->params.framerate >>
1237                               CODA_FRATE_DIV_OFFSET);
1238
1239         return 0;
1240 }
1241
1242 /*
1243  * Approximate timeperframe v4l2_fract with values that can be written
1244  * into the 16-bit CODA_FRATE_DIV and CODA_FRATE_RES fields.
1245  */
1246 static void coda_approximate_timeperframe(struct v4l2_fract *timeperframe)
1247 {
1248         struct v4l2_fract s = *timeperframe;
1249         struct v4l2_fract f0;
1250         struct v4l2_fract f1 = { 1, 0 };
1251         struct v4l2_fract f2 = { 0, 1 };
1252         unsigned int i, div, s_denominator;
1253
1254         /* Lower bound is 1/65535 */
1255         if (s.numerator == 0 || s.denominator / s.numerator > 65535) {
1256                 timeperframe->numerator = 1;
1257                 timeperframe->denominator = 65535;
1258                 return;
1259         }
1260
1261         /* Upper bound is 65536/1 */
1262         if (s.denominator == 0 || s.numerator / s.denominator > 65536) {
1263                 timeperframe->numerator = 65536;
1264                 timeperframe->denominator = 1;
1265                 return;
1266         }
1267
1268         /* Reduce fraction to lowest terms */
1269         div = gcd(s.numerator, s.denominator);
1270         if (div > 1) {
1271                 s.numerator /= div;
1272                 s.denominator /= div;
1273         }
1274
1275         if (s.numerator <= 65536 && s.denominator < 65536) {
1276                 *timeperframe = s;
1277                 return;
1278         }
1279
1280         /* Find successive convergents from continued fraction expansion */
1281         while (f2.numerator <= 65536 && f2.denominator < 65536) {
1282                 f0 = f1;
1283                 f1 = f2;
1284
1285                 /* Stop when f2 exactly equals timeperframe */
1286                 if (s.numerator == 0)
1287                         break;
1288
1289                 i = s.denominator / s.numerator;
1290
1291                 f2.numerator = f0.numerator + i * f1.numerator;
1292                 f2.denominator = f0.denominator + i * f2.denominator;
1293
1294                 s_denominator = s.numerator;
1295                 s.numerator = s.denominator % s.numerator;
1296                 s.denominator = s_denominator;
1297         }
1298
1299         *timeperframe = f1;
1300 }
1301
1302 static uint32_t coda_timeperframe_to_frate(struct v4l2_fract *timeperframe)
1303 {
1304         return ((timeperframe->numerator - 1) << CODA_FRATE_DIV_OFFSET) |
1305                 timeperframe->denominator;
1306 }
1307
1308 static int coda_s_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
1309 {
1310         struct coda_ctx *ctx = fh_to_ctx(fh);
1311         struct v4l2_fract *tpf;
1312
1313         if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
1314                 return -EINVAL;
1315
1316         a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
1317         tpf = &a->parm.output.timeperframe;
1318         coda_approximate_timeperframe(tpf);
1319         ctx->params.framerate = coda_timeperframe_to_frate(tpf);
1320         ctx->params.framerate_changed = true;
1321
1322         return 0;
1323 }
1324
1325 static int coda_subscribe_event(struct v4l2_fh *fh,
1326                                 const struct v4l2_event_subscription *sub)
1327 {
1328         struct coda_ctx *ctx = fh_to_ctx(fh);
1329
1330         switch (sub->type) {
1331         case V4L2_EVENT_EOS:
1332                 return v4l2_event_subscribe(fh, sub, 0, NULL);
1333         case V4L2_EVENT_SOURCE_CHANGE:
1334                 if (ctx->inst_type == CODA_INST_DECODER)
1335                         return v4l2_event_subscribe(fh, sub, 0, NULL);
1336                 else
1337                         return -EINVAL;
1338         default:
1339                 return v4l2_ctrl_subscribe_event(fh, sub);
1340         }
1341 }
1342
1343 static const struct v4l2_ioctl_ops coda_ioctl_ops = {
1344         .vidioc_querycap        = coda_querycap,
1345
1346         .vidioc_enum_fmt_vid_cap = coda_enum_fmt,
1347         .vidioc_g_fmt_vid_cap   = coda_g_fmt,
1348         .vidioc_try_fmt_vid_cap = coda_try_fmt_vid_cap,
1349         .vidioc_s_fmt_vid_cap   = coda_s_fmt_vid_cap,
1350
1351         .vidioc_enum_fmt_vid_out = coda_enum_fmt,
1352         .vidioc_g_fmt_vid_out   = coda_g_fmt,
1353         .vidioc_try_fmt_vid_out = coda_try_fmt_vid_out,
1354         .vidioc_s_fmt_vid_out   = coda_s_fmt_vid_out,
1355
1356         .vidioc_reqbufs         = coda_reqbufs,
1357         .vidioc_querybuf        = v4l2_m2m_ioctl_querybuf,
1358
1359         .vidioc_qbuf            = coda_qbuf,
1360         .vidioc_expbuf          = v4l2_m2m_ioctl_expbuf,
1361         .vidioc_dqbuf           = coda_dqbuf,
1362         .vidioc_create_bufs     = v4l2_m2m_ioctl_create_bufs,
1363         .vidioc_prepare_buf     = v4l2_m2m_ioctl_prepare_buf,
1364
1365         .vidioc_streamon        = v4l2_m2m_ioctl_streamon,
1366         .vidioc_streamoff       = v4l2_m2m_ioctl_streamoff,
1367
1368         .vidioc_g_selection     = coda_g_selection,
1369         .vidioc_s_selection     = coda_s_selection,
1370
1371         .vidioc_try_encoder_cmd = coda_try_encoder_cmd,
1372         .vidioc_encoder_cmd     = coda_encoder_cmd,
1373         .vidioc_try_decoder_cmd = coda_try_decoder_cmd,
1374         .vidioc_decoder_cmd     = coda_decoder_cmd,
1375
1376         .vidioc_g_parm          = coda_g_parm,
1377         .vidioc_s_parm          = coda_s_parm,
1378
1379         .vidioc_enum_framesizes = coda_enum_framesizes,
1380         .vidioc_enum_frameintervals = coda_enum_frameintervals,
1381
1382         .vidioc_subscribe_event = coda_subscribe_event,
1383         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1384 };
1385
1386 /*
1387  * Mem-to-mem operations.
1388  */
1389
1390 static void coda_device_run(void *m2m_priv)
1391 {
1392         struct coda_ctx *ctx = m2m_priv;
1393         struct coda_dev *dev = ctx->dev;
1394
1395         queue_work(dev->workqueue, &ctx->pic_run_work);
1396 }
1397
1398 static void coda_pic_run_work(struct work_struct *work)
1399 {
1400         struct coda_ctx *ctx = container_of(work, struct coda_ctx, pic_run_work);
1401         struct coda_dev *dev = ctx->dev;
1402         int ret;
1403
1404         mutex_lock(&ctx->buffer_mutex);
1405         mutex_lock(&dev->coda_mutex);
1406
1407         ret = ctx->ops->prepare_run(ctx);
1408         if (ret < 0 && ctx->inst_type == CODA_INST_DECODER) {
1409                 mutex_unlock(&dev->coda_mutex);
1410                 mutex_unlock(&ctx->buffer_mutex);
1411                 /* job_finish scheduled by prepare_decode */
1412                 return;
1413         }
1414
1415         if (!wait_for_completion_timeout(&ctx->completion,
1416                                          msecs_to_jiffies(1000))) {
1417                 dev_err(dev->dev, "CODA PIC_RUN timeout\n");
1418
1419                 ctx->hold = true;
1420
1421                 coda_hw_reset(ctx);
1422
1423                 if (ctx->ops->run_timeout)
1424                         ctx->ops->run_timeout(ctx);
1425         } else if (!ctx->aborting) {
1426                 ctx->ops->finish_run(ctx);
1427         }
1428
1429         if ((ctx->aborting || (!ctx->streamon_cap && !ctx->streamon_out)) &&
1430             ctx->ops->seq_end_work)
1431                 queue_work(dev->workqueue, &ctx->seq_end_work);
1432
1433         mutex_unlock(&dev->coda_mutex);
1434         mutex_unlock(&ctx->buffer_mutex);
1435
1436         v4l2_m2m_job_finish(ctx->dev->m2m_dev, ctx->fh.m2m_ctx);
1437 }
1438
1439 static int coda_job_ready(void *m2m_priv)
1440 {
1441         struct coda_ctx *ctx = m2m_priv;
1442         int src_bufs = v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx);
1443
1444         /*
1445          * For both 'P' and 'key' frame cases 1 picture
1446          * and 1 frame are needed. In the decoder case,
1447          * the compressed frame can be in the bitstream.
1448          */
1449         if (!src_bufs && ctx->inst_type != CODA_INST_DECODER) {
1450                 coda_dbg(1, ctx, "not ready: not enough vid-out buffers.\n");
1451                 return 0;
1452         }
1453
1454         if (!v4l2_m2m_num_dst_bufs_ready(ctx->fh.m2m_ctx)) {
1455                 coda_dbg(1, ctx, "not ready: not enough vid-cap buffers.\n");
1456                 return 0;
1457         }
1458
1459         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit) {
1460                 bool stream_end = ctx->bit_stream_param &
1461                                   CODA_BIT_STREAM_END_FLAG;
1462                 int num_metas = ctx->num_metas;
1463                 struct coda_buffer_meta *meta;
1464                 unsigned int count;
1465
1466                 count = hweight32(ctx->frm_dis_flg);
1467                 if (ctx->use_vdoa && count >= (ctx->num_internal_frames - 1)) {
1468                         coda_dbg(1, ctx,
1469                                  "not ready: all internal buffers in use: %d/%d (0x%x)",
1470                                  count, ctx->num_internal_frames,
1471                                  ctx->frm_dis_flg);
1472                         return 0;
1473                 }
1474
1475                 if (ctx->hold && !src_bufs) {
1476                         coda_dbg(1, ctx,
1477                                  "not ready: on hold for more buffers.\n");
1478                         return 0;
1479                 }
1480
1481                 if (!stream_end && (num_metas + src_bufs) < 2) {
1482                         coda_dbg(1, ctx,
1483                                  "not ready: need 2 buffers available (queue:%d + bitstream:%d)\n",
1484                                  num_metas, src_bufs);
1485                         return 0;
1486                 }
1487
1488                 meta = list_first_entry(&ctx->buffer_meta_list,
1489                                         struct coda_buffer_meta, list);
1490                 if (!coda_bitstream_can_fetch_past(ctx, meta->end) &&
1491                     !stream_end) {
1492                         coda_dbg(1, ctx,
1493                                  "not ready: not enough bitstream data to read past %u (%u)\n",
1494                                  meta->end, ctx->bitstream_fifo.kfifo.in);
1495                         return 0;
1496                 }
1497         }
1498
1499         if (ctx->aborting) {
1500                 coda_dbg(1, ctx, "not ready: aborting\n");
1501                 return 0;
1502         }
1503
1504         coda_dbg(2, ctx, "job ready\n");
1505
1506         return 1;
1507 }
1508
1509 static void coda_job_abort(void *priv)
1510 {
1511         struct coda_ctx *ctx = priv;
1512
1513         ctx->aborting = 1;
1514
1515         coda_dbg(1, ctx, "job abort\n");
1516 }
1517
1518 static const struct v4l2_m2m_ops coda_m2m_ops = {
1519         .device_run     = coda_device_run,
1520         .job_ready      = coda_job_ready,
1521         .job_abort      = coda_job_abort,
1522 };
1523
1524 static void set_default_params(struct coda_ctx *ctx)
1525 {
1526         unsigned int max_w, max_h, usize, csize;
1527
1528         ctx->codec = coda_find_codec(ctx->dev, ctx->cvd->src_formats[0],
1529                                      ctx->cvd->dst_formats[0]);
1530         max_w = min(ctx->codec->max_w, 1920U);
1531         max_h = min(ctx->codec->max_h, 1088U);
1532         usize = max_w * max_h * 3 / 2;
1533         csize = coda_estimate_sizeimage(ctx, usize, max_w, max_h);
1534
1535         ctx->params.codec_mode = ctx->codec->mode;
1536         if (ctx->cvd->src_formats[0] == V4L2_PIX_FMT_JPEG)
1537                 ctx->colorspace = V4L2_COLORSPACE_JPEG;
1538         else
1539                 ctx->colorspace = V4L2_COLORSPACE_REC709;
1540         ctx->xfer_func = V4L2_XFER_FUNC_DEFAULT;
1541         ctx->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
1542         ctx->quantization = V4L2_QUANTIZATION_DEFAULT;
1543         ctx->params.framerate = 30;
1544
1545         /* Default formats for output and input queues */
1546         ctx->q_data[V4L2_M2M_SRC].fourcc = ctx->cvd->src_formats[0];
1547         ctx->q_data[V4L2_M2M_DST].fourcc = ctx->cvd->dst_formats[0];
1548         ctx->q_data[V4L2_M2M_SRC].width = max_w;
1549         ctx->q_data[V4L2_M2M_SRC].height = max_h;
1550         ctx->q_data[V4L2_M2M_DST].width = max_w;
1551         ctx->q_data[V4L2_M2M_DST].height = max_h;
1552         if (ctx->codec->src_fourcc == V4L2_PIX_FMT_YUV420) {
1553                 ctx->q_data[V4L2_M2M_SRC].bytesperline = max_w;
1554                 ctx->q_data[V4L2_M2M_SRC].sizeimage = usize;
1555                 ctx->q_data[V4L2_M2M_DST].bytesperline = 0;
1556                 ctx->q_data[V4L2_M2M_DST].sizeimage = csize;
1557         } else {
1558                 ctx->q_data[V4L2_M2M_SRC].bytesperline = 0;
1559                 ctx->q_data[V4L2_M2M_SRC].sizeimage = csize;
1560                 ctx->q_data[V4L2_M2M_DST].bytesperline = max_w;
1561                 ctx->q_data[V4L2_M2M_DST].sizeimage = usize;
1562         }
1563         ctx->q_data[V4L2_M2M_SRC].rect.width = max_w;
1564         ctx->q_data[V4L2_M2M_SRC].rect.height = max_h;
1565         ctx->q_data[V4L2_M2M_DST].rect.width = max_w;
1566         ctx->q_data[V4L2_M2M_DST].rect.height = max_h;
1567
1568         /*
1569          * Since the RBC2AXI logic only supports a single chroma plane,
1570          * macroblock tiling only works for to NV12 pixel format.
1571          */
1572         ctx->tiled_map_type = GDI_LINEAR_FRAME_MAP;
1573 }
1574
1575 /*
1576  * Queue operations
1577  */
1578 static int coda_queue_setup(struct vb2_queue *vq,
1579                                 unsigned int *nbuffers, unsigned int *nplanes,
1580                                 unsigned int sizes[], struct device *alloc_devs[])
1581 {
1582         struct coda_ctx *ctx = vb2_get_drv_priv(vq);
1583         struct coda_q_data *q_data;
1584         unsigned int size;
1585
1586         q_data = get_q_data(ctx, vq->type);
1587         size = q_data->sizeimage;
1588
1589         if (*nplanes)
1590                 return sizes[0] < size ? -EINVAL : 0;
1591
1592         *nplanes = 1;
1593         sizes[0] = size;
1594
1595         coda_dbg(1, ctx, "get %d buffer(s) of size %d each.\n", *nbuffers,
1596                  size);
1597
1598         return 0;
1599 }
1600
1601 static int coda_buf_prepare(struct vb2_buffer *vb)
1602 {
1603         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1604         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1605         struct coda_q_data *q_data;
1606
1607         q_data = get_q_data(ctx, vb->vb2_queue->type);
1608         if (V4L2_TYPE_IS_OUTPUT(vb->vb2_queue->type)) {
1609                 if (vbuf->field == V4L2_FIELD_ANY)
1610                         vbuf->field = V4L2_FIELD_NONE;
1611                 if (vbuf->field != V4L2_FIELD_NONE) {
1612                         v4l2_warn(&ctx->dev->v4l2_dev,
1613                                   "%s field isn't supported\n", __func__);
1614                         return -EINVAL;
1615                 }
1616         }
1617
1618         if (vb2_plane_size(vb, 0) < q_data->sizeimage) {
1619                 v4l2_warn(&ctx->dev->v4l2_dev,
1620                           "%s data will not fit into plane (%lu < %lu)\n",
1621                           __func__, vb2_plane_size(vb, 0),
1622                           (long)q_data->sizeimage);
1623                 return -EINVAL;
1624         }
1625
1626         return 0;
1627 }
1628
1629 static void coda_update_menu_ctrl(struct v4l2_ctrl *ctrl, int value)
1630 {
1631         if (!ctrl)
1632                 return;
1633
1634         v4l2_ctrl_lock(ctrl);
1635
1636         /*
1637          * Extend the control range if the parsed stream contains a known but
1638          * unsupported value or level.
1639          */
1640         if (value > ctrl->maximum) {
1641                 __v4l2_ctrl_modify_range(ctrl, ctrl->minimum, value,
1642                         ctrl->menu_skip_mask & ~(1 << value),
1643                         ctrl->default_value);
1644         } else if (value < ctrl->minimum) {
1645                 __v4l2_ctrl_modify_range(ctrl, value, ctrl->maximum,
1646                         ctrl->menu_skip_mask & ~(1 << value),
1647                         ctrl->default_value);
1648         }
1649
1650         __v4l2_ctrl_s_ctrl(ctrl, value);
1651
1652         v4l2_ctrl_unlock(ctrl);
1653 }
1654
1655 void coda_update_profile_level_ctrls(struct coda_ctx *ctx, u8 profile_idc,
1656                                      u8 level_idc)
1657 {
1658         const char * const *profile_names;
1659         const char * const *level_names;
1660         struct v4l2_ctrl *profile_ctrl;
1661         struct v4l2_ctrl *level_ctrl;
1662         const char *codec_name;
1663         u32 profile_cid;
1664         u32 level_cid;
1665         int profile;
1666         int level;
1667
1668         switch (ctx->codec->src_fourcc) {
1669         case V4L2_PIX_FMT_H264:
1670                 codec_name = "H264";
1671                 profile_cid = V4L2_CID_MPEG_VIDEO_H264_PROFILE;
1672                 level_cid = V4L2_CID_MPEG_VIDEO_H264_LEVEL;
1673                 profile_ctrl = ctx->h264_profile_ctrl;
1674                 level_ctrl = ctx->h264_level_ctrl;
1675                 profile = coda_h264_profile(profile_idc);
1676                 level = coda_h264_level(level_idc);
1677                 break;
1678         case V4L2_PIX_FMT_MPEG2:
1679                 codec_name = "MPEG-2";
1680                 profile_cid = V4L2_CID_MPEG_VIDEO_MPEG2_PROFILE;
1681                 level_cid = V4L2_CID_MPEG_VIDEO_MPEG2_LEVEL;
1682                 profile_ctrl = ctx->mpeg2_profile_ctrl;
1683                 level_ctrl = ctx->mpeg2_level_ctrl;
1684                 profile = coda_mpeg2_profile(profile_idc);
1685                 level = coda_mpeg2_level(level_idc);
1686                 break;
1687         case V4L2_PIX_FMT_MPEG4:
1688                 codec_name = "MPEG-4";
1689                 profile_cid = V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE;
1690                 level_cid = V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL;
1691                 profile_ctrl = ctx->mpeg4_profile_ctrl;
1692                 level_ctrl = ctx->mpeg4_level_ctrl;
1693                 profile = coda_mpeg4_profile(profile_idc);
1694                 level = coda_mpeg4_level(level_idc);
1695                 break;
1696         default:
1697                 return;
1698         }
1699
1700         profile_names = v4l2_ctrl_get_menu(profile_cid);
1701         level_names = v4l2_ctrl_get_menu(level_cid);
1702
1703         if (profile < 0) {
1704                 v4l2_warn(&ctx->dev->v4l2_dev, "Invalid %s profile: %u\n",
1705                           codec_name, profile_idc);
1706         } else {
1707                 coda_dbg(1, ctx, "Parsed %s profile: %s\n", codec_name,
1708                          profile_names[profile]);
1709                 coda_update_menu_ctrl(profile_ctrl, profile);
1710         }
1711
1712         if (level < 0) {
1713                 v4l2_warn(&ctx->dev->v4l2_dev, "Invalid %s level: %u\n",
1714                           codec_name, level_idc);
1715         } else {
1716                 coda_dbg(1, ctx, "Parsed %s level: %s\n", codec_name,
1717                          level_names[level]);
1718                 coda_update_menu_ctrl(level_ctrl, level);
1719         }
1720 }
1721
1722 static void coda_queue_source_change_event(struct coda_ctx *ctx)
1723 {
1724         static const struct v4l2_event source_change_event = {
1725                 .type = V4L2_EVENT_SOURCE_CHANGE,
1726                 .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION,
1727         };
1728
1729         v4l2_event_queue_fh(&ctx->fh, &source_change_event);
1730 }
1731
1732 static void coda_buf_queue(struct vb2_buffer *vb)
1733 {
1734         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1735         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
1736         struct vb2_queue *vq = vb->vb2_queue;
1737         struct coda_q_data *q_data;
1738
1739         q_data = get_q_data(ctx, vb->vb2_queue->type);
1740
1741         /*
1742          * In the decoder case, immediately try to copy the buffer into the
1743          * bitstream ringbuffer and mark it as ready to be dequeued.
1744          */
1745         if (ctx->bitstream.size && vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1746                 /*
1747                  * For backwards compatibility, queuing an empty buffer marks
1748                  * the stream end
1749                  */
1750                 if (vb2_get_plane_payload(vb, 0) == 0)
1751                         coda_bit_stream_end_flag(ctx);
1752
1753                 if (q_data->fourcc == V4L2_PIX_FMT_H264) {
1754                         /*
1755                          * Unless already done, try to obtain profile_idc and
1756                          * level_idc from the SPS header. This allows to decide
1757                          * whether to enable reordering during sequence
1758                          * initialization.
1759                          */
1760                         if (!ctx->params.h264_profile_idc) {
1761                                 coda_sps_parse_profile(ctx, vb);
1762                                 coda_update_profile_level_ctrls(ctx,
1763                                                 ctx->params.h264_profile_idc,
1764                                                 ctx->params.h264_level_idc);
1765                         }
1766                 }
1767
1768                 mutex_lock(&ctx->bitstream_mutex);
1769                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1770                 if (vb2_is_streaming(vb->vb2_queue))
1771                         /* This set buf->sequence = ctx->qsequence++ */
1772                         coda_fill_bitstream(ctx, NULL);
1773                 mutex_unlock(&ctx->bitstream_mutex);
1774
1775                 if (!ctx->initialized) {
1776                         /*
1777                          * Run sequence initialization in case the queued
1778                          * buffer contained headers.
1779                          */
1780                         if (vb2_is_streaming(vb->vb2_queue) &&
1781                             ctx->ops->seq_init_work) {
1782                                 queue_work(ctx->dev->workqueue,
1783                                            &ctx->seq_init_work);
1784                                 flush_work(&ctx->seq_init_work);
1785                         }
1786
1787                         if (ctx->initialized)
1788                                 coda_queue_source_change_event(ctx);
1789                 }
1790         } else {
1791                 if (ctx->inst_type == CODA_INST_ENCODER &&
1792                     vq->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1793                         vbuf->sequence = ctx->qsequence++;
1794                 v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
1795         }
1796 }
1797
1798 int coda_alloc_aux_buf(struct coda_dev *dev, struct coda_aux_buf *buf,
1799                        size_t size, const char *name, struct dentry *parent)
1800 {
1801         buf->vaddr = dma_alloc_coherent(dev->dev, size, &buf->paddr,
1802                                         GFP_KERNEL);
1803         if (!buf->vaddr) {
1804                 v4l2_err(&dev->v4l2_dev,
1805                          "Failed to allocate %s buffer of size %zu\n",
1806                          name, size);
1807                 return -ENOMEM;
1808         }
1809
1810         buf->size = size;
1811
1812         if (name && parent) {
1813                 buf->blob.data = buf->vaddr;
1814                 buf->blob.size = size;
1815                 buf->dentry = debugfs_create_blob(name, 0644, parent,
1816                                                   &buf->blob);
1817                 if (!buf->dentry)
1818                         dev_warn(dev->dev,
1819                                  "failed to create debugfs entry %s\n", name);
1820         }
1821
1822         return 0;
1823 }
1824
1825 void coda_free_aux_buf(struct coda_dev *dev,
1826                        struct coda_aux_buf *buf)
1827 {
1828         if (buf->vaddr) {
1829                 dma_free_coherent(dev->dev, buf->size, buf->vaddr, buf->paddr);
1830                 buf->vaddr = NULL;
1831                 buf->size = 0;
1832                 debugfs_remove(buf->dentry);
1833                 buf->dentry = NULL;
1834         }
1835 }
1836
1837 static int coda_start_streaming(struct vb2_queue *q, unsigned int count)
1838 {
1839         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1840         struct v4l2_device *v4l2_dev = &ctx->dev->v4l2_dev;
1841         struct coda_q_data *q_data_src, *q_data_dst;
1842         struct v4l2_m2m_buffer *m2m_buf, *tmp;
1843         struct vb2_v4l2_buffer *buf;
1844         struct list_head list;
1845         int ret = 0;
1846
1847         if (count < 1)
1848                 return -EINVAL;
1849
1850         coda_dbg(1, ctx, "start streaming %s\n", v4l2_type_names[q->type]);
1851
1852         INIT_LIST_HEAD(&list);
1853
1854         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
1855         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1856                 if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit) {
1857                         /* copy the buffers that were queued before streamon */
1858                         mutex_lock(&ctx->bitstream_mutex);
1859                         coda_fill_bitstream(ctx, &list);
1860                         mutex_unlock(&ctx->bitstream_mutex);
1861
1862                         if (ctx->dev->devtype->product != CODA_960 &&
1863                             coda_get_bitstream_payload(ctx) < 512) {
1864                                 v4l2_err(v4l2_dev, "start payload < 512\n");
1865                                 ret = -EINVAL;
1866                                 goto err;
1867                         }
1868
1869                         if (!ctx->initialized) {
1870                                 /* Run sequence initialization */
1871                                 if (ctx->ops->seq_init_work) {
1872                                         queue_work(ctx->dev->workqueue,
1873                                                    &ctx->seq_init_work);
1874                                         flush_work(&ctx->seq_init_work);
1875                                 }
1876                         }
1877                 }
1878
1879                 ctx->streamon_out = 1;
1880         } else {
1881                 ctx->streamon_cap = 1;
1882         }
1883
1884         /* Don't start the coda unless both queues are on */
1885         if (!(ctx->streamon_out && ctx->streamon_cap))
1886                 goto out;
1887
1888         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1889         if ((q_data_src->rect.width != q_data_dst->width &&
1890              round_up(q_data_src->rect.width, 16) != q_data_dst->width) ||
1891             (q_data_src->rect.height != q_data_dst->height &&
1892              round_up(q_data_src->rect.height, 16) != q_data_dst->height)) {
1893                 v4l2_err(v4l2_dev, "can't convert %dx%d to %dx%d\n",
1894                          q_data_src->rect.width, q_data_src->rect.height,
1895                          q_data_dst->width, q_data_dst->height);
1896                 ret = -EINVAL;
1897                 goto err;
1898         }
1899
1900         /* Allow BIT decoder device_run with no new buffers queued */
1901         if (ctx->inst_type == CODA_INST_DECODER && ctx->use_bit)
1902                 v4l2_m2m_set_src_buffered(ctx->fh.m2m_ctx, true);
1903
1904         ctx->gopcounter = ctx->params.gop_size - 1;
1905
1906         if (q_data_dst->fourcc == V4L2_PIX_FMT_JPEG)
1907                 ctx->params.gop_size = 1;
1908         ctx->gopcounter = ctx->params.gop_size - 1;
1909
1910         ret = ctx->ops->start_streaming(ctx);
1911         if (ctx->inst_type == CODA_INST_DECODER) {
1912                 if (ret == -EAGAIN)
1913                         goto out;
1914         }
1915         if (ret < 0)
1916                 goto err;
1917
1918 out:
1919         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1920                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1921                         list_del(&m2m_buf->list);
1922                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_DONE);
1923                 }
1924         }
1925         return 0;
1926
1927 err:
1928         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1929                 list_for_each_entry_safe(m2m_buf, tmp, &list, list) {
1930                         list_del(&m2m_buf->list);
1931                         v4l2_m2m_buf_done(&m2m_buf->vb, VB2_BUF_STATE_QUEUED);
1932                 }
1933                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1934                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1935         } else {
1936                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1937                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_QUEUED);
1938         }
1939         return ret;
1940 }
1941
1942 static void coda_stop_streaming(struct vb2_queue *q)
1943 {
1944         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1945         struct coda_dev *dev = ctx->dev;
1946         struct vb2_v4l2_buffer *buf;
1947         bool stop;
1948
1949         stop = ctx->streamon_out && ctx->streamon_cap;
1950
1951         coda_dbg(1, ctx, "stop streaming %s\n", v4l2_type_names[q->type]);
1952
1953         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1954                 ctx->streamon_out = 0;
1955
1956                 coda_bit_stream_end_flag(ctx);
1957
1958                 ctx->qsequence = 0;
1959
1960                 while ((buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx)))
1961                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1962         } else {
1963                 ctx->streamon_cap = 0;
1964
1965                 ctx->osequence = 0;
1966                 ctx->sequence_offset = 0;
1967
1968                 while ((buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx)))
1969                         v4l2_m2m_buf_done(buf, VB2_BUF_STATE_ERROR);
1970         }
1971
1972         if (stop) {
1973                 struct coda_buffer_meta *meta;
1974
1975                 if (ctx->ops->seq_end_work) {
1976                         queue_work(dev->workqueue, &ctx->seq_end_work);
1977                         flush_work(&ctx->seq_end_work);
1978                 }
1979                 spin_lock(&ctx->buffer_meta_lock);
1980                 while (!list_empty(&ctx->buffer_meta_list)) {
1981                         meta = list_first_entry(&ctx->buffer_meta_list,
1982                                                 struct coda_buffer_meta, list);
1983                         list_del(&meta->list);
1984                         kfree(meta);
1985                 }
1986                 ctx->num_metas = 0;
1987                 spin_unlock(&ctx->buffer_meta_lock);
1988                 kfifo_init(&ctx->bitstream_fifo,
1989                         ctx->bitstream.vaddr, ctx->bitstream.size);
1990                 ctx->runcounter = 0;
1991                 ctx->aborting = 0;
1992                 ctx->hold = false;
1993         }
1994
1995         if (!ctx->streamon_out && !ctx->streamon_cap)
1996                 ctx->bit_stream_param &= ~CODA_BIT_STREAM_END_FLAG;
1997 }
1998
1999 static const struct vb2_ops coda_qops = {
2000         .queue_setup            = coda_queue_setup,
2001         .buf_prepare            = coda_buf_prepare,
2002         .buf_queue              = coda_buf_queue,
2003         .start_streaming        = coda_start_streaming,
2004         .stop_streaming         = coda_stop_streaming,
2005         .wait_prepare           = vb2_ops_wait_prepare,
2006         .wait_finish            = vb2_ops_wait_finish,
2007 };
2008
2009 static int coda_s_ctrl(struct v4l2_ctrl *ctrl)
2010 {
2011         const char * const *val_names = v4l2_ctrl_get_menu(ctrl->id);
2012         struct coda_ctx *ctx =
2013                         container_of(ctrl->handler, struct coda_ctx, ctrls);
2014
2015         if (val_names)
2016                 coda_dbg(2, ctx, "s_ctrl: id = 0x%x, name = \"%s\", val = %d (\"%s\")\n",
2017                          ctrl->id, ctrl->name, ctrl->val, val_names[ctrl->val]);
2018         else
2019                 coda_dbg(2, ctx, "s_ctrl: id = 0x%x, name = \"%s\", val = %d\n",
2020                          ctrl->id, ctrl->name, ctrl->val);
2021
2022         switch (ctrl->id) {
2023         case V4L2_CID_HFLIP:
2024                 if (ctrl->val)
2025                         ctx->params.rot_mode |= CODA_MIR_HOR;
2026                 else
2027                         ctx->params.rot_mode &= ~CODA_MIR_HOR;
2028                 break;
2029         case V4L2_CID_VFLIP:
2030                 if (ctrl->val)
2031                         ctx->params.rot_mode |= CODA_MIR_VER;
2032                 else
2033                         ctx->params.rot_mode &= ~CODA_MIR_VER;
2034                 break;
2035         case V4L2_CID_MPEG_VIDEO_BITRATE:
2036                 ctx->params.bitrate = ctrl->val / 1000;
2037                 ctx->params.bitrate_changed = true;
2038                 break;
2039         case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
2040                 ctx->params.gop_size = ctrl->val;
2041                 break;
2042         case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
2043                 ctx->params.h264_intra_qp = ctrl->val;
2044                 ctx->params.h264_intra_qp_changed = true;
2045                 break;
2046         case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
2047                 ctx->params.h264_inter_qp = ctrl->val;
2048                 break;
2049         case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
2050                 ctx->params.h264_min_qp = ctrl->val;
2051                 break;
2052         case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
2053                 ctx->params.h264_max_qp = ctrl->val;
2054                 break;
2055         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA:
2056                 ctx->params.h264_slice_alpha_c0_offset_div2 = ctrl->val;
2057                 break;
2058         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA:
2059                 ctx->params.h264_slice_beta_offset_div2 = ctrl->val;
2060                 break;
2061         case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE:
2062                 ctx->params.h264_disable_deblocking_filter_idc = ctrl->val;
2063                 break;
2064         case V4L2_CID_MPEG_VIDEO_H264_CONSTRAINED_INTRA_PREDICTION:
2065                 ctx->params.h264_constrained_intra_pred_flag = ctrl->val;
2066                 break;
2067         case V4L2_CID_MPEG_VIDEO_H264_CHROMA_QP_INDEX_OFFSET:
2068                 ctx->params.h264_chroma_qp_index_offset = ctrl->val;
2069                 break;
2070         case V4L2_CID_MPEG_VIDEO_H264_PROFILE:
2071                 /* TODO: switch between baseline and constrained baseline */
2072                 if (ctx->inst_type == CODA_INST_ENCODER)
2073                         ctx->params.h264_profile_idc = 66;
2074                 break;
2075         case V4L2_CID_MPEG_VIDEO_H264_LEVEL:
2076                 /* nothing to do, this is set by the encoder */
2077                 break;
2078         case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
2079                 ctx->params.mpeg4_intra_qp = ctrl->val;
2080                 break;
2081         case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
2082                 ctx->params.mpeg4_inter_qp = ctrl->val;
2083                 break;
2084         case V4L2_CID_MPEG_VIDEO_MPEG2_PROFILE:
2085         case V4L2_CID_MPEG_VIDEO_MPEG2_LEVEL:
2086         case V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE:
2087         case V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL:
2088                 /* nothing to do, these are fixed */
2089                 break;
2090         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
2091                 ctx->params.slice_mode = ctrl->val;
2092                 ctx->params.slice_mode_changed = true;
2093                 break;
2094         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
2095                 ctx->params.slice_max_mb = ctrl->val;
2096                 ctx->params.slice_mode_changed = true;
2097                 break;
2098         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
2099                 ctx->params.slice_max_bits = ctrl->val * 8;
2100                 ctx->params.slice_mode_changed = true;
2101                 break;
2102         case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
2103                 break;
2104         case V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB:
2105                 ctx->params.intra_refresh = ctrl->val;
2106                 ctx->params.intra_refresh_changed = true;
2107                 break;
2108         case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME:
2109                 ctx->params.force_ipicture = true;
2110                 break;
2111         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
2112                 coda_set_jpeg_compression_quality(ctx, ctrl->val);
2113                 break;
2114         case V4L2_CID_JPEG_RESTART_INTERVAL:
2115                 ctx->params.jpeg_restart_interval = ctrl->val;
2116                 break;
2117         case V4L2_CID_MPEG_VIDEO_VBV_DELAY:
2118                 ctx->params.vbv_delay = ctrl->val;
2119                 break;
2120         case V4L2_CID_MPEG_VIDEO_VBV_SIZE:
2121                 ctx->params.vbv_size = min(ctrl->val * 8192, 0x7fffffff);
2122                 break;
2123         default:
2124                 coda_dbg(1, ctx, "Invalid control, id=%d, val=%d\n",
2125                          ctrl->id, ctrl->val);
2126                 return -EINVAL;
2127         }
2128
2129         return 0;
2130 }
2131
2132 static const struct v4l2_ctrl_ops coda_ctrl_ops = {
2133         .s_ctrl = coda_s_ctrl,
2134 };
2135
2136 static void coda_encode_ctrls(struct coda_ctx *ctx)
2137 {
2138         int max_gop_size = (ctx->dev->devtype->product == CODA_DX6) ? 60 : 99;
2139
2140         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2141                 V4L2_CID_MPEG_VIDEO_BITRATE, 0, 32767000, 1000, 0);
2142         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2143                 V4L2_CID_MPEG_VIDEO_GOP_SIZE, 0, max_gop_size, 1, 16);
2144         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2145                 V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP, 0, 51, 1, 25);
2146         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2147                 V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP, 0, 51, 1, 25);
2148         if (ctx->dev->devtype->product != CODA_960) {
2149                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2150                         V4L2_CID_MPEG_VIDEO_H264_MIN_QP, 0, 51, 1, 12);
2151         }
2152         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2153                 V4L2_CID_MPEG_VIDEO_H264_MAX_QP, 0, 51, 1, 51);
2154         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2155                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA, -6, 6, 1, 0);
2156         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2157                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA, -6, 6, 1, 0);
2158         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2159                 V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE,
2160                 V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY,
2161                 0x0, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED);
2162         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2163                 V4L2_CID_MPEG_VIDEO_H264_CONSTRAINED_INTRA_PREDICTION, 0, 1, 1,
2164                 0);
2165         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2166                 V4L2_CID_MPEG_VIDEO_H264_CHROMA_QP_INDEX_OFFSET, -12, 12, 1, 0);
2167         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2168                 V4L2_CID_MPEG_VIDEO_H264_PROFILE,
2169                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE, 0x0,
2170                 V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE);
2171         if (ctx->dev->devtype->product == CODA_HX4 ||
2172             ctx->dev->devtype->product == CODA_7541) {
2173                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2174                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
2175                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1,
2176                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
2177                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
2178                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1)),
2179                         V4L2_MPEG_VIDEO_H264_LEVEL_3_1);
2180         }
2181         if (ctx->dev->devtype->product == CODA_960) {
2182                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2183                         V4L2_CID_MPEG_VIDEO_H264_LEVEL,
2184                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0,
2185                         ~((1 << V4L2_MPEG_VIDEO_H264_LEVEL_2_0) |
2186                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_0) |
2187                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_1) |
2188                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_3_2) |
2189                           (1 << V4L2_MPEG_VIDEO_H264_LEVEL_4_0)),
2190                         V4L2_MPEG_VIDEO_H264_LEVEL_4_0);
2191         }
2192         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2193                 V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP, 1, 31, 1, 2);
2194         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2195                 V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP, 1, 31, 1, 2);
2196         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2197                 V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE,
2198                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE, 0x0,
2199                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE);
2200         if (ctx->dev->devtype->product == CODA_HX4 ||
2201             ctx->dev->devtype->product == CODA_7541 ||
2202             ctx->dev->devtype->product == CODA_960) {
2203                 v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2204                         V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL,
2205                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5,
2206                         ~(1 << V4L2_MPEG_VIDEO_MPEG4_LEVEL_5),
2207                         V4L2_MPEG_VIDEO_MPEG4_LEVEL_5);
2208         }
2209         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2210                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE,
2211                 V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_MAX_BYTES, 0x0,
2212                 V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE);
2213         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2214                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB, 1, 0x3fffffff, 1, 1);
2215         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2216                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES, 1, 0x3fffffff, 1,
2217                 500);
2218         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
2219                 V4L2_CID_MPEG_VIDEO_HEADER_MODE,
2220                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME,
2221                 (1 << V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE),
2222                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME);
2223         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2224                 V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB, 0,
2225                 1920 * 1088 / 256, 1, 0);
2226         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2227                 V4L2_CID_MPEG_VIDEO_VBV_DELAY, 0, 0x7fff, 1, 0);
2228         /*
2229          * The maximum VBV size value is 0x7fffffff bits,
2230          * one bit less than 262144 KiB
2231          */
2232         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2233                 V4L2_CID_MPEG_VIDEO_VBV_SIZE, 0, 262144, 1, 0);
2234 }
2235
2236 static void coda_jpeg_encode_ctrls(struct coda_ctx *ctx)
2237 {
2238         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2239                 V4L2_CID_JPEG_COMPRESSION_QUALITY, 5, 100, 1, 50);
2240         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2241                 V4L2_CID_JPEG_RESTART_INTERVAL, 0, 100, 1, 0);
2242 }
2243
2244 static void coda_decode_ctrls(struct coda_ctx *ctx)
2245 {
2246         u8 max;
2247
2248         ctx->h264_profile_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2249                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_H264_PROFILE,
2250                 V4L2_MPEG_VIDEO_H264_PROFILE_HIGH,
2251                 ~((1 << V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE) |
2252                   (1 << V4L2_MPEG_VIDEO_H264_PROFILE_MAIN) |
2253                   (1 << V4L2_MPEG_VIDEO_H264_PROFILE_HIGH)),
2254                 V4L2_MPEG_VIDEO_H264_PROFILE_HIGH);
2255         if (ctx->h264_profile_ctrl)
2256                 ctx->h264_profile_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2257
2258         if (ctx->dev->devtype->product == CODA_HX4 ||
2259             ctx->dev->devtype->product == CODA_7541)
2260                 max = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
2261         else if (ctx->dev->devtype->product == CODA_960)
2262                 max = V4L2_MPEG_VIDEO_H264_LEVEL_4_1;
2263         else
2264                 return;
2265         ctx->h264_level_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2266                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_H264_LEVEL, max, 0, max);
2267         if (ctx->h264_level_ctrl)
2268                 ctx->h264_level_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2269
2270         ctx->mpeg2_profile_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2271                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG2_PROFILE,
2272                 V4L2_MPEG_VIDEO_MPEG2_PROFILE_HIGH, 0,
2273                 V4L2_MPEG_VIDEO_MPEG2_PROFILE_HIGH);
2274         if (ctx->mpeg2_profile_ctrl)
2275                 ctx->mpeg2_profile_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2276
2277         ctx->mpeg2_level_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2278                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG2_LEVEL,
2279                 V4L2_MPEG_VIDEO_MPEG2_LEVEL_HIGH, 0,
2280                 V4L2_MPEG_VIDEO_MPEG2_LEVEL_HIGH);
2281         if (ctx->mpeg2_level_ctrl)
2282                 ctx->mpeg2_level_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2283
2284         ctx->mpeg4_profile_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2285                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE,
2286                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY, 0,
2287                 V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY);
2288         if (ctx->mpeg4_profile_ctrl)
2289                 ctx->mpeg4_profile_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2290
2291         ctx->mpeg4_level_ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrls,
2292                 &coda_ctrl_ops, V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL,
2293                 V4L2_MPEG_VIDEO_MPEG4_LEVEL_5, 0,
2294                 V4L2_MPEG_VIDEO_MPEG4_LEVEL_5);
2295         if (ctx->mpeg4_level_ctrl)
2296                 ctx->mpeg4_level_ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;
2297 }
2298
2299 static int coda_ctrls_setup(struct coda_ctx *ctx)
2300 {
2301         v4l2_ctrl_handler_init(&ctx->ctrls, 2);
2302
2303         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2304                 V4L2_CID_HFLIP, 0, 1, 1, 0);
2305         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2306                 V4L2_CID_VFLIP, 0, 1, 1, 0);
2307         if (ctx->inst_type == CODA_INST_ENCODER) {
2308                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2309                                   V4L2_CID_MIN_BUFFERS_FOR_OUTPUT,
2310                                   1, 1, 1, 1);
2311                 if (ctx->cvd->dst_formats[0] == V4L2_PIX_FMT_JPEG)
2312                         coda_jpeg_encode_ctrls(ctx);
2313                 else
2314                         coda_encode_ctrls(ctx);
2315         } else {
2316                 v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
2317                                   V4L2_CID_MIN_BUFFERS_FOR_CAPTURE,
2318                                   1, 1, 1, 1);
2319                 if (ctx->cvd->src_formats[0] == V4L2_PIX_FMT_H264)
2320                         coda_decode_ctrls(ctx);
2321         }
2322
2323         if (ctx->ctrls.error) {
2324                 v4l2_err(&ctx->dev->v4l2_dev,
2325                         "control initialization error (%d)",
2326                         ctx->ctrls.error);
2327                 return -EINVAL;
2328         }
2329
2330         return v4l2_ctrl_handler_setup(&ctx->ctrls);
2331 }
2332
2333 static int coda_queue_init(struct coda_ctx *ctx, struct vb2_queue *vq)
2334 {
2335         vq->drv_priv = ctx;
2336         vq->ops = &coda_qops;
2337         vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
2338         vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
2339         vq->lock = &ctx->dev->dev_mutex;
2340         /* One way to indicate end-of-stream for coda is to set the
2341          * bytesused == 0. However by default videobuf2 handles bytesused
2342          * equal to 0 as a special case and changes its value to the size
2343          * of the buffer. Set the allow_zero_bytesused flag, so
2344          * that videobuf2 will keep the value of bytesused intact.
2345          */
2346         vq->allow_zero_bytesused = 1;
2347         /*
2348          * We might be fine with no buffers on some of the queues, but that
2349          * would need to be reflected in job_ready(). Currently we expect all
2350          * queues to have at least one buffer queued.
2351          */
2352         vq->min_buffers_needed = 1;
2353         vq->dev = ctx->dev->dev;
2354
2355         return vb2_queue_init(vq);
2356 }
2357
2358 int coda_encoder_queue_init(void *priv, struct vb2_queue *src_vq,
2359                             struct vb2_queue *dst_vq)
2360 {
2361         int ret;
2362
2363         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
2364         src_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2365         src_vq->mem_ops = &vb2_dma_contig_memops;
2366
2367         ret = coda_queue_init(priv, src_vq);
2368         if (ret)
2369                 return ret;
2370
2371         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2372         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2373         dst_vq->mem_ops = &vb2_dma_contig_memops;
2374
2375         return coda_queue_init(priv, dst_vq);
2376 }
2377
2378 int coda_decoder_queue_init(void *priv, struct vb2_queue *src_vq,
2379                             struct vb2_queue *dst_vq)
2380 {
2381         int ret;
2382
2383         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
2384         src_vq->io_modes = VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
2385         src_vq->mem_ops = &vb2_vmalloc_memops;
2386
2387         ret = coda_queue_init(priv, src_vq);
2388         if (ret)
2389                 return ret;
2390
2391         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2392         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
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         video_set_drvdata(vfd, dev);
2703
2704         /* Not applicable, use the selection API instead */
2705         v4l2_disable_ioctl(vfd, VIDIOC_CROPCAP);
2706         v4l2_disable_ioctl(vfd, VIDIOC_G_CROP);
2707         v4l2_disable_ioctl(vfd, VIDIOC_S_CROP);
2708
2709         ret = video_register_device(vfd, VFL_TYPE_GRABBER, 0);
2710         if (!ret)
2711                 v4l2_info(&dev->v4l2_dev, "%s registered as %s\n",
2712                           type == CODA_INST_ENCODER ? "encoder" : "decoder",
2713                           video_device_node_name(vfd));
2714         return ret;
2715 }
2716
2717 static void coda_copy_firmware(struct coda_dev *dev, const u8 * const buf,
2718                                size_t size)
2719 {
2720         u32 *src = (u32 *)buf;
2721
2722         /* Check if the firmware has a 16-byte Freescale header, skip it */
2723         if (buf[0] == 'M' && buf[1] == 'X')
2724                 src += 4;
2725         /*
2726          * Check whether the firmware is in native order or pre-reordered for
2727          * memory access. The first instruction opcode always is 0xe40e.
2728          */
2729         if (__le16_to_cpup((__le16 *)src) == 0xe40e) {
2730                 u32 *dst = dev->codebuf.vaddr;
2731                 int i;
2732
2733                 /* Firmware in native order, reorder while copying */
2734                 if (dev->devtype->product == CODA_DX6) {
2735                         for (i = 0; i < (size - 16) / 4; i++)
2736                                 dst[i] = (src[i] << 16) | (src[i] >> 16);
2737                 } else {
2738                         for (i = 0; i < (size - 16) / 4; i += 2) {
2739                                 dst[i] = (src[i + 1] << 16) | (src[i + 1] >> 16);
2740                                 dst[i + 1] = (src[i] << 16) | (src[i] >> 16);
2741                         }
2742                 }
2743         } else {
2744                 /* Copy the already reordered firmware image */
2745                 memcpy(dev->codebuf.vaddr, src, size);
2746         }
2747 }
2748
2749 static void coda_fw_callback(const struct firmware *fw, void *context);
2750
2751 static int coda_firmware_request(struct coda_dev *dev)
2752 {
2753         char *fw;
2754
2755         if (dev->firmware >= ARRAY_SIZE(dev->devtype->firmware))
2756                 return -EINVAL;
2757
2758         fw = dev->devtype->firmware[dev->firmware];
2759
2760         dev_dbg(dev->dev, "requesting firmware '%s' for %s\n", fw,
2761                 coda_product_name(dev->devtype->product));
2762
2763         return reject_firmware_nowait(THIS_MODULE, true, fw, dev->dev,
2764                                        GFP_KERNEL, dev, coda_fw_callback);
2765 }
2766
2767 static void coda_fw_callback(const struct firmware *fw, void *context)
2768 {
2769         struct coda_dev *dev = context;
2770         int i, ret;
2771
2772         if (!fw) {
2773                 dev->firmware++;
2774                 ret = coda_firmware_request(dev);
2775                 if (ret < 0) {
2776                         v4l2_err(&dev->v4l2_dev, "firmware request failed\n");
2777                         goto put_pm;
2778                 }
2779                 return;
2780         }
2781         if (dev->firmware > 0) {
2782                 /*
2783                  * Since we can't suppress warnings for failed asynchronous
2784                  * firmware requests, report that the fallback firmware was
2785                  * found.
2786                  */
2787                 dev_info(dev->dev, "Using fallback firmware %s\n",
2788                          dev->devtype->firmware[dev->firmware]);
2789         }
2790
2791         /* allocate auxiliary per-device code buffer for the BIT processor */
2792         ret = coda_alloc_aux_buf(dev, &dev->codebuf, fw->size, "codebuf",
2793                                  dev->debugfs_root);
2794         if (ret < 0)
2795                 goto put_pm;
2796
2797         coda_copy_firmware(dev, fw->data, fw->size);
2798         release_firmware(fw);
2799
2800         ret = coda_hw_init(dev);
2801         if (ret < 0) {
2802                 v4l2_err(&dev->v4l2_dev, "HW initialization failed\n");
2803                 goto put_pm;
2804         }
2805
2806         ret = coda_check_firmware(dev);
2807         if (ret < 0)
2808                 goto put_pm;
2809
2810         dev->m2m_dev = v4l2_m2m_init(&coda_m2m_ops);
2811         if (IS_ERR(dev->m2m_dev)) {
2812                 v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n");
2813                 goto put_pm;
2814         }
2815
2816         for (i = 0; i < dev->devtype->num_vdevs; i++) {
2817                 ret = coda_register_device(dev, i);
2818                 if (ret) {
2819                         v4l2_err(&dev->v4l2_dev,
2820                                  "Failed to register %s video device: %d\n",
2821                                  dev->devtype->vdevs[i]->name, ret);
2822                         goto rel_vfd;
2823                 }
2824         }
2825
2826         pm_runtime_put_sync(dev->dev);
2827         return;
2828
2829 rel_vfd:
2830         while (--i >= 0)
2831                 video_unregister_device(&dev->vfd[i]);
2832         v4l2_m2m_release(dev->m2m_dev);
2833 put_pm:
2834         pm_runtime_put_sync(dev->dev);
2835 }
2836
2837 enum coda_platform {
2838         CODA_IMX27,
2839         CODA_IMX51,
2840         CODA_IMX53,
2841         CODA_IMX6Q,
2842         CODA_IMX6DL,
2843 };
2844
2845 static const struct coda_devtype coda_devdata[] = {
2846         [CODA_IMX27] = {
2847                 .firmware     = {
2848                         "/*(DEBLOBBED)*/",
2849                         "/*(DEBLOBBED)*/",
2850                         "/*(DEBLOBBED)*/"
2851                 },
2852                 .product      = CODA_DX6,
2853                 .codecs       = codadx6_codecs,
2854                 .num_codecs   = ARRAY_SIZE(codadx6_codecs),
2855                 .vdevs        = codadx6_video_devices,
2856                 .num_vdevs    = ARRAY_SIZE(codadx6_video_devices),
2857                 .workbuf_size = 288 * 1024 + FMO_SLICE_SAVE_BUF_SIZE * 8 * 1024,
2858                 .iram_size    = 0xb000,
2859         },
2860         [CODA_IMX51] = {
2861                 /*(DEBLOBBED)*/{
2862                         "/*(DEBLOBBED)*/",
2863                         "/*(DEBLOBBED)*/",
2864                         "/*(DEBLOBBED)*/"
2865                 },
2866                 .product      = CODA_HX4,
2867                 .codecs       = codahx4_codecs,
2868                 .num_codecs   = ARRAY_SIZE(codahx4_codecs),
2869                 .vdevs        = codahx4_video_devices,
2870                 .num_vdevs    = ARRAY_SIZE(codahx4_video_devices),
2871                 .workbuf_size = 128 * 1024,
2872                 .tempbuf_size = 304 * 1024,
2873                 .iram_size    = 0x14000,
2874         },
2875         [CODA_IMX53] = {
2876                 .firmware     = {
2877                         "/*(DEBLOBBED)*/",
2878                         "/*(DEBLOBBED)*/",
2879                         "/*(DEBLOBBED)*/"
2880                 },
2881                 .product      = CODA_7541,
2882                 .codecs       = coda7_codecs,
2883                 .num_codecs   = ARRAY_SIZE(coda7_codecs),
2884                 .vdevs        = coda7_video_devices,
2885                 .num_vdevs    = ARRAY_SIZE(coda7_video_devices),
2886                 .workbuf_size = 128 * 1024,
2887                 .tempbuf_size = 304 * 1024,
2888                 .iram_size    = 0x14000,
2889         },
2890         [CODA_IMX6Q] = {
2891                 .firmware     = {
2892                         "/*(DEBLOBBED)*/",
2893                         "/*(DEBLOBBED)*/",
2894                         "/*(DEBLOBBED)*/"
2895                 },
2896                 .product      = CODA_960,
2897                 .codecs       = coda9_codecs,
2898                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2899                 .vdevs        = coda9_video_devices,
2900                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2901                 .workbuf_size = 80 * 1024,
2902                 .tempbuf_size = 204 * 1024,
2903                 .iram_size    = 0x21000,
2904         },
2905         [CODA_IMX6DL] = {
2906                 .firmware     = {
2907                         "/*(DEBLOBBED)*/",
2908                         "/*(DEBLOBBED)*/",
2909                         "/*(DEBLOBBED)*/"
2910                 },
2911                 .product      = CODA_960,
2912                 .codecs       = coda9_codecs,
2913                 .num_codecs   = ARRAY_SIZE(coda9_codecs),
2914                 .vdevs        = coda9_video_devices,
2915                 .num_vdevs    = ARRAY_SIZE(coda9_video_devices),
2916                 .workbuf_size = 80 * 1024,
2917                 .tempbuf_size = 204 * 1024,
2918                 .iram_size    = 0x1f000, /* leave 4k for suspend code */
2919         },
2920 };
2921
2922 static const struct platform_device_id coda_platform_ids[] = {
2923         { .name = "coda-imx27", .driver_data = CODA_IMX27 },
2924         { /* sentinel */ }
2925 };
2926 MODULE_DEVICE_TABLE(platform, coda_platform_ids);
2927
2928 #ifdef CONFIG_OF
2929 static const struct of_device_id coda_dt_ids[] = {
2930         { .compatible = "fsl,imx27-vpu", .data = &coda_devdata[CODA_IMX27] },
2931         { .compatible = "fsl,imx51-vpu", .data = &coda_devdata[CODA_IMX51] },
2932         { .compatible = "fsl,imx53-vpu", .data = &coda_devdata[CODA_IMX53] },
2933         { .compatible = "fsl,imx6q-vpu", .data = &coda_devdata[CODA_IMX6Q] },
2934         { .compatible = "fsl,imx6dl-vpu", .data = &coda_devdata[CODA_IMX6DL] },
2935         { /* sentinel */ }
2936 };
2937 MODULE_DEVICE_TABLE(of, coda_dt_ids);
2938 #endif
2939
2940 static int coda_probe(struct platform_device *pdev)
2941 {
2942         const struct of_device_id *of_id =
2943                         of_match_device(of_match_ptr(coda_dt_ids), &pdev->dev);
2944         const struct platform_device_id *pdev_id;
2945         struct coda_platform_data *pdata = pdev->dev.platform_data;
2946         struct device_node *np = pdev->dev.of_node;
2947         struct gen_pool *pool;
2948         struct coda_dev *dev;
2949         int ret, irq;
2950
2951         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
2952         if (!dev)
2953                 return -ENOMEM;
2954
2955         pdev_id = of_id ? of_id->data : platform_get_device_id(pdev);
2956
2957         if (of_id)
2958                 dev->devtype = of_id->data;
2959         else if (pdev_id)
2960                 dev->devtype = &coda_devdata[pdev_id->driver_data];
2961         else
2962                 return -EINVAL;
2963
2964         spin_lock_init(&dev->irqlock);
2965
2966         dev->dev = &pdev->dev;
2967         dev->clk_per = devm_clk_get(&pdev->dev, "per");
2968         if (IS_ERR(dev->clk_per)) {
2969                 dev_err(&pdev->dev, "Could not get per clock\n");
2970                 return PTR_ERR(dev->clk_per);
2971         }
2972
2973         dev->clk_ahb = devm_clk_get(&pdev->dev, "ahb");
2974         if (IS_ERR(dev->clk_ahb)) {
2975                 dev_err(&pdev->dev, "Could not get ahb clock\n");
2976                 return PTR_ERR(dev->clk_ahb);
2977         }
2978
2979         /* Get  memory for physical registers */
2980         dev->regs_base = devm_platform_ioremap_resource(pdev, 0);
2981         if (IS_ERR(dev->regs_base))
2982                 return PTR_ERR(dev->regs_base);
2983
2984         /* IRQ */
2985         irq = platform_get_irq_byname(pdev, "bit");
2986         if (irq < 0)
2987                 irq = platform_get_irq(pdev, 0);
2988         if (irq < 0) {
2989                 dev_err(&pdev->dev, "failed to get irq resource\n");
2990                 return irq;
2991         }
2992
2993         ret = devm_request_irq(&pdev->dev, irq, coda_irq_handler, 0,
2994                                dev_name(&pdev->dev), dev);
2995         if (ret < 0) {
2996                 dev_err(&pdev->dev, "failed to request irq: %d\n", ret);
2997                 return ret;
2998         }
2999
3000         dev->rstc = devm_reset_control_get_optional_exclusive(&pdev->dev,
3001                                                               NULL);
3002         if (IS_ERR(dev->rstc)) {
3003                 ret = PTR_ERR(dev->rstc);
3004                 dev_err(&pdev->dev, "failed get reset control: %d\n", ret);
3005                 return ret;
3006         }
3007
3008         /* Get IRAM pool from device tree or platform data */
3009         pool = of_gen_pool_get(np, "iram", 0);
3010         if (!pool && pdata)
3011                 pool = gen_pool_get(pdata->iram_dev, NULL);
3012         if (!pool) {
3013                 dev_err(&pdev->dev, "iram pool not available\n");
3014                 return -ENOMEM;
3015         }
3016         dev->iram_pool = pool;
3017
3018         /* Get vdoa_data if supported by the platform */
3019         dev->vdoa = coda_get_vdoa_data();
3020         if (PTR_ERR(dev->vdoa) == -EPROBE_DEFER)
3021                 return -EPROBE_DEFER;
3022
3023         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
3024         if (ret)
3025                 return ret;
3026
3027         mutex_init(&dev->dev_mutex);
3028         mutex_init(&dev->coda_mutex);
3029         ida_init(&dev->ida);
3030
3031         dev->debugfs_root = debugfs_create_dir("coda", NULL);
3032         if (!dev->debugfs_root)
3033                 dev_warn(&pdev->dev, "failed to create debugfs root\n");
3034
3035         /* allocate auxiliary per-device buffers for the BIT processor */
3036         if (dev->devtype->product == CODA_DX6) {
3037                 ret = coda_alloc_aux_buf(dev, &dev->workbuf,
3038                                          dev->devtype->workbuf_size, "workbuf",
3039                                          dev->debugfs_root);
3040                 if (ret < 0)
3041                         goto err_v4l2_register;
3042         }
3043
3044         if (dev->devtype->tempbuf_size) {
3045                 ret = coda_alloc_aux_buf(dev, &dev->tempbuf,
3046                                          dev->devtype->tempbuf_size, "tempbuf",
3047                                          dev->debugfs_root);
3048                 if (ret < 0)
3049                         goto err_v4l2_register;
3050         }
3051
3052         dev->iram.size = dev->devtype->iram_size;
3053         dev->iram.vaddr = gen_pool_dma_alloc(dev->iram_pool, dev->iram.size,
3054                                              &dev->iram.paddr);
3055         if (!dev->iram.vaddr) {
3056                 dev_warn(&pdev->dev, "unable to alloc iram\n");
3057         } else {
3058                 memset(dev->iram.vaddr, 0, dev->iram.size);
3059                 dev->iram.blob.data = dev->iram.vaddr;
3060                 dev->iram.blob.size = dev->iram.size;
3061                 dev->iram.dentry = debugfs_create_blob("iram", 0644,
3062                                                        dev->debugfs_root,
3063                                                        &dev->iram.blob);
3064         }
3065
3066         dev->workqueue = alloc_workqueue("coda", WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
3067         if (!dev->workqueue) {
3068                 dev_err(&pdev->dev, "unable to alloc workqueue\n");
3069                 ret = -ENOMEM;
3070                 goto err_v4l2_register;
3071         }
3072
3073         platform_set_drvdata(pdev, dev);
3074
3075         /*
3076          * Start activated so we can directly call coda_hw_init in
3077          * coda_fw_callback regardless of whether CONFIG_PM is
3078          * enabled or whether the device is associated with a PM domain.
3079          */
3080         pm_runtime_get_noresume(&pdev->dev);
3081         pm_runtime_set_active(&pdev->dev);
3082         pm_runtime_enable(&pdev->dev);
3083
3084         ret = coda_firmware_request(dev);
3085         if (ret)
3086                 goto err_alloc_workqueue;
3087         return 0;
3088
3089 err_alloc_workqueue:
3090         destroy_workqueue(dev->workqueue);
3091 err_v4l2_register:
3092         v4l2_device_unregister(&dev->v4l2_dev);
3093         return ret;
3094 }
3095
3096 static int coda_remove(struct platform_device *pdev)
3097 {
3098         struct coda_dev *dev = platform_get_drvdata(pdev);
3099         int i;
3100
3101         for (i = 0; i < ARRAY_SIZE(dev->vfd); i++) {
3102                 if (video_get_drvdata(&dev->vfd[i]))
3103                         video_unregister_device(&dev->vfd[i]);
3104         }
3105         if (dev->m2m_dev)
3106                 v4l2_m2m_release(dev->m2m_dev);
3107         pm_runtime_disable(&pdev->dev);
3108         v4l2_device_unregister(&dev->v4l2_dev);
3109         destroy_workqueue(dev->workqueue);
3110         if (dev->iram.vaddr)
3111                 gen_pool_free(dev->iram_pool, (unsigned long)dev->iram.vaddr,
3112                               dev->iram.size);
3113         coda_free_aux_buf(dev, &dev->codebuf);
3114         coda_free_aux_buf(dev, &dev->tempbuf);
3115         coda_free_aux_buf(dev, &dev->workbuf);
3116         debugfs_remove_recursive(dev->debugfs_root);
3117         ida_destroy(&dev->ida);
3118         return 0;
3119 }
3120
3121 #ifdef CONFIG_PM
3122 static int coda_runtime_resume(struct device *dev)
3123 {
3124         struct coda_dev *cdev = dev_get_drvdata(dev);
3125         int ret = 0;
3126
3127         if (dev->pm_domain && cdev->codebuf.vaddr) {
3128                 ret = coda_hw_init(cdev);
3129                 if (ret)
3130                         v4l2_err(&cdev->v4l2_dev, "HW initialization failed\n");
3131         }
3132
3133         return ret;
3134 }
3135 #endif
3136
3137 static const struct dev_pm_ops coda_pm_ops = {
3138         SET_RUNTIME_PM_OPS(NULL, coda_runtime_resume, NULL)
3139 };
3140
3141 static struct platform_driver coda_driver = {
3142         .probe  = coda_probe,
3143         .remove = coda_remove,
3144         .driver = {
3145                 .name   = CODA_NAME,
3146                 .of_match_table = of_match_ptr(coda_dt_ids),
3147                 .pm     = &coda_pm_ops,
3148         },
3149         .id_table = coda_platform_ids,
3150 };
3151
3152 module_platform_driver(coda_driver);
3153
3154 MODULE_LICENSE("GPL");
3155 MODULE_AUTHOR("Javier Martin <javier.martin@vista-silicon.com>");
3156 MODULE_DESCRIPTION("Coda multi-standard codec V4L2 driver");