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