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