1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 *   (Tentative) USB Audio Driver for ALSA
4 *
5 *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
6 *
7 *   Many codes borrowed from audio.c by
8 *	    Alan Cox (alan@lxorguk.ukuu.org.uk)
9 *	    Thomas Sailer (sailer@ife.ee.ethz.ch)
10 *
11 *   Audio Class 3.0 support by Ruslan Bilovol <ruslan.bilovol@gmail.com>
12 *
13 *  NOTES:
14 *
15 *   - the linked URBs would be preferred but not used so far because of
16 *     the instability of unlinking.
17 *   - type II is not supported properly.  there is no device which supports
18 *     this type *correctly*.  SB extigy looks as if it supports, but it's
19 *     indeed an AC3 stream packed in SPDIF frames (i.e. no real AC3 stream).
20 */
21
22
23#include <linux/bitops.h>
24#include <linux/init.h>
25#include <linux/list.h>
26#include <linux/slab.h>
27#include <linux/string.h>
28#include <linux/ctype.h>
29#include <linux/usb.h>
30#include <linux/moduleparam.h>
31#include <linux/mutex.h>
32#include <linux/usb/audio.h>
33#include <linux/usb/audio-v2.h>
34#include <linux/usb/audio-v3.h>
35#include <linux/module.h>
36
37#include <sound/control.h>
38#include <sound/core.h>
39#include <sound/info.h>
40#include <sound/pcm.h>
41#include <sound/pcm_params.h>
42#include <sound/initval.h>
43
44#include "usbaudio.h"
45#include "card.h"
46#include "midi.h"
47#include "midi2.h"
48#include "mixer.h"
49#include "proc.h"
50#include "quirks.h"
51#include "endpoint.h"
52#include "helper.h"
53#include "pcm.h"
54#include "format.h"
55#include "power.h"
56#include "stream.h"
57#include "media.h"
58
59MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
60MODULE_DESCRIPTION("USB Audio");
61MODULE_LICENSE("GPL");
62
63static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;	/* Index 0-MAX */
64static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;	/* ID for this card */
65static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;/* Enable this card */
66/* Vendor/product IDs for this card */
67static int vid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
68static int pid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
69static int device_setup[SNDRV_CARDS]; /* device parameter for this card */
70static bool ignore_ctl_error;
71static bool autoclock = true;
72static bool lowlatency = true;
73static char *quirk_alias[SNDRV_CARDS];
74static char *delayed_register[SNDRV_CARDS];
75static bool implicit_fb[SNDRV_CARDS];
76static unsigned int quirk_flags[SNDRV_CARDS];
77
78bool snd_usb_use_vmalloc = true;
79bool snd_usb_skip_validation;
80
81module_param_array(index, int, NULL, 0444);
82MODULE_PARM_DESC(index, "Index value for the USB audio adapter.");
83module_param_array(id, charp, NULL, 0444);
84MODULE_PARM_DESC(id, "ID string for the USB audio adapter.");
85module_param_array(enable, bool, NULL, 0444);
86MODULE_PARM_DESC(enable, "Enable USB audio adapter.");
87module_param_array(vid, int, NULL, 0444);
88MODULE_PARM_DESC(vid, "Vendor ID for the USB audio device.");
89module_param_array(pid, int, NULL, 0444);
90MODULE_PARM_DESC(pid, "Product ID for the USB audio device.");
91module_param_array(device_setup, int, NULL, 0444);
92MODULE_PARM_DESC(device_setup, "Specific device setup (if needed).");
93module_param(ignore_ctl_error, bool, 0444);
94MODULE_PARM_DESC(ignore_ctl_error,
95		 "Ignore errors from USB controller for mixer interfaces.");
96module_param(autoclock, bool, 0444);
97MODULE_PARM_DESC(autoclock, "Enable auto-clock selection for UAC2 devices (default: yes).");
98module_param(lowlatency, bool, 0444);
99MODULE_PARM_DESC(lowlatency, "Enable low latency playback (default: yes).");
100module_param_array(quirk_alias, charp, NULL, 0444);
101MODULE_PARM_DESC(quirk_alias, "Quirk aliases, e.g. 0123abcd:5678beef.");
102module_param_array(delayed_register, charp, NULL, 0444);
103MODULE_PARM_DESC(delayed_register, "Quirk for delayed registration, given by id:iface, e.g. 0123abcd:4.");
104module_param_array(implicit_fb, bool, NULL, 0444);
105MODULE_PARM_DESC(implicit_fb, "Apply generic implicit feedback sync mode.");
106module_param_array(quirk_flags, uint, NULL, 0444);
107MODULE_PARM_DESC(quirk_flags, "Driver quirk bit flags.");
108module_param_named(use_vmalloc, snd_usb_use_vmalloc, bool, 0444);
109MODULE_PARM_DESC(use_vmalloc, "Use vmalloc for PCM intermediate buffers (default: yes).");
110module_param_named(skip_validation, snd_usb_skip_validation, bool, 0444);
111MODULE_PARM_DESC(skip_validation, "Skip unit descriptor validation (default: no).");
112
113/*
114 * we keep the snd_usb_audio_t instances by ourselves for merging
115 * the all interfaces on the same card as one sound device.
116 */
117
118static DEFINE_MUTEX(register_mutex);
119static struct snd_usb_audio *usb_chip[SNDRV_CARDS];
120static struct usb_driver usb_audio_driver;
121
122/*
123 * disconnect streams
124 * called from usb_audio_disconnect()
125 */
126static void snd_usb_stream_disconnect(struct snd_usb_stream *as)
127{
128	int idx;
129	struct snd_usb_substream *subs;
130
131	for (idx = 0; idx < 2; idx++) {
132		subs = &as->substream[idx];
133		if (!subs->num_formats)
134			continue;
135		subs->data_endpoint = NULL;
136		subs->sync_endpoint = NULL;
137	}
138}
139
140static int snd_usb_create_stream(struct snd_usb_audio *chip, int ctrlif, int interface)
141{
142	struct usb_device *dev = chip->dev;
143	struct usb_host_interface *alts;
144	struct usb_interface_descriptor *altsd;
145	struct usb_interface *iface = usb_ifnum_to_if(dev, interface);
146
147	if (!iface) {
148		dev_err(&dev->dev, "%u:%d : does not exist\n",
149			ctrlif, interface);
150		return -EINVAL;
151	}
152
153	alts = &iface->altsetting[0];
154	altsd = get_iface_desc(alts);
155
156	/*
157	 * Android with both accessory and audio interfaces enabled gets the
158	 * interface numbers wrong.
159	 */
160	if ((chip->usb_id == USB_ID(0x18d1, 0x2d04) ||
161	     chip->usb_id == USB_ID(0x18d1, 0x2d05)) &&
162	    interface == 0 &&
163	    altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
164	    altsd->bInterfaceSubClass == USB_SUBCLASS_VENDOR_SPEC) {
165		interface = 2;
166		iface = usb_ifnum_to_if(dev, interface);
167		if (!iface)
168			return -EINVAL;
169		alts = &iface->altsetting[0];
170		altsd = get_iface_desc(alts);
171	}
172
173	if (usb_interface_claimed(iface)) {
174		dev_dbg(&dev->dev, "%d:%d: skipping, already claimed\n",
175			ctrlif, interface);
176		return -EINVAL;
177	}
178
179	if ((altsd->bInterfaceClass == USB_CLASS_AUDIO ||
180	     altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC) &&
181	    altsd->bInterfaceSubClass == USB_SUBCLASS_MIDISTREAMING) {
182		int err = snd_usb_midi_v2_create(chip, iface, NULL,
183						 chip->usb_id);
184		if (err < 0) {
185			dev_err(&dev->dev,
186				"%u:%d: cannot create sequencer device\n",
187				ctrlif, interface);
188			return -EINVAL;
189		}
190		return usb_driver_claim_interface(&usb_audio_driver, iface,
191						  USB_AUDIO_IFACE_UNUSED);
192	}
193
194	if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
195	     altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
196	    altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING) {
197		dev_dbg(&dev->dev,
198			"%u:%d: skipping non-supported interface %d\n",
199			ctrlif, interface, altsd->bInterfaceClass);
200		/* skip non-supported classes */
201		return -EINVAL;
202	}
203
204	if (snd_usb_get_speed(dev) == USB_SPEED_LOW) {
205		dev_err(&dev->dev, "low speed audio streaming not supported\n");
206		return -EINVAL;
207	}
208
209	if (! snd_usb_parse_audio_interface(chip, interface)) {
210		usb_set_interface(dev, interface, 0); /* reset the current interface */
211		return usb_driver_claim_interface(&usb_audio_driver, iface,
212						  USB_AUDIO_IFACE_UNUSED);
213	}
214
215	return 0;
216}
217
218/*
219 * parse audio control descriptor and create pcm/midi streams
220 */
221static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)
222{
223	struct usb_device *dev = chip->dev;
224	struct usb_host_interface *host_iface;
225	struct usb_interface_descriptor *altsd;
226	int i, protocol;
227
228	/* find audiocontrol interface */
229	host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
230	altsd = get_iface_desc(host_iface);
231	protocol = altsd->bInterfaceProtocol;
232
233	switch (protocol) {
234	default:
235		dev_warn(&dev->dev,
236			 "unknown interface protocol %#02x, assuming v1\n",
237			 protocol);
238		fallthrough;
239
240	case UAC_VERSION_1: {
241		struct uac1_ac_header_descriptor *h1;
242		int rest_bytes;
243
244		h1 = snd_usb_find_csint_desc(host_iface->extra,
245							 host_iface->extralen,
246							 NULL, UAC_HEADER);
247		if (!h1 || h1->bLength < sizeof(*h1)) {
248			dev_err(&dev->dev, "cannot find UAC_HEADER\n");
249			return -EINVAL;
250		}
251
252		rest_bytes = (void *)(host_iface->extra +
253				host_iface->extralen) - (void *)h1;
254
255		/* just to be sure -- this shouldn't hit at all */
256		if (rest_bytes <= 0) {
257			dev_err(&dev->dev, "invalid control header\n");
258			return -EINVAL;
259		}
260
261		if (rest_bytes < sizeof(*h1)) {
262			dev_err(&dev->dev, "too short v1 buffer descriptor\n");
263			return -EINVAL;
264		}
265
266		if (!h1->bInCollection) {
267			dev_info(&dev->dev, "skipping empty audio interface (v1)\n");
268			return -EINVAL;
269		}
270
271		if (rest_bytes < h1->bLength) {
272			dev_err(&dev->dev, "invalid buffer length (v1)\n");
273			return -EINVAL;
274		}
275
276		if (h1->bLength < sizeof(*h1) + h1->bInCollection) {
277			dev_err(&dev->dev, "invalid UAC_HEADER (v1)\n");
278			return -EINVAL;
279		}
280
281		for (i = 0; i < h1->bInCollection; i++)
282			snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);
283
284		break;
285	}
286
287	case UAC_VERSION_2:
288	case UAC_VERSION_3: {
289		struct usb_interface_assoc_descriptor *assoc =
290			usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
291
292		if (!assoc) {
293			/*
294			 * Firmware writers cannot count to three.  So to find
295			 * the IAD on the NuForce UDH-100, also check the next
296			 * interface.
297			 */
298			struct usb_interface *iface =
299				usb_ifnum_to_if(dev, ctrlif + 1);
300			if (iface &&
301			    iface->intf_assoc &&
302			    iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&
303			    iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)
304				assoc = iface->intf_assoc;
305		}
306
307		if (!assoc) {
308			dev_err(&dev->dev, "Audio class v2/v3 interfaces need an interface association\n");
309			return -EINVAL;
310		}
311
312		if (protocol == UAC_VERSION_3) {
313			int badd = assoc->bFunctionSubClass;
314
315			if (badd != UAC3_FUNCTION_SUBCLASS_FULL_ADC_3_0 &&
316			    (badd < UAC3_FUNCTION_SUBCLASS_GENERIC_IO ||
317			     badd > UAC3_FUNCTION_SUBCLASS_SPEAKERPHONE)) {
318				dev_err(&dev->dev,
319					"Unsupported UAC3 BADD profile\n");
320				return -EINVAL;
321			}
322
323			chip->badd_profile = badd;
324		}
325
326		for (i = 0; i < assoc->bInterfaceCount; i++) {
327			int intf = assoc->bFirstInterface + i;
328
329			if (intf != ctrlif)
330				snd_usb_create_stream(chip, ctrlif, intf);
331		}
332
333		break;
334	}
335	}
336
337	return 0;
338}
339
340/*
341 * Profile name preset table
342 */
343struct usb_audio_device_name {
344	u32 id;
345	const char *vendor_name;
346	const char *product_name;
347	const char *profile_name;	/* override card->longname */
348};
349
350#define PROFILE_NAME(vid, pid, vendor, product, profile)	 \
351	{ .id = USB_ID(vid, pid), .vendor_name = (vendor),	 \
352	  .product_name = (product), .profile_name = (profile) }
353#define DEVICE_NAME(vid, pid, vendor, product) \
354	PROFILE_NAME(vid, pid, vendor, product, NULL)
355
356/* vendor/product and profile name presets, sorted in device id order */
357static const struct usb_audio_device_name usb_audio_names[] = {
358	/* HP Thunderbolt Dock Audio Headset */
359	PROFILE_NAME(0x03f0, 0x0269, "HP", "Thunderbolt Dock Audio Headset",
360		     "HP-Thunderbolt-Dock-Audio-Headset"),
361	/* HP Thunderbolt Dock Audio Module */
362	PROFILE_NAME(0x03f0, 0x0567, "HP", "Thunderbolt Dock Audio Module",
363		     "HP-Thunderbolt-Dock-Audio-Module"),
364
365	/* Two entries for Gigabyte TRX40 Aorus Master:
366	 * TRX40 Aorus Master has two USB-audio devices, one for the front
367	 * headphone with ESS SABRE9218 DAC chip, while another for the rest
368	 * I/O (the rear panel and the front mic) with Realtek ALC1220-VB.
369	 * Here we provide two distinct names for making UCM profiles easier.
370	 */
371	PROFILE_NAME(0x0414, 0xa000, "Gigabyte", "Aorus Master Front Headphone",
372		     "Gigabyte-Aorus-Master-Front-Headphone"),
373	PROFILE_NAME(0x0414, 0xa001, "Gigabyte", "Aorus Master Main Audio",
374		     "Gigabyte-Aorus-Master-Main-Audio"),
375
376	/* Gigabyte TRX40 Aorus Pro WiFi */
377	PROFILE_NAME(0x0414, 0xa002,
378		     "Realtek", "ALC1220-VB-DT", "Realtek-ALC1220-VB-Desktop"),
379
380	/* Creative/E-Mu devices */
381	DEVICE_NAME(0x041e, 0x3010, "Creative Labs", "Sound Blaster MP3+"),
382	/* Creative/Toshiba Multimedia Center SB-0500 */
383	DEVICE_NAME(0x041e, 0x3048, "Toshiba", "SB-0500"),
384
385	DEVICE_NAME(0x046d, 0x0990, "Logitech, Inc.", "QuickCam Pro 9000"),
386
387	DEVICE_NAME(0x05e1, 0x0408, "Syntek", "STK1160"),
388	DEVICE_NAME(0x05e1, 0x0480, "Hauppauge", "Woodbury"),
389
390	/* ASUS ROG Zenith II: this machine has also two devices, one for
391	 * the front headphone and another for the rest
392	 */
393	PROFILE_NAME(0x0b05, 0x1915, "ASUS", "Zenith II Front Headphone",
394		     "Zenith-II-Front-Headphone"),
395	PROFILE_NAME(0x0b05, 0x1916, "ASUS", "Zenith II Main Audio",
396		     "Zenith-II-Main-Audio"),
397
398	/* ASUS ROG Strix */
399	PROFILE_NAME(0x0b05, 0x1917,
400		     "Realtek", "ALC1220-VB-DT", "Realtek-ALC1220-VB-Desktop"),
401	/* ASUS PRIME TRX40 PRO-S */
402	PROFILE_NAME(0x0b05, 0x1918,
403		     "Realtek", "ALC1220-VB-DT", "Realtek-ALC1220-VB-Desktop"),
404
405	/* Dell WD15 Dock */
406	PROFILE_NAME(0x0bda, 0x4014, "Dell", "WD15 Dock", "Dell-WD15-Dock"),
407	/* Dell WD19 Dock */
408	PROFILE_NAME(0x0bda, 0x402e, "Dell", "WD19 Dock", "Dell-WD15-Dock"),
409
410	DEVICE_NAME(0x0ccd, 0x0028, "TerraTec", "Aureon5.1MkII"),
411
412	/*
413	 * The original product_name is "USB Sound Device", however this name
414	 * is also used by the CM106 based cards, so make it unique.
415	 */
416	DEVICE_NAME(0x0d8c, 0x0102, NULL, "ICUSBAUDIO7D"),
417	DEVICE_NAME(0x0d8c, 0x0103, NULL, "Audio Advantage MicroII"),
418
419	/* MSI TRX40 Creator */
420	PROFILE_NAME(0x0db0, 0x0d64,
421		     "Realtek", "ALC1220-VB-DT", "Realtek-ALC1220-VB-Desktop"),
422	/* MSI TRX40 */
423	PROFILE_NAME(0x0db0, 0x543d,
424		     "Realtek", "ALC1220-VB-DT", "Realtek-ALC1220-VB-Desktop"),
425
426	DEVICE_NAME(0x0fd9, 0x0008, "Hauppauge", "HVR-950Q"),
427
428	/* Stanton/N2IT Final Scratch v1 device ('Scratchamp') */
429	DEVICE_NAME(0x103d, 0x0100, "Stanton", "ScratchAmp"),
430	DEVICE_NAME(0x103d, 0x0101, "Stanton", "ScratchAmp"),
431
432	/* aka. Serato Scratch Live DJ Box */
433	DEVICE_NAME(0x13e5, 0x0001, "Rane", "SL-1"),
434
435	/* Lenovo ThinkStation P620 Rear Line-in, Line-out and Microphone */
436	PROFILE_NAME(0x17aa, 0x1046, "Lenovo", "ThinkStation P620 Rear",
437		     "Lenovo-ThinkStation-P620-Rear"),
438	/* Lenovo ThinkStation P620 Internal Speaker + Front Headset */
439	PROFILE_NAME(0x17aa, 0x104d, "Lenovo", "ThinkStation P620 Main",
440		     "Lenovo-ThinkStation-P620-Main"),
441
442	/* Asrock TRX40 Creator */
443	PROFILE_NAME(0x26ce, 0x0a01,
444		     "Realtek", "ALC1220-VB-DT", "Realtek-ALC1220-VB-Desktop"),
445
446	DEVICE_NAME(0x2040, 0x7200, "Hauppauge", "HVR-950Q"),
447	DEVICE_NAME(0x2040, 0x7201, "Hauppauge", "HVR-950Q-MXL"),
448	DEVICE_NAME(0x2040, 0x7210, "Hauppauge", "HVR-950Q"),
449	DEVICE_NAME(0x2040, 0x7211, "Hauppauge", "HVR-950Q-MXL"),
450	DEVICE_NAME(0x2040, 0x7213, "Hauppauge", "HVR-950Q"),
451	DEVICE_NAME(0x2040, 0x7217, "Hauppauge", "HVR-950Q"),
452	DEVICE_NAME(0x2040, 0x721b, "Hauppauge", "HVR-950Q"),
453	DEVICE_NAME(0x2040, 0x721e, "Hauppauge", "HVR-950Q"),
454	DEVICE_NAME(0x2040, 0x721f, "Hauppauge", "HVR-950Q"),
455	DEVICE_NAME(0x2040, 0x7240, "Hauppauge", "HVR-850"),
456	DEVICE_NAME(0x2040, 0x7260, "Hauppauge", "HVR-950Q"),
457	DEVICE_NAME(0x2040, 0x7270, "Hauppauge", "HVR-950Q"),
458	DEVICE_NAME(0x2040, 0x7280, "Hauppauge", "HVR-950Q"),
459	DEVICE_NAME(0x2040, 0x7281, "Hauppauge", "HVR-950Q-MXL"),
460	DEVICE_NAME(0x2040, 0x8200, "Hauppauge", "Woodbury"),
461
462	{ } /* terminator */
463};
464
465static const struct usb_audio_device_name *
466lookup_device_name(u32 id)
467{
468	static const struct usb_audio_device_name *p;
469
470	for (p = usb_audio_names; p->id; p++)
471		if (p->id == id)
472			return p;
473	return NULL;
474}
475
476/*
477 * free the chip instance
478 *
479 * here we have to do not much, since pcm and controls are already freed
480 *
481 */
482
483static void snd_usb_audio_free(struct snd_card *card)
484{
485	struct snd_usb_audio *chip = card->private_data;
486
487	snd_usb_endpoint_free_all(chip);
488	snd_usb_midi_v2_free_all(chip);
489
490	mutex_destroy(&chip->mutex);
491	if (!atomic_read(&chip->shutdown))
492		dev_set_drvdata(&chip->dev->dev, NULL);
493}
494
495static void usb_audio_make_shortname(struct usb_device *dev,
496				     struct snd_usb_audio *chip,
497				     const struct snd_usb_audio_quirk *quirk)
498{
499	struct snd_card *card = chip->card;
500	const struct usb_audio_device_name *preset;
501	const char *s = NULL;
502
503	preset = lookup_device_name(chip->usb_id);
504	if (preset && preset->product_name)
505		s = preset->product_name;
506	else if (quirk && quirk->product_name)
507		s = quirk->product_name;
508	if (s && *s) {
509		strscpy(card->shortname, s, sizeof(card->shortname));
510		return;
511	}
512
513	/* retrieve the device string as shortname */
514	if (!dev->descriptor.iProduct ||
515	    usb_string(dev, dev->descriptor.iProduct,
516		       card->shortname, sizeof(card->shortname)) <= 0) {
517		/* no name available from anywhere, so use ID */
518		sprintf(card->shortname, "USB Device %#04x:%#04x",
519			USB_ID_VENDOR(chip->usb_id),
520			USB_ID_PRODUCT(chip->usb_id));
521	}
522
523	strim(card->shortname);
524}
525
526static void usb_audio_make_longname(struct usb_device *dev,
527				    struct snd_usb_audio *chip,
528				    const struct snd_usb_audio_quirk *quirk)
529{
530	struct snd_card *card = chip->card;
531	const struct usb_audio_device_name *preset;
532	const char *s = NULL;
533	int len;
534
535	preset = lookup_device_name(chip->usb_id);
536
537	/* shortcut - if any pre-defined string is given, use it */
538	if (preset && preset->profile_name)
539		s = preset->profile_name;
540	if (s && *s) {
541		strscpy(card->longname, s, sizeof(card->longname));
542		return;
543	}
544
545	if (preset && preset->vendor_name)
546		s = preset->vendor_name;
547	else if (quirk && quirk->vendor_name)
548		s = quirk->vendor_name;
549	*card->longname = 0;
550	if (s && *s) {
551		strscpy(card->longname, s, sizeof(card->longname));
552	} else {
553		/* retrieve the vendor and device strings as longname */
554		if (dev->descriptor.iManufacturer)
555			usb_string(dev, dev->descriptor.iManufacturer,
556				   card->longname, sizeof(card->longname));
557		/* we don't really care if there isn't any vendor string */
558	}
559	if (*card->longname) {
560		strim(card->longname);
561		if (*card->longname)
562			strlcat(card->longname, " ", sizeof(card->longname));
563	}
564
565	strlcat(card->longname, card->shortname, sizeof(card->longname));
566
567	len = strlcat(card->longname, " at ", sizeof(card->longname));
568
569	if (len < sizeof(card->longname))
570		usb_make_path(dev, card->longname + len, sizeof(card->longname) - len);
571
572	switch (snd_usb_get_speed(dev)) {
573	case USB_SPEED_LOW:
574		strlcat(card->longname, ", low speed", sizeof(card->longname));
575		break;
576	case USB_SPEED_FULL:
577		strlcat(card->longname, ", full speed", sizeof(card->longname));
578		break;
579	case USB_SPEED_HIGH:
580		strlcat(card->longname, ", high speed", sizeof(card->longname));
581		break;
582	case USB_SPEED_SUPER:
583		strlcat(card->longname, ", super speed", sizeof(card->longname));
584		break;
585	case USB_SPEED_SUPER_PLUS:
586		strlcat(card->longname, ", super speed plus", sizeof(card->longname));
587		break;
588	default:
589		break;
590	}
591}
592
593/*
594 * create a chip instance and set its names.
595 */
596static int snd_usb_audio_create(struct usb_interface *intf,
597				struct usb_device *dev, int idx,
598				const struct snd_usb_audio_quirk *quirk,
599				unsigned int usb_id,
600				struct snd_usb_audio **rchip)
601{
602	struct snd_card *card;
603	struct snd_usb_audio *chip;
604	int err;
605	char component[14];
606
607	*rchip = NULL;
608
609	switch (snd_usb_get_speed(dev)) {
610	case USB_SPEED_LOW:
611	case USB_SPEED_FULL:
612	case USB_SPEED_HIGH:
613	case USB_SPEED_SUPER:
614	case USB_SPEED_SUPER_PLUS:
615		break;
616	default:
617		dev_err(&dev->dev, "unknown device speed %d\n", snd_usb_get_speed(dev));
618		return -ENXIO;
619	}
620
621	err = snd_card_new(&intf->dev, index[idx], id[idx], THIS_MODULE,
622			   sizeof(*chip), &card);
623	if (err < 0) {
624		dev_err(&dev->dev, "cannot create card instance %d\n", idx);
625		return err;
626	}
627
628	chip = card->private_data;
629	mutex_init(&chip->mutex);
630	init_waitqueue_head(&chip->shutdown_wait);
631	chip->index = idx;
632	chip->dev = dev;
633	chip->card = card;
634	chip->setup = device_setup[idx];
635	chip->generic_implicit_fb = implicit_fb[idx];
636	chip->autoclock = autoclock;
637	chip->lowlatency = lowlatency;
638	atomic_set(&chip->active, 1); /* avoid autopm during probing */
639	atomic_set(&chip->usage_count, 0);
640	atomic_set(&chip->shutdown, 0);
641
642	chip->usb_id = usb_id;
643	INIT_LIST_HEAD(&chip->pcm_list);
644	INIT_LIST_HEAD(&chip->ep_list);
645	INIT_LIST_HEAD(&chip->iface_ref_list);
646	INIT_LIST_HEAD(&chip->clock_ref_list);
647	INIT_LIST_HEAD(&chip->midi_list);
648	INIT_LIST_HEAD(&chip->midi_v2_list);
649	INIT_LIST_HEAD(&chip->mixer_list);
650
651	if (quirk_flags[idx])
652		chip->quirk_flags = quirk_flags[idx];
653	else
654		snd_usb_init_quirk_flags(chip);
655
656	card->private_free = snd_usb_audio_free;
657
658	strcpy(card->driver, "USB-Audio");
659	sprintf(component, "USB%04x:%04x",
660		USB_ID_VENDOR(chip->usb_id), USB_ID_PRODUCT(chip->usb_id));
661	snd_component_add(card, component);
662
663	usb_audio_make_shortname(dev, chip, quirk);
664	usb_audio_make_longname(dev, chip, quirk);
665
666	snd_usb_audio_create_proc(chip);
667
668	*rchip = chip;
669	return 0;
670}
671
672/* look for a matching quirk alias id */
673static bool get_alias_id(struct usb_device *dev, unsigned int *id)
674{
675	int i;
676	unsigned int src, dst;
677
678	for (i = 0; i < ARRAY_SIZE(quirk_alias); i++) {
679		if (!quirk_alias[i] ||
680		    sscanf(quirk_alias[i], "%x:%x", &src, &dst) != 2 ||
681		    src != *id)
682			continue;
683		dev_info(&dev->dev,
684			 "device (%04x:%04x): applying quirk alias %04x:%04x\n",
685			 USB_ID_VENDOR(*id), USB_ID_PRODUCT(*id),
686			 USB_ID_VENDOR(dst), USB_ID_PRODUCT(dst));
687		*id = dst;
688		return true;
689	}
690
691	return false;
692}
693
694static int check_delayed_register_option(struct snd_usb_audio *chip)
695{
696	int i;
697	unsigned int id, inum;
698
699	for (i = 0; i < ARRAY_SIZE(delayed_register); i++) {
700		if (delayed_register[i] &&
701		    sscanf(delayed_register[i], "%x:%x", &id, &inum) == 2 &&
702		    id == chip->usb_id)
703			return inum;
704	}
705
706	return -1;
707}
708
709static const struct usb_device_id usb_audio_ids[]; /* defined below */
710
711/* look for the last interface that matches with our ids and remember it */
712static void find_last_interface(struct snd_usb_audio *chip)
713{
714	struct usb_host_config *config = chip->dev->actconfig;
715	struct usb_interface *intf;
716	int i;
717
718	if (!config)
719		return;
720	for (i = 0; i < config->desc.bNumInterfaces; i++) {
721		intf = config->interface[i];
722		if (usb_match_id(intf, usb_audio_ids))
723			chip->last_iface = intf->altsetting[0].desc.bInterfaceNumber;
724	}
725	usb_audio_dbg(chip, "Found last interface = %d\n", chip->last_iface);
726}
727
728/* look for the corresponding quirk */
729static const struct snd_usb_audio_quirk *
730get_alias_quirk(struct usb_device *dev, unsigned int id)
731{
732	const struct usb_device_id *p;
733
734	for (p = usb_audio_ids; p->match_flags; p++) {
735		/* FIXME: this checks only vendor:product pair in the list */
736		if ((p->match_flags & USB_DEVICE_ID_MATCH_DEVICE) ==
737		    USB_DEVICE_ID_MATCH_DEVICE &&
738		    p->idVendor == USB_ID_VENDOR(id) &&
739		    p->idProduct == USB_ID_PRODUCT(id))
740			return (const struct snd_usb_audio_quirk *)p->driver_info;
741	}
742
743	return NULL;
744}
745
746/* register card if we reach to the last interface or to the specified
747 * one given via option
748 */
749static int try_to_register_card(struct snd_usb_audio *chip, int ifnum)
750{
751	if (check_delayed_register_option(chip) == ifnum ||
752	    chip->last_iface == ifnum ||
753	    usb_interface_claimed(usb_ifnum_to_if(chip->dev, chip->last_iface)))
754		return snd_card_register(chip->card);
755	return 0;
756}
757
758/*
759 * probe the active usb device
760 *
761 * note that this can be called multiple times per a device, when it
762 * includes multiple audio control interfaces.
763 *
764 * thus we check the usb device pointer and creates the card instance
765 * only at the first time.  the successive calls of this function will
766 * append the pcm interface to the corresponding card.
767 */
768static int usb_audio_probe(struct usb_interface *intf,
769			   const struct usb_device_id *usb_id)
770{
771	struct usb_device *dev = interface_to_usbdev(intf);
772	const struct snd_usb_audio_quirk *quirk =
773		(const struct snd_usb_audio_quirk *)usb_id->driver_info;
774	struct snd_usb_audio *chip;
775	int i, err;
776	struct usb_host_interface *alts;
777	int ifnum;
778	u32 id;
779
780	alts = &intf->altsetting[0];
781	ifnum = get_iface_desc(alts)->bInterfaceNumber;
782	id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
783		    le16_to_cpu(dev->descriptor.idProduct));
784	if (get_alias_id(dev, &id))
785		quirk = get_alias_quirk(dev, id);
786	if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
787		return -ENXIO;
788	if (quirk && quirk->ifnum == QUIRK_NODEV_INTERFACE)
789		return -ENODEV;
790
791	err = snd_usb_apply_boot_quirk(dev, intf, quirk, id);
792	if (err < 0)
793		return err;
794
795	/*
796	 * found a config.  now register to ALSA
797	 */
798
799	/* check whether it's already registered */
800	chip = NULL;
801	mutex_lock(&register_mutex);
802	for (i = 0; i < SNDRV_CARDS; i++) {
803		if (usb_chip[i] && usb_chip[i]->dev == dev) {
804			if (atomic_read(&usb_chip[i]->shutdown)) {
805				dev_err(&dev->dev, "USB device is in the shutdown state, cannot create a card instance\n");
806				err = -EIO;
807				goto __error;
808			}
809			chip = usb_chip[i];
810			atomic_inc(&chip->active); /* avoid autopm */
811			break;
812		}
813	}
814	if (! chip) {
815		err = snd_usb_apply_boot_quirk_once(dev, intf, quirk, id);
816		if (err < 0)
817			goto __error;
818
819		/* it's a fresh one.
820		 * now look for an empty slot and create a new card instance
821		 */
822		for (i = 0; i < SNDRV_CARDS; i++)
823			if (!usb_chip[i] &&
824			    (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&
825			    (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {
826				if (enable[i]) {
827					err = snd_usb_audio_create(intf, dev, i, quirk,
828								   id, &chip);
829					if (err < 0)
830						goto __error;
831					break;
832				} else if (vid[i] != -1 || pid[i] != -1) {
833					dev_info(&dev->dev,
834						 "device (%04x:%04x) is disabled\n",
835						 USB_ID_VENDOR(id),
836						 USB_ID_PRODUCT(id));
837					err = -ENOENT;
838					goto __error;
839				}
840			}
841		if (!chip) {
842			dev_err(&dev->dev, "no available usb audio device\n");
843			err = -ENODEV;
844			goto __error;
845		}
846		find_last_interface(chip);
847	}
848
849	if (chip->num_interfaces >= MAX_CARD_INTERFACES) {
850		dev_info(&dev->dev, "Too many interfaces assigned to the single USB-audio card\n");
851		err = -EINVAL;
852		goto __error;
853	}
854
855	dev_set_drvdata(&dev->dev, chip);
856
857	if (ignore_ctl_error)
858		chip->quirk_flags |= QUIRK_FLAG_IGNORE_CTL_ERROR;
859
860	if (chip->quirk_flags & QUIRK_FLAG_DISABLE_AUTOSUSPEND)
861		usb_disable_autosuspend(interface_to_usbdev(intf));
862
863	/*
864	 * For devices with more than one control interface, we assume the
865	 * first contains the audio controls. We might need a more specific
866	 * check here in the future.
867	 */
868	if (!chip->ctrl_intf)
869		chip->ctrl_intf = alts;
870
871	err = 1; /* continue */
872	if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
873		/* need some special handlings */
874		err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);
875		if (err < 0)
876			goto __error;
877	}
878
879	if (err > 0) {
880		/* create normal USB audio interfaces */
881		err = snd_usb_create_streams(chip, ifnum);
882		if (err < 0)
883			goto __error;
884		err = snd_usb_create_mixer(chip, ifnum);
885		if (err < 0)
886			goto __error;
887	}
888
889	if (chip->need_delayed_register) {
890		dev_info(&dev->dev,
891			 "Found post-registration device assignment: %08x:%02x\n",
892			 chip->usb_id, ifnum);
893		chip->need_delayed_register = false; /* clear again */
894	}
895
896	err = try_to_register_card(chip, ifnum);
897	if (err < 0)
898		goto __error_no_register;
899
900	if (chip->quirk_flags & QUIRK_FLAG_SHARE_MEDIA_DEVICE) {
901		/* don't want to fail when snd_media_device_create() fails */
902		snd_media_device_create(chip, intf);
903	}
904
905	if (quirk)
906		chip->quirk_type = quirk->type;
907
908	usb_chip[chip->index] = chip;
909	chip->intf[chip->num_interfaces] = intf;
910	chip->num_interfaces++;
911	usb_set_intfdata(intf, chip);
912	atomic_dec(&chip->active);
913	mutex_unlock(&register_mutex);
914	return 0;
915
916 __error:
917	/* in the case of error in secondary interface, still try to register */
918	if (chip)
919		try_to_register_card(chip, ifnum);
920
921 __error_no_register:
922	if (chip) {
923		/* chip->active is inside the chip->card object,
924		 * decrement before memory is possibly returned.
925		 */
926		atomic_dec(&chip->active);
927		if (!chip->num_interfaces)
928			snd_card_free(chip->card);
929	}
930	mutex_unlock(&register_mutex);
931	return err;
932}
933
934/*
935 * we need to take care of counter, since disconnection can be called also
936 * many times as well as usb_audio_probe().
937 */
938static void usb_audio_disconnect(struct usb_interface *intf)
939{
940	struct snd_usb_audio *chip = usb_get_intfdata(intf);
941	struct snd_card *card;
942	struct list_head *p;
943
944	if (chip == USB_AUDIO_IFACE_UNUSED)
945		return;
946
947	card = chip->card;
948
949	mutex_lock(&register_mutex);
950	if (atomic_inc_return(&chip->shutdown) == 1) {
951		struct snd_usb_stream *as;
952		struct snd_usb_endpoint *ep;
953		struct usb_mixer_interface *mixer;
954
955		/* wait until all pending tasks done;
956		 * they are protected by snd_usb_lock_shutdown()
957		 */
958		wait_event(chip->shutdown_wait,
959			   !atomic_read(&chip->usage_count));
960		snd_card_disconnect(card);
961		/* release the pcm resources */
962		list_for_each_entry(as, &chip->pcm_list, list) {
963			snd_usb_stream_disconnect(as);
964		}
965		/* release the endpoint resources */
966		list_for_each_entry(ep, &chip->ep_list, list) {
967			snd_usb_endpoint_release(ep);
968		}
969		/* release the midi resources */
970		list_for_each(p, &chip->midi_list) {
971			snd_usbmidi_disconnect(p);
972		}
973		snd_usb_midi_v2_disconnect_all(chip);
974		/*
975		 * Nice to check quirk && quirk->shares_media_device and
976		 * then call the snd_media_device_delete(). Don't have
977		 * access to the quirk here. snd_media_device_delete()
978		 * accesses mixer_list
979		 */
980		snd_media_device_delete(chip);
981
982		/* release mixer resources */
983		list_for_each_entry(mixer, &chip->mixer_list, list) {
984			snd_usb_mixer_disconnect(mixer);
985		}
986	}
987
988	if (chip->quirk_flags & QUIRK_FLAG_DISABLE_AUTOSUSPEND)
989		usb_enable_autosuspend(interface_to_usbdev(intf));
990
991	chip->num_interfaces--;
992	if (chip->num_interfaces <= 0) {
993		usb_chip[chip->index] = NULL;
994		mutex_unlock(&register_mutex);
995		snd_card_free_when_closed(card);
996	} else {
997		mutex_unlock(&register_mutex);
998	}
999}
1000
1001/* lock the shutdown (disconnect) task and autoresume */
1002int snd_usb_lock_shutdown(struct snd_usb_audio *chip)
1003{
1004	int err;
1005
1006	atomic_inc(&chip->usage_count);
1007	if (atomic_read(&chip->shutdown)) {
1008		err = -EIO;
1009		goto error;
1010	}
1011	err = snd_usb_autoresume(chip);
1012	if (err < 0)
1013		goto error;
1014	return 0;
1015
1016 error:
1017	if (atomic_dec_and_test(&chip->usage_count))
1018		wake_up(&chip->shutdown_wait);
1019	return err;
1020}
1021
1022/* autosuspend and unlock the shutdown */
1023void snd_usb_unlock_shutdown(struct snd_usb_audio *chip)
1024{
1025	snd_usb_autosuspend(chip);
1026	if (atomic_dec_and_test(&chip->usage_count))
1027		wake_up(&chip->shutdown_wait);
1028}
1029
1030int snd_usb_autoresume(struct snd_usb_audio *chip)
1031{
1032	int i, err;
1033
1034	if (atomic_read(&chip->shutdown))
1035		return -EIO;
1036	if (atomic_inc_return(&chip->active) != 1)
1037		return 0;
1038
1039	for (i = 0; i < chip->num_interfaces; i++) {
1040		err = usb_autopm_get_interface(chip->intf[i]);
1041		if (err < 0) {
1042			/* rollback */
1043			while (--i >= 0)
1044				usb_autopm_put_interface(chip->intf[i]);
1045			atomic_dec(&chip->active);
1046			return err;
1047		}
1048	}
1049	return 0;
1050}
1051
1052void snd_usb_autosuspend(struct snd_usb_audio *chip)
1053{
1054	int i;
1055
1056	if (atomic_read(&chip->shutdown))
1057		return;
1058	if (!atomic_dec_and_test(&chip->active))
1059		return;
1060
1061	for (i = 0; i < chip->num_interfaces; i++)
1062		usb_autopm_put_interface(chip->intf[i]);
1063}
1064
1065static int usb_audio_suspend(struct usb_interface *intf, pm_message_t message)
1066{
1067	struct snd_usb_audio *chip = usb_get_intfdata(intf);
1068	struct snd_usb_stream *as;
1069	struct snd_usb_endpoint *ep;
1070	struct usb_mixer_interface *mixer;
1071	struct list_head *p;
1072
1073	if (chip == USB_AUDIO_IFACE_UNUSED)
1074		return 0;
1075
1076	if (!chip->num_suspended_intf++) {
1077		list_for_each_entry(as, &chip->pcm_list, list)
1078			snd_usb_pcm_suspend(as);
1079		list_for_each_entry(ep, &chip->ep_list, list)
1080			snd_usb_endpoint_suspend(ep);
1081		list_for_each(p, &chip->midi_list)
1082			snd_usbmidi_suspend(p);
1083		list_for_each_entry(mixer, &chip->mixer_list, list)
1084			snd_usb_mixer_suspend(mixer);
1085		snd_usb_midi_v2_suspend_all(chip);
1086	}
1087
1088	if (!PMSG_IS_AUTO(message) && !chip->system_suspend) {
1089		snd_power_change_state(chip->card, SNDRV_CTL_POWER_D3hot);
1090		chip->system_suspend = chip->num_suspended_intf;
1091	}
1092
1093	return 0;
1094}
1095
1096static int usb_audio_resume(struct usb_interface *intf)
1097{
1098	struct snd_usb_audio *chip = usb_get_intfdata(intf);
1099	struct snd_usb_stream *as;
1100	struct usb_mixer_interface *mixer;
1101	struct list_head *p;
1102	int err = 0;
1103
1104	if (chip == USB_AUDIO_IFACE_UNUSED)
1105		return 0;
1106
1107	atomic_inc(&chip->active); /* avoid autopm */
1108	if (chip->num_suspended_intf > 1)
1109		goto out;
1110
1111	list_for_each_entry(as, &chip->pcm_list, list) {
1112		err = snd_usb_pcm_resume(as);
1113		if (err < 0)
1114			goto err_out;
1115	}
1116
1117	/*
1118	 * ALSA leaves material resumption to user space
1119	 * we just notify and restart the mixers
1120	 */
1121	list_for_each_entry(mixer, &chip->mixer_list, list) {
1122		err = snd_usb_mixer_resume(mixer);
1123		if (err < 0)
1124			goto err_out;
1125	}
1126
1127	list_for_each(p, &chip->midi_list) {
1128		snd_usbmidi_resume(p);
1129	}
1130
1131	snd_usb_midi_v2_resume_all(chip);
1132
1133 out:
1134	if (chip->num_suspended_intf == chip->system_suspend) {
1135		snd_power_change_state(chip->card, SNDRV_CTL_POWER_D0);
1136		chip->system_suspend = 0;
1137	}
1138	chip->num_suspended_intf--;
1139
1140err_out:
1141	atomic_dec(&chip->active); /* allow autopm after this point */
1142	return err;
1143}
1144
1145static const struct usb_device_id usb_audio_ids [] = {
1146#include "quirks-table.h"
1147    { .match_flags = (USB_DEVICE_ID_MATCH_INT_CLASS | USB_DEVICE_ID_MATCH_INT_SUBCLASS),
1148      .bInterfaceClass = USB_CLASS_AUDIO,
1149      .bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL },
1150    { }						/* Terminating entry */
1151};
1152MODULE_DEVICE_TABLE(usb, usb_audio_ids);
1153
1154/*
1155 * entry point for linux usb interface
1156 */
1157
1158static struct usb_driver usb_audio_driver = {
1159	.name =		"snd-usb-audio",
1160	.probe =	usb_audio_probe,
1161	.disconnect =	usb_audio_disconnect,
1162	.suspend =	usb_audio_suspend,
1163	.resume =	usb_audio_resume,
1164	.reset_resume =	usb_audio_resume,
1165	.id_table =	usb_audio_ids,
1166	.supports_autosuspend = 1,
1167};
1168
1169module_usb_driver(usb_audio_driver);
1170