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