usbaudio.c 81.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/*
 *   (Tentative) USB Audio Driver for ALSA
 *
 *   Main and PCM part
 *
 *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
 *
 *   Many codes borrowed from audio.c by 
 *	    Alan Cox (alan@lxorguk.ukuu.org.uk)
 *	    Thomas Sailer (sailer@ife.ee.ethz.ch)
 *
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 */


#include <sound/driver.h>
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/usb.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/pcm.h>
Jaroslav Kysela's avatar
Jaroslav Kysela committed
39
#include <sound/pcm_params.h>
40 41 42 43 44 45 46 47 48 49 50 51 52
#define SNDRV_GET_ID
#include <sound/initval.h>

#include "usbaudio.h"


MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("USB Audio");
MODULE_LICENSE("GPL");
MODULE_CLASSES("{sound}");
MODULE_DEVICES("{{Generic,USB Audio}}");


Jaroslav Kysela's avatar
Jaroslav Kysela committed
53 54 55 56 57
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;	/* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;	/* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;	/* Enable this card */
static int vid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 }; /* Vendor ID for this card */
static int pid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 }; /* Product ID for this card */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
58
static int nrpacks = 4;		/* max. number of packets per urb */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

MODULE_PARM(index, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
MODULE_PARM_DESC(index, "Index value for the USB audio adapter.");
MODULE_PARM_SYNTAX(index, SNDRV_INDEX_DESC);
MODULE_PARM(id, "1-" __MODULE_STRING(SNDRV_CARDS) "s");
MODULE_PARM_DESC(id, "ID string for the USB audio adapter.");
MODULE_PARM_SYNTAX(id, SNDRV_ID_DESC);
MODULE_PARM(enable, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
MODULE_PARM_DESC(enable, "Enable USB audio adapter.");
MODULE_PARM_SYNTAX(enable, SNDRV_ENABLE_DESC);
MODULE_PARM(vid, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
MODULE_PARM_DESC(vid, "Vendor ID for the USB audio device.");
MODULE_PARM_SYNTAX(vid, SNDRV_ENABLED ",allows:{{-1,0xffff}},base:16");
MODULE_PARM(pid, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
MODULE_PARM_DESC(pid, "Product ID for the USB audio device.");
MODULE_PARM_SYNTAX(pid, SNDRV_ENABLED ",allows:{{-1,0xffff}},base:16");
Jaroslav Kysela's avatar
Jaroslav Kysela committed
75 76 77
MODULE_PARM(nrpacks, "i");
MODULE_PARM_DESC(nrpacks, "Max. number of packets per URB.");
MODULE_PARM_SYNTAX(nrpacks, SNDRV_ENABLED ",allows:{{2,10}}");
78 79 80 81 82 83 84 85 86 87 88


/*
 * for using ASYNC unlink mode, define the following.
 * this will make the driver quicker response for request to STOP-trigger,
 * but it may cause oops by some unknown reason (bug of usb driver?),
 * so turning off might be sure.
 */
/* #define SND_USE_ASYNC_UNLINK */

#ifdef SND_USB_ASYNC_UNLINK
89
#define UNLINK_FLAGS	URB_ASYNC_UNLINK
90 91 92
#else
#define UNLINK_FLAGS	0
#endif
93 94


Jaroslav Kysela's avatar
Jaroslav Kysela committed
95 96 97 98 99 100
/*
 * debug the h/w constraints
 */
/* #define HW_CONST_DEBUG */


101 102 103 104
/*
 *
 */

Jaroslav Kysela's avatar
Jaroslav Kysela committed
105
#define MAX_PACKS	10	
106 107 108 109 110 111 112 113 114 115 116
#define MAX_URBS	5	/* max. 20ms long packets */
#define SYNC_URBS	2	/* always two urbs for sync */
#define MIN_PACKS_URB	1	/* minimum 1 packet per urb */

typedef struct snd_usb_substream snd_usb_substream_t;
typedef struct snd_usb_stream snd_usb_stream_t;
typedef struct snd_urb_ctx snd_urb_ctx_t;

struct audioformat {
	struct list_head list;
	snd_pcm_format_t format;	/* format type */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
117
	unsigned int channels;		/* # channels */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
118 119
	unsigned int nonaudio: 1;	/* non-audio (type II) */
	unsigned int frame_size;	/* samples per frame for non-audio */
120
	int iface;			/* interface number */
121 122 123 124 125
	unsigned char altsetting;	/* corresponding alternate setting */
	unsigned char altset_idx;	/* array index of altenate setting */
	unsigned char attributes;	/* corresponding attributes of cs endpoint */
	unsigned char endpoint;		/* endpoint */
	unsigned char ep_attr;		/* endpoint attributes */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
126
	unsigned int maxpacksize;	/* max. packet size */
127
	unsigned int rates;		/* rate bitmasks */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
128 129 130
	unsigned int rate_min, rate_max;	/* min/max rates */
	unsigned int nr_rates;		/* number of rate table entries */
	unsigned int *rate_table;	/* rate table */
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
};

struct snd_urb_ctx {
	struct urb *urb;
	snd_usb_substream_t *subs;
	int index;	/* index for urb array */
	int packets;	/* number of packets per urb */
	int transfer;	/* transferred size */
	char *buf;	/* buffer for capture */
};

struct snd_urb_ops {
	int (*prepare)(snd_usb_substream_t *subs, snd_pcm_runtime_t *runtime, struct urb *u);
	int (*retire)(snd_usb_substream_t *subs, snd_pcm_runtime_t *runtime, struct urb *u);
	int (*prepare_sync)(snd_usb_substream_t *subs, snd_pcm_runtime_t *runtime, struct urb *u);
	int (*retire_sync)(snd_usb_substream_t *subs, snd_pcm_runtime_t *runtime, struct urb *u);
};

struct snd_usb_substream {
	snd_usb_stream_t *stream;
	struct usb_device *dev;
	snd_pcm_substream_t *pcm_substream;
153 154 155
	int direction;	/* playback or capture */
	int interface;	/* current interface */
	int endpoint;	/* assigned endpoint */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
156 157 158
	struct audioformat *cur_audiofmt;	/* current audioformat pointer (for hw_params callback) */
	unsigned int cur_rate;		/* current rate (for hw_params callback) */
	unsigned int period_bytes;	/* current period bytes (for hw_params callback) */
159 160 161 162 163 164 165 166 167 168
	unsigned int format;     /* USB data format */
	unsigned int datapipe;   /* the data i/o pipe */
	unsigned int syncpipe;   /* 1 - async out or adaptive in */
	unsigned int syncinterval;  /* P for adaptive mode, 0 otherwise */
	unsigned int freqn;      /* nominal sampling rate in USB format, i.e. fs/1000 in Q10.14 */
	unsigned int freqm;      /* momentary sampling rate in USB format, i.e. fs/1000 in Q10.14 */
	unsigned int freqmax;    /* maximum sampling rate, used for buffer management */
	unsigned int phase;      /* phase accumulator */
	unsigned int maxpacksize;	/* max packet size in bytes */
	unsigned int maxframesize;	/* max packet size in frames */
169 170
	unsigned int curpacksize;	/* current packet size in bytes (for capture) */
	unsigned int curframesize;	/* current packet size in frames (for capture) */
171
	unsigned int fill_max: 1;	/* fill max packet size always */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
172
	unsigned int nonaudio: 1;	/* Type II format (MPEG, AC3) */
173 174 175

	unsigned int running: 1;	/* running status */

Jaroslav Kysela's avatar
Jaroslav Kysela committed
176 177 178 179
	unsigned int hwptr;			/* free frame position in the buffer (only for playback) */
	unsigned int hwptr_done;			/* processed frame position in the buffer */
	unsigned int transfer_sched;		/* scheduled frames since last period (for playback) */
	unsigned int transfer_done;		/* processed frames since last period update */
180 181 182
	unsigned long active_mask;	/* bitmask of active urbs */
	unsigned long unlink_mask;	/* bitmask of unlinked urbs */

Jaroslav Kysela's avatar
Jaroslav Kysela committed
183
	unsigned int nurbs;			/* # urbs */
184 185
	snd_urb_ctx_t dataurb[MAX_URBS];	/* data urb table */
	snd_urb_ctx_t syncurb[SYNC_URBS];	/* sync urb table */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
186
	char syncbuf[SYNC_URBS * MAX_PACKS * 3]; /* sync buffer; it's so small - let's get static */
187 188 189
	char *tmpbuf;			/* temporary buffer for playback */

	u64 formats;			/* format bitmasks (all or'ed) */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
190
	unsigned int num_formats;		/* number of supported audio formats (list) */
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	struct list_head fmt_list;	/* format list */
	spinlock_t lock;

	struct snd_urb_ops ops;		/* callbacks (must be filled at init) */
};


struct snd_usb_stream {
	snd_usb_audio_t *chip;
	snd_pcm_t *pcm;
	int pcm_index;
	snd_usb_substream_t substream[2];
	struct list_head list;
};

#define chip_t snd_usb_stream_t


/*
 * we keep the snd_usb_audio_t instances by ourselves for merging
 * the all interfaces on the same card as one sound device.
 */

static DECLARE_MUTEX(register_mutex);
static snd_usb_audio_t *usb_chip[SNDRV_CARDS];


/*
 * convert a sampling rate into USB format (fs/1000 in Q10.14)
 * this will overflow at approx 2MSPS
 */
inline static unsigned get_usb_rate(unsigned int rate)
{
	return ((rate << 11) + 62) / 125;
}


/*
 * prepare urb for capture sync pipe
 *
 * fill the length and offset of each urb descriptor.
 * the fixed 10.14 frequency is passed through the pipe.
 */
static int prepare_capture_sync_urb(snd_usb_substream_t *subs,
				    snd_pcm_runtime_t *runtime,
				    struct urb *urb)
{
	unsigned char *cp = urb->transfer_buffer;
	snd_urb_ctx_t *ctx = (snd_urb_ctx_t *)urb->context;
	int i, offs;

	urb->number_of_packets = ctx->packets;
	urb->dev = ctx->subs->dev; /* we need to set this at each time */
	for (i = offs = 0; i < urb->number_of_packets; i++, offs += 3, cp += 3) {
		urb->iso_frame_desc[i].length = 3;
		urb->iso_frame_desc[i].offset = offs;
		cp[0] = subs->freqn;
		cp[1] = subs->freqn >> 8;
		cp[2] = subs->freqn >> 16;
	}
	urb->interval = 1;
	return 0;
}

/*
 * process after capture sync complete
 * - nothing to do
 */
static int retire_capture_sync_urb(snd_usb_substream_t *subs,
				   snd_pcm_runtime_t *runtime,
				   struct urb *urb)
{
	return 0;
}

/*
 * prepare urb for capture data pipe
 *
 * fill the offset and length of each descriptor.
 *
 * we use a temporary buffer to write the captured data.
 * since the length of written data is determined by host, we cannot
 * write onto the pcm buffer directly...  the data is thus copied
 * later at complete callback to the global buffer.
 */
static int prepare_capture_urb(snd_usb_substream_t *subs,
			       snd_pcm_runtime_t *runtime,
			       struct urb *urb)
{
	int i, offs;
	unsigned long flags;
	snd_urb_ctx_t *ctx = (snd_urb_ctx_t *)urb->context;

	offs = 0;
	urb->dev = ctx->subs->dev; /* we need to set this at each time */
	urb->number_of_packets = 0;
	spin_lock_irqsave(&subs->lock, flags);
	for (i = 0; i < ctx->packets; i++) {
		urb->iso_frame_desc[i].offset = offs;
		urb->iso_frame_desc[i].length = subs->curpacksize;
		offs += subs->curpacksize;
		urb->number_of_packets++;
		subs->transfer_sched += subs->curframesize;
		if (subs->transfer_sched >= runtime->period_size) {
			subs->transfer_sched -= runtime->period_size;
			break;
		}
	}
	spin_unlock_irqrestore(&subs->lock, flags);
	urb->transfer_buffer = ctx->buf;
	urb->transfer_buffer_length = offs;
	urb->interval = 1;
Jaroslav Kysela's avatar
ALSA  
Jaroslav Kysela committed
303 304 305 306 307 308 309 310 311 312
#if 0 // for check
	if (! urb->bandwidth) {
		int bustime;
		bustime = usb_check_bandwidth(urb->dev, urb);
		if (bustime < 0) 
			return bustime;
		printk("urb %d: bandwidth = %d (packets = %d)\n", ctx->index, bustime, urb->number_of_packets);
		usb_claim_bandwidth(urb->dev, urb, bustime, 1);
	}
#endif // for check
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	return 0;
}

/*
 * process after capture complete
 *
 * copy the data from each desctiptor to the pcm buffer, and
 * update the current position.
 */
static int retire_capture_urb(snd_usb_substream_t *subs,
			      snd_pcm_runtime_t *runtime,
			      struct urb *urb)
{
	unsigned long flags;
	unsigned char *cp;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
328 329
	int i;
	unsigned int stride, len, oldptr;
330 331 332 333 334

	stride = runtime->frame_bits >> 3;

	for (i = 0; i < urb->number_of_packets; i++) {
		cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset;
Jaroslav Kysela's avatar
ALSA  
Jaroslav Kysela committed
335 336 337 338
		if (urb->iso_frame_desc[i].status) {
			snd_printd(KERN_ERR "frame %d active: %d\n", i, urb->iso_frame_desc[i].status);
			// continue;
		}
339 340 341 342 343 344 345 346 347 348 349 350 351
		len = urb->iso_frame_desc[i].actual_length / stride;
		if (! len)
			continue;
		/* update the current pointer */
		spin_lock_irqsave(&subs->lock, flags);
		oldptr = subs->hwptr_done;
		subs->hwptr_done += len;
		if (subs->hwptr_done >= runtime->buffer_size)
			subs->hwptr_done -= runtime->buffer_size;
		subs->transfer_done += len;
		spin_unlock_irqrestore(&subs->lock, flags);
		/* copy a data chunk */
		if (oldptr + len > runtime->buffer_size) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
352 353
			unsigned int cnt = runtime->buffer_size - oldptr;
			unsigned int blen = cnt * stride;
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
			memcpy(runtime->dma_area + oldptr * stride, cp, blen);
			memcpy(runtime->dma_area, cp + blen, len * stride - blen);
		} else {
			memcpy(runtime->dma_area + oldptr * stride, cp, len * stride);
		}
		/* update the pointer, call callback if necessary */
		spin_lock_irqsave(&subs->lock, flags);
		if (subs->transfer_done >= runtime->period_size) {
			subs->transfer_done -= runtime->period_size;
			spin_unlock_irqrestore(&subs->lock, flags);
			snd_pcm_period_elapsed(subs->pcm_substream);
		} else
			spin_unlock_irqrestore(&subs->lock, flags);
	}
	return 0;
}


/*
 * prepare urb for playback sync pipe
 *
 * set up the offset and length to receive the current frequency.
 */

static int prepare_playback_sync_urb(snd_usb_substream_t *subs,
				     snd_pcm_runtime_t *runtime,
				     struct urb *urb)
{
	int i, offs;
	snd_urb_ctx_t *ctx = (snd_urb_ctx_t *)urb->context;

	urb->number_of_packets = ctx->packets;
	urb->dev = ctx->subs->dev; /* we need to set this at each time */
	for (i = offs = 0; i < urb->number_of_packets; i++, offs += 3) {
		urb->iso_frame_desc[i].length = 3;
		urb->iso_frame_desc[i].offset = offs;
	}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
391
	urb->interval = 1;
392 393 394 395 396 397 398 399 400 401 402 403 404
	return 0;
}

/*
 * process after playback sync complete
 *
 * retrieve the current 10.14 frequency from pipe, and set it.
 * the value is referred in prepare_playback_urb().
 */
static int retire_playback_sync_urb(snd_usb_substream_t *subs,
				    snd_pcm_runtime_t *runtime,
				    struct urb *urb)
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
405 406
	int i;
	unsigned int f, found;
407 408 409 410 411 412 413 414 415
	unsigned char *cp = urb->transfer_buffer;
	unsigned long flags;

	found = 0;
	for (i = 0; i < urb->number_of_packets; i++, cp += 3) {
		if (urb->iso_frame_desc[i].status ||
		    urb->iso_frame_desc[i].actual_length < 3)
			continue;
		f = combine_triple(cp);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
416
#if 0
417
		if (f < subs->freqn - (subs->freqn>>3) || f > subs->freqmax) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
418 419 420
			snd_printd(KERN_WARNING "requested frequency %d (%u,%03uHz) out of range (current nominal %d (%u,%03uHz))\n",
				   f, f >> 14, (f & ((1 << 14) - 1) * 1000) / ((1 << 14) - 1),
				   subs->freqn, subs->freqn >> 14, (subs->freqn & ((1 << 14) - 1) * 1000) / ((1 << 14) - 1));
421 422
			continue;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
423
#endif
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
		found = f;
	}
	if (found) {
		spin_lock_irqsave(&subs->lock, flags);
		subs->freqm = found;
		spin_unlock_irqrestore(&subs->lock, flags);
	}

	return 0;
}

/*
 * prepare urb for playback data pipe
 *
 * we copy the data directly from the pcm buffer.
 * the current position to be copied is held in hwptr field.
 * since a urb can handle only a single linear buffer, if the total
 * transferred area overflows the buffer boundary, we cannot send
 * it directly from the buffer.  thus the data is once copied to
 * a temporary buffer and urb points to that.
 */
static int prepare_playback_urb(snd_usb_substream_t *subs,
				snd_pcm_runtime_t *runtime,
				struct urb *urb)
{
	int i, stride, offs;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
450
	unsigned int counts;
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
	unsigned long flags;
	snd_urb_ctx_t *ctx = (snd_urb_ctx_t *)urb->context;

	stride = runtime->frame_bits >> 3;

	offs = 0;
	urb->dev = ctx->subs->dev; /* we need to set this at each time */
	urb->number_of_packets = 0;
	spin_lock_irqsave(&subs->lock, flags);
	for (i = 0; i < ctx->packets; i++) {
		/* calculate the size of a packet */
		if (subs->fill_max)
			counts = subs->maxframesize; /* fixed */
		else {
			subs->phase = (subs->phase & 0x3fff) + subs->freqm;
			counts = subs->phase >> 14;
			if (counts > subs->maxframesize)
				counts = subs->maxframesize;
		}
		/* set up descriptor */
		urb->iso_frame_desc[i].offset = offs * stride;
		urb->iso_frame_desc[i].length = counts * stride;
		offs += counts;
		urb->number_of_packets++;
		subs->transfer_sched += counts;
		if (subs->transfer_sched >= runtime->period_size) {
			subs->transfer_sched -= runtime->period_size;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
			if (subs->nonaudio) {
				if (subs->transfer_sched > 0) {
					/* FIXME: fill-max mode is not supported yet */
					offs -= subs->transfer_sched;
					counts -= subs->transfer_sched;
					urb->iso_frame_desc[i].length = counts * stride;
					subs->transfer_sched = 0;
				}
				i++;
				if (i < ctx->packets) {
					/* add a transfer delimiter */
					urb->iso_frame_desc[i].offset = offs * stride;
					urb->iso_frame_desc[i].length = 0;
					urb->number_of_packets++;
				}
			}
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
			break;
 		}
	}
	if (subs->hwptr + offs > runtime->buffer_size) {
		/* err, the transferred area goes over buffer boundary.
		 * copy the data to the temp buffer.
		 */
		int len;
		len = runtime->buffer_size - subs->hwptr;
		urb->transfer_buffer = subs->tmpbuf;
		memcpy(subs->tmpbuf, runtime->dma_area + subs->hwptr * stride, len * stride);
		memcpy(subs->tmpbuf + len * stride, runtime->dma_area, (offs - len) * stride);
		subs->hwptr += offs;
		subs->hwptr -= runtime->buffer_size;
	} else {
		/* set the buffer pointer */
		urb->transfer_buffer = runtime->dma_area + subs->hwptr * stride;
		subs->hwptr += offs;
	}
	spin_unlock_irqrestore(&subs->lock, flags);
	urb->transfer_buffer_length = offs * stride;
	ctx->transfer = offs;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
516
	urb->interval = 1;
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

	return 0;
}

/*
 * process after playback data complete
 *
 * update the current position and call callback if a period is processed.
 */
static int retire_playback_urb(snd_usb_substream_t *subs,
			       snd_pcm_runtime_t *runtime,
			       struct urb *urb)
{
	unsigned long flags;
	snd_urb_ctx_t *ctx = (snd_urb_ctx_t *)urb->context;

	spin_lock_irqsave(&subs->lock, flags);
	subs->transfer_done += ctx->transfer;
	subs->hwptr_done += ctx->transfer;
	ctx->transfer = 0;
	if (subs->hwptr_done >= runtime->buffer_size)
		subs->hwptr_done -= runtime->buffer_size;
	if (subs->transfer_done >= runtime->period_size) {
		subs->transfer_done -= runtime->period_size;
		spin_unlock_irqrestore(&subs->lock, flags);
		snd_pcm_period_elapsed(subs->pcm_substream);
	} else
		spin_unlock_irqrestore(&subs->lock, flags);
	return 0;
}


549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
/*
 */
static struct snd_urb_ops audio_urb_ops[2] = {
	{
		.prepare =	prepare_playback_urb,
		.retire =	retire_playback_urb,
		.prepare_sync =	prepare_playback_sync_urb,
		.retire_sync =	retire_playback_sync_urb,
	},
	{
		.prepare =	prepare_capture_urb,
		.retire =	retire_capture_urb,
		.prepare_sync =	prepare_capture_sync_urb,
		.retire_sync =	retire_capture_sync_urb,
	},
};

566 567 568
/*
 * complete callback from data urb
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
569
static void snd_complete_urb(struct urb *urb, struct pt_regs *regs)
570 571 572 573 574 575 576 577 578 579 580
{
	snd_urb_ctx_t *ctx = (snd_urb_ctx_t *)urb->context;
	snd_usb_substream_t *subs = ctx->subs;
	snd_pcm_substream_t *substream = ctx->subs->pcm_substream;
	int err;

	clear_bit(ctx->index, &subs->active_mask);
	if (subs->running && subs->ops.retire(subs, substream->runtime, urb))
		return;
	if (! subs->running) /* can be stopped during retire callback */
		return;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
581
	if ((err = subs->ops.prepare(subs, substream->runtime, urb)) < 0 ||
582 583 584 585 586 587 588 589 590 591 592 593
	    (err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
		snd_printd(KERN_ERR "cannot submit urb (err = %d)\n", err);
		snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
		return;
	}
	set_bit(ctx->index, &subs->active_mask);
}


/*
 * complete callback from sync urb
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
594
static void snd_complete_sync_urb(struct urb *urb, struct pt_regs *regs)
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
{
	snd_urb_ctx_t *ctx = (snd_urb_ctx_t *)urb->context;
	snd_usb_substream_t *subs = ctx->subs;
	snd_pcm_substream_t *substream = ctx->subs->pcm_substream;
	int err;

	clear_bit(ctx->index + 16, &subs->active_mask);
	if (subs->running && subs->ops.retire_sync(subs, substream->runtime, urb))
		return;
	if (! subs->running) /* can be stopped during retire callback */
		return;
	if ((err = subs->ops.prepare_sync(subs, substream->runtime, urb))  < 0 ||
	    (err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
		snd_printd(KERN_ERR "cannot submit sync urb (err = %d)\n", err);
		snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
		return;
	}
	set_bit(ctx->index + 16, &subs->active_mask);
}


/*
 * unlink active urbs.
 * return the number of active urbs.
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
620
static int deactivate_urbs(snd_usb_substream_t *subs, int force)
621
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
622 623
	unsigned int i;
	int alive;
624 625 626

	subs->running = 0;

Jaroslav Kysela's avatar
Jaroslav Kysela committed
627
	if (!force && subs->stream->chip->shutdown) /* to be sure... */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
628 629
		return 0;

630 631 632 633
#ifndef SND_USB_ASYNC_UNLINK
	if (in_interrupt())
		return 0;
#endif
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
	alive = 0;
	for (i = 0; i < subs->nurbs; i++) {
		if (test_bit(i, &subs->active_mask)) {
			alive++;
			if (! test_and_set_bit(i, &subs->unlink_mask))
				usb_unlink_urb(subs->dataurb[i].urb);
		}
	}
	if (subs->syncpipe) {
		for (i = 0; i < SYNC_URBS; i++) {
			if (test_bit(i+16, &subs->active_mask)) {
				alive++;
 				if (! test_and_set_bit(i+16, &subs->unlink_mask))
					usb_unlink_urb(subs->syncurb[i].urb);
			}
		}
	}
651
#ifdef SND_USB_ASYNC_UNLINK
652
	return alive;
653 654 655
#else
	return 0;
#endif
656 657 658 659 660 661 662 663
}


/*
 * set up and start data/sync urbs
 */
static int start_urbs(snd_usb_substream_t *subs, snd_pcm_runtime_t *runtime)
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
664 665
	unsigned int i;
	int err;
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

	for (i = 0; i < subs->nurbs; i++) {
		snd_assert(subs->dataurb[i].urb, return -EINVAL);
		if (subs->ops.prepare(subs, runtime, subs->dataurb[i].urb) < 0) {
			snd_printk(KERN_ERR "cannot prepare datapipe for urb %d\n", i);
			goto __error;
		}
	}
	if (subs->syncpipe) {
		for (i = 0; i < SYNC_URBS; i++) {
			snd_assert(subs->syncurb[i].urb, return -EINVAL);
			if (subs->ops.prepare_sync(subs, runtime, subs->syncurb[i].urb) < 0) {
				snd_printk(KERN_ERR "cannot prepare syncpipe for urb %d\n", i);
				goto __error;
			}
		}
	}

	subs->running = 1;
	for (i = 0; i < subs->nurbs; i++) {
		if ((err = usb_submit_urb(subs->dataurb[i].urb, GFP_KERNEL)) < 0) {
			snd_printk(KERN_ERR "cannot submit datapipe for urb %d, err = %d\n", i, err);
			goto __error;
		}
		set_bit(i, &subs->active_mask);
	}
	if (subs->syncpipe) {
		for (i = 0; i < SYNC_URBS; i++) {
			if ((err = usb_submit_urb(subs->syncurb[i].urb, GFP_KERNEL)) < 0) {
				snd_printk(KERN_ERR "cannot submit syncpipe for urb %d, err = %d\n", i, err);
				goto __error;
			}
			set_bit(i + 16, &subs->active_mask);
		}
	}
	return 0;

 __error:
	// snd_pcm_stop(subs->pcm_substream, SNDRV_PCM_STATE_XRUN);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
705
	deactivate_urbs(subs, 0);
706 707 708 709 710 711 712 713 714 715
	return -EPIPE;
}


