V4L/DVB (9927): em28xx: use a more standard way to specify video formats
[safe/jmp/linux-2.6] / drivers / media / video / em28xx / em28xx-video.c
1 /*
2    em28xx-video.c - driver for Empia EM2800/EM2820/2840 USB
3                     video capture devices
4
5    Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
6                       Markus Rechberger <mrechberger@gmail.com>
7                       Mauro Carvalho Chehab <mchehab@infradead.org>
8                       Sascha Sommer <saschasommer@freenet.de>
9
10         Some parts based on SN9C10x PC Camera Controllers GPL driver made
11                 by Luca Risolia <luca.risolia@studio.unibo.it>
12
13    This program is free software; you can redistribute it and/or modify
14    it under the terms of the GNU General Public License as published by
15    the Free Software Foundation; either version 2 of the License, or
16    (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21    GNU General Public License for more details.
22
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  */
27
28 #include <linux/init.h>
29 #include <linux/list.h>
30 #include <linux/module.h>
31 #include <linux/kernel.h>
32 #include <linux/bitmap.h>
33 #include <linux/usb.h>
34 #include <linux/i2c.h>
35 #include <linux/version.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38
39 #include "em28xx.h"
40 #include <media/v4l2-common.h>
41 #include <media/v4l2-ioctl.h>
42 #include <media/msp3400.h>
43 #include <media/tuner.h>
44
45 #define DRIVER_AUTHOR "Ludovico Cavedon <cavedon@sssup.it>, " \
46                       "Markus Rechberger <mrechberger@gmail.com>, " \
47                       "Mauro Carvalho Chehab <mchehab@infradead.org>, " \
48                       "Sascha Sommer <saschasommer@freenet.de>"
49
50 #define DRIVER_NAME         "em28xx"
51 #define DRIVER_DESC         "Empia em28xx based USB video device driver"
52 #define EM28XX_VERSION_CODE  KERNEL_VERSION(0, 1, 0)
53
54 #define em28xx_videodbg(fmt, arg...) do {\
55         if (video_debug) \
56                 printk(KERN_INFO "%s %s :"fmt, \
57                          dev->name, __func__ , ##arg); } while (0)
58
59 static unsigned int isoc_debug;
60 module_param(isoc_debug, int, 0644);
61 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
62
63 #define em28xx_isocdbg(fmt, arg...) \
64 do {\
65         if (isoc_debug) { \
66                 printk(KERN_INFO "%s %s :"fmt, \
67                          dev->name, __func__ , ##arg); \
68         } \
69   } while (0)
70
71 MODULE_AUTHOR(DRIVER_AUTHOR);
72 MODULE_DESCRIPTION(DRIVER_DESC);
73 MODULE_LICENSE("GPL");
74
75 static LIST_HEAD(em28xx_devlist);
76 static DEFINE_MUTEX(em28xx_devlist_mutex);
77
78 static unsigned int card[]     = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
79 static unsigned int video_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
80 static unsigned int vbi_nr[]   = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
81 static unsigned int radio_nr[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
82
83 module_param_array(card,  int, NULL, 0444);
84 module_param_array(video_nr, int, NULL, 0444);
85 module_param_array(vbi_nr, int, NULL, 0444);
86 module_param_array(radio_nr, int, NULL, 0444);
87 MODULE_PARM_DESC(card,     "card type");
88 MODULE_PARM_DESC(video_nr, "video device numbers");
89 MODULE_PARM_DESC(vbi_nr,   "vbi device numbers");
90 MODULE_PARM_DESC(radio_nr, "radio device numbers");
91
92 static unsigned int video_debug;
93 module_param(video_debug, int, 0644);
94 MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
95
96 /* Bitmask marking allocated devices from 0 to EM28XX_MAXBOARDS */
97 static unsigned long em28xx_devused;
98
99 /* supported video standards */
100 static struct em28xx_fmt format[] = {
101         {
102                 .name     = "16bpp YUY2, 4:2:2, packed",
103                 .fourcc   = V4L2_PIX_FMT_YUYV,
104                 .depth    = 16,
105                 .reg      = 0x14,
106         },
107 };
108
109 /* supported controls */
110 /* Common to all boards */
111 static struct v4l2_queryctrl em28xx_qctrl[] = {
112         {
113                 .id = V4L2_CID_AUDIO_VOLUME,
114                 .type = V4L2_CTRL_TYPE_INTEGER,
115                 .name = "Volume",
116                 .minimum = 0x0,
117                 .maximum = 0x1f,
118                 .step = 0x1,
119                 .default_value = 0x1f,
120                 .flags = 0,
121         }, {
122                 .id = V4L2_CID_AUDIO_MUTE,
123                 .type = V4L2_CTRL_TYPE_BOOLEAN,
124                 .name = "Mute",
125                 .minimum = 0,
126                 .maximum = 1,
127                 .step = 1,
128                 .default_value = 1,
129                 .flags = 0,
130         }
131 };
132
133 static struct usb_driver em28xx_usb_driver;
134
135 /* ------------------------------------------------------------------
136         DMA and thread functions
137    ------------------------------------------------------------------*/
138
139 /*
140  * Announces that a buffer were filled and request the next
141  */
142 static inline void buffer_filled(struct em28xx *dev,
143                                   struct em28xx_dmaqueue *dma_q,
144                                   struct em28xx_buffer *buf)
145 {
146         /* Advice that buffer was filled */
147         em28xx_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
148         buf->vb.state = VIDEOBUF_DONE;
149         buf->vb.field_count++;
150         do_gettimeofday(&buf->vb.ts);
151
152         dev->isoc_ctl.buf = NULL;
153
154         list_del(&buf->vb.queue);
155         wake_up(&buf->vb.done);
156 }
157
158 /*
159  * Identify the buffer header type and properly handles
160  */
161 static void em28xx_copy_video(struct em28xx *dev,
162                               struct em28xx_dmaqueue  *dma_q,
163                               struct em28xx_buffer *buf,
164                               unsigned char *p,
165                               unsigned char *outp, unsigned long len)
166 {
167         void *fieldstart, *startwrite, *startread;
168         int  linesdone, currlinedone, offset, lencopy, remain;
169         int bytesperline = dev->width << 1;
170
171         if (dma_q->pos + len > buf->vb.size)
172                 len = buf->vb.size - dma_q->pos;
173
174         if (p[0] != 0x88 && p[0] != 0x22) {
175                 em28xx_isocdbg("frame is not complete\n");
176                 len += 4;
177         } else
178                 p += 4;
179
180         startread = p;
181         remain = len;
182
183         /* Interlaces frame */
184         if (buf->top_field)
185                 fieldstart = outp;
186         else
187                 fieldstart = outp + bytesperline;
188
189         linesdone = dma_q->pos / bytesperline;
190         currlinedone = dma_q->pos % bytesperline;
191         offset = linesdone * bytesperline * 2 + currlinedone;
192         startwrite = fieldstart + offset;
193         lencopy = bytesperline - currlinedone;
194         lencopy = lencopy > remain ? remain : lencopy;
195
196         if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
197                 em28xx_isocdbg("Overflow of %zi bytes past buffer end (1)\n",
198                                ((char *)startwrite + lencopy) -
199                                ((char *)outp + buf->vb.size));
200                 lencopy = remain = (char *)outp + buf->vb.size - (char *)startwrite;
201         }
202         if (lencopy <= 0)
203                 return;
204         memcpy(startwrite, startread, lencopy);
205
206         remain -= lencopy;
207
208         while (remain > 0) {
209                 startwrite += lencopy + bytesperline;
210                 startread += lencopy;
211                 if (bytesperline > remain)
212                         lencopy = remain;
213                 else
214                         lencopy = bytesperline;
215
216                 if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
217                         em28xx_isocdbg("Overflow of %zi bytes past buffer end (2)\n",
218                                        ((char *)startwrite + lencopy) -
219                                        ((char *)outp + buf->vb.size));
220                         lencopy = remain = (char *)outp + buf->vb.size -
221                                            (char *)startwrite;
222                 }
223                 if (lencopy <= 0)
224                         break;
225
226                 memcpy(startwrite, startread, lencopy);
227
228                 remain -= lencopy;
229         }
230
231         dma_q->pos += len;
232 }
233
234 static inline void print_err_status(struct em28xx *dev,
235                                      int packet, int status)
236 {
237         char *errmsg = "Unknown";
238
239         switch (status) {
240         case -ENOENT:
241                 errmsg = "unlinked synchronuously";
242                 break;
243         case -ECONNRESET:
244                 errmsg = "unlinked asynchronuously";
245                 break;
246         case -ENOSR:
247                 errmsg = "Buffer error (overrun)";
248                 break;
249         case -EPIPE:
250                 errmsg = "Stalled (device not responding)";
251                 break;
252         case -EOVERFLOW:
253                 errmsg = "Babble (bad cable?)";
254                 break;
255         case -EPROTO:
256                 errmsg = "Bit-stuff error (bad cable?)";
257                 break;
258         case -EILSEQ:
259                 errmsg = "CRC/Timeout (could be anything)";
260                 break;
261         case -ETIME:
262                 errmsg = "Device does not respond";
263                 break;
264         }
265         if (packet < 0) {
266                 em28xx_isocdbg("URB status %d [%s].\n", status, errmsg);
267         } else {
268                 em28xx_isocdbg("URB packet %d, status %d [%s].\n",
269                                packet, status, errmsg);
270         }
271 }
272
273 /*
274  * video-buf generic routine to get the next available buffer
275  */
276 static inline void get_next_buf(struct em28xx_dmaqueue *dma_q,
277                                           struct em28xx_buffer **buf)
278 {
279         struct em28xx *dev = container_of(dma_q, struct em28xx, vidq);
280         char *outp;
281
282         if (list_empty(&dma_q->active)) {
283                 em28xx_isocdbg("No active queue to serve\n");
284                 dev->isoc_ctl.buf = NULL;
285                 *buf = NULL;
286                 return;
287         }
288
289         /* Get the next buffer */
290         *buf = list_entry(dma_q->active.next, struct em28xx_buffer, vb.queue);
291
292         /* Cleans up buffer - Usefull for testing for frame/URB loss */
293         outp = videobuf_to_vmalloc(&(*buf)->vb);
294         memset(outp, 0, (*buf)->vb.size);
295
296         dev->isoc_ctl.buf = *buf;
297
298         return;
299 }
300
301 /*
302  * Controls the isoc copy of each urb packet
303  */
304 static inline int em28xx_isoc_copy(struct em28xx *dev, struct urb *urb)
305 {
306         struct em28xx_buffer    *buf;
307         struct em28xx_dmaqueue  *dma_q = urb->context;
308         unsigned char *outp = NULL;
309         int i, len = 0, rc = 1;
310         unsigned char *p;
311
312         if (!dev)
313                 return 0;
314
315         if ((dev->state & DEV_DISCONNECTED) || (dev->state & DEV_MISCONFIGURED))
316                 return 0;
317
318         if (urb->status < 0) {
319                 print_err_status(dev, -1, urb->status);
320                 if (urb->status == -ENOENT)
321                         return 0;
322         }
323
324         buf = dev->isoc_ctl.buf;
325         if (buf != NULL)
326                 outp = videobuf_to_vmalloc(&buf->vb);
327
328         for (i = 0; i < urb->number_of_packets; i++) {
329                 int status = urb->iso_frame_desc[i].status;
330
331                 if (status < 0) {
332                         print_err_status(dev, i, status);
333                         if (urb->iso_frame_desc[i].status != -EPROTO)
334                                 continue;
335                 }
336
337                 len = urb->iso_frame_desc[i].actual_length - 4;
338
339                 if (urb->iso_frame_desc[i].actual_length <= 0) {
340                         /* em28xx_isocdbg("packet %d is empty",i); - spammy */
341                         continue;
342                 }
343                 if (urb->iso_frame_desc[i].actual_length >
344                                                 dev->max_pkt_size) {
345                         em28xx_isocdbg("packet bigger than packet size");
346                         continue;
347                 }
348
349                 p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
350
351                 /* FIXME: incomplete buffer checks where removed to make
352                    logic simpler. Impacts of those changes should be evaluated
353                  */
354                 if (p[0] == 0x33 && p[1] == 0x95 && p[2] == 0x00) {
355                         em28xx_isocdbg("VBI HEADER!!!\n");
356                         /* FIXME: Should add vbi copy */
357                         continue;
358                 }
359                 if (p[0] == 0x22 && p[1] == 0x5a) {
360                         em28xx_isocdbg("Video frame %d, length=%i, %s\n", p[2],
361                                        len, (p[2] & 1)? "odd" : "even");
362
363                         if (!(p[2] & 1)) {
364                                 if (buf != NULL)
365                                         buffer_filled(dev, dma_q, buf);
366                                 get_next_buf(dma_q, &buf);
367                                 if (buf == NULL)
368                                         outp = NULL;
369                                 else
370                                         outp = videobuf_to_vmalloc(&buf->vb);
371                         }
372
373                         if (buf != NULL) {
374                                 if (p[2] & 1)
375                                         buf->top_field = 0;
376                                 else
377                                         buf->top_field = 1;
378                         }
379
380                         dma_q->pos = 0;
381                 }
382                 if (buf != NULL)
383                         em28xx_copy_video(dev, dma_q, buf, p, outp, len);
384         }
385         return rc;
386 }
387
388 /* ------------------------------------------------------------------
389         Videobuf operations
390    ------------------------------------------------------------------*/
391
392 static int
393 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
394 {
395         struct em28xx_fh *fh = vq->priv_data;
396         struct em28xx        *dev = fh->dev;
397         struct v4l2_frequency f;
398
399         *size = (fh->dev->width * fh->dev->height * dev->format->depth + 7) >> 3;
400
401         if (0 == *count)
402                 *count = EM28XX_DEF_BUF;
403
404         if (*count < EM28XX_MIN_BUF)
405                 *count = EM28XX_MIN_BUF;
406
407         /* Ask tuner to go to analog or radio mode */
408         memset(&f, 0, sizeof(f));
409         f.frequency = dev->ctl_freq;
410         f.type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
411
412         em28xx_i2c_call_clients(dev, VIDIOC_S_FREQUENCY, &f);
413
414         return 0;
415 }
416
417 /* This is called *without* dev->slock held; please keep it that way */
418 static void free_buffer(struct videobuf_queue *vq, struct em28xx_buffer *buf)
419 {
420         struct em28xx_fh     *fh  = vq->priv_data;
421         struct em28xx        *dev = fh->dev;
422         unsigned long flags = 0;
423         if (in_interrupt())
424                 BUG();
425
426         /* We used to wait for the buffer to finish here, but this didn't work
427            because, as we were keeping the state as VIDEOBUF_QUEUED,
428            videobuf_queue_cancel marked it as finished for us.
429            (Also, it could wedge forever if the hardware was misconfigured.)
430
431            This should be safe; by the time we get here, the buffer isn't
432            queued anymore. If we ever start marking the buffers as
433            VIDEOBUF_ACTIVE, it won't be, though.
434         */
435         spin_lock_irqsave(&dev->slock, flags);
436         if (dev->isoc_ctl.buf == buf)
437                 dev->isoc_ctl.buf = NULL;
438         spin_unlock_irqrestore(&dev->slock, flags);
439
440         videobuf_vmalloc_free(&buf->vb);
441         buf->vb.state = VIDEOBUF_NEEDS_INIT;
442 }
443
444 static int
445 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
446                                                 enum v4l2_field field)
447 {
448         struct em28xx_fh     *fh  = vq->priv_data;
449         struct em28xx_buffer *buf = container_of(vb, struct em28xx_buffer, vb);
450         struct em28xx        *dev = fh->dev;
451         int                  rc = 0, urb_init = 0;
452
453         buf->vb.size = (fh->dev->width * fh->dev->height * dev->format->depth + 7) >> 3;
454
455         if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
456                 return -EINVAL;
457
458         buf->vb.width  = dev->width;
459         buf->vb.height = dev->height;
460         buf->vb.field  = field;
461
462         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
463                 rc = videobuf_iolock(vq, &buf->vb, NULL);
464                 if (rc < 0)
465                         goto fail;
466         }
467
468         if (!dev->isoc_ctl.num_bufs)
469                 urb_init = 1;
470
471         if (urb_init) {
472                 rc = em28xx_init_isoc(dev, EM28XX_NUM_PACKETS,
473                                       EM28XX_NUM_BUFS, dev->max_pkt_size,
474                                       em28xx_isoc_copy);
475                 if (rc < 0)
476                         goto fail;
477         }
478
479         buf->vb.state = VIDEOBUF_PREPARED;
480         return 0;
481
482 fail:
483         free_buffer(vq, buf);
484         return rc;
485 }
486
487 static void
488 buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
489 {
490         struct em28xx_buffer    *buf     = container_of(vb, struct em28xx_buffer, vb);
491         struct em28xx_fh        *fh      = vq->priv_data;
492         struct em28xx           *dev     = fh->dev;
493         struct em28xx_dmaqueue  *vidq    = &dev->vidq;
494
495         buf->vb.state = VIDEOBUF_QUEUED;
496         list_add_tail(&buf->vb.queue, &vidq->active);
497
498 }
499
500 static void buffer_release(struct videobuf_queue *vq,
501                                 struct videobuf_buffer *vb)
502 {
503         struct em28xx_buffer   *buf  = container_of(vb, struct em28xx_buffer, vb);
504         struct em28xx_fh       *fh   = vq->priv_data;
505         struct em28xx          *dev  = (struct em28xx *)fh->dev;
506
507         em28xx_isocdbg("em28xx: called buffer_release\n");
508
509         free_buffer(vq, buf);
510 }
511
512 static struct videobuf_queue_ops em28xx_video_qops = {
513         .buf_setup      = buffer_setup,
514         .buf_prepare    = buffer_prepare,
515         .buf_queue      = buffer_queue,
516         .buf_release    = buffer_release,
517 };
518
519 /*********************  v4l2 interface  **************************************/
520
521 /*
522  * em28xx_config()
523  * inits registers with sane defaults
524  */
525 static int em28xx_config(struct em28xx *dev)
526 {
527         int retval;
528
529         /* Sets I2C speed to 100 KHz */
530         if (!dev->board.is_em2800) {
531                 retval = em28xx_write_reg(dev, EM28XX_R06_I2C_CLK, 0x40);
532                 if (retval < 0) {
533                         em28xx_errdev("%s: em28xx_write_regs_req failed! retval [%d]\n",
534                                 __func__, retval);
535                         return retval;
536                 }
537         }
538
539         /* enable vbi capturing */
540
541 /*      em28xx_write_reg(dev, EM28XX_R0E_AUDIOSRC, 0xc0); audio register */
542 /*      em28xx_write_reg(dev, EM28XX_R0F_XCLK, 0x80); clk register */
543         em28xx_write_reg(dev, EM28XX_R11_VINCTRL, 0x51);
544
545         dev->mute = 1;          /* maybe not the right place... */
546         dev->volume = 0x1f;
547
548         em28xx_set_outfmt(dev);
549         em28xx_colorlevels_set_default(dev);
550         em28xx_compression_disable(dev);
551
552         return 0;
553 }
554
555 /*
556  * em28xx_config_i2c()
557  * configure i2c attached devices
558  */
559 static void em28xx_config_i2c(struct em28xx *dev)
560 {
561         struct v4l2_routing route;
562         int zero = 0;
563
564         route.input = INPUT(dev->ctl_input)->vmux;
565         route.output = 0;
566         em28xx_i2c_call_clients(dev, VIDIOC_INT_RESET, &zero);
567         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
568         em28xx_i2c_call_clients(dev, VIDIOC_STREAMON, NULL);
569 }
570
571 static void video_mux(struct em28xx *dev, int index)
572 {
573         struct v4l2_routing route;
574
575         route.input = INPUT(index)->vmux;
576         route.output = 0;
577         dev->ctl_input = index;
578         dev->ctl_ainput = INPUT(index)->amux;
579         dev->ctl_aoutput = INPUT(index)->aout;
580
581         if (!dev->ctl_aoutput)
582                 dev->ctl_aoutput = EM28XX_AOUT_MASTER;
583
584         em28xx_i2c_call_clients(dev, VIDIOC_INT_S_VIDEO_ROUTING, &route);
585
586         if (dev->board.has_msp34xx) {
587                 if (dev->i2s_speed) {
588                         em28xx_i2c_call_clients(dev, VIDIOC_INT_I2S_CLOCK_FREQ,
589                                 &dev->i2s_speed);
590                 }
591                 route.input = dev->ctl_ainput;
592                 route.output = MSP_OUTPUT(MSP_SC_IN_DSP_SCART1);
593                 /* Note: this is msp3400 specific */
594                 em28xx_i2c_call_clients(dev, VIDIOC_INT_S_AUDIO_ROUTING,
595                         &route);
596         }
597
598         em28xx_audio_analog_set(dev);
599 }
600
601 /* Usage lock check functions */
602 static int res_get(struct em28xx_fh *fh)
603 {
604         struct em28xx    *dev = fh->dev;
605         int              rc   = 0;
606
607         /* This instance already has stream_on */
608         if (fh->stream_on)
609                 return rc;
610
611         if (dev->stream_on)
612                 return -EBUSY;
613
614         dev->stream_on = 1;
615         fh->stream_on  = 1;
616         return rc;
617 }
618
619 static int res_check(struct em28xx_fh *fh)
620 {
621         return (fh->stream_on);
622 }
623
624 static void res_free(struct em28xx_fh *fh)
625 {
626         struct em28xx    *dev = fh->dev;
627
628         fh->stream_on = 0;
629         dev->stream_on = 0;
630 }
631
632 /*
633  * em28xx_get_ctrl()
634  * return the current saturation, brightness or contrast, mute state
635  */
636 static int em28xx_get_ctrl(struct em28xx *dev, struct v4l2_control *ctrl)
637 {
638         switch (ctrl->id) {
639         case V4L2_CID_AUDIO_MUTE:
640                 ctrl->value = dev->mute;
641                 return 0;
642         case V4L2_CID_AUDIO_VOLUME:
643                 ctrl->value = dev->volume;
644                 return 0;
645         default:
646                 return -EINVAL;
647         }
648 }
649
650 /*
651  * em28xx_set_ctrl()
652  * mute or set new saturation, brightness or contrast
653  */
654 static int em28xx_set_ctrl(struct em28xx *dev, const struct v4l2_control *ctrl)
655 {
656         switch (ctrl->id) {
657         case V4L2_CID_AUDIO_MUTE:
658                 if (ctrl->value != dev->mute) {
659                         dev->mute = ctrl->value;
660                         return em28xx_audio_analog_set(dev);
661                 }
662                 return 0;
663         case V4L2_CID_AUDIO_VOLUME:
664                 dev->volume = ctrl->value;
665                 return em28xx_audio_analog_set(dev);
666         default:
667                 return -EINVAL;
668         }
669 }
670
671 static int check_dev(struct em28xx *dev)
672 {
673         if (dev->state & DEV_DISCONNECTED) {
674                 em28xx_errdev("v4l2 ioctl: device not present\n");
675                 return -ENODEV;
676         }
677
678         if (dev->state & DEV_MISCONFIGURED) {
679                 em28xx_errdev("v4l2 ioctl: device is misconfigured; "
680                               "close and open it again\n");
681                 return -EIO;
682         }
683         return 0;
684 }
685
686 static void get_scale(struct em28xx *dev,
687                         unsigned int width, unsigned int height,
688                         unsigned int *hscale, unsigned int *vscale)
689 {
690         unsigned int          maxw   = norm_maxw(dev);
691         unsigned int          maxh   = norm_maxh(dev);
692
693         *hscale = (((unsigned long)maxw) << 12) / width - 4096L;
694         if (*hscale >= 0x4000)
695                 *hscale = 0x3fff;
696
697         *vscale = (((unsigned long)maxh) << 12) / height - 4096L;
698         if (*vscale >= 0x4000)
699                 *vscale = 0x3fff;
700 }
701
702 /* ------------------------------------------------------------------
703         IOCTL vidioc handling
704    ------------------------------------------------------------------*/
705
706 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
707                                         struct v4l2_format *f)
708 {
709         struct em28xx_fh      *fh  = priv;
710         struct em28xx         *dev = fh->dev;
711
712         mutex_lock(&dev->lock);
713
714         f->fmt.pix.width = dev->width;
715         f->fmt.pix.height = dev->height;
716         f->fmt.pix.pixelformat = dev->format->fourcc;
717         f->fmt.pix.bytesperline = (dev->width * dev->format->depth + 7) >> 3;
718         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline  * dev->height;
719         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
720
721         /* FIXME: TOP? NONE? BOTTOM? ALTENATE? */
722         f->fmt.pix.field = dev->interlaced ?
723                            V4L2_FIELD_INTERLACED : V4L2_FIELD_TOP;
724
725         mutex_unlock(&dev->lock);
726         return 0;
727 }
728
729 static struct em28xx_fmt *format_by_fourcc(unsigned int fourcc)
730 {
731         unsigned int i;
732
733         for (i = 0; i < ARRAY_SIZE(format); i++)
734                 if (format[i].fourcc == fourcc)
735                         return &format[i];
736
737         return NULL;
738 }
739
740 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
741                         struct v4l2_format *f)
742 {
743         struct em28xx_fh      *fh    = priv;
744         struct em28xx         *dev   = fh->dev;
745         int                   width  = f->fmt.pix.width;
746         int                   height = f->fmt.pix.height;
747         unsigned int          maxw   = norm_maxw(dev);
748         unsigned int          maxh   = norm_maxh(dev);
749         unsigned int          hscale, vscale;
750         struct em28xx_fmt     *fmt;
751
752         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
753         if (!fmt) {
754                 em28xx_videodbg("Fourcc format (%08x) invalid.\n",
755                                 f->fmt.pix.pixelformat);
756                 return -EINVAL;
757         }
758
759         /* width must even because of the YUYV format
760            height must be even because of interlacing */
761         height &= 0xfffe;
762         width  &= 0xfffe;
763
764         if (unlikely(height < 32))
765                 height = 32;
766         if (unlikely(height > maxh))
767                 height = maxh;
768         if (unlikely(width < 48))
769                 width = 48;
770         if (unlikely(width > maxw))
771                 width = maxw;
772
773         if (dev->board.is_em2800) {
774                 /* the em2800 can only scale down to 50% */
775                 if (height % (maxh / 2))
776                         height = maxh;
777                 if (width % (maxw / 2))
778                         width = maxw;
779                 /* according to empiatech support */
780                 /* the MaxPacketSize is to small to support */
781                 /* framesizes larger than 640x480 @ 30 fps */
782                 /* or 640x576 @ 25 fps. As this would cut */
783                 /* of a part of the image we prefer */
784                 /* 360x576 or 360x480 for now */
785                 if (width == maxw && height == maxh)
786                         width /= 2;
787         }
788
789         get_scale(dev, width, height, &hscale, &vscale);
790
791         width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
792         height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
793
794         f->fmt.pix.width = width;
795         f->fmt.pix.height = height;
796         f->fmt.pix.pixelformat = fmt->fourcc;
797         f->fmt.pix.bytesperline = (dev->width * fmt->depth + 7) >> 3;
798         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height;
799         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
800         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
801
802         return 0;
803 }
804
805 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
806                         struct v4l2_format *f)
807 {
808         struct em28xx_fh      *fh  = priv;
809         struct em28xx         *dev = fh->dev;
810         int                   rc;
811         struct em28xx_fmt     *fmt;
812
813         rc = check_dev(dev);
814         if (rc < 0)
815                 return rc;
816
817         mutex_lock(&dev->lock);
818
819         vidioc_try_fmt_vid_cap(file, priv, f);
820
821         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
822         if (!fmt)
823                 return -EINVAL;
824
825         if (videobuf_queue_is_busy(&fh->vb_vidq)) {
826                 em28xx_errdev("%s queue busy\n", __func__);
827                 rc = -EBUSY;
828                 goto out;
829         }
830
831         if (dev->stream_on && !fh->stream_on) {
832                 em28xx_errdev("%s device in use by another fh\n", __func__);
833                 rc = -EBUSY;
834                 goto out;
835         }
836
837         /* set new image size */
838         dev->width = f->fmt.pix.width;
839         dev->height = f->fmt.pix.height;
840         dev->format = fmt;
841         get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
842
843         em28xx_set_alternate(dev);
844         em28xx_resolution_set(dev);
845
846         rc = 0;
847
848 out:
849         mutex_unlock(&dev->lock);
850         return rc;
851 }
852
853 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id * norm)
854 {
855         struct em28xx_fh   *fh  = priv;
856         struct em28xx      *dev = fh->dev;
857         struct v4l2_format f;
858         int                rc;
859
860         rc = check_dev(dev);
861         if (rc < 0)
862                 return rc;
863
864         mutex_lock(&dev->lock);
865         dev->norm = *norm;
866
867         /* Adjusts width/height, if needed */
868         f.fmt.pix.width = dev->width;
869         f.fmt.pix.height = dev->height;
870         vidioc_try_fmt_vid_cap(file, priv, &f);
871
872         /* set new image size */
873         dev->width = f.fmt.pix.width;
874         dev->height = f.fmt.pix.height;
875         get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
876
877         em28xx_resolution_set(dev);
878         em28xx_i2c_call_clients(dev, VIDIOC_S_STD, &dev->norm);
879
880         mutex_unlock(&dev->lock);
881         return 0;
882 }
883
884 static const char *iname[] = {
885         [EM28XX_VMUX_COMPOSITE1] = "Composite1",
886         [EM28XX_VMUX_COMPOSITE2] = "Composite2",
887         [EM28XX_VMUX_COMPOSITE3] = "Composite3",
888         [EM28XX_VMUX_COMPOSITE4] = "Composite4",
889         [EM28XX_VMUX_SVIDEO]     = "S-Video",
890         [EM28XX_VMUX_TELEVISION] = "Television",
891         [EM28XX_VMUX_CABLE]      = "Cable TV",
892         [EM28XX_VMUX_DVB]        = "DVB",
893         [EM28XX_VMUX_DEBUG]      = "for debug only",
894 };
895
896 static int vidioc_enum_input(struct file *file, void *priv,
897                                 struct v4l2_input *i)
898 {
899         struct em28xx_fh   *fh  = priv;
900         struct em28xx      *dev = fh->dev;
901         unsigned int       n;
902
903         n = i->index;
904         if (n >= MAX_EM28XX_INPUT)
905                 return -EINVAL;
906         if (0 == INPUT(n)->type)
907                 return -EINVAL;
908
909         i->index = n;
910         i->type = V4L2_INPUT_TYPE_CAMERA;
911
912         strcpy(i->name, iname[INPUT(n)->type]);
913
914         if ((EM28XX_VMUX_TELEVISION == INPUT(n)->type) ||
915                 (EM28XX_VMUX_CABLE == INPUT(n)->type))
916                 i->type = V4L2_INPUT_TYPE_TUNER;
917
918         i->std = dev->vdev->tvnorms;
919
920         return 0;
921 }
922
923 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
924 {
925         struct em28xx_fh   *fh  = priv;
926         struct em28xx      *dev = fh->dev;
927
928         *i = dev->ctl_input;
929
930         return 0;
931 }
932
933 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
934 {
935         struct em28xx_fh   *fh  = priv;
936         struct em28xx      *dev = fh->dev;
937         int                rc;
938
939         rc = check_dev(dev);
940         if (rc < 0)
941                 return rc;
942
943         if (i >= MAX_EM28XX_INPUT)
944                 return -EINVAL;
945         if (0 == INPUT(i)->type)
946                 return -EINVAL;
947
948         mutex_lock(&dev->lock);
949
950         video_mux(dev, i);
951
952         mutex_unlock(&dev->lock);
953         return 0;
954 }
955
956 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
957 {
958         struct em28xx_fh   *fh    = priv;
959         struct em28xx      *dev   = fh->dev;
960
961         switch (a->index) {
962         case EM28XX_AMUX_VIDEO:
963                 strcpy(a->name, "Television");
964                 break;
965         case EM28XX_AMUX_LINE_IN:
966                 strcpy(a->name, "Line In");
967                 break;
968         case EM28XX_AMUX_VIDEO2:
969                 strcpy(a->name, "Television alt");
970                 break;
971         case EM28XX_AMUX_PHONE:
972                 strcpy(a->name, "Phone");
973                 break;
974         case EM28XX_AMUX_MIC:
975                 strcpy(a->name, "Mic");
976                 break;
977         case EM28XX_AMUX_CD:
978                 strcpy(a->name, "CD");
979                 break;
980         case EM28XX_AMUX_AUX:
981                 strcpy(a->name, "Aux");
982                 break;
983         case EM28XX_AMUX_PCM_OUT:
984                 strcpy(a->name, "PCM");
985                 break;
986         default:
987                 return -EINVAL;
988         }
989
990         a->index = dev->ctl_ainput;
991         a->capability = V4L2_AUDCAP_STEREO;
992
993         return 0;
994 }
995
996 static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a)
997 {
998         struct em28xx_fh   *fh  = priv;
999         struct em28xx      *dev = fh->dev;
1000
1001         mutex_lock(&dev->lock);
1002
1003         dev->ctl_ainput = INPUT(a->index)->amux;
1004         dev->ctl_aoutput = INPUT(a->index)->aout;
1005
1006         if (!dev->ctl_aoutput)
1007                 dev->ctl_aoutput = EM28XX_AOUT_MASTER;
1008
1009         mutex_unlock(&dev->lock);
1010         return 0;
1011 }
1012
1013 static int vidioc_queryctrl(struct file *file, void *priv,
1014                                 struct v4l2_queryctrl *qc)
1015 {
1016         struct em28xx_fh      *fh  = priv;
1017         struct em28xx         *dev = fh->dev;
1018         int                   id  = qc->id;
1019         int                   i;
1020         int                   rc;
1021
1022         rc = check_dev(dev);
1023         if (rc < 0)
1024                 return rc;
1025
1026         memset(qc, 0, sizeof(*qc));
1027
1028         qc->id = id;
1029
1030         if (!dev->board.has_msp34xx) {
1031                 for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1032                         if (qc->id && qc->id == em28xx_qctrl[i].id) {
1033                                 memcpy(qc, &(em28xx_qctrl[i]), sizeof(*qc));
1034                                 return 0;
1035                         }
1036                 }
1037         }
1038         mutex_lock(&dev->lock);
1039         em28xx_i2c_call_clients(dev, VIDIOC_QUERYCTRL, qc);
1040         mutex_unlock(&dev->lock);
1041
1042         if (qc->type)
1043                 return 0;
1044         else
1045                 return -EINVAL;
1046 }
1047
1048 static int vidioc_g_ctrl(struct file *file, void *priv,
1049                                 struct v4l2_control *ctrl)
1050 {
1051         struct em28xx_fh      *fh  = priv;
1052         struct em28xx         *dev = fh->dev;
1053         int                   rc;
1054
1055         rc = check_dev(dev);
1056         if (rc < 0)
1057                 return rc;
1058
1059         mutex_lock(&dev->lock);
1060
1061         if (!dev->board.has_msp34xx)
1062                 rc = em28xx_get_ctrl(dev, ctrl);
1063         else
1064                 rc = -EINVAL;
1065
1066         if (rc == -EINVAL) {
1067                 em28xx_i2c_call_clients(dev, VIDIOC_G_CTRL, ctrl);
1068                 rc = 0;
1069         }
1070
1071         mutex_unlock(&dev->lock);
1072         return rc;
1073 }
1074
1075 static int vidioc_s_ctrl(struct file *file, void *priv,
1076                                 struct v4l2_control *ctrl)
1077 {
1078         struct em28xx_fh      *fh  = priv;
1079         struct em28xx         *dev = fh->dev;
1080         u8                    i;
1081         int                   rc;
1082
1083         rc = check_dev(dev);
1084         if (rc < 0)
1085                 return rc;
1086
1087         mutex_lock(&dev->lock);
1088
1089         if (dev->board.has_msp34xx)
1090                 em28xx_i2c_call_clients(dev, VIDIOC_S_CTRL, ctrl);
1091         else {
1092                 rc = 1;
1093                 for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1094                         if (ctrl->id == em28xx_qctrl[i].id) {
1095                                 if (ctrl->value < em28xx_qctrl[i].minimum ||
1096                                     ctrl->value > em28xx_qctrl[i].maximum) {
1097                                         rc = -ERANGE;
1098                                         break;
1099                                 }
1100
1101                                 rc = em28xx_set_ctrl(dev, ctrl);
1102                                 break;
1103                         }
1104                 }
1105         }
1106
1107         /* Control not found - try to send it to the attached devices */
1108         if (rc == 1) {
1109                 em28xx_i2c_call_clients(dev, VIDIOC_S_CTRL, ctrl);
1110                 rc = 0;
1111         }
1112
1113         mutex_unlock(&dev->lock);
1114         return rc;
1115 }
1116
1117 static int vidioc_g_tuner(struct file *file, void *priv,
1118                                 struct v4l2_tuner *t)
1119 {
1120         struct em28xx_fh      *fh  = priv;
1121         struct em28xx         *dev = fh->dev;
1122         int                   rc;
1123
1124         rc = check_dev(dev);
1125         if (rc < 0)
1126                 return rc;
1127
1128         if (0 != t->index)
1129                 return -EINVAL;
1130
1131         strcpy(t->name, "Tuner");
1132
1133         mutex_lock(&dev->lock);
1134
1135         em28xx_i2c_call_clients(dev, VIDIOC_G_TUNER, t);
1136
1137         mutex_unlock(&dev->lock);
1138         return 0;
1139 }
1140
1141 static int vidioc_s_tuner(struct file *file, void *priv,
1142                                 struct v4l2_tuner *t)
1143 {
1144         struct em28xx_fh      *fh  = priv;
1145         struct em28xx         *dev = fh->dev;
1146         int                   rc;
1147
1148         rc = check_dev(dev);
1149         if (rc < 0)
1150                 return rc;
1151
1152         if (0 != t->index)
1153                 return -EINVAL;
1154
1155         mutex_lock(&dev->lock);
1156
1157         em28xx_i2c_call_clients(dev, VIDIOC_S_TUNER, t);
1158
1159         mutex_unlock(&dev->lock);
1160         return 0;
1161 }
1162
1163 static int vidioc_g_frequency(struct file *file, void *priv,
1164                                 struct v4l2_frequency *f)
1165 {
1166         struct em28xx_fh      *fh  = priv;
1167         struct em28xx         *dev = fh->dev;
1168
1169         mutex_lock(&dev->lock);
1170         f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
1171         f->frequency = dev->ctl_freq;
1172         mutex_unlock(&dev->lock);
1173
1174         return 0;
1175 }
1176
1177 static int vidioc_s_frequency(struct file *file, void *priv,
1178                                 struct v4l2_frequency *f)
1179 {
1180         struct em28xx_fh      *fh  = priv;
1181         struct em28xx         *dev = fh->dev;
1182         int                   rc;
1183
1184         rc = check_dev(dev);
1185         if (rc < 0)
1186                 return rc;
1187
1188         if (0 != f->tuner)
1189                 return -EINVAL;
1190
1191         if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV))
1192                 return -EINVAL;
1193         if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO))
1194                 return -EINVAL;
1195
1196         mutex_lock(&dev->lock);
1197
1198         dev->ctl_freq = f->frequency;
1199         em28xx_i2c_call_clients(dev, VIDIOC_S_FREQUENCY, f);
1200
1201         mutex_unlock(&dev->lock);
1202
1203         return 0;
1204 }
1205
1206 #ifdef CONFIG_VIDEO_ADV_DEBUG
1207 static int em28xx_reg_len(int reg)
1208 {
1209         switch (reg) {
1210         case EM28XX_R40_AC97LSB:
1211         case EM28XX_R30_HSCALELOW:
1212         case EM28XX_R32_VSCALELOW:
1213                 return 2;
1214         default:
1215                 return 1;
1216         }
1217 }
1218
1219 static int vidioc_g_register(struct file *file, void *priv,
1220                              struct v4l2_register *reg)
1221 {
1222         struct em28xx_fh      *fh  = priv;
1223         struct em28xx         *dev = fh->dev;
1224         int ret;
1225
1226         if (!v4l2_chip_match_host(reg->match_type, reg->match_chip))
1227                 return -EINVAL;
1228
1229         if (em28xx_reg_len(reg->reg) == 1) {
1230                 mutex_lock(&dev->lock);
1231                 ret = em28xx_read_reg(dev, reg->reg);
1232                 mutex_unlock(&dev->lock);
1233
1234                 if (ret < 0)
1235                         return ret;
1236
1237                 reg->val = ret;
1238         } else {
1239                 __le64 val = 0;
1240                 mutex_lock(&dev->lock);
1241                 ret = em28xx_read_reg_req_len(dev, USB_REQ_GET_STATUS,
1242                                                    reg->reg, (char *)&val, 2);
1243                 mutex_unlock(&dev->lock);
1244                 if (ret < 0)
1245                         return ret;
1246
1247                 reg->val = le64_to_cpu(val);
1248         }
1249
1250         return 0;
1251 }
1252
1253 static int vidioc_s_register(struct file *file, void *priv,
1254                              struct v4l2_register *reg)
1255 {
1256         struct em28xx_fh      *fh  = priv;
1257         struct em28xx         *dev = fh->dev;
1258         __le64 buf;
1259         int    rc;
1260
1261         buf = cpu_to_le64(reg->val);
1262
1263         mutex_lock(&dev->lock);
1264         rc = em28xx_write_regs(dev, reg->reg, (char *)&buf,
1265                                em28xx_reg_len(reg->reg));
1266         mutex_unlock(&dev->lock);
1267
1268         return rc;
1269 }
1270 #endif
1271
1272
1273 static int vidioc_cropcap(struct file *file, void *priv,
1274                                         struct v4l2_cropcap *cc)
1275 {
1276         struct em28xx_fh      *fh  = priv;
1277         struct em28xx         *dev = fh->dev;
1278
1279         if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1280                 return -EINVAL;
1281
1282         cc->bounds.left = 0;
1283         cc->bounds.top = 0;
1284         cc->bounds.width = dev->width;
1285         cc->bounds.height = dev->height;
1286         cc->defrect = cc->bounds;
1287         cc->pixelaspect.numerator = 54; /* 4:3 FIXME: remove magic numbers */
1288         cc->pixelaspect.denominator = 59;
1289
1290         return 0;
1291 }
1292
1293 static int vidioc_streamon(struct file *file, void *priv,
1294                                         enum v4l2_buf_type type)
1295 {
1296         struct em28xx_fh      *fh  = priv;
1297         struct em28xx         *dev = fh->dev;
1298         int                   rc;
1299
1300         rc = check_dev(dev);
1301         if (rc < 0)
1302                 return rc;
1303
1304
1305         mutex_lock(&dev->lock);
1306         rc = res_get(fh);
1307
1308         if (unlikely(rc < 0))
1309                 return rc;
1310
1311         rc = videobuf_streamon(&fh->vb_vidq);
1312
1313         mutex_unlock(&dev->lock);
1314
1315         return rc;
1316 }
1317
1318 static int vidioc_streamoff(struct file *file, void *priv,
1319                                         enum v4l2_buf_type type)
1320 {
1321         struct em28xx_fh      *fh  = priv;
1322         struct em28xx         *dev = fh->dev;
1323         int                   rc;
1324
1325         rc = check_dev(dev);
1326         if (rc < 0)
1327                 return rc;
1328
1329         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1330                 return -EINVAL;
1331         if (type != fh->type)
1332                 return -EINVAL;
1333
1334         mutex_lock(&dev->lock);
1335
1336         videobuf_streamoff(&fh->vb_vidq);
1337         res_free(fh);
1338
1339         mutex_unlock(&dev->lock);
1340
1341         return 0;
1342 }
1343
1344 static int vidioc_querycap(struct file *file, void  *priv,
1345                                         struct v4l2_capability *cap)
1346 {
1347         struct em28xx_fh      *fh  = priv;
1348         struct em28xx         *dev = fh->dev;
1349
1350         strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1351         strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1352         strlcpy(cap->bus_info, dev_name(&dev->udev->dev), sizeof(cap->bus_info));
1353
1354         cap->version = EM28XX_VERSION_CODE;
1355
1356         cap->capabilities =
1357                         V4L2_CAP_SLICED_VBI_CAPTURE |
1358                         V4L2_CAP_VIDEO_CAPTURE |
1359                         V4L2_CAP_AUDIO |
1360                         V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1361
1362         if (dev->tuner_type != TUNER_ABSENT)
1363                 cap->capabilities |= V4L2_CAP_TUNER;
1364
1365         return 0;
1366 }
1367
1368 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1369                                         struct v4l2_fmtdesc *f)
1370 {
1371         if (unlikely(f->index >= ARRAY_SIZE(format)))
1372                 return -EINVAL;
1373
1374         strlcpy(f->description, format[f->index].name, sizeof(f->description));
1375         f->pixelformat = format[f->index].fourcc;
1376
1377         return 0;
1378 }
1379
1380 /* Sliced VBI ioctls */
1381 static int vidioc_g_fmt_sliced_vbi_cap(struct file *file, void *priv,
1382                                         struct v4l2_format *f)
1383 {
1384         struct em28xx_fh      *fh  = priv;
1385         struct em28xx         *dev = fh->dev;
1386         int                   rc;
1387
1388         rc = check_dev(dev);
1389         if (rc < 0)
1390                 return rc;
1391
1392         mutex_lock(&dev->lock);
1393
1394         f->fmt.sliced.service_set = 0;
1395
1396         em28xx_i2c_call_clients(dev, VIDIOC_G_FMT, f);
1397
1398         if (f->fmt.sliced.service_set == 0)
1399                 rc = -EINVAL;
1400
1401         mutex_unlock(&dev->lock);
1402         return rc;
1403 }
1404
1405 static int vidioc_try_set_sliced_vbi_cap(struct file *file, void *priv,
1406                         struct v4l2_format *f)
1407 {
1408         struct em28xx_fh      *fh  = priv;
1409         struct em28xx         *dev = fh->dev;
1410         int                   rc;
1411
1412         rc = check_dev(dev);
1413         if (rc < 0)
1414                 return rc;
1415
1416         mutex_lock(&dev->lock);
1417         em28xx_i2c_call_clients(dev, VIDIOC_G_FMT, f);
1418         mutex_unlock(&dev->lock);
1419
1420         if (f->fmt.sliced.service_set == 0)
1421                 return -EINVAL;
1422
1423         return 0;
1424 }
1425
1426
1427 static int vidioc_reqbufs(struct file *file, void *priv,
1428                           struct v4l2_requestbuffers *rb)
1429 {
1430         struct em28xx_fh      *fh  = priv;
1431         struct em28xx         *dev = fh->dev;
1432         int                   rc;
1433
1434         rc = check_dev(dev);
1435         if (rc < 0)
1436                 return rc;
1437
1438         return (videobuf_reqbufs(&fh->vb_vidq, rb));
1439 }
1440
1441 static int vidioc_querybuf(struct file *file, void *priv,
1442                            struct v4l2_buffer *b)
1443 {
1444         struct em28xx_fh      *fh  = priv;
1445         struct em28xx         *dev = fh->dev;
1446         int                   rc;
1447
1448         rc = check_dev(dev);
1449         if (rc < 0)
1450                 return rc;
1451
1452         return (videobuf_querybuf(&fh->vb_vidq, b));
1453 }
1454
1455 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1456 {
1457         struct em28xx_fh      *fh  = priv;
1458         struct em28xx         *dev = fh->dev;
1459         int                   rc;
1460
1461         rc = check_dev(dev);
1462         if (rc < 0)
1463                 return rc;
1464
1465         return (videobuf_qbuf(&fh->vb_vidq, b));
1466 }
1467
1468 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1469 {
1470         struct em28xx_fh      *fh  = priv;
1471         struct em28xx         *dev = fh->dev;
1472         int                   rc;
1473
1474         rc = check_dev(dev);
1475         if (rc < 0)
1476                 return rc;
1477
1478         return (videobuf_dqbuf(&fh->vb_vidq, b,
1479                                 file->f_flags & O_NONBLOCK));
1480 }
1481
1482 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1483 static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
1484 {
1485         struct em28xx_fh  *fh = priv;
1486
1487         return videobuf_cgmbuf(&fh->vb_vidq, mbuf, 8);
1488 }
1489 #endif
1490
1491
1492 /* ----------------------------------------------------------- */
1493 /* RADIO ESPECIFIC IOCTLS                                      */
1494 /* ----------------------------------------------------------- */
1495
1496 static int radio_querycap(struct file *file, void  *priv,
1497                           struct v4l2_capability *cap)
1498 {
1499         struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1500
1501         strlcpy(cap->driver, "em28xx", sizeof(cap->driver));
1502         strlcpy(cap->card, em28xx_boards[dev->model].name, sizeof(cap->card));
1503         strlcpy(cap->bus_info, dev_name(&dev->udev->dev), sizeof(cap->bus_info));
1504
1505         cap->version = EM28XX_VERSION_CODE;
1506         cap->capabilities = V4L2_CAP_TUNER;
1507         return 0;
1508 }
1509
1510 static int radio_g_tuner(struct file *file, void *priv,
1511                          struct v4l2_tuner *t)
1512 {
1513         struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1514
1515         if (unlikely(t->index > 0))
1516                 return -EINVAL;
1517
1518         strcpy(t->name, "Radio");
1519         t->type = V4L2_TUNER_RADIO;
1520
1521         mutex_lock(&dev->lock);
1522         em28xx_i2c_call_clients(dev, VIDIOC_G_TUNER, t);
1523         mutex_unlock(&dev->lock);
1524
1525         return 0;
1526 }
1527
1528 static int radio_enum_input(struct file *file, void *priv,
1529                             struct v4l2_input *i)
1530 {
1531         if (i->index != 0)
1532                 return -EINVAL;
1533         strcpy(i->name, "Radio");
1534         i->type = V4L2_INPUT_TYPE_TUNER;
1535
1536         return 0;
1537 }
1538
1539 static int radio_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1540 {
1541         if (unlikely(a->index))
1542                 return -EINVAL;
1543
1544         strcpy(a->name, "Radio");
1545         return 0;
1546 }
1547
1548 static int radio_s_tuner(struct file *file, void *priv,
1549                          struct v4l2_tuner *t)
1550 {
1551         struct em28xx *dev = ((struct em28xx_fh *)priv)->dev;
1552
1553         if (0 != t->index)
1554                 return -EINVAL;
1555
1556         mutex_lock(&dev->lock);
1557         em28xx_i2c_call_clients(dev, VIDIOC_S_TUNER, t);
1558         mutex_unlock(&dev->lock);
1559
1560         return 0;
1561 }
1562
1563 static int radio_s_audio(struct file *file, void *fh,
1564                          struct v4l2_audio *a)
1565 {
1566         return 0;
1567 }
1568
1569 static int radio_s_input(struct file *file, void *fh, unsigned int i)
1570 {
1571         return 0;
1572 }
1573
1574 static int radio_queryctrl(struct file *file, void *priv,
1575                            struct v4l2_queryctrl *qc)
1576 {
1577         int i;
1578
1579         if (qc->id <  V4L2_CID_BASE ||
1580                 qc->id >= V4L2_CID_LASTP1)
1581                 return -EINVAL;
1582
1583         for (i = 0; i < ARRAY_SIZE(em28xx_qctrl); i++) {
1584                 if (qc->id && qc->id == em28xx_qctrl[i].id) {
1585                         memcpy(qc, &(em28xx_qctrl[i]), sizeof(*qc));
1586                         return 0;
1587                 }
1588         }
1589
1590         return -EINVAL;
1591 }
1592
1593 /*
1594  * em28xx_v4l2_open()
1595  * inits the device and starts isoc transfer
1596  */
1597 static int em28xx_v4l2_open(struct inode *inode, struct file *filp)
1598 {
1599         int minor = iminor(inode);
1600         int errCode = 0, radio = 0;
1601         struct em28xx *h, *dev = NULL;
1602         struct em28xx_fh *fh;
1603         enum v4l2_buf_type fh_type = 0;
1604
1605         mutex_lock(&em28xx_devlist_mutex);
1606         list_for_each_entry(h, &em28xx_devlist, devlist) {
1607                 if (h->vdev->minor == minor) {
1608                         dev  = h;
1609                         fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1610                 }
1611                 if (h->vbi_dev->minor == minor) {
1612                         dev  = h;
1613                         fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
1614                 }
1615                 if (h->radio_dev &&
1616                     h->radio_dev->minor == minor) {
1617                         radio = 1;
1618                         dev   = h;
1619                 }
1620         }
1621         mutex_unlock(&em28xx_devlist_mutex);
1622
1623         if (NULL == dev)
1624                 return -ENODEV;
1625
1626         mutex_lock(&dev->lock);
1627
1628         em28xx_videodbg("open minor=%d type=%s users=%d\n",
1629                                 minor, v4l2_type_names[fh_type], dev->users);
1630
1631
1632         fh = kzalloc(sizeof(struct em28xx_fh), GFP_KERNEL);
1633         if (!fh) {
1634                 em28xx_errdev("em28xx-video.c: Out of memory?!\n");
1635                 mutex_unlock(&dev->lock);
1636                 return -ENOMEM;
1637         }
1638         fh->dev = dev;
1639         fh->radio = radio;
1640         fh->type = fh_type;
1641         filp->private_data = fh;
1642
1643         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
1644                 dev->width = norm_maxw(dev);
1645                 dev->height = norm_maxh(dev);
1646                 dev->hscale = 0;
1647                 dev->vscale = 0;
1648
1649                 em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
1650                 em28xx_set_alternate(dev);
1651                 em28xx_resolution_set(dev);
1652
1653                 /* Needed, since GPIO might have disabled power of
1654                    some i2c device
1655                  */
1656                 em28xx_config_i2c(dev);
1657
1658         }
1659         if (fh->radio) {
1660                 em28xx_videodbg("video_open: setting radio device\n");
1661                 em28xx_i2c_call_clients(dev, AUDC_SET_RADIO, NULL);
1662         }
1663
1664         dev->users++;
1665
1666         videobuf_queue_vmalloc_init(&fh->vb_vidq, &em28xx_video_qops,
1667                         NULL, &dev->slock, fh->type, V4L2_FIELD_INTERLACED,
1668                         sizeof(struct em28xx_buffer), fh);
1669
1670         mutex_unlock(&dev->lock);
1671
1672         return errCode;
1673 }
1674
1675 /*
1676  * em28xx_realease_resources()
1677  * unregisters the v4l2,i2c and usb devices
1678  * called when the device gets disconected or at module unload
1679 */
1680 static void em28xx_release_resources(struct em28xx *dev)
1681 {
1682
1683         /*FIXME: I2C IR should be disconnected */
1684
1685         list_del(&dev->devlist);
1686         if (dev->sbutton_input_dev)
1687                 em28xx_deregister_snapshot_button(dev);
1688
1689         if (dev->ir)
1690                 em28xx_ir_fini(dev);
1691
1692         if (dev->radio_dev) {
1693                 if (-1 != dev->radio_dev->minor)
1694                         video_unregister_device(dev->radio_dev);
1695                 else
1696                         video_device_release(dev->radio_dev);
1697                 dev->radio_dev = NULL;
1698         }
1699         if (dev->vbi_dev) {
1700                 em28xx_info("V4L2 device /dev/vbi%d deregistered\n",
1701                             dev->vbi_dev->num);
1702                 if (-1 != dev->vbi_dev->minor)
1703                         video_unregister_device(dev->vbi_dev);
1704                 else
1705                         video_device_release(dev->vbi_dev);
1706                 dev->vbi_dev = NULL;
1707         }
1708         if (dev->vdev) {
1709                 em28xx_info("V4L2 device /dev/video%d deregistered\n",
1710                             dev->vdev->num);
1711                 if (-1 != dev->vdev->minor)
1712                         video_unregister_device(dev->vdev);
1713                 else
1714                         video_device_release(dev->vdev);
1715                 dev->vdev = NULL;
1716         }
1717         em28xx_i2c_unregister(dev);
1718         usb_put_dev(dev->udev);
1719
1720         /* Mark device as unused */
1721         em28xx_devused &= ~(1<<dev->devno);
1722 }
1723
1724 /*
1725  * em28xx_v4l2_close()
1726  * stops streaming and deallocates all resources allocated by the v4l2
1727  * calls and ioctls
1728  */
1729 static int em28xx_v4l2_close(struct inode *inode, struct file *filp)
1730 {
1731         struct em28xx_fh *fh  = filp->private_data;
1732         struct em28xx    *dev = fh->dev;
1733         int              errCode;
1734
1735         em28xx_videodbg("users=%d\n", dev->users);
1736
1737
1738         mutex_lock(&dev->lock);
1739         if (res_check(fh))
1740                 res_free(fh);
1741
1742         if (dev->users == 1) {
1743                 videobuf_stop(&fh->vb_vidq);
1744                 videobuf_mmap_free(&fh->vb_vidq);
1745
1746                 /* the device is already disconnect,
1747                    free the remaining resources */
1748                 if (dev->state & DEV_DISCONNECTED) {
1749                         em28xx_release_resources(dev);
1750                         mutex_unlock(&dev->lock);
1751                         kfree(dev);
1752                         return 0;
1753                 }
1754
1755                 /* Save some power by putting tuner to sleep */
1756                 em28xx_i2c_call_clients(dev, TUNER_SET_STANDBY, NULL);
1757
1758                 /* do this before setting alternate! */
1759                 em28xx_uninit_isoc(dev);
1760                 em28xx_set_mode(dev, EM28XX_SUSPEND);
1761
1762                 /* set alternate 0 */
1763                 dev->alt = 0;
1764                 em28xx_videodbg("setting alternate 0\n");
1765                 errCode = usb_set_interface(dev->udev, 0, 0);
1766                 if (errCode < 0) {
1767                         em28xx_errdev("cannot change alternate number to "
1768                                         "0 (error=%i)\n", errCode);
1769                 }
1770         }
1771         kfree(fh);
1772         dev->users--;
1773         wake_up_interruptible_nr(&dev->open, 1);
1774         mutex_unlock(&dev->lock);
1775         return 0;
1776 }
1777
1778 /*
1779  * em28xx_v4l2_read()
1780  * will allocate buffers when called for the first time
1781  */
1782 static ssize_t
1783 em28xx_v4l2_read(struct file *filp, char __user *buf, size_t count,
1784                  loff_t *pos)
1785 {
1786         struct em28xx_fh *fh = filp->private_data;
1787         struct em28xx *dev = fh->dev;
1788         int rc;
1789
1790         rc = check_dev(dev);
1791         if (rc < 0)
1792                 return rc;
1793
1794         /* FIXME: read() is not prepared to allow changing the video
1795            resolution while streaming. Seems a bug at em28xx_set_fmt
1796          */
1797
1798         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1799                 mutex_lock(&dev->lock);
1800                 rc = res_get(fh);
1801                 mutex_unlock(&dev->lock);
1802
1803                 if (unlikely(rc < 0))
1804                         return rc;
1805
1806                 return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
1807                                         filp->f_flags & O_NONBLOCK);
1808         }
1809         return 0;
1810 }
1811
1812 /*
1813  * em28xx_v4l2_poll()
1814  * will allocate buffers when called for the first time
1815  */
1816 static unsigned int em28xx_v4l2_poll(struct file *filp, poll_table * wait)
1817 {
1818         struct em28xx_fh *fh = filp->private_data;
1819         struct em28xx *dev = fh->dev;
1820         int rc;
1821
1822         rc = check_dev(dev);
1823         if (rc < 0)
1824                 return rc;
1825
1826         mutex_lock(&dev->lock);
1827         rc = res_get(fh);
1828         mutex_unlock(&dev->lock);
1829
1830         if (unlikely(rc < 0))
1831                 return POLLERR;
1832
1833         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1834                 return POLLERR;
1835
1836         return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
1837 }
1838
1839 /*
1840  * em28xx_v4l2_mmap()
1841  */
1842 static int em28xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
1843 {
1844         struct em28xx_fh *fh    = filp->private_data;
1845         struct em28xx    *dev   = fh->dev;
1846         int              rc;
1847
1848         rc = check_dev(dev);
1849         if (rc < 0)
1850                 return rc;
1851
1852         mutex_lock(&dev->lock);
1853         rc = res_get(fh);
1854         mutex_unlock(&dev->lock);
1855
1856         if (unlikely(rc < 0))
1857                 return rc;
1858
1859         rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
1860
1861         em28xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
1862                 (unsigned long)vma->vm_start,
1863                 (unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
1864                 rc);
1865
1866         return rc;
1867 }
1868
1869 static const struct file_operations em28xx_v4l_fops = {
1870         .owner         = THIS_MODULE,
1871         .open          = em28xx_v4l2_open,
1872         .release       = em28xx_v4l2_close,
1873         .read          = em28xx_v4l2_read,
1874         .poll          = em28xx_v4l2_poll,
1875         .mmap          = em28xx_v4l2_mmap,
1876         .ioctl         = video_ioctl2,
1877         .llseek        = no_llseek,
1878         .compat_ioctl  = v4l_compat_ioctl32,
1879 };
1880
1881 static const struct v4l2_ioctl_ops video_ioctl_ops = {
1882         .vidioc_querycap            = vidioc_querycap,
1883         .vidioc_enum_fmt_vid_cap    = vidioc_enum_fmt_vid_cap,
1884         .vidioc_g_fmt_vid_cap       = vidioc_g_fmt_vid_cap,
1885         .vidioc_try_fmt_vid_cap     = vidioc_try_fmt_vid_cap,
1886         .vidioc_s_fmt_vid_cap       = vidioc_s_fmt_vid_cap,
1887         .vidioc_g_audio             = vidioc_g_audio,
1888         .vidioc_s_audio             = vidioc_s_audio,
1889         .vidioc_cropcap             = vidioc_cropcap,
1890
1891         .vidioc_g_fmt_sliced_vbi_cap   = vidioc_g_fmt_sliced_vbi_cap,
1892         .vidioc_try_fmt_sliced_vbi_cap = vidioc_try_set_sliced_vbi_cap,
1893         .vidioc_s_fmt_sliced_vbi_cap   = vidioc_try_set_sliced_vbi_cap,
1894
1895         .vidioc_reqbufs             = vidioc_reqbufs,
1896         .vidioc_querybuf            = vidioc_querybuf,
1897         .vidioc_qbuf                = vidioc_qbuf,
1898         .vidioc_dqbuf               = vidioc_dqbuf,
1899         .vidioc_s_std               = vidioc_s_std,
1900         .vidioc_enum_input          = vidioc_enum_input,
1901         .vidioc_g_input             = vidioc_g_input,
1902         .vidioc_s_input             = vidioc_s_input,
1903         .vidioc_queryctrl           = vidioc_queryctrl,
1904         .vidioc_g_ctrl              = vidioc_g_ctrl,
1905         .vidioc_s_ctrl              = vidioc_s_ctrl,
1906         .vidioc_streamon            = vidioc_streamon,
1907         .vidioc_streamoff           = vidioc_streamoff,
1908         .vidioc_g_tuner             = vidioc_g_tuner,
1909         .vidioc_s_tuner             = vidioc_s_tuner,
1910         .vidioc_g_frequency         = vidioc_g_frequency,
1911         .vidioc_s_frequency         = vidioc_s_frequency,
1912 #ifdef CONFIG_VIDEO_ADV_DEBUG
1913         .vidioc_g_register          = vidioc_g_register,
1914         .vidioc_s_register          = vidioc_s_register,
1915 #endif
1916 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1917         .vidiocgmbuf                = vidiocgmbuf,
1918 #endif
1919 };
1920
1921 static const struct video_device em28xx_video_template = {
1922         .fops                       = &em28xx_v4l_fops,
1923         .release                    = video_device_release,
1924         .ioctl_ops                  = &video_ioctl_ops,
1925
1926         .minor                      = -1,
1927
1928         .tvnorms                    = V4L2_STD_ALL,
1929         .current_norm               = V4L2_STD_PAL,
1930 };
1931
1932 static const struct file_operations radio_fops = {
1933         .owner         = THIS_MODULE,
1934         .open          = em28xx_v4l2_open,
1935         .release       = em28xx_v4l2_close,
1936         .ioctl         = video_ioctl2,
1937         .compat_ioctl  = v4l_compat_ioctl32,
1938         .llseek        = no_llseek,
1939 };
1940
1941 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
1942         .vidioc_querycap      = radio_querycap,
1943         .vidioc_g_tuner       = radio_g_tuner,
1944         .vidioc_enum_input    = radio_enum_input,
1945         .vidioc_g_audio       = radio_g_audio,
1946         .vidioc_s_tuner       = radio_s_tuner,
1947         .vidioc_s_audio       = radio_s_audio,
1948         .vidioc_s_input       = radio_s_input,
1949         .vidioc_queryctrl     = radio_queryctrl,
1950         .vidioc_g_ctrl        = vidioc_g_ctrl,
1951         .vidioc_s_ctrl        = vidioc_s_ctrl,
1952         .vidioc_g_frequency   = vidioc_g_frequency,
1953         .vidioc_s_frequency   = vidioc_s_frequency,
1954 #ifdef CONFIG_VIDEO_ADV_DEBUG
1955         .vidioc_g_register    = vidioc_g_register,
1956         .vidioc_s_register    = vidioc_s_register,
1957 #endif
1958 };
1959
1960 static struct video_device em28xx_radio_template = {
1961         .name                 = "em28xx-radio",
1962         .fops                 = &radio_fops,
1963         .ioctl_ops            = &radio_ioctl_ops,
1964         .minor                = -1,
1965 };
1966
1967 /******************************** usb interface ******************************/
1968
1969
1970 static LIST_HEAD(em28xx_extension_devlist);
1971 static DEFINE_MUTEX(em28xx_extension_devlist_lock);
1972
1973 int em28xx_register_extension(struct em28xx_ops *ops)
1974 {
1975         struct em28xx *dev = NULL;
1976
1977         mutex_lock(&em28xx_devlist_mutex);
1978         mutex_lock(&em28xx_extension_devlist_lock);
1979         list_add_tail(&ops->next, &em28xx_extension_devlist);
1980         list_for_each_entry(dev, &em28xx_devlist, devlist) {
1981                 if (dev)
1982                         ops->init(dev);
1983         }
1984         printk(KERN_INFO "Em28xx: Initialized (%s) extension\n", ops->name);
1985         mutex_unlock(&em28xx_extension_devlist_lock);
1986         mutex_unlock(&em28xx_devlist_mutex);
1987         return 0;
1988 }
1989 EXPORT_SYMBOL(em28xx_register_extension);
1990
1991 void em28xx_unregister_extension(struct em28xx_ops *ops)
1992 {
1993         struct em28xx *dev = NULL;
1994
1995         mutex_lock(&em28xx_devlist_mutex);
1996         list_for_each_entry(dev, &em28xx_devlist, devlist) {
1997                 if (dev)
1998                         ops->fini(dev);
1999         }
2000
2001         mutex_lock(&em28xx_extension_devlist_lock);
2002         printk(KERN_INFO "Em28xx: Removed (%s) extension\n", ops->name);
2003         list_del(&ops->next);
2004         mutex_unlock(&em28xx_extension_devlist_lock);
2005         mutex_unlock(&em28xx_devlist_mutex);
2006 }
2007 EXPORT_SYMBOL(em28xx_unregister_extension);
2008
2009 static struct video_device *em28xx_vdev_init(struct em28xx *dev,
2010                                              const struct video_device *template,
2011                                              const char *type_name)
2012 {
2013         struct video_device *vfd;
2014
2015         vfd = video_device_alloc();
2016         if (NULL == vfd)
2017                 return NULL;
2018         *vfd = *template;
2019         vfd->minor   = -1;
2020         vfd->parent = &dev->udev->dev;
2021         vfd->release = video_device_release;
2022         vfd->debug = video_debug;
2023
2024         snprintf(vfd->name, sizeof(vfd->name), "%s %s",
2025                  dev->name, type_name);
2026
2027         return vfd;
2028 }
2029
2030 static int register_analog_devices(struct em28xx *dev)
2031 {
2032         int ret;
2033
2034         /* allocate and fill video video_device struct */
2035         dev->vdev = em28xx_vdev_init(dev, &em28xx_video_template, "video");
2036         if (!dev->vdev) {
2037                 em28xx_errdev("cannot allocate video_device.\n");
2038                 return -ENODEV;
2039         }
2040
2041         /* register v4l2 video video_device */
2042         ret = video_register_device(dev->vdev, VFL_TYPE_GRABBER,
2043                                        video_nr[dev->devno]);
2044         if (ret) {
2045                 em28xx_errdev("unable to register video device (error=%i).\n",
2046                               ret);
2047                 return ret;
2048         }
2049
2050         /* Allocate and fill vbi video_device struct */
2051         dev->vbi_dev = em28xx_vdev_init(dev, &em28xx_video_template, "vbi");
2052
2053         /* register v4l2 vbi video_device */
2054         ret = video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
2055                                         vbi_nr[dev->devno]);
2056         if (ret < 0) {
2057                 em28xx_errdev("unable to register vbi device\n");
2058                 return ret;
2059         }
2060
2061         if (em28xx_boards[dev->model].radio.type == EM28XX_RADIO) {
2062                 dev->radio_dev = em28xx_vdev_init(dev, &em28xx_radio_template, "radio");
2063                 if (!dev->radio_dev) {
2064                         em28xx_errdev("cannot allocate video_device.\n");
2065                         return -ENODEV;
2066                 }
2067                 ret = video_register_device(dev->radio_dev, VFL_TYPE_RADIO,
2068                                             radio_nr[dev->devno]);
2069                 if (ret < 0) {
2070                         em28xx_errdev("can't register radio device\n");
2071                         return ret;
2072                 }
2073                 em28xx_info("Registered radio device as /dev/radio%d\n",
2074                             dev->radio_dev->num);
2075         }
2076
2077         em28xx_info("V4L2 device registered as /dev/video%d and /dev/vbi%d\n",
2078                                 dev->vdev->num, dev->vbi_dev->num);
2079
2080         return 0;
2081 }
2082
2083
2084 /*
2085  * em28xx_init_dev()
2086  * allocates and inits the device structs, registers i2c bus and v4l device
2087  */
2088 static int em28xx_init_dev(struct em28xx **devhandle, struct usb_device *udev,
2089                            int minor)
2090 {
2091         struct em28xx_ops *ops = NULL;
2092         struct em28xx *dev = *devhandle;
2093         int retval = -ENOMEM;
2094         int errCode;
2095         unsigned int maxh, maxw;
2096
2097         dev->udev = udev;
2098         mutex_init(&dev->ctrl_urb_lock);
2099         spin_lock_init(&dev->slock);
2100         init_waitqueue_head(&dev->open);
2101         init_waitqueue_head(&dev->wait_frame);
2102         init_waitqueue_head(&dev->wait_stream);
2103
2104         dev->em28xx_write_regs = em28xx_write_regs;
2105         dev->em28xx_read_reg = em28xx_read_reg;
2106         dev->em28xx_read_reg_req_len = em28xx_read_reg_req_len;
2107         dev->em28xx_write_regs_req = em28xx_write_regs_req;
2108         dev->em28xx_read_reg_req = em28xx_read_reg_req;
2109         dev->board.is_em2800 = em28xx_boards[dev->model].is_em2800;
2110         dev->format = &format[0];
2111
2112         em28xx_pre_card_setup(dev);
2113
2114         errCode = em28xx_config(dev);
2115         if (errCode) {
2116                 em28xx_errdev("error configuring device\n");
2117                 return -ENOMEM;
2118         }
2119
2120         /* register i2c bus */
2121         errCode = em28xx_i2c_register(dev);
2122         if (errCode < 0) {
2123                 em28xx_errdev("%s: em28xx_i2c_register - errCode [%d]!\n",
2124                         __func__, errCode);
2125                 return errCode;
2126         }
2127
2128         /* Do board specific init and eeprom reading */
2129         em28xx_card_setup(dev);
2130
2131         /* Configure audio */
2132         errCode = em28xx_audio_setup(dev);
2133         if (errCode < 0) {
2134                 em28xx_errdev("%s: Error while setting audio - errCode [%d]!\n",
2135                         __func__, errCode);
2136         }
2137
2138         /* configure the device */
2139         em28xx_config_i2c(dev);
2140
2141         /* set default norm */
2142         dev->norm = em28xx_video_template.current_norm;
2143
2144         maxw = norm_maxw(dev);
2145         maxh = norm_maxh(dev);
2146
2147         /* set default image size */
2148         dev->width = maxw;
2149         dev->height = maxh;
2150         dev->interlaced = EM28XX_INTERLACED_DEFAULT;
2151         dev->hscale = 0;
2152         dev->vscale = 0;
2153         dev->ctl_input = 2;
2154
2155         errCode = em28xx_config(dev);
2156         if (errCode < 0) {
2157                 em28xx_errdev("%s: em28xx_config - errCode [%d]!\n",
2158                         __func__, errCode);
2159                 return errCode;
2160         }
2161
2162         /* init video dma queues */
2163         INIT_LIST_HEAD(&dev->vidq.active);
2164         INIT_LIST_HEAD(&dev->vidq.queued);
2165
2166
2167         if (dev->board.has_msp34xx) {
2168                 /* Send a reset to other chips via gpio */
2169                 errCode = em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xf7);
2170                 if (errCode < 0) {
2171                         em28xx_errdev("%s: em28xx_write_regs_req - msp34xx(1) failed! errCode [%d]\n",
2172                                 __func__, errCode);
2173                         return errCode;
2174                 }
2175                 msleep(3);
2176
2177                 errCode = em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xff);
2178                 if (errCode < 0) {
2179                         em28xx_errdev("%s: em28xx_write_regs_req - msp34xx(2) failed! errCode [%d]\n",
2180                                 __func__, errCode);
2181                         return errCode;
2182                 }
2183                 msleep(3);
2184         }
2185
2186         video_mux(dev, 0);
2187
2188         mutex_lock(&em28xx_devlist_mutex);
2189         list_add_tail(&dev->devlist, &em28xx_devlist);
2190         retval = register_analog_devices(dev);
2191         if (retval < 0) {
2192                 em28xx_release_resources(dev);
2193                 mutex_unlock(&em28xx_devlist_mutex);
2194                 goto fail_reg_devices;
2195         }
2196
2197         mutex_lock(&em28xx_extension_devlist_lock);
2198         if (!list_empty(&em28xx_extension_devlist)) {
2199                 list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2200                         if (ops->id)
2201                                 ops->init(dev);
2202                 }
2203         }
2204         mutex_unlock(&em28xx_extension_devlist_lock);
2205         mutex_unlock(&em28xx_devlist_mutex);
2206
2207         /* Save some power by putting tuner to sleep */
2208         em28xx_i2c_call_clients(dev, TUNER_SET_STANDBY, NULL);
2209
2210         return 0;
2211
2212 fail_reg_devices:
2213         return retval;
2214 }
2215
2216 #if defined(CONFIG_MODULES) && defined(MODULE)
2217 static void request_module_async(struct work_struct *work)
2218 {
2219         struct em28xx *dev = container_of(work,
2220                              struct em28xx, request_module_wk);
2221
2222         if (dev->has_audio_class)
2223                 request_module("snd-usb-audio");
2224         else if (dev->has_alsa_audio)
2225                 request_module("em28xx-alsa");
2226
2227         if (dev->board.has_dvb)
2228                 request_module("em28xx-dvb");
2229 }
2230
2231 static void request_modules(struct em28xx *dev)
2232 {
2233         INIT_WORK(&dev->request_module_wk, request_module_async);
2234         schedule_work(&dev->request_module_wk);
2235 }
2236 #else
2237 #define request_modules(dev)
2238 #endif /* CONFIG_MODULES */
2239
2240 /*
2241  * em28xx_usb_probe()
2242  * checks for supported devices
2243  */
2244 static int em28xx_usb_probe(struct usb_interface *interface,
2245                             const struct usb_device_id *id)
2246 {
2247         const struct usb_endpoint_descriptor *endpoint;
2248         struct usb_device *udev;
2249         struct usb_interface *uif;
2250         struct em28xx *dev = NULL;
2251         int retval = -ENODEV;
2252         int i, nr, ifnum, isoc_pipe;
2253         char *speed;
2254         char descr[255] = "";
2255
2256         udev = usb_get_dev(interface_to_usbdev(interface));
2257         ifnum = interface->altsetting[0].desc.bInterfaceNumber;
2258
2259         /* Check to see next free device and mark as used */
2260         nr = find_first_zero_bit(&em28xx_devused, EM28XX_MAXBOARDS);
2261         em28xx_devused |= 1<<nr;
2262
2263         /* Don't register audio interfaces */
2264         if (interface->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2265                 em28xx_err(DRIVER_NAME " audio device (%04x:%04x): "
2266                         "interface %i, class %i\n",
2267                         le16_to_cpu(udev->descriptor.idVendor),
2268                         le16_to_cpu(udev->descriptor.idProduct),
2269                         ifnum,
2270                         interface->altsetting[0].desc.bInterfaceClass);
2271
2272                 em28xx_devused &= ~(1<<nr);
2273                 return -ENODEV;
2274         }
2275
2276         endpoint = &interface->cur_altsetting->endpoint[0].desc;
2277
2278         /* check if the device has the iso in endpoint at the correct place */
2279         if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
2280             USB_ENDPOINT_XFER_ISOC &&
2281             (interface->altsetting[1].endpoint[0].desc.wMaxPacketSize == 940))
2282         {
2283                 /* It's a newer em2874/em2875 device */
2284                 isoc_pipe = 0;
2285         } else {
2286                 int check_interface = 1;
2287                 isoc_pipe = 1;
2288                 endpoint = &interface->cur_altsetting->endpoint[1].desc;
2289                 if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
2290                     USB_ENDPOINT_XFER_ISOC)
2291                         check_interface = 0;
2292
2293                 if ((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT)
2294                         check_interface = 0;
2295
2296                 if (!check_interface) {
2297                         em28xx_err(DRIVER_NAME " video device (%04x:%04x): "
2298                                 "interface %i, class %i found.\n",
2299                                 le16_to_cpu(udev->descriptor.idVendor),
2300                                 le16_to_cpu(udev->descriptor.idProduct),
2301                                 ifnum,
2302                                 interface->altsetting[0].desc.bInterfaceClass);
2303
2304                         em28xx_err(DRIVER_NAME " This is an anciliary "
2305                                 "interface not used by the driver\n");
2306
2307                         em28xx_devused &= ~(1<<nr);
2308                         return -ENODEV;
2309                 }
2310         }
2311
2312         switch (udev->speed) {
2313         case USB_SPEED_LOW:
2314                 speed = "1.5";
2315                 break;
2316         case USB_SPEED_UNKNOWN:
2317         case USB_SPEED_FULL:
2318                 speed = "12";
2319                 break;
2320         case USB_SPEED_HIGH:
2321                 speed = "480";
2322                 break;
2323         default:
2324                 speed = "unknown";
2325         }
2326
2327         if (udev->manufacturer)
2328                 strlcpy(descr, udev->manufacturer, sizeof(descr));
2329
2330         if (udev->product) {
2331                 if (*descr)
2332                         strlcat(descr, " ", sizeof(descr));
2333                 strlcat(descr, udev->product, sizeof(descr));
2334         }
2335         if (*descr)
2336                 strlcat(descr, " ", sizeof(descr));
2337
2338         printk(DRIVER_NAME ": New device %s@ %s Mbps "
2339                 "(%04x:%04x, interface %d, class %d)\n",
2340                 descr,
2341                 speed,
2342                 le16_to_cpu(udev->descriptor.idVendor),
2343                 le16_to_cpu(udev->descriptor.idProduct),
2344                 ifnum,
2345                 interface->altsetting->desc.bInterfaceNumber);
2346
2347         if (nr >= EM28XX_MAXBOARDS) {
2348                 printk(DRIVER_NAME ": Supports only %i em28xx boards.\n",
2349                                 EM28XX_MAXBOARDS);
2350                 em28xx_devused &= ~(1<<nr);
2351                 return -ENOMEM;
2352         }
2353
2354         /* allocate memory for our device state and initialize it */
2355         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2356         if (dev == NULL) {
2357                 em28xx_err(DRIVER_NAME ": out of memory!\n");
2358                 em28xx_devused &= ~(1<<nr);
2359                 return -ENOMEM;
2360         }
2361
2362         snprintf(dev->name, 29, "em28xx #%d", nr);
2363         dev->devno = nr;
2364         dev->model = id->driver_info;
2365         dev->alt   = -1;
2366
2367         /* Checks if audio is provided by some interface */
2368         for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
2369                 uif = udev->config->interface[i];
2370                 if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
2371                         dev->has_audio_class = 1;
2372                         break;
2373                 }
2374         }
2375
2376         /* compute alternate max packet sizes */
2377         uif = udev->actconfig->interface[0];
2378
2379         dev->num_alt = uif->num_altsetting;
2380         em28xx_videodbg("Alternate settings: %i\n", dev->num_alt);
2381 /*      dev->alt_max_pkt_size = kmalloc(sizeof(*dev->alt_max_pkt_size)* */
2382         dev->alt_max_pkt_size = kmalloc(32 * dev->num_alt, GFP_KERNEL);
2383
2384         if (dev->alt_max_pkt_size == NULL) {
2385                 em28xx_errdev("out of memory!\n");
2386                 em28xx_devused &= ~(1<<nr);
2387                 kfree(dev);
2388                 return -ENOMEM;
2389         }
2390
2391         for (i = 0; i < dev->num_alt ; i++) {
2392                 u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[isoc_pipe].desc.
2393                                                         wMaxPacketSize);
2394                 dev->alt_max_pkt_size[i] =
2395                     (tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
2396                 em28xx_videodbg("Alternate setting %i, max size= %i\n", i,
2397                                                 dev->alt_max_pkt_size[i]);
2398         }
2399
2400         if ((card[nr] >= 0) && (card[nr] < em28xx_bcount))
2401                 dev->model = card[nr];
2402
2403         /* allocate device struct */
2404         mutex_init(&dev->lock);
2405         mutex_lock(&dev->lock);
2406         retval = em28xx_init_dev(&dev, udev, nr);
2407         if (retval) {
2408                 em28xx_devused &= ~(1<<dev->devno);
2409                 kfree(dev);
2410
2411                 return retval;
2412         }
2413
2414         /* save our data pointer in this interface device */
2415         usb_set_intfdata(interface, dev);
2416
2417         request_modules(dev);
2418
2419         /* Should be the last thing to do, to avoid newer udev's to
2420            open the device before fully initializing it
2421          */
2422         mutex_unlock(&dev->lock);
2423
2424         return 0;
2425 }
2426
2427 /*
2428  * em28xx_usb_disconnect()
2429  * called when the device gets diconencted
2430  * video device will be unregistered on v4l2_close in case it is still open
2431  */
2432 static void em28xx_usb_disconnect(struct usb_interface *interface)
2433 {
2434         struct em28xx *dev;
2435         struct em28xx_ops *ops = NULL;
2436
2437         dev = usb_get_intfdata(interface);
2438         usb_set_intfdata(interface, NULL);
2439
2440         if (!dev)
2441                 return;
2442
2443         em28xx_info("disconnecting %s\n", dev->vdev->name);
2444
2445         /* wait until all current v4l2 io is finished then deallocate
2446            resources */
2447         mutex_lock(&dev->lock);
2448
2449         wake_up_interruptible_all(&dev->open);
2450
2451         if (dev->users) {
2452                 em28xx_warn
2453                     ("device /dev/video%d is open! Deregistration and memory "
2454                      "deallocation are deferred on close.\n",
2455                                 dev->vdev->num);
2456
2457                 dev->state |= DEV_MISCONFIGURED;
2458                 em28xx_uninit_isoc(dev);
2459                 dev->state |= DEV_DISCONNECTED;
2460                 wake_up_interruptible(&dev->wait_frame);
2461                 wake_up_interruptible(&dev->wait_stream);
2462         } else {
2463                 dev->state |= DEV_DISCONNECTED;
2464                 em28xx_release_resources(dev);
2465         }
2466         mutex_unlock(&dev->lock);
2467
2468         mutex_lock(&em28xx_extension_devlist_lock);
2469         if (!list_empty(&em28xx_extension_devlist)) {
2470                 list_for_each_entry(ops, &em28xx_extension_devlist, next) {
2471                         ops->fini(dev);
2472                 }
2473         }
2474         mutex_unlock(&em28xx_extension_devlist_lock);
2475
2476         if (!dev->users) {
2477                 kfree(dev->alt_max_pkt_size);
2478                 kfree(dev);
2479         }
2480 }
2481
2482 static struct usb_driver em28xx_usb_driver = {
2483         .name = "em28xx",
2484         .probe = em28xx_usb_probe,
2485         .disconnect = em28xx_usb_disconnect,
2486         .id_table = em28xx_id_table,
2487 };
2488
2489 static int __init em28xx_module_init(void)
2490 {
2491         int result;
2492
2493         printk(KERN_INFO DRIVER_NAME " v4l2 driver version %d.%d.%d loaded\n",
2494                (EM28XX_VERSION_CODE >> 16) & 0xff,
2495                (EM28XX_VERSION_CODE >> 8) & 0xff, EM28XX_VERSION_CODE & 0xff);
2496 #ifdef SNAPSHOT
2497         printk(KERN_INFO DRIVER_NAME " snapshot date %04d-%02d-%02d\n",
2498                SNAPSHOT / 10000, (SNAPSHOT / 100) % 100, SNAPSHOT % 100);
2499 #endif
2500
2501         /* register this driver with the USB subsystem */
2502         result = usb_register(&em28xx_usb_driver);
2503         if (result)
2504                 em28xx_err(DRIVER_NAME
2505                            " usb_register failed. Error number %d.\n", result);
2506
2507         return result;
2508 }
2509
2510 static void __exit em28xx_module_exit(void)
2511 {
2512         /* deregister this driver with the USB subsystem */
2513         usb_deregister(&em28xx_usb_driver);
2514 }
2515
2516 module_init(em28xx_module_init);
2517 module_exit(em28xx_module_exit);
2518