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