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