OSDN Git Service

Merge "diag: Prevent out-of-bound access while processing mask commands"
[sagit-ice-cold/kernel_xiaomi_msm8998.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 <linux/export.h>
27 #include <sound/core.h>
28 #include <sound/control.h>
29 #include <sound/tlv.h>
30 #include <sound/info.h>
31 #include <sound/pcm.h>
32 #include <sound/pcm_params.h>
33 #include <sound/timer.h>
34
35 #ifdef CONFIG_SND_PCM_XRUN_DEBUG
36 #define CREATE_TRACE_POINTS
37 #include "pcm_trace.h"
38 #else
39 #define trace_hwptr(substream, pos, in_interrupt)
40 #define trace_xrun(substream)
41 #define trace_hw_ptr_error(substream, reason)
42 #endif
43
44 #define STRING_LENGTH_OF_INT 12
45 #define MAX_USR_CTRL_CNT 128
46
47 /*
48  * fill ring buffer with silence
49  * runtime->silence_start: starting pointer to silence area
50  * runtime->silence_filled: size filled with silence
51  * runtime->silence_threshold: threshold from application
52  * runtime->silence_size: maximal size from application
53  *
54  * when runtime->silence_size >= runtime->boundary - fill processed area with silence immediately
55  */
56 void snd_pcm_playback_silence(struct snd_pcm_substream *substream, snd_pcm_uframes_t new_hw_ptr)
57 {
58         struct snd_pcm_runtime *runtime = substream->runtime;
59         snd_pcm_uframes_t frames, ofs, transfer;
60
61         if (runtime->silence_size < runtime->boundary) {
62                 snd_pcm_sframes_t noise_dist, n;
63                 if (runtime->silence_start != runtime->control->appl_ptr) {
64                         n = runtime->control->appl_ptr - runtime->silence_start;
65                         if (n < 0)
66                                 n += runtime->boundary;
67                         if ((snd_pcm_uframes_t)n < runtime->silence_filled)
68                                 runtime->silence_filled -= n;
69                         else
70                                 runtime->silence_filled = 0;
71                         runtime->silence_start = runtime->control->appl_ptr;
72                 }
73                 if (runtime->silence_filled >= runtime->buffer_size)
74                         return;
75                 noise_dist = snd_pcm_playback_hw_avail(runtime) + runtime->silence_filled;
76                 if (noise_dist >= (snd_pcm_sframes_t) runtime->silence_threshold)
77                         return;
78                 frames = runtime->silence_threshold - noise_dist;
79                 if (frames > runtime->silence_size)
80                         frames = runtime->silence_size;
81         } else {
82                 if (new_hw_ptr == ULONG_MAX) {  /* initialization */
83                         snd_pcm_sframes_t avail = snd_pcm_playback_hw_avail(runtime);
84                         if (avail > runtime->buffer_size)
85                                 avail = runtime->buffer_size;
86                         runtime->silence_filled = avail > 0 ? avail : 0;
87                         runtime->silence_start = (runtime->status->hw_ptr +
88                                                   runtime->silence_filled) %
89                                                  runtime->boundary;
90                 } else {
91                         ofs = runtime->status->hw_ptr;
92                         frames = new_hw_ptr - ofs;
93                         if ((snd_pcm_sframes_t)frames < 0)
94                                 frames += runtime->boundary;
95                         runtime->silence_filled -= frames;
96                         if ((snd_pcm_sframes_t)runtime->silence_filled < 0) {
97                                 runtime->silence_filled = 0;
98                                 runtime->silence_start = new_hw_ptr;
99                         } else {
100                                 runtime->silence_start = ofs;
101                         }
102                 }
103                 frames = runtime->buffer_size - runtime->silence_filled;
104         }
105         if (snd_BUG_ON(frames > runtime->buffer_size))
106                 return;
107         if (frames == 0)
108                 return;
109         ofs = runtime->silence_start % runtime->buffer_size;
110         while (frames > 0) {
111                 transfer = ofs + frames > runtime->buffer_size ? runtime->buffer_size - ofs : frames;
112                 if (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED ||
113                     runtime->access == SNDRV_PCM_ACCESS_MMAP_INTERLEAVED) {
114                         if (substream->ops->silence) {
115                                 int err;
116                                 err = substream->ops->silence(substream, -1, ofs, transfer);
117                                 snd_BUG_ON(err < 0);
118                         } else {
119                                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, ofs);
120                                 snd_pcm_format_set_silence(runtime->format, hwbuf, transfer * runtime->channels);
121                         }
122                 } else {
123                         unsigned int c;
124                         unsigned int channels = runtime->channels;
125                         if (substream->ops->silence) {
126                                 for (c = 0; c < channels; ++c) {
127                                         int err;
128                                         err = substream->ops->silence(substream, c, ofs, transfer);
129                                         snd_BUG_ON(err < 0);
130                                 }
131                         } else {
132                                 size_t dma_csize = runtime->dma_bytes / channels;
133                                 for (c = 0; c < channels; ++c) {
134                                         char *hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, ofs);
135                                         snd_pcm_format_set_silence(runtime->format, hwbuf, transfer);
136                                 }
137                         }
138                 }
139                 runtime->silence_filled += transfer;
140                 frames -= transfer;
141                 ofs = 0;
142         }
143 }
144
145 #ifdef CONFIG_SND_DEBUG
146 void snd_pcm_debug_name(struct snd_pcm_substream *substream,
147                            char *name, size_t len)
148 {
149         snprintf(name, len, "pcmC%dD%d%c:%d",
150                  substream->pcm->card->number,
151                  substream->pcm->device,
152                  substream->stream ? 'c' : 'p',
153                  substream->number);
154 }
155 EXPORT_SYMBOL(snd_pcm_debug_name);
156 #endif
157
158 #define XRUN_DEBUG_BASIC        (1<<0)
159 #define XRUN_DEBUG_STACK        (1<<1)  /* dump also stack */
160 #define XRUN_DEBUG_JIFFIESCHECK (1<<2)  /* do jiffies check */
161
162 #ifdef CONFIG_SND_PCM_XRUN_DEBUG
163
164 #define xrun_debug(substream, mask) \
165                         ((substream)->pstr->xrun_debug & (mask))
166 #else
167 #define xrun_debug(substream, mask)     0
168 #endif
169
170 #define dump_stack_on_xrun(substream) do {                      \
171                 if (xrun_debug(substream, XRUN_DEBUG_STACK))    \
172                         dump_stack();                           \
173         } while (0)
174
175 static void xrun(struct snd_pcm_substream *substream)
176 {
177         struct snd_pcm_runtime *runtime = substream->runtime;
178
179         trace_xrun(substream);
180         if (runtime->tstamp_mode == SNDRV_PCM_TSTAMP_ENABLE)
181                 snd_pcm_gettime(runtime, (struct timespec *)&runtime->status->tstamp);
182         snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
183         if (xrun_debug(substream, XRUN_DEBUG_BASIC)) {
184                 char name[16];
185                 snd_pcm_debug_name(substream, name, sizeof(name));
186                 pcm_warn(substream->pcm, "XRUN: %s\n", name);
187                 dump_stack_on_xrun(substream);
188         }
189 }
190
191 #ifdef CONFIG_SND_PCM_XRUN_DEBUG
192 #define hw_ptr_error(substream, in_interrupt, reason, fmt, args...)     \
193         do {                                                            \
194                 trace_hw_ptr_error(substream, reason);  \
195                 if (xrun_debug(substream, XRUN_DEBUG_BASIC)) {          \
196                         pr_err_ratelimited("ALSA: PCM: [%c] " reason ": " fmt, \
197                                            (in_interrupt) ? 'Q' : 'P', ##args); \
198                         dump_stack_on_xrun(substream);                  \
199                 }                                                       \
200         } while (0)
201
202 #else /* ! CONFIG_SND_PCM_XRUN_DEBUG */
203
204 #define hw_ptr_error(substream, fmt, args...) do { } while (0)
205
206 #endif
207
208 int snd_pcm_update_state(struct snd_pcm_substream *substream,
209                          struct snd_pcm_runtime *runtime)
210 {
211         snd_pcm_uframes_t avail;
212
213         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
214                 avail = snd_pcm_playback_avail(runtime);
215         else
216                 avail = snd_pcm_capture_avail(runtime);
217         if (avail > runtime->avail_max)
218                 runtime->avail_max = avail;
219         if (runtime->status->state == SNDRV_PCM_STATE_DRAINING) {
220                 if (avail >= runtime->buffer_size) {
221                         snd_pcm_drain_done(substream);
222                         return -EPIPE;
223                 }
224         } else {
225                 if (avail >= runtime->stop_threshold) {
226                         xrun(substream);
227                         return -EPIPE;
228                 }
229         }
230         if (runtime->twake) {
231                 if (avail >= runtime->twake)
232                         wake_up(&runtime->tsleep);
233         } else if (avail >= runtime->control->avail_min)
234                 wake_up(&runtime->sleep);
235         return 0;
236 }
237
238 static void update_audio_tstamp(struct snd_pcm_substream *substream,
239                                 struct timespec *curr_tstamp,
240                                 struct timespec *audio_tstamp)
241 {
242         struct snd_pcm_runtime *runtime = substream->runtime;
243         u64 audio_frames, audio_nsecs;
244         struct timespec driver_tstamp;
245
246         if (runtime->tstamp_mode != SNDRV_PCM_TSTAMP_ENABLE)
247                 return;
248
249         if (!(substream->ops->get_time_info) ||
250                 (runtime->audio_tstamp_report.actual_type ==
251                         SNDRV_PCM_AUDIO_TSTAMP_TYPE_DEFAULT)) {
252
253                 /*
254                  * provide audio timestamp derived from pointer position
255                  * add delay only if requested
256                  */
257
258                 audio_frames = runtime->hw_ptr_wrap + runtime->status->hw_ptr;
259
260                 if (runtime->audio_tstamp_config.report_delay) {
261                         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
262                                 audio_frames -=  runtime->delay;
263                         else
264                                 audio_frames +=  runtime->delay;
265                 }
266                 audio_nsecs = div_u64(audio_frames * 1000000000LL,
267                                 runtime->rate);
268                 *audio_tstamp = ns_to_timespec(audio_nsecs);
269         }
270         if (!timespec_equal(&runtime->status->audio_tstamp, audio_tstamp)) {
271                 runtime->status->audio_tstamp = *audio_tstamp;
272                 runtime->status->tstamp = *curr_tstamp;
273         }
274
275         /*
276          * re-take a driver timestamp to let apps detect if the reference tstamp
277          * read by low-level hardware was provided with a delay
278          */
279         snd_pcm_gettime(substream->runtime, (struct timespec *)&driver_tstamp);
280         runtime->driver_tstamp = driver_tstamp;
281 }
282
283 static int snd_pcm_update_hw_ptr0(struct snd_pcm_substream *substream,
284                                   unsigned int in_interrupt)
285 {
286         struct snd_pcm_runtime *runtime = substream->runtime;
287         snd_pcm_uframes_t pos;
288         snd_pcm_uframes_t old_hw_ptr, new_hw_ptr, hw_base;
289         snd_pcm_sframes_t hdelta, delta;
290         unsigned long jdelta;
291         unsigned long curr_jiffies;
292         struct timespec curr_tstamp;
293         struct timespec audio_tstamp;
294         int crossed_boundary = 0;
295
296         old_hw_ptr = runtime->status->hw_ptr;
297
298         /*
299          * group pointer, time and jiffies reads to allow for more
300          * accurate correlations/corrections.
301          * The values are stored at the end of this routine after
302          * corrections for hw_ptr position
303          */
304         pos = substream->ops->pointer(substream);
305         curr_jiffies = jiffies;
306         if (runtime->tstamp_mode == SNDRV_PCM_TSTAMP_ENABLE) {
307                 if ((substream->ops->get_time_info) &&
308                         (runtime->audio_tstamp_config.type_requested != SNDRV_PCM_AUDIO_TSTAMP_TYPE_DEFAULT)) {
309                         substream->ops->get_time_info(substream, &curr_tstamp,
310                                                 &audio_tstamp,
311                                                 &runtime->audio_tstamp_config,
312                                                 &runtime->audio_tstamp_report);
313
314                         /* re-test in case tstamp type is not supported in hardware and was demoted to DEFAULT */
315                         if (runtime->audio_tstamp_report.actual_type == SNDRV_PCM_AUDIO_TSTAMP_TYPE_DEFAULT)
316                                 snd_pcm_gettime(runtime, (struct timespec *)&curr_tstamp);
317                 } else
318                         snd_pcm_gettime(runtime, (struct timespec *)&curr_tstamp);
319         }
320
321         if (pos == SNDRV_PCM_POS_XRUN) {
322                 xrun(substream);
323                 return -EPIPE;
324         }
325         if (pos >= runtime->buffer_size) {
326                 if (printk_ratelimit()) {
327                         char name[16];
328                         snd_pcm_debug_name(substream, name, sizeof(name));
329                         pcm_err(substream->pcm,
330                                 "invalid position: %s, pos = %ld, buffer size = %ld, period size = %ld\n",
331                                 name, pos, runtime->buffer_size,
332                                 runtime->period_size);
333                 }
334                 pos = 0;
335         }
336         pos -= pos % runtime->min_align;
337         trace_hwptr(substream, pos, in_interrupt);
338         hw_base = runtime->hw_ptr_base;
339         new_hw_ptr = hw_base + pos;
340         if (in_interrupt) {
341                 /* we know that one period was processed */
342                 /* delta = "expected next hw_ptr" for in_interrupt != 0 */
343                 delta = runtime->hw_ptr_interrupt + runtime->period_size;
344                 if (delta > new_hw_ptr) {
345                         /* check for double acknowledged interrupts */
346                         hdelta = curr_jiffies - runtime->hw_ptr_jiffies;
347                         if (hdelta > runtime->hw_ptr_buffer_jiffies/2 + 1) {
348                                 hw_base += runtime->buffer_size;
349                                 if (hw_base >= runtime->boundary) {
350                                         hw_base = 0;
351                                         crossed_boundary++;
352                                 }
353                                 new_hw_ptr = hw_base + pos;
354                                 goto __delta;
355                         }
356                 }
357         }
358         /* new_hw_ptr might be lower than old_hw_ptr in case when */
359         /* pointer crosses the end of the ring buffer */
360         if (new_hw_ptr < old_hw_ptr) {
361                 hw_base += runtime->buffer_size;
362                 if (hw_base >= runtime->boundary) {
363                         hw_base = 0;
364                         crossed_boundary++;
365                 }
366                 new_hw_ptr = hw_base + pos;
367         }
368       __delta:
369         delta = new_hw_ptr - old_hw_ptr;
370         if (delta < 0)
371                 delta += runtime->boundary;
372
373         if (runtime->no_period_wakeup) {
374                 snd_pcm_sframes_t xrun_threshold;
375                 /*
376                  * Without regular period interrupts, we have to check
377                  * the elapsed time to detect xruns.
378                  */
379                 jdelta = curr_jiffies - runtime->hw_ptr_jiffies;
380                 if ((jdelta < runtime->hw_ptr_buffer_jiffies / 2) ||
381                     (runtime->hw_ptr_buffer_jiffies <= 0))
382                         goto no_delta_check;
383                 hdelta = jdelta - delta * HZ / runtime->rate;
384                 xrun_threshold = runtime->hw_ptr_buffer_jiffies / 2 + 1;
385                 while (hdelta > xrun_threshold) {
386                         delta += runtime->buffer_size;
387                         hw_base += runtime->buffer_size;
388                         if (hw_base >= runtime->boundary) {
389                                 hw_base = 0;
390                                 crossed_boundary++;
391                         }
392                         new_hw_ptr = hw_base + pos;
393                         hdelta -= runtime->hw_ptr_buffer_jiffies;
394                 }
395                 goto no_delta_check;
396         }
397
398         /* something must be really wrong */
399         if (delta >= runtime->buffer_size + runtime->period_size) {
400                 hw_ptr_error(substream, in_interrupt, "Unexpected hw_ptr",
401                              "(stream=%i, pos=%ld, new_hw_ptr=%ld, old_hw_ptr=%ld)\n",
402                              substream->stream, (long)pos,
403                              (long)new_hw_ptr, (long)old_hw_ptr);
404                 return 0;
405         }
406
407         /* Do jiffies check only in xrun_debug mode */
408         if (!xrun_debug(substream, XRUN_DEBUG_JIFFIESCHECK))
409                 goto no_jiffies_check;
410
411         /* Skip the jiffies check for hardwares with BATCH flag.
412          * Such hardware usually just increases the position at each IRQ,
413          * thus it can't give any strange position.
414          */
415         if (runtime->hw.info & SNDRV_PCM_INFO_BATCH)
416                 goto no_jiffies_check;
417         hdelta = delta;
418         if (hdelta < runtime->delay)
419                 goto no_jiffies_check;
420         hdelta -= runtime->delay;
421         jdelta = curr_jiffies - runtime->hw_ptr_jiffies;
422         if (((hdelta * HZ) / runtime->rate) > jdelta + HZ/100) {
423                 delta = jdelta /
424                         (((runtime->period_size * HZ) / runtime->rate)
425                                                                 + HZ/100);
426                 /* move new_hw_ptr according jiffies not pos variable */
427                 new_hw_ptr = old_hw_ptr;
428                 hw_base = delta;
429                 /* use loop to avoid checks for delta overflows */
430                 /* the delta value is small or zero in most cases */
431                 while (delta > 0) {
432                         new_hw_ptr += runtime->period_size;
433                         if (new_hw_ptr >= runtime->boundary) {
434                                 new_hw_ptr -= runtime->boundary;
435                                 crossed_boundary--;
436                         }
437                         delta--;
438                 }
439                 /* align hw_base to buffer_size */
440                 hw_ptr_error(substream, in_interrupt, "hw_ptr skipping",
441                              "(pos=%ld, delta=%ld, period=%ld, jdelta=%lu/%lu/%lu, hw_ptr=%ld/%ld)\n",
442                              (long)pos, (long)hdelta,
443                              (long)runtime->period_size, jdelta,
444                              ((hdelta * HZ) / runtime->rate), hw_base,
445                              (unsigned long)old_hw_ptr,
446                              (unsigned long)new_hw_ptr);
447                 /* reset values to proper state */
448                 delta = 0;
449                 hw_base = new_hw_ptr - (new_hw_ptr % runtime->buffer_size);
450         }
451  no_jiffies_check:
452         if (delta > runtime->period_size + runtime->period_size / 2) {
453                 hw_ptr_error(substream, in_interrupt,
454                              "Lost interrupts?",
455                              "(stream=%i, delta=%ld, new_hw_ptr=%ld, old_hw_ptr=%ld)\n",
456                              substream->stream, (long)delta,
457                              (long)new_hw_ptr,
458                              (long)old_hw_ptr);
459         }
460
461  no_delta_check:
462         if (runtime->status->hw_ptr == new_hw_ptr) {
463                 update_audio_tstamp(substream, &curr_tstamp, &audio_tstamp);
464                 return 0;
465         }
466
467         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK &&
468             runtime->silence_size > 0)
469                 snd_pcm_playback_silence(substream, new_hw_ptr);
470
471         if (in_interrupt) {
472                 delta = new_hw_ptr - runtime->hw_ptr_interrupt;
473                 if (delta < 0)
474                         delta += runtime->boundary;
475                 delta -= (snd_pcm_uframes_t)delta % runtime->period_size;
476                 runtime->hw_ptr_interrupt += delta;
477                 if (runtime->hw_ptr_interrupt >= runtime->boundary)
478                         runtime->hw_ptr_interrupt -= runtime->boundary;
479         }
480         runtime->hw_ptr_base = hw_base;
481         runtime->status->hw_ptr = new_hw_ptr;
482         runtime->hw_ptr_jiffies = curr_jiffies;
483         if (crossed_boundary) {
484                 snd_BUG_ON(crossed_boundary != 1);
485                 runtime->hw_ptr_wrap += runtime->boundary;
486         }
487
488         update_audio_tstamp(substream, &curr_tstamp, &audio_tstamp);
489
490         return snd_pcm_update_state(substream, runtime);
491 }
492
493 /* CAUTION: call it with irq disabled */
494 int snd_pcm_update_hw_ptr(struct snd_pcm_substream *substream)
495 {
496         return snd_pcm_update_hw_ptr0(substream, 0);
497 }
498
499 /**
500  * snd_pcm_set_ops - set the PCM operators
501  * @pcm: the pcm instance
502  * @direction: stream direction, SNDRV_PCM_STREAM_XXX
503  * @ops: the operator table
504  *
505  * Sets the given PCM operators to the pcm instance.
506  */
507 void snd_pcm_set_ops(struct snd_pcm *pcm, int direction,
508                      const struct snd_pcm_ops *ops)
509 {
510         struct snd_pcm_str *stream = &pcm->streams[direction];
511         struct snd_pcm_substream *substream;
512         
513         for (substream = stream->substream; substream != NULL; substream = substream->next)
514                 substream->ops = ops;
515 }
516
517 EXPORT_SYMBOL(snd_pcm_set_ops);
518
519 /**
520  * snd_pcm_sync - set the PCM sync id
521  * @substream: the pcm substream
522  *
523  * Sets the PCM sync identifier for the card.
524  */
525 void snd_pcm_set_sync(struct snd_pcm_substream *substream)
526 {
527         struct snd_pcm_runtime *runtime = substream->runtime;
528         
529         runtime->sync.id32[0] = substream->pcm->card->number;
530         runtime->sync.id32[1] = -1;
531         runtime->sync.id32[2] = -1;
532         runtime->sync.id32[3] = -1;
533 }
534
535 EXPORT_SYMBOL(snd_pcm_set_sync);
536
537 /*
538  *  Standard ioctl routine
539  */
540
541 static inline unsigned int div32(unsigned int a, unsigned int b, 
542                                  unsigned int *r)
543 {
544         if (b == 0) {
545                 *r = 0;
546                 return UINT_MAX;
547         }
548         *r = a % b;
549         return a / b;
550 }
551
552 static inline unsigned int div_down(unsigned int a, unsigned int b)
553 {
554         if (b == 0)
555                 return UINT_MAX;
556         return a / b;
557 }
558
559 static inline unsigned int div_up(unsigned int a, unsigned int b)
560 {
561         unsigned int r;
562         unsigned int q;
563         if (b == 0)
564                 return UINT_MAX;
565         q = div32(a, b, &r);
566         if (r)
567                 ++q;
568         return q;
569 }
570
571 static inline unsigned int mul(unsigned int a, unsigned int b)
572 {
573         if (a == 0)
574                 return 0;
575         if (div_down(UINT_MAX, a) < b)
576                 return UINT_MAX;
577         return a * b;
578 }
579
580 static inline unsigned int muldiv32(unsigned int a, unsigned int b,
581                                     unsigned int c, unsigned int *r)
582 {
583         u_int64_t n = (u_int64_t) a * b;
584         if (c == 0) {
585                 *r = 0;
586                 return UINT_MAX;
587         }
588         n = div_u64_rem(n, c, r);
589         if (n >= UINT_MAX) {
590                 *r = 0;
591                 return UINT_MAX;
592         }
593         return n;
594 }
595
596 /**
597  * snd_interval_refine - refine the interval value of configurator
598  * @i: the interval value to refine
599  * @v: the interval value to refer to
600  *
601  * Refines the interval value with the reference value.
602  * The interval is changed to the range satisfying both intervals.
603  * The interval status (min, max, integer, etc.) are evaluated.
604  *
605  * Return: Positive if the value is changed, zero if it's not changed, or a
606  * negative error code.
607  */
608 int snd_interval_refine(struct snd_interval *i, const struct snd_interval *v)
609 {
610         int changed = 0;
611         if (snd_BUG_ON(snd_interval_empty(i)))
612                 return -EINVAL;
613         if (i->min < v->min) {
614                 i->min = v->min;
615                 i->openmin = v->openmin;
616                 changed = 1;
617         } else if (i->min == v->min && !i->openmin && v->openmin) {
618                 i->openmin = 1;
619                 changed = 1;
620         }
621         if (i->max > v->max) {
622                 i->max = v->max;
623                 i->openmax = v->openmax;
624                 changed = 1;
625         } else if (i->max == v->max && !i->openmax && v->openmax) {
626                 i->openmax = 1;
627                 changed = 1;
628         }
629         if (!i->integer && v->integer) {
630                 i->integer = 1;
631                 changed = 1;
632         }
633         if (i->integer) {
634                 if (i->openmin) {
635                         i->min++;
636                         i->openmin = 0;
637                 }
638                 if (i->openmax) {
639                         i->max--;
640                         i->openmax = 0;
641                 }
642         } else if (!i->openmin && !i->openmax && i->min == i->max)
643                 i->integer = 1;
644         if (snd_interval_checkempty(i)) {
645                 snd_interval_none(i);
646                 return -EINVAL;
647         }
648         return changed;
649 }
650
651 EXPORT_SYMBOL(snd_interval_refine);
652
653 static int snd_interval_refine_first(struct snd_interval *i)
654 {
655         const unsigned int last_max = i->max;
656
657         if (snd_BUG_ON(snd_interval_empty(i)))
658                 return -EINVAL;
659         if (snd_interval_single(i))
660                 return 0;
661         i->max = i->min;
662         if (i->openmin)
663                 i->max++;
664         /* only exclude max value if also excluded before refine */
665         i->openmax = (i->openmax && i->max >= last_max);
666         return 1;
667 }
668
669 static int snd_interval_refine_last(struct snd_interval *i)
670 {
671         const unsigned int last_min = i->min;
672
673         if (snd_BUG_ON(snd_interval_empty(i)))
674                 return -EINVAL;
675         if (snd_interval_single(i))
676                 return 0;
677         i->min = i->max;
678         if (i->openmax)
679                 i->min--;
680         /* only exclude min value if also excluded before refine */
681         i->openmin = (i->openmin && i->min <= last_min);
682         return 1;
683 }
684
685 void snd_interval_mul(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c)
686 {
687         if (a->empty || b->empty) {
688                 snd_interval_none(c);
689                 return;
690         }
691         c->empty = 0;
692         c->min = mul(a->min, b->min);
693         c->openmin = (a->openmin || b->openmin);
694         c->max = mul(a->max,  b->max);
695         c->openmax = (a->openmax || b->openmax);
696         c->integer = (a->integer && b->integer);
697 }
698
699 /**
700  * snd_interval_div - refine the interval value with division
701  * @a: dividend
702  * @b: divisor
703  * @c: quotient
704  *
705  * c = a / b
706  *
707  * Returns non-zero if the value is changed, zero if not changed.
708  */
709 void snd_interval_div(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c)
710 {
711         unsigned int r;
712         if (a->empty || b->empty) {
713                 snd_interval_none(c);
714                 return;
715         }
716         c->empty = 0;
717         c->min = div32(a->min, b->max, &r);
718         c->openmin = (r || a->openmin || b->openmax);
719         if (b->min > 0) {
720                 c->max = div32(a->max, b->min, &r);
721                 if (r) {
722                         c->max++;
723                         c->openmax = 1;
724                 } else
725                         c->openmax = (a->openmax || b->openmin);
726         } else {
727                 c->max = UINT_MAX;
728                 c->openmax = 0;
729         }
730         c->integer = 0;
731 }
732
733 /**
734  * snd_interval_muldivk - refine the interval value
735  * @a: dividend 1
736  * @b: dividend 2
737  * @k: divisor (as integer)
738  * @c: result
739   *
740  * c = a * b / k
741  *
742  * Returns non-zero if the value is changed, zero if not changed.
743  */
744 void snd_interval_muldivk(const struct snd_interval *a, const struct snd_interval *b,
745                       unsigned int k, struct snd_interval *c)
746 {
747         unsigned int r;
748         if (a->empty || b->empty) {
749                 snd_interval_none(c);
750                 return;
751         }
752         c->empty = 0;
753         c->min = muldiv32(a->min, b->min, k, &r);
754         c->openmin = (r || a->openmin || b->openmin);
755         c->max = muldiv32(a->max, b->max, k, &r);
756         if (r) {
757                 c->max++;
758                 c->openmax = 1;
759         } else
760                 c->openmax = (a->openmax || b->openmax);
761         c->integer = 0;
762 }
763
764 /**
765  * snd_interval_mulkdiv - refine the interval value
766  * @a: dividend 1
767  * @k: dividend 2 (as integer)
768  * @b: divisor
769  * @c: result
770  *
771  * c = a * k / b
772  *
773  * Returns non-zero if the value is changed, zero if not changed.
774  */
775 void snd_interval_mulkdiv(const struct snd_interval *a, unsigned int k,
776                       const struct snd_interval *b, struct snd_interval *c)
777 {
778         unsigned int r;
779         if (a->empty || b->empty) {
780                 snd_interval_none(c);
781                 return;
782         }
783         c->empty = 0;
784         c->min = muldiv32(a->min, k, b->max, &r);
785         c->openmin = (r || a->openmin || b->openmax);
786         if (b->min > 0) {
787                 c->max = muldiv32(a->max, k, b->min, &r);
788                 if (r) {
789                         c->max++;
790                         c->openmax = 1;
791                 } else
792                         c->openmax = (a->openmax || b->openmin);
793         } else {
794                 c->max = UINT_MAX;
795                 c->openmax = 0;
796         }
797         c->integer = 0;
798 }
799
800 /* ---- */
801
802
803 /**
804  * snd_interval_ratnum - refine the interval value
805  * @i: interval to refine
806  * @rats_count: number of ratnum_t 
807  * @rats: ratnum_t array
808  * @nump: pointer to store the resultant numerator
809  * @denp: pointer to store the resultant denominator
810  *
811  * Return: Positive if the value is changed, zero if it's not changed, or a
812  * negative error code.
813  */
814 int snd_interval_ratnum(struct snd_interval *i,
815                         unsigned int rats_count, const struct snd_ratnum *rats,
816                         unsigned int *nump, unsigned int *denp)
817 {
818         unsigned int best_num, best_den;
819         int best_diff;
820         unsigned int k;
821         struct snd_interval t;
822         int err;
823         unsigned int result_num, result_den;
824         int result_diff;
825
826         best_num = best_den = best_diff = 0;
827         for (k = 0; k < rats_count; ++k) {
828                 unsigned int num = rats[k].num;
829                 unsigned int den;
830                 unsigned int q = i->min;
831                 int diff;
832                 if (q == 0)
833                         q = 1;
834                 den = div_up(num, q);
835                 if (den < rats[k].den_min)
836                         continue;
837                 if (den > rats[k].den_max)
838                         den = rats[k].den_max;
839                 else {
840                         unsigned int r;
841                         r = (den - rats[k].den_min) % rats[k].den_step;
842                         if (r != 0)
843                                 den -= r;
844                 }
845                 diff = num - q * den;
846                 if (diff < 0)
847                         diff = -diff;
848                 if (best_num == 0 ||
849                     diff * best_den < best_diff * den) {
850                         best_diff = diff;
851                         best_den = den;
852                         best_num = num;
853                 }
854         }
855         if (best_den == 0) {
856                 i->empty = 1;
857                 return -EINVAL;
858         }
859         t.min = div_down(best_num, best_den);
860         t.openmin = !!(best_num % best_den);
861         
862         result_num = best_num;
863         result_diff = best_diff;
864         result_den = best_den;
865         best_num = best_den = best_diff = 0;
866         for (k = 0; k < rats_count; ++k) {
867                 unsigned int num = rats[k].num;
868                 unsigned int den;
869                 unsigned int q = i->max;
870                 int diff;
871                 if (q == 0) {
872                         i->empty = 1;
873                         return -EINVAL;
874                 }
875                 den = div_down(num, q);
876                 if (den > rats[k].den_max)
877                         continue;
878                 if (den < rats[k].den_min)
879                         den = rats[k].den_min;
880                 else {
881                         unsigned int r;
882                         r = (den - rats[k].den_min) % rats[k].den_step;
883                         if (r != 0)
884                                 den += rats[k].den_step - r;
885                 }
886                 diff = q * den - num;
887                 if (diff < 0)
888                         diff = -diff;
889                 if (best_num == 0 ||
890                     diff * best_den < best_diff * den) {
891                         best_diff = diff;
892                         best_den = den;
893                         best_num = num;
894                 }
895         }
896         if (best_den == 0) {
897                 i->empty = 1;
898                 return -EINVAL;
899         }
900         t.max = div_up(best_num, best_den);
901         t.openmax = !!(best_num % best_den);
902         t.integer = 0;
903         err = snd_interval_refine(i, &t);
904         if (err < 0)
905                 return err;
906
907         if (snd_interval_single(i)) {
908                 if (best_diff * result_den < result_diff * best_den) {
909                         result_num = best_num;
910                         result_den = best_den;
911                 }
912                 if (nump)
913                         *nump = result_num;
914                 if (denp)
915                         *denp = result_den;
916         }
917         return err;
918 }
919
920 EXPORT_SYMBOL(snd_interval_ratnum);
921
922 /**
923  * snd_interval_ratden - refine the interval value
924  * @i: interval to refine
925  * @rats_count: number of struct ratden
926  * @rats: struct ratden array
927  * @nump: pointer to store the resultant numerator
928  * @denp: pointer to store the resultant denominator
929  *
930  * Return: Positive if the value is changed, zero if it's not changed, or a
931  * negative error code.
932  */
933 static int snd_interval_ratden(struct snd_interval *i,
934                                unsigned int rats_count,
935                                const struct snd_ratden *rats,
936                                unsigned int *nump, unsigned int *denp)
937 {
938         unsigned int best_num, best_diff, best_den;
939         unsigned int k;
940         struct snd_interval t;
941         int err;
942
943         best_num = best_den = best_diff = 0;
944         for (k = 0; k < rats_count; ++k) {
945                 unsigned int num;
946                 unsigned int den = rats[k].den;
947                 unsigned int q = i->min;
948                 int diff;
949                 num = mul(q, den);
950                 if (num > rats[k].num_max)
951                         continue;
952                 if (num < rats[k].num_min)
953                         num = rats[k].num_max;
954                 else {
955                         unsigned int r;
956                         r = (num - rats[k].num_min) % rats[k].num_step;
957                         if (r != 0)
958                                 num += rats[k].num_step - r;
959                 }
960                 diff = num - q * den;
961                 if (best_num == 0 ||
962                     diff * best_den < best_diff * den) {
963                         best_diff = diff;
964                         best_den = den;
965                         best_num = num;
966                 }
967         }
968         if (best_den == 0) {
969                 i->empty = 1;
970                 return -EINVAL;
971         }
972         t.min = div_down(best_num, best_den);
973         t.openmin = !!(best_num % best_den);
974         
975         best_num = best_den = best_diff = 0;
976         for (k = 0; k < rats_count; ++k) {
977                 unsigned int num;
978                 unsigned int den = rats[k].den;
979                 unsigned int q = i->max;
980                 int diff;
981                 num = mul(q, den);
982                 if (num < rats[k].num_min)
983                         continue;
984                 if (num > rats[k].num_max)
985                         num = rats[k].num_max;
986                 else {
987                         unsigned int r;
988                         r = (num - rats[k].num_min) % rats[k].num_step;
989                         if (r != 0)
990                                 num -= r;
991                 }
992                 diff = q * den - num;
993                 if (best_num == 0 ||
994                     diff * best_den < best_diff * den) {
995                         best_diff = diff;
996                         best_den = den;
997                         best_num = num;
998                 }
999         }
1000         if (best_den == 0) {
1001                 i->empty = 1;
1002                 return -EINVAL;
1003         }
1004         t.max = div_up(best_num, best_den);
1005         t.openmax = !!(best_num % best_den);
1006         t.integer = 0;
1007         err = snd_interval_refine(i, &t);
1008         if (err < 0)
1009                 return err;
1010
1011         if (snd_interval_single(i)) {
1012                 if (nump)
1013                         *nump = best_num;
1014                 if (denp)
1015                         *denp = best_den;
1016         }
1017         return err;
1018 }
1019
1020 /**
1021  * snd_interval_list - refine the interval value from the list
1022  * @i: the interval value to refine
1023  * @count: the number of elements in the list
1024  * @list: the value list
1025  * @mask: the bit-mask to evaluate
1026  *
1027  * Refines the interval value from the list.
1028  * When mask is non-zero, only the elements corresponding to bit 1 are
1029  * evaluated.
1030  *
1031  * Return: Positive if the value is changed, zero if it's not changed, or a
1032  * negative error code.
1033  */
1034 int snd_interval_list(struct snd_interval *i, unsigned int count,
1035                       const unsigned int *list, unsigned int mask)
1036 {
1037         unsigned int k;
1038         struct snd_interval list_range;
1039
1040         if (!count) {
1041                 i->empty = 1;
1042                 return -EINVAL;
1043         }
1044         snd_interval_any(&list_range);
1045         list_range.min = UINT_MAX;
1046         list_range.max = 0;
1047         for (k = 0; k < count; k++) {
1048                 if (mask && !(mask & (1 << k)))
1049                         continue;
1050                 if (!snd_interval_test(i, list[k]))
1051                         continue;
1052                 list_range.min = min(list_range.min, list[k]);
1053                 list_range.max = max(list_range.max, list[k]);
1054         }
1055         return snd_interval_refine(i, &list_range);
1056 }
1057
1058 EXPORT_SYMBOL(snd_interval_list);
1059
1060 /**
1061  * snd_interval_ranges - refine the interval value from the list of ranges
1062  * @i: the interval value to refine
1063  * @count: the number of elements in the list of ranges
1064  * @ranges: the ranges list
1065  * @mask: the bit-mask to evaluate
1066  *
1067  * Refines the interval value from the list of ranges.
1068  * When mask is non-zero, only the elements corresponding to bit 1 are
1069  * evaluated.
1070  *
1071  * Return: Positive if the value is changed, zero if it's not changed, or a
1072  * negative error code.
1073  */
1074 int snd_interval_ranges(struct snd_interval *i, unsigned int count,
1075                         const struct snd_interval *ranges, unsigned int mask)
1076 {
1077         unsigned int k;
1078         struct snd_interval range_union;
1079         struct snd_interval range;
1080
1081         if (!count) {
1082                 snd_interval_none(i);
1083                 return -EINVAL;
1084         }
1085         snd_interval_any(&range_union);
1086         range_union.min = UINT_MAX;
1087         range_union.max = 0;
1088         for (k = 0; k < count; k++) {
1089                 if (mask && !(mask & (1 << k)))
1090                         continue;
1091                 snd_interval_copy(&range, &ranges[k]);
1092                 if (snd_interval_refine(&range, i) < 0)
1093                         continue;
1094                 if (snd_interval_empty(&range))
1095                         continue;
1096
1097                 if (range.min < range_union.min) {
1098                         range_union.min = range.min;
1099                         range_union.openmin = 1;
1100                 }
1101                 if (range.min == range_union.min && !range.openmin)
1102                         range_union.openmin = 0;
1103                 if (range.max > range_union.max) {
1104                         range_union.max = range.max;
1105                         range_union.openmax = 1;
1106                 }
1107                 if (range.max == range_union.max && !range.openmax)
1108                         range_union.openmax = 0;
1109         }
1110         return snd_interval_refine(i, &range_union);
1111 }
1112 EXPORT_SYMBOL(snd_interval_ranges);
1113
1114 static int snd_interval_step(struct snd_interval *i, unsigned int step)
1115 {
1116         unsigned int n;
1117         int changed = 0;
1118         n = i->min % step;
1119         if (n != 0 || i->openmin) {
1120                 i->min += step - n;
1121                 i->openmin = 0;
1122                 changed = 1;
1123         }
1124         n = i->max % step;
1125         if (n != 0 || i->openmax) {
1126                 i->max -= n;
1127                 i->openmax = 0;
1128                 changed = 1;
1129         }
1130         if (snd_interval_checkempty(i)) {
1131                 i->empty = 1;
1132                 return -EINVAL;
1133         }
1134         return changed;
1135 }
1136
1137 /* Info constraints helpers */
1138
1139 /**
1140  * snd_pcm_hw_rule_add - add the hw-constraint rule
1141  * @runtime: the pcm runtime instance
1142  * @cond: condition bits
1143  * @var: the variable to evaluate
1144  * @func: the evaluation function
1145  * @private: the private data pointer passed to function
1146  * @dep: the dependent variables
1147  *
1148  * Return: Zero if successful, or a negative error code on failure.
1149  */
1150 int snd_pcm_hw_rule_add(struct snd_pcm_runtime *runtime, unsigned int cond,
1151                         int var,
1152                         snd_pcm_hw_rule_func_t func, void *private,
1153                         int dep, ...)
1154 {
1155         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1156         struct snd_pcm_hw_rule *c;
1157         unsigned int k;
1158         va_list args;
1159         va_start(args, dep);
1160         if (constrs->rules_num >= constrs->rules_all) {
1161                 struct snd_pcm_hw_rule *new;
1162                 unsigned int new_rules = constrs->rules_all + 16;
1163                 new = kcalloc(new_rules, sizeof(*c), GFP_KERNEL);
1164                 if (!new) {
1165                         va_end(args);
1166                         return -ENOMEM;
1167                 }
1168                 if (constrs->rules) {
1169                         memcpy(new, constrs->rules,
1170                                constrs->rules_num * sizeof(*c));
1171                         kfree(constrs->rules);
1172                 }
1173                 constrs->rules = new;
1174                 constrs->rules_all = new_rules;
1175         }
1176         c = &constrs->rules[constrs->rules_num];
1177         c->cond = cond;
1178         c->func = func;
1179         c->var = var;
1180         c->private = private;
1181         k = 0;
1182         while (1) {
1183                 if (snd_BUG_ON(k >= ARRAY_SIZE(c->deps))) {
1184                         va_end(args);
1185                         return -EINVAL;
1186                 }
1187                 c->deps[k++] = dep;
1188                 if (dep < 0)
1189                         break;
1190                 dep = va_arg(args, int);
1191         }
1192         constrs->rules_num++;
1193         va_end(args);
1194         return 0;
1195 }
1196
1197 EXPORT_SYMBOL(snd_pcm_hw_rule_add);
1198
1199 /**
1200  * snd_pcm_hw_constraint_mask - apply the given bitmap mask constraint
1201  * @runtime: PCM runtime instance
1202  * @var: hw_params variable to apply the mask
1203  * @mask: the bitmap mask
1204  *
1205  * Apply the constraint of the given bitmap mask to a 32-bit mask parameter.
1206  *
1207  * Return: Zero if successful, or a negative error code on failure.
1208  */
1209 int snd_pcm_hw_constraint_mask(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1210                                u_int32_t mask)
1211 {
1212         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1213         struct snd_mask *maskp = constrs_mask(constrs, var);
1214         *maskp->bits &= mask;
1215         memset(maskp->bits + 1, 0, (SNDRV_MASK_MAX-32) / 8); /* clear rest */
1216         if (*maskp->bits == 0)
1217                 return -EINVAL;
1218         return 0;
1219 }
1220
1221 /**
1222  * snd_pcm_hw_constraint_mask64 - apply the given bitmap mask constraint
1223  * @runtime: PCM runtime instance
1224  * @var: hw_params variable to apply the mask
1225  * @mask: the 64bit bitmap mask
1226  *
1227  * Apply the constraint of the given bitmap mask to a 64-bit mask parameter.
1228  *
1229  * Return: Zero if successful, or a negative error code on failure.
1230  */
1231 int snd_pcm_hw_constraint_mask64(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1232                                  u_int64_t mask)
1233 {
1234         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1235         struct snd_mask *maskp = constrs_mask(constrs, var);
1236         maskp->bits[0] &= (u_int32_t)mask;
1237         maskp->bits[1] &= (u_int32_t)(mask >> 32);
1238         memset(maskp->bits + 2, 0, (SNDRV_MASK_MAX-64) / 8); /* clear rest */
1239         if (! maskp->bits[0] && ! maskp->bits[1])
1240                 return -EINVAL;
1241         return 0;
1242 }
1243 EXPORT_SYMBOL(snd_pcm_hw_constraint_mask64);
1244
1245 /**
1246  * snd_pcm_hw_constraint_integer - apply an integer constraint to an interval
1247  * @runtime: PCM runtime instance
1248  * @var: hw_params variable to apply the integer constraint
1249  *
1250  * Apply the constraint of integer to an interval parameter.
1251  *
1252  * Return: Positive if the value is changed, zero if it's not changed, or a
1253  * negative error code.
1254  */
1255 int snd_pcm_hw_constraint_integer(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var)
1256 {
1257         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1258         return snd_interval_setinteger(constrs_interval(constrs, var));
1259 }
1260
1261 EXPORT_SYMBOL(snd_pcm_hw_constraint_integer);
1262
1263 /**
1264  * snd_pcm_hw_constraint_minmax - apply a min/max range constraint to an interval
1265  * @runtime: PCM runtime instance
1266  * @var: hw_params variable to apply the range
1267  * @min: the minimal value
1268  * @max: the maximal value
1269  * 
1270  * Apply the min/max range constraint to an interval parameter.
1271  *
1272  * Return: Positive if the value is changed, zero if it's not changed, or a
1273  * negative error code.
1274  */
1275 int snd_pcm_hw_constraint_minmax(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var,
1276                                  unsigned int min, unsigned int max)
1277 {
1278         struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
1279         struct snd_interval t;
1280         t.min = min;
1281         t.max = max;
1282         t.openmin = t.openmax = 0;
1283         t.integer = 0;
1284         return snd_interval_refine(constrs_interval(constrs, var), &t);
1285 }
1286
1287 EXPORT_SYMBOL(snd_pcm_hw_constraint_minmax);
1288
1289 static int snd_pcm_hw_rule_list(struct snd_pcm_hw_params *params,
1290                                 struct snd_pcm_hw_rule *rule)
1291 {
1292         struct snd_pcm_hw_constraint_list *list = rule->private;
1293         return snd_interval_list(hw_param_interval(params, rule->var), list->count, list->list, list->mask);
1294 }               
1295
1296
1297 /**
1298  * snd_pcm_hw_constraint_list - apply a list of constraints to a parameter
1299  * @runtime: PCM runtime instance
1300  * @cond: condition bits
1301  * @var: hw_params variable to apply the list constraint
1302  * @l: list
1303  * 
1304  * Apply the list of constraints to an interval parameter.
1305  *
1306  * Return: Zero if successful, or a negative error code on failure.
1307  */
1308 int snd_pcm_hw_constraint_list(struct snd_pcm_runtime *runtime,
1309                                unsigned int cond,
1310                                snd_pcm_hw_param_t var,
1311                                const struct snd_pcm_hw_constraint_list *l)
1312 {
1313         return snd_pcm_hw_rule_add(runtime, cond, var,
1314                                    snd_pcm_hw_rule_list, (void *)l,
1315                                    var, -1);
1316 }
1317
1318 EXPORT_SYMBOL(snd_pcm_hw_constraint_list);
1319
1320 static int snd_pcm_hw_rule_ranges(struct snd_pcm_hw_params *params,
1321                                   struct snd_pcm_hw_rule *rule)
1322 {
1323         struct snd_pcm_hw_constraint_ranges *r = rule->private;
1324         return snd_interval_ranges(hw_param_interval(params, rule->var),
1325                                    r->count, r->ranges, r->mask);
1326 }
1327
1328
1329 /**
1330  * snd_pcm_hw_constraint_ranges - apply list of range constraints to a parameter
1331  * @runtime: PCM runtime instance
1332  * @cond: condition bits
1333  * @var: hw_params variable to apply the list of range constraints
1334  * @r: ranges
1335  *
1336  * Apply the list of range constraints to an interval parameter.
1337  *
1338  * Return: Zero if successful, or a negative error code on failure.
1339  */
1340 int snd_pcm_hw_constraint_ranges(struct snd_pcm_runtime *runtime,
1341                                  unsigned int cond,
1342                                  snd_pcm_hw_param_t var,
1343                                  const struct snd_pcm_hw_constraint_ranges *r)
1344 {
1345         return snd_pcm_hw_rule_add(runtime, cond, var,
1346                                    snd_pcm_hw_rule_ranges, (void *)r,
1347                                    var, -1);
1348 }
1349 EXPORT_SYMBOL(snd_pcm_hw_constraint_ranges);
1350
1351 static int snd_pcm_hw_rule_ratnums(struct snd_pcm_hw_params *params,
1352                                    struct snd_pcm_hw_rule *rule)
1353 {
1354         const struct snd_pcm_hw_constraint_ratnums *r = rule->private;
1355         unsigned int num = 0, den = 0;
1356         int err;
1357         err = snd_interval_ratnum(hw_param_interval(params, rule->var),
1358                                   r->nrats, r->rats, &num, &den);
1359         if (err >= 0 && den && rule->var == SNDRV_PCM_HW_PARAM_RATE) {
1360                 params->rate_num = num;
1361                 params->rate_den = den;
1362         }
1363         return err;
1364 }
1365
1366 /**
1367  * snd_pcm_hw_constraint_ratnums - apply ratnums constraint to a parameter
1368  * @runtime: PCM runtime instance
1369  * @cond: condition bits
1370  * @var: hw_params variable to apply the ratnums constraint
1371  * @r: struct snd_ratnums constriants
1372  *
1373  * Return: Zero if successful, or a negative error code on failure.
1374  */
1375 int snd_pcm_hw_constraint_ratnums(struct snd_pcm_runtime *runtime, 
1376                                   unsigned int cond,
1377                                   snd_pcm_hw_param_t var,
1378                                   const struct snd_pcm_hw_constraint_ratnums *r)
1379 {
1380         return snd_pcm_hw_rule_add(runtime, cond, var,
1381                                    snd_pcm_hw_rule_ratnums, (void *)r,
1382                                    var, -1);
1383 }
1384
1385 EXPORT_SYMBOL(snd_pcm_hw_constraint_ratnums);
1386
1387 static int snd_pcm_hw_rule_ratdens(struct snd_pcm_hw_params *params,
1388                                    struct snd_pcm_hw_rule *rule)
1389 {
1390         const struct snd_pcm_hw_constraint_ratdens *r = rule->private;
1391         unsigned int num = 0, den = 0;
1392         int err = snd_interval_ratden(hw_param_interval(params, rule->var),
1393                                   r->nrats, r->rats, &num, &den);
1394         if (err >= 0 && den && rule->var == SNDRV_PCM_HW_PARAM_RATE) {
1395                 params->rate_num = num;
1396                 params->rate_den = den;
1397         }
1398         return err;
1399 }
1400
1401 /**
1402  * snd_pcm_hw_constraint_ratdens - apply ratdens constraint to a parameter
1403  * @runtime: PCM runtime instance
1404  * @cond: condition bits
1405  * @var: hw_params variable to apply the ratdens constraint
1406  * @r: struct snd_ratdens constriants
1407  *
1408  * Return: Zero if successful, or a negative error code on failure.
1409  */
1410 int snd_pcm_hw_constraint_ratdens(struct snd_pcm_runtime *runtime, 
1411                                   unsigned int cond,
1412                                   snd_pcm_hw_param_t var,
1413                                   const struct snd_pcm_hw_constraint_ratdens *r)
1414 {
1415         return snd_pcm_hw_rule_add(runtime, cond, var,
1416                                    snd_pcm_hw_rule_ratdens, (void *)r,
1417                                    var, -1);
1418 }
1419
1420 EXPORT_SYMBOL(snd_pcm_hw_constraint_ratdens);
1421
1422 static int snd_pcm_hw_rule_msbits(struct snd_pcm_hw_params *params,
1423                                   struct snd_pcm_hw_rule *rule)
1424 {
1425         unsigned int l = (unsigned long) rule->private;
1426         int width = l & 0xffff;
1427         unsigned int msbits = l >> 16;
1428         struct snd_interval *i = hw_param_interval(params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS);
1429
1430         if (!snd_interval_single(i))
1431                 return 0;
1432
1433         if ((snd_interval_value(i) == width) ||
1434             (width == 0 && snd_interval_value(i) > msbits))
1435                 params->msbits = min_not_zero(params->msbits, msbits);
1436
1437         return 0;
1438 }
1439
1440 /**
1441  * snd_pcm_hw_constraint_msbits - add a hw constraint msbits rule
1442  * @runtime: PCM runtime instance
1443  * @cond: condition bits
1444  * @width: sample bits width
1445  * @msbits: msbits width
1446  *
1447  * This constraint will set the number of most significant bits (msbits) if a
1448  * sample format with the specified width has been select. If width is set to 0
1449  * the msbits will be set for any sample format with a width larger than the
1450  * specified msbits.
1451  *
1452  * Return: Zero if successful, or a negative error code on failure.
1453  */
1454 int snd_pcm_hw_constraint_msbits(struct snd_pcm_runtime *runtime, 
1455                                  unsigned int cond,
1456                                  unsigned int width,
1457                                  unsigned int msbits)
1458 {
1459         unsigned long l = (msbits << 16) | width;
1460         return snd_pcm_hw_rule_add(runtime, cond, -1,
1461                                     snd_pcm_hw_rule_msbits,
1462                                     (void*) l,
1463                                     SNDRV_PCM_HW_PARAM_SAMPLE_BITS, -1);
1464 }
1465
1466 EXPORT_SYMBOL(snd_pcm_hw_constraint_msbits);
1467
1468 static int snd_pcm_hw_rule_step(struct snd_pcm_hw_params *params,
1469                                 struct snd_pcm_hw_rule *rule)
1470 {
1471         unsigned long step = (unsigned long) rule->private;
1472         return snd_interval_step(hw_param_interval(params, rule->var), step);
1473 }
1474
1475 /**
1476  * snd_pcm_hw_constraint_step - add a hw constraint step rule
1477  * @runtime: PCM runtime instance
1478  * @cond: condition bits
1479  * @var: hw_params variable to apply the step constraint
1480  * @step: step size
1481  *
1482  * Return: Zero if successful, or a negative error code on failure.
1483  */
1484 int snd_pcm_hw_constraint_step(struct snd_pcm_runtime *runtime,
1485                                unsigned int cond,
1486                                snd_pcm_hw_param_t var,
1487                                unsigned long step)
1488 {
1489         return snd_pcm_hw_rule_add(runtime, cond, var, 
1490                                    snd_pcm_hw_rule_step, (void *) step,
1491                                    var, -1);
1492 }
1493
1494 EXPORT_SYMBOL(snd_pcm_hw_constraint_step);
1495
1496 static int snd_pcm_hw_rule_pow2(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule)
1497 {
1498         static unsigned int pow2_sizes[] = {
1499                 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7,
1500                 1<<8, 1<<9, 1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15,
1501                 1<<16, 1<<17, 1<<18, 1<<19, 1<<20, 1<<21, 1<<22, 1<<23,
1502                 1<<24, 1<<25, 1<<26, 1<<27, 1<<28, 1<<29, 1<<30
1503         };
1504         return snd_interval_list(hw_param_interval(params, rule->var),
1505                                  ARRAY_SIZE(pow2_sizes), pow2_sizes, 0);
1506 }               
1507
1508 /**
1509  * snd_pcm_hw_constraint_pow2 - add a hw constraint power-of-2 rule
1510  * @runtime: PCM runtime instance
1511  * @cond: condition bits
1512  * @var: hw_params variable to apply the power-of-2 constraint
1513  *
1514  * Return: Zero if successful, or a negative error code on failure.
1515  */
1516 int snd_pcm_hw_constraint_pow2(struct snd_pcm_runtime *runtime,
1517                                unsigned int cond,
1518                                snd_pcm_hw_param_t var)
1519 {
1520         return snd_pcm_hw_rule_add(runtime, cond, var, 
1521                                    snd_pcm_hw_rule_pow2, NULL,
1522                                    var, -1);
1523 }
1524
1525 EXPORT_SYMBOL(snd_pcm_hw_constraint_pow2);
1526
1527 static int snd_pcm_hw_rule_noresample_func(struct snd_pcm_hw_params *params,
1528                                            struct snd_pcm_hw_rule *rule)
1529 {
1530         unsigned int base_rate = (unsigned int)(uintptr_t)rule->private;
1531         struct snd_interval *rate;
1532
1533         rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1534         return snd_interval_list(rate, 1, &base_rate, 0);
1535 }
1536
1537 /**
1538  * snd_pcm_hw_rule_noresample - add a rule to allow disabling hw resampling
1539  * @runtime: PCM runtime instance
1540  * @base_rate: the rate at which the hardware does not resample
1541  *
1542  * Return: Zero if successful, or a negative error code on failure.
1543  */
1544 int snd_pcm_hw_rule_noresample(struct snd_pcm_runtime *runtime,
1545                                unsigned int base_rate)
1546 {
1547         return snd_pcm_hw_rule_add(runtime, SNDRV_PCM_HW_PARAMS_NORESAMPLE,
1548                                    SNDRV_PCM_HW_PARAM_RATE,
1549                                    snd_pcm_hw_rule_noresample_func,
1550                                    (void *)(uintptr_t)base_rate,
1551                                    SNDRV_PCM_HW_PARAM_RATE, -1);
1552 }
1553 EXPORT_SYMBOL(snd_pcm_hw_rule_noresample);
1554
1555 static void _snd_pcm_hw_param_any(struct snd_pcm_hw_params *params,
1556                                   snd_pcm_hw_param_t var)
1557 {
1558         if (hw_is_mask(var)) {
1559                 snd_mask_any(hw_param_mask(params, var));
1560                 params->cmask |= 1 << var;
1561                 params->rmask |= 1 << var;
1562                 return;
1563         }
1564         if (hw_is_interval(var)) {
1565                 snd_interval_any(hw_param_interval(params, var));
1566                 params->cmask |= 1 << var;
1567                 params->rmask |= 1 << var;
1568                 return;
1569         }
1570         snd_BUG();
1571 }
1572
1573 void _snd_pcm_hw_params_any(struct snd_pcm_hw_params *params)
1574 {
1575         unsigned int k;
1576         memset(params, 0, sizeof(*params));
1577         for (k = SNDRV_PCM_HW_PARAM_FIRST_MASK; k <= SNDRV_PCM_HW_PARAM_LAST_MASK; k++)
1578                 _snd_pcm_hw_param_any(params, k);
1579         for (k = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; k <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; k++)
1580                 _snd_pcm_hw_param_any(params, k);
1581         params->info = ~0U;
1582 }
1583
1584 EXPORT_SYMBOL(_snd_pcm_hw_params_any);
1585
1586 /**
1587  * snd_pcm_hw_param_value - return @params field @var value
1588  * @params: the hw_params instance
1589  * @var: parameter to retrieve
1590  * @dir: pointer to the direction (-1,0,1) or %NULL
1591  *
1592  * Return: The value for field @var if it's fixed in configuration space
1593  * defined by @params. -%EINVAL otherwise.
1594  */
1595 int snd_pcm_hw_param_value(const struct snd_pcm_hw_params *params,
1596                            snd_pcm_hw_param_t var, int *dir)
1597 {
1598         if (hw_is_mask(var)) {
1599                 const struct snd_mask *mask = hw_param_mask_c(params, var);
1600                 if (!snd_mask_single(mask))
1601                         return -EINVAL;
1602                 if (dir)
1603                         *dir = 0;
1604                 return snd_mask_value(mask);
1605         }
1606         if (hw_is_interval(var)) {
1607                 const struct snd_interval *i = hw_param_interval_c(params, var);
1608                 if (!snd_interval_single(i))
1609                         return -EINVAL;
1610                 if (dir)
1611                         *dir = i->openmin;
1612                 return snd_interval_value(i);
1613         }
1614         return -EINVAL;
1615 }
1616
1617 EXPORT_SYMBOL(snd_pcm_hw_param_value);
1618
1619 void _snd_pcm_hw_param_setempty(struct snd_pcm_hw_params *params,
1620                                 snd_pcm_hw_param_t var)
1621 {
1622         if (hw_is_mask(var)) {
1623                 snd_mask_none(hw_param_mask(params, var));
1624                 params->cmask |= 1 << var;
1625                 params->rmask |= 1 << var;
1626         } else if (hw_is_interval(var)) {
1627                 snd_interval_none(hw_param_interval(params, var));
1628                 params->cmask |= 1 << var;
1629                 params->rmask |= 1 << var;
1630         } else {
1631                 snd_BUG();
1632         }
1633 }
1634
1635 EXPORT_SYMBOL(_snd_pcm_hw_param_setempty);
1636
1637 static int _snd_pcm_hw_param_first(struct snd_pcm_hw_params *params,
1638                                    snd_pcm_hw_param_t var)
1639 {
1640         int changed;
1641         if (hw_is_mask(var))
1642                 changed = snd_mask_refine_first(hw_param_mask(params, var));
1643         else if (hw_is_interval(var))
1644                 changed = snd_interval_refine_first(hw_param_interval(params, var));
1645         else
1646                 return -EINVAL;
1647         if (changed) {
1648                 params->cmask |= 1 << var;
1649                 params->rmask |= 1 << var;
1650         }
1651         return changed;
1652 }
1653
1654
1655 /**
1656  * snd_pcm_hw_param_first - refine config space and return minimum value
1657  * @pcm: PCM instance
1658  * @params: the hw_params instance
1659  * @var: parameter to retrieve
1660  * @dir: pointer to the direction (-1,0,1) or %NULL
1661  *
1662  * Inside configuration space defined by @params remove from @var all
1663  * values > minimum. Reduce configuration space accordingly.
1664  *
1665  * Return: The minimum, or a negative error code on failure.
1666  */
1667 int snd_pcm_hw_param_first(struct snd_pcm_substream *pcm, 
1668                            struct snd_pcm_hw_params *params, 
1669                            snd_pcm_hw_param_t var, int *dir)
1670 {
1671         int changed = _snd_pcm_hw_param_first(params, var);
1672         if (changed < 0)
1673                 return changed;
1674         if (params->rmask) {
1675                 int err = snd_pcm_hw_refine(pcm, params);
1676                 if (err < 0)
1677                         return err;
1678         }
1679         return snd_pcm_hw_param_value(params, var, dir);
1680 }
1681
1682 EXPORT_SYMBOL(snd_pcm_hw_param_first);
1683
1684 static int _snd_pcm_hw_param_last(struct snd_pcm_hw_params *params,
1685                                   snd_pcm_hw_param_t var)
1686 {
1687         int changed;
1688         if (hw_is_mask(var))
1689                 changed = snd_mask_refine_last(hw_param_mask(params, var));
1690         else if (hw_is_interval(var))
1691                 changed = snd_interval_refine_last(hw_param_interval(params, var));
1692         else
1693                 return -EINVAL;
1694         if (changed) {
1695                 params->cmask |= 1 << var;
1696                 params->rmask |= 1 << var;
1697         }
1698         return changed;
1699 }
1700
1701
1702 /**
1703  * snd_pcm_hw_param_last - refine config space and return maximum value
1704  * @pcm: PCM instance
1705  * @params: the hw_params instance
1706  * @var: parameter to retrieve
1707  * @dir: pointer to the direction (-1,0,1) or %NULL
1708  *
1709  * Inside configuration space defined by @params remove from @var all
1710  * values < maximum. Reduce configuration space accordingly.
1711  *
1712  * Return: The maximum, or a negative error code on failure.
1713  */
1714 int snd_pcm_hw_param_last(struct snd_pcm_substream *pcm, 
1715                           struct snd_pcm_hw_params *params,
1716                           snd_pcm_hw_param_t var, int *dir)
1717 {
1718         int changed = _snd_pcm_hw_param_last(params, var);
1719         if (changed < 0)
1720                 return changed;
1721         if (params->rmask) {
1722                 int err = snd_pcm_hw_refine(pcm, params);
1723                 if (err < 0)
1724                         return err;
1725         }
1726         return snd_pcm_hw_param_value(params, var, dir);
1727 }
1728
1729 EXPORT_SYMBOL(snd_pcm_hw_param_last);
1730
1731 /**
1732  * snd_pcm_hw_param_choose - choose a configuration defined by @params
1733  * @pcm: PCM instance
1734  * @params: the hw_params instance
1735  *
1736  * Choose one configuration from configuration space defined by @params.
1737  * The configuration chosen is that obtained fixing in this order:
1738  * first access, first format, first subformat, min channels,
1739  * min rate, min period time, max buffer size, min tick time
1740  *
1741  * Return: Zero if successful, or a negative error code on failure.
1742  */
1743 int snd_pcm_hw_params_choose(struct snd_pcm_substream *pcm,
1744                              struct snd_pcm_hw_params *params)
1745 {
1746         static int vars[] = {
1747                 SNDRV_PCM_HW_PARAM_ACCESS,
1748                 SNDRV_PCM_HW_PARAM_FORMAT,
1749                 SNDRV_PCM_HW_PARAM_SUBFORMAT,
1750                 SNDRV_PCM_HW_PARAM_CHANNELS,
1751                 SNDRV_PCM_HW_PARAM_RATE,
1752                 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1753                 SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
1754                 SNDRV_PCM_HW_PARAM_TICK_TIME,
1755                 -1
1756         };
1757         int err, *v;
1758
1759         for (v = vars; *v != -1; v++) {
1760                 if (*v != SNDRV_PCM_HW_PARAM_BUFFER_SIZE)
1761                         err = snd_pcm_hw_param_first(pcm, params, *v, NULL);
1762                 else
1763                         err = snd_pcm_hw_param_last(pcm, params, *v, NULL);
1764                 if (snd_BUG_ON(err < 0))
1765                         return err;
1766         }
1767         return 0;
1768 }
1769
1770 static int snd_pcm_lib_ioctl_reset(struct snd_pcm_substream *substream,
1771                                    void *arg)
1772 {
1773         struct snd_pcm_runtime *runtime = substream->runtime;
1774         unsigned long flags;
1775         snd_pcm_stream_lock_irqsave(substream, flags);
1776         if (snd_pcm_running(substream) &&
1777             snd_pcm_update_hw_ptr(substream) >= 0)
1778                 runtime->status->hw_ptr %= runtime->buffer_size;
1779         else {
1780                 runtime->status->hw_ptr = 0;
1781                 runtime->hw_ptr_wrap = 0;
1782         }
1783         snd_pcm_stream_unlock_irqrestore(substream, flags);
1784         return 0;
1785 }
1786
1787 static int snd_pcm_lib_ioctl_channel_info(struct snd_pcm_substream *substream,
1788                                           void *arg)
1789 {
1790         struct snd_pcm_channel_info *info = arg;
1791         struct snd_pcm_runtime *runtime = substream->runtime;
1792         int width;
1793         if (!(runtime->info & SNDRV_PCM_INFO_MMAP)) {
1794                 info->offset = -1;
1795                 return 0;
1796         }
1797         width = snd_pcm_format_physical_width(runtime->format);
1798         if (width < 0)
1799                 return width;
1800         info->offset = 0;
1801         switch (runtime->access) {
1802         case SNDRV_PCM_ACCESS_MMAP_INTERLEAVED:
1803         case SNDRV_PCM_ACCESS_RW_INTERLEAVED:
1804                 if ((UINT_MAX/width) < info->channel) {
1805                         snd_printd("%s: integer overflow while multiply\n",
1806                                    __func__);
1807                         return -EINVAL;
1808                 }
1809                 info->first = info->channel * width;
1810                 info->step = runtime->channels * width;
1811                 break;
1812         case SNDRV_PCM_ACCESS_MMAP_NONINTERLEAVED:
1813         case SNDRV_PCM_ACCESS_RW_NONINTERLEAVED:
1814         {
1815                 size_t size = runtime->dma_bytes / runtime->channels;
1816
1817                 if ((size > 0) && ((UINT_MAX/(size * 8)) < info->channel)) {
1818                         snd_printd("%s: integer overflow while multiply\n",
1819                                    __func__);
1820                         return -EINVAL;
1821                 }
1822                 info->first = info->channel * size * 8;
1823                 info->step = width;
1824                 break;
1825         }
1826         default:
1827                 snd_BUG();
1828                 break;
1829         }
1830         return 0;
1831 }
1832
1833 static int snd_pcm_lib_ioctl_fifo_size(struct snd_pcm_substream *substream,
1834                                        void *arg)
1835 {
1836         struct snd_pcm_hw_params *params = arg;
1837         snd_pcm_format_t format;
1838         int channels;
1839         ssize_t frame_size;
1840
1841         params->fifo_size = substream->runtime->hw.fifo_size;
1842         if (!(substream->runtime->hw.info & SNDRV_PCM_INFO_FIFO_IN_FRAMES)) {
1843                 format = params_format(params);
1844                 channels = params_channels(params);
1845                 frame_size = snd_pcm_format_size(format, channels);
1846                 if (frame_size > 0)
1847                         params->fifo_size /= (unsigned)frame_size;
1848         }
1849         return 0;
1850 }
1851
1852 /**
1853  * snd_pcm_lib_ioctl - a generic PCM ioctl callback
1854  * @substream: the pcm substream instance
1855  * @cmd: ioctl command
1856  * @arg: ioctl argument
1857  *
1858  * Processes the generic ioctl commands for PCM.
1859  * Can be passed as the ioctl callback for PCM ops.
1860  *
1861  * Return: Zero if successful, or a negative error code on failure.
1862  */
1863 int snd_pcm_lib_ioctl(struct snd_pcm_substream *substream,
1864                       unsigned int cmd, void *arg)
1865 {
1866         switch (cmd) {
1867         case SNDRV_PCM_IOCTL1_RESET:
1868                 return snd_pcm_lib_ioctl_reset(substream, arg);
1869         case SNDRV_PCM_IOCTL1_CHANNEL_INFO:
1870                 return snd_pcm_lib_ioctl_channel_info(substream, arg);
1871         case SNDRV_PCM_IOCTL1_FIFO_SIZE:
1872                 return snd_pcm_lib_ioctl_fifo_size(substream, arg);
1873         }
1874         return -ENXIO;
1875 }
1876
1877 EXPORT_SYMBOL(snd_pcm_lib_ioctl);
1878
1879 /**
1880  * snd_pcm_period_elapsed - update the pcm status for the next period
1881  * @substream: the pcm substream instance
1882  *
1883  * This function is called from the interrupt handler when the
1884  * PCM has processed the period size.  It will update the current
1885  * pointer, wake up sleepers, etc.
1886  *
1887  * Even if more than one periods have elapsed since the last call, you
1888  * have to call this only once.
1889  */
1890 void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
1891 {
1892         struct snd_pcm_runtime *runtime;
1893         unsigned long flags;
1894
1895         if (PCM_RUNTIME_CHECK(substream))
1896                 return;
1897         runtime = substream->runtime;
1898
1899         snd_pcm_stream_lock_irqsave(substream, flags);
1900         if (!snd_pcm_running(substream) ||
1901             snd_pcm_update_hw_ptr0(substream, 1) < 0)
1902                 goto _end;
1903
1904 #ifdef CONFIG_SND_PCM_TIMER
1905         if (substream->timer_running)
1906                 snd_timer_interrupt(substream->timer, 1);
1907 #endif
1908  _end:
1909         kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
1910         snd_pcm_stream_unlock_irqrestore(substream, flags);
1911 }
1912
1913 EXPORT_SYMBOL(snd_pcm_period_elapsed);
1914
1915 /*
1916  * Wait until avail_min data becomes available
1917  * Returns a negative error code if any error occurs during operation.
1918  * The available space is stored on availp.  When err = 0 and avail = 0
1919  * on the capture stream, it indicates the stream is in DRAINING state.
1920  */
1921 static int wait_for_avail(struct snd_pcm_substream *substream,
1922                               snd_pcm_uframes_t *availp)
1923 {
1924         struct snd_pcm_runtime *runtime = substream->runtime;
1925         int is_playback = substream->stream == SNDRV_PCM_STREAM_PLAYBACK;
1926         wait_queue_t wait;
1927         int err = 0;
1928         snd_pcm_uframes_t avail = 0;
1929         long wait_time, tout;
1930
1931         init_waitqueue_entry(&wait, current);
1932         set_current_state(TASK_INTERRUPTIBLE);
1933         add_wait_queue(&runtime->tsleep, &wait);
1934
1935         if (runtime->no_period_wakeup)
1936                 wait_time = MAX_SCHEDULE_TIMEOUT;
1937         else {
1938                 wait_time = 10;
1939                 if (runtime->rate) {
1940                         long t = runtime->period_size * 2 / runtime->rate;
1941                         wait_time = max(t, wait_time);
1942                 }
1943                 wait_time = msecs_to_jiffies(wait_time * 1000);
1944         }
1945
1946         for (;;) {
1947                 if (signal_pending(current)) {
1948                         err = -ERESTARTSYS;
1949                         break;
1950                 }
1951
1952                 /*
1953                  * We need to check if space became available already
1954                  * (and thus the wakeup happened already) first to close
1955                  * the race of space already having become available.
1956                  * This check must happen after been added to the waitqueue
1957                  * and having current state be INTERRUPTIBLE.
1958                  */
1959                 if (is_playback)
1960                         avail = snd_pcm_playback_avail(runtime);
1961                 else
1962                         avail = snd_pcm_capture_avail(runtime);
1963                 if (avail >= runtime->twake)
1964                         break;
1965                 snd_pcm_stream_unlock_irq(substream);
1966
1967                 tout = schedule_timeout(wait_time);
1968
1969                 snd_pcm_stream_lock_irq(substream);
1970                 set_current_state(TASK_INTERRUPTIBLE);
1971                 switch (runtime->status->state) {
1972                 case SNDRV_PCM_STATE_SUSPENDED:
1973                         err = -ESTRPIPE;
1974                         goto _endloop;
1975                 case SNDRV_PCM_STATE_XRUN:
1976                         err = -EPIPE;
1977                         goto _endloop;
1978                 case SNDRV_PCM_STATE_DRAINING:
1979                         if (is_playback)
1980                                 err = -EPIPE;
1981                         else 
1982                                 avail = 0; /* indicate draining */
1983                         goto _endloop;
1984                 case SNDRV_PCM_STATE_OPEN:
1985                 case SNDRV_PCM_STATE_SETUP:
1986                 case SNDRV_PCM_STATE_DISCONNECTED:
1987                         err = -EBADFD;
1988                         goto _endloop;
1989                 case SNDRV_PCM_STATE_PAUSED:
1990                         continue;
1991                 }
1992                 if (!tout) {
1993                         pcm_dbg(substream->pcm,
1994                                 "%s write error (DMA or IRQ trouble?)\n",
1995                                 is_playback ? "playback" : "capture");
1996                         err = -EIO;
1997                         break;
1998                 }
1999         }
2000  _endloop:
2001         set_current_state(TASK_RUNNING);
2002         remove_wait_queue(&runtime->tsleep, &wait);
2003         *availp = avail;
2004         return err;
2005 }
2006         
2007 static int snd_pcm_lib_write_transfer(struct snd_pcm_substream *substream,
2008                                       unsigned int hwoff,
2009                                       unsigned long data, unsigned int off,
2010                                       snd_pcm_uframes_t frames)
2011 {
2012         struct snd_pcm_runtime *runtime = substream->runtime;
2013         int err;
2014         char __user *buf = (char __user *) data + frames_to_bytes(runtime, off);
2015         if (substream->ops->copy) {
2016                 if ((err = substream->ops->copy(substream, -1, hwoff, buf, frames)) < 0)
2017                         return err;
2018         } else {
2019                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);
2020                 if (copy_from_user(hwbuf, buf, frames_to_bytes(runtime, frames)))
2021                         return -EFAULT;
2022         }
2023         return 0;
2024 }
2025  
2026 typedef int (*transfer_f)(struct snd_pcm_substream *substream, unsigned int hwoff,
2027                           unsigned long data, unsigned int off,
2028                           snd_pcm_uframes_t size);
2029
2030 static snd_pcm_sframes_t snd_pcm_lib_write1(struct snd_pcm_substream *substream, 
2031                                             unsigned long data,
2032                                             snd_pcm_uframes_t size,
2033                                             int nonblock,
2034                                             transfer_f transfer)
2035 {
2036         struct snd_pcm_runtime *runtime = substream->runtime;
2037         snd_pcm_uframes_t xfer = 0;
2038         snd_pcm_uframes_t offset = 0;
2039         snd_pcm_uframes_t avail;
2040         int err = 0;
2041
2042         if (size == 0)
2043                 return 0;
2044
2045         snd_pcm_stream_lock_irq(substream);
2046         switch (runtime->status->state) {
2047         case SNDRV_PCM_STATE_PREPARED:
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         if (runtime->status->state == SNDRV_PCM_STATE_RUNNING)
2064                 snd_pcm_update_hw_ptr(substream);
2065         avail = snd_pcm_playback_avail(runtime);
2066         while (size > 0) {
2067                 snd_pcm_uframes_t frames, appl_ptr, appl_ofs;
2068                 snd_pcm_uframes_t cont;
2069                 if (!avail) {
2070                         if (nonblock) {
2071                                 err = -EAGAIN;
2072                                 goto _end_unlock;
2073                         }
2074                         runtime->twake = min_t(snd_pcm_uframes_t, size,
2075                                         runtime->control->avail_min ? : 1);
2076                         err = wait_for_avail(substream, &avail);
2077                         if (err < 0)
2078                                 goto _end_unlock;
2079                 }
2080                 frames = size > avail ? avail : size;
2081                 cont = runtime->buffer_size - runtime->control->appl_ptr % runtime->buffer_size;
2082                 if (frames > cont)
2083                         frames = cont;
2084                 if (snd_BUG_ON(!frames)) {
2085                         runtime->twake = 0;
2086                         snd_pcm_stream_unlock_irq(substream);
2087                         return -EINVAL;
2088                 }
2089                 appl_ptr = runtime->control->appl_ptr;
2090                 appl_ofs = appl_ptr % runtime->buffer_size;
2091                 snd_pcm_stream_unlock_irq(substream);
2092                 err = transfer(substream, appl_ofs, data, offset, frames);
2093                 snd_pcm_stream_lock_irq(substream);
2094                 if (err < 0)
2095                         goto _end_unlock;
2096                 switch (runtime->status->state) {
2097                 case SNDRV_PCM_STATE_XRUN:
2098                         err = -EPIPE;
2099                         goto _end_unlock;
2100                 case SNDRV_PCM_STATE_SUSPENDED:
2101                         err = -ESTRPIPE;
2102                         goto _end_unlock;
2103                 default:
2104                         break;
2105                 }
2106                 appl_ptr += frames;
2107                 if (appl_ptr >= runtime->boundary)
2108                         appl_ptr -= runtime->boundary;
2109                 runtime->control->appl_ptr = appl_ptr;
2110                 if (substream->ops->ack)
2111                         substream->ops->ack(substream);
2112
2113                 offset += frames;
2114                 size -= frames;
2115                 xfer += frames;
2116                 avail -= frames;
2117                 if (runtime->status->state == SNDRV_PCM_STATE_PREPARED &&
2118                     snd_pcm_playback_hw_avail(runtime) >= (snd_pcm_sframes_t)runtime->start_threshold) {
2119                         err = snd_pcm_start(substream);
2120                         if (err < 0)
2121                                 goto _end_unlock;
2122                 }
2123         }
2124  _end_unlock:
2125         runtime->twake = 0;
2126         if (xfer > 0 && err >= 0)
2127                 snd_pcm_update_state(substream, runtime);
2128         snd_pcm_stream_unlock_irq(substream);
2129         return xfer > 0 ? (snd_pcm_sframes_t)xfer : err;
2130 }
2131
2132 /* sanity-check for read/write methods */
2133 static int pcm_sanity_check(struct snd_pcm_substream *substream)
2134 {
2135         struct snd_pcm_runtime *runtime;
2136         if (PCM_RUNTIME_CHECK(substream))
2137                 return -ENXIO;
2138         /* TODO: consider and -EINVAL here */
2139         if (substream->hw_no_buffer)
2140                 snd_printd("%s: warning this PCM is host less\n", __func__);
2141         runtime = substream->runtime;
2142         if (snd_BUG_ON(!substream->ops->copy && !runtime->dma_area))
2143                 return -EINVAL;
2144         if (runtime->status->state == SNDRV_PCM_STATE_OPEN)
2145                 return -EBADFD;
2146         return 0;
2147 }
2148
2149 snd_pcm_sframes_t snd_pcm_lib_write(struct snd_pcm_substream *substream, const void __user *buf, snd_pcm_uframes_t size)
2150 {
2151         struct snd_pcm_runtime *runtime;
2152         int nonblock;
2153         int err;
2154
2155         err = pcm_sanity_check(substream);
2156         if (err < 0)
2157                 return err;
2158         runtime = substream->runtime;
2159         nonblock = !!(substream->f_flags & O_NONBLOCK);
2160
2161         if (runtime->access != SNDRV_PCM_ACCESS_RW_INTERLEAVED &&
2162             runtime->channels > 1)
2163                 return -EINVAL;
2164         return snd_pcm_lib_write1(substream, (unsigned long)buf, size, nonblock,
2165                                   snd_pcm_lib_write_transfer);
2166 }
2167
2168 EXPORT_SYMBOL(snd_pcm_lib_write);
2169
2170 static int snd_pcm_lib_writev_transfer(struct snd_pcm_substream *substream,
2171                                        unsigned int hwoff,
2172                                        unsigned long data, unsigned int off,
2173                                        snd_pcm_uframes_t frames)
2174 {
2175         struct snd_pcm_runtime *runtime = substream->runtime;
2176         int err;
2177         void __user **bufs = (void __user **)data;
2178         int channels = runtime->channels;
2179         int c;
2180         if (substream->ops->copy) {
2181                 if (snd_BUG_ON(!substream->ops->silence))
2182                         return -EINVAL;
2183                 for (c = 0; c < channels; ++c, ++bufs) {
2184                         if (*bufs == NULL) {
2185                                 if ((err = substream->ops->silence(substream, c, hwoff, frames)) < 0)
2186                                         return err;
2187                         } else {
2188                                 char __user *buf = *bufs + samples_to_bytes(runtime, off);
2189                                 if ((err = substream->ops->copy(substream, c, hwoff, buf, frames)) < 0)
2190                                         return err;
2191                         }
2192                 }
2193         } else {
2194                 /* default transfer behaviour */
2195                 size_t dma_csize = runtime->dma_bytes / channels;
2196                 for (c = 0; c < channels; ++c, ++bufs) {
2197                         char *hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, hwoff);
2198                         if (*bufs == NULL) {
2199                                 snd_pcm_format_set_silence(runtime->format, hwbuf, frames);
2200                         } else {
2201                                 char __user *buf = *bufs + samples_to_bytes(runtime, off);
2202                                 if (copy_from_user(hwbuf, buf, samples_to_bytes(runtime, frames)))
2203                                         return -EFAULT;
2204                         }
2205                 }
2206         }
2207         return 0;
2208 }
2209  
2210 snd_pcm_sframes_t snd_pcm_lib_writev(struct snd_pcm_substream *substream,
2211                                      void __user **bufs,
2212                                      snd_pcm_uframes_t frames)
2213 {
2214         struct snd_pcm_runtime *runtime;
2215         int nonblock;
2216         int err;
2217
2218         err = pcm_sanity_check(substream);
2219         if (err < 0)
2220                 return err;
2221         runtime = substream->runtime;
2222         nonblock = !!(substream->f_flags & O_NONBLOCK);
2223
2224         if (runtime->access != SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)
2225                 return -EINVAL;
2226         return snd_pcm_lib_write1(substream, (unsigned long)bufs, frames,
2227                                   nonblock, snd_pcm_lib_writev_transfer);
2228 }
2229
2230 EXPORT_SYMBOL(snd_pcm_lib_writev);
2231
2232 static int snd_pcm_lib_read_transfer(struct snd_pcm_substream *substream, 
2233                                      unsigned int hwoff,
2234                                      unsigned long data, unsigned int off,
2235                                      snd_pcm_uframes_t frames)
2236 {
2237         struct snd_pcm_runtime *runtime = substream->runtime;
2238         int err;
2239         char __user *buf = (char __user *) data + frames_to_bytes(runtime, off);
2240         if (substream->ops->copy) {
2241                 if ((err = substream->ops->copy(substream, -1, hwoff, buf, frames)) < 0)
2242                         return err;
2243         } else {
2244                 char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);
2245                 if (copy_to_user(buf, hwbuf, frames_to_bytes(runtime, frames)))
2246                         return -EFAULT;
2247         }
2248         return 0;
2249 }
2250
2251 static snd_pcm_sframes_t snd_pcm_lib_read1(struct snd_pcm_substream *substream,
2252                                            unsigned long data,
2253                                            snd_pcm_uframes_t size,
2254                                            int nonblock,
2255                                            transfer_f transfer)
2256 {
2257         struct snd_pcm_runtime *runtime = substream->runtime;
2258         snd_pcm_uframes_t xfer = 0;
2259         snd_pcm_uframes_t offset = 0;
2260         snd_pcm_uframes_t avail;
2261         int err = 0;
2262
2263         if (size == 0)
2264                 return 0;
2265
2266         snd_pcm_stream_lock_irq(substream);
2267         switch (runtime->status->state) {
2268         case SNDRV_PCM_STATE_PREPARED:
2269                 if (size >= runtime->start_threshold) {
2270                         err = snd_pcm_start(substream);
2271                         if (err < 0)
2272                                 goto _end_unlock;
2273                 }
2274                 break;
2275         case SNDRV_PCM_STATE_DRAINING:
2276         case SNDRV_PCM_STATE_RUNNING:
2277         case SNDRV_PCM_STATE_PAUSED:
2278                 break;
2279         case SNDRV_PCM_STATE_XRUN:
2280                 err = -EPIPE;
2281                 goto _end_unlock;
2282         case SNDRV_PCM_STATE_SUSPENDED:
2283                 err = -ESTRPIPE;
2284                 goto _end_unlock;
2285         default:
2286                 err = -EBADFD;
2287                 goto _end_unlock;
2288         }
2289
2290         runtime->twake = runtime->control->avail_min ? : 1;
2291         if (runtime->status->state == SNDRV_PCM_STATE_RUNNING)
2292                 snd_pcm_update_hw_ptr(substream);
2293         avail = snd_pcm_capture_avail(runtime);
2294         while (size > 0) {
2295                 snd_pcm_uframes_t frames, appl_ptr, appl_ofs;
2296                 snd_pcm_uframes_t cont;
2297                 if (!avail) {
2298                         if (runtime->status->state ==
2299                             SNDRV_PCM_STATE_DRAINING) {
2300                                 snd_pcm_stop(substream, SNDRV_PCM_STATE_SETUP);
2301                                 goto _end_unlock;
2302                         }
2303                         if (nonblock) {
2304                                 err = -EAGAIN;
2305                                 goto _end_unlock;
2306                         }
2307                         runtime->twake = min_t(snd_pcm_uframes_t, size,
2308                                         runtime->control->avail_min ? : 1);
2309                         err = wait_for_avail(substream, &avail);
2310                         if (err < 0)
2311                                 goto _end_unlock;
2312                         if (!avail)
2313                                 continue; /* draining */
2314                 }
2315                 frames = size > avail ? avail : size;
2316                 cont = runtime->buffer_size - runtime->control->appl_ptr % runtime->buffer_size;
2317                 if (frames > cont)
2318                         frames = cont;
2319                 if (snd_BUG_ON(!frames)) {
2320                         runtime->twake = 0;
2321                         snd_pcm_stream_unlock_irq(substream);
2322                         return -EINVAL;
2323                 }
2324                 appl_ptr = runtime->control->appl_ptr;
2325                 appl_ofs = appl_ptr % runtime->buffer_size;
2326                 snd_pcm_stream_unlock_irq(substream);
2327                 err = transfer(substream, appl_ofs, data, offset, frames);
2328                 snd_pcm_stream_lock_irq(substream);
2329                 if (err < 0)
2330                         goto _end_unlock;
2331                 switch (runtime->status->state) {
2332                 case SNDRV_PCM_STATE_XRUN:
2333                         err = -EPIPE;
2334                         goto _end_unlock;
2335                 case SNDRV_PCM_STATE_SUSPENDED:
2336                         err = -ESTRPIPE;
2337                         goto _end_unlock;
2338                 default:
2339                         break;
2340                 }
2341                 appl_ptr += frames;
2342                 if (appl_ptr >= runtime->boundary)
2343                         appl_ptr -= runtime->boundary;
2344                 runtime->control->appl_ptr = appl_ptr;
2345                 if (substream->ops->ack)
2346                         substream->ops->ack(substream);
2347
2348                 offset += frames;
2349                 size -= frames;
2350                 xfer += frames;
2351                 avail -= frames;
2352         }
2353  _end_unlock:
2354         runtime->twake = 0;
2355         if (xfer > 0 && err >= 0)
2356                 snd_pcm_update_state(substream, runtime);
2357         snd_pcm_stream_unlock_irq(substream);
2358         return xfer > 0 ? (snd_pcm_sframes_t)xfer : err;
2359 }
2360
2361 snd_pcm_sframes_t snd_pcm_lib_read(struct snd_pcm_substream *substream, void __user *buf, snd_pcm_uframes_t size)
2362 {
2363         struct snd_pcm_runtime *runtime;
2364         int nonblock;
2365         int err;
2366         
2367         err = pcm_sanity_check(substream);
2368         if (err < 0)
2369                 return err;
2370         runtime = substream->runtime;
2371         nonblock = !!(substream->f_flags & O_NONBLOCK);
2372         if (runtime->access != SNDRV_PCM_ACCESS_RW_INTERLEAVED)
2373                 return -EINVAL;
2374         return snd_pcm_lib_read1(substream, (unsigned long)buf, size, nonblock, snd_pcm_lib_read_transfer);
2375 }
2376
2377 EXPORT_SYMBOL(snd_pcm_lib_read);
2378
2379 static int snd_pcm_lib_readv_transfer(struct snd_pcm_substream *substream,
2380                                       unsigned int hwoff,
2381                                       unsigned long data, unsigned int off,
2382                                       snd_pcm_uframes_t frames)
2383 {
2384         struct snd_pcm_runtime *runtime = substream->runtime;
2385         int err;
2386         void __user **bufs = (void __user **)data;
2387         int channels = runtime->channels;
2388         int c;
2389         if (substream->ops->copy) {
2390                 for (c = 0; c < channels; ++c, ++bufs) {
2391                         char __user *buf;
2392                         if (*bufs == NULL)
2393                                 continue;
2394                         buf = *bufs + samples_to_bytes(runtime, off);
2395                         if ((err = substream->ops->copy(substream, c, hwoff, buf, frames)) < 0)
2396                                 return err;
2397                 }
2398         } else {
2399                 snd_pcm_uframes_t dma_csize = runtime->dma_bytes / channels;
2400                 for (c = 0; c < channels; ++c, ++bufs) {
2401                         char *hwbuf;
2402                         char __user *buf;
2403                         if (*bufs == NULL)
2404                                 continue;
2405
2406                         hwbuf = runtime->dma_area + (c * dma_csize) + samples_to_bytes(runtime, hwoff);
2407                         buf = *bufs + samples_to_bytes(runtime, off);
2408                         if (copy_to_user(buf, hwbuf, samples_to_bytes(runtime, frames)))
2409                                 return -EFAULT;
2410                 }
2411         }
2412         return 0;
2413 }
2414  
2415 snd_pcm_sframes_t snd_pcm_lib_readv(struct snd_pcm_substream *substream,
2416                                     void __user **bufs,
2417                                     snd_pcm_uframes_t frames)
2418 {
2419         struct snd_pcm_runtime *runtime;
2420         int nonblock;
2421         int err;
2422
2423         err = pcm_sanity_check(substream);
2424         if (err < 0)
2425                 return err;
2426         runtime = substream->runtime;
2427         if (runtime->status->state == SNDRV_PCM_STATE_OPEN)
2428                 return -EBADFD;
2429
2430         nonblock = !!(substream->f_flags & O_NONBLOCK);
2431         if (runtime->access != SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)
2432                 return -EINVAL;
2433         return snd_pcm_lib_read1(substream, (unsigned long)bufs, frames, nonblock, snd_pcm_lib_readv_transfer);
2434 }
2435
2436 EXPORT_SYMBOL(snd_pcm_lib_readv);
2437
2438 /*
2439  * standard channel mapping helpers
2440  */
2441
2442 /* default channel maps for multi-channel playbacks, up to 8 channels */
2443 const struct snd_pcm_chmap_elem snd_pcm_std_chmaps[] = {
2444         { .channels = 1,
2445           .map = { SNDRV_CHMAP_MONO } },
2446         { .channels = 2,
2447           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR } },
2448         { .channels = 4,
2449           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
2450                    SNDRV_CHMAP_RL, SNDRV_CHMAP_RR } },
2451         { .channels = 6,
2452           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
2453                    SNDRV_CHMAP_RL, SNDRV_CHMAP_RR,
2454                    SNDRV_CHMAP_FC, SNDRV_CHMAP_LFE } },
2455         { .channels = 8,
2456           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
2457                    SNDRV_CHMAP_RL, SNDRV_CHMAP_RR,
2458                    SNDRV_CHMAP_FC, SNDRV_CHMAP_LFE,
2459                    SNDRV_CHMAP_SL, SNDRV_CHMAP_SR } },
2460         { }
2461 };
2462 EXPORT_SYMBOL_GPL(snd_pcm_std_chmaps);
2463
2464 /* alternative channel maps with CLFE <-> surround swapped for 6/8 channels */
2465 const struct snd_pcm_chmap_elem snd_pcm_alt_chmaps[] = {
2466         { .channels = 1,
2467           .map = { SNDRV_CHMAP_MONO } },
2468         { .channels = 2,
2469           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR } },
2470         { .channels = 4,
2471           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
2472                    SNDRV_CHMAP_RL, SNDRV_CHMAP_RR } },
2473         { .channels = 6,
2474           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
2475                    SNDRV_CHMAP_FC, SNDRV_CHMAP_LFE,
2476                    SNDRV_CHMAP_RL, SNDRV_CHMAP_RR } },
2477         { .channels = 8,
2478           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
2479                    SNDRV_CHMAP_FC, SNDRV_CHMAP_LFE,
2480                    SNDRV_CHMAP_RL, SNDRV_CHMAP_RR,
2481                    SNDRV_CHMAP_SL, SNDRV_CHMAP_SR } },
2482         { }
2483 };
2484 EXPORT_SYMBOL_GPL(snd_pcm_alt_chmaps);
2485
2486 static bool valid_chmap_channels(const struct snd_pcm_chmap *info, int ch)
2487 {
2488         if (ch > info->max_channels)
2489                 return false;
2490         return !info->channel_mask || (info->channel_mask & (1U << ch));
2491 }
2492
2493 static int pcm_chmap_ctl_info(struct snd_kcontrol *kcontrol,
2494                               struct snd_ctl_elem_info *uinfo)
2495 {
2496         struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
2497
2498         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
2499         uinfo->count = 0;
2500         uinfo->count = info->max_channels;
2501         uinfo->value.integer.min = 0;
2502         uinfo->value.integer.max = SNDRV_CHMAP_LAST;
2503         return 0;
2504 }
2505
2506 /* get callback for channel map ctl element
2507  * stores the channel position firstly matching with the current channels
2508  */
2509 static int pcm_chmap_ctl_get(struct snd_kcontrol *kcontrol,
2510                              struct snd_ctl_elem_value *ucontrol)
2511 {
2512         struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
2513         unsigned int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id);
2514         struct snd_pcm_substream *substream;
2515         const struct snd_pcm_chmap_elem *map;
2516
2517         if (snd_BUG_ON(!info->chmap))
2518                 return -EINVAL;
2519         substream = snd_pcm_chmap_substream(info, idx);
2520         if (!substream)
2521                 return -ENODEV;
2522         memset(ucontrol->value.integer.value, 0,
2523                sizeof(ucontrol->value.integer.value));
2524         if (!substream->runtime)
2525                 return 0; /* no channels set */
2526         for (map = info->chmap; map->channels; map++) {
2527                 int i;
2528                 if (map->channels == substream->runtime->channels &&
2529                     valid_chmap_channels(info, map->channels)) {
2530                         for (i = 0; i < map->channels; i++)
2531                                 ucontrol->value.integer.value[i] = map->map[i];
2532                         return 0;
2533                 }
2534         }
2535         return -EINVAL;
2536 }
2537
2538 /* tlv callback for channel map ctl element
2539  * expands the pre-defined channel maps in a form of TLV
2540  */
2541 static int pcm_chmap_ctl_tlv(struct snd_kcontrol *kcontrol, int op_flag,
2542                              unsigned int size, unsigned int __user *tlv)
2543 {
2544         struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
2545         const struct snd_pcm_chmap_elem *map;
2546         unsigned int __user *dst;
2547         int c, count = 0;
2548
2549         if (snd_BUG_ON(!info->chmap))
2550                 return -EINVAL;
2551         if (size < 8)
2552                 return -ENOMEM;
2553         if (put_user(SNDRV_CTL_TLVT_CONTAINER, tlv))
2554                 return -EFAULT;
2555         size -= 8;
2556         dst = tlv + 2;
2557         for (map = info->chmap; map->channels; map++) {
2558                 int chs_bytes = map->channels * 4;
2559                 if (!valid_chmap_channels(info, map->channels))
2560                         continue;
2561                 if (size < 8)
2562                         return -ENOMEM;
2563                 if (put_user(SNDRV_CTL_TLVT_CHMAP_FIXED, dst) ||
2564                     put_user(chs_bytes, dst + 1))
2565                         return -EFAULT;
2566                 dst += 2;
2567                 size -= 8;
2568                 count += 8;
2569                 if (size < chs_bytes)
2570                         return -ENOMEM;
2571                 size -= chs_bytes;
2572                 count += chs_bytes;
2573                 for (c = 0; c < map->channels; c++) {
2574                         if (put_user(map->map[c], dst))
2575                                 return -EFAULT;
2576                         dst++;
2577                 }
2578         }
2579         if (put_user(count, tlv + 1))
2580                 return -EFAULT;
2581         return 0;
2582 }
2583
2584 static void pcm_chmap_ctl_private_free(struct snd_kcontrol *kcontrol)
2585 {
2586         struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
2587         info->pcm->streams[info->stream].chmap_kctl = NULL;
2588         kfree(info);
2589 }
2590
2591 static int pcm_volume_ctl_info(struct snd_kcontrol *kcontrol,
2592                                 struct snd_ctl_elem_info *uinfo)
2593 {
2594         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
2595         uinfo->count = 1;
2596         uinfo->value.integer.min = 0;
2597         uinfo->value.integer.max = 0x2000;
2598         return 0;
2599 }
2600
2601 static void pcm_volume_ctl_private_free(struct snd_kcontrol *kcontrol)
2602 {
2603         struct snd_pcm_volume *info = snd_kcontrol_chip(kcontrol);
2604         info->pcm->streams[info->stream].vol_kctl = NULL;
2605         kfree(info);
2606 }
2607
2608 /**
2609  * snd_pcm_add_chmap_ctls - create channel-mapping control elements
2610  * @pcm: the assigned PCM instance
2611  * @stream: stream direction
2612  * @chmap: channel map elements (for query)
2613  * @max_channels: the max number of channels for the stream
2614  * @private_value: the value passed to each kcontrol's private_value field
2615  * @info_ret: store struct snd_pcm_chmap instance if non-NULL
2616  *
2617  * Create channel-mapping control elements assigned to the given PCM stream(s).
2618  * Return: Zero if successful, or a negative error value.
2619  */
2620 int snd_pcm_add_chmap_ctls(struct snd_pcm *pcm, int stream,
2621                            const struct snd_pcm_chmap_elem *chmap,
2622                            int max_channels,
2623                            unsigned long private_value,
2624                            struct snd_pcm_chmap **info_ret)
2625 {
2626         struct snd_pcm_chmap *info;
2627         struct snd_kcontrol_new knew = {
2628                 .iface = SNDRV_CTL_ELEM_IFACE_PCM,
2629                 .access = SNDRV_CTL_ELEM_ACCESS_READ |
2630                         SNDRV_CTL_ELEM_ACCESS_TLV_READ |
2631                         SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK,
2632                 .info = pcm_chmap_ctl_info,
2633                 .get = pcm_chmap_ctl_get,
2634                 .tlv.c = pcm_chmap_ctl_tlv,
2635         };
2636         int err;
2637
2638         info = kzalloc(sizeof(*info), GFP_KERNEL);
2639         if (!info)
2640                 return -ENOMEM;
2641         info->pcm = pcm;
2642         info->stream = stream;
2643         info->chmap = chmap;
2644         info->max_channels = max_channels;
2645         if (stream == SNDRV_PCM_STREAM_PLAYBACK)
2646                 knew.name = "Playback Channel Map";
2647         else
2648                 knew.name = "Capture Channel Map";
2649         knew.device = pcm->device;
2650         knew.count = pcm->streams[stream].substream_count;
2651         knew.private_value = private_value;
2652         info->kctl = snd_ctl_new1(&knew, info);
2653         if (!info->kctl) {
2654                 kfree(info);
2655                 return -ENOMEM;
2656         }
2657         info->kctl->private_free = pcm_chmap_ctl_private_free;
2658         err = snd_ctl_add(pcm->card, info->kctl);
2659         if (err < 0)
2660                 return err;
2661         pcm->streams[stream].chmap_kctl = info->kctl;
2662         if (info_ret)
2663                 *info_ret = info;
2664         return 0;
2665 }
2666 EXPORT_SYMBOL_GPL(snd_pcm_add_chmap_ctls);
2667
2668 /**
2669  * snd_pcm_add_volume_ctls - create volume control elements
2670  * @pcm: the assigned PCM instance
2671  * @stream: stream direction
2672  * @max_length: the max length of the volume parameter of stream
2673  * @private_value: the value passed to each kcontrol's private_value field
2674  * @info_ret: store struct snd_pcm_volume instance if non-NULL
2675  *
2676  * Create volume control elements assigned to the given PCM stream(s).
2677  * Returns zero if succeed, or a negative error value.
2678  */
2679 int snd_pcm_add_volume_ctls(struct snd_pcm *pcm, int stream,
2680                            const struct snd_pcm_volume_elem *volume,
2681                            int max_length,
2682                            unsigned long private_value,
2683                            struct snd_pcm_volume **info_ret)
2684 {
2685         struct snd_pcm_volume *info;
2686         struct snd_kcontrol_new knew = {
2687                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2688                 .access = SNDRV_CTL_ELEM_ACCESS_TLV_READ |
2689                         SNDRV_CTL_ELEM_ACCESS_READWRITE,
2690                 .info = pcm_volume_ctl_info,
2691         };
2692         int err;
2693         int size;
2694
2695         info = kzalloc(sizeof(*info), GFP_KERNEL);
2696         if (!info)
2697                 return -ENOMEM;
2698         info->pcm = pcm;
2699         info->stream = stream;
2700         info->volume = volume;
2701         info->max_length = max_length;
2702         size = sizeof("Playback ") + sizeof(" Volume") +
2703                 STRING_LENGTH_OF_INT*sizeof(char) + 1;
2704         knew.name = kzalloc(size, GFP_KERNEL);
2705         if (!knew.name) {
2706                 kfree(info);
2707                 return -ENOMEM;
2708         }
2709         if (stream == SNDRV_PCM_STREAM_PLAYBACK)
2710                 snprintf((char *)knew.name, size, "%s %d %s",
2711                         "Playback", pcm->device, "Volume");
2712         else
2713                 snprintf((char *)knew.name, size, "%s %d %s",
2714                         "Capture", pcm->device, "Volume");
2715         knew.device = pcm->device;
2716         knew.count = pcm->streams[stream].substream_count;
2717         knew.private_value = private_value;
2718         info->kctl = snd_ctl_new1(&knew, info);
2719         if (!info->kctl) {
2720                 kfree(info);
2721                 kfree(knew.name);
2722                 return -ENOMEM;
2723         }
2724         info->kctl->private_free = pcm_volume_ctl_private_free;
2725         err = snd_ctl_add(pcm->card, info->kctl);
2726         if (err < 0) {
2727                 kfree(info);
2728                 kfree(knew.name);
2729                 return -ENOMEM;
2730         }
2731         pcm->streams[stream].vol_kctl = info->kctl;
2732         if (info_ret)
2733                 *info_ret = info;
2734         kfree(knew.name);
2735         return 0;
2736 }
2737 EXPORT_SYMBOL_GPL(snd_pcm_add_volume_ctls);
2738
2739 static int pcm_usr_ctl_info(struct snd_kcontrol *kcontrol,
2740                             struct snd_ctl_elem_info *uinfo)
2741 {
2742         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
2743         uinfo->count = MAX_USR_CTRL_CNT;
2744         uinfo->value.integer.min = 0;
2745         uinfo->value.integer.max = INT_MAX;
2746         return 0;
2747 }
2748
2749 static void pcm_usr_ctl_private_free(struct snd_kcontrol *kcontrol)
2750 {
2751         struct snd_pcm_usr *info = snd_kcontrol_chip(kcontrol);
2752         info->pcm->streams[info->stream].usr_kctl = NULL;
2753         kfree(info);
2754 }
2755
2756 /**
2757  * snd_pcm_add_usr_ctls - create user control elements
2758  * @pcm: the assigned PCM instance
2759  * @stream: stream direction
2760  * @max_length: the max length of the user parameter of stream
2761  * @private_value: the value passed to each kcontrol's private_value field
2762  * @info_ret: store struct snd_pcm_usr instance if non-NULL
2763  *
2764  * Create usr control elements assigned to the given PCM stream(s).
2765  * Returns zero if succeed, or a negative error value.
2766  */
2767 int snd_pcm_add_usr_ctls(struct snd_pcm *pcm, int stream,
2768                          const struct snd_pcm_usr_elem *usr,
2769                          int max_length, int max_kctrl_str_len,
2770                          unsigned long private_value,
2771                          struct snd_pcm_usr **info_ret)
2772 {
2773         struct snd_pcm_usr *info;
2774         struct snd_kcontrol_new knew = {
2775                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2776                 .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
2777                 .info = pcm_usr_ctl_info,
2778         };
2779         int err;
2780         char *buf;
2781
2782         info = kzalloc(sizeof(*info), GFP_KERNEL);
2783         if (!info) {
2784                 pr_err("%s: snd_pcm_usr alloc failed\n", __func__);
2785                 return -ENOMEM;
2786         }
2787         info->pcm = pcm;
2788         info->stream = stream;
2789         info->usr = usr;
2790         info->max_length = max_length;
2791         buf = kzalloc(max_kctrl_str_len, GFP_KERNEL);
2792         if (!buf) {
2793                 pr_err("%s: buffer allocation failed\n", __func__);
2794                 kfree(info);
2795                 return -ENOMEM;
2796         }
2797         knew.name = buf;
2798         if (stream == SNDRV_PCM_STREAM_PLAYBACK)
2799                 snprintf(buf, max_kctrl_str_len, "%s %d %s",
2800                         "Playback", pcm->device, "User kcontrol");
2801         else
2802                 snprintf(buf, max_kctrl_str_len, "%s %d %s",
2803                         "Capture", pcm->device, "User kcontrol");
2804         knew.device = pcm->device;
2805         knew.count = pcm->streams[stream].substream_count;
2806         knew.private_value = private_value;
2807         info->kctl = snd_ctl_new1(&knew, info);
2808         if (!info->kctl) {
2809                 kfree(info);
2810                 kfree(knew.name);
2811                 pr_err("%s: snd_ctl_new failed\n", __func__);
2812                 return -ENOMEM;
2813         }
2814         info->kctl->private_free = pcm_usr_ctl_private_free;
2815         err = snd_ctl_add(pcm->card, info->kctl);
2816         if (err < 0) {
2817                 kfree(info);
2818                 kfree(knew.name);
2819                 pr_err("%s: snd_ctl_add failed:%d\n", __func__,
2820                         err);
2821                 return -ENOMEM;
2822         }
2823         pcm->streams[stream].usr_kctl = info->kctl;
2824         if (info_ret)
2825                 *info_ret = info;
2826         kfree(knew.name);
2827         return 0;
2828 }
2829 EXPORT_SYMBOL(snd_pcm_add_usr_ctls);