ALSA: snd-aloop: Fix hw_params restrictions and checking
[linux-2.6.git] / sound / drivers / aloop.c
1 /*
2  *  Loopback soundcard
3  *
4  *  Original code:
5  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
6  *
7  *  More accurate positioning and full-duplex support:
8  *  Copyright (c) Ahmet ─░nan <ainan at mathematik.uni-freiburg.de>
9  *
10  *  Major (almost complete) rewrite:
11  *  Copyright (c) by Takashi Iwai <tiwai@suse.de>
12  *
13  *  A next major update in 2010 (separate timers for playback and capture):
14  *  Copyright (c) Jaroslav Kysela <perex@perex.cz>
15  *
16  *   This program is free software; you can redistribute it and/or modify
17  *   it under the terms of the GNU General Public License as published by
18  *   the Free Software Foundation; either version 2 of the License, or
19  *   (at your option) any later version.
20  *
21  *   This program is distributed in the hope that it will be useful,
22  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
23  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  *   GNU General Public License for more details.
25  *
26  *   You should have received a copy of the GNU General Public License
27  *   along with this program; if not, write to the Free Software
28  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
29  *
30  */
31
32 #include <linux/init.h>
33 #include <linux/jiffies.h>
34 #include <linux/slab.h>
35 #include <linux/time.h>
36 #include <linux/wait.h>
37 #include <linux/moduleparam.h>
38 #include <linux/platform_device.h>
39 #include <sound/core.h>
40 #include <sound/control.h>
41 #include <sound/pcm.h>
42 #include <sound/initval.h>
43
44 MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
45 MODULE_DESCRIPTION("A loopback soundcard");
46 MODULE_LICENSE("GPL");
47 MODULE_SUPPORTED_DEVICE("{{ALSA,Loopback soundcard}}");
48
49 #define MAX_PCM_SUBSTREAMS      8
50
51 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 0-MAX */
52 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
53 static int enable[SNDRV_CARDS] = {1, [1 ... (SNDRV_CARDS - 1)] = 0};
54 static int pcm_substreams[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 8};
55 static int pcm_notify[SNDRV_CARDS];
56
57 module_param_array(index, int, NULL, 0444);
58 MODULE_PARM_DESC(index, "Index value for loopback soundcard.");
59 module_param_array(id, charp, NULL, 0444);
60 MODULE_PARM_DESC(id, "ID string for loopback soundcard.");
61 module_param_array(enable, bool, NULL, 0444);
62 MODULE_PARM_DESC(enable, "Enable this loopback soundcard.");
63 module_param_array(pcm_substreams, int, NULL, 0444);
64 MODULE_PARM_DESC(pcm_substreams, "PCM substreams # (1-8) for loopback driver.");
65 module_param_array(pcm_notify, int, NULL, 0444);
66 MODULE_PARM_DESC(pcm_notify, "Break capture when PCM format/rate/channels changes.");
67
68 #define NO_PITCH 100000
69
70 struct loopback_pcm;
71
72 struct loopback_cable {
73         spinlock_t lock;
74         struct loopback_pcm *streams[2];
75         struct snd_pcm_hardware hw;
76         /* flags */
77         unsigned int valid;
78         unsigned int running;
79 };
80
81 struct loopback_setup {
82         unsigned int notify: 1;
83         unsigned int rate_shift;
84         unsigned int format;
85         unsigned int rate;
86         unsigned int channels;
87         struct snd_ctl_elem_id active_id;
88         struct snd_ctl_elem_id format_id;
89         struct snd_ctl_elem_id rate_id;
90         struct snd_ctl_elem_id channels_id;
91 };
92
93 struct loopback {
94         struct snd_card *card;
95         struct mutex cable_lock;
96         struct loopback_cable *cables[MAX_PCM_SUBSTREAMS][2];
97         struct snd_pcm *pcm[2];
98         struct loopback_setup setup[MAX_PCM_SUBSTREAMS][2];
99 };
100
101 struct loopback_pcm {
102         struct loopback *loopback;
103         struct snd_pcm_substream *substream;
104         struct loopback_cable *cable;
105         unsigned int pcm_buffer_size;
106         unsigned int buf_pos;   /* position in buffer */
107         unsigned int silent_size;
108         /* PCM parameters */
109         unsigned int pcm_period_size;
110         unsigned int pcm_bps;           /* bytes per second */
111         unsigned int pcm_salign;        /* bytes per sample * channels */
112         unsigned int pcm_rate_shift;    /* rate shift value */
113         /* flags */
114         unsigned int period_update_pending :1;
115         /* timer stuff */
116         unsigned int irq_pos;           /* fractional IRQ position */
117         unsigned int period_size_frac;
118         unsigned long last_jiffies;
119         struct timer_list timer;
120 };
121
122 static struct platform_device *devices[SNDRV_CARDS];
123
124 static inline unsigned int byte_pos(struct loopback_pcm *dpcm, unsigned int x)
125 {
126         if (dpcm->pcm_rate_shift == NO_PITCH) {
127                 x /= HZ;
128         } else {
129                 x = div_u64(NO_PITCH * (unsigned long long)x,
130                             HZ * (unsigned long long)dpcm->pcm_rate_shift);
131         }
132         return x - (x % dpcm->pcm_salign);
133 }
134
135 static inline unsigned int frac_pos(struct loopback_pcm *dpcm, unsigned int x)
136 {
137         if (dpcm->pcm_rate_shift == NO_PITCH) { /* no pitch */
138                 return x * HZ;
139         } else {
140                 x = div_u64(dpcm->pcm_rate_shift * (unsigned long long)x * HZ,
141                             NO_PITCH);
142         }
143         return x;
144 }
145
146 static inline struct loopback_setup *get_setup(struct loopback_pcm *dpcm)
147 {
148         int device = dpcm->substream->pstr->pcm->device;
149         
150         if (dpcm->substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
151                 device ^= 1;
152         return &dpcm->loopback->setup[dpcm->substream->number][device];
153 }
154
155 static inline unsigned int get_notify(struct loopback_pcm *dpcm)
156 {
157         return get_setup(dpcm)->notify;
158 }
159
160 static inline unsigned int get_rate_shift(struct loopback_pcm *dpcm)
161 {
162         return get_setup(dpcm)->rate_shift;
163 }
164
165 static void loopback_timer_start(struct loopback_pcm *dpcm)
166 {
167         unsigned long tick;
168         unsigned int rate_shift = get_rate_shift(dpcm);
169
170         if (rate_shift != dpcm->pcm_rate_shift) {
171                 dpcm->pcm_rate_shift = rate_shift;
172                 dpcm->period_size_frac = frac_pos(dpcm, dpcm->pcm_period_size);
173         }
174         tick = dpcm->period_size_frac - dpcm->irq_pos;
175         tick = (tick + dpcm->pcm_bps - 1) / dpcm->pcm_bps;
176         dpcm->timer.expires = jiffies + tick;
177         add_timer(&dpcm->timer);
178 }
179
180 static inline void loopback_timer_stop(struct loopback_pcm *dpcm)
181 {
182         del_timer(&dpcm->timer);
183 }
184
185 #define CABLE_VALID_PLAYBACK    (1 << SNDRV_PCM_STREAM_PLAYBACK)
186 #define CABLE_VALID_CAPTURE     (1 << SNDRV_PCM_STREAM_CAPTURE)
187 #define CABLE_VALID_BOTH        (CABLE_VALID_PLAYBACK|CABLE_VALID_CAPTURE)
188
189 static int loopback_check_format(struct loopback_cable *cable, int stream)
190 {
191         struct snd_pcm_runtime *runtime, *cruntime;
192         struct loopback_setup *setup;
193         struct snd_card *card;
194         int check;
195
196         if (cable->valid != CABLE_VALID_BOTH) {
197                 if (stream == SNDRV_PCM_STREAM_PLAYBACK)
198                         goto __notify;
199                 return 0;
200         }
201         runtime = cable->streams[SNDRV_PCM_STREAM_PLAYBACK]->
202                                                         substream->runtime;
203         cruntime = cable->streams[SNDRV_PCM_STREAM_CAPTURE]->
204                                                         substream->runtime;
205         check = runtime->format != cruntime->format ||
206                 runtime->rate != cruntime->rate ||
207                 runtime->channels != cruntime->channels;
208         if (!check)
209                 return 0;
210         if (stream == SNDRV_PCM_STREAM_CAPTURE) {
211                 return -EIO;
212         } else {
213                 snd_pcm_stop(cable->streams[SNDRV_PCM_STREAM_CAPTURE]->
214                                         substream, SNDRV_PCM_STATE_DRAINING);
215               __notify:
216                 runtime = cable->streams[SNDRV_PCM_STREAM_PLAYBACK]->
217                                                         substream->runtime;
218                 setup = get_setup(cable->streams[SNDRV_PCM_STREAM_PLAYBACK]);
219                 card = cable->streams[SNDRV_PCM_STREAM_PLAYBACK]->loopback->card;
220                 if (setup->format != runtime->format) {
221                         snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
222                                                         &setup->format_id);
223                         setup->format = runtime->format;
224                 }
225                 if (setup->rate != runtime->rate) {
226                         snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
227                                                         &setup->rate_id);
228                         setup->rate = runtime->rate;
229                 }
230                 if (setup->channels != runtime->channels) {
231                         snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
232                                                         &setup->channels_id);
233                         setup->channels = runtime->channels;
234                 }
235         }
236         return 0;
237 }
238
239 static void loopback_active_notify(struct loopback_pcm *dpcm)
240 {
241         snd_ctl_notify(dpcm->loopback->card,
242                        SNDRV_CTL_EVENT_MASK_VALUE,
243                        &get_setup(dpcm)->active_id);
244 }
245
246 static int loopback_trigger(struct snd_pcm_substream *substream, int cmd)
247 {
248         struct snd_pcm_runtime *runtime = substream->runtime;
249         struct loopback_pcm *dpcm = runtime->private_data;
250         struct loopback_cable *cable = dpcm->cable;
251         int err;
252
253         switch (cmd) {
254         case SNDRV_PCM_TRIGGER_START:
255                 err = loopback_check_format(cable, substream->stream);
256                 if (err < 0)
257                         return err;
258                 dpcm->last_jiffies = jiffies;
259                 dpcm->pcm_rate_shift = 0;
260                 loopback_timer_start(dpcm);
261                 cable->running |= (1 << substream->stream);
262                 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
263                         loopback_active_notify(dpcm);
264                 break;
265         case SNDRV_PCM_TRIGGER_STOP:
266                 cable->running &= ~(1 << substream->stream);
267                 loopback_timer_stop(dpcm);
268                 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
269                         loopback_active_notify(dpcm);
270                 break;
271         default:
272                 return -EINVAL;
273         }
274         return 0;
275 }
276
277 static void params_change_substream(struct loopback_pcm *dpcm,
278                                     struct snd_pcm_runtime *runtime)
279 {
280         struct snd_pcm_runtime *dst_runtime;
281
282         if (dpcm == NULL || dpcm->substream == NULL)
283                 return;
284         dst_runtime = dpcm->substream->runtime;
285         if (dst_runtime == NULL)
286                 return;
287         dst_runtime->hw = dpcm->cable->hw;
288 }
289
290 static void params_change(struct snd_pcm_substream *substream)
291 {
292         struct snd_pcm_runtime *runtime = substream->runtime;
293         struct loopback_pcm *dpcm = runtime->private_data;
294         struct loopback_cable *cable = dpcm->cable;
295
296         cable->hw.formats = (1ULL << runtime->format);
297         cable->hw.rate_min = runtime->rate;
298         cable->hw.rate_max = runtime->rate;
299         cable->hw.channels_min = runtime->channels;
300         cable->hw.channels_max = runtime->channels;
301         params_change_substream(cable->streams[SNDRV_PCM_STREAM_PLAYBACK],
302                                 runtime);
303         params_change_substream(cable->streams[SNDRV_PCM_STREAM_CAPTURE],
304                                 runtime);
305 }
306
307 static int loopback_prepare(struct snd_pcm_substream *substream)
308 {
309         struct snd_pcm_runtime *runtime = substream->runtime;
310         struct loopback_pcm *dpcm = runtime->private_data;
311         struct loopback_cable *cable = dpcm->cable;
312         int bps, salign;
313
314         salign = (snd_pcm_format_width(runtime->format) *
315                                                 runtime->channels) / 8;
316         bps = salign * runtime->rate;
317         if (bps <= 0 || salign <= 0)
318                 return -EINVAL;
319
320         dpcm->buf_pos = 0;
321         dpcm->pcm_buffer_size = frames_to_bytes(runtime, runtime->buffer_size);
322         if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
323                 /* clear capture buffer */
324                 dpcm->silent_size = dpcm->pcm_buffer_size;
325                 snd_pcm_format_set_silence(runtime->format, runtime->dma_area,
326                                            runtime->buffer_size * runtime->channels);
327         }
328
329         dpcm->irq_pos = 0;
330         dpcm->period_update_pending = 0;
331         dpcm->pcm_bps = bps;
332         dpcm->pcm_salign = salign;
333         dpcm->pcm_period_size = frames_to_bytes(runtime, runtime->period_size);
334
335         mutex_lock(&dpcm->loopback->cable_lock);
336         if (!(cable->valid & ~(1 << substream->stream)) ||
337             (get_setup(dpcm)->notify &&
338              substream->stream == SNDRV_PCM_STREAM_PLAYBACK))
339                 params_change(substream);
340         cable->valid |= 1 << substream->stream;
341         mutex_unlock(&dpcm->loopback->cable_lock);
342
343         return 0;
344 }
345
346 static void clear_capture_buf(struct loopback_pcm *dpcm, unsigned int bytes)
347 {
348         struct snd_pcm_runtime *runtime = dpcm->substream->runtime;
349         char *dst = runtime->dma_area;
350         unsigned int dst_off = dpcm->buf_pos;
351
352         if (dpcm->silent_size >= dpcm->pcm_buffer_size)
353                 return;
354         if (dpcm->silent_size + bytes > dpcm->pcm_buffer_size)
355                 bytes = dpcm->pcm_buffer_size - dpcm->silent_size;
356
357         for (;;) {
358                 unsigned int size = bytes;
359                 if (dst_off + size > dpcm->pcm_buffer_size)
360                         size = dpcm->pcm_buffer_size - dst_off;
361                 snd_pcm_format_set_silence(runtime->format, dst + dst_off,
362                                            bytes_to_frames(runtime, size) *
363                                                 runtime->channels);
364                 dpcm->silent_size += size;
365                 bytes -= size;
366                 if (!bytes)
367                         break;
368                 dst_off = 0;
369         }
370 }
371
372 static void copy_play_buf(struct loopback_pcm *play,
373                           struct loopback_pcm *capt,
374                           unsigned int bytes)
375 {
376         struct snd_pcm_runtime *runtime = play->substream->runtime;
377         char *src = runtime->dma_area;
378         char *dst = capt->substream->runtime->dma_area;
379         unsigned int src_off = play->buf_pos;
380         unsigned int dst_off = capt->buf_pos;
381         unsigned int clear_bytes = 0;
382
383         /* check if playback is draining, trim the capture copy size
384          * when our pointer is at the end of playback ring buffer */
385         if (runtime->status->state == SNDRV_PCM_STATE_DRAINING &&
386             snd_pcm_playback_hw_avail(runtime) < runtime->buffer_size) { 
387                 snd_pcm_uframes_t appl_ptr, appl_ptr1, diff;
388                 appl_ptr = appl_ptr1 = runtime->control->appl_ptr;
389                 appl_ptr1 -= appl_ptr1 % runtime->buffer_size;
390                 appl_ptr1 += play->buf_pos / play->pcm_salign;
391                 if (appl_ptr < appl_ptr1)
392                         appl_ptr1 -= runtime->buffer_size;
393                 diff = (appl_ptr - appl_ptr1) * play->pcm_salign;
394                 if (diff < bytes) {
395                         clear_bytes = bytes - diff;
396                         bytes = diff;
397                 }
398         }
399
400         for (;;) {
401                 unsigned int size = bytes;
402                 if (src_off + size > play->pcm_buffer_size)
403                         size = play->pcm_buffer_size - src_off;
404                 if (dst_off + size > capt->pcm_buffer_size)
405                         size = capt->pcm_buffer_size - dst_off;
406                 memcpy(dst + dst_off, src + src_off, size);
407                 capt->silent_size = 0;
408                 bytes -= size;
409                 if (!bytes)
410                         break;
411                 src_off = (src_off + size) % play->pcm_buffer_size;
412                 dst_off = (dst_off + size) % capt->pcm_buffer_size;
413         }
414
415         if (clear_bytes > 0) {
416                 clear_capture_buf(capt, clear_bytes);
417                 capt->silent_size = 0;
418         }
419 }
420
421 #define BYTEPOS_UPDATE_POSONLY  0
422 #define BYTEPOS_UPDATE_CLEAR    1
423 #define BYTEPOS_UPDATE_COPY     2
424
425 static void loopback_bytepos_update(struct loopback_pcm *dpcm,
426                                     unsigned int delta,
427                                     unsigned int cmd)
428 {
429         unsigned int count;
430         unsigned long last_pos;
431
432         last_pos = byte_pos(dpcm, dpcm->irq_pos);
433         dpcm->irq_pos += delta * dpcm->pcm_bps;
434         count = byte_pos(dpcm, dpcm->irq_pos) - last_pos;
435         if (!count)
436                 return;
437         if (cmd == BYTEPOS_UPDATE_CLEAR)
438                 clear_capture_buf(dpcm, count);
439         else if (cmd == BYTEPOS_UPDATE_COPY)
440                 copy_play_buf(dpcm->cable->streams[SNDRV_PCM_STREAM_PLAYBACK],
441                               dpcm->cable->streams[SNDRV_PCM_STREAM_CAPTURE],
442                               count);
443         dpcm->buf_pos += count;
444         dpcm->buf_pos %= dpcm->pcm_buffer_size;
445         if (dpcm->irq_pos >= dpcm->period_size_frac) {
446                 dpcm->irq_pos %= dpcm->period_size_frac;
447                 dpcm->period_update_pending = 1;
448         }
449 }
450
451 static void loopback_pos_update(struct loopback_cable *cable)
452 {
453         struct loopback_pcm *dpcm_play =
454                         cable->streams[SNDRV_PCM_STREAM_PLAYBACK];
455         struct loopback_pcm *dpcm_capt =
456                         cable->streams[SNDRV_PCM_STREAM_CAPTURE];
457         unsigned long delta_play = 0, delta_capt = 0;
458
459         spin_lock(&cable->lock);        
460         if (cable->running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) {
461                 delta_play = jiffies - dpcm_play->last_jiffies;
462                 dpcm_play->last_jiffies += delta_play;
463         }
464
465         if (cable->running & (1 << SNDRV_PCM_STREAM_CAPTURE)) {
466                 delta_capt = jiffies - dpcm_capt->last_jiffies;
467                 dpcm_capt->last_jiffies += delta_capt;
468         }
469
470         if (delta_play == 0 && delta_capt == 0) {
471                 spin_unlock(&cable->lock);
472                 return;
473         }
474                 
475         if (delta_play > delta_capt) {
476                 loopback_bytepos_update(dpcm_play, delta_play - delta_capt,
477                                         BYTEPOS_UPDATE_POSONLY);
478                 delta_play = delta_capt;
479         } else if (delta_play < delta_capt) {
480                 loopback_bytepos_update(dpcm_capt, delta_capt - delta_play,
481                                         BYTEPOS_UPDATE_CLEAR);
482                 delta_capt = delta_play;
483         }
484
485         if (delta_play == 0 && delta_capt == 0) {
486                 spin_unlock(&cable->lock);
487                 return;
488         }
489         /* note delta_capt == delta_play at this moment */
490         loopback_bytepos_update(dpcm_capt, delta_capt, BYTEPOS_UPDATE_COPY);
491         loopback_bytepos_update(dpcm_play, delta_play, BYTEPOS_UPDATE_POSONLY);
492         spin_unlock(&cable->lock);
493 }
494
495 static void loopback_timer_function(unsigned long data)
496 {
497         struct loopback_pcm *dpcm = (struct loopback_pcm *)data;
498         int stream;
499
500         loopback_pos_update(dpcm->cable);
501         stream = dpcm->substream->stream;
502         if (dpcm->cable->running & (1 << stream))
503                 loopback_timer_start(dpcm);
504         if (dpcm->period_update_pending) {
505                 dpcm->period_update_pending = 0;
506                 if (dpcm->cable->running & (1 << stream))
507                         snd_pcm_period_elapsed(dpcm->substream);
508         }
509 }
510
511 static snd_pcm_uframes_t loopback_pointer(struct snd_pcm_substream *substream)
512 {
513         struct snd_pcm_runtime *runtime = substream->runtime;
514         struct loopback_pcm *dpcm = runtime->private_data;
515
516         loopback_pos_update(dpcm->cable);
517         return bytes_to_frames(runtime, dpcm->buf_pos);
518 }
519
520 static struct snd_pcm_hardware loopback_pcm_hardware =
521 {
522         .info =         (SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP |
523                          SNDRV_PCM_INFO_MMAP_VALID),
524         .formats =      (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE |
525                          SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE |
526                          SNDRV_PCM_FMTBIT_FLOAT_LE | SNDRV_PCM_FMTBIT_FLOAT_BE),
527         .rates =        SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_192000,
528         .rate_min =             8000,
529         .rate_max =             192000,
530         .channels_min =         1,
531         .channels_max =         32,
532         .buffer_bytes_max =     2 * 1024 * 1024,
533         .period_bytes_min =     64,
534         .period_bytes_max =     2 * 1024 * 1024,
535         .periods_min =          1,
536         .periods_max =          1024,
537         .fifo_size =            0,
538 };
539
540 static void loopback_runtime_free(struct snd_pcm_runtime *runtime)
541 {
542         struct loopback_pcm *dpcm = runtime->private_data;
543         kfree(dpcm);
544 }
545
546 static int loopback_hw_params(struct snd_pcm_substream *substream,
547                               struct snd_pcm_hw_params *params)
548 {
549         return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(params));
550 }
551
552 static int loopback_hw_free(struct snd_pcm_substream *substream)
553 {
554         struct snd_pcm_runtime *runtime = substream->runtime;
555         struct loopback_pcm *dpcm = runtime->private_data;
556         struct loopback_cable *cable = dpcm->cable;
557
558         mutex_lock(&dpcm->loopback->cable_lock);
559         cable->valid &= ~(1 << substream->stream);
560         mutex_unlock(&dpcm->loopback->cable_lock);
561         return snd_pcm_lib_free_pages(substream);
562 }
563
564 static unsigned int get_cable_index(struct snd_pcm_substream *substream)
565 {
566         if (!substream->pcm->device)
567                 return substream->stream;
568         else
569                 return !substream->stream;
570 }
571
572 static int rule_format(struct snd_pcm_hw_params *params,
573                        struct snd_pcm_hw_rule *rule)
574 {
575
576         struct snd_pcm_hardware *hw = rule->private;
577         struct snd_mask *maskp = hw_param_mask(params, rule->var);
578
579         maskp->bits[0] &= (u_int32_t)hw->formats;
580         maskp->bits[1] &= (u_int32_t)(hw->formats >> 32);
581         memset(maskp->bits + 2, 0, (SNDRV_MASK_MAX-64) / 8); /* clear rest */
582         if (! maskp->bits[0] && ! maskp->bits[1])
583                 return -EINVAL;
584         return 0;
585 }
586
587 static int rule_rate(struct snd_pcm_hw_params *params,
588                      struct snd_pcm_hw_rule *rule)
589 {
590         struct snd_pcm_hardware *hw = rule->private;
591         struct snd_interval t;
592
593         t.min = hw->rate_min;
594         t.max = hw->rate_max;
595         t.openmin = t.openmax = 0;
596         t.integer = 0;
597         return snd_interval_refine(hw_param_interval(params, rule->var), &t);
598 }
599
600 static int rule_channels(struct snd_pcm_hw_params *params,
601                          struct snd_pcm_hw_rule *rule)
602 {
603         struct snd_pcm_hardware *hw = rule->private;
604         struct snd_interval t;
605
606         t.min = hw->channels_min;
607         t.max = hw->channels_max;
608         t.openmin = t.openmax = 0;
609         t.integer = 0;
610         return snd_interval_refine(hw_param_interval(params, rule->var), &t);
611 }
612
613 static int loopback_open(struct snd_pcm_substream *substream)
614 {
615         struct snd_pcm_runtime *runtime = substream->runtime;
616         struct loopback *loopback = substream->private_data;
617         struct loopback_pcm *dpcm;
618         struct loopback_cable *cable;
619         int err = 0;
620         int dev = get_cable_index(substream);
621
622         mutex_lock(&loopback->cable_lock);
623         dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
624         if (!dpcm) {
625                 err = -ENOMEM;
626                 goto unlock;
627         }
628         dpcm->loopback = loopback;
629         dpcm->substream = substream;
630         setup_timer(&dpcm->timer, loopback_timer_function,
631                     (unsigned long)dpcm);
632
633         cable = loopback->cables[substream->number][dev];
634         if (!cable) {
635                 cable = kzalloc(sizeof(*cable), GFP_KERNEL);
636                 if (!cable) {
637                         kfree(dpcm);
638                         err = -ENOMEM;
639                         goto unlock;
640                 }
641                 spin_lock_init(&cable->lock);
642                 cable->hw = loopback_pcm_hardware;
643                 loopback->cables[substream->number][dev] = cable;
644         }
645         dpcm->cable = cable;
646         cable->streams[substream->stream] = dpcm;
647
648         snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
649
650         /* use dynamic rules based on actual runtime->hw values */
651         /* note that the default rules created in the PCM midlevel code */
652         /* are cached -> they do not reflect the actual state */
653         err = snd_pcm_hw_rule_add(runtime, 0,
654                                   SNDRV_PCM_HW_PARAM_FORMAT,
655                                   rule_format, &runtime->hw,
656                                   SNDRV_PCM_HW_PARAM_FORMAT, -1);
657         if (err < 0)
658                 goto unlock;
659         err = snd_pcm_hw_rule_add(runtime, 0,
660                                   SNDRV_PCM_HW_PARAM_RATE,
661                                   rule_rate, &runtime->hw,
662                                   SNDRV_PCM_HW_PARAM_RATE, -1);
663         if (err < 0)
664                 goto unlock;
665         err = snd_pcm_hw_rule_add(runtime, 0,
666                                   SNDRV_PCM_HW_PARAM_CHANNELS,
667                                   rule_channels, &runtime->hw,
668                                   SNDRV_PCM_HW_PARAM_CHANNELS, -1);
669         if (err < 0)
670                 goto unlock;
671
672         runtime->private_data = dpcm;
673         runtime->private_free = loopback_runtime_free;
674         if (get_notify(dpcm))
675                 runtime->hw = loopback_pcm_hardware;
676         else
677                 runtime->hw = cable->hw;
678  unlock:
679         mutex_unlock(&loopback->cable_lock);
680         return err;
681 }
682
683 static int loopback_close(struct snd_pcm_substream *substream)
684 {
685         struct loopback *loopback = substream->private_data;
686         struct loopback_pcm *dpcm = substream->runtime->private_data;
687         struct loopback_cable *cable;
688         int dev = get_cable_index(substream);
689
690         loopback_timer_stop(dpcm);
691         mutex_lock(&loopback->cable_lock);
692         cable = loopback->cables[substream->number][dev];
693         if (cable->streams[!substream->stream]) {
694                 /* other stream is still alive */
695                 cable->streams[substream->stream] = NULL;
696         } else {
697                 /* free the cable */
698                 loopback->cables[substream->number][dev] = NULL;
699                 kfree(cable);
700         }
701         mutex_unlock(&loopback->cable_lock);
702         return 0;
703 }
704
705 static struct snd_pcm_ops loopback_playback_ops = {
706         .open =         loopback_open,
707         .close =        loopback_close,
708         .ioctl =        snd_pcm_lib_ioctl,
709         .hw_params =    loopback_hw_params,
710         .hw_free =      loopback_hw_free,
711         .prepare =      loopback_prepare,
712         .trigger =      loopback_trigger,
713         .pointer =      loopback_pointer,
714 };
715
716 static struct snd_pcm_ops loopback_capture_ops = {
717         .open =         loopback_open,
718         .close =        loopback_close,
719         .ioctl =        snd_pcm_lib_ioctl,
720         .hw_params =    loopback_hw_params,
721         .hw_free =      loopback_hw_free,
722         .prepare =      loopback_prepare,
723         .trigger =      loopback_trigger,
724         .pointer =      loopback_pointer,
725 };
726
727 static int __devinit loopback_pcm_new(struct loopback *loopback,
728                                       int device, int substreams)
729 {
730         struct snd_pcm *pcm;
731         int err;
732
733         err = snd_pcm_new(loopback->card, "Loopback PCM", device,
734                           substreams, substreams, &pcm);
735         if (err < 0)
736                 return err;
737         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &loopback_playback_ops);
738         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &loopback_capture_ops);
739
740         pcm->private_data = loopback;
741         pcm->info_flags = 0;
742         strcpy(pcm->name, "Loopback PCM");
743
744         loopback->pcm[device] = pcm;
745
746         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
747                         snd_dma_continuous_data(GFP_KERNEL),
748                         0, 2 * 1024 * 1024);
749         return 0;
750 }
751
752 static int loopback_rate_shift_info(struct snd_kcontrol *kcontrol,   
753                                     struct snd_ctl_elem_info *uinfo) 
754 {
755         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
756         uinfo->count = 1;
757         uinfo->value.integer.min = 80000;
758         uinfo->value.integer.max = 120000;
759         uinfo->value.integer.step = 1;
760         return 0;
761 }                                  
762
763 static int loopback_rate_shift_get(struct snd_kcontrol *kcontrol,
764                                    struct snd_ctl_elem_value *ucontrol)
765 {
766         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
767         
768         ucontrol->value.integer.value[0] =
769                 loopback->setup[kcontrol->id.subdevice]
770                                [kcontrol->id.device].rate_shift;
771         return 0;
772 }
773
774 static int loopback_rate_shift_put(struct snd_kcontrol *kcontrol,
775                                    struct snd_ctl_elem_value *ucontrol)
776 {
777         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
778         unsigned int val;
779         int change = 0;
780
781         val = ucontrol->value.integer.value[0];
782         if (val < 80000)
783                 val = 80000;
784         if (val > 120000)
785                 val = 120000;   
786         mutex_lock(&loopback->cable_lock);
787         if (val != loopback->setup[kcontrol->id.subdevice]
788                                   [kcontrol->id.device].rate_shift) {
789                 loopback->setup[kcontrol->id.subdevice]
790                                [kcontrol->id.device].rate_shift = val;
791                 change = 1;
792         }
793         mutex_unlock(&loopback->cable_lock);
794         return change;
795 }
796
797 static int loopback_notify_get(struct snd_kcontrol *kcontrol,
798                                struct snd_ctl_elem_value *ucontrol)
799 {
800         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
801         
802         ucontrol->value.integer.value[0] =
803                 loopback->setup[kcontrol->id.subdevice]
804                                [kcontrol->id.device].notify;
805         return 0;
806 }
807
808 static int loopback_notify_put(struct snd_kcontrol *kcontrol,
809                                struct snd_ctl_elem_value *ucontrol)
810 {
811         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
812         unsigned int val;
813         int change = 0;
814
815         val = ucontrol->value.integer.value[0] ? 1 : 0;
816         if (val != loopback->setup[kcontrol->id.subdevice]
817                                 [kcontrol->id.device].notify) {
818                 loopback->setup[kcontrol->id.subdevice]
819                         [kcontrol->id.device].notify = val;
820                 change = 1;
821         }
822         return change;
823 }
824
825 static int loopback_active_get(struct snd_kcontrol *kcontrol,
826                                struct snd_ctl_elem_value *ucontrol)
827 {
828         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
829         struct loopback_cable *cable = loopback->cables
830                         [kcontrol->id.subdevice][kcontrol->id.device ^ 1];
831         unsigned int val = 0;
832
833         if (cable != NULL)
834                 val = (cable->running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ?
835                                                                         1 : 0;
836         ucontrol->value.integer.value[0] = val;
837         return 0;
838 }
839
840 static int loopback_format_info(struct snd_kcontrol *kcontrol,   
841                                 struct snd_ctl_elem_info *uinfo) 
842 {
843         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
844         uinfo->count = 1;
845         uinfo->value.integer.min = 0;
846         uinfo->value.integer.max = SNDRV_PCM_FORMAT_LAST;
847         uinfo->value.integer.step = 1;
848         return 0;
849 }                                  
850
851 static int loopback_format_get(struct snd_kcontrol *kcontrol,
852                                struct snd_ctl_elem_value *ucontrol)
853 {
854         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
855         
856         ucontrol->value.integer.value[0] =
857                 loopback->setup[kcontrol->id.subdevice]
858                                [kcontrol->id.device].format;
859         return 0;
860 }
861
862 static int loopback_rate_info(struct snd_kcontrol *kcontrol,   
863                               struct snd_ctl_elem_info *uinfo) 
864 {
865         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
866         uinfo->count = 1;
867         uinfo->value.integer.min = 0;
868         uinfo->value.integer.max = 192000;
869         uinfo->value.integer.step = 1;
870         return 0;
871 }                                  
872
873 static int loopback_rate_get(struct snd_kcontrol *kcontrol,
874                              struct snd_ctl_elem_value *ucontrol)
875 {
876         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
877         
878         ucontrol->value.integer.value[0] =
879                 loopback->setup[kcontrol->id.subdevice]
880                                [kcontrol->id.device].rate;
881         return 0;
882 }
883
884 static int loopback_channels_info(struct snd_kcontrol *kcontrol,   
885                                   struct snd_ctl_elem_info *uinfo) 
886 {
887         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
888         uinfo->count = 1;
889         uinfo->value.integer.min = 1;
890         uinfo->value.integer.max = 1024;
891         uinfo->value.integer.step = 1;
892         return 0;
893 }                                  
894
895 static int loopback_channels_get(struct snd_kcontrol *kcontrol,
896                                  struct snd_ctl_elem_value *ucontrol)
897 {
898         struct loopback *loopback = snd_kcontrol_chip(kcontrol);
899         
900         ucontrol->value.integer.value[0] =
901                 loopback->setup[kcontrol->id.subdevice]
902                                [kcontrol->id.device].channels;
903         return 0;
904 }
905
906 static struct snd_kcontrol_new loopback_controls[]  __devinitdata = {
907 {
908         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
909         .name =         "PCM Rate Shift 100000",
910         .info =         loopback_rate_shift_info,
911         .get =          loopback_rate_shift_get,
912         .put =          loopback_rate_shift_put,
913 },
914 {
915         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
916         .name =         "PCM Notify",
917         .info =         snd_ctl_boolean_mono_info,
918         .get =          loopback_notify_get,
919         .put =          loopback_notify_put,
920 },
921 #define ACTIVE_IDX 2
922 {
923         .access =       SNDRV_CTL_ELEM_ACCESS_READ,
924         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
925         .name =         "PCM Slave Active",
926         .info =         snd_ctl_boolean_mono_info,
927         .get =          loopback_active_get,
928 },
929 #define FORMAT_IDX 3
930 {
931         .access =       SNDRV_CTL_ELEM_ACCESS_READ,
932         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
933         .name =         "PCM Slave Format",
934         .info =         loopback_format_info,
935         .get =          loopback_format_get
936 },
937 #define RATE_IDX 4
938 {
939         .access =       SNDRV_CTL_ELEM_ACCESS_READ,
940         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
941         .name =         "PCM Slave Rate",
942         .info =         loopback_rate_info,
943         .get =          loopback_rate_get
944 },
945 #define CHANNELS_IDX 5
946 {
947         .access =       SNDRV_CTL_ELEM_ACCESS_READ,
948         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
949         .name =         "PCM Slave Channels",
950         .info =         loopback_channels_info,
951         .get =          loopback_channels_get
952 }
953 };
954
955 static int __devinit loopback_mixer_new(struct loopback *loopback, int notify)
956 {
957         struct snd_card *card = loopback->card;
958         struct snd_pcm *pcm;
959         struct snd_kcontrol *kctl;
960         struct loopback_setup *setup;
961         int err, dev, substr, substr_count, idx;
962
963         strcpy(card->mixername, "Loopback Mixer");
964         for (dev = 0; dev < 2; dev++) {
965                 pcm = loopback->pcm[dev];
966                 substr_count =
967                     pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream_count;
968                 for (substr = 0; substr < substr_count; substr++) {
969                         setup = &loopback->setup[substr][dev];
970                         setup->notify = notify;
971                         setup->rate_shift = NO_PITCH;
972                         setup->format = SNDRV_PCM_FORMAT_S16_LE;
973                         setup->rate = 48000;
974                         setup->channels = 2;
975                         for (idx = 0; idx < ARRAY_SIZE(loopback_controls);
976                                                                         idx++) {
977                                 kctl = snd_ctl_new1(&loopback_controls[idx],
978                                                     loopback);
979                                 if (!kctl)
980                                         return -ENOMEM;
981                                 kctl->id.device = dev;
982                                 kctl->id.subdevice = substr;
983                                 switch (idx) {
984                                 case ACTIVE_IDX:
985                                         setup->active_id = kctl->id;
986                                         break;
987                                 case FORMAT_IDX:
988                                         setup->format_id = kctl->id;
989                                         break;
990                                 case RATE_IDX:
991                                         setup->rate_id = kctl->id;
992                                         break;
993                                 case CHANNELS_IDX:
994                                         setup->channels_id = kctl->id;
995                                         break;
996                                 default:
997                                         break;
998                                 }
999                                 err = snd_ctl_add(card, kctl);
1000                                 if (err < 0)
1001                                         return err;
1002                         }
1003                 }
1004         }
1005         return 0;
1006 }
1007
1008 static int __devinit loopback_probe(struct platform_device *devptr)
1009 {
1010         struct snd_card *card;
1011         struct loopback *loopback;
1012         int dev = devptr->id;
1013         int err;
1014
1015         err = snd_card_create(index[dev], id[dev], THIS_MODULE,
1016                               sizeof(struct loopback), &card);
1017         if (err < 0)
1018                 return err;
1019         loopback = card->private_data;
1020
1021         if (pcm_substreams[dev] < 1)
1022                 pcm_substreams[dev] = 1;
1023         if (pcm_substreams[dev] > MAX_PCM_SUBSTREAMS)
1024                 pcm_substreams[dev] = MAX_PCM_SUBSTREAMS;
1025         
1026         loopback->card = card;
1027         mutex_init(&loopback->cable_lock);
1028
1029         err = loopback_pcm_new(loopback, 0, pcm_substreams[dev]);
1030         if (err < 0)
1031                 goto __nodev;
1032         err = loopback_pcm_new(loopback, 1, pcm_substreams[dev]);
1033         if (err < 0)
1034                 goto __nodev;
1035         err = loopback_mixer_new(loopback, pcm_notify[dev] ? 1 : 0);
1036         if (err < 0)
1037                 goto __nodev;
1038         strcpy(card->driver, "Loopback");
1039         strcpy(card->shortname, "Loopback");
1040         sprintf(card->longname, "Loopback %i", dev + 1);
1041         err = snd_card_register(card);
1042         if (!err) {
1043                 platform_set_drvdata(devptr, card);
1044                 return 0;
1045         }
1046       __nodev:
1047         snd_card_free(card);
1048         return err;
1049 }
1050
1051 static int __devexit loopback_remove(struct platform_device *devptr)
1052 {
1053         snd_card_free(platform_get_drvdata(devptr));
1054         platform_set_drvdata(devptr, NULL);
1055         return 0;
1056 }
1057
1058 #ifdef CONFIG_PM
1059 static int loopback_suspend(struct platform_device *pdev,
1060                                 pm_message_t state)
1061 {
1062         struct snd_card *card = platform_get_drvdata(pdev);
1063         struct loopback *loopback = card->private_data;
1064
1065         snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
1066
1067         snd_pcm_suspend_all(loopback->pcm[0]);
1068         snd_pcm_suspend_all(loopback->pcm[1]);
1069         return 0;
1070 }
1071         
1072 static int loopback_resume(struct platform_device *pdev)
1073 {
1074         struct snd_card *card = platform_get_drvdata(pdev);
1075
1076         snd_power_change_state(card, SNDRV_CTL_POWER_D0);
1077         return 0;
1078 }
1079 #endif
1080
1081 #define SND_LOOPBACK_DRIVER     "snd_aloop"
1082
1083 static struct platform_driver loopback_driver = {
1084         .probe          = loopback_probe,
1085         .remove         = __devexit_p(loopback_remove),
1086 #ifdef CONFIG_PM
1087         .suspend        = loopback_suspend,
1088         .resume         = loopback_resume,
1089 #endif
1090         .driver         = {
1091                 .name   = SND_LOOPBACK_DRIVER
1092         },
1093 };
1094
1095 static void loopback_unregister_all(void)
1096 {
1097         int i;
1098
1099         for (i = 0; i < ARRAY_SIZE(devices); ++i)
1100                 platform_device_unregister(devices[i]);
1101         platform_driver_unregister(&loopback_driver);
1102 }
1103
1104 static int __init alsa_card_loopback_init(void)
1105 {
1106         int i, err, cards;
1107
1108         err = platform_driver_register(&loopback_driver);
1109         if (err < 0)
1110                 return err;
1111
1112
1113         cards = 0;
1114         for (i = 0; i < SNDRV_CARDS; i++) {
1115                 struct platform_device *device;
1116                 if (!enable[i])
1117                         continue;
1118                 device = platform_device_register_simple(SND_LOOPBACK_DRIVER,
1119                                                          i, NULL, 0);
1120                 if (IS_ERR(device))
1121                         continue;
1122                 if (!platform_get_drvdata(device)) {
1123                         platform_device_unregister(device);
1124                         continue;
1125                 }
1126                 devices[i] = device;
1127                 cards++;
1128         }
1129         if (!cards) {
1130 #ifdef MODULE
1131                 printk(KERN_ERR "aloop: No loopback enabled\n");
1132 #endif
1133                 loopback_unregister_all();
1134                 return -ENODEV;
1135         }
1136         return 0;
1137 }
1138
1139 static void __exit alsa_card_loopback_exit(void)
1140 {
1141         loopback_unregister_all();
1142 }
1143
1144 module_init(alsa_card_loopback_init)
1145 module_exit(alsa_card_loopback_exit)