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