1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Samsung S5P/EXYNOS4 SoC series camera interface (camera capture) driver
4  *
5  * Copyright (C) 2010 - 2012 Samsung Electronics Co., Ltd.
6  * Sylwester Nawrocki <s.nawrocki@samsung.com>
7  */
8 
9 #include <linux/module.h>
10 #include <linux/kernel.h>
11 #include <linux/types.h>
12 #include <linux/errno.h>
13 #include <linux/bug.h>
14 #include <linux/interrupt.h>
15 #include <linux/device.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/list.h>
18 #include <linux/slab.h>
19 
20 #include <linux/videodev2.h>
21 #include <media/v4l2-device.h>
22 #include <media/v4l2-ioctl.h>
23 #include <media/v4l2-mem2mem.h>
24 #include <media/v4l2-rect.h>
25 #include <media/videobuf2-v4l2.h>
26 #include <media/videobuf2-dma-contig.h>
27 
28 #include "common.h"
29 #include "fimc-core.h"
30 #include "fimc-reg.h"
31 #include "media-dev.h"
32 
33 static int fimc_capture_hw_init(struct fimc_dev *fimc)
34 {
35 	struct fimc_source_info *si = &fimc->vid_cap.source_config;
36 	struct fimc_ctx *ctx = fimc->vid_cap.ctx;
37 	int ret;
38 	unsigned long flags;
39 
40 	if (ctx == NULL || ctx->s_frame.fmt == NULL)
41 		return -EINVAL;
42 
43 	if (si->fimc_bus_type == FIMC_BUS_TYPE_ISP_WRITEBACK) {
44 		ret = fimc_hw_camblk_cfg_writeback(fimc);
45 		if (ret < 0)
46 			return ret;
47 	}
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, si);
54 	fimc_hw_set_camera_type(fimc, si);
55 	fimc_hw_set_camera_source(fimc, si);
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->drv_data->alpha_color)
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, 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, 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(&cap->ve, set_stream, 0);
122 	else
123 		return 0;
124 }
125 
126 static int fimc_stop_capture(struct fimc_dev *fimc, bool suspend)
127 {
128 	unsigned long flags;
129 
130 	if (!fimc_capture_active(fimc))
131 		return 0;
132 
133 	spin_lock_irqsave(&fimc->slock, flags);
134 	set_bit(ST_CAPT_SHUT, &fimc->state);
135 	fimc_deactivate_capture(fimc);
136 	spin_unlock_irqrestore(&fimc->slock, flags);
137 
138 	wait_event_timeout(fimc->irq_queue,
139 			   !test_bit(ST_CAPT_SHUT, &fimc->state),
140 			   (2*HZ/10)); /* 200 ms */
141 
142 	return fimc_capture_state_cleanup(fimc, suspend);
143 }
144 
145 /**
146  * fimc_capture_config_update - apply the camera interface configuration
147  * @ctx: FIMC capture context
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->drv_data->alpha_color)
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_pipeline *p = to_fimc_pipeline(cap->ve.pipe);
182 	struct v4l2_subdev *csis = p->subdevs[IDX_CSIS];
183 	struct fimc_frame *f = &cap->ctx->d_frame;
184 	struct fimc_vid_buffer *v_buf;
185 
186 	if (test_and_clear_bit(ST_CAPT_SHUT, &fimc->state)) {
187 		wake_up(&fimc->irq_queue);
188 		goto done;
189 	}
190 
191 	if (!list_empty(&cap->active_buf_q) &&
192 	    test_bit(ST_CAPT_RUN, &fimc->state) && deq_buf) {
193 		v_buf = fimc_active_queue_pop(cap);
194 
195 		v_buf->vb.vb2_buf.timestamp = ktime_get_ns();
196 		v_buf->vb.sequence = cap->frame_count++;
197 
198 		vb2_buffer_done(&v_buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
199 	}
200 
201 	if (!list_empty(&cap->pending_buf_q)) {
202 
203 		v_buf = fimc_pending_queue_pop(cap);
204 		fimc_hw_set_output_addr(fimc, &v_buf->addr, cap->buf_index);
205 		v_buf->index = cap->buf_index;
206 
207 		/* Move the buffer to the capture active queue */
208 		fimc_active_queue_add(cap, v_buf);
209 
210 		dbg("next frame: %d, done frame: %d",
211 		    fimc_hw_get_frame_index(fimc), v_buf->index);
212 
213 		if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
214 			cap->buf_index = 0;
215 	}
216 	/*
217 	 * Set up a buffer at MIPI-CSIS if current image format
218 	 * requires the frame embedded data capture.
219 	 */
220 	if (f->fmt->mdataplanes && !list_empty(&cap->active_buf_q)) {
221 		unsigned int plane = ffs(f->fmt->mdataplanes) - 1;
222 		unsigned int size = f->payload[plane];
223 		s32 index = fimc_hw_get_frame_index(fimc);
224 		void *vaddr;
225 
226 		list_for_each_entry(v_buf, &cap->active_buf_q, list) {
227 			if (v_buf->index != index)
228 				continue;
229 			vaddr = vb2_plane_vaddr(&v_buf->vb.vb2_buf, plane);
230 			v4l2_subdev_call(csis, video, s_rx_buffer,
231 					 vaddr, &size);
232 			break;
233 		}
234 	}
235 
236 	if (cap->active_buf_cnt == 0) {
237 		if (deq_buf)
238 			clear_bit(ST_CAPT_RUN, &fimc->state);
239 
240 		if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
241 			cap->buf_index = 0;
242 	} else {
243 		set_bit(ST_CAPT_RUN, &fimc->state);
244 	}
245 
246 	if (test_bit(ST_CAPT_APPLY_CFG, &fimc->state))
247 		fimc_capture_config_update(cap->ctx);
248 done:
249 	if (cap->active_buf_cnt == 1) {
250 		fimc_deactivate_capture(fimc);
251 		clear_bit(ST_CAPT_STREAM, &fimc->state);
252 	}
253 
254 	dbg("frame: %d, active_buf_cnt: %d",
255 	    fimc_hw_get_frame_index(fimc), cap->active_buf_cnt);
256 }
257 
258 
259 static int start_streaming(struct vb2_queue *q, unsigned int count)
260 {
261 	struct fimc_ctx *ctx = q->drv_priv;
262 	struct fimc_dev *fimc = ctx->fimc_dev;
263 	struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
264 	int min_bufs;
265 	int ret;
266 
267 	vid_cap->frame_count = 0;
268 
269 	ret = fimc_capture_hw_init(fimc);
270 	if (ret) {
271 		fimc_capture_state_cleanup(fimc, false);
272 		return ret;
273 	}
274 
275 	set_bit(ST_CAPT_PEND, &fimc->state);
276 
277 	min_bufs = fimc->vid_cap.reqbufs_count > 1 ? 2 : 1;
278 
279 	if (vid_cap->active_buf_cnt >= min_bufs &&
280 	    !test_and_set_bit(ST_CAPT_STREAM, &fimc->state)) {
281 		fimc_activate_capture(ctx);
282 
283 		if (!test_and_set_bit(ST_CAPT_ISP_STREAM, &fimc->state))
284 			return fimc_pipeline_call(&vid_cap->ve, set_stream, 1);
285 	}
286 
287 	return 0;
288 }
289 
290 static void stop_streaming(struct vb2_queue *q)
291 {
292 	struct fimc_ctx *ctx = q->drv_priv;
293 	struct fimc_dev *fimc = ctx->fimc_dev;
294 
295 	if (!fimc_capture_active(fimc))
296 		return;
297 
298 	fimc_stop_capture(fimc, false);
299 }
300 
301 int fimc_capture_suspend(struct fimc_dev *fimc)
302 {
303 	bool suspend = fimc_capture_busy(fimc);
304 
305 	int ret = fimc_stop_capture(fimc, suspend);
306 	if (ret)
307 		return ret;
308 	return fimc_pipeline_call(&fimc->vid_cap.ve, close);
309 }
310 
311 static void buffer_queue(struct vb2_buffer *vb);
312 
313 int fimc_capture_resume(struct fimc_dev *fimc)
314 {
315 	struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
316 	struct exynos_video_entity *ve = &vid_cap->ve;
317 	struct fimc_vid_buffer *buf;
318 	int i;
319 
320 	if (!test_and_clear_bit(ST_CAPT_SUSPENDED, &fimc->state))
321 		return 0;
322 
323 	INIT_LIST_HEAD(&fimc->vid_cap.active_buf_q);
324 	vid_cap->buf_index = 0;
325 	fimc_pipeline_call(ve, open, &ve->vdev.entity, false);
326 	fimc_capture_hw_init(fimc);
327 
328 	clear_bit(ST_CAPT_SUSPENDED, &fimc->state);
329 
330 	for (i = 0; i < vid_cap->reqbufs_count; i++) {
331 		if (list_empty(&vid_cap->pending_buf_q))
332 			break;
333 		buf = fimc_pending_queue_pop(vid_cap);
334 		buffer_queue(&buf->vb.vb2_buf);
335 	}
336 	return 0;
337 
338 }
339 
340 static int queue_setup(struct vb2_queue *vq,
341 		       unsigned int *num_buffers, unsigned int *num_planes,
342 		       unsigned int sizes[], struct device *alloc_devs[])
343 {
344 	struct fimc_ctx *ctx = vq->drv_priv;
345 	struct fimc_frame *frame = &ctx->d_frame;
346 	struct fimc_fmt *fmt = frame->fmt;
347 	unsigned long wh = frame->f_width * frame->f_height;
348 	int i;
349 
350 	if (fmt == NULL)
351 		return -EINVAL;
352 
353 	if (*num_planes) {
354 		if (*num_planes != fmt->memplanes)
355 			return -EINVAL;
356 		for (i = 0; i < *num_planes; i++)
357 			if (sizes[i] < (wh * fmt->depth[i]) / 8)
358 				return -EINVAL;
359 		return 0;
360 	}
361 
362 	*num_planes = fmt->memplanes;
363 
364 	for (i = 0; i < fmt->memplanes; i++) {
365 		unsigned int size = (wh * fmt->depth[i]) / 8;
366 
367 		if (fimc_fmt_is_user_defined(fmt->color))
368 			sizes[i] = frame->payload[i];
369 		else
370 			sizes[i] = max_t(u32, size, frame->payload[i]);
371 	}
372 
373 	return 0;
374 }
375 
376 static int buffer_prepare(struct vb2_buffer *vb)
377 {
378 	struct vb2_queue *vq = vb->vb2_queue;
379 	struct fimc_ctx *ctx = vq->drv_priv;
380 	int i;
381 
382 	if (ctx->d_frame.fmt == NULL)
383 		return -EINVAL;
384 
385 	for (i = 0; i < ctx->d_frame.fmt->memplanes; i++) {
386 		unsigned long size = ctx->d_frame.payload[i];
387 
388 		if (vb2_plane_size(vb, i) < size) {
389 			v4l2_err(&ctx->fimc_dev->vid_cap.ve.vdev,
390 				 "User buffer too small (%ld < %ld)\n",
391 				 vb2_plane_size(vb, i), size);
392 			return -EINVAL;
393 		}
394 		vb2_set_plane_payload(vb, i, size);
395 	}
396 
397 	return 0;
398 }
399 
400 static void buffer_queue(struct vb2_buffer *vb)
401 {
402 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
403 	struct fimc_vid_buffer *buf
404 		= container_of(vbuf, struct fimc_vid_buffer, vb);
405 	struct fimc_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
406 	struct fimc_dev *fimc = ctx->fimc_dev;
407 	struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
408 	struct exynos_video_entity *ve = &vid_cap->ve;
409 	unsigned long flags;
410 	int min_bufs;
411 
412 	spin_lock_irqsave(&fimc->slock, flags);
413 	fimc_prepare_addr(ctx, &buf->vb.vb2_buf, &ctx->d_frame, &buf->addr);
414 
415 	if (!test_bit(ST_CAPT_SUSPENDED, &fimc->state) &&
416 	    !test_bit(ST_CAPT_STREAM, &fimc->state) &&
417 	    vid_cap->active_buf_cnt < FIMC_MAX_OUT_BUFS) {
418 		/* Setup the buffer directly for processing. */
419 		int buf_id = (vid_cap->reqbufs_count == 1) ? -1 :
420 				vid_cap->buf_index;
421 
422 		fimc_hw_set_output_addr(fimc, &buf->addr, buf_id);
423 		buf->index = vid_cap->buf_index;
424 		fimc_active_queue_add(vid_cap, buf);
425 
426 		if (++vid_cap->buf_index >= FIMC_MAX_OUT_BUFS)
427 			vid_cap->buf_index = 0;
428 	} else {
429 		fimc_pending_queue_add(vid_cap, buf);
430 	}
431 
432 	min_bufs = vid_cap->reqbufs_count > 1 ? 2 : 1;
433 
434 
435 	if (vb2_is_streaming(&vid_cap->vbq) &&
436 	    vid_cap->active_buf_cnt >= min_bufs &&
437 	    !test_and_set_bit(ST_CAPT_STREAM, &fimc->state)) {
438 		int ret;
439 
440 		fimc_activate_capture(ctx);
441 		spin_unlock_irqrestore(&fimc->slock, flags);
442 
443 		if (test_and_set_bit(ST_CAPT_ISP_STREAM, &fimc->state))
444 			return;
445 
446 		ret = fimc_pipeline_call(ve, set_stream, 1);
447 		if (ret < 0)
448 			v4l2_err(&ve->vdev, "stream on failed: %d\n", ret);
449 		return;
450 	}
451 	spin_unlock_irqrestore(&fimc->slock, flags);
452 }
453 
454 static const struct vb2_ops fimc_capture_qops = {
455 	.queue_setup		= queue_setup,
456 	.buf_prepare		= buffer_prepare,
457 	.buf_queue		= buffer_queue,
458 	.wait_prepare		= vb2_ops_wait_prepare,
459 	.wait_finish		= vb2_ops_wait_finish,
460 	.start_streaming	= start_streaming,
461 	.stop_streaming		= stop_streaming,
462 };
463 
464 static int fimc_capture_set_default_format(struct fimc_dev *fimc);
465 
466 static int fimc_capture_open(struct file *file)
467 {
468 	struct fimc_dev *fimc = video_drvdata(file);
469 	struct fimc_vid_cap *vc = &fimc->vid_cap;
470 	struct exynos_video_entity *ve = &vc->ve;
471 	int ret = -EBUSY;
472 
473 	dbg("pid: %d, state: 0x%lx", task_pid_nr(current), fimc->state);
474 
475 	mutex_lock(&fimc->lock);
476 
477 	if (fimc_m2m_active(fimc))
478 		goto unlock;
479 
480 	set_bit(ST_CAPT_BUSY, &fimc->state);
481 	ret = pm_runtime_resume_and_get(&fimc->pdev->dev);
482 	if (ret < 0)
483 		goto unlock;
484 
485 	ret = v4l2_fh_open(file);
486 	if (ret) {
487 		pm_runtime_put_sync(&fimc->pdev->dev);
488 		goto unlock;
489 	}
490 
491 	if (v4l2_fh_is_singular_file(file)) {
492 		fimc_md_graph_lock(ve);
493 
494 		ret = fimc_pipeline_call(ve, open, &ve->vdev.entity, true);
495 
496 		if (ret == 0)
497 			ve->vdev.entity.use_count++;
498 
499 		fimc_md_graph_unlock(ve);
500 
501 		if (ret == 0)
502 			ret = fimc_capture_set_default_format(fimc);
503 
504 		if (ret < 0) {
505 			clear_bit(ST_CAPT_BUSY, &fimc->state);
506 			pm_runtime_put_sync(&fimc->pdev->dev);
507 			v4l2_fh_release(file);
508 		}
509 	}
510 unlock:
511 	mutex_unlock(&fimc->lock);
512 	return ret;
513 }
514 
515 static int fimc_capture_release(struct file *file)
516 {
517 	struct fimc_dev *fimc = video_drvdata(file);
518 	struct fimc_vid_cap *vc = &fimc->vid_cap;
519 	bool close = v4l2_fh_is_singular_file(file);
520 	int ret;
521 
522 	dbg("pid: %d, state: 0x%lx", task_pid_nr(current), fimc->state);
523 
524 	mutex_lock(&fimc->lock);
525 
526 	if (close && vc->streaming) {
527 		video_device_pipeline_stop(&vc->ve.vdev);
528 		vc->streaming = false;
529 	}
530 
531 	ret = _vb2_fop_release(file, NULL);
532 
533 	if (close) {
534 		clear_bit(ST_CAPT_BUSY, &fimc->state);
535 		fimc_pipeline_call(&vc->ve, close);
536 		clear_bit(ST_CAPT_SUSPENDED, &fimc->state);
537 
538 		fimc_md_graph_lock(&vc->ve);
539 		vc->ve.vdev.entity.use_count--;
540 		fimc_md_graph_unlock(&vc->ve);
541 	}
542 
543 	pm_runtime_put_sync(&fimc->pdev->dev);
544 	mutex_unlock(&fimc->lock);
545 
546 	return ret;
547 }
548 
549 static const struct v4l2_file_operations fimc_capture_fops = {
550 	.owner		= THIS_MODULE,
551 	.open		= fimc_capture_open,
552 	.release	= fimc_capture_release,
553 	.poll		= vb2_fop_poll,
554 	.unlocked_ioctl	= video_ioctl2,
555 	.mmap		= vb2_fop_mmap,
556 };
557 
558 /*
559  * Format and crop negotiation helpers
560  */
561 
562 static struct fimc_fmt *fimc_capture_try_format(struct fimc_ctx *ctx,
563 						u32 *width, u32 *height,
564 						u32 *code, u32 *fourcc, int pad)
565 {
566 	bool rotation = ctx->rotation == 90 || ctx->rotation == 270;
567 	struct fimc_dev *fimc = ctx->fimc_dev;
568 	const struct fimc_variant *var = fimc->variant;
569 	const struct fimc_pix_limit *pl = var->pix_limit;
570 	struct fimc_frame *dst = &ctx->d_frame;
571 	u32 depth, min_w, max_w, min_h, align_h = 3;
572 	u32 mask = FMT_FLAGS_CAM;
573 	struct fimc_fmt *ffmt;
574 
575 	/* Conversion from/to JPEG or User Defined format is not supported */
576 	if (code && ctx->s_frame.fmt && pad == FIMC_SD_PAD_SOURCE &&
577 	    fimc_fmt_is_user_defined(ctx->s_frame.fmt->color))
578 		*code = ctx->s_frame.fmt->mbus_code;
579 
580 	if (fourcc && *fourcc != V4L2_PIX_FMT_JPEG && pad == FIMC_SD_PAD_SOURCE)
581 		mask |= FMT_FLAGS_M2M;
582 
583 	if (pad == FIMC_SD_PAD_SINK_FIFO)
584 		mask = FMT_FLAGS_WRITEBACK;
585 
586 	ffmt = fimc_find_format(fourcc, code, mask, 0);
587 	if (WARN_ON(!ffmt))
588 		return NULL;
589 
590 	if (code)
591 		*code = ffmt->mbus_code;
592 	if (fourcc)
593 		*fourcc = ffmt->fourcc;
594 
595 	if (pad != FIMC_SD_PAD_SOURCE) {
596 		max_w = fimc_fmt_is_user_defined(ffmt->color) ?
597 			pl->scaler_dis_w : pl->scaler_en_w;
598 		/* Apply the camera input interface pixel constraints */
599 		v4l_bound_align_image(width, max_t(u32, *width, 32), max_w, 4,
600 				      height, max_t(u32, *height, 32),
601 				      FIMC_CAMIF_MAX_HEIGHT,
602 				      fimc_fmt_is_user_defined(ffmt->color) ?
603 				      3 : 1,
604 				      0);
605 		return ffmt;
606 	}
607 	/* Can't scale or crop in transparent (JPEG) transfer mode */
608 	if (fimc_fmt_is_user_defined(ffmt->color)) {
609 		*width  = ctx->s_frame.f_width;
610 		*height = ctx->s_frame.f_height;
611 		return ffmt;
612 	}
613 	/* Apply the scaler and the output DMA constraints */
614 	max_w = rotation ? pl->out_rot_en_w : pl->out_rot_dis_w;
615 	if (ctx->state & FIMC_COMPOSE) {
616 		min_w = dst->offs_h + dst->width;
617 		min_h = dst->offs_v + dst->height;
618 	} else {
619 		min_w = var->min_out_pixsize;
620 		min_h = var->min_out_pixsize;
621 	}
622 	if (var->min_vsize_align == 1 && !rotation)
623 		align_h = fimc_fmt_is_rgb(ffmt->color) ? 0 : 1;
624 
625 	depth = fimc_get_format_depth(ffmt);
626 	v4l_bound_align_image(width, min_w, max_w,
627 			      ffs(var->min_out_pixsize) - 1,
628 			      height, min_h, FIMC_CAMIF_MAX_HEIGHT,
629 			      align_h,
630 			      64/(ALIGN(depth, 8)));
631 
632 	dbg("pad%d: code: 0x%x, %dx%d. dst fmt: %dx%d",
633 	    pad, code ? *code : 0, *width, *height,
634 	    dst->f_width, dst->f_height);
635 
636 	return ffmt;
637 }
638 
639 static void fimc_capture_try_selection(struct fimc_ctx *ctx,
640 				       struct v4l2_rect *r,
641 				       int target)
642 {
643 	bool rotate = ctx->rotation == 90 || ctx->rotation == 270;
644 	struct fimc_dev *fimc = ctx->fimc_dev;
645 	const struct fimc_variant *var = fimc->variant;
646 	const struct fimc_pix_limit *pl = var->pix_limit;
647 	struct fimc_frame *sink = &ctx->s_frame;
648 	u32 max_w, max_h, min_w = 0, min_h = 0, min_sz;
649 	u32 align_sz = 0, align_h = 4;
650 	u32 max_sc_h, max_sc_v;
651 
652 	/* In JPEG transparent transfer mode cropping is not supported */
653 	if (fimc_fmt_is_user_defined(ctx->d_frame.fmt->color)) {
654 		r->width  = sink->f_width;
655 		r->height = sink->f_height;
656 		r->left   = r->top = 0;
657 		return;
658 	}
659 	if (target == V4L2_SEL_TGT_COMPOSE) {
660 		u32 tmp_min_h = ffs(sink->width) - 3;
661 		u32 tmp_min_v = ffs(sink->height) - 1;
662 
663 		if (ctx->rotation != 90 && ctx->rotation != 270)
664 			align_h = 1;
665 		max_sc_h = min(SCALER_MAX_HRATIO, 1 << tmp_min_h);
666 		max_sc_v = min(SCALER_MAX_VRATIO, 1 << tmp_min_v);
667 		min_sz = var->min_out_pixsize;
668 	} else {
669 		u32 depth = fimc_get_format_depth(sink->fmt);
670 		align_sz = 64/ALIGN(depth, 8);
671 		min_sz = var->min_inp_pixsize;
672 		min_w = min_h = min_sz;
673 		max_sc_h = max_sc_v = 1;
674 	}
675 	/*
676 	 * For the compose rectangle the following constraints must be met:
677 	 * - it must fit in the sink pad format rectangle (f_width/f_height);
678 	 * - maximum downscaling ratio is 64;
679 	 * - maximum crop size depends if the rotator is used or not;
680 	 * - the sink pad format width/height must be 4 multiple of the
681 	 *   prescaler ratios determined by sink pad size and source pad crop,
682 	 *   the prescaler ratio is returned by fimc_get_scaler_factor().
683 	 */
684 	max_w = min_t(u32,
685 		      rotate ? pl->out_rot_en_w : pl->out_rot_dis_w,
686 		      rotate ? sink->f_height : sink->f_width);
687 	max_h = min_t(u32, FIMC_CAMIF_MAX_HEIGHT, sink->f_height);
688 
689 	if (target == V4L2_SEL_TGT_COMPOSE) {
690 		min_w = min_t(u32, max_w, sink->f_width / max_sc_h);
691 		min_h = min_t(u32, max_h, sink->f_height / max_sc_v);
692 		if (rotate) {
693 			swap(max_sc_h, max_sc_v);
694 			swap(min_w, min_h);
695 		}
696 	}
697 	v4l_bound_align_image(&r->width, min_w, max_w, ffs(min_sz) - 1,
698 			      &r->height, min_h, max_h, align_h,
699 			      align_sz);
700 	/* Adjust left/top if crop/compose rectangle is out of bounds */
701 	r->left = clamp_t(u32, r->left, 0, sink->f_width - r->width);
702 	r->top  = clamp_t(u32, r->top, 0, sink->f_height - r->height);
703 	r->left = round_down(r->left, var->hor_offs_align);
704 
705 	dbg("target %#x: (%d,%d)/%dx%d, sink fmt: %dx%d",
706 	    target, r->left, r->top, r->width, r->height,
707 	    sink->f_width, sink->f_height);
708 }
709 
710 /*
711  * The video node ioctl operations
712  */
713 static int fimc_cap_querycap(struct file *file, void *priv,
714 					struct v4l2_capability *cap)
715 {
716 	struct fimc_dev *fimc = video_drvdata(file);
717 
718 	__fimc_vidioc_querycap(&fimc->pdev->dev, cap);
719 	return 0;
720 }
721 
722 static int fimc_cap_enum_fmt(struct file *file, void *priv,
723 			     struct v4l2_fmtdesc *f)
724 {
725 	struct fimc_fmt *fmt;
726 
727 	fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_CAM | FMT_FLAGS_M2M,
728 			       f->index);
729 	if (!fmt)
730 		return -EINVAL;
731 	f->pixelformat = fmt->fourcc;
732 	return 0;
733 }
734 
735 static struct media_entity *fimc_pipeline_get_head(struct media_entity *me)
736 {
737 	struct media_pad *pad = &me->pads[0];
738 
739 	while (!(pad->flags & MEDIA_PAD_FL_SOURCE)) {
740 		pad = media_pad_remote_pad_first(pad);
741 		if (!pad)
742 			break;
743 		me = pad->entity;
744 		pad = &me->pads[0];
745 	}
746 
747 	return me;
748 }
749 
750 /**
751  * fimc_pipeline_try_format - negotiate and/or set formats at pipeline
752  *                            elements
753  * @ctx: FIMC capture context
754  * @tfmt: media bus format to try/set on subdevs
755  * @fmt_id: fimc pixel format id corresponding to returned @tfmt (output)
756  * @set: true to set format on subdevs, false to try only
757  */
758 static int fimc_pipeline_try_format(struct fimc_ctx *ctx,
759 				    struct v4l2_mbus_framefmt *tfmt,
760 				    struct fimc_fmt **fmt_id,
761 				    bool set)
762 {
763 	struct fimc_dev *fimc = ctx->fimc_dev;
764 	struct fimc_pipeline *p = to_fimc_pipeline(fimc->vid_cap.ve.pipe);
765 	struct v4l2_subdev *sd = p->subdevs[IDX_SENSOR];
766 	struct v4l2_subdev_format sfmt;
767 	struct v4l2_mbus_framefmt *mf = &sfmt.format;
768 	struct media_entity *me;
769 	struct fimc_fmt *ffmt;
770 	struct media_pad *pad;
771 	int ret, i = 1;
772 	u32 fcc;
773 
774 	if (WARN_ON(!sd || !tfmt))
775 		return -EINVAL;
776 
777 	memset(&sfmt, 0, sizeof(sfmt));
778 	sfmt.format = *tfmt;
779 	sfmt.which = set ? V4L2_SUBDEV_FORMAT_ACTIVE : V4L2_SUBDEV_FORMAT_TRY;
780 
781 	me = fimc_pipeline_get_head(&sd->entity);
782 
783 	while (1) {
784 		ffmt = fimc_find_format(NULL, mf->code != 0 ? &mf->code : NULL,
785 					FMT_FLAGS_CAM, i++);
786 		if (ffmt == NULL) {
787 			/*
788 			 * Notify user-space if common pixel code for
789 			 * host and sensor does not exist.
790 			 */
791 			return -EINVAL;
792 		}
793 		mf->code = tfmt->code = ffmt->mbus_code;
794 
795 		/* set format on all pipeline subdevs */
796 		while (me != &fimc->vid_cap.subdev.entity) {
797 			sd = media_entity_to_v4l2_subdev(me);
798 
799 			sfmt.pad = 0;
800 			ret = v4l2_subdev_call(sd, pad, set_fmt, NULL, &sfmt);
801 			if (ret)
802 				return ret;
803 
804 			if (me->pads[0].flags & MEDIA_PAD_FL_SINK) {
805 				sfmt.pad = me->num_pads - 1;
806 				mf->code = tfmt->code;
807 				ret = v4l2_subdev_call(sd, pad, set_fmt, NULL,
808 									&sfmt);
809 				if (ret)
810 					return ret;
811 			}
812 
813 			pad = media_pad_remote_pad_first(&me->pads[sfmt.pad]);
814 			if (!pad)
815 				return -EINVAL;
816 			me = pad->entity;
817 		}
818 
819 		if (mf->code != tfmt->code)
820 			continue;
821 
822 		fcc = ffmt->fourcc;
823 		tfmt->width  = mf->width;
824 		tfmt->height = mf->height;
825 		ffmt = fimc_capture_try_format(ctx, &tfmt->width, &tfmt->height,
826 					NULL, &fcc, FIMC_SD_PAD_SINK_CAM);
827 		ffmt = fimc_capture_try_format(ctx, &tfmt->width, &tfmt->height,
828 					NULL, &fcc, FIMC_SD_PAD_SOURCE);
829 		if (ffmt && ffmt->mbus_code)
830 			mf->code = ffmt->mbus_code;
831 		if (mf->width != tfmt->width || mf->height != tfmt->height)
832 			continue;
833 		tfmt->code = mf->code;
834 		break;
835 	}
836 
837 	if (fmt_id && ffmt)
838 		*fmt_id = ffmt;
839 	*tfmt = *mf;
840 
841 	return 0;
842 }
843 
844 /**
845  * fimc_get_sensor_frame_desc - query the sensor for media bus frame parameters
846  * @sensor: pointer to the sensor subdev
847  * @plane_fmt: provides plane sizes corresponding to the frame layout entries
848  * @num_planes: number of planes
849  * @try: true to set the frame parameters, false to query only
850  *
851  * This function is used by this driver only for compressed/blob data formats.
852  */
853 static int fimc_get_sensor_frame_desc(struct v4l2_subdev *sensor,
854 				      struct v4l2_plane_pix_format *plane_fmt,
855 				      unsigned int num_planes, bool try)
856 {
857 	struct v4l2_mbus_frame_desc fd;
858 	int i, ret;
859 	int pad;
860 
861 	for (i = 0; i < num_planes; i++)
862 		fd.entry[i].length = plane_fmt[i].sizeimage;
863 
864 	pad = sensor->entity.num_pads - 1;
865 	if (try)
866 		ret = v4l2_subdev_call(sensor, pad, set_frame_desc, pad, &fd);
867 	else
868 		ret = v4l2_subdev_call(sensor, pad, get_frame_desc, pad, &fd);
869 
870 	if (ret < 0)
871 		return ret;
872 
873 	if (num_planes != fd.num_entries)
874 		return -EINVAL;
875 
876 	for (i = 0; i < num_planes; i++)
877 		plane_fmt[i].sizeimage = fd.entry[i].length;
878 
879 	if (fd.entry[0].length > FIMC_MAX_JPEG_BUF_SIZE) {
880 		v4l2_err(sensor->v4l2_dev,  "Unsupported buffer size: %u\n",
881 			 fd.entry[0].length);
882 
883 		return -EINVAL;
884 	}
885 
886 	return 0;
887 }
888 
889 static int fimc_cap_g_fmt_mplane(struct file *file, void *fh,
890 				 struct v4l2_format *f)
891 {
892 	struct fimc_dev *fimc = video_drvdata(file);
893 
894 	__fimc_get_format(&fimc->vid_cap.ctx->d_frame, f);
895 	return 0;
896 }
897 
898 /*
899  * Try or set format on the fimc.X.capture video node and additionally
900  * on the whole pipeline if @try is false.
901  * Locking: the caller must _not_ hold the graph mutex.
902  */
903 static int __video_try_or_set_format(struct fimc_dev *fimc,
904 				     struct v4l2_format *f, bool try,
905 				     struct fimc_fmt **inp_fmt,
906 				     struct fimc_fmt **out_fmt)
907 {
908 	struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
909 	struct fimc_vid_cap *vc = &fimc->vid_cap;
910 	struct exynos_video_entity *ve = &vc->ve;
911 	struct fimc_ctx *ctx = vc->ctx;
912 	unsigned int width = 0, height = 0;
913 	int ret = 0;
914 
915 	/* Pre-configure format at the camera input interface, for JPEG only */
916 	if (fimc_jpeg_fourcc(pix->pixelformat)) {
917 		fimc_capture_try_format(ctx, &pix->width, &pix->height,
918 					NULL, &pix->pixelformat,
919 					FIMC_SD_PAD_SINK_CAM);
920 		if (try) {
921 			width = pix->width;
922 			height = pix->height;
923 		} else {
924 			ctx->s_frame.f_width = pix->width;
925 			ctx->s_frame.f_height = pix->height;
926 		}
927 	}
928 
929 	/* Try the format at the scaler and the DMA output */
930 	*out_fmt = fimc_capture_try_format(ctx, &pix->width, &pix->height,
931 					  NULL, &pix->pixelformat,
932 					  FIMC_SD_PAD_SOURCE);
933 	if (*out_fmt == NULL)
934 		return -EINVAL;
935 
936 	/* Restore image width/height for JPEG (no resizing supported). */
937 	if (try && fimc_jpeg_fourcc(pix->pixelformat)) {
938 		pix->width = width;
939 		pix->height = height;
940 	}
941 
942 	/* Try to match format at the host and the sensor */
943 	if (!vc->user_subdev_api) {
944 		struct v4l2_mbus_framefmt mbus_fmt;
945 		struct v4l2_mbus_framefmt *mf;
946 
947 		mf = try ? &mbus_fmt : &fimc->vid_cap.ci_fmt;
948 
949 		mf->code = (*out_fmt)->mbus_code;
950 		mf->width = pix->width;
951 		mf->height = pix->height;
952 
953 		fimc_md_graph_lock(ve);
954 		ret = fimc_pipeline_try_format(ctx, mf, inp_fmt, try);
955 		fimc_md_graph_unlock(ve);
956 
957 		if (ret < 0)
958 			return ret;
959 
960 		pix->width = mf->width;
961 		pix->height = mf->height;
962 	}
963 
964 	fimc_adjust_mplane_format(*out_fmt, pix->width, pix->height, pix);
965 
966 	if ((*out_fmt)->flags & FMT_FLAGS_COMPRESSED) {
967 		struct v4l2_subdev *sensor;
968 
969 		fimc_md_graph_lock(ve);
970 
971 		sensor = __fimc_md_get_subdev(ve->pipe, IDX_SENSOR);
972 		if (sensor)
973 			fimc_get_sensor_frame_desc(sensor, pix->plane_fmt,
974 						   (*out_fmt)->memplanes, try);
975 		else
976 			ret = -EPIPE;
977 
978 		fimc_md_graph_unlock(ve);
979 	}
980 
981 	return ret;
982 }
983 
984 static int fimc_cap_try_fmt_mplane(struct file *file, void *fh,
985 				   struct v4l2_format *f)
986 {
987 	struct fimc_dev *fimc = video_drvdata(file);
988 	struct fimc_fmt *out_fmt = NULL, *inp_fmt = NULL;
989 
990 	return __video_try_or_set_format(fimc, f, true, &inp_fmt, &out_fmt);
991 }
992 
993 static void fimc_capture_mark_jpeg_xfer(struct fimc_ctx *ctx,
994 					enum fimc_color_fmt color)
995 {
996 	bool jpeg = fimc_fmt_is_user_defined(color);
997 
998 	ctx->scaler.enabled = !jpeg;
999 	fimc_ctrls_activate(ctx, !jpeg);
1000 
1001 	if (jpeg)
1002 		set_bit(ST_CAPT_JPEG, &ctx->fimc_dev->state);
1003 	else
1004 		clear_bit(ST_CAPT_JPEG, &ctx->fimc_dev->state);
1005 }
1006 
1007 static int __fimc_capture_set_format(struct fimc_dev *fimc,
1008 				     struct v4l2_format *f)
1009 {
1010 	struct fimc_vid_cap *vc = &fimc->vid_cap;
1011 	struct fimc_ctx *ctx = vc->ctx;
1012 	struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
1013 	struct fimc_frame *ff = &ctx->d_frame;
1014 	struct fimc_fmt *inp_fmt = NULL;
1015 	int ret, i;
1016 
1017 	if (vb2_is_busy(&fimc->vid_cap.vbq))
1018 		return -EBUSY;
1019 
1020 	ret = __video_try_or_set_format(fimc, f, false, &inp_fmt, &ff->fmt);
1021 	if (ret < 0)
1022 		return ret;
1023 
1024 	/* Update RGB Alpha control state and value range */
1025 	fimc_alpha_ctrl_update(ctx);
1026 
1027 	for (i = 0; i < ff->fmt->memplanes; i++) {
1028 		ff->bytesperline[i] = pix->plane_fmt[i].bytesperline;
1029 		ff->payload[i] = pix->plane_fmt[i].sizeimage;
1030 	}
1031 
1032 	set_frame_bounds(ff, pix->width, pix->height);
1033 	/* Reset the composition rectangle if not yet configured */
1034 	if (!(ctx->state & FIMC_COMPOSE))
1035 		set_frame_crop(ff, 0, 0, pix->width, pix->height);
1036 
1037 	fimc_capture_mark_jpeg_xfer(ctx, ff->fmt->color);
1038 
1039 	/* Reset cropping and set format at the camera interface input */
1040 	if (!vc->user_subdev_api) {
1041 		ctx->s_frame.fmt = inp_fmt;
1042 		set_frame_bounds(&ctx->s_frame, pix->width, pix->height);
1043 		set_frame_crop(&ctx->s_frame, 0, 0, pix->width, pix->height);
1044 	}
1045 
1046 	return ret;
1047 }
1048 
1049 static int fimc_cap_s_fmt_mplane(struct file *file, void *priv,
1050 				 struct v4l2_format *f)
1051 {
1052 	struct fimc_dev *fimc = video_drvdata(file);
1053 
1054 	return __fimc_capture_set_format(fimc, f);
1055 }
1056 
1057 static int fimc_cap_enum_input(struct file *file, void *priv,
1058 			       struct v4l2_input *i)
1059 {
1060 	struct fimc_dev *fimc = video_drvdata(file);
1061 	struct exynos_video_entity *ve = &fimc->vid_cap.ve;
1062 	struct v4l2_subdev *sd;
1063 
1064 	if (i->index != 0)
1065 		return -EINVAL;
1066 
1067 	i->type = V4L2_INPUT_TYPE_CAMERA;
1068 	fimc_md_graph_lock(ve);
1069 	sd = __fimc_md_get_subdev(ve->pipe, IDX_SENSOR);
1070 	fimc_md_graph_unlock(ve);
1071 
1072 	if (sd)
1073 		strscpy(i->name, sd->name, sizeof(i->name));
1074 
1075 	return 0;
1076 }
1077 
1078 static int fimc_cap_s_input(struct file *file, void *priv, unsigned int i)
1079 {
1080 	return i == 0 ? i : -EINVAL;
1081 }
1082 
1083 static int fimc_cap_g_input(struct file *file, void *priv, unsigned int *i)
1084 {
1085 	*i = 0;
1086 	return 0;
1087 }
1088 
1089 /**
1090  * fimc_pipeline_validate - check for formats inconsistencies
1091  *                          between source and sink pad of each link
1092  * @fimc:	the FIMC device this context applies to
1093  *
1094  * Return 0 if all formats match or -EPIPE otherwise.
1095  */
1096 static int fimc_pipeline_validate(struct fimc_dev *fimc)
1097 {
1098 	struct v4l2_subdev_format sink_fmt, src_fmt;
1099 	struct fimc_vid_cap *vc = &fimc->vid_cap;
1100 	struct v4l2_subdev *sd = &vc->subdev;
1101 	struct fimc_pipeline *p = to_fimc_pipeline(vc->ve.pipe);
1102 	struct media_pad *sink_pad, *src_pad;
1103 	int i, ret;
1104 
1105 	while (1) {
1106 		/*
1107 		 * Find current entity sink pad and any remote sink pad linked
1108 		 * to it. We stop if there is no sink pad in current entity or
1109 		 * it is not linked to any other remote entity.
1110 		 */
1111 		src_pad = NULL;
1112 
1113 		for (i = 0; i < sd->entity.num_pads; i++) {
1114 			struct media_pad *p = &sd->entity.pads[i];
1115 
1116 			if (p->flags & MEDIA_PAD_FL_SINK) {
1117 				sink_pad = p;
1118 				src_pad = media_pad_remote_pad_first(sink_pad);
1119 				if (src_pad)
1120 					break;
1121 			}
1122 		}
1123 
1124 		if (!src_pad || !is_media_entity_v4l2_subdev(src_pad->entity))
1125 			break;
1126 
1127 		/* Don't call FIMC subdev operation to avoid nested locking */
1128 		if (sd == &vc->subdev) {
1129 			struct fimc_frame *ff = &vc->ctx->s_frame;
1130 			sink_fmt.format.width = ff->f_width;
1131 			sink_fmt.format.height = ff->f_height;
1132 			sink_fmt.format.code = ff->fmt ? ff->fmt->mbus_code : 0;
1133 		} else {
1134 			sink_fmt.pad = sink_pad->index;
1135 			sink_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1136 			ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &sink_fmt);
1137 			if (ret < 0 && ret != -ENOIOCTLCMD)
1138 				return -EPIPE;
1139 		}
1140 
1141 		/* Retrieve format at the source pad */
1142 		sd = media_entity_to_v4l2_subdev(src_pad->entity);
1143 		src_fmt.pad = src_pad->index;
1144 		src_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1145 		ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &src_fmt);
1146 		if (ret < 0 && ret != -ENOIOCTLCMD)
1147 			return -EPIPE;
1148 
1149 		if (src_fmt.format.width != sink_fmt.format.width ||
1150 		    src_fmt.format.height != sink_fmt.format.height ||
1151 		    src_fmt.format.code != sink_fmt.format.code)
1152 			return -EPIPE;
1153 
1154 		if (sd == p->subdevs[IDX_SENSOR] &&
1155 		    fimc_user_defined_mbus_fmt(src_fmt.format.code)) {
1156 			struct v4l2_plane_pix_format plane_fmt[FIMC_MAX_PLANES];
1157 			struct fimc_frame *frame = &vc->ctx->d_frame;
1158 			unsigned int i;
1159 
1160 			ret = fimc_get_sensor_frame_desc(sd, plane_fmt,
1161 							 frame->fmt->memplanes,
1162 							 false);
1163 			if (ret < 0)
1164 				return -EPIPE;
1165 
1166 			for (i = 0; i < frame->fmt->memplanes; i++)
1167 				if (frame->payload[i] < plane_fmt[i].sizeimage)
1168 					return -EPIPE;
1169 		}
1170 	}
1171 	return 0;
1172 }
1173 
1174 static int fimc_cap_streamon(struct file *file, void *priv,
1175 			     enum v4l2_buf_type type)
1176 {
1177 	struct fimc_dev *fimc = video_drvdata(file);
1178 	struct fimc_vid_cap *vc = &fimc->vid_cap;
1179 	struct fimc_source_info *si = NULL;
1180 	struct v4l2_subdev *sd;
1181 	int ret;
1182 
1183 	if (fimc_capture_active(fimc))
1184 		return -EBUSY;
1185 
1186 	ret = video_device_pipeline_start(&vc->ve.vdev, &vc->ve.pipe->mp);
1187 	if (ret < 0)
1188 		return ret;
1189 
1190 	sd = __fimc_md_get_subdev(vc->ve.pipe, IDX_SENSOR);
1191 	if (sd)
1192 		si = v4l2_get_subdev_hostdata(sd);
1193 
1194 	if (si == NULL) {
1195 		ret = -EPIPE;
1196 		goto err_p_stop;
1197 	}
1198 	/*
1199 	 * Save configuration data related to currently attached image
1200 	 * sensor or other data source, e.g. FIMC-IS.
1201 	 */
1202 	vc->source_config = *si;
1203 
1204 	if (vc->input == GRP_ID_FIMC_IS)
1205 		vc->source_config.fimc_bus_type = FIMC_BUS_TYPE_ISP_WRITEBACK;
1206 
1207 	if (vc->user_subdev_api) {
1208 		ret = fimc_pipeline_validate(fimc);
1209 		if (ret < 0)
1210 			goto err_p_stop;
1211 	}
1212 
1213 	ret = vb2_ioctl_streamon(file, priv, type);
1214 	if (!ret) {
1215 		vc->streaming = true;
1216 		return ret;
1217 	}
1218 
1219 err_p_stop:
1220 	video_device_pipeline_stop(&vc->ve.vdev);
1221 	return ret;
1222 }
1223 
1224 static int fimc_cap_streamoff(struct file *file, void *priv,
1225 			    enum v4l2_buf_type type)
1226 {
1227 	struct fimc_dev *fimc = video_drvdata(file);
1228 	struct fimc_vid_cap *vc = &fimc->vid_cap;
1229 	int ret;
1230 
1231 	ret = vb2_ioctl_streamoff(file, priv, type);
1232 	if (ret < 0)
1233 		return ret;
1234 
1235 	if (vc->streaming) {
1236 		video_device_pipeline_stop(&vc->ve.vdev);
1237 		vc->streaming = false;
1238 	}
1239 
1240 	return 0;
1241 }
1242 
1243 static int fimc_cap_reqbufs(struct file *file, void *priv,
1244 			    struct v4l2_requestbuffers *reqbufs)
1245 {
1246 	struct fimc_dev *fimc = video_drvdata(file);
1247 	int ret;
1248 
1249 	ret = vb2_ioctl_reqbufs(file, priv, reqbufs);
1250 
1251 	if (!ret)
1252 		fimc->vid_cap.reqbufs_count = reqbufs->count;
1253 
1254 	return ret;
1255 }
1256 
1257 static int fimc_cap_g_selection(struct file *file, void *fh,
1258 				struct v4l2_selection *s)
1259 {
1260 	struct fimc_dev *fimc = video_drvdata(file);
1261 	struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1262 	struct fimc_frame *f = &ctx->s_frame;
1263 
1264 	if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1265 		return -EINVAL;
1266 
1267 	switch (s->target) {
1268 	case V4L2_SEL_TGT_COMPOSE_DEFAULT:
1269 	case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1270 		f = &ctx->d_frame;
1271 		fallthrough;
1272 	case V4L2_SEL_TGT_CROP_BOUNDS:
1273 	case V4L2_SEL_TGT_CROP_DEFAULT:
1274 		s->r.left = 0;
1275 		s->r.top = 0;
1276 		s->r.width = f->o_width;
1277 		s->r.height = f->o_height;
1278 		return 0;
1279 
1280 	case V4L2_SEL_TGT_COMPOSE:
1281 		f = &ctx->d_frame;
1282 		fallthrough;
1283 	case V4L2_SEL_TGT_CROP:
1284 		s->r.left = f->offs_h;
1285 		s->r.top = f->offs_v;
1286 		s->r.width = f->width;
1287 		s->r.height = f->height;
1288 		return 0;
1289 	}
1290 
1291 	return -EINVAL;
1292 }
1293 
1294 static int fimc_cap_s_selection(struct file *file, void *fh,
1295 				struct v4l2_selection *s)
1296 {
1297 	struct fimc_dev *fimc = video_drvdata(file);
1298 	struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1299 	struct v4l2_rect rect = s->r;
1300 	struct fimc_frame *f;
1301 	unsigned long flags;
1302 
1303 	if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1304 		return -EINVAL;
1305 
1306 	if (s->target == V4L2_SEL_TGT_COMPOSE)
1307 		f = &ctx->d_frame;
1308 	else if (s->target == V4L2_SEL_TGT_CROP)
1309 		f = &ctx->s_frame;
1310 	else
1311 		return -EINVAL;
1312 
1313 	fimc_capture_try_selection(ctx, &rect, s->target);
1314 
1315 	if (s->flags & V4L2_SEL_FLAG_LE &&
1316 	    !v4l2_rect_enclosed(&rect, &s->r))
1317 		return -ERANGE;
1318 
1319 	if (s->flags & V4L2_SEL_FLAG_GE &&
1320 	    !v4l2_rect_enclosed(&s->r, &rect))
1321 		return -ERANGE;
1322 
1323 	s->r = rect;
1324 	spin_lock_irqsave(&fimc->slock, flags);
1325 	set_frame_crop(f, s->r.left, s->r.top, s->r.width,
1326 		       s->r.height);
1327 	spin_unlock_irqrestore(&fimc->slock, flags);
1328 
1329 	set_bit(ST_CAPT_APPLY_CFG, &fimc->state);
1330 	return 0;
1331 }
1332 
1333 static const struct v4l2_ioctl_ops fimc_capture_ioctl_ops = {
1334 	.vidioc_querycap		= fimc_cap_querycap,
1335 
1336 	.vidioc_enum_fmt_vid_cap	= fimc_cap_enum_fmt,
1337 	.vidioc_try_fmt_vid_cap_mplane	= fimc_cap_try_fmt_mplane,
1338 	.vidioc_s_fmt_vid_cap_mplane	= fimc_cap_s_fmt_mplane,
1339 	.vidioc_g_fmt_vid_cap_mplane	= fimc_cap_g_fmt_mplane,
1340 
1341 	.vidioc_reqbufs			= fimc_cap_reqbufs,
1342 	.vidioc_querybuf		= vb2_ioctl_querybuf,
1343 	.vidioc_qbuf			= vb2_ioctl_qbuf,
1344 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
1345 	.vidioc_expbuf			= vb2_ioctl_expbuf,
1346 	.vidioc_prepare_buf		= vb2_ioctl_prepare_buf,
1347 	.vidioc_create_bufs		= vb2_ioctl_create_bufs,
1348 
1349 	.vidioc_streamon		= fimc_cap_streamon,
1350 	.vidioc_streamoff		= fimc_cap_streamoff,
1351 
1352 	.vidioc_g_selection		= fimc_cap_g_selection,
1353 	.vidioc_s_selection		= fimc_cap_s_selection,
1354 
1355 	.vidioc_enum_input		= fimc_cap_enum_input,
1356 	.vidioc_s_input			= fimc_cap_s_input,
1357 	.vidioc_g_input			= fimc_cap_g_input,
1358 };
1359 
1360 /* Capture subdev media entity operations */
1361 static int fimc_link_setup(struct media_entity *entity,
1362 			   const struct media_pad *local,
1363 			   const struct media_pad *remote, u32 flags)
1364 {
1365 	struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
1366 	struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1367 	struct fimc_vid_cap *vc = &fimc->vid_cap;
1368 	struct v4l2_subdev *sensor;
1369 
1370 	if (!is_media_entity_v4l2_subdev(remote->entity))
1371 		return -EINVAL;
1372 
1373 	if (WARN_ON(fimc == NULL))
1374 		return 0;
1375 
1376 	dbg("%s --> %s, flags: 0x%x. input: 0x%x",
1377 	    local->entity->name, remote->entity->name, flags,
1378 	    fimc->vid_cap.input);
1379 
1380 	if (!(flags & MEDIA_LNK_FL_ENABLED)) {
1381 		fimc->vid_cap.input = 0;
1382 		return 0;
1383 	}
1384 
1385 	if (vc->input != 0)
1386 		return -EBUSY;
1387 
1388 	vc->input = sd->grp_id;
1389 
1390 	if (vc->user_subdev_api)
1391 		return 0;
1392 
1393 	/* Inherit V4L2 controls from the image sensor subdev. */
1394 	sensor = fimc_find_remote_sensor(&vc->subdev.entity);
1395 	if (sensor == NULL)
1396 		return 0;
1397 
1398 	return v4l2_ctrl_add_handler(&vc->ctx->ctrls.handler,
1399 				     sensor->ctrl_handler, NULL, true);
1400 }
1401 
1402 static const struct media_entity_operations fimc_sd_media_ops = {
1403 	.link_setup = fimc_link_setup,
1404 };
1405 
1406 /**
1407  * fimc_sensor_notify - v4l2_device notification from a sensor subdev
1408  * @sd: pointer to a subdev generating the notification
1409  * @notification: the notification type, must be S5P_FIMC_TX_END_NOTIFY
1410  * @arg: pointer to an u32 type integer that stores the frame payload value
1411  *
1412  * The End Of Frame notification sent by sensor subdev in its still capture
1413  * mode. If there is only a single VSYNC generated by the sensor at the
1414  * beginning of a frame transmission, FIMC does not issue the LastIrq
1415  * (end of frame) interrupt. And this notification is used to complete the
1416  * frame capture and returning a buffer to user-space. Subdev drivers should
1417  * call this notification from their last 'End of frame capture' interrupt.
1418  */
1419 void fimc_sensor_notify(struct v4l2_subdev *sd, unsigned int notification,
1420 			void *arg)
1421 {
1422 	struct fimc_source_info	*si;
1423 	struct fimc_vid_buffer *buf;
1424 	struct fimc_md *fmd;
1425 	struct fimc_dev *fimc;
1426 	unsigned long flags;
1427 
1428 	if (sd == NULL)
1429 		return;
1430 
1431 	si = v4l2_get_subdev_hostdata(sd);
1432 	fmd = entity_to_fimc_mdev(&sd->entity);
1433 
1434 	spin_lock_irqsave(&fmd->slock, flags);
1435 
1436 	fimc = si ? source_to_sensor_info(si)->host : NULL;
1437 
1438 	if (fimc && arg && notification == S5P_FIMC_TX_END_NOTIFY &&
1439 	    test_bit(ST_CAPT_PEND, &fimc->state)) {
1440 		unsigned long irq_flags;
1441 		spin_lock_irqsave(&fimc->slock, irq_flags);
1442 		if (!list_empty(&fimc->vid_cap.active_buf_q)) {
1443 			buf = list_entry(fimc->vid_cap.active_buf_q.next,
1444 					 struct fimc_vid_buffer, list);
1445 			vb2_set_plane_payload(&buf->vb.vb2_buf, 0,
1446 					      *((u32 *)arg));
1447 		}
1448 		fimc_capture_irq_handler(fimc, 1);
1449 		fimc_deactivate_capture(fimc);
1450 		spin_unlock_irqrestore(&fimc->slock, irq_flags);
1451 	}
1452 	spin_unlock_irqrestore(&fmd->slock, flags);
1453 }
1454 
1455 static int fimc_subdev_enum_mbus_code(struct v4l2_subdev *sd,
1456 				      struct v4l2_subdev_state *sd_state,
1457 				      struct v4l2_subdev_mbus_code_enum *code)
1458 {
1459 	struct fimc_fmt *fmt;
1460 
1461 	fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_CAM, code->index);
1462 	if (!fmt)
1463 		return -EINVAL;
1464 	code->code = fmt->mbus_code;
1465 	return 0;
1466 }
1467 
1468 static int fimc_subdev_get_fmt(struct v4l2_subdev *sd,
1469 			       struct v4l2_subdev_state *sd_state,
1470 			       struct v4l2_subdev_format *fmt)
1471 {
1472 	struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1473 	struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1474 	struct fimc_frame *ff = &ctx->s_frame;
1475 	struct v4l2_mbus_framefmt *mf;
1476 
1477 	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
1478 		mf = v4l2_subdev_get_try_format(sd, sd_state, fmt->pad);
1479 		fmt->format = *mf;
1480 		return 0;
1481 	}
1482 
1483 	mf = &fmt->format;
1484 	mutex_lock(&fimc->lock);
1485 
1486 	switch (fmt->pad) {
1487 	case FIMC_SD_PAD_SOURCE:
1488 		if (!WARN_ON(ff->fmt == NULL))
1489 			mf->code = ff->fmt->mbus_code;
1490 		/* Sink pads crop rectangle size */
1491 		mf->width = ff->width;
1492 		mf->height = ff->height;
1493 		break;
1494 	case FIMC_SD_PAD_SINK_FIFO:
1495 		*mf = fimc->vid_cap.wb_fmt;
1496 		break;
1497 	case FIMC_SD_PAD_SINK_CAM:
1498 	default:
1499 		*mf = fimc->vid_cap.ci_fmt;
1500 		break;
1501 	}
1502 
1503 	mutex_unlock(&fimc->lock);
1504 	mf->colorspace = V4L2_COLORSPACE_JPEG;
1505 
1506 	return 0;
1507 }
1508 
1509 static int fimc_subdev_set_fmt(struct v4l2_subdev *sd,
1510 			       struct v4l2_subdev_state *sd_state,
1511 			       struct v4l2_subdev_format *fmt)
1512 {
1513 	struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1514 	struct v4l2_mbus_framefmt *mf = &fmt->format;
1515 	struct fimc_vid_cap *vc = &fimc->vid_cap;
1516 	struct fimc_ctx *ctx = vc->ctx;
1517 	struct fimc_frame *ff;
1518 	struct fimc_fmt *ffmt;
1519 
1520 	dbg("pad%d: code: 0x%x, %dx%d",
1521 	    fmt->pad, mf->code, mf->width, mf->height);
1522 
1523 	if (fmt->pad == FIMC_SD_PAD_SOURCE && vb2_is_busy(&vc->vbq))
1524 		return -EBUSY;
1525 
1526 	mutex_lock(&fimc->lock);
1527 	ffmt = fimc_capture_try_format(ctx, &mf->width, &mf->height,
1528 				       &mf->code, NULL, fmt->pad);
1529 	mutex_unlock(&fimc->lock);
1530 	mf->colorspace = V4L2_COLORSPACE_JPEG;
1531 
1532 	if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) {
1533 		mf = v4l2_subdev_get_try_format(sd, sd_state, fmt->pad);
1534 		*mf = fmt->format;
1535 		return 0;
1536 	}
1537 	/* There must be a bug in the driver if this happens */
1538 	if (WARN_ON(ffmt == NULL))
1539 		return -EINVAL;
1540 
1541 	/* Update RGB Alpha control state and value range */
1542 	fimc_alpha_ctrl_update(ctx);
1543 
1544 	fimc_capture_mark_jpeg_xfer(ctx, ffmt->color);
1545 	if (fmt->pad == FIMC_SD_PAD_SOURCE) {
1546 		ff = &ctx->d_frame;
1547 		/* Sink pads crop rectangle size */
1548 		mf->width = ctx->s_frame.width;
1549 		mf->height = ctx->s_frame.height;
1550 	} else {
1551 		ff = &ctx->s_frame;
1552 	}
1553 
1554 	mutex_lock(&fimc->lock);
1555 	set_frame_bounds(ff, mf->width, mf->height);
1556 
1557 	if (fmt->pad == FIMC_SD_PAD_SINK_FIFO)
1558 		vc->wb_fmt = *mf;
1559 	else if (fmt->pad == FIMC_SD_PAD_SINK_CAM)
1560 		vc->ci_fmt = *mf;
1561 
1562 	ff->fmt = ffmt;
1563 
1564 	/* Reset the crop rectangle if required. */
1565 	if (!(fmt->pad == FIMC_SD_PAD_SOURCE && (ctx->state & FIMC_COMPOSE)))
1566 		set_frame_crop(ff, 0, 0, mf->width, mf->height);
1567 
1568 	if (fmt->pad != FIMC_SD_PAD_SOURCE)
1569 		ctx->state &= ~FIMC_COMPOSE;
1570 
1571 	mutex_unlock(&fimc->lock);
1572 	return 0;
1573 }
1574 
1575 static int fimc_subdev_get_selection(struct v4l2_subdev *sd,
1576 				     struct v4l2_subdev_state *sd_state,
1577 				     struct v4l2_subdev_selection *sel)
1578 {
1579 	struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1580 	struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1581 	struct fimc_frame *f = &ctx->s_frame;
1582 	struct v4l2_rect *r = &sel->r;
1583 	struct v4l2_rect *try_sel;
1584 
1585 	if (sel->pad == FIMC_SD_PAD_SOURCE)
1586 		return -EINVAL;
1587 
1588 	mutex_lock(&fimc->lock);
1589 
1590 	switch (sel->target) {
1591 	case V4L2_SEL_TGT_COMPOSE_BOUNDS:
1592 		f = &ctx->d_frame;
1593 		fallthrough;
1594 	case V4L2_SEL_TGT_CROP_BOUNDS:
1595 		r->width = f->o_width;
1596 		r->height = f->o_height;
1597 		r->left = 0;
1598 		r->top = 0;
1599 		mutex_unlock(&fimc->lock);
1600 		return 0;
1601 
1602 	case V4L2_SEL_TGT_CROP:
1603 		try_sel = v4l2_subdev_get_try_crop(sd, sd_state, sel->pad);
1604 		break;
1605 	case V4L2_SEL_TGT_COMPOSE:
1606 		try_sel = v4l2_subdev_get_try_compose(sd, sd_state, sel->pad);
1607 		f = &ctx->d_frame;
1608 		break;
1609 	default:
1610 		mutex_unlock(&fimc->lock);
1611 		return -EINVAL;
1612 	}
1613 
1614 	if (sel->which == V4L2_SUBDEV_FORMAT_TRY) {
1615 		sel->r = *try_sel;
1616 	} else {
1617 		r->left = f->offs_h;
1618 		r->top = f->offs_v;
1619 		r->width = f->width;
1620 		r->height = f->height;
1621 	}
1622 
1623 	dbg("target %#x: l:%d, t:%d, %dx%d, f_w: %d, f_h: %d",
1624 	    sel->pad, r->left, r->top, r->width, r->height,
1625 	    f->f_width, f->f_height);
1626 
1627 	mutex_unlock(&fimc->lock);
1628 	return 0;
1629 }
1630 
1631 static int fimc_subdev_set_selection(struct v4l2_subdev *sd,
1632 				     struct v4l2_subdev_state *sd_state,
1633 				     struct v4l2_subdev_selection *sel)
1634 {
1635 	struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1636 	struct fimc_ctx *ctx = fimc->vid_cap.ctx;
1637 	struct fimc_frame *f = &ctx->s_frame;
1638 	struct v4l2_rect *r = &sel->r;
1639 	struct v4l2_rect *try_sel;
1640 	unsigned long flags;
1641 
1642 	if (sel->pad == FIMC_SD_PAD_SOURCE)
1643 		return -EINVAL;
1644 
1645 	mutex_lock(&fimc->lock);
1646 	fimc_capture_try_selection(ctx, r, V4L2_SEL_TGT_CROP);
1647 
1648 	switch (sel->target) {
1649 	case V4L2_SEL_TGT_CROP:
1650 		try_sel = v4l2_subdev_get_try_crop(sd, sd_state, sel->pad);
1651 		break;
1652 	case V4L2_SEL_TGT_COMPOSE:
1653 		try_sel = v4l2_subdev_get_try_compose(sd, sd_state, sel->pad);
1654 		f = &ctx->d_frame;
1655 		break;
1656 	default:
1657 		mutex_unlock(&fimc->lock);
1658 		return -EINVAL;
1659 	}
1660 
1661 	if (sel->which == V4L2_SUBDEV_FORMAT_TRY) {
1662 		*try_sel = sel->r;
1663 	} else {
1664 		spin_lock_irqsave(&fimc->slock, flags);
1665 		set_frame_crop(f, r->left, r->top, r->width, r->height);
1666 		set_bit(ST_CAPT_APPLY_CFG, &fimc->state);
1667 		if (sel->target == V4L2_SEL_TGT_COMPOSE)
1668 			ctx->state |= FIMC_COMPOSE;
1669 		spin_unlock_irqrestore(&fimc->slock, flags);
1670 	}
1671 
1672 	dbg("target %#x: (%d,%d)/%dx%d", sel->target, r->left, r->top,
1673 	    r->width, r->height);
1674 
1675 	mutex_unlock(&fimc->lock);
1676 	return 0;
1677 }
1678 
1679 static const struct v4l2_subdev_pad_ops fimc_subdev_pad_ops = {
1680 	.enum_mbus_code = fimc_subdev_enum_mbus_code,
1681 	.get_selection = fimc_subdev_get_selection,
1682 	.set_selection = fimc_subdev_set_selection,
1683 	.get_fmt = fimc_subdev_get_fmt,
1684 	.set_fmt = fimc_subdev_set_fmt,
1685 };
1686 
1687 static const struct v4l2_subdev_ops fimc_subdev_ops = {
1688 	.pad = &fimc_subdev_pad_ops,
1689 };
1690 
1691 /* Set default format at the sensor and host interface */
1692 static int fimc_capture_set_default_format(struct fimc_dev *fimc)
1693 {
1694 	struct v4l2_format fmt = {
1695 		.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
1696 		.fmt.pix_mp = {
1697 			.width		= FIMC_DEFAULT_WIDTH,
1698 			.height		= FIMC_DEFAULT_HEIGHT,
1699 			.pixelformat	= V4L2_PIX_FMT_YUYV,
1700 			.field		= V4L2_FIELD_NONE,
1701 			.colorspace	= V4L2_COLORSPACE_JPEG,
1702 		},
1703 	};
1704 
1705 	return __fimc_capture_set_format(fimc, &fmt);
1706 }
1707 
1708 /* fimc->lock must be already initialized */
1709 static int fimc_register_capture_device(struct fimc_dev *fimc,
1710 				 struct v4l2_device *v4l2_dev)
1711 {
1712 	struct video_device *vfd = &fimc->vid_cap.ve.vdev;
1713 	struct vb2_queue *q = &fimc->vid_cap.vbq;
1714 	struct fimc_ctx *ctx;
1715 	struct fimc_vid_cap *vid_cap;
1716 	struct fimc_fmt *fmt;
1717 	int ret = -ENOMEM;
1718 
1719 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1720 	if (!ctx)
1721 		return -ENOMEM;
1722 
1723 	ctx->fimc_dev	 = fimc;
1724 	ctx->in_path	 = FIMC_IO_CAMERA;
1725 	ctx->out_path	 = FIMC_IO_DMA;
1726 	ctx->state	 = FIMC_CTX_CAP;
1727 	ctx->s_frame.fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_CAM, 0);
1728 	ctx->d_frame.fmt = ctx->s_frame.fmt;
1729 
1730 	memset(vfd, 0, sizeof(*vfd));
1731 	snprintf(vfd->name, sizeof(vfd->name), "fimc.%d.capture", fimc->id);
1732 
1733 	vfd->fops	= &fimc_capture_fops;
1734 	vfd->ioctl_ops	= &fimc_capture_ioctl_ops;
1735 	vfd->v4l2_dev	= v4l2_dev;
1736 	vfd->minor	= -1;
1737 	vfd->release	= video_device_release_empty;
1738 	vfd->queue	= q;
1739 	vfd->lock	= &fimc->lock;
1740 	vfd->device_caps = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_CAPTURE_MPLANE;
1741 
1742 	video_set_drvdata(vfd, fimc);
1743 	vid_cap = &fimc->vid_cap;
1744 	vid_cap->active_buf_cnt = 0;
1745 	vid_cap->reqbufs_count = 0;
1746 	vid_cap->ctx = ctx;
1747 
1748 	INIT_LIST_HEAD(&vid_cap->pending_buf_q);
1749 	INIT_LIST_HEAD(&vid_cap->active_buf_q);
1750 
1751 	memset(q, 0, sizeof(*q));
1752 	q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1753 	q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1754 	q->drv_priv = ctx;
1755 	q->ops = &fimc_capture_qops;
1756 	q->mem_ops = &vb2_dma_contig_memops;
1757 	q->buf_struct_size = sizeof(struct fimc_vid_buffer);
1758 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1759 	q->lock = &fimc->lock;
1760 	q->dev = &fimc->pdev->dev;
1761 
1762 	ret = vb2_queue_init(q);
1763 	if (ret)
1764 		goto err_free_ctx;
1765 
1766 	/* Default format configuration */
1767 	fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_CAM, 0);
1768 	vid_cap->ci_fmt.width = FIMC_DEFAULT_WIDTH;
1769 	vid_cap->ci_fmt.height = FIMC_DEFAULT_HEIGHT;
1770 	vid_cap->ci_fmt.code = fmt->mbus_code;
1771 
1772 	ctx->s_frame.width = FIMC_DEFAULT_WIDTH;
1773 	ctx->s_frame.height = FIMC_DEFAULT_HEIGHT;
1774 	ctx->s_frame.fmt = fmt;
1775 
1776 	fmt = fimc_find_format(NULL, NULL, FMT_FLAGS_WRITEBACK, 0);
1777 	vid_cap->wb_fmt = vid_cap->ci_fmt;
1778 	vid_cap->wb_fmt.code = fmt->mbus_code;
1779 
1780 	vid_cap->vd_pad.flags = MEDIA_PAD_FL_SINK;
1781 	vfd->entity.function = MEDIA_ENT_F_PROC_VIDEO_SCALER;
1782 	ret = media_entity_pads_init(&vfd->entity, 1, &vid_cap->vd_pad);
1783 	if (ret)
1784 		goto err_free_ctx;
1785 
1786 	ret = fimc_ctrls_create(ctx);
1787 	if (ret)
1788 		goto err_me_cleanup;
1789 
1790 	ret = video_register_device(vfd, VFL_TYPE_VIDEO, -1);
1791 	if (ret)
1792 		goto err_ctrl_free;
1793 
1794 	v4l2_info(v4l2_dev, "Registered %s as /dev/%s\n",
1795 		  vfd->name, video_device_node_name(vfd));
1796 
1797 	vfd->ctrl_handler = &ctx->ctrls.handler;
1798 	return 0;
1799 
1800 err_ctrl_free:
1801 	fimc_ctrls_delete(ctx);
1802 err_me_cleanup:
1803 	media_entity_cleanup(&vfd->entity);
1804 err_free_ctx:
1805 	kfree(ctx);
1806 	return ret;
1807 }
1808 
1809 static int fimc_capture_subdev_registered(struct v4l2_subdev *sd)
1810 {
1811 	struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1812 	int ret;
1813 
1814 	if (fimc == NULL)
1815 		return -ENXIO;
1816 
1817 	ret = fimc_register_m2m_device(fimc, sd->v4l2_dev);
1818 	if (ret)
1819 		return ret;
1820 
1821 	fimc->vid_cap.ve.pipe = v4l2_get_subdev_hostdata(sd);
1822 
1823 	ret = fimc_register_capture_device(fimc, sd->v4l2_dev);
1824 	if (ret) {
1825 		fimc_unregister_m2m_device(fimc);
1826 		fimc->vid_cap.ve.pipe = NULL;
1827 	}
1828 
1829 	return ret;
1830 }
1831 
1832 static void fimc_capture_subdev_unregistered(struct v4l2_subdev *sd)
1833 {
1834 	struct fimc_dev *fimc = v4l2_get_subdevdata(sd);
1835 	struct video_device *vdev;
1836 
1837 	if (fimc == NULL)
1838 		return;
1839 
1840 	mutex_lock(&fimc->lock);
1841 
1842 	fimc_unregister_m2m_device(fimc);
1843 	vdev = &fimc->vid_cap.ve.vdev;
1844 
1845 	if (video_is_registered(vdev)) {
1846 		video_unregister_device(vdev);
1847 		media_entity_cleanup(&vdev->entity);
1848 		fimc_ctrls_delete(fimc->vid_cap.ctx);
1849 		fimc->vid_cap.ve.pipe = NULL;
1850 	}
1851 	kfree(fimc->vid_cap.ctx);
1852 	fimc->vid_cap.ctx = NULL;
1853 
1854 	mutex_unlock(&fimc->lock);
1855 }
1856 
1857 static const struct v4l2_subdev_internal_ops fimc_capture_sd_internal_ops = {
1858 	.registered = fimc_capture_subdev_registered,
1859 	.unregistered = fimc_capture_subdev_unregistered,
1860 };
1861 
1862 int fimc_initialize_capture_subdev(struct fimc_dev *fimc)
1863 {
1864 	struct v4l2_subdev *sd = &fimc->vid_cap.subdev;
1865 	int ret;
1866 
1867 	v4l2_subdev_init(sd, &fimc_subdev_ops);
1868 	sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
1869 	snprintf(sd->name, sizeof(sd->name), "FIMC.%d", fimc->id);
1870 
1871 	fimc->vid_cap.sd_pads[FIMC_SD_PAD_SINK_CAM].flags = MEDIA_PAD_FL_SINK;
1872 	fimc->vid_cap.sd_pads[FIMC_SD_PAD_SINK_FIFO].flags = MEDIA_PAD_FL_SINK;
1873 	fimc->vid_cap.sd_pads[FIMC_SD_PAD_SOURCE].flags = MEDIA_PAD_FL_SOURCE;
1874 	ret = media_entity_pads_init(&sd->entity, FIMC_SD_PADS_NUM,
1875 				fimc->vid_cap.sd_pads);
1876 	if (ret)
1877 		return ret;
1878 
1879 	sd->entity.ops = &fimc_sd_media_ops;
1880 	sd->entity.function = MEDIA_ENT_F_PROC_VIDEO_SCALER;
1881 	sd->internal_ops = &fimc_capture_sd_internal_ops;
1882 	v4l2_set_subdevdata(sd, fimc);
1883 	return 0;
1884 }
1885 
1886 void fimc_unregister_capture_subdev(struct fimc_dev *fimc)
1887 {
1888 	struct v4l2_subdev *sd = &fimc->vid_cap.subdev;
1889 
1890 	v4l2_device_unregister_subdev(sd);
1891 	media_entity_cleanup(&sd->entity);
1892 	v4l2_set_subdevdata(sd, NULL);
1893 }
1894