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