]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/media/platform/s5p-fimc/fimc-capture.c
Merge branch 'for-next' of git://git.kernel.org/pub/scm/linux/kernel/git/nab/target...
[karo-tx-linux.git] / drivers / media / platform / s5p-fimc / fimc-capture.c
1 /*
2  * Samsung S5P/EXYNOS4 SoC series camera interface (camera capture) driver
3  *
4  * Copyright (C) 2010 - 2012 Samsung Electronics Co., Ltd.
5  * 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
12 #include <linux/module.h>
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/errno.h>
16 #include <linux/bug.h>
17 #include <linux/interrupt.h>
18 #include <linux/device.h>
19 #include <linux/pm_runtime.h>
20 #include <linux/list.h>
21 #include <linux/slab.h>
22
23 #include <linux/videodev2.h>
24 #include <media/v4l2-device.h>
25 #include <media/v4l2-ioctl.h>
26 #include <media/v4l2-mem2mem.h>
27 #include <media/videobuf2-core.h>
28 #include <media/videobuf2-dma-contig.h>
29
30 #include "fimc-mdevice.h"
31 #include "fimc-core.h"
32 #include "fimc-reg.h"
33
34 static int fimc_capture_hw_init(struct fimc_dev *fimc)
35 {
36         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
37         struct fimc_pipeline *p = &fimc->pipeline;
38         struct fimc_sensor_info *sensor;
39         unsigned long flags;
40         int ret = 0;
41
42         if (p->subdevs[IDX_SENSOR] == NULL || ctx == NULL)
43                 return -ENXIO;
44         if (ctx->s_frame.fmt == NULL)
45                 return -EINVAL;
46
47         sensor = v4l2_get_subdev_hostdata(p->subdevs[IDX_SENSOR]);
48
49         spin_lock_irqsave(&fimc->slock, flags);
50         fimc_prepare_dma_offset(ctx, &ctx->d_frame);
51         fimc_set_yuv_order(ctx);
52
53         fimc_hw_set_camera_polarity(fimc, &sensor->pdata);
54         fimc_hw_set_camera_type(fimc, &sensor->pdata);
55         fimc_hw_set_camera_source(fimc, &sensor->pdata);
56         fimc_hw_set_camera_offset(fimc, &ctx->s_frame);
57
58         ret = fimc_set_scaler_info(ctx);
59         if (!ret) {
60                 fimc_hw_set_input_path(ctx);
61                 fimc_hw_set_prescaler(ctx);
62                 fimc_hw_set_mainscaler(ctx);
63                 fimc_hw_set_target_format(ctx);
64                 fimc_hw_set_rotation(ctx);
65                 fimc_hw_set_effect(ctx);
66                 fimc_hw_set_output_path(ctx);
67                 fimc_hw_set_out_dma(ctx);
68                 if (fimc->variant->has_alpha)
69                         fimc_hw_set_rgb_alpha(ctx);
70                 clear_bit(ST_CAPT_APPLY_CFG, &fimc->state);
71         }
72         spin_unlock_irqrestore(&fimc->slock, flags);
73         return ret;
74 }
75
76 /*
77  * Reinitialize the driver so it is ready to start the streaming again.
78  * Set fimc->state to indicate stream off and the hardware shut down state.
79  * If not suspending (@suspend is false), return any buffers to videobuf2.
80  * Otherwise put any owned buffers onto the pending buffers queue, so they
81  * can be re-spun when the device is being resumed. Also perform FIMC
82  * software reset and disable streaming on the whole pipeline if required.
83  */
84 static int fimc_capture_state_cleanup(struct fimc_dev *fimc, bool suspend)
85 {
86         struct fimc_vid_cap *cap = &fimc->vid_cap;
87         struct fimc_vid_buffer *buf;
88         unsigned long flags;
89         bool streaming;
90
91         spin_lock_irqsave(&fimc->slock, flags);
92         streaming = fimc->state & (1 << ST_CAPT_ISP_STREAM);
93
94         fimc->state &= ~(1 << ST_CAPT_RUN | 1 << ST_CAPT_SHUT |
95                          1 << ST_CAPT_STREAM | 1 << ST_CAPT_ISP_STREAM);
96         if (suspend)
97                 fimc->state |= (1 << ST_CAPT_SUSPENDED);
98         else
99                 fimc->state &= ~(1 << ST_CAPT_PEND | 1 << ST_CAPT_SUSPENDED);
100
101         /* Release unused buffers */
102         while (!suspend && !list_empty(&cap->pending_buf_q)) {
103                 buf = fimc_pending_queue_pop(cap);
104                 vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
105         }
106         /* If suspending put unused buffers onto pending queue */
107         while (!list_empty(&cap->active_buf_q)) {
108                 buf = fimc_active_queue_pop(cap);
109                 if (suspend)
110                         fimc_pending_queue_add(cap, buf);
111                 else
112                         vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
113         }
114
115         fimc_hw_reset(fimc);
116         cap->buf_index = 0;
117
118         spin_unlock_irqrestore(&fimc->slock, flags);
119
120         if (streaming)
121                 return fimc_pipeline_call(fimc, set_stream,
122                                           &fimc->pipeline, 0);
123         else
124                 return 0;
125 }
126
127 static int fimc_stop_capture(struct fimc_dev *fimc, bool suspend)
128 {
129         unsigned long flags;
130
131         if (!fimc_capture_active(fimc))
132                 return 0;
133
134         spin_lock_irqsave(&fimc->slock, flags);
135         set_bit(ST_CAPT_SHUT, &fimc->state);
136         fimc_deactivate_capture(fimc);
137         spin_unlock_irqrestore(&fimc->slock, flags);
138
139         wait_event_timeout(fimc->irq_queue,
140                            !test_bit(ST_CAPT_SHUT, &fimc->state),
141                            (2*HZ/10)); /* 200 ms */
142
143         return fimc_capture_state_cleanup(fimc, suspend);
144 }
145
146 /**
147  * fimc_capture_config_update - apply the camera interface configuration
148  *
149  * To be called from within the interrupt handler with fimc.slock
150  * spinlock held. It updates the camera pixel crop, rotation and
151  * image flip in H/W.
152  */
153 static int fimc_capture_config_update(struct fimc_ctx *ctx)
154 {
155         struct fimc_dev *fimc = ctx->fimc_dev;
156         int ret;
157
158         fimc_hw_set_camera_offset(fimc, &ctx->s_frame);
159
160         ret = fimc_set_scaler_info(ctx);
161         if (ret)
162                 return ret;
163
164         fimc_hw_set_prescaler(ctx);
165         fimc_hw_set_mainscaler(ctx);
166         fimc_hw_set_target_format(ctx);
167         fimc_hw_set_rotation(ctx);
168         fimc_hw_set_effect(ctx);
169         fimc_prepare_dma_offset(ctx, &ctx->d_frame);
170         fimc_hw_set_out_dma(ctx);
171         if (fimc->variant->has_alpha)
172                 fimc_hw_set_rgb_alpha(ctx);
173
174         clear_bit(ST_CAPT_APPLY_CFG, &fimc->state);
175         return ret;
176 }
177
178 void fimc_capture_irq_handler(struct fimc_dev *fimc, int deq_buf)
179 {
180         struct fimc_vid_cap *cap = &fimc->vid_cap;
181         struct fimc_vid_buffer *v_buf;
182         struct timeval *tv;
183         struct timespec ts;
184
185         if (test_and_clear_bit(ST_CAPT_SHUT, &fimc->state)) {
186                 wake_up(&fimc->irq_queue);
187                 goto done;
188         }
189
190         if (!list_empty(&cap->active_buf_q) &&
191             test_bit(ST_CAPT_RUN, &fimc->state) && deq_buf) {
192                 ktime_get_real_ts(&ts);
193
194                 v_buf = fimc_active_queue_pop(cap);
195
196                 tv = &v_buf->vb.v4l2_buf.timestamp;
197                 tv->tv_sec = ts.tv_sec;
198                 tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
199                 v_buf->vb.v4l2_buf.sequence = cap->frame_count++;
200
201                 vb2_buffer_done(&v_buf->vb, VB2_BUF_STATE_DONE);
202         }
203
204         if (!list_empty(&cap->pending_buf_q)) {
205
206                 v_buf = fimc_pending_queue_pop(cap);
207                 fimc_hw_set_output_addr(fimc, &v_buf->paddr, cap->buf_index);
208                 v_buf->index = cap->buf_index;
209
210                 /* Move the buffer to the capture active queue */
211                 fimc_active_queue_add(cap, v_buf);
212
213                 dbg("next frame: %d, done frame: %d",
214                     fimc_hw_get_frame_index(fimc), v_buf->index);
215
216                 if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
217                         cap->buf_index = 0;
218         }
219
220         if (cap->active_buf_cnt == 0) {
221                 if (deq_buf)
222                         clear_bit(ST_CAPT_RUN, &fimc->state);
223
224                 if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
225                         cap->buf_index = 0;
226         } else {
227                 set_bit(ST_CAPT_RUN, &fimc->state);
228         }
229
230         if (test_bit(ST_CAPT_APPLY_CFG, &fimc->state))
231                 fimc_capture_config_update(cap->ctx);
232 done:
233         if (cap->active_buf_cnt == 1) {
234                 fimc_deactivate_capture(fimc);
235                 clear_bit(ST_CAPT_STREAM, &fimc->state);
236         }
237
238         dbg("frame: %d, active_buf_cnt: %d",
239             fimc_hw_get_frame_index(fimc), cap->active_buf_cnt);
240 }
241
242
243 static int start_streaming(struct vb2_queue *q, unsigned int count)
244 {
245         struct fimc_ctx *ctx = q->drv_priv;
246         struct fimc_dev *fimc = ctx->fimc_dev;
247         struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
248         int min_bufs;
249         int ret;
250
251         vid_cap->frame_count = 0;
252
253         ret = fimc_capture_hw_init(fimc);
254         if (ret) {
255                 fimc_capture_state_cleanup(fimc, false);
256                 return ret;
257         }
258
259         set_bit(ST_CAPT_PEND, &fimc->state);
260
261         min_bufs = fimc->vid_cap.reqbufs_count > 1 ? 2 : 1;
262
263         if (vid_cap->active_buf_cnt >= min_bufs &&
264             !test_and_set_bit(ST_CAPT_STREAM, &fimc->state)) {
265                 fimc_activate_capture(ctx);
266
267                 if (!test_and_set_bit(ST_CAPT_ISP_STREAM, &fimc->state))
268                         fimc_pipeline_call(fimc, set_stream,
269                                            &fimc->pipeline, 1);
270         }
271
272         return 0;
273 }
274
275 static int stop_streaming(struct vb2_queue *q)
276 {
277         struct fimc_ctx *ctx = q->drv_priv;
278         struct fimc_dev *fimc = ctx->fimc_dev;
279
280         if (!fimc_capture_active(fimc))
281                 return -EINVAL;
282
283         return fimc_stop_capture(fimc, false);
284 }
285
286 int fimc_capture_suspend(struct fimc_dev *fimc)
287 {
288         bool suspend = fimc_capture_busy(fimc);
289
290         int ret = fimc_stop_capture(fimc, suspend);
291         if (ret)
292                 return ret;
293         return fimc_pipeline_call(fimc, close, &fimc->pipeline);
294 }
295
296 static void buffer_queue(struct vb2_buffer *vb);
297
298 int fimc_capture_resume(struct fimc_dev *fimc)
299 {
300         struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
301         struct fimc_vid_buffer *buf;
302         int i;
303
304         if (!test_and_clear_bit(ST_CAPT_SUSPENDED, &fimc->state))
305                 return 0;
306
307         INIT_LIST_HEAD(&fimc->vid_cap.active_buf_q);
308         vid_cap->buf_index = 0;
309         fimc_pipeline_call(fimc, open, &fimc->pipeline,
310                            &vid_cap->vfd.entity, false);
311         fimc_capture_hw_init(fimc);
312
313         clear_bit(ST_CAPT_SUSPENDED, &fimc->state);
314
315         for (i = 0; i < vid_cap->reqbufs_count; i++) {
316                 if (list_empty(&vid_cap->pending_buf_q))
317                         break;
318                 buf = fimc_pending_queue_pop(vid_cap);
319                 buffer_queue(&buf->vb);
320         }
321         return 0;
322
323 }
324
325 static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *pfmt,
326                        unsigned int *num_buffers, unsigned int *num_planes,
327                        unsigned int sizes[], void *allocators[])
328 {
329         const struct v4l2_pix_format_mplane *pixm = NULL;
330         struct fimc_ctx *ctx = vq->drv_priv;
331         struct fimc_frame *frame = &ctx->d_frame;
332         struct fimc_fmt *fmt = frame->fmt;
333         unsigned long wh;
334         int i;
335
336         if (pfmt) {
337                 pixm = &pfmt->fmt.pix_mp;
338                 fmt = fimc_find_format(&pixm->pixelformat, NULL,
339                                        FMT_FLAGS_CAM | FMT_FLAGS_M2M, -1);
340                 wh = pixm->width * pixm->height;
341         } else {
342                 wh = frame->f_width * frame->f_height;
343         }
344
345         if (fmt == NULL)
346                 return -EINVAL;
347
348         *num_planes = fmt->memplanes;
349
350         for (i = 0; i < fmt->memplanes; i++) {
351                 unsigned int size = (wh * fmt->depth[i]) / 8;
352                 if (pixm)
353                         sizes[i] = max(size, pixm->plane_fmt[i].sizeimage);
354                 else
355                         sizes[i] = max_t(u32, size, frame->payload[i]);
356
357                 allocators[i] = ctx->fimc_dev->alloc_ctx;
358         }
359
360         return 0;
361 }
362
363 static int buffer_prepare(struct vb2_buffer *vb)
364 {
365         struct vb2_queue *vq = vb->vb2_queue;
366         struct fimc_ctx *ctx = vq->drv_priv;
367         int i;
368
369         if (ctx->d_frame.fmt == NULL)
370                 return -EINVAL;
371
372         for (i = 0; i < ctx->d_frame.fmt->memplanes; i++) {
373                 unsigned long size = ctx->d_frame.payload[i];
374
375                 if (vb2_plane_size(vb, i) < size) {
376                         v4l2_err(&ctx->fimc_dev->vid_cap.vfd,
377                                  "User buffer too small (%ld < %ld)\n",
378                                  vb2_plane_size(vb, i), size);
379                         return -EINVAL;
380                 }
381                 vb2_set_plane_payload(vb, i, size);
382         }
383
384         return 0;
385 }
386
387 static void buffer_queue(struct vb2_buffer *vb)
388 {
389         struct fimc_vid_buffer *buf
390                 = container_of(vb, struct fimc_vid_buffer, vb);
391         struct fimc_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
392         struct fimc_dev *fimc = ctx->fimc_dev;
393         struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
394         unsigned long flags;
395         int min_bufs;
396
397         spin_lock_irqsave(&fimc->slock, flags);
398         fimc_prepare_addr(ctx, &buf->vb, &ctx->d_frame, &buf->paddr);
399
400         if (!test_bit(ST_CAPT_SUSPENDED, &fimc->state) &&
401             !test_bit(ST_CAPT_STREAM, &fimc->state) &&
402             vid_cap->active_buf_cnt < FIMC_MAX_OUT_BUFS) {
403                 /* Setup the buffer directly for processing. */
404                 int buf_id = (vid_cap->reqbufs_count == 1) ? -1 :
405                                 vid_cap->buf_index;
406
407                 fimc_hw_set_output_addr(fimc, &buf->paddr, buf_id);
408                 buf->index = vid_cap->buf_index;
409                 fimc_active_queue_add(vid_cap, buf);
410
411                 if (++vid_cap->buf_index >= FIMC_MAX_OUT_BUFS)
412                         vid_cap->buf_index = 0;
413         } else {
414                 fimc_pending_queue_add(vid_cap, buf);
415         }
416
417         min_bufs = vid_cap->reqbufs_count > 1 ? 2 : 1;
418
419
420         if (vb2_is_streaming(&vid_cap->vbq) &&
421             vid_cap->active_buf_cnt >= min_bufs &&
422             !test_and_set_bit(ST_CAPT_STREAM, &fimc->state)) {
423                 fimc_activate_capture(ctx);
424                 spin_unlock_irqrestore(&fimc->slock, flags);
425
426                 if (!test_and_set_bit(ST_CAPT_ISP_STREAM, &fimc->state))
427                         fimc_pipeline_call(fimc, set_stream,
428                                            &fimc->pipeline, 1);
429                 return;
430         }
431         spin_unlock_irqrestore(&fimc->slock, flags);
432 }
433
434 static void fimc_lock(struct vb2_queue *vq)
435 {
436         struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
437         mutex_lock(&ctx->fimc_dev->lock);
438 }
439
440 static void fimc_unlock(struct vb2_queue *vq)
441 {
442         struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
443         mutex_unlock(&ctx->fimc_dev->lock);
444 }
445
446 static struct vb2_ops fimc_capture_qops = {
447         .queue_setup            = queue_setup,
448         .buf_prepare            = buffer_prepare,
449         .buf_queue              = buffer_queue,
450         .wait_prepare           = fimc_unlock,
451         .wait_finish            = fimc_lock,
452         .start_streaming        = start_streaming,
453         .stop_streaming         = stop_streaming,
454 };
455
456 /**
457  * fimc_capture_ctrls_create - initialize the control handler
458  * Initialize the capture video node control handler and fill it
459  * with the FIMC controls. Inherit any sensor's controls if the
460  * 'user_subdev_api' flag is false (default behaviour).
461  * This function need to be called with the graph mutex held.
462  */
463 int fimc_capture_ctrls_create(struct fimc_dev *fimc)
464 {
465         struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
466         int ret;
467
468         if (WARN_ON(vid_cap->ctx == NULL))
469                 return -ENXIO;
470         if (vid_cap->ctx->ctrls.ready)
471                 return 0;
472
473         ret = fimc_ctrls_create(vid_cap->ctx);
474         if (ret || vid_cap->user_subdev_api || !vid_cap->ctx->ctrls.ready)
475                 return ret;
476
477         return v4l2_ctrl_add_handler(&vid_cap->ctx->ctrls.handler,
478                     fimc->pipeline.subdevs[IDX_SENSOR]->ctrl_handler, NULL);
479 }
480
481 static int fimc_capture_set_default_format(struct fimc_dev *fimc);
482
483 static int fimc_capture_open(struct file *file)
484 {
485         struct fimc_dev *fimc = video_drvdata(file);
486         int ret = -EBUSY;
487
488         dbg("pid: %d, state: 0x%lx", task_pid_nr(current), fimc->state);
489
490         if (mutex_lock_interruptible(&fimc->lock))
491                 return -ERESTARTSYS;
492
493         if (fimc_m2m_active(fimc))
494                 goto unlock;
495
496         set_bit(ST_CAPT_BUSY, &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) {
503                 pm_runtime_put(&fimc->pdev->dev);
504                 goto unlock;
505         }
506
507         if (++fimc->vid_cap.refcnt == 1) {
508                 ret = fimc_pipeline_call(fimc, open, &fimc->pipeline,
509                                          &fimc->vid_cap.vfd.entity, true);
510
511                 if (!ret && !fimc->vid_cap.user_subdev_api)
512                         ret = fimc_capture_set_default_format(fimc);
513
514                 if (!ret)
515                         ret = fimc_capture_ctrls_create(fimc);
516
517                 if (ret < 0) {
518                         clear_bit(ST_CAPT_BUSY, &fimc->state);
519                         pm_runtime_put_sync(&fimc->pdev->dev);
520                         fimc->vid_cap.refcnt--;
521                         v4l2_fh_release(file);
522                 }
523         }
524 unlock:
525         mutex_unlock(&fimc->lock);
526         return ret;
527 }
528
529 static int fimc_capture_close(struct file *file)
530 {
531         struct fimc_dev *fimc = video_drvdata(file);
532         int ret;
533
534         dbg("pid: %d, state: 0x%lx", task_pid_nr(current), fimc->state);
535
536         if (mutex_lock_interruptible(&fimc->lock))
537                 return -ERESTARTSYS;
538
539         if (--fimc->vid_cap.refcnt == 0) {
540                 clear_bit(ST_CAPT_BUSY, &fimc->state);
541                 fimc_stop_capture(fimc, false);
542                 fimc_pipeline_call(fimc, close, &fimc->pipeline);
543                 clear_bit(ST_CAPT_SUSPENDED, &fimc->state);
544         }
545
546         pm_runtime_put(&fimc->pdev->dev);
547
548         if (fimc->vid_cap.refcnt == 0) {
549                 vb2_queue_release(&fimc->vid_cap.vbq);
550                 fimc_ctrls_delete(fimc->vid_cap.ctx);
551         }
552
553         ret = v4l2_fh_release(file);
554
555         mutex_unlock(&fimc->lock);
556         return ret;
557 }
558
559 static unsigned int fimc_capture_poll(struct file *file,
560                                       struct poll_table_struct *wait)
561 {
562         struct fimc_dev *fimc = video_drvdata(file);
563         int ret;
564
565         if (mutex_lock_interruptible(&fimc->lock))
566                 return POLL_ERR;
567
568         ret = vb2_poll(&fimc->vid_cap.vbq, file, wait);
569         mutex_unlock(&fimc->lock);
570
571         return ret;
572 }
573
574 static int fimc_capture_mmap(struct file *file, struct vm_area_struct *vma)
575 {
576         struct fimc_dev *fimc = video_drvdata(file);
577         int ret;
578
579         if (mutex_lock_interruptible(&fimc->lock))
580                 return -ERESTARTSYS;
581
582         ret = vb2_mmap(&fimc->vid_cap.vbq, vma);
583         mutex_unlock(&fimc->lock);
584
585         return ret;
586 }
587
588 static const struct v4l2_file_operations fimc_capture_fops = {
589         .owner          = THIS_MODULE,
590         .open           = fimc_capture_open,
591         .release        = fimc_capture_close,
592         .poll           = fimc_capture_poll,
593         .unlocked_ioctl = video_ioctl2,
594         .mmap           = fimc_capture_mmap,
595 };
596
597 /*
598  * Format and crop negotiation helpers
599  */
600
601 static struct fimc_fmt *fimc_capture_try_format(struct fimc_ctx *ctx,
602                                                 u32 *width, u32 *height,
603                                                 u32 *code, u32 *fourcc, int pad)
604 {
605         bool rotation = ctx->rotation == 90 || ctx->rotation == 270;
606         struct fimc_dev *fimc = ctx->fimc_dev;
607         struct fimc_variant *var = fimc->variant;
608         struct fimc_pix_limit *pl = var->pix_limit;
609         struct fimc_frame *dst = &ctx->d_frame;
610         u32 depth, min_w, max_w, min_h, align_h = 3;
611         u32 mask = FMT_FLAGS_CAM;
612         struct fimc_fmt *ffmt;
613
614         /* Color conversion from/to JPEG is not supported */
615         if (code && ctx->s_frame.fmt && pad == FIMC_SD_PAD_SOURCE &&
616             fimc_fmt_is_jpeg(ctx->s_frame.fmt->color))
617                 *code = V4L2_MBUS_FMT_JPEG_1X8;
618
619         if (fourcc && *fourcc != V4L2_PIX_FMT_JPEG && pad != FIMC_SD_PAD_SINK)
620                 mask |= FMT_FLAGS_M2M;
621
622         ffmt = fimc_find_format(fourcc, code, mask, 0);
623         if (WARN_ON(!ffmt))
624                 return NULL;
625         if (code)
626                 *code = ffmt->mbus_code;
627         if (fourcc)
628                 *fourcc = ffmt->fourcc;
629
630         if (pad == FIMC_SD_PAD_SINK) {
631                 max_w = fimc_fmt_is_jpeg(ffmt->color) ?
632                         pl->scaler_dis_w : pl->scaler_en_w;
633                 /* Apply the camera input interface pixel constraints */
634                 v4l_bound_align_image(width, max_t(u32, *width, 32), max_w, 4,
635                                       height, max_t(u32, *height, 32),
636                                       FIMC_CAMIF_MAX_HEIGHT,
637                                       fimc_fmt_is_jpeg(ffmt->color) ? 3 : 1,
638                                       0);
639                 return ffmt;
640         }
641         /* Can't scale or crop in transparent (JPEG) transfer mode */
642         if (fimc_fmt_is_jpeg(ffmt->color)) {
643                 *width  = ctx->s_frame.f_width;
644                 *height = ctx->s_frame.f_height;
645                 return ffmt;
646         }
647         /* Apply the scaler and the output DMA constraints */
648         max_w = rotation ? pl->out_rot_en_w : pl->out_rot_dis_w;
649         if (ctx->state & FIMC_COMPOSE) {
650                 min_w = dst->offs_h + dst->width;
651                 min_h = dst->offs_v + dst->height;
652         } else {
653                 min_w = var->min_out_pixsize;
654                 min_h = var->min_out_pixsize;
655         }
656         if (var->min_vsize_align == 1 && !rotation)
657                 align_h = fimc_fmt_is_rgb(ffmt->color) ? 0 : 1;
658
659         depth = fimc_get_format_depth(ffmt);
660         v4l_bound_align_image(width, min_w, max_w,
661                               ffs(var->min_out_pixsize) - 1,
662                               height, min_h, FIMC_CAMIF_MAX_HEIGHT,
663                               align_h,
664                               64/(ALIGN(depth, 8)));
665
666         dbg("pad%d: code: 0x%x, %dx%d. dst fmt: %dx%d",
667             pad, code ? *code : 0, *width, *height,
668             dst->f_width, dst->f_height);
669
670         return ffmt;
671 }
672
673 static void fimc_capture_try_selection(struct fimc_ctx *ctx,
674                                        struct v4l2_rect *r,
675                                        int target)
676 {
677         bool rotate = ctx->rotation == 90 || ctx->rotation == 270;
678         struct fimc_dev *fimc = ctx->fimc_dev;
679         struct fimc_variant *var = fimc->variant;
680         struct fimc_pix_limit *pl = var->pix_limit;
681         struct fimc_frame *sink = &ctx->s_frame;
682         u32 max_w, max_h, min_w = 0, min_h = 0, min_sz;
683         u32 align_sz = 0, align_h = 4;
684         u32 max_sc_h, max_sc_v;
685
686         /* In JPEG transparent transfer mode cropping is not supported */
687         if (fimc_fmt_is_jpeg(ctx->d_frame.fmt->color)) {
688                 r->width  = sink->f_width;
689                 r->height = sink->f_height;
690                 r->left   = r->top = 0;
691                 return;
692         }
693         if (target == V4L2_SEL_TGT_COMPOSE) {
694                 if (ctx->rotation != 90 && ctx->rotation != 270)
695                         align_h = 1;
696                 max_sc_h = min(SCALER_MAX_HRATIO, 1 << (ffs(sink->width) - 3));
697                 max_sc_v = min(SCALER_MAX_VRATIO, 1 << (ffs(sink->height) - 1));
698                 min_sz = var->min_out_pixsize;
699         } else {
700                 u32 depth = fimc_get_format_depth(sink->fmt);
701                 align_sz = 64/ALIGN(depth, 8);
702                 min_sz = var->min_inp_pixsize;
703                 min_w = min_h = min_sz;
704                 max_sc_h = max_sc_v = 1;
705         }
706         /*
707          * For the compose rectangle the following constraints must be met:
708          * - it must fit in the sink pad format rectangle (f_width/f_height);
709          * - maximum downscaling ratio is 64;
710          * - maximum crop size depends if the rotator is used or not;
711          * - the sink pad format width/height must be 4 multiple of the
712          *   prescaler ratios determined by sink pad size and source pad crop,
713          *   the prescaler ratio is returned by fimc_get_scaler_factor().
714          */
715         max_w = min_t(u32,
716                       rotate ? pl->out_rot_en_w : pl->out_rot_dis_w,
717                       rotate ? sink->f_height : sink->f_width);
718         max_h = min_t(u32, FIMC_CAMIF_MAX_HEIGHT, sink->f_height);
719
720         if (target == V4L2_SEL_TGT_COMPOSE) {
721                 min_w = min_t(u32, max_w, sink->f_width / max_sc_h);
722                 min_h = min_t(u32, max_h, sink->f_height / max_sc_v);
723                 if (rotate) {
724                         swap(max_sc_h, max_sc_v);
725                         swap(min_w, min_h);
726                 }
727         }
728         v4l_bound_align_image(&r->width, min_w, max_w, ffs(min_sz) - 1,
729                               &r->height, min_h, max_h, align_h,
730                               align_sz);
731         /* Adjust left/top if crop/compose rectangle is out of bounds */
732         r->left = clamp_t(u32, r->left, 0, sink->f_width - r->width);
733         r->top  = clamp_t(u32, r->top, 0, sink->f_height - r->height);
734         r->left = round_down(r->left, var->hor_offs_align);
735
736         dbg("target %#x: (%d,%d)/%dx%d, sink fmt: %dx%d",
737             target, r->left, r->top, r->width, r->height,
738             sink->f_width, sink->f_height);
739 }
740
741 /*
742  * The video node ioctl operations
743  */
744 static int fimc_vidioc_querycap_capture(struct file *file, void *priv,
745                                         struct v4l2_capability *cap)
746 {
747         struct fimc_dev *fimc = video_drvdata(file);
748
749         strncpy(cap->driver, fimc->pdev->name, sizeof(cap->driver) - 1);
750         strncpy(cap->card, fimc->pdev->name, sizeof(cap->card) - 1);
751         cap->bus_info[0] = 0;
752         cap->capabilities = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_CAPTURE_MPLANE;
753
754         return 0;
755 }
756
757 static int fimc_cap_enum_fmt_mplane(struct file *file, void *priv,
758                                     struct v4l2_fmtdesc *f)
759 {
760         struct fimc_fmt *fmt;
761
762         fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_CAM | FMT_FLAGS_M2M,
763                                f->index);
764         if (!fmt)
765                 return -EINVAL;
766         strncpy(f->description, fmt->name, sizeof(f->description) - 1);
767         f->pixelformat = fmt->fourcc;
768         if (fmt->fourcc == V4L2_MBUS_FMT_JPEG_1X8)
769                 f->flags |= V4L2_FMT_FLAG_COMPRESSED;
770         return 0;
771 }
772
773 /**
774  * fimc_pipeline_try_format - negotiate and/or set formats at pipeline
775  *                            elements
776  * @ctx: FIMC capture context
777  * @tfmt: media bus format to try/set on subdevs
778  * @fmt_id: fimc pixel format id corresponding to returned @tfmt (output)
779  * @set: true to set format on subdevs, false to try only
780  */
781 static int fimc_pipeline_try_format(struct fimc_ctx *ctx,
782                                     struct v4l2_mbus_framefmt *tfmt,
783                                     struct fimc_fmt **fmt_id,
784                                     bool set)
785 {
786         struct fimc_dev *fimc = ctx->fimc_dev;
787         struct v4l2_subdev *sd = fimc->pipeline.subdevs[IDX_SENSOR];
788         struct v4l2_subdev *csis = fimc->pipeline.subdevs[IDX_CSIS];
789         struct v4l2_subdev_format sfmt;
790         struct v4l2_mbus_framefmt *mf = &sfmt.format;
791         struct fimc_fmt *ffmt = NULL;
792         int ret, i = 0;
793
794         if (WARN_ON(!sd || !tfmt))
795                 return -EINVAL;
796
797         memset(&sfmt, 0, sizeof(sfmt));
798         sfmt.format = *tfmt;
799
800         sfmt.which = set ? V4L2_SUBDEV_FORMAT_ACTIVE : V4L2_SUBDEV_FORMAT_TRY;
801         while (1) {
802                 ffmt = fimc_find_format(NULL, mf->code != 0 ? &mf->code : NULL,
803                                         FMT_FLAGS_CAM, i++);
804                 if (ffmt == NULL) {
805                         /*
806                          * Notify user-space if common pixel code for
807                          * host and sensor does not exist.
808                          */
809                         return -EINVAL;
810                 }
811                 mf->code = tfmt->code = ffmt->mbus_code;
812
813                 ret = v4l2_subdev_call(sd, pad, set_fmt, NULL, &sfmt);
814                 if (ret)
815                         return ret;
816                 if (mf->code != tfmt->code) {
817                         mf->code = 0;
818                         continue;
819                 }
820                 if (mf->width != tfmt->width || mf->height != tfmt->height) {
821                         u32 fcc = ffmt->fourcc;
822                         tfmt->width  = mf->width;
823                         tfmt->height = mf->height;
824                         ffmt = fimc_capture_try_format(ctx,
825                                                &tfmt->width, &tfmt->height,
826                                                NULL, &fcc, FIMC_SD_PAD_SOURCE);
827                         if (ffmt && ffmt->mbus_code)
828                                 mf->code = ffmt->mbus_code;
829                         if (mf->width != tfmt->width ||
830                             mf->height != tfmt->height)
831                                 continue;
832                         tfmt->code = mf->code;
833                 }
834                 if (csis)
835                         ret = v4l2_subdev_call(csis, pad, set_fmt, NULL, &sfmt);
836
837                 if (mf->code == tfmt->code &&
838                     mf->width == tfmt->width && mf->height == tfmt->height)
839                         break;
840         }
841
842         if (fmt_id && ffmt)
843                 *fmt_id = ffmt;
844         *tfmt = *mf;
845
846         dbg("code: 0x%x, %dx%d, %p", mf->code, mf->width, mf->height, ffmt);
847         return 0;
848 }
849
850 static int fimc_cap_g_fmt_mplane(struct file *file, void *fh,
851                                  struct v4l2_format *f)
852 {
853         struct fimc_dev *fimc = video_drvdata(file);
854         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
855
856         return fimc_fill_format(&ctx->d_frame, f);
857 }
858
859 static int fimc_cap_try_fmt_mplane(struct file *file, void *fh,
860                                    struct v4l2_format *f)
861 {
862         struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
863         struct fimc_dev *fimc = video_drvdata(file);
864         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
865         struct v4l2_mbus_framefmt mf;
866         struct fimc_fmt *ffmt = NULL;
867
868         if (pix->pixelformat == V4L2_PIX_FMT_JPEG) {
869                 fimc_capture_try_format(ctx, &pix->width, &pix->height,
870                                         NULL, &pix->pixelformat,
871                                         FIMC_SD_PAD_SINK);
872                 ctx->s_frame.f_width  = pix->width;
873                 ctx->s_frame.f_height = pix->height;
874         }
875         ffmt = fimc_capture_try_format(ctx, &pix->width, &pix->height,
876                                        NULL, &pix->pixelformat,
877                                        FIMC_SD_PAD_SOURCE);
878         if (!ffmt)
879                 return -EINVAL;
880
881         if (!fimc->vid_cap.user_subdev_api) {
882                 mf.width  = pix->width;
883                 mf.height = pix->height;
884                 mf.code   = ffmt->mbus_code;
885                 fimc_md_graph_lock(fimc);
886                 fimc_pipeline_try_format(ctx, &mf, &ffmt, false);
887                 fimc_md_graph_unlock(fimc);
888
889                 pix->width       = mf.width;
890                 pix->height      = mf.height;
891                 if (ffmt)
892                         pix->pixelformat = ffmt->fourcc;
893         }
894
895         fimc_adjust_mplane_format(ffmt, pix->width, pix->height, pix);
896         return 0;
897 }
898
899 static void fimc_capture_mark_jpeg_xfer(struct fimc_ctx *ctx, bool jpeg)
900 {
901         ctx->scaler.enabled = !jpeg;
902         fimc_ctrls_activate(ctx, !jpeg);
903
904         if (jpeg)
905                 set_bit(ST_CAPT_JPEG, &ctx->fimc_dev->state);
906         else
907                 clear_bit(ST_CAPT_JPEG, &ctx->fimc_dev->state);
908 }
909
910 static int fimc_capture_set_format(struct fimc_dev *fimc, struct v4l2_format *f)
911 {
912         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
913         struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
914         struct v4l2_mbus_framefmt *mf = &fimc->vid_cap.mf;
915         struct fimc_frame *ff = &ctx->d_frame;
916         struct fimc_fmt *s_fmt = NULL;
917         int ret, i;
918
919         if (vb2_is_busy(&fimc->vid_cap.vbq))
920                 return -EBUSY;
921
922         /* Pre-configure format at camera interface input, for JPEG only */
923         if (pix->pixelformat == V4L2_PIX_FMT_JPEG) {
924                 fimc_capture_try_format(ctx, &pix->width, &pix->height,
925                                         NULL, &pix->pixelformat,
926                                         FIMC_SD_PAD_SINK);
927                 ctx->s_frame.f_width  = pix->width;
928                 ctx->s_frame.f_height = pix->height;
929         }
930         /* Try the format at the scaler and the DMA output */
931         ff->fmt = fimc_capture_try_format(ctx, &pix->width, &pix->height,
932                                           NULL, &pix->pixelformat,
933                                           FIMC_SD_PAD_SOURCE);
934         if (!ff->fmt)
935                 return -EINVAL;
936
937         /* Update RGB Alpha control state and value range */
938         fimc_alpha_ctrl_update(ctx);
939
940         /* Try to match format at the host and the sensor */
941         if (!fimc->vid_cap.user_subdev_api) {
942                 mf->code   = ff->fmt->mbus_code;
943                 mf->width  = pix->width;
944                 mf->height = pix->height;
945
946                 fimc_md_graph_lock(fimc);
947                 ret = fimc_pipeline_try_format(ctx, mf, &s_fmt, true);
948                 fimc_md_graph_unlock(fimc);
949                 if (ret)
950                         return ret;
951                 pix->width  = mf->width;
952                 pix->height = mf->height;
953         }
954
955         fimc_adjust_mplane_format(ff->fmt, pix->width, pix->height, pix);
956         for (i = 0; i < ff->fmt->colplanes; i++)
957                 ff->payload[i] = pix->plane_fmt[i].sizeimage;
958
959         set_frame_bounds(ff, pix->width, pix->height);
960         /* Reset the composition rectangle if not yet configured */
961         if (!(ctx->state & FIMC_COMPOSE))
962                 set_frame_crop(ff, 0, 0, pix->width, pix->height);
963
964         fimc_capture_mark_jpeg_xfer(ctx, fimc_fmt_is_jpeg(ff->fmt->color));
965
966         /* Reset cropping and set format at the camera interface input */
967         if (!fimc->vid_cap.user_subdev_api) {
968                 ctx->s_frame.fmt = s_fmt;
969                 set_frame_bounds(&ctx->s_frame, pix->width, pix->height);
970                 set_frame_crop(&ctx->s_frame, 0, 0, pix->width, pix->height);
971         }
972
973         return ret;
974 }
975
976 static int fimc_cap_s_fmt_mplane(struct file *file, void *priv,
977                                  struct v4l2_format *f)
978 {
979         struct fimc_dev *fimc = video_drvdata(file);
980
981         return fimc_capture_set_format(fimc, f);
982 }
983
984 static int fimc_cap_enum_input(struct file *file, void *priv,
985                                struct v4l2_input *i)
986 {
987         struct fimc_dev *fimc = video_drvdata(file);
988         struct v4l2_subdev *sd = fimc->pipeline.subdevs[IDX_SENSOR];
989
990         if (i->index != 0)
991                 return -EINVAL;
992
993         i->type = V4L2_INPUT_TYPE_CAMERA;
994         if (sd)
995                 strlcpy(i->name, sd->name, sizeof(i->name));
996         return 0;
997 }
998
999 static int fimc_cap_s_input(struct file *file, void *priv, unsigned int i)
1000 {
1001         return i == 0 ? i : -EINVAL;
1002 }
1003
1004 static int fimc_cap_g_input(struct file *file, void *priv, unsigned int *i)
1005 {
1006         *i = 0;
1007         return 0;
1008 }
1009
1010 /**
1011  * fimc_pipeline_validate - check for formats inconsistencies
1012  *                          between source and sink pad of each link
1013  *
1014  * Return 0 if all formats match or -EPIPE otherwise.
1015  */
1016 static int fimc_pipeline_validate(struct fimc_dev *fimc)
1017 {
1018         struct v4l2_subdev_format sink_fmt, src_fmt;
1019         struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
1020         struct v4l2_subdev *sd;
1021         struct media_pad *pad;
1022         int ret;
1023
1024         /* Start with the video capture node pad */
1025         pad = media_entity_remote_source(&vid_cap->vd_pad);
1026         if (pad == NULL)
1027                 return -EPIPE;
1028         /* FIMC.{N} subdevice */
1029         sd = media_entity_to_v4l2_subdev(pad->entity);
1030
1031         while (1) {
1032                 /* Retrieve format at the sink pad */
1033                 pad = &sd->entity.pads[0];
1034                 if (!(pad->flags & MEDIA_PAD_FL_SINK))
1035                         break;
1036                 /* Don't call FIMC subdev operation to avoid nested locking */
1037                 if (sd == &fimc->vid_cap.subdev) {
1038                         struct fimc_frame *ff = &vid_cap->ctx->s_frame;
1039                         sink_fmt.format.width = ff->f_width;
1040                         sink_fmt.format.height = ff->f_height;
1041                         sink_fmt.format.code = ff->fmt ? ff->fmt->mbus_code : 0;
1042                 } else {
1043                         sink_fmt.pad = pad->index;
1044                         sink_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1045                         ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &sink_fmt);
1046                         if (ret < 0 && ret != -ENOIOCTLCMD)
1047                                 return -EPIPE;
1048                 }
1049                 /* Retrieve format at the source pad */
1050                 pad = media_entity_remote_source(pad);
1051                 if (pad == NULL ||
1052                     media_entity_type(pad->entity) != MEDIA_ENT_T_V4L2_SUBDEV)
1053                         break;
1054
1055                 sd = media_entity_to_v4l2_subdev(pad->entity);
1056                 src_fmt.pad = pad->index;
1057                 src_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1058                 ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &src_fmt);
1059                 if (ret < 0 && ret != -ENOIOCTLCMD)
1060                         return -EPIPE;
1061
1062                 if (src_fmt.format.width != sink_fmt.format.width ||
1063                     src_fmt.format.height != sink_fmt.format.height ||
1064                     src_fmt.format.code != sink_fmt.format.code)
1065                         return -EPIPE;
1066         }
1067         return 0;
1068 }
1069
1070 static int fimc_cap_streamon(struct file *file, void *priv,
1071                              enum v4l2_buf_type type)
1072 {
1073         struct fimc_dev *fimc = video_drvdata(file);
1074         struct fimc_pipeline *p = &fimc->pipeline;
1075         struct v4l2_subdev *sd = p->subdevs[IDX_SENSOR];
1076         int ret;
1077
1078         if (fimc_capture_active(fimc))
1079                 return -EBUSY;
1080
1081         ret = media_entity_pipeline_start(&sd->entity, p->m_pipeline);
1082         if (ret < 0)
1083                 return ret;
1084
1085         if (fimc->vid_cap.user_subdev_api) {
1086                 ret = fimc_pipeline_validate(fimc);
1087                 if (ret < 0) {
1088                         media_entity_pipeline_stop(&sd->entity);
1089                         return ret;
1090                 }
1091         }
1092         return vb2_streamon(&fimc->vid_cap.vbq, type);
1093 }
1094
1095 static int fimc_cap_streamoff(struct file *file, void *priv,
1096                             enum v4l2_buf_type type)
1097 {
1098         struct fimc_dev *fimc = video_drvdata(file);
1099         struct v4l2_subdev *sd = fimc->pipeline.subdevs[IDX_SENSOR];
1100         int ret;
1101
1102         ret = vb2_streamoff(&fimc->vid_cap.vbq, type);
1103         if (ret == 0)
1104                 media_entity_pipeline_stop(&sd->entity);
1105         return ret;
1106 }
1107
1108 static int fimc_cap_reqbufs(struct file *file, void *priv,
1109                             struct v4l2_requestbuffers *reqbufs)
1110 {
1111         struct fimc_dev *fimc = video_drvdata(file);
1112         int ret = vb2_reqbufs(&fimc->vid_cap.vbq, reqbufs);
1113
1114         if (!ret)
1115                 fimc->vid_cap.reqbufs_count = reqbufs->count;
1116         return ret;
1117 }
1118
1119 static int fimc_cap_querybuf(struct file *file, void *priv,
1120                            struct v4l2_buffer *buf)
1121 {
1122         struct fimc_dev *fimc = video_drvdata(file);
1123
1124         return vb2_querybuf(&fimc->vid_cap.vbq, buf);
1125 }
1126
1127 static int fimc_cap_qbuf(struct file *file, void *priv,
1128                           struct v4l2_buffer *buf)
1129 {
1130         struct fimc_dev *fimc = video_drvdata(file);
1131
1132         return vb2_qbuf(&fimc->vid_cap.vbq, buf);
1133 }
1134
1135 static int fimc_cap_dqbuf(struct file *file, void *priv,
1136                            struct v4l2_buffer *buf)
1137 {
1138         struct fimc_dev *fimc = video_drvdata(file);
1139
1140         return vb2_dqbuf(&fimc->vid_cap.vbq, buf, file->f_flags & O_NONBLOCK);
1141 }
1142
1143 static int fimc_cap_create_bufs(struct file *file, void *priv,
1144                                 struct v4l2_create_buffers *create)
1145 {
1146         struct fimc_dev *fimc = video_drvdata(file);
1147
1148         return vb2_create_bufs(&fimc->vid_cap.vbq, create);
1149 }
1150
1151 static int fimc_cap_prepare_buf(struct file *file, void *priv,
1152                                 struct v4l2_buffer *b)
1153 {
1154         struct fimc_dev *fimc = video_drvdata(file);
1155
1156         return vb2_prepare_buf(&fimc->vid_cap.vbq, b);
1157 }
1158
1159 static int fimc_cap_g_selection(struct file *file, void *fh,
1160                                 struct v4l2_selection *s)
1161 {
1162         struct fimc_dev *fimc = video_drvdata(file);
1163         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1164         struct fimc_frame *f = &ctx->s_frame;
1165
1166         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
1167                 return -EINVAL;
1168
1169         switch (s->target) {
1170         case V4L2_SEL_TGT_COMPOSE_DEFAULT:
1171         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1172                 f = &ctx->d_frame;
1173         case V4L2_SEL_TGT_CROP_BOUNDS:
1174         case V4L2_SEL_TGT_CROP_DEFAULT:
1175                 s->r.left = 0;
1176                 s->r.top = 0;
1177                 s->r.width = f->o_width;
1178                 s->r.height = f->o_height;
1179                 return 0;
1180
1181         case V4L2_SEL_TGT_COMPOSE:
1182                 f = &ctx->d_frame;
1183         case V4L2_SEL_TGT_CROP:
1184                 s->r.left = f->offs_h;
1185                 s->r.top = f->offs_v;
1186                 s->r.width = f->width;
1187                 s->r.height = f->height;
1188                 return 0;
1189         }
1190
1191         return -EINVAL;
1192 }
1193
1194 /* Return 1 if rectangle a is enclosed in rectangle b, or 0 otherwise. */
1195 static int enclosed_rectangle(struct v4l2_rect *a, struct v4l2_rect *b)
1196 {
1197         if (a->left < b->left || a->top < b->top)
1198                 return 0;
1199         if (a->left + a->width > b->left + b->width)
1200                 return 0;
1201         if (a->top + a->height > b->top + b->height)
1202                 return 0;
1203
1204         return 1;
1205 }
1206
1207 static int fimc_cap_s_selection(struct file *file, void *fh,
1208                                 struct v4l2_selection *s)
1209 {
1210         struct fimc_dev *fimc = video_drvdata(file);
1211         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1212         struct v4l2_rect rect = s->r;
1213         struct fimc_frame *f;
1214         unsigned long flags;
1215
1216         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
1217                 return -EINVAL;
1218
1219         if (s->target == V4L2_SEL_TGT_COMPOSE)
1220                 f = &ctx->d_frame;
1221         else if (s->target == V4L2_SEL_TGT_CROP)
1222                 f = &ctx->s_frame;
1223         else
1224                 return -EINVAL;
1225
1226         fimc_capture_try_selection(ctx, &rect, s->target);
1227
1228         if (s->flags & V4L2_SEL_FLAG_LE &&
1229             !enclosed_rectangle(&rect, &s->r))
1230                 return -ERANGE;
1231
1232         if (s->flags & V4L2_SEL_FLAG_GE &&
1233             !enclosed_rectangle(&s->r, &rect))
1234                 return -ERANGE;
1235
1236         s->r = rect;
1237         spin_lock_irqsave(&fimc->slock, flags);
1238         set_frame_crop(f, s->r.left, s->r.top, s->r.width,
1239                        s->r.height);
1240         spin_unlock_irqrestore(&fimc->slock, flags);
1241
1242         set_bit(ST_CAPT_APPLY_CFG, &fimc->state);
1243         return 0;
1244 }
1245
1246 static const struct v4l2_ioctl_ops fimc_capture_ioctl_ops = {
1247         .vidioc_querycap                = fimc_vidioc_querycap_capture,
1248
1249         .vidioc_enum_fmt_vid_cap_mplane = fimc_cap_enum_fmt_mplane,
1250         .vidioc_try_fmt_vid_cap_mplane  = fimc_cap_try_fmt_mplane,
1251         .vidioc_s_fmt_vid_cap_mplane    = fimc_cap_s_fmt_mplane,
1252         .vidioc_g_fmt_vid_cap_mplane    = fimc_cap_g_fmt_mplane,
1253
1254         .vidioc_reqbufs                 = fimc_cap_reqbufs,
1255         .vidioc_querybuf                = fimc_cap_querybuf,
1256
1257         .vidioc_qbuf                    = fimc_cap_qbuf,
1258         .vidioc_dqbuf                   = fimc_cap_dqbuf,
1259
1260         .vidioc_prepare_buf             = fimc_cap_prepare_buf,
1261         .vidioc_create_bufs             = fimc_cap_create_bufs,
1262
1263         .vidioc_streamon                = fimc_cap_streamon,
1264         .vidioc_streamoff               = fimc_cap_streamoff,
1265
1266         .vidioc_g_selection             = fimc_cap_g_selection,
1267         .vidioc_s_selection             = fimc_cap_s_selection,
1268
1269         .vidioc_enum_input              = fimc_cap_enum_input,
1270         .vidioc_s_input                 = fimc_cap_s_input,
1271         .vidioc_g_input                 = fimc_cap_g_input,
1272 };
1273
1274 /* Capture subdev media entity operations */
1275 static int fimc_link_setup(struct media_entity *entity,
1276                            const struct media_pad *local,
1277                            const struct media_pad *remote, u32 flags)
1278 {
1279         struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
1280         struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1281
1282         if (media_entity_type(remote->entity) != MEDIA_ENT_T_V4L2_SUBDEV)
1283                 return -EINVAL;
1284
1285         if (WARN_ON(fimc == NULL))
1286                 return 0;
1287
1288         dbg("%s --> %s, flags: 0x%x. input: 0x%x",
1289             local->entity->name, remote->entity->name, flags,
1290             fimc->vid_cap.input);
1291
1292         if (flags & MEDIA_LNK_FL_ENABLED) {
1293                 if (fimc->vid_cap.input != 0)
1294                         return -EBUSY;
1295                 fimc->vid_cap.input = sd->grp_id;
1296                 return 0;
1297         }
1298
1299         fimc->vid_cap.input = 0;
1300         return 0;
1301 }
1302
1303 static const struct media_entity_operations fimc_sd_media_ops = {
1304         .link_setup = fimc_link_setup,
1305 };
1306
1307 /**
1308  * fimc_sensor_notify - v4l2_device notification from a sensor subdev
1309  * @sd: pointer to a subdev generating the notification
1310  * @notification: the notification type, must be S5P_FIMC_TX_END_NOTIFY
1311  * @arg: pointer to an u32 type integer that stores the frame payload value
1312  *
1313  * The End Of Frame notification sent by sensor subdev in its still capture
1314  * mode. If there is only a single VSYNC generated by the sensor at the
1315  * beginning of a frame transmission, FIMC does not issue the LastIrq
1316  * (end of frame) interrupt. And this notification is used to complete the
1317  * frame capture and returning a buffer to user-space. Subdev drivers should
1318  * call this notification from their last 'End of frame capture' interrupt.
1319  */
1320 void fimc_sensor_notify(struct v4l2_subdev *sd, unsigned int notification,
1321                         void *arg)
1322 {
1323         struct fimc_sensor_info *sensor;
1324         struct fimc_vid_buffer *buf;
1325         struct fimc_md *fmd;
1326         struct fimc_dev *fimc;
1327         unsigned long flags;
1328
1329         if (sd == NULL)
1330                 return;
1331
1332         sensor = v4l2_get_subdev_hostdata(sd);
1333         fmd = entity_to_fimc_mdev(&sd->entity);
1334
1335         spin_lock_irqsave(&fmd->slock, flags);
1336         fimc = sensor ? sensor->host : NULL;
1337
1338         if (fimc && arg && notification == S5P_FIMC_TX_END_NOTIFY &&
1339             test_bit(ST_CAPT_PEND, &fimc->state)) {
1340                 unsigned long irq_flags;
1341                 spin_lock_irqsave(&fimc->slock, irq_flags);
1342                 if (!list_empty(&fimc->vid_cap.active_buf_q)) {
1343                         buf = list_entry(fimc->vid_cap.active_buf_q.next,
1344                                          struct fimc_vid_buffer, list);
1345                         vb2_set_plane_payload(&buf->vb, 0, *((u32 *)arg));
1346                 }
1347                 fimc_capture_irq_handler(fimc, 1);
1348                 fimc_deactivate_capture(fimc);
1349                 spin_unlock_irqrestore(&fimc->slock, irq_flags);
1350         }
1351         spin_unlock_irqrestore(&fmd->slock, flags);
1352 }
1353
1354 static int fimc_subdev_enum_mbus_code(struct v4l2_subdev *sd,
1355                                       struct v4l2_subdev_fh *fh,
1356                                       struct v4l2_subdev_mbus_code_enum *code)
1357 {
1358         struct fimc_fmt *fmt;
1359
1360         fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_CAM, code->index);
1361         if (!fmt)
1362                 return -EINVAL;
1363         code->code = fmt->mbus_code;
1364         return 0;
1365 }
1366
1367 static int fimc_subdev_get_fmt(struct v4l2_subdev *sd,
1368                                struct v4l2_subdev_fh *fh,
1369                                struct v4l2_subdev_format *fmt)
1370 {
1371         struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1372         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1373         struct v4l2_mbus_framefmt *mf;
1374         struct fimc_frame *ff;
1375
1376         if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
1377                 mf = v4l2_subdev_get_try_format(fh, fmt->pad);
1378                 fmt->format = *mf;
1379                 return 0;
1380         }
1381         mf = &fmt->format;
1382         mf->colorspace = V4L2_COLORSPACE_JPEG;
1383         ff = fmt->pad == FIMC_SD_PAD_SINK ? &ctx->s_frame : &ctx->d_frame;
1384
1385         mutex_lock(&fimc->lock);
1386         /* The pixel code is same on both input and output pad */
1387         if (!WARN_ON(ctx->s_frame.fmt == NULL))
1388                 mf->code = ctx->s_frame.fmt->mbus_code;
1389         mf->width  = ff->f_width;
1390         mf->height = ff->f_height;
1391         mutex_unlock(&fimc->lock);
1392
1393         return 0;
1394 }
1395
1396 static int fimc_subdev_set_fmt(struct v4l2_subdev *sd,
1397                                struct v4l2_subdev_fh *fh,
1398                                struct v4l2_subdev_format *fmt)
1399 {
1400         struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1401         struct v4l2_mbus_framefmt *mf = &fmt->format;
1402         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1403         struct fimc_frame *ff;
1404         struct fimc_fmt *ffmt;
1405
1406         dbg("pad%d: code: 0x%x, %dx%d",
1407             fmt->pad, mf->code, mf->width, mf->height);
1408
1409         if (fmt->pad == FIMC_SD_PAD_SOURCE &&
1410             vb2_is_busy(&fimc->vid_cap.vbq))
1411                 return -EBUSY;
1412
1413         mutex_lock(&fimc->lock);
1414         ffmt = fimc_capture_try_format(ctx, &mf->width, &mf->height,
1415                                        &mf->code, NULL, fmt->pad);
1416         mutex_unlock(&fimc->lock);
1417         mf->colorspace = V4L2_COLORSPACE_JPEG;
1418
1419         if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
1420                 mf = v4l2_subdev_get_try_format(fh, fmt->pad);
1421                 *mf = fmt->format;
1422                 return 0;
1423         }
1424         /* Update RGB Alpha control state and value range */
1425         fimc_alpha_ctrl_update(ctx);
1426
1427         fimc_capture_mark_jpeg_xfer(ctx, fimc_fmt_is_jpeg(ffmt->color));
1428
1429         ff = fmt->pad == FIMC_SD_PAD_SINK ?
1430                 &ctx->s_frame : &ctx->d_frame;
1431
1432         mutex_lock(&fimc->lock);
1433         set_frame_bounds(ff, mf->width, mf->height);
1434         fimc->vid_cap.mf = *mf;
1435         ff->fmt = ffmt;
1436
1437         /* Reset the crop rectangle if required. */
1438         if (!(fmt->pad == FIMC_SD_PAD_SOURCE && (ctx->state & FIMC_COMPOSE)))
1439                 set_frame_crop(ff, 0, 0, mf->width, mf->height);
1440
1441         if (fmt->pad == FIMC_SD_PAD_SINK)
1442                 ctx->state &= ~FIMC_COMPOSE;
1443         mutex_unlock(&fimc->lock);
1444         return 0;
1445 }
1446
1447 static int fimc_subdev_get_selection(struct v4l2_subdev *sd,
1448                                      struct v4l2_subdev_fh *fh,
1449                                      struct v4l2_subdev_selection *sel)
1450 {
1451         struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1452         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1453         struct fimc_frame *f = &ctx->s_frame;
1454         struct v4l2_rect *r = &sel->r;
1455         struct v4l2_rect *try_sel;
1456
1457         if (sel->pad != FIMC_SD_PAD_SINK)
1458                 return -EINVAL;
1459
1460         mutex_lock(&fimc->lock);
1461
1462         switch (sel->target) {
1463         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1464                 f = &ctx->d_frame;
1465         case V4L2_SEL_TGT_CROP_BOUNDS:
1466                 r->width = f->o_width;
1467                 r->height = f->o_height;
1468                 r->left = 0;
1469                 r->top = 0;
1470                 mutex_unlock(&fimc->lock);
1471                 return 0;
1472
1473         case V4L2_SEL_TGT_CROP:
1474                 try_sel = v4l2_subdev_get_try_crop(fh, sel->pad);
1475                 break;
1476         case V4L2_SEL_TGT_COMPOSE:
1477                 try_sel = v4l2_subdev_get_try_compose(fh, sel->pad);
1478                 f = &ctx->d_frame;
1479                 break;
1480         default:
1481                 mutex_unlock(&fimc->lock);
1482                 return -EINVAL;
1483         }
1484
1485         if (sel->which == V4L2_SUBDEV_FORMAT_TRY) {
1486                 sel->r = *try_sel;
1487         } else {
1488                 r->left = f->offs_h;
1489                 r->top = f->offs_v;
1490                 r->width = f->width;
1491                 r->height = f->height;
1492         }
1493
1494         dbg("target %#x: l:%d, t:%d, %dx%d, f_w: %d, f_h: %d",
1495             sel->pad, r->left, r->top, r->width, r->height,
1496             f->f_width, f->f_height);
1497
1498         mutex_unlock(&fimc->lock);
1499         return 0;
1500 }
1501
1502 static int fimc_subdev_set_selection(struct v4l2_subdev *sd,
1503                                      struct v4l2_subdev_fh *fh,
1504                                      struct v4l2_subdev_selection *sel)
1505 {
1506         struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1507         struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1508         struct fimc_frame *f = &ctx->s_frame;
1509         struct v4l2_rect *r = &sel->r;
1510         struct v4l2_rect *try_sel;
1511         unsigned long flags;
1512
1513         if (sel->pad != FIMC_SD_PAD_SINK)
1514                 return -EINVAL;
1515
1516         mutex_lock(&fimc->lock);
1517         fimc_capture_try_selection(ctx, r, V4L2_SEL_TGT_CROP);
1518
1519         switch (sel->target) {
1520         case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1521                 f = &ctx->d_frame;
1522         case V4L2_SEL_TGT_CROP_BOUNDS:
1523                 r->width = f->o_width;
1524                 r->height = f->o_height;
1525                 r->left = 0;
1526                 r->top = 0;
1527                 mutex_unlock(&fimc->lock);
1528                 return 0;
1529
1530         case V4L2_SEL_TGT_CROP:
1531                 try_sel = v4l2_subdev_get_try_crop(fh, sel->pad);
1532                 break;
1533         case V4L2_SEL_TGT_COMPOSE:
1534                 try_sel = v4l2_subdev_get_try_compose(fh, sel->pad);
1535                 f = &ctx->d_frame;
1536                 break;
1537         default:
1538                 mutex_unlock(&fimc->lock);
1539                 return -EINVAL;
1540         }
1541
1542         if (sel->which == V4L2_SUBDEV_FORMAT_TRY) {
1543                 *try_sel = sel->r;
1544         } else {
1545                 spin_lock_irqsave(&fimc->slock, flags);
1546                 set_frame_crop(f, r->left, r->top, r->width, r->height);
1547                 set_bit(ST_CAPT_APPLY_CFG, &fimc->state);
1548                 spin_unlock_irqrestore(&fimc->slock, flags);
1549                 if (sel->target == V4L2_SEL_TGT_COMPOSE)
1550                         ctx->state |= FIMC_COMPOSE;
1551         }
1552
1553         dbg("target %#x: (%d,%d)/%dx%d", sel->target, r->left, r->top,
1554             r->width, r->height);
1555
1556         mutex_unlock(&fimc->lock);
1557         return 0;
1558 }
1559
1560 static struct v4l2_subdev_pad_ops fimc_subdev_pad_ops = {
1561         .enum_mbus_code = fimc_subdev_enum_mbus_code,
1562         .get_selection = fimc_subdev_get_selection,
1563         .set_selection = fimc_subdev_set_selection,
1564         .get_fmt = fimc_subdev_get_fmt,
1565         .set_fmt = fimc_subdev_set_fmt,
1566 };
1567
1568 static struct v4l2_subdev_ops fimc_subdev_ops = {
1569         .pad = &fimc_subdev_pad_ops,
1570 };
1571
1572 /* Set default format at the sensor and host interface */
1573 static int fimc_capture_set_default_format(struct fimc_dev *fimc)
1574 {
1575         struct v4l2_format fmt = {
1576                 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
1577                 .fmt.pix_mp = {
1578                         .width          = 640,
1579                         .height         = 480,
1580                         .pixelformat    = V4L2_PIX_FMT_YUYV,
1581                         .field          = V4L2_FIELD_NONE,
1582                         .colorspace     = V4L2_COLORSPACE_JPEG,
1583                 },
1584         };
1585
1586         return fimc_capture_set_format(fimc, &fmt);
1587 }
1588
1589 /* fimc->lock must be already initialized */
1590 static int fimc_register_capture_device(struct fimc_dev *fimc,
1591                                  struct v4l2_device *v4l2_dev)
1592 {
1593         struct video_device *vfd = &fimc->vid_cap.vfd;
1594         struct fimc_vid_cap *vid_cap;
1595         struct fimc_ctx *ctx;
1596         struct vb2_queue *q;
1597         int ret = -ENOMEM;
1598
1599         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1600         if (!ctx)
1601                 return -ENOMEM;
1602
1603         ctx->fimc_dev    = fimc;
1604         ctx->in_path     = FIMC_IO_CAMERA;
1605         ctx->out_path    = FIMC_IO_DMA;
1606         ctx->state       = FIMC_CTX_CAP;
1607         ctx->s_frame.fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_CAM, 0);
1608         ctx->d_frame.fmt = ctx->s_frame.fmt;
1609
1610         memset(vfd, 0, sizeof(*vfd));
1611         snprintf(vfd->name, sizeof(vfd->name), "fimc.%d.capture", fimc->id);
1612
1613         vfd->fops       = &fimc_capture_fops;
1614         vfd->ioctl_ops  = &fimc_capture_ioctl_ops;
1615         vfd->v4l2_dev   = v4l2_dev;
1616         vfd->minor      = -1;
1617         vfd->release    = video_device_release_empty;
1618         vfd->lock       = &fimc->lock;
1619
1620         video_set_drvdata(vfd, fimc);
1621
1622         vid_cap = &fimc->vid_cap;
1623         vid_cap->active_buf_cnt = 0;
1624         vid_cap->reqbufs_count  = 0;
1625         vid_cap->refcnt = 0;
1626
1627         INIT_LIST_HEAD(&vid_cap->pending_buf_q);
1628         INIT_LIST_HEAD(&vid_cap->active_buf_q);
1629         vid_cap->ctx = ctx;
1630
1631         q = &fimc->vid_cap.vbq;
1632         memset(q, 0, sizeof(*q));
1633         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1634         q->io_modes = VB2_MMAP | VB2_USERPTR;
1635         q->drv_priv = fimc->vid_cap.ctx;
1636         q->ops = &fimc_capture_qops;
1637         q->mem_ops = &vb2_dma_contig_memops;
1638         q->buf_struct_size = sizeof(struct fimc_vid_buffer);
1639
1640         vb2_queue_init(q);
1641
1642         vid_cap->vd_pad.flags = MEDIA_PAD_FL_SINK;
1643         ret = media_entity_init(&vfd->entity, 1, &vid_cap->vd_pad, 0);
1644         if (ret)
1645                 goto err_ent;
1646
1647         ret = video_register_device(vfd, VFL_TYPE_GRABBER, -1);
1648         if (ret)
1649                 goto err_vd;
1650
1651         v4l2_info(v4l2_dev, "Registered %s as /dev/%s\n",
1652                   vfd->name, video_device_node_name(vfd));
1653
1654         vfd->ctrl_handler = &ctx->ctrls.handler;
1655         return 0;
1656
1657 err_vd:
1658         media_entity_cleanup(&vfd->entity);
1659 err_ent:
1660         kfree(ctx);
1661         return ret;
1662 }
1663
1664 static int fimc_capture_subdev_registered(struct v4l2_subdev *sd)
1665 {
1666         struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1667         int ret;
1668
1669         if (fimc == NULL)
1670                 return -ENXIO;
1671
1672         ret = fimc_register_m2m_device(fimc, sd->v4l2_dev);
1673         if (ret)
1674                 return ret;
1675
1676         ret = fimc_register_capture_device(fimc, sd->v4l2_dev);
1677         if (ret)
1678                 fimc_unregister_m2m_device(fimc);
1679
1680         return ret;
1681 }
1682
1683 static void fimc_capture_subdev_unregistered(struct v4l2_subdev *sd)
1684 {
1685         struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1686
1687         if (fimc == NULL)
1688                 return;
1689
1690         fimc_unregister_m2m_device(fimc);
1691
1692         if (video_is_registered(&fimc->vid_cap.vfd)) {
1693                 video_unregister_device(&fimc->vid_cap.vfd);
1694                 media_entity_cleanup(&fimc->vid_cap.vfd.entity);
1695         }
1696         kfree(fimc->vid_cap.ctx);
1697         fimc->vid_cap.ctx = NULL;
1698 }
1699
1700 static const struct v4l2_subdev_internal_ops fimc_capture_sd_internal_ops = {
1701         .registered = fimc_capture_subdev_registered,
1702         .unregistered = fimc_capture_subdev_unregistered,
1703 };
1704
1705 int fimc_initialize_capture_subdev(struct fimc_dev *fimc)
1706 {
1707         struct v4l2_subdev *sd = &fimc->vid_cap.subdev;
1708         int ret;
1709
1710         v4l2_subdev_init(sd, &fimc_subdev_ops);
1711         sd->flags = V4L2_SUBDEV_FL_HAS_DEVNODE;
1712         snprintf(sd->name, sizeof(sd->name), "FIMC.%d", fimc->pdev->id);
1713
1714         fimc->vid_cap.sd_pads[FIMC_SD_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
1715         fimc->vid_cap.sd_pads[FIMC_SD_PAD_SOURCE].flags = MEDIA_PAD_FL_SOURCE;
1716         ret = media_entity_init(&sd->entity, FIMC_SD_PADS_NUM,
1717                                 fimc->vid_cap.sd_pads, 0);
1718         if (ret)
1719                 return ret;
1720
1721         sd->entity.ops = &fimc_sd_media_ops;
1722         sd->internal_ops = &fimc_capture_sd_internal_ops;
1723         v4l2_set_subdevdata(sd, fimc);
1724         return 0;
1725 }
1726
1727 void fimc_unregister_capture_subdev(struct fimc_dev *fimc)
1728 {
1729         struct v4l2_subdev *sd = &fimc->vid_cap.subdev;
1730
1731         v4l2_device_unregister_subdev(sd);
1732         media_entity_cleanup(&sd->entity);
1733         v4l2_set_subdevdata(sd, NULL);
1734 }