Merge branches 'for-3.19/hid-report-len', 'for-3.19/i2c-hid', 'for-3.19/lenovo',...
[firefly-linux-kernel-4.4.55.git] / drivers / media / usb / em28xx / em28xx-audio.c
1 /*
2  *  Empiatech em28x1 audio extension
3  *
4  *  Copyright (C) 2006 Markus Rechberger <mrechberger@gmail.com>
5  *
6  *  Copyright (C) 2007-2014 Mauro Carvalho Chehab
7  *      - Port to work with the in-kernel driver
8  *      - Cleanups, fixes, alsa-controls, etc.
9  *
10  *  This driver is based on my previous au600 usb pstn audio driver
11  *  and inherits all the copyrights
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/kernel.h>
29 #include <linux/usb.h>
30 #include <linux/init.h>
31 #include <linux/sound.h>
32 #include <linux/spinlock.h>
33 #include <linux/soundcard.h>
34 #include <linux/slab.h>
35 #include <linux/vmalloc.h>
36 #include <linux/proc_fs.h>
37 #include <linux/module.h>
38 #include <sound/core.h>
39 #include <sound/pcm.h>
40 #include <sound/pcm_params.h>
41 #include <sound/info.h>
42 #include <sound/initval.h>
43 #include <sound/control.h>
44 #include <sound/tlv.h>
45 #include <sound/ac97_codec.h>
46 #include <media/v4l2-common.h>
47 #include "em28xx.h"
48
49 static int debug;
50 module_param(debug, int, 0644);
51 MODULE_PARM_DESC(debug, "activates debug info");
52
53 #define EM28XX_MAX_AUDIO_BUFS           5
54 #define EM28XX_MIN_AUDIO_PACKETS        64
55
56 #define dprintk(fmt, arg...) do {                                       \
57             if (debug)                                                  \
58                 printk(KERN_INFO "em28xx-audio %s: " fmt,               \
59                                   __func__, ##arg);             \
60         } while (0)
61
62 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
63
64 static int em28xx_deinit_isoc_audio(struct em28xx *dev)
65 {
66         int i;
67
68         dprintk("Stopping isoc\n");
69         for (i = 0; i < dev->adev.num_urb; i++) {
70                 struct urb *urb = dev->adev.urb[i];
71
72                 if (!irqs_disabled())
73                         usb_kill_urb(urb);
74                 else
75                         usb_unlink_urb(urb);
76         }
77
78         return 0;
79 }
80
81 static void em28xx_audio_isocirq(struct urb *urb)
82 {
83         struct em28xx            *dev = urb->context;
84         int                      i;
85         unsigned int             oldptr;
86         int                      period_elapsed = 0;
87         int                      status;
88         unsigned char            *cp;
89         unsigned int             stride;
90         struct snd_pcm_substream *substream;
91         struct snd_pcm_runtime   *runtime;
92
93         if (dev->disconnected) {
94                 dprintk("device disconnected while streaming. URB status=%d.\n", urb->status);
95                 atomic_set(&dev->adev.stream_started, 0);
96                 return;
97         }
98
99         switch (urb->status) {
100         case 0:             /* success */
101         case -ETIMEDOUT:    /* NAK */
102                 break;
103         case -ECONNRESET:   /* kill */
104         case -ENOENT:
105         case -ESHUTDOWN:
106                 return;
107         default:            /* error */
108                 dprintk("urb completition error %d.\n", urb->status);
109                 break;
110         }
111
112         if (atomic_read(&dev->adev.stream_started) == 0)
113                 return;
114
115         if (dev->adev.capture_pcm_substream) {
116                 substream = dev->adev.capture_pcm_substream;
117                 runtime = substream->runtime;
118                 stride = runtime->frame_bits >> 3;
119
120                 for (i = 0; i < urb->number_of_packets; i++) {
121                         int length =
122                             urb->iso_frame_desc[i].actual_length / stride;
123                         cp = (unsigned char *)urb->transfer_buffer +
124                             urb->iso_frame_desc[i].offset;
125
126                         if (!length)
127                                 continue;
128
129                         oldptr = dev->adev.hwptr_done_capture;
130                         if (oldptr + length >= runtime->buffer_size) {
131                                 unsigned int cnt =
132                                     runtime->buffer_size - oldptr;
133                                 memcpy(runtime->dma_area + oldptr * stride, cp,
134                                        cnt * stride);
135                                 memcpy(runtime->dma_area, cp + cnt * stride,
136                                        length * stride - cnt * stride);
137                         } else {
138                                 memcpy(runtime->dma_area + oldptr * stride, cp,
139                                        length * stride);
140                         }
141
142                         snd_pcm_stream_lock(substream);
143
144                         dev->adev.hwptr_done_capture += length;
145                         if (dev->adev.hwptr_done_capture >=
146                             runtime->buffer_size)
147                                 dev->adev.hwptr_done_capture -=
148                                     runtime->buffer_size;
149
150                         dev->adev.capture_transfer_done += length;
151                         if (dev->adev.capture_transfer_done >=
152                             runtime->period_size) {
153                                 dev->adev.capture_transfer_done -=
154                                     runtime->period_size;
155                                 period_elapsed = 1;
156                         }
157
158                         snd_pcm_stream_unlock(substream);
159                 }
160                 if (period_elapsed)
161                         snd_pcm_period_elapsed(substream);
162         }
163         urb->status = 0;
164
165         status = usb_submit_urb(urb, GFP_ATOMIC);
166         if (status < 0)
167                 em28xx_errdev("resubmit of audio urb failed (error=%i)\n",
168                               status);
169         return;
170 }
171
172 static int em28xx_init_audio_isoc(struct em28xx *dev)
173 {
174         int       i, errCode;
175
176         dprintk("Starting isoc transfers\n");
177
178         /* Start streaming */
179         for (i = 0; i < dev->adev.num_urb; i++) {
180                 memset(dev->adev.transfer_buffer[i], 0x80,
181                        dev->adev.urb[i]->transfer_buffer_length);
182
183                 errCode = usb_submit_urb(dev->adev.urb[i], GFP_ATOMIC);
184                 if (errCode) {
185                         em28xx_errdev("submit of audio urb failed (error=%i)\n",
186                                       errCode);
187                         em28xx_deinit_isoc_audio(dev);
188                         atomic_set(&dev->adev.stream_started, 0);
189                         return errCode;
190                 }
191
192         }
193
194         return 0;
195 }
196
197 static int snd_pcm_alloc_vmalloc_buffer(struct snd_pcm_substream *subs,
198                                         size_t size)
199 {
200         struct snd_pcm_runtime *runtime = subs->runtime;
201
202         dprintk("Allocating vbuffer\n");
203         if (runtime->dma_area) {
204                 if (runtime->dma_bytes > size)
205                         return 0;
206
207                 vfree(runtime->dma_area);
208         }
209         runtime->dma_area = vmalloc(size);
210         if (!runtime->dma_area)
211                 return -ENOMEM;
212
213         runtime->dma_bytes = size;
214
215         return 0;
216 }
217
218 static struct snd_pcm_hardware snd_em28xx_hw_capture = {
219         .info = SNDRV_PCM_INFO_BLOCK_TRANSFER |
220                 SNDRV_PCM_INFO_MMAP           |
221                 SNDRV_PCM_INFO_INTERLEAVED    |
222                 SNDRV_PCM_INFO_BATCH          |
223                 SNDRV_PCM_INFO_MMAP_VALID,
224
225         .formats = SNDRV_PCM_FMTBIT_S16_LE,
226
227         .rates = SNDRV_PCM_RATE_48000,
228
229         .rate_min = 48000,
230         .rate_max = 48000,
231         .channels_min = 2,
232         .channels_max = 2,
233         .buffer_bytes_max = 62720 * 8,  /* just about the value in usbaudio.c */
234
235
236         /*
237          * The period is 12.288 bytes. Allow a 10% of variation along its
238          * value, in order to avoid overruns/underruns due to some clock
239          * drift.
240          *
241          * FIXME: This period assumes 64 packets, and a 48000 PCM rate.
242          * Calculate it dynamically.
243          */
244         .period_bytes_min = 11059,
245         .period_bytes_max = 13516,
246
247         .periods_min = 2,
248         .periods_max = 98,              /* 12544, */
249 };
250
251 static int snd_em28xx_capture_open(struct snd_pcm_substream *substream)
252 {
253         struct em28xx *dev = snd_pcm_substream_chip(substream);
254         struct snd_pcm_runtime *runtime = substream->runtime;
255         int nonblock, ret = 0;
256
257         if (!dev) {
258                 em28xx_err("BUG: em28xx can't find device struct."
259                                 " Can't proceed with open\n");
260                 return -ENODEV;
261         }
262
263         if (dev->disconnected)
264                 return -ENODEV;
265
266         dprintk("opening device and trying to acquire exclusive lock\n");
267
268         nonblock = !!(substream->f_flags & O_NONBLOCK);
269         if (nonblock) {
270                 if (!mutex_trylock(&dev->lock))
271                         return -EAGAIN;
272         } else
273                 mutex_lock(&dev->lock);
274
275         runtime->hw = snd_em28xx_hw_capture;
276
277         if (dev->adev.users == 0) {
278                 if (dev->alt == 0 || dev->is_audio_only) {
279                         if (dev->is_audio_only)
280                                 /* audio is on a separate interface */
281                                 dev->alt = 1;
282                         else
283                                 /* audio is on the same interface as video */
284                                 dev->alt = 7;
285                                 /*
286                                  * FIXME: The intention seems to be to select
287                                  * the alt setting with the largest
288                                  * wMaxPacketSize for the video endpoint.
289                                  * At least dev->alt should be used instead, but
290                                  * we should probably not touch it at all if it
291                                  * is already >0, because wMaxPacketSize of the
292                                  * audio endpoints seems to be the same for all.
293                                  */
294                         dprintk("changing alternate number on interface %d to %d\n",
295                                 dev->ifnum, dev->alt);
296                         usb_set_interface(dev->udev, dev->ifnum, dev->alt);
297                 }
298
299                 /* Sets volume, mute, etc */
300                 dev->mute = 0;
301                 ret = em28xx_audio_analog_set(dev);
302                 if (ret < 0)
303                         goto err;
304         }
305
306         kref_get(&dev->ref);
307         dev->adev.users++;
308         mutex_unlock(&dev->lock);
309
310         /* Dynamically adjust the period size */
311         snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
312         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_BYTES,
313                                      dev->adev.period * 95 / 100,
314                                      dev->adev.period * 105 / 100);
315
316         dev->adev.capture_pcm_substream = substream;
317
318         return 0;
319 err:
320         mutex_unlock(&dev->lock);
321
322         em28xx_err("Error while configuring em28xx mixer\n");
323         return ret;
324 }
325
326 static int snd_em28xx_pcm_close(struct snd_pcm_substream *substream)
327 {
328         struct em28xx *dev = snd_pcm_substream_chip(substream);
329
330         dprintk("closing device\n");
331
332         dev->mute = 1;
333         mutex_lock(&dev->lock);
334         dev->adev.users--;
335         if (atomic_read(&dev->adev.stream_started) > 0) {
336                 atomic_set(&dev->adev.stream_started, 0);
337                 schedule_work(&dev->adev.wq_trigger);
338         }
339
340         em28xx_audio_analog_set(dev);
341         if (substream->runtime->dma_area) {
342                 dprintk("freeing\n");
343                 vfree(substream->runtime->dma_area);
344                 substream->runtime->dma_area = NULL;
345         }
346         mutex_unlock(&dev->lock);
347         kref_put(&dev->ref, em28xx_free_device);
348
349         return 0;
350 }
351
352 static int snd_em28xx_hw_capture_params(struct snd_pcm_substream *substream,
353                                         struct snd_pcm_hw_params *hw_params)
354 {
355         int ret;
356         struct em28xx *dev = snd_pcm_substream_chip(substream);
357
358         if (dev->disconnected)
359                 return -ENODEV;
360
361         dprintk("Setting capture parameters\n");
362
363         ret = snd_pcm_alloc_vmalloc_buffer(substream,
364                                 params_buffer_bytes(hw_params));
365         if (ret < 0)
366                 return ret;
367 #if 0
368         /* TODO: set up em28xx audio chip to deliver the correct audio format,
369            current default is 48000hz multiplexed => 96000hz mono
370            which shouldn't matter since analogue TV only supports mono */
371         unsigned int channels, rate, format;
372
373         format = params_format(hw_params);
374         rate = params_rate(hw_params);
375         channels = params_channels(hw_params);
376 #endif
377
378         return 0;
379 }
380
381 static int snd_em28xx_hw_capture_free(struct snd_pcm_substream *substream)
382 {
383         struct em28xx *dev = snd_pcm_substream_chip(substream);
384         struct em28xx_audio *adev = &dev->adev;
385
386         dprintk("Stop capture, if needed\n");
387
388         if (atomic_read(&adev->stream_started) > 0) {
389                 atomic_set(&adev->stream_started, 0);
390                 schedule_work(&adev->wq_trigger);
391         }
392
393         return 0;
394 }
395
396 static int snd_em28xx_prepare(struct snd_pcm_substream *substream)
397 {
398         struct em28xx *dev = snd_pcm_substream_chip(substream);
399
400         if (dev->disconnected)
401                 return -ENODEV;
402
403         dev->adev.hwptr_done_capture = 0;
404         dev->adev.capture_transfer_done = 0;
405
406         return 0;
407 }
408
409 static void audio_trigger(struct work_struct *work)
410 {
411         struct em28xx_audio *adev =
412                             container_of(work, struct em28xx_audio, wq_trigger);
413         struct em28xx *dev = container_of(adev, struct em28xx, adev);
414
415         if (atomic_read(&adev->stream_started)) {
416                 dprintk("starting capture");
417                 em28xx_init_audio_isoc(dev);
418         } else {
419                 dprintk("stopping capture");
420                 em28xx_deinit_isoc_audio(dev);
421         }
422 }
423
424 static int snd_em28xx_capture_trigger(struct snd_pcm_substream *substream,
425                                       int cmd)
426 {
427         struct em28xx *dev = snd_pcm_substream_chip(substream);
428         int retval = 0;
429
430         if (dev->disconnected)
431                 return -ENODEV;
432
433         switch (cmd) {
434         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: /* fall through */
435         case SNDRV_PCM_TRIGGER_RESUME: /* fall through */
436         case SNDRV_PCM_TRIGGER_START:
437                 atomic_set(&dev->adev.stream_started, 1);
438                 break;
439         case SNDRV_PCM_TRIGGER_PAUSE_PUSH: /* fall through */
440         case SNDRV_PCM_TRIGGER_SUSPEND: /* fall through */
441         case SNDRV_PCM_TRIGGER_STOP:
442                 atomic_set(&dev->adev.stream_started, 0);
443                 break;
444         default:
445                 retval = -EINVAL;
446         }
447         schedule_work(&dev->adev.wq_trigger);
448         return retval;
449 }
450
451 static snd_pcm_uframes_t snd_em28xx_capture_pointer(struct snd_pcm_substream
452                                                     *substream)
453 {
454         unsigned long flags;
455         struct em28xx *dev;
456         snd_pcm_uframes_t hwptr_done;
457
458         dev = snd_pcm_substream_chip(substream);
459         if (dev->disconnected)
460                 return SNDRV_PCM_POS_XRUN;
461
462         spin_lock_irqsave(&dev->adev.slock, flags);
463         hwptr_done = dev->adev.hwptr_done_capture;
464         spin_unlock_irqrestore(&dev->adev.slock, flags);
465
466         return hwptr_done;
467 }
468
469 static struct page *snd_pcm_get_vmalloc_page(struct snd_pcm_substream *subs,
470                                              unsigned long offset)
471 {
472         void *pageptr = subs->runtime->dma_area + offset;
473
474         return vmalloc_to_page(pageptr);
475 }
476
477 /*
478  * AC97 volume control support
479  */
480 static int em28xx_vol_info(struct snd_kcontrol *kcontrol,
481                                 struct snd_ctl_elem_info *info)
482 {
483         struct em28xx *dev = snd_kcontrol_chip(kcontrol);
484
485         if (dev->disconnected)
486                 return -ENODEV;
487
488         info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
489         info->count = 2;
490         info->value.integer.min = 0;
491         info->value.integer.max = 0x1f;
492
493         return 0;
494 }
495
496 static int em28xx_vol_put(struct snd_kcontrol *kcontrol,
497                                struct snd_ctl_elem_value *value)
498 {
499         struct em28xx *dev = snd_kcontrol_chip(kcontrol);
500         struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
501         u16 val = (0x1f - (value->value.integer.value[0] & 0x1f)) |
502                   (0x1f - (value->value.integer.value[1] & 0x1f)) << 8;
503         int nonblock = 0;
504         int rc;
505
506         if (dev->disconnected)
507                 return -ENODEV;
508
509         if (substream)
510                 nonblock = !!(substream->f_flags & O_NONBLOCK);
511         if (nonblock) {
512                 if (!mutex_trylock(&dev->lock))
513                         return -EAGAIN;
514         } else
515                 mutex_lock(&dev->lock);
516         rc = em28xx_read_ac97(dev, kcontrol->private_value);
517         if (rc < 0)
518                 goto err;
519
520         val |= rc & 0x8000;     /* Preserve the mute flag */
521
522         rc = em28xx_write_ac97(dev, kcontrol->private_value, val);
523         if (rc < 0)
524                 goto err;
525
526         dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n",
527                 (val & 0x8000) ? "muted " : "",
528                 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
529                 val, (int)kcontrol->private_value);
530
531 err:
532         mutex_unlock(&dev->lock);
533         return rc;
534 }
535
536 static int em28xx_vol_get(struct snd_kcontrol *kcontrol,
537                                struct snd_ctl_elem_value *value)
538 {
539         struct em28xx *dev = snd_kcontrol_chip(kcontrol);
540         struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
541         int nonblock = 0;
542         int val;
543
544         if (dev->disconnected)
545                 return -ENODEV;
546
547         if (substream)
548                 nonblock = !!(substream->f_flags & O_NONBLOCK);
549         if (nonblock) {
550                 if (!mutex_trylock(&dev->lock))
551                         return -EAGAIN;
552         } else
553                 mutex_lock(&dev->lock);
554         val = em28xx_read_ac97(dev, kcontrol->private_value);
555         mutex_unlock(&dev->lock);
556         if (val < 0)
557                 return val;
558
559         dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n",
560                 (val & 0x8000) ? "muted " : "",
561                 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
562                 val, (int)kcontrol->private_value);
563
564         value->value.integer.value[0] = 0x1f - (val & 0x1f);
565         value->value.integer.value[1] = 0x1f - ((val << 8) & 0x1f);
566
567         return 0;
568 }
569
570 static int em28xx_vol_put_mute(struct snd_kcontrol *kcontrol,
571                                struct snd_ctl_elem_value *value)
572 {
573         struct em28xx *dev = snd_kcontrol_chip(kcontrol);
574         u16 val = value->value.integer.value[0];
575         struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
576         int nonblock = 0;
577         int rc;
578
579         if (dev->disconnected)
580                 return -ENODEV;
581
582         if (substream)
583                 nonblock = !!(substream->f_flags & O_NONBLOCK);
584         if (nonblock) {
585                 if (!mutex_trylock(&dev->lock))
586                         return -EAGAIN;
587         } else
588                 mutex_lock(&dev->lock);
589         rc = em28xx_read_ac97(dev, kcontrol->private_value);
590         if (rc < 0)
591                 goto err;
592
593         if (val)
594                 rc &= 0x1f1f;
595         else
596                 rc |= 0x8000;
597
598         rc = em28xx_write_ac97(dev, kcontrol->private_value, rc);
599         if (rc < 0)
600                 goto err;
601
602         dprintk("%sleft vol %d, right vol %d (0x%04x) to ac97 volume control 0x%04x\n",
603                 (val & 0x8000) ? "muted " : "",
604                 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
605                 val, (int)kcontrol->private_value);
606
607 err:
608         mutex_unlock(&dev->lock);
609         return rc;
610 }
611
612 static int em28xx_vol_get_mute(struct snd_kcontrol *kcontrol,
613                                struct snd_ctl_elem_value *value)
614 {
615         struct em28xx *dev = snd_kcontrol_chip(kcontrol);
616         struct snd_pcm_substream *substream = dev->adev.capture_pcm_substream;
617         int nonblock = 0;
618         int val;
619
620         if (dev->disconnected)
621                 return -ENODEV;
622
623         if (substream)
624                 nonblock = !!(substream->f_flags & O_NONBLOCK);
625         if (nonblock) {
626                 if (!mutex_trylock(&dev->lock))
627                         return -EAGAIN;
628         } else
629                 mutex_lock(&dev->lock);
630         val = em28xx_read_ac97(dev, kcontrol->private_value);
631         mutex_unlock(&dev->lock);
632         if (val < 0)
633                 return val;
634
635         if (val & 0x8000)
636                 value->value.integer.value[0] = 0;
637         else
638                 value->value.integer.value[0] = 1;
639
640         dprintk("%sleft vol %d, right vol %d (0x%04x) from ac97 volume control 0x%04x\n",
641                 (val & 0x8000) ? "muted " : "",
642                 0x1f - ((val >> 8) & 0x1f), 0x1f - (val & 0x1f),
643                 val, (int)kcontrol->private_value);
644
645         return 0;
646 }
647
648 static const DECLARE_TLV_DB_SCALE(em28xx_db_scale, -3450, 150, 0);
649
650 static int em28xx_cvol_new(struct snd_card *card, struct em28xx *dev,
651                            char *name, int id)
652 {
653         int err;
654         char ctl_name[44];
655         struct snd_kcontrol *kctl;
656         struct snd_kcontrol_new tmp;
657
658         memset (&tmp, 0, sizeof(tmp));
659         tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
660         tmp.private_value = id,
661         tmp.name  = ctl_name,
662
663         /* Add Mute Control */
664         sprintf(ctl_name, "%s Switch", name);
665         tmp.get  = em28xx_vol_get_mute;
666         tmp.put  = em28xx_vol_put_mute;
667         tmp.info = snd_ctl_boolean_mono_info;
668         kctl = snd_ctl_new1(&tmp, dev);
669         err = snd_ctl_add(card, kctl);
670         if (err < 0)
671                 return err;
672         dprintk("Added control %s for ac97 volume control 0x%04x\n",
673                 ctl_name, id);
674
675         memset (&tmp, 0, sizeof(tmp));
676         tmp.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
677         tmp.private_value = id,
678         tmp.name  = ctl_name,
679
680         /* Add Volume Control */
681         sprintf(ctl_name, "%s Volume", name);
682         tmp.get   = em28xx_vol_get;
683         tmp.put   = em28xx_vol_put;
684         tmp.info  = em28xx_vol_info;
685         tmp.tlv.p = em28xx_db_scale,
686         kctl = snd_ctl_new1(&tmp, dev);
687         err = snd_ctl_add(card, kctl);
688         if (err < 0)
689                 return err;
690         dprintk("Added control %s for ac97 volume control 0x%04x\n",
691                 ctl_name, id);
692
693         return 0;
694 }
695
696 /*
697  * register/unregister code and data
698  */
699 static struct snd_pcm_ops snd_em28xx_pcm_capture = {
700         .open      = snd_em28xx_capture_open,
701         .close     = snd_em28xx_pcm_close,
702         .ioctl     = snd_pcm_lib_ioctl,
703         .hw_params = snd_em28xx_hw_capture_params,
704         .hw_free   = snd_em28xx_hw_capture_free,
705         .prepare   = snd_em28xx_prepare,
706         .trigger   = snd_em28xx_capture_trigger,
707         .pointer   = snd_em28xx_capture_pointer,
708         .page      = snd_pcm_get_vmalloc_page,
709 };
710
711 static void em28xx_audio_free_urb(struct em28xx *dev)
712 {
713         int i;
714
715         for (i = 0; i < dev->adev.num_urb; i++) {
716                 struct urb *urb = dev->adev.urb[i];
717
718                 if (!urb)
719                         continue;
720
721                 usb_free_coherent(dev->udev, urb->transfer_buffer_length,
722                                   dev->adev.transfer_buffer[i],
723                                   urb->transfer_dma);
724
725                 usb_free_urb(urb);
726         }
727         kfree(dev->adev.urb);
728         kfree(dev->adev.transfer_buffer);
729         dev->adev.num_urb = 0;
730 }
731
732 /* high bandwidth multiplier, as encoded in highspeed endpoint descriptors */
733 static int em28xx_audio_ep_packet_size(struct usb_device *udev,
734                                         struct usb_endpoint_descriptor *e)
735 {
736         int size = le16_to_cpu(e->wMaxPacketSize);
737
738         if (udev->speed == USB_SPEED_HIGH)
739                 return (size & 0x7ff) *  (1 + (((size) >> 11) & 0x03));
740
741         return size & 0x7ff;
742 }
743
744 static int em28xx_audio_urb_init(struct em28xx *dev)
745 {
746         struct usb_interface *intf;
747         struct usb_endpoint_descriptor *e, *ep = NULL;
748         int                 i, ep_size, interval, num_urb, npackets;
749         int                 urb_size, bytes_per_transfer;
750         u8 alt;
751
752         if (dev->ifnum)
753                 alt = 1;
754         else
755                 alt = 7;
756
757         intf = usb_ifnum_to_if(dev->udev, dev->ifnum);
758
759         if (intf->num_altsetting <= alt) {
760                 em28xx_errdev("alt %d doesn't exist on interface %d\n",
761                               dev->ifnum, alt);
762                 return -ENODEV;
763         }
764
765         for (i = 0; i < intf->altsetting[alt].desc.bNumEndpoints; i++) {
766                 e = &intf->altsetting[alt].endpoint[i].desc;
767                 if (!usb_endpoint_dir_in(e))
768                         continue;
769                 if (e->bEndpointAddress == EM28XX_EP_AUDIO) {
770                         ep = e;
771                         break;
772                 }
773         }
774
775         if (!ep) {
776                 em28xx_errdev("Couldn't find an audio endpoint");
777                 return -ENODEV;
778         }
779
780         ep_size = em28xx_audio_ep_packet_size(dev->udev, ep);
781         interval = 1 << (ep->bInterval - 1);
782
783         em28xx_info("Endpoint 0x%02x %s on intf %d alt %d interval = %d, size %d\n",
784                      EM28XX_EP_AUDIO, usb_speed_string(dev->udev->speed),
785                      dev->ifnum, alt,
786                      interval,
787                      ep_size);
788
789         /* Calculate the number and size of URBs to better fit the audio samples */
790
791         /*
792          * Estimate the number of bytes per DMA transfer.
793          *
794          * This is given by the bit rate (for now, only 48000 Hz) multiplied
795          * by 2 channels and 2 bytes/sample divided by the number of microframe
796          * intervals and by the microframe rate (125 us)
797          */
798         bytes_per_transfer = DIV_ROUND_UP(48000 * 2 * 2, 125 * interval);
799
800         /*
801          * Estimate the number of transfer URBs. Don't let it go past the
802          * maximum number of URBs that is known to be supported by the device.
803          */
804         num_urb = DIV_ROUND_UP(bytes_per_transfer, ep_size);
805         if (num_urb > EM28XX_MAX_AUDIO_BUFS)
806                 num_urb = EM28XX_MAX_AUDIO_BUFS;
807
808         /*
809          * Now that we know the number of bytes per transfer and the number of
810          * URBs, estimate the typical size of an URB, in order to adjust the
811          * minimal number of packets.
812          */
813         urb_size = bytes_per_transfer / num_urb;
814
815         /*
816          * Now, calculate the amount of audio packets to be filled on each
817          * URB. In order to preserve the old behaviour, use a minimal
818          * threshold for this value.
819          */
820         npackets = EM28XX_MIN_AUDIO_PACKETS;
821         if (urb_size > ep_size * npackets)
822                 npackets = DIV_ROUND_UP(urb_size, ep_size);
823
824         em28xx_info("Number of URBs: %d, with %d packets and %d size",
825                     num_urb, npackets, urb_size);
826
827         /* Estimate the bytes per period */
828         dev->adev.period = urb_size * npackets;
829
830         /* Allocate space to store the number of URBs to be used */
831
832         dev->adev.transfer_buffer = kcalloc(num_urb,
833                                             sizeof(*dev->adev.transfer_buffer),
834                                             GFP_ATOMIC);
835         if (!dev->adev.transfer_buffer) {
836                 return -ENOMEM;
837         }
838
839         dev->adev.urb = kcalloc(num_urb, sizeof(*dev->adev.urb), GFP_ATOMIC);
840         if (!dev->adev.urb) {
841                 kfree(dev->adev.transfer_buffer);
842                 return -ENOMEM;
843         }
844
845         /* Alloc memory for each URB and for each transfer buffer */
846         dev->adev.num_urb = num_urb;
847         for (i = 0; i < num_urb; i++) {
848                 struct urb *urb;
849                 int j, k;
850                 void *buf;
851
852                 urb = usb_alloc_urb(npackets, GFP_ATOMIC);
853                 if (!urb) {
854                         em28xx_errdev("usb_alloc_urb failed!\n");
855                         em28xx_audio_free_urb(dev);
856                         return -ENOMEM;
857                 }
858                 dev->adev.urb[i] = urb;
859
860                 buf = usb_alloc_coherent(dev->udev, npackets * ep_size, GFP_ATOMIC,
861                                          &urb->transfer_dma);
862                 if (!buf) {
863                         em28xx_errdev("usb_alloc_coherent failed!\n");
864                         em28xx_audio_free_urb(dev);
865                         return -ENOMEM;
866                 }
867                 dev->adev.transfer_buffer[i] = buf;
868
869                 urb->dev = dev->udev;
870                 urb->context = dev;
871                 urb->pipe = usb_rcvisocpipe(dev->udev, EM28XX_EP_AUDIO);
872                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
873                 urb->transfer_buffer = buf;
874                 urb->interval = interval;
875                 urb->complete = em28xx_audio_isocirq;
876                 urb->number_of_packets = npackets;
877                 urb->transfer_buffer_length = ep_size * npackets;
878
879                 for (j = k = 0; j < npackets; j++, k += ep_size) {
880                         urb->iso_frame_desc[j].offset = k;
881                         urb->iso_frame_desc[j].length = ep_size;
882                 }
883         }
884
885         return 0;
886 }
887
888 static int em28xx_audio_init(struct em28xx *dev)
889 {
890         struct em28xx_audio *adev = &dev->adev;
891         struct snd_pcm      *pcm;
892         struct snd_card     *card;
893         static int          devnr;
894         int                 err;
895
896         if (dev->usb_audio_type != EM28XX_USB_AUDIO_VENDOR) {
897                 /* This device does not support the extension (in this case
898                    the device is expecting the snd-usb-audio module or
899                    doesn't have analog audio support at all) */
900                 return 0;
901         }
902
903         em28xx_info("Binding audio extension\n");
904
905         kref_get(&dev->ref);
906
907         printk(KERN_INFO "em28xx-audio.c: Copyright (C) 2006 Markus "
908                          "Rechberger\n");
909         printk(KERN_INFO
910                "em28xx-audio.c: Copyright (C) 2007-2014 Mauro Carvalho Chehab\n");
911
912         err = snd_card_new(&dev->udev->dev, index[devnr], "Em28xx Audio",
913                            THIS_MODULE, 0, &card);
914         if (err < 0)
915                 return err;
916
917         spin_lock_init(&adev->slock);
918         adev->sndcard = card;
919         adev->udev = dev->udev;
920
921         err = snd_pcm_new(card, "Em28xx Audio", 0, 0, 1, &pcm);
922         if (err < 0)
923                 goto card_free;
924
925         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_em28xx_pcm_capture);
926         pcm->info_flags = 0;
927         pcm->private_data = dev;
928         strcpy(pcm->name, "Empia 28xx Capture");
929
930         strcpy(card->driver, "Em28xx-Audio");
931         strcpy(card->shortname, "Em28xx Audio");
932         strcpy(card->longname, "Empia Em28xx Audio");
933
934         INIT_WORK(&adev->wq_trigger, audio_trigger);
935
936         if (dev->audio_mode.ac97 != EM28XX_NO_AC97) {
937                 em28xx_cvol_new(card, dev, "Video", AC97_VIDEO);
938                 em28xx_cvol_new(card, dev, "Line In", AC97_LINE);
939                 em28xx_cvol_new(card, dev, "Phone", AC97_PHONE);
940                 em28xx_cvol_new(card, dev, "Microphone", AC97_MIC);
941                 em28xx_cvol_new(card, dev, "CD", AC97_CD);
942                 em28xx_cvol_new(card, dev, "AUX", AC97_AUX);
943                 em28xx_cvol_new(card, dev, "PCM", AC97_PCM);
944
945                 em28xx_cvol_new(card, dev, "Master", AC97_MASTER);
946                 em28xx_cvol_new(card, dev, "Line", AC97_HEADPHONE);
947                 em28xx_cvol_new(card, dev, "Mono", AC97_MASTER_MONO);
948                 em28xx_cvol_new(card, dev, "LFE", AC97_CENTER_LFE_MASTER);
949                 em28xx_cvol_new(card, dev, "Surround", AC97_SURROUND_MASTER);
950         }
951
952         err = em28xx_audio_urb_init(dev);
953         if (err)
954                 goto card_free;
955
956         err = snd_card_register(card);
957         if (err < 0)
958                 goto urb_free;
959
960         em28xx_info("Audio extension successfully initialized\n");
961         return 0;
962
963 urb_free:
964         em28xx_audio_free_urb(dev);
965
966 card_free:
967         snd_card_free(card);
968         adev->sndcard = NULL;
969
970         return err;
971 }
972
973 static int em28xx_audio_fini(struct em28xx *dev)
974 {
975         if (dev == NULL)
976                 return 0;
977
978         if (dev->usb_audio_type != EM28XX_USB_AUDIO_VENDOR) {
979                 /* This device does not support the extension (in this case
980                    the device is expecting the snd-usb-audio module or
981                    doesn't have analog audio support at all) */
982                 return 0;
983         }
984
985         em28xx_info("Closing audio extension");
986
987         if (dev->adev.sndcard) {
988                 snd_card_disconnect(dev->adev.sndcard);
989                 flush_work(&dev->adev.wq_trigger);
990
991                 em28xx_audio_free_urb(dev);
992
993                 snd_card_free(dev->adev.sndcard);
994                 dev->adev.sndcard = NULL;
995         }
996
997         kref_put(&dev->ref, em28xx_free_device);
998         return 0;
999 }
1000
1001 static int em28xx_audio_suspend(struct em28xx *dev)
1002 {
1003         if (dev == NULL)
1004                 return 0;
1005
1006         if (dev->usb_audio_type != EM28XX_USB_AUDIO_VENDOR)
1007                 return 0;
1008
1009         em28xx_info("Suspending audio extension");
1010         em28xx_deinit_isoc_audio(dev);
1011         atomic_set(&dev->adev.stream_started, 0);
1012         return 0;
1013 }
1014
1015 static int em28xx_audio_resume(struct em28xx *dev)
1016 {
1017         if (dev == NULL)
1018                 return 0;
1019
1020         if (dev->usb_audio_type != EM28XX_USB_AUDIO_VENDOR)
1021                 return 0;
1022
1023         em28xx_info("Resuming audio extension");
1024         /* Nothing to do other than schedule_work() ?? */
1025         schedule_work(&dev->adev.wq_trigger);
1026         return 0;
1027 }
1028
1029 static struct em28xx_ops audio_ops = {
1030         .id   = EM28XX_AUDIO,
1031         .name = "Em28xx Audio Extension",
1032         .init = em28xx_audio_init,
1033         .fini = em28xx_audio_fini,
1034         .suspend = em28xx_audio_suspend,
1035         .resume = em28xx_audio_resume,
1036 };
1037
1038 static int __init em28xx_alsa_register(void)
1039 {
1040         return em28xx_register_extension(&audio_ops);
1041 }
1042
1043 static void __exit em28xx_alsa_unregister(void)
1044 {
1045         em28xx_unregister_extension(&audio_ops);
1046 }
1047
1048 MODULE_LICENSE("GPL");
1049 MODULE_AUTHOR("Markus Rechberger <mrechberger@gmail.com>");
1050 MODULE_AUTHOR("Mauro Carvalho Chehab");
1051 MODULE_DESCRIPTION(DRIVER_DESC " - audio interface");
1052 MODULE_VERSION(EM28XX_VERSION);
1053
1054 module_init(em28xx_alsa_register);
1055 module_exit(em28xx_alsa_unregister);