[media] exynos4-is: Fix fimc-lite bayer formats
[platform/kernel/linux-3.10.git] / drivers / media / platform / exynos4-is / fimc-lite.c
1 /*
2  * Samsung EXYNOS FIMC-LITE (camera host interface) driver
3 *
4  * Copyright (C) 2012 - 2013 Samsung Electronics Co., Ltd.
5  * Author: Sylwester Nawrocki <s.nawrocki@samsung.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11 #define pr_fmt(fmt) "%s:%d " fmt, __func__, __LINE__
12
13 #include <linux/bug.h>
14 #include <linux/clk.h>
15 #include <linux/device.h>
16 #include <linux/errno.h>
17 #include <linux/interrupt.h>
18 #include <linux/kernel.h>
19 #include <linux/list.h>
20 #include <linux/module.h>
21 #include <linux/of.h>
22 #include <linux/types.h>
23 #include <linux/platform_device.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/slab.h>
26 #include <linux/videodev2.h>
27
28 #include <media/v4l2-device.h>
29 #include <media/v4l2-ioctl.h>
30 #include <media/v4l2-mem2mem.h>
31 #include <media/videobuf2-core.h>
32 #include <media/videobuf2-dma-contig.h>
33 #include <media/s5p_fimc.h>
34
35 #include "common.h"
36 #include "fimc-core.h"
37 #include "fimc-lite.h"
38 #include "fimc-lite-reg.h"
39
40 static int debug;
41 module_param(debug, int, 0644);
42
43 static const struct fimc_fmt fimc_lite_formats[] = {
44         {
45                 .name           = "YUV 4:2:2 packed, YCbYCr",
46                 .fourcc         = V4L2_PIX_FMT_YUYV,
47                 .colorspace     = V4L2_COLORSPACE_JPEG,
48                 .depth          = { 16 },
49                 .color          = FIMC_FMT_YCBYCR422,
50                 .memplanes      = 1,
51                 .mbus_code      = V4L2_MBUS_FMT_YUYV8_2X8,
52                 .flags          = FMT_FLAGS_YUV,
53         }, {
54                 .name           = "YUV 4:2:2 packed, CbYCrY",
55                 .fourcc         = V4L2_PIX_FMT_UYVY,
56                 .colorspace     = V4L2_COLORSPACE_JPEG,
57                 .depth          = { 16 },
58                 .color          = FIMC_FMT_CBYCRY422,
59                 .memplanes      = 1,
60                 .mbus_code      = V4L2_MBUS_FMT_UYVY8_2X8,
61                 .flags          = FMT_FLAGS_YUV,
62         }, {
63                 .name           = "YUV 4:2:2 packed, CrYCbY",
64                 .fourcc         = V4L2_PIX_FMT_VYUY,
65                 .colorspace     = V4L2_COLORSPACE_JPEG,
66                 .depth          = { 16 },
67                 .color          = FIMC_FMT_CRYCBY422,
68                 .memplanes      = 1,
69                 .mbus_code      = V4L2_MBUS_FMT_VYUY8_2X8,
70                 .flags          = FMT_FLAGS_YUV,
71         }, {
72                 .name           = "YUV 4:2:2 packed, YCrYCb",
73                 .fourcc         = V4L2_PIX_FMT_YVYU,
74                 .colorspace     = V4L2_COLORSPACE_JPEG,
75                 .depth          = { 16 },
76                 .color          = FIMC_FMT_YCRYCB422,
77                 .memplanes      = 1,
78                 .mbus_code      = V4L2_MBUS_FMT_YVYU8_2X8,
79                 .flags          = FMT_FLAGS_YUV,
80         }, {
81                 .name           = "RAW8 (GRBG)",
82                 .fourcc         = V4L2_PIX_FMT_SGRBG8,
83                 .colorspace     = V4L2_COLORSPACE_SRGB,
84                 .depth          = { 8 },
85                 .color          = FIMC_FMT_RAW8,
86                 .memplanes      = 1,
87                 .mbus_code      = V4L2_MBUS_FMT_SGRBG8_1X8,
88                 .flags          = FMT_FLAGS_RAW_BAYER,
89         }, {
90                 .name           = "RAW10 (GRBG)",
91                 .fourcc         = V4L2_PIX_FMT_SGRBG10,
92                 .colorspace     = V4L2_COLORSPACE_SRGB,
93                 .depth          = { 16 },
94                 .color          = FIMC_FMT_RAW10,
95                 .memplanes      = 1,
96                 .mbus_code      = V4L2_MBUS_FMT_SGRBG10_1X10,
97                 .flags          = FMT_FLAGS_RAW_BAYER,
98         }, {
99                 .name           = "RAW12 (GRBG)",
100                 .fourcc         = V4L2_PIX_FMT_SGRBG12,
101                 .colorspace     = V4L2_COLORSPACE_SRGB,
102                 .depth          = { 16 },
103                 .color          = FIMC_FMT_RAW12,
104                 .memplanes      = 1,
105                 .mbus_code      = V4L2_MBUS_FMT_SGRBG12_1X12,
106                 .flags          = FMT_FLAGS_RAW_BAYER,
107         },
108 };
109
110 /**
111  * fimc_lite_find_format - lookup fimc color format by fourcc or media bus code
112  * @pixelformat: fourcc to match, ignored if null
113  * @mbus_code: media bus code to match, ignored if null
114  * @mask: the color format flags to match
115  * @index: index to the fimc_lite_formats array, ignored if negative
116  */
117 static const struct fimc_fmt *fimc_lite_find_format(const u32 *pixelformat,
118                         const u32 *mbus_code, unsigned int mask, int index)
119 {
120         const struct fimc_fmt *fmt, *def_fmt = NULL;
121         unsigned int i;
122         int id = 0;
123
124         if (index >= (int)ARRAY_SIZE(fimc_lite_formats))
125                 return NULL;
126
127         for (i = 0; i < ARRAY_SIZE(fimc_lite_formats); ++i) {
128                 fmt = &fimc_lite_formats[i];
129                 if (mask && !(fmt->flags & mask))
130                         continue;
131                 if (pixelformat && fmt->fourcc == *pixelformat)
132                         return fmt;
133                 if (mbus_code && fmt->mbus_code == *mbus_code)
134                         return fmt;
135                 if (index == id)
136                         def_fmt = fmt;
137                 id++;
138         }
139         return def_fmt;
140 }
141
142 static int fimc_lite_hw_init(struct fimc_lite *fimc, bool isp_output)
143 {
144         struct fimc_source_info *si;
145         unsigned long flags;
146
147         if (fimc->sensor == NULL)
148                 return -ENXIO;
149
150         if (fimc->inp_frame.fmt == NULL || fimc->out_frame.fmt == NULL)
151                 return -EINVAL;
152
153         /* Get sensor configuration data from the sensor subdev */
154         si = v4l2_get_subdev_hostdata(fimc->sensor);
155         if (!si)
156                 return -EINVAL;
157
158         spin_lock_irqsave(&fimc->slock, flags);
159
160         flite_hw_set_camera_bus(fimc, si);
161         flite_hw_set_source_format(fimc, &fimc->inp_frame);
162         flite_hw_set_window_offset(fimc, &fimc->inp_frame);
163         flite_hw_set_dma_buf_mask(fimc, 0);
164         flite_hw_set_output_path(fimc, !isp_output, isp_output);
165         if (!isp_output)
166                 flite_hw_configure_output_dma(fimc, &fimc->out_frame);
167         flite_hw_clear_last_capture_end(fimc);
168         flite_hw_set_interrupt_mask(fimc);
169         flite_hw_set_test_pattern(fimc, fimc->test_pattern->val);
170
171         if (debug > 0)
172                 flite_hw_dump_regs(fimc, __func__);
173
174         spin_unlock_irqrestore(&fimc->slock, flags);
175         return 0;
176 }
177
178 /*
179  * Reinitialize the driver so it is ready to start the streaming again.
180  * Set fimc->state to indicate stream off and the hardware shut down state.
181  * If not suspending (@suspend is false), return any buffers to videobuf2.
182  * Otherwise put any owned buffers onto the pending buffers queue, so they
183  * can be re-spun when the device is being resumed. Also perform FIMC
184  * software reset and disable streaming on the whole pipeline if required.
185  */
186 static int fimc_lite_reinit(struct fimc_lite *fimc, bool suspend)
187 {
188         struct flite_buffer *buf;
189         unsigned long flags;
190         bool streaming;
191
192         spin_lock_irqsave(&fimc->slock, flags);
193         streaming = fimc->state & (1 << ST_SENSOR_STREAM);
194
195         fimc->state &= ~(1 << ST_FLITE_RUN | 1 << ST_FLITE_OFF |
196                          1 << ST_FLITE_STREAM | 1 << ST_SENSOR_STREAM);
197         if (suspend)
198                 fimc->state |= (1 << ST_FLITE_SUSPENDED);
199         else
200                 fimc->state &= ~(1 << ST_FLITE_PENDING |
201                                  1 << ST_FLITE_SUSPENDED);
202
203         /* Release unused buffers */
204         while (!suspend && !list_empty(&fimc->pending_buf_q)) {
205                 buf = fimc_lite_pending_queue_pop(fimc);
206                 vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
207         }
208         /* If suspending put unused buffers onto pending queue */
209         while (!list_empty(&fimc->active_buf_q)) {
210                 buf = fimc_lite_active_queue_pop(fimc);
211                 if (suspend)
212                         fimc_lite_pending_queue_add(fimc, buf);
213                 else
214                         vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
215         }
216
217         spin_unlock_irqrestore(&fimc->slock, flags);
218
219         flite_hw_reset(fimc);
220
221         if (!streaming)
222                 return 0;
223
224         return fimc_pipeline_call(&fimc->ve, set_stream, 0);
225 }
226
227 static int fimc_lite_stop_capture(struct fimc_lite *fimc, bool suspend)
228 {
229         unsigned long flags;
230
231         if (!fimc_lite_active(fimc))
232                 return 0;
233
234         spin_lock_irqsave(&fimc->slock, flags);
235         set_bit(ST_FLITE_OFF, &fimc->state);
236         flite_hw_capture_stop(fimc);
237         spin_unlock_irqrestore(&fimc->slock, flags);
238
239         wait_event_timeout(fimc->irq_queue,
240                            !test_bit(ST_FLITE_OFF, &fimc->state),
241                            (2*HZ/10)); /* 200 ms */
242
243         return fimc_lite_reinit(fimc, suspend);
244 }
245
246 /* Must be called  with fimc.slock spinlock held. */
247 static void fimc_lite_config_update(struct fimc_lite *fimc)
248 {
249         flite_hw_set_window_offset(fimc, &fimc->inp_frame);
250         flite_hw_set_dma_window(fimc, &fimc->out_frame);
251         flite_hw_set_test_pattern(fimc, fimc->test_pattern->val);
252         clear_bit(ST_FLITE_CONFIG, &fimc->state);
253 }
254
255 static irqreturn_t flite_irq_handler(int irq, void *priv)
256 {
257         struct fimc_lite *fimc = priv;
258         struct flite_buffer *vbuf;
259         unsigned long flags;
260         struct timeval *tv;
261         struct timespec ts;
262         u32 intsrc;
263
264         spin_lock_irqsave(&fimc->slock, flags);
265
266         intsrc = flite_hw_get_interrupt_source(fimc);
267         flite_hw_clear_pending_irq(fimc);
268
269         if (test_and_clear_bit(ST_FLITE_OFF, &fimc->state)) {
270                 wake_up(&fimc->irq_queue);
271                 goto done;
272         }
273
274         if (intsrc & FLITE_REG_CISTATUS_IRQ_SRC_OVERFLOW) {
275                 clear_bit(ST_FLITE_RUN, &fimc->state);
276                 fimc->events.data_overflow++;
277         }
278
279         if (intsrc & FLITE_REG_CISTATUS_IRQ_SRC_LASTCAPEND) {
280                 flite_hw_clear_last_capture_end(fimc);
281                 clear_bit(ST_FLITE_STREAM, &fimc->state);
282                 wake_up(&fimc->irq_queue);
283         }
284
285         if (atomic_read(&fimc->out_path) != FIMC_IO_DMA)
286                 goto done;
287
288         if ((intsrc & FLITE_REG_CISTATUS_IRQ_SRC_FRMSTART)){
289                 if (test_bit(ST_FLITE_RUN, &fimc->state) &&
290                     !list_empty(&fimc->pending_buf_q)) {
291                         vbuf = fimc_lite_pending_queue_pop(fimc);
292                         flite_hw_set_dma_buffer(fimc, vbuf);
293                         fimc_lite_active_queue_add(fimc, vbuf);
294                 }
295         }
296
297         if ((intsrc & FLITE_REG_CISTATUS_IRQ_SRC_FRMEND)) {
298                 if (test_bit(ST_FLITE_RUN, &fimc->state) &&
299                 !list_empty(&fimc->active_buf_q)) {
300                         vbuf = fimc_lite_active_queue_pop(fimc);
301                         ktime_get_ts(&ts);
302                         tv = &vbuf->vb.v4l2_buf.timestamp;
303                         tv->tv_sec = ts.tv_sec;
304                         tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
305                         vbuf->vb.v4l2_buf.sequence = fimc->frame_count++;
306                         flite_hw_mask_dma_buffer(fimc, vbuf->index);
307                         vb2_buffer_done(&vbuf->vb, VB2_BUF_STATE_DONE);
308                 }
309                 v4l2_subdev_notify(&fimc->subdev, EXYNOS_FIMC_IS_FRAME_DONE, NULL);
310         }
311
312         if (test_bit(ST_FLITE_CONFIG, &fimc->state))
313                 fimc_lite_config_update(fimc);
314
315         if (list_empty(&fimc->pending_buf_q)) {
316                 flite_hw_capture_stop(fimc);
317                 clear_bit(ST_FLITE_STREAM, &fimc->state);
318         }
319 done:
320         set_bit(ST_FLITE_RUN, &fimc->state);
321         spin_unlock_irqrestore(&fimc->slock, flags);
322         return IRQ_HANDLED;
323 }
324
325 static int start_streaming(struct vb2_queue *q, unsigned int count)
326 {
327         struct fimc_lite *fimc = q->drv_priv;
328         unsigned long flags;
329         int ret;
330
331         spin_lock_irqsave(&fimc->slock, flags);
332
333         fimc->buf_index = 0;
334         fimc->frame_count = 0;
335
336         spin_unlock_irqrestore(&fimc->slock, flags);
337
338         ret = fimc_lite_hw_init(fimc, false);
339         if (ret) {
340                 fimc_lite_reinit(fimc, false);
341                 return ret;
342         }
343
344         set_bit(ST_FLITE_PENDING, &fimc->state);
345
346         if (!list_empty(&fimc->active_buf_q) &&
347             !test_and_set_bit(ST_FLITE_STREAM, &fimc->state)) {
348                 flite_hw_capture_start(fimc);
349
350                 if (!test_and_set_bit(ST_SENSOR_STREAM, &fimc->state))
351                         fimc_pipeline_call(&fimc->ve, set_stream, 1);
352         }
353         if (debug > 0)
354                 flite_hw_dump_regs(fimc, __func__);
355
356         return 0;
357 }
358
359 static void stop_streaming(struct vb2_queue *q)
360 {
361         struct fimc_lite *fimc = q->drv_priv;
362
363         if (!fimc_lite_active(fimc))
364                 return;
365
366         fimc_lite_stop_capture(fimc, false);
367 }
368
369 static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *pfmt,
370                        unsigned int *num_buffers, unsigned int *num_planes,
371                        unsigned int sizes[], void *allocators[])
372 {
373         const struct v4l2_pix_format_mplane *pixm = NULL;
374         struct fimc_lite *fimc = vq->drv_priv;
375         struct flite_frame *frame = &fimc->out_frame;
376         const struct fimc_fmt *fmt = frame->fmt;
377         unsigned long wh;
378         int i;
379
380         if (pfmt) {
381                 pixm = &pfmt->fmt.pix_mp;
382                 fmt = fimc_lite_find_format(&pixm->pixelformat, NULL, 0, -1);
383                 wh = pixm->width * pixm->height;
384         } else {
385                 wh = frame->f_width * frame->f_height;
386         }
387
388         if (fmt == NULL)
389                 return -EINVAL;
390
391         *num_planes = fmt->memplanes;
392
393         for (i = 0; i < fmt->memplanes; i++) {
394                 unsigned int size = (wh * fmt->depth[i]) / 8;
395                 if (pixm)
396                         sizes[i] = max(size, pixm->plane_fmt[i].sizeimage);
397                 else
398                         sizes[i] = size;
399                 allocators[i] = fimc->alloc_ctx;
400         }
401
402         return 0;
403 }
404
405 static int buffer_prepare(struct vb2_buffer *vb)
406 {
407         struct vb2_queue *vq = vb->vb2_queue;
408         struct fimc_lite *fimc = vq->drv_priv;
409         int i;
410
411         if (fimc->out_frame.fmt == NULL)
412                 return -EINVAL;
413
414         for (i = 0; i < fimc->out_frame.fmt->memplanes; i++) {
415                 unsigned long size = fimc->payload[i];
416
417                 if (vb2_plane_size(vb, i) < size) {
418                         v4l2_err(&fimc->ve.vdev,
419                                  "User buffer too small (%ld < %ld)\n",
420                                  vb2_plane_size(vb, i), size);
421                         return -EINVAL;
422                 }
423                 vb2_set_plane_payload(vb, i, size);
424         }
425
426         return 0;
427 }
428
429 static void buffer_queue(struct vb2_buffer *vb)
430 {
431         struct flite_buffer *buf
432                 = container_of(vb, struct flite_buffer, vb);
433         struct fimc_lite *fimc = vb2_get_drv_priv(vb->vb2_queue);
434         unsigned long flags;
435
436         spin_lock_irqsave(&fimc->slock, flags);
437         buf->paddr = vb2_dma_contig_plane_dma_addr(vb, 0);
438
439         buf->index = fimc->buf_index++;
440         if (fimc->buf_index >= fimc->reqbufs_count)
441                 fimc->buf_index = 0;
442
443         if (!test_bit(ST_FLITE_SUSPENDED, &fimc->state) &&
444             !test_bit(ST_FLITE_STREAM, &fimc->state) &&
445             list_empty(&fimc->active_buf_q)) {
446                 flite_hw_set_dma_buffer(fimc, buf);
447                 fimc_lite_active_queue_add(fimc, buf);
448         } else {
449                 fimc_lite_pending_queue_add(fimc, buf);
450         }
451
452         if (vb2_is_streaming(&fimc->vb_queue) &&
453             !list_empty(&fimc->pending_buf_q) &&
454             !test_and_set_bit(ST_FLITE_STREAM, &fimc->state)) {
455                 flite_hw_capture_start(fimc);
456                 spin_unlock_irqrestore(&fimc->slock, flags);
457
458                 if (!test_and_set_bit(ST_SENSOR_STREAM, &fimc->state))
459                         fimc_pipeline_call(&fimc->ve, set_stream, 1);
460                 return;
461         }
462         spin_unlock_irqrestore(&fimc->slock, flags);
463 }
464
465 static const struct vb2_ops fimc_lite_qops = {
466         .queue_setup     = queue_setup,
467         .buf_prepare     = buffer_prepare,
468         .buf_queue       = buffer_queue,
469         .wait_prepare    = vb2_ops_wait_prepare,
470         .wait_finish     = vb2_ops_wait_finish,
471         .start_streaming = start_streaming,
472         .stop_streaming  = stop_streaming,
473 };
474
475 static void fimc_lite_clear_event_counters(struct fimc_lite *fimc)
476 {
477         unsigned long flags;
478
479         spin_lock_irqsave(&fimc->slock, flags);
480         memset(&fimc->events, 0, sizeof(fimc->events));
481         spin_unlock_irqrestore(&fimc->slock, flags);
482 }
483
484 static int fimc_lite_open(struct file *file)
485 {
486         struct fimc_lite *fimc = video_drvdata(file);
487         struct media_entity *me = &fimc->ve.vdev.entity;
488         int ret;
489
490         mutex_lock(&fimc->lock);
491         if (atomic_read(&fimc->out_path) != FIMC_IO_DMA) {
492                 ret = -EBUSY;
493                 goto unlock;
494         }
495
496         set_bit(ST_FLITE_IN_USE, &fimc->state);
497         ret = pm_runtime_get_sync(&fimc->pdev->dev);
498         if (ret < 0)
499                 goto unlock;
500
501         ret = v4l2_fh_open(file);
502         if (ret < 0)
503                 goto err_pm;
504
505         if (!v4l2_fh_is_singular_file(file) ||
506             atomic_read(&fimc->out_path) != FIMC_IO_DMA)
507                 goto unlock;
508
509         mutex_lock(&me->parent->graph_mutex);
510
511         ret = fimc_pipeline_call(&fimc->ve, open, me, true);
512
513         /* Mark video pipeline ending at this video node as in use. */
514         if (ret == 0)
515                 me->use_count++;
516
517         mutex_unlock(&me->parent->graph_mutex);
518
519         if (!ret) {
520                 fimc_lite_clear_event_counters(fimc);
521                 goto unlock;
522         }
523
524         v4l2_fh_release(file);
525 err_pm:
526         pm_runtime_put_sync(&fimc->pdev->dev);
527         clear_bit(ST_FLITE_IN_USE, &fimc->state);
528 unlock:
529         mutex_unlock(&fimc->lock);
530         return ret;
531 }
532
533 static int fimc_lite_release(struct file *file)
534 {
535         struct fimc_lite *fimc = video_drvdata(file);
536         struct media_entity *entity = &fimc->ve.vdev.entity;
537
538         mutex_lock(&fimc->lock);
539
540         if (v4l2_fh_is_singular_file(file) &&
541             atomic_read(&fimc->out_path) == FIMC_IO_DMA) {
542                 if (fimc->streaming) {
543                         media_entity_pipeline_stop(entity);
544                         fimc->streaming = false;
545                 }
546                 fimc_lite_stop_capture(fimc, false);
547                 fimc_pipeline_call(&fimc->ve, close);
548                 clear_bit(ST_FLITE_IN_USE, &fimc->state);
549
550                 mutex_lock(&entity->parent->graph_mutex);
551                 entity->use_count--;
552                 mutex_unlock(&entity->parent->graph_mutex);
553         }
554
555         _vb2_fop_release(file, NULL);
556         pm_runtime_put(&fimc->pdev->dev);
557         clear_bit(ST_FLITE_SUSPENDED, &fimc->state);
558
559         mutex_unlock(&fimc->lock);
560         return 0;
561 }
562
563 static const struct v4l2_file_operations fimc_lite_fops = {
564         .owner          = THIS_MODULE,
565         .open           = fimc_lite_open,
566         .release        = fimc_lite_release,
567         .poll           = vb2_fop_poll,
568         .unlocked_ioctl = video_ioctl2,
569         .mmap           = vb2_fop_mmap,
570 };
571
572 /*
573  * Format and crop negotiation helpers
574  */
575
576 static const struct fimc_fmt *fimc_lite_subdev_try_fmt(struct fimc_lite *fimc,
577                                         struct v4l2_subdev_fh *fh,
578                                         struct v4l2_subdev_format *format)
579 {
580         struct flite_drvdata *dd = fimc->dd;
581         struct v4l2_mbus_framefmt *mf = &format->format;
582         const struct fimc_fmt *fmt = NULL;
583
584         if (format->pad == FLITE_SD_PAD_SINK) {
585                 v4l_bound_align_image(&mf->width, 8, dd->max_width,
586                                 ffs(dd->out_width_align) - 1,
587                                 &mf->height, 0, dd->max_height, 0, 0);
588
589                 fmt = fimc_lite_find_format(NULL, &mf->code, 0, 0);
590                 if (WARN_ON(!fmt))
591                         return NULL;
592
593                 mf->colorspace = fmt->colorspace;
594                 mf->code = fmt->mbus_code;
595         } else {
596                 struct flite_frame *sink = &fimc->inp_frame;
597                 struct v4l2_mbus_framefmt *sink_fmt;
598                 struct v4l2_rect *rect;
599
600                 if (format->which == V4L2_SUBDEV_FORMAT_TRY) {
601                         sink_fmt = v4l2_subdev_get_try_format(fh,
602                                                 FLITE_SD_PAD_SINK);
603
604                         mf->code = sink_fmt->code;
605                         mf->colorspace = sink_fmt->colorspace;
606
607                         rect = v4l2_subdev_get_try_crop(fh,
608                                                 FLITE_SD_PAD_SINK);
609                 } else {
610                         mf->code = sink->fmt->mbus_code;
611                         mf->colorspace = sink->fmt->colorspace;
612                         rect = &sink->rect;
613                 }
614
615                 /* Allow changing format only on sink pad */
616                 mf->width = rect->width;
617                 mf->height = rect->height;
618         }
619
620         mf->field = V4L2_FIELD_NONE;
621
622         v4l2_dbg(1, debug, &fimc->subdev, "code: %#x (%d), %dx%d\n",
623                  mf->code, mf->colorspace, mf->width, mf->height);
624
625         return fmt;
626 }
627
628 static void fimc_lite_try_crop(struct fimc_lite *fimc, struct v4l2_rect *r)
629 {
630         struct flite_frame *frame = &fimc->inp_frame;
631
632         v4l_bound_align_image(&r->width, 0, frame->f_width, 0,
633                               &r->height, 0, frame->f_height, 0, 0);
634
635         /* Adjust left/top if cropping rectangle got out of bounds */
636         r->left = clamp_t(u32, r->left, 0, frame->f_width - r->width);
637         r->left = round_down(r->left, fimc->dd->win_hor_offs_align);
638         r->top  = clamp_t(u32, r->top, 0, frame->f_height - r->height);
639
640         v4l2_dbg(1, debug, &fimc->subdev, "(%d,%d)/%dx%d, sink fmt: %dx%d\n",
641                  r->left, r->top, r->width, r->height,
642                  frame->f_width, frame->f_height);
643 }
644
645 static void fimc_lite_try_compose(struct fimc_lite *fimc, struct v4l2_rect *r)
646 {
647         struct flite_frame *frame = &fimc->out_frame;
648         struct v4l2_rect *crop_rect = &fimc->inp_frame.rect;
649
650         /* Scaling is not supported so we enforce compose rectangle size
651            same as size of the sink crop rectangle. */
652         r->width = crop_rect->width;
653         r->height = crop_rect->height;
654
655         /* Adjust left/top if the composing rectangle got out of bounds */
656         r->left = clamp_t(u32, r->left, 0, frame->f_width - r->width);
657         r->left = round_down(r->left, fimc->dd->out_hor_offs_align);
658         r->top  = clamp_t(u32, r->top, 0, fimc->out_frame.f_height - r->height);
659
660         v4l2_dbg(1, debug, &fimc->subdev, "(%d,%d)/%dx%d, source fmt: %dx%d\n",
661                  r->left, r->top, r->width, r->height,
662                  frame->f_width, frame->f_height);
663 }
664
665 /*
666  * Video node ioctl operations
667  */
668 static int fimc_lite_querycap(struct file *file, void *priv,
669                                         struct v4l2_capability *cap)
670 {
671         struct fimc_lite *fimc = video_drvdata(file);
672
673         strlcpy(cap->driver, FIMC_LITE_DRV_NAME, sizeof(cap->driver));
674         strlcpy(cap->card, FIMC_LITE_DRV_NAME, sizeof(cap->card));
675         snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s",
676                                         dev_name(&fimc->pdev->dev));
677
678         cap->device_caps = V4L2_CAP_STREAMING;
679         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
680         return 0;
681 }
682
683 static int fimc_lite_enum_fmt_mplane(struct file *file, void *priv,
684                                      struct v4l2_fmtdesc *f)
685 {
686         const struct fimc_fmt *fmt;
687
688         if (f->index >= ARRAY_SIZE(fimc_lite_formats))
689                 return -EINVAL;
690
691         fmt = &fimc_lite_formats[f->index];
692         strlcpy(f->description, fmt->name, sizeof(f->description));
693         f->pixelformat = fmt->fourcc;
694
695         return 0;
696 }
697
698 static int fimc_lite_g_fmt_mplane(struct file *file, void *fh,
699                                   struct v4l2_format *f)
700 {
701         struct fimc_lite *fimc = video_drvdata(file);
702         struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp;
703         struct v4l2_plane_pix_format *plane_fmt = &pixm->plane_fmt[0];
704         struct flite_frame *frame = &fimc->out_frame;
705         const struct fimc_fmt *fmt = frame->fmt;
706
707         plane_fmt->bytesperline = (frame->f_width * fmt->depth[0]) / 8;
708         plane_fmt->sizeimage = plane_fmt->bytesperline * frame->f_height;
709
710         pixm->num_planes = fmt->memplanes;
711         pixm->pixelformat = fmt->fourcc;
712         pixm->width = frame->f_width;
713         pixm->height = frame->f_height;
714         pixm->field = V4L2_FIELD_NONE;
715         pixm->colorspace = fmt->colorspace;
716         return 0;
717 }
718
719 static int fimc_lite_try_fmt(struct fimc_lite *fimc,
720                              struct v4l2_pix_format_mplane *pixm,
721                              const struct fimc_fmt **ffmt)
722 {
723         u32 bpl = pixm->plane_fmt[0].bytesperline;
724         struct flite_drvdata *dd = fimc->dd;
725         const struct fimc_fmt *inp_fmt = fimc->inp_frame.fmt;
726         const struct fimc_fmt *fmt;
727
728         if (WARN_ON(inp_fmt == NULL))
729                 return -EINVAL;
730         /*
731          * We allow some flexibility only for YUV formats. In case of raw
732          * raw Bayer the FIMC-LITE's output format must match its camera
733          * interface input format.
734          */
735         if (inp_fmt->flags & FMT_FLAGS_YUV)
736                 fmt = fimc_lite_find_format(&pixm->pixelformat, NULL,
737                                                 inp_fmt->flags, 0);
738         else
739                 fmt = inp_fmt;
740
741         if (WARN_ON(fmt == NULL))
742                 return -EINVAL;
743         if (ffmt)
744                 *ffmt = fmt;
745         v4l_bound_align_image(&pixm->width, 8, dd->max_width,
746                               ffs(dd->out_width_align) - 1,
747                               &pixm->height, 0, dd->max_height, 0, 0);
748
749         if ((bpl == 0 || ((bpl * 8) / fmt->depth[0]) < pixm->width))
750                 pixm->plane_fmt[0].bytesperline = (pixm->width *
751                                                    fmt->depth[0]) / 8;
752
753         if (pixm->plane_fmt[0].sizeimage == 0)
754                 pixm->plane_fmt[0].sizeimage = (pixm->width * pixm->height *
755                                                 fmt->depth[0]) / 8;
756         pixm->num_planes = fmt->memplanes;
757         pixm->pixelformat = fmt->fourcc;
758         pixm->colorspace = fmt->colorspace;
759         pixm->field = V4L2_FIELD_NONE;
760         return 0;
761 }
762
763 static int fimc_lite_try_fmt_mplane(struct file *file, void *fh,
764                                     struct v4l2_format *f)
765 {
766         struct fimc_lite *fimc = video_drvdata(file);
767         return fimc_lite_try_fmt(fimc, &f->fmt.pix_mp, NULL);
768 }
769
770 static int fimc_lite_s_fmt_mplane(struct file *file, void *priv,
771                                   struct v4l2_format *f)
772 {
773         struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp;
774         struct fimc_lite *fimc = video_drvdata(file);
775         struct flite_frame *frame = &fimc->out_frame;
776         const struct fimc_fmt *fmt = NULL;
777         int ret;
778
779         if (vb2_is_busy(&fimc->vb_queue))
780                 return -EBUSY;
781
782         ret = fimc_lite_try_fmt(fimc, &f->fmt.pix_mp, &fmt);
783         if (ret < 0)
784                 return ret;
785
786         frame->fmt = fmt;
787         fimc->payload[0] = max((pixm->width * pixm->height * fmt->depth[0]) / 8,
788                                pixm->plane_fmt[0].sizeimage);
789         frame->f_width = pixm->width;
790         frame->f_height = pixm->height;
791
792         return 0;
793 }
794
795 static int fimc_pipeline_validate(struct fimc_lite *fimc)
796 {
797         struct v4l2_subdev *sd = &fimc->subdev;
798         struct v4l2_subdev_format sink_fmt, src_fmt;
799         struct media_pad *pad;
800         int ret;
801
802         while (1) {
803                 /* Retrieve format at the sink pad */
804                 pad = &sd->entity.pads[0];
805                 if (!(pad->flags & MEDIA_PAD_FL_SINK))
806                         break;
807                 /* Don't call FIMC subdev operation to avoid nested locking */
808                 if (sd == &fimc->subdev) {
809                         struct flite_frame *ff = &fimc->out_frame;
810                         sink_fmt.format.width = ff->f_width;
811                         sink_fmt.format.height = ff->f_height;
812                         sink_fmt.format.code = fimc->inp_frame.fmt->mbus_code;
813                 } else {
814                         sink_fmt.pad = pad->index;
815                         sink_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
816                         ret = v4l2_subdev_call(sd, pad, get_fmt, NULL,
817                                                &sink_fmt);
818                         if (ret < 0 && ret != -ENOIOCTLCMD)
819                                 return -EPIPE;
820                 }
821                 /* Retrieve format at the source pad */
822                 pad = media_entity_remote_pad(pad);
823                 if (pad == NULL ||
824                     media_entity_type(pad->entity) != MEDIA_ENT_T_V4L2_SUBDEV)
825                         break;
826
827                 sd = media_entity_to_v4l2_subdev(pad->entity);
828                 src_fmt.pad = pad->index;
829                 src_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
830                 ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &src_fmt);
831                 if (ret < 0 && ret != -ENOIOCTLCMD)
832                         return -EPIPE;
833
834                 if (src_fmt.format.width != sink_fmt.format.width ||
835                     src_fmt.format.height != sink_fmt.format.height ||
836                     src_fmt.format.code != sink_fmt.format.code)
837                         return -EPIPE;
838         }
839         return 0;
840 }
841
842 static int fimc_lite_streamon(struct file *file, void *priv,
843                               enum v4l2_buf_type type)
844 {
845         struct fimc_lite *fimc = video_drvdata(file);
846         struct media_entity *entity = &fimc->ve.vdev.entity;
847         int ret;
848
849         if (fimc_lite_active(fimc))
850                 return -EBUSY;
851
852         ret = media_entity_pipeline_start(entity, &fimc->ve.pipe->mp);
853         if (ret < 0)
854                 return ret;
855
856         ret = fimc_pipeline_validate(fimc);
857         if (ret < 0)
858                 goto err_p_stop;
859
860         fimc->sensor = fimc_find_remote_sensor(&fimc->subdev.entity);
861
862         ret = vb2_ioctl_streamon(file, priv, type);
863         if (!ret) {
864                 fimc->streaming = true;
865                 return ret;
866         }
867
868 err_p_stop:
869         media_entity_pipeline_stop(entity);
870         return 0;
871 }
872
873 static int fimc_lite_streamoff(struct file *file, void *priv,
874                                enum v4l2_buf_type type)
875 {
876         struct fimc_lite *fimc = video_drvdata(file);
877         int ret;
878
879         ret = vb2_ioctl_streamoff(file, priv, type);
880         if (ret < 0)
881                 return ret;
882
883         media_entity_pipeline_stop(&fimc->ve.vdev.entity);
884         fimc->streaming = false;
885         return 0;
886 }
887
888 static int fimc_lite_reqbufs(struct file *file, void *priv,
889                              struct v4l2_requestbuffers *reqbufs)
890 {
891         struct fimc_lite *fimc = video_drvdata(file);
892         int ret;
893
894         reqbufs->count = max_t(u32, FLITE_REQ_BUFS_MIN, reqbufs->count);
895         ret = vb2_ioctl_reqbufs(file, priv, reqbufs);
896         if (!ret)
897                 fimc->reqbufs_count = reqbufs->count;
898
899         return ret;
900 }
901
902 /* Return 1 if rectangle a is enclosed in rectangle b, or 0 otherwise. */
903 static int enclosed_rectangle(struct v4l2_rect *a, struct v4l2_rect *b)
904 {
905         if (a->left < b->left || a->top < b->top)
906                 return 0;
907         if (a->left + a->width > b->left + b->width)
908                 return 0;
909         if (a->top + a->height > b->top + b->height)
910                 return 0;
911
912         return 1;
913 }
914
915 static int fimc_lite_g_selection(struct file *file, void *fh,
916                                  struct v4l2_selection *sel)
917 {
918         struct fimc_lite *fimc = video_drvdata(file);
919         struct flite_frame *f = &fimc->out_frame;
920
921         if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
922                 return -EINVAL;
923
924         switch (sel->target) {
925         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
926         case V4L2_SEL_TGT_COMPOSE_DEFAULT:
927                 sel->r.left = 0;
928                 sel->r.top = 0;
929                 sel->r.width = f->f_width;
930                 sel->r.height = f->f_height;
931                 return 0;
932
933         case V4L2_SEL_TGT_COMPOSE:
934                 sel->r = f->rect;
935                 return 0;
936         }
937
938         return -EINVAL;
939 }
940
941 static int fimc_lite_s_selection(struct file *file, void *fh,
942                                  struct v4l2_selection *sel)
943 {
944         struct fimc_lite *fimc = video_drvdata(file);
945         struct flite_frame *f = &fimc->out_frame;
946         struct v4l2_rect rect = sel->r;
947         unsigned long flags;
948
949         if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE ||
950             sel->target != V4L2_SEL_TGT_COMPOSE)
951                 return -EINVAL;
952
953         fimc_lite_try_compose(fimc, &rect);
954
955         if ((sel->flags & V4L2_SEL_FLAG_LE) &&
956             !enclosed_rectangle(&rect, &sel->r))
957                 return -ERANGE;
958
959         if ((sel->flags & V4L2_SEL_FLAG_GE) &&
960             !enclosed_rectangle(&sel->r, &rect))
961                 return -ERANGE;
962
963         sel->r = rect;
964         spin_lock_irqsave(&fimc->slock, flags);
965         f->rect = rect;
966         set_bit(ST_FLITE_CONFIG, &fimc->state);
967         spin_unlock_irqrestore(&fimc->slock, flags);
968
969         return 0;
970 }
971
972 static const struct v4l2_ioctl_ops fimc_lite_ioctl_ops = {
973         .vidioc_querycap                = fimc_lite_querycap,
974         .vidioc_enum_fmt_vid_cap_mplane = fimc_lite_enum_fmt_mplane,
975         .vidioc_try_fmt_vid_cap_mplane  = fimc_lite_try_fmt_mplane,
976         .vidioc_s_fmt_vid_cap_mplane    = fimc_lite_s_fmt_mplane,
977         .vidioc_g_fmt_vid_cap_mplane    = fimc_lite_g_fmt_mplane,
978         .vidioc_g_selection             = fimc_lite_g_selection,
979         .vidioc_s_selection             = fimc_lite_s_selection,
980         .vidioc_reqbufs                 = fimc_lite_reqbufs,
981         .vidioc_querybuf                = vb2_ioctl_querybuf,
982         .vidioc_prepare_buf             = vb2_ioctl_prepare_buf,
983         .vidioc_create_bufs             = vb2_ioctl_create_bufs,
984         .vidioc_qbuf                    = vb2_ioctl_qbuf,
985         .vidioc_dqbuf                   = vb2_ioctl_dqbuf,
986         .vidioc_streamon                = fimc_lite_streamon,
987         .vidioc_streamoff               = fimc_lite_streamoff,
988 };
989
990 /* Capture subdev media entity operations */
991 static int fimc_lite_link_setup(struct media_entity *entity,
992                                 const struct media_pad *local,
993                                 const struct media_pad *remote, u32 flags)
994 {
995         struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
996         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
997         unsigned int remote_ent_type = media_entity_type(remote->entity);
998         int ret = 0;
999
1000         if (WARN_ON(fimc == NULL))
1001                 return 0;
1002
1003         v4l2_dbg(1, debug, sd, "%s: %s --> %s, flags: 0x%x. source_id: 0x%x\n",
1004                  __func__, remote->entity->name, local->entity->name,
1005                  flags, fimc->source_subdev_grp_id);
1006
1007         switch (local->index) {
1008         case FLITE_SD_PAD_SINK:
1009                 if (remote_ent_type != MEDIA_ENT_T_V4L2_SUBDEV) {
1010                         ret = -EINVAL;
1011                         break;
1012                 }
1013                 if (flags & MEDIA_LNK_FL_ENABLED) {
1014                         if (fimc->source_subdev_grp_id == 0)
1015                                 fimc->source_subdev_grp_id = sd->grp_id;
1016                         else
1017                                 ret = -EBUSY;
1018                 } else {
1019                         fimc->source_subdev_grp_id = 0;
1020                         fimc->sensor = NULL;
1021                 }
1022                 break;
1023
1024         case FLITE_SD_PAD_SOURCE_DMA:
1025                 if (!(flags & MEDIA_LNK_FL_ENABLED))
1026                         atomic_set(&fimc->out_path, FIMC_IO_NONE);
1027                 else if (remote_ent_type == MEDIA_ENT_T_DEVNODE)
1028                         atomic_set(&fimc->out_path, FIMC_IO_DMA);
1029                 else
1030                         ret = -EINVAL;
1031                 break;
1032
1033         case FLITE_SD_PAD_SOURCE_ISP:
1034                 if (!(flags & MEDIA_LNK_FL_ENABLED))
1035                         atomic_set(&fimc->out_path, FIMC_IO_NONE);
1036                 else if (remote_ent_type == MEDIA_ENT_T_V4L2_SUBDEV)
1037                         atomic_set(&fimc->out_path, FIMC_IO_ISP);
1038                 else
1039                         ret = -EINVAL;
1040                 break;
1041
1042         default:
1043                 v4l2_err(sd, "Invalid pad index\n");
1044                 ret = -EINVAL;
1045         }
1046         mb();
1047
1048         return ret;
1049 }
1050
1051 static const struct media_entity_operations fimc_lite_subdev_media_ops = {
1052         .link_setup = fimc_lite_link_setup,
1053 };
1054
1055 static int fimc_lite_subdev_enum_mbus_code(struct v4l2_subdev *sd,
1056                                            struct v4l2_subdev_fh *fh,
1057                                            struct v4l2_subdev_mbus_code_enum *code)
1058 {
1059         const struct fimc_fmt *fmt;
1060
1061         fmt = fimc_lite_find_format(NULL, NULL, 0, code->index);
1062         if (!fmt)
1063                 return -EINVAL;
1064         code->code = fmt->mbus_code;
1065         return 0;
1066 }
1067
1068 static struct v4l2_mbus_framefmt *__fimc_lite_subdev_get_try_fmt(
1069                         struct v4l2_subdev_fh *fh, unsigned int pad)
1070 {
1071         if (pad != FLITE_SD_PAD_SINK)
1072                 pad = FLITE_SD_PAD_SOURCE_DMA;
1073
1074         return v4l2_subdev_get_try_format(fh, pad);
1075 }
1076
1077 static int fimc_lite_subdev_get_fmt(struct v4l2_subdev *sd,
1078                                     struct v4l2_subdev_fh *fh,
1079                                     struct v4l2_subdev_format *fmt)
1080 {
1081         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1082         struct v4l2_mbus_framefmt *mf = &fmt->format;
1083         struct flite_frame *f = &fimc->inp_frame;
1084
1085         if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
1086                 mf = __fimc_lite_subdev_get_try_fmt(fh, fmt->pad);
1087                 fmt->format = *mf;
1088                 return 0;
1089         }
1090
1091         mutex_lock(&fimc->lock);
1092         mf->colorspace = f->fmt->colorspace;
1093         mf->code = f->fmt->mbus_code;
1094
1095         if (fmt->pad == FLITE_SD_PAD_SINK) {
1096                 /* full camera input frame size */
1097                 mf->width = f->f_width;
1098                 mf->height = f->f_height;
1099         } else {
1100                 /* crop size */
1101                 mf->width = f->rect.width;
1102                 mf->height = f->rect.height;
1103         }
1104         mutex_unlock(&fimc->lock);
1105         return 0;
1106 }
1107
1108 static int fimc_lite_subdev_set_fmt(struct v4l2_subdev *sd,
1109                                     struct v4l2_subdev_fh *fh,
1110                                     struct v4l2_subdev_format *fmt)
1111 {
1112         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1113         struct v4l2_mbus_framefmt *mf = &fmt->format;
1114         struct flite_frame *sink = &fimc->inp_frame;
1115         struct flite_frame *source = &fimc->out_frame;
1116         const struct fimc_fmt *ffmt;
1117
1118         v4l2_dbg(1, debug, sd, "pad%d: code: 0x%x, %dx%d\n",
1119                  fmt->pad, mf->code, mf->width, mf->height);
1120
1121         mutex_lock(&fimc->lock);
1122
1123         if ((atomic_read(&fimc->out_path) == FIMC_IO_ISP &&
1124             sd->entity.stream_count > 0) ||
1125             (atomic_read(&fimc->out_path) == FIMC_IO_DMA &&
1126             vb2_is_busy(&fimc->vb_queue))) {
1127                 mutex_unlock(&fimc->lock);
1128                 return -EBUSY;
1129         }
1130
1131         ffmt = fimc_lite_subdev_try_fmt(fimc, fh, fmt);
1132
1133         if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
1134                 struct v4l2_mbus_framefmt *src_fmt;
1135
1136                 mf = __fimc_lite_subdev_get_try_fmt(fh, fmt->pad);
1137                 *mf = fmt->format;
1138
1139                 if (fmt->pad == FLITE_SD_PAD_SINK) {
1140                         unsigned int pad = FLITE_SD_PAD_SOURCE_DMA;
1141                         src_fmt = __fimc_lite_subdev_get_try_fmt(fh, pad);
1142                         *src_fmt = *mf;
1143                 }
1144
1145                 mutex_unlock(&fimc->lock);
1146                 return 0;
1147         }
1148
1149         if (fmt->pad == FLITE_SD_PAD_SINK) {
1150                 sink->f_width = mf->width;
1151                 sink->f_height = mf->height;
1152                 sink->fmt = ffmt;
1153                 /* Set sink crop rectangle */
1154                 sink->rect.width = mf->width;
1155                 sink->rect.height = mf->height;
1156                 sink->rect.left = 0;
1157                 sink->rect.top = 0;
1158                 /* Reset source format and crop rectangle */
1159                 source->rect = sink->rect;
1160                 source->f_width = mf->width;
1161                 source->f_height = mf->height;
1162         }
1163
1164         mutex_unlock(&fimc->lock);
1165         return 0;
1166 }
1167
1168 static int fimc_lite_subdev_get_selection(struct v4l2_subdev *sd,
1169                                           struct v4l2_subdev_fh *fh,
1170                                           struct v4l2_subdev_selection *sel)
1171 {
1172         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1173         struct flite_frame *f = &fimc->inp_frame;
1174
1175         if ((sel->target != V4L2_SEL_TGT_CROP &&
1176              sel->target != V4L2_SEL_TGT_CROP_BOUNDS) ||
1177              sel->pad != FLITE_SD_PAD_SINK)
1178                 return -EINVAL;
1179
1180         if (sel->which == V4L2_SUBDEV_FORMAT_TRY) {
1181                 sel->r = *v4l2_subdev_get_try_crop(fh, sel->pad);
1182                 return 0;
1183         }
1184
1185         mutex_lock(&fimc->lock);
1186         if (sel->target == V4L2_SEL_TGT_CROP) {
1187                 sel->r = f->rect;
1188         } else {
1189                 sel->r.left = 0;
1190                 sel->r.top = 0;
1191                 sel->r.width = f->f_width;
1192                 sel->r.height = f->f_height;
1193         }
1194         mutex_unlock(&fimc->lock);
1195
1196         v4l2_dbg(1, debug, sd, "%s: (%d,%d) %dx%d, f_w: %d, f_h: %d\n",
1197                  __func__, f->rect.left, f->rect.top, f->rect.width,
1198                  f->rect.height, f->f_width, f->f_height);
1199
1200         return 0;
1201 }
1202
1203 static int fimc_lite_subdev_set_selection(struct v4l2_subdev *sd,
1204                                           struct v4l2_subdev_fh *fh,
1205                                           struct v4l2_subdev_selection *sel)
1206 {
1207         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1208         struct flite_frame *f = &fimc->inp_frame;
1209         int ret = 0;
1210
1211         if (sel->target != V4L2_SEL_TGT_CROP || sel->pad != FLITE_SD_PAD_SINK)
1212                 return -EINVAL;
1213
1214         mutex_lock(&fimc->lock);
1215         fimc_lite_try_crop(fimc, &sel->r);
1216
1217         if (sel->which == V4L2_SUBDEV_FORMAT_TRY) {
1218                 *v4l2_subdev_get_try_crop(fh, sel->pad) = sel->r;
1219         } else {
1220                 unsigned long flags;
1221                 spin_lock_irqsave(&fimc->slock, flags);
1222                 f->rect = sel->r;
1223                 /* Same crop rectangle on the source pad */
1224                 fimc->out_frame.rect = sel->r;
1225                 set_bit(ST_FLITE_CONFIG, &fimc->state);
1226                 spin_unlock_irqrestore(&fimc->slock, flags);
1227         }
1228         mutex_unlock(&fimc->lock);
1229
1230         v4l2_dbg(1, debug, sd, "%s: (%d,%d) %dx%d, f_w: %d, f_h: %d\n",
1231                  __func__, f->rect.left, f->rect.top, f->rect.width,
1232                  f->rect.height, f->f_width, f->f_height);
1233
1234         return ret;
1235 }
1236
1237 static int fimc_lite_subdev_s_stream(struct v4l2_subdev *sd, int on)
1238 {
1239         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1240         unsigned long flags;
1241         int ret;
1242
1243         /*
1244          * Find sensor subdev linked to FIMC-LITE directly or through
1245          * MIPI-CSIS. This is required for configuration where FIMC-LITE
1246          * is used as a subdev only and feeds data internally to FIMC-IS.
1247          * The pipeline links are protected through entity.stream_count
1248          * so there is no need to take the media graph mutex here.
1249          */
1250         fimc->sensor = fimc_find_remote_sensor(&sd->entity);
1251
1252         if (atomic_read(&fimc->out_path) != FIMC_IO_ISP)
1253                 return -ENOIOCTLCMD;
1254
1255         mutex_lock(&fimc->lock);
1256         if (on) {
1257                 flite_hw_reset(fimc);
1258                 ret = fimc_lite_hw_init(fimc, true);
1259                 if (!ret) {
1260                         spin_lock_irqsave(&fimc->slock, flags);
1261                         flite_hw_capture_start(fimc);
1262                         spin_unlock_irqrestore(&fimc->slock, flags);
1263                 }
1264         } else {
1265                 set_bit(ST_FLITE_OFF, &fimc->state);
1266
1267                 spin_lock_irqsave(&fimc->slock, flags);
1268                 /* Make sure both output DMA and local FIFO are disabled */
1269                 flite_hw_set_output_path(fimc, false, false);
1270                 flite_hw_set_dma_buf_mask(fimc, 0);
1271                 flite_hw_capture_stop(fimc);
1272                 spin_unlock_irqrestore(&fimc->slock, flags);
1273
1274                 ret = wait_event_timeout(fimc->irq_queue,
1275                                 !test_bit(ST_FLITE_OFF, &fimc->state),
1276                                 msecs_to_jiffies(200));
1277                 if (ret == 0)
1278                         v4l2_err(sd, "s_stream(0) timeout\n");
1279                 clear_bit(ST_FLITE_RUN, &fimc->state);
1280                 flite_hw_clear_interrupt_mask(fimc);
1281         }
1282
1283         mutex_unlock(&fimc->lock);
1284         return ret;
1285 }
1286
1287 static int fimc_lite_log_status(struct v4l2_subdev *sd)
1288 {
1289         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1290
1291         flite_hw_dump_regs(fimc, __func__);
1292         return 0;
1293 }
1294
1295 static int fimc_lite_subdev_registered(struct v4l2_subdev *sd)
1296 {
1297         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1298         struct vb2_queue *q = &fimc->vb_queue;
1299         struct video_device *vfd = &fimc->ve.vdev;
1300         int ret;
1301
1302         memset(vfd, 0, sizeof(*vfd));
1303         atomic_set(&fimc->out_path, FIMC_IO_DMA);
1304
1305         snprintf(vfd->name, sizeof(vfd->name), "fimc-lite.%d.capture",
1306                  fimc->index);
1307
1308         vfd->fops = &fimc_lite_fops;
1309         vfd->ioctl_ops = &fimc_lite_ioctl_ops;
1310         vfd->v4l2_dev = sd->v4l2_dev;
1311         vfd->minor = -1;
1312         vfd->release = video_device_release_empty;
1313         vfd->queue = q;
1314         fimc->reqbufs_count = 0;
1315
1316         INIT_LIST_HEAD(&fimc->pending_buf_q);
1317         INIT_LIST_HEAD(&fimc->active_buf_q);
1318
1319         memset(q, 0, sizeof(*q));
1320         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1321         q->io_modes = VB2_MMAP | VB2_USERPTR;
1322         q->ops = &fimc_lite_qops;
1323         q->mem_ops = &vb2_dma_contig_memops;
1324         q->buf_struct_size = sizeof(struct flite_buffer);
1325         q->drv_priv = fimc;
1326         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1327         q->lock = &fimc->lock;
1328
1329         ret = vb2_queue_init(q);
1330         if (ret < 0)
1331                 return ret;
1332
1333         fimc->vd_pad.flags = MEDIA_PAD_FL_SINK;
1334         ret = media_entity_init(&vfd->entity, 1, &fimc->vd_pad, 0);
1335         if (ret < 0)
1336                 return ret;
1337
1338         video_set_drvdata(vfd, fimc);
1339         fimc->ve.pipe = v4l2_get_subdev_hostdata(sd);
1340
1341         ret = video_register_device(vfd, VFL_TYPE_GRABBER, -1);
1342         if (ret < 0) {
1343                 media_entity_cleanup(&vfd->entity);
1344                 fimc->ve.pipe = NULL;
1345                 return ret;
1346         }
1347
1348         v4l2_info(sd->v4l2_dev, "Registered %s as /dev/%s\n",
1349                   vfd->name, video_device_node_name(vfd));
1350         return 0;
1351 }
1352
1353 static void fimc_lite_subdev_unregistered(struct v4l2_subdev *sd)
1354 {
1355         struct fimc_lite *fimc = v4l2_get_subdevdata(sd);
1356
1357         if (fimc == NULL)
1358                 return;
1359
1360         mutex_lock(&fimc->lock);
1361
1362         if (video_is_registered(&fimc->ve.vdev)) {
1363                 video_unregister_device(&fimc->ve.vdev);
1364                 media_entity_cleanup(&fimc->ve.vdev.entity);
1365                 fimc->ve.pipe = NULL;
1366         }
1367
1368         mutex_unlock(&fimc->lock);
1369 }
1370
1371 static const struct v4l2_subdev_internal_ops fimc_lite_subdev_internal_ops = {
1372         .registered = fimc_lite_subdev_registered,
1373         .unregistered = fimc_lite_subdev_unregistered,
1374 };
1375
1376 static const struct v4l2_subdev_pad_ops fimc_lite_subdev_pad_ops = {
1377         .enum_mbus_code = fimc_lite_subdev_enum_mbus_code,
1378         .get_selection = fimc_lite_subdev_get_selection,
1379         .set_selection = fimc_lite_subdev_set_selection,
1380         .get_fmt = fimc_lite_subdev_get_fmt,
1381         .set_fmt = fimc_lite_subdev_set_fmt,
1382 };
1383
1384 static const struct v4l2_subdev_video_ops fimc_lite_subdev_video_ops = {
1385         .s_stream = fimc_lite_subdev_s_stream,
1386 };
1387
1388 static const struct v4l2_subdev_core_ops fimc_lite_core_ops = {
1389         .log_status = fimc_lite_log_status,
1390 };
1391
1392 static struct v4l2_subdev_ops fimc_lite_subdev_ops = {
1393         .core = &fimc_lite_core_ops,
1394         .video = &fimc_lite_subdev_video_ops,
1395         .pad = &fimc_lite_subdev_pad_ops,
1396 };
1397
1398 static int fimc_lite_s_ctrl(struct v4l2_ctrl *ctrl)
1399 {
1400         struct fimc_lite *fimc = container_of(ctrl->handler, struct fimc_lite,
1401                                               ctrl_handler);
1402         set_bit(ST_FLITE_CONFIG, &fimc->state);
1403         return 0;
1404 }
1405
1406 static const struct v4l2_ctrl_ops fimc_lite_ctrl_ops = {
1407         .s_ctrl = fimc_lite_s_ctrl,
1408 };
1409
1410 static const struct v4l2_ctrl_config fimc_lite_ctrl = {
1411         .ops    = &fimc_lite_ctrl_ops,
1412         .id     = V4L2_CTRL_CLASS_USER | 0x1001,
1413         .type   = V4L2_CTRL_TYPE_BOOLEAN,
1414         .name   = "Test Pattern 640x480",
1415         .step   = 1,
1416 };
1417
1418 static void fimc_lite_set_default_config(struct fimc_lite *fimc)
1419 {
1420         struct flite_frame *sink = &fimc->inp_frame;
1421         struct flite_frame *source = &fimc->out_frame;
1422
1423         sink->fmt = &fimc_lite_formats[0];
1424         sink->f_width = FLITE_DEFAULT_WIDTH;
1425         sink->f_height = FLITE_DEFAULT_HEIGHT;
1426
1427         sink->rect.width = FLITE_DEFAULT_WIDTH;
1428         sink->rect.height = FLITE_DEFAULT_HEIGHT;
1429         sink->rect.left = 0;
1430         sink->rect.top = 0;
1431
1432         *source = *sink;
1433 }
1434
1435 static int fimc_lite_create_capture_subdev(struct fimc_lite *fimc)
1436 {
1437         struct v4l2_ctrl_handler *handler = &fimc->ctrl_handler;
1438         struct v4l2_subdev *sd = &fimc->subdev;
1439         int ret;
1440
1441         v4l2_subdev_init(sd, &fimc_lite_subdev_ops);
1442         sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
1443         snprintf(sd->name, sizeof(sd->name), "FIMC-LITE.%d", fimc->index);
1444
1445         fimc->subdev_pads[FLITE_SD_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
1446         fimc->subdev_pads[FLITE_SD_PAD_SOURCE_DMA].flags = MEDIA_PAD_FL_SOURCE;
1447         fimc->subdev_pads[FLITE_SD_PAD_SOURCE_ISP].flags = MEDIA_PAD_FL_SOURCE;
1448         ret = media_entity_init(&sd->entity, FLITE_SD_PADS_NUM,
1449                                 fimc->subdev_pads, 0);
1450         if (ret)
1451                 return ret;
1452
1453         v4l2_ctrl_handler_init(handler, 1);
1454         fimc->test_pattern = v4l2_ctrl_new_custom(handler, &fimc_lite_ctrl,
1455                                                   NULL);
1456         if (handler->error) {
1457                 media_entity_cleanup(&sd->entity);
1458                 return handler->error;
1459         }
1460
1461         sd->ctrl_handler = handler;
1462         sd->internal_ops = &fimc_lite_subdev_internal_ops;
1463         sd->entity.ops = &fimc_lite_subdev_media_ops;
1464         sd->owner = THIS_MODULE;
1465         v4l2_set_subdevdata(sd, fimc);
1466
1467         return 0;
1468 }
1469
1470 static void fimc_lite_unregister_capture_subdev(struct fimc_lite *fimc)
1471 {
1472         struct v4l2_subdev *sd = &fimc->subdev;
1473
1474         v4l2_device_unregister_subdev(sd);
1475         media_entity_cleanup(&sd->entity);
1476         v4l2_ctrl_handler_free(&fimc->ctrl_handler);
1477         v4l2_set_subdevdata(sd, NULL);
1478 }
1479
1480 static void fimc_lite_clk_put(struct fimc_lite *fimc)
1481 {
1482         if (IS_ERR(fimc->clock))
1483                 return;
1484
1485         clk_unprepare(fimc->clock);
1486         clk_put(fimc->clock);
1487         fimc->clock = ERR_PTR(-EINVAL);
1488 }
1489
1490 static int fimc_lite_clk_get(struct fimc_lite *fimc)
1491 {
1492         int ret;
1493
1494         fimc->clock = clk_get(&fimc->pdev->dev, FLITE_CLK_NAME);
1495         if (IS_ERR(fimc->clock))
1496                 return PTR_ERR(fimc->clock);
1497
1498         ret = clk_prepare(fimc->clock);
1499         if (ret < 0) {
1500                 clk_put(fimc->clock);
1501                 fimc->clock = ERR_PTR(-EINVAL);
1502         }
1503         return ret;
1504 }
1505
1506 static const struct of_device_id flite_of_match[];
1507
1508 static int fimc_lite_probe(struct platform_device *pdev)
1509 {
1510         struct flite_drvdata *drv_data = NULL;
1511         struct device *dev = &pdev->dev;
1512         const struct of_device_id *of_id;
1513         struct fimc_lite *fimc;
1514         struct resource *res;
1515         int ret;
1516
1517         if (!dev->of_node)
1518                 return -ENODEV;
1519
1520         fimc = devm_kzalloc(dev, sizeof(*fimc), GFP_KERNEL);
1521         if (!fimc)
1522                 return -ENOMEM;
1523
1524         of_id = of_match_node(flite_of_match, dev->of_node);
1525         if (of_id)
1526                 drv_data = (struct flite_drvdata *)of_id->data;
1527         fimc->index = of_alias_get_id(dev->of_node, "fimc-lite");
1528
1529         if (!drv_data || fimc->index >= drv_data->num_instances ||
1530                                                 fimc->index < 0) {
1531                 dev_err(dev, "Wrong %s node alias\n",
1532                                         dev->of_node->full_name);
1533                 return -EINVAL;
1534         }
1535
1536         fimc->dd = drv_data;
1537         fimc->pdev = pdev;
1538
1539         init_waitqueue_head(&fimc->irq_queue);
1540         spin_lock_init(&fimc->slock);
1541         mutex_init(&fimc->lock);
1542
1543         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1544         fimc->regs = devm_ioremap_resource(dev, res);
1545         if (IS_ERR(fimc->regs))
1546                 return PTR_ERR(fimc->regs);
1547
1548         res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
1549         if (res == NULL) {
1550                 dev_err(dev, "Failed to get IRQ resource\n");
1551                 return -ENXIO;
1552         }
1553
1554         ret = fimc_lite_clk_get(fimc);
1555         if (ret)
1556                 return ret;
1557
1558         ret = devm_request_irq(dev, res->start, flite_irq_handler,
1559                                0, dev_name(dev), fimc);
1560         if (ret) {
1561                 dev_err(dev, "Failed to install irq (%d)\n", ret);
1562                 goto err_clk;
1563         }
1564
1565         /* The video node will be created within the subdev's registered() op */
1566         ret = fimc_lite_create_capture_subdev(fimc);
1567         if (ret)
1568                 goto err_clk;
1569
1570         platform_set_drvdata(pdev, fimc);
1571
1572         fimc->alloc_ctx = vb2_dma_contig_init_ctx(dev);
1573         if (IS_ERR(fimc->alloc_ctx)) {
1574                 ret = PTR_ERR(fimc->alloc_ctx);
1575                 goto err_sd;
1576         }
1577
1578         fimc_lite_set_default_config(fimc);
1579
1580         pm_runtime_enable(dev);
1581
1582         dev_dbg(dev, "FIMC-LITE.%d registered successfully\n",
1583                 fimc->index);
1584         return 0;
1585
1586 err_sd:
1587         fimc_lite_unregister_capture_subdev(fimc);
1588 err_clk:
1589         fimc_lite_clk_put(fimc);
1590         return ret;
1591 }
1592
1593 static int fimc_lite_runtime_resume(struct device *dev)
1594 {
1595         struct fimc_lite *fimc = dev_get_drvdata(dev);
1596
1597         clk_enable(fimc->clock);
1598         return 0;
1599 }
1600
1601 static int fimc_lite_runtime_suspend(struct device *dev)
1602 {
1603         struct fimc_lite *fimc = dev_get_drvdata(dev);
1604
1605         clk_disable(fimc->clock);
1606         return 0;
1607 }
1608
1609 #ifdef CONFIG_PM_SLEEP
1610 static int fimc_lite_resume(struct device *dev)
1611 {
1612         struct fimc_lite *fimc = dev_get_drvdata(dev);
1613         struct flite_buffer *buf;
1614         unsigned long flags;
1615         int i;
1616
1617         spin_lock_irqsave(&fimc->slock, flags);
1618         if (!test_and_clear_bit(ST_LPM, &fimc->state) ||
1619             !test_bit(ST_FLITE_IN_USE, &fimc->state)) {
1620                 spin_unlock_irqrestore(&fimc->slock, flags);
1621                 return 0;
1622         }
1623         flite_hw_reset(fimc);
1624         spin_unlock_irqrestore(&fimc->slock, flags);
1625
1626         if (!test_and_clear_bit(ST_FLITE_SUSPENDED, &fimc->state))
1627                 return 0;
1628
1629         INIT_LIST_HEAD(&fimc->active_buf_q);
1630         fimc_pipeline_call(&fimc->ve, open,
1631                            &fimc->ve.vdev.entity, false);
1632         fimc_lite_hw_init(fimc, atomic_read(&fimc->out_path) == FIMC_IO_ISP);
1633         clear_bit(ST_FLITE_SUSPENDED, &fimc->state);
1634
1635         for (i = 0; i < fimc->reqbufs_count; i++) {
1636                 if (list_empty(&fimc->pending_buf_q))
1637                         break;
1638                 buf = fimc_lite_pending_queue_pop(fimc);
1639                 buffer_queue(&buf->vb);
1640         }
1641         return 0;
1642 }
1643
1644 static int fimc_lite_suspend(struct device *dev)
1645 {
1646         struct fimc_lite *fimc = dev_get_drvdata(dev);
1647         bool suspend = test_bit(ST_FLITE_IN_USE, &fimc->state);
1648         int ret;
1649
1650         if (test_and_set_bit(ST_LPM, &fimc->state))
1651                 return 0;
1652
1653         ret = fimc_lite_stop_capture(fimc, suspend);
1654         if (ret < 0 || !fimc_lite_active(fimc))
1655                 return ret;
1656
1657         return fimc_pipeline_call(&fimc->ve, close);
1658 }
1659 #endif /* CONFIG_PM_SLEEP */
1660
1661 static int fimc_lite_remove(struct platform_device *pdev)
1662 {
1663         struct fimc_lite *fimc = platform_get_drvdata(pdev);
1664         struct device *dev = &pdev->dev;
1665
1666         pm_runtime_disable(dev);
1667         pm_runtime_set_suspended(dev);
1668         fimc_lite_unregister_capture_subdev(fimc);
1669         vb2_dma_contig_cleanup_ctx(fimc->alloc_ctx);
1670         fimc_lite_clk_put(fimc);
1671
1672         dev_info(dev, "Driver unloaded\n");
1673         return 0;
1674 }
1675
1676 static const struct dev_pm_ops fimc_lite_pm_ops = {
1677         SET_SYSTEM_SLEEP_PM_OPS(fimc_lite_suspend, fimc_lite_resume)
1678         SET_RUNTIME_PM_OPS(fimc_lite_runtime_suspend, fimc_lite_runtime_resume,
1679                            NULL)
1680 };
1681
1682 /* EXYNOS3250 */
1683 static struct flite_drvdata fimc_lite_drvdata_exynos3250 = {
1684         .max_width              = 8192,
1685         .max_height             = 8192,
1686         .out_width_align        = 8,
1687         .win_hor_offs_align     = 2,
1688         .out_hor_offs_align     = 8,
1689         .max_dma_bufs           = 32,
1690         .num_instances          = 2,
1691         .has_out_local_enable   = 1,
1692 };
1693
1694 /* EXYNOS4212, EXYNOS4412 */
1695 static struct flite_drvdata fimc_lite_drvdata_exynos4 = {
1696         .max_width              = 8192,
1697         .max_height             = 8192,
1698         .out_width_align        = 8,
1699         .win_hor_offs_align     = 2,
1700         .out_hor_offs_align     = 8,
1701         .max_dma_bufs           = 1,
1702         .num_instances          = 2,
1703 };
1704
1705 /* EXYNOS5250 */
1706 static struct flite_drvdata fimc_lite_drvdata_exynos5 = {
1707         .max_width              = 8192,
1708         .max_height             = 8192,
1709         .out_width_align        = 8,
1710         .win_hor_offs_align     = 2,
1711         .out_hor_offs_align     = 8,
1712         .max_dma_bufs           = 32,
1713         .num_instances          = 3,
1714         .has_out_local_enable   = 1,
1715 };
1716
1717 static const struct of_device_id flite_of_match[] = {
1718         {
1719                 .compatible = "samsung,exynos3250-fimc-lite",
1720                 .data = &fimc_lite_drvdata_exynos3250,
1721         }, {
1722                 .compatible = "samsung,exynos4212-fimc-lite",
1723                 .data = &fimc_lite_drvdata_exynos4,
1724         }, {
1725                 .compatible = "samsung,exynos5250-fimc-lite",
1726                 .data = &fimc_lite_drvdata_exynos5,
1727         },
1728         { /* sentinel */ },
1729 };
1730 MODULE_DEVICE_TABLE(of, flite_of_match);
1731
1732 static struct platform_driver fimc_lite_driver = {
1733         .probe          = fimc_lite_probe,
1734         .remove         = fimc_lite_remove,
1735         .driver = {
1736                 .of_match_table = flite_of_match,
1737                 .name           = FIMC_LITE_DRV_NAME,
1738                 .owner          = THIS_MODULE,
1739                 .pm             = &fimc_lite_pm_ops,
1740         }
1741 };
1742 module_platform_driver(fimc_lite_driver);
1743 MODULE_LICENSE("GPL");
1744 MODULE_ALIAS("platform:" FIMC_LITE_DRV_NAME);