• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /netgear-R7000-V1.0.7.12_1.2.5/components/opensource/linux/linux-2.6.36/drivers/media/video/
1/*
2 * V4L2 Driver for SuperH Mobile CEU interface
3 *
4 * Copyright (C) 2008 Magnus Damm
5 *
6 * Based on V4L2 Driver for PXA camera host - "pxa_camera.c",
7 *
8 * Copyright (C) 2006, Sascha Hauer, Pengutronix
9 * Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 */
16
17#include <linux/init.h>
18#include <linux/module.h>
19#include <linux/io.h>
20#include <linux/delay.h>
21#include <linux/dma-mapping.h>
22#include <linux/errno.h>
23#include <linux/fs.h>
24#include <linux/interrupt.h>
25#include <linux/kernel.h>
26#include <linux/mm.h>
27#include <linux/moduleparam.h>
28#include <linux/time.h>
29#include <linux/version.h>
30#include <linux/slab.h>
31#include <linux/device.h>
32#include <linux/platform_device.h>
33#include <linux/videodev2.h>
34#include <linux/pm_runtime.h>
35#include <linux/sched.h>
36
37#include <media/v4l2-common.h>
38#include <media/v4l2-dev.h>
39#include <media/soc_camera.h>
40#include <media/sh_mobile_ceu.h>
41#include <media/videobuf-dma-contig.h>
42#include <media/v4l2-mediabus.h>
43#include <media/soc_mediabus.h>
44
45/* register offsets for sh7722 / sh7723 */
46
47#define CAPSR  0x00 /* Capture start register */
48#define CAPCR  0x04 /* Capture control register */
49#define CAMCR  0x08 /* Capture interface control register */
50#define CMCYR  0x0c /* Capture interface cycle  register */
51#define CAMOR  0x10 /* Capture interface offset register */
52#define CAPWR  0x14 /* Capture interface width register */
53#define CAIFR  0x18 /* Capture interface input format register */
54#define CSTCR  0x20 /* Camera strobe control register (<= sh7722) */
55#define CSECR  0x24 /* Camera strobe emission count register (<= sh7722) */
56#define CRCNTR 0x28 /* CEU register control register */
57#define CRCMPR 0x2c /* CEU register forcible control register */
58#define CFLCR  0x30 /* Capture filter control register */
59#define CFSZR  0x34 /* Capture filter size clip register */
60#define CDWDR  0x38 /* Capture destination width register */
61#define CDAYR  0x3c /* Capture data address Y register */
62#define CDACR  0x40 /* Capture data address C register */
63#define CDBYR  0x44 /* Capture data bottom-field address Y register */
64#define CDBCR  0x48 /* Capture data bottom-field address C register */
65#define CBDSR  0x4c /* Capture bundle destination size register */
66#define CFWCR  0x5c /* Firewall operation control register */
67#define CLFCR  0x60 /* Capture low-pass filter control register */
68#define CDOCR  0x64 /* Capture data output control register */
69#define CDDCR  0x68 /* Capture data complexity level register */
70#define CDDAR  0x6c /* Capture data complexity level address register */
71#define CEIER  0x70 /* Capture event interrupt enable register */
72#define CETCR  0x74 /* Capture event flag clear register */
73#define CSTSR  0x7c /* Capture status register */
74#define CSRTR  0x80 /* Capture software reset register */
75#define CDSSR  0x84 /* Capture data size register */
76#define CDAYR2 0x90 /* Capture data address Y register 2 */
77#define CDACR2 0x94 /* Capture data address C register 2 */
78#define CDBYR2 0x98 /* Capture data bottom-field address Y register 2 */
79#define CDBCR2 0x9c /* Capture data bottom-field address C register 2 */
80
81#undef DEBUG_GEOMETRY
82#ifdef DEBUG_GEOMETRY
83#define dev_geo	dev_info
84#else
85#define dev_geo	dev_dbg
86#endif
87
88/* per video frame buffer */
89struct sh_mobile_ceu_buffer {
90	struct videobuf_buffer vb; /* v4l buffer must be first */
91	enum v4l2_mbus_pixelcode code;
92};
93
94struct sh_mobile_ceu_dev {
95	struct soc_camera_host ici;
96	struct soc_camera_device *icd;
97
98	unsigned int irq;
99	void __iomem *base;
100	unsigned long video_limit;
101
102	/* lock used to protect videobuf */
103	spinlock_t lock;
104	struct list_head capture;
105	struct videobuf_buffer *active;
106
107	struct sh_mobile_ceu_info *pdata;
108
109	u32 cflcr;
110
111	enum v4l2_field field;
112
113	unsigned int image_mode:1;
114	unsigned int is_16bit:1;
115};
116
117struct sh_mobile_ceu_cam {
118	/* CEU offsets within scaled by the CEU camera output */
119	unsigned int ceu_left;
120	unsigned int ceu_top;
121	/* Client output, as seen by the CEU */
122	unsigned int width;
123	unsigned int height;
124	/*
125	 * User window from S_CROP / G_CROP, produced by client cropping and
126	 * scaling, CEU scaling and CEU cropping, mapped back onto the client
127	 * input window
128	 */
129	struct v4l2_rect subrect;
130	/* Camera cropping rectangle */
131	struct v4l2_rect rect;
132	const struct soc_mbus_pixelfmt *extra_fmt;
133	enum v4l2_mbus_pixelcode code;
134};
135
136static unsigned long make_bus_param(struct sh_mobile_ceu_dev *pcdev)
137{
138	unsigned long flags;
139
140	flags = SOCAM_MASTER |
141		SOCAM_PCLK_SAMPLE_RISING |
142		SOCAM_HSYNC_ACTIVE_HIGH |
143		SOCAM_HSYNC_ACTIVE_LOW |
144		SOCAM_VSYNC_ACTIVE_HIGH |
145		SOCAM_VSYNC_ACTIVE_LOW |
146		SOCAM_DATA_ACTIVE_HIGH;
147
148	if (pcdev->pdata->flags & SH_CEU_FLAG_USE_8BIT_BUS)
149		flags |= SOCAM_DATAWIDTH_8;
150
151	if (pcdev->pdata->flags & SH_CEU_FLAG_USE_16BIT_BUS)
152		flags |= SOCAM_DATAWIDTH_16;
153
154	if (flags & SOCAM_DATAWIDTH_MASK)
155		return flags;
156
157	return 0;
158}
159
160static void ceu_write(struct sh_mobile_ceu_dev *priv,
161		      unsigned long reg_offs, u32 data)
162{
163	iowrite32(data, priv->base + reg_offs);
164}
165
166static u32 ceu_read(struct sh_mobile_ceu_dev *priv, unsigned long reg_offs)
167{
168	return ioread32(priv->base + reg_offs);
169}
170
171static int sh_mobile_ceu_soft_reset(struct sh_mobile_ceu_dev *pcdev)
172{
173	int i, success = 0;
174	struct soc_camera_device *icd = pcdev->icd;
175
176	ceu_write(pcdev, CAPSR, 1 << 16); /* reset */
177
178	/* wait CSTSR.CPTON bit */
179	for (i = 0; i < 1000; i++) {
180		if (!(ceu_read(pcdev, CSTSR) & 1)) {
181			success++;
182			break;
183		}
184		udelay(1);
185	}
186
187	/* wait CAPSR.CPKIL bit */
188	for (i = 0; i < 1000; i++) {
189		if (!(ceu_read(pcdev, CAPSR) & (1 << 16))) {
190			success++;
191			break;
192		}
193		udelay(1);
194	}
195
196
197	if (2 != success) {
198		dev_warn(&icd->dev, "soft reset time out\n");
199		return -EIO;
200	}
201
202	return 0;
203}
204
205/*
206 *  Videobuf operations
207 */
208static int sh_mobile_ceu_videobuf_setup(struct videobuf_queue *vq,
209					unsigned int *count,
210					unsigned int *size)
211{
212	struct soc_camera_device *icd = vq->priv_data;
213	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
214	struct sh_mobile_ceu_dev *pcdev = ici->priv;
215	int bytes_per_line = soc_mbus_bytes_per_line(icd->user_width,
216						icd->current_fmt->host_fmt);
217
218	if (bytes_per_line < 0)
219		return bytes_per_line;
220
221	*size = bytes_per_line * icd->user_height;
222
223	if (0 == *count)
224		*count = 2;
225
226	if (pcdev->video_limit) {
227		if (PAGE_ALIGN(*size) * *count > pcdev->video_limit)
228			*count = pcdev->video_limit / PAGE_ALIGN(*size);
229	}
230
231	dev_dbg(icd->dev.parent, "count=%d, size=%d\n", *count, *size);
232
233	return 0;
234}
235
236static void free_buffer(struct videobuf_queue *vq,
237			struct sh_mobile_ceu_buffer *buf)
238{
239	struct soc_camera_device *icd = vq->priv_data;
240	struct device *dev = icd->dev.parent;
241
242	dev_dbg(dev, "%s (vb=0x%p) 0x%08lx %zd\n", __func__,
243		&buf->vb, buf->vb.baddr, buf->vb.bsize);
244
245	if (in_interrupt())
246		BUG();
247
248	videobuf_waiton(&buf->vb, 0, 0);
249	videobuf_dma_contig_free(vq, &buf->vb);
250	dev_dbg(dev, "%s freed\n", __func__);
251	buf->vb.state = VIDEOBUF_NEEDS_INIT;
252}
253
254#define CEU_CETCR_MAGIC 0x0317f313 /* acknowledge magical interrupt sources */
255#define CEU_CETCR_IGRW (1 << 4) /* prohibited register access interrupt bit */
256#define CEU_CEIER_CPEIE (1 << 0) /* one-frame capture end interrupt */
257#define CEU_CEIER_VBP   (1 << 20) /* vbp error */
258#define CEU_CAPCR_CTNCP (1 << 16) /* continuous capture mode (if set) */
259#define CEU_CEIER_MASK (CEU_CEIER_CPEIE | CEU_CEIER_VBP)
260
261
262/*
263 * return value doesn't reflex the success/failure to queue the new buffer,
264 * but rather the status of the previous buffer.
265 */
266static int sh_mobile_ceu_capture(struct sh_mobile_ceu_dev *pcdev)
267{
268	struct soc_camera_device *icd = pcdev->icd;
269	dma_addr_t phys_addr_top, phys_addr_bottom;
270	unsigned long top1, top2;
271	unsigned long bottom1, bottom2;
272	u32 status;
273	int ret = 0;
274
275	/*
276	 * The hardware is _very_ picky about this sequence. Especially
277	 * the CEU_CETCR_MAGIC value. It seems like we need to acknowledge
278	 * several not-so-well documented interrupt sources in CETCR.
279	 */
280	ceu_write(pcdev, CEIER, ceu_read(pcdev, CEIER) & ~CEU_CEIER_MASK);
281	status = ceu_read(pcdev, CETCR);
282	ceu_write(pcdev, CETCR, ~status & CEU_CETCR_MAGIC);
283	ceu_write(pcdev, CEIER, ceu_read(pcdev, CEIER) | CEU_CEIER_MASK);
284	ceu_write(pcdev, CAPCR, ceu_read(pcdev, CAPCR) & ~CEU_CAPCR_CTNCP);
285	ceu_write(pcdev, CETCR, CEU_CETCR_MAGIC ^ CEU_CETCR_IGRW);
286
287	/*
288	 * When a VBP interrupt occurs, a capture end interrupt does not occur
289	 * and the image of that frame is not captured correctly. So, soft reset
290	 * is needed here.
291	 */
292	if (status & CEU_CEIER_VBP) {
293		sh_mobile_ceu_soft_reset(pcdev);
294		ret = -EIO;
295	}
296
297	if (!pcdev->active)
298		return ret;
299
300	if (V4L2_FIELD_INTERLACED_BT == pcdev->field) {
301		top1	= CDBYR;
302		top2	= CDBCR;
303		bottom1	= CDAYR;
304		bottom2	= CDACR;
305	} else {
306		top1	= CDAYR;
307		top2	= CDACR;
308		bottom1	= CDBYR;
309		bottom2	= CDBCR;
310	}
311
312	phys_addr_top = videobuf_to_dma_contig(pcdev->active);
313	ceu_write(pcdev, top1, phys_addr_top);
314	if (V4L2_FIELD_NONE != pcdev->field) {
315		phys_addr_bottom = phys_addr_top + icd->user_width;
316		ceu_write(pcdev, bottom1, phys_addr_bottom);
317	}
318
319	switch (icd->current_fmt->host_fmt->fourcc) {
320	case V4L2_PIX_FMT_NV12:
321	case V4L2_PIX_FMT_NV21:
322	case V4L2_PIX_FMT_NV16:
323	case V4L2_PIX_FMT_NV61:
324		phys_addr_top += icd->user_width *
325			icd->user_height;
326		ceu_write(pcdev, top2, phys_addr_top);
327		if (V4L2_FIELD_NONE != pcdev->field) {
328			phys_addr_bottom = phys_addr_top + icd->user_width;
329			ceu_write(pcdev, bottom2, phys_addr_bottom);
330		}
331	}
332
333	pcdev->active->state = VIDEOBUF_ACTIVE;
334	ceu_write(pcdev, CAPSR, 0x1); /* start capture */
335
336	return ret;
337}
338
339static int sh_mobile_ceu_videobuf_prepare(struct videobuf_queue *vq,
340					  struct videobuf_buffer *vb,
341					  enum v4l2_field field)
342{
343	struct soc_camera_device *icd = vq->priv_data;
344	struct sh_mobile_ceu_buffer *buf;
345	int bytes_per_line = soc_mbus_bytes_per_line(icd->user_width,
346						icd->current_fmt->host_fmt);
347	int ret;
348
349	if (bytes_per_line < 0)
350		return bytes_per_line;
351
352	buf = container_of(vb, struct sh_mobile_ceu_buffer, vb);
353
354	dev_dbg(icd->dev.parent, "%s (vb=0x%p) 0x%08lx %zd\n", __func__,
355		vb, vb->baddr, vb->bsize);
356
357	/* Added list head initialization on alloc */
358	WARN_ON(!list_empty(&vb->queue));
359
360#ifdef DEBUG
361	/*
362	 * This can be useful if you want to see if we actually fill
363	 * the buffer with something
364	 */
365	memset((void *)vb->baddr, 0xaa, vb->bsize);
366#endif
367
368	BUG_ON(NULL == icd->current_fmt);
369
370	if (buf->code	!= icd->current_fmt->code ||
371	    vb->width	!= icd->user_width ||
372	    vb->height	!= icd->user_height ||
373	    vb->field	!= field) {
374		buf->code	= icd->current_fmt->code;
375		vb->width	= icd->user_width;
376		vb->height	= icd->user_height;
377		vb->field	= field;
378		vb->state	= VIDEOBUF_NEEDS_INIT;
379	}
380
381	vb->size = vb->height * bytes_per_line;
382	if (0 != vb->baddr && vb->bsize < vb->size) {
383		ret = -EINVAL;
384		goto out;
385	}
386
387	if (vb->state == VIDEOBUF_NEEDS_INIT) {
388		ret = videobuf_iolock(vq, vb, NULL);
389		if (ret)
390			goto fail;
391		vb->state = VIDEOBUF_PREPARED;
392	}
393
394	return 0;
395fail:
396	free_buffer(vq, buf);
397out:
398	return ret;
399}
400
401/* Called under spinlock_irqsave(&pcdev->lock, ...) */
402static void sh_mobile_ceu_videobuf_queue(struct videobuf_queue *vq,
403					 struct videobuf_buffer *vb)
404{
405	struct soc_camera_device *icd = vq->priv_data;
406	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
407	struct sh_mobile_ceu_dev *pcdev = ici->priv;
408
409	dev_dbg(icd->dev.parent, "%s (vb=0x%p) 0x%08lx %zd\n", __func__,
410		vb, vb->baddr, vb->bsize);
411
412	vb->state = VIDEOBUF_QUEUED;
413	list_add_tail(&vb->queue, &pcdev->capture);
414
415	if (!pcdev->active) {
416		/*
417		 * Because there were no active buffer at this moment,
418		 * we are not interested in the return value of
419		 * sh_mobile_ceu_capture here.
420		 */
421		pcdev->active = vb;
422		sh_mobile_ceu_capture(pcdev);
423	}
424}
425
426static void sh_mobile_ceu_videobuf_release(struct videobuf_queue *vq,
427					   struct videobuf_buffer *vb)
428{
429	struct soc_camera_device *icd = vq->priv_data;
430	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
431	struct sh_mobile_ceu_dev *pcdev = ici->priv;
432	unsigned long flags;
433
434	spin_lock_irqsave(&pcdev->lock, flags);
435
436	if (pcdev->active == vb) {
437		/* disable capture (release DMA buffer), reset */
438		ceu_write(pcdev, CAPSR, 1 << 16);
439		pcdev->active = NULL;
440	}
441
442	if ((vb->state == VIDEOBUF_ACTIVE || vb->state == VIDEOBUF_QUEUED) &&
443	    !list_empty(&vb->queue)) {
444		vb->state = VIDEOBUF_ERROR;
445		list_del_init(&vb->queue);
446	}
447
448	spin_unlock_irqrestore(&pcdev->lock, flags);
449
450	free_buffer(vq, container_of(vb, struct sh_mobile_ceu_buffer, vb));
451}
452
453static struct videobuf_queue_ops sh_mobile_ceu_videobuf_ops = {
454	.buf_setup      = sh_mobile_ceu_videobuf_setup,
455	.buf_prepare    = sh_mobile_ceu_videobuf_prepare,
456	.buf_queue      = sh_mobile_ceu_videobuf_queue,
457	.buf_release    = sh_mobile_ceu_videobuf_release,
458};
459
460static irqreturn_t sh_mobile_ceu_irq(int irq, void *data)
461{
462	struct sh_mobile_ceu_dev *pcdev = data;
463	struct videobuf_buffer *vb;
464	unsigned long flags;
465
466	spin_lock_irqsave(&pcdev->lock, flags);
467
468	vb = pcdev->active;
469	if (!vb)
470		/* Stale interrupt from a released buffer */
471		goto out;
472
473	list_del_init(&vb->queue);
474
475	if (!list_empty(&pcdev->capture))
476		pcdev->active = list_entry(pcdev->capture.next,
477					   struct videobuf_buffer, queue);
478	else
479		pcdev->active = NULL;
480
481	vb->state = (sh_mobile_ceu_capture(pcdev) < 0) ?
482		VIDEOBUF_ERROR : VIDEOBUF_DONE;
483	do_gettimeofday(&vb->ts);
484	vb->field_count++;
485	wake_up(&vb->done);
486
487out:
488	spin_unlock_irqrestore(&pcdev->lock, flags);
489
490	return IRQ_HANDLED;
491}
492
493/* Called with .video_lock held */
494static int sh_mobile_ceu_add_device(struct soc_camera_device *icd)
495{
496	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
497	struct sh_mobile_ceu_dev *pcdev = ici->priv;
498	int ret;
499
500	if (pcdev->icd)
501		return -EBUSY;
502
503	dev_info(icd->dev.parent,
504		 "SuperH Mobile CEU driver attached to camera %d\n",
505		 icd->devnum);
506
507	pm_runtime_get_sync(ici->v4l2_dev.dev);
508
509	ret = sh_mobile_ceu_soft_reset(pcdev);
510	if (!ret)
511		pcdev->icd = icd;
512
513	return ret;
514}
515
516/* Called with .video_lock held */
517static void sh_mobile_ceu_remove_device(struct soc_camera_device *icd)
518{
519	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
520	struct sh_mobile_ceu_dev *pcdev = ici->priv;
521	unsigned long flags;
522
523	BUG_ON(icd != pcdev->icd);
524
525	/* disable capture, disable interrupts */
526	ceu_write(pcdev, CEIER, 0);
527	sh_mobile_ceu_soft_reset(pcdev);
528
529	/* make sure active buffer is canceled */
530	spin_lock_irqsave(&pcdev->lock, flags);
531	if (pcdev->active) {
532		list_del(&pcdev->active->queue);
533		pcdev->active->state = VIDEOBUF_ERROR;
534		wake_up_all(&pcdev->active->done);
535		pcdev->active = NULL;
536	}
537	spin_unlock_irqrestore(&pcdev->lock, flags);
538
539	pm_runtime_put_sync(ici->v4l2_dev.dev);
540
541	dev_info(icd->dev.parent,
542		 "SuperH Mobile CEU driver detached from camera %d\n",
543		 icd->devnum);
544
545	pcdev->icd = NULL;
546}
547
548/*
549 * See chapter 29.4.12 "Capture Filter Control Register (CFLCR)"
550 * in SH7722 Hardware Manual
551 */
552static unsigned int size_dst(unsigned int src, unsigned int scale)
553{
554	unsigned int mant_pre = scale >> 12;
555	if (!src || !scale)
556		return src;
557	return ((mant_pre + 2 * (src - 1)) / (2 * mant_pre) - 1) *
558		mant_pre * 4096 / scale + 1;
559}
560
561static u16 calc_scale(unsigned int src, unsigned int *dst)
562{
563	u16 scale;
564
565	if (src == *dst)
566		return 0;
567
568	scale = (src * 4096 / *dst) & ~7;
569
570	while (scale > 4096 && size_dst(src, scale) < *dst)
571		scale -= 8;
572
573	*dst = size_dst(src, scale);
574
575	return scale;
576}
577
578/* rect is guaranteed to not exceed the scaled camera rectangle */
579static void sh_mobile_ceu_set_rect(struct soc_camera_device *icd)
580{
581	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
582	struct sh_mobile_ceu_cam *cam = icd->host_priv;
583	struct sh_mobile_ceu_dev *pcdev = ici->priv;
584	unsigned int height, width, cdwdr_width, in_width, in_height;
585	unsigned int left_offset, top_offset;
586	u32 camor;
587
588	dev_geo(icd->dev.parent, "Crop %ux%u@%u:%u\n",
589		icd->user_width, icd->user_height, cam->ceu_left, cam->ceu_top);
590
591	left_offset	= cam->ceu_left;
592	top_offset	= cam->ceu_top;
593
594	/* CEU cropping (CFSZR) is applied _after_ the scaling filter (CFLCR) */
595	if (pcdev->image_mode) {
596		in_width = cam->width;
597		if (!pcdev->is_16bit) {
598			in_width *= 2;
599			left_offset *= 2;
600		}
601		width = icd->user_width;
602		cdwdr_width = icd->user_width;
603	} else {
604		int bytes_per_line = soc_mbus_bytes_per_line(icd->user_width,
605						icd->current_fmt->host_fmt);
606		unsigned int w_factor;
607
608		width = icd->user_width;
609
610		switch (icd->current_fmt->host_fmt->packing) {
611		case SOC_MBUS_PACKING_2X8_PADHI:
612			w_factor = 2;
613			break;
614		default:
615			w_factor = 1;
616		}
617
618		in_width = cam->width * w_factor;
619		left_offset = left_offset * w_factor;
620
621		if (bytes_per_line < 0)
622			cdwdr_width = icd->user_width;
623		else
624			cdwdr_width = bytes_per_line;
625	}
626
627	height = icd->user_height;
628	in_height = cam->height;
629	if (V4L2_FIELD_NONE != pcdev->field) {
630		height /= 2;
631		in_height /= 2;
632		top_offset /= 2;
633		cdwdr_width *= 2;
634	}
635
636	/* CSI2 special configuration */
637	if (pcdev->pdata->csi2_dev) {
638		in_width = ((in_width - 2) * 2);
639		left_offset *= 2;
640	}
641
642	/* Set CAMOR, CAPWR, CFSZR, take care of CDWDR */
643	camor = left_offset | (top_offset << 16);
644
645	dev_geo(icd->dev.parent,
646		"CAMOR 0x%x, CAPWR 0x%x, CFSZR 0x%x, CDWDR 0x%x\n", camor,
647		(in_height << 16) | in_width, (height << 16) | width,
648		cdwdr_width);
649
650	ceu_write(pcdev, CAMOR, camor);
651	ceu_write(pcdev, CAPWR, (in_height << 16) | in_width);
652	ceu_write(pcdev, CFSZR, (height << 16) | width);
653	ceu_write(pcdev, CDWDR, cdwdr_width);
654}
655
656static u32 capture_save_reset(struct sh_mobile_ceu_dev *pcdev)
657{
658	u32 capsr = ceu_read(pcdev, CAPSR);
659	ceu_write(pcdev, CAPSR, 1 << 16); /* reset, stop capture */
660	return capsr;
661}
662
663static void capture_restore(struct sh_mobile_ceu_dev *pcdev, u32 capsr)
664{
665	unsigned long timeout = jiffies + 10 * HZ;
666
667	/*
668	 * Wait until the end of the current frame. It can take a long time,
669	 * but if it has been aborted by a CAPSR reset, it shoule exit sooner.
670	 */
671	while ((ceu_read(pcdev, CSTSR) & 1) && time_before(jiffies, timeout))
672		msleep(1);
673
674	if (time_after(jiffies, timeout)) {
675		dev_err(pcdev->ici.v4l2_dev.dev,
676			"Timeout waiting for frame end! Interface problem?\n");
677		return;
678	}
679
680	/* Wait until reset clears, this shall not hang... */
681	while (ceu_read(pcdev, CAPSR) & (1 << 16))
682		udelay(10);
683
684	/* Anything to restore? */
685	if (capsr & ~(1 << 16))
686		ceu_write(pcdev, CAPSR, capsr);
687}
688
689static int sh_mobile_ceu_set_bus_param(struct soc_camera_device *icd,
690				       __u32 pixfmt)
691{
692	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
693	struct sh_mobile_ceu_dev *pcdev = ici->priv;
694	int ret;
695	unsigned long camera_flags, common_flags, value;
696	int yuv_lineskip;
697	struct sh_mobile_ceu_cam *cam = icd->host_priv;
698	u32 capsr = capture_save_reset(pcdev);
699
700	camera_flags = icd->ops->query_bus_param(icd);
701	common_flags = soc_camera_bus_param_compatible(camera_flags,
702						       make_bus_param(pcdev));
703	if (!common_flags)
704		return -EINVAL;
705
706	/* Make choises, based on platform preferences */
707	if ((common_flags & SOCAM_HSYNC_ACTIVE_HIGH) &&
708	    (common_flags & SOCAM_HSYNC_ACTIVE_LOW)) {
709		if (pcdev->pdata->flags & SH_CEU_FLAG_HSYNC_LOW)
710			common_flags &= ~SOCAM_HSYNC_ACTIVE_HIGH;
711		else
712			common_flags &= ~SOCAM_HSYNC_ACTIVE_LOW;
713	}
714
715	if ((common_flags & SOCAM_VSYNC_ACTIVE_HIGH) &&
716	    (common_flags & SOCAM_VSYNC_ACTIVE_LOW)) {
717		if (pcdev->pdata->flags & SH_CEU_FLAG_VSYNC_LOW)
718			common_flags &= ~SOCAM_VSYNC_ACTIVE_HIGH;
719		else
720			common_flags &= ~SOCAM_VSYNC_ACTIVE_LOW;
721	}
722
723	ret = icd->ops->set_bus_param(icd, common_flags);
724	if (ret < 0)
725		return ret;
726
727	switch (common_flags & SOCAM_DATAWIDTH_MASK) {
728	case SOCAM_DATAWIDTH_8:
729		pcdev->is_16bit = 0;
730		break;
731	case SOCAM_DATAWIDTH_16:
732		pcdev->is_16bit = 1;
733		break;
734	default:
735		return -EINVAL;
736	}
737
738	ceu_write(pcdev, CRCNTR, 0);
739	ceu_write(pcdev, CRCMPR, 0);
740
741	value = 0x00000010; /* data fetch by default */
742	yuv_lineskip = 0;
743
744	switch (icd->current_fmt->host_fmt->fourcc) {
745	case V4L2_PIX_FMT_NV12:
746	case V4L2_PIX_FMT_NV21:
747		yuv_lineskip = 1; /* skip for NV12/21, no skip for NV16/61 */
748		/* fall-through */
749	case V4L2_PIX_FMT_NV16:
750	case V4L2_PIX_FMT_NV61:
751		switch (cam->code) {
752		case V4L2_MBUS_FMT_UYVY8_2X8:
753			value = 0x00000000; /* Cb0, Y0, Cr0, Y1 */
754			break;
755		case V4L2_MBUS_FMT_VYUY8_2X8:
756			value = 0x00000100; /* Cr0, Y0, Cb0, Y1 */
757			break;
758		case V4L2_MBUS_FMT_YUYV8_2X8:
759			value = 0x00000200; /* Y0, Cb0, Y1, Cr0 */
760			break;
761		case V4L2_MBUS_FMT_YVYU8_2X8:
762			value = 0x00000300; /* Y0, Cr0, Y1, Cb0 */
763			break;
764		default:
765			BUG();
766		}
767	}
768
769	if (icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_NV21 ||
770	    icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_NV61)
771		value ^= 0x00000100; /* swap U, V to change from NV1x->NVx1 */
772
773	value |= common_flags & SOCAM_VSYNC_ACTIVE_LOW ? 1 << 1 : 0;
774	value |= common_flags & SOCAM_HSYNC_ACTIVE_LOW ? 1 << 0 : 0;
775	value |= pcdev->is_16bit ? 1 << 12 : 0;
776
777	/* CSI2 mode */
778	if (pcdev->pdata->csi2_dev)
779		value |= 3 << 12;
780
781	ceu_write(pcdev, CAMCR, value);
782
783	ceu_write(pcdev, CAPCR, 0x00300000);
784
785	switch (pcdev->field) {
786	case V4L2_FIELD_INTERLACED_TB:
787		value = 0x101;
788		break;
789	case V4L2_FIELD_INTERLACED_BT:
790		value = 0x102;
791		break;
792	default:
793		value = 0;
794		break;
795	}
796	ceu_write(pcdev, CAIFR, value);
797
798	sh_mobile_ceu_set_rect(icd);
799	mdelay(1);
800
801	dev_geo(icd->dev.parent, "CFLCR 0x%x\n", pcdev->cflcr);
802	ceu_write(pcdev, CFLCR, pcdev->cflcr);
803
804	/*
805	 * A few words about byte order (observed in Big Endian mode)
806	 *
807	 * In data fetch mode bytes are received in chunks of 8 bytes.
808	 * D0, D1, D2, D3, D4, D5, D6, D7 (D0 received first)
809	 *
810	 * The data is however by default written to memory in reverse order:
811	 * D7, D6, D5, D4, D3, D2, D1, D0 (D7 written to lowest byte)
812	 *
813	 * The lowest three bits of CDOCR allows us to do swapping,
814	 * using 7 we swap the data bytes to match the incoming order:
815	 * D0, D1, D2, D3, D4, D5, D6, D7
816	 */
817	value = 0x00000017;
818	if (yuv_lineskip)
819		value &= ~0x00000010; /* convert 4:2:2 -> 4:2:0 */
820
821	ceu_write(pcdev, CDOCR, value);
822	ceu_write(pcdev, CFWCR, 0); /* keep "datafetch firewall" disabled */
823
824	dev_dbg(icd->dev.parent, "S_FMT successful for %c%c%c%c %ux%u\n",
825		pixfmt & 0xff, (pixfmt >> 8) & 0xff,
826		(pixfmt >> 16) & 0xff, (pixfmt >> 24) & 0xff,
827		icd->user_width, icd->user_height);
828
829	capture_restore(pcdev, capsr);
830
831	/* not in bundle mode: skip CBDSR, CDAYR2, CDACR2, CDBYR2, CDBCR2 */
832	return 0;
833}
834
835static int sh_mobile_ceu_try_bus_param(struct soc_camera_device *icd,
836				       unsigned char buswidth)
837{
838	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
839	struct sh_mobile_ceu_dev *pcdev = ici->priv;
840	unsigned long camera_flags, common_flags;
841
842	camera_flags = icd->ops->query_bus_param(icd);
843	common_flags = soc_camera_bus_param_compatible(camera_flags,
844						       make_bus_param(pcdev));
845	if (!common_flags || buswidth > 16 ||
846	    (buswidth > 8 && !(common_flags & SOCAM_DATAWIDTH_16)))
847		return -EINVAL;
848
849	return 0;
850}
851
852static const struct soc_mbus_pixelfmt sh_mobile_ceu_formats[] = {
853	{
854		.fourcc			= V4L2_PIX_FMT_NV12,
855		.name			= "NV12",
856		.bits_per_sample	= 12,
857		.packing		= SOC_MBUS_PACKING_NONE,
858		.order			= SOC_MBUS_ORDER_LE,
859	}, {
860		.fourcc			= V4L2_PIX_FMT_NV21,
861		.name			= "NV21",
862		.bits_per_sample	= 12,
863		.packing		= SOC_MBUS_PACKING_NONE,
864		.order			= SOC_MBUS_ORDER_LE,
865	}, {
866		.fourcc			= V4L2_PIX_FMT_NV16,
867		.name			= "NV16",
868		.bits_per_sample	= 16,
869		.packing		= SOC_MBUS_PACKING_NONE,
870		.order			= SOC_MBUS_ORDER_LE,
871	}, {
872		.fourcc			= V4L2_PIX_FMT_NV61,
873		.name			= "NV61",
874		.bits_per_sample	= 16,
875		.packing		= SOC_MBUS_PACKING_NONE,
876		.order			= SOC_MBUS_ORDER_LE,
877	},
878};
879
880/* This will be corrected as we get more formats */
881static bool sh_mobile_ceu_packing_supported(const struct soc_mbus_pixelfmt *fmt)
882{
883	return	fmt->packing == SOC_MBUS_PACKING_NONE ||
884		(fmt->bits_per_sample == 8 &&
885		 fmt->packing == SOC_MBUS_PACKING_2X8_PADHI) ||
886		(fmt->bits_per_sample > 8 &&
887		 fmt->packing == SOC_MBUS_PACKING_EXTEND16);
888}
889
890static int client_g_rect(struct v4l2_subdev *sd, struct v4l2_rect *rect);
891
892static int sh_mobile_ceu_get_formats(struct soc_camera_device *icd, unsigned int idx,
893				     struct soc_camera_format_xlate *xlate)
894{
895	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
896	struct device *dev = icd->dev.parent;
897	struct soc_camera_host *ici = to_soc_camera_host(dev);
898	struct sh_mobile_ceu_dev *pcdev = ici->priv;
899	int ret, k, n;
900	int formats = 0;
901	struct sh_mobile_ceu_cam *cam;
902	enum v4l2_mbus_pixelcode code;
903	const struct soc_mbus_pixelfmt *fmt;
904
905	ret = v4l2_subdev_call(sd, video, enum_mbus_fmt, idx, &code);
906	if (ret < 0)
907		/* No more formats */
908		return 0;
909
910	fmt = soc_mbus_get_fmtdesc(code);
911	if (!fmt) {
912		dev_err(dev, "Invalid format code #%u: %d\n", idx, code);
913		return -EINVAL;
914	}
915
916	if (!pcdev->pdata->csi2_dev) {
917		ret = sh_mobile_ceu_try_bus_param(icd, fmt->bits_per_sample);
918		if (ret < 0)
919			return 0;
920	}
921
922	if (!icd->host_priv) {
923		struct v4l2_mbus_framefmt mf;
924		struct v4l2_rect rect;
925		int shift = 0;
926
927
928		/* Cache current client geometry */
929		ret = client_g_rect(sd, &rect);
930		if (ret < 0)
931			return ret;
932
933		/* First time */
934		ret = v4l2_subdev_call(sd, video, g_mbus_fmt, &mf);
935		if (ret < 0)
936			return ret;
937
938		while ((mf.width > 2560 || mf.height > 1920) && shift < 4) {
939			/* Try 2560x1920, 1280x960, 640x480, 320x240 */
940			mf.width	= 2560 >> shift;
941			mf.height	= 1920 >> shift;
942			ret = v4l2_device_call_until_err(sd->v4l2_dev, 0, video,
943							 s_mbus_fmt, &mf);
944			if (ret < 0)
945				return ret;
946			shift++;
947		}
948
949		if (shift == 4) {
950			dev_err(dev, "Failed to configure the client below %ux%x\n",
951				mf.width, mf.height);
952			return -EIO;
953		}
954
955		dev_geo(dev, "camera fmt %ux%u\n", mf.width, mf.height);
956
957		cam = kzalloc(sizeof(*cam), GFP_KERNEL);
958		if (!cam)
959			return -ENOMEM;
960
961		/* We are called with current camera crop, initialise subrect with it */
962		cam->rect	= rect;
963		cam->subrect	= rect;
964
965		cam->width	= mf.width;
966		cam->height	= mf.height;
967
968		cam->width	= mf.width;
969		cam->height	= mf.height;
970
971		icd->host_priv = cam;
972	} else {
973		cam = icd->host_priv;
974	}
975
976	/* Beginning of a pass */
977	if (!idx)
978		cam->extra_fmt = NULL;
979
980	switch (code) {
981	case V4L2_MBUS_FMT_UYVY8_2X8:
982	case V4L2_MBUS_FMT_VYUY8_2X8:
983	case V4L2_MBUS_FMT_YUYV8_2X8:
984	case V4L2_MBUS_FMT_YVYU8_2X8:
985		if (cam->extra_fmt)
986			break;
987
988		/*
989		 * Our case is simple so far: for any of the above four camera
990		 * formats we add all our four synthesized NV* formats, so,
991		 * just marking the device with a single flag suffices. If
992		 * the format generation rules are more complex, you would have
993		 * to actually hang your already added / counted formats onto
994		 * the host_priv pointer and check whether the format you're
995		 * going to add now is already there.
996		 */
997		cam->extra_fmt = sh_mobile_ceu_formats;
998
999		n = ARRAY_SIZE(sh_mobile_ceu_formats);
1000		formats += n;
1001		for (k = 0; xlate && k < n; k++) {
1002			xlate->host_fmt	= &sh_mobile_ceu_formats[k];
1003			xlate->code	= code;
1004			xlate++;
1005			dev_dbg(dev, "Providing format %s using code %d\n",
1006				sh_mobile_ceu_formats[k].name, code);
1007		}
1008		break;
1009	default:
1010		if (!sh_mobile_ceu_packing_supported(fmt))
1011			return 0;
1012	}
1013
1014	/* Generic pass-through */
1015	formats++;
1016	if (xlate) {
1017		xlate->host_fmt	= fmt;
1018		xlate->code	= code;
1019		xlate++;
1020		dev_dbg(dev, "Providing format %s in pass-through mode\n",
1021			fmt->name);
1022	}
1023
1024	return formats;
1025}
1026
1027static void sh_mobile_ceu_put_formats(struct soc_camera_device *icd)
1028{
1029	kfree(icd->host_priv);
1030	icd->host_priv = NULL;
1031}
1032
1033/* Check if any dimension of r1 is smaller than respective one of r2 */
1034static bool is_smaller(struct v4l2_rect *r1, struct v4l2_rect *r2)
1035{
1036	return r1->width < r2->width || r1->height < r2->height;
1037}
1038
1039/* Check if r1 fails to cover r2 */
1040static bool is_inside(struct v4l2_rect *r1, struct v4l2_rect *r2)
1041{
1042	return r1->left > r2->left || r1->top > r2->top ||
1043		r1->left + r1->width < r2->left + r2->width ||
1044		r1->top + r1->height < r2->top + r2->height;
1045}
1046
1047static unsigned int scale_down(unsigned int size, unsigned int scale)
1048{
1049	return (size * 4096 + scale / 2) / scale;
1050}
1051
1052static unsigned int calc_generic_scale(unsigned int input, unsigned int output)
1053{
1054	return (input * 4096 + output / 2) / output;
1055}
1056
1057/* Get and store current client crop */
1058static int client_g_rect(struct v4l2_subdev *sd, struct v4l2_rect *rect)
1059{
1060	struct v4l2_crop crop;
1061	struct v4l2_cropcap cap;
1062	int ret;
1063
1064	crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1065
1066	ret = v4l2_subdev_call(sd, video, g_crop, &crop);
1067	if (!ret) {
1068		*rect = crop.c;
1069		return ret;
1070	}
1071
1072	/* Camera driver doesn't support .g_crop(), assume default rectangle */
1073	cap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1074
1075	ret = v4l2_subdev_call(sd, video, cropcap, &cap);
1076	if (!ret)
1077		*rect = cap.defrect;
1078
1079	return ret;
1080}
1081
1082/* Client crop has changed, update our sub-rectangle to remain within the area */
1083static void update_subrect(struct sh_mobile_ceu_cam *cam)
1084{
1085	struct v4l2_rect *rect = &cam->rect, *subrect = &cam->subrect;
1086
1087	if (rect->width < subrect->width)
1088		subrect->width = rect->width;
1089
1090	if (rect->height < subrect->height)
1091		subrect->height = rect->height;
1092
1093	if (rect->left > subrect->left)
1094		subrect->left = rect->left;
1095	else if (rect->left + rect->width >
1096		 subrect->left + subrect->width)
1097		subrect->left = rect->left + rect->width -
1098			subrect->width;
1099
1100	if (rect->top > subrect->top)
1101		subrect->top = rect->top;
1102	else if (rect->top + rect->height >
1103		 subrect->top + subrect->height)
1104		subrect->top = rect->top + rect->height -
1105			subrect->height;
1106}
1107
1108/*
1109 * The common for both scaling and cropping iterative approach is:
1110 * 1. try if the client can produce exactly what requested by the user
1111 * 2. if (1) failed, try to double the client image until we get one big enough
1112 * 3. if (2) failed, try to request the maximum image
1113 */
1114static int client_s_crop(struct soc_camera_device *icd, struct v4l2_crop *crop,
1115			 struct v4l2_crop *cam_crop)
1116{
1117	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
1118	struct v4l2_rect *rect = &crop->c, *cam_rect = &cam_crop->c;
1119	struct device *dev = sd->v4l2_dev->dev;
1120	struct sh_mobile_ceu_cam *cam = icd->host_priv;
1121	struct v4l2_cropcap cap;
1122	int ret;
1123	unsigned int width, height;
1124
1125	v4l2_subdev_call(sd, video, s_crop, crop);
1126	ret = client_g_rect(sd, cam_rect);
1127	if (ret < 0)
1128		return ret;
1129
1130	/*
1131	 * Now cam_crop contains the current camera input rectangle, and it must
1132	 * be within camera cropcap bounds
1133	 */
1134	if (!memcmp(rect, cam_rect, sizeof(*rect))) {
1135		/* Even if camera S_CROP failed, but camera rectangle matches */
1136		dev_dbg(dev, "Camera S_CROP successful for %dx%d@%d:%d\n",
1137			rect->width, rect->height, rect->left, rect->top);
1138		cam->rect = *cam_rect;
1139		return 0;
1140	}
1141
1142	/* Try to fix cropping, that camera hasn't managed to set */
1143	dev_geo(dev, "Fix camera S_CROP for %dx%d@%d:%d to %dx%d@%d:%d\n",
1144		cam_rect->width, cam_rect->height,
1145		cam_rect->left, cam_rect->top,
1146		rect->width, rect->height, rect->left, rect->top);
1147
1148	/* We need sensor maximum rectangle */
1149	ret = v4l2_subdev_call(sd, video, cropcap, &cap);
1150	if (ret < 0)
1151		return ret;
1152
1153	/* Put user requested rectangle within sensor bounds */
1154	soc_camera_limit_side(&rect->left, &rect->width, cap.bounds.left, 2,
1155			      cap.bounds.width);
1156	soc_camera_limit_side(&rect->top, &rect->height, cap.bounds.top, 4,
1157			      cap.bounds.height);
1158
1159	/*
1160	 * Popular special case - some cameras can only handle fixed sizes like
1161	 * QVGA, VGA,... Take care to avoid infinite loop.
1162	 */
1163	width = max(cam_rect->width, 2);
1164	height = max(cam_rect->height, 2);
1165
1166	/*
1167	 * Loop as long as sensor is not covering the requested rectangle and
1168	 * is still within its bounds
1169	 */
1170	while (!ret && (is_smaller(cam_rect, rect) ||
1171			is_inside(cam_rect, rect)) &&
1172	       (cap.bounds.width > width || cap.bounds.height > height)) {
1173
1174		width *= 2;
1175		height *= 2;
1176
1177		cam_rect->width = width;
1178		cam_rect->height = height;
1179
1180		/*
1181		 * We do not know what capabilities the camera has to set up
1182		 * left and top borders. We could try to be smarter in iterating
1183		 * them, e.g., if camera current left is to the right of the
1184		 * target left, set it to the middle point between the current
1185		 * left and minimum left. But that would add too much
1186		 * complexity: we would have to iterate each border separately.
1187		 * Instead we just drop to the left and top bounds.
1188		 */
1189		if (cam_rect->left > rect->left)
1190			cam_rect->left = cap.bounds.left;
1191
1192		if (cam_rect->left + cam_rect->width < rect->left + rect->width)
1193			cam_rect->width = rect->left + rect->width -
1194				cam_rect->left;
1195
1196		if (cam_rect->top > rect->top)
1197			cam_rect->top = cap.bounds.top;
1198
1199		if (cam_rect->top + cam_rect->height < rect->top + rect->height)
1200			cam_rect->height = rect->top + rect->height -
1201				cam_rect->top;
1202
1203		v4l2_subdev_call(sd, video, s_crop, cam_crop);
1204		ret = client_g_rect(sd, cam_rect);
1205		dev_geo(dev, "Camera S_CROP %d for %dx%d@%d:%d\n", ret,
1206			cam_rect->width, cam_rect->height,
1207			cam_rect->left, cam_rect->top);
1208	}
1209
1210	/* S_CROP must not modify the rectangle */
1211	if (is_smaller(cam_rect, rect) || is_inside(cam_rect, rect)) {
1212		/*
1213		 * The camera failed to configure a suitable cropping,
1214		 * we cannot use the current rectangle, set to max
1215		 */
1216		*cam_rect = cap.bounds;
1217		v4l2_subdev_call(sd, video, s_crop, cam_crop);
1218		ret = client_g_rect(sd, cam_rect);
1219		dev_geo(dev, "Camera S_CROP %d for max %dx%d@%d:%d\n", ret,
1220			cam_rect->width, cam_rect->height,
1221			cam_rect->left, cam_rect->top);
1222	}
1223
1224	if (!ret) {
1225		cam->rect = *cam_rect;
1226		update_subrect(cam);
1227	}
1228
1229	return ret;
1230}
1231
1232/* Iterative s_mbus_fmt, also updates cached client crop on success */
1233static int client_s_fmt(struct soc_camera_device *icd,
1234			struct v4l2_mbus_framefmt *mf, bool ceu_can_scale)
1235{
1236	struct sh_mobile_ceu_cam *cam = icd->host_priv;
1237	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
1238	struct device *dev = icd->dev.parent;
1239	unsigned int width = mf->width, height = mf->height, tmp_w, tmp_h;
1240	unsigned int max_width, max_height;
1241	struct v4l2_cropcap cap;
1242	int ret;
1243
1244	ret = v4l2_device_call_until_err(sd->v4l2_dev, 0, video,
1245					 s_mbus_fmt, mf);
1246	if (ret < 0)
1247		return ret;
1248
1249	dev_geo(dev, "camera scaled to %ux%u\n", mf->width, mf->height);
1250
1251	if ((width == mf->width && height == mf->height) || !ceu_can_scale)
1252		goto update_cache;
1253
1254	cap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1255
1256	ret = v4l2_subdev_call(sd, video, cropcap, &cap);
1257	if (ret < 0)
1258		return ret;
1259
1260	max_width = min(cap.bounds.width, 2560);
1261	max_height = min(cap.bounds.height, 1920);
1262
1263	/* Camera set a format, but geometry is not precise, try to improve */
1264	tmp_w = mf->width;
1265	tmp_h = mf->height;
1266
1267	/* width <= max_width && height <= max_height - guaranteed by try_fmt */
1268	while ((width > tmp_w || height > tmp_h) &&
1269	       tmp_w < max_width && tmp_h < max_height) {
1270		tmp_w = min(2 * tmp_w, max_width);
1271		tmp_h = min(2 * tmp_h, max_height);
1272		mf->width = tmp_w;
1273		mf->height = tmp_h;
1274		ret = v4l2_device_call_until_err(sd->v4l2_dev, 0, video,
1275						 s_mbus_fmt, mf);
1276		dev_geo(dev, "Camera scaled to %ux%u\n",
1277			mf->width, mf->height);
1278		if (ret < 0) {
1279			/* This shouldn't happen */
1280			dev_err(dev, "Client failed to set format: %d\n", ret);
1281			return ret;
1282		}
1283	}
1284
1285update_cache:
1286	/* Update cache */
1287	ret = client_g_rect(sd, &cam->rect);
1288	if (ret < 0)
1289		return ret;
1290
1291	update_subrect(cam);
1292
1293	return 0;
1294}
1295
1296/**
1297 * @width	- on output: user width, mapped back to input
1298 * @height	- on output: user height, mapped back to input
1299 * @mf		- in- / output camera output window
1300 */
1301static int client_scale(struct soc_camera_device *icd,
1302			struct v4l2_mbus_framefmt *mf,
1303			unsigned int *width, unsigned int *height,
1304			bool ceu_can_scale)
1305{
1306	struct sh_mobile_ceu_cam *cam = icd->host_priv;
1307	struct device *dev = icd->dev.parent;
1308	struct v4l2_mbus_framefmt mf_tmp = *mf;
1309	unsigned int scale_h, scale_v;
1310	int ret;
1311
1312	/*
1313	 * 5. Apply iterative camera S_FMT for camera user window (also updates
1314	 *    client crop cache and the imaginary sub-rectangle).
1315	 */
1316	ret = client_s_fmt(icd, &mf_tmp, ceu_can_scale);
1317	if (ret < 0)
1318		return ret;
1319
1320	dev_geo(dev, "5: camera scaled to %ux%u\n",
1321		mf_tmp.width, mf_tmp.height);
1322
1323	/* 6. Retrieve camera output window (g_fmt) */
1324
1325	/* unneeded - it is already in "mf_tmp" */
1326
1327	/* 7. Calculate new client scales. */
1328	scale_h = calc_generic_scale(cam->rect.width, mf_tmp.width);
1329	scale_v = calc_generic_scale(cam->rect.height, mf_tmp.height);
1330
1331	mf->width	= mf_tmp.width;
1332	mf->height	= mf_tmp.height;
1333	mf->colorspace	= mf_tmp.colorspace;
1334
1335	/*
1336	 * 8. Calculate new CEU crop - apply camera scales to previously
1337	 *    updated "effective" crop.
1338	 */
1339	*width = scale_down(cam->subrect.width, scale_h);
1340	*height = scale_down(cam->subrect.height, scale_v);
1341
1342	dev_geo(dev, "8: new client sub-window %ux%u\n", *width, *height);
1343
1344	return 0;
1345}
1346
1347/*
1348 * CEU can scale and crop, but we don't want to waste bandwidth and kill the
1349 * framerate by always requesting the maximum image from the client. See
1350 * Documentation/video4linux/sh_mobile_camera_ceu.txt for a description of
1351 * scaling and cropping algorithms and for the meaning of referenced here steps.
1352 */
1353static int sh_mobile_ceu_set_crop(struct soc_camera_device *icd,
1354				  struct v4l2_crop *a)
1355{
1356	struct v4l2_rect *rect = &a->c;
1357	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
1358	struct sh_mobile_ceu_dev *pcdev = ici->priv;
1359	struct v4l2_crop cam_crop;
1360	struct sh_mobile_ceu_cam *cam = icd->host_priv;
1361	struct v4l2_rect *cam_rect = &cam_crop.c;
1362	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
1363	struct device *dev = icd->dev.parent;
1364	struct v4l2_mbus_framefmt mf;
1365	unsigned int scale_cam_h, scale_cam_v, scale_ceu_h, scale_ceu_v,
1366		out_width, out_height, scale_h, scale_v;
1367	int interm_width, interm_height;
1368	u32 capsr, cflcr;
1369	int ret;
1370
1371	dev_geo(dev, "S_CROP(%ux%u@%u:%u)\n", rect->width, rect->height,
1372		rect->left, rect->top);
1373
1374	/* During camera cropping its output window can change too, stop CEU */
1375	capsr = capture_save_reset(pcdev);
1376	dev_dbg(dev, "CAPSR 0x%x, CFLCR 0x%x\n", capsr, pcdev->cflcr);
1377
1378	/* 1. - 2. Apply iterative camera S_CROP for new input window. */
1379	ret = client_s_crop(icd, a, &cam_crop);
1380	if (ret < 0)
1381		return ret;
1382
1383	dev_geo(dev, "1-2: camera cropped to %ux%u@%u:%u\n",
1384		cam_rect->width, cam_rect->height,
1385		cam_rect->left, cam_rect->top);
1386
1387	/* On success cam_crop contains current camera crop */
1388
1389	/* 3. Retrieve camera output window */
1390	ret = v4l2_subdev_call(sd, video, g_mbus_fmt, &mf);
1391	if (ret < 0)
1392		return ret;
1393
1394	if (mf.width > 2560 || mf.height > 1920)
1395		return -EINVAL;
1396
1397	/* Cache camera output window */
1398	cam->width	= mf.width;
1399	cam->height	= mf.height;
1400
1401	/* 4. Calculate camera scales */
1402	scale_cam_h	= calc_generic_scale(cam_rect->width, mf.width);
1403	scale_cam_v	= calc_generic_scale(cam_rect->height, mf.height);
1404
1405	/* Calculate intermediate window */
1406	interm_width	= scale_down(rect->width, scale_cam_h);
1407	interm_height	= scale_down(rect->height, scale_cam_v);
1408
1409	if (pcdev->image_mode) {
1410		out_width	= min(interm_width, icd->user_width);
1411		out_height	= min(interm_height, icd->user_height);
1412	} else {
1413		out_width	= interm_width;
1414		out_height	= interm_height;
1415	}
1416
1417	/*
1418	 * 5. Calculate CEU scales from camera scales from results of (5) and
1419	 *    the user window
1420	 */
1421	scale_ceu_h	= calc_scale(interm_width, &out_width);
1422	scale_ceu_v	= calc_scale(interm_height, &out_height);
1423
1424	/* Calculate camera scales */
1425	scale_h		= calc_generic_scale(cam_rect->width, out_width);
1426	scale_v		= calc_generic_scale(cam_rect->height, out_height);
1427
1428	dev_geo(dev, "5: CEU scales %u:%u\n", scale_ceu_h, scale_ceu_v);
1429
1430	/* Apply CEU scales. */
1431	cflcr = scale_ceu_h | (scale_ceu_v << 16);
1432	if (cflcr != pcdev->cflcr) {
1433		pcdev->cflcr = cflcr;
1434		ceu_write(pcdev, CFLCR, cflcr);
1435	}
1436
1437	icd->user_width	 = out_width;
1438	icd->user_height = out_height;
1439	cam->ceu_left	 = scale_down(rect->left - cam_rect->left, scale_h) & ~1;
1440	cam->ceu_top	 = scale_down(rect->top - cam_rect->top, scale_v) & ~1;
1441
1442	/* 6. Use CEU cropping to crop to the new window. */
1443	sh_mobile_ceu_set_rect(icd);
1444
1445	cam->subrect = *rect;
1446
1447	dev_geo(dev, "6: CEU cropped to %ux%u@%u:%u\n",
1448		icd->user_width, icd->user_height,
1449		cam->ceu_left, cam->ceu_top);
1450
1451	/* Restore capture */
1452	if (pcdev->active)
1453		capsr |= 1;
1454	capture_restore(pcdev, capsr);
1455
1456	/* Even if only camera cropping succeeded */
1457	return ret;
1458}
1459
1460static int sh_mobile_ceu_get_crop(struct soc_camera_device *icd,
1461				  struct v4l2_crop *a)
1462{
1463	struct sh_mobile_ceu_cam *cam = icd->host_priv;
1464
1465	a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1466	a->c = cam->subrect;
1467
1468	return 0;
1469}
1470
1471/*
1472 * Calculate real client output window by applying new scales to the current
1473 * client crop. New scales are calculated from the requested output format and
1474 * CEU crop, mapped backed onto the client input (subrect).
1475 */
1476static void calculate_client_output(struct soc_camera_device *icd,
1477		struct v4l2_pix_format *pix, struct v4l2_mbus_framefmt *mf)
1478{
1479	struct sh_mobile_ceu_cam *cam = icd->host_priv;
1480	struct device *dev = icd->dev.parent;
1481	struct v4l2_rect *cam_subrect = &cam->subrect;
1482	unsigned int scale_v, scale_h;
1483
1484	if (cam_subrect->width == cam->rect.width &&
1485	    cam_subrect->height == cam->rect.height) {
1486		/* No sub-cropping */
1487		mf->width	= pix->width;
1488		mf->height	= pix->height;
1489		return;
1490	}
1491
1492	/* 1.-2. Current camera scales and subwin - cached. */
1493
1494	dev_geo(dev, "2: subwin %ux%u@%u:%u\n",
1495		cam_subrect->width, cam_subrect->height,
1496		cam_subrect->left, cam_subrect->top);
1497
1498	/*
1499	 * 3. Calculate new combined scales from input sub-window to requested
1500	 *    user window.
1501	 */
1502
1503	/*
1504	 * TODO: CEU cannot scale images larger than VGA to smaller than SubQCIF
1505	 * (128x96) or larger than VGA
1506	 */
1507	scale_h = calc_generic_scale(cam_subrect->width, pix->width);
1508	scale_v = calc_generic_scale(cam_subrect->height, pix->height);
1509
1510	dev_geo(dev, "3: scales %u:%u\n", scale_h, scale_v);
1511
1512	/*
1513	 * 4. Calculate client output window by applying combined scales to real
1514	 *    input window.
1515	 */
1516	mf->width	= scale_down(cam->rect.width, scale_h);
1517	mf->height	= scale_down(cam->rect.height, scale_v);
1518}
1519
1520/* Similar to set_crop multistage iterative algorithm */
1521static int sh_mobile_ceu_set_fmt(struct soc_camera_device *icd,
1522				 struct v4l2_format *f)
1523{
1524	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
1525	struct sh_mobile_ceu_dev *pcdev = ici->priv;
1526	struct sh_mobile_ceu_cam *cam = icd->host_priv;
1527	struct v4l2_pix_format *pix = &f->fmt.pix;
1528	struct v4l2_mbus_framefmt mf;
1529	struct device *dev = icd->dev.parent;
1530	__u32 pixfmt = pix->pixelformat;
1531	const struct soc_camera_format_xlate *xlate;
1532	/* Keep Compiler Happy */
1533	unsigned int ceu_sub_width = 0, ceu_sub_height = 0;
1534	u16 scale_v, scale_h;
1535	int ret;
1536	bool image_mode;
1537	enum v4l2_field field;
1538
1539	dev_geo(dev, "S_FMT(pix=0x%x, %ux%u)\n", pixfmt, pix->width, pix->height);
1540
1541	switch (pix->field) {
1542	default:
1543		pix->field = V4L2_FIELD_NONE;
1544		/* fall-through */
1545	case V4L2_FIELD_INTERLACED_TB:
1546	case V4L2_FIELD_INTERLACED_BT:
1547	case V4L2_FIELD_NONE:
1548		field = pix->field;
1549		break;
1550	case V4L2_FIELD_INTERLACED:
1551		field = V4L2_FIELD_INTERLACED_TB;
1552		break;
1553	}
1554
1555	xlate = soc_camera_xlate_by_fourcc(icd, pixfmt);
1556	if (!xlate) {
1557		dev_warn(dev, "Format %x not found\n", pixfmt);
1558		return -EINVAL;
1559	}
1560
1561	/* 1.-4. Calculate client output geometry */
1562	calculate_client_output(icd, &f->fmt.pix, &mf);
1563	mf.field	= pix->field;
1564	mf.colorspace	= pix->colorspace;
1565	mf.code		= xlate->code;
1566
1567	switch (pixfmt) {
1568	case V4L2_PIX_FMT_NV12:
1569	case V4L2_PIX_FMT_NV21:
1570	case V4L2_PIX_FMT_NV16:
1571	case V4L2_PIX_FMT_NV61:
1572		image_mode = true;
1573		break;
1574	default:
1575		image_mode = false;
1576	}
1577
1578	dev_geo(dev, "4: request camera output %ux%u\n", mf.width, mf.height);
1579
1580	/* 5. - 9. */
1581	ret = client_scale(icd, &mf, &ceu_sub_width, &ceu_sub_height,
1582			   image_mode && V4L2_FIELD_NONE == field);
1583
1584	dev_geo(dev, "5-9: client scale return %d\n", ret);
1585
1586	/* Done with the camera. Now see if we can improve the result */
1587
1588	dev_geo(dev, "fmt %ux%u, requested %ux%u\n",
1589		mf.width, mf.height, pix->width, pix->height);
1590	if (ret < 0)
1591		return ret;
1592
1593	if (mf.code != xlate->code)
1594		return -EINVAL;
1595
1596	/* 9. Prepare CEU crop */
1597	cam->width = mf.width;
1598	cam->height = mf.height;
1599
1600	/* 10. Use CEU scaling to scale to the requested user window. */
1601
1602	/* We cannot scale up */
1603	if (pix->width > ceu_sub_width)
1604		ceu_sub_width = pix->width;
1605
1606	if (pix->height > ceu_sub_height)
1607		ceu_sub_height = pix->height;
1608
1609	pix->colorspace = mf.colorspace;
1610
1611	if (image_mode) {
1612		/* Scale pix->{width x height} down to width x height */
1613		scale_h		= calc_scale(ceu_sub_width, &pix->width);
1614		scale_v		= calc_scale(ceu_sub_height, &pix->height);
1615	} else {
1616		pix->width	= ceu_sub_width;
1617		pix->height	= ceu_sub_height;
1618		scale_h		= 0;
1619		scale_v		= 0;
1620	}
1621
1622	pcdev->cflcr = scale_h | (scale_v << 16);
1623
1624	/*
1625	 * We have calculated CFLCR, the actual configuration will be performed
1626	 * in sh_mobile_ceu_set_bus_param()
1627	 */
1628
1629	dev_geo(dev, "10: W: %u : 0x%x = %u, H: %u : 0x%x = %u\n",
1630		ceu_sub_width, scale_h, pix->width,
1631		ceu_sub_height, scale_v, pix->height);
1632
1633	cam->code		= xlate->code;
1634	icd->current_fmt	= xlate;
1635
1636	pcdev->field = field;
1637	pcdev->image_mode = image_mode;
1638
1639	return 0;
1640}
1641
1642static int sh_mobile_ceu_try_fmt(struct soc_camera_device *icd,
1643				 struct v4l2_format *f)
1644{
1645	const struct soc_camera_format_xlate *xlate;
1646	struct v4l2_pix_format *pix = &f->fmt.pix;
1647	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
1648	struct v4l2_mbus_framefmt mf;
1649	__u32 pixfmt = pix->pixelformat;
1650	int width, height;
1651	int ret;
1652
1653	dev_geo(icd->dev.parent, "TRY_FMT(pix=0x%x, %ux%u)\n",
1654		 pixfmt, pix->width, pix->height);
1655
1656	xlate = soc_camera_xlate_by_fourcc(icd, pixfmt);
1657	if (!xlate) {
1658		dev_warn(icd->dev.parent, "Format %x not found\n", pixfmt);
1659		return -EINVAL;
1660	}
1661
1662
1663	v4l_bound_align_image(&pix->width, 2, 2560, 1,
1664			      &pix->height, 4, 1920, 2, 0);
1665
1666	width = pix->width;
1667	height = pix->height;
1668
1669	pix->bytesperline = soc_mbus_bytes_per_line(width, xlate->host_fmt);
1670	if ((int)pix->bytesperline < 0)
1671		return pix->bytesperline;
1672	pix->sizeimage = height * pix->bytesperline;
1673
1674	/* limit to sensor capabilities */
1675	mf.width	= pix->width;
1676	mf.height	= pix->height;
1677	mf.field	= pix->field;
1678	mf.code		= xlate->code;
1679	mf.colorspace	= pix->colorspace;
1680
1681	ret = v4l2_device_call_until_err(sd->v4l2_dev, 0, video, try_mbus_fmt, &mf);
1682	if (ret < 0)
1683		return ret;
1684
1685	pix->width	= mf.width;
1686	pix->height	= mf.height;
1687	pix->field	= mf.field;
1688	pix->colorspace	= mf.colorspace;
1689
1690	switch (pixfmt) {
1691	case V4L2_PIX_FMT_NV12:
1692	case V4L2_PIX_FMT_NV21:
1693	case V4L2_PIX_FMT_NV16:
1694	case V4L2_PIX_FMT_NV61:
1695		/* We can scale precisely, need a bigger image from camera */
1696		if (pix->width < width || pix->height < height) {
1697			/*
1698			 * We presume, the sensor behaves sanely, i.e., if
1699			 * requested a bigger rectangle, it will not return a
1700			 * smaller one.
1701			 */
1702			mf.width = 2560;
1703			mf.height = 1920;
1704			ret = v4l2_device_call_until_err(sd->v4l2_dev, 0, video,
1705							 try_mbus_fmt, &mf);
1706			if (ret < 0) {
1707				/* Shouldn't actually happen... */
1708				dev_err(icd->dev.parent,
1709					"FIXME: client try_fmt() = %d\n", ret);
1710				return ret;
1711			}
1712		}
1713		/* We will scale exactly */
1714		if (mf.width > width)
1715			pix->width = width;
1716		if (mf.height > height)
1717			pix->height = height;
1718	}
1719
1720	dev_geo(icd->dev.parent, "%s(): return %d, fmt 0x%x, %ux%u\n",
1721		__func__, ret, pix->pixelformat, pix->width, pix->height);
1722
1723	return ret;
1724}
1725
1726static int sh_mobile_ceu_reqbufs(struct soc_camera_file *icf,
1727				 struct v4l2_requestbuffers *p)
1728{
1729	int i;
1730
1731	/*
1732	 * This is for locking debugging only. I removed spinlocks and now I
1733	 * check whether .prepare is ever called on a linked buffer, or whether
1734	 * a dma IRQ can occur for an in-work or unlinked buffer. Until now
1735	 * it hadn't triggered
1736	 */
1737	for (i = 0; i < p->count; i++) {
1738		struct sh_mobile_ceu_buffer *buf;
1739
1740		buf = container_of(icf->vb_vidq.bufs[i],
1741				   struct sh_mobile_ceu_buffer, vb);
1742		INIT_LIST_HEAD(&buf->vb.queue);
1743	}
1744
1745	return 0;
1746}
1747
1748static unsigned int sh_mobile_ceu_poll(struct file *file, poll_table *pt)
1749{
1750	struct soc_camera_file *icf = file->private_data;
1751	struct sh_mobile_ceu_buffer *buf;
1752
1753	buf = list_entry(icf->vb_vidq.stream.next,
1754			 struct sh_mobile_ceu_buffer, vb.stream);
1755
1756	poll_wait(file, &buf->vb.done, pt);
1757
1758	if (buf->vb.state == VIDEOBUF_DONE ||
1759	    buf->vb.state == VIDEOBUF_ERROR)
1760		return POLLIN|POLLRDNORM;
1761
1762	return 0;
1763}
1764
1765static int sh_mobile_ceu_querycap(struct soc_camera_host *ici,
1766				  struct v4l2_capability *cap)
1767{
1768	strlcpy(cap->card, "SuperH_Mobile_CEU", sizeof(cap->card));
1769	cap->version = KERNEL_VERSION(0, 0, 5);
1770	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
1771	return 0;
1772}
1773
1774static void sh_mobile_ceu_init_videobuf(struct videobuf_queue *q,
1775					struct soc_camera_device *icd)
1776{
1777	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
1778	struct sh_mobile_ceu_dev *pcdev = ici->priv;
1779
1780	videobuf_queue_dma_contig_init(q,
1781				       &sh_mobile_ceu_videobuf_ops,
1782				       icd->dev.parent, &pcdev->lock,
1783				       V4L2_BUF_TYPE_VIDEO_CAPTURE,
1784				       pcdev->field,
1785				       sizeof(struct sh_mobile_ceu_buffer),
1786				       icd);
1787}
1788
1789static int sh_mobile_ceu_get_parm(struct soc_camera_device *icd,
1790				  struct v4l2_streamparm *parm)
1791{
1792	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
1793
1794	return v4l2_subdev_call(sd, video, g_parm, parm);
1795}
1796
1797static int sh_mobile_ceu_set_parm(struct soc_camera_device *icd,
1798				  struct v4l2_streamparm *parm)
1799{
1800	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
1801
1802	return v4l2_subdev_call(sd, video, s_parm, parm);
1803}
1804
1805static int sh_mobile_ceu_get_ctrl(struct soc_camera_device *icd,
1806				  struct v4l2_control *ctrl)
1807{
1808	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
1809	struct sh_mobile_ceu_dev *pcdev = ici->priv;
1810	u32 val;
1811
1812	switch (ctrl->id) {
1813	case V4L2_CID_SHARPNESS:
1814		val = ceu_read(pcdev, CLFCR);
1815		ctrl->value = val ^ 1;
1816		return 0;
1817	}
1818	return -ENOIOCTLCMD;
1819}
1820
1821static int sh_mobile_ceu_set_ctrl(struct soc_camera_device *icd,
1822				  struct v4l2_control *ctrl)
1823{
1824	struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
1825	struct sh_mobile_ceu_dev *pcdev = ici->priv;
1826
1827	switch (ctrl->id) {
1828	case V4L2_CID_SHARPNESS:
1829		switch (icd->current_fmt->host_fmt->fourcc) {
1830		case V4L2_PIX_FMT_NV12:
1831		case V4L2_PIX_FMT_NV21:
1832		case V4L2_PIX_FMT_NV16:
1833		case V4L2_PIX_FMT_NV61:
1834			ceu_write(pcdev, CLFCR, !ctrl->value);
1835			return 0;
1836		}
1837		return -EINVAL;
1838	}
1839	return -ENOIOCTLCMD;
1840}
1841
1842static const struct v4l2_queryctrl sh_mobile_ceu_controls[] = {
1843	{
1844		.id		= V4L2_CID_SHARPNESS,
1845		.type		= V4L2_CTRL_TYPE_BOOLEAN,
1846		.name		= "Low-pass filter",
1847		.minimum	= 0,
1848		.maximum	= 1,
1849		.step		= 1,
1850		.default_value	= 0,
1851	},
1852};
1853
1854static struct soc_camera_host_ops sh_mobile_ceu_host_ops = {
1855	.owner		= THIS_MODULE,
1856	.add		= sh_mobile_ceu_add_device,
1857	.remove		= sh_mobile_ceu_remove_device,
1858	.get_formats	= sh_mobile_ceu_get_formats,
1859	.put_formats	= sh_mobile_ceu_put_formats,
1860	.get_crop	= sh_mobile_ceu_get_crop,
1861	.set_crop	= sh_mobile_ceu_set_crop,
1862	.set_fmt	= sh_mobile_ceu_set_fmt,
1863	.try_fmt	= sh_mobile_ceu_try_fmt,
1864	.set_ctrl	= sh_mobile_ceu_set_ctrl,
1865	.get_ctrl	= sh_mobile_ceu_get_ctrl,
1866	.set_parm	= sh_mobile_ceu_set_parm,
1867	.get_parm	= sh_mobile_ceu_get_parm,
1868	.reqbufs	= sh_mobile_ceu_reqbufs,
1869	.poll		= sh_mobile_ceu_poll,
1870	.querycap	= sh_mobile_ceu_querycap,
1871	.set_bus_param	= sh_mobile_ceu_set_bus_param,
1872	.init_videobuf	= sh_mobile_ceu_init_videobuf,
1873	.controls	= sh_mobile_ceu_controls,
1874	.num_controls	= ARRAY_SIZE(sh_mobile_ceu_controls),
1875};
1876
1877struct bus_wait {
1878	struct notifier_block	notifier;
1879	struct completion	completion;
1880	struct device		*dev;
1881};
1882
1883static int bus_notify(struct notifier_block *nb,
1884		      unsigned long action, void *data)
1885{
1886	struct device *dev = data;
1887	struct bus_wait *wait = container_of(nb, struct bus_wait, notifier);
1888
1889	if (wait->dev != dev)
1890		return NOTIFY_DONE;
1891
1892	switch (action) {
1893	case BUS_NOTIFY_UNBOUND_DRIVER:
1894		/* Protect from module unloading */
1895		wait_for_completion(&wait->completion);
1896		return NOTIFY_OK;
1897	}
1898	return NOTIFY_DONE;
1899}
1900
1901static int __devinit sh_mobile_ceu_probe(struct platform_device *pdev)
1902{
1903	struct sh_mobile_ceu_dev *pcdev;
1904	struct resource *res;
1905	void __iomem *base;
1906	unsigned int irq;
1907	int err = 0;
1908	struct bus_wait wait = {
1909		.completion = COMPLETION_INITIALIZER_ONSTACK(wait.completion),
1910		.notifier.notifier_call = bus_notify,
1911	};
1912	struct device *csi2;
1913
1914	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1915	irq = platform_get_irq(pdev, 0);
1916	if (!res || (int)irq <= 0) {
1917		dev_err(&pdev->dev, "Not enough CEU platform resources.\n");
1918		err = -ENODEV;
1919		goto exit;
1920	}
1921
1922	pcdev = kzalloc(sizeof(*pcdev), GFP_KERNEL);
1923	if (!pcdev) {
1924		dev_err(&pdev->dev, "Could not allocate pcdev\n");
1925		err = -ENOMEM;
1926		goto exit;
1927	}
1928
1929	INIT_LIST_HEAD(&pcdev->capture);
1930	spin_lock_init(&pcdev->lock);
1931
1932	pcdev->pdata = pdev->dev.platform_data;
1933	if (!pcdev->pdata) {
1934		err = -EINVAL;
1935		dev_err(&pdev->dev, "CEU platform data not set.\n");
1936		goto exit_kfree;
1937	}
1938
1939	base = ioremap_nocache(res->start, resource_size(res));
1940	if (!base) {
1941		err = -ENXIO;
1942		dev_err(&pdev->dev, "Unable to ioremap CEU registers.\n");
1943		goto exit_kfree;
1944	}
1945
1946	pcdev->irq = irq;
1947	pcdev->base = base;
1948	pcdev->video_limit = 0; /* only enabled if second resource exists */
1949
1950	res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
1951	if (res) {
1952		err = dma_declare_coherent_memory(&pdev->dev, res->start,
1953						  res->start,
1954						  resource_size(res),
1955						  DMA_MEMORY_MAP |
1956						  DMA_MEMORY_EXCLUSIVE);
1957		if (!err) {
1958			dev_err(&pdev->dev, "Unable to declare CEU memory.\n");
1959			err = -ENXIO;
1960			goto exit_iounmap;
1961		}
1962
1963		pcdev->video_limit = resource_size(res);
1964	}
1965
1966	/* request irq */
1967	err = request_irq(pcdev->irq, sh_mobile_ceu_irq, IRQF_DISABLED,
1968			  dev_name(&pdev->dev), pcdev);
1969	if (err) {
1970		dev_err(&pdev->dev, "Unable to register CEU interrupt.\n");
1971		goto exit_release_mem;
1972	}
1973
1974	pm_suspend_ignore_children(&pdev->dev, true);
1975	pm_runtime_enable(&pdev->dev);
1976	pm_runtime_resume(&pdev->dev);
1977
1978	pcdev->ici.priv = pcdev;
1979	pcdev->ici.v4l2_dev.dev = &pdev->dev;
1980	pcdev->ici.nr = pdev->id;
1981	pcdev->ici.drv_name = dev_name(&pdev->dev);
1982	pcdev->ici.ops = &sh_mobile_ceu_host_ops;
1983
1984	/* CSI2 interfacing */
1985	csi2 = pcdev->pdata->csi2_dev;
1986	if (csi2) {
1987		wait.dev = csi2;
1988
1989		err = bus_register_notifier(&platform_bus_type, &wait.notifier);
1990		if (err < 0)
1991			goto exit_free_clk;
1992
1993		/*
1994		 * From this point the driver module will not unload, until
1995		 * we complete the completion.
1996		 */
1997
1998		if (!csi2->driver || !csi2->driver->owner) {
1999			complete(&wait.completion);
2000			/* Either too late, or probing failed */
2001			bus_unregister_notifier(&platform_bus_type, &wait.notifier);
2002			err = -ENXIO;
2003			goto exit_free_clk;
2004		}
2005
2006		/*
2007		 * The module is still loaded, in the worst case it is hanging
2008		 * in device release on our completion. So, _now_ dereferencing
2009		 * the "owner" is safe!
2010		 */
2011
2012		err = try_module_get(csi2->driver->owner);
2013
2014		/* Let notifier complete, if it has been locked */
2015		complete(&wait.completion);
2016		bus_unregister_notifier(&platform_bus_type, &wait.notifier);
2017		if (!err) {
2018			err = -ENODEV;
2019			goto exit_free_clk;
2020		}
2021	}
2022
2023	err = soc_camera_host_register(&pcdev->ici);
2024	if (err)
2025		goto exit_module_put;
2026
2027	return 0;
2028
2029exit_module_put:
2030	if (csi2 && csi2->driver)
2031		module_put(csi2->driver->owner);
2032exit_free_clk:
2033	pm_runtime_disable(&pdev->dev);
2034	free_irq(pcdev->irq, pcdev);
2035exit_release_mem:
2036	if (platform_get_resource(pdev, IORESOURCE_MEM, 1))
2037		dma_release_declared_memory(&pdev->dev);
2038exit_iounmap:
2039	iounmap(base);
2040exit_kfree:
2041	kfree(pcdev);
2042exit:
2043	return err;
2044}
2045
2046static int __devexit sh_mobile_ceu_remove(struct platform_device *pdev)
2047{
2048	struct soc_camera_host *soc_host = to_soc_camera_host(&pdev->dev);
2049	struct sh_mobile_ceu_dev *pcdev = container_of(soc_host,
2050					struct sh_mobile_ceu_dev, ici);
2051	struct device *csi2 = pcdev->pdata->csi2_dev;
2052
2053	soc_camera_host_unregister(soc_host);
2054	pm_runtime_disable(&pdev->dev);
2055	free_irq(pcdev->irq, pcdev);
2056	if (platform_get_resource(pdev, IORESOURCE_MEM, 1))
2057		dma_release_declared_memory(&pdev->dev);
2058	iounmap(pcdev->base);
2059	if (csi2 && csi2->driver)
2060		module_put(csi2->driver->owner);
2061	kfree(pcdev);
2062
2063	return 0;
2064}
2065
2066static int sh_mobile_ceu_runtime_nop(struct device *dev)
2067{
2068	/* Runtime PM callback shared between ->runtime_suspend()
2069	 * and ->runtime_resume(). Simply returns success.
2070	 *
2071	 * This driver re-initializes all registers after
2072	 * pm_runtime_get_sync() anyway so there is no need
2073	 * to save and restore registers here.
2074	 */
2075	return 0;
2076}
2077
2078static const struct dev_pm_ops sh_mobile_ceu_dev_pm_ops = {
2079	.runtime_suspend = sh_mobile_ceu_runtime_nop,
2080	.runtime_resume = sh_mobile_ceu_runtime_nop,
2081};
2082
2083static struct platform_driver sh_mobile_ceu_driver = {
2084	.driver 	= {
2085		.name	= "sh_mobile_ceu",
2086		.pm	= &sh_mobile_ceu_dev_pm_ops,
2087	},
2088	.probe		= sh_mobile_ceu_probe,
2089	.remove		= __devexit_p(sh_mobile_ceu_remove),
2090};
2091
2092static int __init sh_mobile_ceu_init(void)
2093{
2094	/* Whatever return code */
2095	request_module("sh_mobile_csi2");
2096	return platform_driver_register(&sh_mobile_ceu_driver);
2097}
2098
2099static void __exit sh_mobile_ceu_exit(void)
2100{
2101	platform_driver_unregister(&sh_mobile_ceu_driver);
2102}
2103
2104module_init(sh_mobile_ceu_init);
2105module_exit(sh_mobile_ceu_exit);
2106
2107MODULE_DESCRIPTION("SuperH Mobile CEU driver");
2108MODULE_AUTHOR("Magnus Damm");
2109MODULE_LICENSE("GPL");
2110MODULE_ALIAS("platform:sh_mobile_ceu");
2111