/* 
 *  wait until all urbs are processed.
 */
static int wait_clear_urbs(snd_usb_substream_t *subs)
{
	int timeout = HZ;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
716 717
	unsigned int i;
	int alive;
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764

	do {
		alive = 0;
		for (i = 0; i < subs->nurbs; i++) {
			if (test_bit(i, &subs->active_mask))
				alive++;
		}
		if (subs->syncpipe) {
			for (i = 0; i < SYNC_URBS; i++) {
				if (test_bit(i + 16, &subs->active_mask))
					alive++;
			}
		}
		if (! alive)
			break;
		set_current_state(TASK_UNINTERRUPTIBLE);
		schedule_timeout(1);
	} while (--timeout > 0);
	if (alive)
		snd_printk(KERN_ERR "timeout: still %d active urbs..\n", alive);
	return 0;
}


/*
 * return the current pcm pointer.  just return the hwptr_done value.
 */
static snd_pcm_uframes_t snd_usb_pcm_pointer(snd_pcm_substream_t *substream)
{
	snd_usb_substream_t *subs = (snd_usb_substream_t *)substream->runtime->private_data;
	return subs->hwptr_done;
}


/*
 * start/stop substream
 */
static int snd_usb_pcm_trigger(snd_pcm_substream_t *substream, int cmd)
{
	snd_usb_substream_t *subs = (snd_usb_substream_t *)substream->runtime->private_data;
	int err;

	switch (cmd) {
	case SNDRV_PCM_TRIGGER_START:
		err = start_urbs(subs, substream->runtime);
		break;
	case SNDRV_PCM_TRIGGER_STOP:
Jaroslav Kysela's avatar
Jaroslav Kysela committed
765
		err = deactivate_urbs(subs, 0);
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
		break;
	default:
		err = -EINVAL;
		break;
	}
	return err < 0 ? err : 0;
}


