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