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