/*
 * release a urb data
 */
static void release_urb_ctx(snd_urb_ctx_t *u)
{
	if (u->urb) {
		usb_free_urb(u->urb);
		u->urb = 0;
	}
	if (u->buf) {
		kfree(u->buf);
		u->buf = 0;
	}
}

/*
 * release a substream
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
793
static void release_substream_urbs(snd_usb_substream_t *subs, int force)
794 795 796 797
{
	int i;

	/* stop urbs (to be sure) */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
798
	if (deactivate_urbs(subs, force) > 0)
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
		wait_clear_urbs(subs);

	for (i = 0; i < MAX_URBS; i++)
		release_urb_ctx(&subs->dataurb[i]);
	for (i = 0; i < SYNC_URBS; i++)
		release_urb_ctx(&subs->syncurb[i]);
	if (subs->tmpbuf) {
		kfree(subs->tmpbuf);
		subs->tmpbuf = 0;
	}
	subs->nurbs = 0;
}

/*
 * initialize a substream for plaback/capture
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
815 816
static int init_substream_urbs(snd_usb_substream_t *subs, unsigned int period_bytes,
			       unsigned int rate, unsigned int frame_bits)
817
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
818
	unsigned int maxsize, n, i;
819
	int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
820
	unsigned int npacks[MAX_URBS], total_packs;
821 822

	/* calculate the frequency in 10.14 format */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
823
	subs->freqn = subs->freqm = get_usb_rate(rate);
824 825 826 827 828 829 830 831 832 833 834 835
	subs->freqmax = subs->freqn + (subs->freqn >> 2); /* max. allowed frequency */
	subs->phase = 0;

	/* reset the pointer */
	subs->hwptr = 0;
	subs->hwptr_done = 0;
	subs->transfer_sched = 0;
	subs->transfer_done = 0;
	subs->active_mask = 0;
	subs->unlink_mask = 0;

	/* calculate the max. size of packet */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
836
	maxsize = ((subs->freqmax + 0x3fff) * (frame_bits >> 3)) >> 14;
837 838 839 840 841 842 843 844 845 846 847 848 849
	if (subs->maxpacksize && maxsize > subs->maxpacksize) {
		//snd_printd(KERN_DEBUG "maxsize %d is greater than defined size %d\n",
		//	   maxsize, subs->maxpacksize);
		maxsize = subs->maxpacksize;
	}

	if (subs->fill_max)
		subs->curpacksize = subs->maxpacksize;
	else
		subs->curpacksize = maxsize;

	/* allocate a temporary buffer for playback */
	if (is_playback) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
850
		subs->tmpbuf = kmalloc(maxsize * nrpacks, GFP_KERNEL);
851 852 853 854 855 856 857
		if (! subs->tmpbuf) {
			snd_printk(KERN_ERR "cannot malloc tmpbuf\n");
			return -ENOMEM;
		}
	}

	/* decide how many packets to be used */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
858
	total_packs = (period_bytes + maxsize - 1) / maxsize;
859 860
	if (total_packs < 2 * MIN_PACKS_URB)
		total_packs = 2 * MIN_PACKS_URB;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
861
	subs->nurbs = (total_packs + nrpacks - 1) / nrpacks;
862 863 864
	if (subs->nurbs > MAX_URBS) {
		/* too much... */
		subs->nurbs = MAX_URBS;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
865
		total_packs = MAX_URBS * nrpacks;
866 867 868
	}
	n = total_packs;
	for (i = 0; i < subs->nurbs; i++) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
869 870
		npacks[i] = n > nrpacks ? nrpacks : n;
		n -= nrpacks;
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	}
	if (subs->nurbs <= 1) {
		/* too little - we need at least two packets
		 * to ensure contiguous playback/capture
		 */
		subs->nurbs = 2;
		npacks[0] = (total_packs + 1) / 2;
		npacks[1] = total_packs - npacks[0];
	} else if (npacks[subs->nurbs-1] < MIN_PACKS_URB) {
		/* the last packet is too small.. */
		if (subs->nurbs > 2) {
			/* merge to the first one */
			npacks[0] += npacks[subs->nurbs - 1];
			subs->nurbs--;
		} else {
			/* divide to two */
			subs->nurbs = 2;
			npacks[0] = (total_packs + 1) / 2;
			npacks[1] = total_packs - npacks[0];
		}
	}

	/* allocate and initialize data urbs */
	for (i = 0; i < subs->nurbs; i++) {
		snd_urb_ctx_t *u = &subs->dataurb[i];
		u->index = i;
		u->subs = subs;
		u->transfer = 0;
		u->packets = npacks[i];
Jaroslav Kysela's avatar
Jaroslav Kysela committed
900 901
		if (subs->nonaudio)
			u->packets++; /* for transfer delimiter */
902 903 904 905
		if (! is_playback) {
			/* allocate a capture buffer per urb */
			u->buf = kmalloc(maxsize * u->packets, GFP_KERNEL);
			if (! u->buf) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
906
				release_substream_urbs(subs, 0);
907 908 909 910 911
				return -ENOMEM;
			}
		}
		u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
		if (! u->urb) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
912
			release_substream_urbs(subs, 0);
913 914 915 916
			return -ENOMEM;
		}
		u->urb->dev = subs->dev;
		u->urb->pipe = subs->datapipe;
917
		u->urb->transfer_flags = URB_ISO_ASAP | UNLINK_FLAGS;
918 919
		u->urb->number_of_packets = u->packets;
		u->urb->context = u;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
920
		u->urb->complete = snd_usb_complete_callback(snd_complete_urb);
921 922 923 924 925 926 927 928
	}

	if (subs->syncpipe) {
		/* allocate and initialize sync urbs */
		for (i = 0; i < SYNC_URBS; i++) {
			snd_urb_ctx_t *u = &subs->syncurb[i];
			u->index = i;
			u->subs = subs;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
929
			u->packets = nrpacks;
930 931
			u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
			if (! u->urb) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
932
				release_substream_urbs(subs, 0);
933 934
				return -ENOMEM;
			}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
935 936
			u->urb->transfer_buffer = subs->syncbuf + i * nrpacks * 3;
			u->urb->transfer_buffer_length = nrpacks * 3;
937 938
			u->urb->dev = subs->dev;
			u->urb->pipe = subs->syncpipe;
939
			u->urb->transfer_flags = URB_ISO_ASAP | UNLINK_FLAGS;
940 941
			u->urb->number_of_packets = u->packets;
			u->urb->context = u;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
942
			u->urb->complete = snd_usb_complete_callback(snd_complete_sync_urb);
943 944 945 946 947 948 949 950 951
		}
	}
	return 0;
}


/*
 * find a matching audio format
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
952 953
static struct audioformat *find_format(snd_usb_substream_t *subs, unsigned int format,
				       unsigned int rate, unsigned int channels)
954 955
{
	struct list_head *p;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
956
	struct audioformat *found = NULL;
957 958 959 960

	list_for_each(p, &subs->fmt_list) {
		struct audioformat *fp;
		fp = list_entry(p, struct audioformat, list);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
961
		if (fp->format != format || fp->channels != channels)
962
			continue;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
963
		if (rate < fp->rate_min || rate > fp->rate_max)
964
			continue;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
965
		if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
966
			unsigned int i;
967
			for (i = 0; i < fp->nr_rates; i++)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
968
				if (fp->rate_table[i] == rate)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
969
					break;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
970 971
			if (i >= fp->nr_rates)
				continue;
972
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
973 974 975
		/* find the format with the largest max. packet size */
		if (! found || fp->maxpacksize > found->maxpacksize)
			found = fp;
976
	}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
977
	return found;
978 979 980
}


Jaroslav Kysela's avatar
Jaroslav Kysela committed
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
/*
 * initialize the picth control and sample rate
 */
static int init_usb_pitch(struct usb_device *dev, int iface,
			  struct usb_host_interface *alts,
			  struct audioformat *fmt)
{
	unsigned int ep;
	unsigned char data[1];
	int err;

	ep = get_endpoint(alts, 0)->bEndpointAddress;
	/* if endpoint has pitch control, enable it */
	if (fmt->attributes & EP_CS_ATTR_PITCH_CONTROL) {
		data[0] = 1;
		if ((err = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR,
					   USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT, 
					   PITCH_CONTROL << 8, ep, data, 1, HZ)) < 0) {
			snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
				   dev->devnum, iface, ep);
			return err;
		}
	}
	return 0;
}

static int init_usb_sample_rate(struct usb_device *dev, int iface,
				struct usb_host_interface *alts,
				struct audioformat *fmt, int rate)
{
	unsigned int ep;
	unsigned char data[3];
	int err;

	ep = get_endpoint(alts, 0)->bEndpointAddress;
	/* if endpoint has sampling rate control, set it */
	if (fmt->attributes & EP_CS_ATTR_SAMPLE_RATE) {
		int crate;
		data[0] = rate;
		data[1] = rate >> 8;
		data[2] = rate >> 16;
		if ((err = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR,
					   USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT, 
					   SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
			snd_printk(KERN_ERR "%d:%d:%d: cannot set freq %d to ep 0x%x\n",
				   dev->devnum, iface, fmt->altsetting, rate, ep);
			return err;
		}
		if ((err = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), GET_CUR,
					   USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_IN,
					   SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
			snd_printk(KERN_ERR "%d:%d:%d: cannot get freq at ep 0x%x\n",
				   dev->devnum, iface, fmt->altsetting, ep);
			return err;
		}
		crate = data[0] | (data[1] << 8) | (data[2] << 16);
		if (crate != rate) {
			snd_printd(KERN_WARNING "current rate %d is different from the runtime rate %d\n", crate, rate);
			// runtime->rate = crate;
		}
	}
	return 0;
}

1045 1046 1047
/*
 * find a matching format and set up the interface
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1048
static int set_format(snd_usb_substream_t *subs, struct audioformat *fmt)
1049 1050
{
	struct usb_device *dev = subs->dev;
1051 1052
	struct usb_host_config *config = dev->actconfig;
	struct usb_host_interface *alts;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1053 1054
	struct usb_interface_descriptor *altsd;
	struct usb_interface *iface;
1055
	unsigned int ep, attr;
1056
	int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
1057 1058
	int err;

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1059
	iface = get_iface(config, fmt->iface);
1060
	alts = &iface->altsetting[fmt->altset_idx];
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1061 1062
	altsd = get_iface_desc(alts);
	snd_assert(altsd->bAlternateSetting == fmt->altsetting, return -EINVAL);
1063

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1064 1065 1066
	if (fmt == subs->cur_audiofmt)
		return 0;

1067 1068 1069 1070
	/* close the old interface */
	if (subs->interface >= 0 && subs->interface != fmt->iface) {
		usb_set_interface(subs->dev, subs->interface, 0);
		subs->interface = -1;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
		subs->format = 0;
	}

	/* set interface */
	if (subs->interface != fmt->iface || subs->format != fmt->altset_idx) {
		if (usb_set_interface(dev, fmt->iface, fmt->altset_idx) < 0) {
			snd_printk(KERN_ERR "%d:%d:%d: usb_set_interface failed\n",
				   dev->devnum, fmt->iface, fmt->altsetting);
			return -EIO;
		}
		snd_printdd(KERN_INFO "setting usb interface %d:%d\n", fmt->iface, fmt->altset_idx);
		subs->interface = fmt->iface;
		subs->format = fmt->altset_idx;
1084 1085
	}

1086
	/* create a data pipe */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1087
	ep = fmt->endpoint & USB_ENDPOINT_NUMBER_MASK;
1088 1089 1090 1091 1092
	if (is_playback)
		subs->datapipe = usb_sndisocpipe(dev, ep);
	else
		subs->datapipe = usb_rcvisocpipe(dev, ep);
	subs->syncpipe = subs->syncinterval = 0;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1093
	subs->maxpacksize = get_endpoint(alts, 0)->wMaxPacketSize;
1094 1095 1096
	subs->fill_max = 0;

