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