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