	/* we need a sync pipe in async OUT or adaptive IN mode */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1097 1098 1099 1100
	/* check the number of EP, since some devices have broken
	 * descriptors which fool us.  if it has only one EP,
	 * assume it as adaptive-out or sync-in.
	 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1101
	attr = fmt->ep_attr & EP_ATTR_MASK;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1102 1103 1104 1105 1106
	if (((is_playback && attr == EP_ATTR_ASYNC) ||
	     (! is_playback && attr == EP_ATTR_ADAPTIVE)) &&
	    altsd->bNumEndpoints >= 2) {
		/* check sync-pipe endpoint */
		if (get_endpoint(alts, 1)->bmAttributes != 0x01 ||
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1107
		    get_endpoint(alts, 1)->bSynchAddress != 0) {
1108
			snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
1109
				   dev->devnum, fmt->iface, fmt->altsetting);
1110 1111
			return -EINVAL;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1112
		ep = get_endpoint(alts, 1)->bEndpointAddress;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1113 1114
		if ((is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
		    (! is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN))) {
1115
			snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
1116
				   dev->devnum, fmt->iface, fmt->altsetting);
1117 1118 1119 1120 1121 1122 1123
			return -EINVAL;
		}
		ep &= USB_ENDPOINT_NUMBER_MASK;
		if (is_playback)
			subs->syncpipe = usb_rcvisocpipe(dev, ep);
		else
			subs->syncpipe = usb_sndisocpipe(dev, ep);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1124
		subs->syncinterval = get_endpoint(alts, 1)->bRefresh;
1125 1126 1127 1128 1129 1130
	}

	/* always fill max packet size */
	if (fmt->attributes & EP_CS_ATTR_FILL_MAX)
		subs->fill_max = 1;

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1131 1132 1133 1134 1135
	if ((err = init_usb_pitch(dev, subs->interface, alts, fmt)) < 0)
		return err;

	subs->cur_audiofmt = fmt;

1136 1137
#if 0
	printk("setting done: format = %d, rate = %d, channels = %d\n",
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1138
	       fmt->format, fmt->rate, fmt->channels);
1139 1140 1141 1142 1143 1144 1145 1146
	printk("  datapipe = 0x%0x, syncpipe = 0x%0x\n",
	       subs->datapipe, subs->syncpipe);
#endif

	return 0;
}

/*
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1147 1148 1149
 * hw_params callback
 *
 * allocate a buffer and set the given audio format.
1150 1151 1152 1153 1154 1155 1156 1157 1158
 *
 * so far we use a physically linear buffer although packetize transfer
 * doesn't need a continuous area.
 * if sg buffer is supported on the later version of alsa, we'll follow
 * that.
 */
static int snd_usb_hw_params(snd_pcm_substream_t *substream,
			     snd_pcm_hw_params_t *hw_params)
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
	snd_usb_substream_t *subs = (snd_usb_substream_t *)substream->runtime->private_data;
	struct audioformat *fmt;
	unsigned int channels, rate, format;
	int ret, changed;

	ret = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
	if (ret < 0)
		return ret;
	
	format = params_format(hw_params);
	rate = params_rate(hw_params);
	channels = params_channels(hw_params);
	fmt = find_format(subs, format, rate, channels);
	if (! fmt) {
		snd_printd(KERN_DEBUG "cannot set format: format = %s, rate = %d, channels = %d\n",
			   snd_pcm_format_name(format), rate, channels);
		return -EINVAL;
	}

	changed = subs->cur_audiofmt != fmt ||
		subs->period_bytes != params_period_bytes(hw_params) ||
		subs->cur_rate != rate;
	if ((ret = set_format(subs, fmt)) < 0)
		return ret;

	if (subs->cur_rate != rate) {
		struct usb_host_config *config = subs->dev->actconfig;
		struct usb_host_interface *alts;
		struct usb_interface *iface;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1188
		iface = get_iface(config, fmt->iface);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
		alts = &iface->altsetting[fmt->altset_idx];
		ret = init_usb_sample_rate(subs->dev, subs->interface, alts, fmt, rate);
		if (ret < 0)
			return ret;
		subs->cur_rate = rate;
	}

	if (changed) {
		/* format changed */
		release_substream_urbs(subs, 0);
		/* influenced: period_bytes, channels, rate, format, */
		ret = init_substream_urbs(subs, params_period_bytes(hw_params),
					  params_rate(hw_params),
					  snd_pcm_format_physical_width(params_format(hw_params)) * params_channels(hw_params));
	}

	return ret;
1206 1207 1208
}

/*
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1209 1210 1211
 * hw_free callback
 *
 * reset the audio format and release the buffer
1212 1213 1214
 */
static int snd_usb_hw_free(snd_pcm_substream_t *substream)
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1215 1216 1217 1218 1219 1220
	snd_usb_substream_t *subs = (snd_usb_substream_t *)substream->runtime->private_data;

	subs->cur_audiofmt = NULL;
	subs->cur_rate = 0;
	subs->period_bytes = 0;
	release_substream_urbs(subs, 0);
1221 1222 1223 1224 1225 1226
	return snd_pcm_lib_free_pages(substream);
}

/*
 * prepare callback
 *
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1227
 * only a few subtle things...
1228 1229 1230 1231 1232 1233
 */
static int snd_usb_pcm_prepare(snd_pcm_substream_t *substream)
{
	snd_pcm_runtime_t *runtime = substream->runtime;
	snd_usb_substream_t *subs = (snd_usb_substream_t *)runtime->private_data;

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1234 1235 1236 1237
	if (! subs->cur_audiofmt) {
		snd_printk(KERN_ERR "usbaudio: no format is specified!\n");
		return -ENXIO;
	}
1238

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1239 1240 1241 1242 1243
	/* some unit conversions in runtime */
	subs->maxframesize = bytes_to_frames(runtime, subs->maxpacksize);
	subs->curframesize = bytes_to_frames(runtime, subs->curpacksize);

	return 0;
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
}

static snd_pcm_hardware_t snd_usb_playback =
{
	.info =			(SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
				 SNDRV_PCM_INFO_BLOCK_TRANSFER |
				 SNDRV_PCM_INFO_MMAP_VALID),
	.buffer_bytes_max =	(128*1024),
	.period_bytes_min =	64,
	.period_bytes_max =	(128*1024),
	.periods_min =		2,
	.periods_max =		1024,
};

static snd_pcm_hardware_t snd_usb_capture =
{
	.info =			(SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
				 SNDRV_PCM_INFO_BLOCK_TRANSFER |
				 SNDRV_PCM_INFO_MMAP_VALID),
	.buffer_bytes_max =	(128*1024),
	.period_bytes_min =	64,
	.period_bytes_max =	(128*1024),
	.periods_min =		2,
	.periods_max =		1024,
};

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
/*
 * h/w constraints
 */

#ifdef HW_CONST_DEBUG
#define hwc_debug(fmt, args...) printk(KERN_DEBUG fmt, ##args)
#else
#define hwc_debug(fmt, args...) /**/
#endif

static int hw_check_valid_format(snd_pcm_hw_params_t *params, struct audioformat *fp)
{
	snd_interval_t *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
	snd_interval_t *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
	snd_mask_t *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);

	/* check the format */
	if (! snd_mask_test(fmts, fp->format)) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1288
		hwc_debug("   > check: no supported format %d\n", fp->format);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
		return 0;
	}
	/* check the channels */
	if (fp->channels < ct->min || fp->channels > ct->max) {
		hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
		return 0;
	}
	/* check the rate is within the range */
	if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
		hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
		return 0;
	}
	if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
		hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
		return 0;
	}
	return 1;
}

static int hw_rule_rate(snd_pcm_hw_params_t *params,
			snd_pcm_hw_rule_t *rule)
{
	snd_usb_substream_t *subs = rule->private;
	struct list_head *p;
	snd_interval_t *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1314 1315
	unsigned int rmin, rmax;
	int changed;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
	
	hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
	changed = 0;
	rmin = rmax = 0;
	list_for_each(p, &subs->fmt_list) {
		struct audioformat *fp;
		fp = list_entry(p, struct audioformat, list);
		if (! hw_check_valid_format(params, fp))
			continue;
		if (changed++) {
			if (rmin > fp->rate_min)
				rmin = fp->rate_min;
			if (rmax < fp->rate_max)
				rmax = fp->rate_max;
		} else {
			rmin = fp->rate_min;
			rmax = fp->rate_max;
		}
	}

	if (! changed) {
		hwc_debug("  --> get empty\n");
		it->empty = 1;
		return -EINVAL;
	}

	changed = 0;
	if (it->min < rmin) {
		it->min = rmin;
		it->openmin = 0;
		changed = 1;
	}
	if (it->max > rmax) {
		it->max = rmax;
		it->openmax = 0;
		changed = 1;
	}
	if (snd_interval_checkempty(it)) {
		it->empty = 1;
		return -EINVAL;
	}
	hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
	return changed;
}


static int hw_rule_channels(snd_pcm_hw_params_t *params,
			    snd_pcm_hw_rule_t *rule)
{
	snd_usb_substream_t *subs = rule->private;
	struct list_head *p;
	snd_interval_t *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1368 1369
	unsigned int rmin, rmax;
	int changed;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
	
	hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
	changed = 0;
	rmin = rmax = 0;
	list_for_each(p, &subs->fmt_list) {
		struct audioformat *fp;
		fp = list_entry(p, struct audioformat, list);
		if (! hw_check_valid_format(params, fp))
			continue;
		if (changed++) {
			if (rmin > fp->channels)
				rmin = fp->channels;
			if (rmax < fp->channels)
				rmax = fp->channels;
		} else {
			rmin = fp->channels;
			rmax = fp->channels;
		}
	}

	if (! changed) {
		hwc_debug("  --> get empty\n");
		it->empty = 1;
		return -EINVAL;
	}

	changed = 0;
	if (it->min < rmin) {
		it->min = rmin;
		it->openmin = 0;
		changed = 1;
	}
	if (it->max > rmax) {
		it->max = rmax;
		it->openmax = 0;
		changed = 1;
	}
	if (snd_interval_checkempty(it)) {
		it->empty = 1;
		return -EINVAL;
	}
	hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
	return changed;
}

static int hw_rule_format(snd_pcm_hw_params_t *params,
			  snd_pcm_hw_rule_t *rule)
{
	snd_usb_substream_t *subs = rule->private;
	struct list_head *p;
	snd_mask_t *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
	u64 fbits;
	u32 oldbits[2];
	int changed;
	
	hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
	fbits = 0;
	list_for_each(p, &subs->fmt_list) {
		struct audioformat *fp;
		fp = list_entry(p, struct audioformat, list);
		if (! hw_check_valid_format(params, fp))
			continue;
		fbits |= (1UL << fp->format);
	}

	oldbits[0] = fmt->bits[0];
	oldbits[1] = fmt->bits[1];
	fmt->bits[0] &= (u32)fbits;
	fmt->bits[1] &= (u32)(fbits >> 32);
	if (! fmt->bits[0] && ! fmt->bits[1]) {
		hwc_debug("  --> get empty\n");
		return -EINVAL;
	}
	changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
	hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
	return changed;
}

/*
 * check whether the registered audio formats need special hw-constraints
 */
static int check_hw_params_convention(snd_usb_substream_t *subs)
{
	int i;
	u32 channels[64];
	u32 rates[64];
	u32 cmaster, rmaster;
	struct list_head *p;

	memset(channels, 0, sizeof(channels));
	memset(rates, 0, sizeof(rates));

	list_for_each(p, &subs->fmt_list) {
		struct audioformat *f;
		f = list_entry(p, struct audioformat, list);
		/* unconventional channels? */
		if (f->channels > 32)
			return 1;
		/* combination of continuous rates and fixed rates? */
		if (rates[f->format] & SNDRV_PCM_RATE_CONTINUOUS) {
			if (f->rates != rates[f->format])
				return 1;
		}
		if (f->rates & SNDRV_PCM_RATE_CONTINUOUS) {
			if (rates[f->format] && rates[f->format] != f->rates)
				return 1;
		}
		channels[f->format] |= (1 << f->channels);
		rates[f->format] |= f->rates;
	}
	/* check whether channels and rates match for all formats */
	cmaster = rmaster = 0;
	for (i = 0; i < 64; i++) {
		if (cmaster != channels[i] && cmaster && channels[i])
			return 1;
		if (rmaster != rates[i] && rmaster && rates[i])
			return 1;
		if (channels[i])
			cmaster = channels[i];
		if (rates[i])
			rmaster = rates[i];
	}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
	/* check whether channels match for all distinct rates */
	memset(channels, 0, sizeof(channels));
	list_for_each(p, &subs->fmt_list) {
		struct audioformat *f;
		f = list_entry(p, struct audioformat, list);
		if (f->rates & SNDRV_PCM_RATE_CONTINUOUS)
			continue;
		for (i = 0; i < 32; i++) {
			if (f->rates & (1 << i))
				channels[i] |= (1 << f->channels);
		}
	}
	cmaster = 0;
	for (i = 0; i < 32; i++) {
		if (cmaster != channels[i] && cmaster && channels[i])
			return 1;
		if (channels[i])
			cmaster = channels[i];
	}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1511 1512 1513 1514
	return 0;
}


