1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 *   US-X2Y AUDIO
4 *   Copyright (c) 2002-2004 by Karsten Wiese
5 *
6 *   based on
7 *
8 *   (Tentative) USB Audio Driver for ALSA
9 *
10 *   Main and PCM part
11 *
12 *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
13 *
14 *   Many codes borrowed from audio.c by
15 *	    Alan Cox (alan@lxorguk.ukuu.org.uk)
16 *	    Thomas Sailer (sailer@ife.ee.ethz.ch)
17 */
18
19
20#include <linux/interrupt.h>
21#include <linux/slab.h>
22#include <linux/usb.h>
23#include <linux/moduleparam.h>
24#include <sound/core.h>
25#include <sound/info.h>
26#include <sound/pcm.h>
27#include <sound/pcm_params.h>
28#include "usx2y.h"
29#include "usbusx2y.h"
30
31#define USX2Y_NRPACKS 4			/* Default value used for nr of packs per urb.
32					  1 to 4 have been tested ok on uhci.
33					  To use 3 on ohci, you'd need a patch:
34					  look for "0000425-linux-2.6.9-rc4-mm1_ohci-hcd.patch.gz" on
35					  "https://bugtrack.alsa-project.org/alsa-bug/bug_view_page.php?bug_id=0000425"
36					  .
37					  1, 2 and 4 work out of the box on ohci, if I recall correctly.
38					  Bigger is safer operation,
39					  smaller gives lower latencies.
40					*/
41#define USX2Y_NRPACKS_VARIABLE y	/* If your system works ok with this module's parameter
42					   nrpacks set to 1, you might as well comment
43					   this #define out, and thereby produce smaller, faster code.
44					   You'd also set USX2Y_NRPACKS to 1 then.
45					*/
46
47#ifdef USX2Y_NRPACKS_VARIABLE
48 static int nrpacks = USX2Y_NRPACKS; /* number of packets per urb */
49 #define  nr_of_packs() nrpacks
50 module_param(nrpacks, int, 0444);
51 MODULE_PARM_DESC(nrpacks, "Number of packets per URB.");
52#else
53 #define nr_of_packs() USX2Y_NRPACKS
54#endif
55
56
57static int usx2y_urb_capt_retire(struct snd_usx2y_substream *subs)
58{
59	struct urb	*urb = subs->completed_urb;
60	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
61	unsigned char	*cp;
62	int 		i, len, lens = 0, hwptr_done = subs->hwptr_done;
63	struct usx2ydev	*usx2y = subs->usx2y;
64
65	for (i = 0; i < nr_of_packs(); i++) {
66		cp = (unsigned char*)urb->transfer_buffer + urb->iso_frame_desc[i].offset;
67		if (urb->iso_frame_desc[i].status) { /* active? hmm, skip this */
68			snd_printk(KERN_ERR "active frame status %i. "
69				   "Most probably some hardware problem.\n",
70				   urb->iso_frame_desc[i].status);
71			return urb->iso_frame_desc[i].status;
72		}
73		len = urb->iso_frame_desc[i].actual_length / usx2y->stride;
74		if (! len) {
75			snd_printd("0 == len ERROR!\n");
76			continue;
77		}
78
79		/* copy a data chunk */
80		if ((hwptr_done + len) > runtime->buffer_size) {
81			int cnt = runtime->buffer_size - hwptr_done;
82			int blen = cnt * usx2y->stride;
83			memcpy(runtime->dma_area + hwptr_done * usx2y->stride, cp, blen);
84			memcpy(runtime->dma_area, cp + blen, len * usx2y->stride - blen);
85		} else {
86			memcpy(runtime->dma_area + hwptr_done * usx2y->stride, cp,
87			       len * usx2y->stride);
88		}
89		lens += len;
90		if ((hwptr_done += len) >= runtime->buffer_size)
91			hwptr_done -= runtime->buffer_size;
92	}
93
94	subs->hwptr_done = hwptr_done;
95	subs->transfer_done += lens;
96	/* update the pointer, call callback if necessary */
97	if (subs->transfer_done >= runtime->period_size) {
98		subs->transfer_done -= runtime->period_size;
99		snd_pcm_period_elapsed(subs->pcm_substream);
100	}
101	return 0;
102}
103/*
104 * prepare urb for playback data pipe
105 *
106 * we copy the data directly from the pcm buffer.
107 * the current position to be copied is held in hwptr field.
108 * since a urb can handle only a single linear buffer, if the total
109 * transferred area overflows the buffer boundary, we cannot send
110 * it directly from the buffer.  thus the data is once copied to
111 * a temporary buffer and urb points to that.
112 */
113static int usx2y_urb_play_prepare(struct snd_usx2y_substream *subs,
114				  struct urb *cap_urb,
115				  struct urb *urb)
116{
117	int count, counts, pack;
118	struct usx2ydev *usx2y = subs->usx2y;
119	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
120
121	count = 0;
122	for (pack = 0; pack <  nr_of_packs(); pack++) {
123		/* calculate the size of a packet */
124		counts = cap_urb->iso_frame_desc[pack].actual_length / usx2y->stride;
125		count += counts;
126		if (counts < 43 || counts > 50) {
127			snd_printk(KERN_ERR "should not be here with counts=%i\n", counts);
128			return -EPIPE;
129		}
130		/* set up descriptor */
131		urb->iso_frame_desc[pack].offset = pack ?
132			urb->iso_frame_desc[pack - 1].offset +
133			urb->iso_frame_desc[pack - 1].length :
134			0;
135		urb->iso_frame_desc[pack].length = cap_urb->iso_frame_desc[pack].actual_length;
136	}
137	if (atomic_read(&subs->state) >= STATE_PRERUNNING)
138		if (subs->hwptr + count > runtime->buffer_size) {
139			/* err, the transferred area goes over buffer boundary.
140			 * copy the data to the temp buffer.
141			 */
142			int len;
143			len = runtime->buffer_size - subs->hwptr;
144			urb->transfer_buffer = subs->tmpbuf;
145			memcpy(subs->tmpbuf, runtime->dma_area +
146			       subs->hwptr * usx2y->stride, len * usx2y->stride);
147			memcpy(subs->tmpbuf + len * usx2y->stride,
148			       runtime->dma_area, (count - len) * usx2y->stride);
149			subs->hwptr += count;
150			subs->hwptr -= runtime->buffer_size;
151		} else {
152			/* set the buffer pointer */
153			urb->transfer_buffer = runtime->dma_area + subs->hwptr * usx2y->stride;
154			if ((subs->hwptr += count) >= runtime->buffer_size)
155				subs->hwptr -= runtime->buffer_size;
156		}
157	else
158		urb->transfer_buffer = subs->tmpbuf;
159	urb->transfer_buffer_length = count * usx2y->stride;
160	return 0;
161}
162
163/*
164 * process after playback data complete
165 *
166 * update the current position and call callback if a period is processed.
167 */
168static void usx2y_urb_play_retire(struct snd_usx2y_substream *subs, struct urb *urb)
169{
170	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
171	int		len = urb->actual_length / subs->usx2y->stride;
172
173	subs->transfer_done += len;
174	subs->hwptr_done +=  len;
175	if (subs->hwptr_done >= runtime->buffer_size)
176		subs->hwptr_done -= runtime->buffer_size;
177	if (subs->transfer_done >= runtime->period_size) {
178		subs->transfer_done -= runtime->period_size;
179		snd_pcm_period_elapsed(subs->pcm_substream);
180	}
181}
182
183static int usx2y_urb_submit(struct snd_usx2y_substream *subs, struct urb *urb, int frame)
184{
185	int err;
186	if (!urb)
187		return -ENODEV;
188	urb->start_frame = (frame + NRURBS * nr_of_packs());  // let hcd do rollover sanity checks
189	urb->hcpriv = NULL;
190	urb->dev = subs->usx2y->dev; /* we need to set this at each time */
191	if ((err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
192		snd_printk(KERN_ERR "usb_submit_urb() returned %i\n", err);
193		return err;
194	}
195	return 0;
196}
197
198static inline int usx2y_usbframe_complete(struct snd_usx2y_substream *capsubs,
199					  struct snd_usx2y_substream *playbacksubs,
200					  int frame)
201{
202	int err, state;
203	struct urb *urb = playbacksubs->completed_urb;
204
205	state = atomic_read(&playbacksubs->state);
206	if (NULL != urb) {
207		if (state == STATE_RUNNING)
208			usx2y_urb_play_retire(playbacksubs, urb);
209		else if (state >= STATE_PRERUNNING)
210			atomic_inc(&playbacksubs->state);
211	} else {
212		switch (state) {
213		case STATE_STARTING1:
214			urb = playbacksubs->urb[0];
215			atomic_inc(&playbacksubs->state);
216			break;
217		case STATE_STARTING2:
218			urb = playbacksubs->urb[1];
219			atomic_inc(&playbacksubs->state);
220			break;
221		}
222	}
223	if (urb) {
224		if ((err = usx2y_urb_play_prepare(playbacksubs, capsubs->completed_urb, urb)) ||
225		    (err = usx2y_urb_submit(playbacksubs, urb, frame))) {
226			return err;
227		}
228	}
229
230	playbacksubs->completed_urb = NULL;
231
232	state = atomic_read(&capsubs->state);
233	if (state >= STATE_PREPARED) {
234		if (state == STATE_RUNNING) {
235			if ((err = usx2y_urb_capt_retire(capsubs)))
236				return err;
237		} else if (state >= STATE_PRERUNNING)
238			atomic_inc(&capsubs->state);
239		if ((err = usx2y_urb_submit(capsubs, capsubs->completed_urb, frame)))
240			return err;
241	}
242	capsubs->completed_urb = NULL;
243	return 0;
244}
245
246
247static void usx2y_clients_stop(struct usx2ydev *usx2y)
248{
249	int s, u;
250
251	for (s = 0; s < 4; s++) {
252		struct snd_usx2y_substream *subs = usx2y->subs[s];
253		if (subs) {
254			snd_printdd("%i %p state=%i\n", s, subs, atomic_read(&subs->state));
255			atomic_set(&subs->state, STATE_STOPPED);
256		}
257	}
258	for (s = 0; s < 4; s++) {
259		struct snd_usx2y_substream *subs = usx2y->subs[s];
260		if (subs) {
261			if (atomic_read(&subs->state) >= STATE_PRERUNNING)
262				snd_pcm_stop_xrun(subs->pcm_substream);
263			for (u = 0; u < NRURBS; u++) {
264				struct urb *urb = subs->urb[u];
265				if (NULL != urb)
266					snd_printdd("%i status=%i start_frame=%i\n",
267						    u, urb->status, urb->start_frame);
268			}
269		}
270	}
271	usx2y->prepare_subs = NULL;
272	wake_up(&usx2y->prepare_wait_queue);
273}
274
275static void usx2y_error_urb_status(struct usx2ydev *usx2y,
276				   struct snd_usx2y_substream *subs, struct urb *urb)
277{
278	snd_printk(KERN_ERR "ep=%i stalled with status=%i\n", subs->endpoint, urb->status);
279	urb->status = 0;
280	usx2y_clients_stop(usx2y);
281}
282
283static void i_usx2y_urb_complete(struct urb *urb)
284{
285	struct snd_usx2y_substream *subs = urb->context;
286	struct usx2ydev *usx2y = subs->usx2y;
287
288	if (unlikely(atomic_read(&subs->state) < STATE_PREPARED)) {
289		snd_printdd("hcd_frame=%i ep=%i%s status=%i start_frame=%i\n",
290			    usb_get_current_frame_number(usx2y->dev),
291			    subs->endpoint, usb_pipein(urb->pipe) ? "in" : "out",
292			    urb->status, urb->start_frame);
293		return;
294	}
295	if (unlikely(urb->status)) {
296		usx2y_error_urb_status(usx2y, subs, urb);
297		return;
298	}
299
300	subs->completed_urb = urb;
301
302	{
303		struct snd_usx2y_substream *capsubs = usx2y->subs[SNDRV_PCM_STREAM_CAPTURE],
304			*playbacksubs = usx2y->subs[SNDRV_PCM_STREAM_PLAYBACK];
305		if (capsubs->completed_urb &&
306		    atomic_read(&capsubs->state) >= STATE_PREPARED &&
307		    (playbacksubs->completed_urb ||
308		     atomic_read(&playbacksubs->state) < STATE_PREPARED)) {
309			if (!usx2y_usbframe_complete(capsubs, playbacksubs, urb->start_frame))
310				usx2y->wait_iso_frame += nr_of_packs();
311			else {
312				snd_printdd("\n");
313				usx2y_clients_stop(usx2y);
314			}
315		}
316	}
317}
318
319static void usx2y_urbs_set_complete(struct usx2ydev * usx2y,
320				    void (*complete)(struct urb *))
321{
322	int s, u;
323	for (s = 0; s < 4; s++) {
324		struct snd_usx2y_substream *subs = usx2y->subs[s];
325		if (NULL != subs)
326			for (u = 0; u < NRURBS; u++) {
327				struct urb * urb = subs->urb[u];
328				if (NULL != urb)
329					urb->complete = complete;
330			}
331	}
332}
333
334static void usx2y_subs_startup_finish(struct usx2ydev * usx2y)
335{
336	usx2y_urbs_set_complete(usx2y, i_usx2y_urb_complete);
337	usx2y->prepare_subs = NULL;
338}
339
340static void i_usx2y_subs_startup(struct urb *urb)
341{
342	struct snd_usx2y_substream *subs = urb->context;
343	struct usx2ydev *usx2y = subs->usx2y;
344	struct snd_usx2y_substream *prepare_subs = usx2y->prepare_subs;
345	if (NULL != prepare_subs)
346		if (urb->start_frame == prepare_subs->urb[0]->start_frame) {
347			usx2y_subs_startup_finish(usx2y);
348			atomic_inc(&prepare_subs->state);
349			wake_up(&usx2y->prepare_wait_queue);
350		}
351
352	i_usx2y_urb_complete(urb);
353}
354
355static void usx2y_subs_prepare(struct snd_usx2y_substream *subs)
356{
357	snd_printdd("usx2y_substream_prepare(%p) ep=%i urb0=%p urb1=%p\n",
358		    subs, subs->endpoint, subs->urb[0], subs->urb[1]);
359	/* reset the pointer */
360	subs->hwptr = 0;
361	subs->hwptr_done = 0;
362	subs->transfer_done = 0;
363}
364
365
366static void usx2y_urb_release(struct urb **urb, int free_tb)
367{
368	if (*urb) {
369		usb_kill_urb(*urb);
370		if (free_tb)
371			kfree((*urb)->transfer_buffer);
372		usb_free_urb(*urb);
373		*urb = NULL;
374	}
375}
376/*
377 * release a substreams urbs
378 */
379static void usx2y_urbs_release(struct snd_usx2y_substream *subs)
380{
381	int i;
382	snd_printdd("usx2y_urbs_release() %i\n", subs->endpoint);
383	for (i = 0; i < NRURBS; i++)
384		usx2y_urb_release(subs->urb + i,
385				  subs != subs->usx2y->subs[SNDRV_PCM_STREAM_PLAYBACK]);
386
387	kfree(subs->tmpbuf);
388	subs->tmpbuf = NULL;
389}
390/*
391 * initialize a substream's urbs
392 */
393static int usx2y_urbs_allocate(struct snd_usx2y_substream *subs)
394{
395	int i;
396	unsigned int pipe;
397	int is_playback = subs == subs->usx2y->subs[SNDRV_PCM_STREAM_PLAYBACK];
398	struct usb_device *dev = subs->usx2y->dev;
399
400	pipe = is_playback ? usb_sndisocpipe(dev, subs->endpoint) :
401			usb_rcvisocpipe(dev, subs->endpoint);
402	subs->maxpacksize = usb_maxpacket(dev, pipe, is_playback);
403	if (!subs->maxpacksize)
404		return -EINVAL;
405
406	if (is_playback && NULL == subs->tmpbuf) {	/* allocate a temporary buffer for playback */
407		subs->tmpbuf = kcalloc(nr_of_packs(), subs->maxpacksize, GFP_KERNEL);
408		if (!subs->tmpbuf)
409			return -ENOMEM;
410	}
411	/* allocate and initialize data urbs */
412	for (i = 0; i < NRURBS; i++) {
413		struct urb **purb = subs->urb + i;
414		if (*purb) {
415			usb_kill_urb(*purb);
416			continue;
417		}
418		*purb = usb_alloc_urb(nr_of_packs(), GFP_KERNEL);
419		if (NULL == *purb) {
420			usx2y_urbs_release(subs);
421			return -ENOMEM;
422		}
423		if (!is_playback && !(*purb)->transfer_buffer) {
424			/* allocate a capture buffer per urb */
425			(*purb)->transfer_buffer =
426				kmalloc_array(subs->maxpacksize,
427					      nr_of_packs(), GFP_KERNEL);
428			if (NULL == (*purb)->transfer_buffer) {
429				usx2y_urbs_release(subs);
430				return -ENOMEM;
431			}
432		}
433		(*purb)->dev = dev;
434		(*purb)->pipe = pipe;
435		(*purb)->number_of_packets = nr_of_packs();
436		(*purb)->context = subs;
437		(*purb)->interval = 1;
438		(*purb)->complete = i_usx2y_subs_startup;
439	}
440	return 0;
441}
442
443static void usx2y_subs_startup(struct snd_usx2y_substream *subs)
444{
445	struct usx2ydev *usx2y = subs->usx2y;
446	usx2y->prepare_subs = subs;
447	subs->urb[0]->start_frame = -1;
448	wmb();
449	usx2y_urbs_set_complete(usx2y, i_usx2y_subs_startup);
450}
451
452static int usx2y_urbs_start(struct snd_usx2y_substream *subs)
453{
454	int i, err;
455	struct usx2ydev *usx2y = subs->usx2y;
456
457	if ((err = usx2y_urbs_allocate(subs)) < 0)
458		return err;
459	subs->completed_urb = NULL;
460	for (i = 0; i < 4; i++) {
461		struct snd_usx2y_substream *subs = usx2y->subs[i];
462		if (subs != NULL && atomic_read(&subs->state) >= STATE_PREPARED)
463			goto start;
464	}
465
466 start:
467	usx2y_subs_startup(subs);
468	for (i = 0; i < NRURBS; i++) {
469		struct urb *urb = subs->urb[i];
470		if (usb_pipein(urb->pipe)) {
471			unsigned long pack;
472			if (0 == i)
473				atomic_set(&subs->state, STATE_STARTING3);
474			urb->dev = usx2y->dev;
475			for (pack = 0; pack < nr_of_packs(); pack++) {
476				urb->iso_frame_desc[pack].offset = subs->maxpacksize * pack;
477				urb->iso_frame_desc[pack].length = subs->maxpacksize;
478			}
479			urb->transfer_buffer_length = subs->maxpacksize * nr_of_packs();
480			if ((err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
481				snd_printk (KERN_ERR "cannot submit datapipe for urb %d, err = %d\n", i, err);
482				err = -EPIPE;
483				goto cleanup;
484			} else
485				if (i == 0)
486					usx2y->wait_iso_frame = urb->start_frame;
487			urb->transfer_flags = 0;
488		} else {
489			atomic_set(&subs->state, STATE_STARTING1);
490			break;
491		}
492	}
493	err = 0;
494	wait_event(usx2y->prepare_wait_queue, NULL == usx2y->prepare_subs);
495	if (atomic_read(&subs->state) != STATE_PREPARED)
496		err = -EPIPE;
497
498 cleanup:
499	if (err) {
500		usx2y_subs_startup_finish(usx2y);
501		usx2y_clients_stop(usx2y);		// something is completely wroong > stop evrything
502	}
503	return err;
504}
505
506/*
507 * return the current pcm pointer.  just return the hwptr_done value.
508 */
509static snd_pcm_uframes_t snd_usx2y_pcm_pointer(struct snd_pcm_substream *substream)
510{
511	struct snd_usx2y_substream *subs = substream->runtime->private_data;
512	return subs->hwptr_done;
513}
514/*
515 * start/stop substream
516 */
517static int snd_usx2y_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
518{
519	struct snd_usx2y_substream *subs = substream->runtime->private_data;
520
521	switch (cmd) {
522	case SNDRV_PCM_TRIGGER_START:
523		snd_printdd("snd_usx2y_pcm_trigger(START)\n");
524		if (atomic_read(&subs->state) == STATE_PREPARED &&
525		    atomic_read(&subs->usx2y->subs[SNDRV_PCM_STREAM_CAPTURE]->state) >= STATE_PREPARED) {
526			atomic_set(&subs->state, STATE_PRERUNNING);
527		} else {
528			snd_printdd("\n");
529			return -EPIPE;
530		}
531		break;
532	case SNDRV_PCM_TRIGGER_STOP:
533		snd_printdd("snd_usx2y_pcm_trigger(STOP)\n");
534		if (atomic_read(&subs->state) >= STATE_PRERUNNING)
535			atomic_set(&subs->state, STATE_PREPARED);
536		break;
537	default:
538		return -EINVAL;
539	}
540	return 0;
541}
542
543
544/*
545 * allocate a buffer, setup samplerate
546 *
547 * so far we use a physically linear buffer although packetize transfer
548 * doesn't need a continuous area.
549 * if sg buffer is supported on the later version of alsa, we'll follow
550 * that.
551 */
552static const struct s_c2
553{
554	char c1, c2;
555}
556	setrate_44100[] =
557{
558	{ 0x14, 0x08},	// this line sets 44100, well actually a little less
559	{ 0x18, 0x40},	// only tascam / frontier design knows the further lines .......
560	{ 0x18, 0x42},
561	{ 0x18, 0x45},
562	{ 0x18, 0x46},
563	{ 0x18, 0x48},
564	{ 0x18, 0x4A},
565	{ 0x18, 0x4C},
566	{ 0x18, 0x4E},
567	{ 0x18, 0x50},
568	{ 0x18, 0x52},
569	{ 0x18, 0x54},
570	{ 0x18, 0x56},
571	{ 0x18, 0x58},
572	{ 0x18, 0x5A},
573	{ 0x18, 0x5C},
574	{ 0x18, 0x5E},
575	{ 0x18, 0x60},
576	{ 0x18, 0x62},
577	{ 0x18, 0x64},
578	{ 0x18, 0x66},
579	{ 0x18, 0x68},
580	{ 0x18, 0x6A},
581	{ 0x18, 0x6C},
582	{ 0x18, 0x6E},
583	{ 0x18, 0x70},
584	{ 0x18, 0x72},
585	{ 0x18, 0x74},
586	{ 0x18, 0x76},
587	{ 0x18, 0x78},
588	{ 0x18, 0x7A},
589	{ 0x18, 0x7C},
590	{ 0x18, 0x7E}
591};
592static const struct s_c2 setrate_48000[] =
593{
594	{ 0x14, 0x09},	// this line sets 48000, well actually a little less
595	{ 0x18, 0x40},	// only tascam / frontier design knows the further lines .......
596	{ 0x18, 0x42},
597	{ 0x18, 0x45},
598	{ 0x18, 0x46},
599	{ 0x18, 0x48},
600	{ 0x18, 0x4A},
601	{ 0x18, 0x4C},
602	{ 0x18, 0x4E},
603	{ 0x18, 0x50},
604	{ 0x18, 0x52},
605	{ 0x18, 0x54},
606	{ 0x18, 0x56},
607	{ 0x18, 0x58},
608	{ 0x18, 0x5A},
609	{ 0x18, 0x5C},
610	{ 0x18, 0x5E},
611	{ 0x18, 0x60},
612	{ 0x18, 0x62},
613	{ 0x18, 0x64},
614	{ 0x18, 0x66},
615	{ 0x18, 0x68},
616	{ 0x18, 0x6A},
617	{ 0x18, 0x6C},
618	{ 0x18, 0x6E},
619	{ 0x18, 0x70},
620	{ 0x18, 0x73},
621	{ 0x18, 0x74},
622	{ 0x18, 0x76},
623	{ 0x18, 0x78},
624	{ 0x18, 0x7A},
625	{ 0x18, 0x7C},
626	{ 0x18, 0x7E}
627};
628#define NOOF_SETRATE_URBS ARRAY_SIZE(setrate_48000)
629
630static void i_usx2y_04int(struct urb *urb)
631{
632	struct usx2ydev *usx2y = urb->context;
633
634	if (urb->status)
635		snd_printk(KERN_ERR "snd_usx2y_04int() urb->status=%i\n", urb->status);
636	if (0 == --usx2y->us04->len)
637		wake_up(&usx2y->in04_wait_queue);
638}
639
640static int usx2y_rate_set(struct usx2ydev *usx2y, int rate)
641{
642	int			err = 0, i;
643	struct snd_usx2y_urb_seq	*us = NULL;
644	int			*usbdata = NULL;
645	const struct s_c2	*ra = rate == 48000 ? setrate_48000 : setrate_44100;
646
647	if (usx2y->rate != rate) {
648		us = kzalloc(sizeof(*us) + sizeof(struct urb*) * NOOF_SETRATE_URBS, GFP_KERNEL);
649		if (NULL == us) {
650			err = -ENOMEM;
651			goto cleanup;
652		}
653		usbdata = kmalloc_array(NOOF_SETRATE_URBS, sizeof(int),
654					GFP_KERNEL);
655		if (NULL == usbdata) {
656			err = -ENOMEM;
657			goto cleanup;
658		}
659		for (i = 0; i < NOOF_SETRATE_URBS; ++i) {
660			if (NULL == (us->urb[i] = usb_alloc_urb(0, GFP_KERNEL))) {
661				err = -ENOMEM;
662				goto cleanup;
663			}
664			((char*)(usbdata + i))[0] = ra[i].c1;
665			((char*)(usbdata + i))[1] = ra[i].c2;
666			usb_fill_bulk_urb(us->urb[i], usx2y->dev, usb_sndbulkpipe(usx2y->dev, 4),
667					  usbdata + i, 2, i_usx2y_04int, usx2y);
668		}
669		err = usb_urb_ep_type_check(us->urb[0]);
670		if (err < 0)
671			goto cleanup;
672		us->submitted =	0;
673		us->len =	NOOF_SETRATE_URBS;
674		usx2y->us04 =	us;
675		wait_event_timeout(usx2y->in04_wait_queue, 0 == us->len, HZ);
676		usx2y->us04 =	NULL;
677		if (us->len)
678			err = -ENODEV;
679	cleanup:
680		if (us) {
681			us->submitted =	2*NOOF_SETRATE_URBS;
682			for (i = 0; i < NOOF_SETRATE_URBS; ++i) {
683				struct urb *urb = us->urb[i];
684				if (!urb)
685					continue;
686				if (urb->status) {
687					if (!err)
688						err = -ENODEV;
689					usb_kill_urb(urb);
690				}
691				usb_free_urb(urb);
692			}
693			usx2y->us04 = NULL;
694			kfree(usbdata);
695			kfree(us);
696			if (!err)
697				usx2y->rate = rate;
698		}
699	}
700
701	return err;
702}
703
704
705static int usx2y_format_set(struct usx2ydev *usx2y, snd_pcm_format_t format)
706{
707	int alternate, err;
708	struct list_head* p;
709	if (format == SNDRV_PCM_FORMAT_S24_3LE) {
710		alternate = 2;
711		usx2y->stride = 6;
712	} else {
713		alternate = 1;
714		usx2y->stride = 4;
715	}
716	list_for_each(p, &usx2y->midi_list) {
717		snd_usbmidi_input_stop(p);
718	}
719	usb_kill_urb(usx2y->in04_urb);
720	if ((err = usb_set_interface(usx2y->dev, 0, alternate))) {
721		snd_printk(KERN_ERR "usb_set_interface error \n");
722		return err;
723	}
724	usx2y->in04_urb->dev = usx2y->dev;
725	err = usb_submit_urb(usx2y->in04_urb, GFP_KERNEL);
726	list_for_each(p, &usx2y->midi_list) {
727		snd_usbmidi_input_start(p);
728	}
729	usx2y->format = format;
730	usx2y->rate = 0;
731	return err;
732}
733
734
735static int snd_usx2y_pcm_hw_params(struct snd_pcm_substream *substream,
736				   struct snd_pcm_hw_params *hw_params)
737{
738	int			err = 0;
739	unsigned int		rate = params_rate(hw_params);
740	snd_pcm_format_t	format = params_format(hw_params);
741	struct snd_card *card = substream->pstr->pcm->card;
742	struct usx2ydev	*dev = usx2y(card);
743	int i;
744
745	mutex_lock(&usx2y(card)->pcm_mutex);
746	snd_printdd("snd_usx2y_hw_params(%p, %p)\n", substream, hw_params);
747	/* all pcm substreams off one usx2y have to operate at the same
748	 * rate & format
749	 */
750	for (i = 0; i < dev->pcm_devs * 2; i++) {
751		struct snd_usx2y_substream *subs = dev->subs[i];
752		struct snd_pcm_substream *test_substream;
753
754		if (!subs)
755			continue;
756		test_substream = subs->pcm_substream;
757		if (!test_substream || test_substream == substream ||
758		    !test_substream->runtime)
759			continue;
760		if ((test_substream->runtime->format &&
761		     test_substream->runtime->format != format) ||
762		    (test_substream->runtime->rate &&
763		     test_substream->runtime->rate != rate)) {
764			err = -EINVAL;
765			goto error;
766		}
767	}
768
769 error:
770	mutex_unlock(&usx2y(card)->pcm_mutex);
771	return err;
772}
773
774/*
775 * free the buffer
776 */
777static int snd_usx2y_pcm_hw_free(struct snd_pcm_substream *substream)
778{
779	struct snd_pcm_runtime *runtime = substream->runtime;
780	struct snd_usx2y_substream *subs = runtime->private_data;
781	mutex_lock(&subs->usx2y->pcm_mutex);
782	snd_printdd("snd_usx2y_hw_free(%p)\n", substream);
783
784	if (SNDRV_PCM_STREAM_PLAYBACK == substream->stream) {
785		struct snd_usx2y_substream *cap_subs = subs->usx2y->subs[SNDRV_PCM_STREAM_CAPTURE];
786		atomic_set(&subs->state, STATE_STOPPED);
787		usx2y_urbs_release(subs);
788		if (!cap_subs->pcm_substream ||
789		    !cap_subs->pcm_substream->runtime ||
790		    !cap_subs->pcm_substream->runtime->status ||
791		    cap_subs->pcm_substream->runtime->status->state < SNDRV_PCM_STATE_PREPARED) {
792			atomic_set(&cap_subs->state, STATE_STOPPED);
793			usx2y_urbs_release(cap_subs);
794		}
795	} else {
796		struct snd_usx2y_substream *playback_subs = subs->usx2y->subs[SNDRV_PCM_STREAM_PLAYBACK];
797		if (atomic_read(&playback_subs->state) < STATE_PREPARED) {
798			atomic_set(&subs->state, STATE_STOPPED);
799			usx2y_urbs_release(subs);
800		}
801	}
802	mutex_unlock(&subs->usx2y->pcm_mutex);
803	return 0;
804}
805/*
806 * prepare callback
807 *
808 * set format and initialize urbs
809 */
810static int snd_usx2y_pcm_prepare(struct snd_pcm_substream *substream)
811{
812	struct snd_pcm_runtime *runtime = substream->runtime;
813	struct snd_usx2y_substream *subs = runtime->private_data;
814	struct usx2ydev *usx2y = subs->usx2y;
815	struct snd_usx2y_substream *capsubs = subs->usx2y->subs[SNDRV_PCM_STREAM_CAPTURE];
816	int err = 0;
817	snd_printdd("snd_usx2y_pcm_prepare(%p)\n", substream);
818
819	mutex_lock(&usx2y->pcm_mutex);
820	usx2y_subs_prepare(subs);
821// Start hardware streams
822// SyncStream first....
823	if (atomic_read(&capsubs->state) < STATE_PREPARED) {
824		if (usx2y->format != runtime->format)
825			if ((err = usx2y_format_set(usx2y, runtime->format)) < 0)
826				goto up_prepare_mutex;
827		if (usx2y->rate != runtime->rate)
828			if ((err = usx2y_rate_set(usx2y, runtime->rate)) < 0)
829				goto up_prepare_mutex;
830		snd_printdd("starting capture pipe for %s\n", subs == capsubs ? "self" : "playpipe");
831		if (0 > (err = usx2y_urbs_start(capsubs)))
832			goto up_prepare_mutex;
833	}
834
835	if (subs != capsubs && atomic_read(&subs->state) < STATE_PREPARED)
836		err = usx2y_urbs_start(subs);
837
838 up_prepare_mutex:
839	mutex_unlock(&usx2y->pcm_mutex);
840	return err;
841}
842
843static const struct snd_pcm_hardware snd_usx2y_2c =
844{
845	.info =			(SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
846				 SNDRV_PCM_INFO_BLOCK_TRANSFER |
847				 SNDRV_PCM_INFO_MMAP_VALID |
848				 SNDRV_PCM_INFO_BATCH),
849	.formats =                 SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_3LE,
850	.rates =                   SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
851	.rate_min =                44100,
852	.rate_max =                48000,
853	.channels_min =            2,
854	.channels_max =            2,
855	.buffer_bytes_max =	(2*128*1024),
856	.period_bytes_min =	64,
857	.period_bytes_max =	(128*1024),
858	.periods_min =		2,
859	.periods_max =		1024,
860	.fifo_size =              0
861};
862
863
864
865static int snd_usx2y_pcm_open(struct snd_pcm_substream *substream)
866{
867	struct snd_usx2y_substream	*subs = ((struct snd_usx2y_substream **)
868					 snd_pcm_substream_chip(substream))[substream->stream];
869	struct snd_pcm_runtime	*runtime = substream->runtime;
870
871	if (subs->usx2y->chip_status & USX2Y_STAT_CHIP_MMAP_PCM_URBS)
872		return -EBUSY;
873
874	runtime->hw = snd_usx2y_2c;
875	runtime->private_data = subs;
876	subs->pcm_substream = substream;
877	snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME, 1000, 200000);
878	return 0;
879}
880
881
882
883static int snd_usx2y_pcm_close(struct snd_pcm_substream *substream)
884{
885	struct snd_pcm_runtime *runtime = substream->runtime;
886	struct snd_usx2y_substream *subs = runtime->private_data;
887
888	subs->pcm_substream = NULL;
889
890	return 0;
891}
892
893
894static const struct snd_pcm_ops snd_usx2y_pcm_ops =
895{
896	.open =		snd_usx2y_pcm_open,
897	.close =	snd_usx2y_pcm_close,
898	.hw_params =	snd_usx2y_pcm_hw_params,
899	.hw_free =	snd_usx2y_pcm_hw_free,
900	.prepare =	snd_usx2y_pcm_prepare,
901	.trigger =	snd_usx2y_pcm_trigger,
902	.pointer =	snd_usx2y_pcm_pointer,
903};
904
905
906/*
907 * free a usb stream instance
908 */
909static void usx2y_audio_stream_free(struct snd_usx2y_substream **usx2y_substream)
910{
911	int stream;
912
913	for_each_pcm_streams(stream) {
914		kfree(usx2y_substream[stream]);
915		usx2y_substream[stream] = NULL;
916	}
917}
918
919static void snd_usx2y_pcm_private_free(struct snd_pcm *pcm)
920{
921	struct snd_usx2y_substream **usx2y_stream = pcm->private_data;
922	if (usx2y_stream)
923		usx2y_audio_stream_free(usx2y_stream);
924}
925
926static int usx2y_audio_stream_new(struct snd_card *card, int playback_endpoint, int capture_endpoint)
927{
928	struct snd_pcm *pcm;
929	int err, i;
930	struct snd_usx2y_substream **usx2y_substream =
931		usx2y(card)->subs + 2 * usx2y(card)->pcm_devs;
932
933	for (i = playback_endpoint ? SNDRV_PCM_STREAM_PLAYBACK : SNDRV_PCM_STREAM_CAPTURE;
934	     i <= SNDRV_PCM_STREAM_CAPTURE; ++i) {
935		usx2y_substream[i] = kzalloc(sizeof(struct snd_usx2y_substream), GFP_KERNEL);
936		if (!usx2y_substream[i])
937			return -ENOMEM;
938
939		usx2y_substream[i]->usx2y = usx2y(card);
940	}
941
942	if (playback_endpoint)
943		usx2y_substream[SNDRV_PCM_STREAM_PLAYBACK]->endpoint = playback_endpoint;
944	usx2y_substream[SNDRV_PCM_STREAM_CAPTURE]->endpoint = capture_endpoint;
945
946	err = snd_pcm_new(card, NAME_ALLCAPS" Audio", usx2y(card)->pcm_devs,
947			  playback_endpoint ? 1 : 0, 1,
948			  &pcm);
949	if (err < 0) {
950		usx2y_audio_stream_free(usx2y_substream);
951		return err;
952	}
953
954	if (playback_endpoint)
955		snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_usx2y_pcm_ops);
956	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_usx2y_pcm_ops);
957
958	pcm->private_data = usx2y_substream;
959	pcm->private_free = snd_usx2y_pcm_private_free;
960	pcm->info_flags = 0;
961
962	sprintf(pcm->name, NAME_ALLCAPS" Audio #%d", usx2y(card)->pcm_devs);
963
964	if (playback_endpoint) {
965		snd_pcm_set_managed_buffer(pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream,
966					   SNDRV_DMA_TYPE_CONTINUOUS,
967					   NULL,
968					   64*1024, 128*1024);
969	}
970
971	snd_pcm_set_managed_buffer(pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream,
972				   SNDRV_DMA_TYPE_CONTINUOUS,
973				   NULL,
974				   64*1024, 128*1024);
975	usx2y(card)->pcm_devs++;
976
977	return 0;
978}
979
980/*
981 * create a chip instance and set its names.
982 */
983int usx2y_audio_create(struct snd_card *card)
984{
985	int err = 0;
986
987	INIT_LIST_HEAD(&usx2y(card)->pcm_list);
988
989	if (0 > (err = usx2y_audio_stream_new(card, 0xA, 0x8)))
990		return err;
991	if (le16_to_cpu(usx2y(card)->dev->descriptor.idProduct) == USB_ID_US428)
992	     if (0 > (err = usx2y_audio_stream_new(card, 0, 0xA)))
993		     return err;
994	if (le16_to_cpu(usx2y(card)->dev->descriptor.idProduct) != USB_ID_US122)
995		err = usx2y_rate_set(usx2y(card), 44100);	// Lets us428 recognize output-volume settings, disturbs us122.
996	return err;
997}
998