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