1515 1516 1517 1518
/*
 * set up the runtime hardware information.
 */

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1519
static int setup_hw_info(snd_pcm_runtime_t *runtime, snd_usb_substream_t *subs)
1520 1521
{
	struct list_head *p;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1522
	int err;
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

	runtime->hw.formats = subs->formats;

	runtime->hw.rate_min = 0x7fffffff;
	runtime->hw.rate_max = 0;
	runtime->hw.channels_min = 256;
	runtime->hw.channels_max = 0;
	runtime->hw.rates = 0;
	/* check min/max rates and channels */
	list_for_each(p, &subs->fmt_list) {
		struct audioformat *fp;
		fp = list_entry(p, struct audioformat, list);
		runtime->hw.rates |= fp->rates;
		if (runtime->hw.rate_min > fp->rate_min)
			runtime->hw.rate_min = fp->rate_min;
		if (runtime->hw.rate_max < fp->rate_max)
			runtime->hw.rate_max = fp->rate_max;
		if (runtime->hw.channels_min > fp->channels)
			runtime->hw.channels_min = fp->channels;
		if (runtime->hw.channels_max < fp->channels)
			runtime->hw.channels_max = fp->channels;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1544 1545 1546 1547 1548
		if (fp->nonaudio && fp->frame_size > 0) {
			/* FIXME: there might be more than one audio formats... */
			runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
				fp->frame_size;
		}
1549 1550 1551 1552 1553
	}

	/* set the period time minimum 1ms */
	snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
				     1000 * MIN_PACKS_URB,
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1554
				     /*(nrpacks * MAX_URBS) * 1000*/ UINT_MAX);
1555

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
	if (check_hw_params_convention(subs)) {
		hwc_debug("setting extra hw constraints...\n");
		if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, 
					       hw_rule_rate, subs,
					       SNDRV_PCM_HW_PARAM_FORMAT,
					       SNDRV_PCM_HW_PARAM_CHANNELS,
					       -1)) < 0)
			return err;
		if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, 
					       hw_rule_channels, subs,
					       SNDRV_PCM_HW_PARAM_FORMAT,
					       SNDRV_PCM_HW_PARAM_RATE,
					       -1)) < 0)
			return err;
		if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
					       hw_rule_format, subs,
					       SNDRV_PCM_HW_PARAM_RATE,
					       SNDRV_PCM_HW_PARAM_CHANNELS,
					       -1)) < 0)
			return err;
	}
	return 0;
1578 1579 1580 1581 1582 1583 1584 1585 1586
}

static int snd_usb_pcm_open(snd_pcm_substream_t *substream, int direction,
			    snd_pcm_hardware_t *hw)
{
	snd_usb_stream_t *as = snd_pcm_substream_chip(substream);
	snd_pcm_runtime_t *runtime = substream->runtime;
	snd_usb_substream_t *subs = &as->substream[direction];

1587
	subs->interface = -1;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1588
	subs->format = 0;
1589 1590 1591
	runtime->hw = *hw;
	runtime->private_data = subs;
	subs->pcm_substream = substream;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1592
	return setup_hw_info(runtime, subs);
1593 1594 1595 1596 1597 1598
}

static int snd_usb_pcm_close(snd_pcm_substream_t *substream, int direction)
{
	snd_usb_stream_t *as = snd_pcm_substream_chip(substream);
	snd_usb_substream_t *subs = &as->substream[direction];
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1599

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1600
	if (subs->interface >= 0) {
1601
		usb_set_interface(subs->dev, subs->interface, 0);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1602 1603
		subs->interface = -1;
	}
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
	subs->pcm_substream = NULL;
	return 0;
}

static int snd_usb_playback_open(snd_pcm_substream_t *substream)
{
	return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK, &snd_usb_playback);
}

static int snd_usb_playback_close(snd_pcm_substream_t *substream)
{
	return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
}

static int snd_usb_capture_open(snd_pcm_substream_t *substream)
{
	return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE, &snd_usb_capture);
}

static int snd_usb_capture_close(snd_pcm_substream_t *substream)
{
	return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
}

static snd_pcm_ops_t snd_usb_playback_ops = {
	.open =		snd_usb_playback_open,
	.close =	snd_usb_playback_close,
	.ioctl =	snd_pcm_lib_ioctl,
	.hw_params =	snd_usb_hw_params,
	.hw_free =	snd_usb_hw_free,
	.prepare =	snd_usb_pcm_prepare,
	.trigger =	snd_usb_pcm_trigger,
	.pointer =	snd_usb_pcm_pointer,
};

static snd_pcm_ops_t snd_usb_capture_ops = {
	.open =		snd_usb_capture_open,
	.close =	snd_usb_capture_close,
	.ioctl =	snd_pcm_lib_ioctl,
	.hw_params =	snd_usb_hw_params,
	.hw_free =	snd_usb_hw_free,
	.prepare =	snd_usb_pcm_prepare,
	.trigger =	snd_usb_pcm_trigger,
	.pointer =	snd_usb_pcm_pointer,
};



/*
 * helper functions
 */

/*
 * combine bytes and get an integer value
 */
unsigned int snd_usb_combine_bytes(unsigned char *bytes, int size)
{
	switch (size) {
	case 1:  return *bytes;
	case 2:  return combine_word(bytes);
	case 3:  return combine_triple(bytes);
	case 4:  return combine_quad(bytes);
	default: return 0;
	}
}

/*
 * parse descriptor buffer and return the pointer starting the given
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1672
 * descriptor type.
1673
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1674
void *snd_usb_find_desc(void *descstart, int desclen, void *after, u8 dtype)
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
{
	u8 *p, *end, *next;

	p = descstart;
	end = p + desclen;
	for (; p < end;) {
		if (p[0] < 2)
			return NULL;
		next = p + p[0];
		if (next > end)
			return NULL;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1686
		if (p[1] == dtype && (!after || (void *)p > after)) {
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
			return p;
		}
		p = next;
	}
	return NULL;
}

/*
 * find a class-specified interface descriptor with the given subtype.
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1697
void *snd_usb_find_csint_desc(void *buffer, int buflen, void *after, u8 dsubtype)
1698 1699 1700 1701
{
	unsigned char *p = after;

	while ((p = snd_usb_find_desc(buffer, buflen, p,
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1702
				      USB_DT_CS_INTERFACE)) != NULL) {
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
		if (p[0] >= 3 && p[2] == dsubtype)
			return p;
	}
	return NULL;
}


/*
 * entry point for linux usb interface
 */

Jaroslav Kysela's avatar
Jaroslav Kysela committed
1714 1715 1716
static int usb_audio_probe(struct usb_interface *intf,
			   const struct usb_device_id *id);
static void usb_audio_disconnect(struct usb_interface *intf);
1717 1718

static struct usb_device_id usb_audio_ids [] = {
1719
#include "usbquirks.h"
1720 1721 1722 1723 1724 1725 1726 1727 1728
    { .match_flags = (USB_DEVICE_ID_MATCH_INT_CLASS | USB_DEVICE_ID_MATCH_INT_SUBCLASS),
      .bInterfaceClass = USB_CLASS_AUDIO,
      .bInterfaceSubClass = USB_SUBCLASS_AUDIO_CONTROL },
    { }						/* Terminating entry */
};

MODULE_DEVICE_TABLE (usb, usb_audio_ids);

static struct usb_driver usb_audio_driver = {
1729
	.owner =	THIS_MODULE,
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
	.name =		"snd-usb-audio",
	.probe =	usb_audio_probe,
	.disconnect =	usb_audio_disconnect,
	.id_table =	usb_audio_ids,
};


/*
 * proc interface for list the supported pcm formats
 */
static void proc_dump_substream_formats(snd_usb_substream_t *subs, snd_info_buffer_t *buffer)
{
	struct list_head *p;
	static char *sync_types[4] = {
		"NONE", "ASYNC", "ADAPTIVE", "SYNC"
	};

	list_for_each(p, &subs->fmt_list) {
		struct audioformat *fp;
		fp = list_entry(p, struct audioformat, list);
1750 1751
		snd_iprintf(buffer, "  Interface %d\n", fp->iface);
		snd_iprintf(buffer, "    Altset %d\n", fp->altset_idx);
1752 1753 1754 1755 1756 1757 1758
		snd_iprintf(buffer, "    Format: %s\n", snd_pcm_format_name(fp->format));
		snd_iprintf(buffer, "    Channels: %d\n", fp->channels);
		snd_iprintf(buffer, "    Endpoint: %d %s (%s)\n",
			    fp->endpoint & USB_ENDPOINT_NUMBER_MASK,
			    fp->endpoint & USB_DIR_IN ? "IN" : "OUT",
			    sync_types[(fp->ep_attr & EP_ATTR_MASK) >> 2]);
		if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1759
			snd_iprintf(buffer, "    Rates: %d - %d (continuous)\n",
1760 1761
				    fp->rate_min, fp->rate_max);
		} else {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1762
			unsigned int i;
1763 1764 1765 1766 1767 1768 1769 1770
			snd_iprintf(buffer, "    Rates: ");
			for (i = 0; i < fp->nr_rates; i++) {
				if (i > 0)
					snd_iprintf(buffer, ", ");
				snd_iprintf(buffer, "%d", fp->rate_table[i]);
			}
			snd_iprintf(buffer, "\n");
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1771 1772
		// snd_iprintf(buffer, "    Max Packet Size = %d\n", fp->maxpacksize);
		// snd_iprintf(buffer, "    EP Attribute = 0x%x\n", fp->attributes);
1773 1774 1775 1776 1777 1778
	}
}

static void proc_dump_substream_status(snd_usb_substream_t *subs, snd_info_buffer_t *buffer)
{
	if (subs->running) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1779
		unsigned int i;
1780
		snd_iprintf(buffer, "  Status: Running\n");
1781
		snd_iprintf(buffer, "    Interface = %d\n", subs->interface);
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
		snd_iprintf(buffer, "    Altset = %d\n", subs->format);
		snd_iprintf(buffer, "    URBs = %d [ ", subs->nurbs);
		for (i = 0; i < subs->nurbs; i++)
			snd_iprintf(buffer, "%d ", subs->dataurb[i].packets);
		snd_iprintf(buffer, "]\n");
		snd_iprintf(buffer, "    Packet Size = %d\n", subs->curpacksize);
		snd_iprintf(buffer, "    Momentary freq = %d,%03d Hz\n",
			    subs->freqm >> 14,
			    ((subs->freqm & ((1 << 14) - 1)) * 1000) / ((1 << 14) - 1));
	} else {
		snd_iprintf(buffer, "  Status: Stop\n");
	}
}

static void proc_pcm_format_read(snd_info_entry_t *entry, snd_info_buffer_t *buffer)
{
	snd_usb_stream_t *stream = snd_magic_cast(snd_usb_stream_t, entry->private_data, return);
	
	snd_iprintf(buffer, "%s : %s\n", stream->chip->card->longname, stream->pcm->name);

	if (stream->substream[SNDRV_PCM_STREAM_PLAYBACK].num_formats) {
		snd_iprintf(buffer, "\nPlayback:\n");
		proc_dump_substream_status(&stream->substream[SNDRV_PCM_STREAM_PLAYBACK], buffer);
		proc_dump_substream_formats(&stream->substream[SNDRV_PCM_STREAM_PLAYBACK], buffer);
	}
	if (stream->substream[SNDRV_PCM_STREAM_CAPTURE].num_formats) {
		snd_iprintf(buffer, "\nCapture:\n");
		proc_dump_substream_status(&stream->substream[SNDRV_PCM_STREAM_CAPTURE], buffer);
		proc_dump_substream_formats(&stream->substream[SNDRV_PCM_STREAM_CAPTURE], buffer);
	}
}

static void proc_pcm_format_add(snd_usb_stream_t *stream)
{
	snd_info_entry_t *entry;
	char name[32];
	snd_card_t *card = stream->chip->card;

	sprintf(name, "stream%d", stream->pcm_index);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1821 1822
	if (! snd_card_proc_new(card, name, &entry))
		snd_info_set_text_ops(entry, stream, proc_pcm_format_read);
1823 1824 1825
}


1826
/*
1827
 * initialize the substream instance.
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
 */

static void init_substream(snd_usb_stream_t *as, int stream, struct audioformat *fp)
{
	snd_usb_substream_t *subs = &as->substream[stream];

	INIT_LIST_HEAD(&subs->fmt_list);
	spin_lock_init(&subs->lock);

	subs->stream = as;
	subs->direction = stream;
	subs->dev = as->chip->dev;
	subs->ops = audio_urb_ops[stream];
	snd_pcm_lib_preallocate_pages(as->pcm->streams[stream].substream,
				      64 * 1024, 128 * 1024, GFP_ATOMIC);
	snd_pcm_set_ops(as->pcm, stream,
			stream == SNDRV_PCM_STREAM_PLAYBACK ?
			&snd_usb_playback_ops : &snd_usb_capture_ops);

	list_add_tail(&fp->list, &subs->fmt_list);
	subs->formats |= 1ULL << fp->format;
	subs->endpoint = fp->endpoint;
	subs->num_formats++;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1851
	subs->nonaudio = fp->nonaudio;
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
}


/*
 * free a substream
 */
static void free_substream(snd_usb_substream_t *subs)
{
	struct list_head *p, *n;

	if (! subs->num_formats)
		return; /* not initialized */
	list_for_each_safe(p, n, &subs->fmt_list) {
		struct audioformat *fp = list_entry(p, struct audioformat, list);
		if (fp->rate_table)
			kfree(fp->rate_table);
		kfree(fp);
	}
}


1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
/*
 * free a usb stream instance
 */
static void snd_usb_audio_stream_free(snd_usb_stream_t *stream)
{
	free_substream(&stream->substream[0]);
	free_substream(&stream->substream[1]);
	list_del(&stream->list);
	snd_magic_kfree(stream);
}

