ALSA: pcm_lib - cleanup & merge hw_ptr update functions
[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 static int snd_pcm_update_hw_ptr_post(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 (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) {
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_hw_ptr_post(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_diff, best_den;
765         unsigned int k;
766         struct snd_interval t;
767         int err;
768
769         best_num = best_den = best_diff = 0;
770         for (k = 0; k < rats_count; ++k) {
771                 unsigned int num = rats[k].num;
772                 unsigned int den;
773                 unsigned int q = i->min;
774                 int diff;
775                 if (q == 0)
776                         q = 1;
777                 den = div_down(num, q);
778                 if (den < rats[k].den_min)
779                         continue;
780                 if (den > rats[k].den_max)
781                         den = rats[k].den_max;
782                 else {
783                         unsigned int r;
784                         r = (den - rats[k].den_min) % rats[k].den_step;
785                         if (r != 0)
786                                 den -= r;
787                 }
788                 diff = num - q * den;
789                 if (best_num == 0 ||
790                     diff * best_den < best_diff * den) {
791                         best_diff = diff;
792                         best_den = den;
793                         best_num = num;
794                 }
795         }
796         if (best_den == 0) {
797                 i->empty = 1;
798                 return -EINVAL;
799         }
800         t.min = div_down(best_num, best_den);
801         t.openmin = !!(best_num % best_den);
802         
803         best_num = best_den = best_diff = 0;
804         for (k = 0; k < rats_count; ++k) {
805                 unsigned int num = rats[k].num;
806                 unsigned int den;
807                 unsigned int q = i->max;
808                 int diff;
809                 if (q == 0) {
810                         i->empty = 1;
811                         return -EINVAL;
812                 }
813                 den = div_up(num, q);
814                 if (den > rats[k].den_max)
815                         continue;
816                 if (den < rats[k].den_min)
817                         den = rats[k].den_min;
818                 else {
819                         unsigned int r;
820                         r = (den - rats[k].den_min) % rats[k].den_step;
821                         if (r != 0)
822                                 den += rats[k].den_step - r;
823                 }
824                 diff = q * den - num;
825                 if (best_num == 0 ||
826                     diff * best_den < best_diff * den) {
827                         best_diff = diff;
828                         best_den = den;
829                         best_num = num;
830                 }
831         }
832         if (best_den == 0) {
833                 i->empty = 1;
834                 return -EINVAL;
835         }
836         t.max = div_up(best_num, best_den);
837         t.openmax = !!(best_num % best_den);
838         t.integer = 0;
839         err = snd_interval_refine(i, &t);
840         if (err < 0)
841                 return err;
842
843         if (snd_interval_single(i)) {
844                 if (nump)
845                         *nump = best_num;
846                 if (denp)
847                         *denp = best_den;
848         }
849         return err;
850 }
851
852 EXPORT_SYMBOL(snd_interval_ratnum);
853
854 /**
855  * snd_interval_ratden - refine the interval value
856  * @i: interval to refine
857  * @rats_count: number of struct ratden
858  * @rats: struct ratden array
859  * @nump: pointer to store the resultant numerator
860  * @denp: pointer to store the resultant denominator
861  *
862  * Returns non-zero if the value is changed, zero if not changed.
863  */
864 static int snd_interval_ratden(struct snd_interval *i,
865                                unsigned int rats_count, struct snd_ratden *rats,
866                                unsigned int *nump, unsigned int *denp)
867 {
868         unsigned int best_num, best_diff, best_den;
869         unsigned int k;
870         struct snd_interval t;
871         int err;
872
873         best_num = best_den = best_diff = 0;
874         for (k = 0; k < rats_count; ++k) {
875                 unsigned int num;
876                 unsigned int den = rats[k].den;
877                 unsigned int q = i->min;
878                 int diff;
879                 num = mul(q, den);
880                 if (num > rats[k].num_max)
881                         continue;
882                 if (num < rats[k].num_min)
883                         num = rats[k].num_max;
884                 else {
885                         unsigned int r;
886                         r = (num - rats[k].num_min) % rats[k].num_step;
887                         if (r != 0)
888                                 num += rats[k].num_step - r;
889                 }
890                 diff = num - q * den;
891                 if (best_num == 0 ||
892                     diff * best_den < best_diff * den) {
893                         best_diff = diff;
894                         best_den = den;
895                         best_num = num;
896                 }
897         }
898         if (best_den == 0) {
899                 i->empty = 1;
900                 return -EINVAL;
901         }
902         t.min = div_down(best_num, best_den);
903         t.openmin = !!(best_num % best_den);
904         
905         best_num = best_den = best_diff = 0;
906         for (k = 0; k < rats_count; ++k) {
907                 unsigned int num;
908                 unsigned int den = rats[k].den;
909                 unsigned int q = i->max;
910                 int diff;
911                 num = mul(q, den);
912                 if (num < rats[k].num_min)
913                         continue;
914                 if (num > rats[k].num_max)
915                         num = rats[k].num_max;
916                 else {
917                         unsigned int r;
918                         r = (num - rats[k].num_min) % rats[k].num_step;
919                         if (r != 0)
920                                 num -= r;
921                 }
922                 diff = q * den - num;
923                 if (best_num == 0 ||
924                     diff * best_den < best_diff * den) {
925                         best_diff = diff;
926                         best_den = den;
927                         best_num = num;
928                 }
929         }
930         if (best_den == 0) {
931                 i->empty = 1;
932                 return -EINVAL;
933         }
934         t.max = div_up(best_num, best_den);
935         t.openmax = !!(best_num % best_den);
936         t.integer = 0;
937         err = snd_interval_refine(i, &t);
938         if (err < 0)
939                 return err;
940
941         if (snd_interval_single(i)) {
942                 if (nump)
943                         *nump = best_num;
944                 if (denp)
945                         *denp = best_den;
946         }
947         return err;
948 }
949
950 /**
951  * snd_interval_list - refine the interval value from the list
952  * @i: the interval value to refine
953  * @count: the number of elements in the list
954  * @list: the value list
955  * @mask: the bit-mask to evaluate
956  *
957  * Refines the interval value from the list.
958  * When mask is non-zero, only the elements corresponding to bit 1 are
959  * evaluated.
960  *
961  * Returns non-zero if the value is changed, zero if not changed.
962  */
963 int snd_interval_list(struct snd_interval *i, unsigned int count, unsigned int *list, unsigned int mask)
964 {
965         unsigned int k;
966         struct snd_interval list_range;
967
968         if (!count) {
969                 i->empty = 1;
970                 return -EINVAL;
971         }
972         snd_interval_any(&list_range);
973         list_range.min = UINT_MAX;
974         list_range.max = 0;
975         for (k = 0; k < count; k++) {
976                 if (mask && !(mask & (1 << k)))
977                         continue;
978                 if (!snd_interval_test(i, list[k]))
979                         continue;
980                 list_range.min = min(list_range.min, list[k]);
981                 list_range.max = max(list_range.max, list[k]);
982         }
983         return snd_interval_refine(i, &list_range);
984 }
985
986 EXPORT_SYMBOL(snd_interval_list);
987
988 static int snd_interval_step(struct snd_interval *i, unsigned int min, unsigned int step)
989 {
990         unsigned int n;
991         int changed = 0;
992         n = (i->min - min) % step;
993         if (n != 0 || i->openmin) {
994                 i->min += step - n;
995                 changed = 1;
996         }
997         n = (i->max - min) % step;
998         if (n != 0 || i->openmax) {
999                 i->max -= n;
1000                 changed = 1;
1001         }
1002         if (snd_interval_checkempty(i)) {
1003                 i->empty = 1;
1004                 return -EINVAL;
1005         }
1006         return changed;
1007 }
1008
1009 /* Info constraints helpers */
1010
1011 /**
1012  * snd_pcm_hw_rule_add - add the hw-constraint rule
1013  * @runtime: the pcm runtime instance
1014  * @cond: condition bits
1015  * @var: the variable to evaluate
1016  * @func: the evaluation function
1017  * @private: the private data pointer passed to function
1018  * @dep: the dependent variables
1019  *
1020  * Returns zero if successful, or a negative error code on failure.
1021  */
1022 int snd_pcm_hw_rule_add(struct snd_pcm_runtime *runtime, unsigned int cond,
1023                         int var,
1024                         snd_pcm_hw_rule_func_t func, void *private,
1025                         int dep, ...)
1026 {
1027         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1028         struct snd_pcm_hw_rule *c;
1029         unsigned int k;
1030         va_list args;
1031         va_start(args, dep);
1032         if (constrs->rules_num >= constrs->rules_all) {
1033                 struct snd_pcm_hw_rule *new;
1034                 unsigned int new_rules = constrs->rules_all + 16;
1035                 new = kcalloc(new_rules, sizeof(*c), GFP_KERNEL);
1036                 if (!new)
1037                         return -ENOMEM;
1038                 if (constrs->rules) {
1039                         memcpy(new, constrs->rules,
1040                                constrs->rules_num * sizeof(*c));
1041                         kfree(constrs->rules);
1042                 }
1043                 constrs->rules = new;
1044                 constrs->rules_all = new_rules;
1045         }
1046         c = &constrs->rules[constrs->rules_num];
1047         c->cond = cond;
1048         c->func = func;
1049         c->var = var;
1050         c->private = private;
1051         k = 0;
1052         while (1) {
1053                 if (snd_BUG_ON(k >= ARRAY_SIZE(c->deps)))
1054                         return -EINVAL;
1055                 c->deps[k++] = dep;
1056                 if (dep < 0)
1057                         break;
1058                 dep = va_arg(args, int);
1059         }
1060         constrs->rules_num++;
1061         va_end(args);
1062         return 0;
1063 }                                   
1064
1065 EXPORT_SYMBOL(snd_pcm_hw_rule_add);
1066
1067 /**
1068  * snd_pcm_hw_constraint_mask - apply the given bitmap mask constraint
1069  * @runtime: PCM runtime instance
1070  * @var: hw_params variable to apply the mask
1071  * @mask: the bitmap mask
1072  *
1073  * Apply the constraint of the given bitmap mask to a 32-bit mask parameter.
1074  */
1075 int snd_pcm_hw_constraint_mask(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1076                                u_int32_t mask)
1077 {
1078         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1079         struct snd_mask *maskp = constrs_mask(constrs, var);
1080         *maskp->bits &= mask;
1081         memset(maskp->bits + 1, 0, (SNDRV_MASK_MAX-32) / 8); /* clear rest */
1082         if (*maskp->bits == 0)
1083                 return -EINVAL;
1084         return 0;
1085 }
1086
1087 /**
1088  * snd_pcm_hw_constraint_mask64 - apply the given bitmap mask constraint
1089  * @runtime: PCM runtime instance
1090  * @var: hw_params variable to apply the mask
1091  * @mask: the 64bit bitmap mask
1092  *
1093  * Apply the constraint of the given bitmap mask to a 64-bit mask parameter.
1094  */
1095 int snd_pcm_hw_constraint_mask64(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1096                                  u_int64_t mask)
1097 {
1098         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1099         struct snd_mask *maskp = constrs_mask(constrs, var);
1100         maskp->bits[0] &= (u_int32_t)mask;
1101         maskp->bits[1] &= (u_int32_t)(mask >> 32);
1102         memset(maskp->bits + 2, 0, (SNDRV_MASK_MAX-64) / 8); /* clear rest */
1103         if (! maskp->bits[0] && ! maskp->bits[1])
1104                 return -EINVAL;
1105         return 0;
1106 }
1107
1108 /**
1109  * snd_pcm_hw_constraint_integer - apply an integer constraint to an interval
1110  * @runtime: PCM runtime instance
1111  * @var: hw_params variable to apply the integer constraint
1112  *
1113  * Apply the constraint of integer to an interval parameter.
1114  */
1115 int snd_pcm_hw_constraint_integer(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var)
1116 {
1117         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1118         return snd_interval_setinteger(constrs_interval(constrs, var));
1119 }
1120
1121 EXPORT_SYMBOL(snd_pcm_hw_constraint_integer);
1122
1123 /**
1124  * snd_pcm_hw_constraint_minmax - apply a min/max range constraint to an interval
1125  * @runtime: PCM runtime instance
1126  * @var: hw_params variable to apply the range
1127  * @min: the minimal value
1128  * @max: the maximal value
1129  * 
1130  * Apply the min/max range constraint to an interval parameter.
1131  */
1132 int snd_pcm_hw_constraint_minmax(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1133                                  unsigned int min, unsigned int max)
1134 {
1135         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1136         struct snd_interval t;
1137         t.min = min;
1138         t.max = max;
1139         t.openmin = t.openmax = 0;
1140         t.integer = 0;
1141         return snd_interval_refine(constrs_interval(constrs, var), &t);
1142 }
1143
1144 EXPORT_SYMBOL(snd_pcm_hw_constraint_minmax);
1145
1146 static int snd_pcm_hw_rule_list(struct snd_pcm_hw_params *params,
1147                                 struct snd_pcm_hw_rule *rule)
1148 {
1149         struct snd_pcm_hw_constraint_list *list = rule->private;
1150         return snd_interval_list(hw_param_interval(params, rule->var), list->count, list->list, list->mask);
1151 }               
1152
1153
1154 /**
1155  * snd_pcm_hw_constraint_list - apply a list of constraints to a parameter
1156  * @runtime: PCM runtime instance
1157  * @cond: condition bits
1158  * @var: hw_params variable to apply the list constraint
1159  * @l: list
1160  * 
1161  * Apply the list of constraints to an interval parameter.
1162  */
1163 int snd_pcm_hw_constraint_list(struct snd_pcm_runtime *runtime,
1164                                unsigned int cond,
1165                                snd_pcm_hw_param_t var,
1166                                struct snd_pcm_hw_constraint_list *l)
1167 {
1168         return snd_pcm_hw_rule_add(runtime, cond, var,
1169                                    snd_pcm_hw_rule_list, l,
1170                                    var, -1);
1171 }
1172
1173 EXPORT_SYMBOL(snd_pcm_hw_constraint_list);
1174
1175 static int snd_pcm_hw_rule_ratnums(struct snd_pcm_hw_params *params,
1176                                    struct snd_pcm_hw_rule *rule)
1177 {
1178         struct snd_pcm_hw_constraint_ratnums *r = rule->private;
1179         unsigned int num = 0, den = 0;
1180         int err;
1181         err = snd_interval_ratnum(hw_param_interval(params, rule->var),
1182                                   r->nrats, r->rats, &num, &den);
1183         if (err >= 0 && den && rule->var == SNDRV_PCM_HW_PARAM_RATE) {
1184                 params->rate_num = num;
1185                 params->rate_den = den;
1186         }
1187         return err;
1188 }
1189
1190 /**
1191  * snd_pcm_hw_constraint_ratnums - apply ratnums constraint to a parameter
1192  * @runtime: PCM runtime instance
1193  * @cond: condition bits
1194  * @var: hw_params variable to apply the ratnums constraint
1195  * @r: struct snd_ratnums constriants
1196  */
1197 int snd_pcm_hw_constraint_ratnums(struct snd_pcm_runtime *runtime, 
1198                                   unsigned int cond,
1199                                   snd_pcm_hw_param_t var,
1200                                   struct snd_pcm_hw_constraint_ratnums *r)
1201 {
1202         return snd_pcm_hw_rule_add(runtime, cond, var,
1203                                    snd_pcm_hw_rule_ratnums, r,
1204                                    var, -1);
1205 }
1206
1207 EXPORT_SYMBOL(snd_pcm_hw_constraint_ratnums);
1208
1209 static int snd_pcm_hw_rule_ratdens(struct snd_pcm_hw_params *params,
1210                                    struct snd_pcm_hw_rule *rule)
1211 {
1212         struct snd_pcm_hw_constraint_ratdens *r = rule->private;
1213         unsigned int num = 0, den = 0;
1214         int err = snd_interval_ratden(hw_param_interval(params, rule->var),
1215                                   r->nrats, r->rats, &num, &den);
1216         if (err >= 0 && den && rule->var == SNDRV_PCM_HW_PARAM_RATE) {
1217                 params->rate_num = num;
1218                 params->rate_den = den;
1219         }
1220         return err;
1221 }
1222
1223 /**
1224  * snd_pcm_hw_constraint_ratdens - apply ratdens constraint to a parameter
1225  * @runtime: PCM runtime instance
1226  * @cond: condition bits
1227  * @var: hw_params variable to apply the ratdens constraint
1228  * @r: struct snd_ratdens constriants
1229  */
1230 int snd_pcm_hw_constraint_ratdens(struct snd_pcm_runtime *runtime, 
1231                                   unsigned int cond,
1232                                   snd_pcm_hw_param_t var,
1233                                   struct snd_pcm_hw_constraint_ratdens *r)
1234 {
1235         return snd_pcm_hw_rule_add(runtime, cond, var,
1236                                    snd_pcm_hw_rule_ratdens, r,
1237                                    var, -1);
1238 }
1239
1240 EXPORT_SYMBOL(snd_pcm_hw_constraint_ratdens);
1241
1242 static int snd_pcm_hw_rule_msbits(struct snd_pcm_hw_params *params,
1243                                   struct snd_pcm_hw_rule *rule)
1244 {
1245         unsigned int l = (unsigned long) rule->private;
1246         int width = l & 0xffff;
1247         unsigned int msbits = l >> 16;
1248         struct snd_interval *i = hw_param_interval(params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS);
1249         if (snd_interval_single(i) && snd_interval_value(i) == width)
1250                 params->msbits = msbits;
1251         return 0;
1252 }
1253
1254 /**
1255  * snd_pcm_hw_constraint_msbits - add a hw constraint msbits rule
1256  * @runtime: PCM runtime instance
1257  * @cond: condition bits
1258  * @width: sample bits width
1259  * @msbits: msbits width
1260  */
1261 int snd_pcm_hw_constraint_msbits(struct snd_pcm_runtime *runtime, 
1262                                  unsigned int cond,
1263                                  unsigned int width,
1264                                  unsigned int msbits)
1265 {
1266         unsigned long l = (msbits << 16) | width;
1267         return snd_pcm_hw_rule_add(runtime, cond, -1,
1268                                     snd_pcm_hw_rule_msbits,
1269                                     (void*) l,
1270                                     SNDRV_PCM_HW_PARAM_SAMPLE_BITS, -1);
1271 }
1272
1273 EXPORT_SYMBOL(snd_pcm_hw_constraint_msbits);
1274
1275 static int snd_pcm_hw_rule_step(struct snd_pcm_hw_params *params,
1276                                 struct snd_pcm_hw_rule *rule)
1277 {
1278         unsigned long step = (unsigned long) rule->private;
1279         return snd_interval_step(hw_param_interval(params, rule->var), 0, step);
1280 }
1281
1282 /**
1283  * snd_pcm_hw_constraint_step - add a hw constraint step rule
1284  * @runtime: PCM runtime instance
1285  * @cond: condition bits
1286  * @var: hw_params variable to apply the step constraint
1287  * @step: step size
1288  */
1289 int snd_pcm_hw_constraint_step(struct snd_pcm_runtime *runtime,
1290                                unsigned int cond,
1291                                snd_pcm_hw_param_t var,
1292                                unsigned long step)
1293 {
1294         return snd_pcm_hw_rule_add(runtime, cond, var, 
1295                                    snd_pcm_hw_rule_step, (void *) step,
1296                                    var, -1);
1297 }
1298
1299 EXPORT_SYMBOL(snd_pcm_hw_constraint_step);
1300
1301 static int snd_pcm_hw_rule_pow2(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule)
1302 {
1303         static unsigned int pow2_sizes[] = {
1304                 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7,
1305                 1<<8, 1<<9, 1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15,
1306                 1<<16, 1<<17, 1<<18, 1<<19, 1<<20, 1<<21, 1<<22, 1<<23,
1307                 1<<24, 1<<25, 1<<26, 1<<27, 1<<28, 1<<29, 1<<30
1308         };
1309         return snd_interval_list(hw_param_interval(params, rule->var),
1310                                  ARRAY_SIZE(pow2_sizes), pow2_sizes, 0);
1311 }               
1312
1313 /**
1314  * snd_pcm_hw_constraint_pow2 - add a hw constraint power-of-2 rule
1315  * @runtime: PCM runtime instance
1316  * @cond: condition bits
1317  * @var: hw_params variable to apply the power-of-2 constraint
1318  */
1319 int snd_pcm_hw_constraint_pow2(struct snd_pcm_runtime *runtime,
1320                                unsigned int cond,
1321                                snd_pcm_hw_param_t var)
1322 {
1323         return snd_pcm_hw_rule_add(runtime, cond, var, 
1324                                    snd_pcm_hw_rule_pow2, NULL,
1325                                    var, -1);
1326 }
1327
1328 EXPORT_SYMBOL(snd_pcm_hw_constraint_pow2);
1329
1330 static void _snd_pcm_hw_param_any(struct snd_pcm_hw_params *params,
1331                                   snd_pcm_hw_param_t var)
1332 {
1333         if (hw_is_mask(var)) {
1334                 snd_mask_any(hw_param_mask(params, var));
1335                 params->cmask |= 1 << var;
1336                 params->rmask |= 1 << var;
1337                 return;
1338         }
1339         if (hw_is_interval(var)) {
1340                 snd_interval_any(hw_param_interval(params, var));
1341                 params->cmask |= 1 << var;
1342                 params->rmask |= 1 << var;
1343                 return;
1344         }
1345         snd_BUG();
1346 }
1347
1348 void _snd_pcm_hw_params_any(struct snd_pcm_hw_params *params)
1349 {
1350         unsigned int k;
1351         memset(params, 0, sizeof(*params));
1352         for (k = SNDRV_PCM_HW_PARAM_FIRST_MASK; k <= SNDRV_PCM_HW_PARAM_LAST_MASK; k++)
1353                 _snd_pcm_hw_param_any(params, k);
1354         for (k = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; k <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; k++)
1355                 _snd_pcm_hw_param_any(params, k);
1356         params->info = ~0U;
1357 }
1358
1359 EXPORT_SYMBOL(_snd_pcm_hw_params_any);
1360
1361 /**
1362  * snd_pcm_hw_param_value - return @params field @var value
1363  * @params: the hw_params instance
1364  * @var: parameter to retrieve
1365  * @dir: pointer to the direction (-1,0,1) or %NULL
1366  *
1367  * Return the value for field @var if it's fixed in configuration space
1368  * defined by @params. Return -%EINVAL otherwise.
1369  */
1370 int snd_pcm_hw_param_value(const struct snd_pcm_hw_params *params,
1371                            snd_pcm_hw_param_t var, int *dir)
1372 {
1373         if (hw_is_mask(var)) {
1374                 const struct snd_mask *mask = hw_param_mask_c(params, var);
1375                 if (!snd_mask_single(mask))
1376                         return -EINVAL;
1377                 if (dir)
1378                         *dir = 0;
1379                 return snd_mask_value(mask);
1380         }
1381         if (hw_is_interval(var)) {
1382                 const struct snd_interval *i = hw_param_interval_c(params, var);
1383                 if (!snd_interval_single(i))
1384                         return -EINVAL;
1385                 if (dir)
1386                         *dir = i->openmin;
1387                 return snd_interval_value(i);
1388         }
1389         return -EINVAL;
1390 }
1391
1392 EXPORT_SYMBOL(snd_pcm_hw_param_value);
1393
1394 void _snd_pcm_hw_param_setempty(struct snd_pcm_hw_params *params,
1395                                 snd_pcm_hw_param_t var)
1396 {
1397         if (hw_is_mask(var)) {
1398                 snd_mask_none(hw_param_mask(params, var));
1399                 params->cmask |= 1 << var;
1400                 params->rmask |= 1 << var;
1401         } else if (hw_is_interval(var)) {
1402                 snd_interval_none(hw_param_interval(params, var));
1403                 params->cmask |= 1 << var;
1404                 params->rmask |= 1 << var;
1405         } else {
1406                 snd_BUG();
1407         }
1408 }
1409
1410 EXPORT_SYMBOL(_snd_pcm_hw_param_setempty);
1411
1412 static int _snd_pcm_hw_param_first(struct snd_pcm_hw_params *params,
1413                                    snd_pcm_hw_param_t var)
1414 {
1415         int changed;
1416         if (hw_is_mask(var))
1417                 changed = snd_mask_refine_first(hw_param_mask(params, var));
1418         else if (hw_is_interval(var))
1419                 changed = snd_interval_refine_first(hw_param_interval(params, var));
1420         else
1421                 return -EINVAL;
1422         if (changed) {
1423                 params->cmask |= 1 << var;
1424                 params->rmask |= 1 << var;
1425         }
1426         return changed;
1427 }
1428
1429
1430 /**
1431  * snd_pcm_hw_param_first - refine config space and return minimum value
1432  * @pcm: PCM instance
1433  * @params: the hw_params instance
1434  * @var: parameter to retrieve
1435  * @dir: pointer to the direction (-1,0,1) or %NULL
1436  *
1437  * Inside configuration space defined by @params remove from @var all
1438  * values > minimum. Reduce configuration space accordingly.
1439  * Return the minimum.
1440  */
1441 int snd_pcm_hw_param_first(struct snd_pcm_substream *pcm, 
1442                            struct snd_pcm_hw_params *params, 
1443                            snd_pcm_hw_param_t var, int *dir)
1444 {
1445         int changed = _snd_pcm_hw_param_first(params, var);
1446         if (changed < 0)
1447                 return changed;
1448         if (params->rmask) {
1449                 int err = snd_pcm_hw_refine(pcm, params);
1450                 if (snd_BUG_ON(err < 0))
1451                         return err;
1452         }
1453         return snd_pcm_hw_param_value(params, var, dir);
1454 }
1455
1456 EXPORT_SYMBOL(snd_pcm_hw_param_first);
1457
1458 static int _snd_pcm_hw_param_last(struct snd_pcm_hw_params *params,
1459                                   snd_pcm_hw_param_t var)
1460 {
1461         int changed;
1462         if (hw_is_mask(var))
1463                 changed = snd_mask_refine_last(hw_param_mask(params, var));
1464         else if (hw_is_interval(var))
1465                 changed = snd_interval_refine_last(hw_param_interval(params, var));
1466         else
1467                 return -EINVAL;
1468         if (changed) {
1469                 params->cmask |= 1 << var;
1470                 params->rmask |= 1 << var;
1471         }
1472         return changed;
1473 }
1474
1475
1476 /**
1477  * snd_pcm_hw_param_last - refine config space and return maximum value
1478  * @pcm: PCM instance
1479  * @params: the hw_params instance
1480  * @var: parameter to retrieve
1481  * @dir: pointer to the direction (-1,0,1) or %NULL
1482  *
1483  * Inside configuration space defined by @params remove from @var all
1484  * values < maximum. Reduce configuration space accordingly.
1485  * Return the maximum.
1486  */
1487 int snd_pcm_hw_param_last(struct snd_pcm_substream *pcm, 
1488                           struct snd_pcm_hw_params *params,
1489                           snd_pcm_hw_param_t var, int *dir)
1490 {
1491         int changed = _snd_pcm_hw_param_last(params, var);
1492         if (changed < 0)
1493                 return changed;
1494         if (params->rmask) {
1495                 int err = snd_pcm_hw_refine(pcm, params);
1496                 if (snd_BUG_ON(err < 0))
1497                         return err;
1498         }
1499         return snd_pcm_hw_param_value(params, var, dir);
1500 }
1501
1502 EXPORT_SYMBOL(snd_pcm_hw_param_last);
1503
1504 /**
1505  * snd_pcm_hw_param_choose - choose a configuration defined by @params
1506  * @pcm: PCM instance
1507  * @params: the hw_params instance
1508  *
1509  * Choose one configuration from configuration space defined by @params.
1510  * The configuration chosen is that obtained fixing in this order:
1511  * first access, first format, first subformat, min channels,
1512  * min rate, min period time, max buffer size, min tick time
1513  */
1514 int snd_pcm_hw_params_choose(struct snd_pcm_substream *pcm,
1515                              struct snd_pcm_hw_params *params)
1516 {
1517         static int vars[] = {
1518                 SNDRV_PCM_HW_PARAM_ACCESS,
1519                 SNDRV_PCM_HW_PARAM_FORMAT,
1520                 SNDRV_PCM_HW_PARAM_SUBFORMAT,
1521                 SNDRV_PCM_HW_PARAM_CHANNELS,
1522                 SNDRV_PCM_HW_PARAM_RATE,
1523                 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1524                 SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
1525                 SNDRV_PCM_HW_PARAM_TICK_TIME,
1526                 -1
1527         };
1528         int err, *v;
1529
1530         for (v = vars; *v != -1; v++) {
1531                 if (*v != SNDRV_PCM_HW_PARAM_BUFFER_SIZE)
1532                         err = snd_pcm_hw_param_first(pcm, params, *v, NULL);
1533                 else
1534                         err = snd_pcm_hw_param_last(pcm, params, *v, NULL);
1535                 if (snd_BUG_ON(err < 0))
1536                         return err;
1537         }
1538         return 0;
1539 }
1540
1541 static int snd_pcm_lib_ioctl_reset(struct snd_pcm_substream *substream,
1542                                    void *arg)
1543 {
1544         struct snd_pcm_runtime *runtime = substream->runtime;
1545         unsigned long flags;
1546         snd_pcm_stream_lock_irqsave(substream, flags);
1547         if (snd_pcm_running(substream) &&
1548             snd_pcm_update_hw_ptr(substream) >= 0)
1549                 runtime->status->hw_ptr %= runtime->buffer_size;
1550         else
1551                 runtime->status->hw_ptr = 0;
1552         snd_pcm_stream_unlock_irqrestore(substream, flags);
1553         return 0;
1554 }
1555
1556 static int snd_pcm_lib_ioctl_channel_info(struct snd_pcm_substream *substream,
1557                                           void *arg)
1558 {
1559         struct snd_pcm_channel_info *info = arg;
1560         struct snd_pcm_runtime *runtime = substream->runtime;
1561         int width;
1562         if (!(runtime->info & SNDRV_PCM_INFO_MMAP)) {
1563                 info->offset = -1;
1564                 return 0;
1565         }
1566         width = snd_pcm_format_physical_width(runtime->format);
1567         if (width < 0)
1568                 return width;
1569         info->offset = 0;
1570         switch (runtime->access) {
1571         case SNDRV_PCM_ACCESS_MMAP_INTERLEAVED:
1572         case SNDRV_PCM_ACCESS_RW_INTERLEAVED:
1573                 info->first = info->channel * width;
1574                 info->step = runtime->channels * width;
1575                 break;
1576         case SNDRV_PCM_ACCESS_MMAP_NONINTERLEAVED:
1577         case SNDRV_PCM_ACCESS_RW_NONINTERLEAVED:
1578         {
1579                 size_t size = runtime->dma_bytes / runtime->channels;
1580                 info->first = info->channel * size * 8;
1581                 info->step = width;
1582                 break;
1583         }
1584         default:
1585                 snd_BUG();
1586                 break;
1587         }
1588         return 0;
1589 }
1590
1591 static int snd_pcm_lib_ioctl_fifo_size(struct snd_pcm_substream *substream,
1592                                        void *arg)
1593 {
1594         struct snd_pcm_hw_params *params = arg;
1595         snd_pcm_format_t format;
1596         int channels, width;
1597
1598         params->fifo_size = substream->runtime->hw.fifo_size;
1599         if (!(substream->runtime->hw.info & SNDRV_PCM_INFO_FIFO_IN_FRAMES)) {
1600                 format = params_format(params);
1601                 channels = params_channels(params);
1602                 width = snd_pcm_format_physical_width(format);
1603                 params->fifo_size /= width * channels;
1604         }
1605         return 0;
1606 }
1607
1608 /**
1609  * snd_pcm_lib_ioctl - a generic PCM ioctl callback
1610  * @substream: the pcm substream instance
1611  * @cmd: ioctl command
1612  * @arg: ioctl argument
1613  *
1614  * Processes the generic ioctl commands for PCM.
1615  * Can be passed as the ioctl callback for PCM ops.
1616  *
1617  * Returns zero if successful, or a negative error code on failure.
1618  */
1619 int snd_pcm_lib_ioctl(struct snd_pcm_substream *substream,
1620                       unsigned int cmd, void *arg)
1621 {
1622         switch (cmd) {
1623         case SNDRV_PCM_IOCTL1_INFO:
1624                 return 0;
1625         case SNDRV_PCM_IOCTL1_RESET:
1626                 return snd_pcm_lib_ioctl_reset(substream, arg);
1627         case SNDRV_PCM_IOCTL1_CHANNEL_INFO:
1628                 return snd_pcm_lib_ioctl_channel_info(substream, arg);
1629         case SNDRV_PCM_IOCTL1_FIFO_SIZE:
1630                 return snd_pcm_lib_ioctl_fifo_size(substream, arg);
1631         }
1632         return -ENXIO;
1633 }
1634
1635 EXPORT_SYMBOL(snd_pcm_lib_ioctl);
1636
1637 /**
1638  * snd_pcm_period_elapsed - update the pcm status for the next period
1639  * @substream: the pcm substream instance
1640  *
1641  * This function is called from the interrupt handler when the
1642  * PCM has processed the period size.  It will update the current
1643  * pointer, wake up sleepers, etc.
1644  *
1645  * Even if more than one periods have elapsed since the last call, you
1646  * have to call this only once.
1647  */
1648 void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
1649 {
1650         struct snd_pcm_runtime *runtime;
1651         unsigned long flags;
1652
1653         if (PCM_RUNTIME_CHECK(substream))
1654                 return;
1655         runtime = substream->runtime;
1656
1657         if (runtime->transfer_ack_begin)
1658                 runtime->transfer_ack_begin(substream);
1659
1660         snd_pcm_stream_lock_irqsave(substream, flags);
1661         if (!snd_pcm_running(substream) ||
1662             snd_pcm_update_hw_ptr0(substream, 1) < 0)
1663                 goto _end;
1664
1665         if (substream->timer_running)
1666                 snd_timer_interrupt(substream->timer, 1);
1667  _end:
1668         snd_pcm_stream_unlock_irqrestore(substream, flags);
1669         if (runtime->transfer_ack_end)
1670                 runtime->transfer_ack_end(substream);
1671         kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
1672 }
1673
1674 EXPORT_SYMBOL(snd_pcm_period_elapsed);
1675
1676 /*
1677  * Wait until avail_min data becomes available
1678  * Returns a negative error code if any error occurs during operation.
1679  * The available space is stored on availp.  When err = 0 and avail = 0
1680  * on the capture stream, it indicates the stream is in DRAINING state.
1681  */
1682 static int wait_for_avail_min(struct snd_pcm_substream *substream,
1683                               snd_pcm_uframes_t *availp)
1684 {
1685         struct snd_pcm_runtime *runtime = substream->runtime;
1686         int is_playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK;
1687         wait_queue_t wait;
1688         int err = 0;
1689         snd_pcm_uframes_t avail = 0;
1690         long tout;
1691
1692         init_waitqueue_entry(&wait, current);
1693         add_wait_queue(&runtime->sleep, &wait);
1694         for (;;) {
1695                 if (signal_pending(current)) {
1696                         err = -ERESTARTSYS;
1697                         break;
1698                 }
1699                 set_current_state(TASK_INTERRUPTIBLE);
1700                 snd_pcm_stream_unlock_irq(substream);
1701                 tout = schedule_timeout(msecs_to_jiffies(10000));
1702                 snd_pcm_stream_lock_irq(substream);
1703                 switch (runtime->status->state) {
1704                 case SNDRV_PCM_STATE_SUSPENDED:
1705                         err = -ESTRPIPE;
1706                         goto _endloop;
1707                 case SNDRV_PCM_STATE_XRUN:
1708                         err = -EPIPE;
1709                         goto _endloop;
1710                 case SNDRV_PCM_STATE_DRAINING:
1711                         if (is_playback)
1712                                 err = -EPIPE;
1713                         else 
1714                                 avail = 0; /* indicate draining */
1715                         goto _endloop;
1716                 case SNDRV_PCM_STATE_OPEN:
1717                 case SNDRV_PCM_STATE_SETUP:
1718                 case SNDRV_PCM_STATE_DISCONNECTED:
1719                         err = -EBADFD;
1720                         goto _endloop;
1721                 }
1722                 if (!tout) {
1723                         snd_printd("%s write error (DMA or IRQ trouble?)\n",
1724                                    is_playback ? "playback" : "capture");
1725                         err = -EIO;
1726                         break;
1727                 }
1728                 if (is_playback)
1729                         avail = snd_pcm_playback_avail(runtime);
1730                 else
1731                         avail = snd_pcm_capture_avail(runtime);
1732                 if (avail >= runtime->control->avail_min)
1733                         break;
1734         }
1735  _endloop:
1736         remove_wait_queue(&runtime->sleep, &wait);
1737         *availp = avail;
1738         return err;
1739 }
1740         
1741 static int snd_pcm_lib_write_transfer(struct snd_pcm_substream *substream,
1742                                       unsigned int hwoff,
1743                                       unsigned long data, unsigned int off,
1744                                       snd_pcm_uframes_t frames)
1745 {
1746         struct snd_pcm_runtime *runtime = substream->runtime;
1747         int err;
1748         char __user *buf = (char __user *) data + frames_to_bytes(runtime, off);
1749         if (substream->ops->copy) {
1750                 if ((err = substream->ops->copy(substream, -1, hwoff, buf, frames)) < 0)
1751                         return err;
1752         } else {
1753                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);
1754                 if (copy_from_user(hwbuf, buf, frames_to_bytes(runtime, frames)))
1755                         return -EFAULT;
1756         }
1757         return 0;
1758 }
1759  
1760 typedef int (*transfer_f)(struct snd_pcm_substream *substream, unsigned int hwoff,
1761                           unsigned long data, unsigned int off,
1762                           snd_pcm_uframes_t size);
1763
1764 static snd_pcm_sframes_t snd_pcm_lib_write1(struct snd_pcm_substream *substream, 
1765                                             unsigned long data,
1766                                             snd_pcm_uframes_t size,
1767                                             int nonblock,
1768                                             transfer_f transfer)
1769 {
1770         struct snd_pcm_runtime *runtime = substream->runtime;
1771         snd_pcm_uframes_t xfer = 0;
1772         snd_pcm_uframes_t offset = 0;
1773         int err = 0;
1774
1775         if (size == 0)
1776                 return 0;
1777
1778         snd_pcm_stream_lock_irq(substream);
1779         switch (runtime->status->state) {
1780         case SNDRV_PCM_STATE_PREPARED:
1781         case SNDRV_PCM_STATE_RUNNING:
1782         case SNDRV_PCM_STATE_PAUSED:
1783                 break;
1784         case SNDRV_PCM_STATE_XRUN:
1785                 err = -EPIPE;
1786                 goto _end_unlock;
1787         case SNDRV_PCM_STATE_SUSPENDED:
1788                 err = -ESTRPIPE;
1789                 goto _end_unlock;
1790         default:
1791                 err = -EBADFD;
1792                 goto _end_unlock;
1793         }
1794
1795         while (size > 0) {
1796                 snd_pcm_uframes_t frames, appl_ptr, appl_ofs;
1797                 snd_pcm_uframes_t avail;
1798                 snd_pcm_uframes_t cont;
1799                 if (runtime->status->state == SNDRV_PCM_STATE_RUNNING)
1800                         snd_pcm_update_hw_ptr(substream);
1801                 avail = snd_pcm_playback_avail(runtime);
1802                 if (!avail) {
1803                         if (nonblock) {
1804                                 err = -EAGAIN;
1805                                 goto _end_unlock;
1806                         }
1807                         err = wait_for_avail_min(substream, &avail);
1808                         if (err < 0)
1809                                 goto _end_unlock;
1810                 }
1811                 frames = size > avail ? avail : size;
1812                 cont = runtime->buffer_size - runtime->control->appl_ptr % runtime->buffer_size;
1813                 if (frames > cont)
1814                         frames = cont;
1815                 if (snd_BUG_ON(!frames)) {
1816                         snd_pcm_stream_unlock_irq(substream);
1817                         return -EINVAL;
1818                 }
1819                 appl_ptr = runtime->control->appl_ptr;
1820                 appl_ofs = appl_ptr % runtime->buffer_size;
1821                 snd_pcm_stream_unlock_irq(substream);
1822                 if ((err = transfer(substream, appl_ofs, data, offset, frames)) < 0)
1823                         goto _end;
1824                 snd_pcm_stream_lock_irq(substream);
1825                 switch (runtime->status->state) {
1826                 case SNDRV_PCM_STATE_XRUN:
1827                         err = -EPIPE;
1828                         goto _end_unlock;
1829                 case SNDRV_PCM_STATE_SUSPENDED:
1830                         err = -ESTRPIPE;
1831                         goto _end_unlock;
1832                 default:
1833                         break;
1834                 }
1835                 appl_ptr += frames;
1836                 if (appl_ptr >= runtime->boundary)
1837                         appl_ptr -= runtime->boundary;
1838                 runtime->control->appl_ptr = appl_ptr;
1839                 if (substream->ops->ack)
1840                         substream->ops->ack(substream);
1841
1842                 offset += frames;
1843                 size -= frames;
1844                 xfer += frames;
1845                 if (runtime->status->state == SNDRV_PCM_STATE_PREPARED &&
1846                     snd_pcm_playback_hw_avail(runtime) >= (snd_pcm_sframes_t)runtime->start_threshold) {
1847                         err = snd_pcm_start(substream);
1848                         if (err < 0)
1849                                 goto _end_unlock;
1850                 }
1851         }
1852  _end_unlock:
1853         snd_pcm_stream_unlock_irq(substream);
1854  _end:
1855         return xfer > 0 ? (snd_pcm_sframes_t)xfer : err;
1856 }
1857
1858 /* sanity-check for read/write methods */
1859 static int pcm_sanity_check(struct snd_pcm_substream *substream)
1860 {
1861         struct snd_pcm_runtime *runtime;
1862         if (PCM_RUNTIME_CHECK(substream))
1863                 return -ENXIO;
1864         runtime = substream->runtime;
1865         if (snd_BUG_ON(!substream->ops->copy && !runtime->dma_area))
1866                 return -EINVAL;
1867         if (runtime->status->state == SNDRV_PCM_STATE_OPEN)
1868                 return -EBADFD;
1869         return 0;
1870 }
1871
1872 snd_pcm_sframes_t snd_pcm_lib_write(struct snd_pcm_substream *substream, const void __user *buf, snd_pcm_uframes_t size)
1873 {
1874         struct snd_pcm_runtime *runtime;
1875         int nonblock;
1876         int err;
1877
1878         err = pcm_sanity_check(substream);
1879         if (err < 0)
1880                 return err;
1881         runtime = substream->runtime;
1882         nonblock = !!(substream->f_flags & O_NONBLOCK);
1883
1884         if (runtime->access != SNDRV_PCM_ACCESS_RW_INTERLEAVED &&
1885             runtime->channels > 1)
1886                 return -EINVAL;
1887         return snd_pcm_lib_write1(substream, (unsigned long)buf, size, nonblock,
1888                                   snd_pcm_lib_write_transfer);
1889 }
1890
1891 EXPORT_SYMBOL(snd_pcm_lib_write);
1892
1893 static int snd_pcm_lib_writev_transfer(struct snd_pcm_substream *substream,
1894                                        unsigned int hwoff,
1895                                        unsigned long data, unsigned int off,
1896                                        snd_pcm_uframes_t frames)
1897 {
1898         struct snd_pcm_runtime *runtime = substream->runtime;
1899         int err;
1900         void __user **bufs = (void __user **)data;
1901         int channels = runtime->channels;
1902         int c;
1903         if (substream->ops->copy) {
1904                 if (snd_BUG_ON(!substream->ops->silence))
1905                         return -EINVAL;
1906                 for (c = 0; c < channels; ++c, ++bufs) {
1907                         if (*bufs == NULL) {
1908                                 if ((err = substream->ops->silence(substream, c, hwoff, frames)) < 0)
1909                                         return err;
1910                         } else {
1911                                 char __user *buf = *bufs + samples_to_bytes(runtime, off);
1912                                 if ((err = substream->ops->copy(substream, c, hwoff, buf, frames)) < 0)
1913                                         return err;
1914                         }
1915                 }
1916         } else {
1917                 /* default transfer behaviour */
1918                 size_t dma_csize = runtime->dma_bytes / channels;
1919                 for (c = 0; c < channels; ++c, ++bufs) {
1920                         char *hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, hwoff);
1921                         if (*bufs == NULL) {
1922                                 snd_pcm_format_set_silence(runtime->format, hwbuf, frames);
1923                         } else {
1924                                 char __user *buf = *bufs + samples_to_bytes(runtime, off);
1925                                 if (copy_from_user(hwbuf, buf, samples_to_bytes(runtime, frames)))
1926                                         return -EFAULT;
1927                         }
1928                 }
1929         }
1930         return 0;
1931 }
1932  
1933 snd_pcm_sframes_t snd_pcm_lib_writev(struct snd_pcm_substream *substream,
1934                                      void __user **bufs,
1935                                      snd_pcm_uframes_t frames)
1936 {
1937         struct snd_pcm_runtime *runtime;
1938         int nonblock;
1939         int err;
1940
1941         err = pcm_sanity_check(substream);
1942         if (err < 0)
1943                 return err;
1944         runtime = substream->runtime;
1945         nonblock = !!(substream->f_flags & O_NONBLOCK);
1946
1947         if (runtime->access != SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)
1948                 return -EINVAL;
1949         return snd_pcm_lib_write1(substream, (unsigned long)bufs, frames,
1950                                   nonblock, snd_pcm_lib_writev_transfer);
1951 }
1952
1953 EXPORT_SYMBOL(snd_pcm_lib_writev);
1954
1955 static int snd_pcm_lib_read_transfer(struct snd_pcm_substream *substream, 
1956                                      unsigned int hwoff,
1957                                      unsigned long data, unsigned int off,
1958                                      snd_pcm_uframes_t frames)
1959 {
1960         struct snd_pcm_runtime *runtime = substream->runtime;
1961         int err;
1962         char __user *buf = (char __user *) data + frames_to_bytes(runtime, off);
1963         if (substream->ops->copy) {
1964                 if ((err = substream->ops->copy(substream, -1, hwoff, buf, frames)) < 0)
1965                         return err;
1966         } else {
1967                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);
1968                 if (copy_to_user(buf, hwbuf, frames_to_bytes(runtime, frames)))
1969                         return -EFAULT;
1970         }
1971         return 0;
1972 }
1973
1974 static snd_pcm_sframes_t snd_pcm_lib_read1(struct snd_pcm_substream *substream,
1975                                            unsigned long data,
1976                                            snd_pcm_uframes_t size,
1977                                            int nonblock,
1978                                            transfer_f transfer)
1979 {
1980         struct snd_pcm_runtime *runtime = substream->runtime;
1981         snd_pcm_uframes_t xfer = 0;
1982         snd_pcm_uframes_t offset = 0;
1983         int err = 0;
1984
1985         if (size == 0)
1986                 return 0;
1987
1988         snd_pcm_stream_lock_irq(substream);
1989         switch (runtime->status->state) {
1990         case SNDRV_PCM_STATE_PREPARED:
1991                 if (size >= runtime->start_threshold) {
1992                         err = snd_pcm_start(substream);
1993                         if (err < 0)
1994                                 goto _end_unlock;
1995                 }
1996                 break;
1997         case SNDRV_PCM_STATE_DRAINING:
1998         case SNDRV_PCM_STATE_RUNNING:
1999         case SNDRV_PCM_STATE_PAUSED:
2000                 break;
2001         case SNDRV_PCM_STATE_XRUN:
2002                 err = -EPIPE;
2003                 goto _end_unlock;
2004         case SNDRV_PCM_STATE_SUSPENDED:
2005                 err = -ESTRPIPE;
2006                 goto _end_unlock;
2007         default:
2008                 err = -EBADFD;
2009                 goto _end_unlock;
2010         }
2011
2012         while (size > 0) {
2013                 snd_pcm_uframes_t frames, appl_ptr, appl_ofs;
2014                 snd_pcm_uframes_t avail;
2015                 snd_pcm_uframes_t cont;
2016                 if (runtime->status->state == SNDRV_PCM_STATE_RUNNING)
2017                         snd_pcm_update_hw_ptr(substream);
2018                 avail = snd_pcm_capture_avail(runtime);
2019                 if (!avail) {
2020                         if (runtime->status->state ==
2021                             SNDRV_PCM_STATE_DRAINING) {
2022                                 snd_pcm_stop(substream, SNDRV_PCM_STATE_SETUP);
2023                                 goto _end_unlock;
2024                         }
2025                         if (nonblock) {
2026                                 err = -EAGAIN;
2027                                 goto _end_unlock;
2028                         }
2029                         err = wait_for_avail_min(substream, &avail);
2030                         if (err < 0)
2031                                 goto _end_unlock;
2032                         if (!avail)
2033                                 continue; /* draining */
2034                 }
2035                 frames = size > avail ? avail : size;
2036                 cont = runtime->buffer_size - runtime->control->appl_ptr % runtime->buffer_size;
2037                 if (frames > cont)
2038                         frames = cont;
2039                 if (snd_BUG_ON(!frames)) {
2040                         snd_pcm_stream_unlock_irq(substream);
2041                         return -EINVAL;
2042                 }
2043                 appl_ptr = runtime->control->appl_ptr;
2044                 appl_ofs = appl_ptr % runtime->buffer_size;
2045                 snd_pcm_stream_unlock_irq(substream);
2046                 if ((err = transfer(substream, appl_ofs, data, offset, frames)) < 0)
2047                         goto _end;
2048                 snd_pcm_stream_lock_irq(substream);
2049                 switch (runtime->status->state) {
2050                 case SNDRV_PCM_STATE_XRUN:
2051                         err = -EPIPE;
2052                         goto _end_unlock;
2053                 case SNDRV_PCM_STATE_SUSPENDED:
2054                         err = -ESTRPIPE;
2055                         goto _end_unlock;
2056                 default:
2057                         break;
2058                 }
2059                 appl_ptr += frames;
2060                 if (appl_ptr >= runtime->boundary)
2061                         appl_ptr -= runtime->boundary;
2062                 runtime->control->appl_ptr = appl_ptr;
2063                 if (substream->ops->ack)
2064                         substream->ops->ack(substream);
2065
2066                 offset += frames;
2067                 size -= frames;
2068                 xfer += frames;
2069         }
2070  _end_unlock:
2071         snd_pcm_stream_unlock_irq(substream);
2072  _end:
2073         return xfer > 0 ? (snd_pcm_sframes_t)xfer : err;
2074 }
2075
2076 snd_pcm_sframes_t snd_pcm_lib_read(struct snd_pcm_substream *substream, void __user *buf, snd_pcm_uframes_t size)
2077 {
2078         struct snd_pcm_runtime *runtime;
2079         int nonblock;
2080         int err;
2081         
2082         err = pcm_sanity_check(substream);
2083         if (err < 0)
2084                 return err;
2085         runtime = substream->runtime;
2086         nonblock = !!(substream->f_flags & O_NONBLOCK);
2087         if (runtime->access != SNDRV_PCM_ACCESS_RW_INTERLEAVED)
2088                 return -EINVAL;
2089         return snd_pcm_lib_read1(substream, (unsigned long)buf, size, nonblock, snd_pcm_lib_read_transfer);
2090 }
2091
2092 EXPORT_SYMBOL(snd_pcm_lib_read);
2093
2094 static int snd_pcm_lib_readv_transfer(struct snd_pcm_substream *substream,
2095                                       unsigned int hwoff,
2096                                       unsigned long data, unsigned int off,
2097                                       snd_pcm_uframes_t frames)
2098 {
2099         struct snd_pcm_runtime *runtime = substream->runtime;
2100         int err;
2101         void __user **bufs = (void __user **)data;
2102         int channels = runtime->channels;
2103         int c;
2104         if (substream->ops->copy) {
2105                 for (c = 0; c < channels; ++c, ++bufs) {
2106                         char __user *buf;
2107                         if (*bufs == NULL)
2108                                 continue;
2109                         buf = *bufs + samples_to_bytes(runtime, off);
2110                         if ((err = substream->ops->copy(substream, c, hwoff, buf, frames)) < 0)
2111                                 return err;
2112                 }
2113         } else {
2114                 snd_pcm_uframes_t dma_csize = runtime->dma_bytes / channels;
2115                 for (c = 0; c < channels; ++c, ++bufs) {
2116                         char *hwbuf;
2117                         char __user *buf;
2118                         if (*bufs == NULL)
2119                                 continue;
2120
2121                         hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, hwoff);
2122                         buf = *bufs + samples_to_bytes(runtime, off);
2123                         if (copy_to_user(buf, hwbuf, samples_to_bytes(runtime, frames)))
2124                                 return -EFAULT;
2125                 }
2126         }
2127         return 0;
2128 }
2129  
2130 snd_pcm_sframes_t snd_pcm_lib_readv(struct snd_pcm_substream *substream,
2131                                     void __user **bufs,
2132                                     snd_pcm_uframes_t frames)
2133 {
2134         struct snd_pcm_runtime *runtime;
2135         int nonblock;
2136         int err;
2137
2138         err = pcm_sanity_check(substream);
2139         if (err < 0)
2140                 return err;
2141         runtime = substream->runtime;
2142         if (runtime->status->state == SNDRV_PCM_STATE_OPEN)
2143                 return -EBADFD;
2144
2145         nonblock = !!(substream->f_flags & O_NONBLOCK);
2146         if (runtime->access != SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)
2147                 return -EINVAL;
2148         return snd_pcm_lib_read1(substream, (unsigned long)bufs, frames, nonblock, snd_pcm_lib_readv_transfer);
2149 }
2150
2151 EXPORT_SYMBOL(snd_pcm_lib_readv);