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