static void snd_usb_audio_pcm_free(snd_pcm_t *pcm)
{
	snd_usb_stream_t *stream = pcm->private_data;
	if (stream) {
		stream->pcm = NULL;
		snd_pcm_lib_preallocate_free_for_all(pcm);
		snd_usb_audio_stream_free(stream);
	}
}

1894 1895 1896 1897 1898 1899 1900

/*
 * add this endpoint to the chip instance.
 * if a stream with the same endpoint already exists, append to it.
 * if not, create a new pcm stream.
 */
static int add_audio_endpoint(snd_usb_audio_t *chip, int stream, struct audioformat *fp)
1901
{
1902
	struct list_head *p;
1903
	snd_usb_stream_t *as;
1904
	snd_usb_substream_t *subs;
1905 1906 1907
	snd_pcm_t *pcm;
	int err;

1908 1909 1910 1911 1912 1913
	list_for_each(p, &chip->pcm_list) {
		as = list_entry(p, snd_usb_stream_t, list);
		subs = &as->substream[stream];
		if (! subs->endpoint)
			break;
		if (subs->endpoint == fp->endpoint) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1914 1915 1916 1917 1918 1919 1920
			if (fp->nonaudio) {
				if (!subs->nonaudio || subs->formats != (1ULL << fp->format))
					continue; /* non-linear formats are handled exclusively */
			} else {
				if (subs->nonaudio)
					continue;
			}
1921 1922 1923 1924 1925
			list_add_tail(&fp->list, &subs->fmt_list);
			subs->num_formats++;
			subs->formats |= 1ULL << fp->format;
			return 0;
		}
1926
	}
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
	/* look for an empty stream */
	list_for_each(p, &chip->pcm_list) {
		as = list_entry(p, snd_usb_stream_t, list);
		subs = &as->substream[stream];
		if (subs->endpoint)
			continue;
		err = snd_pcm_new_stream(as->pcm, stream, 1);
		if (err < 0)
			return err;
		init_substream(as, stream, fp);
1937 1938 1939
		return 0;
	}

1940 1941 1942 1943 1944 1945 1946
	/* create a new pcm */
	as = snd_magic_kmalloc(snd_usb_stream_t, 0, GFP_KERNEL);
	if (! as)
		return -ENOMEM;
	memset(as, 0, sizeof(*as));
	as->pcm_index = chip->pcm_devs;
	as->chip = chip;
1947
	err = snd_pcm_new(chip->card, "USB Audio", chip->pcm_devs,
1948 1949
			  stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0,
			  stream == SNDRV_PCM_STREAM_PLAYBACK ? 0 : 1,
1950 1951
			  &pcm);
	if (err < 0) {
1952
		snd_magic_kfree(as);
1953 1954 1955 1956 1957 1958
		return err;
	}
	as->pcm = pcm;
	pcm->private_data = as;
	pcm->private_free = snd_usb_audio_pcm_free;
	pcm->info_flags = 0;
1959 1960 1961 1962
	if (chip->pcm_devs > 0)
		sprintf(pcm->name, "USB Audio #%d", chip->pcm_devs);
	else
		strcpy(pcm->name, "USB Audio");
1963

1964
	init_substream(as, stream, fp);
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974

	list_add(&as->list, &chip->pcm_list);
	chip->pcm_devs++;

	proc_pcm_format_add(as);

	return 0;
}


1975
/*
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1976
 * parse the audio format type I descriptor
1977
 * and returns the corresponding pcm format
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1978 1979 1980 1981 1982
 *
 * @dev: usb device
 * @fp: audioformat record
 * @format: the format tag (wFormatTag)
 * @fmt: the format type descriptor
1983
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1984 1985
static int parse_audio_format_i_type(struct usb_device *dev, struct audioformat *fp,
				     int format, unsigned char *fmt)
1986 1987
{
	int pcm_format;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1988
	int sample_width, sample_bytes;
1989 1990 1991

	/* FIXME: correct endianess and sign? */
	pcm_format = -1;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1992 1993
	sample_width = fmt[6];
	sample_bytes = fmt[5];
1994
	switch (format) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1995
	case 0: /* some devices don't define this correctly... */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1996
		snd_printdd(KERN_INFO "%d:%u:%d : format type 0 is detected, processed as PCM\n",
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1997
			    dev->devnum, fp->iface, fp->altsetting);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
1998
		/* fall-through */
1999
	case USB_AUDIO_FORMAT_PCM:
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2000 2001 2002 2003 2004
		if (sample_width > sample_bytes * 8) {
			snd_printk(KERN_INFO "%d:%u:%d : sample bitwidth %d in over sample bytes %d\n",
				   dev->devnum, fp->iface, fp->altsetting,
				   sample_width, sample_bytes);
		}
2005
		/* check the format byte size */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2006 2007
		switch (fmt[5]) {
		case 1:
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2008
			pcm_format = SNDRV_PCM_FORMAT_S8;
2009
			break;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2010
		case 2:
2011 2012
			pcm_format = SNDRV_PCM_FORMAT_S16_LE;
			break;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2013 2014
		case 3:
			pcm_format = SNDRV_PCM_FORMAT_S24_3LE;
2015
			break;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2016
		case 4:
2017 2018 2019 2020
			pcm_format = SNDRV_PCM_FORMAT_S32_LE;
			break;
		default:
			snd_printk(KERN_INFO "%d:%u:%d : unsupported sample bitwidth %d in %d bytes\n",
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2021
				   dev->devnum, fp->iface, fp->altsetting, sample_width, sample_bytes);
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
			break;
		}
		break;
	case USB_AUDIO_FORMAT_PCM8:
		/* Dallas DS4201 workaround */
		if (dev->descriptor.idVendor == 0x04fa && dev->descriptor.idProduct == 0x4201)
			pcm_format = SNDRV_PCM_FORMAT_S8;
		else
			pcm_format = SNDRV_PCM_FORMAT_U8;
		break;
	case USB_AUDIO_FORMAT_IEEE_FLOAT:
		pcm_format = SNDRV_PCM_FORMAT_FLOAT_LE;
		break;
	case USB_AUDIO_FORMAT_ALAW:
		pcm_format = SNDRV_PCM_FORMAT_A_LAW;
		break;
	case USB_AUDIO_FORMAT_MU_LAW:
		pcm_format = SNDRV_PCM_FORMAT_MU_LAW;
		break;
	default:
		snd_printk(KERN_INFO "%d:%u:%d : unsupported format type %d\n",
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2043
			   dev->devnum, fp->iface, fp->altsetting, format);
2044 2045 2046 2047 2048 2049
		break;
	}
	return pcm_format;
}


Jaroslav Kysela's avatar
Jaroslav Kysela committed
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
/*
 * parse the format descriptor and stores the possible sample rates
 * on the audioformat table.
 *
 * @dev: usb device
 * @fp: audioformat record
 * @fmt: the format descriptor
 * @offset: the start offset of descriptor pointing the rate type
 *          (7 for type I and II, 8 for type II)
 */
static int parse_audio_format_rates(struct usb_device *dev, struct audioformat *fp,
				    unsigned char *fmt, int offset)
{
	int nr_rates = fmt[offset];
	if (fmt[0] < offset + 1 + 3 * (nr_rates ? nr_rates : 2)) {
		snd_printk(KERN_ERR "%d:%u:%d : invalid FORMAT_TYPE desc\n", 
				   dev->devnum, fp->iface, fp->altsetting);
		return -1;
	}

	if (nr_rates) {
		/*
		 * build the rate table and bitmap flags
		 */
		int r, idx, c;
		/* this table corresponds to the SNDRV_PCM_RATE_XXX bit */
		static unsigned int conv_rates[] = {
			5512, 8000, 11025, 16000, 22050, 32000, 44100, 48000,
			64000, 88200, 96000, 176400, 192000
		};
		fp->rate_table = kmalloc(sizeof(int) * nr_rates, GFP_KERNEL);
		if (fp->rate_table == NULL) {
			snd_printk(KERN_ERR "cannot malloc\n");
			return -1;
		}

		fp->nr_rates = nr_rates;
		fp->rate_min = fp->rate_max = combine_triple(&fmt[8]);
		for (r = 0, idx = offset + 1; r < nr_rates; r++, idx += 3) {
			unsigned int rate = fp->rate_table[r] = combine_triple(&fmt[idx]);
			if (rate < fp->rate_min)
				fp->rate_min = rate;
			else if (rate > fp->rate_max)
				fp->rate_max = rate;
			for (c = 0; c < (int)ARRAY_SIZE(conv_rates); c++) {
				if (rate == conv_rates[c]) {
					fp->rates |= (1 << c);
					break;
				}
			}
		}
	} else {
		/* continuous rates */
		fp->rates = SNDRV_PCM_RATE_CONTINUOUS;
		fp->rate_min = combine_triple(&fmt[offset + 1]);
		fp->rate_max = combine_triple(&fmt[offset + 4]);
	}
	return 0;
}

/*
 * parse the format type I and III descriptors
 */
static int parse_audio_format_i(struct usb_device *dev, struct audioformat *fp,
				int format, unsigned char *fmt)
{
	int pcm_format;

	if (fmt[3] == USB_FORMAT_TYPE_III) {
		/* FIXME: the format type is really IECxxx
		 *        but we give normal PCM format to get the existing
		 *        apps working...
		 */
		pcm_format = SNDRV_PCM_FORMAT_S16_LE;
	} else {
		pcm_format = parse_audio_format_i_type(dev, fp, format, fmt);
		if (pcm_format < 0)
			return -1;
	}
	fp->format = pcm_format;
	fp->channels = fmt[4];
	if (fp->channels < 1) {
		snd_printk(KERN_ERR "%d:%u:%d : invalid channels %d\n",
			   dev->devnum, fp->iface, fp->altsetting, fp->channels);
		return -1;
	}
	return parse_audio_format_rates(dev, fp, fmt, 7);
}

/*
 * prase the format type II descriptor
 */
static int parse_audio_format_ii(struct usb_device *dev, struct audioformat *fp,
				 int format, unsigned char *fmt)
{
	int brate, framesize;
	switch (format) {
	case USB_AUDIO_FORMAT_AC3:
		/* FIXME: there is no AC3 format defined yet */
		// fp->format = SNDRV_PCM_FORMAT_AC3;
		fp->format = SNDRV_PCM_FORMAT_U8; /* temporarily hack to receive byte streams */
		break;
	case USB_AUDIO_FORMAT_MPEG:
		fp->format = SNDRV_PCM_FORMAT_MPEG;
		break;
	default:
		snd_printd(KERN_INFO "%d:%u:%d : unknown format tag 0x%x is detected.  processed as MPEG.\n",
			   dev->devnum, fp->iface, fp->altsetting, format);
		fp->format = SNDRV_PCM_FORMAT_MPEG;
		break;
	}
	fp->channels = 1;
	fp->nonaudio = 1;
	brate = combine_word(&fmt[4]); 	/* fmt[4,5] : wMaxBitRate (in kbps) */
	framesize = combine_word(&fmt[6]); /* fmt[6,7]: wSamplesPerFrame */
	snd_printd(KERN_INFO "found format II with max.bitrate = %d, frame size=%d\n", brate, framesize);
	fp->frame_size = framesize;
	return parse_audio_format_rates(dev, fp, fmt, 8); /* fmt[8..] sample rates */
}

static int parse_audio_format(struct usb_device *dev, struct audioformat *fp,
			      int format, unsigned char *fmt, int stream)
{
	int err;

	switch (fmt[3]) {
	case USB_FORMAT_TYPE_I:
	case USB_FORMAT_TYPE_III:
		err = parse_audio_format_i(dev, fp, format, fmt);
		break;
	case USB_FORMAT_TYPE_II:
		err = parse_audio_format_ii(dev, fp, format, fmt);
		break;
	default:
		snd_printd(KERN_INFO "%d:%u:%d : format type %d is not supported yet\n",
			   dev->devnum, fp->iface, fp->altsetting, fmt[3]);
		return -1;
	}
	if (err < 0)
		return err;
#if 1
	/* FIXME: temporary hack for extigy */
	/* extigy apparently supports sample rates other than 48k
	 * but not in ordinary way.  so we enable only 48k atm.
	 */
	if (dev->descriptor.idVendor == 0x041e && dev->descriptor.idProduct == 0x3000) {
		if (fmt[3] == USB_FORMAT_TYPE_I &&
		    stream == SNDRV_PCM_STREAM_PLAYBACK &&
		    fp->rates != SNDRV_PCM_RATE_48000)
			return -1; /* use 48k only */
	}
#endif
	return 0;
}	

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2205
static int parse_audio_endpoints(snd_usb_audio_t *chip, int iface_no)
2206 2207
{
	struct usb_device *dev;
2208
	struct usb_host_config *config;
2209
	struct usb_interface *iface;
2210
	struct usb_host_interface *alts;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2211
	struct usb_interface_descriptor *altsd;
2212
	int i, altno, err, stream;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2213
	int format;
2214 2215 2216 2217 2218 2219 2220
	struct audioformat *fp;
	unsigned char *fmt, *csep;

	dev = chip->dev;
	config = dev->actconfig;

	/* parse the interface's altsettings */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2221
	iface = get_iface(config, iface_no);
2222 2223
	for (i = 0; i < iface->num_altsetting; i++) {
		alts = &iface->altsetting[i];
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2224
		altsd = get_iface_desc(alts);
2225
		/* skip invalid one */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2226 2227
		if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
		     altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2228 2229 2230 2231
		    (altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIO_STREAMING &&
		     altsd->bInterfaceSubClass != USB_SUBCLASS_VENDOR_SPEC) ||
		    altsd->bNumEndpoints < 1 ||
		    get_endpoint(alts, 0)->wMaxPacketSize == 0)
2232 2233
			continue;
		/* must be isochronous */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2234
		if ((get_endpoint(alts, 0)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
2235 2236 2237
		    USB_ENDPOINT_XFER_ISOC)
			continue;
		/* check direction */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2238
		stream = (get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN) ?
2239
			SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2240
		altno = altsd->bAlternateSetting;
2241 2242

		/* get audio formats */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2243
		fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, AS_GENERAL);
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
		if (!fmt) {
			snd_printk(KERN_ERR "%d:%u:%d : AS_GENERAL descriptor not found\n",
				   dev->devnum, iface_no, altno);
			continue;
		}

		if (fmt[0] < 7) {
			snd_printk(KERN_ERR "%d:%u:%d : invalid AS_GENERAL desc\n", 
				   dev->devnum, iface_no, altno);
			continue;
		}

		format = (fmt[6] << 8) | fmt[5]; /* remember the format value */
			
		/* get format type */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2259
		fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, FORMAT_TYPE);
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
		if (!fmt) {
			snd_printk(KERN_ERR "%d:%u:%d : no FORMAT_TYPE desc\n", 
				   dev->devnum, iface_no, altno);
			continue;
		}
		if (fmt[0] < 8) {
			snd_printk(KERN_ERR "%d:%u:%d : invalid FORMAT_TYPE desc\n", 
				   dev->devnum, iface_no, altno);
			continue;
		}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2271
		csep = snd_usb_find_desc(alts->endpoint[0].extra, alts->endpoint[0].extralen, NULL, USB_DT_CS_ENDPOINT);
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
		if (!csep || csep[0] < 7 || csep[2] != EP_GENERAL) {
			snd_printk(KERN_ERR "%d:%u:%d : no or invalid class specific endpoint descriptor\n", 
				   dev->devnum, iface_no, altno);
			continue;
		}

		fp = kmalloc(sizeof(*fp), GFP_KERNEL);
		if (! fp) {
			snd_printk(KERN_ERR "cannot malloc\n");
			return -ENOMEM;
		}

		memset(fp, 0, sizeof(*fp));
		fp->iface = iface_no;
		fp->altsetting = altno;
		fp->altset_idx = i;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2288 2289
		fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
		fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2290
		fp->maxpacksize = get_endpoint(alts, 0)->wMaxPacketSize;
