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