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