2291 2292
		fp->attributes = csep[3];

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
		/* some quirks for attributes here */

		/* workaround for AudioTrak Optoplay */
		if (dev->descriptor.idVendor == 0x0a92 &&
		    dev->descriptor.idProduct == 0x0053) {
			/* Optoplay sets the sample rate attribute although
			 * it seems not supporting it in fact.
			 */
			fp->attributes &= ~EP_CS_ATTR_SAMPLE_RATE;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2303 2304 2305 2306 2307 2308 2309 2310

		/* workaround for M-Audio Audiophile USB */
		if (dev->descriptor.idVendor == 0x0763 &&
		    dev->descriptor.idProduct == 0x2003) {
			/* doesn't set the sample rate attribute, but supports it */
			fp->attributes |= EP_CS_ATTR_SAMPLE_RATE;
		}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
		/*
		 * plantronics headset and Griffin iMic have set adaptive-in
		 * although it's really not...
		 */
		if ((dev->descriptor.idVendor == 0x047f &&
		     dev->descriptor.idProduct == 0x0ca1) ||
		    /* Griffin iMic (note that there is an older model 77d:223) */
		    (dev->descriptor.idVendor == 0x077d &&
		     dev->descriptor.idProduct == 0x07af)) {
			fp->ep_attr &= ~EP_ATTR_MASK;
			if (stream == SNDRV_PCM_STREAM_PLAYBACK)
				fp->ep_attr |= EP_ATTR_ADAPTIVE;
			else
				fp->ep_attr |= EP_ATTR_SYNC;
		}

		/* ok, let's parse further... */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2328 2329 2330 2331 2332
		if (parse_audio_format(dev, fp, format, fmt, stream) < 0) {
			if (fp->rate_table)
				kfree(fp->rate_table);
			kfree(fp);
			continue;
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
		}

		snd_printdd(KERN_INFO "%d:%u:%d: add audio endpoint 0x%x\n", dev->devnum, iface_no, i, fp->endpoint);
		err = add_audio_endpoint(chip, stream, fp);
		if (err < 0) {
			if (fp->rate_table)
				kfree(fp->rate_table);
			kfree(fp);
			return err;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2343 2344 2345 2346
		/* try to set the interface... */
		usb_set_interface(chip->dev, iface_no, i);
		init_usb_pitch(chip->dev, iface_no, alts, fp);
		init_usb_sample_rate(chip->dev, iface_no, alts, fp, fp->rate_max);
2347 2348 2349 2350 2351
	}
	return 0;
}


Jaroslav Kysela's avatar
Jaroslav Kysela committed
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
/*
 * disconnect streams
 * called from snd_usb_audio_disconnect()
 */
static void snd_usb_stream_disconnect(struct list_head *head, struct usb_driver *driver)
{
	int idx;
	snd_usb_stream_t *as;
	snd_usb_substream_t *subs;
	struct list_head *p;

	as = list_entry(head, snd_usb_stream_t, list);
	for (idx = 0; idx < 2; idx++) {
		subs = &as->substream[idx];
		if (!subs->num_formats)
			return;
		release_substream_urbs(subs, 1);
		subs->interface = -1;
		/* release interfaces */
		list_for_each(p, &subs->fmt_list) {
			struct audioformat *fp = list_entry(p, struct audioformat, list);
			usb_driver_release_interface(driver, usb_ifnum_to_if(subs->dev, fp->iface));
		}
	}
}

2378
/*
2379
 * parse audio control descriptor and create pcm/midi streams
2380
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2381
static int snd_usb_create_streams(snd_usb_audio_t *chip, int ctrlif)
2382 2383
{
	struct usb_device *dev = chip->dev;
2384
	struct usb_host_config *config;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2385
	struct usb_host_interface *host_iface;
2386 2387
	struct usb_interface *iface;
	unsigned char *p1;
2388
	int i, j;
2389 2390

	/* find audiocontrol interface */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2391
	config = dev->actconfig;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2392
	host_iface = &get_iface(config, ctrlif)->altsetting[0];
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2393
	if (!(p1 = snd_usb_find_csint_desc(host_iface->extra, host_iface->extralen, NULL, HEADER))) {
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
		snd_printk(KERN_ERR "cannot find HEADER\n");
		return -EINVAL;
	}
	if (! p1[7] || p1[0] < 8 + p1[7]) {
		snd_printk(KERN_ERR "invalid HEADER\n");
		return -EINVAL;
	}

	/*
	 * parse all USB audio streaming interfaces
	 */
	for (i = 0; i < p1[7]; i++) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2406 2407
		struct usb_host_interface *alts;
		struct usb_interface_descriptor *altsd;
2408
		j = p1[8 + i];
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2409
		if (j >= get_cfg_desc(config)->bNumInterfaces) {
2410 2411 2412 2413
			snd_printk(KERN_ERR "%d:%u:%d : does not exist\n",
				   dev->devnum, ctrlif, j);
			continue;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2414
		iface = get_iface(config, j);
2415 2416 2417 2418
		if (usb_interface_claimed(iface)) {
			snd_printdd(KERN_INFO "%d:%d:%d: skipping, already claimed\n", dev->devnum, ctrlif, j);
			continue;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2419 2420
		alts = &iface->altsetting[0];
		altsd = get_iface_desc(alts);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2421 2422
		if ((altsd->bInterfaceClass == USB_CLASS_AUDIO ||
		     altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC) &&
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2423
		    altsd->bInterfaceSubClass == USB_SUBCLASS_MIDI_STREAMING) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2424
			if (snd_usb_create_midi_interface(chip, iface, NULL) < 0) {
2425 2426 2427
				snd_printk(KERN_ERR "%d:%u:%d: cannot create sequencer device\n", dev->devnum, ctrlif, j);
				continue;
			}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2428
			usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
2429 2430
			continue;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2431 2432
		if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
		     altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2433 2434
		    altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIO_STREAMING) {
			snd_printdd(KERN_ERR "%d:%u:%d: skipping non-supported interface %d\n", dev->devnum, ctrlif, j, altsd->bInterfaceClass);
2435 2436 2437
			/* skip non-supported classes */
			continue;
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2438
		if (! parse_audio_endpoints(chip, j)) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2439
			usb_set_interface(dev, j, 0); /* reset the current interface */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2440
			usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2441
		}
2442 2443 2444 2445 2446
	}

	return 0;
}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2447 2448 2449 2450 2451 2452
/*
 * create a stream for an endpoint/altsetting without proper descriptors
 */
static int create_fixed_stream_quirk(snd_usb_audio_t *chip,
				     struct usb_interface *iface,
				     const snd_usb_audio_quirk_t *quirk)
2453
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2454
	struct audioformat *fp;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2455 2456
	struct usb_host_interface *alts;
	int stream, err;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2457 2458 2459 2460 2461 2462

	fp = kmalloc(sizeof(*fp), GFP_KERNEL);
	if (! fp) {
		snd_printk(KERN_ERR "cannot malloc\n");
		return -ENOMEM;
	}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2463 2464 2465 2466
	memcpy(fp, quirk->data, sizeof(*fp));
	stream = (fp->endpoint & USB_DIR_IN)
		? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
	err = add_audio_endpoint(chip, stream, fp);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2467 2468 2469 2470
	if (err < 0) {
		kfree(fp);
		return err;
	}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2471 2472 2473 2474
	alts = &iface->altsetting[fp->altset_idx];
	usb_set_interface(chip->dev, fp->iface, 0);
	init_usb_pitch(chip->dev, fp->iface, alts, fp);
	init_usb_sample_rate(chip->dev, fp->iface, alts, fp, fp->rate_max);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2475 2476 2477
	return 0;
}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2478 2479 2480 2481
/*
 * create a stream for an interface with proper descriptors
 */
static int create_standard_interface_quirk(snd_usb_audio_t *chip,
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2482 2483
					   struct usb_interface *iface,
					   const snd_usb_audio_quirk_t *quirk)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2484 2485 2486 2487 2488 2489 2490
{
	struct usb_host_interface *alts;
	struct usb_interface_descriptor *altsd;
	int err;

	alts = &iface->altsetting[0];
	altsd = get_iface_desc(alts);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2491 2492
	switch (quirk->type) {
	case QUIRK_AUDIO_STANDARD_INTERFACE:
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2493 2494 2495 2496
		err = parse_audio_endpoints(chip, altsd->bInterfaceNumber);
		if (!err)
			usb_set_interface(chip->dev, altsd->bInterfaceNumber, 0); /* reset the current interface */
		break;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2497
	case QUIRK_MIDI_STANDARD_INTERFACE:
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2498 2499 2500
		err = snd_usb_create_midi_interface(chip, iface, NULL);
		break;
	default:
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2501 2502
		snd_printd(KERN_ERR "invalid quirk type %d\n", quirk->type);
		return -ENXIO;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2503 2504 2505 2506 2507 2508 2509 2510 2511
	}
	if (err < 0) {
		snd_printk(KERN_ERR "cannot setup if %d: error %d\n",
			   altsd->bInterfaceNumber, err);
		return err;
	}
	return 0;
}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
static int snd_usb_create_quirk(snd_usb_audio_t *chip,
				struct usb_interface *iface,
				const snd_usb_audio_quirk_t *quirk);

/*
 * handle the quirks for the contained interfaces
 */
static int create_composite_quirk(snd_usb_audio_t *chip,
				  struct usb_interface *iface,
				  const snd_usb_audio_quirk_t *quirk)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2522
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2523
	struct usb_host_config *config = chip->dev->actconfig;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2524
	int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2525 2526
	int err;

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2527
	for (quirk = quirk->data; quirk->ifnum >= 0; ++quirk) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2528
		if (quirk->ifnum >= get_cfg_desc(config)->bNumInterfaces)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2529
			continue;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2530
		iface = get_iface(config, quirk->ifnum);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2531 2532 2533 2534 2535
		if (quirk->ifnum != probed_ifnum &&
		    usb_interface_claimed(iface))
			continue;
		err = snd_usb_create_quirk(chip, iface, quirk);
		if (err < 0)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2536
			return err;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2537
		if (quirk->ifnum != probed_ifnum)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2538
			usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2539 2540 2541 2542
	}
	return 0;
}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2543 2544 2545 2546 2547 2548 2549 2550

/*
 * boot quirks
 */

#define EXTIGY_FIRMWARE_SIZE_OLD 794
#define EXTIGY_FIRMWARE_SIZE_NEW 483

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2551
static int snd_usb_extigy_boot_quirk(struct usb_device *dev, struct usb_interface *intf)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2552 2553
{
	struct usb_host_config *config = dev->actconfig;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2554
	int err;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2555

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
	if (get_cfg_desc(config)->wTotalLength == EXTIGY_FIRMWARE_SIZE_OLD ||
	    get_cfg_desc(config)->wTotalLength == EXTIGY_FIRMWARE_SIZE_NEW) {
		snd_printdd("sending Extigy boot sequence...\n");
		/* Send message to force it to reconnect with full interface. */
		err = usb_control_msg(dev, usb_sndctrlpipe(dev,0),
				      0x10, 0x43, 0x0001, 0x000a, NULL, 0, HZ);
		if (err < 0) snd_printdd("error sending boot message: %d\n", err);
		err = usb_get_device_descriptor(dev);
		config = dev->actconfig;
		if (err < 0) snd_printdd("error usb_get_device_descriptor: %d\n", err);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2566 2567
		err = usb_reset_configuration(dev);
		if (err < 0) snd_printdd("error usb_reset_configuration: %d\n", err);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2568 2569
		snd_printdd("extigy_boot: new boot length = %d\n", get_cfg_desc(config)->wTotalLength);
		return -ENODEV; /* quit this anyway */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2570 2571 2572 2573 2574 2575 2576
	}
	return 0;
}


