1f3ab53670f880bb71c09adb03e5cd111561fb97
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / media / platform / coda.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/delay.h>
16 #include <linux/firmware.h>
17 #include <linux/genalloc.h>
18 #include <linux/interrupt.h>
19 #include <linux/io.h>
20 #include <linux/irq.h>
21 #include <linux/module.h>
22 #include <linux/of_device.h>
23 #include <linux/platform_device.h>
24 #include <linux/slab.h>
25 #include <linux/videodev2.h>
26 #include <linux/of.h>
27 #include <linux/platform_data/coda.h>
28
29 #include <media/v4l2-ctrls.h>
30 #include <media/v4l2-device.h>
31 #include <media/v4l2-ioctl.h>
32 #include <media/v4l2-mem2mem.h>
33 #include <media/videobuf2-core.h>
34 #include <media/videobuf2-dma-contig.h>
35
36 #include "coda.h"
37
38 #define CODA_NAME               "coda"
39
40 #define CODA_MAX_INSTANCES      4
41
42 #define CODA_FMO_BUF_SIZE       32
43 #define CODADX6_WORK_BUF_SIZE   (288 * 1024 + CODA_FMO_BUF_SIZE * 8 * 1024)
44 #define CODA7_WORK_BUF_SIZE     (512 * 1024 + CODA_FMO_BUF_SIZE * 8 * 1024)
45 #define CODA_PARA_BUF_SIZE      (10 * 1024)
46 #define CODA_ISRAM_SIZE (2048 * 2)
47 #define CODADX6_IRAM_SIZE       0xb000
48 #define CODA7_IRAM_SIZE         0x14000 /* 81920 bytes */
49
50 #define CODA_MAX_FRAMEBUFFERS   2
51
52 #define MAX_W           720
53 #define MAX_H           576
54 #define CODA_MAX_FRAME_SIZE     0x90000
55 #define FMO_SLICE_SAVE_BUF_SIZE         (32)
56 #define CODA_DEFAULT_GAMMA              4096
57
58 #define MIN_W 176
59 #define MIN_H 144
60 #define MAX_W 720
61 #define MAX_H 576
62
63 #define S_ALIGN         1 /* multiple of 2 */
64 #define W_ALIGN         1 /* multiple of 2 */
65 #define H_ALIGN         1 /* multiple of 2 */
66
67 #define fh_to_ctx(__fh) container_of(__fh, struct coda_ctx, fh)
68
69 static int coda_debug;
70 module_param(coda_debug, int, 0644);
71 MODULE_PARM_DESC(coda_debug, "Debug level (0-1)");
72
73 enum {
74         V4L2_M2M_SRC = 0,
75         V4L2_M2M_DST = 1,
76 };
77
78 enum coda_fmt_type {
79         CODA_FMT_ENC,
80         CODA_FMT_RAW,
81 };
82
83 enum coda_inst_type {
84         CODA_INST_ENCODER,
85         CODA_INST_DECODER,
86 };
87
88 enum coda_product {
89         CODA_DX6 = 0xf001,
90         CODA_7541 = 0xf012,
91 };
92
93 struct coda_fmt {
94         char *name;
95         u32 fourcc;
96         enum coda_fmt_type type;
97 };
98
99 struct coda_devtype {
100         char                    *firmware;
101         enum coda_product       product;
102         struct coda_fmt         *formats;
103         unsigned int            num_formats;
104         size_t                  workbuf_size;
105 };
106
107 /* Per-queue, driver-specific private data */
108 struct coda_q_data {
109         unsigned int            width;
110         unsigned int            height;
111         unsigned int            sizeimage;
112         struct coda_fmt *fmt;
113 };
114
115 struct coda_aux_buf {
116         void                    *vaddr;
117         dma_addr_t              paddr;
118         u32                     size;
119 };
120
121 struct coda_dev {
122         struct v4l2_device      v4l2_dev;
123         struct video_device     vfd;
124         struct platform_device  *plat_dev;
125         const struct coda_devtype *devtype;
126
127         void __iomem            *regs_base;
128         struct clk              *clk_per;
129         struct clk              *clk_ahb;
130
131         struct coda_aux_buf     codebuf;
132         struct coda_aux_buf     workbuf;
133         struct gen_pool         *iram_pool;
134         long unsigned int       iram_vaddr;
135         long unsigned int       iram_paddr;
136         unsigned long           iram_size;
137
138         spinlock_t              irqlock;
139         struct mutex            dev_mutex;
140         struct v4l2_m2m_dev     *m2m_dev;
141         struct vb2_alloc_ctx    *alloc_ctx;
142         struct list_head        instances;
143         unsigned long           instance_mask;
144         struct delayed_work     timeout;
145         struct completion       done;
146 };
147
148 struct coda_params {
149         u8                      rot_mode;
150         u8                      h264_intra_qp;
151         u8                      h264_inter_qp;
152         u8                      mpeg4_intra_qp;
153         u8                      mpeg4_inter_qp;
154         u8                      gop_size;
155         int                     codec_mode;
156         enum v4l2_mpeg_video_multi_slice_mode slice_mode;
157         u32                     framerate;
158         u16                     bitrate;
159         u32                     slice_max_bits;
160         u32                     slice_max_mb;
161 };
162
163 struct coda_ctx {
164         struct coda_dev                 *dev;
165         struct list_head                list;
166         int                             aborting;
167         int                             rawstreamon;
168         int                             compstreamon;
169         u32                             isequence;
170         struct coda_q_data              q_data[2];
171         enum coda_inst_type             inst_type;
172         enum v4l2_colorspace            colorspace;
173         struct coda_params              params;
174         struct v4l2_m2m_ctx             *m2m_ctx;
175         struct v4l2_ctrl_handler        ctrls;
176         struct v4l2_fh                  fh;
177         int                             gopcounter;
178         char                            vpu_header[3][64];
179         int                             vpu_header_size[3];
180         struct coda_aux_buf             parabuf;
181         struct coda_aux_buf             internal_frames[CODA_MAX_FRAMEBUFFERS];
182         int                             num_internal_frames;
183         int                             idx;
184 };
185
186 static const u8 coda_filler_nal[14] = { 0x00, 0x00, 0x00, 0x01, 0x0c, 0xff,
187                         0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80 };
188 static const u8 coda_filler_size[8] = { 0, 7, 14, 13, 12, 11, 10, 9 };
189
190 static inline void coda_write(struct coda_dev *dev, u32 data, u32 reg)
191 {
192         v4l2_dbg(1, coda_debug, &dev->v4l2_dev,
193                  "%s: data=0x%x, reg=0x%x\n", __func__, data, reg);
194         writel(data, dev->regs_base + reg);
195 }
196
197 static inline unsigned int coda_read(struct coda_dev *dev, u32 reg)
198 {
199         u32 data;
200         data = readl(dev->regs_base + reg);
201         v4l2_dbg(1, coda_debug, &dev->v4l2_dev,
202                  "%s: data=0x%x, reg=0x%x\n", __func__, data, reg);
203         return data;
204 }
205
206 static inline unsigned long coda_isbusy(struct coda_dev *dev)
207 {
208         return coda_read(dev, CODA_REG_BIT_BUSY);
209 }
210
211 static inline int coda_is_initialized(struct coda_dev *dev)
212 {
213         return (coda_read(dev, CODA_REG_BIT_CUR_PC) != 0);
214 }
215
216 static int coda_wait_timeout(struct coda_dev *dev)
217 {
218         unsigned long timeout = jiffies + msecs_to_jiffies(1000);
219
220         while (coda_isbusy(dev)) {
221                 if (time_after(jiffies, timeout))
222                         return -ETIMEDOUT;
223         }
224         return 0;
225 }
226
227 static void coda_command_async(struct coda_ctx *ctx, int cmd)
228 {
229         struct coda_dev *dev = ctx->dev;
230         coda_write(dev, CODA_REG_BIT_BUSY_FLAG, CODA_REG_BIT_BUSY);
231
232         coda_write(dev, ctx->idx, CODA_REG_BIT_RUN_INDEX);
233         coda_write(dev, ctx->params.codec_mode, CODA_REG_BIT_RUN_COD_STD);
234         coda_write(dev, cmd, CODA_REG_BIT_RUN_COMMAND);
235 }
236
237 static int coda_command_sync(struct coda_ctx *ctx, int cmd)
238 {
239         struct coda_dev *dev = ctx->dev;
240
241         coda_command_async(ctx, cmd);
242         return coda_wait_timeout(dev);
243 }
244
245 static struct coda_q_data *get_q_data(struct coda_ctx *ctx,
246                                          enum v4l2_buf_type type)
247 {
248         switch (type) {
249         case V4L2_BUF_TYPE_VIDEO_OUTPUT:
250                 return &(ctx->q_data[V4L2_M2M_SRC]);
251         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
252                 return &(ctx->q_data[V4L2_M2M_DST]);
253         default:
254                 BUG();
255         }
256         return NULL;
257 }
258
259 /*
260  * Add one array of supported formats for each version of Coda:
261  *  i.MX27 -> codadx6
262  *  i.MX51 -> coda7
263  *  i.MX6  -> coda960
264  */
265 static struct coda_fmt codadx6_formats[] = {
266         {
267                 .name = "YUV 4:2:0 Planar",
268                 .fourcc = V4L2_PIX_FMT_YUV420,
269                 .type = CODA_FMT_RAW,
270         },
271         {
272                 .name = "H264 Encoded Stream",
273                 .fourcc = V4L2_PIX_FMT_H264,
274                 .type = CODA_FMT_ENC,
275         },
276         {
277                 .name = "MPEG4 Encoded Stream",
278                 .fourcc = V4L2_PIX_FMT_MPEG4,
279                 .type = CODA_FMT_ENC,
280         },
281 };
282
283 static struct coda_fmt coda7_formats[] = {
284         {
285                 .name = "YUV 4:2:0 Planar",
286                 .fourcc = V4L2_PIX_FMT_YUV420,
287                 .type = CODA_FMT_RAW,
288         },
289         {
290                 .name = "H264 Encoded Stream",
291                 .fourcc = V4L2_PIX_FMT_H264,
292                 .type = CODA_FMT_ENC,
293         },
294         {
295                 .name = "MPEG4 Encoded Stream",
296                 .fourcc = V4L2_PIX_FMT_MPEG4,
297                 .type = CODA_FMT_ENC,
298         },
299 };
300
301 static struct coda_fmt *find_format(struct coda_dev *dev, struct v4l2_format *f)
302 {
303         struct coda_fmt *formats = dev->devtype->formats;
304         int num_formats = dev->devtype->num_formats;
305         unsigned int k;
306
307         for (k = 0; k < num_formats; k++) {
308                 if (formats[k].fourcc == f->fmt.pix.pixelformat)
309                         break;
310         }
311
312         if (k == num_formats)
313                 return NULL;
314
315         return &formats[k];
316 }
317
318 /*
319  * V4L2 ioctl() operations.
320  */
321 static int vidioc_querycap(struct file *file, void *priv,
322                            struct v4l2_capability *cap)
323 {
324         strlcpy(cap->driver, CODA_NAME, sizeof(cap->driver));
325         strlcpy(cap->card, CODA_NAME, sizeof(cap->card));
326         strlcpy(cap->bus_info, "platform:" CODA_NAME, sizeof(cap->bus_info));
327         /*
328          * This is only a mem-to-mem video device. The capture and output
329          * device capability flags are left only for backward compatibility
330          * and are scheduled for removal.
331          */
332         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT |
333                            V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
334         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
335
336         return 0;
337 }
338
339 static int enum_fmt(void *priv, struct v4l2_fmtdesc *f,
340                         enum coda_fmt_type type)
341 {
342         struct coda_ctx *ctx = fh_to_ctx(priv);
343         struct coda_dev *dev = ctx->dev;
344         struct coda_fmt *formats = dev->devtype->formats;
345         struct coda_fmt *fmt;
346         int num_formats = dev->devtype->num_formats;
347         int i, num = 0;
348
349         for (i = 0; i < num_formats; i++) {
350                 if (formats[i].type == type) {
351                         if (num == f->index)
352                                 break;
353                         ++num;
354                 }
355         }
356
357         if (i < num_formats) {
358                 fmt = &formats[i];
359                 strlcpy(f->description, fmt->name, sizeof(f->description));
360                 f->pixelformat = fmt->fourcc;
361                 return 0;
362         }
363
364         /* Format not found */
365         return -EINVAL;
366 }
367
368 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
369                                    struct v4l2_fmtdesc *f)
370 {
371         return enum_fmt(priv, f, CODA_FMT_ENC);
372 }
373
374 static int vidioc_enum_fmt_vid_out(struct file *file, void *priv,
375                                    struct v4l2_fmtdesc *f)
376 {
377         return enum_fmt(priv, f, CODA_FMT_RAW);
378 }
379
380 static int vidioc_g_fmt(struct file *file, void *priv, struct v4l2_format *f)
381 {
382         struct vb2_queue *vq;
383         struct coda_q_data *q_data;
384         struct coda_ctx *ctx = fh_to_ctx(priv);
385
386         vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
387         if (!vq)
388                 return -EINVAL;
389
390         q_data = get_q_data(ctx, f->type);
391
392         f->fmt.pix.field        = V4L2_FIELD_NONE;
393         f->fmt.pix.pixelformat  = q_data->fmt->fourcc;
394         f->fmt.pix.width        = q_data->width;
395         f->fmt.pix.height       = q_data->height;
396         if (f->fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420)
397                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 2);
398         else /* encoded formats h.264/mpeg4 */
399                 f->fmt.pix.bytesperline = 0;
400
401         f->fmt.pix.sizeimage    = q_data->sizeimage;
402         f->fmt.pix.colorspace   = ctx->colorspace;
403
404         return 0;
405 }
406
407 static int vidioc_try_fmt(struct coda_dev *dev, struct v4l2_format *f)
408 {
409         enum v4l2_field field;
410
411         field = f->fmt.pix.field;
412         if (field == V4L2_FIELD_ANY)
413                 field = V4L2_FIELD_NONE;
414         else if (V4L2_FIELD_NONE != field)
415                 return -EINVAL;
416
417         /* V4L2 specification suggests the driver corrects the format struct
418          * if any of the dimensions is unsupported */
419         f->fmt.pix.field = field;
420
421         if (f->fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) {
422                 v4l_bound_align_image(&f->fmt.pix.width, MIN_W, MAX_W,
423                                       W_ALIGN, &f->fmt.pix.height,
424                                       MIN_H, MAX_H, H_ALIGN, S_ALIGN);
425                 f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 2);
426                 f->fmt.pix.sizeimage = f->fmt.pix.width *
427                                         f->fmt.pix.height * 3 / 2;
428         } else { /*encoded formats h.264/mpeg4 */
429                 f->fmt.pix.bytesperline = 0;
430                 f->fmt.pix.sizeimage = CODA_MAX_FRAME_SIZE;
431         }
432
433         return 0;
434 }
435
436 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
437                                   struct v4l2_format *f)
438 {
439         int ret;
440         struct coda_fmt *fmt;
441         struct coda_ctx *ctx = fh_to_ctx(priv);
442
443         fmt = find_format(ctx->dev, f);
444         /*
445          * Since decoding support is not implemented yet do not allow
446          * CODA_FMT_RAW formats in the capture interface.
447          */
448         if (!fmt || !(fmt->type == CODA_FMT_ENC))
449                 f->fmt.pix.pixelformat = V4L2_PIX_FMT_H264;
450
451         f->fmt.pix.colorspace = ctx->colorspace;
452
453         ret = vidioc_try_fmt(ctx->dev, f);
454         if (ret < 0)
455                 return ret;
456
457         return 0;
458 }
459
460 static int vidioc_try_fmt_vid_out(struct file *file, void *priv,
461                                   struct v4l2_format *f)
462 {
463         struct coda_ctx *ctx = fh_to_ctx(priv);
464         struct coda_fmt *fmt;
465         int ret;
466
467         fmt = find_format(ctx->dev, f);
468         /*
469          * Since decoding support is not implemented yet do not allow
470          * CODA_FMT formats in the capture interface.
471          */
472         if (!fmt || !(fmt->type == CODA_FMT_RAW))
473                 f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;
474
475         if (!f->fmt.pix.colorspace)
476                 f->fmt.pix.colorspace = V4L2_COLORSPACE_REC709;
477
478         ret = vidioc_try_fmt(ctx->dev, f);
479         if (ret < 0)
480                 return ret;
481
482         return 0;
483 }
484
485 static int vidioc_s_fmt(struct coda_ctx *ctx, struct v4l2_format *f)
486 {
487         struct coda_q_data *q_data;
488         struct vb2_queue *vq;
489         int ret;
490
491         vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
492         if (!vq)
493                 return -EINVAL;
494
495         q_data = get_q_data(ctx, f->type);
496         if (!q_data)
497                 return -EINVAL;
498
499         if (vb2_is_busy(vq)) {
500                 v4l2_err(&ctx->dev->v4l2_dev, "%s queue busy\n", __func__);
501                 return -EBUSY;
502         }
503
504         ret = vidioc_try_fmt(ctx->dev, f);
505         if (ret)
506                 return ret;
507
508         q_data->fmt = find_format(ctx->dev, f);
509         q_data->width = f->fmt.pix.width;
510         q_data->height = f->fmt.pix.height;
511         q_data->sizeimage = f->fmt.pix.sizeimage;
512
513         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
514                 "Setting format for type %d, wxh: %dx%d, fmt: %d\n",
515                 f->type, q_data->width, q_data->height, q_data->fmt->fourcc);
516
517         return 0;
518 }
519
520 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
521                                 struct v4l2_format *f)
522 {
523         int ret;
524
525         ret = vidioc_try_fmt_vid_cap(file, priv, f);
526         if (ret)
527                 return ret;
528
529         return vidioc_s_fmt(fh_to_ctx(priv), f);
530 }
531
532 static int vidioc_s_fmt_vid_out(struct file *file, void *priv,
533                                 struct v4l2_format *f)
534 {
535         struct coda_ctx *ctx = fh_to_ctx(priv);
536         int ret;
537
538         ret = vidioc_try_fmt_vid_out(file, priv, f);
539         if (ret)
540                 return ret;
541
542         ret = vidioc_s_fmt(ctx, f);
543         if (ret)
544                 ctx->colorspace = f->fmt.pix.colorspace;
545
546         return ret;
547 }
548
549 static int vidioc_reqbufs(struct file *file, void *priv,
550                           struct v4l2_requestbuffers *reqbufs)
551 {
552         struct coda_ctx *ctx = fh_to_ctx(priv);
553
554         return v4l2_m2m_reqbufs(file, ctx->m2m_ctx, reqbufs);
555 }
556
557 static int vidioc_querybuf(struct file *file, void *priv,
558                            struct v4l2_buffer *buf)
559 {
560         struct coda_ctx *ctx = fh_to_ctx(priv);
561
562         return v4l2_m2m_querybuf(file, ctx->m2m_ctx, buf);
563 }
564
565 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
566 {
567         struct coda_ctx *ctx = fh_to_ctx(priv);
568
569         return v4l2_m2m_qbuf(file, ctx->m2m_ctx, buf);
570 }
571
572 static int vidioc_expbuf(struct file *file, void *priv,
573                          struct v4l2_exportbuffer *eb)
574 {
575         struct coda_ctx *ctx = fh_to_ctx(priv);
576
577         return v4l2_m2m_expbuf(file, ctx->m2m_ctx, eb);
578 }
579
580 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
581 {
582         struct coda_ctx *ctx = fh_to_ctx(priv);
583
584         return v4l2_m2m_dqbuf(file, ctx->m2m_ctx, buf);
585 }
586
587 static int vidioc_streamon(struct file *file, void *priv,
588                            enum v4l2_buf_type type)
589 {
590         struct coda_ctx *ctx = fh_to_ctx(priv);
591
592         return v4l2_m2m_streamon(file, ctx->m2m_ctx, type);
593 }
594
595 static int vidioc_streamoff(struct file *file, void *priv,
596                             enum v4l2_buf_type type)
597 {
598         struct coda_ctx *ctx = fh_to_ctx(priv);
599
600         return v4l2_m2m_streamoff(file, ctx->m2m_ctx, type);
601 }
602
603 static const struct v4l2_ioctl_ops coda_ioctl_ops = {
604         .vidioc_querycap        = vidioc_querycap,
605
606         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
607         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt,
608         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
609         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
610
611         .vidioc_enum_fmt_vid_out = vidioc_enum_fmt_vid_out,
612         .vidioc_g_fmt_vid_out   = vidioc_g_fmt,
613         .vidioc_try_fmt_vid_out = vidioc_try_fmt_vid_out,
614         .vidioc_s_fmt_vid_out   = vidioc_s_fmt_vid_out,
615
616         .vidioc_reqbufs         = vidioc_reqbufs,
617         .vidioc_querybuf        = vidioc_querybuf,
618
619         .vidioc_qbuf            = vidioc_qbuf,
620         .vidioc_expbuf          = vidioc_expbuf,
621         .vidioc_dqbuf           = vidioc_dqbuf,
622
623         .vidioc_streamon        = vidioc_streamon,
624         .vidioc_streamoff       = vidioc_streamoff,
625 };
626
627 /*
628  * Mem-to-mem operations.
629  */
630 static void coda_device_run(void *m2m_priv)
631 {
632         struct coda_ctx *ctx = m2m_priv;
633         struct coda_q_data *q_data_src, *q_data_dst;
634         struct vb2_buffer *src_buf, *dst_buf;
635         struct coda_dev *dev = ctx->dev;
636         int force_ipicture;
637         int quant_param = 0;
638         u32 picture_y, picture_cb, picture_cr;
639         u32 pic_stream_buffer_addr, pic_stream_buffer_size;
640         u32 dst_fourcc;
641
642         src_buf = v4l2_m2m_next_src_buf(ctx->m2m_ctx);
643         dst_buf = v4l2_m2m_next_dst_buf(ctx->m2m_ctx);
644         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
645         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
646         dst_fourcc = q_data_dst->fmt->fourcc;
647
648         src_buf->v4l2_buf.sequence = ctx->isequence;
649         dst_buf->v4l2_buf.sequence = ctx->isequence;
650         ctx->isequence++;
651
652         /*
653          * Workaround coda firmware BUG that only marks the first
654          * frame as IDR. This is a problem for some decoders that can't
655          * recover when a frame is lost.
656          */
657         if (src_buf->v4l2_buf.sequence % ctx->params.gop_size) {
658                 src_buf->v4l2_buf.flags |= V4L2_BUF_FLAG_PFRAME;
659                 src_buf->v4l2_buf.flags &= ~V4L2_BUF_FLAG_KEYFRAME;
660         } else {
661                 src_buf->v4l2_buf.flags |= V4L2_BUF_FLAG_KEYFRAME;
662                 src_buf->v4l2_buf.flags &= ~V4L2_BUF_FLAG_PFRAME;
663         }
664
665         /*
666          * Copy headers at the beginning of the first frame for H.264 only.
667          * In MPEG4 they are already copied by the coda.
668          */
669         if (src_buf->v4l2_buf.sequence == 0) {
670                 pic_stream_buffer_addr =
671                         vb2_dma_contig_plane_dma_addr(dst_buf, 0) +
672                         ctx->vpu_header_size[0] +
673                         ctx->vpu_header_size[1] +
674                         ctx->vpu_header_size[2];
675                 pic_stream_buffer_size = CODA_MAX_FRAME_SIZE -
676                         ctx->vpu_header_size[0] -
677                         ctx->vpu_header_size[1] -
678                         ctx->vpu_header_size[2];
679                 memcpy(vb2_plane_vaddr(dst_buf, 0),
680                        &ctx->vpu_header[0][0], ctx->vpu_header_size[0]);
681                 memcpy(vb2_plane_vaddr(dst_buf, 0) + ctx->vpu_header_size[0],
682                        &ctx->vpu_header[1][0], ctx->vpu_header_size[1]);
683                 memcpy(vb2_plane_vaddr(dst_buf, 0) + ctx->vpu_header_size[0] +
684                         ctx->vpu_header_size[1], &ctx->vpu_header[2][0],
685                         ctx->vpu_header_size[2]);
686         } else {
687                 pic_stream_buffer_addr =
688                         vb2_dma_contig_plane_dma_addr(dst_buf, 0);
689                 pic_stream_buffer_size = CODA_MAX_FRAME_SIZE;
690         }
691
692         if (src_buf->v4l2_buf.flags & V4L2_BUF_FLAG_KEYFRAME) {
693                 force_ipicture = 1;
694                 switch (dst_fourcc) {
695                 case V4L2_PIX_FMT_H264:
696                         quant_param = ctx->params.h264_intra_qp;
697                         break;
698                 case V4L2_PIX_FMT_MPEG4:
699                         quant_param = ctx->params.mpeg4_intra_qp;
700                         break;
701                 default:
702                         v4l2_warn(&ctx->dev->v4l2_dev,
703                                 "cannot set intra qp, fmt not supported\n");
704                         break;
705                 }
706         } else {
707                 force_ipicture = 0;
708                 switch (dst_fourcc) {
709                 case V4L2_PIX_FMT_H264:
710                         quant_param = ctx->params.h264_inter_qp;
711                         break;
712                 case V4L2_PIX_FMT_MPEG4:
713                         quant_param = ctx->params.mpeg4_inter_qp;
714                         break;
715                 default:
716                         v4l2_warn(&ctx->dev->v4l2_dev,
717                                 "cannot set inter qp, fmt not supported\n");
718                         break;
719                 }
720         }
721
722         /* submit */
723         coda_write(dev, CODA_ROT_MIR_ENABLE | ctx->params.rot_mode, CODA_CMD_ENC_PIC_ROT_MODE);
724         coda_write(dev, quant_param, CODA_CMD_ENC_PIC_QS);
725
726
727         picture_y = vb2_dma_contig_plane_dma_addr(src_buf, 0);
728         picture_cb = picture_y + q_data_src->width * q_data_src->height;
729         picture_cr = picture_cb + q_data_src->width / 2 *
730                         q_data_src->height / 2;
731
732         coda_write(dev, picture_y, CODA_CMD_ENC_PIC_SRC_ADDR_Y);
733         coda_write(dev, picture_cb, CODA_CMD_ENC_PIC_SRC_ADDR_CB);
734         coda_write(dev, picture_cr, CODA_CMD_ENC_PIC_SRC_ADDR_CR);
735         coda_write(dev, force_ipicture << 1 & 0x2,
736                    CODA_CMD_ENC_PIC_OPTION);
737
738         coda_write(dev, pic_stream_buffer_addr, CODA_CMD_ENC_PIC_BB_START);
739         coda_write(dev, pic_stream_buffer_size / 1024,
740                    CODA_CMD_ENC_PIC_BB_SIZE);
741
742         if (dev->devtype->product == CODA_7541) {
743                 coda_write(dev, CODA7_USE_BIT_ENABLE | CODA7_USE_HOST_BIT_ENABLE |
744                                 CODA7_USE_ME_ENABLE | CODA7_USE_HOST_ME_ENABLE,
745                                 CODA7_REG_BIT_AXI_SRAM_USE);
746         }
747
748         /* 1 second timeout in case CODA locks up */
749         schedule_delayed_work(&dev->timeout, HZ);
750
751         INIT_COMPLETION(dev->done);
752         coda_command_async(ctx, CODA_COMMAND_PIC_RUN);
753 }
754
755 static int coda_job_ready(void *m2m_priv)
756 {
757         struct coda_ctx *ctx = m2m_priv;
758
759         /*
760          * For both 'P' and 'key' frame cases 1 picture
761          * and 1 frame are needed.
762          */
763         if (!v4l2_m2m_num_src_bufs_ready(ctx->m2m_ctx) ||
764                 !v4l2_m2m_num_dst_bufs_ready(ctx->m2m_ctx)) {
765                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
766                          "not ready: not enough video buffers.\n");
767                 return 0;
768         }
769
770         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
771                         "job ready\n");
772         return 1;
773 }
774
775 static void coda_job_abort(void *priv)
776 {
777         struct coda_ctx *ctx = priv;
778         struct coda_dev *dev = ctx->dev;
779
780         ctx->aborting = 1;
781
782         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
783                  "Aborting task\n");
784
785         v4l2_m2m_job_finish(dev->m2m_dev, ctx->m2m_ctx);
786 }
787
788 static void coda_lock(void *m2m_priv)
789 {
790         struct coda_ctx *ctx = m2m_priv;
791         struct coda_dev *pcdev = ctx->dev;
792         mutex_lock(&pcdev->dev_mutex);
793 }
794
795 static void coda_unlock(void *m2m_priv)
796 {
797         struct coda_ctx *ctx = m2m_priv;
798         struct coda_dev *pcdev = ctx->dev;
799         mutex_unlock(&pcdev->dev_mutex);
800 }
801
802 static struct v4l2_m2m_ops coda_m2m_ops = {
803         .device_run     = coda_device_run,
804         .job_ready      = coda_job_ready,
805         .job_abort      = coda_job_abort,
806         .lock           = coda_lock,
807         .unlock         = coda_unlock,
808 };
809
810 static void set_default_params(struct coda_ctx *ctx)
811 {
812         struct coda_dev *dev = ctx->dev;
813
814         ctx->params.codec_mode = CODA_MODE_INVALID;
815         ctx->colorspace = V4L2_COLORSPACE_REC709;
816         ctx->params.framerate = 30;
817         ctx->aborting = 0;
818
819         /* Default formats for output and input queues */
820         ctx->q_data[V4L2_M2M_SRC].fmt = &dev->devtype->formats[0];
821         ctx->q_data[V4L2_M2M_DST].fmt = &dev->devtype->formats[1];
822         ctx->q_data[V4L2_M2M_SRC].width = MAX_W;
823         ctx->q_data[V4L2_M2M_SRC].height = MAX_H;
824         ctx->q_data[V4L2_M2M_SRC].sizeimage = (MAX_W * MAX_H * 3) / 2;
825         ctx->q_data[V4L2_M2M_DST].width = MAX_W;
826         ctx->q_data[V4L2_M2M_DST].height = MAX_H;
827         ctx->q_data[V4L2_M2M_DST].sizeimage = CODA_MAX_FRAME_SIZE;
828 }
829
830 /*
831  * Queue operations
832  */
833 static int coda_queue_setup(struct vb2_queue *vq,
834                                 const struct v4l2_format *fmt,
835                                 unsigned int *nbuffers, unsigned int *nplanes,
836                                 unsigned int sizes[], void *alloc_ctxs[])
837 {
838         struct coda_ctx *ctx = vb2_get_drv_priv(vq);
839         struct coda_q_data *q_data;
840         unsigned int size;
841
842         q_data = get_q_data(ctx, vq->type);
843         size = q_data->sizeimage;
844
845         *nplanes = 1;
846         sizes[0] = size;
847
848         alloc_ctxs[0] = ctx->dev->alloc_ctx;
849
850         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
851                  "get %d buffer(s) of size %d each.\n", *nbuffers, size);
852
853         return 0;
854 }
855
856 static int coda_buf_prepare(struct vb2_buffer *vb)
857 {
858         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
859         struct coda_q_data *q_data;
860
861         q_data = get_q_data(ctx, vb->vb2_queue->type);
862
863         if (vb2_plane_size(vb, 0) < q_data->sizeimage) {
864                 v4l2_warn(&ctx->dev->v4l2_dev,
865                           "%s data will not fit into plane (%lu < %lu)\n",
866                           __func__, vb2_plane_size(vb, 0),
867                           (long)q_data->sizeimage);
868                 return -EINVAL;
869         }
870
871         vb2_set_plane_payload(vb, 0, q_data->sizeimage);
872
873         return 0;
874 }
875
876 static void coda_buf_queue(struct vb2_buffer *vb)
877 {
878         struct coda_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
879         v4l2_m2m_buf_queue(ctx->m2m_ctx, vb);
880 }
881
882 static void coda_wait_prepare(struct vb2_queue *q)
883 {
884         struct coda_ctx *ctx = vb2_get_drv_priv(q);
885         coda_unlock(ctx);
886 }
887
888 static void coda_wait_finish(struct vb2_queue *q)
889 {
890         struct coda_ctx *ctx = vb2_get_drv_priv(q);
891         coda_lock(ctx);
892 }
893
894 static void coda_free_framebuffers(struct coda_ctx *ctx)
895 {
896         int i;
897
898         for (i = 0; i < CODA_MAX_FRAMEBUFFERS; i++) {
899                 if (ctx->internal_frames[i].vaddr) {
900                         dma_free_coherent(&ctx->dev->plat_dev->dev,
901                                 ctx->internal_frames[i].size,
902                                 ctx->internal_frames[i].vaddr,
903                                 ctx->internal_frames[i].paddr);
904                         ctx->internal_frames[i].vaddr = NULL;
905                 }
906         }
907 }
908
909 static int coda_alloc_framebuffers(struct coda_ctx *ctx, struct coda_q_data *q_data, u32 fourcc)
910 {
911         struct coda_dev *dev = ctx->dev;
912
913         int height = q_data->height;
914         int width = q_data->width;
915         u32 *p;
916         int i;
917
918         /* Allocate frame buffers */
919         ctx->num_internal_frames = CODA_MAX_FRAMEBUFFERS;
920         for (i = 0; i < ctx->num_internal_frames; i++) {
921                 ctx->internal_frames[i].size = q_data->sizeimage;
922                 if (fourcc == V4L2_PIX_FMT_H264 && dev->devtype->product != CODA_DX6)
923                         ctx->internal_frames[i].size += width / 2 * height / 2;
924                 ctx->internal_frames[i].vaddr = dma_alloc_coherent(
925                                 &dev->plat_dev->dev, ctx->internal_frames[i].size,
926                                 &ctx->internal_frames[i].paddr, GFP_KERNEL);
927                 if (!ctx->internal_frames[i].vaddr) {
928                         coda_free_framebuffers(ctx);
929                         return -ENOMEM;
930                 }
931         }
932
933         /* Register frame buffers in the parameter buffer */
934         p = ctx->parabuf.vaddr;
935
936         if (dev->devtype->product == CODA_DX6) {
937                 for (i = 0; i < ctx->num_internal_frames; i++) {
938                         p[i * 3] = ctx->internal_frames[i].paddr; /* Y */
939                         p[i * 3 + 1] = p[i * 3] + width * height; /* Cb */
940                         p[i * 3 + 2] = p[i * 3 + 1] + width / 2 * height / 2; /* Cr */
941                 }
942         } else {
943                 for (i = 0; i < ctx->num_internal_frames; i += 2) {
944                         p[i * 3 + 1] = ctx->internal_frames[i].paddr; /* Y */
945                         p[i * 3] = p[i * 3 + 1] + width * height; /* Cb */
946                         p[i * 3 + 3] = p[i * 3] + (width / 2) * (height / 2); /* Cr */
947
948                         if (fourcc == V4L2_PIX_FMT_H264)
949                                 p[96 + i + 1] = p[i * 3 + 3] + (width / 2) * (height / 2);
950
951                         if (i + 1 < ctx->num_internal_frames) {
952                                 p[i * 3 + 2] = ctx->internal_frames[i+1].paddr; /* Y */
953                                 p[i * 3 + 5] = p[i * 3 + 2] + width * height ; /* Cb */
954                                 p[i * 3 + 4] = p[i * 3 + 5] + (width / 2) * (height / 2); /* Cr */
955
956                                 if (fourcc == V4L2_PIX_FMT_H264)
957                                         p[96 + i] = p[i * 3 + 4] + (width / 2) * (height / 2);
958                         }
959                 }
960         }
961
962         return 0;
963 }
964
965 static int coda_h264_padding(int size, char *p)
966 {
967         int nal_size;
968         int diff;
969
970         diff = size - (size & ~0x7);
971         if (diff == 0)
972                 return 0;
973
974         nal_size = coda_filler_size[diff];
975         memcpy(p, coda_filler_nal, nal_size);
976
977         /* Add rbsp stop bit and trailing at the end */
978         *(p + nal_size - 1) = 0x80;
979
980         return nal_size;
981 }
982
983 static int coda_start_streaming(struct vb2_queue *q, unsigned int count)
984 {
985         struct coda_ctx *ctx = vb2_get_drv_priv(q);
986         struct v4l2_device *v4l2_dev = &ctx->dev->v4l2_dev;
987         u32 bitstream_buf, bitstream_size;
988         struct coda_dev *dev = ctx->dev;
989         struct coda_q_data *q_data_src, *q_data_dst;
990         struct vb2_buffer *buf;
991         u32 dst_fourcc;
992         u32 value;
993         int ret;
994
995         if (count < 1)
996                 return -EINVAL;
997
998         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
999                 ctx->rawstreamon = 1;
1000         else
1001                 ctx->compstreamon = 1;
1002
1003         /* Don't start the coda unless both queues are on */
1004         if (!(ctx->rawstreamon & ctx->compstreamon))
1005                 return 0;
1006
1007         if (coda_isbusy(dev))
1008                 if (wait_for_completion_interruptible_timeout(&dev->done, HZ) <= 0)
1009                         return -EBUSY;
1010
1011         ctx->gopcounter = ctx->params.gop_size - 1;
1012
1013         q_data_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
1014         buf = v4l2_m2m_next_dst_buf(ctx->m2m_ctx);
1015         bitstream_buf = vb2_dma_contig_plane_dma_addr(buf, 0);
1016         q_data_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1017         bitstream_size = q_data_dst->sizeimage;
1018         dst_fourcc = q_data_dst->fmt->fourcc;
1019
1020         /* Find out whether coda must encode or decode */
1021         if (q_data_src->fmt->type == CODA_FMT_RAW &&
1022             q_data_dst->fmt->type == CODA_FMT_ENC) {
1023                 ctx->inst_type = CODA_INST_ENCODER;
1024         } else if (q_data_src->fmt->type == CODA_FMT_ENC &&
1025                    q_data_dst->fmt->type == CODA_FMT_RAW) {
1026                 ctx->inst_type = CODA_INST_DECODER;
1027                 v4l2_err(v4l2_dev, "decoding not supported.\n");
1028                 return -EINVAL;
1029         } else {
1030                 v4l2_err(v4l2_dev, "couldn't tell instance type.\n");
1031                 return -EINVAL;
1032         }
1033
1034         if (!coda_is_initialized(dev)) {
1035                 v4l2_err(v4l2_dev, "coda is not initialized.\n");
1036                 return -EFAULT;
1037         }
1038         coda_write(dev, ctx->parabuf.paddr, CODA_REG_BIT_PARA_BUF_ADDR);
1039         coda_write(dev, bitstream_buf, CODA_REG_BIT_RD_PTR(ctx->idx));
1040         coda_write(dev, bitstream_buf, CODA_REG_BIT_WR_PTR(ctx->idx));
1041         switch (dev->devtype->product) {
1042         case CODA_DX6:
1043                 coda_write(dev, CODADX6_STREAM_BUF_DYNALLOC_EN |
1044                         CODADX6_STREAM_BUF_PIC_RESET, CODA_REG_BIT_STREAM_CTRL);
1045                 break;
1046         default:
1047                 coda_write(dev, CODA7_STREAM_BUF_DYNALLOC_EN |
1048                         CODA7_STREAM_BUF_PIC_RESET, CODA_REG_BIT_STREAM_CTRL);
1049         }
1050
1051         if (dev->devtype->product == CODA_DX6) {
1052                 /* Configure the coda */
1053                 coda_write(dev, dev->iram_paddr, CODADX6_REG_BIT_SEARCH_RAM_BASE_ADDR);
1054         }
1055
1056         /* Could set rotation here if needed */
1057         switch (dev->devtype->product) {
1058         case CODA_DX6:
1059                 value = (q_data_src->width & CODADX6_PICWIDTH_MASK) << CODADX6_PICWIDTH_OFFSET;
1060                 break;
1061         default:
1062                 value = (q_data_src->width & CODA7_PICWIDTH_MASK) << CODA7_PICWIDTH_OFFSET;
1063         }
1064         value |= (q_data_src->height & CODA_PICHEIGHT_MASK) << CODA_PICHEIGHT_OFFSET;
1065         coda_write(dev, value, CODA_CMD_ENC_SEQ_SRC_SIZE);
1066         coda_write(dev, ctx->params.framerate,
1067                    CODA_CMD_ENC_SEQ_SRC_F_RATE);
1068
1069         switch (dst_fourcc) {
1070         case V4L2_PIX_FMT_MPEG4:
1071                 if (dev->devtype->product == CODA_DX6)
1072                         ctx->params.codec_mode = CODADX6_MODE_ENCODE_MP4;
1073                 else
1074                         ctx->params.codec_mode = CODA7_MODE_ENCODE_MP4;
1075
1076                 coda_write(dev, CODA_STD_MPEG4, CODA_CMD_ENC_SEQ_COD_STD);
1077                 coda_write(dev, 0, CODA_CMD_ENC_SEQ_MP4_PARA);
1078                 break;
1079         case V4L2_PIX_FMT_H264:
1080                 if (dev->devtype->product == CODA_DX6)
1081                         ctx->params.codec_mode = CODADX6_MODE_ENCODE_H264;
1082                 else
1083                         ctx->params.codec_mode = CODA7_MODE_ENCODE_H264;
1084
1085                 coda_write(dev, CODA_STD_H264, CODA_CMD_ENC_SEQ_COD_STD);
1086                 coda_write(dev, 0, CODA_CMD_ENC_SEQ_264_PARA);
1087                 break;
1088         default:
1089                 v4l2_err(v4l2_dev,
1090                          "dst format (0x%08x) invalid.\n", dst_fourcc);
1091                 return -EINVAL;
1092         }
1093
1094         switch (ctx->params.slice_mode) {
1095         case V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE:
1096                 value = 0;
1097                 break;
1098         case V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB:
1099                 value  = (ctx->params.slice_max_mb & CODA_SLICING_SIZE_MASK) << CODA_SLICING_SIZE_OFFSET;
1100                 value |= (1 & CODA_SLICING_UNIT_MASK) << CODA_SLICING_UNIT_OFFSET;
1101                 value |=  1 & CODA_SLICING_MODE_MASK;
1102                 break;
1103         case V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES:
1104                 value  = (ctx->params.slice_max_bits & CODA_SLICING_SIZE_MASK) << CODA_SLICING_SIZE_OFFSET;
1105                 value |= (0 & CODA_SLICING_UNIT_MASK) << CODA_SLICING_UNIT_OFFSET;
1106                 value |=  1 & CODA_SLICING_MODE_MASK;
1107                 break;
1108         }
1109         coda_write(dev, value, CODA_CMD_ENC_SEQ_SLICE_MODE);
1110         value = ctx->params.gop_size & CODA_GOP_SIZE_MASK;
1111         coda_write(dev, value, CODA_CMD_ENC_SEQ_GOP_SIZE);
1112
1113         if (ctx->params.bitrate) {
1114                 /* Rate control enabled */
1115                 value = (ctx->params.bitrate & CODA_RATECONTROL_BITRATE_MASK) << CODA_RATECONTROL_BITRATE_OFFSET;
1116                 value |=  1 & CODA_RATECONTROL_ENABLE_MASK;
1117         } else {
1118                 value = 0;
1119         }
1120         coda_write(dev, value, CODA_CMD_ENC_SEQ_RC_PARA);
1121
1122         coda_write(dev, 0, CODA_CMD_ENC_SEQ_RC_BUF_SIZE);
1123         coda_write(dev, 0, CODA_CMD_ENC_SEQ_INTRA_REFRESH);
1124
1125         coda_write(dev, bitstream_buf, CODA_CMD_ENC_SEQ_BB_START);
1126         coda_write(dev, bitstream_size / 1024, CODA_CMD_ENC_SEQ_BB_SIZE);
1127
1128         /* set default gamma */
1129         value = (CODA_DEFAULT_GAMMA & CODA_GAMMA_MASK) << CODA_GAMMA_OFFSET;
1130         coda_write(dev, value, CODA_CMD_ENC_SEQ_RC_GAMMA);
1131
1132         if (CODA_DEFAULT_GAMMA > 0) {
1133                 if (dev->devtype->product == CODA_DX6)
1134                         value  = 1 << CODADX6_OPTION_GAMMA_OFFSET;
1135                 else
1136                         value  = 1 << CODA7_OPTION_GAMMA_OFFSET;
1137         } else {
1138                 value = 0;
1139         }
1140         coda_write(dev, value, CODA_CMD_ENC_SEQ_OPTION);
1141
1142         if (dst_fourcc == V4L2_PIX_FMT_H264) {
1143                 value  = (FMO_SLICE_SAVE_BUF_SIZE << 7);
1144                 value |= (0 & CODA_FMOPARAM_TYPE_MASK) << CODA_FMOPARAM_TYPE_OFFSET;
1145                 value |=  0 & CODA_FMOPARAM_SLICENUM_MASK;
1146                 if (dev->devtype->product == CODA_DX6) {
1147                         coda_write(dev, value, CODADX6_CMD_ENC_SEQ_FMO);
1148                 } else {
1149                         coda_write(dev, dev->iram_paddr, CODA7_CMD_ENC_SEQ_SEARCH_BASE);
1150                         coda_write(dev, 48 * 1024, CODA7_CMD_ENC_SEQ_SEARCH_SIZE);
1151                 }
1152         }
1153
1154         if (coda_command_sync(ctx, CODA_COMMAND_SEQ_INIT)) {
1155                 v4l2_err(v4l2_dev, "CODA_COMMAND_SEQ_INIT timeout\n");
1156                 return -ETIMEDOUT;
1157         }
1158
1159         if (coda_read(dev, CODA_RET_ENC_SEQ_SUCCESS) == 0)
1160                 return -EFAULT;
1161
1162         ret = coda_alloc_framebuffers(ctx, q_data_src, dst_fourcc);
1163         if (ret < 0)
1164                 return ret;
1165
1166         coda_write(dev, ctx->num_internal_frames, CODA_CMD_SET_FRAME_BUF_NUM);
1167         coda_write(dev, round_up(q_data_src->width, 8), CODA_CMD_SET_FRAME_BUF_STRIDE);
1168         if (dev->devtype->product != CODA_DX6) {
1169                 coda_write(dev, round_up(q_data_src->width, 8), CODA7_CMD_SET_FRAME_SOURCE_BUF_STRIDE);
1170                 coda_write(dev, dev->iram_paddr + 48 * 1024, CODA7_CMD_SET_FRAME_AXI_DBKY_ADDR);
1171                 coda_write(dev, dev->iram_paddr + 53 * 1024, CODA7_CMD_SET_FRAME_AXI_DBKC_ADDR);
1172                 coda_write(dev, dev->iram_paddr + 58 * 1024, CODA7_CMD_SET_FRAME_AXI_BIT_ADDR);
1173                 coda_write(dev, dev->iram_paddr + 68 * 1024, CODA7_CMD_SET_FRAME_AXI_IPACDC_ADDR);
1174                 coda_write(dev, 0x0, CODA7_CMD_SET_FRAME_AXI_OVL_ADDR);
1175         }
1176         if (coda_command_sync(ctx, CODA_COMMAND_SET_FRAME_BUF)) {
1177                 v4l2_err(v4l2_dev, "CODA_COMMAND_SET_FRAME_BUF timeout\n");
1178                 return -ETIMEDOUT;
1179         }
1180
1181         /* Save stream headers */
1182         buf = v4l2_m2m_next_dst_buf(ctx->m2m_ctx);
1183         switch (dst_fourcc) {
1184         case V4L2_PIX_FMT_H264:
1185                 /*
1186                  * Get SPS in the first frame and copy it to an
1187                  * intermediate buffer.
1188                  */
1189                 coda_write(dev, vb2_dma_contig_plane_dma_addr(buf, 0), CODA_CMD_ENC_HEADER_BB_START);
1190                 coda_write(dev, bitstream_size, CODA_CMD_ENC_HEADER_BB_SIZE);
1191                 coda_write(dev, CODA_HEADER_H264_SPS, CODA_CMD_ENC_HEADER_CODE);
1192                 if (coda_command_sync(ctx, CODA_COMMAND_ENCODE_HEADER)) {
1193                         v4l2_err(v4l2_dev, "CODA_COMMAND_ENCODE_HEADER timeout\n");
1194                         return -ETIMEDOUT;
1195                 }
1196                 ctx->vpu_header_size[0] = coda_read(dev, CODA_REG_BIT_WR_PTR(ctx->idx)) -
1197                                 coda_read(dev, CODA_CMD_ENC_HEADER_BB_START);
1198                 memcpy(&ctx->vpu_header[0][0], vb2_plane_vaddr(buf, 0),
1199                        ctx->vpu_header_size[0]);
1200
1201                 /*
1202                  * Get PPS in the first frame and copy it to an
1203                  * intermediate buffer.
1204                  */
1205                 coda_write(dev, vb2_dma_contig_plane_dma_addr(buf, 0), CODA_CMD_ENC_HEADER_BB_START);
1206                 coda_write(dev, bitstream_size, CODA_CMD_ENC_HEADER_BB_SIZE);
1207                 coda_write(dev, CODA_HEADER_H264_PPS, CODA_CMD_ENC_HEADER_CODE);
1208                 if (coda_command_sync(ctx, CODA_COMMAND_ENCODE_HEADER)) {
1209                         v4l2_err(v4l2_dev, "CODA_COMMAND_ENCODE_HEADER timeout\n");
1210                         return -ETIMEDOUT;
1211                 }
1212                 ctx->vpu_header_size[1] = coda_read(dev, CODA_REG_BIT_WR_PTR(ctx->idx)) -
1213                                 coda_read(dev, CODA_CMD_ENC_HEADER_BB_START);
1214                 memcpy(&ctx->vpu_header[1][0], vb2_plane_vaddr(buf, 0),
1215                        ctx->vpu_header_size[1]);
1216                 /*
1217                  * Length of H.264 headers is variable and thus it might not be
1218                  * aligned for the coda to append the encoded frame. In that is
1219                  * the case a filler NAL must be added to header 2.
1220                  */
1221                 ctx->vpu_header_size[2] = coda_h264_padding(
1222                                         (ctx->vpu_header_size[0] +
1223                                          ctx->vpu_header_size[1]),
1224                                          ctx->vpu_header[2]);
1225                 break;
1226         case V4L2_PIX_FMT_MPEG4:
1227                 /*
1228                  * Get VOS in the first frame and copy it to an
1229                  * intermediate buffer
1230                  */
1231                 coda_write(dev, vb2_dma_contig_plane_dma_addr(buf, 0), CODA_CMD_ENC_HEADER_BB_START);
1232                 coda_write(dev, bitstream_size, CODA_CMD_ENC_HEADER_BB_SIZE);
1233                 coda_write(dev, CODA_HEADER_MP4V_VOS, CODA_CMD_ENC_HEADER_CODE);
1234                 if (coda_command_sync(ctx, CODA_COMMAND_ENCODE_HEADER)) {
1235                         v4l2_err(v4l2_dev, "CODA_COMMAND_ENCODE_HEADER timeout\n");
1236                         return -ETIMEDOUT;
1237                 }
1238                 ctx->vpu_header_size[0] = coda_read(dev, CODA_REG_BIT_WR_PTR(ctx->idx)) -
1239                                 coda_read(dev, CODA_CMD_ENC_HEADER_BB_START);
1240                 memcpy(&ctx->vpu_header[0][0], vb2_plane_vaddr(buf, 0),
1241                        ctx->vpu_header_size[0]);
1242
1243                 coda_write(dev, vb2_dma_contig_plane_dma_addr(buf, 0), CODA_CMD_ENC_HEADER_BB_START);
1244                 coda_write(dev, bitstream_size, CODA_CMD_ENC_HEADER_BB_SIZE);
1245                 coda_write(dev, CODA_HEADER_MP4V_VIS, CODA_CMD_ENC_HEADER_CODE);
1246                 if (coda_command_sync(ctx, CODA_COMMAND_ENCODE_HEADER)) {
1247                         v4l2_err(v4l2_dev, "CODA_COMMAND_ENCODE_HEADER failed\n");
1248                         return -ETIMEDOUT;
1249                 }
1250                 ctx->vpu_header_size[1] = coda_read(dev, CODA_REG_BIT_WR_PTR(ctx->idx)) -
1251                                 coda_read(dev, CODA_CMD_ENC_HEADER_BB_START);
1252                 memcpy(&ctx->vpu_header[1][0], vb2_plane_vaddr(buf, 0),
1253                        ctx->vpu_header_size[1]);
1254
1255                 coda_write(dev, vb2_dma_contig_plane_dma_addr(buf, 0), CODA_CMD_ENC_HEADER_BB_START);
1256                 coda_write(dev, bitstream_size, CODA_CMD_ENC_HEADER_BB_SIZE);
1257                 coda_write(dev, CODA_HEADER_MP4V_VOL, CODA_CMD_ENC_HEADER_CODE);
1258                 if (coda_command_sync(ctx, CODA_COMMAND_ENCODE_HEADER)) {
1259                         v4l2_err(v4l2_dev, "CODA_COMMAND_ENCODE_HEADER failed\n");
1260                         return -ETIMEDOUT;
1261                 }
1262                 ctx->vpu_header_size[2] = coda_read(dev, CODA_REG_BIT_WR_PTR(ctx->idx)) -
1263                                 coda_read(dev, CODA_CMD_ENC_HEADER_BB_START);
1264                 memcpy(&ctx->vpu_header[2][0], vb2_plane_vaddr(buf, 0),
1265                        ctx->vpu_header_size[2]);
1266                 break;
1267         default:
1268                 /* No more formats need to save headers at the moment */
1269                 break;
1270         }
1271
1272         return 0;
1273 }
1274
1275 static int coda_stop_streaming(struct vb2_queue *q)
1276 {
1277         struct coda_ctx *ctx = vb2_get_drv_priv(q);
1278         struct coda_dev *dev = ctx->dev;
1279
1280         if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
1281                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1282                          "%s: output\n", __func__);
1283                 ctx->rawstreamon = 0;
1284         } else {
1285                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1286                          "%s: capture\n", __func__);
1287                 ctx->compstreamon = 0;
1288         }
1289
1290         /* Don't stop the coda unless both queues are off */
1291         if (ctx->rawstreamon || ctx->compstreamon)
1292                 return 0;
1293
1294         if (coda_isbusy(dev)) {
1295                 if (wait_for_completion_interruptible_timeout(&dev->done, HZ) <= 0) {
1296                         v4l2_warn(&dev->v4l2_dev,
1297                                   "%s: timeout, sending SEQ_END anyway\n", __func__);
1298                 }
1299         }
1300
1301         cancel_delayed_work(&dev->timeout);
1302
1303         v4l2_dbg(1, coda_debug, &dev->v4l2_dev,
1304                  "%s: sent command 'SEQ_END' to coda\n", __func__);
1305         if (coda_command_sync(ctx, CODA_COMMAND_SEQ_END)) {
1306                 v4l2_err(&dev->v4l2_dev,
1307                          "CODA_COMMAND_SEQ_END failed\n");
1308                 return -ETIMEDOUT;
1309         }
1310
1311         coda_free_framebuffers(ctx);
1312
1313         return 0;
1314 }
1315
1316 static struct vb2_ops coda_qops = {
1317         .queue_setup            = coda_queue_setup,
1318         .buf_prepare            = coda_buf_prepare,
1319         .buf_queue              = coda_buf_queue,
1320         .wait_prepare           = coda_wait_prepare,
1321         .wait_finish            = coda_wait_finish,
1322         .start_streaming        = coda_start_streaming,
1323         .stop_streaming         = coda_stop_streaming,
1324 };
1325
1326 static int coda_s_ctrl(struct v4l2_ctrl *ctrl)
1327 {
1328         struct coda_ctx *ctx =
1329                         container_of(ctrl->handler, struct coda_ctx, ctrls);
1330
1331         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1332                  "s_ctrl: id = %d, val = %d\n", ctrl->id, ctrl->val);
1333
1334         switch (ctrl->id) {
1335         case V4L2_CID_HFLIP:
1336                 if (ctrl->val)
1337                         ctx->params.rot_mode |= CODA_MIR_HOR;
1338                 else
1339                         ctx->params.rot_mode &= ~CODA_MIR_HOR;
1340                 break;
1341         case V4L2_CID_VFLIP:
1342                 if (ctrl->val)
1343                         ctx->params.rot_mode |= CODA_MIR_VER;
1344                 else
1345                         ctx->params.rot_mode &= ~CODA_MIR_VER;
1346                 break;
1347         case V4L2_CID_MPEG_VIDEO_BITRATE:
1348                 ctx->params.bitrate = ctrl->val / 1000;
1349                 break;
1350         case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
1351                 ctx->params.gop_size = ctrl->val;
1352                 break;
1353         case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
1354                 ctx->params.h264_intra_qp = ctrl->val;
1355                 break;
1356         case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
1357                 ctx->params.h264_inter_qp = ctrl->val;
1358                 break;
1359         case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
1360                 ctx->params.mpeg4_intra_qp = ctrl->val;
1361                 break;
1362         case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
1363                 ctx->params.mpeg4_inter_qp = ctrl->val;
1364                 break;
1365         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
1366                 ctx->params.slice_mode = ctrl->val;
1367                 break;
1368         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
1369                 ctx->params.slice_max_mb = ctrl->val;
1370                 break;
1371         case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
1372                 ctx->params.slice_max_bits = ctrl->val * 8;
1373                 break;
1374         case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
1375                 break;
1376         default:
1377                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1378                         "Invalid control, id=%d, val=%d\n",
1379                         ctrl->id, ctrl->val);
1380                 return -EINVAL;
1381         }
1382
1383         return 0;
1384 }
1385
1386 static struct v4l2_ctrl_ops coda_ctrl_ops = {
1387         .s_ctrl = coda_s_ctrl,
1388 };
1389
1390 static int coda_ctrls_setup(struct coda_ctx *ctx)
1391 {
1392         v4l2_ctrl_handler_init(&ctx->ctrls, 9);
1393
1394         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1395                 V4L2_CID_HFLIP, 0, 1, 1, 0);
1396         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1397                 V4L2_CID_VFLIP, 0, 1, 1, 0);
1398         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1399                 V4L2_CID_MPEG_VIDEO_BITRATE, 0, 32767000, 1, 0);
1400         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1401                 V4L2_CID_MPEG_VIDEO_GOP_SIZE, 1, 60, 1, 16);
1402         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1403                 V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP, 1, 51, 1, 25);
1404         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1405                 V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP, 1, 51, 1, 25);
1406         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1407                 V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP, 1, 31, 1, 2);
1408         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1409                 V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP, 1, 31, 1, 2);
1410         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1411                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE,
1412                 V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES, 0x0,
1413                 V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE);
1414         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1415                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB, 1, 0x3fffffff, 1, 1);
1416         v4l2_ctrl_new_std(&ctx->ctrls, &coda_ctrl_ops,
1417                 V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES, 1, 0x3fffffff, 1, 500);
1418         v4l2_ctrl_new_std_menu(&ctx->ctrls, &coda_ctrl_ops,
1419                 V4L2_CID_MPEG_VIDEO_HEADER_MODE,
1420                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME,
1421                 (1 << V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE),
1422                 V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME);
1423
1424         if (ctx->ctrls.error) {
1425                 v4l2_err(&ctx->dev->v4l2_dev, "control initialization error (%d)",
1426                         ctx->ctrls.error);
1427                 return -EINVAL;
1428         }
1429
1430         return v4l2_ctrl_handler_setup(&ctx->ctrls);
1431 }
1432
1433 static int coda_queue_init(void *priv, struct vb2_queue *src_vq,
1434                       struct vb2_queue *dst_vq)
1435 {
1436         struct coda_ctx *ctx = priv;
1437         int ret;
1438
1439         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
1440         src_vq->io_modes = VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
1441         src_vq->drv_priv = ctx;
1442         src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
1443         src_vq->ops = &coda_qops;
1444         src_vq->mem_ops = &vb2_dma_contig_memops;
1445         src_vq->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1446
1447         ret = vb2_queue_init(src_vq);
1448         if (ret)
1449                 return ret;
1450
1451         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1452         dst_vq->io_modes = VB2_DMABUF | VB2_MMAP | VB2_USERPTR;
1453         dst_vq->drv_priv = ctx;
1454         dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
1455         dst_vq->ops = &coda_qops;
1456         dst_vq->mem_ops = &vb2_dma_contig_memops;
1457         dst_vq->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1458
1459         return vb2_queue_init(dst_vq);
1460 }
1461
1462 static int coda_next_free_instance(struct coda_dev *dev)
1463 {
1464         return ffz(dev->instance_mask);
1465 }
1466
1467 static int coda_open(struct file *file)
1468 {
1469         struct coda_dev *dev = video_drvdata(file);
1470         struct coda_ctx *ctx = NULL;
1471         int ret = 0;
1472         int idx;
1473
1474         idx = coda_next_free_instance(dev);
1475         if (idx >= CODA_MAX_INSTANCES)
1476                 return -EBUSY;
1477         set_bit(idx, &dev->instance_mask);
1478
1479         ctx = kzalloc(sizeof *ctx, GFP_KERNEL);
1480         if (!ctx)
1481                 return -ENOMEM;
1482
1483         v4l2_fh_init(&ctx->fh, video_devdata(file));
1484         file->private_data = &ctx->fh;
1485         v4l2_fh_add(&ctx->fh);
1486         ctx->dev = dev;
1487         ctx->idx = idx;
1488
1489         set_default_params(ctx);
1490         ctx->m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx,
1491                                          &coda_queue_init);
1492         if (IS_ERR(ctx->m2m_ctx)) {
1493                 ret = PTR_ERR(ctx->m2m_ctx);
1494
1495                 v4l2_err(&dev->v4l2_dev, "%s return error (%d)\n",
1496                          __func__, ret);
1497                 goto err;
1498         }
1499         ret = coda_ctrls_setup(ctx);
1500         if (ret) {
1501                 v4l2_err(&dev->v4l2_dev, "failed to setup coda controls\n");
1502                 goto err;
1503         }
1504
1505         ctx->fh.ctrl_handler = &ctx->ctrls;
1506
1507         ctx->parabuf.vaddr = dma_alloc_coherent(&dev->plat_dev->dev,
1508                         CODA_PARA_BUF_SIZE, &ctx->parabuf.paddr, GFP_KERNEL);
1509         if (!ctx->parabuf.vaddr) {
1510                 v4l2_err(&dev->v4l2_dev, "failed to allocate parabuf");
1511                 ret = -ENOMEM;
1512                 goto err;
1513         }
1514
1515         coda_lock(ctx);
1516         list_add(&ctx->list, &dev->instances);
1517         coda_unlock(ctx);
1518
1519         clk_prepare_enable(dev->clk_per);
1520         clk_prepare_enable(dev->clk_ahb);
1521
1522         v4l2_dbg(1, coda_debug, &dev->v4l2_dev, "Created instance %d (%p)\n",
1523                  ctx->idx, ctx);
1524
1525         return 0;
1526
1527 err:
1528         v4l2_fh_del(&ctx->fh);
1529         v4l2_fh_exit(&ctx->fh);
1530         kfree(ctx);
1531         return ret;
1532 }
1533
1534 static int coda_release(struct file *file)
1535 {
1536         struct coda_dev *dev = video_drvdata(file);
1537         struct coda_ctx *ctx = fh_to_ctx(file->private_data);
1538
1539         v4l2_dbg(1, coda_debug, &dev->v4l2_dev, "Releasing instance %p\n",
1540                  ctx);
1541
1542         coda_lock(ctx);
1543         list_del(&ctx->list);
1544         coda_unlock(ctx);
1545
1546         dma_free_coherent(&dev->plat_dev->dev, CODA_PARA_BUF_SIZE,
1547                 ctx->parabuf.vaddr, ctx->parabuf.paddr);
1548         v4l2_m2m_ctx_release(ctx->m2m_ctx);
1549         v4l2_ctrl_handler_free(&ctx->ctrls);
1550         clk_disable_unprepare(dev->clk_per);
1551         clk_disable_unprepare(dev->clk_ahb);
1552         v4l2_fh_del(&ctx->fh);
1553         v4l2_fh_exit(&ctx->fh);
1554         clear_bit(ctx->idx, &dev->instance_mask);
1555         kfree(ctx);
1556
1557         return 0;
1558 }
1559
1560 static unsigned int coda_poll(struct file *file,
1561                                  struct poll_table_struct *wait)
1562 {
1563         struct coda_ctx *ctx = fh_to_ctx(file->private_data);
1564         int ret;
1565
1566         coda_lock(ctx);
1567         ret = v4l2_m2m_poll(file, ctx->m2m_ctx, wait);
1568         coda_unlock(ctx);
1569         return ret;
1570 }
1571
1572 static int coda_mmap(struct file *file, struct vm_area_struct *vma)
1573 {
1574         struct coda_ctx *ctx = fh_to_ctx(file->private_data);
1575
1576         return v4l2_m2m_mmap(file, ctx->m2m_ctx, vma);
1577 }
1578
1579 static const struct v4l2_file_operations coda_fops = {
1580         .owner          = THIS_MODULE,
1581         .open           = coda_open,
1582         .release        = coda_release,
1583         .poll           = coda_poll,
1584         .unlocked_ioctl = video_ioctl2,
1585         .mmap           = coda_mmap,
1586 };
1587
1588 static irqreturn_t coda_irq_handler(int irq, void *data)
1589 {
1590         struct vb2_buffer *src_buf, *dst_buf;
1591         struct coda_dev *dev = data;
1592         u32 wr_ptr, start_ptr;
1593         struct coda_ctx *ctx;
1594
1595         cancel_delayed_work(&dev->timeout);
1596
1597         /* read status register to attend the IRQ */
1598         coda_read(dev, CODA_REG_BIT_INT_STATUS);
1599         coda_write(dev, CODA_REG_BIT_INT_CLEAR_SET,
1600                       CODA_REG_BIT_INT_CLEAR);
1601
1602         ctx = v4l2_m2m_get_curr_priv(dev->m2m_dev);
1603         if (ctx == NULL) {
1604                 v4l2_err(&dev->v4l2_dev, "Instance released before the end of transaction\n");
1605                 return IRQ_HANDLED;
1606         }
1607
1608         if (ctx->aborting) {
1609                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1610                          "task has been aborted\n");
1611                 return IRQ_HANDLED;
1612         }
1613
1614         if (coda_isbusy(ctx->dev)) {
1615                 v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev,
1616                          "coda is still busy!!!!\n");
1617                 return IRQ_NONE;
1618         }
1619
1620         complete(&dev->done);
1621
1622         src_buf = v4l2_m2m_src_buf_remove(ctx->m2m_ctx);
1623         dst_buf = v4l2_m2m_dst_buf_remove(ctx->m2m_ctx);
1624
1625         /* Get results from the coda */
1626         coda_read(dev, CODA_RET_ENC_PIC_TYPE);
1627         start_ptr = coda_read(dev, CODA_CMD_ENC_PIC_BB_START);
1628         wr_ptr = coda_read(dev, CODA_REG_BIT_WR_PTR(ctx->idx));
1629         /* Calculate bytesused field */
1630         if (dst_buf->v4l2_buf.sequence == 0) {
1631                 dst_buf->v4l2_planes[0].bytesused = (wr_ptr - start_ptr) +
1632                                                 ctx->vpu_header_size[0] +
1633                                                 ctx->vpu_header_size[1] +
1634                                                 ctx->vpu_header_size[2];
1635         } else {
1636                 dst_buf->v4l2_planes[0].bytesused = (wr_ptr - start_ptr);
1637         }
1638
1639         v4l2_dbg(1, coda_debug, &ctx->dev->v4l2_dev, "frame size = %u\n",
1640                  wr_ptr - start_ptr);
1641
1642         coda_read(dev, CODA_RET_ENC_PIC_SLICE_NUM);
1643         coda_read(dev, CODA_RET_ENC_PIC_FLAG);
1644
1645         if (src_buf->v4l2_buf.flags & V4L2_BUF_FLAG_KEYFRAME) {
1646                 dst_buf->v4l2_buf.flags |= V4L2_BUF_FLAG_KEYFRAME;
1647                 dst_buf->v4l2_buf.flags &= ~V4L2_BUF_FLAG_PFRAME;
1648         } else {
1649                 dst_buf->v4l2_buf.flags |= V4L2_BUF_FLAG_PFRAME;
1650                 dst_buf->v4l2_buf.flags &= ~V4L2_BUF_FLAG_KEYFRAME;
1651         }
1652
1653         dst_buf->v4l2_buf.timestamp = src_buf->v4l2_buf.timestamp;
1654         dst_buf->v4l2_buf.timecode = src_buf->v4l2_buf.timecode;
1655
1656         v4l2_m2m_buf_done(src_buf, VB2_BUF_STATE_DONE);
1657         v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_DONE);
1658
1659         ctx->gopcounter--;
1660         if (ctx->gopcounter < 0)
1661                 ctx->gopcounter = ctx->params.gop_size - 1;
1662
1663         v4l2_dbg(1, coda_debug, &dev->v4l2_dev,
1664                 "job finished: encoding frame (%d) (%s)\n",
1665                 dst_buf->v4l2_buf.sequence,
1666                 (dst_buf->v4l2_buf.flags & V4L2_BUF_FLAG_KEYFRAME) ?
1667                 "KEYFRAME" : "PFRAME");
1668
1669         v4l2_m2m_job_finish(ctx->dev->m2m_dev, ctx->m2m_ctx);
1670
1671         return IRQ_HANDLED;
1672 }
1673
1674 static void coda_timeout(struct work_struct *work)
1675 {
1676         struct coda_ctx *ctx;
1677         struct coda_dev *dev = container_of(to_delayed_work(work),
1678                                             struct coda_dev, timeout);
1679
1680         if (completion_done(&dev->done))
1681                 return;
1682
1683         complete(&dev->done);
1684
1685         dev_err(&dev->plat_dev->dev, "CODA PIC_RUN timeout, stopping all streams\n");
1686
1687         mutex_lock(&dev->dev_mutex);
1688         list_for_each_entry(ctx, &dev->instances, list) {
1689                 v4l2_m2m_streamoff(NULL, ctx->m2m_ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
1690                 v4l2_m2m_streamoff(NULL, ctx->m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1691         }
1692         mutex_unlock(&dev->dev_mutex);
1693 }
1694
1695 static u32 coda_supported_firmwares[] = {
1696         CODA_FIRMWARE_VERNUM(CODA_DX6, 2, 2, 5),
1697         CODA_FIRMWARE_VERNUM(CODA_7541, 13, 4, 29),
1698 };
1699
1700 static bool coda_firmware_supported(u32 vernum)
1701 {
1702         int i;
1703
1704         for (i = 0; i < ARRAY_SIZE(coda_supported_firmwares); i++)
1705                 if (vernum == coda_supported_firmwares[i])
1706                         return true;
1707         return false;
1708 }
1709
1710 static char *coda_product_name(int product)
1711 {
1712         static char buf[9];
1713
1714         switch (product) {
1715         case CODA_DX6:
1716                 return "CodaDx6";
1717         case CODA_7541:
1718                 return "CODA7541";
1719         default:
1720                 snprintf(buf, sizeof(buf), "(0x%04x)", product);
1721                 return buf;
1722         }
1723 }
1724
1725 static int coda_hw_init(struct coda_dev *dev)
1726 {
1727         u16 product, major, minor, release;
1728         u32 data;
1729         u16 *p;
1730         int i;
1731
1732         clk_prepare_enable(dev->clk_per);
1733         clk_prepare_enable(dev->clk_ahb);
1734
1735         /*
1736          * Copy the first CODA_ISRAM_SIZE in the internal SRAM.
1737          * The 16-bit chars in the code buffer are in memory access
1738          * order, re-sort them to CODA order for register download.
1739          * Data in this SRAM survives a reboot.
1740          */
1741         p = (u16 *)dev->codebuf.vaddr;
1742         if (dev->devtype->product == CODA_DX6) {
1743                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++)  {
1744                         data = CODA_DOWN_ADDRESS_SET(i) |
1745                                 CODA_DOWN_DATA_SET(p[i ^ 1]);
1746                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
1747                 }
1748         } else {
1749                 for (i = 0; i < (CODA_ISRAM_SIZE / 2); i++) {
1750                         data = CODA_DOWN_ADDRESS_SET(i) |
1751                                 CODA_DOWN_DATA_SET(p[round_down(i, 4) +
1752                                                         3 - (i % 4)]);
1753                         coda_write(dev, data, CODA_REG_BIT_CODE_DOWN);
1754                 }
1755         }
1756
1757         /* Tell the BIT where to find everything it needs */
1758         coda_write(dev, dev->workbuf.paddr,
1759                       CODA_REG_BIT_WORK_BUF_ADDR);
1760         coda_write(dev, dev->codebuf.paddr,
1761                       CODA_REG_BIT_CODE_BUF_ADDR);
1762         coda_write(dev, 0, CODA_REG_BIT_CODE_RUN);
1763
1764         /* Set default values */
1765         switch (dev->devtype->product) {
1766         case CODA_DX6:
1767                 coda_write(dev, CODADX6_STREAM_BUF_PIC_FLUSH, CODA_REG_BIT_STREAM_CTRL);
1768                 break;
1769         default:
1770                 coda_write(dev, CODA7_STREAM_BUF_PIC_FLUSH, CODA_REG_BIT_STREAM_CTRL);
1771         }
1772         coda_write(dev, 0, CODA_REG_BIT_FRAME_MEM_CTRL);
1773
1774         if (dev->devtype->product != CODA_DX6)
1775                 coda_write(dev, 0, CODA7_REG_BIT_AXI_SRAM_USE);
1776
1777         coda_write(dev, CODA_INT_INTERRUPT_ENABLE,
1778                       CODA_REG_BIT_INT_ENABLE);
1779
1780         /* Reset VPU and start processor */
1781         data = coda_read(dev, CODA_REG_BIT_CODE_RESET);
1782         data |= CODA_REG_RESET_ENABLE;
1783         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
1784         udelay(10);
1785         data &= ~CODA_REG_RESET_ENABLE;
1786         coda_write(dev, data, CODA_REG_BIT_CODE_RESET);
1787         coda_write(dev, CODA_REG_RUN_ENABLE, CODA_REG_BIT_CODE_RUN);
1788
1789         /* Load firmware */
1790         coda_write(dev, 0, CODA_CMD_FIRMWARE_VERNUM);
1791         coda_write(dev, CODA_REG_BIT_BUSY_FLAG, CODA_REG_BIT_BUSY);
1792         coda_write(dev, 0, CODA_REG_BIT_RUN_INDEX);
1793         coda_write(dev, 0, CODA_REG_BIT_RUN_COD_STD);
1794         coda_write(dev, CODA_COMMAND_FIRMWARE_GET, CODA_REG_BIT_RUN_COMMAND);
1795         if (coda_wait_timeout(dev)) {
1796                 clk_disable_unprepare(dev->clk_per);
1797                 clk_disable_unprepare(dev->clk_ahb);
1798                 v4l2_err(&dev->v4l2_dev, "firmware get command error\n");
1799                 return -EIO;
1800         }
1801
1802         /* Check we are compatible with the loaded firmware */
1803         data = coda_read(dev, CODA_CMD_FIRMWARE_VERNUM);
1804         product = CODA_FIRMWARE_PRODUCT(data);
1805         major = CODA_FIRMWARE_MAJOR(data);
1806         minor = CODA_FIRMWARE_MINOR(data);
1807         release = CODA_FIRMWARE_RELEASE(data);
1808
1809         clk_disable_unprepare(dev->clk_per);
1810         clk_disable_unprepare(dev->clk_ahb);
1811
1812         if (product != dev->devtype->product) {
1813                 v4l2_err(&dev->v4l2_dev, "Wrong firmware. Hw: %s, Fw: %s,"
1814                          " Version: %u.%u.%u\n",
1815                          coda_product_name(dev->devtype->product),
1816                          coda_product_name(product), major, minor, release);
1817                 return -EINVAL;
1818         }
1819
1820         v4l2_info(&dev->v4l2_dev, "Initialized %s.\n",
1821                   coda_product_name(product));
1822
1823         if (coda_firmware_supported(data)) {
1824                 v4l2_info(&dev->v4l2_dev, "Firmware version: %u.%u.%u\n",
1825                           major, minor, release);
1826         } else {
1827                 v4l2_warn(&dev->v4l2_dev, "Unsupported firmware version: "
1828                           "%u.%u.%u\n", major, minor, release);
1829         }
1830
1831         return 0;
1832 }
1833
1834 static void coda_fw_callback(const struct firmware *fw, void *context)
1835 {
1836         struct coda_dev *dev = context;
1837         struct platform_device *pdev = dev->plat_dev;
1838         int ret;
1839
1840         if (!fw) {
1841                 v4l2_err(&dev->v4l2_dev, "firmware request failed\n");
1842                 return;
1843         }
1844
1845         /* allocate auxiliary per-device code buffer for the BIT processor */
1846         dev->codebuf.size = fw->size;
1847         dev->codebuf.vaddr = dma_alloc_coherent(&pdev->dev, fw->size,
1848                                                     &dev->codebuf.paddr,
1849                                                     GFP_KERNEL);
1850         if (!dev->codebuf.vaddr) {
1851                 dev_err(&pdev->dev, "failed to allocate code buffer\n");
1852                 return;
1853         }
1854
1855         /* Copy the whole firmware image to the code buffer */
1856         memcpy(dev->codebuf.vaddr, fw->data, fw->size);
1857         release_firmware(fw);
1858
1859         ret = coda_hw_init(dev);
1860         if (ret) {
1861                 v4l2_err(&dev->v4l2_dev, "HW initialization failed\n");
1862                 return;
1863         }
1864
1865         dev->vfd.fops   = &coda_fops,
1866         dev->vfd.ioctl_ops      = &coda_ioctl_ops;
1867         dev->vfd.release        = video_device_release_empty,
1868         dev->vfd.lock   = &dev->dev_mutex;
1869         dev->vfd.v4l2_dev       = &dev->v4l2_dev;
1870         dev->vfd.vfl_dir        = VFL_DIR_M2M;
1871         snprintf(dev->vfd.name, sizeof(dev->vfd.name), "%s", CODA_NAME);
1872         video_set_drvdata(&dev->vfd, dev);
1873
1874         dev->alloc_ctx = vb2_dma_contig_init_ctx(&pdev->dev);
1875         if (IS_ERR(dev->alloc_ctx)) {
1876                 v4l2_err(&dev->v4l2_dev, "Failed to alloc vb2 context\n");
1877                 return;
1878         }
1879
1880         dev->m2m_dev = v4l2_m2m_init(&coda_m2m_ops);
1881         if (IS_ERR(dev->m2m_dev)) {
1882                 v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n");
1883                 goto rel_ctx;
1884         }
1885
1886         ret = video_register_device(&dev->vfd, VFL_TYPE_GRABBER, 0);
1887         if (ret) {
1888                 v4l2_err(&dev->v4l2_dev, "Failed to register video device\n");
1889                 goto rel_m2m;
1890         }
1891         v4l2_info(&dev->v4l2_dev, "codec registered as /dev/video%d\n",
1892                   dev->vfd.num);
1893
1894         return;
1895
1896 rel_m2m:
1897         v4l2_m2m_release(dev->m2m_dev);
1898 rel_ctx:
1899         vb2_dma_contig_cleanup_ctx(dev->alloc_ctx);
1900 }
1901
1902 static int coda_firmware_request(struct coda_dev *dev)
1903 {
1904         char *fw = dev->devtype->firmware;
1905
1906         dev_dbg(&dev->plat_dev->dev, "requesting firmware '%s' for %s\n", fw,
1907                 coda_product_name(dev->devtype->product));
1908
1909         return request_firmware_nowait(THIS_MODULE, true,
1910                 fw, &dev->plat_dev->dev, GFP_KERNEL, dev, coda_fw_callback);
1911 }
1912
1913 enum coda_platform {
1914         CODA_IMX27,
1915         CODA_IMX53,
1916 };
1917
1918 static const struct coda_devtype coda_devdata[] = {
1919         [CODA_IMX27] = {
1920                 .firmware    = "v4l-codadx6-imx27.bin",
1921                 .product     = CODA_DX6,
1922                 .formats     = codadx6_formats,
1923                 .num_formats = ARRAY_SIZE(codadx6_formats),
1924         },
1925         [CODA_IMX53] = {
1926                 .firmware    = "v4l-coda7541-imx53.bin",
1927                 .product     = CODA_7541,
1928                 .formats     = coda7_formats,
1929                 .num_formats = ARRAY_SIZE(coda7_formats),
1930         },
1931 };
1932
1933 static struct platform_device_id coda_platform_ids[] = {
1934         { .name = "coda-imx27", .driver_data = CODA_IMX27 },
1935         { .name = "coda-imx53", .driver_data = CODA_IMX53 },
1936         { /* sentinel */ }
1937 };
1938 MODULE_DEVICE_TABLE(platform, coda_platform_ids);
1939
1940 #ifdef CONFIG_OF
1941 static const struct of_device_id coda_dt_ids[] = {
1942         { .compatible = "fsl,imx27-vpu", .data = &coda_platform_ids[CODA_IMX27] },
1943         { .compatible = "fsl,imx53-vpu", .data = &coda_devdata[CODA_IMX53] },
1944         { /* sentinel */ }
1945 };
1946 MODULE_DEVICE_TABLE(of, coda_dt_ids);
1947 #endif
1948
1949 static int coda_probe(struct platform_device *pdev)
1950 {
1951         const struct of_device_id *of_id =
1952                         of_match_device(of_match_ptr(coda_dt_ids), &pdev->dev);
1953         const struct platform_device_id *pdev_id;
1954         struct coda_platform_data *pdata = pdev->dev.platform_data;
1955         struct device_node *np = pdev->dev.of_node;
1956         struct gen_pool *pool;
1957         struct coda_dev *dev;
1958         struct resource *res;
1959         int ret, irq;
1960
1961         dev = devm_kzalloc(&pdev->dev, sizeof *dev, GFP_KERNEL);
1962         if (!dev) {
1963                 dev_err(&pdev->dev, "Not enough memory for %s\n",
1964                         CODA_NAME);
1965                 return -ENOMEM;
1966         }
1967
1968         spin_lock_init(&dev->irqlock);
1969         INIT_LIST_HEAD(&dev->instances);
1970         INIT_DELAYED_WORK(&dev->timeout, coda_timeout);
1971         init_completion(&dev->done);
1972         complete(&dev->done);
1973
1974         dev->plat_dev = pdev;
1975         dev->clk_per = devm_clk_get(&pdev->dev, "per");
1976         if (IS_ERR(dev->clk_per)) {
1977                 dev_err(&pdev->dev, "Could not get per clock\n");
1978                 return PTR_ERR(dev->clk_per);
1979         }
1980
1981         dev->clk_ahb = devm_clk_get(&pdev->dev, "ahb");
1982         if (IS_ERR(dev->clk_ahb)) {
1983                 dev_err(&pdev->dev, "Could not get ahb clock\n");
1984                 return PTR_ERR(dev->clk_ahb);
1985         }
1986
1987         /* Get  memory for physical registers */
1988         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1989         if (res == NULL) {
1990                 dev_err(&pdev->dev, "failed to get memory region resource\n");
1991                 return -ENOENT;
1992         }
1993
1994         dev->regs_base = devm_ioremap_resource(&pdev->dev, res);
1995         if (IS_ERR(dev->regs_base))
1996                 return PTR_ERR(dev->regs_base);
1997
1998         /* IRQ */
1999         irq = platform_get_irq(pdev, 0);
2000         if (irq < 0) {
2001                 dev_err(&pdev->dev, "failed to get irq resource\n");
2002                 return -ENOENT;
2003         }
2004
2005         if (devm_request_irq(&pdev->dev, irq, coda_irq_handler,
2006                 0, CODA_NAME, dev) < 0) {
2007                 dev_err(&pdev->dev, "failed to request irq\n");
2008                 return -ENOENT;
2009         }
2010
2011         /* Get IRAM pool from device tree or platform data */
2012         pool = of_get_named_gen_pool(np, "iram", 0);
2013         if (!pool && pdata)
2014                 pool = dev_get_gen_pool(pdata->iram_dev);
2015         if (!pool) {
2016                 dev_err(&pdev->dev, "iram pool not available\n");
2017                 return -ENOMEM;
2018         }
2019         dev->iram_pool = pool;
2020
2021         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
2022         if (ret)
2023                 return ret;
2024
2025         mutex_init(&dev->dev_mutex);
2026
2027         pdev_id = of_id ? of_id->data : platform_get_device_id(pdev);
2028
2029         if (of_id) {
2030                 dev->devtype = of_id->data;
2031         } else if (pdev_id) {
2032                 dev->devtype = &coda_devdata[pdev_id->driver_data];
2033         } else {
2034                 v4l2_device_unregister(&dev->v4l2_dev);
2035                 return -EINVAL;
2036         }
2037
2038         /* allocate auxiliary per-device buffers for the BIT processor */
2039         switch (dev->devtype->product) {
2040         case CODA_DX6:
2041                 dev->workbuf.size = CODADX6_WORK_BUF_SIZE;
2042                 break;
2043         default:
2044                 dev->workbuf.size = CODA7_WORK_BUF_SIZE;
2045         }
2046         dev->workbuf.vaddr = dma_alloc_coherent(&pdev->dev, dev->workbuf.size,
2047                                                     &dev->workbuf.paddr,
2048                                                     GFP_KERNEL);
2049         if (!dev->workbuf.vaddr) {
2050                 dev_err(&pdev->dev, "failed to allocate work buffer\n");
2051                 v4l2_device_unregister(&dev->v4l2_dev);
2052                 return -ENOMEM;
2053         }
2054
2055         if (dev->devtype->product == CODA_DX6)
2056                 dev->iram_size = CODADX6_IRAM_SIZE;
2057         else
2058                 dev->iram_size = CODA7_IRAM_SIZE;
2059         dev->iram_vaddr = gen_pool_alloc(dev->iram_pool, dev->iram_size);
2060         if (!dev->iram_vaddr) {
2061                 dev_err(&pdev->dev, "unable to alloc iram\n");
2062                 return -ENOMEM;
2063         }
2064         dev->iram_paddr = gen_pool_virt_to_phys(dev->iram_pool,
2065                                                 dev->iram_vaddr);
2066
2067         platform_set_drvdata(pdev, dev);
2068
2069         return coda_firmware_request(dev);
2070 }
2071
2072 static int coda_remove(struct platform_device *pdev)
2073 {
2074         struct coda_dev *dev = platform_get_drvdata(pdev);
2075
2076         video_unregister_device(&dev->vfd);
2077         if (dev->m2m_dev)
2078                 v4l2_m2m_release(dev->m2m_dev);
2079         if (dev->alloc_ctx)
2080                 vb2_dma_contig_cleanup_ctx(dev->alloc_ctx);
2081         v4l2_device_unregister(&dev->v4l2_dev);
2082         if (dev->iram_vaddr)
2083                 gen_pool_free(dev->iram_pool, dev->iram_vaddr, dev->iram_size);
2084         if (dev->codebuf.vaddr)
2085                 dma_free_coherent(&pdev->dev, dev->codebuf.size,
2086                                   &dev->codebuf.vaddr, dev->codebuf.paddr);
2087         if (dev->workbuf.vaddr)
2088                 dma_free_coherent(&pdev->dev, dev->workbuf.size, &dev->workbuf.vaddr,
2089                           dev->workbuf.paddr);
2090         return 0;
2091 }
2092
2093 static struct platform_driver coda_driver = {
2094         .probe  = coda_probe,
2095         .remove = coda_remove,
2096         .driver = {
2097                 .name   = CODA_NAME,
2098                 .owner  = THIS_MODULE,
2099                 .of_match_table = of_match_ptr(coda_dt_ids),
2100         },
2101         .id_table = coda_platform_ids,
2102 };
2103
2104 module_platform_driver(coda_driver);
2105
2106 MODULE_LICENSE("GPL");
2107 MODULE_AUTHOR("Javier Martin <javier.martin@vista-silicon.com>");
2108 MODULE_DESCRIPTION("Coda multi-standard codec V4L2 driver");