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