Merge master.kernel.org:/home/rmk/linux-2.6-arm
[linux-2.6] / drivers / media / video / em28xx / em28xx-core.c
1 /*
2    em28xx-core.c - driver for Empia EM2800/EM2820/2840 USB video capture devices
3
4    Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
5                       Markus Rechberger <mrechberger@gmail.com>
6                       Mauro Carvalho Chehab <mchehab@brturbo.com.br>
7                       Sascha Sommer <saschasommer@freenet.de>
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  */
23
24 #include <linux/init.h>
25 #include <linux/list.h>
26 #include <linux/module.h>
27 #include <linux/moduleparam.h>
28 #include <linux/usb.h>
29 #include <linux/vmalloc.h>
30
31 #include "em28xx.h"
32
33 /* #define ENABLE_DEBUG_ISOC_FRAMES */
34
35 static unsigned int core_debug;
36 module_param(core_debug,int,0644);
37 MODULE_PARM_DESC(core_debug,"enable debug messages [core]");
38
39 #define em28xx_coredbg(fmt, arg...) do {\
40         if (core_debug) \
41                 printk(KERN_INFO "%s %s :"fmt, \
42                          dev->name, __FUNCTION__ , ##arg); } while (0)
43
44 static unsigned int reg_debug;
45 module_param(reg_debug,int,0644);
46 MODULE_PARM_DESC(reg_debug,"enable debug messages [URB reg]");
47
48 #define em28xx_regdbg(fmt, arg...) do {\
49         if (reg_debug) \
50                 printk(KERN_INFO "%s %s :"fmt, \
51                          dev->name, __FUNCTION__ , ##arg); } while (0)
52
53 static unsigned int isoc_debug;
54 module_param(isoc_debug,int,0644);
55 MODULE_PARM_DESC(isoc_debug,"enable debug messages [isoc transfers]");
56
57 #define em28xx_isocdbg(fmt, arg...) do {\
58         if (isoc_debug) \
59                 printk(KERN_INFO "%s %s :"fmt, \
60                          dev->name, __FUNCTION__ , ##arg); } while (0)
61
62 static int alt = EM28XX_PINOUT;
63 module_param(alt, int, 0644);
64 MODULE_PARM_DESC(alt, "alternate setting to use for video endpoint");
65
66 /* ------------------------------------------------------------------ */
67 /* debug help functions                                               */
68
69 static const char *v4l1_ioctls[] = {
70         "0", "CGAP", "GCHAN", "SCHAN", "GTUNER", "STUNER", "GPICT", "SPICT",
71         "CCAPTURE", "GWIN", "SWIN", "GFBUF", "SFBUF", "KEY", "GFREQ",
72         "SFREQ", "GAUDIO", "SAUDIO", "SYNC", "MCAPTURE", "GMBUF", "GUNIT",
73         "GCAPTURE", "SCAPTURE", "SPLAYMODE", "SWRITEMODE", "GPLAYINFO",
74         "SMICROCODE", "GVBIFMT", "SVBIFMT" };
75 #define V4L1_IOCTLS ARRAY_SIZE(v4l1_ioctls)
76
77 static const char *v4l2_ioctls[] = {
78         "QUERYCAP", "1", "ENUM_PIXFMT", "ENUM_FBUFFMT", "G_FMT", "S_FMT",
79         "G_COMP", "S_COMP", "REQBUFS", "QUERYBUF", "G_FBUF", "S_FBUF",
80         "G_WIN", "S_WIN", "PREVIEW", "QBUF", "16", "DQBUF", "STREAMON",
81         "STREAMOFF", "G_PERF", "G_PARM", "S_PARM", "G_STD", "S_STD",
82         "ENUMSTD", "ENUMINPUT", "G_CTRL", "S_CTRL", "G_TUNER", "S_TUNER",
83         "G_FREQ", "S_FREQ", "G_AUDIO", "S_AUDIO", "35", "QUERYCTRL",
84         "QUERYMENU", "G_INPUT", "S_INPUT", "ENUMCVT", "41", "42", "43",
85         "44", "45",  "G_OUTPUT", "S_OUTPUT", "ENUMOUTPUT", "G_AUDOUT",
86         "S_AUDOUT", "ENUMFX", "G_EFFECT", "S_EFFECT", "G_MODULATOR",
87         "S_MODULATOR"
88 };
89 #define V4L2_IOCTLS ARRAY_SIZE(v4l2_ioctls)
90
91 void em28xx_print_ioctl(char *name, unsigned int cmd)
92 {
93         char *dir;
94
95         switch (_IOC_DIR(cmd)) {
96         case _IOC_NONE:              dir = "--"; break;
97         case _IOC_READ:              dir = "r-"; break;
98         case _IOC_WRITE:             dir = "-w"; break;
99         case _IOC_READ | _IOC_WRITE: dir = "rw"; break;
100         default:                     dir = "??"; break;
101         }
102         switch (_IOC_TYPE(cmd)) {
103         case 'v':
104                 printk(KERN_DEBUG "%s: ioctl 0x%08x (v4l1, %s, VIDIOC%s)\n",
105                        name, cmd, dir, (_IOC_NR(cmd) < V4L1_IOCTLS) ?
106                        v4l1_ioctls[_IOC_NR(cmd)] : "???");
107                 break;
108         case 'V':
109                 printk(KERN_DEBUG "%s: ioctl 0x%08x (v4l2, %s, VIDIOC_%s)\n",
110                        name, cmd, dir, (_IOC_NR(cmd) < V4L2_IOCTLS) ?
111                        v4l2_ioctls[_IOC_NR(cmd)] : "???");
112                 break;
113         default:
114                 printk(KERN_DEBUG "%s: ioctl 0x%08x (???, %s, #%d)\n",
115                        name, cmd, dir, _IOC_NR(cmd));
116         }
117 }
118
119 static void *rvmalloc(size_t size)
120 {
121         void *mem;
122         unsigned long adr;
123
124         size = PAGE_ALIGN(size);
125
126         mem = vmalloc_32((unsigned long)size);
127         if (!mem)
128                 return NULL;
129
130         memset(mem, 0, size);
131
132         adr = (unsigned long)mem;
133         while (size > 0) {
134                 SetPageReserved(vmalloc_to_page((void *)adr));
135                 adr += PAGE_SIZE;
136                 size -= PAGE_SIZE;
137         }
138
139         return mem;
140 }
141
142 static void rvfree(void *mem, size_t size)
143 {
144         unsigned long adr;
145
146         if (!mem)
147                 return;
148
149         size = PAGE_ALIGN(size);
150
151         adr = (unsigned long)mem;
152         while (size > 0) {
153                 ClearPageReserved(vmalloc_to_page((void *)adr));
154                 adr += PAGE_SIZE;
155                 size -= PAGE_SIZE;
156         }
157
158         vfree(mem);
159 }
160
161 /*
162  * em28xx_request_buffers()
163  * allocate a number of buffers
164  */
165 u32 em28xx_request_buffers(struct em28xx *dev, u32 count)
166 {
167         const size_t imagesize = PAGE_ALIGN(dev->frame_size);   /*needs to be page aligned cause the buffers can be mapped individually! */
168         void *buff = NULL;
169         u32 i;
170         em28xx_coredbg("requested %i buffers with size %i", count, imagesize);
171         if (count > EM28XX_NUM_FRAMES)
172                 count = EM28XX_NUM_FRAMES;
173
174         dev->num_frames = count;
175         while (dev->num_frames > 0) {
176                 if ((buff = rvmalloc(dev->num_frames * imagesize)))
177                         break;
178                 dev->num_frames--;
179         }
180
181         for (i = 0; i < dev->num_frames; i++) {
182                 dev->frame[i].bufmem = buff + i * imagesize;
183                 dev->frame[i].buf.index = i;
184                 dev->frame[i].buf.m.offset = i * imagesize;
185                 dev->frame[i].buf.length = dev->frame_size;
186                 dev->frame[i].buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
187                 dev->frame[i].buf.sequence = 0;
188                 dev->frame[i].buf.field = V4L2_FIELD_NONE;
189                 dev->frame[i].buf.memory = V4L2_MEMORY_MMAP;
190                 dev->frame[i].buf.flags = 0;
191         }
192         return dev->num_frames;
193 }
194
195 /*
196  * em28xx_queue_unusedframes()
197  * add all frames that are not currently in use to the inbuffer queue
198  */
199 void em28xx_queue_unusedframes(struct em28xx *dev)
200 {
201         unsigned long lock_flags;
202         u32 i;
203
204         for (i = 0; i < dev->num_frames; i++)
205                 if (dev->frame[i].state == F_UNUSED) {
206                         dev->frame[i].state = F_QUEUED;
207                         spin_lock_irqsave(&dev->queue_lock, lock_flags);
208                         list_add_tail(&dev->frame[i].frame, &dev->inqueue);
209                         spin_unlock_irqrestore(&dev->queue_lock, lock_flags);
210                 }
211 }
212
213 /*
214  * em28xx_release_buffers()
215  * free frame buffers
216  */
217 void em28xx_release_buffers(struct em28xx *dev)
218 {
219         if (dev->num_frames) {
220                 rvfree(dev->frame[0].bufmem,
221                        dev->num_frames * PAGE_ALIGN(dev->frame[0].buf.length));
222                 dev->num_frames = 0;
223         }
224 }
225
226 /*
227  * em28xx_read_reg_req()
228  * reads data from the usb device specifying bRequest
229  */
230 int em28xx_read_reg_req_len(struct em28xx *dev, u8 req, u16 reg,
231                                    char *buf, int len)
232 {
233         int ret, byte;
234
235         em28xx_regdbg("req=%02x, reg=%02x ", req, reg);
236
237         ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), req,
238                               USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
239                               0x0000, reg, buf, len, HZ);
240
241         if (reg_debug){
242                 printk(ret < 0 ? " failed!\n" : "%02x values: ", ret);
243                 for (byte = 0; byte < len; byte++) {
244                         printk(" %02x", buf[byte]);
245                 }
246                 printk("\n");
247         }
248
249         return ret;
250 }
251
252 /*
253  * em28xx_read_reg_req()
254  * reads data from the usb device specifying bRequest
255  */
256 int em28xx_read_reg_req(struct em28xx *dev, u8 req, u16 reg)
257 {
258         u8 val;
259         int ret;
260
261         em28xx_regdbg("req=%02x, reg=%02x:", req, reg);
262
263         ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), req,
264                               USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
265                               0x0000, reg, &val, 1, HZ);
266
267         if (reg_debug)
268                 printk(ret < 0 ? " failed!\n" : "%02x\n", val);
269
270         if (ret < 0)
271                 return ret;
272
273         return val;
274 }
275
276 int em28xx_read_reg(struct em28xx *dev, u16 reg)
277 {
278         return em28xx_read_reg_req(dev, USB_REQ_GET_STATUS, reg);
279 }
280
281 /*
282  * em28xx_write_regs_req()
283  * sends data to the usb device, specifying bRequest
284  */
285 int em28xx_write_regs_req(struct em28xx *dev, u8 req, u16 reg, char *buf,
286                                  int len)
287 {
288         int ret;
289
290         /*usb_control_msg seems to expect a kmalloced buffer */
291         unsigned char *bufs = kmalloc(len, GFP_KERNEL);
292
293         em28xx_regdbg("req=%02x reg=%02x:", req, reg);
294
295         if (reg_debug) {
296                 int i;
297                 for (i = 0; i < len; ++i)
298                         printk (" %02x", (unsigned char)buf[i]);
299                 printk ("\n");
300         }
301
302         if (!bufs)
303                 return -ENOMEM;
304         memcpy(bufs, buf, len);
305         ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0), req,
306                               USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
307                               0x0000, reg, bufs, len, HZ);
308         mdelay(5);              /* FIXME: magic number */
309         kfree(bufs);
310         return ret;
311 }
312
313 int em28xx_write_regs(struct em28xx *dev, u16 reg, char *buf, int len)
314 {
315         return em28xx_write_regs_req(dev, USB_REQ_GET_STATUS, reg, buf, len);
316 }
317
318 /*
319  * em28xx_write_reg_bits()
320  * sets only some bits (specified by bitmask) of a register, by first reading
321  * the actual value
322  */
323 int em28xx_write_reg_bits(struct em28xx *dev, u16 reg, u8 val,
324                                  u8 bitmask)
325 {
326         int oldval;
327         u8 newval;
328         if ((oldval = em28xx_read_reg(dev, reg)) < 0)
329                 return oldval;
330         newval = (((u8) oldval) & ~bitmask) | (val & bitmask);
331         return em28xx_write_regs(dev, reg, &newval, 1);
332 }
333
334 /*
335  * em28xx_write_ac97()
336  * write a 16 bit value to the specified AC97 address (LSB first!)
337  */
338 int em28xx_write_ac97(struct em28xx *dev, u8 reg, u8 * val)
339 {
340         int ret;
341         u8 addr = reg & 0x7f;
342         if ((ret = em28xx_write_regs(dev, AC97LSB_REG, val, 2)) < 0)
343                 return ret;
344         if ((ret = em28xx_write_regs(dev, AC97ADDR_REG, &addr, 1)) < 0)
345                 return ret;
346         if ((ret = em28xx_read_reg(dev, AC97BUSY_REG)) < 0)
347                 return ret;
348         else if (((u8) ret) & 0x01) {
349                 em28xx_warn ("AC97 command still being exectuted: not handled properly!\n");
350         }
351         return 0;
352 }
353
354 int em28xx_audio_analog_set(struct em28xx *dev)
355 {
356         char s[2] = { 0x00, 0x00 };
357         s[0] |= 0x1f - dev->volume;
358         s[1] |= 0x1f - dev->volume;
359         if (dev->mute)
360                 s[1] |= 0x80;
361         return em28xx_write_ac97(dev, MASTER_AC97, s);
362 }
363
364
365 int em28xx_colorlevels_set_default(struct em28xx *dev)
366 {
367         em28xx_write_regs(dev, YGAIN_REG, "\x10", 1);   /* contrast */
368         em28xx_write_regs(dev, YOFFSET_REG, "\x00", 1); /* brightness */
369         em28xx_write_regs(dev, UVGAIN_REG, "\x10", 1);  /* saturation */
370         em28xx_write_regs(dev, UOFFSET_REG, "\x00", 1);
371         em28xx_write_regs(dev, VOFFSET_REG, "\x00", 1);
372         em28xx_write_regs(dev, SHARPNESS_REG, "\x00", 1);
373
374         em28xx_write_regs(dev, GAMMA_REG, "\x20", 1);
375         em28xx_write_regs(dev, RGAIN_REG, "\x20", 1);
376         em28xx_write_regs(dev, GGAIN_REG, "\x20", 1);
377         em28xx_write_regs(dev, BGAIN_REG, "\x20", 1);
378         em28xx_write_regs(dev, ROFFSET_REG, "\x00", 1);
379         em28xx_write_regs(dev, GOFFSET_REG, "\x00", 1);
380         return em28xx_write_regs(dev, BOFFSET_REG, "\x00", 1);
381 }
382
383 int em28xx_capture_start(struct em28xx *dev, int start)
384 {
385         int ret;
386         /* FIXME: which is the best order? */
387         /* video registers are sampled by VREF */
388         if ((ret = em28xx_write_reg_bits(dev, USBSUSP_REG, start ? 0x10 : 0x00,
389                                           0x10)) < 0)
390                 return ret;
391         /* enable video capture */
392         return em28xx_write_regs(dev, VINENABLE_REG, start ? "\x67" : "\x27", 1);
393 }
394
395 int em28xx_outfmt_set_yuv422(struct em28xx *dev)
396 {
397         em28xx_write_regs(dev, OUTFMT_REG, "\x34", 1);
398         em28xx_write_regs(dev, VINMODE_REG, "\x10", 1);
399         return em28xx_write_regs(dev, VINCTRL_REG, "\x11", 1);
400 }
401
402 int em28xx_accumulator_set(struct em28xx *dev, u8 xmin, u8 xmax, u8 ymin,
403                                   u8 ymax)
404 {
405         em28xx_coredbg("em28xx Scale: (%d,%d)-(%d,%d)\n", xmin, ymin, xmax, ymax);
406
407         em28xx_write_regs(dev, XMIN_REG, &xmin, 1);
408         em28xx_write_regs(dev, XMAX_REG, &xmax, 1);
409         em28xx_write_regs(dev, YMIN_REG, &ymin, 1);
410         return em28xx_write_regs(dev, YMAX_REG, &ymax, 1);
411 }
412
413 int em28xx_capture_area_set(struct em28xx *dev, u8 hstart, u8 vstart,
414                                    u16 width, u16 height)
415 {
416         u8 cwidth = width;
417         u8 cheight = height;
418         u8 overflow = (height >> 7 & 0x02) | (width >> 8 & 0x01);
419
420         em28xx_coredbg("em28xx Area Set: (%d,%d)\n", (width | (overflow & 2) << 7),
421                         (height | (overflow & 1) << 8));
422
423         em28xx_write_regs(dev, HSTART_REG, &hstart, 1);
424         em28xx_write_regs(dev, VSTART_REG, &vstart, 1);
425         em28xx_write_regs(dev, CWIDTH_REG, &cwidth, 1);
426         em28xx_write_regs(dev, CHEIGHT_REG, &cheight, 1);
427         return em28xx_write_regs(dev, OFLOW_REG, &overflow, 1);
428 }
429
430 int em28xx_scaler_set(struct em28xx *dev, u16 h, u16 v)
431 {
432         u8 mode;
433         /* the em2800 scaler only supports scaling down to 50% */
434         if(dev->is_em2800)
435                 mode = (v ? 0x20 : 0x00) | (h ? 0x10 : 0x00);
436         else {
437                 u8 buf[2];
438                 buf[0] = h;
439                 buf[1] = h >> 8;
440                 em28xx_write_regs(dev, HSCALELOW_REG, (char *)buf, 2);
441                 buf[0] = v;
442                 buf[1] = v >> 8;
443                 em28xx_write_regs(dev, VSCALELOW_REG, (char *)buf, 2);
444                 /* it seems that both H and V scalers must be active to work correctly */
445                 mode = (h || v)? 0x30: 0x00;
446         }
447         return em28xx_write_reg_bits(dev, COMPR_REG, mode, 0x30);
448 }
449
450 /* FIXME: this only function read values from dev */
451 int em28xx_resolution_set(struct em28xx *dev)
452 {
453         int width, height;
454         width = norm_maxw(dev);
455         height = norm_maxh(dev) >> 1;
456
457         em28xx_outfmt_set_yuv422(dev);
458         em28xx_accumulator_set(dev, 1, (width - 4) >> 2, 1, (height - 4) >> 2);
459         em28xx_capture_area_set(dev, 0, 0, width >> 2, height >> 2);
460         return em28xx_scaler_set(dev, dev->hscale, dev->vscale);
461 }
462
463
464 /******************* isoc transfer handling ****************************/
465
466 #ifdef ENABLE_DEBUG_ISOC_FRAMES
467 static void em28xx_isoc_dump(struct urb *urb, struct pt_regs *regs)
468 {
469         int len = 0;
470         int ntrans = 0;
471         int i;
472
473         printk(KERN_DEBUG "isocIrq: sf=%d np=%d ec=%x\n",
474                urb->start_frame, urb->number_of_packets,
475                urb->error_count);
476         for (i = 0; i < urb->number_of_packets; i++) {
477                 unsigned char *buf =
478                                 urb->transfer_buffer +
479                                 urb->iso_frame_desc[i].offset;
480                 int alen = urb->iso_frame_desc[i].actual_length;
481                 if (alen > 0) {
482                         if (buf[0] == 0x88) {
483                                 ntrans++;
484                                 len += alen;
485                         } else if (buf[0] == 0x22) {
486                                 printk(KERN_DEBUG
487                                                 "= l=%d nt=%d bpp=%d\n",
488                                 len - 4 * ntrans, ntrans,
489                                 ntrans == 0 ? 0 : len / ntrans);
490                                 ntrans = 1;
491                                 len = alen;
492                         } else
493                                 printk(KERN_DEBUG "!\n");
494                 }
495                 printk(KERN_DEBUG "   n=%d s=%d al=%d %x\n", i,
496                        urb->iso_frame_desc[i].status,
497                        urb->iso_frame_desc[i].actual_length,
498                        (unsigned int)
499                                        *((unsigned char *)(urb->transfer_buffer +
500                                        urb->iso_frame_desc[i].
501                                        offset)));
502         }
503 }
504 #endif
505
506 static inline int em28xx_isoc_video(struct em28xx *dev,struct em28xx_frame_t **f,
507                                     unsigned long *lock_flags, unsigned char buf)
508 {
509         if (!(buf & 0x01)) {
510                 if ((*f)->state == F_GRABBING) {
511                         /*previous frame is incomplete */
512                         if ((*f)->fieldbytesused < dev->field_size) {
513                                 (*f)->state = F_ERROR;
514                                 em28xx_isocdbg ("dropping incomplete bottom field (%i missing bytes)",
515                                          dev->field_size-(*f)->fieldbytesused);
516                         } else {
517                                 (*f)->state = F_DONE;
518                                 (*f)->buf.bytesused = dev->frame_size;
519                         }
520                 }
521                 if ((*f)->state == F_DONE || (*f)->state == F_ERROR) {
522                         /* move current frame to outqueue and get next free buffer from inqueue */
523                         spin_lock_irqsave(&dev-> queue_lock, *lock_flags);
524                         list_move_tail(&(*f)->frame, &dev->outqueue);
525                         if (!list_empty(&dev->inqueue))
526                                 (*f) = list_entry(dev-> inqueue.next,
527                         struct em28xx_frame_t,frame);
528                         else
529                                 (*f) = NULL;
530                         spin_unlock_irqrestore(&dev->queue_lock,*lock_flags);
531                 }
532                 if (!(*f)) {
533                         em28xx_isocdbg ("new frame but no buffer is free");
534                         return -1;
535                 }
536                 do_gettimeofday(&(*f)->buf.timestamp);
537                 (*f)->buf.sequence = ++dev->frame_count;
538                 (*f)->buf.field = V4L2_FIELD_INTERLACED;
539                 (*f)->state = F_GRABBING;
540                 (*f)->buf.bytesused = 0;
541                 (*f)->top_field = 1;
542                 (*f)->fieldbytesused = 0;
543         } else {
544                                         /* acquiring bottom field */
545                 if ((*f)->state == F_GRABBING) {
546                         if (!(*f)->top_field) {
547                                 (*f)->state = F_ERROR;
548                                 em28xx_isocdbg ("unexpected begin of bottom field; discarding it");
549                         } else if ((*f)-> fieldbytesused < dev->field_size - 172) {
550                                 (*f)->state = F_ERROR;
551                                 em28xx_isocdbg ("dropping incomplete top field (%i missing bytes)",
552                                          dev->field_size-(*f)->fieldbytesused);
553                         } else {
554                                 (*f)->top_field = 0;
555                                 (*f)->fieldbytesused = 0;
556                         }
557                 }
558         }
559         return (0);
560 }
561
562 static inline void em28xx_isoc_video_copy(struct em28xx *dev,
563                                           struct em28xx_frame_t **f, unsigned char *buf, int len)
564 {
565         void *fieldstart, *startwrite, *startread;
566         int linesdone, currlinedone, offset, lencopy,remain;
567
568         if(dev->frame_size != (*f)->buf.length){
569                 em28xx_err("frame_size %i and buf.length %i are different!!!\n",dev->frame_size,(*f)->buf.length);
570                 return;
571         }
572
573         if ((*f)->fieldbytesused + len > dev->field_size)
574                 len =dev->field_size - (*f)->fieldbytesused;
575
576         if (buf[0] != 0x88 && buf[0] != 0x22) {
577                 em28xx_isocdbg("frame is not complete\n");
578                 startread = buf;
579                 len+=4;
580         } else
581                 startread = buf + 4;
582
583         remain = len;
584
585         if ((*f)->top_field)
586                 fieldstart = (*f)->bufmem;
587         else
588                 fieldstart = (*f)->bufmem + dev->bytesperline;
589
590         linesdone = (*f)->fieldbytesused / dev->bytesperline;
591         currlinedone = (*f)->fieldbytesused % dev->bytesperline;
592         offset = linesdone * dev->bytesperline * 2 + currlinedone;
593         startwrite = fieldstart + offset;
594         lencopy = dev->bytesperline - currlinedone;
595         lencopy = lencopy > remain ? remain : lencopy;
596
597         memcpy(startwrite, startread, lencopy);
598         remain -= lencopy;
599
600         while (remain > 0) {
601                 startwrite += lencopy + dev->bytesperline;
602                 startread += lencopy;
603                 if (dev->bytesperline > remain)
604                         lencopy = remain;
605                 else
606                         lencopy = dev->bytesperline;
607
608                 memcpy(startwrite, startread, lencopy);
609                 remain -= lencopy;
610         }
611
612         (*f)->fieldbytesused += len;
613 }
614
615 /*
616  * em28xx_isoIrq()
617  * handles the incoming isoc urbs and fills the frames from our inqueue
618  */
619 void em28xx_isocIrq(struct urb *urb, struct pt_regs *regs)
620 {
621         struct em28xx *dev = urb->context;
622         int i, status;
623         struct em28xx_frame_t **f;
624         unsigned long lock_flags;
625
626         if (!dev)
627                 return;
628 #ifdef ENABLE_DEBUG_ISOC_FRAMES
629         if (isoc_debug>1)
630                 em28xx_isoc_dump(urb, regs);
631 #endif
632
633         if (urb->status == -ENOENT)
634                 return;
635
636         f = &dev->frame_current;
637
638         if (dev->stream == STREAM_INTERRUPT) {
639                 dev->stream = STREAM_OFF;
640                 if ((*f))
641                         (*f)->state = F_QUEUED;
642                 em28xx_isocdbg("stream interrupted");
643                 wake_up_interruptible(&dev->wait_stream);
644         }
645
646         if ((dev->state & DEV_DISCONNECTED) || (dev->state & DEV_MISCONFIGURED))
647                 return;
648
649         if (dev->stream == STREAM_ON && !list_empty(&dev->inqueue)) {
650                 if (!(*f))
651                         (*f) = list_entry(dev->inqueue.next,
652                 struct em28xx_frame_t, frame);
653
654                 for (i = 0; i < urb->number_of_packets; i++) {
655                         unsigned char *buf = urb->transfer_buffer +
656                                         urb->iso_frame_desc[i].offset;
657                         int len = urb->iso_frame_desc[i].actual_length - 4;
658
659                         if (urb->iso_frame_desc[i].status) {
660                                 em28xx_isocdbg("data error: [%d] len=%d, status=%d", i,
661                                         urb->iso_frame_desc[i].actual_length,
662                                         urb->iso_frame_desc[i].status);
663                                 if (urb->iso_frame_desc[i].status != -EPROTO)
664                                         continue;
665                         }
666                         if (urb->iso_frame_desc[i].actual_length <= 0) {
667                                 em28xx_isocdbg("packet %d is empty",i);
668                                 continue;
669                         }
670                         if (urb->iso_frame_desc[i].actual_length >
671                                                  dev->max_pkt_size) {
672                                 em28xx_isocdbg("packet bigger than packet size");
673                                 continue;
674                         }
675                         /*new frame */
676                         if (buf[0] == 0x22 && buf[1] == 0x5a) {
677                                 em28xx_isocdbg("Video frame, length=%i!",len);
678
679                                 if (em28xx_isoc_video(dev,f,&lock_flags,buf[2]))
680                                 break;
681                         } else if (buf[0]==0x33 && buf[1]==0x95 && buf[2]==0x00) {
682                                 em28xx_isocdbg("VBI HEADER!!!");
683                         }
684
685                         /* actual copying */
686                         if ((*f)->state == F_GRABBING) {
687                                 em28xx_isoc_video_copy(dev,f,buf, len);
688                         }
689                 }
690         }
691
692         for (i = 0; i < urb->number_of_packets; i++) {
693                 urb->iso_frame_desc[i].status = 0;
694                 urb->iso_frame_desc[i].actual_length = 0;
695         }
696
697         urb->status = 0;
698         if ((status = usb_submit_urb(urb, GFP_ATOMIC))) {
699                 em28xx_errdev("resubmit of urb failed (error=%i)\n", status);
700                 dev->state |= DEV_MISCONFIGURED;
701         }
702         wake_up_interruptible(&dev->wait_frame);
703         return;
704 }
705
706 /*
707  * em28xx_uninit_isoc()
708  * deallocates the buffers and urbs allocated during em28xx_init_iosc()
709  */
710 void em28xx_uninit_isoc(struct em28xx *dev)
711 {
712         int i;
713
714         for (i = 0; i < EM28XX_NUM_BUFS; i++) {
715                 if (dev->urb[i]) {
716                         usb_kill_urb(dev->urb[i]);
717                         if (dev->transfer_buffer[i]){
718                                 usb_buffer_free(dev->udev,(EM28XX_NUM_PACKETS*dev->max_pkt_size),dev->transfer_buffer[i],dev->urb[i]->transfer_dma);
719                         }
720                         usb_free_urb(dev->urb[i]);
721                 }
722                 dev->urb[i] = NULL;
723                 dev->transfer_buffer[i] = NULL;
724         }
725         em28xx_capture_start(dev, 0);
726 }
727
728 /*
729  * em28xx_init_isoc()
730  * allocates transfer buffers and submits the urbs for isoc transfer
731  */
732 int em28xx_init_isoc(struct em28xx *dev)
733 {
734         /* change interface to 3 which allowes the biggest packet sizes */
735         int i, errCode;
736         const int sb_size = EM28XX_NUM_PACKETS * dev->max_pkt_size;
737
738         /* reset streaming vars */
739         dev->frame_current = NULL;
740         dev->frame_count = 0;
741
742         /* allocate urbs */
743         for (i = 0; i < EM28XX_NUM_BUFS; i++) {
744                 struct urb *urb;
745                 int j, k;
746                 /* allocate transfer buffer */
747                 urb = usb_alloc_urb(EM28XX_NUM_PACKETS, GFP_KERNEL);
748                 if (!urb){
749                         em28xx_errdev("cannot alloc urb %i\n", i);
750                         em28xx_uninit_isoc(dev);
751                         return -ENOMEM;
752                 }
753                 dev->transfer_buffer[i] = usb_buffer_alloc(dev->udev, sb_size, GFP_KERNEL,&urb->transfer_dma);
754                 if (!dev->transfer_buffer[i]) {
755                         em28xx_errdev
756                                         ("unable to allocate %i bytes for transfer buffer %i\n",
757                                          sb_size, i);
758                         em28xx_uninit_isoc(dev);
759                         return -ENOMEM;
760                 }
761                 memset(dev->transfer_buffer[i], 0, sb_size);
762                 urb->dev = dev->udev;
763                 urb->context = dev;
764                 urb->pipe = usb_rcvisocpipe(dev->udev, 0x82);
765                 urb->transfer_flags = URB_ISO_ASAP;
766                 urb->interval = 1;
767                 urb->transfer_buffer = dev->transfer_buffer[i];
768                 urb->complete = em28xx_isocIrq;
769                 urb->number_of_packets = EM28XX_NUM_PACKETS;
770                 urb->transfer_buffer_length = sb_size;
771                 for (j = k = 0; j < EM28XX_NUM_PACKETS;
772                                 j++, k += dev->max_pkt_size) {
773                         urb->iso_frame_desc[j].offset = k;
774                         urb->iso_frame_desc[j].length =
775                                 dev->max_pkt_size;
776                 }
777                 dev->urb[i] = urb;
778         }
779
780         /* submit urbs */
781         for (i = 0; i < EM28XX_NUM_BUFS; i++) {
782                 errCode = usb_submit_urb(dev->urb[i], GFP_KERNEL);
783                 if (errCode) {
784                         em28xx_errdev("submit of urb %i failed (error=%i)\n", i,
785                                       errCode);
786                         em28xx_uninit_isoc(dev);
787                         return errCode;
788                 }
789         }
790
791         return 0;
792 }
793
794 int em28xx_set_alternate(struct em28xx *dev)
795 {
796         int errCode, prev_alt = dev->alt;
797         dev->alt = alt;
798         if (dev->alt == 0) {
799                 int i;
800                 for(i=0;i< dev->num_alt; i++)
801                         if(dev->alt_max_pkt_size[i]>dev->alt_max_pkt_size[dev->alt])
802                                 dev->alt=i;
803         }
804
805         if (dev->alt != prev_alt) {
806                 dev->max_pkt_size = dev->alt_max_pkt_size[dev->alt];
807                 em28xx_coredbg("setting alternate %d with wMaxPacketSize=%u\n", dev->alt,
808                        dev->max_pkt_size);
809                 errCode = usb_set_interface(dev->udev, 0, dev->alt);
810                 if (errCode < 0) {
811                         em28xx_errdev ("cannot change alternate number to %d (error=%i)\n",
812                                                         dev->alt, errCode);
813                         return errCode;
814                 }
815         }
816         return 0;
817 }