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