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