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