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