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