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