/*
 * audio-interface quirks
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2577 2578 2579 2580 2581
 *
 * returns zero if no standard audio/MIDI parsing is needed.
 * returns a postive value if standard audio/midi interfaces are parsed
 * after this.
 * returns a negative value at error.
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2582
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2583 2584 2585 2586 2587 2588 2589 2590 2591
static int snd_usb_create_quirk(snd_usb_audio_t *chip,
				struct usb_interface *iface,
				const snd_usb_audio_quirk_t *quirk)
{
	switch (quirk->type) {
	case QUIRK_MIDI_FIXED_ENDPOINT:
	case QUIRK_MIDI_YAMAHA:
	case QUIRK_MIDI_MIDIMAN:
		return snd_usb_create_midi_interface(chip, iface, quirk);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2592 2593 2594 2595
	case QUIRK_COMPOSITE:
		return create_composite_quirk(chip, iface, quirk);
	case QUIRK_AUDIO_FIXED_ENDPOINT:
		return create_fixed_stream_quirk(chip, iface, quirk);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2596 2597 2598
	case QUIRK_AUDIO_STANDARD_INTERFACE:
	case QUIRK_MIDI_STANDARD_INTERFACE:
		return create_standard_interface_quirk(chip, iface, quirk);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2599 2600 2601 2602
	default:
		snd_printd(KERN_ERR "invalid quirk type %d\n", quirk->type);
		return -ENXIO;
	}
2603 2604
}

2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631

/*
 * free the chip instance
 *
 * here we have to do not much, since pcm and controls are already freed
 *
 */

static int snd_usb_audio_free(snd_usb_audio_t *chip)
{
	down(&register_mutex);
	usb_chip[chip->index] = NULL;
	up(&register_mutex);
	snd_magic_kfree(chip);
	return 0;
}

static int snd_usb_audio_dev_free(snd_device_t *device)
{
	snd_usb_audio_t *chip = snd_magic_cast(snd_usb_audio_t, device->device_data, return -ENXIO);
	return snd_usb_audio_free(chip);
}


/*
 * create a chip instance and set its names.
 */
2632 2633 2634
static int snd_usb_audio_create(snd_card_t *card, struct usb_device *dev,
				const snd_usb_audio_quirk_t *quirk,
				snd_usb_audio_t **rchip)
2635 2636 2637 2638
{
	snd_usb_audio_t *chip;
	int err, len;
	static snd_device_ops_t ops = {
2639
		.dev_free =	snd_usb_audio_dev_free,
2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
	};
	
	*rchip = NULL;
	chip = snd_magic_kcalloc(snd_usb_audio_t, 0, GFP_KERNEL);
	if (! chip)
		return -ENOMEM;

	chip->dev = dev;
	chip->card = card;
	INIT_LIST_HEAD(&chip->pcm_list);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2650
	INIT_LIST_HEAD(&chip->midi_list);
2651 2652 2653 2654 2655 2656 2657

	if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
		snd_usb_audio_free(chip);
		return err;
	}

	strcpy(card->driver, "USB-Audio");
2658 2659 2660 2661 2662 2663 2664 2665 2666

	/* retrieve the device string as shortname */
	if (dev->descriptor.iProduct)
		len = usb_string(dev, dev->descriptor.iProduct,
				 card->shortname, sizeof(card->shortname));
	else
		len = 0;
	if (len <= 0) {
 		if (quirk && quirk->product_name) {
2667
			strlcpy(card->shortname, quirk->product_name, sizeof(card->shortname));
2668 2669 2670 2671 2672
		} else {
			sprintf(card->shortname, "USB Device %#04x:%#04x",
				dev->descriptor.idVendor, dev->descriptor.idProduct);
		}
	}
2673 2674

	/* retrieve the vendor and device strings as longname */
2675 2676
	if (dev->descriptor.iManufacturer)
		len = usb_string(dev, dev->descriptor.iManufacturer,
2677
				 card->longname, sizeof(card->longname));
2678
	else
2679
		len = 0;
2680 2681
	if (len <= 0) {
		if (quirk && quirk->vendor_name) {
2682
			len = strlcpy(card->longname, quirk->vendor_name, sizeof(card->longname));
2683 2684 2685 2686
		} else {
			len = 0;
		}
	}
2687
	if (len > 0)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2688
		strlcat(card->longname, " ", sizeof(card->longname));
2689 2690 2691

	len = strlen(card->longname);

2692 2693 2694 2695
	if ((!dev->descriptor.iProduct
	     || usb_string(dev, dev->descriptor.iProduct,
			   card->longname + len, sizeof(card->longname) - len) <= 0)
	    && quirk && quirk->product_name) {
2696
		strlcat(card->longname, quirk->product_name, sizeof(card->longname));
2697
	}
2698 2699 2700 2701

	len = strlcat(card->longname, " at ", sizeof(card->longname));

	if (len < sizeof(card->longname))
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2702
		usb_make_path(dev, card->longname + len, sizeof(card->longname) - len);
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718

	*rchip = chip;
	return 0;
}


/*
 * probe the active usb device
 *
 * note that this can be called multiple times per a device, when it
 * includes multiple audio control interfaces.
 *
 * thus we check the usb device pointer and creates the card instance
 * only at the first time.  the successive calls of this function will
 * append the pcm interface to the corresponding card.
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2719 2720
static void *snd_usb_audio_probe(struct usb_device *dev,
				 struct usb_interface *intf,
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2721
				 const struct usb_device_id *usb_id)
2722
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2723
	struct usb_host_config *config = dev->actconfig;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2724
	const snd_usb_audio_quirk_t *quirk = (const snd_usb_audio_quirk_t *)usb_id->driver_info;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2725
	int i, err;
2726 2727
	snd_card_t *card;
	snd_usb_audio_t *chip;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2728 2729 2730 2731 2732
	struct usb_host_interface *alts;
	int ifnum;

	alts = &intf->altsetting[0];
	ifnum = get_iface_desc(alts)->bInterfaceNumber;
2733

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2734
	if (quirk && quirk->ifnum != QUIRK_ANY_INTERFACE && ifnum != quirk->ifnum)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2735
		goto __err_val;
2736

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2737 2738 2739 2740
	/* SB Extigy needs special boot-up sequence */
	/* if more models come, this will go to the quirk list. */
	if (dev->descriptor.idVendor == 0x041e && dev->descriptor.idProduct == 0x3000) {
		if (snd_usb_extigy_boot_quirk(dev, intf) < 0)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2741
			goto __err_val;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2742
		config = dev->actconfig;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2743 2744
	}

2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
	/*
	 * found a config.  now register to ALSA
	 */

	/* check whether it's already registered */
	chip = NULL;
	down(&register_mutex);
	for (i = 0; i < SNDRV_CARDS; i++) {
		if (usb_chip[i] && usb_chip[i]->dev == dev) {
			chip = usb_chip[i];
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2755 2756 2757 2758
			if (chip->shutdown) {
				snd_printk(KERN_ERR "USB device is in the shutdown state, cannot create a card instance\n");
				goto __error;
			}
2759 2760 2761 2762 2763 2764 2765
			break;
		}
	}
	if (! chip) {
		/* it's a fresh one.
		 * now look for an empty slot and create a new card instance
		 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2766
		/* first, set the current configuration for this device */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2767 2768
		if (usb_reset_configuration(dev) < 0) {
			snd_printk(KERN_ERR "cannot reset configuration (value 0x%x)\n", get_cfg_desc(config)->bConfigurationValue);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2769 2770
			goto __error;
		}
2771
		for (i = 0; i < SNDRV_CARDS; i++)
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2772 2773 2774 2775
			if (enable[i] && ! usb_chip[i] &&
			    (vid[i] == -1 || vid[i] == dev->descriptor.idVendor) &&
			    (pid[i] == -1 || pid[i] == dev->descriptor.idProduct)) {
				card = snd_card_new(index[i], id[i], THIS_MODULE, 0);
2776 2777 2778 2779
				if (card == NULL) {
					snd_printk(KERN_ERR "cannot create a card instance %d\n", i);
					goto __error;
				}
2780
				if (snd_usb_audio_create(card, dev, quirk, &chip) < 0) {
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
					snd_card_free(card);
					goto __error;
				}
				chip->index = i;
				usb_chip[i] = chip;
				break;
			}
		if (! chip) {
			snd_printk(KERN_ERR "no available usb audio device\n");
			goto __error;
		}
	}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2794 2795 2796 2797 2798 2799 2800 2801 2802
	err = 1; /* continue */
	if (quirk) {
		/* need some special handlings */
		if ((err = snd_usb_create_quirk(chip, intf, quirk)) < 0)
			goto __error;
	}

	if (err > 0) {
		/* create normal USB audio interfaces */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2803 2804
		if (snd_usb_create_streams(chip, ifnum) < 0 ||
		    snd_usb_create_mixer(chip, ifnum) < 0) {
2805
			goto __error;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2806
		}
2807
	}
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821

	/* we are allowed to call snd_card_register() many times */
	if (snd_card_register(chip->card) < 0) {
		if (! chip->num_interfaces)
			snd_card_free(chip->card);
		goto __error;
	}

	chip->num_interfaces++;
	up(&register_mutex);
	return chip;

 __error:
	up(&register_mutex);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2822
 __err_val:
2823 2824 2825 2826 2827 2828 2829
	return NULL;
}

/*
 * we need to take care of counter, since disconnection can be called also
 * many times as well as usb_audio_probe(). 
 */
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2830
static void snd_usb_audio_disconnect(struct usb_device *dev, void *ptr)
2831 2832
{
	snd_usb_audio_t *chip;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2833 2834
	snd_card_t *card;
	struct list_head *p;
2835

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2836
	if (ptr == (void *)-1L)
2837 2838 2839
		return;

	chip = snd_magic_cast(snd_usb_audio_t, ptr, return);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2840 2841 2842
	card = chip->card;
	down(&register_mutex);
	chip->shutdown = 1;
2843
	chip->num_interfaces--;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2844
	if (chip->num_interfaces <= 0) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2845
		snd_card_disconnect(card);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2846 2847
		/* release the pcm resources */
		list_for_each(p, &chip->pcm_list) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2848
			snd_usb_stream_disconnect(p, &usb_audio_driver);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2849
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2850 2851
		/* release the midi resources */
		list_for_each(p, &chip->midi_list) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2852
			snd_usbmidi_disconnect(p, &usb_audio_driver);
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2853
		}
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2854 2855 2856 2857 2858
		up(&register_mutex);
		snd_card_free_in_thread(card);
	} else {
		up(&register_mutex);
	}
2859 2860
}

Jaroslav Kysela's avatar
Jaroslav Kysela committed
2861 2862 2863
/*
 * new 2.5 USB kernel API
 */
Jaroslav Kysela's avatar
ALSA  
Jaroslav Kysela committed
2864 2865 2866 2867
static int usb_audio_probe(struct usb_interface *intf,
			   const struct usb_device_id *id)
{
	void *chip;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2868
	chip = snd_usb_audio_probe(interface_to_usbdev(intf), intf, id);
Jaroslav Kysela's avatar
ALSA  
Jaroslav Kysela committed
2869
	if (chip) {
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2870
		dev_set_drvdata(&intf->dev, chip);
Jaroslav Kysela's avatar
ALSA  
Jaroslav Kysela committed
2871 2872 2873 2874 2875 2876 2877
		return 0;
	} else
		return -EIO;
}

static void usb_audio_disconnect(struct usb_interface *intf)
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2878
	snd_usb_audio_disconnect(interface_to_usbdev(intf),
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2879
				 dev_get_drvdata(&intf->dev));
Jaroslav Kysela's avatar
ALSA  
Jaroslav Kysela committed
2880 2881 2882
}


2883 2884
static int __init snd_usb_audio_init(void)
{
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2885 2886 2887 2888
	if (nrpacks < 2 || nrpacks > MAX_PACKS) {
		printk(KERN_WARNING "invalid nrpacks value.\n");
		return -EINVAL;
	}
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
	usb_register(&usb_audio_driver);
	return 0;
}


static void __exit snd_usb_audio_cleanup(void)
{
	usb_deregister(&usb_audio_driver);
}

module_init(snd_usb_audio_init);
module_exit(snd_usb_audio_cleanup);

#ifndef MODULE
/*
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2904
 * format is snd-usb-audio=enable,index,id,vid,pid
2905 2906 2907 2908 2909 2910 2911
 */
static int __init snd_usb_audio_module_setup(char* str)
{
	static unsigned __initdata nr_dev = 0;

	if (nr_dev >= SNDRV_CARDS)
		return 0;
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2912 2913
	(void)(get_option(&str, &enable[nr_dev]) == 2 &&
	       get_option(&str, &index[nr_dev]) == 2 &&
Jaroslav Kysela's avatar
Jaroslav Kysela committed
2914 2915 2916
	       get_id(&str, &id[nr_dev]) == 2 &&
	       get_option(&str, &vid[nr_dev]) == 2 &&
	       get_option(&str, &pid[nr_dev]) == 2);
2917 2918 2919 2920 2921 2922 2923
	++nr_dev;
	return 1;
}

__setup("snd-usb-audio=", snd_usb_audio_module_setup);

#endif /* !MODULE */