V4L/DVB (11114): cafe_ccic: convert to v4l2_device.
[linux-2.6] / drivers / media / video / cafe_ccic.c
1 /*
2  * A driver for the CMOS camera controller in the Marvell 88ALP01 "cafe"
3  * multifunction chip.  Currently works with the Omnivision OV7670
4  * sensor.
5  *
6  * The data sheet for this device can be found at:
7  *    http://www.marvell.com/products/pcconn/88ALP01.jsp
8  *
9  * Copyright 2006 One Laptop Per Child Association, Inc.
10  * Copyright 2006-7 Jonathan Corbet <corbet@lwn.net>
11  *
12  * Written by Jonathan Corbet, corbet@lwn.net.
13  *
14  * This file may be distributed under the terms of the GNU General
15  * Public License, version 2.
16  */
17
18 #include <linux/kernel.h>
19 #include <linux/module.h>
20 #include <linux/init.h>
21 #include <linux/fs.h>
22 #include <linux/mm.h>
23 #include <linux/pci.h>
24 #include <linux/i2c.h>
25 #include <linux/interrupt.h>
26 #include <linux/spinlock.h>
27 #include <linux/videodev2.h>
28 #include <media/v4l2-device.h>
29 #include <media/v4l2-ioctl.h>
30 #include <media/v4l2-chip-ident.h>
31 #include <linux/device.h>
32 #include <linux/wait.h>
33 #include <linux/list.h>
34 #include <linux/dma-mapping.h>
35 #include <linux/delay.h>
36 #include <linux/debugfs.h>
37 #include <linux/jiffies.h>
38 #include <linux/vmalloc.h>
39
40 #include <asm/uaccess.h>
41 #include <asm/io.h>
42
43 #include "cafe_ccic-regs.h"
44
45 #define CAFE_VERSION 0x000002
46
47
48 /*
49  * Parameters.
50  */
51 MODULE_AUTHOR("Jonathan Corbet <corbet@lwn.net>");
52 MODULE_DESCRIPTION("Marvell 88ALP01 CMOS Camera Controller driver");
53 MODULE_LICENSE("GPL");
54 MODULE_SUPPORTED_DEVICE("Video");
55
56 /*
57  * Internal DMA buffer management.  Since the controller cannot do S/G I/O,
58  * we must have physically contiguous buffers to bring frames into.
59  * These parameters control how many buffers we use, whether we
60  * allocate them at load time (better chance of success, but nails down
61  * memory) or when somebody tries to use the camera (riskier), and,
62  * for load-time allocation, how big they should be.
63  *
64  * The controller can cycle through three buffers.  We could use
65  * more by flipping pointers around, but it probably makes little
66  * sense.
67  */
68
69 #define MAX_DMA_BUFS 3
70 static int alloc_bufs_at_read;
71 module_param(alloc_bufs_at_read, bool, 0444);
72 MODULE_PARM_DESC(alloc_bufs_at_read,
73                 "Non-zero value causes DMA buffers to be allocated when the "
74                 "video capture device is read, rather than at module load "
75                 "time.  This saves memory, but decreases the chances of "
76                 "successfully getting those buffers.");
77
78 static int n_dma_bufs = 3;
79 module_param(n_dma_bufs, uint, 0644);
80 MODULE_PARM_DESC(n_dma_bufs,
81                 "The number of DMA buffers to allocate.  Can be either two "
82                 "(saves memory, makes timing tighter) or three.");
83
84 static int dma_buf_size = VGA_WIDTH * VGA_HEIGHT * 2;  /* Worst case */
85 module_param(dma_buf_size, uint, 0444);
86 MODULE_PARM_DESC(dma_buf_size,
87                 "The size of the allocated DMA buffers.  If actual operating "
88                 "parameters require larger buffers, an attempt to reallocate "
89                 "will be made.");
90
91 static int min_buffers = 1;
92 module_param(min_buffers, uint, 0644);
93 MODULE_PARM_DESC(min_buffers,
94                 "The minimum number of streaming I/O buffers we are willing "
95                 "to work with.");
96
97 static int max_buffers = 10;
98 module_param(max_buffers, uint, 0644);
99 MODULE_PARM_DESC(max_buffers,
100                 "The maximum number of streaming I/O buffers an application "
101                 "will be allowed to allocate.  These buffers are big and live "
102                 "in vmalloc space.");
103
104 static int flip;
105 module_param(flip, bool, 0444);
106 MODULE_PARM_DESC(flip,
107                 "If set, the sensor will be instructed to flip the image "
108                 "vertically.");
109
110
111 enum cafe_state {
112         S_NOTREADY,     /* Not yet initialized */
113         S_IDLE,         /* Just hanging around */
114         S_FLAKED,       /* Some sort of problem */
115         S_SINGLEREAD,   /* In read() */
116         S_SPECREAD,     /* Speculative read (for future read()) */
117         S_STREAMING     /* Streaming data */
118 };
119
120 /*
121  * Tracking of streaming I/O buffers.
122  */
123 struct cafe_sio_buffer {
124         struct list_head list;
125         struct v4l2_buffer v4lbuf;
126         char *buffer;   /* Where it lives in kernel space */
127         int mapcount;
128         struct cafe_camera *cam;
129 };
130
131 /*
132  * A description of one of our devices.
133  * Locking: controlled by s_mutex.  Certain fields, however, require
134  *          the dev_lock spinlock; they are marked as such by comments.
135  *          dev_lock is also required for access to device registers.
136  */
137 struct cafe_camera
138 {
139         struct v4l2_device v4l2_dev;
140         enum cafe_state state;
141         unsigned long flags;            /* Buffer status, mainly (dev_lock) */
142         int users;                      /* How many open FDs */
143         struct file *owner;             /* Who has data access (v4l2) */
144
145         /*
146          * Subsystem structures.
147          */
148         struct pci_dev *pdev;
149         struct video_device vdev;
150         struct i2c_adapter i2c_adapter;
151         struct i2c_client *sensor;
152
153         unsigned char __iomem *regs;
154         struct list_head dev_list;      /* link to other devices */
155
156         /* DMA buffers */
157         unsigned int nbufs;             /* How many are alloc'd */
158         int next_buf;                   /* Next to consume (dev_lock) */
159         unsigned int dma_buf_size;      /* allocated size */
160         void *dma_bufs[MAX_DMA_BUFS];   /* Internal buffer addresses */
161         dma_addr_t dma_handles[MAX_DMA_BUFS]; /* Buffer bus addresses */
162         unsigned int specframes;        /* Unconsumed spec frames (dev_lock) */
163         unsigned int sequence;          /* Frame sequence number */
164         unsigned int buf_seq[MAX_DMA_BUFS]; /* Sequence for individual buffers */
165
166         /* Streaming buffers */
167         unsigned int n_sbufs;           /* How many we have */
168         struct cafe_sio_buffer *sb_bufs; /* The array of housekeeping structs */
169         struct list_head sb_avail;      /* Available for data (we own) (dev_lock) */
170         struct list_head sb_full;       /* With data (user space owns) (dev_lock) */
171         struct tasklet_struct s_tasklet;
172
173         /* Current operating parameters */
174         u32 sensor_type;                /* Currently ov7670 only */
175         struct v4l2_pix_format pix_format;
176
177         /* Locks */
178         struct mutex s_mutex; /* Access to this structure */
179         spinlock_t dev_lock;  /* Access to device */
180
181         /* Misc */
182         wait_queue_head_t smbus_wait;   /* Waiting on i2c events */
183         wait_queue_head_t iowait;       /* Waiting on frame data */
184 #ifdef CONFIG_VIDEO_ADV_DEBUG
185         struct dentry *dfs_regs;
186         struct dentry *dfs_cam_regs;
187 #endif
188 };
189
190 /*
191  * Status flags.  Always manipulated with bit operations.
192  */
193 #define CF_BUF0_VALID    0      /* Buffers valid - first three */
194 #define CF_BUF1_VALID    1
195 #define CF_BUF2_VALID    2
196 #define CF_DMA_ACTIVE    3      /* A frame is incoming */
197 #define CF_CONFIG_NEEDED 4      /* Must configure hardware */
198
199
200 static inline struct cafe_camera *to_cam(struct v4l2_device *dev)
201 {
202         return container_of(dev, struct cafe_camera, v4l2_dev);
203 }
204
205
206 /*
207  * Start over with DMA buffers - dev_lock needed.
208  */
209 static void cafe_reset_buffers(struct cafe_camera *cam)
210 {
211         int i;
212
213         cam->next_buf = -1;
214         for (i = 0; i < cam->nbufs; i++)
215                 clear_bit(i, &cam->flags);
216         cam->specframes = 0;
217 }
218
219 static inline int cafe_needs_config(struct cafe_camera *cam)
220 {
221         return test_bit(CF_CONFIG_NEEDED, &cam->flags);
222 }
223
224 static void cafe_set_config_needed(struct cafe_camera *cam, int needed)
225 {
226         if (needed)
227                 set_bit(CF_CONFIG_NEEDED, &cam->flags);
228         else
229                 clear_bit(CF_CONFIG_NEEDED, &cam->flags);
230 }
231
232
233
234
235 /*
236  * Debugging and related.
237  */
238 #define cam_err(cam, fmt, arg...) \
239         dev_err(&(cam)->pdev->dev, fmt, ##arg);
240 #define cam_warn(cam, fmt, arg...) \
241         dev_warn(&(cam)->pdev->dev, fmt, ##arg);
242 #define cam_dbg(cam, fmt, arg...) \
243         dev_dbg(&(cam)->pdev->dev, fmt, ##arg);
244
245
246 /* ---------------------------------------------------------------------*/
247
248 /*
249  * Device register I/O
250  */
251 static inline void cafe_reg_write(struct cafe_camera *cam, unsigned int reg,
252                 unsigned int val)
253 {
254         iowrite32(val, cam->regs + reg);
255 }
256
257 static inline unsigned int cafe_reg_read(struct cafe_camera *cam,
258                 unsigned int reg)
259 {
260         return ioread32(cam->regs + reg);
261 }
262
263
264 static inline void cafe_reg_write_mask(struct cafe_camera *cam, unsigned int reg,
265                 unsigned int val, unsigned int mask)
266 {
267         unsigned int v = cafe_reg_read(cam, reg);
268
269         v = (v & ~mask) | (val & mask);
270         cafe_reg_write(cam, reg, v);
271 }
272
273 static inline void cafe_reg_clear_bit(struct cafe_camera *cam,
274                 unsigned int reg, unsigned int val)
275 {
276         cafe_reg_write_mask(cam, reg, 0, val);
277 }
278
279 static inline void cafe_reg_set_bit(struct cafe_camera *cam,
280                 unsigned int reg, unsigned int val)
281 {
282         cafe_reg_write_mask(cam, reg, val, val);
283 }
284
285
286
287 /* -------------------------------------------------------------------- */
288 /*
289  * The I2C/SMBUS interface to the camera itself starts here.  The
290  * controller handles SMBUS itself, presenting a relatively simple register
291  * interface; all we have to do is to tell it where to route the data.
292  */
293 #define CAFE_SMBUS_TIMEOUT (HZ)  /* generous */
294
295 static int cafe_smbus_write_done(struct cafe_camera *cam)
296 {
297         unsigned long flags;
298         int c1;
299
300         /*
301          * We must delay after the interrupt, or the controller gets confused
302          * and never does give us good status.  Fortunately, we don't do this
303          * often.
304          */
305         udelay(20);
306         spin_lock_irqsave(&cam->dev_lock, flags);
307         c1 = cafe_reg_read(cam, REG_TWSIC1);
308         spin_unlock_irqrestore(&cam->dev_lock, flags);
309         return (c1 & (TWSIC1_WSTAT|TWSIC1_ERROR)) != TWSIC1_WSTAT;
310 }
311
312 static int cafe_smbus_write_data(struct cafe_camera *cam,
313                 u16 addr, u8 command, u8 value)
314 {
315         unsigned int rval;
316         unsigned long flags;
317         DEFINE_WAIT(the_wait);
318
319         spin_lock_irqsave(&cam->dev_lock, flags);
320         rval = TWSIC0_EN | ((addr << TWSIC0_SID_SHIFT) & TWSIC0_SID);
321         rval |= TWSIC0_OVMAGIC;  /* Make OV sensors work */
322         /*
323          * Marvell sez set clkdiv to all 1's for now.
324          */
325         rval |= TWSIC0_CLKDIV;
326         cafe_reg_write(cam, REG_TWSIC0, rval);
327         (void) cafe_reg_read(cam, REG_TWSIC1); /* force write */
328         rval = value | ((command << TWSIC1_ADDR_SHIFT) & TWSIC1_ADDR);
329         cafe_reg_write(cam, REG_TWSIC1, rval);
330         spin_unlock_irqrestore(&cam->dev_lock, flags);
331
332         /*
333          * Time to wait for the write to complete.  THIS IS A RACY
334          * WAY TO DO IT, but the sad fact is that reading the TWSIC1
335          * register too quickly after starting the operation sends
336          * the device into a place that may be kinder and better, but
337          * which is absolutely useless for controlling the sensor.  In
338          * practice we have plenty of time to get into our sleep state
339          * before the interrupt hits, and the worst case is that we
340          * time out and then see that things completed, so this seems
341          * the best way for now.
342          */
343         do {
344                 prepare_to_wait(&cam->smbus_wait, &the_wait,
345                                 TASK_UNINTERRUPTIBLE);
346                 schedule_timeout(1); /* even 1 jiffy is too long */
347                 finish_wait(&cam->smbus_wait, &the_wait);
348         } while (!cafe_smbus_write_done(cam));
349
350 #ifdef IF_THE_CAFE_HARDWARE_WORKED_RIGHT
351         wait_event_timeout(cam->smbus_wait, cafe_smbus_write_done(cam),
352                         CAFE_SMBUS_TIMEOUT);
353 #endif
354         spin_lock_irqsave(&cam->dev_lock, flags);
355         rval = cafe_reg_read(cam, REG_TWSIC1);
356         spin_unlock_irqrestore(&cam->dev_lock, flags);
357
358         if (rval & TWSIC1_WSTAT) {
359                 cam_err(cam, "SMBUS write (%02x/%02x/%02x) timed out\n", addr,
360                                 command, value);
361                 return -EIO;
362         }
363         if (rval & TWSIC1_ERROR) {
364                 cam_err(cam, "SMBUS write (%02x/%02x/%02x) error\n", addr,
365                                 command, value);
366                 return -EIO;
367         }
368         return 0;
369 }
370
371
372
373 static int cafe_smbus_read_done(struct cafe_camera *cam)
374 {
375         unsigned long flags;
376         int c1;
377
378         /*
379          * We must delay after the interrupt, or the controller gets confused
380          * and never does give us good status.  Fortunately, we don't do this
381          * often.
382          */
383         udelay(20);
384         spin_lock_irqsave(&cam->dev_lock, flags);
385         c1 = cafe_reg_read(cam, REG_TWSIC1);
386         spin_unlock_irqrestore(&cam->dev_lock, flags);
387         return c1 & (TWSIC1_RVALID|TWSIC1_ERROR);
388 }
389
390
391
392 static int cafe_smbus_read_data(struct cafe_camera *cam,
393                 u16 addr, u8 command, u8 *value)
394 {
395         unsigned int rval;
396         unsigned long flags;
397
398         spin_lock_irqsave(&cam->dev_lock, flags);
399         rval = TWSIC0_EN | ((addr << TWSIC0_SID_SHIFT) & TWSIC0_SID);
400         rval |= TWSIC0_OVMAGIC; /* Make OV sensors work */
401         /*
402          * Marvel sez set clkdiv to all 1's for now.
403          */
404         rval |= TWSIC0_CLKDIV;
405         cafe_reg_write(cam, REG_TWSIC0, rval);
406         (void) cafe_reg_read(cam, REG_TWSIC1); /* force write */
407         rval = TWSIC1_READ | ((command << TWSIC1_ADDR_SHIFT) & TWSIC1_ADDR);
408         cafe_reg_write(cam, REG_TWSIC1, rval);
409         spin_unlock_irqrestore(&cam->dev_lock, flags);
410
411         wait_event_timeout(cam->smbus_wait,
412                         cafe_smbus_read_done(cam), CAFE_SMBUS_TIMEOUT);
413         spin_lock_irqsave(&cam->dev_lock, flags);
414         rval = cafe_reg_read(cam, REG_TWSIC1);
415         spin_unlock_irqrestore(&cam->dev_lock, flags);
416
417         if (rval & TWSIC1_ERROR) {
418                 cam_err(cam, "SMBUS read (%02x/%02x) error\n", addr, command);
419                 return -EIO;
420         }
421         if (! (rval & TWSIC1_RVALID)) {
422                 cam_err(cam, "SMBUS read (%02x/%02x) timed out\n", addr,
423                                 command);
424                 return -EIO;
425         }
426         *value = rval & 0xff;
427         return 0;
428 }
429
430 /*
431  * Perform a transfer over SMBUS.  This thing is called under
432  * the i2c bus lock, so we shouldn't race with ourselves...
433  */
434 static int cafe_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
435                 unsigned short flags, char rw, u8 command,
436                 int size, union i2c_smbus_data *data)
437 {
438         struct v4l2_device *v4l2_dev = i2c_get_adapdata(adapter);
439         struct cafe_camera *cam = to_cam(v4l2_dev);
440         int ret = -EINVAL;
441
442         /*
443          * Refuse to talk to anything but OV cam chips.  We should
444          * never even see an attempt to do so, but one never knows.
445          */
446         if (cam->sensor && addr != cam->sensor->addr) {
447                 cam_err(cam, "funky smbus addr %d\n", addr);
448                 return -EINVAL;
449         }
450         /*
451          * This interface would appear to only do byte data ops.  OK
452          * it can do word too, but the cam chip has no use for that.
453          */
454         if (size != I2C_SMBUS_BYTE_DATA) {
455                 cam_err(cam, "funky xfer size %d\n", size);
456                 return -EINVAL;
457         }
458
459         if (rw == I2C_SMBUS_WRITE)
460                 ret = cafe_smbus_write_data(cam, addr, command, data->byte);
461         else if (rw == I2C_SMBUS_READ)
462                 ret = cafe_smbus_read_data(cam, addr, command, &data->byte);
463         return ret;
464 }
465
466
467 static void cafe_smbus_enable_irq(struct cafe_camera *cam)
468 {
469         unsigned long flags;
470
471         spin_lock_irqsave(&cam->dev_lock, flags);
472         cafe_reg_set_bit(cam, REG_IRQMASK, TWSIIRQS);
473         spin_unlock_irqrestore(&cam->dev_lock, flags);
474 }
475
476 static u32 cafe_smbus_func(struct i2c_adapter *adapter)
477 {
478         return I2C_FUNC_SMBUS_READ_BYTE_DATA  |
479                I2C_FUNC_SMBUS_WRITE_BYTE_DATA;
480 }
481
482 static struct i2c_algorithm cafe_smbus_algo = {
483         .smbus_xfer = cafe_smbus_xfer,
484         .functionality = cafe_smbus_func
485 };
486
487 /* Somebody is on the bus */
488 static int cafe_cam_init(struct cafe_camera *cam);
489 static void cafe_ctlr_stop_dma(struct cafe_camera *cam);
490 static void cafe_ctlr_power_down(struct cafe_camera *cam);
491
492 static int cafe_smbus_attach(struct i2c_client *client)
493 {
494         struct v4l2_device *v4l2_dev = i2c_get_adapdata(client->adapter);
495         struct cafe_camera *cam = to_cam(v4l2_dev);
496
497         /*
498          * Don't talk to chips we don't recognize.
499          */
500         if (client->driver->id == I2C_DRIVERID_OV7670) {
501                 cam->sensor = client;
502                 return cafe_cam_init(cam);
503         }
504         return -EINVAL;
505 }
506
507 static int cafe_smbus_detach(struct i2c_client *client)
508 {
509         struct v4l2_device *v4l2_dev = i2c_get_adapdata(client->adapter);
510         struct cafe_camera *cam = to_cam(v4l2_dev);
511
512         if (cam->sensor == client) {
513                 cafe_ctlr_stop_dma(cam);
514                 cafe_ctlr_power_down(cam);
515                 cam_err(cam, "lost the sensor!\n");
516                 cam->sensor = NULL;  /* Bummer, no camera */
517                 cam->state = S_NOTREADY;
518         }
519         return 0;
520 }
521
522 static int cafe_smbus_setup(struct cafe_camera *cam)
523 {
524         struct i2c_adapter *adap = &cam->i2c_adapter;
525         int ret;
526
527         cafe_smbus_enable_irq(cam);
528         adap->id = I2C_HW_SMBUS_CAFE;
529         adap->owner = THIS_MODULE;
530         adap->client_register = cafe_smbus_attach;
531         adap->client_unregister = cafe_smbus_detach;
532         adap->algo = &cafe_smbus_algo;
533         strcpy(adap->name, "cafe_ccic");
534         adap->dev.parent = &cam->pdev->dev;
535         i2c_set_adapdata(adap, &cam->v4l2_dev);
536         ret = i2c_add_adapter(adap);
537         if (ret)
538                 printk(KERN_ERR "Unable to register cafe i2c adapter\n");
539         return ret;
540 }
541
542 static void cafe_smbus_shutdown(struct cafe_camera *cam)
543 {
544         i2c_del_adapter(&cam->i2c_adapter);
545 }
546
547
548 /* ------------------------------------------------------------------- */
549 /*
550  * Deal with the controller.
551  */
552
553 /*
554  * Do everything we think we need to have the interface operating
555  * according to the desired format.
556  */
557 static void cafe_ctlr_dma(struct cafe_camera *cam)
558 {
559         /*
560          * Store the first two Y buffers (we aren't supporting
561          * planar formats for now, so no UV bufs).  Then either
562          * set the third if it exists, or tell the controller
563          * to just use two.
564          */
565         cafe_reg_write(cam, REG_Y0BAR, cam->dma_handles[0]);
566         cafe_reg_write(cam, REG_Y1BAR, cam->dma_handles[1]);
567         if (cam->nbufs > 2) {
568                 cafe_reg_write(cam, REG_Y2BAR, cam->dma_handles[2]);
569                 cafe_reg_clear_bit(cam, REG_CTRL1, C1_TWOBUFS);
570         }
571         else
572                 cafe_reg_set_bit(cam, REG_CTRL1, C1_TWOBUFS);
573         cafe_reg_write(cam, REG_UBAR, 0); /* 32 bits only for now */
574 }
575
576 static void cafe_ctlr_image(struct cafe_camera *cam)
577 {
578         int imgsz;
579         struct v4l2_pix_format *fmt = &cam->pix_format;
580
581         imgsz = ((fmt->height << IMGSZ_V_SHIFT) & IMGSZ_V_MASK) |
582                 (fmt->bytesperline & IMGSZ_H_MASK);
583         cafe_reg_write(cam, REG_IMGSIZE, imgsz);
584         cafe_reg_write(cam, REG_IMGOFFSET, 0);
585         /* YPITCH just drops the last two bits */
586         cafe_reg_write_mask(cam, REG_IMGPITCH, fmt->bytesperline,
587                         IMGP_YP_MASK);
588         /*
589          * Tell the controller about the image format we are using.
590          */
591         switch (cam->pix_format.pixelformat) {
592         case V4L2_PIX_FMT_YUYV:
593             cafe_reg_write_mask(cam, REG_CTRL0,
594                             C0_DF_YUV|C0_YUV_PACKED|C0_YUVE_YUYV,
595                             C0_DF_MASK);
596             break;
597
598         case V4L2_PIX_FMT_RGB444:
599             cafe_reg_write_mask(cam, REG_CTRL0,
600                             C0_DF_RGB|C0_RGBF_444|C0_RGB4_XRGB,
601                             C0_DF_MASK);
602                 /* Alpha value? */
603             break;
604
605         case V4L2_PIX_FMT_RGB565:
606             cafe_reg_write_mask(cam, REG_CTRL0,
607                             C0_DF_RGB|C0_RGBF_565|C0_RGB5_BGGR,
608                             C0_DF_MASK);
609             break;
610
611         default:
612             cam_err(cam, "Unknown format %x\n", cam->pix_format.pixelformat);
613             break;
614         }
615         /*
616          * Make sure it knows we want to use hsync/vsync.
617          */
618         cafe_reg_write_mask(cam, REG_CTRL0, C0_SIF_HVSYNC,
619                         C0_SIFM_MASK);
620 }
621
622
623 /*
624  * Configure the controller for operation; caller holds the
625  * device mutex.
626  */
627 static int cafe_ctlr_configure(struct cafe_camera *cam)
628 {
629         unsigned long flags;
630
631         spin_lock_irqsave(&cam->dev_lock, flags);
632         cafe_ctlr_dma(cam);
633         cafe_ctlr_image(cam);
634         cafe_set_config_needed(cam, 0);
635         spin_unlock_irqrestore(&cam->dev_lock, flags);
636         return 0;
637 }
638
639 static void cafe_ctlr_irq_enable(struct cafe_camera *cam)
640 {
641         /*
642          * Clear any pending interrupts, since we do not
643          * expect to have I/O active prior to enabling.
644          */
645         cafe_reg_write(cam, REG_IRQSTAT, FRAMEIRQS);
646         cafe_reg_set_bit(cam, REG_IRQMASK, FRAMEIRQS);
647 }
648
649 static void cafe_ctlr_irq_disable(struct cafe_camera *cam)
650 {
651         cafe_reg_clear_bit(cam, REG_IRQMASK, FRAMEIRQS);
652 }
653
654 /*
655  * Make the controller start grabbing images.  Everything must
656  * be set up before doing this.
657  */
658 static void cafe_ctlr_start(struct cafe_camera *cam)
659 {
660         /* set_bit performs a read, so no other barrier should be
661            needed here */
662         cafe_reg_set_bit(cam, REG_CTRL0, C0_ENABLE);
663 }
664
665 static void cafe_ctlr_stop(struct cafe_camera *cam)
666 {
667         cafe_reg_clear_bit(cam, REG_CTRL0, C0_ENABLE);
668 }
669
670 static void cafe_ctlr_init(struct cafe_camera *cam)
671 {
672         unsigned long flags;
673
674         spin_lock_irqsave(&cam->dev_lock, flags);
675         /*
676          * Added magic to bring up the hardware on the B-Test board
677          */
678         cafe_reg_write(cam, 0x3038, 0x8);
679         cafe_reg_write(cam, 0x315c, 0x80008);
680         /*
681          * Go through the dance needed to wake the device up.
682          * Note that these registers are global and shared
683          * with the NAND and SD devices.  Interaction between the
684          * three still needs to be examined.
685          */
686         cafe_reg_write(cam, REG_GL_CSR, GCSR_SRS|GCSR_MRS); /* Needed? */
687         cafe_reg_write(cam, REG_GL_CSR, GCSR_SRC|GCSR_MRC);
688         cafe_reg_write(cam, REG_GL_CSR, GCSR_SRC|GCSR_MRS);
689         /*
690          * Here we must wait a bit for the controller to come around.
691          */
692         spin_unlock_irqrestore(&cam->dev_lock, flags);
693         msleep(5);
694         spin_lock_irqsave(&cam->dev_lock, flags);
695
696         cafe_reg_write(cam, REG_GL_CSR, GCSR_CCIC_EN|GCSR_SRC|GCSR_MRC);
697         cafe_reg_set_bit(cam, REG_GL_IMASK, GIMSK_CCIC_EN);
698         /*
699          * Make sure it's not powered down.
700          */
701         cafe_reg_clear_bit(cam, REG_CTRL1, C1_PWRDWN);
702         /*
703          * Turn off the enable bit.  It sure should be off anyway,
704          * but it's good to be sure.
705          */
706         cafe_reg_clear_bit(cam, REG_CTRL0, C0_ENABLE);
707         /*
708          * Mask all interrupts.
709          */
710         cafe_reg_write(cam, REG_IRQMASK, 0);
711         /*
712          * Clock the sensor appropriately.  Controller clock should
713          * be 48MHz, sensor "typical" value is half that.
714          */
715         cafe_reg_write_mask(cam, REG_CLKCTRL, 2, CLK_DIV_MASK);
716         spin_unlock_irqrestore(&cam->dev_lock, flags);
717 }
718
719
720 /*
721  * Stop the controller, and don't return until we're really sure that no
722  * further DMA is going on.
723  */
724 static void cafe_ctlr_stop_dma(struct cafe_camera *cam)
725 {
726         unsigned long flags;
727
728         /*
729          * Theory: stop the camera controller (whether it is operating
730          * or not).  Delay briefly just in case we race with the SOF
731          * interrupt, then wait until no DMA is active.
732          */
733         spin_lock_irqsave(&cam->dev_lock, flags);
734         cafe_ctlr_stop(cam);
735         spin_unlock_irqrestore(&cam->dev_lock, flags);
736         mdelay(1);
737         wait_event_timeout(cam->iowait,
738                         !test_bit(CF_DMA_ACTIVE, &cam->flags), HZ);
739         if (test_bit(CF_DMA_ACTIVE, &cam->flags))
740                 cam_err(cam, "Timeout waiting for DMA to end\n");
741                 /* This would be bad news - what now? */
742         spin_lock_irqsave(&cam->dev_lock, flags);
743         cam->state = S_IDLE;
744         cafe_ctlr_irq_disable(cam);
745         spin_unlock_irqrestore(&cam->dev_lock, flags);
746 }
747
748 /*
749  * Power up and down.
750  */
751 static void cafe_ctlr_power_up(struct cafe_camera *cam)
752 {
753         unsigned long flags;
754
755         spin_lock_irqsave(&cam->dev_lock, flags);
756         cafe_reg_clear_bit(cam, REG_CTRL1, C1_PWRDWN);
757         /*
758          * Part one of the sensor dance: turn the global
759          * GPIO signal on.
760          */
761         cafe_reg_write(cam, REG_GL_FCR, GFCR_GPIO_ON);
762         cafe_reg_write(cam, REG_GL_GPIOR, GGPIO_OUT|GGPIO_VAL);
763         /*
764          * Put the sensor into operational mode (assumes OLPC-style
765          * wiring).  Control 0 is reset - set to 1 to operate.
766          * Control 1 is power down, set to 0 to operate.
767          */
768         cafe_reg_write(cam, REG_GPR, GPR_C1EN|GPR_C0EN); /* pwr up, reset */
769 /*      mdelay(1); */ /* Marvell says 1ms will do it */
770         cafe_reg_write(cam, REG_GPR, GPR_C1EN|GPR_C0EN|GPR_C0);
771 /*      mdelay(1); */ /* Enough? */
772         spin_unlock_irqrestore(&cam->dev_lock, flags);
773         msleep(5); /* Just to be sure */
774 }
775
776 static void cafe_ctlr_power_down(struct cafe_camera *cam)
777 {
778         unsigned long flags;
779
780         spin_lock_irqsave(&cam->dev_lock, flags);
781         cafe_reg_write(cam, REG_GPR, GPR_C1EN|GPR_C0EN|GPR_C1);
782         cafe_reg_write(cam, REG_GL_FCR, GFCR_GPIO_ON);
783         cafe_reg_write(cam, REG_GL_GPIOR, GGPIO_OUT);
784         cafe_reg_set_bit(cam, REG_CTRL1, C1_PWRDWN);
785         spin_unlock_irqrestore(&cam->dev_lock, flags);
786 }
787
788 /* -------------------------------------------------------------------- */
789 /*
790  * Communications with the sensor.
791  */
792
793 static int __cafe_cam_cmd(struct cafe_camera *cam, int cmd, void *arg)
794 {
795         struct i2c_client *sc = cam->sensor;
796         int ret;
797
798         if (sc == NULL || sc->driver == NULL || sc->driver->command == NULL)
799                 return -EINVAL;
800         ret = sc->driver->command(sc, cmd, arg);
801         if (ret == -EPERM) /* Unsupported command */
802                 return 0;
803         return ret;
804 }
805
806 static int __cafe_cam_reset(struct cafe_camera *cam)
807 {
808         int zero = 0;
809         return __cafe_cam_cmd(cam, VIDIOC_INT_RESET, &zero);
810 }
811
812 /*
813  * We have found the sensor on the i2c.  Let's try to have a
814  * conversation.
815  */
816 static int cafe_cam_init(struct cafe_camera *cam)
817 {
818         struct v4l2_dbg_chip_ident chip;
819         int ret;
820
821         mutex_lock(&cam->s_mutex);
822         if (cam->state != S_NOTREADY)
823                 cam_warn(cam, "Cam init with device in funky state %d",
824                                 cam->state);
825         ret = __cafe_cam_reset(cam);
826         if (ret)
827                 goto out;
828         chip.match.type = V4L2_CHIP_MATCH_I2C_ADDR;
829         chip.match.addr = cam->sensor->addr;
830         ret = __cafe_cam_cmd(cam, VIDIOC_DBG_G_CHIP_IDENT, &chip);
831         if (ret)
832                 goto out;
833         cam->sensor_type = chip.ident;
834 /*      if (cam->sensor->addr != OV7xx0_SID) { */
835         if (cam->sensor_type != V4L2_IDENT_OV7670) {
836                 cam_err(cam, "Unsupported sensor type %d", cam->sensor->addr);
837                 ret = -EINVAL;
838                 goto out;
839         }
840 /* Get/set parameters? */
841         ret = 0;
842         cam->state = S_IDLE;
843   out:
844         cafe_ctlr_power_down(cam);
845         mutex_unlock(&cam->s_mutex);
846         return ret;
847 }
848
849 /*
850  * Configure the sensor to match the parameters we have.  Caller should
851  * hold s_mutex
852  */
853 static int cafe_cam_set_flip(struct cafe_camera *cam)
854 {
855         struct v4l2_control ctrl;
856
857         memset(&ctrl, 0, sizeof(ctrl));
858         ctrl.id = V4L2_CID_VFLIP;
859         ctrl.value = flip;
860         return __cafe_cam_cmd(cam, VIDIOC_S_CTRL, &ctrl);
861 }
862
863
864 static int cafe_cam_configure(struct cafe_camera *cam)
865 {
866         struct v4l2_format fmt;
867         int ret, zero = 0;
868
869         if (cam->state != S_IDLE)
870                 return -EINVAL;
871         fmt.fmt.pix = cam->pix_format;
872         ret = __cafe_cam_cmd(cam, VIDIOC_INT_INIT, &zero);
873         if (ret == 0)
874                 ret = __cafe_cam_cmd(cam, VIDIOC_S_FMT, &fmt);
875         /*
876          * OV7670 does weird things if flip is set *before* format...
877          */
878         ret += cafe_cam_set_flip(cam);
879         return ret;
880 }
881
882 /* -------------------------------------------------------------------- */
883 /*
884  * DMA buffer management.  These functions need s_mutex held.
885  */
886
887 /* FIXME: this is inefficient as hell, since dma_alloc_coherent just
888  * does a get_free_pages() call, and we waste a good chunk of an orderN
889  * allocation.  Should try to allocate the whole set in one chunk.
890  */
891 static int cafe_alloc_dma_bufs(struct cafe_camera *cam, int loadtime)
892 {
893         int i;
894
895         cafe_set_config_needed(cam, 1);
896         if (loadtime)
897                 cam->dma_buf_size = dma_buf_size;
898         else
899                 cam->dma_buf_size = cam->pix_format.sizeimage;
900         if (n_dma_bufs > 3)
901                 n_dma_bufs = 3;
902
903         cam->nbufs = 0;
904         for (i = 0; i < n_dma_bufs; i++) {
905                 cam->dma_bufs[i] = dma_alloc_coherent(&cam->pdev->dev,
906                                 cam->dma_buf_size, cam->dma_handles + i,
907                                 GFP_KERNEL);
908                 if (cam->dma_bufs[i] == NULL) {
909                         cam_warn(cam, "Failed to allocate DMA buffer\n");
910                         break;
911                 }
912                 /* For debug, remove eventually */
913                 memset(cam->dma_bufs[i], 0xcc, cam->dma_buf_size);
914                 (cam->nbufs)++;
915         }
916
917         switch (cam->nbufs) {
918         case 1:
919             dma_free_coherent(&cam->pdev->dev, cam->dma_buf_size,
920                             cam->dma_bufs[0], cam->dma_handles[0]);
921             cam->nbufs = 0;
922         case 0:
923             cam_err(cam, "Insufficient DMA buffers, cannot operate\n");
924             return -ENOMEM;
925
926         case 2:
927             if (n_dma_bufs > 2)
928                     cam_warn(cam, "Will limp along with only 2 buffers\n");
929             break;
930         }
931         return 0;
932 }
933
934 static void cafe_free_dma_bufs(struct cafe_camera *cam)
935 {
936         int i;
937
938         for (i = 0; i < cam->nbufs; i++) {
939                 dma_free_coherent(&cam->pdev->dev, cam->dma_buf_size,
940                                 cam->dma_bufs[i], cam->dma_handles[i]);
941                 cam->dma_bufs[i] = NULL;
942         }
943         cam->nbufs = 0;
944 }
945
946
947
948
949
950 /* ----------------------------------------------------------------------- */
951 /*
952  * Here starts the V4L2 interface code.
953  */
954
955 /*
956  * Read an image from the device.
957  */
958 static ssize_t cafe_deliver_buffer(struct cafe_camera *cam,
959                 char __user *buffer, size_t len, loff_t *pos)
960 {
961         int bufno;
962         unsigned long flags;
963
964         spin_lock_irqsave(&cam->dev_lock, flags);
965         if (cam->next_buf < 0) {
966                 cam_err(cam, "deliver_buffer: No next buffer\n");
967                 spin_unlock_irqrestore(&cam->dev_lock, flags);
968                 return -EIO;
969         }
970         bufno = cam->next_buf;
971         clear_bit(bufno, &cam->flags);
972         if (++(cam->next_buf) >= cam->nbufs)
973                 cam->next_buf = 0;
974         if (! test_bit(cam->next_buf, &cam->flags))
975                 cam->next_buf = -1;
976         cam->specframes = 0;
977         spin_unlock_irqrestore(&cam->dev_lock, flags);
978
979         if (len > cam->pix_format.sizeimage)
980                 len = cam->pix_format.sizeimage;
981         if (copy_to_user(buffer, cam->dma_bufs[bufno], len))
982                 return -EFAULT;
983         (*pos) += len;
984         return len;
985 }
986
987 /*
988  * Get everything ready, and start grabbing frames.
989  */
990 static int cafe_read_setup(struct cafe_camera *cam, enum cafe_state state)
991 {
992         int ret;
993         unsigned long flags;
994
995         /*
996          * Configuration.  If we still don't have DMA buffers,
997          * make one last, desperate attempt.
998          */
999         if (cam->nbufs == 0)
1000                 if (cafe_alloc_dma_bufs(cam, 0))
1001                         return -ENOMEM;
1002
1003         if (cafe_needs_config(cam)) {
1004                 cafe_cam_configure(cam);
1005                 ret = cafe_ctlr_configure(cam);
1006                 if (ret)
1007                         return ret;
1008         }
1009
1010         /*
1011          * Turn it loose.
1012          */
1013         spin_lock_irqsave(&cam->dev_lock, flags);
1014         cafe_reset_buffers(cam);
1015         cafe_ctlr_irq_enable(cam);
1016         cam->state = state;
1017         cafe_ctlr_start(cam);
1018         spin_unlock_irqrestore(&cam->dev_lock, flags);
1019         return 0;
1020 }
1021
1022
1023 static ssize_t cafe_v4l_read(struct file *filp,
1024                 char __user *buffer, size_t len, loff_t *pos)
1025 {
1026         struct cafe_camera *cam = filp->private_data;
1027         int ret = 0;
1028
1029         /*
1030          * Perhaps we're in speculative read mode and already
1031          * have data?
1032          */
1033         mutex_lock(&cam->s_mutex);
1034         if (cam->state == S_SPECREAD) {
1035                 if (cam->next_buf >= 0) {
1036                         ret = cafe_deliver_buffer(cam, buffer, len, pos);
1037                         if (ret != 0)
1038                                 goto out_unlock;
1039                 }
1040         } else if (cam->state == S_FLAKED || cam->state == S_NOTREADY) {
1041                 ret = -EIO;
1042                 goto out_unlock;
1043         } else if (cam->state != S_IDLE) {
1044                 ret = -EBUSY;
1045                 goto out_unlock;
1046         }
1047
1048         /*
1049          * v4l2: multiple processes can open the device, but only
1050          * one gets to grab data from it.
1051          */
1052         if (cam->owner && cam->owner != filp) {
1053                 ret = -EBUSY;
1054                 goto out_unlock;
1055         }
1056         cam->owner = filp;
1057
1058         /*
1059          * Do setup if need be.
1060          */
1061         if (cam->state != S_SPECREAD) {
1062                 ret = cafe_read_setup(cam, S_SINGLEREAD);
1063                 if (ret)
1064                         goto out_unlock;
1065         }
1066         /*
1067          * Wait for something to happen.  This should probably
1068          * be interruptible (FIXME).
1069          */
1070         wait_event_timeout(cam->iowait, cam->next_buf >= 0, HZ);
1071         if (cam->next_buf < 0) {
1072                 cam_err(cam, "read() operation timed out\n");
1073                 cafe_ctlr_stop_dma(cam);
1074                 ret = -EIO;
1075                 goto out_unlock;
1076         }
1077         /*
1078          * Give them their data and we should be done.
1079          */
1080         ret = cafe_deliver_buffer(cam, buffer, len, pos);
1081
1082   out_unlock:
1083         mutex_unlock(&cam->s_mutex);
1084         return ret;
1085 }
1086
1087
1088
1089
1090
1091
1092
1093
1094 /*
1095  * Streaming I/O support.
1096  */
1097
1098
1099
1100 static int cafe_vidioc_streamon(struct file *filp, void *priv,
1101                 enum v4l2_buf_type type)
1102 {
1103         struct cafe_camera *cam = filp->private_data;
1104         int ret = -EINVAL;
1105
1106         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1107                 goto out;
1108         mutex_lock(&cam->s_mutex);
1109         if (cam->state != S_IDLE || cam->n_sbufs == 0)
1110                 goto out_unlock;
1111
1112         cam->sequence = 0;
1113         ret = cafe_read_setup(cam, S_STREAMING);
1114
1115   out_unlock:
1116         mutex_unlock(&cam->s_mutex);
1117   out:
1118         return ret;
1119 }
1120
1121
1122 static int cafe_vidioc_streamoff(struct file *filp, void *priv,
1123                 enum v4l2_buf_type type)
1124 {
1125         struct cafe_camera *cam = filp->private_data;
1126         int ret = -EINVAL;
1127
1128         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1129                 goto out;
1130         mutex_lock(&cam->s_mutex);
1131         if (cam->state != S_STREAMING)
1132                 goto out_unlock;
1133
1134         cafe_ctlr_stop_dma(cam);
1135         ret = 0;
1136
1137   out_unlock:
1138         mutex_unlock(&cam->s_mutex);
1139   out:
1140         return ret;
1141 }
1142
1143
1144
1145 static int cafe_setup_siobuf(struct cafe_camera *cam, int index)
1146 {
1147         struct cafe_sio_buffer *buf = cam->sb_bufs + index;
1148
1149         INIT_LIST_HEAD(&buf->list);
1150         buf->v4lbuf.length = PAGE_ALIGN(cam->pix_format.sizeimage);
1151         buf->buffer = vmalloc_user(buf->v4lbuf.length);
1152         if (buf->buffer == NULL)
1153                 return -ENOMEM;
1154         buf->mapcount = 0;
1155         buf->cam = cam;
1156
1157         buf->v4lbuf.index = index;
1158         buf->v4lbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1159         buf->v4lbuf.field = V4L2_FIELD_NONE;
1160         buf->v4lbuf.memory = V4L2_MEMORY_MMAP;
1161         /*
1162          * Offset: must be 32-bit even on a 64-bit system.  videobuf-dma-sg
1163          * just uses the length times the index, but the spec warns
1164          * against doing just that - vma merging problems.  So we
1165          * leave a gap between each pair of buffers.
1166          */
1167         buf->v4lbuf.m.offset = 2*index*buf->v4lbuf.length;
1168         return 0;
1169 }
1170
1171 static int cafe_free_sio_buffers(struct cafe_camera *cam)
1172 {
1173         int i;
1174
1175         /*
1176          * If any buffers are mapped, we cannot free them at all.
1177          */
1178         for (i = 0; i < cam->n_sbufs; i++)
1179                 if (cam->sb_bufs[i].mapcount > 0)
1180                         return -EBUSY;
1181         /*
1182          * OK, let's do it.
1183          */
1184         for (i = 0; i < cam->n_sbufs; i++)
1185                 vfree(cam->sb_bufs[i].buffer);
1186         cam->n_sbufs = 0;
1187         kfree(cam->sb_bufs);
1188         cam->sb_bufs = NULL;
1189         INIT_LIST_HEAD(&cam->sb_avail);
1190         INIT_LIST_HEAD(&cam->sb_full);
1191         return 0;
1192 }
1193
1194
1195
1196 static int cafe_vidioc_reqbufs(struct file *filp, void *priv,
1197                 struct v4l2_requestbuffers *req)
1198 {
1199         struct cafe_camera *cam = filp->private_data;
1200         int ret = 0;  /* Silence warning */
1201
1202         /*
1203          * Make sure it's something we can do.  User pointers could be
1204          * implemented without great pain, but that's not been done yet.
1205          */
1206         if (req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1207                 return -EINVAL;
1208         if (req->memory != V4L2_MEMORY_MMAP)
1209                 return -EINVAL;
1210         /*
1211          * If they ask for zero buffers, they really want us to stop streaming
1212          * (if it's happening) and free everything.  Should we check owner?
1213          */
1214         mutex_lock(&cam->s_mutex);
1215         if (req->count == 0) {
1216                 if (cam->state == S_STREAMING)
1217                         cafe_ctlr_stop_dma(cam);
1218                 ret = cafe_free_sio_buffers (cam);
1219                 goto out;
1220         }
1221         /*
1222          * Device needs to be idle and working.  We *could* try to do the
1223          * right thing in S_SPECREAD by shutting things down, but it
1224          * probably doesn't matter.
1225          */
1226         if (cam->state != S_IDLE || (cam->owner && cam->owner != filp)) {
1227                 ret = -EBUSY;
1228                 goto out;
1229         }
1230         cam->owner = filp;
1231
1232         if (req->count < min_buffers)
1233                 req->count = min_buffers;
1234         else if (req->count > max_buffers)
1235                 req->count = max_buffers;
1236         if (cam->n_sbufs > 0) {
1237                 ret = cafe_free_sio_buffers(cam);
1238                 if (ret)
1239                         goto out;
1240         }
1241
1242         cam->sb_bufs = kzalloc(req->count*sizeof(struct cafe_sio_buffer),
1243                         GFP_KERNEL);
1244         if (cam->sb_bufs == NULL) {
1245                 ret = -ENOMEM;
1246                 goto out;
1247         }
1248         for (cam->n_sbufs = 0; cam->n_sbufs < req->count; (cam->n_sbufs++)) {
1249                 ret = cafe_setup_siobuf(cam, cam->n_sbufs);
1250                 if (ret)
1251                         break;
1252         }
1253
1254         if (cam->n_sbufs == 0)  /* no luck at all - ret already set */
1255                 kfree(cam->sb_bufs);
1256         req->count = cam->n_sbufs;  /* In case of partial success */
1257
1258   out:
1259         mutex_unlock(&cam->s_mutex);
1260         return ret;
1261 }
1262
1263
1264 static int cafe_vidioc_querybuf(struct file *filp, void *priv,
1265                 struct v4l2_buffer *buf)
1266 {
1267         struct cafe_camera *cam = filp->private_data;
1268         int ret = -EINVAL;
1269
1270         mutex_lock(&cam->s_mutex);
1271         if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1272                 goto out;
1273         if (buf->index < 0 || buf->index >= cam->n_sbufs)
1274                 goto out;
1275         *buf = cam->sb_bufs[buf->index].v4lbuf;
1276         ret = 0;
1277   out:
1278         mutex_unlock(&cam->s_mutex);
1279         return ret;
1280 }
1281
1282 static int cafe_vidioc_qbuf(struct file *filp, void *priv,
1283                 struct v4l2_buffer *buf)
1284 {
1285         struct cafe_camera *cam = filp->private_data;
1286         struct cafe_sio_buffer *sbuf;
1287         int ret = -EINVAL;
1288         unsigned long flags;
1289
1290         mutex_lock(&cam->s_mutex);
1291         if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1292                 goto out;
1293         if (buf->index < 0 || buf->index >= cam->n_sbufs)
1294                 goto out;
1295         sbuf = cam->sb_bufs + buf->index;
1296         if (sbuf->v4lbuf.flags & V4L2_BUF_FLAG_QUEUED) {
1297                 ret = 0; /* Already queued?? */
1298                 goto out;
1299         }
1300         if (sbuf->v4lbuf.flags & V4L2_BUF_FLAG_DONE) {
1301                 /* Spec doesn't say anything, seems appropriate tho */
1302                 ret = -EBUSY;
1303                 goto out;
1304         }
1305         sbuf->v4lbuf.flags |= V4L2_BUF_FLAG_QUEUED;
1306         spin_lock_irqsave(&cam->dev_lock, flags);
1307         list_add(&sbuf->list, &cam->sb_avail);
1308         spin_unlock_irqrestore(&cam->dev_lock, flags);
1309         ret = 0;
1310   out:
1311         mutex_unlock(&cam->s_mutex);
1312         return ret;
1313 }
1314
1315 static int cafe_vidioc_dqbuf(struct file *filp, void *priv,
1316                 struct v4l2_buffer *buf)
1317 {
1318         struct cafe_camera *cam = filp->private_data;
1319         struct cafe_sio_buffer *sbuf;
1320         int ret = -EINVAL;
1321         unsigned long flags;
1322
1323         mutex_lock(&cam->s_mutex);
1324         if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1325                 goto out_unlock;
1326         if (cam->state != S_STREAMING)
1327                 goto out_unlock;
1328         if (list_empty(&cam->sb_full) && filp->f_flags & O_NONBLOCK) {
1329                 ret = -EAGAIN;
1330                 goto out_unlock;
1331         }
1332
1333         while (list_empty(&cam->sb_full) && cam->state == S_STREAMING) {
1334                 mutex_unlock(&cam->s_mutex);
1335                 if (wait_event_interruptible(cam->iowait,
1336                                                 !list_empty(&cam->sb_full))) {
1337                         ret = -ERESTARTSYS;
1338                         goto out;
1339                 }
1340                 mutex_lock(&cam->s_mutex);
1341         }
1342
1343         if (cam->state != S_STREAMING)
1344                 ret = -EINTR;
1345         else {
1346                 spin_lock_irqsave(&cam->dev_lock, flags);
1347                 /* Should probably recheck !list_empty() here */
1348                 sbuf = list_entry(cam->sb_full.next,
1349                                 struct cafe_sio_buffer, list);
1350                 list_del_init(&sbuf->list);
1351                 spin_unlock_irqrestore(&cam->dev_lock, flags);
1352                 sbuf->v4lbuf.flags &= ~V4L2_BUF_FLAG_DONE;
1353                 *buf = sbuf->v4lbuf;
1354                 ret = 0;
1355         }
1356
1357   out_unlock:
1358         mutex_unlock(&cam->s_mutex);
1359   out:
1360         return ret;
1361 }
1362
1363
1364
1365 static void cafe_v4l_vm_open(struct vm_area_struct *vma)
1366 {
1367         struct cafe_sio_buffer *sbuf = vma->vm_private_data;
1368         /*
1369          * Locking: done under mmap_sem, so we don't need to
1370          * go back to the camera lock here.
1371          */
1372         sbuf->mapcount++;
1373 }
1374
1375
1376 static void cafe_v4l_vm_close(struct vm_area_struct *vma)
1377 {
1378         struct cafe_sio_buffer *sbuf = vma->vm_private_data;
1379
1380         mutex_lock(&sbuf->cam->s_mutex);
1381         sbuf->mapcount--;
1382         /* Docs say we should stop I/O too... */
1383         if (sbuf->mapcount == 0)
1384                 sbuf->v4lbuf.flags &= ~V4L2_BUF_FLAG_MAPPED;
1385         mutex_unlock(&sbuf->cam->s_mutex);
1386 }
1387
1388 static struct vm_operations_struct cafe_v4l_vm_ops = {
1389         .open = cafe_v4l_vm_open,
1390         .close = cafe_v4l_vm_close
1391 };
1392
1393
1394 static int cafe_v4l_mmap(struct file *filp, struct vm_area_struct *vma)
1395 {
1396         struct cafe_camera *cam = filp->private_data;
1397         unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
1398         int ret = -EINVAL;
1399         int i;
1400         struct cafe_sio_buffer *sbuf = NULL;
1401
1402         if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED))
1403                 return -EINVAL;
1404         /*
1405          * Find the buffer they are looking for.
1406          */
1407         mutex_lock(&cam->s_mutex);
1408         for (i = 0; i < cam->n_sbufs; i++)
1409                 if (cam->sb_bufs[i].v4lbuf.m.offset == offset) {
1410                         sbuf = cam->sb_bufs + i;
1411                         break;
1412                 }
1413         if (sbuf == NULL)
1414                 goto out;
1415
1416         ret = remap_vmalloc_range(vma, sbuf->buffer, 0);
1417         if (ret)
1418                 goto out;
1419         vma->vm_flags |= VM_DONTEXPAND;
1420         vma->vm_private_data = sbuf;
1421         vma->vm_ops = &cafe_v4l_vm_ops;
1422         sbuf->v4lbuf.flags |= V4L2_BUF_FLAG_MAPPED;
1423         cafe_v4l_vm_open(vma);
1424         ret = 0;
1425   out:
1426         mutex_unlock(&cam->s_mutex);
1427         return ret;
1428 }
1429
1430
1431
1432 static int cafe_v4l_open(struct file *filp)
1433 {
1434         struct cafe_camera *cam = video_drvdata(filp);
1435
1436         filp->private_data = cam;
1437
1438         mutex_lock(&cam->s_mutex);
1439         if (cam->users == 0) {
1440                 cafe_ctlr_power_up(cam);
1441                 __cafe_cam_reset(cam);
1442                 cafe_set_config_needed(cam, 1);
1443         /* FIXME make sure this is complete */
1444         }
1445         (cam->users)++;
1446         mutex_unlock(&cam->s_mutex);
1447         return 0;
1448 }
1449
1450
1451 static int cafe_v4l_release(struct file *filp)
1452 {
1453         struct cafe_camera *cam = filp->private_data;
1454
1455         mutex_lock(&cam->s_mutex);
1456         (cam->users)--;
1457         if (filp == cam->owner) {
1458                 cafe_ctlr_stop_dma(cam);
1459                 cafe_free_sio_buffers(cam);
1460                 cam->owner = NULL;
1461         }
1462         if (cam->users == 0) {
1463                 cafe_ctlr_power_down(cam);
1464                 if (alloc_bufs_at_read)
1465                         cafe_free_dma_bufs(cam);
1466         }
1467         mutex_unlock(&cam->s_mutex);
1468         return 0;
1469 }
1470
1471
1472
1473 static unsigned int cafe_v4l_poll(struct file *filp,
1474                 struct poll_table_struct *pt)
1475 {
1476         struct cafe_camera *cam = filp->private_data;
1477
1478         poll_wait(filp, &cam->iowait, pt);
1479         if (cam->next_buf >= 0)
1480                 return POLLIN | POLLRDNORM;
1481         return 0;
1482 }
1483
1484
1485
1486 static int cafe_vidioc_queryctrl(struct file *filp, void *priv,
1487                 struct v4l2_queryctrl *qc)
1488 {
1489         struct cafe_camera *cam = priv;
1490         int ret;
1491
1492         mutex_lock(&cam->s_mutex);
1493         ret = __cafe_cam_cmd(cam, VIDIOC_QUERYCTRL, qc);
1494         mutex_unlock(&cam->s_mutex);
1495         return ret;
1496 }
1497
1498
1499 static int cafe_vidioc_g_ctrl(struct file *filp, void *priv,
1500                 struct v4l2_control *ctrl)
1501 {
1502         struct cafe_camera *cam = priv;
1503         int ret;
1504
1505         mutex_lock(&cam->s_mutex);
1506         ret = __cafe_cam_cmd(cam, VIDIOC_G_CTRL, ctrl);
1507         mutex_unlock(&cam->s_mutex);
1508         return ret;
1509 }
1510
1511
1512 static int cafe_vidioc_s_ctrl(struct file *filp, void *priv,
1513                 struct v4l2_control *ctrl)
1514 {
1515         struct cafe_camera *cam = priv;
1516         int ret;
1517
1518         mutex_lock(&cam->s_mutex);
1519         ret = __cafe_cam_cmd(cam, VIDIOC_S_CTRL, ctrl);
1520         mutex_unlock(&cam->s_mutex);
1521         return ret;
1522 }
1523
1524
1525
1526
1527
1528 static int cafe_vidioc_querycap(struct file *file, void *priv,
1529                 struct v4l2_capability *cap)
1530 {
1531         strcpy(cap->driver, "cafe_ccic");
1532         strcpy(cap->card, "cafe_ccic");
1533         cap->version = CAFE_VERSION;
1534         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
1535                 V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1536         return 0;
1537 }
1538
1539
1540 /*
1541  * The default format we use until somebody says otherwise.
1542  */
1543 static struct v4l2_pix_format cafe_def_pix_format = {
1544         .width          = VGA_WIDTH,
1545         .height         = VGA_HEIGHT,
1546         .pixelformat    = V4L2_PIX_FMT_YUYV,
1547         .field          = V4L2_FIELD_NONE,
1548         .bytesperline   = VGA_WIDTH*2,
1549         .sizeimage      = VGA_WIDTH*VGA_HEIGHT*2,
1550 };
1551
1552 static int cafe_vidioc_enum_fmt_vid_cap(struct file *filp,
1553                 void *priv, struct v4l2_fmtdesc *fmt)
1554 {
1555         struct cafe_camera *cam = priv;
1556         int ret;
1557
1558         if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1559                 return -EINVAL;
1560         mutex_lock(&cam->s_mutex);
1561         ret = __cafe_cam_cmd(cam, VIDIOC_ENUM_FMT, fmt);
1562         mutex_unlock(&cam->s_mutex);
1563         return ret;
1564 }
1565
1566
1567 static int cafe_vidioc_try_fmt_vid_cap(struct file *filp, void *priv,
1568                 struct v4l2_format *fmt)
1569 {
1570         struct cafe_camera *cam = priv;
1571         int ret;
1572
1573         mutex_lock(&cam->s_mutex);
1574         ret = __cafe_cam_cmd(cam, VIDIOC_TRY_FMT, fmt);
1575         mutex_unlock(&cam->s_mutex);
1576         return ret;
1577 }
1578
1579 static int cafe_vidioc_s_fmt_vid_cap(struct file *filp, void *priv,
1580                 struct v4l2_format *fmt)
1581 {
1582         struct cafe_camera *cam = priv;
1583         int ret;
1584
1585         /*
1586          * Can't do anything if the device is not idle
1587          * Also can't if there are streaming buffers in place.
1588          */
1589         if (cam->state != S_IDLE || cam->n_sbufs > 0)
1590                 return -EBUSY;
1591         /*
1592          * See if the formatting works in principle.
1593          */
1594         ret = cafe_vidioc_try_fmt_vid_cap(filp, priv, fmt);
1595         if (ret)
1596                 return ret;
1597         /*
1598          * Now we start to change things for real, so let's do it
1599          * under lock.
1600          */
1601         mutex_lock(&cam->s_mutex);
1602         cam->pix_format = fmt->fmt.pix;
1603         /*
1604          * Make sure we have appropriate DMA buffers.
1605          */
1606         ret = -ENOMEM;
1607         if (cam->nbufs > 0 && cam->dma_buf_size < cam->pix_format.sizeimage)
1608                 cafe_free_dma_bufs(cam);
1609         if (cam->nbufs == 0) {
1610                 if (cafe_alloc_dma_bufs(cam, 0))
1611                         goto out;
1612         }
1613         /*
1614          * It looks like this might work, so let's program the sensor.
1615          */
1616         ret = cafe_cam_configure(cam);
1617         if (! ret)
1618                 ret = cafe_ctlr_configure(cam);
1619   out:
1620         mutex_unlock(&cam->s_mutex);
1621         return ret;
1622 }
1623
1624 /*
1625  * Return our stored notion of how the camera is/should be configured.
1626  * The V4l2 spec wants us to be smarter, and actually get this from
1627  * the camera (and not mess with it at open time).  Someday.
1628  */
1629 static int cafe_vidioc_g_fmt_vid_cap(struct file *filp, void *priv,
1630                 struct v4l2_format *f)
1631 {
1632         struct cafe_camera *cam = priv;
1633
1634         f->fmt.pix = cam->pix_format;
1635         return 0;
1636 }
1637
1638 /*
1639  * We only have one input - the sensor - so minimize the nonsense here.
1640  */
1641 static int cafe_vidioc_enum_input(struct file *filp, void *priv,
1642                 struct v4l2_input *input)
1643 {
1644         if (input->index != 0)
1645                 return -EINVAL;
1646
1647         input->type = V4L2_INPUT_TYPE_CAMERA;
1648         input->std = V4L2_STD_ALL; /* Not sure what should go here */
1649         strcpy(input->name, "Camera");
1650         return 0;
1651 }
1652
1653 static int cafe_vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
1654 {
1655         *i = 0;
1656         return 0;
1657 }
1658
1659 static int cafe_vidioc_s_input(struct file *filp, void *priv, unsigned int i)
1660 {
1661         if (i != 0)
1662                 return -EINVAL;
1663         return 0;
1664 }
1665
1666 /* from vivi.c */
1667 static int cafe_vidioc_s_std(struct file *filp, void *priv, v4l2_std_id *a)
1668 {
1669         return 0;
1670 }
1671
1672 /*
1673  * G/S_PARM.  Most of this is done by the sensor, but we are
1674  * the level which controls the number of read buffers.
1675  */
1676 static int cafe_vidioc_g_parm(struct file *filp, void *priv,
1677                 struct v4l2_streamparm *parms)
1678 {
1679         struct cafe_camera *cam = priv;
1680         int ret;
1681
1682         mutex_lock(&cam->s_mutex);
1683         ret = __cafe_cam_cmd(cam, VIDIOC_G_PARM, parms);
1684         mutex_unlock(&cam->s_mutex);
1685         parms->parm.capture.readbuffers = n_dma_bufs;
1686         return ret;
1687 }
1688
1689 static int cafe_vidioc_s_parm(struct file *filp, void *priv,
1690                 struct v4l2_streamparm *parms)
1691 {
1692         struct cafe_camera *cam = priv;
1693         int ret;
1694
1695         mutex_lock(&cam->s_mutex);
1696         ret = __cafe_cam_cmd(cam, VIDIOC_S_PARM, parms);
1697         mutex_unlock(&cam->s_mutex);
1698         parms->parm.capture.readbuffers = n_dma_bufs;
1699         return ret;
1700 }
1701
1702 /*
1703  * This template device holds all of those v4l2 methods; we
1704  * clone it for specific real devices.
1705  */
1706
1707 static const struct v4l2_file_operations cafe_v4l_fops = {
1708         .owner = THIS_MODULE,
1709         .open = cafe_v4l_open,
1710         .release = cafe_v4l_release,
1711         .read = cafe_v4l_read,
1712         .poll = cafe_v4l_poll,
1713         .mmap = cafe_v4l_mmap,
1714         .ioctl = video_ioctl2,
1715 };
1716
1717 static const struct v4l2_ioctl_ops cafe_v4l_ioctl_ops = {
1718         .vidioc_querycap        = cafe_vidioc_querycap,
1719         .vidioc_enum_fmt_vid_cap = cafe_vidioc_enum_fmt_vid_cap,
1720         .vidioc_try_fmt_vid_cap = cafe_vidioc_try_fmt_vid_cap,
1721         .vidioc_s_fmt_vid_cap   = cafe_vidioc_s_fmt_vid_cap,
1722         .vidioc_g_fmt_vid_cap   = cafe_vidioc_g_fmt_vid_cap,
1723         .vidioc_enum_input      = cafe_vidioc_enum_input,
1724         .vidioc_g_input         = cafe_vidioc_g_input,
1725         .vidioc_s_input         = cafe_vidioc_s_input,
1726         .vidioc_s_std           = cafe_vidioc_s_std,
1727         .vidioc_reqbufs         = cafe_vidioc_reqbufs,
1728         .vidioc_querybuf        = cafe_vidioc_querybuf,
1729         .vidioc_qbuf            = cafe_vidioc_qbuf,
1730         .vidioc_dqbuf           = cafe_vidioc_dqbuf,
1731         .vidioc_streamon        = cafe_vidioc_streamon,
1732         .vidioc_streamoff       = cafe_vidioc_streamoff,
1733         .vidioc_queryctrl       = cafe_vidioc_queryctrl,
1734         .vidioc_g_ctrl          = cafe_vidioc_g_ctrl,
1735         .vidioc_s_ctrl          = cafe_vidioc_s_ctrl,
1736         .vidioc_g_parm          = cafe_vidioc_g_parm,
1737         .vidioc_s_parm          = cafe_vidioc_s_parm,
1738 };
1739
1740 static struct video_device cafe_v4l_template = {
1741         .name = "cafe",
1742         .minor = -1, /* Get one dynamically */
1743         .tvnorms = V4L2_STD_NTSC_M,
1744         .current_norm = V4L2_STD_NTSC_M,  /* make mplayer happy */
1745
1746         .fops = &cafe_v4l_fops,
1747         .ioctl_ops = &cafe_v4l_ioctl_ops,
1748         .release = video_device_release_empty,
1749 };
1750
1751
1752 /* ---------------------------------------------------------------------- */
1753 /*
1754  * Interrupt handler stuff
1755  */
1756
1757
1758
1759 static void cafe_frame_tasklet(unsigned long data)
1760 {
1761         struct cafe_camera *cam = (struct cafe_camera *) data;
1762         int i;
1763         unsigned long flags;
1764         struct cafe_sio_buffer *sbuf;
1765
1766         spin_lock_irqsave(&cam->dev_lock, flags);
1767         for (i = 0; i < cam->nbufs; i++) {
1768                 int bufno = cam->next_buf;
1769                 if (bufno < 0) {  /* "will never happen" */
1770                         cam_err(cam, "No valid bufs in tasklet!\n");
1771                         break;
1772                 }
1773                 if (++(cam->next_buf) >= cam->nbufs)
1774                         cam->next_buf = 0;
1775                 if (! test_bit(bufno, &cam->flags))
1776                         continue;
1777                 if (list_empty(&cam->sb_avail))
1778                         break;  /* Leave it valid, hope for better later */
1779                 clear_bit(bufno, &cam->flags);
1780                 sbuf = list_entry(cam->sb_avail.next,
1781                                 struct cafe_sio_buffer, list);
1782                 /*
1783                  * Drop the lock during the big copy.  This *should* be safe...
1784                  */
1785                 spin_unlock_irqrestore(&cam->dev_lock, flags);
1786                 memcpy(sbuf->buffer, cam->dma_bufs[bufno],
1787                                 cam->pix_format.sizeimage);
1788                 sbuf->v4lbuf.bytesused = cam->pix_format.sizeimage;
1789                 sbuf->v4lbuf.sequence = cam->buf_seq[bufno];
1790                 sbuf->v4lbuf.flags &= ~V4L2_BUF_FLAG_QUEUED;
1791                 sbuf->v4lbuf.flags |= V4L2_BUF_FLAG_DONE;
1792                 spin_lock_irqsave(&cam->dev_lock, flags);
1793                 list_move_tail(&sbuf->list, &cam->sb_full);
1794         }
1795         if (! list_empty(&cam->sb_full))
1796                 wake_up(&cam->iowait);
1797         spin_unlock_irqrestore(&cam->dev_lock, flags);
1798 }
1799
1800
1801
1802 static void cafe_frame_complete(struct cafe_camera *cam, int frame)
1803 {
1804         /*
1805          * Basic frame housekeeping.
1806          */
1807         if (test_bit(frame, &cam->flags) && printk_ratelimit())
1808                 cam_err(cam, "Frame overrun on %d, frames lost\n", frame);
1809         set_bit(frame, &cam->flags);
1810         clear_bit(CF_DMA_ACTIVE, &cam->flags);
1811         if (cam->next_buf < 0)
1812                 cam->next_buf = frame;
1813         cam->buf_seq[frame] = ++(cam->sequence);
1814
1815         switch (cam->state) {
1816         /*
1817          * If in single read mode, try going speculative.
1818          */
1819             case S_SINGLEREAD:
1820                 cam->state = S_SPECREAD;
1821                 cam->specframes = 0;
1822                 wake_up(&cam->iowait);
1823                 break;
1824
1825         /*
1826          * If we are already doing speculative reads, and nobody is
1827          * reading them, just stop.
1828          */
1829             case S_SPECREAD:
1830                 if (++(cam->specframes) >= cam->nbufs) {
1831                         cafe_ctlr_stop(cam);
1832                         cafe_ctlr_irq_disable(cam);
1833                         cam->state = S_IDLE;
1834                 }
1835                 wake_up(&cam->iowait);
1836                 break;
1837         /*
1838          * For the streaming case, we defer the real work to the
1839          * camera tasklet.
1840          *
1841          * FIXME: if the application is not consuming the buffers,
1842          * we should eventually put things on hold and restart in
1843          * vidioc_dqbuf().
1844          */
1845             case S_STREAMING:
1846                 tasklet_schedule(&cam->s_tasklet);
1847                 break;
1848
1849             default:
1850                 cam_err(cam, "Frame interrupt in non-operational state\n");
1851                 break;
1852         }
1853 }
1854
1855
1856
1857
1858 static void cafe_frame_irq(struct cafe_camera *cam, unsigned int irqs)
1859 {
1860         unsigned int frame;
1861
1862         cafe_reg_write(cam, REG_IRQSTAT, FRAMEIRQS); /* Clear'em all */
1863         /*
1864          * Handle any frame completions.  There really should
1865          * not be more than one of these, or we have fallen
1866          * far behind.
1867          */
1868         for (frame = 0; frame < cam->nbufs; frame++)
1869                 if (irqs & (IRQ_EOF0 << frame))
1870                         cafe_frame_complete(cam, frame);
1871         /*
1872          * If a frame starts, note that we have DMA active.  This
1873          * code assumes that we won't get multiple frame interrupts
1874          * at once; may want to rethink that.
1875          */
1876         if (irqs & (IRQ_SOF0 | IRQ_SOF1 | IRQ_SOF2))
1877                 set_bit(CF_DMA_ACTIVE, &cam->flags);
1878 }
1879
1880
1881
1882 static irqreturn_t cafe_irq(int irq, void *data)
1883 {
1884         struct cafe_camera *cam = data;
1885         unsigned int irqs;
1886
1887         spin_lock(&cam->dev_lock);
1888         irqs = cafe_reg_read(cam, REG_IRQSTAT);
1889         if ((irqs & ALLIRQS) == 0) {
1890                 spin_unlock(&cam->dev_lock);
1891                 return IRQ_NONE;
1892         }
1893         if (irqs & FRAMEIRQS)
1894                 cafe_frame_irq(cam, irqs);
1895         if (irqs & TWSIIRQS) {
1896                 cafe_reg_write(cam, REG_IRQSTAT, TWSIIRQS);
1897                 wake_up(&cam->smbus_wait);
1898         }
1899         spin_unlock(&cam->dev_lock);
1900         return IRQ_HANDLED;
1901 }
1902
1903
1904 /* -------------------------------------------------------------------------- */
1905 #ifdef CONFIG_VIDEO_ADV_DEBUG
1906 /*
1907  * Debugfs stuff.
1908  */
1909
1910 static char cafe_debug_buf[1024];
1911 static struct dentry *cafe_dfs_root;
1912
1913 static void cafe_dfs_setup(void)
1914 {
1915         cafe_dfs_root = debugfs_create_dir("cafe_ccic", NULL);
1916         if (IS_ERR(cafe_dfs_root)) {
1917                 cafe_dfs_root = NULL;  /* Never mind */
1918                 printk(KERN_NOTICE "cafe_ccic unable to set up debugfs\n");
1919         }
1920 }
1921
1922 static void cafe_dfs_shutdown(void)
1923 {
1924         if (cafe_dfs_root)
1925                 debugfs_remove(cafe_dfs_root);
1926 }
1927
1928 static int cafe_dfs_open(struct inode *inode, struct file *file)
1929 {
1930         file->private_data = inode->i_private;
1931         return 0;
1932 }
1933
1934 static ssize_t cafe_dfs_read_regs(struct file *file,
1935                 char __user *buf, size_t count, loff_t *ppos)
1936 {
1937         struct cafe_camera *cam = file->private_data;
1938         char *s = cafe_debug_buf;
1939         int offset;
1940
1941         for (offset = 0; offset < 0x44; offset += 4)
1942                 s += sprintf(s, "%02x: %08x\n", offset,
1943                                 cafe_reg_read(cam, offset));
1944         for (offset = 0x88; offset <= 0x90; offset += 4)
1945                 s += sprintf(s, "%02x: %08x\n", offset,
1946                                 cafe_reg_read(cam, offset));
1947         for (offset = 0xb4; offset <= 0xbc; offset += 4)
1948                 s += sprintf(s, "%02x: %08x\n", offset,
1949                                 cafe_reg_read(cam, offset));
1950         for (offset = 0x3000; offset <= 0x300c; offset += 4)
1951                 s += sprintf(s, "%04x: %08x\n", offset,
1952                                 cafe_reg_read(cam, offset));
1953         return simple_read_from_buffer(buf, count, ppos, cafe_debug_buf,
1954                         s - cafe_debug_buf);
1955 }
1956
1957 static const struct file_operations cafe_dfs_reg_ops = {
1958         .owner = THIS_MODULE,
1959         .read = cafe_dfs_read_regs,
1960         .open = cafe_dfs_open
1961 };
1962
1963 static ssize_t cafe_dfs_read_cam(struct file *file,
1964                 char __user *buf, size_t count, loff_t *ppos)
1965 {
1966         struct cafe_camera *cam = file->private_data;
1967         char *s = cafe_debug_buf;
1968         int offset;
1969
1970         if (! cam->sensor)
1971                 return -EINVAL;
1972         for (offset = 0x0; offset < 0x8a; offset++)
1973         {
1974                 u8 v;
1975
1976                 cafe_smbus_read_data(cam, cam->sensor->addr, offset, &v);
1977                 s += sprintf(s, "%02x: %02x\n", offset, v);
1978         }
1979         return simple_read_from_buffer(buf, count, ppos, cafe_debug_buf,
1980                         s - cafe_debug_buf);
1981 }
1982
1983 static const struct file_operations cafe_dfs_cam_ops = {
1984         .owner = THIS_MODULE,
1985         .read = cafe_dfs_read_cam,
1986         .open = cafe_dfs_open
1987 };
1988
1989
1990
1991 static void cafe_dfs_cam_setup(struct cafe_camera *cam)
1992 {
1993         char fname[40];
1994
1995         if (!cafe_dfs_root)
1996                 return;
1997         sprintf(fname, "regs-%d", cam->vdev.num);
1998         cam->dfs_regs = debugfs_create_file(fname, 0444, cafe_dfs_root,
1999                         cam, &cafe_dfs_reg_ops);
2000         sprintf(fname, "cam-%d", cam->vdev.num);
2001         cam->dfs_cam_regs = debugfs_create_file(fname, 0444, cafe_dfs_root,
2002                         cam, &cafe_dfs_cam_ops);
2003 }
2004
2005
2006 static void cafe_dfs_cam_shutdown(struct cafe_camera *cam)
2007 {
2008         if (! IS_ERR(cam->dfs_regs))
2009                 debugfs_remove(cam->dfs_regs);
2010         if (! IS_ERR(cam->dfs_cam_regs))
2011                 debugfs_remove(cam->dfs_cam_regs);
2012 }
2013
2014 #else
2015
2016 #define cafe_dfs_setup()
2017 #define cafe_dfs_shutdown()
2018 #define cafe_dfs_cam_setup(cam)
2019 #define cafe_dfs_cam_shutdown(cam)
2020 #endif    /* CONFIG_VIDEO_ADV_DEBUG */
2021
2022
2023
2024
2025 /* ------------------------------------------------------------------------*/
2026 /*
2027  * PCI interface stuff.
2028  */
2029
2030 static int cafe_pci_probe(struct pci_dev *pdev,
2031                 const struct pci_device_id *id)
2032 {
2033         int ret;
2034         struct cafe_camera *cam;
2035
2036         /*
2037          * Start putting together one of our big camera structures.
2038          */
2039         ret = -ENOMEM;
2040         cam = kzalloc(sizeof(struct cafe_camera), GFP_KERNEL);
2041         if (cam == NULL)
2042                 goto out;
2043         ret = v4l2_device_register(&pdev->dev, &cam->v4l2_dev);
2044         if (ret)
2045                 goto out_free;
2046
2047         mutex_init(&cam->s_mutex);
2048         mutex_lock(&cam->s_mutex);
2049         spin_lock_init(&cam->dev_lock);
2050         cam->state = S_NOTREADY;
2051         cafe_set_config_needed(cam, 1);
2052         init_waitqueue_head(&cam->smbus_wait);
2053         init_waitqueue_head(&cam->iowait);
2054         cam->pdev = pdev;
2055         cam->pix_format = cafe_def_pix_format;
2056         INIT_LIST_HEAD(&cam->dev_list);
2057         INIT_LIST_HEAD(&cam->sb_avail);
2058         INIT_LIST_HEAD(&cam->sb_full);
2059         tasklet_init(&cam->s_tasklet, cafe_frame_tasklet, (unsigned long) cam);
2060         /*
2061          * Get set up on the PCI bus.
2062          */
2063         ret = pci_enable_device(pdev);
2064         if (ret)
2065                 goto out_unreg;
2066         pci_set_master(pdev);
2067
2068         ret = -EIO;
2069         cam->regs = pci_iomap(pdev, 0, 0);
2070         if (! cam->regs) {
2071                 printk(KERN_ERR "Unable to ioremap cafe-ccic regs\n");
2072                 goto out_unreg;
2073         }
2074         ret = request_irq(pdev->irq, cafe_irq, IRQF_SHARED, "cafe-ccic", cam);
2075         if (ret)
2076                 goto out_iounmap;
2077         /*
2078          * Initialize the controller and leave it powered up.  It will
2079          * stay that way until the sensor driver shows up.
2080          */
2081         cafe_ctlr_init(cam);
2082         cafe_ctlr_power_up(cam);
2083         /*
2084          * Set up I2C/SMBUS communications.  We have to drop the mutex here
2085          * because the sensor could attach in this call chain, leading to
2086          * unsightly deadlocks.
2087          */
2088         mutex_unlock(&cam->s_mutex);  /* attach can deadlock */
2089         ret = cafe_smbus_setup(cam);
2090         if (ret)
2091                 goto out_freeirq;
2092         /*
2093          * Get the v4l2 setup done.
2094          */
2095         mutex_lock(&cam->s_mutex);
2096         cam->vdev = cafe_v4l_template;
2097         cam->vdev.debug = 0;
2098 /*      cam->vdev.debug = V4L2_DEBUG_IOCTL_ARG;*/
2099         cam->vdev.v4l2_dev = &cam->v4l2_dev;
2100         ret = video_register_device(&cam->vdev, VFL_TYPE_GRABBER, -1);
2101         if (ret)
2102                 goto out_smbus;
2103         video_set_drvdata(&cam->vdev, cam);
2104
2105         /*
2106          * If so requested, try to get our DMA buffers now.
2107          */
2108         if (!alloc_bufs_at_read) {
2109                 if (cafe_alloc_dma_bufs(cam, 1))
2110                         cam_warn(cam, "Unable to alloc DMA buffers at load"
2111                                         " will try again later.");
2112         }
2113
2114         cafe_dfs_cam_setup(cam);
2115         mutex_unlock(&cam->s_mutex);
2116         return 0;
2117
2118 out_smbus:
2119         cafe_smbus_shutdown(cam);
2120 out_freeirq:
2121         cafe_ctlr_power_down(cam);
2122         free_irq(pdev->irq, cam);
2123 out_iounmap:
2124         pci_iounmap(pdev, cam->regs);
2125 out_free:
2126         v4l2_device_unregister(&cam->v4l2_dev);
2127 out_unreg:
2128         kfree(cam);
2129 out:
2130         return ret;
2131 }
2132
2133
2134 /*
2135  * Shut down an initialized device
2136  */
2137 static void cafe_shutdown(struct cafe_camera *cam)
2138 {
2139 /* FIXME: Make sure we take care of everything here */
2140         cafe_dfs_cam_shutdown(cam);
2141         if (cam->n_sbufs > 0)
2142                 /* What if they are still mapped?  Shouldn't be, but... */
2143                 cafe_free_sio_buffers(cam);
2144         cafe_ctlr_stop_dma(cam);
2145         cafe_ctlr_power_down(cam);
2146         cafe_smbus_shutdown(cam);
2147         cafe_free_dma_bufs(cam);
2148         free_irq(cam->pdev->irq, cam);
2149         pci_iounmap(cam->pdev, cam->regs);
2150         video_unregister_device(&cam->vdev);
2151 }
2152
2153
2154 static void cafe_pci_remove(struct pci_dev *pdev)
2155 {
2156         struct v4l2_device *v4l2_dev = dev_get_drvdata(&pdev->dev);
2157         struct cafe_camera *cam = to_cam(v4l2_dev);
2158
2159         if (cam == NULL) {
2160                 printk(KERN_WARNING "pci_remove on unknown pdev %p\n", pdev);
2161                 return;
2162         }
2163         mutex_lock(&cam->s_mutex);
2164         if (cam->users > 0)
2165                 cam_warn(cam, "Removing a device with users!\n");
2166         cafe_shutdown(cam);
2167         v4l2_device_unregister(&cam->v4l2_dev);
2168         kfree(cam);
2169 /* No unlock - it no longer exists */
2170 }
2171
2172
2173 #ifdef CONFIG_PM
2174 /*
2175  * Basic power management.
2176  */
2177 static int cafe_pci_suspend(struct pci_dev *pdev, pm_message_t state)
2178 {
2179         struct v4l2_device *v4l2_dev = dev_get_drvdata(&pdev->dev);
2180         struct cafe_camera *cam = to_cam(v4l2_dev);
2181         int ret;
2182         enum cafe_state cstate;
2183
2184         ret = pci_save_state(pdev);
2185         if (ret)
2186                 return ret;
2187         cstate = cam->state; /* HACK - stop_dma sets to idle */
2188         cafe_ctlr_stop_dma(cam);
2189         cafe_ctlr_power_down(cam);
2190         pci_disable_device(pdev);
2191         cam->state = cstate;
2192         return 0;
2193 }
2194
2195
2196 static int cafe_pci_resume(struct pci_dev *pdev)
2197 {
2198         struct v4l2_device *v4l2_dev = dev_get_drvdata(&pdev->dev);
2199         struct cafe_camera *cam = to_cam(v4l2_dev);
2200         int ret = 0;
2201
2202         ret = pci_restore_state(pdev);
2203         if (ret)
2204                 return ret;
2205         ret = pci_enable_device(pdev);
2206
2207         if (ret) {
2208                 cam_warn(cam, "Unable to re-enable device on resume!\n");
2209                 return ret;
2210         }
2211         cafe_ctlr_init(cam);
2212         cafe_ctlr_power_down(cam);
2213
2214         mutex_lock(&cam->s_mutex);
2215         if (cam->users > 0) {
2216                 cafe_ctlr_power_up(cam);
2217                 __cafe_cam_reset(cam);
2218         }
2219         mutex_unlock(&cam->s_mutex);
2220
2221         set_bit(CF_CONFIG_NEEDED, &cam->flags);
2222         if (cam->state == S_SPECREAD)
2223                 cam->state = S_IDLE;  /* Don't bother restarting */
2224         else if (cam->state == S_SINGLEREAD || cam->state == S_STREAMING)
2225                 ret = cafe_read_setup(cam, cam->state);
2226         return ret;
2227 }
2228
2229 #endif  /* CONFIG_PM */
2230
2231
2232 static struct pci_device_id cafe_ids[] = {
2233         { PCI_DEVICE(PCI_VENDOR_ID_MARVELL,
2234                      PCI_DEVICE_ID_MARVELL_88ALP01_CCIC) },
2235         { 0, }
2236 };
2237
2238 MODULE_DEVICE_TABLE(pci, cafe_ids);
2239
2240 static struct pci_driver cafe_pci_driver = {
2241         .name = "cafe1000-ccic",
2242         .id_table = cafe_ids,
2243         .probe = cafe_pci_probe,
2244         .remove = cafe_pci_remove,
2245 #ifdef CONFIG_PM
2246         .suspend = cafe_pci_suspend,
2247         .resume = cafe_pci_resume,
2248 #endif
2249 };
2250
2251
2252
2253
2254 static int __init cafe_init(void)
2255 {
2256         int ret;
2257
2258         printk(KERN_NOTICE "Marvell M88ALP01 'CAFE' Camera Controller version %d\n",
2259                         CAFE_VERSION);
2260         cafe_dfs_setup();
2261         ret = pci_register_driver(&cafe_pci_driver);
2262         if (ret) {
2263                 printk(KERN_ERR "Unable to register cafe_ccic driver\n");
2264                 goto out;
2265         }
2266         request_module("ov7670");  /* FIXME want something more general */
2267         ret = 0;
2268
2269   out:
2270         return ret;
2271 }
2272
2273
2274 static void __exit cafe_exit(void)
2275 {
2276         pci_unregister_driver(&cafe_pci_driver);
2277         cafe_dfs_shutdown();
2278 }
2279
2280 module_init(cafe_init);
2281 module_exit(cafe_exit);