Merge commit alsa/devel into topic/misc
[safe/jmp/linux-2.6] / sound / core / pcm_lib.c
1 /*
2  *  Digital Audio (PCM) abstract layer
3  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
4  *                   Abramo Bagnara <abramo@alsa-project.org>
5  *
6  *
7  *   This program is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU General Public License as published by
9  *   the Free Software Foundation; either version 2 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This program is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with this program; if not, write to the Free Software
19  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20  *
21  */
22
23 #include <linux/slab.h>
24 #include <linux/time.h>
25 #include <linux/math64.h>
26 #include <sound/core.h>
27 #include <sound/control.h>
28 #include <sound/info.h>
29 #include <sound/pcm.h>
30 #include <sound/pcm_params.h>
31 #include <sound/timer.h>
32
33 /*
34  * fill ring buffer with silence
35  * runtime->silence_start: starting pointer to silence area
36  * runtime->silence_filled: size filled with silence
37  * runtime->silence_threshold: threshold from application
38  * runtime->silence_size: maximal size from application
39  *
40  * when runtime->silence_size >= runtime->boundary - fill processed area with silence immediately
41  */
42 void snd_pcm_playback_silence(struct snd_pcm_substream *substream, snd_pcm_uframes_t new_hw_ptr)
43 {
44         struct snd_pcm_runtime *runtime = substream->runtime;
45         snd_pcm_uframes_t frames, ofs, transfer;
46
47         if (runtime->silence_size < runtime->boundary) {
48                 snd_pcm_sframes_t noise_dist, n;
49                 if (runtime->silence_start != runtime->control->appl_ptr) {
50                         n = runtime->control->appl_ptr - runtime->silence_start;
51                         if (n < 0)
52                                 n += runtime->boundary;
53                         if ((snd_pcm_uframes_t)n < runtime->silence_filled)
54                                 runtime->silence_filled -= n;
55                         else
56                                 runtime->silence_filled = 0;
57                         runtime->silence_start = runtime->control->appl_ptr;
58                 }
59                 if (runtime->silence_filled >= runtime->buffer_size)
60                         return;
61                 noise_dist = snd_pcm_playback_hw_avail(runtime) + runtime->silence_filled;
62                 if (noise_dist >= (snd_pcm_sframes_t) runtime->silence_threshold)
63                         return;
64                 frames = runtime->silence_threshold - noise_dist;
65                 if (frames > runtime->silence_size)
66                         frames = runtime->silence_size;
67         } else {
68                 if (new_hw_ptr == ULONG_MAX) {  /* initialization */
69                         snd_pcm_sframes_t avail = snd_pcm_playback_hw_avail(runtime);
70                         runtime->silence_filled = avail > 0 ? avail : 0;
71                         runtime->silence_start = (runtime->status->hw_ptr +
72                                                   runtime->silence_filled) %
73                                                  runtime->boundary;
74                 } else {
75                         ofs = runtime->status->hw_ptr;
76                         frames = new_hw_ptr - ofs;
77                         if ((snd_pcm_sframes_t)frames < 0)
78                                 frames += runtime->boundary;
79                         runtime->silence_filled -= frames;
80                         if ((snd_pcm_sframes_t)runtime->silence_filled < 0) {
81                                 runtime->silence_filled = 0;
82                                 runtime->silence_start = new_hw_ptr;
83                         } else {
84                                 runtime->silence_start = ofs;
85                         }
86                 }
87                 frames = runtime->buffer_size - runtime->silence_filled;
88         }
89         if (snd_BUG_ON(frames > runtime->buffer_size))
90                 return;
91         if (frames == 0)
92                 return;
93         ofs = runtime->silence_start % runtime->buffer_size;
94         while (frames > 0) {
95                 transfer = ofs + frames > runtime->buffer_size ? runtime->buffer_size - ofs : frames;
96                 if (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED ||
97                     runtime->access == SNDRV_PCM_ACCESS_MMAP_INTERLEAVED) {
98                         if (substream->ops->silence) {
99                                 int err;
100                                 err = substream->ops->silence(substream, -1, ofs, transfer);
101                                 snd_BUG_ON(err < 0);
102                         } else {
103                                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, ofs);
104                                 snd_pcm_format_set_silence(runtime->format, hwbuf, transfer * runtime->channels);
105                         }
106                 } else {
107                         unsigned int c;
108                         unsigned int channels = runtime->channels;
109                         if (substream->ops->silence) {
110                                 for (c = 0; c < channels; ++c) {
111                                         int err;
112                                         err = substream->ops->silence(substream, c, ofs, transfer);
113                                         snd_BUG_ON(err < 0);
114                                 }
115                         } else {
116                                 size_t dma_csize = runtime->dma_bytes / channels;
117                                 for (c = 0; c < channels; ++c) {
118                                         char *hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, ofs);
119                                         snd_pcm_format_set_silence(runtime->format, hwbuf, transfer);
120                                 }
121                         }
122                 }
123                 runtime->silence_filled += transfer;
124                 frames -= transfer;
125                 ofs = 0;
126         }
127 }
128
129 static void pcm_debug_name(struct snd_pcm_substream *substream,
130                            char *name, size_t len)
131 {
132         snprintf(name, len, "pcmC%dD%d%c:%d",
133                  substream->pcm->card->number,
134                  substream->pcm->device,
135                  substream->stream ? 'c' : 'p',
136                  substream->number);
137 }
138
139 #define XRUN_DEBUG_BASIC        (1<<0)
140 #define XRUN_DEBUG_STACK        (1<<1)  /* dump also stack */
141 #define XRUN_DEBUG_JIFFIESCHECK (1<<2)  /* do jiffies check */
142 #define XRUN_DEBUG_PERIODUPDATE (1<<3)  /* full period update info */
143 #define XRUN_DEBUG_HWPTRUPDATE  (1<<4)  /* full hwptr update info */
144 #define XRUN_DEBUG_LOG          (1<<5)  /* show last 10 positions on err */
145 #define XRUN_DEBUG_LOGONCE      (1<<6)  /* do above only once */
146
147 #ifdef CONFIG_SND_PCM_XRUN_DEBUG
148
149 #define xrun_debug(substream, mask) \
150                         ((substream)->pstr->xrun_debug & (mask))
151
152 #define dump_stack_on_xrun(substream) do {                      \
153                 if (xrun_debug(substream, XRUN_DEBUG_STACK))    \
154                         dump_stack();                           \
155         } while (0)
156
157 static void xrun(struct snd_pcm_substream *substream)
158 {
159         struct snd_pcm_runtime *runtime = substream->runtime;
160
161         if (runtime->tstamp_mode == SNDRV_PCM_TSTAMP_ENABLE)
162                 snd_pcm_gettime(runtime, (struct timespec *)&runtime->status->tstamp);
163         snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
164         if (xrun_debug(substream, XRUN_DEBUG_BASIC)) {
165                 char name[16];
166                 pcm_debug_name(substream, name, sizeof(name));
167                 snd_printd(KERN_DEBUG "XRUN: %s\n", name);
168                 dump_stack_on_xrun(substream);
169         }
170 }
171
172 #define hw_ptr_error(substream, fmt, args...)                           \
173         do {                                                            \
174                 if (xrun_debug(substream, XRUN_DEBUG_BASIC)) {          \
175                         xrun_log_show(substream);                       \
176                         if (printk_ratelimit()) {                       \
177                                 snd_printd("PCM: " fmt, ##args);        \
178                         }                                               \
179                         dump_stack_on_xrun(substream);                  \
180                 }                                                       \
181         } while (0)
182
183 #define XRUN_LOG_CNT    10
184
185 struct hwptr_log_entry {
186         unsigned long jiffies;
187         snd_pcm_uframes_t pos;
188         snd_pcm_uframes_t period_size;
189         snd_pcm_uframes_t buffer_size;
190         snd_pcm_uframes_t old_hw_ptr;
191         snd_pcm_uframes_t hw_ptr_base;
192 };
193
194 struct snd_pcm_hwptr_log {
195         unsigned int idx;
196         unsigned int hit: 1;
197         struct hwptr_log_entry entries[XRUN_LOG_CNT];
198 };
199
200 static void xrun_log(struct snd_pcm_substream *substream,
201                      snd_pcm_uframes_t pos)
202 {
203         struct snd_pcm_runtime *runtime = substream->runtime;
204         struct snd_pcm_hwptr_log *log = runtime->hwptr_log;
205         struct hwptr_log_entry *entry;
206
207         if (log == NULL) {
208                 log = kzalloc(sizeof(*log), GFP_ATOMIC);
209                 if (log == NULL)
210                         return;
211                 runtime->hwptr_log = log;
212         } else {
213                 if (xrun_debug(substream, XRUN_DEBUG_LOGONCE) && log->hit)
214                         return;
215         }
216         entry = &log->entries[log->idx];
217         entry->jiffies = jiffies;
218         entry->pos = pos;
219         entry->period_size = runtime->period_size;
220         entry->buffer_size = runtime->buffer_size;;
221         entry->old_hw_ptr = runtime->status->hw_ptr;
222         entry->hw_ptr_base = runtime->hw_ptr_base;
223         log->idx = (log->idx + 1) % XRUN_LOG_CNT;
224 }
225
226 static void xrun_log_show(struct snd_pcm_substream *substream)
227 {
228         struct snd_pcm_hwptr_log *log = substream->runtime->hwptr_log;
229         struct hwptr_log_entry *entry;
230         char name[16];
231         unsigned int idx;
232         int cnt;
233
234         if (log == NULL)
235                 return;
236         if (xrun_debug(substream, XRUN_DEBUG_LOGONCE) && log->hit)
237                 return;
238         pcm_debug_name(substream, name, sizeof(name));
239         for (cnt = 0, idx = log->idx; cnt < XRUN_LOG_CNT; cnt++) {
240                 entry = &log->entries[idx];
241                 if (entry->period_size == 0)
242                         break;
243                 snd_printd("hwptr log: %s: j=%lu, pos=%ld/%ld/%ld, "
244                            "hwptr=%ld/%ld\n",
245                            name, entry->jiffies, (unsigned long)entry->pos,
246                            (unsigned long)entry->period_size,
247                            (unsigned long)entry->buffer_size,
248                            (unsigned long)entry->old_hw_ptr,
249                            (unsigned long)entry->hw_ptr_base);
250                 idx++;
251                 idx %= XRUN_LOG_CNT;
252         }
253         log->hit = 1;
254 }
255
256 #else /* ! CONFIG_SND_PCM_XRUN_DEBUG */
257
258 #define xrun_debug(substream, mask)     0
259 #define xrun(substream)                 do { } while (0)
260 #define hw_ptr_error(substream, fmt, args...) do { } while (0)
261 #define xrun_log(substream, pos)        do { } while (0)
262 #define xrun_log_show(substream)        do { } while (0)
263
264 #endif
265
266 int snd_pcm_update_state(struct snd_pcm_substream *substream,
267                          struct snd_pcm_runtime *runtime)
268 {
269         snd_pcm_uframes_t avail;
270
271         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
272                 avail = snd_pcm_playback_avail(runtime);
273         else
274                 avail = snd_pcm_capture_avail(runtime);
275         if (avail > runtime->avail_max)
276                 runtime->avail_max = avail;
277         if (runtime->status->state == SNDRV_PCM_STATE_DRAINING) {
278                 if (avail >= runtime->buffer_size) {
279                         snd_pcm_drain_done(substream);
280                         return -EPIPE;
281                 }
282         } else {
283                 if (avail >= runtime->stop_threshold) {
284                         xrun(substream);
285                         return -EPIPE;
286                 }
287         }
288         if (!runtime->nowake && avail >= runtime->control->avail_min)
289                 wake_up(&runtime->sleep);
290         return 0;
291 }
292
293 static int snd_pcm_update_hw_ptr0(struct snd_pcm_substream *substream,
294                                   unsigned int in_interrupt)
295 {
296         struct snd_pcm_runtime *runtime = substream->runtime;
297         snd_pcm_uframes_t pos;
298         snd_pcm_uframes_t old_hw_ptr, new_hw_ptr, hw_base;
299         snd_pcm_sframes_t hdelta, delta;
300         unsigned long jdelta;
301
302         old_hw_ptr = runtime->status->hw_ptr;
303         pos = substream->ops->pointer(substream);
304         if (pos == SNDRV_PCM_POS_XRUN) {
305                 xrun(substream);
306                 return -EPIPE;
307         }
308         if (pos >= runtime->buffer_size) {
309                 if (printk_ratelimit()) {
310                         char name[16];
311                         pcm_debug_name(substream, name, sizeof(name));
312                         xrun_log_show(substream);
313                         snd_printd(KERN_ERR  "BUG: %s, pos = %ld, "
314                                    "buffer size = %ld, period size = %ld\n",
315                                    name, pos, runtime->buffer_size,
316                                    runtime->period_size);
317                 }
318                 pos = 0;
319         }
320         pos -= pos % runtime->min_align;
321         if (xrun_debug(substream, XRUN_DEBUG_LOG))
322                 xrun_log(substream, pos);
323         hw_base = runtime->hw_ptr_base;
324         new_hw_ptr = hw_base + pos;
325         if (in_interrupt) {
326                 /* we know that one period was processed */
327                 /* delta = "expected next hw_ptr" for in_interrupt != 0 */
328                 delta = old_hw_ptr - (old_hw_ptr % runtime->period_size)
329                         + runtime->period_size;
330                 if (delta > new_hw_ptr) {
331                         hw_base += runtime->buffer_size;
332                         if (hw_base >= runtime->boundary)
333                                 hw_base = 0;
334                         new_hw_ptr = hw_base + pos;
335                         goto __delta;
336                 }
337         }
338         /* new_hw_ptr might be lower than old_hw_ptr in case when */
339         /* pointer crosses the end of the ring buffer */
340         if (new_hw_ptr < old_hw_ptr) {
341                 hw_base += runtime->buffer_size;
342                 if (hw_base >= runtime->boundary)
343                         hw_base = 0;
344                 new_hw_ptr = hw_base + pos;
345         }
346       __delta:
347         delta = (new_hw_ptr - old_hw_ptr) % runtime->boundary;
348         if (xrun_debug(substream, in_interrupt ?
349                         XRUN_DEBUG_PERIODUPDATE : XRUN_DEBUG_HWPTRUPDATE)) {
350                 char name[16];
351                 pcm_debug_name(substream, name, sizeof(name));
352                 snd_printd("%s_update: %s: pos=%u/%u/%u, "
353                            "hwptr=%ld/%ld/%ld/%ld\n",
354                            in_interrupt ? "period" : "hwptr",
355                            name,
356                            (unsigned int)pos,
357                            (unsigned int)runtime->period_size,
358                            (unsigned int)runtime->buffer_size,
359                            (unsigned long)delta,
360                            (unsigned long)old_hw_ptr,
361                            (unsigned long)new_hw_ptr,
362                            (unsigned long)runtime->hw_ptr_base);
363         }
364         /* something must be really wrong */
365         if (delta >= runtime->buffer_size + runtime->period_size) {
366                 hw_ptr_error(substream,
367                                "Unexpected hw_pointer value %s"
368                                "(stream=%i, pos=%ld, new_hw_ptr=%ld, "
369                                "old_hw_ptr=%ld)\n",
370                                      in_interrupt ? "[Q] " : "[P]",
371                                      substream->stream, (long)pos,
372                                      (long)new_hw_ptr, (long)old_hw_ptr);
373                 return 0;
374         }
375
376         /* Do jiffies check only in xrun_debug mode */
377         if (!xrun_debug(substream, XRUN_DEBUG_JIFFIESCHECK))
378                 goto no_jiffies_check;
379
380         /* Skip the jiffies check for hardwares with BATCH flag.
381          * Such hardware usually just increases the position at each IRQ,
382          * thus it can't give any strange position.
383          */
384         if (runtime->hw.info & SNDRV_PCM_INFO_BATCH)
385                 goto no_jiffies_check;
386         hdelta = delta;
387         if (hdelta < runtime->delay)
388                 goto no_jiffies_check;
389         hdelta -= runtime->delay;
390         jdelta = jiffies - runtime->hw_ptr_jiffies;
391         if (((hdelta * HZ) / runtime->rate) > jdelta + HZ/100) {
392                 delta = jdelta /
393                         (((runtime->period_size * HZ) / runtime->rate)
394                                                                 + HZ/100);
395                 /* move new_hw_ptr according jiffies not pos variable */
396                 new_hw_ptr = old_hw_ptr;
397                 /* use loop to avoid checks for delta overflows */
398                 /* the delta value is small or zero in most cases */
399                 while (delta > 0) {
400                         new_hw_ptr += runtime->period_size;
401                         if (new_hw_ptr >= runtime->boundary)
402                                 new_hw_ptr -= runtime->boundary;
403                         delta--;
404                 }
405                 /* align hw_base to buffer_size */
406                 hw_base = new_hw_ptr - (new_hw_ptr % runtime->buffer_size);
407                 delta = 0;
408                 hw_ptr_error(substream,
409                              "hw_ptr skipping! %s"
410                              "(pos=%ld, delta=%ld, period=%ld, "
411                              "jdelta=%lu/%lu/%lu, hw_ptr=%ld/%ld)\n",
412                              in_interrupt ? "[Q] " : "",
413                              (long)pos, (long)hdelta,
414                              (long)runtime->period_size, jdelta,
415                              ((hdelta * HZ) / runtime->rate), delta,
416                              (unsigned long)old_hw_ptr,
417                              (unsigned long)new_hw_ptr);
418         }
419  no_jiffies_check:
420         if (delta > runtime->period_size + runtime->period_size / 2) {
421                 hw_ptr_error(substream,
422                              "Lost interrupts? %s"
423                              "(stream=%i, delta=%ld, new_hw_ptr=%ld, "
424                              "old_hw_ptr=%ld)\n",
425                              in_interrupt ? "[Q] " : "",
426                              substream->stream, (long)delta,
427                              (long)new_hw_ptr,
428                              (long)old_hw_ptr);
429         }
430
431         if (runtime->status->hw_ptr == new_hw_ptr)
432                 return 0;
433
434         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK &&
435             runtime->silence_size > 0)
436                 snd_pcm_playback_silence(substream, new_hw_ptr);
437
438         runtime->hw_ptr_base = hw_base;
439         runtime->status->hw_ptr = new_hw_ptr;
440         runtime->hw_ptr_jiffies = jiffies;
441         if (runtime->tstamp_mode == SNDRV_PCM_TSTAMP_ENABLE)
442                 snd_pcm_gettime(runtime, (struct timespec *)&runtime->status->tstamp);
443
444         return snd_pcm_update_state(substream, runtime);
445 }
446
447 /* CAUTION: call it with irq disabled */
448 int snd_pcm_update_hw_ptr(struct snd_pcm_substream *substream)
449 {
450         return snd_pcm_update_hw_ptr0(substream, 0);
451 }
452
453 /**
454  * snd_pcm_set_ops - set the PCM operators
455  * @pcm: the pcm instance
456  * @direction: stream direction, SNDRV_PCM_STREAM_XXX
457  * @ops: the operator table
458  *
459  * Sets the given PCM operators to the pcm instance.
460  */
461 void snd_pcm_set_ops(struct snd_pcm *pcm, int direction, struct snd_pcm_ops *ops)
462 {
463         struct snd_pcm_str *stream = &pcm->streams[direction];
464         struct snd_pcm_substream *substream;
465         
466         for (substream = stream->substream; substream != NULL; substream = substream->next)
467                 substream->ops = ops;
468 }
469
470 EXPORT_SYMBOL(snd_pcm_set_ops);
471
472 /**
473  * snd_pcm_sync - set the PCM sync id
474  * @substream: the pcm substream
475  *
476  * Sets the PCM sync identifier for the card.
477  */
478 void snd_pcm_set_sync(struct snd_pcm_substream *substream)
479 {
480         struct snd_pcm_runtime *runtime = substream->runtime;
481         
482         runtime->sync.id32[0] = substream->pcm->card->number;
483         runtime->sync.id32[1] = -1;
484         runtime->sync.id32[2] = -1;
485         runtime->sync.id32[3] = -1;
486 }
487
488 EXPORT_SYMBOL(snd_pcm_set_sync);
489
490 /*
491  *  Standard ioctl routine
492  */
493
494 static inline unsigned int div32(unsigned int a, unsigned int b, 
495                                  unsigned int *r)
496 {
497         if (b == 0) {
498                 *r = 0;
499                 return UINT_MAX;
500         }
501         *r = a % b;
502         return a / b;
503 }
504
505 static inline unsigned int div_down(unsigned int a, unsigned int b)
506 {
507         if (b == 0)
508                 return UINT_MAX;
509         return a / b;
510 }
511
512 static inline unsigned int div_up(unsigned int a, unsigned int b)
513 {
514         unsigned int r;
515         unsigned int q;
516         if (b == 0)
517                 return UINT_MAX;
518         q = div32(a, b, &r);
519         if (r)
520                 ++q;
521         return q;
522 }
523
524 static inline unsigned int mul(unsigned int a, unsigned int b)
525 {
526         if (a == 0)
527                 return 0;
528         if (div_down(UINT_MAX, a) < b)
529                 return UINT_MAX;
530         return a * b;
531 }
532
533 static inline unsigned int muldiv32(unsigned int a, unsigned int b,
534                                     unsigned int c, unsigned int *r)
535 {
536         u_int64_t n = (u_int64_t) a * b;
537         if (c == 0) {
538                 snd_BUG_ON(!n);
539                 *r = 0;
540                 return UINT_MAX;
541         }
542         n = div_u64_rem(n, c, r);
543         if (n >= UINT_MAX) {
544                 *r = 0;
545                 return UINT_MAX;
546         }
547         return n;
548 }
549
550 /**
551  * snd_interval_refine - refine the interval value of configurator
552  * @i: the interval value to refine
553  * @v: the interval value to refer to
554  *
555  * Refines the interval value with the reference value.
556  * The interval is changed to the range satisfying both intervals.
557  * The interval status (min, max, integer, etc.) are evaluated.
558  *
559  * Returns non-zero if the value is changed, zero if not changed.
560  */
561 int snd_interval_refine(struct snd_interval *i, const struct snd_interval *v)
562 {
563         int changed = 0;
564         if (snd_BUG_ON(snd_interval_empty(i)))
565                 return -EINVAL;
566         if (i->min < v->min) {
567                 i->min = v->min;
568                 i->openmin = v->openmin;
569                 changed = 1;
570         } else if (i->min == v->min && !i->openmin && v->openmin) {
571                 i->openmin = 1;
572                 changed = 1;
573         }
574         if (i->max > v->max) {
575                 i->max = v->max;
576                 i->openmax = v->openmax;
577                 changed = 1;
578         } else if (i->max == v->max && !i->openmax && v->openmax) {
579                 i->openmax = 1;
580                 changed = 1;
581         }
582         if (!i->integer && v->integer) {
583                 i->integer = 1;
584                 changed = 1;
585         }
586         if (i->integer) {
587                 if (i->openmin) {
588                         i->min++;
589                         i->openmin = 0;
590                 }
591                 if (i->openmax) {
592                         i->max--;
593                         i->openmax = 0;
594                 }
595         } else if (!i->openmin && !i->openmax && i->min == i->max)
596                 i->integer = 1;
597         if (snd_interval_checkempty(i)) {
598                 snd_interval_none(i);
599                 return -EINVAL;
600         }
601         return changed;
602 }
603
604 EXPORT_SYMBOL(snd_interval_refine);
605
606 static int snd_interval_refine_first(struct snd_interval *i)
607 {
608         if (snd_BUG_ON(snd_interval_empty(i)))
609                 return -EINVAL;
610         if (snd_interval_single(i))
611                 return 0;
612         i->max = i->min;
613         i->openmax = i->openmin;
614         if (i->openmax)
615                 i->max++;
616         return 1;
617 }
618
619 static int snd_interval_refine_last(struct snd_interval *i)
620 {
621         if (snd_BUG_ON(snd_interval_empty(i)))
622                 return -EINVAL;
623         if (snd_interval_single(i))
624                 return 0;
625         i->min = i->max;
626         i->openmin = i->openmax;
627         if (i->openmin)
628                 i->min--;
629         return 1;
630 }
631
632 void snd_interval_mul(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c)
633 {
634         if (a->empty || b->empty) {
635                 snd_interval_none(c);
636                 return;
637         }
638         c->empty = 0;
639         c->min = mul(a->min, b->min);
640         c->openmin = (a->openmin || b->openmin);
641         c->max = mul(a->max,  b->max);
642         c->openmax = (a->openmax || b->openmax);
643         c->integer = (a->integer && b->integer);
644 }
645
646 /**
647  * snd_interval_div - refine the interval value with division
648  * @a: dividend
649  * @b: divisor
650  * @c: quotient
651  *
652  * c = a / b
653  *
654  * Returns non-zero if the value is changed, zero if not changed.
655  */
656 void snd_interval_div(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c)
657 {
658         unsigned int r;
659         if (a->empty || b->empty) {
660                 snd_interval_none(c);
661                 return;
662         }
663         c->empty = 0;
664         c->min = div32(a->min, b->max, &r);
665         c->openmin = (r || a->openmin || b->openmax);
666         if (b->min > 0) {
667                 c->max = div32(a->max, b->min, &r);
668                 if (r) {
669                         c->max++;
670                         c->openmax = 1;
671                 } else
672                         c->openmax = (a->openmax || b->openmin);
673         } else {
674                 c->max = UINT_MAX;
675                 c->openmax = 0;
676         }
677         c->integer = 0;
678 }
679
680 /**
681  * snd_interval_muldivk - refine the interval value
682  * @a: dividend 1
683  * @b: dividend 2
684  * @k: divisor (as integer)
685  * @c: result
686   *
687  * c = a * b / k
688  *
689  * Returns non-zero if the value is changed, zero if not changed.
690  */
691 void snd_interval_muldivk(const struct snd_interval *a, const struct snd_interval *b,
692                       unsigned int k, struct snd_interval *c)
693 {
694         unsigned int r;
695         if (a->empty || b->empty) {
696                 snd_interval_none(c);
697                 return;
698         }
699         c->empty = 0;
700         c->min = muldiv32(a->min, b->min, k, &r);
701         c->openmin = (r || a->openmin || b->openmin);
702         c->max = muldiv32(a->max, b->max, k, &r);
703         if (r) {
704                 c->max++;
705                 c->openmax = 1;
706         } else
707                 c->openmax = (a->openmax || b->openmax);
708         c->integer = 0;
709 }
710
711 /**
712  * snd_interval_mulkdiv - refine the interval value
713  * @a: dividend 1
714  * @k: dividend 2 (as integer)
715  * @b: divisor
716  * @c: result
717  *
718  * c = a * k / b
719  *
720  * Returns non-zero if the value is changed, zero if not changed.
721  */
722 void snd_interval_mulkdiv(const struct snd_interval *a, unsigned int k,
723                       const struct snd_interval *b, struct snd_interval *c)
724 {
725         unsigned int r;
726         if (a->empty || b->empty) {
727                 snd_interval_none(c);
728                 return;
729         }
730         c->empty = 0;
731         c->min = muldiv32(a->min, k, b->max, &r);
732         c->openmin = (r || a->openmin || b->openmax);
733         if (b->min > 0) {
734                 c->max = muldiv32(a->max, k, b->min, &r);
735                 if (r) {
736                         c->max++;
737                         c->openmax = 1;
738                 } else
739                         c->openmax = (a->openmax || b->openmin);
740         } else {
741                 c->max = UINT_MAX;
742                 c->openmax = 0;
743         }
744         c->integer = 0;
745 }
746
747 /* ---- */
748
749
750 /**
751  * snd_interval_ratnum - refine the interval value
752  * @i: interval to refine
753  * @rats_count: number of ratnum_t 
754  * @rats: ratnum_t array
755  * @nump: pointer to store the resultant numerator
756  * @denp: pointer to store the resultant denominator
757  *
758  * Returns non-zero if the value is changed, zero if not changed.
759  */
760 int snd_interval_ratnum(struct snd_interval *i,
761                         unsigned int rats_count, struct snd_ratnum *rats,
762                         unsigned int *nump, unsigned int *denp)
763 {
764         unsigned int best_num, best_den;
765         int best_diff;
766         unsigned int k;
767         struct snd_interval t;
768         int err;
769         unsigned int result_num, result_den;
770         int result_diff;
771
772         best_num = best_den = best_diff = 0;
773         for (k = 0; k < rats_count; ++k) {
774                 unsigned int num = rats[k].num;
775                 unsigned int den;
776                 unsigned int q = i->min;
777                 int diff;
778                 if (q == 0)
779                         q = 1;
780                 den = div_up(num, q);
781                 if (den < rats[k].den_min)
782                         continue;
783                 if (den > rats[k].den_max)
784                         den = rats[k].den_max;
785                 else {
786                         unsigned int r;
787                         r = (den - rats[k].den_min) % rats[k].den_step;
788                         if (r != 0)
789                                 den -= r;
790                 }
791                 diff = num - q * den;
792                 if (diff < 0)
793                         diff = -diff;
794                 if (best_num == 0 ||
795                     diff * best_den < best_diff * den) {
796                         best_diff = diff;
797                         best_den = den;
798                         best_num = num;
799                 }
800         }
801         if (best_den == 0) {
802                 i->empty = 1;
803                 return -EINVAL;
804         }
805         t.min = div_down(best_num, best_den);
806         t.openmin = !!(best_num % best_den);
807         
808         result_num = best_num;
809         result_diff = best_diff;
810         result_den = best_den;
811         best_num = best_den = best_diff = 0;
812         for (k = 0; k < rats_count; ++k) {
813                 unsigned int num = rats[k].num;
814                 unsigned int den;
815                 unsigned int q = i->max;
816                 int diff;
817                 if (q == 0) {
818                         i->empty = 1;
819                         return -EINVAL;
820                 }
821                 den = div_down(num, q);
822                 if (den > rats[k].den_max)
823                         continue;
824                 if (den < rats[k].den_min)
825                         den = rats[k].den_min;
826                 else {
827                         unsigned int r;
828                         r = (den - rats[k].den_min) % rats[k].den_step;
829                         if (r != 0)
830                                 den += rats[k].den_step - r;
831                 }
832                 diff = q * den - num;
833                 if (diff < 0)
834                         diff = -diff;
835                 if (best_num == 0 ||
836                     diff * best_den < best_diff * den) {
837                         best_diff = diff;
838                         best_den = den;
839                         best_num = num;
840                 }
841         }
842         if (best_den == 0) {
843                 i->empty = 1;
844                 return -EINVAL;
845         }
846         t.max = div_up(best_num, best_den);
847         t.openmax = !!(best_num % best_den);
848         t.integer = 0;
849         err = snd_interval_refine(i, &t);
850         if (err < 0)
851                 return err;
852
853         if (snd_interval_single(i)) {
854                 if (best_diff * result_den < result_diff * best_den) {
855                         result_num = best_num;
856                         result_den = best_den;
857                 }
858                 if (nump)
859                         *nump = result_num;
860                 if (denp)
861                         *denp = result_den;
862         }
863         return err;
864 }
865
866 EXPORT_SYMBOL(snd_interval_ratnum);
867
868 /**
869  * snd_interval_ratden - refine the interval value
870  * @i: interval to refine
871  * @rats_count: number of struct ratden
872  * @rats: struct ratden array
873  * @nump: pointer to store the resultant numerator
874  * @denp: pointer to store the resultant denominator
875  *
876  * Returns non-zero if the value is changed, zero if not changed.
877  */
878 static int snd_interval_ratden(struct snd_interval *i,
879                                unsigned int rats_count, struct snd_ratden *rats,
880                                unsigned int *nump, unsigned int *denp)
881 {
882         unsigned int best_num, best_diff, best_den;
883         unsigned int k;
884         struct snd_interval t;
885         int err;
886
887         best_num = best_den = best_diff = 0;
888         for (k = 0; k < rats_count; ++k) {
889                 unsigned int num;
890                 unsigned int den = rats[k].den;
891                 unsigned int q = i->min;
892                 int diff;
893                 num = mul(q, den);
894                 if (num > rats[k].num_max)
895                         continue;
896                 if (num < rats[k].num_min)
897                         num = rats[k].num_max;
898                 else {
899                         unsigned int r;
900                         r = (num - rats[k].num_min) % rats[k].num_step;
901                         if (r != 0)
902                                 num += rats[k].num_step - r;
903                 }
904                 diff = num - q * den;
905                 if (best_num == 0 ||
906                     diff * best_den < best_diff * den) {
907                         best_diff = diff;
908                         best_den = den;
909                         best_num = num;
910                 }
911         }
912         if (best_den == 0) {
913                 i->empty = 1;
914                 return -EINVAL;
915         }
916         t.min = div_down(best_num, best_den);
917         t.openmin = !!(best_num % best_den);
918         
919         best_num = best_den = best_diff = 0;
920         for (k = 0; k < rats_count; ++k) {
921                 unsigned int num;
922                 unsigned int den = rats[k].den;
923                 unsigned int q = i->max;
924                 int diff;
925                 num = mul(q, den);
926                 if (num < rats[k].num_min)
927                         continue;
928                 if (num > rats[k].num_max)
929                         num = rats[k].num_max;
930                 else {
931                         unsigned int r;
932                         r = (num - rats[k].num_min) % rats[k].num_step;
933                         if (r != 0)
934                                 num -= r;
935                 }
936                 diff = q * den - num;
937                 if (best_num == 0 ||
938                     diff * best_den < best_diff * den) {
939                         best_diff = diff;
940                         best_den = den;
941                         best_num = num;
942                 }
943         }
944         if (best_den == 0) {
945                 i->empty = 1;
946                 return -EINVAL;
947         }
948         t.max = div_up(best_num, best_den);
949         t.openmax = !!(best_num % best_den);
950         t.integer = 0;
951         err = snd_interval_refine(i, &t);
952         if (err < 0)
953                 return err;
954
955         if (snd_interval_single(i)) {
956                 if (nump)
957                         *nump = best_num;
958                 if (denp)
959                         *denp = best_den;
960         }
961         return err;
962 }
963
964 /**
965  * snd_interval_list - refine the interval value from the list
966  * @i: the interval value to refine
967  * @count: the number of elements in the list
968  * @list: the value list
969  * @mask: the bit-mask to evaluate
970  *
971  * Refines the interval value from the list.
972  * When mask is non-zero, only the elements corresponding to bit 1 are
973  * evaluated.
974  *
975  * Returns non-zero if the value is changed, zero if not changed.
976  */
977 int snd_interval_list(struct snd_interval *i, unsigned int count, unsigned int *list, unsigned int mask)
978 {
979         unsigned int k;
980         struct snd_interval list_range;
981
982         if (!count) {
983                 i->empty = 1;
984                 return -EINVAL;
985         }
986         snd_interval_any(&list_range);
987         list_range.min = UINT_MAX;
988         list_range.max = 0;
989         for (k = 0; k < count; k++) {
990                 if (mask && !(mask & (1 << k)))
991                         continue;
992                 if (!snd_interval_test(i, list[k]))
993                         continue;
994                 list_range.min = min(list_range.min, list[k]);
995                 list_range.max = max(list_range.max, list[k]);
996         }
997         return snd_interval_refine(i, &list_range);
998 }
999
1000 EXPORT_SYMBOL(snd_interval_list);
1001
1002 static int snd_interval_step(struct snd_interval *i, unsigned int min, unsigned int step)
1003 {
1004         unsigned int n;
1005         int changed = 0;
1006         n = (i->min - min) % step;
1007         if (n != 0 || i->openmin) {
1008                 i->min += step - n;
1009                 changed = 1;
1010         }
1011         n = (i->max - min) % step;
1012         if (n != 0 || i->openmax) {
1013                 i->max -= n;
1014                 changed = 1;
1015         }
1016         if (snd_interval_checkempty(i)) {
1017                 i->empty = 1;
1018                 return -EINVAL;
1019         }
1020         return changed;
1021 }
1022
1023 /* Info constraints helpers */
1024
1025 /**
1026  * snd_pcm_hw_rule_add - add the hw-constraint rule
1027  * @runtime: the pcm runtime instance
1028  * @cond: condition bits
1029  * @var: the variable to evaluate
1030  * @func: the evaluation function
1031  * @private: the private data pointer passed to function
1032  * @dep: the dependent variables
1033  *
1034  * Returns zero if successful, or a negative error code on failure.
1035  */
1036 int snd_pcm_hw_rule_add(struct snd_pcm_runtime *runtime, unsigned int cond,
1037                         int var,
1038                         snd_pcm_hw_rule_func_t func, void *private,
1039                         int dep, ...)
1040 {
1041         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1042         struct snd_pcm_hw_rule *c;
1043         unsigned int k;
1044         va_list args;
1045         va_start(args, dep);
1046         if (constrs->rules_num >= constrs->rules_all) {
1047                 struct snd_pcm_hw_rule *new;
1048                 unsigned int new_rules = constrs->rules_all + 16;
1049                 new = kcalloc(new_rules, sizeof(*c), GFP_KERNEL);
1050                 if (!new)
1051                         return -ENOMEM;
1052                 if (constrs->rules) {
1053                         memcpy(new, constrs->rules,
1054                                constrs->rules_num * sizeof(*c));
1055                         kfree(constrs->rules);
1056                 }
1057                 constrs->rules = new;
1058                 constrs->rules_all = new_rules;
1059         }
1060         c = &constrs->rules[constrs->rules_num];
1061         c->cond = cond;
1062         c->func = func;
1063         c->var = var;
1064         c->private = private;
1065         k = 0;
1066         while (1) {
1067                 if (snd_BUG_ON(k >= ARRAY_SIZE(c->deps)))
1068                         return -EINVAL;
1069                 c->deps[k++] = dep;
1070                 if (dep < 0)
1071                         break;
1072                 dep = va_arg(args, int);
1073         }
1074         constrs->rules_num++;
1075         va_end(args);
1076         return 0;
1077 }                                   
1078
1079 EXPORT_SYMBOL(snd_pcm_hw_rule_add);
1080
1081 /**
1082  * snd_pcm_hw_constraint_mask - apply the given bitmap mask constraint
1083  * @runtime: PCM runtime instance
1084  * @var: hw_params variable to apply the mask
1085  * @mask: the bitmap mask
1086  *
1087  * Apply the constraint of the given bitmap mask to a 32-bit mask parameter.
1088  */
1089 int snd_pcm_hw_constraint_mask(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1090                                u_int32_t mask)
1091 {
1092         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1093         struct snd_mask *maskp = constrs_mask(constrs, var);
1094         *maskp->bits &= mask;
1095         memset(maskp->bits + 1, 0, (SNDRV_MASK_MAX-32) / 8); /* clear rest */
1096         if (*maskp->bits == 0)
1097                 return -EINVAL;
1098         return 0;
1099 }
1100
1101 /**
1102  * snd_pcm_hw_constraint_mask64 - apply the given bitmap mask constraint
1103  * @runtime: PCM runtime instance
1104  * @var: hw_params variable to apply the mask
1105  * @mask: the 64bit bitmap mask
1106  *
1107  * Apply the constraint of the given bitmap mask to a 64-bit mask parameter.
1108  */
1109 int snd_pcm_hw_constraint_mask64(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1110                                  u_int64_t mask)
1111 {
1112         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1113         struct snd_mask *maskp = constrs_mask(constrs, var);
1114         maskp->bits[0] &= (u_int32_t)mask;
1115         maskp->bits[1] &= (u_int32_t)(mask >> 32);
1116         memset(maskp->bits + 2, 0, (SNDRV_MASK_MAX-64) / 8); /* clear rest */
1117         if (! maskp->bits[0] && ! maskp->bits[1])
1118                 return -EINVAL;
1119         return 0;
1120 }
1121
1122 /**
1123  * snd_pcm_hw_constraint_integer - apply an integer constraint to an interval
1124  * @runtime: PCM runtime instance
1125  * @var: hw_params variable to apply the integer constraint
1126  *
1127  * Apply the constraint of integer to an interval parameter.
1128  */
1129 int snd_pcm_hw_constraint_integer(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var)
1130 {
1131         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1132         return snd_interval_setinteger(constrs_interval(constrs, var));
1133 }
1134
1135 EXPORT_SYMBOL(snd_pcm_hw_constraint_integer);
1136
1137 /**
1138  * snd_pcm_hw_constraint_minmax - apply a min/max range constraint to an interval
1139  * @runtime: PCM runtime instance
1140  * @var: hw_params variable to apply the range
1141  * @min: the minimal value
1142  * @max: the maximal value
1143  * 
1144  * Apply the min/max range constraint to an interval parameter.
1145  */
1146 int snd_pcm_hw_constraint_minmax(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1147                                  unsigned int min, unsigned int max)
1148 {
1149         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1150         struct snd_interval t;
1151         t.min = min;
1152         t.max = max;
1153         t.openmin = t.openmax = 0;
1154         t.integer = 0;
1155         return snd_interval_refine(constrs_interval(constrs, var), &t);
1156 }
1157
1158 EXPORT_SYMBOL(snd_pcm_hw_constraint_minmax);
1159
1160 static int snd_pcm_hw_rule_list(struct snd_pcm_hw_params *params,
1161                                 struct snd_pcm_hw_rule *rule)
1162 {
1163         struct snd_pcm_hw_constraint_list *list = rule->private;
1164         return snd_interval_list(hw_param_interval(params, rule->var), list->count, list->list, list->mask);
1165 }               
1166
1167
1168 /**
1169  * snd_pcm_hw_constraint_list - apply a list of constraints to a parameter
1170  * @runtime: PCM runtime instance
1171  * @cond: condition bits
1172  * @var: hw_params variable to apply the list constraint
1173  * @l: list
1174  * 
1175  * Apply the list of constraints to an interval parameter.
1176  */
1177 int snd_pcm_hw_constraint_list(struct snd_pcm_runtime *runtime,
1178                                unsigned int cond,
1179                                snd_pcm_hw_param_t var,
1180                                struct snd_pcm_hw_constraint_list *l)
1181 {
1182         return snd_pcm_hw_rule_add(runtime, cond, var,
1183                                    snd_pcm_hw_rule_list, l,
1184                                    var, -1);
1185 }
1186
1187 EXPORT_SYMBOL(snd_pcm_hw_constraint_list);
1188
1189 static int snd_pcm_hw_rule_ratnums(struct snd_pcm_hw_params *params,
1190                                    struct snd_pcm_hw_rule *rule)
1191 {
1192         struct snd_pcm_hw_constraint_ratnums *r = rule->private;
1193         unsigned int num = 0, den = 0;
1194         int err;
1195         err = snd_interval_ratnum(hw_param_interval(params, rule->var),
1196                                   r->nrats, r->rats, &num, &den);
1197         if (err >= 0 && den && rule->var == SNDRV_PCM_HW_PARAM_RATE) {
1198                 params->rate_num = num;
1199                 params->rate_den = den;
1200         }
1201         return err;
1202 }
1203
1204 /**
1205  * snd_pcm_hw_constraint_ratnums - apply ratnums constraint to a parameter
1206  * @runtime: PCM runtime instance
1207  * @cond: condition bits
1208  * @var: hw_params variable to apply the ratnums constraint
1209  * @r: struct snd_ratnums constriants
1210  */
1211 int snd_pcm_hw_constraint_ratnums(struct snd_pcm_runtime *runtime, 
1212                                   unsigned int cond,
1213                                   snd_pcm_hw_param_t var,
1214                                   struct snd_pcm_hw_constraint_ratnums *r)
1215 {
1216         return snd_pcm_hw_rule_add(runtime, cond, var,
1217                                    snd_pcm_hw_rule_ratnums, r,
1218                                    var, -1);
1219 }
1220
1221 EXPORT_SYMBOL(snd_pcm_hw_constraint_ratnums);
1222
1223 static int snd_pcm_hw_rule_ratdens(struct snd_pcm_hw_params *params,
1224                                    struct snd_pcm_hw_rule *rule)
1225 {
1226         struct snd_pcm_hw_constraint_ratdens *r = rule->private;
1227         unsigned int num = 0, den = 0;
1228         int err = snd_interval_ratden(hw_param_interval(params, rule->var),
1229                                   r->nrats, r->rats, &num, &den);
1230         if (err >= 0 && den && rule->var == SNDRV_PCM_HW_PARAM_RATE) {
1231                 params->rate_num = num;
1232                 params->rate_den = den;
1233         }
1234         return err;
1235 }
1236
1237 /**
1238  * snd_pcm_hw_constraint_ratdens - apply ratdens constraint to a parameter
1239  * @runtime: PCM runtime instance
1240  * @cond: condition bits
1241  * @var: hw_params variable to apply the ratdens constraint
1242  * @r: struct snd_ratdens constriants
1243  */
1244 int snd_pcm_hw_constraint_ratdens(struct snd_pcm_runtime *runtime, 
1245                                   unsigned int cond,
1246                                   snd_pcm_hw_param_t var,
1247                                   struct snd_pcm_hw_constraint_ratdens *r)
1248 {
1249         return snd_pcm_hw_rule_add(runtime, cond, var,
1250                                    snd_pcm_hw_rule_ratdens, r,
1251                                    var, -1);
1252 }
1253
1254 EXPORT_SYMBOL(snd_pcm_hw_constraint_ratdens);
1255
1256 static int snd_pcm_hw_rule_msbits(struct snd_pcm_hw_params *params,
1257                                   struct snd_pcm_hw_rule *rule)
1258 {
1259         unsigned int l = (unsigned long) rule->private;
1260         int width = l & 0xffff;
1261         unsigned int msbits = l >> 16;
1262         struct snd_interval *i = hw_param_interval(params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS);
1263         if (snd_interval_single(i) && snd_interval_value(i) == width)
1264                 params->msbits = msbits;
1265         return 0;
1266 }
1267
1268 /**
1269  * snd_pcm_hw_constraint_msbits - add a hw constraint msbits rule
1270  * @runtime: PCM runtime instance
1271  * @cond: condition bits
1272  * @width: sample bits width
1273  * @msbits: msbits width
1274  */
1275 int snd_pcm_hw_constraint_msbits(struct snd_pcm_runtime *runtime, 
1276                                  unsigned int cond,
1277                                  unsigned int width,
1278                                  unsigned int msbits)
1279 {
1280         unsigned long l = (msbits << 16) | width;
1281         return snd_pcm_hw_rule_add(runtime, cond, -1,
1282                                     snd_pcm_hw_rule_msbits,
1283                                     (void*) l,
1284                                     SNDRV_PCM_HW_PARAM_SAMPLE_BITS, -1);
1285 }
1286
1287 EXPORT_SYMBOL(snd_pcm_hw_constraint_msbits);
1288
1289 static int snd_pcm_hw_rule_step(struct snd_pcm_hw_params *params,
1290                                 struct snd_pcm_hw_rule *rule)
1291 {
1292         unsigned long step = (unsigned long) rule->private;
1293         return snd_interval_step(hw_param_interval(params, rule->var), 0, step);
1294 }
1295
1296 /**
1297  * snd_pcm_hw_constraint_step - add a hw constraint step rule
1298  * @runtime: PCM runtime instance
1299  * @cond: condition bits
1300  * @var: hw_params variable to apply the step constraint
1301  * @step: step size
1302  */
1303 int snd_pcm_hw_constraint_step(struct snd_pcm_runtime *runtime,
1304                                unsigned int cond,
1305                                snd_pcm_hw_param_t var,
1306                                unsigned long step)
1307 {
1308         return snd_pcm_hw_rule_add(runtime, cond, var, 
1309                                    snd_pcm_hw_rule_step, (void *) step,
1310                                    var, -1);
1311 }
1312
1313 EXPORT_SYMBOL(snd_pcm_hw_constraint_step);
1314
1315 static int snd_pcm_hw_rule_pow2(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule)
1316 {
1317         static unsigned int pow2_sizes[] = {
1318                 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7,
1319                 1<<8, 1<<9, 1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15,
1320                 1<<16, 1<<17, 1<<18, 1<<19, 1<<20, 1<<21, 1<<22, 1<<23,
1321                 1<<24, 1<<25, 1<<26, 1<<27, 1<<28, 1<<29, 1<<30
1322         };
1323         return snd_interval_list(hw_param_interval(params, rule->var),
1324                                  ARRAY_SIZE(pow2_sizes), pow2_sizes, 0);
1325 }               
1326
1327 /**
1328  * snd_pcm_hw_constraint_pow2 - add a hw constraint power-of-2 rule
1329  * @runtime: PCM runtime instance
1330  * @cond: condition bits
1331  * @var: hw_params variable to apply the power-of-2 constraint
1332  */
1333 int snd_pcm_hw_constraint_pow2(struct snd_pcm_runtime *runtime,
1334                                unsigned int cond,
1335                                snd_pcm_hw_param_t var)
1336 {
1337         return snd_pcm_hw_rule_add(runtime, cond, var, 
1338                                    snd_pcm_hw_rule_pow2, NULL,
1339                                    var, -1);
1340 }
1341
1342 EXPORT_SYMBOL(snd_pcm_hw_constraint_pow2);
1343
1344 static void _snd_pcm_hw_param_any(struct snd_pcm_hw_params *params,
1345                                   snd_pcm_hw_param_t var)
1346 {
1347         if (hw_is_mask(var)) {
1348                 snd_mask_any(hw_param_mask(params, var));
1349                 params->cmask |= 1 << var;
1350                 params->rmask |= 1 << var;
1351                 return;
1352         }
1353         if (hw_is_interval(var)) {
1354                 snd_interval_any(hw_param_interval(params, var));
1355                 params->cmask |= 1 << var;
1356                 params->rmask |= 1 << var;
1357                 return;
1358         }
1359         snd_BUG();
1360 }
1361
1362 void _snd_pcm_hw_params_any(struct snd_pcm_hw_params *params)
1363 {
1364         unsigned int k;
1365         memset(params, 0, sizeof(*params));
1366         for (k = SNDRV_PCM_HW_PARAM_FIRST_MASK; k <= SNDRV_PCM_HW_PARAM_LAST_MASK; k++)
1367                 _snd_pcm_hw_param_any(params, k);
1368         for (k = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; k <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; k++)
1369                 _snd_pcm_hw_param_any(params, k);
1370         params->info = ~0U;
1371 }
1372
1373 EXPORT_SYMBOL(_snd_pcm_hw_params_any);
1374
1375 /**
1376  * snd_pcm_hw_param_value - return @params field @var value
1377  * @params: the hw_params instance
1378  * @var: parameter to retrieve
1379  * @dir: pointer to the direction (-1,0,1) or %NULL
1380  *
1381  * Return the value for field @var if it's fixed in configuration space
1382  * defined by @params. Return -%EINVAL otherwise.
1383  */
1384 int snd_pcm_hw_param_value(const struct snd_pcm_hw_params *params,
1385                            snd_pcm_hw_param_t var, int *dir)
1386 {
1387         if (hw_is_mask(var)) {
1388                 const struct snd_mask *mask = hw_param_mask_c(params, var);
1389                 if (!snd_mask_single(mask))
1390                         return -EINVAL;
1391                 if (dir)
1392                         *dir = 0;
1393                 return snd_mask_value(mask);
1394         }
1395         if (hw_is_interval(var)) {
1396                 const struct snd_interval *i = hw_param_interval_c(params, var);
1397                 if (!snd_interval_single(i))
1398                         return -EINVAL;
1399                 if (dir)
1400                         *dir = i->openmin;
1401                 return snd_interval_value(i);
1402         }
1403         return -EINVAL;
1404 }
1405
1406 EXPORT_SYMBOL(snd_pcm_hw_param_value);
1407
1408 void _snd_pcm_hw_param_setempty(struct snd_pcm_hw_params *params,
1409                                 snd_pcm_hw_param_t var)
1410 {
1411         if (hw_is_mask(var)) {
1412                 snd_mask_none(hw_param_mask(params, var));
1413                 params->cmask |= 1 << var;
1414                 params->rmask |= 1 << var;
1415         } else if (hw_is_interval(var)) {
1416                 snd_interval_none(hw_param_interval(params, var));
1417                 params->cmask |= 1 << var;
1418                 params->rmask |= 1 << var;
1419         } else {
1420                 snd_BUG();
1421         }
1422 }
1423
1424 EXPORT_SYMBOL(_snd_pcm_hw_param_setempty);
1425
1426 static int _snd_pcm_hw_param_first(struct snd_pcm_hw_params *params,
1427                                    snd_pcm_hw_param_t var)
1428 {
1429         int changed;
1430         if (hw_is_mask(var))
1431                 changed = snd_mask_refine_first(hw_param_mask(params, var));
1432         else if (hw_is_interval(var))
1433                 changed = snd_interval_refine_first(hw_param_interval(params, var));
1434         else
1435                 return -EINVAL;
1436         if (changed) {
1437                 params->cmask |= 1 << var;
1438                 params->rmask |= 1 << var;
1439         }
1440         return changed;
1441 }
1442
1443
1444 /**
1445  * snd_pcm_hw_param_first - refine config space and return minimum value
1446  * @pcm: PCM instance
1447  * @params: the hw_params instance
1448  * @var: parameter to retrieve
1449  * @dir: pointer to the direction (-1,0,1) or %NULL
1450  *
1451  * Inside configuration space defined by @params remove from @var all
1452  * values > minimum. Reduce configuration space accordingly.
1453  * Return the minimum.
1454  */
1455 int snd_pcm_hw_param_first(struct snd_pcm_substream *pcm, 
1456                            struct snd_pcm_hw_params *params, 
1457                            snd_pcm_hw_param_t var, int *dir)
1458 {
1459         int changed = _snd_pcm_hw_param_first(params, var);
1460         if (changed < 0)
1461                 return changed;
1462         if (params->rmask) {
1463                 int err = snd_pcm_hw_refine(pcm, params);
1464                 if (snd_BUG_ON(err < 0))
1465                         return err;
1466         }
1467         return snd_pcm_hw_param_value(params, var, dir);
1468 }
1469
1470 EXPORT_SYMBOL(snd_pcm_hw_param_first);
1471
1472 static int _snd_pcm_hw_param_last(struct snd_pcm_hw_params *params,
1473                                   snd_pcm_hw_param_t var)
1474 {
1475         int changed;
1476         if (hw_is_mask(var))
1477                 changed = snd_mask_refine_last(hw_param_mask(params, var));
1478         else if (hw_is_interval(var))
1479                 changed = snd_interval_refine_last(hw_param_interval(params, var));
1480         else
1481                 return -EINVAL;
1482         if (changed) {
1483                 params->cmask |= 1 << var;
1484                 params->rmask |= 1 << var;
1485         }
1486         return changed;
1487 }
1488
1489
1490 /**
1491  * snd_pcm_hw_param_last - refine config space and return maximum value
1492  * @pcm: PCM instance
1493  * @params: the hw_params instance
1494  * @var: parameter to retrieve
1495  * @dir: pointer to the direction (-1,0,1) or %NULL
1496  *
1497  * Inside configuration space defined by @params remove from @var all
1498  * values < maximum. Reduce configuration space accordingly.
1499  * Return the maximum.
1500  */
1501 int snd_pcm_hw_param_last(struct snd_pcm_substream *pcm, 
1502                           struct snd_pcm_hw_params *params,
1503                           snd_pcm_hw_param_t var, int *dir)
1504 {
1505         int changed = _snd_pcm_hw_param_last(params, var);
1506         if (changed < 0)
1507                 return changed;
1508         if (params->rmask) {
1509                 int err = snd_pcm_hw_refine(pcm, params);
1510                 if (snd_BUG_ON(err < 0))
1511                         return err;
1512         }
1513         return snd_pcm_hw_param_value(params, var, dir);
1514 }
1515
1516 EXPORT_SYMBOL(snd_pcm_hw_param_last);
1517
1518 /**
1519  * snd_pcm_hw_param_choose - choose a configuration defined by @params
1520  * @pcm: PCM instance
1521  * @params: the hw_params instance
1522  *
1523  * Choose one configuration from configuration space defined by @params.
1524  * The configuration chosen is that obtained fixing in this order:
1525  * first access, first format, first subformat, min channels,
1526  * min rate, min period time, max buffer size, min tick time
1527  */
1528 int snd_pcm_hw_params_choose(struct snd_pcm_substream *pcm,
1529                              struct snd_pcm_hw_params *params)
1530 {
1531         static int vars[] = {
1532                 SNDRV_PCM_HW_PARAM_ACCESS,
1533                 SNDRV_PCM_HW_PARAM_FORMAT,
1534                 SNDRV_PCM_HW_PARAM_SUBFORMAT,
1535                 SNDRV_PCM_HW_PARAM_CHANNELS,
1536                 SNDRV_PCM_HW_PARAM_RATE,
1537                 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1538                 SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
1539                 SNDRV_PCM_HW_PARAM_TICK_TIME,
1540                 -1
1541         };
1542         int err, *v;
1543
1544         for (v = vars; *v != -1; v++) {
1545                 if (*v != SNDRV_PCM_HW_PARAM_BUFFER_SIZE)
1546                         err = snd_pcm_hw_param_first(pcm, params, *v, NULL);
1547                 else
1548                         err = snd_pcm_hw_param_last(pcm, params, *v, NULL);
1549                 if (snd_BUG_ON(err < 0))
1550                         return err;
1551         }
1552         return 0;
1553 }
1554
1555 static int snd_pcm_lib_ioctl_reset(struct snd_pcm_substream *substream,
1556                                    void *arg)
1557 {
1558         struct snd_pcm_runtime *runtime = substream->runtime;
1559         unsigned long flags;
1560         snd_pcm_stream_lock_irqsave(substream, flags);
1561         if (snd_pcm_running(substream) &&
1562             snd_pcm_update_hw_ptr(substream) >= 0)
1563                 runtime->status->hw_ptr %= runtime->buffer_size;
1564         else
1565                 runtime->status->hw_ptr = 0;
1566         snd_pcm_stream_unlock_irqrestore(substream, flags);
1567         return 0;
1568 }
1569
1570 static int snd_pcm_lib_ioctl_channel_info(struct snd_pcm_substream *substream,
1571                                           void *arg)
1572 {
1573         struct snd_pcm_channel_info *info = arg;
1574         struct snd_pcm_runtime *runtime = substream->runtime;
1575         int width;
1576         if (!(runtime->info & SNDRV_PCM_INFO_MMAP)) {
1577                 info->offset = -1;
1578                 return 0;
1579         }
1580         width = snd_pcm_format_physical_width(runtime->format);
1581         if (width < 0)
1582                 return width;
1583         info->offset = 0;
1584         switch (runtime->access) {
1585         case SNDRV_PCM_ACCESS_MMAP_INTERLEAVED:
1586         case SNDRV_PCM_ACCESS_RW_INTERLEAVED:
1587                 info->first = info->channel * width;
1588                 info->step = runtime->channels * width;
1589                 break;
1590         case SNDRV_PCM_ACCESS_MMAP_NONINTERLEAVED:
1591         case SNDRV_PCM_ACCESS_RW_NONINTERLEAVED:
1592         {
1593                 size_t size = runtime->dma_bytes / runtime->channels;
1594                 info->first = info->channel * size * 8;
1595                 info->step = width;
1596                 break;
1597         }
1598         default:
1599                 snd_BUG();
1600                 break;
1601         }
1602         return 0;
1603 }
1604
1605 static int snd_pcm_lib_ioctl_fifo_size(struct snd_pcm_substream *substream,
1606                                        void *arg)
1607 {
1608         struct snd_pcm_hw_params *params = arg;
1609         snd_pcm_format_t format;
1610         int channels, width;
1611
1612         params->fifo_size = substream->runtime->hw.fifo_size;
1613         if (!(substream->runtime->hw.info & SNDRV_PCM_INFO_FIFO_IN_FRAMES)) {
1614                 format = params_format(params);
1615                 channels = params_channels(params);
1616                 width = snd_pcm_format_physical_width(format);
1617                 params->fifo_size /= width * channels;
1618         }
1619         return 0;
1620 }
1621
1622 /**
1623  * snd_pcm_lib_ioctl - a generic PCM ioctl callback
1624  * @substream: the pcm substream instance
1625  * @cmd: ioctl command
1626  * @arg: ioctl argument
1627  *
1628  * Processes the generic ioctl commands for PCM.
1629  * Can be passed as the ioctl callback for PCM ops.
1630  *
1631  * Returns zero if successful, or a negative error code on failure.
1632  */
1633 int snd_pcm_lib_ioctl(struct snd_pcm_substream *substream,
1634                       unsigned int cmd, void *arg)
1635 {
1636         switch (cmd) {
1637         case SNDRV_PCM_IOCTL1_INFO:
1638                 return 0;
1639         case SNDRV_PCM_IOCTL1_RESET:
1640                 return snd_pcm_lib_ioctl_reset(substream, arg);
1641         case SNDRV_PCM_IOCTL1_CHANNEL_INFO:
1642                 return snd_pcm_lib_ioctl_channel_info(substream, arg);
1643         case SNDRV_PCM_IOCTL1_FIFO_SIZE:
1644                 return snd_pcm_lib_ioctl_fifo_size(substream, arg);
1645         }
1646         return -ENXIO;
1647 }
1648
1649 EXPORT_SYMBOL(snd_pcm_lib_ioctl);
1650
1651 /**
1652  * snd_pcm_period_elapsed - update the pcm status for the next period
1653  * @substream: the pcm substream instance
1654  *
1655  * This function is called from the interrupt handler when the
1656  * PCM has processed the period size.  It will update the current
1657  * pointer, wake up sleepers, etc.
1658  *
1659  * Even if more than one periods have elapsed since the last call, you
1660  * have to call this only once.
1661  */
1662 void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
1663 {
1664         struct snd_pcm_runtime *runtime;
1665         unsigned long flags;
1666
1667         if (PCM_RUNTIME_CHECK(substream))
1668                 return;
1669         runtime = substream->runtime;
1670
1671         if (runtime->transfer_ack_begin)
1672                 runtime->transfer_ack_begin(substream);
1673
1674         snd_pcm_stream_lock_irqsave(substream, flags);
1675         if (!snd_pcm_running(substream) ||
1676             snd_pcm_update_hw_ptr0(substream, 1) < 0)
1677                 goto _end;
1678
1679         if (substream->timer_running)
1680                 snd_timer_interrupt(substream->timer, 1);
1681  _end:
1682         snd_pcm_stream_unlock_irqrestore(substream, flags);
1683         if (runtime->transfer_ack_end)
1684                 runtime->transfer_ack_end(substream);
1685         kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
1686 }
1687
1688 EXPORT_SYMBOL(snd_pcm_period_elapsed);
1689
1690 /*
1691  * Wait until avail_min data becomes available
1692  * Returns a negative error code if any error occurs during operation.
1693  * The available space is stored on availp.  When err = 0 and avail = 0
1694  * on the capture stream, it indicates the stream is in DRAINING state.
1695  */
1696 static int wait_for_avail_min(struct snd_pcm_substream *substream,
1697                               snd_pcm_uframes_t *availp)
1698 {
1699         struct snd_pcm_runtime *runtime = substream->runtime;
1700         int is_playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK;
1701         wait_queue_t wait;
1702         int err = 0;
1703         snd_pcm_uframes_t avail = 0;
1704         long tout;
1705
1706         init_waitqueue_entry(&wait, current);
1707         add_wait_queue(&runtime->sleep, &wait);
1708         for (;;) {
1709                 if (signal_pending(current)) {
1710                         err = -ERESTARTSYS;
1711                         break;
1712                 }
1713                 set_current_state(TASK_INTERRUPTIBLE);
1714                 snd_pcm_stream_unlock_irq(substream);
1715                 tout = schedule_timeout(msecs_to_jiffies(10000));
1716                 snd_pcm_stream_lock_irq(substream);
1717                 switch (runtime->status->state) {
1718                 case SNDRV_PCM_STATE_SUSPENDED:
1719                         err = -ESTRPIPE;
1720                         goto _endloop;
1721                 case SNDRV_PCM_STATE_XRUN:
1722                         err = -EPIPE;
1723                         goto _endloop;
1724                 case SNDRV_PCM_STATE_DRAINING:
1725                         if (is_playback)
1726                                 err = -EPIPE;
1727                         else 
1728                                 avail = 0; /* indicate draining */
1729                         goto _endloop;
1730                 case SNDRV_PCM_STATE_OPEN:
1731                 case SNDRV_PCM_STATE_SETUP:
1732                 case SNDRV_PCM_STATE_DISCONNECTED:
1733                         err = -EBADFD;
1734                         goto _endloop;
1735                 }
1736                 if (!tout) {
1737                         snd_printd("%s write error (DMA or IRQ trouble?)\n",
1738                                    is_playback ? "playback" : "capture");
1739                         err = -EIO;
1740                         break;
1741                 }
1742                 if (is_playback)
1743                         avail = snd_pcm_playback_avail(runtime);
1744                 else
1745                         avail = snd_pcm_capture_avail(runtime);
1746                 if (avail >= runtime->control->avail_min)
1747                         break;
1748         }
1749  _endloop:
1750         remove_wait_queue(&runtime->sleep, &wait);
1751         *availp = avail;
1752         return err;
1753 }
1754         
1755 static int snd_pcm_lib_write_transfer(struct snd_pcm_substream *substream,
1756                                       unsigned int hwoff,
1757                                       unsigned long data, unsigned int off,
1758                                       snd_pcm_uframes_t frames)
1759 {
1760         struct snd_pcm_runtime *runtime = substream->runtime;
1761         int err;
1762         char __user *buf = (char __user *) data + frames_to_bytes(runtime, off);
1763         if (substream->ops->copy) {
1764                 if ((err = substream->ops->copy(substream, -1, hwoff, buf, frames)) < 0)
1765                         return err;
1766         } else {
1767                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);
1768                 if (copy_from_user(hwbuf, buf, frames_to_bytes(runtime, frames)))
1769                         return -EFAULT;
1770         }
1771         return 0;
1772 }
1773  
1774 typedef int (*transfer_f)(struct snd_pcm_substream *substream, unsigned int hwoff,
1775                           unsigned long data, unsigned int off,
1776                           snd_pcm_uframes_t size);
1777
1778 static snd_pcm_sframes_t snd_pcm_lib_write1(struct snd_pcm_substream *substream, 
1779                                             unsigned long data,
1780                                             snd_pcm_uframes_t size,
1781                                             int nonblock,
1782                                             transfer_f transfer)
1783 {
1784         struct snd_pcm_runtime *runtime = substream->runtime;
1785         snd_pcm_uframes_t xfer = 0;
1786         snd_pcm_uframes_t offset = 0;
1787         int err = 0;
1788
1789         if (size == 0)
1790                 return 0;
1791
1792         snd_pcm_stream_lock_irq(substream);
1793         switch (runtime->status->state) {
1794         case SNDRV_PCM_STATE_PREPARED:
1795         case SNDRV_PCM_STATE_RUNNING:
1796         case SNDRV_PCM_STATE_PAUSED:
1797                 break;
1798         case SNDRV_PCM_STATE_XRUN:
1799                 err = -EPIPE;
1800                 goto _end_unlock;
1801         case SNDRV_PCM_STATE_SUSPENDED:
1802                 err = -ESTRPIPE;
1803                 goto _end_unlock;
1804         default:
1805                 err = -EBADFD;
1806                 goto _end_unlock;
1807         }
1808
1809         runtime->nowake = 1;
1810         while (size > 0) {
1811                 snd_pcm_uframes_t frames, appl_ptr, appl_ofs;
1812                 snd_pcm_uframes_t avail;
1813                 snd_pcm_uframes_t cont;
1814                 if (runtime->status->state == SNDRV_PCM_STATE_RUNNING)
1815                         snd_pcm_update_hw_ptr(substream);
1816                 avail = snd_pcm_playback_avail(runtime);
1817                 if (!avail) {
1818                         if (nonblock) {
1819                                 err = -EAGAIN;
1820                                 goto _end_unlock;
1821                         }
1822                         err = wait_for_avail_min(substream, &avail);
1823                         if (err < 0)
1824                                 goto _end_unlock;
1825                 }
1826                 frames = size > avail ? avail : size;
1827                 cont = runtime->buffer_size - runtime->control->appl_ptr % runtime->buffer_size;
1828                 if (frames > cont)
1829                         frames = cont;
1830                 if (snd_BUG_ON(!frames)) {
1831                         runtime->nowake = 0;
1832                         snd_pcm_stream_unlock_irq(substream);
1833                         return -EINVAL;
1834                 }
1835                 appl_ptr = runtime->control->appl_ptr;
1836                 appl_ofs = appl_ptr % runtime->buffer_size;
1837                 snd_pcm_stream_unlock_irq(substream);
1838                 err = transfer(substream, appl_ofs, data, offset, frames);
1839                 snd_pcm_stream_lock_irq(substream);
1840                 if (err < 0)
1841                         goto _end_unlock;
1842                 switch (runtime->status->state) {
1843                 case SNDRV_PCM_STATE_XRUN:
1844                         err = -EPIPE;
1845                         goto _end_unlock;
1846                 case SNDRV_PCM_STATE_SUSPENDED:
1847                         err = -ESTRPIPE;
1848                         goto _end_unlock;
1849                 default:
1850                         break;
1851                 }
1852                 appl_ptr += frames;
1853                 if (appl_ptr >= runtime->boundary)
1854                         appl_ptr -= runtime->boundary;
1855                 runtime->control->appl_ptr = appl_ptr;
1856                 if (substream->ops->ack)
1857                         substream->ops->ack(substream);
1858
1859                 offset += frames;
1860                 size -= frames;
1861                 xfer += frames;
1862                 if (runtime->status->state == SNDRV_PCM_STATE_PREPARED &&
1863                     snd_pcm_playback_hw_avail(runtime) >= (snd_pcm_sframes_t)runtime->start_threshold) {
1864                         err = snd_pcm_start(substream);
1865                         if (err < 0)
1866                                 goto _end_unlock;
1867                 }
1868         }
1869  _end_unlock:
1870         runtime->nowake = 0;
1871         if (xfer > 0 && err >= 0)
1872                 snd_pcm_update_state(substream, runtime);
1873         snd_pcm_stream_unlock_irq(substream);
1874         return xfer > 0 ? (snd_pcm_sframes_t)xfer : err;
1875 }
1876
1877 /* sanity-check for read/write methods */
1878 static int pcm_sanity_check(struct snd_pcm_substream *substream)
1879 {
1880         struct snd_pcm_runtime *runtime;
1881         if (PCM_RUNTIME_CHECK(substream))
1882                 return -ENXIO;
1883         runtime = substream->runtime;
1884         if (snd_BUG_ON(!substream->ops->copy && !runtime->dma_area))
1885                 return -EINVAL;
1886         if (runtime->status->state == SNDRV_PCM_STATE_OPEN)
1887                 return -EBADFD;
1888         return 0;
1889 }
1890
1891 snd_pcm_sframes_t snd_pcm_lib_write(struct snd_pcm_substream *substream, const void __user *buf, snd_pcm_uframes_t size)
1892 {
1893         struct snd_pcm_runtime *runtime;
1894         int nonblock;
1895         int err;
1896
1897         err = pcm_sanity_check(substream);
1898         if (err < 0)
1899                 return err;
1900         runtime = substream->runtime;
1901         nonblock = !!(substream->f_flags & O_NONBLOCK);
1902
1903         if (runtime->access != SNDRV_PCM_ACCESS_RW_INTERLEAVED &&
1904             runtime->channels > 1)
1905                 return -EINVAL;
1906         return snd_pcm_lib_write1(substream, (unsigned long)buf, size, nonblock,
1907                                   snd_pcm_lib_write_transfer);
1908 }
1909
1910 EXPORT_SYMBOL(snd_pcm_lib_write);
1911
1912 static int snd_pcm_lib_writev_transfer(struct snd_pcm_substream *substream,
1913                                        unsigned int hwoff,
1914                                        unsigned long data, unsigned int off,
1915                                        snd_pcm_uframes_t frames)
1916 {
1917         struct snd_pcm_runtime *runtime = substream->runtime;
1918         int err;
1919         void __user **bufs = (void __user **)data;
1920         int channels = runtime->channels;
1921         int c;
1922         if (substream->ops->copy) {
1923                 if (snd_BUG_ON(!substream->ops->silence))
1924                         return -EINVAL;
1925                 for (c = 0; c < channels; ++c, ++bufs) {
1926                         if (*bufs == NULL) {
1927                                 if ((err = substream->ops->silence(substream, c, hwoff, frames)) < 0)
1928                                         return err;
1929                         } else {
1930                                 char __user *buf = *bufs + samples_to_bytes(runtime, off);
1931                                 if ((err = substream->ops->copy(substream, c, hwoff, buf, frames)) < 0)
1932                                         return err;
1933                         }
1934                 }
1935         } else {
1936                 /* default transfer behaviour */
1937                 size_t dma_csize = runtime->dma_bytes / channels;
1938                 for (c = 0; c < channels; ++c, ++bufs) {
1939                         char *hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, hwoff);
1940                         if (*bufs == NULL) {
1941                                 snd_pcm_format_set_silence(runtime->format, hwbuf, frames);
1942                         } else {
1943                                 char __user *buf = *bufs + samples_to_bytes(runtime, off);
1944                                 if (copy_from_user(hwbuf, buf, samples_to_bytes(runtime, frames)))
1945                                         return -EFAULT;
1946                         }
1947                 }
1948         }
1949         return 0;
1950 }
1951  
1952 snd_pcm_sframes_t snd_pcm_lib_writev(struct snd_pcm_substream *substream,
1953                                      void __user **bufs,
1954                                      snd_pcm_uframes_t frames)
1955 {
1956         struct snd_pcm_runtime *runtime;
1957         int nonblock;
1958         int err;
1959
1960         err = pcm_sanity_check(substream);
1961         if (err < 0)
1962                 return err;
1963         runtime = substream->runtime;
1964         nonblock = !!(substream->f_flags & O_NONBLOCK);
1965
1966         if (runtime->access != SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)
1967                 return -EINVAL;
1968         return snd_pcm_lib_write1(substream, (unsigned long)bufs, frames,
1969                                   nonblock, snd_pcm_lib_writev_transfer);
1970 }
1971
1972 EXPORT_SYMBOL(snd_pcm_lib_writev);
1973
1974 static int snd_pcm_lib_read_transfer(struct snd_pcm_substream *substream, 
1975                                      unsigned int hwoff,
1976                                      unsigned long data, unsigned int off,
1977                                      snd_pcm_uframes_t frames)
1978 {
1979         struct snd_pcm_runtime *runtime = substream->runtime;
1980         int err;
1981         char __user *buf = (char __user *) data + frames_to_bytes(runtime, off);
1982         if (substream->ops->copy) {
1983                 if ((err = substream->ops->copy(substream, -1, hwoff, buf, frames)) < 0)
1984                         return err;
1985         } else {
1986                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);
1987                 if (copy_to_user(buf, hwbuf, frames_to_bytes(runtime, frames)))
1988                         return -EFAULT;
1989         }
1990         return 0;
1991 }
1992
1993 static snd_pcm_sframes_t snd_pcm_lib_read1(struct snd_pcm_substream *substream,
1994                                            unsigned long data,
1995                                            snd_pcm_uframes_t size,
1996                                            int nonblock,
1997                                            transfer_f transfer)
1998 {
1999         struct snd_pcm_runtime *runtime = substream->runtime;
2000         snd_pcm_uframes_t xfer = 0;
2001         snd_pcm_uframes_t offset = 0;
2002         int err = 0;
2003
2004         if (size == 0)
2005                 return 0;
2006
2007         snd_pcm_stream_lock_irq(substream);
2008         switch (runtime->status->state) {
2009         case SNDRV_PCM_STATE_PREPARED:
2010                 if (size >= runtime->start_threshold) {
2011                         err = snd_pcm_start(substream);
2012                         if (err < 0)
2013                                 goto _end_unlock;
2014                 }
2015                 break;
2016         case SNDRV_PCM_STATE_DRAINING:
2017         case SNDRV_PCM_STATE_RUNNING:
2018         case SNDRV_PCM_STATE_PAUSED:
2019                 break;
2020         case SNDRV_PCM_STATE_XRUN:
2021                 err = -EPIPE;
2022                 goto _end_unlock;
2023         case SNDRV_PCM_STATE_SUSPENDED:
2024                 err = -ESTRPIPE;
2025                 goto _end_unlock;
2026         default:
2027                 err = -EBADFD;
2028                 goto _end_unlock;
2029         }
2030
2031         runtime->nowake = 1;
2032         while (size > 0) {
2033                 snd_pcm_uframes_t frames, appl_ptr, appl_ofs;
2034                 snd_pcm_uframes_t avail;
2035                 snd_pcm_uframes_t cont;
2036                 if (runtime->status->state == SNDRV_PCM_STATE_RUNNING)
2037                         snd_pcm_update_hw_ptr(substream);
2038                 avail = snd_pcm_capture_avail(runtime);
2039                 if (!avail) {
2040                         if (runtime->status->state ==
2041                             SNDRV_PCM_STATE_DRAINING) {
2042                                 snd_pcm_stop(substream, SNDRV_PCM_STATE_SETUP);
2043                                 goto _end_unlock;
2044                         }
2045                         if (nonblock) {
2046                                 err = -EAGAIN;
2047                                 goto _end_unlock;
2048                         }
2049                         err = wait_for_avail_min(substream, &avail);
2050                         if (err < 0)
2051                                 goto _end_unlock;
2052                         if (!avail)
2053                                 continue; /* draining */
2054                 }
2055                 frames = size > avail ? avail : size;
2056                 cont = runtime->buffer_size - runtime->control->appl_ptr % runtime->buffer_size;
2057                 if (frames > cont)
2058                         frames = cont;
2059                 if (snd_BUG_ON(!frames)) {
2060                         runtime->nowake = 0;
2061                         snd_pcm_stream_unlock_irq(substream);
2062                         return -EINVAL;
2063                 }
2064                 appl_ptr = runtime->control->appl_ptr;
2065                 appl_ofs = appl_ptr % runtime->buffer_size;
2066                 snd_pcm_stream_unlock_irq(substream);
2067                 err = transfer(substream, appl_ofs, data, offset, frames);
2068                 snd_pcm_stream_lock_irq(substream);
2069                 if (err < 0)
2070                         goto _end_unlock;
2071                 switch (runtime->status->state) {
2072                 case SNDRV_PCM_STATE_XRUN:
2073                         err = -EPIPE;
2074                         goto _end_unlock;
2075                 case SNDRV_PCM_STATE_SUSPENDED:
2076                         err = -ESTRPIPE;
2077                         goto _end_unlock;
2078                 default:
2079                         break;
2080                 }
2081                 appl_ptr += frames;
2082                 if (appl_ptr >= runtime->boundary)
2083                         appl_ptr -= runtime->boundary;
2084                 runtime->control->appl_ptr = appl_ptr;
2085                 if (substream->ops->ack)
2086                         substream->ops->ack(substream);
2087
2088                 offset += frames;
2089                 size -= frames;
2090                 xfer += frames;
2091         }
2092  _end_unlock:
2093         runtime->nowake = 0;
2094         if (xfer > 0 && err >= 0)
2095                 snd_pcm_update_state(substream, runtime);
2096         snd_pcm_stream_unlock_irq(substream);
2097         return xfer > 0 ? (snd_pcm_sframes_t)xfer : err;
2098 }
2099
2100 snd_pcm_sframes_t snd_pcm_lib_read(struct snd_pcm_substream *substream, void __user *buf, snd_pcm_uframes_t size)
2101 {
2102         struct snd_pcm_runtime *runtime;
2103         int nonblock;
2104         int err;
2105         
2106         err = pcm_sanity_check(substream);
2107         if (err < 0)
2108                 return err;
2109         runtime = substream->runtime;
2110         nonblock = !!(substream->f_flags & O_NONBLOCK);
2111         if (runtime->access != SNDRV_PCM_ACCESS_RW_INTERLEAVED)
2112                 return -EINVAL;
2113         return snd_pcm_lib_read1(substream, (unsigned long)buf, size, nonblock, snd_pcm_lib_read_transfer);
2114 }
2115
2116 EXPORT_SYMBOL(snd_pcm_lib_read);
2117
2118 static int snd_pcm_lib_readv_transfer(struct snd_pcm_substream *substream,
2119                                       unsigned int hwoff,
2120                                       unsigned long data, unsigned int off,
2121                                       snd_pcm_uframes_t frames)
2122 {
2123         struct snd_pcm_runtime *runtime = substream->runtime;
2124         int err;
2125         void __user **bufs = (void __user **)data;
2126         int channels = runtime->channels;
2127         int c;
2128         if (substream->ops->copy) {
2129                 for (c = 0; c < channels; ++c, ++bufs) {
2130                         char __user *buf;
2131                         if (*bufs == NULL)
2132                                 continue;
2133                         buf = *bufs + samples_to_bytes(runtime, off);
2134                         if ((err = substream->ops->copy(substream, c, hwoff, buf, frames)) < 0)
2135                                 return err;
2136                 }
2137         } else {
2138                 snd_pcm_uframes_t dma_csize = runtime->dma_bytes / channels;
2139                 for (c = 0; c < channels; ++c, ++bufs) {
2140                         char *hwbuf;
2141                         char __user *buf;
2142                         if (*bufs == NULL)
2143                                 continue;
2144
2145                         hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, hwoff);
2146                         buf = *bufs + samples_to_bytes(runtime, off);
2147                         if (copy_to_user(buf, hwbuf, samples_to_bytes(runtime, frames)))
2148                                 return -EFAULT;
2149                 }
2150         }
2151         return 0;
2152 }
2153  
2154 snd_pcm_sframes_t snd_pcm_lib_readv(struct snd_pcm_substream *substream,
2155                                     void __user **bufs,
2156                                     snd_pcm_uframes_t frames)
2157 {
2158         struct snd_pcm_runtime *runtime;
2159         int nonblock;
2160         int err;
2161
2162         err = pcm_sanity_check(substream);
2163         if (err < 0)
2164                 return err;
2165         runtime = substream->runtime;
2166         if (runtime->status->state == SNDRV_PCM_STATE_OPEN)
2167                 return -EBADFD;
2168
2169         nonblock = !!(substream->f_flags & O_NONBLOCK);
2170         if (runtime->access != SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)
2171                 return -EINVAL;
2172         return snd_pcm_lib_read1(substream, (unsigned long)bufs, frames, nonblock, snd_pcm_lib_readv_transfer);
2173 }
2174
2175 EXPORT_SYMBOL(snd_pcm_lib_readv);