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