linux/drivers/media/platform/stm32/stm32-dcmi.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Driver for STM32 Digital Camera Memory Interface
   4 *
   5 * Copyright (C) STMicroelectronics SA 2017
   6 * Authors: Yannick Fertre <yannick.fertre@st.com>
   7 *          Hugues Fruchet <hugues.fruchet@st.com>
   8 *          for STMicroelectronics.
   9 *
  10 * This driver is based on atmel_isi.c
  11 *
  12 */
  13
  14#include <linux/clk.h>
  15#include <linux/completion.h>
  16#include <linux/delay.h>
  17#include <linux/dmaengine.h>
  18#include <linux/init.h>
  19#include <linux/interrupt.h>
  20#include <linux/kernel.h>
  21#include <linux/module.h>
  22#include <linux/of.h>
  23#include <linux/of_device.h>
  24#include <linux/of_graph.h>
  25#include <linux/pinctrl/consumer.h>
  26#include <linux/platform_device.h>
  27#include <linux/pm_runtime.h>
  28#include <linux/reset.h>
  29#include <linux/videodev2.h>
  30
  31#include <media/v4l2-ctrls.h>
  32#include <media/v4l2-dev.h>
  33#include <media/v4l2-device.h>
  34#include <media/v4l2-event.h>
  35#include <media/v4l2-fwnode.h>
  36#include <media/v4l2-image-sizes.h>
  37#include <media/v4l2-ioctl.h>
  38#include <media/v4l2-rect.h>
  39#include <media/videobuf2-dma-contig.h>
  40
  41#define DRV_NAME "stm32-dcmi"
  42
  43/* Registers offset for DCMI */
  44#define DCMI_CR         0x00 /* Control Register */
  45#define DCMI_SR         0x04 /* Status Register */
  46#define DCMI_RIS        0x08 /* Raw Interrupt Status register */
  47#define DCMI_IER        0x0C /* Interrupt Enable Register */
  48#define DCMI_MIS        0x10 /* Masked Interrupt Status register */
  49#define DCMI_ICR        0x14 /* Interrupt Clear Register */
  50#define DCMI_ESCR       0x18 /* Embedded Synchronization Code Register */
  51#define DCMI_ESUR       0x1C /* Embedded Synchronization Unmask Register */
  52#define DCMI_CWSTRT     0x20 /* Crop Window STaRT */
  53#define DCMI_CWSIZE     0x24 /* Crop Window SIZE */
  54#define DCMI_DR         0x28 /* Data Register */
  55#define DCMI_IDR        0x2C /* IDentifier Register */
  56
  57/* Bits definition for control register (DCMI_CR) */
  58#define CR_CAPTURE      BIT(0)
  59#define CR_CM           BIT(1)
  60#define CR_CROP         BIT(2)
  61#define CR_JPEG         BIT(3)
  62#define CR_ESS          BIT(4)
  63#define CR_PCKPOL       BIT(5)
  64#define CR_HSPOL        BIT(6)
  65#define CR_VSPOL        BIT(7)
  66#define CR_FCRC_0       BIT(8)
  67#define CR_FCRC_1       BIT(9)
  68#define CR_EDM_0        BIT(10)
  69#define CR_EDM_1        BIT(11)
  70#define CR_ENABLE       BIT(14)
  71
  72/* Bits definition for status register (DCMI_SR) */
  73#define SR_HSYNC        BIT(0)
  74#define SR_VSYNC        BIT(1)
  75#define SR_FNE          BIT(2)
  76
  77/*
  78 * Bits definition for interrupt registers
  79 * (DCMI_RIS, DCMI_IER, DCMI_MIS, DCMI_ICR)
  80 */
  81#define IT_FRAME        BIT(0)
  82#define IT_OVR          BIT(1)
  83#define IT_ERR          BIT(2)
  84#define IT_VSYNC        BIT(3)
  85#define IT_LINE         BIT(4)
  86
  87enum state {
  88        STOPPED = 0,
  89        WAIT_FOR_BUFFER,
  90        RUNNING,
  91};
  92
  93#define MIN_WIDTH       16U
  94#define MAX_WIDTH       2592U
  95#define MIN_HEIGHT      16U
  96#define MAX_HEIGHT      2592U
  97
  98#define TIMEOUT_MS      1000
  99
 100#define OVERRUN_ERROR_THRESHOLD 3
 101
 102struct dcmi_graph_entity {
 103        struct v4l2_async_subdev asd;
 104
 105        struct device_node *remote_node;
 106        struct v4l2_subdev *source;
 107};
 108
 109struct dcmi_format {
 110        u32     fourcc;
 111        u32     mbus_code;
 112        u8      bpp;
 113};
 114
 115struct dcmi_framesize {
 116        u32     width;
 117        u32     height;
 118};
 119
 120struct dcmi_buf {
 121        struct vb2_v4l2_buffer  vb;
 122        bool                    prepared;
 123        dma_addr_t              paddr;
 124        size_t                  size;
 125        struct list_head        list;
 126};
 127
 128struct stm32_dcmi {
 129        /* Protects the access of variables shared within the interrupt */
 130        spinlock_t                      irqlock;
 131        struct device                   *dev;
 132        void __iomem                    *regs;
 133        struct resource                 *res;
 134        struct reset_control            *rstc;
 135        int                             sequence;
 136        struct list_head                buffers;
 137        struct dcmi_buf                 *active;
 138
 139        struct v4l2_device              v4l2_dev;
 140        struct video_device             *vdev;
 141        struct v4l2_async_notifier      notifier;
 142        struct dcmi_graph_entity        entity;
 143        struct v4l2_format              fmt;
 144        struct v4l2_rect                crop;
 145        bool                            do_crop;
 146
 147        const struct dcmi_format        **sd_formats;
 148        unsigned int                    num_of_sd_formats;
 149        const struct dcmi_format        *sd_format;
 150        struct dcmi_framesize           *sd_framesizes;
 151        unsigned int                    num_of_sd_framesizes;
 152        struct dcmi_framesize           sd_framesize;
 153        struct v4l2_rect                sd_bounds;
 154
 155        /* Protect this data structure */
 156        struct mutex                    lock;
 157        struct vb2_queue                queue;
 158
 159        struct v4l2_fwnode_bus_parallel bus;
 160        struct completion               complete;
 161        struct clk                      *mclk;
 162        enum state                      state;
 163        struct dma_chan                 *dma_chan;
 164        dma_cookie_t                    dma_cookie;
 165        u32                             misr;
 166        int                             errors_count;
 167        int                             overrun_count;
 168        int                             buffers_count;
 169
 170        /* Ensure DMA operations atomicity */
 171        struct mutex                    dma_lock;
 172
 173        struct media_device             mdev;
 174        struct media_pad                vid_cap_pad;
 175        struct media_pipeline           pipeline;
 176};
 177
 178static inline struct stm32_dcmi *notifier_to_dcmi(struct v4l2_async_notifier *n)
 179{
 180        return container_of(n, struct stm32_dcmi, notifier);
 181}
 182
 183static inline u32 reg_read(void __iomem *base, u32 reg)
 184{
 185        return readl_relaxed(base + reg);
 186}
 187
 188static inline void reg_write(void __iomem *base, u32 reg, u32 val)
 189{
 190        writel_relaxed(val, base + reg);
 191}
 192
 193static inline void reg_set(void __iomem *base, u32 reg, u32 mask)
 194{
 195        reg_write(base, reg, reg_read(base, reg) | mask);
 196}
 197
 198static inline void reg_clear(void __iomem *base, u32 reg, u32 mask)
 199{
 200        reg_write(base, reg, reg_read(base, reg) & ~mask);
 201}
 202
 203static int dcmi_start_capture(struct stm32_dcmi *dcmi, struct dcmi_buf *buf);
 204
 205static void dcmi_buffer_done(struct stm32_dcmi *dcmi,
 206                             struct dcmi_buf *buf,
 207                             size_t bytesused,
 208                             int err)
 209{
 210        struct vb2_v4l2_buffer *vbuf;
 211
 212        if (!buf)
 213                return;
 214
 215        list_del_init(&buf->list);
 216
 217        vbuf = &buf->vb;
 218
 219        vbuf->sequence = dcmi->sequence++;
 220        vbuf->field = V4L2_FIELD_NONE;
 221        vbuf->vb2_buf.timestamp = ktime_get_ns();
 222        vb2_set_plane_payload(&vbuf->vb2_buf, 0, bytesused);
 223        vb2_buffer_done(&vbuf->vb2_buf,
 224                        err ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
 225        dev_dbg(dcmi->dev, "buffer[%d] done seq=%d, bytesused=%zu\n",
 226                vbuf->vb2_buf.index, vbuf->sequence, bytesused);
 227
 228        dcmi->buffers_count++;
 229        dcmi->active = NULL;
 230}
 231
 232static int dcmi_restart_capture(struct stm32_dcmi *dcmi)
 233{
 234        struct dcmi_buf *buf;
 235
 236        spin_lock_irq(&dcmi->irqlock);
 237
 238        if (dcmi->state != RUNNING) {
 239                spin_unlock_irq(&dcmi->irqlock);
 240                return -EINVAL;
 241        }
 242
 243        /* Restart a new DMA transfer with next buffer */
 244        if (list_empty(&dcmi->buffers)) {
 245                dev_dbg(dcmi->dev, "Capture restart is deferred to next buffer queueing\n");
 246                dcmi->state = WAIT_FOR_BUFFER;
 247                spin_unlock_irq(&dcmi->irqlock);
 248                return 0;
 249        }
 250        buf = list_entry(dcmi->buffers.next, struct dcmi_buf, list);
 251        dcmi->active = buf;
 252
 253        spin_unlock_irq(&dcmi->irqlock);
 254
 255        return dcmi_start_capture(dcmi, buf);
 256}
 257
 258static void dcmi_dma_callback(void *param)
 259{
 260        struct stm32_dcmi *dcmi = (struct stm32_dcmi *)param;
 261        struct dma_tx_state state;
 262        enum dma_status status;
 263        struct dcmi_buf *buf = dcmi->active;
 264
 265        spin_lock_irq(&dcmi->irqlock);
 266
 267        /* Check DMA status */
 268        status = dmaengine_tx_status(dcmi->dma_chan, dcmi->dma_cookie, &state);
 269
 270        switch (status) {
 271        case DMA_IN_PROGRESS:
 272                dev_dbg(dcmi->dev, "%s: Received DMA_IN_PROGRESS\n", __func__);
 273                break;
 274        case DMA_PAUSED:
 275                dev_err(dcmi->dev, "%s: Received DMA_PAUSED\n", __func__);
 276                break;
 277        case DMA_ERROR:
 278                dev_err(dcmi->dev, "%s: Received DMA_ERROR\n", __func__);
 279
 280                /* Return buffer to V4L2 in error state */
 281                dcmi_buffer_done(dcmi, buf, 0, -EIO);
 282                break;
 283        case DMA_COMPLETE:
 284                dev_dbg(dcmi->dev, "%s: Received DMA_COMPLETE\n", __func__);
 285
 286                /* Return buffer to V4L2 */
 287                dcmi_buffer_done(dcmi, buf, buf->size, 0);
 288
 289                spin_unlock_irq(&dcmi->irqlock);
 290
 291                /* Restart capture */
 292                if (dcmi_restart_capture(dcmi))
 293                        dev_err(dcmi->dev, "%s: Cannot restart capture on DMA complete\n",
 294                                __func__);
 295                return;
 296        default:
 297                dev_err(dcmi->dev, "%s: Received unknown status\n", __func__);
 298                break;
 299        }
 300
 301        spin_unlock_irq(&dcmi->irqlock);
 302}
 303
 304static int dcmi_start_dma(struct stm32_dcmi *dcmi,
 305                          struct dcmi_buf *buf)
 306{
 307        struct dma_async_tx_descriptor *desc = NULL;
 308        struct dma_slave_config config;
 309        int ret;
 310
 311        memset(&config, 0, sizeof(config));
 312
 313        config.src_addr = (dma_addr_t)dcmi->res->start + DCMI_DR;
 314        config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
 315        config.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
 316        config.dst_maxburst = 4;
 317
 318        /* Configure DMA channel */
 319        ret = dmaengine_slave_config(dcmi->dma_chan, &config);
 320        if (ret < 0) {
 321                dev_err(dcmi->dev, "%s: DMA channel config failed (%d)\n",
 322                        __func__, ret);
 323                return ret;
 324        }
 325
 326        /*
 327         * Avoid call of dmaengine_terminate_all() between
 328         * dmaengine_prep_slave_single() and dmaengine_submit()
 329         * by locking the whole DMA submission sequence
 330         */
 331        mutex_lock(&dcmi->dma_lock);
 332
 333        /* Prepare a DMA transaction */
 334        desc = dmaengine_prep_slave_single(dcmi->dma_chan, buf->paddr,
 335                                           buf->size,
 336                                           DMA_DEV_TO_MEM,
 337                                           DMA_PREP_INTERRUPT);
 338        if (!desc) {
 339                dev_err(dcmi->dev, "%s: DMA dmaengine_prep_slave_single failed for buffer phy=%pad size=%zu\n",
 340                        __func__, &buf->paddr, buf->size);
 341                mutex_unlock(&dcmi->dma_lock);
 342                return -EINVAL;
 343        }
 344
 345        /* Set completion callback routine for notification */
 346        desc->callback = dcmi_dma_callback;
 347        desc->callback_param = dcmi;
 348
 349        /* Push current DMA transaction in the pending queue */
 350        dcmi->dma_cookie = dmaengine_submit(desc);
 351        if (dma_submit_error(dcmi->dma_cookie)) {
 352                dev_err(dcmi->dev, "%s: DMA submission failed\n", __func__);
 353                mutex_unlock(&dcmi->dma_lock);
 354                return -ENXIO;
 355        }
 356
 357        mutex_unlock(&dcmi->dma_lock);
 358
 359        dma_async_issue_pending(dcmi->dma_chan);
 360
 361        return 0;
 362}
 363
 364static int dcmi_start_capture(struct stm32_dcmi *dcmi, struct dcmi_buf *buf)
 365{
 366        int ret;
 367
 368        if (!buf)
 369                return -EINVAL;
 370
 371        ret = dcmi_start_dma(dcmi, buf);
 372        if (ret) {
 373                dcmi->errors_count++;
 374                return ret;
 375        }
 376
 377        /* Enable capture */
 378        reg_set(dcmi->regs, DCMI_CR, CR_CAPTURE);
 379
 380        return 0;
 381}
 382
 383static void dcmi_set_crop(struct stm32_dcmi *dcmi)
 384{
 385        u32 size, start;
 386
 387        /* Crop resolution */
 388        size = ((dcmi->crop.height - 1) << 16) |
 389                ((dcmi->crop.width << 1) - 1);
 390        reg_write(dcmi->regs, DCMI_CWSIZE, size);
 391
 392        /* Crop start point */
 393        start = ((dcmi->crop.top) << 16) |
 394                 ((dcmi->crop.left << 1));
 395        reg_write(dcmi->regs, DCMI_CWSTRT, start);
 396
 397        dev_dbg(dcmi->dev, "Cropping to %ux%u@%u:%u\n",
 398                dcmi->crop.width, dcmi->crop.height,
 399                dcmi->crop.left, dcmi->crop.top);
 400
 401        /* Enable crop */
 402        reg_set(dcmi->regs, DCMI_CR, CR_CROP);
 403}
 404
 405static void dcmi_process_jpeg(struct stm32_dcmi *dcmi)
 406{
 407        struct dma_tx_state state;
 408        enum dma_status status;
 409        struct dcmi_buf *buf = dcmi->active;
 410
 411        if (!buf)
 412                return;
 413
 414        /*
 415         * Because of variable JPEG buffer size sent by sensor,
 416         * DMA transfer never completes due to transfer size never reached.
 417         * In order to ensure that all the JPEG data are transferred
 418         * in active buffer memory, DMA is drained.
 419         * Then DMA tx status gives the amount of data transferred
 420         * to memory, which is then returned to V4L2 through the active
 421         * buffer payload.
 422         */
 423
 424        /* Drain DMA */
 425        dmaengine_synchronize(dcmi->dma_chan);
 426
 427        /* Get DMA residue to get JPEG size */
 428        status = dmaengine_tx_status(dcmi->dma_chan, dcmi->dma_cookie, &state);
 429        if (status != DMA_ERROR && state.residue < buf->size) {
 430                /* Return JPEG buffer to V4L2 with received JPEG buffer size */
 431                dcmi_buffer_done(dcmi, buf, buf->size - state.residue, 0);
 432        } else {
 433                dcmi->errors_count++;
 434                dev_err(dcmi->dev, "%s: Cannot get JPEG size from DMA\n",
 435                        __func__);
 436                /* Return JPEG buffer to V4L2 in ERROR state */
 437                dcmi_buffer_done(dcmi, buf, 0, -EIO);
 438        }
 439
 440        /* Abort DMA operation */
 441        dmaengine_terminate_all(dcmi->dma_chan);
 442
 443        /* Restart capture */
 444        if (dcmi_restart_capture(dcmi))
 445                dev_err(dcmi->dev, "%s: Cannot restart capture on JPEG received\n",
 446                        __func__);
 447}
 448
 449static irqreturn_t dcmi_irq_thread(int irq, void *arg)
 450{
 451        struct stm32_dcmi *dcmi = arg;
 452
 453        spin_lock_irq(&dcmi->irqlock);
 454
 455        if (dcmi->misr & IT_OVR) {
 456                dcmi->overrun_count++;
 457                if (dcmi->overrun_count > OVERRUN_ERROR_THRESHOLD)
 458                        dcmi->errors_count++;
 459        }
 460        if (dcmi->misr & IT_ERR)
 461                dcmi->errors_count++;
 462
 463        if (dcmi->sd_format->fourcc == V4L2_PIX_FMT_JPEG &&
 464            dcmi->misr & IT_FRAME) {
 465                /* JPEG received */
 466                spin_unlock_irq(&dcmi->irqlock);
 467                dcmi_process_jpeg(dcmi);
 468                return IRQ_HANDLED;
 469        }
 470
 471        spin_unlock_irq(&dcmi->irqlock);
 472        return IRQ_HANDLED;
 473}
 474
 475static irqreturn_t dcmi_irq_callback(int irq, void *arg)
 476{
 477        struct stm32_dcmi *dcmi = arg;
 478        unsigned long flags;
 479
 480        spin_lock_irqsave(&dcmi->irqlock, flags);
 481
 482        dcmi->misr = reg_read(dcmi->regs, DCMI_MIS);
 483
 484        /* Clear interrupt */
 485        reg_set(dcmi->regs, DCMI_ICR, IT_FRAME | IT_OVR | IT_ERR);
 486
 487        spin_unlock_irqrestore(&dcmi->irqlock, flags);
 488
 489        return IRQ_WAKE_THREAD;
 490}
 491
 492static int dcmi_queue_setup(struct vb2_queue *vq,
 493                            unsigned int *nbuffers,
 494                            unsigned int *nplanes,
 495                            unsigned int sizes[],
 496                            struct device *alloc_devs[])
 497{
 498        struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
 499        unsigned int size;
 500
 501        size = dcmi->fmt.fmt.pix.sizeimage;
 502
 503        /* Make sure the image size is large enough */
 504        if (*nplanes)
 505                return sizes[0] < size ? -EINVAL : 0;
 506
 507        *nplanes = 1;
 508        sizes[0] = size;
 509
 510        dev_dbg(dcmi->dev, "Setup queue, count=%d, size=%d\n",
 511                *nbuffers, size);
 512
 513        return 0;
 514}
 515
 516static int dcmi_buf_init(struct vb2_buffer *vb)
 517{
 518        struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
 519        struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
 520
 521        INIT_LIST_HEAD(&buf->list);
 522
 523        return 0;
 524}
 525
 526static int dcmi_buf_prepare(struct vb2_buffer *vb)
 527{
 528        struct stm32_dcmi *dcmi =  vb2_get_drv_priv(vb->vb2_queue);
 529        struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
 530        struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
 531        unsigned long size;
 532
 533        size = dcmi->fmt.fmt.pix.sizeimage;
 534
 535        if (vb2_plane_size(vb, 0) < size) {
 536                dev_err(dcmi->dev, "%s data will not fit into plane (%lu < %lu)\n",
 537                        __func__, vb2_plane_size(vb, 0), size);
 538                return -EINVAL;
 539        }
 540
 541        vb2_set_plane_payload(vb, 0, size);
 542
 543        if (!buf->prepared) {
 544                /* Get memory addresses */
 545                buf->paddr =
 546                        vb2_dma_contig_plane_dma_addr(&buf->vb.vb2_buf, 0);
 547                buf->size = vb2_plane_size(&buf->vb.vb2_buf, 0);
 548                buf->prepared = true;
 549
 550                vb2_set_plane_payload(&buf->vb.vb2_buf, 0, buf->size);
 551
 552                dev_dbg(dcmi->dev, "buffer[%d] phy=%pad size=%zu\n",
 553                        vb->index, &buf->paddr, buf->size);
 554        }
 555
 556        return 0;
 557}
 558
 559static void dcmi_buf_queue(struct vb2_buffer *vb)
 560{
 561        struct stm32_dcmi *dcmi =  vb2_get_drv_priv(vb->vb2_queue);
 562        struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
 563        struct dcmi_buf *buf = container_of(vbuf, struct dcmi_buf, vb);
 564
 565        spin_lock_irq(&dcmi->irqlock);
 566
 567        /* Enqueue to video buffers list */
 568        list_add_tail(&buf->list, &dcmi->buffers);
 569
 570        if (dcmi->state == WAIT_FOR_BUFFER) {
 571                dcmi->state = RUNNING;
 572                dcmi->active = buf;
 573
 574                dev_dbg(dcmi->dev, "Starting capture on buffer[%d] queued\n",
 575                        buf->vb.vb2_buf.index);
 576
 577                spin_unlock_irq(&dcmi->irqlock);
 578                if (dcmi_start_capture(dcmi, buf))
 579                        dev_err(dcmi->dev, "%s: Cannot restart capture on overflow or error\n",
 580                                __func__);
 581                return;
 582        }
 583
 584        spin_unlock_irq(&dcmi->irqlock);
 585}
 586
 587static struct media_entity *dcmi_find_source(struct stm32_dcmi *dcmi)
 588{
 589        struct media_entity *entity = &dcmi->vdev->entity;
 590        struct media_pad *pad;
 591
 592        /* Walk searching for entity having no sink */
 593        while (1) {
 594                pad = &entity->pads[0];
 595                if (!(pad->flags & MEDIA_PAD_FL_SINK))
 596                        break;
 597
 598                pad = media_entity_remote_pad(pad);
 599                if (!pad || !is_media_entity_v4l2_subdev(pad->entity))
 600                        break;
 601
 602                entity = pad->entity;
 603        }
 604
 605        return entity;
 606}
 607
 608static int dcmi_pipeline_s_fmt(struct stm32_dcmi *dcmi,
 609                               struct v4l2_subdev_pad_config *pad_cfg,
 610                               struct v4l2_subdev_format *format)
 611{
 612        struct media_entity *entity = &dcmi->entity.source->entity;
 613        struct v4l2_subdev *subdev;
 614        struct media_pad *sink_pad = NULL;
 615        struct media_pad *src_pad = NULL;
 616        struct media_pad *pad = NULL;
 617        struct v4l2_subdev_format fmt = *format;
 618        bool found = false;
 619        int ret;
 620
 621        /*
 622         * Starting from sensor subdevice, walk within
 623         * pipeline and set format on each subdevice
 624         */
 625        while (1) {
 626                unsigned int i;
 627
 628                /* Search if current entity has a source pad */
 629                for (i = 0; i < entity->num_pads; i++) {
 630                        pad = &entity->pads[i];
 631                        if (pad->flags & MEDIA_PAD_FL_SOURCE) {
 632                                src_pad = pad;
 633                                found = true;
 634                                break;
 635                        }
 636                }
 637                if (!found)
 638                        break;
 639
 640                subdev = media_entity_to_v4l2_subdev(entity);
 641
 642                /* Propagate format on sink pad if any, otherwise source pad */
 643                if (sink_pad)
 644                        pad = sink_pad;
 645
 646                dev_dbg(dcmi->dev, "\"%s\":%d pad format set to 0x%x %ux%u\n",
 647                        subdev->name, pad->index, format->format.code,
 648                        format->format.width, format->format.height);
 649
 650                fmt.pad = pad->index;
 651                ret = v4l2_subdev_call(subdev, pad, set_fmt, pad_cfg, &fmt);
 652                if (ret < 0) {
 653                        dev_err(dcmi->dev, "%s: Failed to set format 0x%x %ux%u on \"%s\":%d pad (%d)\n",
 654                                __func__, format->format.code,
 655                                format->format.width, format->format.height,
 656                                subdev->name, pad->index, ret);
 657                        return ret;
 658                }
 659
 660                if (fmt.format.code != format->format.code ||
 661                    fmt.format.width != format->format.width ||
 662                    fmt.format.height != format->format.height) {
 663                        dev_dbg(dcmi->dev, "\"%s\":%d pad format has been changed to 0x%x %ux%u\n",
 664                                subdev->name, pad->index, fmt.format.code,
 665                                fmt.format.width, fmt.format.height);
 666                }
 667
 668                /* Walk to next entity */
 669                sink_pad = media_entity_remote_pad(src_pad);
 670                if (!sink_pad || !is_media_entity_v4l2_subdev(sink_pad->entity))
 671                        break;
 672
 673                entity = sink_pad->entity;
 674        }
 675        *format = fmt;
 676
 677        return 0;
 678}
 679
 680static int dcmi_pipeline_s_stream(struct stm32_dcmi *dcmi, int state)
 681{
 682        struct media_entity *entity = &dcmi->vdev->entity;
 683        struct v4l2_subdev *subdev;
 684        struct media_pad *pad;
 685        int ret;
 686
 687        /* Start/stop all entities within pipeline */
 688        while (1) {
 689                pad = &entity->pads[0];
 690                if (!(pad->flags & MEDIA_PAD_FL_SINK))
 691                        break;
 692
 693                pad = media_entity_remote_pad(pad);
 694                if (!pad || !is_media_entity_v4l2_subdev(pad->entity))
 695                        break;
 696
 697                entity = pad->entity;
 698                subdev = media_entity_to_v4l2_subdev(entity);
 699
 700                ret = v4l2_subdev_call(subdev, video, s_stream, state);
 701                if (ret < 0 && ret != -ENOIOCTLCMD) {
 702                        dev_err(dcmi->dev, "%s: \"%s\" failed to %s streaming (%d)\n",
 703                                __func__, subdev->name,
 704                                state ? "start" : "stop", ret);
 705                        return ret;
 706                }
 707
 708                dev_dbg(dcmi->dev, "\"%s\" is %s\n",
 709                        subdev->name, state ? "started" : "stopped");
 710        }
 711
 712        return 0;
 713}
 714
 715static int dcmi_pipeline_start(struct stm32_dcmi *dcmi)
 716{
 717        return dcmi_pipeline_s_stream(dcmi, 1);
 718}
 719
 720static void dcmi_pipeline_stop(struct stm32_dcmi *dcmi)
 721{
 722        dcmi_pipeline_s_stream(dcmi, 0);
 723}
 724
 725static int dcmi_start_streaming(struct vb2_queue *vq, unsigned int count)
 726{
 727        struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
 728        struct dcmi_buf *buf, *node;
 729        u32 val = 0;
 730        int ret;
 731
 732        ret = pm_runtime_get_sync(dcmi->dev);
 733        if (ret < 0) {
 734                dev_err(dcmi->dev, "%s: Failed to start streaming, cannot get sync (%d)\n",
 735                        __func__, ret);
 736                goto err_pm_put;
 737        }
 738
 739        ret = media_pipeline_start(&dcmi->vdev->entity, &dcmi->pipeline);
 740        if (ret < 0) {
 741                dev_err(dcmi->dev, "%s: Failed to start streaming, media pipeline start error (%d)\n",
 742                        __func__, ret);
 743                goto err_pm_put;
 744        }
 745
 746        ret = dcmi_pipeline_start(dcmi);
 747        if (ret)
 748                goto err_media_pipeline_stop;
 749
 750        spin_lock_irq(&dcmi->irqlock);
 751
 752        /* Set bus width */
 753        switch (dcmi->bus.bus_width) {
 754        case 14:
 755                val |= CR_EDM_0 | CR_EDM_1;
 756                break;
 757        case 12:
 758                val |= CR_EDM_1;
 759                break;
 760        case 10:
 761                val |= CR_EDM_0;
 762                break;
 763        default:
 764                /* Set bus width to 8 bits by default */
 765                break;
 766        }
 767
 768        /* Set vertical synchronization polarity */
 769        if (dcmi->bus.flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH)
 770                val |= CR_VSPOL;
 771
 772        /* Set horizontal synchronization polarity */
 773        if (dcmi->bus.flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH)
 774                val |= CR_HSPOL;
 775
 776        /* Set pixel clock polarity */
 777        if (dcmi->bus.flags & V4L2_MBUS_PCLK_SAMPLE_RISING)
 778                val |= CR_PCKPOL;
 779
 780        reg_write(dcmi->regs, DCMI_CR, val);
 781
 782        /* Set crop */
 783        if (dcmi->do_crop)
 784                dcmi_set_crop(dcmi);
 785
 786        /* Enable jpeg capture */
 787        if (dcmi->sd_format->fourcc == V4L2_PIX_FMT_JPEG)
 788                reg_set(dcmi->regs, DCMI_CR, CR_CM);/* Snapshot mode */
 789
 790        /* Enable dcmi */
 791        reg_set(dcmi->regs, DCMI_CR, CR_ENABLE);
 792
 793        dcmi->sequence = 0;
 794        dcmi->errors_count = 0;
 795        dcmi->overrun_count = 0;
 796        dcmi->buffers_count = 0;
 797
 798        /*
 799         * Start transfer if at least one buffer has been queued,
 800         * otherwise transfer is deferred at buffer queueing
 801         */
 802        if (list_empty(&dcmi->buffers)) {
 803                dev_dbg(dcmi->dev, "Start streaming is deferred to next buffer queueing\n");
 804                dcmi->state = WAIT_FOR_BUFFER;
 805                spin_unlock_irq(&dcmi->irqlock);
 806                return 0;
 807        }
 808
 809        buf = list_entry(dcmi->buffers.next, struct dcmi_buf, list);
 810        dcmi->active = buf;
 811
 812        dcmi->state = RUNNING;
 813
 814        dev_dbg(dcmi->dev, "Start streaming, starting capture\n");
 815
 816        spin_unlock_irq(&dcmi->irqlock);
 817        ret = dcmi_start_capture(dcmi, buf);
 818        if (ret) {
 819                dev_err(dcmi->dev, "%s: Start streaming failed, cannot start capture\n",
 820                        __func__);
 821                goto err_pipeline_stop;
 822        }
 823
 824        /* Enable interruptions */
 825        if (dcmi->sd_format->fourcc == V4L2_PIX_FMT_JPEG)
 826                reg_set(dcmi->regs, DCMI_IER, IT_FRAME | IT_OVR | IT_ERR);
 827        else
 828                reg_set(dcmi->regs, DCMI_IER, IT_OVR | IT_ERR);
 829
 830        return 0;
 831
 832err_pipeline_stop:
 833        dcmi_pipeline_stop(dcmi);
 834
 835err_media_pipeline_stop:
 836        media_pipeline_stop(&dcmi->vdev->entity);
 837
 838err_pm_put:
 839        pm_runtime_put(dcmi->dev);
 840        spin_lock_irq(&dcmi->irqlock);
 841        /*
 842         * Return all buffers to vb2 in QUEUED state.
 843         * This will give ownership back to userspace
 844         */
 845        list_for_each_entry_safe(buf, node, &dcmi->buffers, list) {
 846                list_del_init(&buf->list);
 847                vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
 848        }
 849        dcmi->active = NULL;
 850        spin_unlock_irq(&dcmi->irqlock);
 851
 852        return ret;
 853}
 854
 855static void dcmi_stop_streaming(struct vb2_queue *vq)
 856{
 857        struct stm32_dcmi *dcmi = vb2_get_drv_priv(vq);
 858        struct dcmi_buf *buf, *node;
 859
 860        dcmi_pipeline_stop(dcmi);
 861
 862        media_pipeline_stop(&dcmi->vdev->entity);
 863
 864        spin_lock_irq(&dcmi->irqlock);
 865
 866        /* Disable interruptions */
 867        reg_clear(dcmi->regs, DCMI_IER, IT_FRAME | IT_OVR | IT_ERR);
 868
 869        /* Disable DCMI */
 870        reg_clear(dcmi->regs, DCMI_CR, CR_ENABLE);
 871
 872        /* Return all queued buffers to vb2 in ERROR state */
 873        list_for_each_entry_safe(buf, node, &dcmi->buffers, list) {
 874                list_del_init(&buf->list);
 875                vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
 876        }
 877
 878        dcmi->active = NULL;
 879        dcmi->state = STOPPED;
 880
 881        spin_unlock_irq(&dcmi->irqlock);
 882
 883        /* Stop all pending DMA operations */
 884        mutex_lock(&dcmi->dma_lock);
 885        dmaengine_terminate_all(dcmi->dma_chan);
 886        mutex_unlock(&dcmi->dma_lock);
 887
 888        pm_runtime_put(dcmi->dev);
 889
 890        if (dcmi->errors_count)
 891                dev_warn(dcmi->dev, "Some errors found while streaming: errors=%d (overrun=%d), buffers=%d\n",
 892                         dcmi->errors_count, dcmi->overrun_count,
 893                         dcmi->buffers_count);
 894        dev_dbg(dcmi->dev, "Stop streaming, errors=%d (overrun=%d), buffers=%d\n",
 895                dcmi->errors_count, dcmi->overrun_count,
 896                dcmi->buffers_count);
 897}
 898
 899static const struct vb2_ops dcmi_video_qops = {
 900        .queue_setup            = dcmi_queue_setup,
 901        .buf_init               = dcmi_buf_init,
 902        .buf_prepare            = dcmi_buf_prepare,
 903        .buf_queue              = dcmi_buf_queue,
 904        .start_streaming        = dcmi_start_streaming,
 905        .stop_streaming         = dcmi_stop_streaming,
 906        .wait_prepare           = vb2_ops_wait_prepare,
 907        .wait_finish            = vb2_ops_wait_finish,
 908};
 909
 910static int dcmi_g_fmt_vid_cap(struct file *file, void *priv,
 911                              struct v4l2_format *fmt)
 912{
 913        struct stm32_dcmi *dcmi = video_drvdata(file);
 914
 915        *fmt = dcmi->fmt;
 916
 917        return 0;
 918}
 919
 920static const struct dcmi_format *find_format_by_fourcc(struct stm32_dcmi *dcmi,
 921                                                       unsigned int fourcc)
 922{
 923        unsigned int num_formats = dcmi->num_of_sd_formats;
 924        const struct dcmi_format *fmt;
 925        unsigned int i;
 926
 927        for (i = 0; i < num_formats; i++) {
 928                fmt = dcmi->sd_formats[i];
 929                if (fmt->fourcc == fourcc)
 930                        return fmt;
 931        }
 932
 933        return NULL;
 934}
 935
 936static void __find_outer_frame_size(struct stm32_dcmi *dcmi,
 937                                    struct v4l2_pix_format *pix,
 938                                    struct dcmi_framesize *framesize)
 939{
 940        struct dcmi_framesize *match = NULL;
 941        unsigned int i;
 942        unsigned int min_err = UINT_MAX;
 943
 944        for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
 945                struct dcmi_framesize *fsize = &dcmi->sd_framesizes[i];
 946                int w_err = (fsize->width - pix->width);
 947                int h_err = (fsize->height - pix->height);
 948                int err = w_err + h_err;
 949
 950                if (w_err >= 0 && h_err >= 0 && err < min_err) {
 951                        min_err = err;
 952                        match = fsize;
 953                }
 954        }
 955        if (!match)
 956                match = &dcmi->sd_framesizes[0];
 957
 958        *framesize = *match;
 959}
 960
 961static int dcmi_try_fmt(struct stm32_dcmi *dcmi, struct v4l2_format *f,
 962                        const struct dcmi_format **sd_format,
 963                        struct dcmi_framesize *sd_framesize)
 964{
 965        const struct dcmi_format *sd_fmt;
 966        struct dcmi_framesize sd_fsize;
 967        struct v4l2_pix_format *pix = &f->fmt.pix;
 968        struct v4l2_subdev_pad_config pad_cfg;
 969        struct v4l2_subdev_format format = {
 970                .which = V4L2_SUBDEV_FORMAT_TRY,
 971        };
 972        bool do_crop;
 973        int ret;
 974
 975        sd_fmt = find_format_by_fourcc(dcmi, pix->pixelformat);
 976        if (!sd_fmt) {
 977                if (!dcmi->num_of_sd_formats)
 978                        return -ENODATA;
 979
 980                sd_fmt = dcmi->sd_formats[dcmi->num_of_sd_formats - 1];
 981                pix->pixelformat = sd_fmt->fourcc;
 982        }
 983
 984        /* Limit to hardware capabilities */
 985        pix->width = clamp(pix->width, MIN_WIDTH, MAX_WIDTH);
 986        pix->height = clamp(pix->height, MIN_HEIGHT, MAX_HEIGHT);
 987
 988        /* No crop if JPEG is requested */
 989        do_crop = dcmi->do_crop && (pix->pixelformat != V4L2_PIX_FMT_JPEG);
 990
 991        if (do_crop && dcmi->num_of_sd_framesizes) {
 992                struct dcmi_framesize outer_sd_fsize;
 993                /*
 994                 * If crop is requested and sensor have discrete frame sizes,
 995                 * select the frame size that is just larger than request
 996                 */
 997                __find_outer_frame_size(dcmi, pix, &outer_sd_fsize);
 998                pix->width = outer_sd_fsize.width;
 999                pix->height = outer_sd_fsize.height;
1000        }
1001
1002        v4l2_fill_mbus_format(&format.format, pix, sd_fmt->mbus_code);
1003        ret = v4l2_subdev_call(dcmi->entity.source, pad, set_fmt,
1004                               &pad_cfg, &format);
1005        if (ret < 0)
1006                return ret;
1007
1008        /* Update pix regarding to what sensor can do */
1009        v4l2_fill_pix_format(pix, &format.format);
1010
1011        /* Save resolution that sensor can actually do */
1012        sd_fsize.width = pix->width;
1013        sd_fsize.height = pix->height;
1014
1015        if (do_crop) {
1016                struct v4l2_rect c = dcmi->crop;
1017                struct v4l2_rect max_rect;
1018
1019                /*
1020                 * Adjust crop by making the intersection between
1021                 * format resolution request and crop request
1022                 */
1023                max_rect.top = 0;
1024                max_rect.left = 0;
1025                max_rect.width = pix->width;
1026                max_rect.height = pix->height;
1027                v4l2_rect_map_inside(&c, &max_rect);
1028                c.top  = clamp_t(s32, c.top, 0, pix->height - c.height);
1029                c.left = clamp_t(s32, c.left, 0, pix->width - c.width);
1030                dcmi->crop = c;
1031
1032                /* Adjust format resolution request to crop */
1033                pix->width = dcmi->crop.width;
1034                pix->height = dcmi->crop.height;
1035        }
1036
1037        pix->field = V4L2_FIELD_NONE;
1038        pix->bytesperline = pix->width * sd_fmt->bpp;
1039        pix->sizeimage = pix->bytesperline * pix->height;
1040
1041        if (sd_format)
1042                *sd_format = sd_fmt;
1043        if (sd_framesize)
1044                *sd_framesize = sd_fsize;
1045
1046        return 0;
1047}
1048
1049static int dcmi_set_fmt(struct stm32_dcmi *dcmi, struct v4l2_format *f)
1050{
1051        struct v4l2_subdev_format format = {
1052                .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1053        };
1054        const struct dcmi_format *sd_format;
1055        struct dcmi_framesize sd_framesize;
1056        struct v4l2_mbus_framefmt *mf = &format.format;
1057        struct v4l2_pix_format *pix = &f->fmt.pix;
1058        int ret;
1059
1060        /*
1061         * Try format, fmt.width/height could have been changed
1062         * to match sensor capability or crop request
1063         * sd_format & sd_framesize will contain what subdev
1064         * can do for this request.
1065         */
1066        ret = dcmi_try_fmt(dcmi, f, &sd_format, &sd_framesize);
1067        if (ret)
1068                return ret;
1069
1070        /* Disable crop if JPEG is requested */
1071        if (pix->pixelformat == V4L2_PIX_FMT_JPEG)
1072                dcmi->do_crop = false;
1073
1074        /* pix to mbus format */
1075        v4l2_fill_mbus_format(mf, pix,
1076                              sd_format->mbus_code);
1077        mf->width = sd_framesize.width;
1078        mf->height = sd_framesize.height;
1079
1080        ret = dcmi_pipeline_s_fmt(dcmi, NULL, &format);
1081        if (ret < 0)
1082                return ret;
1083
1084        dev_dbg(dcmi->dev, "Sensor format set to 0x%x %ux%u\n",
1085                mf->code, mf->width, mf->height);
1086        dev_dbg(dcmi->dev, "Buffer format set to %4.4s %ux%u\n",
1087                (char *)&pix->pixelformat,
1088                pix->width, pix->height);
1089
1090        dcmi->fmt = *f;
1091        dcmi->sd_format = sd_format;
1092        dcmi->sd_framesize = sd_framesize;
1093
1094        return 0;
1095}
1096
1097static int dcmi_s_fmt_vid_cap(struct file *file, void *priv,
1098                              struct v4l2_format *f)
1099{
1100        struct stm32_dcmi *dcmi = video_drvdata(file);
1101
1102        if (vb2_is_streaming(&dcmi->queue))
1103                return -EBUSY;
1104
1105        return dcmi_set_fmt(dcmi, f);
1106}
1107
1108static int dcmi_try_fmt_vid_cap(struct file *file, void *priv,
1109                                struct v4l2_format *f)
1110{
1111        struct stm32_dcmi *dcmi = video_drvdata(file);
1112
1113        return dcmi_try_fmt(dcmi, f, NULL, NULL);
1114}
1115
1116static int dcmi_enum_fmt_vid_cap(struct file *file, void  *priv,
1117                                 struct v4l2_fmtdesc *f)
1118{
1119        struct stm32_dcmi *dcmi = video_drvdata(file);
1120
1121        if (f->index >= dcmi->num_of_sd_formats)
1122                return -EINVAL;
1123
1124        f->pixelformat = dcmi->sd_formats[f->index]->fourcc;
1125        return 0;
1126}
1127
1128static int dcmi_get_sensor_format(struct stm32_dcmi *dcmi,
1129                                  struct v4l2_pix_format *pix)
1130{
1131        struct v4l2_subdev_format fmt = {
1132                .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1133        };
1134        int ret;
1135
1136        ret = v4l2_subdev_call(dcmi->entity.source, pad, get_fmt, NULL, &fmt);
1137        if (ret)
1138                return ret;
1139
1140        v4l2_fill_pix_format(pix, &fmt.format);
1141
1142        return 0;
1143}
1144
1145static int dcmi_set_sensor_format(struct stm32_dcmi *dcmi,
1146                                  struct v4l2_pix_format *pix)
1147{
1148        const struct dcmi_format *sd_fmt;
1149        struct v4l2_subdev_format format = {
1150                .which = V4L2_SUBDEV_FORMAT_TRY,
1151        };
1152        struct v4l2_subdev_pad_config pad_cfg;
1153        int ret;
1154
1155        sd_fmt = find_format_by_fourcc(dcmi, pix->pixelformat);
1156        if (!sd_fmt) {
1157                if (!dcmi->num_of_sd_formats)
1158                        return -ENODATA;
1159
1160                sd_fmt = dcmi->sd_formats[dcmi->num_of_sd_formats - 1];
1161                pix->pixelformat = sd_fmt->fourcc;
1162        }
1163
1164        v4l2_fill_mbus_format(&format.format, pix, sd_fmt->mbus_code);
1165        ret = v4l2_subdev_call(dcmi->entity.source, pad, set_fmt,
1166                               &pad_cfg, &format);
1167        if (ret < 0)
1168                return ret;
1169
1170        return 0;
1171}
1172
1173static int dcmi_get_sensor_bounds(struct stm32_dcmi *dcmi,
1174                                  struct v4l2_rect *r)
1175{
1176        struct v4l2_subdev_selection bounds = {
1177                .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1178                .target = V4L2_SEL_TGT_CROP_BOUNDS,
1179        };
1180        unsigned int max_width, max_height, max_pixsize;
1181        struct v4l2_pix_format pix;
1182        unsigned int i;
1183        int ret;
1184
1185        /*
1186         * Get sensor bounds first
1187         */
1188        ret = v4l2_subdev_call(dcmi->entity.source, pad, get_selection,
1189                               NULL, &bounds);
1190        if (!ret)
1191                *r = bounds.r;
1192        if (ret != -ENOIOCTLCMD)
1193                return ret;
1194
1195        /*
1196         * If selection is not implemented,
1197         * fallback by enumerating sensor frame sizes
1198         * and take the largest one
1199         */
1200        max_width = 0;
1201        max_height = 0;
1202        max_pixsize = 0;
1203        for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
1204                struct dcmi_framesize *fsize = &dcmi->sd_framesizes[i];
1205                unsigned int pixsize = fsize->width * fsize->height;
1206
1207                if (pixsize > max_pixsize) {
1208                        max_pixsize = pixsize;
1209                        max_width = fsize->width;
1210                        max_height = fsize->height;
1211                }
1212        }
1213        if (max_pixsize > 0) {
1214                r->top = 0;
1215                r->left = 0;
1216                r->width = max_width;
1217                r->height = max_height;
1218                return 0;
1219        }
1220
1221        /*
1222         * If frame sizes enumeration is not implemented,
1223         * fallback by getting current sensor frame size
1224         */
1225        ret = dcmi_get_sensor_format(dcmi, &pix);
1226        if (ret)
1227                return ret;
1228
1229        r->top = 0;
1230        r->left = 0;
1231        r->width = pix.width;
1232        r->height = pix.height;
1233
1234        return 0;
1235}
1236
1237static int dcmi_g_selection(struct file *file, void *fh,
1238                            struct v4l2_selection *s)
1239{
1240        struct stm32_dcmi *dcmi = video_drvdata(file);
1241
1242        if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1243                return -EINVAL;
1244
1245        switch (s->target) {
1246        case V4L2_SEL_TGT_CROP_DEFAULT:
1247        case V4L2_SEL_TGT_CROP_BOUNDS:
1248                s->r = dcmi->sd_bounds;
1249                return 0;
1250        case V4L2_SEL_TGT_CROP:
1251                if (dcmi->do_crop) {
1252                        s->r = dcmi->crop;
1253                } else {
1254                        s->r.top = 0;
1255                        s->r.left = 0;
1256                        s->r.width = dcmi->fmt.fmt.pix.width;
1257                        s->r.height = dcmi->fmt.fmt.pix.height;
1258                }
1259                break;
1260        default:
1261                return -EINVAL;
1262        }
1263
1264        return 0;
1265}
1266
1267static int dcmi_s_selection(struct file *file, void *priv,
1268                            struct v4l2_selection *s)
1269{
1270        struct stm32_dcmi *dcmi = video_drvdata(file);
1271        struct v4l2_rect r = s->r;
1272        struct v4l2_rect max_rect;
1273        struct v4l2_pix_format pix;
1274
1275        if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1276            s->target != V4L2_SEL_TGT_CROP)
1277                return -EINVAL;
1278
1279        /* Reset sensor resolution to max resolution */
1280        pix.pixelformat = dcmi->fmt.fmt.pix.pixelformat;
1281        pix.width = dcmi->sd_bounds.width;
1282        pix.height = dcmi->sd_bounds.height;
1283        dcmi_set_sensor_format(dcmi, &pix);
1284
1285        /*
1286         * Make the intersection between
1287         * sensor resolution
1288         * and crop request
1289         */
1290        max_rect.top = 0;
1291        max_rect.left = 0;
1292        max_rect.width = pix.width;
1293        max_rect.height = pix.height;
1294        v4l2_rect_map_inside(&r, &max_rect);
1295        r.top  = clamp_t(s32, r.top, 0, pix.height - r.height);
1296        r.left = clamp_t(s32, r.left, 0, pix.width - r.width);
1297
1298        if (!(r.top == dcmi->sd_bounds.top &&
1299              r.left == dcmi->sd_bounds.left &&
1300              r.width == dcmi->sd_bounds.width &&
1301              r.height == dcmi->sd_bounds.height)) {
1302                /* Crop if request is different than sensor resolution */
1303                dcmi->do_crop = true;
1304                dcmi->crop = r;
1305                dev_dbg(dcmi->dev, "s_selection: crop %ux%u@(%u,%u) from %ux%u\n",
1306                        r.width, r.height, r.left, r.top,
1307                        pix.width, pix.height);
1308        } else {
1309                /* Disable crop */
1310                dcmi->do_crop = false;
1311                dev_dbg(dcmi->dev, "s_selection: crop is disabled\n");
1312        }
1313
1314        s->r = r;
1315        return 0;
1316}
1317
1318static int dcmi_querycap(struct file *file, void *priv,
1319                         struct v4l2_capability *cap)
1320{
1321        strscpy(cap->driver, DRV_NAME, sizeof(cap->driver));
1322        strscpy(cap->card, "STM32 Camera Memory Interface",
1323                sizeof(cap->card));
1324        strscpy(cap->bus_info, "platform:dcmi", sizeof(cap->bus_info));
1325        return 0;
1326}
1327
1328static int dcmi_enum_input(struct file *file, void *priv,
1329                           struct v4l2_input *i)
1330{
1331        if (i->index != 0)
1332                return -EINVAL;
1333
1334        i->type = V4L2_INPUT_TYPE_CAMERA;
1335        strscpy(i->name, "Camera", sizeof(i->name));
1336        return 0;
1337}
1338
1339static int dcmi_g_input(struct file *file, void *priv, unsigned int *i)
1340{
1341        *i = 0;
1342        return 0;
1343}
1344
1345static int dcmi_s_input(struct file *file, void *priv, unsigned int i)
1346{
1347        if (i > 0)
1348                return -EINVAL;
1349        return 0;
1350}
1351
1352static int dcmi_enum_framesizes(struct file *file, void *fh,
1353                                struct v4l2_frmsizeenum *fsize)
1354{
1355        struct stm32_dcmi *dcmi = video_drvdata(file);
1356        const struct dcmi_format *sd_fmt;
1357        struct v4l2_subdev_frame_size_enum fse = {
1358                .index = fsize->index,
1359                .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1360        };
1361        int ret;
1362
1363        sd_fmt = find_format_by_fourcc(dcmi, fsize->pixel_format);
1364        if (!sd_fmt)
1365                return -EINVAL;
1366
1367        fse.code = sd_fmt->mbus_code;
1368
1369        ret = v4l2_subdev_call(dcmi->entity.source, pad, enum_frame_size,
1370                               NULL, &fse);
1371        if (ret)
1372                return ret;
1373
1374        fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1375        fsize->discrete.width = fse.max_width;
1376        fsize->discrete.height = fse.max_height;
1377
1378        return 0;
1379}
1380
1381static int dcmi_g_parm(struct file *file, void *priv,
1382                       struct v4l2_streamparm *p)
1383{
1384        struct stm32_dcmi *dcmi = video_drvdata(file);
1385
1386        return v4l2_g_parm_cap(video_devdata(file), dcmi->entity.source, p);
1387}
1388
1389static int dcmi_s_parm(struct file *file, void *priv,
1390                       struct v4l2_streamparm *p)
1391{
1392        struct stm32_dcmi *dcmi = video_drvdata(file);
1393
1394        return v4l2_s_parm_cap(video_devdata(file), dcmi->entity.source, p);
1395}
1396
1397static int dcmi_enum_frameintervals(struct file *file, void *fh,
1398                                    struct v4l2_frmivalenum *fival)
1399{
1400        struct stm32_dcmi *dcmi = video_drvdata(file);
1401        const struct dcmi_format *sd_fmt;
1402        struct v4l2_subdev_frame_interval_enum fie = {
1403                .index = fival->index,
1404                .width = fival->width,
1405                .height = fival->height,
1406                .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1407        };
1408        int ret;
1409
1410        sd_fmt = find_format_by_fourcc(dcmi, fival->pixel_format);
1411        if (!sd_fmt)
1412                return -EINVAL;
1413
1414        fie.code = sd_fmt->mbus_code;
1415
1416        ret = v4l2_subdev_call(dcmi->entity.source, pad,
1417                               enum_frame_interval, NULL, &fie);
1418        if (ret)
1419                return ret;
1420
1421        fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1422        fival->discrete = fie.interval;
1423
1424        return 0;
1425}
1426
1427static const struct of_device_id stm32_dcmi_of_match[] = {
1428        { .compatible = "st,stm32-dcmi"},
1429        { /* end node */ },
1430};
1431MODULE_DEVICE_TABLE(of, stm32_dcmi_of_match);
1432
1433static int dcmi_open(struct file *file)
1434{
1435        struct stm32_dcmi *dcmi = video_drvdata(file);
1436        struct v4l2_subdev *sd = dcmi->entity.source;
1437        int ret;
1438
1439        if (mutex_lock_interruptible(&dcmi->lock))
1440                return -ERESTARTSYS;
1441
1442        ret = v4l2_fh_open(file);
1443        if (ret < 0)
1444                goto unlock;
1445
1446        if (!v4l2_fh_is_singular_file(file))
1447                goto fh_rel;
1448
1449        ret = v4l2_subdev_call(sd, core, s_power, 1);
1450        if (ret < 0 && ret != -ENOIOCTLCMD)
1451                goto fh_rel;
1452
1453        ret = dcmi_set_fmt(dcmi, &dcmi->fmt);
1454        if (ret)
1455                v4l2_subdev_call(sd, core, s_power, 0);
1456fh_rel:
1457        if (ret)
1458                v4l2_fh_release(file);
1459unlock:
1460        mutex_unlock(&dcmi->lock);
1461        return ret;
1462}
1463
1464static int dcmi_release(struct file *file)
1465{
1466        struct stm32_dcmi *dcmi = video_drvdata(file);
1467        struct v4l2_subdev *sd = dcmi->entity.source;
1468        bool fh_singular;
1469        int ret;
1470
1471        mutex_lock(&dcmi->lock);
1472
1473        fh_singular = v4l2_fh_is_singular_file(file);
1474
1475        ret = _vb2_fop_release(file, NULL);
1476
1477        if (fh_singular)
1478                v4l2_subdev_call(sd, core, s_power, 0);
1479
1480        mutex_unlock(&dcmi->lock);
1481
1482        return ret;
1483}
1484
1485static const struct v4l2_ioctl_ops dcmi_ioctl_ops = {
1486        .vidioc_querycap                = dcmi_querycap,
1487
1488        .vidioc_try_fmt_vid_cap         = dcmi_try_fmt_vid_cap,
1489        .vidioc_g_fmt_vid_cap           = dcmi_g_fmt_vid_cap,
1490        .vidioc_s_fmt_vid_cap           = dcmi_s_fmt_vid_cap,
1491        .vidioc_enum_fmt_vid_cap        = dcmi_enum_fmt_vid_cap,
1492        .vidioc_g_selection             = dcmi_g_selection,
1493        .vidioc_s_selection             = dcmi_s_selection,
1494
1495        .vidioc_enum_input              = dcmi_enum_input,
1496        .vidioc_g_input                 = dcmi_g_input,
1497        .vidioc_s_input                 = dcmi_s_input,
1498
1499        .vidioc_g_parm                  = dcmi_g_parm,
1500        .vidioc_s_parm                  = dcmi_s_parm,
1501
1502        .vidioc_enum_framesizes         = dcmi_enum_framesizes,
1503        .vidioc_enum_frameintervals     = dcmi_enum_frameintervals,
1504
1505        .vidioc_reqbufs                 = vb2_ioctl_reqbufs,
1506        .vidioc_create_bufs             = vb2_ioctl_create_bufs,
1507        .vidioc_querybuf                = vb2_ioctl_querybuf,
1508        .vidioc_qbuf                    = vb2_ioctl_qbuf,
1509        .vidioc_dqbuf                   = vb2_ioctl_dqbuf,
1510        .vidioc_expbuf                  = vb2_ioctl_expbuf,
1511        .vidioc_prepare_buf             = vb2_ioctl_prepare_buf,
1512        .vidioc_streamon                = vb2_ioctl_streamon,
1513        .vidioc_streamoff               = vb2_ioctl_streamoff,
1514
1515        .vidioc_log_status              = v4l2_ctrl_log_status,
1516        .vidioc_subscribe_event         = v4l2_ctrl_subscribe_event,
1517        .vidioc_unsubscribe_event       = v4l2_event_unsubscribe,
1518};
1519
1520static const struct v4l2_file_operations dcmi_fops = {
1521        .owner          = THIS_MODULE,
1522        .unlocked_ioctl = video_ioctl2,
1523        .open           = dcmi_open,
1524        .release        = dcmi_release,
1525        .poll           = vb2_fop_poll,
1526        .mmap           = vb2_fop_mmap,
1527#ifndef CONFIG_MMU
1528        .get_unmapped_area = vb2_fop_get_unmapped_area,
1529#endif
1530        .read           = vb2_fop_read,
1531};
1532
1533static int dcmi_set_default_fmt(struct stm32_dcmi *dcmi)
1534{
1535        struct v4l2_format f = {
1536                .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1537                .fmt.pix = {
1538                        .width          = CIF_WIDTH,
1539                        .height         = CIF_HEIGHT,
1540                        .field          = V4L2_FIELD_NONE,
1541                        .pixelformat    = dcmi->sd_formats[0]->fourcc,
1542                },
1543        };
1544        int ret;
1545
1546        ret = dcmi_try_fmt(dcmi, &f, NULL, NULL);
1547        if (ret)
1548                return ret;
1549        dcmi->sd_format = dcmi->sd_formats[0];
1550        dcmi->fmt = f;
1551        return 0;
1552}
1553
1554/*
1555 * FIXME: For the time being we only support subdevices
1556 * which expose RGB & YUV "parallel form" mbus code (_2X8).
1557 * Nevertheless, this allows to support serial source subdevices
1558 * and serial to parallel bridges which conform to this.
1559 */
1560static const struct dcmi_format dcmi_formats[] = {
1561        {
1562                .fourcc = V4L2_PIX_FMT_RGB565,
1563                .mbus_code = MEDIA_BUS_FMT_RGB565_2X8_LE,
1564                .bpp = 2,
1565        }, {
1566                .fourcc = V4L2_PIX_FMT_YUYV,
1567                .mbus_code = MEDIA_BUS_FMT_YUYV8_2X8,
1568                .bpp = 2,
1569        }, {
1570                .fourcc = V4L2_PIX_FMT_UYVY,
1571                .mbus_code = MEDIA_BUS_FMT_UYVY8_2X8,
1572                .bpp = 2,
1573        }, {
1574                .fourcc = V4L2_PIX_FMT_JPEG,
1575                .mbus_code = MEDIA_BUS_FMT_JPEG_1X8,
1576                .bpp = 1,
1577        },
1578};
1579
1580static int dcmi_formats_init(struct stm32_dcmi *dcmi)
1581{
1582        const struct dcmi_format *sd_fmts[ARRAY_SIZE(dcmi_formats)];
1583        unsigned int num_fmts = 0, i, j;
1584        struct v4l2_subdev *subdev = dcmi->entity.source;
1585        struct v4l2_subdev_mbus_code_enum mbus_code = {
1586                .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1587        };
1588
1589        while (!v4l2_subdev_call(subdev, pad, enum_mbus_code,
1590                                 NULL, &mbus_code)) {
1591                for (i = 0; i < ARRAY_SIZE(dcmi_formats); i++) {
1592                        if (dcmi_formats[i].mbus_code != mbus_code.code)
1593                                continue;
1594
1595                        /* Code supported, have we got this fourcc yet? */
1596                        for (j = 0; j < num_fmts; j++)
1597                                if (sd_fmts[j]->fourcc ==
1598                                                dcmi_formats[i].fourcc) {
1599                                        /* Already available */
1600                                        dev_dbg(dcmi->dev, "Skipping fourcc/code: %4.4s/0x%x\n",
1601                                                (char *)&sd_fmts[j]->fourcc,
1602                                                mbus_code.code);
1603                                        break;
1604                                }
1605                        if (j == num_fmts) {
1606                                /* New */
1607                                sd_fmts[num_fmts++] = dcmi_formats + i;
1608                                dev_dbg(dcmi->dev, "Supported fourcc/code: %4.4s/0x%x\n",
1609                                        (char *)&sd_fmts[num_fmts - 1]->fourcc,
1610                                        sd_fmts[num_fmts - 1]->mbus_code);
1611                        }
1612                }
1613                mbus_code.index++;
1614        }
1615
1616        if (!num_fmts)
1617                return -ENXIO;
1618
1619        dcmi->num_of_sd_formats = num_fmts;
1620        dcmi->sd_formats = devm_kcalloc(dcmi->dev,
1621                                        num_fmts, sizeof(struct dcmi_format *),
1622                                        GFP_KERNEL);
1623        if (!dcmi->sd_formats) {
1624                dev_err(dcmi->dev, "Could not allocate memory\n");
1625                return -ENOMEM;
1626        }
1627
1628        memcpy(dcmi->sd_formats, sd_fmts,
1629               num_fmts * sizeof(struct dcmi_format *));
1630        dcmi->sd_format = dcmi->sd_formats[0];
1631
1632        return 0;
1633}
1634
1635static int dcmi_framesizes_init(struct stm32_dcmi *dcmi)
1636{
1637        unsigned int num_fsize = 0;
1638        struct v4l2_subdev *subdev = dcmi->entity.source;
1639        struct v4l2_subdev_frame_size_enum fse = {
1640                .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1641                .code = dcmi->sd_format->mbus_code,
1642        };
1643        unsigned int ret;
1644        unsigned int i;
1645
1646        /* Allocate discrete framesizes array */
1647        while (!v4l2_subdev_call(subdev, pad, enum_frame_size,
1648                                 NULL, &fse))
1649                fse.index++;
1650
1651        num_fsize = fse.index;
1652        if (!num_fsize)
1653                return 0;
1654
1655        dcmi->num_of_sd_framesizes = num_fsize;
1656        dcmi->sd_framesizes = devm_kcalloc(dcmi->dev, num_fsize,
1657                                           sizeof(struct dcmi_framesize),
1658                                           GFP_KERNEL);
1659        if (!dcmi->sd_framesizes) {
1660                dev_err(dcmi->dev, "Could not allocate memory\n");
1661                return -ENOMEM;
1662        }
1663
1664        /* Fill array with sensor supported framesizes */
1665        dev_dbg(dcmi->dev, "Sensor supports %u frame sizes:\n", num_fsize);
1666        for (i = 0; i < dcmi->num_of_sd_framesizes; i++) {
1667                fse.index = i;
1668                ret = v4l2_subdev_call(subdev, pad, enum_frame_size,
1669                                       NULL, &fse);
1670                if (ret)
1671                        return ret;
1672                dcmi->sd_framesizes[fse.index].width = fse.max_width;
1673                dcmi->sd_framesizes[fse.index].height = fse.max_height;
1674                dev_dbg(dcmi->dev, "%ux%u\n", fse.max_width, fse.max_height);
1675        }
1676
1677        return 0;
1678}
1679
1680static int dcmi_graph_notify_complete(struct v4l2_async_notifier *notifier)
1681{
1682        struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1683        int ret;
1684
1685        /*
1686         * Now that the graph is complete,
1687         * we search for the source subdevice
1688         * in order to expose it through V4L2 interface
1689         */
1690        dcmi->entity.source =
1691                media_entity_to_v4l2_subdev(dcmi_find_source(dcmi));
1692        if (!dcmi->entity.source) {
1693                dev_err(dcmi->dev, "Source subdevice not found\n");
1694                return -ENODEV;
1695        }
1696
1697        dcmi->vdev->ctrl_handler = dcmi->entity.source->ctrl_handler;
1698
1699        ret = dcmi_formats_init(dcmi);
1700        if (ret) {
1701                dev_err(dcmi->dev, "No supported mediabus format found\n");
1702                return ret;
1703        }
1704
1705        ret = dcmi_framesizes_init(dcmi);
1706        if (ret) {
1707                dev_err(dcmi->dev, "Could not initialize framesizes\n");
1708                return ret;
1709        }
1710
1711        ret = dcmi_get_sensor_bounds(dcmi, &dcmi->sd_bounds);
1712        if (ret) {
1713                dev_err(dcmi->dev, "Could not get sensor bounds\n");
1714                return ret;
1715        }
1716
1717        ret = dcmi_set_default_fmt(dcmi);
1718        if (ret) {
1719                dev_err(dcmi->dev, "Could not set default format\n");
1720                return ret;
1721        }
1722
1723        return 0;
1724}
1725
1726static void dcmi_graph_notify_unbind(struct v4l2_async_notifier *notifier,
1727                                     struct v4l2_subdev *sd,
1728                                     struct v4l2_async_subdev *asd)
1729{
1730        struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1731
1732        dev_dbg(dcmi->dev, "Removing %s\n", video_device_node_name(dcmi->vdev));
1733
1734        /* Checks internally if vdev has been init or not */
1735        video_unregister_device(dcmi->vdev);
1736}
1737
1738static int dcmi_graph_notify_bound(struct v4l2_async_notifier *notifier,
1739                                   struct v4l2_subdev *subdev,
1740                                   struct v4l2_async_subdev *asd)
1741{
1742        struct stm32_dcmi *dcmi = notifier_to_dcmi(notifier);
1743        unsigned int ret;
1744        int src_pad;
1745
1746        dev_dbg(dcmi->dev, "Subdev \"%s\" bound\n", subdev->name);
1747
1748        /*
1749         * Link this sub-device to DCMI, it could be
1750         * a parallel camera sensor or a bridge
1751         */
1752        src_pad = media_entity_get_fwnode_pad(&subdev->entity,
1753                                              subdev->fwnode,
1754                                              MEDIA_PAD_FL_SOURCE);
1755
1756        ret = media_create_pad_link(&subdev->entity, src_pad,
1757                                    &dcmi->vdev->entity, 0,
1758                                    MEDIA_LNK_FL_IMMUTABLE |
1759                                    MEDIA_LNK_FL_ENABLED);
1760        if (ret)
1761                dev_err(dcmi->dev, "Failed to create media pad link with subdev \"%s\"\n",
1762                        subdev->name);
1763        else
1764                dev_dbg(dcmi->dev, "DCMI is now linked to \"%s\"\n",
1765                        subdev->name);
1766
1767        return ret;
1768}
1769
1770static const struct v4l2_async_notifier_operations dcmi_graph_notify_ops = {
1771        .bound = dcmi_graph_notify_bound,
1772        .unbind = dcmi_graph_notify_unbind,
1773        .complete = dcmi_graph_notify_complete,
1774};
1775
1776static int dcmi_graph_parse(struct stm32_dcmi *dcmi, struct device_node *node)
1777{
1778        struct device_node *ep = NULL;
1779        struct device_node *remote;
1780
1781        ep = of_graph_get_next_endpoint(node, ep);
1782        if (!ep)
1783                return -EINVAL;
1784
1785        remote = of_graph_get_remote_port_parent(ep);
1786        of_node_put(ep);
1787        if (!remote)
1788                return -EINVAL;
1789
1790        /* Remote node to connect */
1791        dcmi->entity.remote_node = remote;
1792        dcmi->entity.asd.match_type = V4L2_ASYNC_MATCH_FWNODE;
1793        dcmi->entity.asd.match.fwnode = of_fwnode_handle(remote);
1794        return 0;
1795}
1796
1797static int dcmi_graph_init(struct stm32_dcmi *dcmi)
1798{
1799        int ret;
1800
1801        /* Parse the graph to extract a list of subdevice DT nodes. */
1802        ret = dcmi_graph_parse(dcmi, dcmi->dev->of_node);
1803        if (ret < 0) {
1804                dev_err(dcmi->dev, "Failed to parse graph\n");
1805                return ret;
1806        }
1807
1808        v4l2_async_notifier_init(&dcmi->notifier);
1809
1810        ret = v4l2_async_notifier_add_subdev(&dcmi->notifier,
1811                                             &dcmi->entity.asd);
1812        if (ret) {
1813                dev_err(dcmi->dev, "Failed to add subdev notifier\n");
1814                of_node_put(dcmi->entity.remote_node);
1815                return ret;
1816        }
1817
1818        dcmi->notifier.ops = &dcmi_graph_notify_ops;
1819
1820        ret = v4l2_async_notifier_register(&dcmi->v4l2_dev, &dcmi->notifier);
1821        if (ret < 0) {
1822                dev_err(dcmi->dev, "Failed to register notifier\n");
1823                v4l2_async_notifier_cleanup(&dcmi->notifier);
1824                return ret;
1825        }
1826
1827        return 0;
1828}
1829
1830static int dcmi_probe(struct platform_device *pdev)
1831{
1832        struct device_node *np = pdev->dev.of_node;
1833        const struct of_device_id *match = NULL;
1834        struct v4l2_fwnode_endpoint ep = { .bus_type = 0 };
1835        struct stm32_dcmi *dcmi;
1836        struct vb2_queue *q;
1837        struct dma_chan *chan;
1838        struct clk *mclk;
1839        int irq;
1840        int ret = 0;
1841
1842        match = of_match_device(of_match_ptr(stm32_dcmi_of_match), &pdev->dev);
1843        if (!match) {
1844                dev_err(&pdev->dev, "Could not find a match in devicetree\n");
1845                return -ENODEV;
1846        }
1847
1848        dcmi = devm_kzalloc(&pdev->dev, sizeof(struct stm32_dcmi), GFP_KERNEL);
1849        if (!dcmi)
1850                return -ENOMEM;
1851
1852        dcmi->rstc = devm_reset_control_get_exclusive(&pdev->dev, NULL);
1853        if (IS_ERR(dcmi->rstc)) {
1854                dev_err(&pdev->dev, "Could not get reset control\n");
1855                return PTR_ERR(dcmi->rstc);
1856        }
1857
1858        /* Get bus characteristics from devicetree */
1859        np = of_graph_get_next_endpoint(np, NULL);
1860        if (!np) {
1861                dev_err(&pdev->dev, "Could not find the endpoint\n");
1862                return -ENODEV;
1863        }
1864
1865        ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(np), &ep);
1866        of_node_put(np);
1867        if (ret) {
1868                dev_err(&pdev->dev, "Could not parse the endpoint\n");
1869                return ret;
1870        }
1871
1872        if (ep.bus_type == V4L2_MBUS_CSI2_DPHY) {
1873                dev_err(&pdev->dev, "CSI bus not supported\n");
1874                return -ENODEV;
1875        }
1876        dcmi->bus.flags = ep.bus.parallel.flags;
1877        dcmi->bus.bus_width = ep.bus.parallel.bus_width;
1878        dcmi->bus.data_shift = ep.bus.parallel.data_shift;
1879
1880        irq = platform_get_irq(pdev, 0);
1881        if (irq <= 0)
1882                return irq ? irq : -ENXIO;
1883
1884        dcmi->res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1885        if (!dcmi->res) {
1886                dev_err(&pdev->dev, "Could not get resource\n");
1887                return -ENODEV;
1888        }
1889
1890        dcmi->regs = devm_ioremap_resource(&pdev->dev, dcmi->res);
1891        if (IS_ERR(dcmi->regs)) {
1892                dev_err(&pdev->dev, "Could not map registers\n");
1893                return PTR_ERR(dcmi->regs);
1894        }
1895
1896        ret = devm_request_threaded_irq(&pdev->dev, irq, dcmi_irq_callback,
1897                                        dcmi_irq_thread, IRQF_ONESHOT,
1898                                        dev_name(&pdev->dev), dcmi);
1899        if (ret) {
1900                dev_err(&pdev->dev, "Unable to request irq %d\n", irq);
1901                return ret;
1902        }
1903
1904        mclk = devm_clk_get(&pdev->dev, "mclk");
1905        if (IS_ERR(mclk)) {
1906                if (PTR_ERR(mclk) != -EPROBE_DEFER)
1907                        dev_err(&pdev->dev, "Unable to get mclk\n");
1908                return PTR_ERR(mclk);
1909        }
1910
1911        chan = dma_request_chan(&pdev->dev, "tx");
1912        if (IS_ERR(chan)) {
1913                ret = PTR_ERR(chan);
1914                if (ret != -EPROBE_DEFER)
1915                        dev_err(&pdev->dev,
1916                                "Failed to request DMA channel: %d\n", ret);
1917                return ret;
1918        }
1919
1920        spin_lock_init(&dcmi->irqlock);
1921        mutex_init(&dcmi->lock);
1922        mutex_init(&dcmi->dma_lock);
1923        init_completion(&dcmi->complete);
1924        INIT_LIST_HEAD(&dcmi->buffers);
1925
1926        dcmi->dev = &pdev->dev;
1927        dcmi->mclk = mclk;
1928        dcmi->state = STOPPED;
1929        dcmi->dma_chan = chan;
1930
1931        q = &dcmi->queue;
1932
1933        dcmi->v4l2_dev.mdev = &dcmi->mdev;
1934
1935        /* Initialize media device */
1936        strscpy(dcmi->mdev.model, DRV_NAME, sizeof(dcmi->mdev.model));
1937        snprintf(dcmi->mdev.bus_info, sizeof(dcmi->mdev.bus_info),
1938                 "platform:%s", DRV_NAME);
1939        dcmi->mdev.dev = &pdev->dev;
1940        media_device_init(&dcmi->mdev);
1941
1942        /* Initialize the top-level structure */
1943        ret = v4l2_device_register(&pdev->dev, &dcmi->v4l2_dev);
1944        if (ret)
1945                goto err_media_device_cleanup;
1946
1947        dcmi->vdev = video_device_alloc();
1948        if (!dcmi->vdev) {
1949                ret = -ENOMEM;
1950                goto err_device_unregister;
1951        }
1952
1953        /* Video node */
1954        dcmi->vdev->fops = &dcmi_fops;
1955        dcmi->vdev->v4l2_dev = &dcmi->v4l2_dev;
1956        dcmi->vdev->queue = &dcmi->queue;
1957        strscpy(dcmi->vdev->name, KBUILD_MODNAME, sizeof(dcmi->vdev->name));
1958        dcmi->vdev->release = video_device_release;
1959        dcmi->vdev->ioctl_ops = &dcmi_ioctl_ops;
1960        dcmi->vdev->lock = &dcmi->lock;
1961        dcmi->vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
1962                                  V4L2_CAP_READWRITE;
1963        video_set_drvdata(dcmi->vdev, dcmi);
1964
1965        /* Media entity pads */
1966        dcmi->vid_cap_pad.flags = MEDIA_PAD_FL_SINK;
1967        ret = media_entity_pads_init(&dcmi->vdev->entity,
1968                                     1, &dcmi->vid_cap_pad);
1969        if (ret) {
1970                dev_err(dcmi->dev, "Failed to init media entity pad\n");
1971                goto err_device_release;
1972        }
1973        dcmi->vdev->entity.flags |= MEDIA_ENT_FL_DEFAULT;
1974
1975        ret = video_register_device(dcmi->vdev, VFL_TYPE_VIDEO, -1);
1976        if (ret) {
1977                dev_err(dcmi->dev, "Failed to register video device\n");
1978                goto err_media_entity_cleanup;
1979        }
1980
1981        dev_dbg(dcmi->dev, "Device registered as %s\n",
1982                video_device_node_name(dcmi->vdev));
1983
1984        /* Buffer queue */
1985        q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1986        q->io_modes = VB2_MMAP | VB2_READ | VB2_DMABUF;
1987        q->lock = &dcmi->lock;
1988        q->drv_priv = dcmi;
1989        q->buf_struct_size = sizeof(struct dcmi_buf);
1990        q->ops = &dcmi_video_qops;
1991        q->mem_ops = &vb2_dma_contig_memops;
1992        q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1993        q->min_buffers_needed = 2;
1994        q->dev = &pdev->dev;
1995
1996        ret = vb2_queue_init(q);
1997        if (ret < 0) {
1998                dev_err(&pdev->dev, "Failed to initialize vb2 queue\n");
1999                goto err_media_entity_cleanup;
2000        }
2001
2002        ret = dcmi_graph_init(dcmi);
2003        if (ret < 0)
2004                goto err_media_entity_cleanup;
2005
2006        /* Reset device */
2007        ret = reset_control_assert(dcmi->rstc);
2008        if (ret) {
2009                dev_err(&pdev->dev, "Failed to assert the reset line\n");
2010                goto err_cleanup;
2011        }
2012
2013        usleep_range(3000, 5000);
2014
2015        ret = reset_control_deassert(dcmi->rstc);
2016        if (ret) {
2017                dev_err(&pdev->dev, "Failed to deassert the reset line\n");
2018                goto err_cleanup;
2019        }
2020
2021        dev_info(&pdev->dev, "Probe done\n");
2022
2023        platform_set_drvdata(pdev, dcmi);
2024
2025        pm_runtime_enable(&pdev->dev);
2026
2027        return 0;
2028
2029err_cleanup:
2030        v4l2_async_notifier_cleanup(&dcmi->notifier);
2031err_media_entity_cleanup:
2032        media_entity_cleanup(&dcmi->vdev->entity);
2033err_device_release:
2034        video_device_release(dcmi->vdev);
2035err_device_unregister:
2036        v4l2_device_unregister(&dcmi->v4l2_dev);
2037err_media_device_cleanup:
2038        media_device_cleanup(&dcmi->mdev);
2039        dma_release_channel(dcmi->dma_chan);
2040
2041        return ret;
2042}
2043
2044static int dcmi_remove(struct platform_device *pdev)
2045{
2046        struct stm32_dcmi *dcmi = platform_get_drvdata(pdev);
2047
2048        pm_runtime_disable(&pdev->dev);
2049
2050        v4l2_async_notifier_unregister(&dcmi->notifier);
2051        v4l2_async_notifier_cleanup(&dcmi->notifier);
2052        media_entity_cleanup(&dcmi->vdev->entity);
2053        v4l2_device_unregister(&dcmi->v4l2_dev);
2054        media_device_cleanup(&dcmi->mdev);
2055
2056        dma_release_channel(dcmi->dma_chan);
2057
2058        return 0;
2059}
2060
2061static __maybe_unused int dcmi_runtime_suspend(struct device *dev)
2062{
2063        struct stm32_dcmi *dcmi = dev_get_drvdata(dev);
2064
2065        clk_disable_unprepare(dcmi->mclk);
2066
2067        return 0;
2068}
2069
2070static __maybe_unused int dcmi_runtime_resume(struct device *dev)
2071{
2072        struct stm32_dcmi *dcmi = dev_get_drvdata(dev);
2073        int ret;
2074
2075        ret = clk_prepare_enable(dcmi->mclk);
2076        if (ret)
2077                dev_err(dev, "%s: Failed to prepare_enable clock\n", __func__);
2078
2079        return ret;
2080}
2081
2082static __maybe_unused int dcmi_suspend(struct device *dev)
2083{
2084        /* disable clock */
2085        pm_runtime_force_suspend(dev);
2086
2087        /* change pinctrl state */
2088        pinctrl_pm_select_sleep_state(dev);
2089
2090        return 0;
2091}
2092
2093static __maybe_unused int dcmi_resume(struct device *dev)
2094{
2095        /* restore pinctl default state */
2096        pinctrl_pm_select_default_state(dev);
2097
2098        /* clock enable */
2099        pm_runtime_force_resume(dev);
2100
2101        return 0;
2102}
2103
2104static const struct dev_pm_ops dcmi_pm_ops = {
2105        SET_SYSTEM_SLEEP_PM_OPS(dcmi_suspend, dcmi_resume)
2106        SET_RUNTIME_PM_OPS(dcmi_runtime_suspend,
2107                           dcmi_runtime_resume, NULL)
2108};
2109
2110static struct platform_driver stm32_dcmi_driver = {
2111        .probe          = dcmi_probe,
2112        .remove         = dcmi_remove,
2113        .driver         = {
2114                .name = DRV_NAME,
2115                .of_match_table = of_match_ptr(stm32_dcmi_of_match),
2116                .pm = &dcmi_pm_ops,
2117        },
2118};
2119
2120module_platform_driver(stm32_dcmi_driver);
2121
2122MODULE_AUTHOR("Yannick Fertre <yannick.fertre@st.com>");
2123MODULE_AUTHOR("Hugues Fruchet <hugues.fruchet@st.com>");
2124MODULE_DESCRIPTION("STMicroelectronics STM32 Digital Camera Memory Interface driver");
2125MODULE_LICENSE("GPL");
2126MODULE_SUPPORTED_DEVICE("video");
2127