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