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