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