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