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