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