1 /*
2  * Edirol UA-101/UA-1000 driver
3  * Copyright (c) Clemens Ladisch <clemens@ladisch.de>
4  *
5  * This driver is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License, version 2.
7  *
8  * This driver is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this driver.  If not, see <http://www.gnu.org/licenses/>.
15  */
16 
17 #include <linux/init.h>
18 #include <linux/module.h>
19 #include <linux/slab.h>
20 #include <linux/usb.h>
21 #include <linux/usb/audio.h>
22 #include <sound/core.h>
23 #include <sound/initval.h>
24 #include <sound/pcm.h>
25 #include <sound/pcm_params.h>
26 #include "../usbaudio.h"
27 #include "../midi.h"
28 
29 MODULE_DESCRIPTION("Edirol UA-101/1000 driver");
30 MODULE_AUTHOR("Clemens Ladisch <clemens@ladisch.de>");
31 MODULE_LICENSE("GPL v2");
32 MODULE_SUPPORTED_DEVICE("{{Edirol,UA-101},{Edirol,UA-1000}}");
33 
34 /*
35  * Should not be lower than the minimum scheduling delay of the host
36  * controller.  Some Intel controllers need more than one frame; as long as
37  * that driver doesn't tell us about this, use 1.5 frames just to be sure.
38  */
39 #define MIN_QUEUE_LENGTH	12
40 /* Somewhat random. */
41 #define MAX_QUEUE_LENGTH	30
42 /*
43  * This magic value optimizes memory usage efficiency for the UA-101's packet
44  * sizes at all sample rates, taking into account the stupid cache pool sizes
45  * that usb_alloc_coherent() uses.
46  */
47 #define DEFAULT_QUEUE_LENGTH	21
48 
49 #define MAX_PACKET_SIZE		672 /* hardware specific */
50 #define MAX_MEMORY_BUFFERS	DIV_ROUND_UP(MAX_QUEUE_LENGTH, \
51 					     PAGE_SIZE / MAX_PACKET_SIZE)
52 
53 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
54 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
55 static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
56 static unsigned int queue_length = 21;
57 
58 module_param_array(index, int, NULL, 0444);
59 MODULE_PARM_DESC(index, "card index");
60 module_param_array(id, charp, NULL, 0444);
61 MODULE_PARM_DESC(id, "ID string");
62 module_param_array(enable, bool, NULL, 0444);
63 MODULE_PARM_DESC(enable, "enable card");
64 module_param(queue_length, uint, 0644);
65 MODULE_PARM_DESC(queue_length, "USB queue length in microframes, "
66 		 __stringify(MIN_QUEUE_LENGTH)"-"__stringify(MAX_QUEUE_LENGTH));
67 
68 enum {
69 	INTF_PLAYBACK,
70 	INTF_CAPTURE,
71 	INTF_MIDI,
72 
73 	INTF_COUNT
74 };
75 
76 /* bits in struct ua101::states */
77 enum {
78 	USB_CAPTURE_RUNNING,
79 	USB_PLAYBACK_RUNNING,
80 	ALSA_CAPTURE_OPEN,
81 	ALSA_PLAYBACK_OPEN,
82 	ALSA_CAPTURE_RUNNING,
83 	ALSA_PLAYBACK_RUNNING,
84 	CAPTURE_URB_COMPLETED,
85 	PLAYBACK_URB_COMPLETED,
86 	DISCONNECTED,
87 };
88 
89 struct ua101 {
90 	struct usb_device *dev;
91 	struct snd_card *card;
92 	struct usb_interface *intf[INTF_COUNT];
93 	int card_index;
94 	struct snd_pcm *pcm;
95 	struct list_head midi_list;
96 	u64 format_bit;
97 	unsigned int rate;
98 	unsigned int packets_per_second;
99 	spinlock_t lock;
100 	struct mutex mutex;
101 	unsigned long states;
102 
103 	/* FIFO to synchronize playback rate to capture rate */
104 	unsigned int rate_feedback_start;
105 	unsigned int rate_feedback_count;
106 	u8 rate_feedback[MAX_QUEUE_LENGTH];
107 
108 	struct list_head ready_playback_urbs;
109 	struct tasklet_struct playback_tasklet;
110 	wait_queue_head_t alsa_capture_wait;
111 	wait_queue_head_t rate_feedback_wait;
112 	wait_queue_head_t alsa_playback_wait;
113 	struct ua101_stream {
114 		struct snd_pcm_substream *substream;
115 		unsigned int usb_pipe;
116 		unsigned int channels;
117 		unsigned int frame_bytes;
118 		unsigned int max_packet_bytes;
119 		unsigned int period_pos;
120 		unsigned int buffer_pos;
121 		unsigned int queue_length;
122 		struct ua101_urb {
123 			struct urb urb;
124 			struct usb_iso_packet_descriptor iso_frame_desc[1];
125 			struct list_head ready_list;
126 		} *urbs[MAX_QUEUE_LENGTH];
127 		struct {
128 			unsigned int size;
129 			void *addr;
130 			dma_addr_t dma;
131 		} buffers[MAX_MEMORY_BUFFERS];
132 	} capture, playback;
133 };
134 
135 static DEFINE_MUTEX(devices_mutex);
136 static unsigned int devices_used;
137 static struct usb_driver ua101_driver;
138 
139 static void abort_alsa_playback(struct ua101 *ua);
140 static void abort_alsa_capture(struct ua101 *ua);
141 
usb_error_string(int err)142 static const char *usb_error_string(int err)
143 {
144 	switch (err) {
145 	case -ENODEV:
146 		return "no device";
147 	case -ENOENT:
148 		return "endpoint not enabled";
149 	case -EPIPE:
150 		return "endpoint stalled";
151 	case -ENOSPC:
152 		return "not enough bandwidth";
153 	case -ESHUTDOWN:
154 		return "device disabled";
155 	case -EHOSTUNREACH:
156 		return "device suspended";
157 	case -EINVAL:
158 	case -EAGAIN:
159 	case -EFBIG:
160 	case -EMSGSIZE:
161 		return "internal error";
162 	default:
163 		return "unknown error";
164 	}
165 }
166 
abort_usb_capture(struct ua101 * ua)167 static void abort_usb_capture(struct ua101 *ua)
168 {
169 	if (test_and_clear_bit(USB_CAPTURE_RUNNING, &ua->states)) {
170 		wake_up(&ua->alsa_capture_wait);
171 		wake_up(&ua->rate_feedback_wait);
172 	}
173 }
174 
abort_usb_playback(struct ua101 * ua)175 static void abort_usb_playback(struct ua101 *ua)
176 {
177 	if (test_and_clear_bit(USB_PLAYBACK_RUNNING, &ua->states))
178 		wake_up(&ua->alsa_playback_wait);
179 }
180 
playback_urb_complete(struct urb * usb_urb)181 static void playback_urb_complete(struct urb *usb_urb)
182 {
183 	struct ua101_urb *urb = (struct ua101_urb *)usb_urb;
184 	struct ua101 *ua = urb->urb.context;
185 	unsigned long flags;
186 
187 	if (unlikely(urb->urb.status == -ENOENT ||	/* unlinked */
188 		     urb->urb.status == -ENODEV ||	/* device removed */
189 		     urb->urb.status == -ECONNRESET ||	/* unlinked */
190 		     urb->urb.status == -ESHUTDOWN)) {	/* device disabled */
191 		abort_usb_playback(ua);
192 		abort_alsa_playback(ua);
193 		return;
194 	}
195 
196 	if (test_bit(USB_PLAYBACK_RUNNING, &ua->states)) {
197 		/* append URB to FIFO */
198 		spin_lock_irqsave(&ua->lock, flags);
199 		list_add_tail(&urb->ready_list, &ua->ready_playback_urbs);
200 		if (ua->rate_feedback_count > 0)
201 			tasklet_schedule(&ua->playback_tasklet);
202 		ua->playback.substream->runtime->delay -=
203 				urb->urb.iso_frame_desc[0].length /
204 						ua->playback.frame_bytes;
205 		spin_unlock_irqrestore(&ua->lock, flags);
206 	}
207 }
208 
first_playback_urb_complete(struct urb * urb)209 static void first_playback_urb_complete(struct urb *urb)
210 {
211 	struct ua101 *ua = urb->context;
212 
213 	urb->complete = playback_urb_complete;
214 	playback_urb_complete(urb);
215 
216 	set_bit(PLAYBACK_URB_COMPLETED, &ua->states);
217 	wake_up(&ua->alsa_playback_wait);
218 }
219 
220 /* copy data from the ALSA ring buffer into the URB buffer */
copy_playback_data(struct ua101_stream * stream,struct urb * urb,unsigned int frames)221 static bool copy_playback_data(struct ua101_stream *stream, struct urb *urb,
222 			       unsigned int frames)
223 {
224 	struct snd_pcm_runtime *runtime;
225 	unsigned int frame_bytes, frames1;
226 	const u8 *source;
227 
228 	runtime = stream->substream->runtime;
229 	frame_bytes = stream->frame_bytes;
230 	source = runtime->dma_area + stream->buffer_pos * frame_bytes;
231 	if (stream->buffer_pos + frames <= runtime->buffer_size) {
232 		memcpy(urb->transfer_buffer, source, frames * frame_bytes);
233 	} else {
234 		/* wrap around at end of ring buffer */
235 		frames1 = runtime->buffer_size - stream->buffer_pos;
236 		memcpy(urb->transfer_buffer, source, frames1 * frame_bytes);
237 		memcpy(urb->transfer_buffer + frames1 * frame_bytes,
238 		       runtime->dma_area, (frames - frames1) * frame_bytes);
239 	}
240 
241 	stream->buffer_pos += frames;
242 	if (stream->buffer_pos >= runtime->buffer_size)
243 		stream->buffer_pos -= runtime->buffer_size;
244 	stream->period_pos += frames;
245 	if (stream->period_pos >= runtime->period_size) {
246 		stream->period_pos -= runtime->period_size;
247 		return true;
248 	}
249 	return false;
250 }
251 
add_with_wraparound(struct ua101 * ua,unsigned int * value,unsigned int add)252 static inline void add_with_wraparound(struct ua101 *ua,
253 				       unsigned int *value, unsigned int add)
254 {
255 	*value += add;
256 	if (*value >= ua->playback.queue_length)
257 		*value -= ua->playback.queue_length;
258 }
259 
playback_tasklet(unsigned long data)260 static void playback_tasklet(unsigned long data)
261 {
262 	struct ua101 *ua = (void *)data;
263 	unsigned long flags;
264 	unsigned int frames;
265 	struct ua101_urb *urb;
266 	bool do_period_elapsed = false;
267 	int err;
268 
269 	if (unlikely(!test_bit(USB_PLAYBACK_RUNNING, &ua->states)))
270 		return;
271 
272 	/*
273 	 * Synchronizing the playback rate to the capture rate is done by using
274 	 * the same sequence of packet sizes for both streams.
275 	 * Submitting a playback URB therefore requires both a ready URB and
276 	 * the size of the corresponding capture packet, i.e., both playback
277 	 * and capture URBs must have been completed.  Since the USB core does
278 	 * not guarantee that playback and capture complete callbacks are
279 	 * called alternately, we use two FIFOs for packet sizes and read URBs;
280 	 * submitting playback URBs is possible as long as both FIFOs are
281 	 * nonempty.
282 	 */
283 	spin_lock_irqsave(&ua->lock, flags);
284 	while (ua->rate_feedback_count > 0 &&
285 	       !list_empty(&ua->ready_playback_urbs)) {
286 		/* take packet size out of FIFO */
287 		frames = ua->rate_feedback[ua->rate_feedback_start];
288 		add_with_wraparound(ua, &ua->rate_feedback_start, 1);
289 		ua->rate_feedback_count--;
290 
291 		/* take URB out of FIFO */
292 		urb = list_first_entry(&ua->ready_playback_urbs,
293 				       struct ua101_urb, ready_list);
294 		list_del(&urb->ready_list);
295 
296 		/* fill packet with data or silence */
297 		urb->urb.iso_frame_desc[0].length =
298 			frames * ua->playback.frame_bytes;
299 		if (test_bit(ALSA_PLAYBACK_RUNNING, &ua->states))
300 			do_period_elapsed |= copy_playback_data(&ua->playback,
301 								&urb->urb,
302 								frames);
303 		else
304 			memset(urb->urb.transfer_buffer, 0,
305 			       urb->urb.iso_frame_desc[0].length);
306 
307 		/* and off you go ... */
308 		err = usb_submit_urb(&urb->urb, GFP_ATOMIC);
309 		if (unlikely(err < 0)) {
310 			spin_unlock_irqrestore(&ua->lock, flags);
311 			abort_usb_playback(ua);
312 			abort_alsa_playback(ua);
313 			dev_err(&ua->dev->dev, "USB request error %d: %s\n",
314 				err, usb_error_string(err));
315 			return;
316 		}
317 		ua->playback.substream->runtime->delay += frames;
318 	}
319 	spin_unlock_irqrestore(&ua->lock, flags);
320 	if (do_period_elapsed)
321 		snd_pcm_period_elapsed(ua->playback.substream);
322 }
323 
324 /* copy data from the URB buffer into the ALSA ring buffer */
copy_capture_data(struct ua101_stream * stream,struct urb * urb,unsigned int frames)325 static bool copy_capture_data(struct ua101_stream *stream, struct urb *urb,
326 			      unsigned int frames)
327 {
328 	struct snd_pcm_runtime *runtime;
329 	unsigned int frame_bytes, frames1;
330 	u8 *dest;
331 
332 	runtime = stream->substream->runtime;
333 	frame_bytes = stream->frame_bytes;
334 	dest = runtime->dma_area + stream->buffer_pos * frame_bytes;
335 	if (stream->buffer_pos + frames <= runtime->buffer_size) {
336 		memcpy(dest, urb->transfer_buffer, frames * frame_bytes);
337 	} else {
338 		/* wrap around at end of ring buffer */
339 		frames1 = runtime->buffer_size - stream->buffer_pos;
340 		memcpy(dest, urb->transfer_buffer, frames1 * frame_bytes);
341 		memcpy(runtime->dma_area,
342 		       urb->transfer_buffer + frames1 * frame_bytes,
343 		       (frames - frames1) * frame_bytes);
344 	}
345 
346 	stream->buffer_pos += frames;
347 	if (stream->buffer_pos >= runtime->buffer_size)
348 		stream->buffer_pos -= runtime->buffer_size;
349 	stream->period_pos += frames;
350 	if (stream->period_pos >= runtime->period_size) {
351 		stream->period_pos -= runtime->period_size;
352 		return true;
353 	}
354 	return false;
355 }
356 
capture_urb_complete(struct urb * urb)357 static void capture_urb_complete(struct urb *urb)
358 {
359 	struct ua101 *ua = urb->context;
360 	struct ua101_stream *stream = &ua->capture;
361 	unsigned long flags;
362 	unsigned int frames, write_ptr;
363 	bool do_period_elapsed;
364 	int err;
365 
366 	if (unlikely(urb->status == -ENOENT ||		/* unlinked */
367 		     urb->status == -ENODEV ||		/* device removed */
368 		     urb->status == -ECONNRESET ||	/* unlinked */
369 		     urb->status == -ESHUTDOWN))	/* device disabled */
370 		goto stream_stopped;
371 
372 	if (urb->status >= 0 && urb->iso_frame_desc[0].status >= 0)
373 		frames = urb->iso_frame_desc[0].actual_length /
374 			stream->frame_bytes;
375 	else
376 		frames = 0;
377 
378 	spin_lock_irqsave(&ua->lock, flags);
379 
380 	if (frames > 0 && test_bit(ALSA_CAPTURE_RUNNING, &ua->states))
381 		do_period_elapsed = copy_capture_data(stream, urb, frames);
382 	else
383 		do_period_elapsed = false;
384 
385 	if (test_bit(USB_CAPTURE_RUNNING, &ua->states)) {
386 		err = usb_submit_urb(urb, GFP_ATOMIC);
387 		if (unlikely(err < 0)) {
388 			spin_unlock_irqrestore(&ua->lock, flags);
389 			dev_err(&ua->dev->dev, "USB request error %d: %s\n",
390 				err, usb_error_string(err));
391 			goto stream_stopped;
392 		}
393 
394 		/* append packet size to FIFO */
395 		write_ptr = ua->rate_feedback_start;
396 		add_with_wraparound(ua, &write_ptr, ua->rate_feedback_count);
397 		ua->rate_feedback[write_ptr] = frames;
398 		if (ua->rate_feedback_count < ua->playback.queue_length) {
399 			ua->rate_feedback_count++;
400 			if (ua->rate_feedback_count ==
401 						ua->playback.queue_length)
402 				wake_up(&ua->rate_feedback_wait);
403 		} else {
404 			/*
405 			 * Ring buffer overflow; this happens when the playback
406 			 * stream is not running.  Throw away the oldest entry,
407 			 * so that the playback stream, when it starts, sees
408 			 * the most recent packet sizes.
409 			 */
410 			add_with_wraparound(ua, &ua->rate_feedback_start, 1);
411 		}
412 		if (test_bit(USB_PLAYBACK_RUNNING, &ua->states) &&
413 		    !list_empty(&ua->ready_playback_urbs))
414 			tasklet_schedule(&ua->playback_tasklet);
415 	}
416 
417 	spin_unlock_irqrestore(&ua->lock, flags);
418 
419 	if (do_period_elapsed)
420 		snd_pcm_period_elapsed(stream->substream);
421 
422 	return;
423 
424 stream_stopped:
425 	abort_usb_playback(ua);
426 	abort_usb_capture(ua);
427 	abort_alsa_playback(ua);
428 	abort_alsa_capture(ua);
429 }
430 
first_capture_urb_complete(struct urb * urb)431 static void first_capture_urb_complete(struct urb *urb)
432 {
433 	struct ua101 *ua = urb->context;
434 
435 	urb->complete = capture_urb_complete;
436 	capture_urb_complete(urb);
437 
438 	set_bit(CAPTURE_URB_COMPLETED, &ua->states);
439 	wake_up(&ua->alsa_capture_wait);
440 }
441 
submit_stream_urbs(struct ua101 * ua,struct ua101_stream * stream)442 static int submit_stream_urbs(struct ua101 *ua, struct ua101_stream *stream)
443 {
444 	unsigned int i;
445 
446 	for (i = 0; i < stream->queue_length; ++i) {
447 		int err = usb_submit_urb(&stream->urbs[i]->urb, GFP_KERNEL);
448 		if (err < 0) {
449 			dev_err(&ua->dev->dev, "USB request error %d: %s\n",
450 				err, usb_error_string(err));
451 			return err;
452 		}
453 	}
454 	return 0;
455 }
456 
kill_stream_urbs(struct ua101_stream * stream)457 static void kill_stream_urbs(struct ua101_stream *stream)
458 {
459 	unsigned int i;
460 
461 	for (i = 0; i < stream->queue_length; ++i)
462 		if (stream->urbs[i])
463 			usb_kill_urb(&stream->urbs[i]->urb);
464 }
465 
enable_iso_interface(struct ua101 * ua,unsigned int intf_index)466 static int enable_iso_interface(struct ua101 *ua, unsigned int intf_index)
467 {
468 	struct usb_host_interface *alts;
469 
470 	alts = ua->intf[intf_index]->cur_altsetting;
471 	if (alts->desc.bAlternateSetting != 1) {
472 		int err = usb_set_interface(ua->dev,
473 					    alts->desc.bInterfaceNumber, 1);
474 		if (err < 0) {
475 			dev_err(&ua->dev->dev,
476 				"cannot initialize interface; error %d: %s\n",
477 				err, usb_error_string(err));
478 			return err;
479 		}
480 	}
481 	return 0;
482 }
483 
disable_iso_interface(struct ua101 * ua,unsigned int intf_index)484 static void disable_iso_interface(struct ua101 *ua, unsigned int intf_index)
485 {
486 	struct usb_host_interface *alts;
487 
488 	if (!ua->intf[intf_index])
489 		return;
490 
491 	alts = ua->intf[intf_index]->cur_altsetting;
492 	if (alts->desc.bAlternateSetting != 0) {
493 		int err = usb_set_interface(ua->dev,
494 					    alts->desc.bInterfaceNumber, 0);
495 		if (err < 0 && !test_bit(DISCONNECTED, &ua->states))
496 			dev_warn(&ua->dev->dev,
497 				 "interface reset failed; error %d: %s\n",
498 				 err, usb_error_string(err));
499 	}
500 }
501 
stop_usb_capture(struct ua101 * ua)502 static void stop_usb_capture(struct ua101 *ua)
503 {
504 	clear_bit(USB_CAPTURE_RUNNING, &ua->states);
505 
506 	kill_stream_urbs(&ua->capture);
507 
508 	disable_iso_interface(ua, INTF_CAPTURE);
509 }
510 
start_usb_capture(struct ua101 * ua)511 static int start_usb_capture(struct ua101 *ua)
512 {
513 	int err;
514 
515 	if (test_bit(DISCONNECTED, &ua->states))
516 		return -ENODEV;
517 
518 	if (test_bit(USB_CAPTURE_RUNNING, &ua->states))
519 		return 0;
520 
521 	kill_stream_urbs(&ua->capture);
522 
523 	err = enable_iso_interface(ua, INTF_CAPTURE);
524 	if (err < 0)
525 		return err;
526 
527 	clear_bit(CAPTURE_URB_COMPLETED, &ua->states);
528 	ua->capture.urbs[0]->urb.complete = first_capture_urb_complete;
529 	ua->rate_feedback_start = 0;
530 	ua->rate_feedback_count = 0;
531 
532 	set_bit(USB_CAPTURE_RUNNING, &ua->states);
533 	err = submit_stream_urbs(ua, &ua->capture);
534 	if (err < 0)
535 		stop_usb_capture(ua);
536 	return err;
537 }
538 
stop_usb_playback(struct ua101 * ua)539 static void stop_usb_playback(struct ua101 *ua)
540 {
541 	clear_bit(USB_PLAYBACK_RUNNING, &ua->states);
542 
543 	kill_stream_urbs(&ua->playback);
544 
545 	tasklet_kill(&ua->playback_tasklet);
546 
547 	disable_iso_interface(ua, INTF_PLAYBACK);
548 }
549 
start_usb_playback(struct ua101 * ua)550 static int start_usb_playback(struct ua101 *ua)
551 {
552 	unsigned int i, frames;
553 	struct urb *urb;
554 	int err = 0;
555 
556 	if (test_bit(DISCONNECTED, &ua->states))
557 		return -ENODEV;
558 
559 	if (test_bit(USB_PLAYBACK_RUNNING, &ua->states))
560 		return 0;
561 
562 	kill_stream_urbs(&ua->playback);
563 	tasklet_kill(&ua->playback_tasklet);
564 
565 	err = enable_iso_interface(ua, INTF_PLAYBACK);
566 	if (err < 0)
567 		return err;
568 
569 	clear_bit(PLAYBACK_URB_COMPLETED, &ua->states);
570 	ua->playback.urbs[0]->urb.complete =
571 		first_playback_urb_complete;
572 	spin_lock_irq(&ua->lock);
573 	INIT_LIST_HEAD(&ua->ready_playback_urbs);
574 	spin_unlock_irq(&ua->lock);
575 
576 	/*
577 	 * We submit the initial URBs all at once, so we have to wait for the
578 	 * packet size FIFO to be full.
579 	 */
580 	wait_event(ua->rate_feedback_wait,
581 		   ua->rate_feedback_count >= ua->playback.queue_length ||
582 		   !test_bit(USB_CAPTURE_RUNNING, &ua->states) ||
583 		   test_bit(DISCONNECTED, &ua->states));
584 	if (test_bit(DISCONNECTED, &ua->states)) {
585 		stop_usb_playback(ua);
586 		return -ENODEV;
587 	}
588 	if (!test_bit(USB_CAPTURE_RUNNING, &ua->states)) {
589 		stop_usb_playback(ua);
590 		return -EIO;
591 	}
592 
593 	for (i = 0; i < ua->playback.queue_length; ++i) {
594 		/* all initial URBs contain silence */
595 		spin_lock_irq(&ua->lock);
596 		frames = ua->rate_feedback[ua->rate_feedback_start];
597 		add_with_wraparound(ua, &ua->rate_feedback_start, 1);
598 		ua->rate_feedback_count--;
599 		spin_unlock_irq(&ua->lock);
600 		urb = &ua->playback.urbs[i]->urb;
601 		urb->iso_frame_desc[0].length =
602 			frames * ua->playback.frame_bytes;
603 		memset(urb->transfer_buffer, 0,
604 		       urb->iso_frame_desc[0].length);
605 	}
606 
607 	set_bit(USB_PLAYBACK_RUNNING, &ua->states);
608 	err = submit_stream_urbs(ua, &ua->playback);
609 	if (err < 0)
610 		stop_usb_playback(ua);
611 	return err;
612 }
613 
abort_alsa_capture(struct ua101 * ua)614 static void abort_alsa_capture(struct ua101 *ua)
615 {
616 	unsigned long flags;
617 
618 	if (test_bit(ALSA_CAPTURE_RUNNING, &ua->states)) {
619 		snd_pcm_stream_lock_irqsave(ua->capture.substream, flags);
620 		snd_pcm_stop(ua->capture.substream, SNDRV_PCM_STATE_XRUN);
621 		snd_pcm_stream_unlock_irqrestore(ua->capture.substream, flags);
622 	}
623 }
624 
abort_alsa_playback(struct ua101 * ua)625 static void abort_alsa_playback(struct ua101 *ua)
626 {
627 	unsigned long flags;
628 
629 	if (test_bit(ALSA_PLAYBACK_RUNNING, &ua->states)) {
630 		snd_pcm_stream_lock_irqsave(ua->playback.substream, flags);
631 		snd_pcm_stop(ua->playback.substream, SNDRV_PCM_STATE_XRUN);
632 		snd_pcm_stream_unlock_irqrestore(ua->playback.substream, flags);
633 	}
634 }
635 
set_stream_hw(struct ua101 * ua,struct snd_pcm_substream * substream,unsigned int channels)636 static int set_stream_hw(struct ua101 *ua, struct snd_pcm_substream *substream,
637 			 unsigned int channels)
638 {
639 	int err;
640 
641 	substream->runtime->hw.info =
642 		SNDRV_PCM_INFO_MMAP |
643 		SNDRV_PCM_INFO_MMAP_VALID |
644 		SNDRV_PCM_INFO_BATCH |
645 		SNDRV_PCM_INFO_INTERLEAVED |
646 		SNDRV_PCM_INFO_BLOCK_TRANSFER |
647 		SNDRV_PCM_INFO_FIFO_IN_FRAMES;
648 	substream->runtime->hw.formats = ua->format_bit;
649 	substream->runtime->hw.rates = snd_pcm_rate_to_rate_bit(ua->rate);
650 	substream->runtime->hw.rate_min = ua->rate;
651 	substream->runtime->hw.rate_max = ua->rate;
652 	substream->runtime->hw.channels_min = channels;
653 	substream->runtime->hw.channels_max = channels;
654 	substream->runtime->hw.buffer_bytes_max = 45000 * 1024;
655 	substream->runtime->hw.period_bytes_min = 1;
656 	substream->runtime->hw.period_bytes_max = UINT_MAX;
657 	substream->runtime->hw.periods_min = 2;
658 	substream->runtime->hw.periods_max = UINT_MAX;
659 	err = snd_pcm_hw_constraint_minmax(substream->runtime,
660 					   SNDRV_PCM_HW_PARAM_PERIOD_TIME,
661 					   1500000 / ua->packets_per_second,
662 					   UINT_MAX);
663 	if (err < 0)
664 		return err;
665 	err = snd_pcm_hw_constraint_msbits(substream->runtime, 0, 32, 24);
666 	return err;
667 }
668 
capture_pcm_open(struct snd_pcm_substream * substream)669 static int capture_pcm_open(struct snd_pcm_substream *substream)
670 {
671 	struct ua101 *ua = substream->private_data;
672 	int err;
673 
674 	ua->capture.substream = substream;
675 	err = set_stream_hw(ua, substream, ua->capture.channels);
676 	if (err < 0)
677 		return err;
678 	substream->runtime->hw.fifo_size =
679 		DIV_ROUND_CLOSEST(ua->rate, ua->packets_per_second);
680 	substream->runtime->delay = substream->runtime->hw.fifo_size;
681 
682 	mutex_lock(&ua->mutex);
683 	err = start_usb_capture(ua);
684 	if (err >= 0)
685 		set_bit(ALSA_CAPTURE_OPEN, &ua->states);
686 	mutex_unlock(&ua->mutex);
687 	return err;
688 }
689 
playback_pcm_open(struct snd_pcm_substream * substream)690 static int playback_pcm_open(struct snd_pcm_substream *substream)
691 {
692 	struct ua101 *ua = substream->private_data;
693 	int err;
694 
695 	ua->playback.substream = substream;
696 	err = set_stream_hw(ua, substream, ua->playback.channels);
697 	if (err < 0)
698 		return err;
699 	substream->runtime->hw.fifo_size =
700 		DIV_ROUND_CLOSEST(ua->rate * ua->playback.queue_length,
701 				  ua->packets_per_second);
702 
703 	mutex_lock(&ua->mutex);
704 	err = start_usb_capture(ua);
705 	if (err < 0)
706 		goto error;
707 	err = start_usb_playback(ua);
708 	if (err < 0) {
709 		if (!test_bit(ALSA_CAPTURE_OPEN, &ua->states))
710 			stop_usb_capture(ua);
711 		goto error;
712 	}
713 	set_bit(ALSA_PLAYBACK_OPEN, &ua->states);
714 error:
715 	mutex_unlock(&ua->mutex);
716 	return err;
717 }
718 
capture_pcm_close(struct snd_pcm_substream * substream)719 static int capture_pcm_close(struct snd_pcm_substream *substream)
720 {
721 	struct ua101 *ua = substream->private_data;
722 
723 	mutex_lock(&ua->mutex);
724 	clear_bit(ALSA_CAPTURE_OPEN, &ua->states);
725 	if (!test_bit(ALSA_PLAYBACK_OPEN, &ua->states))
726 		stop_usb_capture(ua);
727 	mutex_unlock(&ua->mutex);
728 	return 0;
729 }
730 
playback_pcm_close(struct snd_pcm_substream * substream)731 static int playback_pcm_close(struct snd_pcm_substream *substream)
732 {
733 	struct ua101 *ua = substream->private_data;
734 
735 	mutex_lock(&ua->mutex);
736 	stop_usb_playback(ua);
737 	clear_bit(ALSA_PLAYBACK_OPEN, &ua->states);
738 	if (!test_bit(ALSA_CAPTURE_OPEN, &ua->states))
739 		stop_usb_capture(ua);
740 	mutex_unlock(&ua->mutex);
741 	return 0;
742 }
743 
capture_pcm_hw_params(struct snd_pcm_substream * substream,struct snd_pcm_hw_params * hw_params)744 static int capture_pcm_hw_params(struct snd_pcm_substream *substream,
745 				 struct snd_pcm_hw_params *hw_params)
746 {
747 	struct ua101 *ua = substream->private_data;
748 	int err;
749 
750 	mutex_lock(&ua->mutex);
751 	err = start_usb_capture(ua);
752 	mutex_unlock(&ua->mutex);
753 	if (err < 0)
754 		return err;
755 
756 	return snd_pcm_lib_alloc_vmalloc_buffer(substream,
757 						params_buffer_bytes(hw_params));
758 }
759 
playback_pcm_hw_params(struct snd_pcm_substream * substream,struct snd_pcm_hw_params * hw_params)760 static int playback_pcm_hw_params(struct snd_pcm_substream *substream,
761 				  struct snd_pcm_hw_params *hw_params)
762 {
763 	struct ua101 *ua = substream->private_data;
764 	int err;
765 
766 	mutex_lock(&ua->mutex);
767 	err = start_usb_capture(ua);
768 	if (err >= 0)
769 		err = start_usb_playback(ua);
770 	mutex_unlock(&ua->mutex);
771 	if (err < 0)
772 		return err;
773 
774 	return snd_pcm_lib_alloc_vmalloc_buffer(substream,
775 						params_buffer_bytes(hw_params));
776 }
777 
ua101_pcm_hw_free(struct snd_pcm_substream * substream)778 static int ua101_pcm_hw_free(struct snd_pcm_substream *substream)
779 {
780 	return snd_pcm_lib_free_vmalloc_buffer(substream);
781 }
782 
capture_pcm_prepare(struct snd_pcm_substream * substream)783 static int capture_pcm_prepare(struct snd_pcm_substream *substream)
784 {
785 	struct ua101 *ua = substream->private_data;
786 	int err;
787 
788 	mutex_lock(&ua->mutex);
789 	err = start_usb_capture(ua);
790 	mutex_unlock(&ua->mutex);
791 	if (err < 0)
792 		return err;
793 
794 	/*
795 	 * The EHCI driver schedules the first packet of an iso stream at 10 ms
796 	 * in the future, i.e., no data is actually captured for that long.
797 	 * Take the wait here so that the stream is known to be actually
798 	 * running when the start trigger has been called.
799 	 */
800 	wait_event(ua->alsa_capture_wait,
801 		   test_bit(CAPTURE_URB_COMPLETED, &ua->states) ||
802 		   !test_bit(USB_CAPTURE_RUNNING, &ua->states));
803 	if (test_bit(DISCONNECTED, &ua->states))
804 		return -ENODEV;
805 	if (!test_bit(USB_CAPTURE_RUNNING, &ua->states))
806 		return -EIO;
807 
808 	ua->capture.period_pos = 0;
809 	ua->capture.buffer_pos = 0;
810 	return 0;
811 }
812 
playback_pcm_prepare(struct snd_pcm_substream * substream)813 static int playback_pcm_prepare(struct snd_pcm_substream *substream)
814 {
815 	struct ua101 *ua = substream->private_data;
816 	int err;
817 
818 	mutex_lock(&ua->mutex);
819 	err = start_usb_capture(ua);
820 	if (err >= 0)
821 		err = start_usb_playback(ua);
822 	mutex_unlock(&ua->mutex);
823 	if (err < 0)
824 		return err;
825 
826 	/* see the comment in capture_pcm_prepare() */
827 	wait_event(ua->alsa_playback_wait,
828 		   test_bit(PLAYBACK_URB_COMPLETED, &ua->states) ||
829 		   !test_bit(USB_PLAYBACK_RUNNING, &ua->states));
830 	if (test_bit(DISCONNECTED, &ua->states))
831 		return -ENODEV;
832 	if (!test_bit(USB_PLAYBACK_RUNNING, &ua->states))
833 		return -EIO;
834 
835 	substream->runtime->delay = 0;
836 	ua->playback.period_pos = 0;
837 	ua->playback.buffer_pos = 0;
838 	return 0;
839 }
840 
capture_pcm_trigger(struct snd_pcm_substream * substream,int cmd)841 static int capture_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
842 {
843 	struct ua101 *ua = substream->private_data;
844 
845 	switch (cmd) {
846 	case SNDRV_PCM_TRIGGER_START:
847 		if (!test_bit(USB_CAPTURE_RUNNING, &ua->states))
848 			return -EIO;
849 		set_bit(ALSA_CAPTURE_RUNNING, &ua->states);
850 		return 0;
851 	case SNDRV_PCM_TRIGGER_STOP:
852 		clear_bit(ALSA_CAPTURE_RUNNING, &ua->states);
853 		return 0;
854 	default:
855 		return -EINVAL;
856 	}
857 }
858 
playback_pcm_trigger(struct snd_pcm_substream * substream,int cmd)859 static int playback_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
860 {
861 	struct ua101 *ua = substream->private_data;
862 
863 	switch (cmd) {
864 	case SNDRV_PCM_TRIGGER_START:
865 		if (!test_bit(USB_PLAYBACK_RUNNING, &ua->states))
866 			return -EIO;
867 		set_bit(ALSA_PLAYBACK_RUNNING, &ua->states);
868 		return 0;
869 	case SNDRV_PCM_TRIGGER_STOP:
870 		clear_bit(ALSA_PLAYBACK_RUNNING, &ua->states);
871 		return 0;
872 	default:
873 		return -EINVAL;
874 	}
875 }
876 
ua101_pcm_pointer(struct ua101 * ua,struct ua101_stream * stream)877 static inline snd_pcm_uframes_t ua101_pcm_pointer(struct ua101 *ua,
878 						  struct ua101_stream *stream)
879 {
880 	unsigned long flags;
881 	unsigned int pos;
882 
883 	spin_lock_irqsave(&ua->lock, flags);
884 	pos = stream->buffer_pos;
885 	spin_unlock_irqrestore(&ua->lock, flags);
886 	return pos;
887 }
888 
capture_pcm_pointer(struct snd_pcm_substream * subs)889 static snd_pcm_uframes_t capture_pcm_pointer(struct snd_pcm_substream *subs)
890 {
891 	struct ua101 *ua = subs->private_data;
892 
893 	return ua101_pcm_pointer(ua, &ua->capture);
894 }
895 
playback_pcm_pointer(struct snd_pcm_substream * subs)896 static snd_pcm_uframes_t playback_pcm_pointer(struct snd_pcm_substream *subs)
897 {
898 	struct ua101 *ua = subs->private_data;
899 
900 	return ua101_pcm_pointer(ua, &ua->playback);
901 }
902 
903 static struct snd_pcm_ops capture_pcm_ops = {
904 	.open = capture_pcm_open,
905 	.close = capture_pcm_close,
906 	.ioctl = snd_pcm_lib_ioctl,
907 	.hw_params = capture_pcm_hw_params,
908 	.hw_free = ua101_pcm_hw_free,
909 	.prepare = capture_pcm_prepare,
910 	.trigger = capture_pcm_trigger,
911 	.pointer = capture_pcm_pointer,
912 	.page = snd_pcm_lib_get_vmalloc_page,
913 	.mmap = snd_pcm_lib_mmap_vmalloc,
914 };
915 
916 static struct snd_pcm_ops playback_pcm_ops = {
917 	.open = playback_pcm_open,
918 	.close = playback_pcm_close,
919 	.ioctl = snd_pcm_lib_ioctl,
920 	.hw_params = playback_pcm_hw_params,
921 	.hw_free = ua101_pcm_hw_free,
922 	.prepare = playback_pcm_prepare,
923 	.trigger = playback_pcm_trigger,
924 	.pointer = playback_pcm_pointer,
925 	.page = snd_pcm_lib_get_vmalloc_page,
926 	.mmap = snd_pcm_lib_mmap_vmalloc,
927 };
928 
929 static const struct uac_format_type_i_discrete_descriptor *
find_format_descriptor(struct usb_interface * interface)930 find_format_descriptor(struct usb_interface *interface)
931 {
932 	struct usb_host_interface *alt;
933 	u8 *extra;
934 	int extralen;
935 
936 	if (interface->num_altsetting != 2) {
937 		dev_err(&interface->dev, "invalid num_altsetting\n");
938 		return NULL;
939 	}
940 
941 	alt = &interface->altsetting[0];
942 	if (alt->desc.bNumEndpoints != 0) {
943 		dev_err(&interface->dev, "invalid bNumEndpoints\n");
944 		return NULL;
945 	}
946 
947 	alt = &interface->altsetting[1];
948 	if (alt->desc.bNumEndpoints != 1) {
949 		dev_err(&interface->dev, "invalid bNumEndpoints\n");
950 		return NULL;
951 	}
952 
953 	extra = alt->extra;
954 	extralen = alt->extralen;
955 	while (extralen >= sizeof(struct usb_descriptor_header)) {
956 		struct uac_format_type_i_discrete_descriptor *desc;
957 
958 		desc = (struct uac_format_type_i_discrete_descriptor *)extra;
959 		if (desc->bLength > extralen) {
960 			dev_err(&interface->dev, "descriptor overflow\n");
961 			return NULL;
962 		}
963 		if (desc->bLength == UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1) &&
964 		    desc->bDescriptorType == USB_DT_CS_INTERFACE &&
965 		    desc->bDescriptorSubtype == UAC_FORMAT_TYPE) {
966 			if (desc->bFormatType != UAC_FORMAT_TYPE_I_PCM ||
967 			    desc->bSamFreqType != 1) {
968 				dev_err(&interface->dev,
969 					"invalid format type\n");
970 				return NULL;
971 			}
972 			return desc;
973 		}
974 		extralen -= desc->bLength;
975 		extra += desc->bLength;
976 	}
977 	dev_err(&interface->dev, "sample format descriptor not found\n");
978 	return NULL;
979 }
980 
detect_usb_format(struct ua101 * ua)981 static int detect_usb_format(struct ua101 *ua)
982 {
983 	const struct uac_format_type_i_discrete_descriptor *fmt_capture;
984 	const struct uac_format_type_i_discrete_descriptor *fmt_playback;
985 	const struct usb_endpoint_descriptor *epd;
986 	unsigned int rate2;
987 
988 	fmt_capture = find_format_descriptor(ua->intf[INTF_CAPTURE]);
989 	fmt_playback = find_format_descriptor(ua->intf[INTF_PLAYBACK]);
990 	if (!fmt_capture || !fmt_playback)
991 		return -ENXIO;
992 
993 	switch (fmt_capture->bSubframeSize) {
994 	case 3:
995 		ua->format_bit = SNDRV_PCM_FMTBIT_S24_3LE;
996 		break;
997 	case 4:
998 		ua->format_bit = SNDRV_PCM_FMTBIT_S32_LE;
999 		break;
1000 	default:
1001 		dev_err(&ua->dev->dev, "sample width is not 24 or 32 bits\n");
1002 		return -ENXIO;
1003 	}
1004 	if (fmt_capture->bSubframeSize != fmt_playback->bSubframeSize) {
1005 		dev_err(&ua->dev->dev,
1006 			"playback/capture sample widths do not match\n");
1007 		return -ENXIO;
1008 	}
1009 
1010 	if (fmt_capture->bBitResolution != 24 ||
1011 	    fmt_playback->bBitResolution != 24) {
1012 		dev_err(&ua->dev->dev, "sample width is not 24 bits\n");
1013 		return -ENXIO;
1014 	}
1015 
1016 	ua->rate = combine_triple(fmt_capture->tSamFreq[0]);
1017 	rate2 = combine_triple(fmt_playback->tSamFreq[0]);
1018 	if (ua->rate != rate2) {
1019 		dev_err(&ua->dev->dev,
1020 			"playback/capture rates do not match: %u/%u\n",
1021 			rate2, ua->rate);
1022 		return -ENXIO;
1023 	}
1024 
1025 	switch (ua->dev->speed) {
1026 	case USB_SPEED_FULL:
1027 		ua->packets_per_second = 1000;
1028 		break;
1029 	case USB_SPEED_HIGH:
1030 		ua->packets_per_second = 8000;
1031 		break;
1032 	default:
1033 		dev_err(&ua->dev->dev, "unknown device speed\n");
1034 		return -ENXIO;
1035 	}
1036 
1037 	ua->capture.channels = fmt_capture->bNrChannels;
1038 	ua->playback.channels = fmt_playback->bNrChannels;
1039 	ua->capture.frame_bytes =
1040 		fmt_capture->bSubframeSize * ua->capture.channels;
1041 	ua->playback.frame_bytes =
1042 		fmt_playback->bSubframeSize * ua->playback.channels;
1043 
1044 	epd = &ua->intf[INTF_CAPTURE]->altsetting[1].endpoint[0].desc;
1045 	if (!usb_endpoint_is_isoc_in(epd)) {
1046 		dev_err(&ua->dev->dev, "invalid capture endpoint\n");
1047 		return -ENXIO;
1048 	}
1049 	ua->capture.usb_pipe = usb_rcvisocpipe(ua->dev, usb_endpoint_num(epd));
1050 	ua->capture.max_packet_bytes = le16_to_cpu(epd->wMaxPacketSize);
1051 
1052 	epd = &ua->intf[INTF_PLAYBACK]->altsetting[1].endpoint[0].desc;
1053 	if (!usb_endpoint_is_isoc_out(epd)) {
1054 		dev_err(&ua->dev->dev, "invalid playback endpoint\n");
1055 		return -ENXIO;
1056 	}
1057 	ua->playback.usb_pipe = usb_sndisocpipe(ua->dev, usb_endpoint_num(epd));
1058 	ua->playback.max_packet_bytes = le16_to_cpu(epd->wMaxPacketSize);
1059 	return 0;
1060 }
1061 
alloc_stream_buffers(struct ua101 * ua,struct ua101_stream * stream)1062 static int alloc_stream_buffers(struct ua101 *ua, struct ua101_stream *stream)
1063 {
1064 	unsigned int remaining_packets, packets, packets_per_page, i;
1065 	size_t size;
1066 
1067 	stream->queue_length = queue_length;
1068 	stream->queue_length = max(stream->queue_length,
1069 				   (unsigned int)MIN_QUEUE_LENGTH);
1070 	stream->queue_length = min(stream->queue_length,
1071 				   (unsigned int)MAX_QUEUE_LENGTH);
1072 
1073 	/*
1074 	 * The cache pool sizes used by usb_alloc_coherent() (128, 512, 2048) are
1075 	 * quite bad when used with the packet sizes of this device (e.g. 280,
1076 	 * 520, 624).  Therefore, we allocate and subdivide entire pages, using
1077 	 * a smaller buffer only for the last chunk.
1078 	 */
1079 	remaining_packets = stream->queue_length;
1080 	packets_per_page = PAGE_SIZE / stream->max_packet_bytes;
1081 	for (i = 0; i < ARRAY_SIZE(stream->buffers); ++i) {
1082 		packets = min(remaining_packets, packets_per_page);
1083 		size = packets * stream->max_packet_bytes;
1084 		stream->buffers[i].addr =
1085 			usb_alloc_coherent(ua->dev, size, GFP_KERNEL,
1086 					   &stream->buffers[i].dma);
1087 		if (!stream->buffers[i].addr)
1088 			return -ENOMEM;
1089 		stream->buffers[i].size = size;
1090 		remaining_packets -= packets;
1091 		if (!remaining_packets)
1092 			break;
1093 	}
1094 	if (remaining_packets) {
1095 		dev_err(&ua->dev->dev, "too many packets\n");
1096 		return -ENXIO;
1097 	}
1098 	return 0;
1099 }
1100 
free_stream_buffers(struct ua101 * ua,struct ua101_stream * stream)1101 static void free_stream_buffers(struct ua101 *ua, struct ua101_stream *stream)
1102 {
1103 	unsigned int i;
1104 
1105 	for (i = 0; i < ARRAY_SIZE(stream->buffers); ++i)
1106 		usb_free_coherent(ua->dev,
1107 				  stream->buffers[i].size,
1108 				  stream->buffers[i].addr,
1109 				  stream->buffers[i].dma);
1110 }
1111 
alloc_stream_urbs(struct ua101 * ua,struct ua101_stream * stream,void (* urb_complete)(struct urb *))1112 static int alloc_stream_urbs(struct ua101 *ua, struct ua101_stream *stream,
1113 			     void (*urb_complete)(struct urb *))
1114 {
1115 	unsigned max_packet_size = stream->max_packet_bytes;
1116 	struct ua101_urb *urb;
1117 	unsigned int b, u = 0;
1118 
1119 	for (b = 0; b < ARRAY_SIZE(stream->buffers); ++b) {
1120 		unsigned int size = stream->buffers[b].size;
1121 		u8 *addr = stream->buffers[b].addr;
1122 		dma_addr_t dma = stream->buffers[b].dma;
1123 
1124 		while (size >= max_packet_size) {
1125 			if (u >= stream->queue_length)
1126 				goto bufsize_error;
1127 			urb = kmalloc(sizeof(*urb), GFP_KERNEL);
1128 			if (!urb)
1129 				return -ENOMEM;
1130 			usb_init_urb(&urb->urb);
1131 			urb->urb.dev = ua->dev;
1132 			urb->urb.pipe = stream->usb_pipe;
1133 			urb->urb.transfer_flags = URB_ISO_ASAP |
1134 					URB_NO_TRANSFER_DMA_MAP;
1135 			urb->urb.transfer_buffer = addr;
1136 			urb->urb.transfer_dma = dma;
1137 			urb->urb.transfer_buffer_length = max_packet_size;
1138 			urb->urb.number_of_packets = 1;
1139 			urb->urb.interval = 1;
1140 			urb->urb.context = ua;
1141 			urb->urb.complete = urb_complete;
1142 			urb->urb.iso_frame_desc[0].offset = 0;
1143 			urb->urb.iso_frame_desc[0].length = max_packet_size;
1144 			stream->urbs[u++] = urb;
1145 			size -= max_packet_size;
1146 			addr += max_packet_size;
1147 			dma += max_packet_size;
1148 		}
1149 	}
1150 	if (u == stream->queue_length)
1151 		return 0;
1152 bufsize_error:
1153 	dev_err(&ua->dev->dev, "internal buffer size error\n");
1154 	return -ENXIO;
1155 }
1156 
free_stream_urbs(struct ua101_stream * stream)1157 static void free_stream_urbs(struct ua101_stream *stream)
1158 {
1159 	unsigned int i;
1160 
1161 	for (i = 0; i < stream->queue_length; ++i) {
1162 		kfree(stream->urbs[i]);
1163 		stream->urbs[i] = NULL;
1164 	}
1165 }
1166 
free_usb_related_resources(struct ua101 * ua,struct usb_interface * interface)1167 static void free_usb_related_resources(struct ua101 *ua,
1168 				       struct usb_interface *interface)
1169 {
1170 	unsigned int i;
1171 	struct usb_interface *intf;
1172 
1173 	mutex_lock(&ua->mutex);
1174 	free_stream_urbs(&ua->capture);
1175 	free_stream_urbs(&ua->playback);
1176 	mutex_unlock(&ua->mutex);
1177 	free_stream_buffers(ua, &ua->capture);
1178 	free_stream_buffers(ua, &ua->playback);
1179 
1180 	for (i = 0; i < ARRAY_SIZE(ua->intf); ++i) {
1181 		mutex_lock(&ua->mutex);
1182 		intf = ua->intf[i];
1183 		ua->intf[i] = NULL;
1184 		mutex_unlock(&ua->mutex);
1185 		if (intf) {
1186 			usb_set_intfdata(intf, NULL);
1187 			if (intf != interface)
1188 				usb_driver_release_interface(&ua101_driver,
1189 							     intf);
1190 		}
1191 	}
1192 }
1193 
ua101_card_free(struct snd_card * card)1194 static void ua101_card_free(struct snd_card *card)
1195 {
1196 	struct ua101 *ua = card->private_data;
1197 
1198 	mutex_destroy(&ua->mutex);
1199 }
1200 
ua101_probe(struct usb_interface * interface,const struct usb_device_id * usb_id)1201 static int ua101_probe(struct usb_interface *interface,
1202 		       const struct usb_device_id *usb_id)
1203 {
1204 	static const struct snd_usb_midi_endpoint_info midi_ep = {
1205 		.out_cables = 0x0001,
1206 		.in_cables = 0x0001
1207 	};
1208 	static const struct snd_usb_audio_quirk midi_quirk = {
1209 		.type = QUIRK_MIDI_FIXED_ENDPOINT,
1210 		.data = &midi_ep
1211 	};
1212 	static const int intf_numbers[2][3] = {
1213 		{	/* UA-101 */
1214 			[INTF_PLAYBACK] = 0,
1215 			[INTF_CAPTURE] = 1,
1216 			[INTF_MIDI] = 2,
1217 		},
1218 		{	/* UA-1000 */
1219 			[INTF_CAPTURE] = 1,
1220 			[INTF_PLAYBACK] = 2,
1221 			[INTF_MIDI] = 3,
1222 		},
1223 	};
1224 	struct snd_card *card;
1225 	struct ua101 *ua;
1226 	unsigned int card_index, i;
1227 	int is_ua1000;
1228 	const char *name;
1229 	char usb_path[32];
1230 	int err;
1231 
1232 	is_ua1000 = usb_id->idProduct == 0x0044;
1233 
1234 	if (interface->altsetting->desc.bInterfaceNumber !=
1235 	    intf_numbers[is_ua1000][0])
1236 		return -ENODEV;
1237 
1238 	mutex_lock(&devices_mutex);
1239 
1240 	for (card_index = 0; card_index < SNDRV_CARDS; ++card_index)
1241 		if (enable[card_index] && !(devices_used & (1 << card_index)))
1242 			break;
1243 	if (card_index >= SNDRV_CARDS) {
1244 		mutex_unlock(&devices_mutex);
1245 		return -ENOENT;
1246 	}
1247 	err = snd_card_create(index[card_index], id[card_index], THIS_MODULE,
1248 			      sizeof(*ua), &card);
1249 	if (err < 0) {
1250 		mutex_unlock(&devices_mutex);
1251 		return err;
1252 	}
1253 	card->private_free = ua101_card_free;
1254 	ua = card->private_data;
1255 	ua->dev = interface_to_usbdev(interface);
1256 	ua->card = card;
1257 	ua->card_index = card_index;
1258 	INIT_LIST_HEAD(&ua->midi_list);
1259 	spin_lock_init(&ua->lock);
1260 	mutex_init(&ua->mutex);
1261 	INIT_LIST_HEAD(&ua->ready_playback_urbs);
1262 	tasklet_init(&ua->playback_tasklet,
1263 		     playback_tasklet, (unsigned long)ua);
1264 	init_waitqueue_head(&ua->alsa_capture_wait);
1265 	init_waitqueue_head(&ua->rate_feedback_wait);
1266 	init_waitqueue_head(&ua->alsa_playback_wait);
1267 
1268 	ua->intf[0] = interface;
1269 	for (i = 1; i < ARRAY_SIZE(ua->intf); ++i) {
1270 		ua->intf[i] = usb_ifnum_to_if(ua->dev,
1271 					      intf_numbers[is_ua1000][i]);
1272 		if (!ua->intf[i]) {
1273 			dev_err(&ua->dev->dev, "interface %u not found\n",
1274 				intf_numbers[is_ua1000][i]);
1275 			err = -ENXIO;
1276 			goto probe_error;
1277 		}
1278 		err = usb_driver_claim_interface(&ua101_driver,
1279 						 ua->intf[i], ua);
1280 		if (err < 0) {
1281 			ua->intf[i] = NULL;
1282 			err = -EBUSY;
1283 			goto probe_error;
1284 		}
1285 	}
1286 
1287 	snd_card_set_dev(card, &interface->dev);
1288 
1289 	err = detect_usb_format(ua);
1290 	if (err < 0)
1291 		goto probe_error;
1292 
1293 	name = usb_id->idProduct == 0x0044 ? "UA-1000" : "UA-101";
1294 	strcpy(card->driver, "UA-101");
1295 	strcpy(card->shortname, name);
1296 	usb_make_path(ua->dev, usb_path, sizeof(usb_path));
1297 	snprintf(ua->card->longname, sizeof(ua->card->longname),
1298 		 "EDIROL %s (serial %s), %u Hz at %s, %s speed", name,
1299 		 ua->dev->serial ? ua->dev->serial : "?", ua->rate, usb_path,
1300 		 ua->dev->speed == USB_SPEED_HIGH ? "high" : "full");
1301 
1302 	err = alloc_stream_buffers(ua, &ua->capture);
1303 	if (err < 0)
1304 		goto probe_error;
1305 	err = alloc_stream_buffers(ua, &ua->playback);
1306 	if (err < 0)
1307 		goto probe_error;
1308 
1309 	err = alloc_stream_urbs(ua, &ua->capture, capture_urb_complete);
1310 	if (err < 0)
1311 		goto probe_error;
1312 	err = alloc_stream_urbs(ua, &ua->playback, playback_urb_complete);
1313 	if (err < 0)
1314 		goto probe_error;
1315 
1316 	err = snd_pcm_new(card, name, 0, 1, 1, &ua->pcm);
1317 	if (err < 0)
1318 		goto probe_error;
1319 	ua->pcm->private_data = ua;
1320 	strcpy(ua->pcm->name, name);
1321 	snd_pcm_set_ops(ua->pcm, SNDRV_PCM_STREAM_PLAYBACK, &playback_pcm_ops);
1322 	snd_pcm_set_ops(ua->pcm, SNDRV_PCM_STREAM_CAPTURE, &capture_pcm_ops);
1323 
1324 	err = snd_usbmidi_create(card, ua->intf[INTF_MIDI],
1325 				 &ua->midi_list, &midi_quirk);
1326 	if (err < 0)
1327 		goto probe_error;
1328 
1329 	err = snd_card_register(card);
1330 	if (err < 0)
1331 		goto probe_error;
1332 
1333 	usb_set_intfdata(interface, ua);
1334 	devices_used |= 1 << card_index;
1335 
1336 	mutex_unlock(&devices_mutex);
1337 	return 0;
1338 
1339 probe_error:
1340 	free_usb_related_resources(ua, interface);
1341 	snd_card_free(card);
1342 	mutex_unlock(&devices_mutex);
1343 	return err;
1344 }
1345 
ua101_disconnect(struct usb_interface * interface)1346 static void ua101_disconnect(struct usb_interface *interface)
1347 {
1348 	struct ua101 *ua = usb_get_intfdata(interface);
1349 	struct list_head *midi;
1350 
1351 	if (!ua)
1352 		return;
1353 
1354 	mutex_lock(&devices_mutex);
1355 
1356 	set_bit(DISCONNECTED, &ua->states);
1357 	wake_up(&ua->rate_feedback_wait);
1358 
1359 	/* make sure that userspace cannot create new requests */
1360 	snd_card_disconnect(ua->card);
1361 
1362 	/* make sure that there are no pending USB requests */
1363 	__list_for_each(midi, &ua->midi_list)
1364 		snd_usbmidi_disconnect(midi);
1365 	abort_alsa_playback(ua);
1366 	abort_alsa_capture(ua);
1367 	mutex_lock(&ua->mutex);
1368 	stop_usb_playback(ua);
1369 	stop_usb_capture(ua);
1370 	mutex_unlock(&ua->mutex);
1371 
1372 	free_usb_related_resources(ua, interface);
1373 
1374 	devices_used &= ~(1 << ua->card_index);
1375 
1376 	snd_card_free_when_closed(ua->card);
1377 
1378 	mutex_unlock(&devices_mutex);
1379 }
1380 
1381 static struct usb_device_id ua101_ids[] = {
1382 	{ USB_DEVICE(0x0582, 0x0044) }, /* UA-1000 high speed */
1383 	{ USB_DEVICE(0x0582, 0x007d) }, /* UA-101 high speed */
1384 	{ USB_DEVICE(0x0582, 0x008d) }, /* UA-101 full speed */
1385 	{ }
1386 };
1387 MODULE_DEVICE_TABLE(usb, ua101_ids);
1388 
1389 static struct usb_driver ua101_driver = {
1390 	.name = "snd-ua101",
1391 	.id_table = ua101_ids,
1392 	.probe = ua101_probe,
1393 	.disconnect = ua101_disconnect,
1394 #if 0
1395 	.suspend = ua101_suspend,
1396 	.resume = ua101_resume,
1397 #endif
1398 };
1399 
1400 module_usb_driver(ua101_driver);
1401