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