[media] marvell-ccic: use internal variable replace global frame stats variable
[platform/kernel/linux-rpi.git] / drivers / media / platform / marvell-ccic / mcam-core.c
1 /*
2  * The Marvell camera core.  This device appears in a number of settings,
3  * so it needs platform-specific support outside of the core.
4  *
5  * Copyright 2011 Jonathan Corbet corbet@lwn.net
6  */
7 #include <linux/kernel.h>
8 #include <linux/module.h>
9 #include <linux/fs.h>
10 #include <linux/mm.h>
11 #include <linux/i2c.h>
12 #include <linux/interrupt.h>
13 #include <linux/spinlock.h>
14 #include <linux/slab.h>
15 #include <linux/device.h>
16 #include <linux/wait.h>
17 #include <linux/list.h>
18 #include <linux/dma-mapping.h>
19 #include <linux/delay.h>
20 #include <linux/vmalloc.h>
21 #include <linux/io.h>
22 #include <linux/videodev2.h>
23 #include <media/v4l2-device.h>
24 #include <media/v4l2-ioctl.h>
25 #include <media/v4l2-chip-ident.h>
26 #include <media/ov7670.h>
27 #include <media/videobuf2-vmalloc.h>
28 #include <media/videobuf2-dma-contig.h>
29 #include <media/videobuf2-dma-sg.h>
30
31 #include "mcam-core.h"
32
33 #ifdef MCAM_MODE_VMALLOC
34 /*
35  * Internal DMA buffer management.  Since the controller cannot do S/G I/O,
36  * we must have physically contiguous buffers to bring frames into.
37  * These parameters control how many buffers we use, whether we
38  * allocate them at load time (better chance of success, but nails down
39  * memory) or when somebody tries to use the camera (riskier), and,
40  * for load-time allocation, how big they should be.
41  *
42  * The controller can cycle through three buffers.  We could use
43  * more by flipping pointers around, but it probably makes little
44  * sense.
45  */
46
47 static bool alloc_bufs_at_read;
48 module_param(alloc_bufs_at_read, bool, 0444);
49 MODULE_PARM_DESC(alloc_bufs_at_read,
50                 "Non-zero value causes DMA buffers to be allocated when the "
51                 "video capture device is read, rather than at module load "
52                 "time.  This saves memory, but decreases the chances of "
53                 "successfully getting those buffers.  This parameter is "
54                 "only used in the vmalloc buffer mode");
55
56 static int n_dma_bufs = 3;
57 module_param(n_dma_bufs, uint, 0644);
58 MODULE_PARM_DESC(n_dma_bufs,
59                 "The number of DMA buffers to allocate.  Can be either two "
60                 "(saves memory, makes timing tighter) or three.");
61
62 static int dma_buf_size = VGA_WIDTH * VGA_HEIGHT * 2;  /* Worst case */
63 module_param(dma_buf_size, uint, 0444);
64 MODULE_PARM_DESC(dma_buf_size,
65                 "The size of the allocated DMA buffers.  If actual operating "
66                 "parameters require larger buffers, an attempt to reallocate "
67                 "will be made.");
68 #else /* MCAM_MODE_VMALLOC */
69 static const bool alloc_bufs_at_read = 0;
70 static const int n_dma_bufs = 3;  /* Used by S/G_PARM */
71 #endif /* MCAM_MODE_VMALLOC */
72
73 static bool flip;
74 module_param(flip, bool, 0444);
75 MODULE_PARM_DESC(flip,
76                 "If set, the sensor will be instructed to flip the image "
77                 "vertically.");
78
79 static int buffer_mode = -1;
80 module_param(buffer_mode, int, 0444);
81 MODULE_PARM_DESC(buffer_mode,
82                 "Set the buffer mode to be used; default is to go with what "
83                 "the platform driver asks for.  Set to 0 for vmalloc, 1 for "
84                 "DMA contiguous.");
85
86 /*
87  * Status flags.  Always manipulated with bit operations.
88  */
89 #define CF_BUF0_VALID    0      /* Buffers valid - first three */
90 #define CF_BUF1_VALID    1
91 #define CF_BUF2_VALID    2
92 #define CF_DMA_ACTIVE    3      /* A frame is incoming */
93 #define CF_CONFIG_NEEDED 4      /* Must configure hardware */
94 #define CF_SINGLE_BUFFER 5      /* Running with a single buffer */
95 #define CF_SG_RESTART    6      /* SG restart needed */
96
97 #define sensor_call(cam, o, f, args...) \
98         v4l2_subdev_call(cam->sensor, o, f, ##args)
99
100 static struct mcam_format_struct {
101         __u8 *desc;
102         __u32 pixelformat;
103         int bpp;   /* Bytes per pixel */
104         enum v4l2_mbus_pixelcode mbus_code;
105 } mcam_formats[] = {
106         {
107                 .desc           = "YUYV 4:2:2",
108                 .pixelformat    = V4L2_PIX_FMT_YUYV,
109                 .mbus_code      = V4L2_MBUS_FMT_YUYV8_2X8,
110                 .bpp            = 2,
111         },
112         {
113                 .desc           = "RGB 444",
114                 .pixelformat    = V4L2_PIX_FMT_RGB444,
115                 .mbus_code      = V4L2_MBUS_FMT_RGB444_2X8_PADHI_LE,
116                 .bpp            = 2,
117         },
118         {
119                 .desc           = "RGB 565",
120                 .pixelformat    = V4L2_PIX_FMT_RGB565,
121                 .mbus_code      = V4L2_MBUS_FMT_RGB565_2X8_LE,
122                 .bpp            = 2,
123         },
124         {
125                 .desc           = "Raw RGB Bayer",
126                 .pixelformat    = V4L2_PIX_FMT_SBGGR8,
127                 .mbus_code      = V4L2_MBUS_FMT_SBGGR8_1X8,
128                 .bpp            = 1
129         },
130 };
131 #define N_MCAM_FMTS ARRAY_SIZE(mcam_formats)
132
133 static struct mcam_format_struct *mcam_find_format(u32 pixelformat)
134 {
135         unsigned i;
136
137         for (i = 0; i < N_MCAM_FMTS; i++)
138                 if (mcam_formats[i].pixelformat == pixelformat)
139                         return mcam_formats + i;
140         /* Not found? Then return the first format. */
141         return mcam_formats;
142 }
143
144 /*
145  * The default format we use until somebody says otherwise.
146  */
147 static const struct v4l2_pix_format mcam_def_pix_format = {
148         .width          = VGA_WIDTH,
149         .height         = VGA_HEIGHT,
150         .pixelformat    = V4L2_PIX_FMT_YUYV,
151         .field          = V4L2_FIELD_NONE,
152         .bytesperline   = VGA_WIDTH*2,
153         .sizeimage      = VGA_WIDTH*VGA_HEIGHT*2,
154 };
155
156 static const enum v4l2_mbus_pixelcode mcam_def_mbus_code =
157                                         V4L2_MBUS_FMT_YUYV8_2X8;
158
159
160 /*
161  * The two-word DMA descriptor format used by the Armada 610 and like.  There
162  * Is a three-word format as well (set C1_DESC_3WORD) where the third
163  * word is a pointer to the next descriptor, but we don't use it.  Two-word
164  * descriptors have to be contiguous in memory.
165  */
166 struct mcam_dma_desc {
167         u32 dma_addr;
168         u32 segment_len;
169 };
170
171 /*
172  * Our buffer type for working with videobuf2.  Note that the vb2
173  * developers have decreed that struct vb2_buffer must be at the
174  * beginning of this structure.
175  */
176 struct mcam_vb_buffer {
177         struct vb2_buffer vb_buf;
178         struct list_head queue;
179         struct mcam_dma_desc *dma_desc; /* Descriptor virtual address */
180         dma_addr_t dma_desc_pa;         /* Descriptor physical address */
181         int dma_desc_nent;              /* Number of mapped descriptors */
182 };
183
184 static inline struct mcam_vb_buffer *vb_to_mvb(struct vb2_buffer *vb)
185 {
186         return container_of(vb, struct mcam_vb_buffer, vb_buf);
187 }
188
189 /*
190  * Hand a completed buffer back to user space.
191  */
192 static void mcam_buffer_done(struct mcam_camera *cam, int frame,
193                 struct vb2_buffer *vbuf)
194 {
195         vbuf->v4l2_buf.bytesused = cam->pix_format.sizeimage;
196         vbuf->v4l2_buf.sequence = cam->buf_seq[frame];
197         vb2_set_plane_payload(vbuf, 0, cam->pix_format.sizeimage);
198         vb2_buffer_done(vbuf, VB2_BUF_STATE_DONE);
199 }
200
201
202
203 /*
204  * Debugging and related.
205  */
206 #define cam_err(cam, fmt, arg...) \
207         dev_err((cam)->dev, fmt, ##arg);
208 #define cam_warn(cam, fmt, arg...) \
209         dev_warn((cam)->dev, fmt, ##arg);
210 #define cam_dbg(cam, fmt, arg...) \
211         dev_dbg((cam)->dev, fmt, ##arg);
212
213
214 /*
215  * Flag manipulation helpers
216  */
217 static void mcam_reset_buffers(struct mcam_camera *cam)
218 {
219         int i;
220
221         cam->next_buf = -1;
222         for (i = 0; i < cam->nbufs; i++)
223                 clear_bit(i, &cam->flags);
224 }
225
226 static inline int mcam_needs_config(struct mcam_camera *cam)
227 {
228         return test_bit(CF_CONFIG_NEEDED, &cam->flags);
229 }
230
231 static void mcam_set_config_needed(struct mcam_camera *cam, int needed)
232 {
233         if (needed)
234                 set_bit(CF_CONFIG_NEEDED, &cam->flags);
235         else
236                 clear_bit(CF_CONFIG_NEEDED, &cam->flags);
237 }
238
239 /* ------------------------------------------------------------------- */
240 /*
241  * Make the controller start grabbing images.  Everything must
242  * be set up before doing this.
243  */
244 static void mcam_ctlr_start(struct mcam_camera *cam)
245 {
246         /* set_bit performs a read, so no other barrier should be
247            needed here */
248         mcam_reg_set_bit(cam, REG_CTRL0, C0_ENABLE);
249 }
250
251 static void mcam_ctlr_stop(struct mcam_camera *cam)
252 {
253         mcam_reg_clear_bit(cam, REG_CTRL0, C0_ENABLE);
254 }
255
256 /* ------------------------------------------------------------------- */
257
258 #ifdef MCAM_MODE_VMALLOC
259 /*
260  * Code specific to the vmalloc buffer mode.
261  */
262
263 /*
264  * Allocate in-kernel DMA buffers for vmalloc mode.
265  */
266 static int mcam_alloc_dma_bufs(struct mcam_camera *cam, int loadtime)
267 {
268         int i;
269
270         mcam_set_config_needed(cam, 1);
271         if (loadtime)
272                 cam->dma_buf_size = dma_buf_size;
273         else
274                 cam->dma_buf_size = cam->pix_format.sizeimage;
275         if (n_dma_bufs > 3)
276                 n_dma_bufs = 3;
277
278         cam->nbufs = 0;
279         for (i = 0; i < n_dma_bufs; i++) {
280                 cam->dma_bufs[i] = dma_alloc_coherent(cam->dev,
281                                 cam->dma_buf_size, cam->dma_handles + i,
282                                 GFP_KERNEL);
283                 if (cam->dma_bufs[i] == NULL) {
284                         cam_warn(cam, "Failed to allocate DMA buffer\n");
285                         break;
286                 }
287                 (cam->nbufs)++;
288         }
289
290         switch (cam->nbufs) {
291         case 1:
292                 dma_free_coherent(cam->dev, cam->dma_buf_size,
293                                 cam->dma_bufs[0], cam->dma_handles[0]);
294                 cam->nbufs = 0;
295         case 0:
296                 cam_err(cam, "Insufficient DMA buffers, cannot operate\n");
297                 return -ENOMEM;
298
299         case 2:
300                 if (n_dma_bufs > 2)
301                         cam_warn(cam, "Will limp along with only 2 buffers\n");
302                 break;
303         }
304         return 0;
305 }
306
307 static void mcam_free_dma_bufs(struct mcam_camera *cam)
308 {
309         int i;
310
311         for (i = 0; i < cam->nbufs; i++) {
312                 dma_free_coherent(cam->dev, cam->dma_buf_size,
313                                 cam->dma_bufs[i], cam->dma_handles[i]);
314                 cam->dma_bufs[i] = NULL;
315         }
316         cam->nbufs = 0;
317 }
318
319
320 /*
321  * Set up DMA buffers when operating in vmalloc mode
322  */
323 static void mcam_ctlr_dma_vmalloc(struct mcam_camera *cam)
324 {
325         /*
326          * Store the first two Y buffers (we aren't supporting
327          * planar formats for now, so no UV bufs).  Then either
328          * set the third if it exists, or tell the controller
329          * to just use two.
330          */
331         mcam_reg_write(cam, REG_Y0BAR, cam->dma_handles[0]);
332         mcam_reg_write(cam, REG_Y1BAR, cam->dma_handles[1]);
333         if (cam->nbufs > 2) {
334                 mcam_reg_write(cam, REG_Y2BAR, cam->dma_handles[2]);
335                 mcam_reg_clear_bit(cam, REG_CTRL1, C1_TWOBUFS);
336         } else
337                 mcam_reg_set_bit(cam, REG_CTRL1, C1_TWOBUFS);
338         if (cam->chip_id == V4L2_IDENT_CAFE)
339                 mcam_reg_write(cam, REG_UBAR, 0); /* 32 bits only */
340 }
341
342 /*
343  * Copy data out to user space in the vmalloc case
344  */
345 static void mcam_frame_tasklet(unsigned long data)
346 {
347         struct mcam_camera *cam = (struct mcam_camera *) data;
348         int i;
349         unsigned long flags;
350         struct mcam_vb_buffer *buf;
351
352         spin_lock_irqsave(&cam->dev_lock, flags);
353         for (i = 0; i < cam->nbufs; i++) {
354                 int bufno = cam->next_buf;
355
356                 if (cam->state != S_STREAMING || bufno < 0)
357                         break;  /* I/O got stopped */
358                 if (++(cam->next_buf) >= cam->nbufs)
359                         cam->next_buf = 0;
360                 if (!test_bit(bufno, &cam->flags))
361                         continue;
362                 if (list_empty(&cam->buffers)) {
363                         cam->frame_state.singles++;
364                         break;  /* Leave it valid, hope for better later */
365                 }
366                 cam->frame_state.delivered++;
367                 clear_bit(bufno, &cam->flags);
368                 buf = list_first_entry(&cam->buffers, struct mcam_vb_buffer,
369                                 queue);
370                 list_del_init(&buf->queue);
371                 /*
372                  * Drop the lock during the big copy.  This *should* be safe...
373                  */
374                 spin_unlock_irqrestore(&cam->dev_lock, flags);
375                 memcpy(vb2_plane_vaddr(&buf->vb_buf, 0), cam->dma_bufs[bufno],
376                                 cam->pix_format.sizeimage);
377                 mcam_buffer_done(cam, bufno, &buf->vb_buf);
378                 spin_lock_irqsave(&cam->dev_lock, flags);
379         }
380         spin_unlock_irqrestore(&cam->dev_lock, flags);
381 }
382
383
384 /*
385  * Make sure our allocated buffers are up to the task.
386  */
387 static int mcam_check_dma_buffers(struct mcam_camera *cam)
388 {
389         if (cam->nbufs > 0 && cam->dma_buf_size < cam->pix_format.sizeimage)
390                         mcam_free_dma_bufs(cam);
391         if (cam->nbufs == 0)
392                 return mcam_alloc_dma_bufs(cam, 0);
393         return 0;
394 }
395
396 static void mcam_vmalloc_done(struct mcam_camera *cam, int frame)
397 {
398         tasklet_schedule(&cam->s_tasklet);
399 }
400
401 #else /* MCAM_MODE_VMALLOC */
402
403 static inline int mcam_alloc_dma_bufs(struct mcam_camera *cam, int loadtime)
404 {
405         return 0;
406 }
407
408 static inline void mcam_free_dma_bufs(struct mcam_camera *cam)
409 {
410         return;
411 }
412
413 static inline int mcam_check_dma_buffers(struct mcam_camera *cam)
414 {
415         return 0;
416 }
417
418
419
420 #endif /* MCAM_MODE_VMALLOC */
421
422
423 #ifdef MCAM_MODE_DMA_CONTIG
424 /* ---------------------------------------------------------------------- */
425 /*
426  * DMA-contiguous code.
427  */
428 /*
429  * Set up a contiguous buffer for the given frame.  Here also is where
430  * the underrun strategy is set: if there is no buffer available, reuse
431  * the buffer from the other BAR and set the CF_SINGLE_BUFFER flag to
432  * keep the interrupt handler from giving that buffer back to user
433  * space.  In this way, we always have a buffer to DMA to and don't
434  * have to try to play games stopping and restarting the controller.
435  */
436 static void mcam_set_contig_buffer(struct mcam_camera *cam, int frame)
437 {
438         struct mcam_vb_buffer *buf;
439         /*
440          * If there are no available buffers, go into single mode
441          */
442         if (list_empty(&cam->buffers)) {
443                 buf = cam->vb_bufs[frame ^ 0x1];
444                 cam->vb_bufs[frame] = buf;
445                 mcam_reg_write(cam, frame == 0 ? REG_Y0BAR : REG_Y1BAR,
446                                 vb2_dma_contig_plane_dma_addr(&buf->vb_buf, 0));
447                 set_bit(CF_SINGLE_BUFFER, &cam->flags);
448                 cam->frame_state.singles++;
449                 return;
450         }
451         /*
452          * OK, we have a buffer we can use.
453          */
454         buf = list_first_entry(&cam->buffers, struct mcam_vb_buffer, queue);
455         list_del_init(&buf->queue);
456         mcam_reg_write(cam, frame == 0 ? REG_Y0BAR : REG_Y1BAR,
457                         vb2_dma_contig_plane_dma_addr(&buf->vb_buf, 0));
458         cam->vb_bufs[frame] = buf;
459         clear_bit(CF_SINGLE_BUFFER, &cam->flags);
460 }
461
462 /*
463  * Initial B_DMA_contig setup.
464  */
465 static void mcam_ctlr_dma_contig(struct mcam_camera *cam)
466 {
467         mcam_reg_set_bit(cam, REG_CTRL1, C1_TWOBUFS);
468         cam->nbufs = 2;
469         mcam_set_contig_buffer(cam, 0);
470         mcam_set_contig_buffer(cam, 1);
471 }
472
473 /*
474  * Frame completion handling.
475  */
476 static void mcam_dma_contig_done(struct mcam_camera *cam, int frame)
477 {
478         struct mcam_vb_buffer *buf = cam->vb_bufs[frame];
479
480         if (!test_bit(CF_SINGLE_BUFFER, &cam->flags)) {
481                 cam->frame_state.delivered++;
482                 mcam_buffer_done(cam, frame, &buf->vb_buf);
483         }
484         mcam_set_contig_buffer(cam, frame);
485 }
486
487 #endif /* MCAM_MODE_DMA_CONTIG */
488
489 #ifdef MCAM_MODE_DMA_SG
490 /* ---------------------------------------------------------------------- */
491 /*
492  * Scatter/gather-specific code.
493  */
494
495 /*
496  * Set up the next buffer for S/G I/O; caller should be sure that
497  * the controller is stopped and a buffer is available.
498  */
499 static void mcam_sg_next_buffer(struct mcam_camera *cam)
500 {
501         struct mcam_vb_buffer *buf;
502
503         buf = list_first_entry(&cam->buffers, struct mcam_vb_buffer, queue);
504         list_del_init(&buf->queue);
505         /*
506          * Very Bad Not Good Things happen if you don't clear
507          * C1_DESC_ENA before making any descriptor changes.
508          */
509         mcam_reg_clear_bit(cam, REG_CTRL1, C1_DESC_ENA);
510         mcam_reg_write(cam, REG_DMA_DESC_Y, buf->dma_desc_pa);
511         mcam_reg_write(cam, REG_DESC_LEN_Y,
512                         buf->dma_desc_nent*sizeof(struct mcam_dma_desc));
513         mcam_reg_write(cam, REG_DESC_LEN_U, 0);
514         mcam_reg_write(cam, REG_DESC_LEN_V, 0);
515         mcam_reg_set_bit(cam, REG_CTRL1, C1_DESC_ENA);
516         cam->vb_bufs[0] = buf;
517 }
518
519 /*
520  * Initial B_DMA_sg setup
521  */
522 static void mcam_ctlr_dma_sg(struct mcam_camera *cam)
523 {
524         /*
525          * The list-empty condition can hit us at resume time
526          * if the buffer list was empty when the system was suspended.
527          */
528         if (list_empty(&cam->buffers)) {
529                 set_bit(CF_SG_RESTART, &cam->flags);
530                 return;
531         }
532
533         mcam_reg_clear_bit(cam, REG_CTRL1, C1_DESC_3WORD);
534         mcam_sg_next_buffer(cam);
535         cam->nbufs = 3;
536 }
537
538
539 /*
540  * Frame completion with S/G is trickier.  We can't muck with
541  * a descriptor chain on the fly, since the controller buffers it
542  * internally.  So we have to actually stop and restart; Marvell
543  * says this is the way to do it.
544  *
545  * Of course, stopping is easier said than done; experience shows
546  * that the controller can start a frame *after* C0_ENABLE has been
547  * cleared.  So when running in S/G mode, the controller is "stopped"
548  * on receipt of the start-of-frame interrupt.  That means we can
549  * safely change the DMA descriptor array here and restart things
550  * (assuming there's another buffer waiting to go).
551  */
552 static void mcam_dma_sg_done(struct mcam_camera *cam, int frame)
553 {
554         struct mcam_vb_buffer *buf = cam->vb_bufs[0];
555
556         /*
557          * If we're no longer supposed to be streaming, don't do anything.
558          */
559         if (cam->state != S_STREAMING)
560                 return;
561         /*
562          * If we have another buffer available, put it in and
563          * restart the engine.
564          */
565         if (!list_empty(&cam->buffers)) {
566                 mcam_sg_next_buffer(cam);
567                 mcam_ctlr_start(cam);
568         /*
569          * Otherwise set CF_SG_RESTART and the controller will
570          * be restarted once another buffer shows up.
571          */
572         } else {
573                 set_bit(CF_SG_RESTART, &cam->flags);
574                 cam->frame_state.singles++;
575                 cam->vb_bufs[0] = NULL;
576         }
577         /*
578          * Now we can give the completed frame back to user space.
579          */
580         cam->frame_state.delivered++;
581         mcam_buffer_done(cam, frame, &buf->vb_buf);
582 }
583
584
585 /*
586  * Scatter/gather mode requires stopping the controller between
587  * frames so we can put in a new DMA descriptor array.  If no new
588  * buffer exists at frame completion, the controller is left stopped;
589  * this function is charged with gettig things going again.
590  */
591 static void mcam_sg_restart(struct mcam_camera *cam)
592 {
593         mcam_ctlr_dma_sg(cam);
594         mcam_ctlr_start(cam);
595         clear_bit(CF_SG_RESTART, &cam->flags);
596 }
597
598 #else /* MCAM_MODE_DMA_SG */
599
600 static inline void mcam_sg_restart(struct mcam_camera *cam)
601 {
602         return;
603 }
604
605 #endif /* MCAM_MODE_DMA_SG */
606
607 /* ---------------------------------------------------------------------- */
608 /*
609  * Buffer-mode-independent controller code.
610  */
611
612 /*
613  * Image format setup
614  */
615 static void mcam_ctlr_image(struct mcam_camera *cam)
616 {
617         int imgsz;
618         struct v4l2_pix_format *fmt = &cam->pix_format;
619
620         imgsz = ((fmt->height << IMGSZ_V_SHIFT) & IMGSZ_V_MASK) |
621                 (fmt->bytesperline & IMGSZ_H_MASK);
622         mcam_reg_write(cam, REG_IMGSIZE, imgsz);
623         mcam_reg_write(cam, REG_IMGOFFSET, 0);
624         /* YPITCH just drops the last two bits */
625         mcam_reg_write_mask(cam, REG_IMGPITCH, fmt->bytesperline,
626                         IMGP_YP_MASK);
627         /*
628          * Tell the controller about the image format we are using.
629          */
630         switch (cam->pix_format.pixelformat) {
631         case V4L2_PIX_FMT_YUYV:
632             mcam_reg_write_mask(cam, REG_CTRL0,
633                             C0_DF_YUV|C0_YUV_PACKED|C0_YUVE_YUYV,
634                             C0_DF_MASK);
635             break;
636
637         case V4L2_PIX_FMT_RGB444:
638             mcam_reg_write_mask(cam, REG_CTRL0,
639                             C0_DF_RGB|C0_RGBF_444|C0_RGB4_XRGB,
640                             C0_DF_MASK);
641                 /* Alpha value? */
642             break;
643
644         case V4L2_PIX_FMT_RGB565:
645             mcam_reg_write_mask(cam, REG_CTRL0,
646                             C0_DF_RGB|C0_RGBF_565|C0_RGB5_BGGR,
647                             C0_DF_MASK);
648             break;
649
650         default:
651             cam_err(cam, "Unknown format %x\n", cam->pix_format.pixelformat);
652             break;
653         }
654         /*
655          * Make sure it knows we want to use hsync/vsync.
656          */
657         mcam_reg_write_mask(cam, REG_CTRL0, C0_SIF_HVSYNC,
658                         C0_SIFM_MASK);
659 }
660
661
662 /*
663  * Configure the controller for operation; caller holds the
664  * device mutex.
665  */
666 static int mcam_ctlr_configure(struct mcam_camera *cam)
667 {
668         unsigned long flags;
669
670         spin_lock_irqsave(&cam->dev_lock, flags);
671         clear_bit(CF_SG_RESTART, &cam->flags);
672         cam->dma_setup(cam);
673         mcam_ctlr_image(cam);
674         mcam_set_config_needed(cam, 0);
675         spin_unlock_irqrestore(&cam->dev_lock, flags);
676         return 0;
677 }
678
679 static void mcam_ctlr_irq_enable(struct mcam_camera *cam)
680 {
681         /*
682          * Clear any pending interrupts, since we do not
683          * expect to have I/O active prior to enabling.
684          */
685         mcam_reg_write(cam, REG_IRQSTAT, FRAMEIRQS);
686         mcam_reg_set_bit(cam, REG_IRQMASK, FRAMEIRQS);
687 }
688
689 static void mcam_ctlr_irq_disable(struct mcam_camera *cam)
690 {
691         mcam_reg_clear_bit(cam, REG_IRQMASK, FRAMEIRQS);
692 }
693
694
695
696 static void mcam_ctlr_init(struct mcam_camera *cam)
697 {
698         unsigned long flags;
699
700         spin_lock_irqsave(&cam->dev_lock, flags);
701         /*
702          * Make sure it's not powered down.
703          */
704         mcam_reg_clear_bit(cam, REG_CTRL1, C1_PWRDWN);
705         /*
706          * Turn off the enable bit.  It sure should be off anyway,
707          * but it's good to be sure.
708          */
709         mcam_reg_clear_bit(cam, REG_CTRL0, C0_ENABLE);
710         /*
711          * Clock the sensor appropriately.  Controller clock should
712          * be 48MHz, sensor "typical" value is half that.
713          */
714         mcam_reg_write_mask(cam, REG_CLKCTRL, 2, CLK_DIV_MASK);
715         spin_unlock_irqrestore(&cam->dev_lock, flags);
716 }
717
718
719 /*
720  * Stop the controller, and don't return until we're really sure that no
721  * further DMA is going on.
722  */
723 static void mcam_ctlr_stop_dma(struct mcam_camera *cam)
724 {
725         unsigned long flags;
726
727         /*
728          * Theory: stop the camera controller (whether it is operating
729          * or not).  Delay briefly just in case we race with the SOF
730          * interrupt, then wait until no DMA is active.
731          */
732         spin_lock_irqsave(&cam->dev_lock, flags);
733         clear_bit(CF_SG_RESTART, &cam->flags);
734         mcam_ctlr_stop(cam);
735         cam->state = S_IDLE;
736         spin_unlock_irqrestore(&cam->dev_lock, flags);
737         /*
738          * This is a brutally long sleep, but experience shows that
739          * it can take the controller a while to get the message that
740          * it needs to stop grabbing frames.  In particular, we can
741          * sometimes (on mmp) get a frame at the end WITHOUT the
742          * start-of-frame indication.
743          */
744         msleep(150);
745         if (test_bit(CF_DMA_ACTIVE, &cam->flags))
746                 cam_err(cam, "Timeout waiting for DMA to end\n");
747                 /* This would be bad news - what now? */
748         spin_lock_irqsave(&cam->dev_lock, flags);
749         mcam_ctlr_irq_disable(cam);
750         spin_unlock_irqrestore(&cam->dev_lock, flags);
751 }
752
753 /*
754  * Power up and down.
755  */
756 static void mcam_ctlr_power_up(struct mcam_camera *cam)
757 {
758         unsigned long flags;
759
760         spin_lock_irqsave(&cam->dev_lock, flags);
761         cam->plat_power_up(cam);
762         mcam_reg_clear_bit(cam, REG_CTRL1, C1_PWRDWN);
763         spin_unlock_irqrestore(&cam->dev_lock, flags);
764         msleep(5); /* Just to be sure */
765 }
766
767 static void mcam_ctlr_power_down(struct mcam_camera *cam)
768 {
769         unsigned long flags;
770
771         spin_lock_irqsave(&cam->dev_lock, flags);
772         /*
773          * School of hard knocks department: be sure we do any register
774          * twiddling on the controller *before* calling the platform
775          * power down routine.
776          */
777         mcam_reg_set_bit(cam, REG_CTRL1, C1_PWRDWN);
778         cam->plat_power_down(cam);
779         spin_unlock_irqrestore(&cam->dev_lock, flags);
780 }
781
782 /* -------------------------------------------------------------------- */
783 /*
784  * Communications with the sensor.
785  */
786
787 static int __mcam_cam_reset(struct mcam_camera *cam)
788 {
789         return sensor_call(cam, core, reset, 0);
790 }
791
792 /*
793  * We have found the sensor on the i2c.  Let's try to have a
794  * conversation.
795  */
796 static int mcam_cam_init(struct mcam_camera *cam)
797 {
798         struct v4l2_dbg_chip_ident chip;
799         int ret;
800
801         mutex_lock(&cam->s_mutex);
802         if (cam->state != S_NOTREADY)
803                 cam_warn(cam, "Cam init with device in funky state %d",
804                                 cam->state);
805         ret = __mcam_cam_reset(cam);
806         if (ret)
807                 goto out;
808         chip.ident = V4L2_IDENT_NONE;
809         chip.match.type = V4L2_CHIP_MATCH_I2C_ADDR;
810         chip.match.addr = cam->sensor_addr;
811         ret = sensor_call(cam, core, g_chip_ident, &chip);
812         if (ret)
813                 goto out;
814         cam->sensor_type = chip.ident;
815         if (cam->sensor_type != V4L2_IDENT_OV7670) {
816                 cam_err(cam, "Unsupported sensor type 0x%x", cam->sensor_type);
817                 ret = -EINVAL;
818                 goto out;
819         }
820 /* Get/set parameters? */
821         ret = 0;
822         cam->state = S_IDLE;
823 out:
824         mcam_ctlr_power_down(cam);
825         mutex_unlock(&cam->s_mutex);
826         return ret;
827 }
828
829 /*
830  * Configure the sensor to match the parameters we have.  Caller should
831  * hold s_mutex
832  */
833 static int mcam_cam_set_flip(struct mcam_camera *cam)
834 {
835         struct v4l2_control ctrl;
836
837         memset(&ctrl, 0, sizeof(ctrl));
838         ctrl.id = V4L2_CID_VFLIP;
839         ctrl.value = flip;
840         return sensor_call(cam, core, s_ctrl, &ctrl);
841 }
842
843
844 static int mcam_cam_configure(struct mcam_camera *cam)
845 {
846         struct v4l2_mbus_framefmt mbus_fmt;
847         int ret;
848
849         v4l2_fill_mbus_format(&mbus_fmt, &cam->pix_format, cam->mbus_code);
850         ret = sensor_call(cam, core, init, 0);
851         if (ret == 0)
852                 ret = sensor_call(cam, video, s_mbus_fmt, &mbus_fmt);
853         /*
854          * OV7670 does weird things if flip is set *before* format...
855          */
856         ret += mcam_cam_set_flip(cam);
857         return ret;
858 }
859
860 /*
861  * Get everything ready, and start grabbing frames.
862  */
863 static int mcam_read_setup(struct mcam_camera *cam)
864 {
865         int ret;
866         unsigned long flags;
867
868         /*
869          * Configuration.  If we still don't have DMA buffers,
870          * make one last, desperate attempt.
871          */
872         if (cam->buffer_mode == B_vmalloc && cam->nbufs == 0 &&
873                         mcam_alloc_dma_bufs(cam, 0))
874                 return -ENOMEM;
875
876         if (mcam_needs_config(cam)) {
877                 mcam_cam_configure(cam);
878                 ret = mcam_ctlr_configure(cam);
879                 if (ret)
880                         return ret;
881         }
882
883         /*
884          * Turn it loose.
885          */
886         spin_lock_irqsave(&cam->dev_lock, flags);
887         clear_bit(CF_DMA_ACTIVE, &cam->flags);
888         mcam_reset_buffers(cam);
889         mcam_ctlr_irq_enable(cam);
890         cam->state = S_STREAMING;
891         if (!test_bit(CF_SG_RESTART, &cam->flags))
892                 mcam_ctlr_start(cam);
893         spin_unlock_irqrestore(&cam->dev_lock, flags);
894         return 0;
895 }
896
897 /* ----------------------------------------------------------------------- */
898 /*
899  * Videobuf2 interface code.
900  */
901
902 static int mcam_vb_queue_setup(struct vb2_queue *vq,
903                 const struct v4l2_format *fmt, unsigned int *nbufs,
904                 unsigned int *num_planes, unsigned int sizes[],
905                 void *alloc_ctxs[])
906 {
907         struct mcam_camera *cam = vb2_get_drv_priv(vq);
908         int minbufs = (cam->buffer_mode == B_DMA_contig) ? 3 : 2;
909
910         sizes[0] = cam->pix_format.sizeimage;
911         *num_planes = 1; /* Someday we have to support planar formats... */
912         if (*nbufs < minbufs)
913                 *nbufs = minbufs;
914         if (cam->buffer_mode == B_DMA_contig)
915                 alloc_ctxs[0] = cam->vb_alloc_ctx;
916         return 0;
917 }
918
919
920 static void mcam_vb_buf_queue(struct vb2_buffer *vb)
921 {
922         struct mcam_vb_buffer *mvb = vb_to_mvb(vb);
923         struct mcam_camera *cam = vb2_get_drv_priv(vb->vb2_queue);
924         unsigned long flags;
925         int start;
926
927         spin_lock_irqsave(&cam->dev_lock, flags);
928         start = (cam->state == S_BUFWAIT) && !list_empty(&cam->buffers);
929         list_add(&mvb->queue, &cam->buffers);
930         if (cam->state == S_STREAMING && test_bit(CF_SG_RESTART, &cam->flags))
931                 mcam_sg_restart(cam);
932         spin_unlock_irqrestore(&cam->dev_lock, flags);
933         if (start)
934                 mcam_read_setup(cam);
935 }
936
937
938 /*
939  * vb2 uses these to release the mutex when waiting in dqbuf.  I'm
940  * not actually sure we need to do this (I'm not sure that vb2_dqbuf() needs
941  * to be called with the mutex held), but better safe than sorry.
942  */
943 static void mcam_vb_wait_prepare(struct vb2_queue *vq)
944 {
945         struct mcam_camera *cam = vb2_get_drv_priv(vq);
946
947         mutex_unlock(&cam->s_mutex);
948 }
949
950 static void mcam_vb_wait_finish(struct vb2_queue *vq)
951 {
952         struct mcam_camera *cam = vb2_get_drv_priv(vq);
953
954         mutex_lock(&cam->s_mutex);
955 }
956
957 /*
958  * These need to be called with the mutex held from vb2
959  */
960 static int mcam_vb_start_streaming(struct vb2_queue *vq, unsigned int count)
961 {
962         struct mcam_camera *cam = vb2_get_drv_priv(vq);
963
964         if (cam->state != S_IDLE) {
965                 INIT_LIST_HEAD(&cam->buffers);
966                 return -EINVAL;
967         }
968         cam->sequence = 0;
969         /*
970          * Videobuf2 sneakily hoards all the buffers and won't
971          * give them to us until *after* streaming starts.  But
972          * we can't actually start streaming until we have a
973          * destination.  So go into a wait state and hope they
974          * give us buffers soon.
975          */
976         if (cam->buffer_mode != B_vmalloc && list_empty(&cam->buffers)) {
977                 cam->state = S_BUFWAIT;
978                 return 0;
979         }
980         return mcam_read_setup(cam);
981 }
982
983 static int mcam_vb_stop_streaming(struct vb2_queue *vq)
984 {
985         struct mcam_camera *cam = vb2_get_drv_priv(vq);
986         unsigned long flags;
987
988         if (cam->state == S_BUFWAIT) {
989                 /* They never gave us buffers */
990                 cam->state = S_IDLE;
991                 return 0;
992         }
993         if (cam->state != S_STREAMING)
994                 return -EINVAL;
995         mcam_ctlr_stop_dma(cam);
996         /*
997          * VB2 reclaims the buffers, so we need to forget
998          * about them.
999          */
1000         spin_lock_irqsave(&cam->dev_lock, flags);
1001         INIT_LIST_HEAD(&cam->buffers);
1002         spin_unlock_irqrestore(&cam->dev_lock, flags);
1003         return 0;
1004 }
1005
1006
1007 static const struct vb2_ops mcam_vb2_ops = {
1008         .queue_setup            = mcam_vb_queue_setup,
1009         .buf_queue              = mcam_vb_buf_queue,
1010         .start_streaming        = mcam_vb_start_streaming,
1011         .stop_streaming         = mcam_vb_stop_streaming,
1012         .wait_prepare           = mcam_vb_wait_prepare,
1013         .wait_finish            = mcam_vb_wait_finish,
1014 };
1015
1016
1017 #ifdef MCAM_MODE_DMA_SG
1018 /*
1019  * Scatter/gather mode uses all of the above functions plus a
1020  * few extras to deal with DMA mapping.
1021  */
1022 static int mcam_vb_sg_buf_init(struct vb2_buffer *vb)
1023 {
1024         struct mcam_vb_buffer *mvb = vb_to_mvb(vb);
1025         struct mcam_camera *cam = vb2_get_drv_priv(vb->vb2_queue);
1026         int ndesc = cam->pix_format.sizeimage/PAGE_SIZE + 1;
1027
1028         mvb->dma_desc = dma_alloc_coherent(cam->dev,
1029                         ndesc * sizeof(struct mcam_dma_desc),
1030                         &mvb->dma_desc_pa, GFP_KERNEL);
1031         if (mvb->dma_desc == NULL) {
1032                 cam_err(cam, "Unable to get DMA descriptor array\n");
1033                 return -ENOMEM;
1034         }
1035         return 0;
1036 }
1037
1038 static int mcam_vb_sg_buf_prepare(struct vb2_buffer *vb)
1039 {
1040         struct mcam_vb_buffer *mvb = vb_to_mvb(vb);
1041         struct mcam_camera *cam = vb2_get_drv_priv(vb->vb2_queue);
1042         struct vb2_dma_sg_desc *sgd = vb2_dma_sg_plane_desc(vb, 0);
1043         struct mcam_dma_desc *desc = mvb->dma_desc;
1044         struct scatterlist *sg;
1045         int i;
1046
1047         mvb->dma_desc_nent = dma_map_sg(cam->dev, sgd->sglist, sgd->num_pages,
1048                         DMA_FROM_DEVICE);
1049         if (mvb->dma_desc_nent <= 0)
1050                 return -EIO;  /* Not sure what's right here */
1051         for_each_sg(sgd->sglist, sg, mvb->dma_desc_nent, i) {
1052                 desc->dma_addr = sg_dma_address(sg);
1053                 desc->segment_len = sg_dma_len(sg);
1054                 desc++;
1055         }
1056         return 0;
1057 }
1058
1059 static int mcam_vb_sg_buf_finish(struct vb2_buffer *vb)
1060 {
1061         struct mcam_camera *cam = vb2_get_drv_priv(vb->vb2_queue);
1062         struct vb2_dma_sg_desc *sgd = vb2_dma_sg_plane_desc(vb, 0);
1063
1064         dma_unmap_sg(cam->dev, sgd->sglist, sgd->num_pages, DMA_FROM_DEVICE);
1065         return 0;
1066 }
1067
1068 static void mcam_vb_sg_buf_cleanup(struct vb2_buffer *vb)
1069 {
1070         struct mcam_camera *cam = vb2_get_drv_priv(vb->vb2_queue);
1071         struct mcam_vb_buffer *mvb = vb_to_mvb(vb);
1072         int ndesc = cam->pix_format.sizeimage/PAGE_SIZE + 1;
1073
1074         dma_free_coherent(cam->dev, ndesc * sizeof(struct mcam_dma_desc),
1075                         mvb->dma_desc, mvb->dma_desc_pa);
1076 }
1077
1078
1079 static const struct vb2_ops mcam_vb2_sg_ops = {
1080         .queue_setup            = mcam_vb_queue_setup,
1081         .buf_init               = mcam_vb_sg_buf_init,
1082         .buf_prepare            = mcam_vb_sg_buf_prepare,
1083         .buf_queue              = mcam_vb_buf_queue,
1084         .buf_finish             = mcam_vb_sg_buf_finish,
1085         .buf_cleanup            = mcam_vb_sg_buf_cleanup,
1086         .start_streaming        = mcam_vb_start_streaming,
1087         .stop_streaming         = mcam_vb_stop_streaming,
1088         .wait_prepare           = mcam_vb_wait_prepare,
1089         .wait_finish            = mcam_vb_wait_finish,
1090 };
1091
1092 #endif /* MCAM_MODE_DMA_SG */
1093
1094 static int mcam_setup_vb2(struct mcam_camera *cam)
1095 {
1096         struct vb2_queue *vq = &cam->vb_queue;
1097
1098         memset(vq, 0, sizeof(*vq));
1099         vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1100         vq->drv_priv = cam;
1101         INIT_LIST_HEAD(&cam->buffers);
1102         switch (cam->buffer_mode) {
1103         case B_DMA_contig:
1104 #ifdef MCAM_MODE_DMA_CONTIG
1105                 vq->ops = &mcam_vb2_ops;
1106                 vq->mem_ops = &vb2_dma_contig_memops;
1107                 cam->vb_alloc_ctx = vb2_dma_contig_init_ctx(cam->dev);
1108                 vq->io_modes = VB2_MMAP | VB2_USERPTR;
1109                 cam->dma_setup = mcam_ctlr_dma_contig;
1110                 cam->frame_complete = mcam_dma_contig_done;
1111 #endif
1112                 break;
1113         case B_DMA_sg:
1114 #ifdef MCAM_MODE_DMA_SG
1115                 vq->ops = &mcam_vb2_sg_ops;
1116                 vq->mem_ops = &vb2_dma_sg_memops;
1117                 vq->io_modes = VB2_MMAP | VB2_USERPTR;
1118                 cam->dma_setup = mcam_ctlr_dma_sg;
1119                 cam->frame_complete = mcam_dma_sg_done;
1120 #endif
1121                 break;
1122         case B_vmalloc:
1123 #ifdef MCAM_MODE_VMALLOC
1124                 tasklet_init(&cam->s_tasklet, mcam_frame_tasklet,
1125                                 (unsigned long) cam);
1126                 vq->ops = &mcam_vb2_ops;
1127                 vq->mem_ops = &vb2_vmalloc_memops;
1128                 vq->buf_struct_size = sizeof(struct mcam_vb_buffer);
1129                 vq->io_modes = VB2_MMAP;
1130                 cam->dma_setup = mcam_ctlr_dma_vmalloc;
1131                 cam->frame_complete = mcam_vmalloc_done;
1132 #endif
1133                 break;
1134         }
1135         return vb2_queue_init(vq);
1136 }
1137
1138 static void mcam_cleanup_vb2(struct mcam_camera *cam)
1139 {
1140         vb2_queue_release(&cam->vb_queue);
1141 #ifdef MCAM_MODE_DMA_CONTIG
1142         if (cam->buffer_mode == B_DMA_contig)
1143                 vb2_dma_contig_cleanup_ctx(cam->vb_alloc_ctx);
1144 #endif
1145 }
1146
1147
1148 /* ---------------------------------------------------------------------- */
1149 /*
1150  * The long list of V4L2 ioctl() operations.
1151  */
1152
1153 static int mcam_vidioc_streamon(struct file *filp, void *priv,
1154                 enum v4l2_buf_type type)
1155 {
1156         struct mcam_camera *cam = filp->private_data;
1157         int ret;
1158
1159         mutex_lock(&cam->s_mutex);
1160         ret = vb2_streamon(&cam->vb_queue, type);
1161         mutex_unlock(&cam->s_mutex);
1162         return ret;
1163 }
1164
1165
1166 static int mcam_vidioc_streamoff(struct file *filp, void *priv,
1167                 enum v4l2_buf_type type)
1168 {
1169         struct mcam_camera *cam = filp->private_data;
1170         int ret;
1171
1172         mutex_lock(&cam->s_mutex);
1173         ret = vb2_streamoff(&cam->vb_queue, type);
1174         mutex_unlock(&cam->s_mutex);
1175         return ret;
1176 }
1177
1178
1179 static int mcam_vidioc_reqbufs(struct file *filp, void *priv,
1180                 struct v4l2_requestbuffers *req)
1181 {
1182         struct mcam_camera *cam = filp->private_data;
1183         int ret;
1184
1185         mutex_lock(&cam->s_mutex);
1186         ret = vb2_reqbufs(&cam->vb_queue, req);
1187         mutex_unlock(&cam->s_mutex);
1188         return ret;
1189 }
1190
1191
1192 static int mcam_vidioc_querybuf(struct file *filp, void *priv,
1193                 struct v4l2_buffer *buf)
1194 {
1195         struct mcam_camera *cam = filp->private_data;
1196         int ret;
1197
1198         mutex_lock(&cam->s_mutex);
1199         ret = vb2_querybuf(&cam->vb_queue, buf);
1200         mutex_unlock(&cam->s_mutex);
1201         return ret;
1202 }
1203
1204 static int mcam_vidioc_qbuf(struct file *filp, void *priv,
1205                 struct v4l2_buffer *buf)
1206 {
1207         struct mcam_camera *cam = filp->private_data;
1208         int ret;
1209
1210         mutex_lock(&cam->s_mutex);
1211         ret = vb2_qbuf(&cam->vb_queue, buf);
1212         mutex_unlock(&cam->s_mutex);
1213         return ret;
1214 }
1215
1216 static int mcam_vidioc_dqbuf(struct file *filp, void *priv,
1217                 struct v4l2_buffer *buf)
1218 {
1219         struct mcam_camera *cam = filp->private_data;
1220         int ret;
1221
1222         mutex_lock(&cam->s_mutex);
1223         ret = vb2_dqbuf(&cam->vb_queue, buf, filp->f_flags & O_NONBLOCK);
1224         mutex_unlock(&cam->s_mutex);
1225         return ret;
1226 }
1227
1228
1229
1230 static int mcam_vidioc_queryctrl(struct file *filp, void *priv,
1231                 struct v4l2_queryctrl *qc)
1232 {
1233         struct mcam_camera *cam = priv;
1234         int ret;
1235
1236         mutex_lock(&cam->s_mutex);
1237         ret = sensor_call(cam, core, queryctrl, qc);
1238         mutex_unlock(&cam->s_mutex);
1239         return ret;
1240 }
1241
1242
1243 static int mcam_vidioc_g_ctrl(struct file *filp, void *priv,
1244                 struct v4l2_control *ctrl)
1245 {
1246         struct mcam_camera *cam = priv;
1247         int ret;
1248
1249         mutex_lock(&cam->s_mutex);
1250         ret = sensor_call(cam, core, g_ctrl, ctrl);
1251         mutex_unlock(&cam->s_mutex);
1252         return ret;
1253 }
1254
1255
1256 static int mcam_vidioc_s_ctrl(struct file *filp, void *priv,
1257                 struct v4l2_control *ctrl)
1258 {
1259         struct mcam_camera *cam = priv;
1260         int ret;
1261
1262         mutex_lock(&cam->s_mutex);
1263         ret = sensor_call(cam, core, s_ctrl, ctrl);
1264         mutex_unlock(&cam->s_mutex);
1265         return ret;
1266 }
1267
1268
1269 static int mcam_vidioc_querycap(struct file *file, void *priv,
1270                 struct v4l2_capability *cap)
1271 {
1272         strcpy(cap->driver, "marvell_ccic");
1273         strcpy(cap->card, "marvell_ccic");
1274         cap->version = 1;
1275         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
1276                 V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1277         return 0;
1278 }
1279
1280
1281 static int mcam_vidioc_enum_fmt_vid_cap(struct file *filp,
1282                 void *priv, struct v4l2_fmtdesc *fmt)
1283 {
1284         if (fmt->index >= N_MCAM_FMTS)
1285                 return -EINVAL;
1286         strlcpy(fmt->description, mcam_formats[fmt->index].desc,
1287                         sizeof(fmt->description));
1288         fmt->pixelformat = mcam_formats[fmt->index].pixelformat;
1289         return 0;
1290 }
1291
1292 static int mcam_vidioc_try_fmt_vid_cap(struct file *filp, void *priv,
1293                 struct v4l2_format *fmt)
1294 {
1295         struct mcam_camera *cam = priv;
1296         struct mcam_format_struct *f;
1297         struct v4l2_pix_format *pix = &fmt->fmt.pix;
1298         struct v4l2_mbus_framefmt mbus_fmt;
1299         int ret;
1300
1301         f = mcam_find_format(pix->pixelformat);
1302         pix->pixelformat = f->pixelformat;
1303         v4l2_fill_mbus_format(&mbus_fmt, pix, f->mbus_code);
1304         mutex_lock(&cam->s_mutex);
1305         ret = sensor_call(cam, video, try_mbus_fmt, &mbus_fmt);
1306         mutex_unlock(&cam->s_mutex);
1307         v4l2_fill_pix_format(pix, &mbus_fmt);
1308         pix->bytesperline = pix->width * f->bpp;
1309         pix->sizeimage = pix->height * pix->bytesperline;
1310         return ret;
1311 }
1312
1313 static int mcam_vidioc_s_fmt_vid_cap(struct file *filp, void *priv,
1314                 struct v4l2_format *fmt)
1315 {
1316         struct mcam_camera *cam = priv;
1317         struct mcam_format_struct *f;
1318         int ret;
1319
1320         /*
1321          * Can't do anything if the device is not idle
1322          * Also can't if there are streaming buffers in place.
1323          */
1324         if (cam->state != S_IDLE || cam->vb_queue.num_buffers > 0)
1325                 return -EBUSY;
1326
1327         f = mcam_find_format(fmt->fmt.pix.pixelformat);
1328
1329         /*
1330          * See if the formatting works in principle.
1331          */
1332         ret = mcam_vidioc_try_fmt_vid_cap(filp, priv, fmt);
1333         if (ret)
1334                 return ret;
1335         /*
1336          * Now we start to change things for real, so let's do it
1337          * under lock.
1338          */
1339         mutex_lock(&cam->s_mutex);
1340         cam->pix_format = fmt->fmt.pix;
1341         cam->mbus_code = f->mbus_code;
1342
1343         /*
1344          * Make sure we have appropriate DMA buffers.
1345          */
1346         if (cam->buffer_mode == B_vmalloc) {
1347                 ret = mcam_check_dma_buffers(cam);
1348                 if (ret)
1349                         goto out;
1350         }
1351         mcam_set_config_needed(cam, 1);
1352 out:
1353         mutex_unlock(&cam->s_mutex);
1354         return ret;
1355 }
1356
1357 /*
1358  * Return our stored notion of how the camera is/should be configured.
1359  * The V4l2 spec wants us to be smarter, and actually get this from
1360  * the camera (and not mess with it at open time).  Someday.
1361  */
1362 static int mcam_vidioc_g_fmt_vid_cap(struct file *filp, void *priv,
1363                 struct v4l2_format *f)
1364 {
1365         struct mcam_camera *cam = priv;
1366
1367         f->fmt.pix = cam->pix_format;
1368         return 0;
1369 }
1370
1371 /*
1372  * We only have one input - the sensor - so minimize the nonsense here.
1373  */
1374 static int mcam_vidioc_enum_input(struct file *filp, void *priv,
1375                 struct v4l2_input *input)
1376 {
1377         if (input->index != 0)
1378                 return -EINVAL;
1379
1380         input->type = V4L2_INPUT_TYPE_CAMERA;
1381         input->std = V4L2_STD_ALL; /* Not sure what should go here */
1382         strcpy(input->name, "Camera");
1383         return 0;
1384 }
1385
1386 static int mcam_vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
1387 {
1388         *i = 0;
1389         return 0;
1390 }
1391
1392 static int mcam_vidioc_s_input(struct file *filp, void *priv, unsigned int i)
1393 {
1394         if (i != 0)
1395                 return -EINVAL;
1396         return 0;
1397 }
1398
1399 /* from vivi.c */
1400 static int mcam_vidioc_s_std(struct file *filp, void *priv, v4l2_std_id *a)
1401 {
1402         return 0;
1403 }
1404
1405 /*
1406  * G/S_PARM.  Most of this is done by the sensor, but we are
1407  * the level which controls the number of read buffers.
1408  */
1409 static int mcam_vidioc_g_parm(struct file *filp, void *priv,
1410                 struct v4l2_streamparm *parms)
1411 {
1412         struct mcam_camera *cam = priv;
1413         int ret;
1414
1415         mutex_lock(&cam->s_mutex);
1416         ret = sensor_call(cam, video, g_parm, parms);
1417         mutex_unlock(&cam->s_mutex);
1418         parms->parm.capture.readbuffers = n_dma_bufs;
1419         return ret;
1420 }
1421
1422 static int mcam_vidioc_s_parm(struct file *filp, void *priv,
1423                 struct v4l2_streamparm *parms)
1424 {
1425         struct mcam_camera *cam = priv;
1426         int ret;
1427
1428         mutex_lock(&cam->s_mutex);
1429         ret = sensor_call(cam, video, s_parm, parms);
1430         mutex_unlock(&cam->s_mutex);
1431         parms->parm.capture.readbuffers = n_dma_bufs;
1432         return ret;
1433 }
1434
1435 static int mcam_vidioc_g_chip_ident(struct file *file, void *priv,
1436                 struct v4l2_dbg_chip_ident *chip)
1437 {
1438         struct mcam_camera *cam = priv;
1439
1440         chip->ident = V4L2_IDENT_NONE;
1441         chip->revision = 0;
1442         if (v4l2_chip_match_host(&chip->match)) {
1443                 chip->ident = cam->chip_id;
1444                 return 0;
1445         }
1446         return sensor_call(cam, core, g_chip_ident, chip);
1447 }
1448
1449 static int mcam_vidioc_enum_framesizes(struct file *filp, void *priv,
1450                 struct v4l2_frmsizeenum *sizes)
1451 {
1452         struct mcam_camera *cam = priv;
1453         int ret;
1454
1455         mutex_lock(&cam->s_mutex);
1456         ret = sensor_call(cam, video, enum_framesizes, sizes);
1457         mutex_unlock(&cam->s_mutex);
1458         return ret;
1459 }
1460
1461 static int mcam_vidioc_enum_frameintervals(struct file *filp, void *priv,
1462                 struct v4l2_frmivalenum *interval)
1463 {
1464         struct mcam_camera *cam = priv;
1465         int ret;
1466
1467         mutex_lock(&cam->s_mutex);
1468         ret = sensor_call(cam, video, enum_frameintervals, interval);
1469         mutex_unlock(&cam->s_mutex);
1470         return ret;
1471 }
1472
1473 #ifdef CONFIG_VIDEO_ADV_DEBUG
1474 static int mcam_vidioc_g_register(struct file *file, void *priv,
1475                 struct v4l2_dbg_register *reg)
1476 {
1477         struct mcam_camera *cam = priv;
1478
1479         if (v4l2_chip_match_host(&reg->match)) {
1480                 reg->val = mcam_reg_read(cam, reg->reg);
1481                 reg->size = 4;
1482                 return 0;
1483         }
1484         return sensor_call(cam, core, g_register, reg);
1485 }
1486
1487 static int mcam_vidioc_s_register(struct file *file, void *priv,
1488                 struct v4l2_dbg_register *reg)
1489 {
1490         struct mcam_camera *cam = priv;
1491
1492         if (v4l2_chip_match_host(&reg->match)) {
1493                 mcam_reg_write(cam, reg->reg, reg->val);
1494                 return 0;
1495         }
1496         return sensor_call(cam, core, s_register, reg);
1497 }
1498 #endif
1499
1500 static const struct v4l2_ioctl_ops mcam_v4l_ioctl_ops = {
1501         .vidioc_querycap        = mcam_vidioc_querycap,
1502         .vidioc_enum_fmt_vid_cap = mcam_vidioc_enum_fmt_vid_cap,
1503         .vidioc_try_fmt_vid_cap = mcam_vidioc_try_fmt_vid_cap,
1504         .vidioc_s_fmt_vid_cap   = mcam_vidioc_s_fmt_vid_cap,
1505         .vidioc_g_fmt_vid_cap   = mcam_vidioc_g_fmt_vid_cap,
1506         .vidioc_enum_input      = mcam_vidioc_enum_input,
1507         .vidioc_g_input         = mcam_vidioc_g_input,
1508         .vidioc_s_input         = mcam_vidioc_s_input,
1509         .vidioc_s_std           = mcam_vidioc_s_std,
1510         .vidioc_reqbufs         = mcam_vidioc_reqbufs,
1511         .vidioc_querybuf        = mcam_vidioc_querybuf,
1512         .vidioc_qbuf            = mcam_vidioc_qbuf,
1513         .vidioc_dqbuf           = mcam_vidioc_dqbuf,
1514         .vidioc_streamon        = mcam_vidioc_streamon,
1515         .vidioc_streamoff       = mcam_vidioc_streamoff,
1516         .vidioc_queryctrl       = mcam_vidioc_queryctrl,
1517         .vidioc_g_ctrl          = mcam_vidioc_g_ctrl,
1518         .vidioc_s_ctrl          = mcam_vidioc_s_ctrl,
1519         .vidioc_g_parm          = mcam_vidioc_g_parm,
1520         .vidioc_s_parm          = mcam_vidioc_s_parm,
1521         .vidioc_enum_framesizes = mcam_vidioc_enum_framesizes,
1522         .vidioc_enum_frameintervals = mcam_vidioc_enum_frameintervals,
1523         .vidioc_g_chip_ident    = mcam_vidioc_g_chip_ident,
1524 #ifdef CONFIG_VIDEO_ADV_DEBUG
1525         .vidioc_g_register      = mcam_vidioc_g_register,
1526         .vidioc_s_register      = mcam_vidioc_s_register,
1527 #endif
1528 };
1529
1530 /* ---------------------------------------------------------------------- */
1531 /*
1532  * Our various file operations.
1533  */
1534 static int mcam_v4l_open(struct file *filp)
1535 {
1536         struct mcam_camera *cam = video_drvdata(filp);
1537         int ret = 0;
1538
1539         filp->private_data = cam;
1540
1541         cam->frame_state.frames = 0;
1542         cam->frame_state.singles = 0;
1543         cam->frame_state.delivered = 0;
1544         mutex_lock(&cam->s_mutex);
1545         if (cam->users == 0) {
1546                 ret = mcam_setup_vb2(cam);
1547                 if (ret)
1548                         goto out;
1549                 mcam_ctlr_power_up(cam);
1550                 __mcam_cam_reset(cam);
1551                 mcam_set_config_needed(cam, 1);
1552         }
1553         (cam->users)++;
1554 out:
1555         mutex_unlock(&cam->s_mutex);
1556         return ret;
1557 }
1558
1559
1560 static int mcam_v4l_release(struct file *filp)
1561 {
1562         struct mcam_camera *cam = filp->private_data;
1563
1564         cam_dbg(cam, "Release, %d frames, %d singles, %d delivered\n",
1565                         cam->frame_state.frames, cam->frame_state.singles,
1566                         cam->frame_state.delivered);
1567         mutex_lock(&cam->s_mutex);
1568         (cam->users)--;
1569         if (cam->users == 0) {
1570                 mcam_ctlr_stop_dma(cam);
1571                 mcam_cleanup_vb2(cam);
1572                 mcam_ctlr_power_down(cam);
1573                 if (cam->buffer_mode == B_vmalloc && alloc_bufs_at_read)
1574                         mcam_free_dma_bufs(cam);
1575         }
1576         mutex_unlock(&cam->s_mutex);
1577         return 0;
1578 }
1579
1580 static ssize_t mcam_v4l_read(struct file *filp,
1581                 char __user *buffer, size_t len, loff_t *pos)
1582 {
1583         struct mcam_camera *cam = filp->private_data;
1584         int ret;
1585
1586         mutex_lock(&cam->s_mutex);
1587         ret = vb2_read(&cam->vb_queue, buffer, len, pos,
1588                         filp->f_flags & O_NONBLOCK);
1589         mutex_unlock(&cam->s_mutex);
1590         return ret;
1591 }
1592
1593
1594
1595 static unsigned int mcam_v4l_poll(struct file *filp,
1596                 struct poll_table_struct *pt)
1597 {
1598         struct mcam_camera *cam = filp->private_data;
1599         int ret;
1600
1601         mutex_lock(&cam->s_mutex);
1602         ret = vb2_poll(&cam->vb_queue, filp, pt);
1603         mutex_unlock(&cam->s_mutex);
1604         return ret;
1605 }
1606
1607
1608 static int mcam_v4l_mmap(struct file *filp, struct vm_area_struct *vma)
1609 {
1610         struct mcam_camera *cam = filp->private_data;
1611         int ret;
1612
1613         mutex_lock(&cam->s_mutex);
1614         ret = vb2_mmap(&cam->vb_queue, vma);
1615         mutex_unlock(&cam->s_mutex);
1616         return ret;
1617 }
1618
1619
1620
1621 static const struct v4l2_file_operations mcam_v4l_fops = {
1622         .owner = THIS_MODULE,
1623         .open = mcam_v4l_open,
1624         .release = mcam_v4l_release,
1625         .read = mcam_v4l_read,
1626         .poll = mcam_v4l_poll,
1627         .mmap = mcam_v4l_mmap,
1628         .unlocked_ioctl = video_ioctl2,
1629 };
1630
1631
1632 /*
1633  * This template device holds all of those v4l2 methods; we
1634  * clone it for specific real devices.
1635  */
1636 static struct video_device mcam_v4l_template = {
1637         .name = "mcam",
1638         .tvnorms = V4L2_STD_NTSC_M,
1639         .current_norm = V4L2_STD_NTSC_M,  /* make mplayer happy */
1640
1641         .fops = &mcam_v4l_fops,
1642         .ioctl_ops = &mcam_v4l_ioctl_ops,
1643         .release = video_device_release_empty,
1644 };
1645
1646 /* ---------------------------------------------------------------------- */
1647 /*
1648  * Interrupt handler stuff
1649  */
1650 static void mcam_frame_complete(struct mcam_camera *cam, int frame)
1651 {
1652         /*
1653          * Basic frame housekeeping.
1654          */
1655         set_bit(frame, &cam->flags);
1656         clear_bit(CF_DMA_ACTIVE, &cam->flags);
1657         cam->next_buf = frame;
1658         cam->buf_seq[frame] = ++(cam->sequence);
1659         cam->frame_state.frames++;
1660         /*
1661          * "This should never happen"
1662          */
1663         if (cam->state != S_STREAMING)
1664                 return;
1665         /*
1666          * Process the frame and set up the next one.
1667          */
1668         cam->frame_complete(cam, frame);
1669 }
1670
1671
1672 /*
1673  * The interrupt handler; this needs to be called from the
1674  * platform irq handler with the lock held.
1675  */
1676 int mccic_irq(struct mcam_camera *cam, unsigned int irqs)
1677 {
1678         unsigned int frame, handled = 0;
1679
1680         mcam_reg_write(cam, REG_IRQSTAT, FRAMEIRQS); /* Clear'em all */
1681         /*
1682          * Handle any frame completions.  There really should
1683          * not be more than one of these, or we have fallen
1684          * far behind.
1685          *
1686          * When running in S/G mode, the frame number lacks any
1687          * real meaning - there's only one descriptor array - but
1688          * the controller still picks a different one to signal
1689          * each time.
1690          */
1691         for (frame = 0; frame < cam->nbufs; frame++)
1692                 if (irqs & (IRQ_EOF0 << frame)) {
1693                         mcam_frame_complete(cam, frame);
1694                         handled = 1;
1695                         if (cam->buffer_mode == B_DMA_sg)
1696                                 break;
1697                 }
1698         /*
1699          * If a frame starts, note that we have DMA active.  This
1700          * code assumes that we won't get multiple frame interrupts
1701          * at once; may want to rethink that.
1702          */
1703         if (irqs & (IRQ_SOF0 | IRQ_SOF1 | IRQ_SOF2)) {
1704                 set_bit(CF_DMA_ACTIVE, &cam->flags);
1705                 handled = 1;
1706                 if (cam->buffer_mode == B_DMA_sg)
1707                         mcam_ctlr_stop(cam);
1708         }
1709         return handled;
1710 }
1711
1712 /* ---------------------------------------------------------------------- */
1713 /*
1714  * Registration and such.
1715  */
1716 static struct ov7670_config sensor_cfg = {
1717         /*
1718          * Exclude QCIF mode, because it only captures a tiny portion
1719          * of the sensor FOV
1720          */
1721         .min_width = 320,
1722         .min_height = 240,
1723 };
1724
1725
1726 int mccic_register(struct mcam_camera *cam)
1727 {
1728         struct i2c_board_info ov7670_info = {
1729                 .type = "ov7670",
1730                 .addr = 0x42 >> 1,
1731                 .platform_data = &sensor_cfg,
1732         };
1733         int ret;
1734
1735         /*
1736          * Validate the requested buffer mode.
1737          */
1738         if (buffer_mode >= 0)
1739                 cam->buffer_mode = buffer_mode;
1740         if (cam->buffer_mode == B_DMA_sg &&
1741                         cam->chip_id == V4L2_IDENT_CAFE) {
1742                 printk(KERN_ERR "marvell-cam: Cafe can't do S/G I/O, "
1743                         "attempting vmalloc mode instead\n");
1744                 cam->buffer_mode = B_vmalloc;
1745         }
1746         if (!mcam_buffer_mode_supported(cam->buffer_mode)) {
1747                 printk(KERN_ERR "marvell-cam: buffer mode %d unsupported\n",
1748                                 cam->buffer_mode);
1749                 return -EINVAL;
1750         }
1751         /*
1752          * Register with V4L
1753          */
1754         ret = v4l2_device_register(cam->dev, &cam->v4l2_dev);
1755         if (ret)
1756                 return ret;
1757
1758         mutex_init(&cam->s_mutex);
1759         cam->state = S_NOTREADY;
1760         mcam_set_config_needed(cam, 1);
1761         cam->pix_format = mcam_def_pix_format;
1762         cam->mbus_code = mcam_def_mbus_code;
1763         INIT_LIST_HEAD(&cam->buffers);
1764         mcam_ctlr_init(cam);
1765
1766         /*
1767          * Try to find the sensor.
1768          */
1769         sensor_cfg.clock_speed = cam->clock_speed;
1770         sensor_cfg.use_smbus = cam->use_smbus;
1771         cam->sensor_addr = ov7670_info.addr;
1772         cam->sensor = v4l2_i2c_new_subdev_board(&cam->v4l2_dev,
1773                         cam->i2c_adapter, &ov7670_info, NULL);
1774         if (cam->sensor == NULL) {
1775                 ret = -ENODEV;
1776                 goto out_unregister;
1777         }
1778
1779         ret = mcam_cam_init(cam);
1780         if (ret)
1781                 goto out_unregister;
1782         /*
1783          * Get the v4l2 setup done.
1784          */
1785         mutex_lock(&cam->s_mutex);
1786         cam->vdev = mcam_v4l_template;
1787         cam->vdev.debug = 0;
1788         cam->vdev.v4l2_dev = &cam->v4l2_dev;
1789         ret = video_register_device(&cam->vdev, VFL_TYPE_GRABBER, -1);
1790         if (ret)
1791                 goto out;
1792         video_set_drvdata(&cam->vdev, cam);
1793
1794         /*
1795          * If so requested, try to get our DMA buffers now.
1796          */
1797         if (cam->buffer_mode == B_vmalloc && !alloc_bufs_at_read) {
1798                 if (mcam_alloc_dma_bufs(cam, 1))
1799                         cam_warn(cam, "Unable to alloc DMA buffers at load"
1800                                         " will try again later.");
1801         }
1802
1803 out:
1804         mutex_unlock(&cam->s_mutex);
1805         return ret;
1806 out_unregister:
1807         v4l2_device_unregister(&cam->v4l2_dev);
1808         return ret;
1809 }
1810
1811
1812 void mccic_shutdown(struct mcam_camera *cam)
1813 {
1814         /*
1815          * If we have no users (and we really, really should have no
1816          * users) the device will already be powered down.  Trying to
1817          * take it down again will wedge the machine, which is frowned
1818          * upon.
1819          */
1820         if (cam->users > 0) {
1821                 cam_warn(cam, "Removing a device with users!\n");
1822                 mcam_ctlr_power_down(cam);
1823         }
1824         vb2_queue_release(&cam->vb_queue);
1825         if (cam->buffer_mode == B_vmalloc)
1826                 mcam_free_dma_bufs(cam);
1827         video_unregister_device(&cam->vdev);
1828         v4l2_device_unregister(&cam->v4l2_dev);
1829 }
1830
1831 /*
1832  * Power management
1833  */
1834 #ifdef CONFIG_PM
1835
1836 void mccic_suspend(struct mcam_camera *cam)
1837 {
1838         mutex_lock(&cam->s_mutex);
1839         if (cam->users > 0) {
1840                 enum mcam_state cstate = cam->state;
1841
1842                 mcam_ctlr_stop_dma(cam);
1843                 mcam_ctlr_power_down(cam);
1844                 cam->state = cstate;
1845         }
1846         mutex_unlock(&cam->s_mutex);
1847 }
1848
1849 int mccic_resume(struct mcam_camera *cam)
1850 {
1851         int ret = 0;
1852
1853         mutex_lock(&cam->s_mutex);
1854         if (cam->users > 0) {
1855                 mcam_ctlr_power_up(cam);
1856                 __mcam_cam_reset(cam);
1857         } else {
1858                 mcam_ctlr_power_down(cam);
1859         }
1860         mutex_unlock(&cam->s_mutex);
1861
1862         set_bit(CF_CONFIG_NEEDED, &cam->flags);
1863         if (cam->state == S_STREAMING) {
1864                 /*
1865                  * If there was a buffer in the DMA engine at suspend
1866                  * time, put it back on the queue or we'll forget about it.
1867                  */
1868                 if (cam->buffer_mode == B_DMA_sg && cam->vb_bufs[0])
1869                         list_add(&cam->vb_bufs[0]->queue, &cam->buffers);
1870                 ret = mcam_read_setup(cam);
1871         }
1872         return ret;
1873 }
1874 #endif /* CONFIG_PM */