ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / media / usbvideo.c
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2, or (at your option)
5  * any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15  */
16
17 #include <linux/kernel.h>
18 #include <linux/sched.h>
19 #include <linux/list.h>
20 #include <linux/slab.h>
21 #include <linux/module.h>
22 #include <linux/mm.h>
23 #include <linux/smp_lock.h>
24 #include <linux/vmalloc.h>
25 #include <linux/init.h>
26 #include <linux/spinlock.h>
27
28 #include <asm/io.h>
29
30 #include "usbvideo.h"
31
32 #if defined(MAP_NR)
33 #define virt_to_page(v) MAP_NR(v)       /* Kernels 2.2.x */
34 #endif
35
36 static int video_nr = -1;
37 MODULE_PARM(video_nr, "i");
38
39 /*
40  * Local prototypes.
41  */
42 static void usbvideo_Disconnect(struct usb_interface *intf);
43 static void usbvideo_CameraRelease(struct uvd *uvd);
44
45 static int usbvideo_v4l_ioctl(struct inode *inode, struct file *file,
46                               unsigned int cmd, unsigned long arg);
47 static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma);
48 static int usbvideo_v4l_open(struct inode *inode, struct file *file);
49 static ssize_t usbvideo_v4l_read(struct file *file, char *buf,
50                              size_t count, loff_t *ppos);
51 static int usbvideo_v4l_close(struct inode *inode, struct file *file);
52
53 static int usbvideo_StartDataPump(struct uvd *uvd);
54 static void usbvideo_StopDataPump(struct uvd *uvd);
55 static int usbvideo_GetFrame(struct uvd *uvd, int frameNum);
56 static int usbvideo_NewFrame(struct uvd *uvd, int framenum);
57 static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd,
58                                                 struct usbvideo_frame *frame);
59
60 /*******************************/
61 /* Memory management functions */
62 /*******************************/
63
64 /*
65  * Here we want the physical address of the memory.
66  * This is used when initializing the contents of the area.
67  */
68 unsigned long usbvideo_kvirt_to_pa(unsigned long adr)
69 {
70         unsigned long kva, ret;
71
72         kva = (unsigned long) page_address(vmalloc_to_page((void *)adr));
73         kva |= adr & (PAGE_SIZE-1); /* restore the offset */
74         ret = __pa(kva);
75         return ret;
76 }
77
78 static void *usbvideo_rvmalloc(unsigned long size)
79 {
80         void *mem;
81         unsigned long adr;
82
83         size = PAGE_ALIGN(size);
84         mem = vmalloc_32(size);
85         if (!mem)
86                 return NULL;
87
88         memset(mem, 0, size); /* Clear the ram out, no junk to the user */
89         adr = (unsigned long) mem;
90         while (size > 0) {
91                 SetPageReserved(vmalloc_to_page((void *)adr));
92                 adr += PAGE_SIZE;
93                 size -= PAGE_SIZE;
94         }
95
96         return mem;
97 }
98
99 static void usbvideo_rvfree(void *mem, unsigned long size)
100 {
101         unsigned long adr;
102
103         if (!mem)
104                 return;
105
106         adr = (unsigned long) mem;
107         while ((long) size > 0) {
108                 ClearPageReserved(vmalloc_to_page((void *)adr));
109                 adr += PAGE_SIZE;
110                 size -= PAGE_SIZE;
111         }
112         vfree(mem);
113 }
114
115 static void RingQueue_Initialize(struct RingQueue *rq)
116 {
117         assert(rq != NULL);
118         init_waitqueue_head(&rq->wqh);
119 }
120
121 static void RingQueue_Allocate(struct RingQueue *rq, int rqLen)
122 {
123         /* Make sure the requested size is a power of 2 and
124            round up if necessary. This allows index wrapping
125            using masks rather than modulo */
126
127         int i = 1;
128         assert(rq != NULL);
129         assert(rqLen > 0);
130
131         while(rqLen >> i)
132                 i++;
133         if(rqLen != 1 << (i-1))
134                 rqLen = 1 << i;
135
136         rq->length = rqLen;
137         rq->ri = rq->wi = 0;
138         rq->queue = usbvideo_rvmalloc(rq->length);
139         assert(rq->queue != NULL);
140 }
141
142 static int RingQueue_IsAllocated(const struct RingQueue *rq)
143 {
144         if (rq == NULL)
145                 return 0;
146         return (rq->queue != NULL) && (rq->length > 0);
147 }
148
149 static void RingQueue_Free(struct RingQueue *rq)
150 {
151         assert(rq != NULL);
152         if (RingQueue_IsAllocated(rq)) {
153                 usbvideo_rvfree(rq->queue, rq->length);
154                 rq->queue = NULL;
155                 rq->length = 0;
156         }
157 }
158
159 int RingQueue_Dequeue(struct RingQueue *rq, unsigned char *dst, int len)
160 {
161         int rql, toread;
162
163         assert(rq != NULL);
164         assert(dst != NULL);
165
166         rql = RingQueue_GetLength(rq);
167         if(!rql)
168                 return 0;
169
170         /* Clip requested length to available data */
171         if(len > rql)
172                 len = rql;
173
174         toread = len;
175         if(rq->ri > rq->wi) {
176                 /* Read data from tail */
177                 int read = (toread < (rq->length - rq->ri)) ? toread : rq->length - rq->ri;
178                 memcpy(dst, rq->queue + rq->ri, read);
179                 toread -= read;
180                 dst += read;
181                 rq->ri = (rq->ri + read) & (rq->length-1);
182         }
183         if(toread) {
184                 /* Read data from head */
185                 memcpy(dst, rq->queue + rq->ri, toread);
186                 rq->ri = (rq->ri + toread) & (rq->length-1);
187         }
188         return len;
189 }
190
191 EXPORT_SYMBOL(RingQueue_Dequeue);
192
193 int RingQueue_Enqueue(struct RingQueue *rq, const unsigned char *cdata, int n)
194 {
195         int enqueued = 0;
196
197         assert(rq != NULL);
198         assert(cdata != NULL);
199         assert(rq->length > 0);
200         while (n > 0) {
201                 int m, q_avail;
202
203                 /* Calculate the largest chunk that fits the tail of the ring */
204                 q_avail = rq->length - rq->wi;
205                 if (q_avail <= 0) {
206                         rq->wi = 0;
207                         q_avail = rq->length;
208                 }
209                 m = n;
210                 assert(q_avail > 0);
211                 if (m > q_avail)
212                         m = q_avail;
213
214                 memcpy(rq->queue + rq->wi, cdata, m);
215                 RING_QUEUE_ADVANCE_INDEX(rq, wi, m);
216                 cdata += m;
217                 enqueued += m;
218                 n -= m;
219         }
220         return enqueued;
221 }
222
223 EXPORT_SYMBOL(RingQueue_Enqueue);
224
225 static void RingQueue_InterruptibleSleepOn(struct RingQueue *rq)
226 {
227         assert(rq != NULL);
228         interruptible_sleep_on(&rq->wqh);
229 }
230
231 void RingQueue_WakeUpInterruptible(struct RingQueue *rq)
232 {
233         assert(rq != NULL);
234         if (waitqueue_active(&rq->wqh))
235                 wake_up_interruptible(&rq->wqh);
236 }
237
238 EXPORT_SYMBOL(RingQueue_WakeUpInterruptible);
239
240 void RingQueue_Flush(struct RingQueue *rq)
241 {
242         assert(rq != NULL);
243         rq->ri = 0;
244         rq->wi = 0;
245 }
246
247 EXPORT_SYMBOL(RingQueue_Flush);
248
249
250 /*
251  * usbvideo_VideosizeToString()
252  *
253  * This procedure converts given videosize value to readable string.
254  *
255  * History:
256  * 07-Aug-2000 Created.
257  * 19-Oct-2000 Reworked for usbvideo module.
258  */
259 static void usbvideo_VideosizeToString(char *buf, int bufLen, videosize_t vs)
260 {
261         char tmp[40];
262         int n;
263
264         n = 1 + sprintf(tmp, "%ldx%ld", VIDEOSIZE_X(vs), VIDEOSIZE_Y(vs));
265         assert(n < sizeof(tmp));
266         if ((buf == NULL) || (bufLen < n))
267                 err("usbvideo_VideosizeToString: buffer is too small.");
268         else
269                 memmove(buf, tmp, n);
270 }
271
272 /*
273  * usbvideo_OverlayChar()
274  *
275  * History:
276  * 01-Feb-2000 Created.
277  */
278 static void usbvideo_OverlayChar(struct uvd *uvd, struct usbvideo_frame *frame,
279                                  int x, int y, int ch)
280 {
281         static const unsigned short digits[16] = {
282                 0xF6DE, /* 0 */
283                 0x2492, /* 1 */
284                 0xE7CE, /* 2 */
285                 0xE79E, /* 3 */
286                 0xB792, /* 4 */
287                 0xF39E, /* 5 */
288                 0xF3DE, /* 6 */
289                 0xF492, /* 7 */
290                 0xF7DE, /* 8 */
291                 0xF79E, /* 9 */
292                 0x77DA, /* a */
293                 0xD75C, /* b */
294                 0xF24E, /* c */
295                 0xD6DC, /* d */
296                 0xF34E, /* e */
297                 0xF348  /* f */
298         };
299         unsigned short digit;
300         int ix, iy;
301
302         if ((uvd == NULL) || (frame == NULL))
303                 return;
304
305         if (ch >= '0' && ch <= '9')
306                 ch -= '0';
307         else if (ch >= 'A' && ch <= 'F')
308                 ch = 10 + (ch - 'A');
309         else if (ch >= 'a' && ch <= 'f')
310                 ch = 10 + (ch - 'a');
311         else
312                 return;
313         digit = digits[ch];
314
315         for (iy=0; iy < 5; iy++) {
316                 for (ix=0; ix < 3; ix++) {
317                         if (digit & 0x8000) {
318                                 if (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24)) {
319 /* TODO */                              RGB24_PUTPIXEL(frame, x+ix, y+iy, 0xFF, 0xFF, 0xFF);
320                                 }
321                         }
322                         digit = digit << 1;
323                 }
324         }
325 }
326
327 /*
328  * usbvideo_OverlayString()
329  *
330  * History:
331  * 01-Feb-2000 Created.
332  */
333 static void usbvideo_OverlayString(struct uvd *uvd, struct usbvideo_frame *frame,
334                                    int x, int y, const char *str)
335 {
336         while (*str) {
337                 usbvideo_OverlayChar(uvd, frame, x, y, *str);
338                 str++;
339                 x += 4; /* 3 pixels character + 1 space */
340         }
341 }
342
343 /*
344  * usbvideo_OverlayStats()
345  *
346  * Overlays important debugging information.
347  *
348  * History:
349  * 01-Feb-2000 Created.
350  */
351 static void usbvideo_OverlayStats(struct uvd *uvd, struct usbvideo_frame *frame)
352 {
353         const int y_diff = 8;
354         char tmp[16];
355         int x = 10, y=10;
356         long i, j, barLength;
357         const int qi_x1 = 60, qi_y1 = 10;
358         const int qi_x2 = VIDEOSIZE_X(frame->request) - 10, qi_h = 10;
359
360         /* Call the user callback, see if we may proceed after that */
361         if (VALID_CALLBACK(uvd, overlayHook)) {
362                 if (GET_CALLBACK(uvd, overlayHook)(uvd, frame) < 0)
363                         return;
364         }
365
366         /*
367          * We draw a (mostly) hollow rectangle with qi_xxx coordinates.
368          * Left edge symbolizes the queue index 0; right edge symbolizes
369          * the full capacity of the queue.
370          */
371         barLength = qi_x2 - qi_x1 - 2;
372         if ((barLength > 10) && (uvd->paletteBits & (1L << VIDEO_PALETTE_RGB24))) {
373 /* TODO */      long u_lo, u_hi, q_used;
374                 long m_ri, m_wi, m_lo, m_hi;
375
376                 /*
377                  * Determine fill zones (used areas of the queue):
378                  * 0 xxxxxxx u_lo ...... uvd->dp.ri xxxxxxxx u_hi ..... uvd->dp.length
379                  *
380                  * if u_lo < 0 then there is no first filler.
381                  */
382
383                 q_used = RingQueue_GetLength(&uvd->dp);
384                 if ((uvd->dp.ri + q_used) >= uvd->dp.length) {
385                         u_hi = uvd->dp.length;
386                         u_lo = (q_used + uvd->dp.ri) & (uvd->dp.length-1);
387                 } else {
388                         u_hi = (q_used + uvd->dp.ri);
389                         u_lo = -1;
390                 }
391
392                 /* Convert byte indices into screen units */
393                 m_ri = qi_x1 + ((barLength * uvd->dp.ri) / uvd->dp.length);
394                 m_wi = qi_x1 + ((barLength * uvd->dp.wi) / uvd->dp.length);
395                 m_lo = (u_lo > 0) ? (qi_x1 + ((barLength * u_lo) / uvd->dp.length)) : -1;
396                 m_hi = qi_x1 + ((barLength * u_hi) / uvd->dp.length);
397
398                 for (j=qi_y1; j < (qi_y1 + qi_h); j++) {
399                         for (i=qi_x1; i < qi_x2; i++) {
400                                 /* Draw border lines */
401                                 if ((j == qi_y1) || (j == (qi_y1 + qi_h - 1)) ||
402                                     (i == qi_x1) || (i == (qi_x2 - 1))) {
403                                         RGB24_PUTPIXEL(frame, i, j, 0xFF, 0xFF, 0xFF);
404                                         continue;
405                                 }
406                                 /* For all other points the Y coordinate does not matter */
407                                 if ((i >= m_ri) && (i <= (m_ri + 3))) {
408                                         RGB24_PUTPIXEL(frame, i, j, 0x00, 0xFF, 0x00);
409                                 } else if ((i >= m_wi) && (i <= (m_wi + 3))) {
410                                         RGB24_PUTPIXEL(frame, i, j, 0xFF, 0x00, 0x00);
411                                 } else if ((i < m_lo) || ((i > m_ri) && (i < m_hi)))
412                                         RGB24_PUTPIXEL(frame, i, j, 0x00, 0x00, 0xFF);
413                         }
414                 }
415         }
416
417         sprintf(tmp, "%8lx", uvd->stats.frame_num);
418         usbvideo_OverlayString(uvd, frame, x, y, tmp);
419         y += y_diff;
420
421         sprintf(tmp, "%8lx", uvd->stats.urb_count);
422         usbvideo_OverlayString(uvd, frame, x, y, tmp);
423         y += y_diff;
424
425         sprintf(tmp, "%8lx", uvd->stats.urb_length);
426         usbvideo_OverlayString(uvd, frame, x, y, tmp);
427         y += y_diff;
428
429         sprintf(tmp, "%8lx", uvd->stats.data_count);
430         usbvideo_OverlayString(uvd, frame, x, y, tmp);
431         y += y_diff;
432
433         sprintf(tmp, "%8lx", uvd->stats.header_count);
434         usbvideo_OverlayString(uvd, frame, x, y, tmp);
435         y += y_diff;
436
437         sprintf(tmp, "%8lx", uvd->stats.iso_skip_count);
438         usbvideo_OverlayString(uvd, frame, x, y, tmp);
439         y += y_diff;
440
441         sprintf(tmp, "%8lx", uvd->stats.iso_err_count);
442         usbvideo_OverlayString(uvd, frame, x, y, tmp);
443         y += y_diff;
444
445         sprintf(tmp, "%8x", uvd->vpic.colour);
446         usbvideo_OverlayString(uvd, frame, x, y, tmp);
447         y += y_diff;
448
449         sprintf(tmp, "%8x", uvd->vpic.hue);
450         usbvideo_OverlayString(uvd, frame, x, y, tmp);
451         y += y_diff;
452
453         sprintf(tmp, "%8x", uvd->vpic.brightness >> 8);
454         usbvideo_OverlayString(uvd, frame, x, y, tmp);
455         y += y_diff;
456
457         sprintf(tmp, "%8x", uvd->vpic.contrast >> 12);
458         usbvideo_OverlayString(uvd, frame, x, y, tmp);
459         y += y_diff;
460
461         sprintf(tmp, "%8d", uvd->vpic.whiteness >> 8);
462         usbvideo_OverlayString(uvd, frame, x, y, tmp);
463         y += y_diff;
464 }
465
466 /*
467  * usbvideo_ReportStatistics()
468  *
469  * This procedure prints packet and transfer statistics.
470  *
471  * History:
472  * 14-Jan-2000 Corrected default multiplier.
473  */
474 static void usbvideo_ReportStatistics(const struct uvd *uvd)
475 {
476         if ((uvd != NULL) && (uvd->stats.urb_count > 0)) {
477                 unsigned long allPackets, badPackets, goodPackets, percent;
478                 allPackets = uvd->stats.urb_count * CAMERA_URB_FRAMES;
479                 badPackets = uvd->stats.iso_skip_count + uvd->stats.iso_err_count;
480                 goodPackets = allPackets - badPackets;
481                 /* Calculate percentage wisely, remember integer limits */
482                 assert(allPackets != 0);
483                 if (goodPackets < (((unsigned long)-1)/100))
484                         percent = (100 * goodPackets) / allPackets;
485                 else
486                         percent = goodPackets / (allPackets / 100);
487                 info("Packet Statistics: Total=%lu. Empty=%lu. Usage=%lu%%",
488                      allPackets, badPackets, percent);
489                 if (uvd->iso_packet_len > 0) {
490                         unsigned long allBytes, xferBytes;
491                         char multiplier = ' ';
492                         allBytes = allPackets * uvd->iso_packet_len;
493                         xferBytes = uvd->stats.data_count;
494                         assert(allBytes != 0);
495                         if (xferBytes < (((unsigned long)-1)/100))
496                                 percent = (100 * xferBytes) / allBytes;
497                         else
498                                 percent = xferBytes / (allBytes / 100);
499                         /* Scale xferBytes for easy reading */
500                         if (xferBytes > 10*1024) {
501                                 xferBytes /= 1024;
502                                 multiplier = 'K';
503                                 if (xferBytes > 10*1024) {
504                                         xferBytes /= 1024;
505                                         multiplier = 'M';
506                                         if (xferBytes > 10*1024) {
507                                                 xferBytes /= 1024;
508                                                 multiplier = 'G';
509                                                 if (xferBytes > 10*1024) {
510                                                         xferBytes /= 1024;
511                                                         multiplier = 'T';
512                                                 }
513                                         }
514                                 }
515                         }
516                         info("Transfer Statistics: Transferred=%lu%cB Usage=%lu%%",
517                              xferBytes, multiplier, percent);
518                 }
519         }
520 }
521
522 /*
523  * usbvideo_DrawLine()
524  *
525  * A standard implementation of Bresenham's line drawing algorithm.
526  * This procedure is provided primarily for debugging or demo
527  * purposes.
528  */
529 void usbvideo_DrawLine(
530         struct usbvideo_frame *frame,
531         int x1, int y1,
532         int x2, int y2,
533         unsigned char cr, unsigned char cg, unsigned char cb)
534 {
535         int i, dx, dy, np, d;
536         int dinc1, dinc2, x, xinc1, xinc2, y, yinc1, yinc2;
537
538         if ((dx = x2 - x1) < 0)
539                 dx = -dx;
540         if ((dy = y2 - y1) < 0)
541                 dy = -dy;
542         if (dx >= dy) {
543                 np = dx + 1;
544                 d = (2 * dy) - dx;
545                 dinc1 = dy << 1;
546                 dinc2 = (dy - dx) << 1;
547                 xinc1 = 1;
548                 xinc2 = 1;
549                 yinc1 = 0;
550                 yinc2 = 1;
551         } else {
552                 np = dy + 1;
553                 d = (2 * dx) - dy;
554                 dinc1 = dx << 1;
555                 dinc2 = (dx - dy) << 1;
556                 xinc1 = 0;
557                 xinc2 = 1;
558                 yinc1 = 1;
559                 yinc2 = 1;
560         }
561         /* Make sure x and y move in the right directions */
562         if (x1 > x2) {
563                 xinc1 = -xinc1;
564                 xinc2 = -xinc2;
565         }
566         if (y1 > y2) {
567                 yinc1 = -yinc1;
568                 yinc2 = -yinc2;
569         }
570         for (i=0, x=x1, y=y1; i < np; i++) {
571                 if (frame->palette == VIDEO_PALETTE_RGB24) {
572 /* TODO */              RGB24_PUTPIXEL(frame, x, y, cr, cg, cb);
573                 }
574                 if (d < 0) {
575                         d += dinc1;
576                         x += xinc1;
577                         y += yinc1;
578                 } else {
579                         d += dinc2;
580                         x += xinc2;
581                         y += yinc2;
582                 }
583         }
584 }
585
586 EXPORT_SYMBOL(usbvideo_DrawLine);
587
588 /*
589  * usbvideo_TestPattern()
590  *
591  * Procedure forms a test pattern (yellow grid on blue background).
592  *
593  * Parameters:
594  * fullframe: if TRUE then entire frame is filled, otherwise the procedure
595  *            continues from the current scanline.
596  * pmode      0: fill the frame with solid blue color (like on VCR or TV)
597  *            1: Draw a colored grid
598  *
599  * History:
600  * 01-Feb-2000 Created.
601  */
602 void usbvideo_TestPattern(struct uvd *uvd, int fullframe, int pmode)
603 {
604         struct usbvideo_frame *frame;
605         int num_cell = 0;
606         int scan_length = 0;
607         static int num_pass = 0;
608
609         if (uvd == NULL) {
610                 err("%s: uvd == NULL", __FUNCTION__);
611                 return;
612         }
613         if ((uvd->curframe < 0) || (uvd->curframe >= USBVIDEO_NUMFRAMES)) {
614                 err("%s: uvd->curframe=%d.", __FUNCTION__, uvd->curframe);
615                 return;
616         }
617
618         /* Grab the current frame */
619         frame = &uvd->frame[uvd->curframe];
620
621         /* Optionally start at the beginning */
622         if (fullframe) {
623                 frame->curline = 0;
624                 frame->seqRead_Length = 0;
625         }
626 #if 0
627         {       /* For debugging purposes only */
628                 char tmp[20];
629                 usbvideo_VideosizeToString(tmp, sizeof(tmp), frame->request);
630                 info("testpattern: frame=%s", tmp);
631         }
632 #endif
633         /* Form every scan line */
634         for (; frame->curline < VIDEOSIZE_Y(frame->request); frame->curline++) {
635                 int i;
636                 unsigned char *f = frame->data +
637                         (VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL * frame->curline);
638                 for (i=0; i < VIDEOSIZE_X(frame->request); i++) {
639                         unsigned char cb=0x80;
640                         unsigned char cg = 0;
641                         unsigned char cr = 0;
642
643                         if (pmode == 1) {
644                                 if (frame->curline % 32 == 0)
645                                         cb = 0, cg = cr = 0xFF;
646                                 else if (i % 32 == 0) {
647                                         if (frame->curline % 32 == 1)
648                                                 num_cell++;
649                                         cb = 0, cg = cr = 0xFF;
650                                 } else {
651                                         cb = ((num_cell*7) + num_pass) & 0xFF;
652                                         cg = ((num_cell*5) + num_pass*2) & 0xFF;
653                                         cr = ((num_cell*3) + num_pass*3) & 0xFF;
654                                 }
655                         } else {
656                                 /* Just the blue screen */
657                         }
658                                 
659                         *f++ = cb;
660                         *f++ = cg;
661                         *f++ = cr;
662                         scan_length += 3;
663                 }
664         }
665
666         frame->frameState = FrameState_Done;
667         frame->seqRead_Length += scan_length;
668         ++num_pass;
669
670         /* We do this unconditionally, regardless of FLAGS_OVERLAY_STATS */
671         usbvideo_OverlayStats(uvd, frame);
672 }
673
674 EXPORT_SYMBOL(usbvideo_TestPattern);
675
676 /*
677  * usbvideo_HexDump()
678  *
679  * A debugging tool. Prints hex dumps.
680  *
681  * History:
682  * 29-Jul-2000 Added printing of offsets.
683  */
684 void usbvideo_HexDump(const unsigned char *data, int len)
685 {
686         const int bytes_per_line = 32;
687         char tmp[128]; /* 32*3 + 5 */
688         int i, k;
689
690         for (i=k=0; len > 0; i++, len--) {
691                 if (i > 0 && ((i % bytes_per_line) == 0)) {
692                         printk("%s\n", tmp);
693                         k=0;
694                 }
695                 if ((i % bytes_per_line) == 0)
696                         k += sprintf(&tmp[k], "%04x: ", i);
697                 k += sprintf(&tmp[k], "%02x ", data[i]);
698         }
699         if (k > 0)
700                 printk("%s\n", tmp);
701 }
702
703 EXPORT_SYMBOL(usbvideo_HexDump);
704
705 /* Debugging aid */
706 void usbvideo_SayAndWait(const char *what)
707 {
708         wait_queue_head_t wq;
709         init_waitqueue_head(&wq);
710         info("Say: %s", what);
711         interruptible_sleep_on_timeout (&wq, HZ*3); /* Timeout */
712 }
713
714 EXPORT_SYMBOL(usbvideo_SayAndWait);
715
716 /* ******************************************************************** */
717
718 /* XXX: this piece of crap really wants some error handling.. */
719 static void usbvideo_ClientIncModCount(struct uvd *uvd)
720 {
721         if (uvd == NULL) {
722                 err("%s: uvd == NULL", __FUNCTION__);
723                 return;
724         }
725         if (uvd->handle == NULL) {
726                 err("%s: uvd->handle == NULL", __FUNCTION__);
727                 return;
728         }
729         if (uvd->handle->md_module == NULL) {
730                 err("%s: uvd->handle->md_module == NULL", __FUNCTION__);
731                 return;
732         }
733         if (!try_module_get(uvd->handle->md_module)) {
734                 err("%s: try_module_get() == 0", __FUNCTION__);
735                 return;
736         }
737 }
738
739 static void usbvideo_ClientDecModCount(struct uvd *uvd)
740 {
741         if (uvd == NULL) {
742                 err("%s: uvd == NULL", __FUNCTION__);
743                 return;
744         }
745         if (uvd->handle == NULL) {
746                 err("%s: uvd->handle == NULL", __FUNCTION__);
747                 return;
748         }
749         if (uvd->handle->md_module == NULL) {
750                 err("%s: uvd->handle->md_module == NULL", __FUNCTION__);
751                 return;
752         }
753         module_put(uvd->handle->md_module);
754 }
755
756 int usbvideo_register(
757         struct usbvideo **pCams,
758         const int num_cams,
759         const int num_extra,
760         const char *driverName,
761         const struct usbvideo_cb *cbTbl,
762         struct module *md,
763         const struct usb_device_id *id_table)
764 {
765         struct usbvideo *cams;
766         int i, base_size, result;
767
768         /* Check parameters for sanity */
769         if ((num_cams <= 0) || (pCams == NULL) || (cbTbl == NULL)) {
770                 err("%s: Illegal call", __FUNCTION__);
771                 return -EINVAL;
772         }
773
774         /* Check registration callback - must be set! */
775         if (cbTbl->probe == NULL) {
776                 err("%s: probe() is required!", __FUNCTION__);
777                 return -EINVAL;
778         }
779
780         base_size = num_cams * sizeof(struct uvd) + sizeof(struct usbvideo);
781         cams = (struct usbvideo *) kmalloc(base_size, GFP_KERNEL);
782         if (cams == NULL) {
783                 err("Failed to allocate %d. bytes for usbvideo struct", base_size);
784                 return -ENOMEM;
785         }
786         dbg("%s: Allocated $%p (%d. bytes) for %d. cameras",
787             __FUNCTION__, cams, base_size, num_cams);
788         memset(cams, 0, base_size);
789
790         /* Copy callbacks, apply defaults for those that are not set */
791         memmove(&cams->cb, cbTbl, sizeof(cams->cb));
792         if (cams->cb.getFrame == NULL)
793                 cams->cb.getFrame = usbvideo_GetFrame;
794         if (cams->cb.disconnect == NULL)
795                 cams->cb.disconnect = usbvideo_Disconnect;
796         if (cams->cb.startDataPump == NULL)
797                 cams->cb.startDataPump = usbvideo_StartDataPump;
798         if (cams->cb.stopDataPump == NULL)
799                 cams->cb.stopDataPump = usbvideo_StopDataPump;
800
801         cams->num_cameras = num_cams;
802         cams->cam = (struct uvd *) &cams[1];
803         cams->md_module = md;
804         if (cams->md_module == NULL)
805                 warn("%s: module == NULL!", __FUNCTION__);
806         init_MUTEX(&cams->lock);        /* to 1 == available */
807
808         for (i = 0; i < num_cams; i++) {
809                 struct uvd *up = &cams->cam[i];
810
811                 up->handle = cams;
812
813                 /* Allocate user_data separately because of kmalloc's limits */
814                 if (num_extra > 0) {
815                         up->user_size = num_cams * num_extra;
816                         up->user_data = (char *) kmalloc(up->user_size, GFP_KERNEL);
817                         if (up->user_data == NULL) {
818                                 err("%s: Failed to allocate user_data (%d. bytes)",
819                                     __FUNCTION__, up->user_size);
820                                 while (i) {
821                                         up = &cams->cam[--i];
822                                         kfree(up->user_data);
823                                 }
824                                 kfree(cams);
825                                 return -ENOMEM;
826                         }
827                         dbg("%s: Allocated cams[%d].user_data=$%p (%d. bytes)",
828                              __FUNCTION__, i, up->user_data, up->user_size);
829                 }
830         }
831
832         /*
833          * Register ourselves with USB stack.
834          */
835         strcpy(cams->drvName, (driverName != NULL) ? driverName : "Unknown");
836         cams->usbdrv.name = cams->drvName;
837         cams->usbdrv.probe = cams->cb.probe;
838         cams->usbdrv.disconnect = cams->cb.disconnect;
839         cams->usbdrv.id_table = id_table;
840
841         /*
842          * Update global handle to usbvideo. This is very important
843          * because probe() can be called before usb_register() returns.
844          * If the handle is not yet updated then the probe() will fail.
845          */
846         *pCams = cams;
847         result = usb_register(&cams->usbdrv);
848         if (result) {
849                 for (i = 0; i < num_cams; i++) {
850                         struct uvd *up = &cams->cam[i];
851                         kfree(up->user_data);
852                 }
853                 kfree(cams);
854         }
855
856         return result;
857 }
858
859 EXPORT_SYMBOL(usbvideo_register);
860
861 /*
862  * usbvideo_Deregister()
863  *
864  * Procedure frees all usbvideo and user data structures. Be warned that
865  * if you had some dynamically allocated components in ->user field then
866  * you should free them before calling here.
867  */
868 void usbvideo_Deregister(struct usbvideo **pCams)
869 {
870         struct usbvideo *cams;
871         int i;
872
873         if (pCams == NULL) {
874                 err("%s: pCams == NULL", __FUNCTION__);
875                 return;
876         }
877         cams = *pCams;
878         if (cams == NULL) {
879                 err("%s: cams == NULL", __FUNCTION__);
880                 return;
881         }
882
883         dbg("%s: Deregistering %s driver.", __FUNCTION__, cams->drvName);
884         usb_deregister(&cams->usbdrv);
885
886         dbg("%s: Deallocating cams=$%p (%d. cameras)", __FUNCTION__, cams, cams->num_cameras);
887         for (i=0; i < cams->num_cameras; i++) {
888                 struct uvd *up = &cams->cam[i];
889                 int warning = 0;
890
891                 if (up->user_data != NULL) {
892                         if (up->user_size <= 0)
893                                 ++warning;
894                 } else {
895                         if (up->user_size > 0)
896                                 ++warning;
897                 }
898                 if (warning) {
899                         err("%s: Warning: user_data=$%p user_size=%d.",
900                             __FUNCTION__, up->user_data, up->user_size);
901                 } else {
902                         dbg("%s: Freeing %d. $%p->user_data=$%p",
903                             __FUNCTION__, i, up, up->user_data);
904                         kfree(up->user_data);
905                 }
906         }
907         /* Whole array was allocated in one chunk */
908         dbg("%s: Freed %d uvd structures",
909             __FUNCTION__, cams->num_cameras);
910         kfree(cams);
911         *pCams = NULL;
912 }
913
914 EXPORT_SYMBOL(usbvideo_Deregister);
915
916 /*
917  * usbvideo_Disconnect()
918  *
919  * This procedure stops all driver activity. Deallocation of
920  * the interface-private structure (pointed by 'ptr') is done now
921  * (if we don't have any open files) or later, when those files
922  * are closed. After that driver should be removable.
923  *
924  * This code handles surprise removal. The uvd->user is a counter which
925  * increments on open() and decrements on close(). If we see here that
926  * this counter is not 0 then we have a client who still has us opened.
927  * We set uvd->remove_pending flag as early as possible, and after that
928  * all access to the camera will gracefully fail. These failures should
929  * prompt client to (eventually) close the video device, and then - in
930  * usbvideo_v4l_close() - we decrement uvd->uvd_used and usage counter.
931  *
932  * History:
933  * 22-Jan-2000 Added polling of MOD_IN_USE to delay removal until all users gone.
934  * 27-Jan-2000 Reworked to allow pending disconnects; see xxx_close()
935  * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
936  * 19-Oct-2000 Moved to usbvideo module.
937  */
938 static void usbvideo_Disconnect(struct usb_interface *intf)
939 {
940         struct uvd *uvd = usb_get_intfdata (intf);
941         int i;
942
943         if (uvd == NULL) {
944                 err("%s($%p): Illegal call.", __FUNCTION__, intf);
945                 return;
946         }
947
948         usb_set_intfdata (intf, NULL);
949
950         usbvideo_ClientIncModCount(uvd);
951         if (uvd->debug > 0)
952                 info("%s(%p.)", __FUNCTION__, intf);
953
954         down(&uvd->lock);
955         uvd->remove_pending = 1; /* Now all ISO data will be ignored */
956
957         /* At this time we ask to cancel outstanding URBs */
958         GET_CALLBACK(uvd, stopDataPump)(uvd);
959
960         for (i=0; i < USBVIDEO_NUMSBUF; i++)
961                 usb_free_urb(uvd->sbuf[i].urb);
962
963         usb_put_dev(uvd->dev);
964         uvd->dev = NULL;            /* USB device is no more */
965
966         video_unregister_device(&uvd->vdev);
967         if (uvd->debug > 0)
968                 info("%s: Video unregistered.", __FUNCTION__);
969
970         if (uvd->user)
971                 info("%s: In use, disconnect pending.", __FUNCTION__);
972         else
973                 usbvideo_CameraRelease(uvd);
974         up(&uvd->lock);
975         info("USB camera disconnected.");
976
977         usbvideo_ClientDecModCount(uvd);
978 }
979
980 /*
981  * usbvideo_CameraRelease()
982  *
983  * This code does final release of uvd. This happens
984  * after the device is disconnected -and- all clients
985  * closed their files.
986  *
987  * History:
988  * 27-Jan-2000 Created.
989  */
990 static void usbvideo_CameraRelease(struct uvd *uvd)
991 {
992         if (uvd == NULL) {
993                 err("%s: Illegal call", __FUNCTION__);
994                 return;
995         }
996
997         RingQueue_Free(&uvd->dp);
998         if (VALID_CALLBACK(uvd, userFree))
999                 GET_CALLBACK(uvd, userFree)(uvd);
1000         uvd->uvd_used = 0;      /* This is atomic, no need to take mutex */
1001 }
1002
1003 /*
1004  * usbvideo_find_struct()
1005  *
1006  * This code searches the array of preallocated (static) structures
1007  * and returns index of the first one that isn't in use. Returns -1
1008  * if there are no free structures.
1009  *
1010  * History:
1011  * 27-Jan-2000 Created.
1012  */
1013 static int usbvideo_find_struct(struct usbvideo *cams)
1014 {
1015         int u, rv = -1;
1016
1017         if (cams == NULL) {
1018                 err("No usbvideo handle?");
1019                 return -1;
1020         }
1021         down(&cams->lock);
1022         for (u = 0; u < cams->num_cameras; u++) {
1023                 struct uvd *uvd = &cams->cam[u];
1024                 if (!uvd->uvd_used) /* This one is free */
1025                 {
1026                         uvd->uvd_used = 1;      /* In use now */
1027                         init_MUTEX(&uvd->lock); /* to 1 == available */
1028                         uvd->dev = NULL;
1029                         rv = u;
1030                         break;
1031                 }
1032         }
1033         up(&cams->lock);
1034         return rv;
1035 }
1036
1037 static struct file_operations usbvideo_fops = {
1038         .owner =  THIS_MODULE,
1039         .open =   usbvideo_v4l_open,
1040         .release =usbvideo_v4l_close,
1041         .read =   usbvideo_v4l_read,
1042         .mmap =   usbvideo_v4l_mmap,
1043         .ioctl =  usbvideo_v4l_ioctl,
1044         .llseek = no_llseek,
1045 };
1046 static struct video_device usbvideo_template = {
1047         .owner =      THIS_MODULE,
1048         .type =       VID_TYPE_CAPTURE,
1049         .hardware =   VID_HARDWARE_CPIA,
1050         .fops =       &usbvideo_fops,
1051 };
1052
1053 struct uvd *usbvideo_AllocateDevice(struct usbvideo *cams)
1054 {
1055         int i, devnum;
1056         struct uvd *uvd = NULL;
1057
1058         if (cams == NULL) {
1059                 err("No usbvideo handle?");
1060                 return NULL;
1061         }
1062
1063         devnum = usbvideo_find_struct(cams);
1064         if (devnum == -1) {
1065                 err("IBM USB camera driver: Too many devices!");
1066                 return NULL;
1067         }
1068         uvd = &cams->cam[devnum];
1069         dbg("Device entry #%d. at $%p", devnum, uvd);
1070
1071         /* Not relying upon caller we increase module counter ourselves */
1072         usbvideo_ClientIncModCount(uvd);
1073
1074         down(&uvd->lock);
1075         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1076                 uvd->sbuf[i].urb = usb_alloc_urb(FRAMES_PER_DESC, GFP_KERNEL);
1077                 if (uvd->sbuf[i].urb == NULL) {
1078                         err("usb_alloc_urb(%d.) failed.", FRAMES_PER_DESC);
1079                         uvd->uvd_used = 0;
1080                         uvd = NULL;
1081                         goto allocate_done;
1082                 }
1083         }
1084         uvd->user=0;
1085         uvd->remove_pending = 0;
1086         uvd->last_error = 0;
1087         RingQueue_Initialize(&uvd->dp);
1088
1089         /* Initialize video device structure */
1090         uvd->vdev = usbvideo_template;
1091         sprintf(uvd->vdev.name, "%.20s USB Camera", cams->drvName);
1092         /*
1093          * The client is free to overwrite those because we
1094          * return control to the client's probe function right now.
1095          */
1096 allocate_done:
1097         up (&uvd->lock);
1098         usbvideo_ClientDecModCount(uvd);
1099         return uvd;
1100 }
1101
1102 EXPORT_SYMBOL(usbvideo_AllocateDevice);
1103
1104 int usbvideo_RegisterVideoDevice(struct uvd *uvd)
1105 {
1106         char tmp1[20], tmp2[20];        /* Buffers for printing */
1107
1108         if (uvd == NULL) {
1109                 err("%s: Illegal call.", __FUNCTION__);
1110                 return -EINVAL;
1111         }
1112         if (uvd->video_endp == 0) {
1113                 info("%s: No video endpoint specified; data pump disabled.", __FUNCTION__);
1114         }
1115         if (uvd->paletteBits == 0) {
1116                 err("%s: No palettes specified!", __FUNCTION__);
1117                 return -EINVAL;
1118         }
1119         if (uvd->defaultPalette == 0) {
1120                 info("%s: No default palette!", __FUNCTION__);
1121         }
1122
1123         uvd->max_frame_size = VIDEOSIZE_X(uvd->canvas) *
1124                 VIDEOSIZE_Y(uvd->canvas) * V4L_BYTES_PER_PIXEL;
1125         usbvideo_VideosizeToString(tmp1, sizeof(tmp1), uvd->videosize);
1126         usbvideo_VideosizeToString(tmp2, sizeof(tmp2), uvd->canvas);
1127
1128         if (uvd->debug > 0) {
1129                 info("%s: iface=%d. endpoint=$%02x paletteBits=$%08lx",
1130                      __FUNCTION__, uvd->iface, uvd->video_endp, uvd->paletteBits);
1131         }
1132         if (video_register_device(&uvd->vdev, VFL_TYPE_GRABBER, video_nr) == -1) {
1133                 err("%s: video_register_device failed", __FUNCTION__);
1134                 return -EPIPE;
1135         }
1136         if (uvd->debug > 1) {
1137                 info("%s: video_register_device() successful", __FUNCTION__);
1138         }
1139         if (uvd->dev == NULL) {
1140                 err("%s: uvd->dev == NULL", __FUNCTION__);
1141                 return -EINVAL;
1142         }
1143
1144         info("%s on /dev/video%d: canvas=%s videosize=%s",
1145              (uvd->handle != NULL) ? uvd->handle->drvName : "???",
1146              uvd->vdev.minor, tmp2, tmp1);
1147
1148         usb_get_dev(uvd->dev);
1149         return 0;
1150 }
1151
1152 EXPORT_SYMBOL(usbvideo_RegisterVideoDevice);
1153
1154 /* ******************************************************************** */
1155
1156 static int usbvideo_v4l_mmap(struct file *file, struct vm_area_struct *vma)
1157 {
1158         struct uvd *uvd = file->private_data;
1159         unsigned long start = vma->vm_start;
1160         unsigned long size  = vma->vm_end-vma->vm_start;
1161         unsigned long page, pos;
1162
1163         if (!CAMERA_IS_OPERATIONAL(uvd))
1164                 return -EFAULT;
1165
1166         if (size > (((USBVIDEO_NUMFRAMES * uvd->max_frame_size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1)))
1167                 return -EINVAL;
1168
1169         pos = (unsigned long) uvd->fbuf;
1170         while (size > 0) {
1171                 page = usbvideo_kvirt_to_pa(pos);
1172                 if (remap_page_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
1173                         return -EAGAIN;
1174
1175                 start += PAGE_SIZE;
1176                 pos += PAGE_SIZE;
1177                 if (size > PAGE_SIZE)
1178                         size -= PAGE_SIZE;
1179                 else
1180                         size = 0;
1181         }
1182
1183         return 0;
1184 }
1185
1186 /*
1187  * usbvideo_v4l_open()
1188  *
1189  * This is part of Video 4 Linux API. The driver can be opened by one
1190  * client only (checks internal counter 'uvdser'). The procedure
1191  * then allocates buffers needed for video processing.
1192  *
1193  * History:
1194  * 22-Jan-2000 Rewrote, moved scratch buffer allocation here. Now the
1195  *             camera is also initialized here (once per connect), at
1196  *             expense of V4L client (it waits on open() call).
1197  * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1198  * 24-May-2000 Corrected to prevent race condition (MOD_xxx_USE_COUNT).
1199  */
1200 static int usbvideo_v4l_open(struct inode *inode, struct file *file)
1201 {
1202         struct video_device *dev = video_devdata(file);
1203         struct uvd *uvd = (struct uvd *) dev;
1204         const int sb_size = FRAMES_PER_DESC * uvd->iso_packet_len;
1205         int i, errCode = 0;
1206
1207         if (uvd->debug > 1)
1208                 info("%s($%p)", __FUNCTION__, dev);
1209
1210         usbvideo_ClientIncModCount(uvd);
1211         down(&uvd->lock);
1212
1213         if (uvd->user) {
1214                 err("%s: Someone tried to open an already opened device!", __FUNCTION__);
1215                 errCode = -EBUSY;
1216         } else {
1217                 /* Clear statistics */
1218                 memset(&uvd->stats, 0, sizeof(uvd->stats));
1219
1220                 /* Clean pointers so we know if we allocated something */
1221                 for (i=0; i < USBVIDEO_NUMSBUF; i++)
1222                         uvd->sbuf[i].data = NULL;
1223
1224                 /* Allocate memory for the frame buffers */
1225                 uvd->fbuf_size = USBVIDEO_NUMFRAMES * uvd->max_frame_size;
1226                 uvd->fbuf = usbvideo_rvmalloc(uvd->fbuf_size);
1227                 RingQueue_Allocate(&uvd->dp, RING_QUEUE_SIZE);
1228                 if ((uvd->fbuf == NULL) ||
1229                     (!RingQueue_IsAllocated(&uvd->dp))) {
1230                         err("%s: Failed to allocate fbuf or dp", __FUNCTION__);
1231                         errCode = -ENOMEM;
1232                 } else {
1233                         /* Allocate all buffers */
1234                         for (i=0; i < USBVIDEO_NUMFRAMES; i++) {
1235                                 uvd->frame[i].frameState = FrameState_Unused;
1236                                 uvd->frame[i].data = uvd->fbuf + i*(uvd->max_frame_size);
1237                                 /*
1238                                  * Set default sizes in case IOCTL (VIDIOCMCAPTURE)
1239                                  * is not used (using read() instead).
1240                                  */
1241                                 uvd->frame[i].canvas = uvd->canvas;
1242                                 uvd->frame[i].seqRead_Index = 0;
1243                         }
1244                         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1245                                 uvd->sbuf[i].data = kmalloc(sb_size, GFP_KERNEL);
1246                                 if (uvd->sbuf[i].data == NULL) {
1247                                         errCode = -ENOMEM;
1248                                         break;
1249                                 }
1250                         }
1251                 }
1252                 if (errCode != 0) {
1253                         /* Have to free all that memory */
1254                         if (uvd->fbuf != NULL) {
1255                                 usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1256                                 uvd->fbuf = NULL;
1257                         }
1258                         RingQueue_Free(&uvd->dp);
1259                         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1260                                 if (uvd->sbuf[i].data != NULL) {
1261                                         kfree (uvd->sbuf[i].data);
1262                                         uvd->sbuf[i].data = NULL;
1263                                 }
1264                         }
1265                 }
1266         }
1267
1268         /* If so far no errors then we shall start the camera */
1269         if (errCode == 0) {
1270                 /* Start data pump if we have valid endpoint */
1271                 if (uvd->video_endp != 0)
1272                         errCode = GET_CALLBACK(uvd, startDataPump)(uvd);
1273                 if (errCode == 0) {
1274                         if (VALID_CALLBACK(uvd, setupOnOpen)) {
1275                                 if (uvd->debug > 1)
1276                                         info("%s: setupOnOpen callback", __FUNCTION__);
1277                                 errCode = GET_CALLBACK(uvd, setupOnOpen)(uvd);
1278                                 if (errCode < 0) {
1279                                         err("%s: setupOnOpen callback failed (%d.).",
1280                                             __FUNCTION__, errCode);
1281                                 } else if (uvd->debug > 1) {
1282                                         info("%s: setupOnOpen callback successful", __FUNCTION__);
1283                                 }
1284                         }
1285                         if (errCode == 0) {
1286                                 uvd->settingsAdjusted = 0;
1287                                 if (uvd->debug > 1)
1288                                         info("%s: Open succeeded.", __FUNCTION__);
1289                                 uvd->user++;
1290                                 file->private_data = uvd;
1291                         }
1292                 }
1293         }
1294         up(&uvd->lock);
1295         if (errCode != 0)
1296                 usbvideo_ClientDecModCount(uvd);
1297         if (uvd->debug > 0)
1298                 info("%s: Returning %d.", __FUNCTION__, errCode);
1299         return errCode;
1300 }
1301
1302 /*
1303  * usbvideo_v4l_close()
1304  *
1305  * This is part of Video 4 Linux API. The procedure
1306  * stops streaming and deallocates all buffers that were earlier
1307  * allocated in usbvideo_v4l_open().
1308  *
1309  * History:
1310  * 22-Jan-2000 Moved scratch buffer deallocation here.
1311  * 27-Jan-2000 Used USBVIDEO_NUMSBUF as number of URB buffers.
1312  * 24-May-2000 Moved MOD_DEC_USE_COUNT outside of code that can sleep.
1313  */
1314 static int usbvideo_v4l_close(struct inode *inode, struct file *file)
1315 {
1316         struct video_device *dev = file->private_data;
1317         struct uvd *uvd = (struct uvd *) dev;
1318         int i;
1319
1320         if (uvd->debug > 1)
1321                 info("%s($%p)", __FUNCTION__, dev);
1322
1323         down(&uvd->lock);
1324         GET_CALLBACK(uvd, stopDataPump)(uvd);
1325         usbvideo_rvfree(uvd->fbuf, uvd->fbuf_size);
1326         uvd->fbuf = NULL;
1327         RingQueue_Free(&uvd->dp);
1328
1329         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1330                 kfree(uvd->sbuf[i].data);
1331                 uvd->sbuf[i].data = NULL;
1332         }
1333
1334 #if USBVIDEO_REPORT_STATS
1335         usbvideo_ReportStatistics(uvd);
1336 #endif    
1337
1338         uvd->user--;
1339         if (uvd->remove_pending) {
1340                 if (uvd->debug > 0)
1341                         info("usbvideo_v4l_close: Final disconnect.");
1342                 usbvideo_CameraRelease(uvd);
1343         }
1344         up(&uvd->lock);
1345         usbvideo_ClientDecModCount(uvd);
1346
1347         if (uvd->debug > 1)
1348                 info("%s: Completed.", __FUNCTION__);
1349         file->private_data = NULL;
1350         return 0;
1351 }
1352
1353 /*
1354  * usbvideo_v4l_ioctl()
1355  *
1356  * This is part of Video 4 Linux API. The procedure handles ioctl() calls.
1357  *
1358  * History:
1359  * 22-Jan-2000 Corrected VIDIOCSPICT to reject unsupported settings.
1360  */
1361 static int usbvideo_v4l_do_ioctl(struct inode *inode, struct file *file,
1362                                  unsigned int cmd, void *arg)
1363 {
1364         struct uvd *uvd = file->private_data;
1365
1366         if (!CAMERA_IS_OPERATIONAL(uvd))
1367                 return -EIO;
1368
1369         switch (cmd) {
1370                 case VIDIOCGCAP:
1371                 {
1372                         struct video_capability *b = arg;
1373                         *b = uvd->vcap;
1374                         return 0;
1375                 }
1376                 case VIDIOCGCHAN:
1377                 {
1378                         struct video_channel *v = arg;
1379                         *v = uvd->vchan;
1380                         return 0;
1381                 }
1382                 case VIDIOCSCHAN:
1383                 {       
1384                         struct video_channel *v = arg;
1385                         if (v->channel != 0)
1386                                 return -EINVAL;
1387                         return 0;
1388                 }
1389                 case VIDIOCGPICT:
1390                 {
1391                         struct video_picture *pic = arg;
1392                         *pic = uvd->vpic;
1393                         return 0;
1394                 }
1395                 case VIDIOCSPICT:
1396                 {
1397                         struct video_picture *pic = arg;
1398                         /*
1399                          * Use temporary 'video_picture' structure to preserve our
1400                          * own settings (such as color depth, palette) that we
1401                          * aren't allowing everyone (V4L client) to change.
1402                          */
1403                         uvd->vpic.brightness = pic->brightness;
1404                         uvd->vpic.hue = pic->hue;
1405                         uvd->vpic.colour = pic->colour;
1406                         uvd->vpic.contrast = pic->contrast;
1407                         uvd->settingsAdjusted = 0;      /* Will force new settings */
1408                         return 0;
1409                 }
1410                 case VIDIOCSWIN:
1411                 {
1412                         struct video_window *vw = arg;
1413
1414                         if(VALID_CALLBACK(uvd, setVideoMode)) {
1415                                 return GET_CALLBACK(uvd, setVideoMode)(uvd, vw);
1416                         }
1417
1418                         if (vw->flags)
1419                                 return -EINVAL;
1420                         if (vw->clipcount)
1421                                 return -EINVAL;
1422                         if (vw->width != VIDEOSIZE_X(uvd->canvas))
1423                                 return -EINVAL;
1424                         if (vw->height != VIDEOSIZE_Y(uvd->canvas))
1425                                 return -EINVAL;
1426
1427                         return 0;
1428                 }
1429                 case VIDIOCGWIN:
1430                 {
1431                         struct video_window *vw = arg;
1432
1433                         vw->x = 0;
1434                         vw->y = 0;
1435                         vw->width = VIDEOSIZE_X(uvd->videosize);
1436                         vw->height = VIDEOSIZE_Y(uvd->videosize);
1437                         vw->chromakey = 0;
1438                         if (VALID_CALLBACK(uvd, getFPS))
1439                                 vw->flags = GET_CALLBACK(uvd, getFPS)(uvd);
1440                         else 
1441                                 vw->flags = 10; /* FIXME: do better! */
1442                         return 0;
1443                 }
1444                 case VIDIOCGMBUF:
1445                 {
1446                         struct video_mbuf *vm = arg;
1447                         int i;
1448
1449                         memset(vm, 0, sizeof(*vm));
1450                         vm->size = uvd->max_frame_size * USBVIDEO_NUMFRAMES;
1451                         vm->frames = USBVIDEO_NUMFRAMES;
1452                         for(i = 0; i < USBVIDEO_NUMFRAMES; i++) 
1453                           vm->offsets[i] = i * uvd->max_frame_size;
1454
1455                         return 0;
1456                 }
1457                 case VIDIOCMCAPTURE:
1458                 {
1459                         struct video_mmap *vm = arg;
1460
1461                         if (uvd->debug >= 1) {
1462                                 info("VIDIOCMCAPTURE: frame=%d. size=%dx%d, format=%d.",
1463                                      vm->frame, vm->width, vm->height, vm->format);
1464                         }
1465                         /*
1466                          * Check if the requested size is supported. If the requestor
1467                          * requests too big a frame then we may be tricked into accessing
1468                          * outside of own preallocated frame buffer (in uvd->frame).
1469                          * This will cause oops or a security hole. Theoretically, we
1470                          * could only clamp the size down to acceptable bounds, but then
1471                          * we'd need to figure out how to insert our smaller buffer into
1472                          * larger caller's buffer... this is not an easy question. So we
1473                          * here just flatly reject too large requests, assuming that the
1474                          * caller will resubmit with smaller size. Callers should know
1475                          * what size we support (returned by VIDIOCGCAP). However vidcat,
1476                          * for one, does not care and allows to ask for any size.
1477                          */
1478                         if ((vm->width > VIDEOSIZE_X(uvd->canvas)) ||
1479                             (vm->height > VIDEOSIZE_Y(uvd->canvas))) {
1480                                 if (uvd->debug > 0) {
1481                                         info("VIDIOCMCAPTURE: Size=%dx%d too large; "
1482                                              "allowed only up to %ldx%ld", vm->width, vm->height,
1483                                              VIDEOSIZE_X(uvd->canvas), VIDEOSIZE_Y(uvd->canvas));
1484                                 }
1485                                 return -EINVAL;
1486                         }
1487                         /* Check if the palette is supported */
1488                         if (((1L << vm->format) & uvd->paletteBits) == 0) {
1489                                 if (uvd->debug > 0) {
1490                                         info("VIDIOCMCAPTURE: format=%d. not supported"
1491                                              " (paletteBits=$%08lx)",
1492                                              vm->format, uvd->paletteBits);
1493                                 }
1494                                 return -EINVAL;
1495                         }
1496                         if ((vm->frame < 0) || (vm->frame >= USBVIDEO_NUMFRAMES)) {
1497                                 err("VIDIOCMCAPTURE: vm.frame=%d. !E [0-%d]", vm->frame, USBVIDEO_NUMFRAMES-1);
1498                                 return -EINVAL;
1499                         }
1500                         if (uvd->frame[vm->frame].frameState == FrameState_Grabbing) {
1501                                 /* Not an error - can happen */
1502                         }
1503                         uvd->frame[vm->frame].request = VIDEOSIZE(vm->width, vm->height);
1504                         uvd->frame[vm->frame].palette = vm->format;
1505
1506                         /* Mark it as ready */
1507                         uvd->frame[vm->frame].frameState = FrameState_Ready;
1508
1509                         return usbvideo_NewFrame(uvd, vm->frame);
1510                 }
1511                 case VIDIOCSYNC:
1512                 {
1513                         int *frameNum = arg;
1514                         int ret;
1515
1516                         if (*frameNum < 0 || *frameNum >= USBVIDEO_NUMFRAMES)
1517                                 return -EINVAL;
1518                                 
1519                         if (uvd->debug >= 1)
1520                                 info("VIDIOCSYNC: syncing to frame %d.", *frameNum);
1521                         if (uvd->flags & FLAGS_NO_DECODING)
1522                                 ret = usbvideo_GetFrame(uvd, *frameNum);
1523                         else if (VALID_CALLBACK(uvd, getFrame)) {
1524                                 ret = GET_CALLBACK(uvd, getFrame)(uvd, *frameNum);
1525                                 if ((ret < 0) && (uvd->debug >= 1)) {
1526                                         err("VIDIOCSYNC: getFrame() returned %d.", ret);
1527                                 }
1528                         } else {
1529                                 err("VIDIOCSYNC: getFrame is not set");
1530                                 ret = -EFAULT;
1531                         }
1532
1533                         /*
1534                          * The frame is in FrameState_Done_Hold state. Release it
1535                          * right now because its data is already mapped into
1536                          * the user space and it's up to the application to
1537                          * make use of it until it asks for another frame.
1538                          */
1539                         uvd->frame[*frameNum].frameState = FrameState_Unused;
1540                         return ret;
1541                 }
1542                 case VIDIOCGFBUF:
1543                 {
1544                         struct video_buffer *vb = arg;
1545
1546                         memset(vb, 0, sizeof(*vb));
1547                         return 0;
1548                 }
1549                 case VIDIOCKEY:
1550                         return 0;
1551
1552                 case VIDIOCCAPTURE:
1553                         return -EINVAL;
1554
1555                 case VIDIOCSFBUF:
1556
1557                 case VIDIOCGTUNER:
1558                 case VIDIOCSTUNER:
1559
1560                 case VIDIOCGFREQ:
1561                 case VIDIOCSFREQ:
1562
1563                 case VIDIOCGAUDIO:
1564                 case VIDIOCSAUDIO:
1565                         return -EINVAL;
1566
1567                 default:
1568                         return -ENOIOCTLCMD;
1569         }
1570         return 0;
1571 }
1572
1573 static int usbvideo_v4l_ioctl(struct inode *inode, struct file *file,
1574                        unsigned int cmd, unsigned long arg)
1575 {
1576         return video_usercopy(inode, file, cmd, arg, usbvideo_v4l_do_ioctl);
1577 }
1578
1579 /*
1580  * usbvideo_v4l_read()
1581  *
1582  * This is mostly boring stuff. We simply ask for a frame and when it
1583  * arrives copy all the video data from it into user space. There is
1584  * no obvious need to override this method.
1585  *
1586  * History:
1587  * 20-Oct-2000 Created.
1588  * 01-Nov-2000 Added mutex (uvd->lock).
1589  */
1590 static ssize_t usbvideo_v4l_read(struct file *file, char *buf,
1591                       size_t count, loff_t *ppos)
1592 {
1593         struct uvd *uvd = file->private_data;
1594         int noblock = file->f_flags & O_NONBLOCK;
1595         int frmx = -1, i;
1596         struct usbvideo_frame *frame;
1597
1598         if (!CAMERA_IS_OPERATIONAL(uvd) || (buf == NULL))
1599                 return -EFAULT;
1600
1601         if (uvd->debug >= 1)
1602                 info("%s: %Zd. bytes, noblock=%d.", __FUNCTION__, count, noblock);
1603
1604         down(&uvd->lock);       
1605
1606         /* See if a frame is completed, then use it. */
1607         for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1608                 if ((uvd->frame[i].frameState == FrameState_Done) ||
1609                     (uvd->frame[i].frameState == FrameState_Done_Hold) ||
1610                     (uvd->frame[i].frameState == FrameState_Error)) {
1611                         frmx = i;
1612                         break;
1613                 }
1614         }
1615
1616         /* FIXME: If we don't start a frame here then who ever does? */
1617         if (noblock && (frmx == -1)) {
1618                 count = -EAGAIN;
1619                 goto read_done;
1620         }
1621
1622         /*
1623          * If no FrameState_Done, look for a FrameState_Grabbing state.
1624          * See if a frame is in process (grabbing), then use it.
1625          * We will need to wait until it becomes cooked, of course.
1626          */
1627         if (frmx == -1) {
1628                 for(i = 0; i < USBVIDEO_NUMFRAMES; i++) {
1629                         if (uvd->frame[i].frameState == FrameState_Grabbing) {
1630                                 frmx = i;
1631                                 break;
1632                         }
1633                 }
1634         }
1635
1636         /*
1637          * If no frame is active, start one. We don't care which one
1638          * it will be, so #0 is as good as any.
1639          * In read access mode we don't have convenience of VIDIOCMCAPTURE
1640          * to specify the requested palette (video format) on per-frame
1641          * basis. This means that we have to return data in -some- format
1642          * and just hope that the client knows what to do with it.
1643          * The default format is configured in uvd->defaultPalette field
1644          * as one of VIDEO_PALETTE_xxx values. We stuff it into the new
1645          * frame and initiate the frame filling process.
1646          */
1647         if (frmx == -1) {
1648                 if (uvd->defaultPalette == 0) {
1649                         err("%s: No default palette; don't know what to do!", __FUNCTION__);
1650                         count = -EFAULT;
1651                         goto read_done;
1652                 }
1653                 frmx = 0;
1654                 /*
1655                  * We have no per-frame control over video size.
1656                  * Therefore we only can use whatever size was
1657                  * specified as default.
1658                  */
1659                 uvd->frame[frmx].request = uvd->videosize;
1660                 uvd->frame[frmx].palette = uvd->defaultPalette;
1661                 uvd->frame[frmx].frameState = FrameState_Ready;
1662                 usbvideo_NewFrame(uvd, frmx);
1663                 /* Now frame 0 is supposed to start filling... */
1664         }
1665
1666         /*
1667          * Get a pointer to the active frame. It is either previously
1668          * completed frame or frame in progress but not completed yet.
1669          */
1670         frame = &uvd->frame[frmx];
1671
1672         /*
1673          * Sit back & wait until the frame gets filled and postprocessed.
1674          * If we fail to get the picture [in time] then return the error.
1675          * In this call we specify that we want the frame to be waited for,
1676          * postprocessed and switched into FrameState_Done_Hold state. This
1677          * state is used to hold the frame as "fully completed" between
1678          * subsequent partial reads of the same frame.
1679          */
1680         if (frame->frameState != FrameState_Done_Hold) {
1681                 long rv = -EFAULT;
1682                 if (uvd->flags & FLAGS_NO_DECODING)
1683                         rv = usbvideo_GetFrame(uvd, frmx);
1684                 else if (VALID_CALLBACK(uvd, getFrame))
1685                         rv = GET_CALLBACK(uvd, getFrame)(uvd, frmx);
1686                 else
1687                         err("getFrame is not set");
1688                 if ((rv != 0) || (frame->frameState != FrameState_Done_Hold)) {
1689                         count = rv;
1690                         goto read_done;
1691                 }
1692         }
1693
1694         /*
1695          * Copy bytes to user space. We allow for partial reads, which
1696          * means that the user application can request read less than
1697          * the full frame size. It is up to the application to issue
1698          * subsequent calls until entire frame is read.
1699          *
1700          * First things first, make sure we don't copy more than we
1701          * have - even if the application wants more. That would be
1702          * a big security embarassment!
1703          */
1704         if ((count + frame->seqRead_Index) > frame->seqRead_Length)
1705                 count = frame->seqRead_Length - frame->seqRead_Index;
1706
1707         /*
1708          * Copy requested amount of data to user space. We start
1709          * copying from the position where we last left it, which
1710          * will be zero for a new frame (not read before).
1711          */
1712         if (copy_to_user(buf, frame->data + frame->seqRead_Index, count)) {
1713                 count = -EFAULT;
1714                 goto read_done;
1715         }
1716
1717         /* Update last read position */
1718         frame->seqRead_Index += count;
1719         if (uvd->debug >= 1) {
1720                 err("%s: {copy} count used=%Zd, new seqRead_Index=%ld",
1721                         __FUNCTION__, count, frame->seqRead_Index);
1722         }
1723
1724         /* Finally check if the frame is done with and "release" it */
1725         if (frame->seqRead_Index >= frame->seqRead_Length) {
1726                 /* All data has been read */
1727                 frame->seqRead_Index = 0;
1728
1729                 /* Mark it as available to be used again. */
1730                 uvd->frame[frmx].frameState = FrameState_Unused;
1731                 if (usbvideo_NewFrame(uvd, (frmx + 1) % USBVIDEO_NUMFRAMES)) {
1732                         err("%s: usbvideo_NewFrame failed.", __FUNCTION__);
1733                 }
1734         }
1735 read_done:
1736         up(&uvd->lock); 
1737         return count;
1738 }
1739
1740 /*
1741  * Make all of the blocks of data contiguous
1742  */
1743 static int usbvideo_CompressIsochronous(struct uvd *uvd, struct urb *urb)
1744 {
1745         char *cdata;
1746         int i, totlen = 0;
1747
1748         for (i = 0; i < urb->number_of_packets; i++) {
1749                 int n = urb->iso_frame_desc[i].actual_length;
1750                 int st = urb->iso_frame_desc[i].status;
1751
1752                 cdata = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1753
1754                 /* Detect and ignore errored packets */
1755                 if (st < 0) {
1756                         if (uvd->debug >= 1)
1757                                 err("Data error: packet=%d. len=%d. status=%d.", i, n, st);
1758                         uvd->stats.iso_err_count++;
1759                         continue;
1760                 }
1761
1762                 /* Detect and ignore empty packets */
1763                 if (n <= 0) {
1764                         uvd->stats.iso_skip_count++;
1765                         continue;
1766                 }
1767                 totlen += n;    /* Little local accounting */
1768                 RingQueue_Enqueue(&uvd->dp, cdata, n);
1769         }
1770         return totlen;
1771 }
1772
1773 static void usbvideo_IsocIrq(struct urb *urb, struct pt_regs *regs)
1774 {
1775         int i, ret, len;
1776         struct uvd *uvd = urb->context;
1777
1778         /* We don't want to do anything if we are about to be removed! */
1779         if (!CAMERA_IS_OPERATIONAL(uvd))
1780                 return;
1781 #if 0
1782         if (urb->actual_length > 0) {
1783                 info("urb=$%p status=%d. errcount=%d. length=%d.",
1784                      urb, urb->status, urb->error_count, urb->actual_length);
1785         } else {
1786                 static int c = 0;
1787                 if (c++ % 100 == 0)
1788                         info("No Isoc data");
1789         }
1790 #endif
1791
1792         if (!uvd->streaming) {
1793                 if (uvd->debug >= 1)
1794                         info("Not streaming, but interrupt!");
1795                 return;
1796         }
1797         
1798         uvd->stats.urb_count++;
1799         if (urb->actual_length <= 0)
1800                 goto urb_done_with;
1801
1802         /* Copy the data received into ring queue */
1803         len = usbvideo_CompressIsochronous(uvd, urb);
1804         uvd->stats.urb_length = len;
1805         if (len <= 0)
1806                 goto urb_done_with;
1807
1808         /* Here we got some data */
1809         uvd->stats.data_count += len;
1810         RingQueue_WakeUpInterruptible(&uvd->dp);
1811
1812 urb_done_with:
1813         for (i = 0; i < FRAMES_PER_DESC; i++) {
1814                 urb->iso_frame_desc[i].status = 0;
1815                 urb->iso_frame_desc[i].actual_length = 0;
1816         }
1817         urb->status = 0;
1818         urb->dev = uvd->dev;
1819         ret = usb_submit_urb (urb, GFP_KERNEL);
1820         if(ret)
1821                 err("usb_submit_urb error (%d)", ret);
1822         return;
1823 }
1824
1825 /*
1826  * usbvideo_StartDataPump()
1827  *
1828  * History:
1829  * 27-Jan-2000 Used ibmcam->iface, ibmcam->ifaceAltActive instead
1830  *             of hardcoded values. Simplified by using for loop,
1831  *             allowed any number of URBs.
1832  */
1833 static int usbvideo_StartDataPump(struct uvd *uvd)
1834 {
1835         struct usb_device *dev = uvd->dev;
1836         int i, errFlag;
1837
1838         if (uvd->debug > 1)
1839                 info("%s($%p)", __FUNCTION__, uvd);
1840
1841         if (!CAMERA_IS_OPERATIONAL(uvd)) {
1842                 err("%s: Camera is not operational", __FUNCTION__);
1843                 return -EFAULT;
1844         }
1845         uvd->curframe = -1;
1846
1847         /* Alternate interface 1 is is the biggest frame size */
1848         i = usb_set_interface(dev, uvd->iface, uvd->ifaceAltActive);
1849         if (i < 0) {
1850                 err("%s: usb_set_interface error", __FUNCTION__);
1851                 uvd->last_error = i;
1852                 return -EBUSY;
1853         }
1854         if (VALID_CALLBACK(uvd, videoStart))
1855                 GET_CALLBACK(uvd, videoStart)(uvd);
1856         else 
1857                 err("%s: videoStart not set", __FUNCTION__);
1858
1859         /* We double buffer the Iso lists */
1860         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1861                 int j, k;
1862                 struct urb *urb = uvd->sbuf[i].urb;
1863                 urb->dev = dev;
1864                 urb->context = uvd;
1865                 urb->pipe = usb_rcvisocpipe(dev, uvd->video_endp);
1866                 urb->interval = 1;
1867                 urb->transfer_flags = URB_ISO_ASAP;
1868                 urb->transfer_buffer = uvd->sbuf[i].data;
1869                 urb->complete = usbvideo_IsocIrq;
1870                 urb->number_of_packets = FRAMES_PER_DESC;
1871                 urb->transfer_buffer_length = uvd->iso_packet_len * FRAMES_PER_DESC;
1872                 for (j=k=0; j < FRAMES_PER_DESC; j++, k += uvd->iso_packet_len) {
1873                         urb->iso_frame_desc[j].offset = k;
1874                         urb->iso_frame_desc[j].length = uvd->iso_packet_len;
1875                 }
1876         }
1877
1878         /* Submit all URBs */
1879         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1880                 errFlag = usb_submit_urb(uvd->sbuf[i].urb, GFP_KERNEL);
1881                 if (errFlag)
1882                         err("%s: usb_submit_isoc(%d) ret %d", __FUNCTION__, i, errFlag);
1883         }
1884
1885         uvd->streaming = 1;
1886         if (uvd->debug > 1)
1887                 info("%s: streaming=1 video_endp=$%02x", __FUNCTION__, uvd->video_endp);
1888         return 0;
1889 }
1890
1891 /*
1892  * usbvideo_StopDataPump()
1893  *
1894  * This procedure stops streaming and deallocates URBs. Then it
1895  * activates zero-bandwidth alt. setting of the video interface.
1896  *
1897  * History:
1898  * 22-Jan-2000 Corrected order of actions to work after surprise removal.
1899  * 27-Jan-2000 Used uvd->iface, uvd->ifaceAltInactive instead of hardcoded values.
1900  */
1901 static void usbvideo_StopDataPump(struct uvd *uvd)
1902 {
1903         int i, j;
1904
1905         if (uvd->debug > 1)
1906                 info("%s($%p)", __FUNCTION__, uvd);
1907
1908         if ((uvd == NULL) || (!uvd->streaming) || (uvd->dev == NULL))
1909                 return;
1910
1911         /* Unschedule all of the iso td's */
1912         for (i=0; i < USBVIDEO_NUMSBUF; i++) {
1913                 j = usb_unlink_urb(uvd->sbuf[i].urb);
1914                 if (j < 0)
1915                         err("%s: usb_unlink_urb() error %d.", __FUNCTION__, j);
1916         }
1917         if (uvd->debug > 1)
1918                 info("%s: streaming=0", __FUNCTION__);
1919         uvd->streaming = 0;
1920
1921         if (!uvd->remove_pending) {
1922                 /* Invoke minidriver's magic to stop the camera */
1923                 if (VALID_CALLBACK(uvd, videoStop))
1924                         GET_CALLBACK(uvd, videoStop)(uvd);
1925                 else 
1926                         err("%s: videoStop not set", __FUNCTION__);
1927
1928                 /* Set packet size to 0 */
1929                 j = usb_set_interface(uvd->dev, uvd->iface, uvd->ifaceAltInactive);
1930                 if (j < 0) {
1931                         err("%s: usb_set_interface() error %d.", __FUNCTION__, j);
1932                         uvd->last_error = j;
1933                 }
1934         }
1935 }
1936
1937 /*
1938  * usbvideo_NewFrame()
1939  *
1940  * History:
1941  * 29-Mar-00 Added copying of previous frame into the current one.
1942  * 6-Aug-00  Added model 3 video sizes, removed redundant width, height.
1943  */
1944 static int usbvideo_NewFrame(struct uvd *uvd, int framenum)
1945 {
1946         struct usbvideo_frame *frame;
1947         int n;
1948
1949         if (uvd->debug > 1)
1950                 info("usbvideo_NewFrame($%p,%d.)", uvd, framenum);
1951
1952         /* If we're not grabbing a frame right now and the other frame is */
1953         /*  ready to be grabbed into, then use it instead */
1954         if (uvd->curframe != -1)
1955                 return 0;
1956
1957         /* If necessary we adjust picture settings between frames */
1958         if (!uvd->settingsAdjusted) {
1959                 if (VALID_CALLBACK(uvd, adjustPicture))
1960                         GET_CALLBACK(uvd, adjustPicture)(uvd);
1961                 uvd->settingsAdjusted = 1;
1962         }
1963
1964         n = (framenum + 1) % USBVIDEO_NUMFRAMES;
1965         if (uvd->frame[n].frameState == FrameState_Ready)
1966                 framenum = n;
1967
1968         frame = &uvd->frame[framenum];
1969
1970         frame->frameState = FrameState_Grabbing;
1971         frame->scanstate = ScanState_Scanning;
1972         frame->seqRead_Length = 0;      /* Accumulated in xxx_parse_data() */
1973         frame->deinterlace = Deinterlace_None;
1974         frame->flags = 0; /* No flags yet, up to minidriver (or us) to set them */
1975         uvd->curframe = framenum;
1976
1977         /*
1978          * Normally we would want to copy previous frame into the current one
1979          * before we even start filling it with data; this allows us to stop
1980          * filling at any moment; top portion of the frame will be new and
1981          * bottom portion will stay as it was in previous frame. If we don't
1982          * do that then missing chunks of video stream will result in flickering
1983          * portions of old data whatever it was before.
1984          *
1985          * If we choose not to copy previous frame (to, for example, save few
1986          * bus cycles - the frame can be pretty large!) then we have an option
1987          * to clear the frame before using. If we experience losses in this
1988          * mode then missing picture will be black (no flickering).
1989          *
1990          * Finally, if user chooses not to clean the current frame before
1991          * filling it with data then the old data will be visible if we fail
1992          * to refill entire frame with new data.
1993          */
1994         if (!(uvd->flags & FLAGS_SEPARATE_FRAMES)) {
1995                 /* This copies previous frame into this one to mask losses */
1996                 int prev = (framenum - 1 + USBVIDEO_NUMFRAMES) % USBVIDEO_NUMFRAMES;
1997                 memmove(frame->data, uvd->frame[prev].data, uvd->max_frame_size);
1998         } else {
1999                 if (uvd->flags & FLAGS_CLEAN_FRAMES) {
2000                         /* This provides a "clean" frame but slows things down */
2001                         memset(frame->data, 0, uvd->max_frame_size);
2002                 }
2003         }
2004         return 0;
2005 }
2006
2007 /*
2008  * usbvideo_CollectRawData()
2009  *
2010  * This procedure can be used instead of 'processData' callback if you
2011  * only want to dump the raw data from the camera into the output
2012  * device (frame buffer). You can look at it with V4L client, but the
2013  * image will be unwatchable. The main purpose of this code and of the
2014  * mode FLAGS_NO_DECODING is debugging and capturing of datastreams from
2015  * new, unknown cameras. This procedure will be automatically invoked
2016  * instead of the specified callback handler when uvd->flags has bit
2017  * FLAGS_NO_DECODING set. Therefore, any regular build of any driver
2018  * based on usbvideo can use this feature at any time.
2019  */
2020 static void usbvideo_CollectRawData(struct uvd *uvd, struct usbvideo_frame *frame)
2021 {
2022         int n;
2023
2024         assert(uvd != NULL);
2025         assert(frame != NULL);
2026
2027         /* Try to move data from queue into frame buffer */
2028         n = RingQueue_GetLength(&uvd->dp);
2029         if (n > 0) {
2030                 int m;
2031                 /* See how much space we have left */
2032                 m = uvd->max_frame_size - frame->seqRead_Length;
2033                 if (n > m)
2034                         n = m;
2035                 /* Now move that much data into frame buffer */
2036                 RingQueue_Dequeue(
2037                         &uvd->dp,
2038                         frame->data + frame->seqRead_Length,
2039                         m);
2040                 frame->seqRead_Length += m;
2041         }
2042         /* See if we filled the frame */
2043         if (frame->seqRead_Length >= uvd->max_frame_size) {
2044                 frame->frameState = FrameState_Done;
2045                 uvd->curframe = -1;
2046                 uvd->stats.frame_num++;
2047         }
2048 }
2049
2050 static int usbvideo_GetFrame(struct uvd *uvd, int frameNum)
2051 {
2052         struct usbvideo_frame *frame = &uvd->frame[frameNum];
2053
2054         if (uvd->debug >= 2)
2055                 info("%s($%p,%d.)", __FUNCTION__, uvd, frameNum);
2056
2057         switch (frame->frameState) {
2058         case FrameState_Unused:
2059                 if (uvd->debug >= 2)
2060                         info("%s: FrameState_Unused", __FUNCTION__);
2061                 return -EINVAL;
2062         case FrameState_Ready:
2063         case FrameState_Grabbing:
2064         case FrameState_Error:
2065         {
2066                 int ntries, signalPending;
2067         redo:
2068                 if (!CAMERA_IS_OPERATIONAL(uvd)) {
2069                         if (uvd->debug >= 2)
2070                                 info("%s: Camera is not operational (1)", __FUNCTION__);
2071                         return -EIO;
2072                 }
2073                 ntries = 0; 
2074                 do {
2075                         RingQueue_InterruptibleSleepOn(&uvd->dp);
2076                         signalPending = signal_pending(current);
2077                         if (!CAMERA_IS_OPERATIONAL(uvd)) {
2078                                 if (uvd->debug >= 2)
2079                                         info("%s: Camera is not operational (2)", __FUNCTION__);
2080                                 return -EIO;
2081                         }
2082                         assert(uvd->fbuf != NULL);
2083                         if (signalPending) {
2084                                 if (uvd->debug >= 2)
2085                                         info("%s: Signal=$%08x", __FUNCTION__, signalPending);
2086                                 if (uvd->flags & FLAGS_RETRY_VIDIOCSYNC) {
2087                                         usbvideo_TestPattern(uvd, 1, 0);
2088                                         uvd->curframe = -1;
2089                                         uvd->stats.frame_num++;
2090                                         if (uvd->debug >= 2)
2091                                                 info("%s: Forced test pattern screen", __FUNCTION__);
2092                                         return 0;
2093                                 } else {
2094                                         /* Standard answer: Interrupted! */
2095                                         if (uvd->debug >= 2)
2096                                                 info("%s: Interrupted!", __FUNCTION__);
2097                                         return -EINTR;
2098                                 }
2099                         } else {
2100                                 /* No signals - we just got new data in dp queue */
2101                                 if (uvd->flags & FLAGS_NO_DECODING)
2102                                         usbvideo_CollectRawData(uvd, frame);
2103                                 else if (VALID_CALLBACK(uvd, processData))
2104                                         GET_CALLBACK(uvd, processData)(uvd, frame);
2105                                 else 
2106                                         err("%s: processData not set", __FUNCTION__);
2107                         }
2108                 } while (frame->frameState == FrameState_Grabbing);
2109                 if (uvd->debug >= 2) {
2110                         info("%s: Grabbing done; state=%d. (%lu. bytes)",
2111                              __FUNCTION__, frame->frameState, frame->seqRead_Length);
2112                 }
2113                 if (frame->frameState == FrameState_Error) {
2114                         int ret = usbvideo_NewFrame(uvd, frameNum);
2115                         if (ret < 0) {
2116                                 err("%s: usbvideo_NewFrame() failed (%d.)", __FUNCTION__, ret);
2117                                 return ret;
2118                         }
2119                         goto redo;
2120                 }
2121                 /* Note that we fall through to meet our destiny below */
2122         }
2123         case FrameState_Done:
2124                 /*
2125                  * Do all necessary postprocessing of data prepared in
2126                  * "interrupt" code and the collecting code above. The
2127                  * frame gets marked as FrameState_Done by queue parsing code.
2128                  * This status means that we collected enough data and
2129                  * most likely processed it as we went through. However
2130                  * the data may need postprocessing, such as deinterlacing
2131                  * or picture adjustments implemented in software (horror!)
2132                  *
2133                  * As soon as the frame becomes "final" it gets promoted to
2134                  * FrameState_Done_Hold status where it will remain until the
2135                  * caller consumed all the video data from the frame. Then
2136                  * the empty shell of ex-frame is thrown out for dogs to eat.
2137                  * But we, worried about pets, will recycle the frame!
2138                  */
2139                 uvd->stats.frame_num++;
2140                 if ((uvd->flags & FLAGS_NO_DECODING) == 0) {
2141                         if (VALID_CALLBACK(uvd, postProcess))
2142                                 GET_CALLBACK(uvd, postProcess)(uvd, frame);
2143                         if (frame->flags & USBVIDEO_FRAME_FLAG_SOFTWARE_CONTRAST)
2144                                 usbvideo_SoftwareContrastAdjustment(uvd, frame);
2145                 }
2146                 frame->frameState = FrameState_Done_Hold;
2147                 if (uvd->debug >= 2)
2148                         info("%s: Entered FrameState_Done_Hold state.", __FUNCTION__);
2149                 return 0;
2150
2151         case FrameState_Done_Hold:
2152                 /*
2153                  * We stay in this state indefinitely until someone external,
2154                  * like ioctl() or read() call finishes digesting the frame
2155                  * data. Then it will mark the frame as FrameState_Unused and
2156                  * it will be released back into the wild to roam freely.
2157                  */
2158                 if (uvd->debug >= 2)
2159                         info("%s: FrameState_Done_Hold state.", __FUNCTION__);
2160                 return 0;
2161         }
2162
2163         /* Catch-all for other cases. We shall not be here. */
2164         err("%s: Invalid state %d.", __FUNCTION__, frame->frameState);
2165         frame->frameState = FrameState_Unused;
2166         return 0;
2167 }
2168
2169 /*
2170  * usbvideo_DeinterlaceFrame()
2171  *
2172  * This procedure deinterlaces the given frame. Some cameras produce
2173  * only half of scanlines - sometimes only even lines, sometimes only
2174  * odd lines. The deinterlacing method is stored in frame->deinterlace
2175  * variable.
2176  *
2177  * Here we scan the frame vertically and replace missing scanlines with
2178  * average between surrounding ones - before and after. If we have no
2179  * line above then we just copy next line. Similarly, if we need to
2180  * create a last line then preceding line is used.
2181  */
2182 void usbvideo_DeinterlaceFrame(struct uvd *uvd, struct usbvideo_frame *frame)
2183 {
2184         if ((uvd == NULL) || (frame == NULL))
2185                 return;
2186
2187         if ((frame->deinterlace == Deinterlace_FillEvenLines) ||
2188             (frame->deinterlace == Deinterlace_FillOddLines))
2189         {
2190                 const int v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2191                 int i = (frame->deinterlace == Deinterlace_FillEvenLines) ? 0 : 1;
2192
2193                 for (; i < VIDEOSIZE_Y(frame->request); i += 2) {
2194                         const unsigned char *fs1, *fs2;
2195                         unsigned char *fd;
2196                         int ip, in, j;  /* Previous and next lines */
2197
2198                         /*
2199                          * Need to average lines before and after 'i'.
2200                          * If we go out of bounds seeking those lines then
2201                          * we point back to existing line.
2202                          */
2203                         ip = i - 1;     /* First, get rough numbers */
2204                         in = i + 1;
2205
2206                         /* Now validate */
2207                         if (ip < 0)
2208                                 ip = in;
2209                         if (in >= VIDEOSIZE_Y(frame->request))
2210                                 in = ip;
2211
2212                         /* Sanity check */
2213                         if ((ip < 0) || (in < 0) ||
2214                             (ip >= VIDEOSIZE_Y(frame->request)) ||
2215                             (in >= VIDEOSIZE_Y(frame->request)))
2216                         {
2217                                 err("Error: ip=%d. in=%d. req.height=%ld.",
2218                                     ip, in, VIDEOSIZE_Y(frame->request));
2219                                 break;
2220                         }
2221
2222                         /* Now we need to average lines 'ip' and 'in' to produce line 'i' */
2223                         fs1 = frame->data + (v4l_linesize * ip);
2224                         fs2 = frame->data + (v4l_linesize * in);
2225                         fd = frame->data + (v4l_linesize * i);
2226
2227                         /* Average lines around destination */
2228                         for (j=0; j < v4l_linesize; j++) {
2229                                 fd[j] = (unsigned char)((((unsigned) fs1[j]) +
2230                                                          ((unsigned)fs2[j])) >> 1);
2231                         }
2232                 }
2233         }
2234
2235         /* Optionally display statistics on the screen */
2236         if (uvd->flags & FLAGS_OVERLAY_STATS)
2237                 usbvideo_OverlayStats(uvd, frame);
2238 }
2239
2240 EXPORT_SYMBOL(usbvideo_DeinterlaceFrame);
2241
2242 /*
2243  * usbvideo_SoftwareContrastAdjustment()
2244  *
2245  * This code adjusts the contrast of the frame, assuming RGB24 format.
2246  * As most software image processing, this job is CPU-intensive.
2247  * Get a camera that supports hardware adjustment!
2248  *
2249  * History:
2250  * 09-Feb-2001  Created.
2251  */
2252 static void usbvideo_SoftwareContrastAdjustment(struct uvd *uvd, 
2253                                                 struct usbvideo_frame *frame)
2254 {
2255         int i, j, v4l_linesize;
2256         signed long adj;
2257         const int ccm = 128; /* Color correction median - see below */
2258
2259         if ((uvd == NULL) || (frame == NULL)) {
2260                 err("%s: Illegal call.", __FUNCTION__);
2261                 return;
2262         }
2263         adj = (uvd->vpic.contrast - 0x8000) >> 8; /* -128..+127 = -ccm..+(ccm-1)*/
2264         RESTRICT_TO_RANGE(adj, -ccm, ccm+1);
2265         if (adj == 0) {
2266                 /* In rare case of no adjustment */
2267                 return;
2268         }
2269         v4l_linesize = VIDEOSIZE_X(frame->request) * V4L_BYTES_PER_PIXEL;
2270         for (i=0; i < VIDEOSIZE_Y(frame->request); i++) {
2271                 unsigned char *fd = frame->data + (v4l_linesize * i);
2272                 for (j=0; j < v4l_linesize; j++) {
2273                         signed long v = (signed long) fd[j];
2274                         /* Magnify up to 2 times, reduce down to zero */
2275                         v = 128 + ((ccm + adj) * (v - 128)) / ccm;
2276                         RESTRICT_TO_RANGE(v, 0, 0xFF); /* Must flatten tails */
2277                         fd[j] = (unsigned char) v;
2278                 }
2279         }
2280 }
2281
2282 MODULE_LICENSE("GPL");