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