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