xref: /linux/sound/core/pcm_native.c (revision 513480da5e9c8f55b4f8f5e89f386e26188fbb3f)
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  */
6 
7 #include <linux/compat.h>
8 #include <linux/mm.h>
9 #include <linux/module.h>
10 #include <linux/file.h>
11 #include <linux/slab.h>
12 #include <linux/sched/signal.h>
13 #include <linux/time.h>
14 #include <linux/pm_qos.h>
15 #include <linux/io.h>
16 #include <linux/dma-mapping.h>
17 #include <linux/vmalloc.h>
18 #include <sound/core.h>
19 #include <sound/control.h>
20 #include <sound/info.h>
21 #include <sound/pcm.h>
22 #include <sound/pcm_params.h>
23 #include <sound/timer.h>
24 #include <sound/minors.h>
25 #include <linux/uio.h>
26 #include <linux/delay.h>
27 #include <linux/bitops.h>
28 
29 #include "pcm_local.h"
30 
31 #ifdef CONFIG_SND_DEBUG
32 #define CREATE_TRACE_POINTS
33 #include "pcm_param_trace.h"
34 #else
35 #define trace_hw_mask_param_enabled()		0
36 #define trace_hw_interval_param_enabled()	0
37 #define trace_hw_mask_param(substream, type, index, prev, curr)
38 #define trace_hw_interval_param(substream, type, index, prev, curr)
39 #endif
40 
41 /*
42  *  Compatibility
43  */
44 
45 struct snd_pcm_hw_params_old {
46 	unsigned int flags;
47 	unsigned int masks[SNDRV_PCM_HW_PARAM_SUBFORMAT -
48 			   SNDRV_PCM_HW_PARAM_ACCESS + 1];
49 	struct snd_interval intervals[SNDRV_PCM_HW_PARAM_TICK_TIME -
50 					SNDRV_PCM_HW_PARAM_SAMPLE_BITS + 1];
51 	unsigned int rmask;
52 	unsigned int cmask;
53 	unsigned int info;
54 	unsigned int msbits;
55 	unsigned int rate_num;
56 	unsigned int rate_den;
57 	snd_pcm_uframes_t fifo_size;
58 	unsigned char reserved[64];
59 };
60 
61 #ifdef CONFIG_SND_SUPPORT_OLD_API
62 #define SNDRV_PCM_IOCTL_HW_REFINE_OLD _IOWR('A', 0x10, struct snd_pcm_hw_params_old)
63 #define SNDRV_PCM_IOCTL_HW_PARAMS_OLD _IOWR('A', 0x11, struct snd_pcm_hw_params_old)
64 
65 static int snd_pcm_hw_refine_old_user(struct snd_pcm_substream *substream,
66 				      struct snd_pcm_hw_params_old __user * _oparams);
67 static int snd_pcm_hw_params_old_user(struct snd_pcm_substream *substream,
68 				      struct snd_pcm_hw_params_old __user * _oparams);
69 #endif
70 static int snd_pcm_open(struct file *file, struct snd_pcm *pcm, int stream);
71 
72 /*
73  *
74  */
75 
76 static DECLARE_RWSEM(snd_pcm_link_rwsem);
77 
78 void snd_pcm_group_init(struct snd_pcm_group *group)
79 {
80 	spin_lock_init(&group->lock);
81 	mutex_init(&group->mutex);
82 	INIT_LIST_HEAD(&group->substreams);
83 	refcount_set(&group->refs, 1);
84 }
85 
86 /* define group lock helpers */
87 #define DEFINE_PCM_GROUP_LOCK(action, bh_lock, bh_unlock, mutex_action) \
88 static void snd_pcm_group_ ## action(struct snd_pcm_group *group, bool nonatomic) \
89 { \
90 	if (nonatomic) { \
91 		mutex_ ## mutex_action(&group->mutex); \
92 	} else { \
93 		if (IS_ENABLED(CONFIG_PREEMPT_RT) && bh_lock)   \
94 			local_bh_disable();			\
95 		spin_ ## action(&group->lock);			\
96 		if (IS_ENABLED(CONFIG_PREEMPT_RT) && bh_unlock) \
97 			local_bh_enable();                      \
98 	}							\
99 }
100 
101 DEFINE_PCM_GROUP_LOCK(lock, false, false, lock);
102 DEFINE_PCM_GROUP_LOCK(unlock, false, false, unlock);
103 DEFINE_PCM_GROUP_LOCK(lock_irq, true, false, lock);
104 DEFINE_PCM_GROUP_LOCK(unlock_irq, false, true, unlock);
105 
106 /**
107  * snd_pcm_stream_lock - Lock the PCM stream
108  * @substream: PCM substream
109  *
110  * This locks the PCM stream's spinlock or mutex depending on the nonatomic
111  * flag of the given substream.  This also takes the global link rw lock
112  * (or rw sem), too, for avoiding the race with linked streams.
113  */
114 void snd_pcm_stream_lock(struct snd_pcm_substream *substream)
115 {
116 	snd_pcm_group_lock(&substream->self_group, substream->pcm->nonatomic);
117 }
118 EXPORT_SYMBOL_GPL(snd_pcm_stream_lock);
119 
120 /**
121  * snd_pcm_stream_unlock - Unlock the PCM stream
122  * @substream: PCM substream
123  *
124  * This unlocks the PCM stream that has been locked via snd_pcm_stream_lock().
125  */
126 void snd_pcm_stream_unlock(struct snd_pcm_substream *substream)
127 {
128 	snd_pcm_group_unlock(&substream->self_group, substream->pcm->nonatomic);
129 }
130 EXPORT_SYMBOL_GPL(snd_pcm_stream_unlock);
131 
132 /**
133  * snd_pcm_stream_lock_irq - Lock the PCM stream
134  * @substream: PCM substream
135  *
136  * This locks the PCM stream like snd_pcm_stream_lock() and disables the local
137  * IRQ (only when nonatomic is false).  In nonatomic case, this is identical
138  * as snd_pcm_stream_lock().
139  */
140 void snd_pcm_stream_lock_irq(struct snd_pcm_substream *substream)
141 {
142 	snd_pcm_group_lock_irq(&substream->self_group,
143 			       substream->pcm->nonatomic);
144 }
145 EXPORT_SYMBOL_GPL(snd_pcm_stream_lock_irq);
146 
147 static void snd_pcm_stream_lock_nested(struct snd_pcm_substream *substream)
148 {
149 	struct snd_pcm_group *group = &substream->self_group;
150 
151 	if (substream->pcm->nonatomic)
152 		mutex_lock_nested(&group->mutex, SINGLE_DEPTH_NESTING);
153 	else
154 		spin_lock_nested(&group->lock, SINGLE_DEPTH_NESTING);
155 }
156 
157 /**
158  * snd_pcm_stream_unlock_irq - Unlock the PCM stream
159  * @substream: PCM substream
160  *
161  * This is a counter-part of snd_pcm_stream_lock_irq().
162  */
163 void snd_pcm_stream_unlock_irq(struct snd_pcm_substream *substream)
164 {
165 	snd_pcm_group_unlock_irq(&substream->self_group,
166 				 substream->pcm->nonatomic);
167 }
168 EXPORT_SYMBOL_GPL(snd_pcm_stream_unlock_irq);
169 
170 unsigned long _snd_pcm_stream_lock_irqsave(struct snd_pcm_substream *substream)
171 {
172 	unsigned long flags = 0;
173 	if (substream->pcm->nonatomic)
174 		mutex_lock(&substream->self_group.mutex);
175 	else
176 		spin_lock_irqsave(&substream->self_group.lock, flags);
177 	return flags;
178 }
179 EXPORT_SYMBOL_GPL(_snd_pcm_stream_lock_irqsave);
180 
181 unsigned long _snd_pcm_stream_lock_irqsave_nested(struct snd_pcm_substream *substream)
182 {
183 	unsigned long flags = 0;
184 	if (substream->pcm->nonatomic)
185 		mutex_lock_nested(&substream->self_group.mutex,
186 				  SINGLE_DEPTH_NESTING);
187 	else
188 		spin_lock_irqsave_nested(&substream->self_group.lock, flags,
189 					 SINGLE_DEPTH_NESTING);
190 	return flags;
191 }
192 EXPORT_SYMBOL_GPL(_snd_pcm_stream_lock_irqsave_nested);
193 
194 /**
195  * snd_pcm_stream_unlock_irqrestore - Unlock the PCM stream
196  * @substream: PCM substream
197  * @flags: irq flags
198  *
199  * This is a counter-part of snd_pcm_stream_lock_irqsave().
200  */
201 void snd_pcm_stream_unlock_irqrestore(struct snd_pcm_substream *substream,
202 				      unsigned long flags)
203 {
204 	if (substream->pcm->nonatomic)
205 		mutex_unlock(&substream->self_group.mutex);
206 	else
207 		spin_unlock_irqrestore(&substream->self_group.lock, flags);
208 }
209 EXPORT_SYMBOL_GPL(snd_pcm_stream_unlock_irqrestore);
210 
211 /* Run PCM ioctl ops */
212 static int snd_pcm_ops_ioctl(struct snd_pcm_substream *substream,
213 			     unsigned cmd, void *arg)
214 {
215 	if (substream->ops->ioctl)
216 		return substream->ops->ioctl(substream, cmd, arg);
217 	else
218 		return snd_pcm_lib_ioctl(substream, cmd, arg);
219 }
220 
221 int snd_pcm_info(struct snd_pcm_substream *substream, struct snd_pcm_info *info)
222 {
223 	struct snd_pcm *pcm = substream->pcm;
224 	struct snd_pcm_str *pstr = substream->pstr;
225 
226 	memset(info, 0, sizeof(*info));
227 	info->card = pcm->card->number;
228 	info->device = pcm->device;
229 	info->stream = substream->stream;
230 	info->subdevice = substream->number;
231 	strscpy(info->id, pcm->id, sizeof(info->id));
232 	strscpy(info->name, pcm->name, sizeof(info->name));
233 	info->dev_class = pcm->dev_class;
234 	info->dev_subclass = pcm->dev_subclass;
235 	info->subdevices_count = pstr->substream_count;
236 	info->subdevices_avail = pstr->substream_count - pstr->substream_opened;
237 	strscpy(info->subname, substream->name, sizeof(info->subname));
238 
239 	return 0;
240 }
241 
242 int snd_pcm_info_user(struct snd_pcm_substream *substream,
243 		      struct snd_pcm_info __user * _info)
244 {
245 	int err;
246 	struct snd_pcm_info *info __free(kfree) =
247 		kmalloc_obj(*info);
248 
249 	if (! info)
250 		return -ENOMEM;
251 	err = snd_pcm_info(substream, info);
252 	if (err >= 0) {
253 		if (copy_to_user(_info, info, sizeof(*info)))
254 			err = -EFAULT;
255 	}
256 	return err;
257 }
258 
259 /* macro for simplified cast */
260 #define PARAM_MASK_BIT(b)	(1U << (__force int)(b))
261 
262 static bool hw_support_mmap(struct snd_pcm_substream *substream)
263 {
264 	struct snd_dma_buffer *dmabuf;
265 
266 	if (!(substream->runtime->hw.info & SNDRV_PCM_INFO_MMAP))
267 		return false;
268 
269 	if (substream->ops->mmap || substream->ops->page)
270 		return true;
271 
272 	dmabuf = snd_pcm_get_dma_buf(substream);
273 	if (!dmabuf)
274 		dmabuf = &substream->dma_buffer;
275 	switch (dmabuf->dev.type) {
276 	case SNDRV_DMA_TYPE_UNKNOWN:
277 		/* we can't know the device, so just assume that the driver does
278 		 * everything right
279 		 */
280 		return true;
281 	case SNDRV_DMA_TYPE_CONTINUOUS:
282 	case SNDRV_DMA_TYPE_VMALLOC:
283 		return true;
284 	default:
285 		return dma_can_mmap(dmabuf->dev.dev);
286 	}
287 }
288 
289 static int constrain_mask_params(struct snd_pcm_substream *substream,
290 				 struct snd_pcm_hw_params *params)
291 {
292 	struct snd_pcm_hw_constraints *constrs =
293 					&substream->runtime->hw_constraints;
294 	struct snd_mask *m;
295 	unsigned int k;
296 	struct snd_mask old_mask __maybe_unused;
297 	int changed;
298 
299 	for (k = SNDRV_PCM_HW_PARAM_FIRST_MASK; k <= SNDRV_PCM_HW_PARAM_LAST_MASK; k++) {
300 		m = hw_param_mask(params, k);
301 		if (snd_mask_empty(m))
302 			return -EINVAL;
303 
304 		/* This parameter is not requested to change by a caller. */
305 		if (!(params->rmask & PARAM_MASK_BIT(k)))
306 			continue;
307 
308 		if (trace_hw_mask_param_enabled())
309 			old_mask = *m;
310 
311 		changed = snd_mask_refine(m, constrs_mask(constrs, k));
312 		if (changed < 0)
313 			return changed;
314 		if (changed == 0)
315 			continue;
316 
317 		/* Set corresponding flag so that the caller gets it. */
318 		trace_hw_mask_param(substream, k, 0, &old_mask, m);
319 		params->cmask |= PARAM_MASK_BIT(k);
320 	}
321 
322 	return 0;
323 }
324 
325 static int constrain_interval_params(struct snd_pcm_substream *substream,
326 				     struct snd_pcm_hw_params *params)
327 {
328 	struct snd_pcm_hw_constraints *constrs =
329 					&substream->runtime->hw_constraints;
330 	struct snd_interval *i;
331 	unsigned int k;
332 	struct snd_interval old_interval __maybe_unused;
333 	int changed;
334 
335 	for (k = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; k <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; k++) {
336 		i = hw_param_interval(params, k);
337 		if (snd_interval_empty(i))
338 			return -EINVAL;
339 
340 		/* This parameter is not requested to change by a caller. */
341 		if (!(params->rmask & PARAM_MASK_BIT(k)))
342 			continue;
343 
344 		if (trace_hw_interval_param_enabled())
345 			old_interval = *i;
346 
347 		changed = snd_interval_refine(i, constrs_interval(constrs, k));
348 		if (changed < 0)
349 			return changed;
350 		if (changed == 0)
351 			continue;
352 
353 		/* Set corresponding flag so that the caller gets it. */
354 		trace_hw_interval_param(substream, k, 0, &old_interval, i);
355 		params->cmask |= PARAM_MASK_BIT(k);
356 	}
357 
358 	return 0;
359 }
360 
361 static int constrain_params_by_rules(struct snd_pcm_substream *substream,
362 				     struct snd_pcm_hw_params *params)
363 {
364 	struct snd_pcm_hw_constraints *constrs =
365 					&substream->runtime->hw_constraints;
366 	unsigned int k;
367 	unsigned int vstamps[SNDRV_PCM_HW_PARAM_LAST_INTERVAL + 1];
368 	unsigned int stamp;
369 	struct snd_pcm_hw_rule *r;
370 	unsigned int d;
371 	struct snd_mask old_mask __maybe_unused;
372 	struct snd_interval old_interval __maybe_unused;
373 	bool again;
374 	int changed, err = 0;
375 
376 	/*
377 	 * Each application of rule has own sequence number.
378 	 *
379 	 * Each member of 'rstamps' array represents the sequence number of
380 	 * recent application of corresponding rule.
381 	 */
382 	unsigned int *rstamps __free(kfree) =
383 		kcalloc(constrs->rules_num, sizeof(unsigned int), GFP_KERNEL);
384 	if (!rstamps)
385 		return -ENOMEM;
386 
387 	/*
388 	 * Each member of 'vstamps' array represents the sequence number of
389 	 * recent application of rule in which corresponding parameters were
390 	 * changed.
391 	 *
392 	 * In initial state, elements corresponding to parameters requested by
393 	 * a caller is 1. For unrequested parameters, corresponding members
394 	 * have 0 so that the parameters are never changed anymore.
395 	 */
396 	for (k = 0; k <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; k++)
397 		vstamps[k] = (params->rmask & PARAM_MASK_BIT(k)) ? 1 : 0;
398 
399 	/* Due to the above design, actual sequence number starts at 2. */
400 	stamp = 2;
401 retry:
402 	/* Apply all rules in order. */
403 	again = false;
404 	for (k = 0; k < constrs->rules_num; k++) {
405 		r = &constrs->rules[k];
406 
407 		/*
408 		 * Check condition bits of this rule. When the rule has
409 		 * some condition bits, parameter without the bits is
410 		 * never processed. SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP
411 		 * is an example of the condition bits.
412 		 */
413 		if (r->cond && !(r->cond & params->flags))
414 			continue;
415 
416 		/*
417 		 * The 'deps' array includes maximum four dependencies
418 		 * to SNDRV_PCM_HW_PARAM_XXXs for this rule. The fifth
419 		 * member of this array is a sentinel and should be
420 		 * negative value.
421 		 *
422 		 * This rule should be processed in this time when dependent
423 		 * parameters were changed at former applications of the other
424 		 * rules.
425 		 */
426 		for (d = 0; r->deps[d] >= 0; d++) {
427 			if (vstamps[r->deps[d]] > rstamps[k])
428 				break;
429 		}
430 		if (r->deps[d] < 0)
431 			continue;
432 
433 		if (trace_hw_mask_param_enabled()) {
434 			if (hw_is_mask(r->var))
435 				old_mask = *hw_param_mask(params, r->var);
436 		}
437 		if (trace_hw_interval_param_enabled()) {
438 			if (hw_is_interval(r->var))
439 				old_interval = *hw_param_interval(params, r->var);
440 		}
441 
442 		changed = r->func(params, r);
443 		if (changed < 0)
444 			return changed;
445 
446 		/*
447 		 * When the parameter is changed, notify it to the caller
448 		 * by corresponding returned bit, then preparing for next
449 		 * iteration.
450 		 */
451 		if (changed && r->var >= 0) {
452 			if (hw_is_mask(r->var)) {
453 				trace_hw_mask_param(substream, r->var,
454 					k + 1, &old_mask,
455 					hw_param_mask(params, r->var));
456 			}
457 			if (hw_is_interval(r->var)) {
458 				trace_hw_interval_param(substream, r->var,
459 					k + 1, &old_interval,
460 					hw_param_interval(params, r->var));
461 			}
462 
463 			params->cmask |= PARAM_MASK_BIT(r->var);
464 			vstamps[r->var] = stamp;
465 			again = true;
466 		}
467 
468 		rstamps[k] = stamp++;
469 	}
470 
471 	/* Iterate to evaluate all rules till no parameters are changed. */
472 	if (again)
473 		goto retry;
474 
475 	return err;
476 }
477 
478 static int fixup_unreferenced_params(struct snd_pcm_substream *substream,
479 				     struct snd_pcm_hw_params *params)
480 {
481 	const struct snd_interval *i;
482 	const struct snd_mask *m;
483 	struct snd_mask *m_rw;
484 	int err;
485 
486 	if (!params->msbits) {
487 		i = hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS);
488 		if (snd_interval_single(i))
489 			params->msbits = snd_interval_value(i);
490 		m = hw_param_mask_c(params, SNDRV_PCM_HW_PARAM_FORMAT);
491 		if (snd_mask_single(m)) {
492 			snd_pcm_format_t format = (__force snd_pcm_format_t)snd_mask_min(m);
493 			params->msbits = snd_pcm_format_width(format);
494 		}
495 	}
496 
497 	if (params->msbits) {
498 		m = hw_param_mask_c(params, SNDRV_PCM_HW_PARAM_FORMAT);
499 		if (snd_mask_single(m)) {
500 			snd_pcm_format_t format = (__force snd_pcm_format_t)snd_mask_min(m);
501 
502 			if (snd_pcm_format_linear(format) &&
503 			    snd_pcm_format_width(format) != params->msbits) {
504 				m_rw = hw_param_mask(params, SNDRV_PCM_HW_PARAM_SUBFORMAT);
505 				snd_mask_reset(m_rw,
506 					       (__force unsigned)SNDRV_PCM_SUBFORMAT_MSBITS_MAX);
507 				if (snd_mask_empty(m_rw))
508 					return -EINVAL;
509 			}
510 		}
511 	}
512 
513 	if (!params->rate_den) {
514 		i = hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_RATE);
515 		if (snd_interval_single(i)) {
516 			params->rate_num = snd_interval_value(i);
517 			params->rate_den = 1;
518 		}
519 	}
520 
521 	if (!params->fifo_size) {
522 		m = hw_param_mask_c(params, SNDRV_PCM_HW_PARAM_FORMAT);
523 		i = hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_CHANNELS);
524 		if (snd_mask_single(m) && snd_interval_single(i)) {
525 			err = snd_pcm_ops_ioctl(substream,
526 						SNDRV_PCM_IOCTL1_FIFO_SIZE,
527 						params);
528 			if (err < 0)
529 				return err;
530 		}
531 	}
532 
533 	if (!params->info) {
534 		params->info = substream->runtime->hw.info;
535 		params->info &= ~(SNDRV_PCM_INFO_FIFO_IN_FRAMES |
536 				  SNDRV_PCM_INFO_DRAIN_TRIGGER);
537 		if (!hw_support_mmap(substream))
538 			params->info &= ~(SNDRV_PCM_INFO_MMAP |
539 					  SNDRV_PCM_INFO_MMAP_VALID);
540 	}
541 
542 	err = snd_pcm_ops_ioctl(substream,
543 				SNDRV_PCM_IOCTL1_SYNC_ID,
544 				params);
545 	if (err < 0)
546 		return err;
547 
548 	return 0;
549 }
550 
551 int snd_pcm_hw_refine(struct snd_pcm_substream *substream,
552 		      struct snd_pcm_hw_params *params)
553 {
554 	int err;
555 
556 	params->info = 0;
557 	params->fifo_size = 0;
558 	if (params->rmask & PARAM_MASK_BIT(SNDRV_PCM_HW_PARAM_SAMPLE_BITS))
559 		params->msbits = 0;
560 	if (params->rmask & PARAM_MASK_BIT(SNDRV_PCM_HW_PARAM_RATE)) {
561 		params->rate_num = 0;
562 		params->rate_den = 0;
563 	}
564 
565 	err = constrain_mask_params(substream, params);
566 	if (err < 0)
567 		return err;
568 
569 	err = constrain_interval_params(substream, params);
570 	if (err < 0)
571 		return err;
572 
573 	err = constrain_params_by_rules(substream, params);
574 	if (err < 0)
575 		return err;
576 
577 	params->rmask = 0;
578 
579 	return 0;
580 }
581 EXPORT_SYMBOL(snd_pcm_hw_refine);
582 
583 static int snd_pcm_hw_refine_user(struct snd_pcm_substream *substream,
584 				  struct snd_pcm_hw_params __user * _params)
585 {
586 	int err;
587 	struct snd_pcm_hw_params *params __free(kfree) =
588 		memdup_user(_params, sizeof(*params));
589 
590 	if (IS_ERR(params))
591 		return PTR_ERR(params);
592 
593 	err = snd_pcm_hw_refine(substream, params);
594 	if (err < 0)
595 		return err;
596 
597 	err = fixup_unreferenced_params(substream, params);
598 	if (err < 0)
599 		return err;
600 
601 	if (copy_to_user(_params, params, sizeof(*params)))
602 		return -EFAULT;
603 	return 0;
604 }
605 
606 static int period_to_usecs(struct snd_pcm_runtime *runtime)
607 {
608 	int usecs;
609 
610 	if (! runtime->rate)
611 		return -1; /* invalid */
612 
613 	/* take 75% of period time as the deadline */
614 	usecs = (750000 / runtime->rate) * runtime->period_size;
615 	usecs += ((750000 % runtime->rate) * runtime->period_size) /
616 		runtime->rate;
617 
618 	return usecs;
619 }
620 
621 /**
622  * snd_pcm_set_state - Set the PCM runtime state with stream lock
623  * @substream: PCM substream
624  * @state: state to set
625  */
626 void snd_pcm_set_state(struct snd_pcm_substream *substream,
627 		       snd_pcm_state_t state)
628 {
629 	guard(pcm_stream_lock_irq)(substream);
630 	if (substream->runtime->state != SNDRV_PCM_STATE_DISCONNECTED)
631 		__snd_pcm_set_state(substream->runtime, state);
632 }
633 EXPORT_SYMBOL_GPL(snd_pcm_set_state);
634 
635 /**
636  * snd_pcm_get_state - Read the PCM runtime state with stream lock
637  * @substream: PCM substream
638  *
639  * Return: the current PCM state
640  */
641 snd_pcm_state_t snd_pcm_get_state(struct snd_pcm_substream *substream)
642 {
643 	guard(pcm_stream_lock_irqsave)(substream);
644 	return substream->runtime->state;
645 }
646 EXPORT_SYMBOL_GPL(snd_pcm_get_state);
647 
648 static inline void snd_pcm_timer_notify(struct snd_pcm_substream *substream,
649 					int event)
650 {
651 #ifdef CONFIG_SND_PCM_TIMER
652 	if (substream->timer)
653 		snd_timer_notify(substream->timer, event,
654 					&substream->runtime->trigger_tstamp);
655 #endif
656 }
657 
658 void snd_pcm_sync_stop(struct snd_pcm_substream *substream, bool sync_irq)
659 {
660 	if (substream->runtime && substream->runtime->stop_operating) {
661 		substream->runtime->stop_operating = false;
662 		if (substream->ops && substream->ops->sync_stop)
663 			substream->ops->sync_stop(substream);
664 		else if (sync_irq && substream->pcm->card->sync_irq > 0)
665 			synchronize_irq(substream->pcm->card->sync_irq);
666 	}
667 }
668 
669 /**
670  * snd_pcm_hw_params_choose - choose a configuration defined by @params
671  * @pcm: PCM instance
672  * @params: the hw_params instance
673  *
674  * Choose one configuration from configuration space defined by @params.
675  * The configuration chosen is that obtained fixing in this order:
676  * first access, first format, first subformat, min channels,
677  * min rate, min period time, max buffer size, min tick time
678  *
679  * Return: Zero if successful, or a negative error code on failure.
680  */
681 static int snd_pcm_hw_params_choose(struct snd_pcm_substream *pcm,
682 				    struct snd_pcm_hw_params *params)
683 {
684 	static const int vars[] = {
685 		SNDRV_PCM_HW_PARAM_ACCESS,
686 		SNDRV_PCM_HW_PARAM_FORMAT,
687 		SNDRV_PCM_HW_PARAM_SUBFORMAT,
688 		SNDRV_PCM_HW_PARAM_CHANNELS,
689 		SNDRV_PCM_HW_PARAM_RATE,
690 		SNDRV_PCM_HW_PARAM_PERIOD_TIME,
691 		SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
692 		SNDRV_PCM_HW_PARAM_TICK_TIME,
693 		-1
694 	};
695 	const int *v;
696 	struct snd_mask old_mask __maybe_unused;
697 	struct snd_interval old_interval __maybe_unused;
698 	int changed;
699 
700 	for (v = vars; *v != -1; v++) {
701 		/* Keep old parameter to trace. */
702 		if (trace_hw_mask_param_enabled()) {
703 			if (hw_is_mask(*v))
704 				old_mask = *hw_param_mask(params, *v);
705 		}
706 		if (trace_hw_interval_param_enabled()) {
707 			if (hw_is_interval(*v))
708 				old_interval = *hw_param_interval(params, *v);
709 		}
710 		if (*v != SNDRV_PCM_HW_PARAM_BUFFER_SIZE)
711 			changed = snd_pcm_hw_param_first(pcm, params, *v, NULL);
712 		else
713 			changed = snd_pcm_hw_param_last(pcm, params, *v, NULL);
714 		if (changed < 0)
715 			return changed;
716 		if (changed == 0)
717 			continue;
718 
719 		/* Trace the changed parameter. */
720 		if (hw_is_mask(*v)) {
721 			trace_hw_mask_param(pcm, *v, 0, &old_mask,
722 					    hw_param_mask(params, *v));
723 		}
724 		if (hw_is_interval(*v)) {
725 			trace_hw_interval_param(pcm, *v, 0, &old_interval,
726 						hw_param_interval(params, *v));
727 		}
728 	}
729 
730 	return 0;
731 }
732 
733 /* acquire buffer_mutex; if it's in r/w operation, return -EBUSY, otherwise
734  * block the further r/w operations
735  */
736 static int snd_pcm_buffer_access_lock(struct snd_pcm_runtime *runtime)
737 {
738 	if (!atomic_dec_unless_positive(&runtime->buffer_accessing))
739 		return -EBUSY;
740 	mutex_lock(&runtime->buffer_mutex);
741 	return 0; /* keep buffer_mutex, unlocked by below */
742 }
743 
744 /* release buffer_mutex and clear r/w access flag */
745 static void snd_pcm_buffer_access_unlock(struct snd_pcm_runtime *runtime)
746 {
747 	mutex_unlock(&runtime->buffer_mutex);
748 	atomic_inc(&runtime->buffer_accessing);
749 }
750 
751 /* fill the PCM buffer with the current silence format; called from pcm_oss.c */
752 int snd_pcm_runtime_buffer_set_silence(struct snd_pcm_runtime *runtime)
753 {
754 	int err;
755 
756 	err = snd_pcm_buffer_access_lock(runtime);
757 	if (err < 0)
758 		return err;
759 	if (runtime->dma_area)
760 		snd_pcm_format_set_silence(runtime->format, runtime->dma_area,
761 					   bytes_to_samples(runtime, runtime->dma_bytes));
762 	snd_pcm_buffer_access_unlock(runtime);
763 	return 0;
764 }
765 EXPORT_SYMBOL_GPL(snd_pcm_runtime_buffer_set_silence);
766 
767 #if IS_ENABLED(CONFIG_SND_PCM_OSS)
768 #define is_oss_stream(substream)	((substream)->oss.oss)
769 #else
770 #define is_oss_stream(substream)	false
771 #endif
772 
773 static int snd_pcm_hw_params(struct snd_pcm_substream *substream,
774 			     struct snd_pcm_hw_params *params)
775 {
776 	struct snd_pcm_runtime *runtime;
777 	int err, usecs;
778 	unsigned int bits;
779 	snd_pcm_uframes_t frames;
780 
781 	if (PCM_RUNTIME_CHECK(substream))
782 		return -ENXIO;
783 	runtime = substream->runtime;
784 	err = snd_pcm_buffer_access_lock(runtime);
785 	if (err < 0)
786 		return err;
787 	scoped_guard(pcm_stream_lock_irq, substream) {
788 		switch (runtime->state) {
789 		case SNDRV_PCM_STATE_OPEN:
790 		case SNDRV_PCM_STATE_SETUP:
791 		case SNDRV_PCM_STATE_PREPARED:
792 			if (!is_oss_stream(substream) &&
793 			    atomic_read(&substream->mmap_count))
794 				err = -EBADFD;
795 			break;
796 		default:
797 			err = -EBADFD;
798 			break;
799 		}
800 	}
801 	if (err)
802 		goto unlock;
803 
804 	snd_pcm_sync_stop(substream, true);
805 
806 	params->rmask = ~0U;
807 	err = snd_pcm_hw_refine(substream, params);
808 	if (err < 0)
809 		goto _error;
810 
811 	err = snd_pcm_hw_params_choose(substream, params);
812 	if (err < 0)
813 		goto _error;
814 
815 	err = fixup_unreferenced_params(substream, params);
816 	if (err < 0)
817 		goto _error;
818 
819 	if (substream->managed_buffer_alloc) {
820 		err = snd_pcm_lib_malloc_pages(substream,
821 					       params_buffer_bytes(params));
822 		if (err < 0)
823 			goto _error;
824 		runtime->buffer_changed = err > 0;
825 	}
826 
827 	if (substream->ops->hw_params != NULL) {
828 		err = substream->ops->hw_params(substream, params);
829 		if (err < 0)
830 			goto _error;
831 	}
832 
833 	runtime->access = params_access(params);
834 	runtime->format = params_format(params);
835 	runtime->subformat = params_subformat(params);
836 	runtime->channels = params_channels(params);
837 	runtime->rate = params_rate(params);
838 	runtime->period_size = params_period_size(params);
839 	runtime->periods = params_periods(params);
840 	runtime->buffer_size = params_buffer_size(params);
841 	runtime->info = params->info;
842 	runtime->rate_num = params->rate_num;
843 	runtime->rate_den = params->rate_den;
844 	runtime->no_period_wakeup =
845 			(params->info & SNDRV_PCM_INFO_NO_PERIOD_WAKEUP) &&
846 			(params->flags & SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP);
847 
848 	bits = snd_pcm_format_physical_width(runtime->format);
849 	runtime->sample_bits = bits;
850 	bits *= runtime->channels;
851 	runtime->frame_bits = bits;
852 	frames = 1;
853 	while (bits % 8 != 0) {
854 		bits *= 2;
855 		frames *= 2;
856 	}
857 	runtime->byte_align = bits / 8;
858 	runtime->min_align = frames;
859 
860 	/* Default sw params */
861 	runtime->tstamp_mode = SNDRV_PCM_TSTAMP_NONE;
862 	runtime->period_step = 1;
863 	runtime->control->avail_min = runtime->period_size;
864 	runtime->start_threshold = 1;
865 	runtime->stop_threshold = runtime->buffer_size;
866 	runtime->silence_threshold = 0;
867 	runtime->silence_size = 0;
868 	runtime->boundary = runtime->buffer_size;
869 	while (runtime->boundary * 2 <= LONG_MAX - runtime->buffer_size)
870 		runtime->boundary *= 2;
871 
872 	/* clear the buffer for avoiding possible kernel info leaks */
873 	if (runtime->dma_area && !substream->ops->copy) {
874 		size_t size = runtime->dma_bytes;
875 
876 		if (runtime->info & SNDRV_PCM_INFO_MMAP)
877 			size = PAGE_ALIGN(size);
878 		memset(runtime->dma_area, 0, size);
879 	}
880 
881 	snd_pcm_timer_resolution_change(substream);
882 	snd_pcm_set_state(substream, SNDRV_PCM_STATE_SETUP);
883 
884 	if (cpu_latency_qos_request_active(&substream->latency_pm_qos_req))
885 		cpu_latency_qos_remove_request(&substream->latency_pm_qos_req);
886 	usecs = period_to_usecs(runtime);
887 	if (usecs >= 0)
888 		cpu_latency_qos_add_request(&substream->latency_pm_qos_req,
889 					    usecs);
890 	err = 0;
891  _error:
892 	if (err) {
893 		/* hardware might be unusable from this time,
894 		 * so we force application to retry to set
895 		 * the correct hardware parameter settings
896 		 */
897 		snd_pcm_set_state(substream, SNDRV_PCM_STATE_OPEN);
898 		if (substream->ops->hw_free != NULL)
899 			substream->ops->hw_free(substream);
900 		if (substream->managed_buffer_alloc)
901 			snd_pcm_lib_free_pages(substream);
902 	}
903  unlock:
904 	snd_pcm_buffer_access_unlock(runtime);
905 	return err;
906 }
907 
908 static int snd_pcm_hw_params_user(struct snd_pcm_substream *substream,
909 				  struct snd_pcm_hw_params __user * _params)
910 {
911 	int err;
912 	struct snd_pcm_hw_params *params __free(kfree) =
913 		memdup_user(_params, sizeof(*params));
914 
915 	if (IS_ERR(params))
916 		return PTR_ERR(params);
917 
918 	err = snd_pcm_hw_params(substream, params);
919 	if (err < 0)
920 		return err;
921 
922 	if (copy_to_user(_params, params, sizeof(*params)))
923 		return -EFAULT;
924 	return err;
925 }
926 
927 static int do_hw_free(struct snd_pcm_substream *substream)
928 {
929 	int result = 0;
930 
931 	snd_pcm_sync_stop(substream, true);
932 	if (substream->ops->hw_free)
933 		result = substream->ops->hw_free(substream);
934 	if (substream->managed_buffer_alloc)
935 		snd_pcm_lib_free_pages(substream);
936 	return result;
937 }
938 
939 static int snd_pcm_hw_free(struct snd_pcm_substream *substream)
940 {
941 	struct snd_pcm_runtime *runtime;
942 	int result = 0;
943 
944 	if (PCM_RUNTIME_CHECK(substream))
945 		return -ENXIO;
946 	runtime = substream->runtime;
947 	result = snd_pcm_buffer_access_lock(runtime);
948 	if (result < 0)
949 		return result;
950 	scoped_guard(pcm_stream_lock_irq, substream) {
951 		switch (runtime->state) {
952 		case SNDRV_PCM_STATE_SETUP:
953 		case SNDRV_PCM_STATE_PREPARED:
954 			if (atomic_read(&substream->mmap_count))
955 				result = -EBADFD;
956 			break;
957 		default:
958 			result = -EBADFD;
959 			break;
960 		}
961 	}
962 	if (result)
963 		goto unlock;
964 	result = do_hw_free(substream);
965 	snd_pcm_set_state(substream, SNDRV_PCM_STATE_OPEN);
966 	cpu_latency_qos_remove_request(&substream->latency_pm_qos_req);
967  unlock:
968 	snd_pcm_buffer_access_unlock(runtime);
969 	return result;
970 }
971 
972 static int snd_pcm_sw_params(struct snd_pcm_substream *substream,
973 			     struct snd_pcm_sw_params *params)
974 {
975 	struct snd_pcm_runtime *runtime;
976 	int err;
977 
978 	if (PCM_RUNTIME_CHECK(substream))
979 		return -ENXIO;
980 	runtime = substream->runtime;
981 	scoped_guard(pcm_stream_lock_irq, substream) {
982 		if (runtime->state == SNDRV_PCM_STATE_OPEN)
983 			return -EBADFD;
984 	}
985 
986 	if (params->tstamp_mode < 0 ||
987 	    params->tstamp_mode > SNDRV_PCM_TSTAMP_LAST)
988 		return -EINVAL;
989 	if (params->proto >= SNDRV_PROTOCOL_VERSION(2, 0, 12) &&
990 	    params->tstamp_type > SNDRV_PCM_TSTAMP_TYPE_LAST)
991 		return -EINVAL;
992 	if (params->avail_min == 0)
993 		return -EINVAL;
994 	if (params->silence_size >= runtime->boundary) {
995 		if (params->silence_threshold != 0)
996 			return -EINVAL;
997 	} else {
998 		if (params->silence_size > params->silence_threshold)
999 			return -EINVAL;
1000 		if (params->silence_threshold > runtime->buffer_size)
1001 			return -EINVAL;
1002 	}
1003 	err = 0;
1004 	scoped_guard(pcm_stream_lock_irq, substream) {
1005 		runtime->tstamp_mode = params->tstamp_mode;
1006 		if (params->proto >= SNDRV_PROTOCOL_VERSION(2, 0, 12))
1007 			runtime->tstamp_type = params->tstamp_type;
1008 		runtime->period_step = params->period_step;
1009 		runtime->control->avail_min = params->avail_min;
1010 		runtime->start_threshold = params->start_threshold;
1011 		runtime->stop_threshold = params->stop_threshold;
1012 		runtime->silence_threshold = params->silence_threshold;
1013 		runtime->silence_size = params->silence_size;
1014 		params->boundary = runtime->boundary;
1015 		if (snd_pcm_running(substream)) {
1016 			if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK &&
1017 			    runtime->silence_size > 0)
1018 				snd_pcm_playback_silence(substream, ULONG_MAX);
1019 			err = snd_pcm_update_state(substream, runtime);
1020 		}
1021 	}
1022 	return err;
1023 }
1024 
1025 static int snd_pcm_sw_params_user(struct snd_pcm_substream *substream,
1026 				  struct snd_pcm_sw_params __user * _params)
1027 {
1028 	struct snd_pcm_sw_params params;
1029 	int err;
1030 	if (copy_from_user(&params, _params, sizeof(params)))
1031 		return -EFAULT;
1032 	err = snd_pcm_sw_params(substream, &params);
1033 	if (copy_to_user(_params, &params, sizeof(params)))
1034 		return -EFAULT;
1035 	return err;
1036 }
1037 
1038 static inline snd_pcm_uframes_t
1039 snd_pcm_calc_delay(struct snd_pcm_substream *substream)
1040 {
1041 	snd_pcm_uframes_t delay;
1042 
1043 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
1044 		delay = snd_pcm_playback_hw_avail(substream->runtime);
1045 	else
1046 		delay = snd_pcm_capture_avail(substream->runtime);
1047 	return delay + substream->runtime->delay;
1048 }
1049 
1050 int snd_pcm_status64(struct snd_pcm_substream *substream,
1051 		     struct snd_pcm_status64 *status)
1052 {
1053 	struct snd_pcm_runtime *runtime = substream->runtime;
1054 
1055 	guard(pcm_stream_lock_irq)(substream);
1056 
1057 	snd_pcm_unpack_audio_tstamp_config(status->audio_tstamp_data,
1058 					&runtime->audio_tstamp_config);
1059 
1060 	/* backwards compatible behavior */
1061 	if (runtime->audio_tstamp_config.type_requested ==
1062 		SNDRV_PCM_AUDIO_TSTAMP_TYPE_COMPAT) {
1063 		if (runtime->hw.info & SNDRV_PCM_INFO_HAS_WALL_CLOCK)
1064 			runtime->audio_tstamp_config.type_requested =
1065 				SNDRV_PCM_AUDIO_TSTAMP_TYPE_LINK;
1066 		else
1067 			runtime->audio_tstamp_config.type_requested =
1068 				SNDRV_PCM_AUDIO_TSTAMP_TYPE_DEFAULT;
1069 		runtime->audio_tstamp_report.valid = 0;
1070 	} else
1071 		runtime->audio_tstamp_report.valid = 1;
1072 
1073 	status->state = runtime->state;
1074 	status->suspended_state = runtime->suspended_state;
1075 	if (status->state == SNDRV_PCM_STATE_OPEN)
1076 		return 0;
1077 	status->trigger_tstamp_sec = runtime->trigger_tstamp.tv_sec;
1078 	status->trigger_tstamp_nsec = runtime->trigger_tstamp.tv_nsec;
1079 	if (snd_pcm_running(substream)) {
1080 		snd_pcm_update_hw_ptr(substream);
1081 		if (runtime->tstamp_mode == SNDRV_PCM_TSTAMP_ENABLE) {
1082 			status->tstamp_sec = runtime->status->tstamp.tv_sec;
1083 			status->tstamp_nsec =
1084 				runtime->status->tstamp.tv_nsec;
1085 			status->driver_tstamp_sec =
1086 				runtime->driver_tstamp.tv_sec;
1087 			status->driver_tstamp_nsec =
1088 				runtime->driver_tstamp.tv_nsec;
1089 			status->audio_tstamp_sec =
1090 				runtime->status->audio_tstamp.tv_sec;
1091 			status->audio_tstamp_nsec =
1092 				runtime->status->audio_tstamp.tv_nsec;
1093 			if (runtime->audio_tstamp_report.valid == 1)
1094 				/* backwards compatibility, no report provided in COMPAT mode */
1095 				snd_pcm_pack_audio_tstamp_report(&status->audio_tstamp_data,
1096 								&status->audio_tstamp_accuracy,
1097 								&runtime->audio_tstamp_report);
1098 
1099 			goto _tstamp_end;
1100 		}
1101 	} else {
1102 		/* get tstamp only in fallback mode and only if enabled */
1103 		if (runtime->tstamp_mode == SNDRV_PCM_TSTAMP_ENABLE) {
1104 			struct timespec64 tstamp;
1105 
1106 			snd_pcm_gettime(runtime, &tstamp);
1107 			status->tstamp_sec = tstamp.tv_sec;
1108 			status->tstamp_nsec = tstamp.tv_nsec;
1109 		}
1110 	}
1111  _tstamp_end:
1112 	status->appl_ptr = runtime->control->appl_ptr;
1113 	status->hw_ptr = runtime->status->hw_ptr;
1114 	status->avail = snd_pcm_avail(substream);
1115 	status->delay = snd_pcm_running(substream) ?
1116 		snd_pcm_calc_delay(substream) : 0;
1117 	status->avail_max = runtime->avail_max;
1118 	status->overrange = runtime->overrange;
1119 	runtime->avail_max = 0;
1120 	runtime->overrange = 0;
1121 	return 0;
1122 }
1123 
1124 static int snd_pcm_status_user64(struct snd_pcm_substream *substream,
1125 				 struct snd_pcm_status64 __user * _status,
1126 				 bool ext)
1127 {
1128 	struct snd_pcm_status64 status;
1129 	int res;
1130 
1131 	memset(&status, 0, sizeof(status));
1132 	/*
1133 	 * with extension, parameters are read/write,
1134 	 * get audio_tstamp_data from user,
1135 	 * ignore rest of status structure
1136 	 */
1137 	if (ext && get_user(status.audio_tstamp_data,
1138 				(u32 __user *)(&_status->audio_tstamp_data)))
1139 		return -EFAULT;
1140 	res = snd_pcm_status64(substream, &status);
1141 	if (res < 0)
1142 		return res;
1143 	if (copy_to_user(_status, &status, sizeof(status)))
1144 		return -EFAULT;
1145 	return 0;
1146 }
1147 
1148 static int snd_pcm_status_user32(struct snd_pcm_substream *substream,
1149 				 struct snd_pcm_status32 __user * _status,
1150 				 bool ext)
1151 {
1152 	struct snd_pcm_status64 status64;
1153 	struct snd_pcm_status32 status32;
1154 	int res;
1155 
1156 	memset(&status64, 0, sizeof(status64));
1157 	memset(&status32, 0, sizeof(status32));
1158 	/*
1159 	 * with extension, parameters are read/write,
1160 	 * get audio_tstamp_data from user,
1161 	 * ignore rest of status structure
1162 	 */
1163 	if (ext && get_user(status64.audio_tstamp_data,
1164 			    (u32 __user *)(&_status->audio_tstamp_data)))
1165 		return -EFAULT;
1166 	res = snd_pcm_status64(substream, &status64);
1167 	if (res < 0)
1168 		return res;
1169 
1170 	status32 = (struct snd_pcm_status32) {
1171 		.state = status64.state,
1172 		.trigger_tstamp_sec = status64.trigger_tstamp_sec,
1173 		.trigger_tstamp_nsec = status64.trigger_tstamp_nsec,
1174 		.tstamp_sec = status64.tstamp_sec,
1175 		.tstamp_nsec = status64.tstamp_nsec,
1176 		.appl_ptr = status64.appl_ptr,
1177 		.hw_ptr = status64.hw_ptr,
1178 		.delay = status64.delay,
1179 		.avail = status64.avail,
1180 		.avail_max = status64.avail_max,
1181 		.overrange = status64.overrange,
1182 		.suspended_state = status64.suspended_state,
1183 		.audio_tstamp_data = status64.audio_tstamp_data,
1184 		.audio_tstamp_sec = status64.audio_tstamp_sec,
1185 		.audio_tstamp_nsec = status64.audio_tstamp_nsec,
1186 		.driver_tstamp_sec = status64.audio_tstamp_sec,
1187 		.driver_tstamp_nsec = status64.audio_tstamp_nsec,
1188 		.audio_tstamp_accuracy = status64.audio_tstamp_accuracy,
1189 	};
1190 
1191 	if (copy_to_user(_status, &status32, sizeof(status32)))
1192 		return -EFAULT;
1193 
1194 	return 0;
1195 }
1196 
1197 static int snd_pcm_channel_info(struct snd_pcm_substream *substream,
1198 				struct snd_pcm_channel_info * info)
1199 {
1200 	struct snd_pcm_runtime *runtime;
1201 	unsigned int channel;
1202 
1203 	channel = info->channel;
1204 	runtime = substream->runtime;
1205 	scoped_guard(pcm_stream_lock_irq, substream) {
1206 		if (runtime->state == SNDRV_PCM_STATE_OPEN)
1207 			return -EBADFD;
1208 	}
1209 	if (channel >= runtime->channels)
1210 		return -EINVAL;
1211 	memset(info, 0, sizeof(*info));
1212 	info->channel = channel;
1213 	return snd_pcm_ops_ioctl(substream, SNDRV_PCM_IOCTL1_CHANNEL_INFO, info);
1214 }
1215 
1216 static int snd_pcm_channel_info_user(struct snd_pcm_substream *substream,
1217 				     struct snd_pcm_channel_info __user * _info)
1218 {
1219 	struct snd_pcm_channel_info info;
1220 	int res;
1221 
1222 	if (copy_from_user(&info, _info, sizeof(info)))
1223 		return -EFAULT;
1224 	res = snd_pcm_channel_info(substream, &info);
1225 	if (res < 0)
1226 		return res;
1227 	if (copy_to_user(_info, &info, sizeof(info)))
1228 		return -EFAULT;
1229 	return 0;
1230 }
1231 
1232 static void snd_pcm_trigger_tstamp(struct snd_pcm_substream *substream)
1233 {
1234 	struct snd_pcm_runtime *runtime = substream->runtime;
1235 	if (runtime->trigger_master == NULL)
1236 		return;
1237 	if (runtime->trigger_master == substream) {
1238 		if (!runtime->trigger_tstamp_latched)
1239 			snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
1240 	} else {
1241 		snd_pcm_trigger_tstamp(runtime->trigger_master);
1242 		runtime->trigger_tstamp = runtime->trigger_master->runtime->trigger_tstamp;
1243 	}
1244 	runtime->trigger_master = NULL;
1245 }
1246 
1247 #define ACTION_ARG_IGNORE	(__force snd_pcm_state_t)0
1248 
1249 struct action_ops {
1250 	int (*pre_action)(struct snd_pcm_substream *substream,
1251 			  snd_pcm_state_t state);
1252 	int (*do_action)(struct snd_pcm_substream *substream,
1253 			 snd_pcm_state_t state);
1254 	void (*undo_action)(struct snd_pcm_substream *substream,
1255 			    snd_pcm_state_t state);
1256 	void (*post_action)(struct snd_pcm_substream *substream,
1257 			    snd_pcm_state_t state);
1258 };
1259 
1260 /*
1261  *  this functions is core for handling of linked stream
1262  *  Note: the stream state might be changed also on failure
1263  *  Note2: call with calling stream lock + link lock
1264  */
1265 static int snd_pcm_action_group(const struct action_ops *ops,
1266 				struct snd_pcm_substream *substream,
1267 				snd_pcm_state_t state,
1268 				bool stream_lock)
1269 {
1270 	struct snd_pcm_substream *s = NULL;
1271 	struct snd_pcm_substream *s1;
1272 	int res = 0, depth = 1;
1273 
1274 	snd_pcm_group_for_each_entry(s, substream) {
1275 		if (s != substream) {
1276 			if (!stream_lock)
1277 				mutex_lock_nested(&s->runtime->buffer_mutex, depth);
1278 			else if (s->pcm->nonatomic)
1279 				mutex_lock_nested(&s->self_group.mutex, depth);
1280 			else
1281 				spin_lock_nested(&s->self_group.lock, depth);
1282 			depth++;
1283 		}
1284 		res = ops->pre_action(s, state);
1285 		if (res < 0)
1286 			goto _unlock;
1287 	}
1288 	snd_pcm_group_for_each_entry(s, substream) {
1289 		res = ops->do_action(s, state);
1290 		if (res < 0) {
1291 			if (ops->undo_action) {
1292 				snd_pcm_group_for_each_entry(s1, substream) {
1293 					if (s1 == s) /* failed stream */
1294 						break;
1295 					ops->undo_action(s1, state);
1296 				}
1297 			}
1298 			s = NULL; /* unlock all */
1299 			goto _unlock;
1300 		}
1301 	}
1302 	snd_pcm_group_for_each_entry(s, substream) {
1303 		ops->post_action(s, state);
1304 	}
1305  _unlock:
1306 	/* unlock streams */
1307 	snd_pcm_group_for_each_entry(s1, substream) {
1308 		if (s1 != substream) {
1309 			if (!stream_lock)
1310 				mutex_unlock(&s1->runtime->buffer_mutex);
1311 			else if (s1->pcm->nonatomic)
1312 				mutex_unlock(&s1->self_group.mutex);
1313 			else
1314 				spin_unlock(&s1->self_group.lock);
1315 		}
1316 		if (s1 == s)	/* end */
1317 			break;
1318 	}
1319 	return res;
1320 }
1321 
1322 /*
1323  *  Note: call with stream lock
1324  */
1325 static int snd_pcm_action_single(const struct action_ops *ops,
1326 				 struct snd_pcm_substream *substream,
1327 				 snd_pcm_state_t state)
1328 {
1329 	int res;
1330 
1331 	res = ops->pre_action(substream, state);
1332 	if (res < 0)
1333 		return res;
1334 	res = ops->do_action(substream, state);
1335 	if (res == 0)
1336 		ops->post_action(substream, state);
1337 	else if (ops->undo_action)
1338 		ops->undo_action(substream, state);
1339 	return res;
1340 }
1341 
1342 static void snd_pcm_group_assign(struct snd_pcm_substream *substream,
1343 				 struct snd_pcm_group *new_group)
1344 {
1345 	substream->group = new_group;
1346 	list_move(&substream->link_list, &new_group->substreams);
1347 }
1348 
1349 /*
1350  * Unref and unlock the group, but keep the stream lock;
1351  * when the group becomes empty and no longer referred, destroy itself
1352  */
1353 static void snd_pcm_group_unref(struct snd_pcm_group *group,
1354 				struct snd_pcm_substream *substream)
1355 {
1356 	bool do_free;
1357 
1358 	if (!group)
1359 		return;
1360 	do_free = refcount_dec_and_test(&group->refs);
1361 	snd_pcm_group_unlock(group, substream->pcm->nonatomic);
1362 	if (do_free)
1363 		kfree(group);
1364 }
1365 
1366 /*
1367  * Lock the group inside a stream lock and reference it;
1368  * return the locked group object, or NULL if not linked
1369  */
1370 static struct snd_pcm_group *
1371 snd_pcm_stream_group_ref(struct snd_pcm_substream *substream)
1372 {
1373 	bool nonatomic = substream->pcm->nonatomic;
1374 	struct snd_pcm_group *group;
1375 	bool trylock;
1376 
1377 	for (;;) {
1378 		if (!snd_pcm_stream_linked(substream))
1379 			return NULL;
1380 		group = substream->group;
1381 		/* block freeing the group object */
1382 		refcount_inc(&group->refs);
1383 
1384 		trylock = nonatomic ? mutex_trylock(&group->mutex) :
1385 			spin_trylock(&group->lock);
1386 		if (trylock)
1387 			break; /* OK */
1388 
1389 		/* re-lock for avoiding ABBA deadlock */
1390 		snd_pcm_stream_unlock(substream);
1391 		snd_pcm_group_lock(group, nonatomic);
1392 		snd_pcm_stream_lock(substream);
1393 
1394 		/* check the group again; the above opens a small race window */
1395 		if (substream->group == group)
1396 			break; /* OK */
1397 		/* group changed, try again */
1398 		snd_pcm_group_unref(group, substream);
1399 	}
1400 	return group;
1401 }
1402 
1403 /*
1404  *  Note: call with stream lock
1405  */
1406 static int snd_pcm_action(const struct action_ops *ops,
1407 			  struct snd_pcm_substream *substream,
1408 			  snd_pcm_state_t state)
1409 {
1410 	struct snd_pcm_group *group;
1411 	int res;
1412 
1413 	group = snd_pcm_stream_group_ref(substream);
1414 	if (group)
1415 		res = snd_pcm_action_group(ops, substream, state, true);
1416 	else
1417 		res = snd_pcm_action_single(ops, substream, state);
1418 	snd_pcm_group_unref(group, substream);
1419 	return res;
1420 }
1421 
1422 /*
1423  *  Note: don't use any locks before
1424  */
1425 static int snd_pcm_action_lock_irq(const struct action_ops *ops,
1426 				   struct snd_pcm_substream *substream,
1427 				   snd_pcm_state_t state)
1428 {
1429 	guard(pcm_stream_lock_irq)(substream);
1430 	return snd_pcm_action(ops, substream, state);
1431 }
1432 
1433 /*
1434  */
1435 static int snd_pcm_action_nonatomic(const struct action_ops *ops,
1436 				    struct snd_pcm_substream *substream,
1437 				    snd_pcm_state_t state)
1438 {
1439 	int res;
1440 
1441 	/* Guarantee the group members won't change during non-atomic action */
1442 	guard(rwsem_read)(&snd_pcm_link_rwsem);
1443 	res = snd_pcm_buffer_access_lock(substream->runtime);
1444 	if (res < 0)
1445 		return res;
1446 	if (snd_pcm_stream_linked(substream))
1447 		res = snd_pcm_action_group(ops, substream, state, false);
1448 	else
1449 		res = snd_pcm_action_single(ops, substream, state);
1450 	snd_pcm_buffer_access_unlock(substream->runtime);
1451 	return res;
1452 }
1453 
1454 /*
1455  * start callbacks
1456  */
1457 static int snd_pcm_pre_start(struct snd_pcm_substream *substream,
1458 			     snd_pcm_state_t state)
1459 {
1460 	struct snd_pcm_runtime *runtime = substream->runtime;
1461 	if (runtime->state != SNDRV_PCM_STATE_PREPARED)
1462 		return -EBADFD;
1463 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK &&
1464 	    !snd_pcm_playback_data(substream))
1465 		return -EPIPE;
1466 	runtime->trigger_tstamp_latched = false;
1467 	runtime->trigger_master = substream;
1468 	return 0;
1469 }
1470 
1471 static int snd_pcm_do_start(struct snd_pcm_substream *substream,
1472 			    snd_pcm_state_t state)
1473 {
1474 	int err;
1475 
1476 	if (substream->runtime->trigger_master != substream)
1477 		return 0;
1478 	err = substream->ops->trigger(substream, SNDRV_PCM_TRIGGER_START);
1479 	/* XRUN happened during the start */
1480 	if (err == -EPIPE)
1481 		__snd_pcm_set_state(substream->runtime, SNDRV_PCM_STATE_XRUN);
1482 	return err;
1483 }
1484 
1485 static void snd_pcm_undo_start(struct snd_pcm_substream *substream,
1486 			       snd_pcm_state_t state)
1487 {
1488 	if (substream->runtime->trigger_master == substream) {
1489 		substream->ops->trigger(substream, SNDRV_PCM_TRIGGER_STOP);
1490 		substream->runtime->stop_operating = true;
1491 	}
1492 }
1493 
1494 static void snd_pcm_post_start(struct snd_pcm_substream *substream,
1495 			       snd_pcm_state_t state)
1496 {
1497 	struct snd_pcm_runtime *runtime = substream->runtime;
1498 	snd_pcm_trigger_tstamp(substream);
1499 	runtime->hw_ptr_jiffies = jiffies;
1500 	runtime->hw_ptr_buffer_jiffies = (runtime->buffer_size * HZ) /
1501 							    runtime->rate;
1502 	__snd_pcm_set_state(runtime, state);
1503 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK &&
1504 	    runtime->silence_size > 0)
1505 		snd_pcm_playback_silence(substream, ULONG_MAX);
1506 	snd_pcm_timer_notify(substream, SNDRV_TIMER_EVENT_MSTART);
1507 }
1508 
1509 static const struct action_ops snd_pcm_action_start = {
1510 	.pre_action = snd_pcm_pre_start,
1511 	.do_action = snd_pcm_do_start,
1512 	.undo_action = snd_pcm_undo_start,
1513 	.post_action = snd_pcm_post_start
1514 };
1515 
1516 /**
1517  * snd_pcm_start - start all linked streams
1518  * @substream: the PCM substream instance
1519  *
1520  * Return: Zero if successful, or a negative error code.
1521  * The stream lock must be acquired before calling this function.
1522  */
1523 int snd_pcm_start(struct snd_pcm_substream *substream)
1524 {
1525 	return snd_pcm_action(&snd_pcm_action_start, substream,
1526 			      SNDRV_PCM_STATE_RUNNING);
1527 }
1528 
1529 /* take the stream lock and start the streams */
1530 static int snd_pcm_start_lock_irq(struct snd_pcm_substream *substream)
1531 {
1532 	return snd_pcm_action_lock_irq(&snd_pcm_action_start, substream,
1533 				       SNDRV_PCM_STATE_RUNNING);
1534 }
1535 
1536 /*
1537  * stop callbacks
1538  */
1539 static int snd_pcm_pre_stop(struct snd_pcm_substream *substream,
1540 			    snd_pcm_state_t state)
1541 {
1542 	struct snd_pcm_runtime *runtime = substream->runtime;
1543 	if (runtime->state == SNDRV_PCM_STATE_OPEN)
1544 		return -EBADFD;
1545 	runtime->trigger_master = substream;
1546 	return 0;
1547 }
1548 
1549 static int snd_pcm_do_stop(struct snd_pcm_substream *substream,
1550 			   snd_pcm_state_t state)
1551 {
1552 	if (substream->runtime->trigger_master == substream &&
1553 	    snd_pcm_running(substream)) {
1554 		substream->ops->trigger(substream, SNDRV_PCM_TRIGGER_STOP);
1555 		substream->runtime->stop_operating = true;
1556 	}
1557 	return 0; /* unconditionally stop all substreams */
1558 }
1559 
1560 static void snd_pcm_post_stop(struct snd_pcm_substream *substream,
1561 			      snd_pcm_state_t state)
1562 {
1563 	struct snd_pcm_runtime *runtime = substream->runtime;
1564 	if (runtime->state != state) {
1565 		snd_pcm_trigger_tstamp(substream);
1566 		__snd_pcm_set_state(runtime, state);
1567 		snd_pcm_timer_notify(substream, SNDRV_TIMER_EVENT_MSTOP);
1568 	}
1569 	wake_up(&runtime->sleep);
1570 	wake_up(&runtime->tsleep);
1571 }
1572 
1573 static const struct action_ops snd_pcm_action_stop = {
1574 	.pre_action = snd_pcm_pre_stop,
1575 	.do_action = snd_pcm_do_stop,
1576 	.post_action = snd_pcm_post_stop
1577 };
1578 
1579 /**
1580  * snd_pcm_stop - try to stop all running streams in the substream group
1581  * @substream: the PCM substream instance
1582  * @state: PCM state after stopping the stream
1583  *
1584  * The state of each stream is then changed to the given state unconditionally.
1585  *
1586  * Return: Zero if successful, or a negative error code.
1587  */
1588 int snd_pcm_stop(struct snd_pcm_substream *substream, snd_pcm_state_t state)
1589 {
1590 	return snd_pcm_action(&snd_pcm_action_stop, substream, state);
1591 }
1592 EXPORT_SYMBOL(snd_pcm_stop);
1593 
1594 /**
1595  * snd_pcm_drain_done - stop the DMA only when the given stream is playback
1596  * @substream: the PCM substream
1597  *
1598  * After stopping, the state is changed to SETUP.
1599  * Unlike snd_pcm_stop(), this affects only the given stream.
1600  *
1601  * Return: Zero if successful, or a negative error code.
1602  */
1603 int snd_pcm_drain_done(struct snd_pcm_substream *substream)
1604 {
1605 	return snd_pcm_action_single(&snd_pcm_action_stop, substream,
1606 				     SNDRV_PCM_STATE_SETUP);
1607 }
1608 
1609 /**
1610  * snd_pcm_stop_xrun - stop the running streams as XRUN
1611  * @substream: the PCM substream instance
1612  *
1613  * This stops the given running substream (and all linked substreams) as XRUN.
1614  * Unlike snd_pcm_stop(), this function takes the substream lock by itself.
1615  *
1616  * Return: Zero if successful, or a negative error code.
1617  */
1618 int snd_pcm_stop_xrun(struct snd_pcm_substream *substream)
1619 {
1620 	guard(pcm_stream_lock_irqsave)(substream);
1621 	if (substream->runtime && snd_pcm_running(substream))
1622 		__snd_pcm_xrun(substream);
1623 	return 0;
1624 }
1625 EXPORT_SYMBOL_GPL(snd_pcm_stop_xrun);
1626 
1627 /*
1628  * pause callbacks: pass boolean (to start pause or resume) as state argument
1629  */
1630 #define pause_pushed(state)	(__force bool)(state)
1631 
1632 static int snd_pcm_pre_pause(struct snd_pcm_substream *substream,
1633 			     snd_pcm_state_t state)
1634 {
1635 	struct snd_pcm_runtime *runtime = substream->runtime;
1636 	if (!(runtime->info & SNDRV_PCM_INFO_PAUSE))
1637 		return -ENOSYS;
1638 	if (pause_pushed(state)) {
1639 		if (runtime->state != SNDRV_PCM_STATE_RUNNING)
1640 			return -EBADFD;
1641 	} else if (runtime->state != SNDRV_PCM_STATE_PAUSED)
1642 		return -EBADFD;
1643 	runtime->trigger_master = substream;
1644 	return 0;
1645 }
1646 
1647 static int snd_pcm_do_pause(struct snd_pcm_substream *substream,
1648 			    snd_pcm_state_t state)
1649 {
1650 	if (substream->runtime->trigger_master != substream)
1651 		return 0;
1652 	/* The jiffies check in snd_pcm_update_hw_ptr*() is done by
1653 	 * a delta between the current jiffies, this gives a large enough
1654 	 * delta, effectively to skip the check once.
1655 	 */
1656 	substream->runtime->hw_ptr_jiffies = jiffies - HZ * 1000;
1657 	return substream->ops->trigger(substream,
1658 				       pause_pushed(state) ?
1659 				       SNDRV_PCM_TRIGGER_PAUSE_PUSH :
1660 				       SNDRV_PCM_TRIGGER_PAUSE_RELEASE);
1661 }
1662 
1663 static void snd_pcm_undo_pause(struct snd_pcm_substream *substream,
1664 			       snd_pcm_state_t state)
1665 {
1666 	if (substream->runtime->trigger_master == substream)
1667 		substream->ops->trigger(substream,
1668 					pause_pushed(state) ?
1669 					SNDRV_PCM_TRIGGER_PAUSE_RELEASE :
1670 					SNDRV_PCM_TRIGGER_PAUSE_PUSH);
1671 }
1672 
1673 static void snd_pcm_post_pause(struct snd_pcm_substream *substream,
1674 			       snd_pcm_state_t state)
1675 {
1676 	struct snd_pcm_runtime *runtime = substream->runtime;
1677 	snd_pcm_trigger_tstamp(substream);
1678 	if (pause_pushed(state)) {
1679 		__snd_pcm_set_state(runtime, SNDRV_PCM_STATE_PAUSED);
1680 		snd_pcm_timer_notify(substream, SNDRV_TIMER_EVENT_MPAUSE);
1681 		wake_up(&runtime->sleep);
1682 		wake_up(&runtime->tsleep);
1683 	} else {
1684 		__snd_pcm_set_state(runtime, SNDRV_PCM_STATE_RUNNING);
1685 		snd_pcm_timer_notify(substream, SNDRV_TIMER_EVENT_MCONTINUE);
1686 	}
1687 }
1688 
1689 static const struct action_ops snd_pcm_action_pause = {
1690 	.pre_action = snd_pcm_pre_pause,
1691 	.do_action = snd_pcm_do_pause,
1692 	.undo_action = snd_pcm_undo_pause,
1693 	.post_action = snd_pcm_post_pause
1694 };
1695 
1696 /*
1697  * Push/release the pause for all linked streams.
1698  */
1699 static int snd_pcm_pause(struct snd_pcm_substream *substream, bool push)
1700 {
1701 	return snd_pcm_action(&snd_pcm_action_pause, substream,
1702 			      (__force snd_pcm_state_t)push);
1703 }
1704 
1705 static int snd_pcm_pause_lock_irq(struct snd_pcm_substream *substream,
1706 				  bool push)
1707 {
1708 	return snd_pcm_action_lock_irq(&snd_pcm_action_pause, substream,
1709 				       (__force snd_pcm_state_t)push);
1710 }
1711 
1712 #ifdef CONFIG_PM
1713 /* suspend callback: state argument ignored */
1714 
1715 static int snd_pcm_pre_suspend(struct snd_pcm_substream *substream,
1716 			       snd_pcm_state_t state)
1717 {
1718 	struct snd_pcm_runtime *runtime = substream->runtime;
1719 	switch (runtime->state) {
1720 	case SNDRV_PCM_STATE_SUSPENDED:
1721 		return -EBUSY;
1722 	/* unresumable PCM state; return -EBUSY for skipping suspend */
1723 	case SNDRV_PCM_STATE_OPEN:
1724 	case SNDRV_PCM_STATE_SETUP:
1725 	case SNDRV_PCM_STATE_DISCONNECTED:
1726 		return -EBUSY;
1727 	}
1728 	runtime->trigger_master = substream;
1729 	return 0;
1730 }
1731 
1732 static int snd_pcm_do_suspend(struct snd_pcm_substream *substream,
1733 			      snd_pcm_state_t state)
1734 {
1735 	struct snd_pcm_runtime *runtime = substream->runtime;
1736 	if (runtime->trigger_master != substream)
1737 		return 0;
1738 	if (! snd_pcm_running(substream))
1739 		return 0;
1740 	substream->ops->trigger(substream, SNDRV_PCM_TRIGGER_SUSPEND);
1741 	runtime->stop_operating = true;
1742 	return 0; /* suspend unconditionally */
1743 }
1744 
1745 static void snd_pcm_post_suspend(struct snd_pcm_substream *substream,
1746 				 snd_pcm_state_t state)
1747 {
1748 	struct snd_pcm_runtime *runtime = substream->runtime;
1749 	snd_pcm_trigger_tstamp(substream);
1750 	runtime->suspended_state = runtime->state;
1751 	runtime->status->suspended_state = runtime->suspended_state;
1752 	__snd_pcm_set_state(runtime, SNDRV_PCM_STATE_SUSPENDED);
1753 	snd_pcm_timer_notify(substream, SNDRV_TIMER_EVENT_MSUSPEND);
1754 	wake_up(&runtime->sleep);
1755 	wake_up(&runtime->tsleep);
1756 }
1757 
1758 static const struct action_ops snd_pcm_action_suspend = {
1759 	.pre_action = snd_pcm_pre_suspend,
1760 	.do_action = snd_pcm_do_suspend,
1761 	.post_action = snd_pcm_post_suspend
1762 };
1763 
1764 /*
1765  * snd_pcm_suspend - trigger SUSPEND to all linked streams
1766  * @substream: the PCM substream
1767  *
1768  * After this call, all streams are changed to SUSPENDED state.
1769  *
1770  * Return: Zero if successful, or a negative error code.
1771  */
1772 static int snd_pcm_suspend(struct snd_pcm_substream *substream)
1773 {
1774 	guard(pcm_stream_lock_irqsave)(substream);
1775 	return snd_pcm_action(&snd_pcm_action_suspend, substream,
1776 			      ACTION_ARG_IGNORE);
1777 }
1778 
1779 /**
1780  * snd_pcm_suspend_all - trigger SUSPEND to all substreams in the given pcm
1781  * @pcm: the PCM instance
1782  *
1783  * Takes and releases pcm->open_mutex to serialize against
1784  * concurrent open/close while walking the substreams.
1785  *
1786  * After this call, all streams are changed to SUSPENDED state.
1787  *
1788  * Return: Zero if successful (or @pcm is %NULL), or a negative error code.
1789  */
1790 int snd_pcm_suspend_all(struct snd_pcm *pcm)
1791 {
1792 	struct snd_pcm_substream *substream;
1793 	int stream, err = 0;
1794 
1795 	if (! pcm)
1796 		return 0;
1797 
1798 	guard(mutex)(&pcm->open_mutex);
1799 
1800 	for_each_pcm_substream(pcm, stream, substream) {
1801 		if (!substream->runtime)
1802 			continue;
1803 
1804 		/*
1805 		 * Skip BE dai link PCM's that are internal and may
1806 		 * not have their substream ops set.
1807 		 */
1808 		if (!substream->ops)
1809 			continue;
1810 
1811 		err = snd_pcm_suspend(substream);
1812 		if (err < 0 && err != -EBUSY)
1813 			return err;
1814 	}
1815 
1816 	for_each_pcm_substream(pcm, stream, substream)
1817 		snd_pcm_sync_stop(substream, false);
1818 
1819 	return 0;
1820 }
1821 EXPORT_SYMBOL(snd_pcm_suspend_all);
1822 
1823 /* resume callbacks: state argument ignored */
1824 
1825 static int snd_pcm_pre_resume(struct snd_pcm_substream *substream,
1826 			      snd_pcm_state_t state)
1827 {
1828 	struct snd_pcm_runtime *runtime = substream->runtime;
1829 	if (runtime->state != SNDRV_PCM_STATE_SUSPENDED)
1830 		return -EBADFD;
1831 	if (!(runtime->info & SNDRV_PCM_INFO_RESUME))
1832 		return -ENOSYS;
1833 	runtime->trigger_master = substream;
1834 	return 0;
1835 }
1836 
1837 static int snd_pcm_do_resume(struct snd_pcm_substream *substream,
1838 			     snd_pcm_state_t state)
1839 {
1840 	struct snd_pcm_runtime *runtime = substream->runtime;
1841 	if (runtime->trigger_master != substream)
1842 		return 0;
1843 	/* DMA not running previously? */
1844 	if (runtime->suspended_state != SNDRV_PCM_STATE_RUNNING &&
1845 	    (runtime->suspended_state != SNDRV_PCM_STATE_DRAINING ||
1846 	     substream->stream != SNDRV_PCM_STREAM_PLAYBACK))
1847 		return 0;
1848 	return substream->ops->trigger(substream, SNDRV_PCM_TRIGGER_RESUME);
1849 }
1850 
1851 static void snd_pcm_undo_resume(struct snd_pcm_substream *substream,
1852 				snd_pcm_state_t state)
1853 {
1854 	if (substream->runtime->trigger_master == substream &&
1855 	    snd_pcm_running(substream))
1856 		substream->ops->trigger(substream, SNDRV_PCM_TRIGGER_SUSPEND);
1857 }
1858 
1859 static void snd_pcm_post_resume(struct snd_pcm_substream *substream,
1860 				snd_pcm_state_t state)
1861 {
1862 	struct snd_pcm_runtime *runtime = substream->runtime;
1863 	snd_pcm_trigger_tstamp(substream);
1864 	__snd_pcm_set_state(runtime, runtime->suspended_state);
1865 	snd_pcm_timer_notify(substream, SNDRV_TIMER_EVENT_MRESUME);
1866 }
1867 
1868 static const struct action_ops snd_pcm_action_resume = {
1869 	.pre_action = snd_pcm_pre_resume,
1870 	.do_action = snd_pcm_do_resume,
1871 	.undo_action = snd_pcm_undo_resume,
1872 	.post_action = snd_pcm_post_resume
1873 };
1874 
1875 static int snd_pcm_resume(struct snd_pcm_substream *substream)
1876 {
1877 	return snd_pcm_action_lock_irq(&snd_pcm_action_resume, substream,
1878 				       ACTION_ARG_IGNORE);
1879 }
1880 
1881 #else
1882 
1883 static int snd_pcm_resume(struct snd_pcm_substream *substream)
1884 {
1885 	return -ENOSYS;
1886 }
1887 
1888 #endif /* CONFIG_PM */
1889 
1890 /*
1891  * xrun ioctl
1892  *
1893  * Change the RUNNING stream(s) to XRUN state.
1894  */
1895 static int snd_pcm_xrun(struct snd_pcm_substream *substream)
1896 {
1897 	struct snd_pcm_runtime *runtime = substream->runtime;
1898 
1899 	guard(pcm_stream_lock_irq)(substream);
1900 	switch (runtime->state) {
1901 	case SNDRV_PCM_STATE_XRUN:
1902 		return 0;	/* already there */
1903 	case SNDRV_PCM_STATE_RUNNING:
1904 		__snd_pcm_xrun(substream);
1905 		return 0;
1906 	default:
1907 		return -EBADFD;
1908 	}
1909 }
1910 
1911 /*
1912  * reset ioctl
1913  */
1914 /* reset callbacks:  state argument ignored */
1915 static int snd_pcm_pre_reset(struct snd_pcm_substream *substream,
1916 			     snd_pcm_state_t state)
1917 {
1918 	struct snd_pcm_runtime *runtime = substream->runtime;
1919 	switch (runtime->state) {
1920 	case SNDRV_PCM_STATE_RUNNING:
1921 	case SNDRV_PCM_STATE_PREPARED:
1922 	case SNDRV_PCM_STATE_PAUSED:
1923 	case SNDRV_PCM_STATE_SUSPENDED:
1924 		return 0;
1925 	default:
1926 		return -EBADFD;
1927 	}
1928 }
1929 
1930 static int snd_pcm_do_reset(struct snd_pcm_substream *substream,
1931 			    snd_pcm_state_t state)
1932 {
1933 	struct snd_pcm_runtime *runtime = substream->runtime;
1934 	int err = snd_pcm_ops_ioctl(substream, SNDRV_PCM_IOCTL1_RESET, NULL);
1935 	if (err < 0)
1936 		return err;
1937 	guard(pcm_stream_lock_irq)(substream);
1938 	runtime->hw_ptr_base = 0;
1939 	runtime->hw_ptr_interrupt = runtime->status->hw_ptr -
1940 		runtime->status->hw_ptr % runtime->period_size;
1941 	runtime->silence_start = runtime->status->hw_ptr;
1942 	runtime->silence_filled = 0;
1943 	return 0;
1944 }
1945 
1946 static void snd_pcm_post_reset(struct snd_pcm_substream *substream,
1947 			       snd_pcm_state_t state)
1948 {
1949 	struct snd_pcm_runtime *runtime = substream->runtime;
1950 	guard(pcm_stream_lock_irq)(substream);
1951 	runtime->control->appl_ptr = runtime->status->hw_ptr;
1952 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK &&
1953 	    runtime->silence_size > 0)
1954 		snd_pcm_playback_silence(substream, ULONG_MAX);
1955 }
1956 
1957 static const struct action_ops snd_pcm_action_reset = {
1958 	.pre_action = snd_pcm_pre_reset,
1959 	.do_action = snd_pcm_do_reset,
1960 	.post_action = snd_pcm_post_reset
1961 };
1962 
1963 static int snd_pcm_reset(struct snd_pcm_substream *substream)
1964 {
1965 	return snd_pcm_action_nonatomic(&snd_pcm_action_reset, substream,
1966 					ACTION_ARG_IGNORE);
1967 }
1968 
1969 /*
1970  * prepare ioctl
1971  */
1972 /* pass f_flags as state argument */
1973 static int snd_pcm_pre_prepare(struct snd_pcm_substream *substream,
1974 			       snd_pcm_state_t state)
1975 {
1976 	snd_pcm_state_t cur_state = snd_pcm_get_state(substream);
1977 	int f_flags = (__force int)state;
1978 
1979 	if (cur_state == SNDRV_PCM_STATE_OPEN ||
1980 	    cur_state == SNDRV_PCM_STATE_DISCONNECTED)
1981 		return -EBADFD;
1982 	if (cur_state == SNDRV_PCM_STATE_RUNNING ||
1983 	    (cur_state == SNDRV_PCM_STATE_DRAINING &&
1984 	     substream->stream == SNDRV_PCM_STREAM_PLAYBACK))
1985 		return -EBUSY;
1986 	substream->f_flags = f_flags;
1987 	return 0;
1988 }
1989 
1990 static int snd_pcm_do_prepare(struct snd_pcm_substream *substream,
1991 			      snd_pcm_state_t state)
1992 {
1993 	int err;
1994 	snd_pcm_sync_stop(substream, true);
1995 	err = substream->ops->prepare(substream);
1996 	if (err < 0)
1997 		return err;
1998 	return snd_pcm_do_reset(substream, state);
1999 }
2000 
2001 static void snd_pcm_post_prepare(struct snd_pcm_substream *substream,
2002 				 snd_pcm_state_t state)
2003 {
2004 	struct snd_pcm_runtime *runtime = substream->runtime;
2005 	runtime->control->appl_ptr = runtime->status->hw_ptr;
2006 	snd_pcm_set_state(substream, SNDRV_PCM_STATE_PREPARED);
2007 }
2008 
2009 static const struct action_ops snd_pcm_action_prepare = {
2010 	.pre_action = snd_pcm_pre_prepare,
2011 	.do_action = snd_pcm_do_prepare,
2012 	.post_action = snd_pcm_post_prepare
2013 };
2014 
2015 /**
2016  * snd_pcm_prepare - prepare the PCM substream to be triggerable
2017  * @substream: the PCM substream instance
2018  * @file: file to refer f_flags
2019  *
2020  * Return: Zero if successful, or a negative error code.
2021  */
2022 static int snd_pcm_prepare(struct snd_pcm_substream *substream,
2023 			   struct file *file)
2024 {
2025 	int f_flags;
2026 
2027 	if (file)
2028 		f_flags = file->f_flags;
2029 	else
2030 		f_flags = substream->f_flags;
2031 
2032 	scoped_guard(pcm_stream_lock_irq, substream) {
2033 		switch (substream->runtime->state) {
2034 		case SNDRV_PCM_STATE_PAUSED:
2035 			snd_pcm_pause(substream, false);
2036 			fallthrough;
2037 		case SNDRV_PCM_STATE_SUSPENDED:
2038 			snd_pcm_stop(substream, SNDRV_PCM_STATE_SETUP);
2039 			break;
2040 		}
2041 	}
2042 
2043 	return snd_pcm_action_nonatomic(&snd_pcm_action_prepare,
2044 					substream,
2045 					(__force snd_pcm_state_t)f_flags);
2046 }
2047 
2048 /*
2049  * drain ioctl
2050  */
2051 
2052 /* drain init callbacks: state argument ignored */
2053 static int snd_pcm_pre_drain_init(struct snd_pcm_substream *substream,
2054 				  snd_pcm_state_t state)
2055 {
2056 	struct snd_pcm_runtime *runtime = substream->runtime;
2057 	switch (runtime->state) {
2058 	case SNDRV_PCM_STATE_OPEN:
2059 	case SNDRV_PCM_STATE_DISCONNECTED:
2060 	case SNDRV_PCM_STATE_SUSPENDED:
2061 		return -EBADFD;
2062 	}
2063 	runtime->trigger_master = substream;
2064 	return 0;
2065 }
2066 
2067 static int snd_pcm_do_drain_init(struct snd_pcm_substream *substream,
2068 				 snd_pcm_state_t state)
2069 {
2070 	struct snd_pcm_runtime *runtime = substream->runtime;
2071 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
2072 		switch (runtime->state) {
2073 		case SNDRV_PCM_STATE_PREPARED:
2074 			/* start playback stream if possible */
2075 			if (! snd_pcm_playback_empty(substream)) {
2076 				snd_pcm_do_start(substream, SNDRV_PCM_STATE_DRAINING);
2077 				snd_pcm_post_start(substream, SNDRV_PCM_STATE_DRAINING);
2078 			} else {
2079 				__snd_pcm_set_state(runtime, SNDRV_PCM_STATE_SETUP);
2080 			}
2081 			break;
2082 		case SNDRV_PCM_STATE_RUNNING:
2083 			__snd_pcm_set_state(runtime, SNDRV_PCM_STATE_DRAINING);
2084 			break;
2085 		case SNDRV_PCM_STATE_XRUN:
2086 			__snd_pcm_set_state(runtime, SNDRV_PCM_STATE_SETUP);
2087 			break;
2088 		default:
2089 			break;
2090 		}
2091 	} else {
2092 		/* stop running stream */
2093 		if (runtime->state == SNDRV_PCM_STATE_RUNNING) {
2094 			snd_pcm_state_t new_state;
2095 
2096 			new_state = snd_pcm_capture_avail(runtime) > 0 ?
2097 				SNDRV_PCM_STATE_DRAINING : SNDRV_PCM_STATE_SETUP;
2098 			snd_pcm_do_stop(substream, new_state);
2099 			snd_pcm_post_stop(substream, new_state);
2100 		}
2101 	}
2102 
2103 	if (runtime->state == SNDRV_PCM_STATE_DRAINING &&
2104 	    runtime->trigger_master == substream &&
2105 	    (runtime->hw.info & SNDRV_PCM_INFO_DRAIN_TRIGGER))
2106 		return substream->ops->trigger(substream,
2107 					       SNDRV_PCM_TRIGGER_DRAIN);
2108 
2109 	return 0;
2110 }
2111 
2112 static void snd_pcm_post_drain_init(struct snd_pcm_substream *substream,
2113 				    snd_pcm_state_t state)
2114 {
2115 }
2116 
2117 static const struct action_ops snd_pcm_action_drain_init = {
2118 	.pre_action = snd_pcm_pre_drain_init,
2119 	.do_action = snd_pcm_do_drain_init,
2120 	.post_action = snd_pcm_post_drain_init
2121 };
2122 
2123 /*
2124  * Drain the stream(s).
2125  * When the substream is linked, sync until the draining of all playback streams
2126  * is finished.
2127  * After this call, all streams are supposed to be either SETUP or DRAINING
2128  * (capture only) state.
2129  */
2130 static int snd_pcm_drain(struct snd_pcm_substream *substream,
2131 			 struct file *file)
2132 {
2133 	struct snd_card *card;
2134 	struct snd_pcm_runtime *runtime;
2135 	struct snd_pcm_substream *s;
2136 	struct snd_pcm_group *group;
2137 	wait_queue_entry_t wait;
2138 	int result = 0;
2139 	int nonblock = 0;
2140 
2141 	card = substream->pcm->card;
2142 	runtime = substream->runtime;
2143 
2144 	if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN)
2145 		return -EBADFD;
2146 
2147 	if (file) {
2148 		if (file->f_flags & O_NONBLOCK)
2149 			nonblock = 1;
2150 	} else if (substream->f_flags & O_NONBLOCK)
2151 		nonblock = 1;
2152 
2153 	snd_pcm_stream_lock_irq(substream);
2154 	/* resume pause */
2155 	if (runtime->state == SNDRV_PCM_STATE_PAUSED)
2156 		snd_pcm_pause(substream, false);
2157 
2158 	/* pre-start/stop - all running streams are changed to DRAINING state */
2159 	result = snd_pcm_action(&snd_pcm_action_drain_init, substream,
2160 				ACTION_ARG_IGNORE);
2161 	if (result < 0)
2162 		goto unlock;
2163 	/* in non-blocking, we don't wait in ioctl but let caller poll */
2164 	if (nonblock) {
2165 		result = -EAGAIN;
2166 		goto unlock;
2167 	}
2168 
2169 	for (;;) {
2170 		long tout;
2171 		struct snd_pcm_runtime *to_check;
2172 		unsigned int drain_rate;
2173 		snd_pcm_uframes_t drain_bufsz;
2174 		bool drain_no_period_wakeup;
2175 
2176 		if (signal_pending(current)) {
2177 			result = -ERESTARTSYS;
2178 			break;
2179 		}
2180 		/* find a substream to drain */
2181 		to_check = NULL;
2182 		group = snd_pcm_stream_group_ref(substream);
2183 		snd_pcm_group_for_each_entry(s, substream) {
2184 			if (s->stream != SNDRV_PCM_STREAM_PLAYBACK)
2185 				continue;
2186 			runtime = s->runtime;
2187 			if (runtime->state == SNDRV_PCM_STATE_DRAINING) {
2188 				to_check = runtime;
2189 				break;
2190 			}
2191 		}
2192 		snd_pcm_group_unref(group, substream);
2193 		if (!to_check)
2194 			break; /* all drained */
2195 		/*
2196 		 * Cache the runtime fields needed after unlock.
2197 		 * A concurrent close() on the linked stream may free
2198 		 * its runtime via snd_pcm_detach_substream() once we
2199 		 * release the stream lock below.
2200 		 */
2201 		drain_no_period_wakeup = to_check->no_period_wakeup;
2202 		drain_rate = to_check->rate;
2203 		drain_bufsz = to_check->buffer_size;
2204 		init_wait_entry(&wait, 0);
2205 		prepare_to_wait(&to_check->sleep, &wait, TASK_INTERRUPTIBLE);
2206 		snd_pcm_stream_unlock_irq(substream);
2207 		if (drain_no_period_wakeup)
2208 			tout = MAX_SCHEDULE_TIMEOUT;
2209 		else {
2210 			tout = 100;
2211 			if (drain_rate) {
2212 				long t = drain_bufsz * 1100 / drain_rate;
2213 				tout = max(t, tout);
2214 			}
2215 			tout = msecs_to_jiffies(tout);
2216 		}
2217 		tout = schedule_timeout(tout);
2218 
2219 		snd_pcm_stream_lock_irq(substream);
2220 		group = snd_pcm_stream_group_ref(substream);
2221 		snd_pcm_group_for_each_entry(s, substream) {
2222 			if (s->runtime == to_check) {
2223 				finish_wait(&to_check->sleep, &wait);
2224 				break;
2225 			}
2226 		}
2227 		snd_pcm_group_unref(group, substream);
2228 
2229 		if (card->shutdown) {
2230 			result = -ENODEV;
2231 			break;
2232 		}
2233 		if (tout == 0) {
2234 			if (substream->runtime->state == SNDRV_PCM_STATE_SUSPENDED)
2235 				result = -ESTRPIPE;
2236 			else {
2237 				dev_dbg(substream->pcm->card->dev,
2238 					"playback drain timeout (DMA or IRQ trouble?)\n");
2239 				snd_pcm_stop(substream, SNDRV_PCM_STATE_SETUP);
2240 				result = -EIO;
2241 			}
2242 			break;
2243 		}
2244 	}
2245 
2246  unlock:
2247 	snd_pcm_stream_unlock_irq(substream);
2248 
2249 	return result;
2250 }
2251 
2252 /*
2253  * drop ioctl
2254  *
2255  * Immediately put all linked substreams into SETUP state.
2256  */
2257 static int snd_pcm_drop(struct snd_pcm_substream *substream)
2258 {
2259 	struct snd_pcm_runtime *runtime;
2260 	int result = 0;
2261 
2262 	if (PCM_RUNTIME_CHECK(substream))
2263 		return -ENXIO;
2264 	runtime = substream->runtime;
2265 
2266 	if (runtime->state == SNDRV_PCM_STATE_OPEN ||
2267 	    runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
2268 		return -EBADFD;
2269 
2270 	guard(pcm_stream_lock_irq)(substream);
2271 	/* resume pause */
2272 	if (runtime->state == SNDRV_PCM_STATE_PAUSED)
2273 		snd_pcm_pause(substream, false);
2274 
2275 	snd_pcm_stop(substream, SNDRV_PCM_STATE_SETUP);
2276 	/* runtime->control->appl_ptr = runtime->status->hw_ptr; */
2277 
2278 	return result;
2279 }
2280 
2281 
2282 static bool is_pcm_file(struct file *file)
2283 {
2284 	struct inode *inode = file_inode(file);
2285 	struct snd_pcm *pcm;
2286 	unsigned int minor;
2287 
2288 	if (!S_ISCHR(inode->i_mode) || imajor(inode) != snd_major)
2289 		return false;
2290 	minor = iminor(inode);
2291 	pcm = snd_lookup_minor_data(minor, SNDRV_DEVICE_TYPE_PCM_PLAYBACK);
2292 	if (!pcm)
2293 		pcm = snd_lookup_minor_data(minor, SNDRV_DEVICE_TYPE_PCM_CAPTURE);
2294 	if (!pcm)
2295 		return false;
2296 	snd_card_unref(pcm->card);
2297 	return true;
2298 }
2299 
2300 /*
2301  * PCM link handling
2302  */
2303 static int snd_pcm_link(struct snd_pcm_substream *substream, int fd)
2304 {
2305 	struct snd_pcm_file *pcm_file;
2306 	struct snd_pcm_substream *substream1;
2307 	struct snd_pcm_group *target_group;
2308 	bool nonatomic = substream->pcm->nonatomic;
2309 	CLASS(fd, f)(fd);
2310 
2311 	if (fd_empty(f))
2312 		return -EBADFD;
2313 	if (!is_pcm_file(fd_file(f)))
2314 		return -EBADFD;
2315 
2316 	pcm_file = fd_file(f)->private_data;
2317 	substream1 = pcm_file->substream;
2318 
2319 	if (substream == substream1)
2320 		return -EINVAL;
2321 
2322 	struct snd_pcm_group *group __free(kfree) =
2323 		kzalloc(sizeof(*group), GFP_KERNEL);
2324 	if (!group)
2325 		return -ENOMEM;
2326 	snd_pcm_group_init(group);
2327 
2328 	guard(rwsem_write)(&snd_pcm_link_rwsem);
2329 	if (substream->runtime->state == SNDRV_PCM_STATE_OPEN ||
2330 	    substream->runtime->state != substream1->runtime->state ||
2331 	    substream->pcm->nonatomic != substream1->pcm->nonatomic)
2332 		return -EBADFD;
2333 	if (snd_pcm_stream_linked(substream1))
2334 		return -EALREADY;
2335 
2336 	scoped_guard(pcm_stream_lock_irq, substream) {
2337 		if (!snd_pcm_stream_linked(substream)) {
2338 			snd_pcm_group_assign(substream, group);
2339 			group = NULL; /* assigned, don't free this one below */
2340 		}
2341 		target_group = substream->group;
2342 	}
2343 
2344 	snd_pcm_group_lock_irq(target_group, nonatomic);
2345 	snd_pcm_stream_lock_nested(substream1);
2346 	snd_pcm_group_assign(substream1, target_group);
2347 	refcount_inc(&target_group->refs);
2348 	snd_pcm_stream_unlock(substream1);
2349 	snd_pcm_group_unlock_irq(target_group, nonatomic);
2350 	return 0;
2351 }
2352 
2353 static void relink_to_local(struct snd_pcm_substream *substream)
2354 {
2355 	snd_pcm_stream_lock_nested(substream);
2356 	snd_pcm_group_assign(substream, &substream->self_group);
2357 	snd_pcm_stream_unlock(substream);
2358 }
2359 
2360 static int snd_pcm_unlink(struct snd_pcm_substream *substream)
2361 {
2362 	struct snd_pcm_group *group;
2363 	bool nonatomic = substream->pcm->nonatomic;
2364 	bool do_free = false;
2365 
2366 	guard(rwsem_write)(&snd_pcm_link_rwsem);
2367 
2368 	if (!snd_pcm_stream_linked(substream))
2369 		return -EALREADY;
2370 
2371 	group = substream->group;
2372 	snd_pcm_group_lock_irq(group, nonatomic);
2373 
2374 	relink_to_local(substream);
2375 	refcount_dec(&group->refs);
2376 
2377 	/* detach the last stream, too */
2378 	if (list_is_singular(&group->substreams)) {
2379 		relink_to_local(list_first_entry(&group->substreams,
2380 						 struct snd_pcm_substream,
2381 						 link_list));
2382 		do_free = refcount_dec_and_test(&group->refs);
2383 	}
2384 
2385 	snd_pcm_group_unlock_irq(group, nonatomic);
2386 	if (do_free)
2387 		kfree(group);
2388 	return 0;
2389 }
2390 
2391 /*
2392  * hw configurator
2393  */
2394 static int snd_pcm_hw_rule_mul(struct snd_pcm_hw_params *params,
2395 			       struct snd_pcm_hw_rule *rule)
2396 {
2397 	struct snd_interval t;
2398 	snd_interval_mul(hw_param_interval_c(params, rule->deps[0]),
2399 		     hw_param_interval_c(params, rule->deps[1]), &t);
2400 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
2401 }
2402 
2403 static int snd_pcm_hw_rule_div(struct snd_pcm_hw_params *params,
2404 			       struct snd_pcm_hw_rule *rule)
2405 {
2406 	struct snd_interval t;
2407 	snd_interval_div(hw_param_interval_c(params, rule->deps[0]),
2408 		     hw_param_interval_c(params, rule->deps[1]), &t);
2409 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
2410 }
2411 
2412 static int snd_pcm_hw_rule_muldivk(struct snd_pcm_hw_params *params,
2413 				   struct snd_pcm_hw_rule *rule)
2414 {
2415 	struct snd_interval t;
2416 	snd_interval_muldivk(hw_param_interval_c(params, rule->deps[0]),
2417 			 hw_param_interval_c(params, rule->deps[1]),
2418 			 (unsigned long) rule->private, &t);
2419 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
2420 }
2421 
2422 static int snd_pcm_hw_rule_mulkdiv(struct snd_pcm_hw_params *params,
2423 				   struct snd_pcm_hw_rule *rule)
2424 {
2425 	struct snd_interval t;
2426 	snd_interval_mulkdiv(hw_param_interval_c(params, rule->deps[0]),
2427 			 (unsigned long) rule->private,
2428 			 hw_param_interval_c(params, rule->deps[1]), &t);
2429 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
2430 }
2431 
2432 static int snd_pcm_hw_rule_format(struct snd_pcm_hw_params *params,
2433 				  struct snd_pcm_hw_rule *rule)
2434 {
2435 	snd_pcm_format_t k;
2436 	const struct snd_interval *i =
2437 				hw_param_interval_c(params, rule->deps[0]);
2438 	struct snd_mask m;
2439 	struct snd_mask *mask = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
2440 	snd_mask_any(&m);
2441 	pcm_for_each_format(k) {
2442 		int bits;
2443 		if (!snd_mask_test_format(mask, k))
2444 			continue;
2445 		bits = snd_pcm_format_physical_width(k);
2446 		if (bits <= 0)
2447 			continue; /* ignore invalid formats */
2448 		if ((unsigned)bits < i->min || (unsigned)bits > i->max)
2449 			snd_mask_reset(&m, (__force unsigned)k);
2450 	}
2451 	return snd_mask_refine(mask, &m);
2452 }
2453 
2454 static int snd_pcm_hw_rule_sample_bits(struct snd_pcm_hw_params *params,
2455 				       struct snd_pcm_hw_rule *rule)
2456 {
2457 	struct snd_interval t;
2458 	snd_pcm_format_t k;
2459 
2460 	t.min = UINT_MAX;
2461 	t.max = 0;
2462 	t.openmin = 0;
2463 	t.openmax = 0;
2464 	pcm_for_each_format(k) {
2465 		int bits;
2466 		if (!snd_mask_test_format(hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT), k))
2467 			continue;
2468 		bits = snd_pcm_format_physical_width(k);
2469 		if (bits <= 0)
2470 			continue; /* ignore invalid formats */
2471 		if (t.min > (unsigned)bits)
2472 			t.min = bits;
2473 		if (t.max < (unsigned)bits)
2474 			t.max = bits;
2475 	}
2476 	t.integer = 1;
2477 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
2478 }
2479 
2480 #if SNDRV_PCM_RATE_5512 != 1 << 0 || SNDRV_PCM_RATE_192000 != 1 << 12 ||\
2481 	SNDRV_PCM_RATE_128000 != 1 << 19
2482 #error "Change this table"
2483 #endif
2484 
2485 /* NOTE: the list is unsorted! */
2486 static const unsigned int rates[] = {
2487 	5512, 8000, 11025, 16000, 22050, 32000, 44100,
2488 	48000, 64000, 88200, 96000, 176400, 192000, 352800, 384000, 705600, 768000,
2489 	/* extended */
2490 	12000, 24000, 128000
2491 };
2492 
2493 const struct snd_pcm_hw_constraint_list snd_pcm_known_rates = {
2494 	.count = ARRAY_SIZE(rates),
2495 	.list = rates,
2496 };
2497 
2498 static int snd_pcm_hw_rule_rate(struct snd_pcm_hw_params *params,
2499 				struct snd_pcm_hw_rule *rule)
2500 {
2501 	struct snd_pcm_hardware *hw = rule->private;
2502 	return snd_interval_list(hw_param_interval(params, rule->var),
2503 				 snd_pcm_known_rates.count,
2504 				 snd_pcm_known_rates.list, hw->rates);
2505 }
2506 
2507 static int snd_pcm_hw_rule_buffer_bytes_max(struct snd_pcm_hw_params *params,
2508 					    struct snd_pcm_hw_rule *rule)
2509 {
2510 	struct snd_interval t;
2511 	struct snd_pcm_substream *substream = rule->private;
2512 	t.min = 0;
2513 	t.max = substream->buffer_bytes_max;
2514 	t.openmin = 0;
2515 	t.openmax = 0;
2516 	t.integer = 1;
2517 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
2518 }
2519 
2520 static int snd_pcm_hw_rule_subformats(struct snd_pcm_hw_params *params,
2521 				      struct snd_pcm_hw_rule *rule)
2522 {
2523 	struct snd_mask *sfmask = hw_param_mask(params, SNDRV_PCM_HW_PARAM_SUBFORMAT);
2524 	struct snd_mask *fmask = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
2525 	u32 *subformats = rule->private;
2526 	snd_pcm_format_t f;
2527 	struct snd_mask m;
2528 
2529 	snd_mask_none(&m);
2530 	/* All PCMs support at least the default STD subformat. */
2531 	snd_mask_set(&m, (__force unsigned)SNDRV_PCM_SUBFORMAT_STD);
2532 
2533 	pcm_for_each_format(f) {
2534 		if (!snd_mask_test(fmask, (__force unsigned)f))
2535 			continue;
2536 
2537 		if (f == SNDRV_PCM_FORMAT_S32_LE && *subformats)
2538 			m.bits[0] |= *subformats;
2539 		else if (snd_pcm_format_linear(f))
2540 			snd_mask_set(&m, (__force unsigned)SNDRV_PCM_SUBFORMAT_MSBITS_MAX);
2541 	}
2542 
2543 	return snd_mask_refine(sfmask, &m);
2544 }
2545 
2546 static int snd_pcm_hw_constraint_subformats(struct snd_pcm_runtime *runtime,
2547 					   unsigned int cond, u32 *subformats)
2548 {
2549 	return snd_pcm_hw_rule_add(runtime, cond, -1,
2550 				   snd_pcm_hw_rule_subformats, (void *)subformats,
2551 				   SNDRV_PCM_HW_PARAM_SUBFORMAT,
2552 				   SNDRV_PCM_HW_PARAM_FORMAT, -1);
2553 }
2554 
2555 static int snd_pcm_hw_constraints_init(struct snd_pcm_substream *substream)
2556 {
2557 	struct snd_pcm_runtime *runtime = substream->runtime;
2558 	struct snd_pcm_hw_constraints *constrs = &runtime->hw_constraints;
2559 	int k, err;
2560 
2561 	for (k = SNDRV_PCM_HW_PARAM_FIRST_MASK; k <= SNDRV_PCM_HW_PARAM_LAST_MASK; k++) {
2562 		snd_mask_any(constrs_mask(constrs, k));
2563 	}
2564 
2565 	for (k = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; k <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; k++) {
2566 		snd_interval_any(constrs_interval(constrs, k));
2567 	}
2568 
2569 	snd_interval_setinteger(constrs_interval(constrs, SNDRV_PCM_HW_PARAM_CHANNELS));
2570 	snd_interval_setinteger(constrs_interval(constrs, SNDRV_PCM_HW_PARAM_BUFFER_SIZE));
2571 	snd_interval_setinteger(constrs_interval(constrs, SNDRV_PCM_HW_PARAM_BUFFER_BYTES));
2572 	snd_interval_setinteger(constrs_interval(constrs, SNDRV_PCM_HW_PARAM_SAMPLE_BITS));
2573 	snd_interval_setinteger(constrs_interval(constrs, SNDRV_PCM_HW_PARAM_FRAME_BITS));
2574 
2575 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
2576 				   snd_pcm_hw_rule_format, NULL,
2577 				   SNDRV_PCM_HW_PARAM_SAMPLE_BITS, -1);
2578 	if (err < 0)
2579 		return err;
2580 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_SAMPLE_BITS,
2581 				  snd_pcm_hw_rule_sample_bits, NULL,
2582 				  SNDRV_PCM_HW_PARAM_FORMAT,
2583 				  SNDRV_PCM_HW_PARAM_SAMPLE_BITS, -1);
2584 	if (err < 0)
2585 		return err;
2586 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_SAMPLE_BITS,
2587 				  snd_pcm_hw_rule_div, NULL,
2588 				  SNDRV_PCM_HW_PARAM_FRAME_BITS, SNDRV_PCM_HW_PARAM_CHANNELS, -1);
2589 	if (err < 0)
2590 		return err;
2591 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FRAME_BITS,
2592 				  snd_pcm_hw_rule_mul, NULL,
2593 				  SNDRV_PCM_HW_PARAM_SAMPLE_BITS, SNDRV_PCM_HW_PARAM_CHANNELS, -1);
2594 	if (err < 0)
2595 		return err;
2596 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FRAME_BITS,
2597 				  snd_pcm_hw_rule_mulkdiv, (void*) 8,
2598 				  SNDRV_PCM_HW_PARAM_PERIOD_BYTES, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, -1);
2599 	if (err < 0)
2600 		return err;
2601 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FRAME_BITS,
2602 				  snd_pcm_hw_rule_mulkdiv, (void*) 8,
2603 				  SNDRV_PCM_HW_PARAM_BUFFER_BYTES, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, -1);
2604 	if (err < 0)
2605 		return err;
2606 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
2607 				  snd_pcm_hw_rule_div, NULL,
2608 				  SNDRV_PCM_HW_PARAM_FRAME_BITS, SNDRV_PCM_HW_PARAM_SAMPLE_BITS, -1);
2609 	if (err < 0)
2610 		return err;
2611 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
2612 				  snd_pcm_hw_rule_mulkdiv, (void*) 1000000,
2613 				  SNDRV_PCM_HW_PARAM_PERIOD_SIZE, SNDRV_PCM_HW_PARAM_PERIOD_TIME, -1);
2614 	if (err < 0)
2615 		return err;
2616 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
2617 				  snd_pcm_hw_rule_mulkdiv, (void*) 1000000,
2618 				  SNDRV_PCM_HW_PARAM_BUFFER_SIZE, SNDRV_PCM_HW_PARAM_BUFFER_TIME, -1);
2619 	if (err < 0)
2620 		return err;
2621 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIODS,
2622 				  snd_pcm_hw_rule_div, NULL,
2623 				  SNDRV_PCM_HW_PARAM_BUFFER_SIZE, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, -1);
2624 	if (err < 0)
2625 		return err;
2626 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
2627 				  snd_pcm_hw_rule_div, NULL,
2628 				  SNDRV_PCM_HW_PARAM_BUFFER_SIZE, SNDRV_PCM_HW_PARAM_PERIODS, -1);
2629 	if (err < 0)
2630 		return err;
2631 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
2632 				  snd_pcm_hw_rule_mulkdiv, (void*) 8,
2633 				  SNDRV_PCM_HW_PARAM_PERIOD_BYTES, SNDRV_PCM_HW_PARAM_FRAME_BITS, -1);
2634 	if (err < 0)
2635 		return err;
2636 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
2637 				  snd_pcm_hw_rule_muldivk, (void*) 1000000,
2638 				  SNDRV_PCM_HW_PARAM_PERIOD_TIME, SNDRV_PCM_HW_PARAM_RATE, -1);
2639 	if (err < 0)
2640 		return err;
2641 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
2642 				  snd_pcm_hw_rule_mul, NULL,
2643 				  SNDRV_PCM_HW_PARAM_PERIOD_SIZE, SNDRV_PCM_HW_PARAM_PERIODS, -1);
2644 	if (err < 0)
2645 		return err;
2646 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
2647 				  snd_pcm_hw_rule_mulkdiv, (void*) 8,
2648 				  SNDRV_PCM_HW_PARAM_BUFFER_BYTES, SNDRV_PCM_HW_PARAM_FRAME_BITS, -1);
2649 	if (err < 0)
2650 		return err;
2651 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
2652 				  snd_pcm_hw_rule_muldivk, (void*) 1000000,
2653 				  SNDRV_PCM_HW_PARAM_BUFFER_TIME, SNDRV_PCM_HW_PARAM_RATE, -1);
2654 	if (err < 0)
2655 		return err;
2656 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES,
2657 				  snd_pcm_hw_rule_muldivk, (void*) 8,
2658 				  SNDRV_PCM_HW_PARAM_PERIOD_SIZE, SNDRV_PCM_HW_PARAM_FRAME_BITS, -1);
2659 	if (err < 0)
2660 		return err;
2661 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
2662 				  snd_pcm_hw_rule_muldivk, (void*) 8,
2663 				  SNDRV_PCM_HW_PARAM_BUFFER_SIZE, SNDRV_PCM_HW_PARAM_FRAME_BITS, -1);
2664 	if (err < 0)
2665 		return err;
2666 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
2667 				  snd_pcm_hw_rule_mulkdiv, (void*) 1000000,
2668 				  SNDRV_PCM_HW_PARAM_PERIOD_SIZE, SNDRV_PCM_HW_PARAM_RATE, -1);
2669 	if (err < 0)
2670 		return err;
2671 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_TIME,
2672 				  snd_pcm_hw_rule_mulkdiv, (void*) 1000000,
2673 				  SNDRV_PCM_HW_PARAM_BUFFER_SIZE, SNDRV_PCM_HW_PARAM_RATE, -1);
2674 	if (err < 0)
2675 		return err;
2676 	return 0;
2677 }
2678 
2679 static int snd_pcm_hw_constraints_complete(struct snd_pcm_substream *substream)
2680 {
2681 	struct snd_pcm_runtime *runtime = substream->runtime;
2682 	struct snd_pcm_hardware *hw = &runtime->hw;
2683 	int err;
2684 	unsigned int mask = 0;
2685 
2686         if (hw->info & SNDRV_PCM_INFO_INTERLEAVED)
2687 		mask |= PARAM_MASK_BIT(SNDRV_PCM_ACCESS_RW_INTERLEAVED);
2688         if (hw->info & SNDRV_PCM_INFO_NONINTERLEAVED)
2689 		mask |= PARAM_MASK_BIT(SNDRV_PCM_ACCESS_RW_NONINTERLEAVED);
2690 	if (hw_support_mmap(substream)) {
2691 		if (hw->info & SNDRV_PCM_INFO_INTERLEAVED)
2692 			mask |= PARAM_MASK_BIT(SNDRV_PCM_ACCESS_MMAP_INTERLEAVED);
2693 		if (hw->info & SNDRV_PCM_INFO_NONINTERLEAVED)
2694 			mask |= PARAM_MASK_BIT(SNDRV_PCM_ACCESS_MMAP_NONINTERLEAVED);
2695 		if (hw->info & SNDRV_PCM_INFO_COMPLEX)
2696 			mask |= PARAM_MASK_BIT(SNDRV_PCM_ACCESS_MMAP_COMPLEX);
2697 	}
2698 	err = snd_pcm_hw_constraint_mask(runtime, SNDRV_PCM_HW_PARAM_ACCESS, mask);
2699 	if (err < 0)
2700 		return err;
2701 
2702 	err = snd_pcm_hw_constraint_mask64(runtime, SNDRV_PCM_HW_PARAM_FORMAT, hw->formats);
2703 	if (err < 0)
2704 		return err;
2705 
2706 	err = snd_pcm_hw_constraint_subformats(runtime, 0, &hw->subformats);
2707 	if (err < 0)
2708 		return err;
2709 
2710 	err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_CHANNELS,
2711 					   hw->channels_min, hw->channels_max);
2712 	if (err < 0)
2713 		return err;
2714 
2715 	err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_RATE,
2716 					   hw->rate_min, hw->rate_max);
2717 	if (err < 0)
2718 		return err;
2719 
2720 	err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_BYTES,
2721 					   hw->period_bytes_min, hw->period_bytes_max);
2722 	if (err < 0)
2723 		return err;
2724 
2725 	err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIODS,
2726 					   hw->periods_min, hw->periods_max);
2727 	if (err < 0)
2728 		return err;
2729 
2730 	err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
2731 					   hw->period_bytes_min, hw->buffer_bytes_max);
2732 	if (err < 0)
2733 		return err;
2734 
2735 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
2736 				  snd_pcm_hw_rule_buffer_bytes_max, substream,
2737 				  SNDRV_PCM_HW_PARAM_BUFFER_BYTES, -1);
2738 	if (err < 0)
2739 		return err;
2740 
2741 	/* FIXME: remove */
2742 	if (runtime->dma_bytes) {
2743 		err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 0, runtime->dma_bytes);
2744 		if (err < 0)
2745 			return err;
2746 	}
2747 
2748 	if (!(hw->rates & (SNDRV_PCM_RATE_KNOT | SNDRV_PCM_RATE_CONTINUOUS))) {
2749 		err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
2750 					  snd_pcm_hw_rule_rate, hw,
2751 					  SNDRV_PCM_HW_PARAM_RATE, -1);
2752 		if (err < 0)
2753 			return err;
2754 	}
2755 
2756 	/* FIXME: this belong to lowlevel */
2757 	snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
2758 
2759 	return 0;
2760 }
2761 
2762 static void pcm_release_private(struct snd_pcm_substream *substream)
2763 {
2764 	if (snd_pcm_stream_linked(substream))
2765 		snd_pcm_unlink(substream);
2766 }
2767 
2768 void snd_pcm_release_substream(struct snd_pcm_substream *substream)
2769 {
2770 	substream->ref_count--;
2771 	if (substream->ref_count > 0)
2772 		return;
2773 
2774 	snd_pcm_drop(substream);
2775 	if (substream->hw_opened) {
2776 		if (substream->runtime->state != SNDRV_PCM_STATE_OPEN)
2777 			do_hw_free(substream);
2778 		substream->ops->close(substream);
2779 		substream->hw_opened = 0;
2780 	}
2781 	if (cpu_latency_qos_request_active(&substream->latency_pm_qos_req))
2782 		cpu_latency_qos_remove_request(&substream->latency_pm_qos_req);
2783 	if (substream->pcm_release) {
2784 		substream->pcm_release(substream);
2785 		substream->pcm_release = NULL;
2786 	}
2787 	snd_pcm_detach_substream(substream);
2788 }
2789 EXPORT_SYMBOL(snd_pcm_release_substream);
2790 
2791 int snd_pcm_open_substream(struct snd_pcm *pcm, int stream,
2792 			   struct file *file,
2793 			   struct snd_pcm_substream **rsubstream)
2794 {
2795 	struct snd_pcm_substream *substream;
2796 	int err;
2797 
2798 	err = snd_pcm_attach_substream(pcm, stream, file, &substream);
2799 	if (err < 0)
2800 		return err;
2801 	if (substream->ref_count > 1) {
2802 		*rsubstream = substream;
2803 		return 0;
2804 	}
2805 
2806 	err = snd_pcm_hw_constraints_init(substream);
2807 	if (err < 0) {
2808 		pcm_dbg(pcm, "snd_pcm_hw_constraints_init failed\n");
2809 		goto error;
2810 	}
2811 
2812 	err = substream->ops->open(substream);
2813 	if (err < 0)
2814 		goto error;
2815 
2816 	substream->hw_opened = 1;
2817 
2818 	err = snd_pcm_hw_constraints_complete(substream);
2819 	if (err < 0) {
2820 		pcm_dbg(pcm, "snd_pcm_hw_constraints_complete failed\n");
2821 		goto error;
2822 	}
2823 
2824 	/* automatically set EXPLICIT_SYNC flag in the managed mode whenever
2825 	 * the DMA buffer requires it
2826 	 */
2827 	if (substream->managed_buffer_alloc &&
2828 	    substream->dma_buffer.dev.need_sync)
2829 		substream->runtime->hw.info |= SNDRV_PCM_INFO_EXPLICIT_SYNC;
2830 
2831 	*rsubstream = substream;
2832 	return 0;
2833 
2834  error:
2835 	snd_pcm_release_substream(substream);
2836 	return err;
2837 }
2838 EXPORT_SYMBOL(snd_pcm_open_substream);
2839 
2840 static int snd_pcm_open_file(struct file *file,
2841 			     struct snd_pcm *pcm,
2842 			     int stream)
2843 {
2844 	struct snd_pcm_file *pcm_file;
2845 	struct snd_pcm_substream *substream;
2846 	int err;
2847 
2848 	err = snd_pcm_open_substream(pcm, stream, file, &substream);
2849 	if (err < 0)
2850 		return err;
2851 
2852 	pcm_file = kzalloc_obj(*pcm_file);
2853 	if (pcm_file == NULL) {
2854 		snd_pcm_release_substream(substream);
2855 		return -ENOMEM;
2856 	}
2857 	pcm_file->substream = substream;
2858 	if (substream->ref_count == 1)
2859 		substream->pcm_release = pcm_release_private;
2860 	file->private_data = pcm_file;
2861 
2862 	return 0;
2863 }
2864 
2865 static int snd_pcm_playback_open(struct inode *inode, struct file *file)
2866 {
2867 	struct snd_pcm *pcm;
2868 	int err = nonseekable_open(inode, file);
2869 	if (err < 0)
2870 		return err;
2871 	pcm = snd_lookup_minor_data(iminor(inode),
2872 				    SNDRV_DEVICE_TYPE_PCM_PLAYBACK);
2873 	err = snd_pcm_open(file, pcm, SNDRV_PCM_STREAM_PLAYBACK);
2874 	if (pcm)
2875 		snd_card_unref(pcm->card);
2876 	return err;
2877 }
2878 
2879 static int snd_pcm_capture_open(struct inode *inode, struct file *file)
2880 {
2881 	struct snd_pcm *pcm;
2882 	int err = nonseekable_open(inode, file);
2883 	if (err < 0)
2884 		return err;
2885 	pcm = snd_lookup_minor_data(iminor(inode),
2886 				    SNDRV_DEVICE_TYPE_PCM_CAPTURE);
2887 	err = snd_pcm_open(file, pcm, SNDRV_PCM_STREAM_CAPTURE);
2888 	if (pcm)
2889 		snd_card_unref(pcm->card);
2890 	return err;
2891 }
2892 
2893 static int snd_pcm_open(struct file *file, struct snd_pcm *pcm, int stream)
2894 {
2895 	int err;
2896 	wait_queue_entry_t wait;
2897 
2898 	if (pcm == NULL) {
2899 		err = -ENODEV;
2900 		goto __error1;
2901 	}
2902 	err = snd_card_file_add(pcm->card, file);
2903 	if (err < 0)
2904 		goto __error1;
2905 	if (!try_module_get(pcm->card->module)) {
2906 		err = -EFAULT;
2907 		goto __error2;
2908 	}
2909 	init_waitqueue_entry(&wait, current);
2910 	add_wait_queue(&pcm->open_wait, &wait);
2911 	mutex_lock(&pcm->open_mutex);
2912 	while (1) {
2913 		err = snd_pcm_open_file(file, pcm, stream);
2914 		if (err >= 0)
2915 			break;
2916 		if (err == -EAGAIN) {
2917 			if (file->f_flags & O_NONBLOCK) {
2918 				err = -EBUSY;
2919 				break;
2920 			}
2921 		} else
2922 			break;
2923 		set_current_state(TASK_INTERRUPTIBLE);
2924 		mutex_unlock(&pcm->open_mutex);
2925 		schedule();
2926 		mutex_lock(&pcm->open_mutex);
2927 		if (pcm->card->shutdown) {
2928 			err = -ENODEV;
2929 			break;
2930 		}
2931 		if (signal_pending(current)) {
2932 			err = -ERESTARTSYS;
2933 			break;
2934 		}
2935 	}
2936 	remove_wait_queue(&pcm->open_wait, &wait);
2937 	mutex_unlock(&pcm->open_mutex);
2938 	if (err < 0)
2939 		goto __error;
2940 	return err;
2941 
2942       __error:
2943 	module_put(pcm->card->module);
2944       __error2:
2945       	snd_card_file_remove(pcm->card, file);
2946       __error1:
2947       	return err;
2948 }
2949 
2950 static int snd_pcm_release(struct inode *inode, struct file *file)
2951 {
2952 	struct snd_pcm *pcm;
2953 	struct snd_pcm_substream *substream;
2954 	struct snd_pcm_file *pcm_file;
2955 
2956 	pcm_file = file->private_data;
2957 	substream = pcm_file->substream;
2958 	if (snd_BUG_ON(!substream))
2959 		return -ENXIO;
2960 	pcm = substream->pcm;
2961 
2962 	/* block until the device gets woken up as it may touch the hardware */
2963 	snd_power_wait(pcm->card);
2964 
2965 	scoped_guard(mutex, &pcm->open_mutex) {
2966 		snd_pcm_release_substream(substream);
2967 		kfree(pcm_file);
2968 	}
2969 	wake_up(&pcm->open_wait);
2970 	module_put(pcm->card->module);
2971 	snd_card_file_remove(pcm->card, file);
2972 	return 0;
2973 }
2974 
2975 /* check and update PCM state; return 0 or a negative error
2976  * call this inside PCM lock
2977  */
2978 static int do_pcm_hwsync(struct snd_pcm_substream *substream)
2979 {
2980 	switch (substream->runtime->state) {
2981 	case SNDRV_PCM_STATE_DRAINING:
2982 		if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
2983 			return -EBADFD;
2984 		fallthrough;
2985 	case SNDRV_PCM_STATE_RUNNING:
2986 		return snd_pcm_update_hw_ptr(substream);
2987 	case SNDRV_PCM_STATE_PREPARED:
2988 	case SNDRV_PCM_STATE_PAUSED:
2989 		return 0;
2990 	case SNDRV_PCM_STATE_SUSPENDED:
2991 		return -ESTRPIPE;
2992 	case SNDRV_PCM_STATE_XRUN:
2993 		return -EPIPE;
2994 	default:
2995 		return -EBADFD;
2996 	}
2997 }
2998 
2999 /* increase the appl_ptr; returns the processed frames or a negative error */
3000 static snd_pcm_sframes_t forward_appl_ptr(struct snd_pcm_substream *substream,
3001 					  snd_pcm_uframes_t frames,
3002 					   snd_pcm_sframes_t avail)
3003 {
3004 	struct snd_pcm_runtime *runtime = substream->runtime;
3005 	snd_pcm_sframes_t appl_ptr;
3006 	int ret;
3007 
3008 	if (avail <= 0)
3009 		return 0;
3010 	if (frames > (snd_pcm_uframes_t)avail)
3011 		frames = avail;
3012 	appl_ptr = runtime->control->appl_ptr + frames;
3013 	if (appl_ptr >= (snd_pcm_sframes_t)runtime->boundary)
3014 		appl_ptr -= runtime->boundary;
3015 	ret = pcm_lib_apply_appl_ptr(substream, appl_ptr);
3016 	return ret < 0 ? ret : frames;
3017 }
3018 
3019 /* decrease the appl_ptr; returns the processed frames or zero for error */
3020 static snd_pcm_sframes_t rewind_appl_ptr(struct snd_pcm_substream *substream,
3021 					 snd_pcm_uframes_t frames,
3022 					 snd_pcm_sframes_t avail)
3023 {
3024 	struct snd_pcm_runtime *runtime = substream->runtime;
3025 	snd_pcm_sframes_t appl_ptr;
3026 	int ret;
3027 
3028 	if (avail <= 0)
3029 		return 0;
3030 	if (frames > (snd_pcm_uframes_t)avail)
3031 		frames = avail;
3032 	appl_ptr = runtime->control->appl_ptr - frames;
3033 	if (appl_ptr < 0)
3034 		appl_ptr += runtime->boundary;
3035 	ret = pcm_lib_apply_appl_ptr(substream, appl_ptr);
3036 	/* NOTE: we return zero for errors because PulseAudio gets depressed
3037 	 * upon receiving an error from rewind ioctl and stops processing
3038 	 * any longer.  Returning zero means that no rewind is done, so
3039 	 * it's not absolutely wrong to answer like that.
3040 	 */
3041 	return ret < 0 ? 0 : frames;
3042 }
3043 
3044 static snd_pcm_sframes_t snd_pcm_rewind(struct snd_pcm_substream *substream,
3045 					snd_pcm_uframes_t frames)
3046 {
3047 	snd_pcm_sframes_t ret;
3048 
3049 	if (frames == 0)
3050 		return 0;
3051 
3052 	scoped_guard(pcm_stream_lock_irq, substream) {
3053 		ret = do_pcm_hwsync(substream);
3054 		if (!ret)
3055 			ret = rewind_appl_ptr(substream, frames,
3056 					      snd_pcm_hw_avail(substream));
3057 	}
3058 	if (ret >= 0)
3059 		snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE);
3060 	return ret;
3061 }
3062 
3063 static snd_pcm_sframes_t snd_pcm_forward(struct snd_pcm_substream *substream,
3064 					 snd_pcm_uframes_t frames)
3065 {
3066 	snd_pcm_sframes_t ret;
3067 
3068 	if (frames == 0)
3069 		return 0;
3070 
3071 	scoped_guard(pcm_stream_lock_irq, substream) {
3072 		ret = do_pcm_hwsync(substream);
3073 		if (!ret)
3074 			ret = forward_appl_ptr(substream, frames,
3075 					       snd_pcm_avail(substream));
3076 	}
3077 	if (ret >= 0)
3078 		snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE);
3079 	return ret;
3080 }
3081 
3082 static int snd_pcm_delay(struct snd_pcm_substream *substream,
3083 			 snd_pcm_sframes_t *delay)
3084 {
3085 	int err;
3086 
3087 	scoped_guard(pcm_stream_lock_irq, substream) {
3088 		err = do_pcm_hwsync(substream);
3089 		if (delay && !err)
3090 			*delay = snd_pcm_calc_delay(substream);
3091 	}
3092 	snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU);
3093 
3094 	return err;
3095 }
3096 
3097 static inline int snd_pcm_hwsync(struct snd_pcm_substream *substream)
3098 {
3099 	return snd_pcm_delay(substream, NULL);
3100 }
3101 
3102 #define snd_pcm_sync_ptr_get_user(__f, __c, __ptr) ({				\
3103 	__label__ failed, failed_begin;						\
3104 	int __err = -EFAULT;							\
3105 	typeof(*(__ptr)) __user *__src = (__ptr);				\
3106 										\
3107 	if (!user_read_access_begin(__src, sizeof(*__src)))			\
3108 		goto failed_begin;						\
3109 	unsafe_get_user(__f, &__src->flags, failed);				\
3110 	unsafe_get_user(__c.appl_ptr, &__src->c.control.appl_ptr, failed);	\
3111 	unsafe_get_user(__c.avail_min, &__src->c.control.avail_min, failed);	\
3112 	__err = 0;								\
3113 failed:										\
3114 	user_read_access_end();							\
3115 failed_begin:									\
3116 	__err;									\
3117 })
3118 
3119 #define snd_pcm_sync_ptr_put_user(__s, __c, __ptr) ({				\
3120 	__label__ failed, failed_begin;						\
3121 	int __err = -EFAULT;							\
3122 	typeof(*(__ptr)) __user *__src = (__ptr);				\
3123 										\
3124 	if (!user_write_access_begin(__src, sizeof(*__src)))			\
3125 		goto failed_begin;						\
3126 	unsafe_put_user(__s.state, &__src->s.status.state, failed);		\
3127 	unsafe_put_user(__s.hw_ptr, &__src->s.status.hw_ptr, failed);		\
3128 	unsafe_put_user(__s.tstamp.tv_sec, &__src->s.status.tstamp.tv_sec, failed);		\
3129 	unsafe_put_user(__s.tstamp.tv_nsec, &__src->s.status.tstamp.tv_nsec, failed);		\
3130 	unsafe_put_user(__s.suspended_state, &__src->s.status.suspended_state, failed);		\
3131 	unsafe_put_user(__s.audio_tstamp.tv_sec, &__src->s.status.audio_tstamp.tv_sec, failed);	\
3132 	unsafe_put_user(__s.audio_tstamp.tv_nsec, &__src->s.status.audio_tstamp.tv_nsec, failed);\
3133 	unsafe_put_user(__c.appl_ptr, &__src->c.control.appl_ptr, failed);	\
3134 	unsafe_put_user(__c.avail_min, &__src->c.control.avail_min, failed);	\
3135 	__err = 0;								\
3136 failed:										\
3137 	user_write_access_end();						\
3138 failed_begin:									\
3139 	__err;									\
3140 })
3141 
3142 static int snd_pcm_sync_ptr(struct snd_pcm_substream *substream,
3143 			    struct snd_pcm_sync_ptr __user *_sync_ptr)
3144 {
3145 	struct snd_pcm_runtime *runtime = substream->runtime;
3146 	volatile struct snd_pcm_mmap_status *status;
3147 	volatile struct snd_pcm_mmap_control *control;
3148 	u32 sflags;
3149 	struct snd_pcm_mmap_control scontrol;
3150 	struct snd_pcm_mmap_status sstatus;
3151 	int err;
3152 
3153 	if (snd_pcm_sync_ptr_get_user(sflags, scontrol, _sync_ptr))
3154 		return -EFAULT;
3155 	status = runtime->status;
3156 	control = runtime->control;
3157 	if (sflags & SNDRV_PCM_SYNC_PTR_HWSYNC) {
3158 		err = snd_pcm_hwsync(substream);
3159 		if (err < 0)
3160 			return err;
3161 	}
3162 	scoped_guard(pcm_stream_lock_irq, substream) {
3163 		if (!(sflags & SNDRV_PCM_SYNC_PTR_APPL)) {
3164 			err = pcm_lib_apply_appl_ptr(substream, scontrol.appl_ptr);
3165 			if (err < 0)
3166 				return err;
3167 		} else {
3168 			scontrol.appl_ptr = control->appl_ptr;
3169 		}
3170 		if (!(sflags & SNDRV_PCM_SYNC_PTR_AVAIL_MIN))
3171 			control->avail_min = scontrol.avail_min;
3172 		else
3173 			scontrol.avail_min = control->avail_min;
3174 		sstatus.state = status->state;
3175 		sstatus.hw_ptr = status->hw_ptr;
3176 		sstatus.tstamp = status->tstamp;
3177 		sstatus.suspended_state = status->suspended_state;
3178 		sstatus.audio_tstamp = status->audio_tstamp;
3179 	}
3180 	if (!(sflags & SNDRV_PCM_SYNC_PTR_APPL))
3181 		snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE);
3182 	if (snd_pcm_sync_ptr_put_user(sstatus, scontrol, _sync_ptr))
3183 		return -EFAULT;
3184 	return 0;
3185 }
3186 
3187 struct snd_pcm_mmap_status32 {
3188 	snd_pcm_state_t state;
3189 	s32 pad1;
3190 	u32 hw_ptr;
3191 	struct __snd_timespec tstamp;
3192 	snd_pcm_state_t suspended_state;
3193 	struct __snd_timespec audio_tstamp;
3194 } __packed;
3195 
3196 struct snd_pcm_mmap_control32 {
3197 	u32 appl_ptr;
3198 	u32 avail_min;
3199 };
3200 
3201 struct snd_pcm_sync_ptr32 {
3202 	u32 flags;
3203 	union {
3204 		struct snd_pcm_mmap_status32 status;
3205 		unsigned char reserved[64];
3206 	} s;
3207 	union {
3208 		struct snd_pcm_mmap_control32 control;
3209 		unsigned char reserved[64];
3210 	} c;
3211 } __packed;
3212 
3213 /* recalculate the boundary within 32bit */
3214 static snd_pcm_uframes_t recalculate_boundary(struct snd_pcm_runtime *runtime)
3215 {
3216 	snd_pcm_uframes_t boundary;
3217 	snd_pcm_uframes_t border;
3218 	int order;
3219 
3220 	if (! runtime->buffer_size)
3221 		return 0;
3222 
3223 	border = 0x7fffffffUL - runtime->buffer_size;
3224 	if (runtime->buffer_size > border)
3225 		return runtime->buffer_size;
3226 
3227 	order = __fls(border) - __fls(runtime->buffer_size);
3228 	boundary = runtime->buffer_size << order;
3229 
3230 	if (boundary <= border)
3231 		return boundary;
3232 	else
3233 		return boundary / 2;
3234 }
3235 
3236 static int snd_pcm_ioctl_sync_ptr_compat(struct snd_pcm_substream *substream,
3237 					 struct snd_pcm_sync_ptr32 __user *src)
3238 {
3239 	struct snd_pcm_runtime *runtime = substream->runtime;
3240 	volatile struct snd_pcm_mmap_status *status;
3241 	volatile struct snd_pcm_mmap_control *control;
3242 	u32 sflags;
3243 	struct snd_pcm_mmap_control scontrol;
3244 	struct snd_pcm_mmap_status sstatus;
3245 	snd_pcm_uframes_t boundary;
3246 	int err;
3247 
3248 	if (snd_BUG_ON(!runtime))
3249 		return -EINVAL;
3250 
3251 	if (snd_pcm_sync_ptr_get_user(sflags, scontrol, src))
3252 		return -EFAULT;
3253 	if (sflags & SNDRV_PCM_SYNC_PTR_HWSYNC) {
3254 		err = snd_pcm_hwsync(substream);
3255 		if (err < 0)
3256 			return err;
3257 	}
3258 	status = runtime->status;
3259 	control = runtime->control;
3260 	boundary = recalculate_boundary(runtime);
3261 	if (! boundary)
3262 		boundary = 0x7fffffff;
3263 	scoped_guard(pcm_stream_lock_irq, substream) {
3264 		/* FIXME: we should consider the boundary for the sync from app */
3265 		if (!(sflags & SNDRV_PCM_SYNC_PTR_APPL)) {
3266 			err = pcm_lib_apply_appl_ptr(substream,
3267 						     scontrol.appl_ptr);
3268 			if (err < 0)
3269 				return err;
3270 		} else
3271 			scontrol.appl_ptr = control->appl_ptr % boundary;
3272 		if (!(sflags & SNDRV_PCM_SYNC_PTR_AVAIL_MIN))
3273 			control->avail_min = scontrol.avail_min;
3274 		else
3275 			scontrol.avail_min = control->avail_min;
3276 		sstatus.state = status->state;
3277 		sstatus.hw_ptr = status->hw_ptr % boundary;
3278 		sstatus.tstamp = status->tstamp;
3279 		sstatus.suspended_state = status->suspended_state;
3280 		sstatus.audio_tstamp = status->audio_tstamp;
3281 	}
3282 	if (!(sflags & SNDRV_PCM_SYNC_PTR_APPL))
3283 		snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE);
3284 	if (snd_pcm_sync_ptr_put_user(sstatus, scontrol, src))
3285 		return -EFAULT;
3286 
3287 	return 0;
3288 }
3289 #define __SNDRV_PCM_IOCTL_SYNC_PTR32 _IOWR('A', 0x23, struct snd_pcm_sync_ptr32)
3290 
3291 static int snd_pcm_tstamp(struct snd_pcm_substream *substream, int __user *_arg)
3292 {
3293 	struct snd_pcm_runtime *runtime = substream->runtime;
3294 	int arg;
3295 
3296 	if (get_user(arg, _arg))
3297 		return -EFAULT;
3298 	if (arg < 0 || arg > SNDRV_PCM_TSTAMP_TYPE_LAST)
3299 		return -EINVAL;
3300 	runtime->tstamp_type = arg;
3301 	return 0;
3302 }
3303 
3304 static int snd_pcm_xferi_frames_ioctl(struct snd_pcm_substream *substream,
3305 				      struct snd_xferi __user *_xferi)
3306 {
3307 	struct snd_xferi xferi;
3308 	snd_pcm_sframes_t result;
3309 
3310 	if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN)
3311 		return -EBADFD;
3312 	if (put_user(0, &_xferi->result))
3313 		return -EFAULT;
3314 	if (copy_from_user(&xferi, _xferi, sizeof(xferi)))
3315 		return -EFAULT;
3316 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
3317 		result = snd_pcm_lib_write(substream, xferi.buf, xferi.frames);
3318 	else
3319 		result = snd_pcm_lib_read(substream, xferi.buf, xferi.frames);
3320 	if (put_user(result, &_xferi->result))
3321 		return -EFAULT;
3322 	return result < 0 ? result : 0;
3323 }
3324 
3325 static int snd_pcm_xfern_frames_ioctl(struct snd_pcm_substream *substream,
3326 				      struct snd_xfern __user *_xfern)
3327 {
3328 	struct snd_xfern xfern;
3329 	struct snd_pcm_runtime *runtime = substream->runtime;
3330 	void *bufs __free(kfree) = NULL;
3331 	snd_pcm_sframes_t result;
3332 
3333 	if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_OPEN)
3334 		return -EBADFD;
3335 	if (runtime->channels > 128)
3336 		return -EINVAL;
3337 	if (put_user(0, &_xfern->result))
3338 		return -EFAULT;
3339 	if (copy_from_user(&xfern, _xfern, sizeof(xfern)))
3340 		return -EFAULT;
3341 
3342 	bufs = memdup_array_user(xfern.bufs, runtime->channels, sizeof(void *));
3343 	if (IS_ERR(bufs))
3344 		return PTR_ERR(bufs);
3345 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
3346 		result = snd_pcm_lib_writev(substream, bufs, xfern.frames);
3347 	else
3348 		result = snd_pcm_lib_readv(substream, bufs, xfern.frames);
3349 	if (put_user(result, &_xfern->result))
3350 		return -EFAULT;
3351 	return result < 0 ? result : 0;
3352 }
3353 
3354 static int snd_pcm_rewind_ioctl(struct snd_pcm_substream *substream,
3355 				snd_pcm_uframes_t __user *_frames)
3356 {
3357 	snd_pcm_uframes_t frames;
3358 	snd_pcm_sframes_t result;
3359 
3360 	if (get_user(frames, _frames))
3361 		return -EFAULT;
3362 	if (put_user(0, _frames))
3363 		return -EFAULT;
3364 	result = snd_pcm_rewind(substream, frames);
3365 	if (put_user(result, _frames))
3366 		return -EFAULT;
3367 	return result < 0 ? result : 0;
3368 }
3369 
3370 static int snd_pcm_forward_ioctl(struct snd_pcm_substream *substream,
3371 				 snd_pcm_uframes_t __user *_frames)
3372 {
3373 	snd_pcm_uframes_t frames;
3374 	snd_pcm_sframes_t result;
3375 
3376 	if (get_user(frames, _frames))
3377 		return -EFAULT;
3378 	if (put_user(0, _frames))
3379 		return -EFAULT;
3380 	result = snd_pcm_forward(substream, frames);
3381 	if (put_user(result, _frames))
3382 		return -EFAULT;
3383 	return result < 0 ? result : 0;
3384 }
3385 
3386 static int snd_pcm_common_ioctl(struct file *file,
3387 				 struct snd_pcm_substream *substream,
3388 				 unsigned int cmd, void __user *arg)
3389 {
3390 	struct snd_pcm_file *pcm_file = file->private_data;
3391 	int res;
3392 
3393 	if (PCM_RUNTIME_CHECK(substream))
3394 		return -ENXIO;
3395 
3396 	if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_DISCONNECTED)
3397 		return -EBADFD;
3398 
3399 	res = snd_power_wait(substream->pcm->card);
3400 	if (res < 0)
3401 		return res;
3402 
3403 	switch (cmd) {
3404 	case SNDRV_PCM_IOCTL_PVERSION:
3405 		return put_user(SNDRV_PCM_VERSION, (int __user *)arg) ? -EFAULT : 0;
3406 	case SNDRV_PCM_IOCTL_INFO:
3407 		return snd_pcm_info_user(substream, arg);
3408 	case SNDRV_PCM_IOCTL_TSTAMP:	/* just for compatibility */
3409 		return 0;
3410 	case SNDRV_PCM_IOCTL_TTSTAMP:
3411 		return snd_pcm_tstamp(substream, arg);
3412 	case SNDRV_PCM_IOCTL_USER_PVERSION:
3413 		if (get_user(pcm_file->user_pversion,
3414 			     (unsigned int __user *)arg))
3415 			return -EFAULT;
3416 		return 0;
3417 	case SNDRV_PCM_IOCTL_HW_REFINE:
3418 		return snd_pcm_hw_refine_user(substream, arg);
3419 	case SNDRV_PCM_IOCTL_HW_PARAMS:
3420 		return snd_pcm_hw_params_user(substream, arg);
3421 	case SNDRV_PCM_IOCTL_HW_FREE:
3422 		return snd_pcm_hw_free(substream);
3423 	case SNDRV_PCM_IOCTL_SW_PARAMS:
3424 		return snd_pcm_sw_params_user(substream, arg);
3425 	case SNDRV_PCM_IOCTL_STATUS32:
3426 		return snd_pcm_status_user32(substream, arg, false);
3427 	case SNDRV_PCM_IOCTL_STATUS_EXT32:
3428 		return snd_pcm_status_user32(substream, arg, true);
3429 	case SNDRV_PCM_IOCTL_STATUS64:
3430 		return snd_pcm_status_user64(substream, arg, false);
3431 	case SNDRV_PCM_IOCTL_STATUS_EXT64:
3432 		return snd_pcm_status_user64(substream, arg, true);
3433 	case SNDRV_PCM_IOCTL_CHANNEL_INFO:
3434 		return snd_pcm_channel_info_user(substream, arg);
3435 	case SNDRV_PCM_IOCTL_PREPARE:
3436 		return snd_pcm_prepare(substream, file);
3437 	case SNDRV_PCM_IOCTL_RESET:
3438 		return snd_pcm_reset(substream);
3439 	case SNDRV_PCM_IOCTL_START:
3440 		return snd_pcm_start_lock_irq(substream);
3441 	case SNDRV_PCM_IOCTL_LINK:
3442 		return snd_pcm_link(substream, (int)(unsigned long) arg);
3443 	case SNDRV_PCM_IOCTL_UNLINK:
3444 		return snd_pcm_unlink(substream);
3445 	case SNDRV_PCM_IOCTL_RESUME:
3446 		return snd_pcm_resume(substream);
3447 	case SNDRV_PCM_IOCTL_XRUN:
3448 		return snd_pcm_xrun(substream);
3449 	case SNDRV_PCM_IOCTL_HWSYNC:
3450 		return snd_pcm_hwsync(substream);
3451 	case SNDRV_PCM_IOCTL_DELAY:
3452 	{
3453 		snd_pcm_sframes_t delay = 0;
3454 		snd_pcm_sframes_t __user *res = arg;
3455 		int err;
3456 
3457 		err = snd_pcm_delay(substream, &delay);
3458 		if (err)
3459 			return err;
3460 		if (put_user(delay, res))
3461 			return -EFAULT;
3462 		return 0;
3463 	}
3464 	case __SNDRV_PCM_IOCTL_SYNC_PTR32:
3465 		return snd_pcm_ioctl_sync_ptr_compat(substream, arg);
3466 	case __SNDRV_PCM_IOCTL_SYNC_PTR64:
3467 		return snd_pcm_sync_ptr(substream, arg);
3468 #ifdef CONFIG_SND_SUPPORT_OLD_API
3469 	case SNDRV_PCM_IOCTL_HW_REFINE_OLD:
3470 		return snd_pcm_hw_refine_old_user(substream, arg);
3471 	case SNDRV_PCM_IOCTL_HW_PARAMS_OLD:
3472 		return snd_pcm_hw_params_old_user(substream, arg);
3473 #endif
3474 	case SNDRV_PCM_IOCTL_DRAIN:
3475 		return snd_pcm_drain(substream, file);
3476 	case SNDRV_PCM_IOCTL_DROP:
3477 		return snd_pcm_drop(substream);
3478 	case SNDRV_PCM_IOCTL_PAUSE:
3479 		return snd_pcm_pause_lock_irq(substream, (unsigned long)arg);
3480 	case SNDRV_PCM_IOCTL_WRITEI_FRAMES:
3481 	case SNDRV_PCM_IOCTL_READI_FRAMES:
3482 		return snd_pcm_xferi_frames_ioctl(substream, arg);
3483 	case SNDRV_PCM_IOCTL_WRITEN_FRAMES:
3484 	case SNDRV_PCM_IOCTL_READN_FRAMES:
3485 		return snd_pcm_xfern_frames_ioctl(substream, arg);
3486 	case SNDRV_PCM_IOCTL_REWIND:
3487 		return snd_pcm_rewind_ioctl(substream, arg);
3488 	case SNDRV_PCM_IOCTL_FORWARD:
3489 		return snd_pcm_forward_ioctl(substream, arg);
3490 	}
3491 	pcm_dbg(substream->pcm, "unknown ioctl = 0x%x\n", cmd);
3492 	return -ENOTTY;
3493 }
3494 
3495 static long snd_pcm_ioctl(struct file *file, unsigned int cmd,
3496 			  unsigned long arg)
3497 {
3498 	struct snd_pcm_file *pcm_file;
3499 
3500 	pcm_file = file->private_data;
3501 
3502 	if (((cmd >> 8) & 0xff) != 'A')
3503 		return -ENOTTY;
3504 
3505 	return snd_pcm_common_ioctl(file, pcm_file->substream, cmd,
3506 				     (void __user *)arg);
3507 }
3508 
3509 /**
3510  * snd_pcm_kernel_ioctl - Execute PCM ioctl in the kernel-space
3511  * @substream: PCM substream
3512  * @cmd: IOCTL cmd
3513  * @arg: IOCTL argument
3514  *
3515  * The function is provided primarily for OSS layer and USB gadget drivers,
3516  * and it allows only the limited set of ioctls (hw_params, sw_params,
3517  * prepare, start, drain, drop, forward).
3518  *
3519  * Return: zero if successful, or a negative error code
3520  */
3521 int snd_pcm_kernel_ioctl(struct snd_pcm_substream *substream,
3522 			 unsigned int cmd, void *arg)
3523 {
3524 	snd_pcm_uframes_t *frames = arg;
3525 	snd_pcm_sframes_t result;
3526 
3527 	if (snd_pcm_get_state(substream) == SNDRV_PCM_STATE_DISCONNECTED)
3528 		return -EBADFD;
3529 
3530 	switch (cmd) {
3531 	case SNDRV_PCM_IOCTL_FORWARD:
3532 	{
3533 		/* provided only for OSS; capture-only and no value returned */
3534 		if (substream->stream != SNDRV_PCM_STREAM_CAPTURE)
3535 			return -EINVAL;
3536 		result = snd_pcm_forward(substream, *frames);
3537 		return result < 0 ? result : 0;
3538 	}
3539 	case SNDRV_PCM_IOCTL_HW_PARAMS:
3540 		return snd_pcm_hw_params(substream, arg);
3541 	case SNDRV_PCM_IOCTL_SW_PARAMS:
3542 		return snd_pcm_sw_params(substream, arg);
3543 	case SNDRV_PCM_IOCTL_PREPARE:
3544 		return snd_pcm_prepare(substream, NULL);
3545 	case SNDRV_PCM_IOCTL_START:
3546 		return snd_pcm_start_lock_irq(substream);
3547 	case SNDRV_PCM_IOCTL_DRAIN:
3548 		return snd_pcm_drain(substream, NULL);
3549 	case SNDRV_PCM_IOCTL_DROP:
3550 		return snd_pcm_drop(substream);
3551 	case SNDRV_PCM_IOCTL_DELAY:
3552 		return snd_pcm_delay(substream, frames);
3553 	default:
3554 		return -EINVAL;
3555 	}
3556 }
3557 EXPORT_SYMBOL(snd_pcm_kernel_ioctl);
3558 
3559 static ssize_t snd_pcm_read(struct file *file, char __user *buf, size_t count,
3560 			    loff_t * offset)
3561 {
3562 	struct snd_pcm_file *pcm_file;
3563 	struct snd_pcm_substream *substream;
3564 	struct snd_pcm_runtime *runtime;
3565 	snd_pcm_sframes_t result;
3566 
3567 	pcm_file = file->private_data;
3568 	substream = pcm_file->substream;
3569 	if (PCM_RUNTIME_CHECK(substream))
3570 		return -ENXIO;
3571 	runtime = substream->runtime;
3572 	if (runtime->state == SNDRV_PCM_STATE_OPEN ||
3573 	    runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
3574 		return -EBADFD;
3575 	if (!frame_aligned(runtime, count))
3576 		return -EINVAL;
3577 	count = bytes_to_frames(runtime, count);
3578 	result = snd_pcm_lib_read(substream, buf, count);
3579 	if (result > 0)
3580 		result = frames_to_bytes(runtime, result);
3581 	return result;
3582 }
3583 
3584 static ssize_t snd_pcm_write(struct file *file, const char __user *buf,
3585 			     size_t count, loff_t * offset)
3586 {
3587 	struct snd_pcm_file *pcm_file;
3588 	struct snd_pcm_substream *substream;
3589 	struct snd_pcm_runtime *runtime;
3590 	snd_pcm_sframes_t result;
3591 
3592 	pcm_file = file->private_data;
3593 	substream = pcm_file->substream;
3594 	if (PCM_RUNTIME_CHECK(substream))
3595 		return -ENXIO;
3596 	runtime = substream->runtime;
3597 	if (runtime->state == SNDRV_PCM_STATE_OPEN ||
3598 	    runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
3599 		return -EBADFD;
3600 	if (!frame_aligned(runtime, count))
3601 		return -EINVAL;
3602 	count = bytes_to_frames(runtime, count);
3603 	result = snd_pcm_lib_write(substream, buf, count);
3604 	if (result > 0)
3605 		result = frames_to_bytes(runtime, result);
3606 	return result;
3607 }
3608 
3609 static ssize_t snd_pcm_readv(struct kiocb *iocb, struct iov_iter *to)
3610 {
3611 	struct snd_pcm_file *pcm_file;
3612 	struct snd_pcm_substream *substream;
3613 	struct snd_pcm_runtime *runtime;
3614 	snd_pcm_sframes_t result;
3615 	unsigned long i;
3616 	snd_pcm_uframes_t frames;
3617 	const struct iovec *iov = iter_iov(to);
3618 
3619 	pcm_file = iocb->ki_filp->private_data;
3620 	substream = pcm_file->substream;
3621 	if (PCM_RUNTIME_CHECK(substream))
3622 		return -ENXIO;
3623 	runtime = substream->runtime;
3624 	if (runtime->state == SNDRV_PCM_STATE_OPEN ||
3625 	    runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
3626 		return -EBADFD;
3627 	if (!user_backed_iter(to))
3628 		return -EINVAL;
3629 	if (to->nr_segs > 1024 || to->nr_segs != runtime->channels)
3630 		return -EINVAL;
3631 	if (!frame_aligned(runtime, iov->iov_len))
3632 		return -EINVAL;
3633 	frames = bytes_to_samples(runtime, iov->iov_len);
3634 
3635 	void __user **bufs __free(kfree) =
3636 		kmalloc_array(to->nr_segs, sizeof(void *), GFP_KERNEL);
3637 	if (bufs == NULL)
3638 		return -ENOMEM;
3639 	for (i = 0; i < to->nr_segs; ++i) {
3640 		bufs[i] = iov->iov_base;
3641 		iov++;
3642 	}
3643 	result = snd_pcm_lib_readv(substream, bufs, frames);
3644 	if (result > 0)
3645 		result = frames_to_bytes(runtime, result);
3646 	return result;
3647 }
3648 
3649 static ssize_t snd_pcm_writev(struct kiocb *iocb, struct iov_iter *from)
3650 {
3651 	struct snd_pcm_file *pcm_file;
3652 	struct snd_pcm_substream *substream;
3653 	struct snd_pcm_runtime *runtime;
3654 	snd_pcm_sframes_t result;
3655 	unsigned long i;
3656 	snd_pcm_uframes_t frames;
3657 	const struct iovec *iov = iter_iov(from);
3658 
3659 	pcm_file = iocb->ki_filp->private_data;
3660 	substream = pcm_file->substream;
3661 	if (PCM_RUNTIME_CHECK(substream))
3662 		return -ENXIO;
3663 	runtime = substream->runtime;
3664 	if (runtime->state == SNDRV_PCM_STATE_OPEN ||
3665 	    runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
3666 		return -EBADFD;
3667 	if (!user_backed_iter(from))
3668 		return -EINVAL;
3669 	if (from->nr_segs > 128 || from->nr_segs != runtime->channels ||
3670 	    !frame_aligned(runtime, iov->iov_len))
3671 		return -EINVAL;
3672 	frames = bytes_to_samples(runtime, iov->iov_len);
3673 
3674 	void __user **bufs __free(kfree) =
3675 		kmalloc_array(from->nr_segs, sizeof(void *), GFP_KERNEL);
3676 	if (bufs == NULL)
3677 		return -ENOMEM;
3678 	for (i = 0; i < from->nr_segs; ++i) {
3679 		bufs[i] = iov->iov_base;
3680 		iov++;
3681 	}
3682 	result = snd_pcm_lib_writev(substream, bufs, frames);
3683 	if (result > 0)
3684 		result = frames_to_bytes(runtime, result);
3685 	return result;
3686 }
3687 
3688 static __poll_t snd_pcm_poll(struct file *file, poll_table *wait)
3689 {
3690 	struct snd_pcm_file *pcm_file;
3691 	struct snd_pcm_substream *substream;
3692 	struct snd_pcm_runtime *runtime;
3693 	__poll_t mask, ok;
3694 	snd_pcm_uframes_t avail;
3695 
3696 	pcm_file = file->private_data;
3697 
3698 	substream = pcm_file->substream;
3699 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
3700 		ok = EPOLLOUT | EPOLLWRNORM;
3701 	else
3702 		ok = EPOLLIN | EPOLLRDNORM;
3703 	if (PCM_RUNTIME_CHECK(substream))
3704 		return ok | EPOLLERR;
3705 
3706 	runtime = substream->runtime;
3707 	if (runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
3708 		return ok | EPOLLERR;
3709 
3710 	poll_wait(file, &runtime->sleep, wait);
3711 
3712 	mask = 0;
3713 	guard(pcm_stream_lock_irq)(substream);
3714 	avail = snd_pcm_avail(substream);
3715 	switch (runtime->state) {
3716 	case SNDRV_PCM_STATE_RUNNING:
3717 	case SNDRV_PCM_STATE_PREPARED:
3718 	case SNDRV_PCM_STATE_PAUSED:
3719 		if (avail >= runtime->control->avail_min)
3720 			mask = ok;
3721 		break;
3722 	case SNDRV_PCM_STATE_DRAINING:
3723 		if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
3724 			mask = ok;
3725 			if (!avail)
3726 				mask |= EPOLLERR;
3727 		}
3728 		break;
3729 	default:
3730 		mask = ok | EPOLLERR;
3731 		break;
3732 	}
3733 	return mask;
3734 }
3735 
3736 /*
3737  * mmap support
3738  */
3739 
3740 /*
3741  * Only on coherent architectures, we can mmap the status and the control records
3742  * for effcient data transfer.  On others, we have to use HWSYNC ioctl...
3743  */
3744 #if defined(CONFIG_X86) || defined(CONFIG_PPC) || defined(CONFIG_ALPHA)
3745 /*
3746  * mmap status record
3747  */
3748 static vm_fault_t snd_pcm_mmap_status_fault(struct vm_fault *vmf)
3749 {
3750 	struct snd_pcm_substream *substream = vmf->vma->vm_private_data;
3751 	struct snd_pcm_runtime *runtime;
3752 
3753 	if (substream == NULL)
3754 		return VM_FAULT_SIGBUS;
3755 	runtime = substream->runtime;
3756 	vmf->page = virt_to_page(runtime->status);
3757 	get_page(vmf->page);
3758 	return 0;
3759 }
3760 
3761 static const struct vm_operations_struct snd_pcm_vm_ops_status =
3762 {
3763 	.fault =	snd_pcm_mmap_status_fault,
3764 };
3765 
3766 static int snd_pcm_mmap_status(struct snd_pcm_substream *substream, struct file *file,
3767 			       struct vm_area_struct *area)
3768 {
3769 	long size;
3770 	if (!(area->vm_flags & VM_READ))
3771 		return -EINVAL;
3772 	size = area->vm_end - area->vm_start;
3773 	if (size != PAGE_ALIGN(sizeof(struct snd_pcm_mmap_status)))
3774 		return -EINVAL;
3775 	area->vm_ops = &snd_pcm_vm_ops_status;
3776 	area->vm_private_data = substream;
3777 	vm_flags_mod(area, VM_DONTEXPAND | VM_DONTDUMP,
3778 		     VM_WRITE | VM_MAYWRITE);
3779 
3780 	return 0;
3781 }
3782 
3783 /*
3784  * mmap control record
3785  */
3786 static vm_fault_t snd_pcm_mmap_control_fault(struct vm_fault *vmf)
3787 {
3788 	struct snd_pcm_substream *substream = vmf->vma->vm_private_data;
3789 	struct snd_pcm_runtime *runtime;
3790 
3791 	if (substream == NULL)
3792 		return VM_FAULT_SIGBUS;
3793 	runtime = substream->runtime;
3794 	vmf->page = virt_to_page(runtime->control);
3795 	get_page(vmf->page);
3796 	return 0;
3797 }
3798 
3799 static const struct vm_operations_struct snd_pcm_vm_ops_control =
3800 {
3801 	.fault =	snd_pcm_mmap_control_fault,
3802 };
3803 
3804 static int snd_pcm_mmap_control(struct snd_pcm_substream *substream, struct file *file,
3805 				struct vm_area_struct *area)
3806 {
3807 	long size;
3808 	if (!(area->vm_flags & VM_READ))
3809 		return -EINVAL;
3810 	size = area->vm_end - area->vm_start;
3811 	if (size != PAGE_ALIGN(sizeof(struct snd_pcm_mmap_control)))
3812 		return -EINVAL;
3813 	area->vm_ops = &snd_pcm_vm_ops_control;
3814 	area->vm_private_data = substream;
3815 	vm_flags_set(area, VM_DONTEXPAND | VM_DONTDUMP);
3816 	return 0;
3817 }
3818 
3819 static bool pcm_status_mmap_allowed(struct snd_pcm_file *pcm_file)
3820 {
3821 	/* If drivers require the explicit sync (typically for non-coherent
3822 	 * pages), we have to disable the mmap of status and control data
3823 	 * to enforce the control via SYNC_PTR ioctl.
3824 	 */
3825 	if (pcm_file->substream->runtime->hw.info & SNDRV_PCM_INFO_EXPLICIT_SYNC)
3826 		return false;
3827 	/* See pcm_control_mmap_allowed() below.
3828 	 * Since older alsa-lib requires both status and control mmaps to be
3829 	 * coupled, we have to disable the status mmap for old alsa-lib, too.
3830 	 */
3831 	if (pcm_file->user_pversion < SNDRV_PROTOCOL_VERSION(2, 0, 14) &&
3832 	    (pcm_file->substream->runtime->hw.info & SNDRV_PCM_INFO_SYNC_APPLPTR))
3833 		return false;
3834 	return true;
3835 }
3836 
3837 static bool pcm_control_mmap_allowed(struct snd_pcm_file *pcm_file)
3838 {
3839 	if (pcm_file->no_compat_mmap)
3840 		return false;
3841 	/* see above */
3842 	if (pcm_file->substream->runtime->hw.info & SNDRV_PCM_INFO_EXPLICIT_SYNC)
3843 		return false;
3844 	/* Disallow the control mmap when SYNC_APPLPTR flag is set;
3845 	 * it enforces the user-space to fall back to snd_pcm_sync_ptr(),
3846 	 * thus it effectively assures the manual update of appl_ptr.
3847 	 */
3848 	if (pcm_file->substream->runtime->hw.info & SNDRV_PCM_INFO_SYNC_APPLPTR)
3849 		return false;
3850 	return true;
3851 }
3852 
3853 #else /* ! coherent mmap */
3854 /*
3855  * don't support mmap for status and control records.
3856  */
3857 #define pcm_status_mmap_allowed(pcm_file)	false
3858 #define pcm_control_mmap_allowed(pcm_file)	false
3859 
3860 static int snd_pcm_mmap_status(struct snd_pcm_substream *substream, struct file *file,
3861 			       struct vm_area_struct *area)
3862 {
3863 	return -ENXIO;
3864 }
3865 static int snd_pcm_mmap_control(struct snd_pcm_substream *substream, struct file *file,
3866 				struct vm_area_struct *area)
3867 {
3868 	return -ENXIO;
3869 }
3870 #endif /* coherent mmap */
3871 
3872 /*
3873  * snd_pcm_mmap_data_open - increase the mmap counter
3874  */
3875 static void snd_pcm_mmap_data_open(struct vm_area_struct *area)
3876 {
3877 	struct snd_pcm_substream *substream = area->vm_private_data;
3878 
3879 	atomic_inc(&substream->mmap_count);
3880 }
3881 
3882 /*
3883  * snd_pcm_mmap_data_close - decrease the mmap counter
3884  */
3885 static void snd_pcm_mmap_data_close(struct vm_area_struct *area)
3886 {
3887 	struct snd_pcm_substream *substream = area->vm_private_data;
3888 
3889 	atomic_dec(&substream->mmap_count);
3890 }
3891 
3892 /*
3893  * fault callback for mmapping a RAM page
3894  */
3895 static vm_fault_t snd_pcm_mmap_data_fault(struct vm_fault *vmf)
3896 {
3897 	struct snd_pcm_substream *substream = vmf->vma->vm_private_data;
3898 	struct snd_pcm_runtime *runtime;
3899 	unsigned long offset;
3900 	struct page * page;
3901 	size_t dma_bytes;
3902 
3903 	if (substream == NULL)
3904 		return VM_FAULT_SIGBUS;
3905 	runtime = substream->runtime;
3906 	offset = vmf->pgoff << PAGE_SHIFT;
3907 	dma_bytes = PAGE_ALIGN(runtime->dma_bytes);
3908 	if (offset > dma_bytes - PAGE_SIZE)
3909 		return VM_FAULT_SIGBUS;
3910 	if (substream->ops->page)
3911 		page = substream->ops->page(substream, offset);
3912 	else if (!snd_pcm_get_dma_buf(substream)) {
3913 		if (WARN_ON_ONCE(!runtime->dma_area))
3914 			return VM_FAULT_SIGBUS;
3915 		page = virt_to_page(runtime->dma_area + offset);
3916 	} else
3917 		page = snd_sgbuf_get_page(snd_pcm_get_dma_buf(substream), offset);
3918 	if (!page)
3919 		return VM_FAULT_SIGBUS;
3920 	get_page(page);
3921 	vmf->page = page;
3922 	return 0;
3923 }
3924 
3925 static const struct vm_operations_struct snd_pcm_vm_ops_data = {
3926 	.open =		snd_pcm_mmap_data_open,
3927 	.close =	snd_pcm_mmap_data_close,
3928 };
3929 
3930 static const struct vm_operations_struct snd_pcm_vm_ops_data_fault = {
3931 	.open =		snd_pcm_mmap_data_open,
3932 	.close =	snd_pcm_mmap_data_close,
3933 	.fault =	snd_pcm_mmap_data_fault,
3934 };
3935 
3936 /*
3937  * mmap the DMA buffer on RAM
3938  */
3939 
3940 /**
3941  * snd_pcm_lib_default_mmap - Default PCM data mmap function
3942  * @substream: PCM substream
3943  * @area: VMA
3944  *
3945  * This is the default mmap handler for PCM data.  When mmap pcm_ops is NULL,
3946  * this function is invoked implicitly.
3947  *
3948  * Return: zero if successful, or a negative error code
3949  */
3950 int snd_pcm_lib_default_mmap(struct snd_pcm_substream *substream,
3951 			     struct vm_area_struct *area)
3952 {
3953 	vm_flags_set(area, VM_DONTEXPAND | VM_DONTDUMP);
3954 	if (!substream->ops->page &&
3955 	    !snd_dma_buffer_mmap(snd_pcm_get_dma_buf(substream), area))
3956 		return 0;
3957 	/* mmap with fault handler */
3958 	area->vm_ops = &snd_pcm_vm_ops_data_fault;
3959 	return 0;
3960 }
3961 EXPORT_SYMBOL_GPL(snd_pcm_lib_default_mmap);
3962 
3963 /*
3964  * mmap the DMA buffer on I/O memory area
3965  */
3966 #if SNDRV_PCM_INFO_MMAP_IOMEM
3967 /**
3968  * snd_pcm_lib_mmap_iomem - Default PCM data mmap function for I/O mem
3969  * @substream: PCM substream
3970  * @area: VMA
3971  *
3972  * When your hardware uses the iomapped pages as the hardware buffer and
3973  * wants to mmap it, pass this function as mmap pcm_ops.  Note that this
3974  * is supposed to work only on limited architectures.
3975  *
3976  * Return: zero if successful, or a negative error code
3977  */
3978 int snd_pcm_lib_mmap_iomem(struct snd_pcm_substream *substream,
3979 			   struct vm_area_struct *area)
3980 {
3981 	struct snd_pcm_runtime *runtime = substream->runtime;
3982 
3983 	area->vm_page_prot = pgprot_noncached(area->vm_page_prot);
3984 	return vm_iomap_memory(area, runtime->dma_addr, runtime->dma_bytes);
3985 }
3986 EXPORT_SYMBOL(snd_pcm_lib_mmap_iomem);
3987 #endif /* SNDRV_PCM_INFO_MMAP */
3988 
3989 /*
3990  * mmap DMA buffer
3991  */
3992 int snd_pcm_mmap_data(struct snd_pcm_substream *substream, struct file *file,
3993 		      struct vm_area_struct *area)
3994 {
3995 	struct snd_pcm_runtime *runtime;
3996 	long size;
3997 	unsigned long offset;
3998 	size_t dma_bytes;
3999 	int err;
4000 
4001 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
4002 		if (!(area->vm_flags & (VM_WRITE|VM_READ)))
4003 			return -EINVAL;
4004 	} else {
4005 		if (!(area->vm_flags & VM_READ))
4006 			return -EINVAL;
4007 	}
4008 	runtime = substream->runtime;
4009 	if (runtime->state == SNDRV_PCM_STATE_OPEN)
4010 		return -EBADFD;
4011 	if (!(runtime->info & SNDRV_PCM_INFO_MMAP))
4012 		return -ENXIO;
4013 	if (runtime->access == SNDRV_PCM_ACCESS_RW_INTERLEAVED ||
4014 	    runtime->access == SNDRV_PCM_ACCESS_RW_NONINTERLEAVED)
4015 		return -EINVAL;
4016 	size = area->vm_end - area->vm_start;
4017 	offset = area->vm_pgoff << PAGE_SHIFT;
4018 	dma_bytes = PAGE_ALIGN(runtime->dma_bytes);
4019 	if ((size_t)size > dma_bytes)
4020 		return -EINVAL;
4021 	if (offset > dma_bytes - size)
4022 		return -EINVAL;
4023 
4024 	area->vm_ops = &snd_pcm_vm_ops_data;
4025 	area->vm_private_data = substream;
4026 	if (substream->ops->mmap)
4027 		err = substream->ops->mmap(substream, area);
4028 	else
4029 		err = snd_pcm_lib_default_mmap(substream, area);
4030 	if (!err)
4031 		atomic_inc(&substream->mmap_count);
4032 	return err;
4033 }
4034 EXPORT_SYMBOL(snd_pcm_mmap_data);
4035 
4036 static int snd_pcm_mmap(struct file *file, struct vm_area_struct *area)
4037 {
4038 	struct snd_pcm_file * pcm_file;
4039 	struct snd_pcm_substream *substream;
4040 	unsigned long offset;
4041 
4042 	pcm_file = file->private_data;
4043 	substream = pcm_file->substream;
4044 	if (PCM_RUNTIME_CHECK(substream))
4045 		return -ENXIO;
4046 	if (substream->runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
4047 		return -EBADFD;
4048 
4049 	offset = area->vm_pgoff << PAGE_SHIFT;
4050 	switch (offset) {
4051 	case SNDRV_PCM_MMAP_OFFSET_STATUS_OLD:
4052 		if (pcm_file->no_compat_mmap || !IS_ENABLED(CONFIG_64BIT))
4053 			return -ENXIO;
4054 		fallthrough;
4055 	case SNDRV_PCM_MMAP_OFFSET_STATUS_NEW:
4056 		if (!pcm_status_mmap_allowed(pcm_file))
4057 			return -ENXIO;
4058 		return snd_pcm_mmap_status(substream, file, area);
4059 	case SNDRV_PCM_MMAP_OFFSET_CONTROL_OLD:
4060 		if (pcm_file->no_compat_mmap || !IS_ENABLED(CONFIG_64BIT))
4061 			return -ENXIO;
4062 		fallthrough;
4063 	case SNDRV_PCM_MMAP_OFFSET_CONTROL_NEW:
4064 		if (!pcm_control_mmap_allowed(pcm_file))
4065 			return -ENXIO;
4066 		return snd_pcm_mmap_control(substream, file, area);
4067 	default:
4068 		return snd_pcm_mmap_data(substream, file, area);
4069 	}
4070 	return 0;
4071 }
4072 
4073 static int snd_pcm_fasync(int fd, struct file * file, int on)
4074 {
4075 	struct snd_pcm_file * pcm_file;
4076 	struct snd_pcm_substream *substream;
4077 	struct snd_pcm_runtime *runtime;
4078 
4079 	pcm_file = file->private_data;
4080 	substream = pcm_file->substream;
4081 	if (PCM_RUNTIME_CHECK(substream))
4082 		return -ENXIO;
4083 	runtime = substream->runtime;
4084 	if (runtime->state == SNDRV_PCM_STATE_DISCONNECTED)
4085 		return -EBADFD;
4086 	return snd_fasync_helper(fd, file, on, &runtime->fasync);
4087 }
4088 
4089 /*
4090  * ioctl32 compat
4091  */
4092 #ifdef CONFIG_COMPAT
4093 #include "pcm_compat.c"
4094 #else
4095 #define snd_pcm_ioctl_compat	NULL
4096 #endif
4097 
4098 /*
4099  *  To be removed helpers to keep binary compatibility
4100  */
4101 
4102 #ifdef CONFIG_SND_SUPPORT_OLD_API
4103 #define __OLD_TO_NEW_MASK(x) ((x&7)|((x&0x07fffff8)<<5))
4104 #define __NEW_TO_OLD_MASK(x) ((x&7)|((x&0xffffff00)>>5))
4105 
4106 static void snd_pcm_hw_convert_from_old_params(struct snd_pcm_hw_params *params,
4107 					       struct snd_pcm_hw_params_old *oparams)
4108 {
4109 	unsigned int i;
4110 
4111 	memset(params, 0, sizeof(*params));
4112 	params->flags = oparams->flags;
4113 	for (i = 0; i < ARRAY_SIZE(oparams->masks); i++)
4114 		params->masks[i].bits[0] = oparams->masks[i];
4115 	memcpy(params->intervals, oparams->intervals, sizeof(oparams->intervals));
4116 	params->rmask = __OLD_TO_NEW_MASK(oparams->rmask);
4117 	params->cmask = __OLD_TO_NEW_MASK(oparams->cmask);
4118 	params->info = oparams->info;
4119 	params->msbits = oparams->msbits;
4120 	params->rate_num = oparams->rate_num;
4121 	params->rate_den = oparams->rate_den;
4122 	params->fifo_size = oparams->fifo_size;
4123 }
4124 
4125 static void snd_pcm_hw_convert_to_old_params(struct snd_pcm_hw_params_old *oparams,
4126 					     struct snd_pcm_hw_params *params)
4127 {
4128 	unsigned int i;
4129 
4130 	memset(oparams, 0, sizeof(*oparams));
4131 	oparams->flags = params->flags;
4132 	for (i = 0; i < ARRAY_SIZE(oparams->masks); i++)
4133 		oparams->masks[i] = params->masks[i].bits[0];
4134 	memcpy(oparams->intervals, params->intervals, sizeof(oparams->intervals));
4135 	oparams->rmask = __NEW_TO_OLD_MASK(params->rmask);
4136 	oparams->cmask = __NEW_TO_OLD_MASK(params->cmask);
4137 	oparams->info = params->info;
4138 	oparams->msbits = params->msbits;
4139 	oparams->rate_num = params->rate_num;
4140 	oparams->rate_den = params->rate_den;
4141 	oparams->fifo_size = params->fifo_size;
4142 }
4143 
4144 static int snd_pcm_hw_refine_old_user(struct snd_pcm_substream *substream,
4145 				      struct snd_pcm_hw_params_old __user * _oparams)
4146 {
4147 	int err;
4148 
4149 	struct snd_pcm_hw_params *params __free(kfree) =
4150 		kmalloc_obj(*params);
4151 	if (!params)
4152 		return -ENOMEM;
4153 
4154 	struct snd_pcm_hw_params_old *oparams __free(kfree) =
4155 		memdup_user(_oparams, sizeof(*oparams));
4156 	if (IS_ERR(oparams))
4157 		return PTR_ERR(oparams);
4158 	snd_pcm_hw_convert_from_old_params(params, oparams);
4159 	err = snd_pcm_hw_refine(substream, params);
4160 	if (err < 0)
4161 		return err;
4162 
4163 	err = fixup_unreferenced_params(substream, params);
4164 	if (err < 0)
4165 		return err;
4166 
4167 	snd_pcm_hw_convert_to_old_params(oparams, params);
4168 	if (copy_to_user(_oparams, oparams, sizeof(*oparams)))
4169 		return -EFAULT;
4170 	return 0;
4171 }
4172 
4173 static int snd_pcm_hw_params_old_user(struct snd_pcm_substream *substream,
4174 				      struct snd_pcm_hw_params_old __user * _oparams)
4175 {
4176 	int err;
4177 
4178 	struct snd_pcm_hw_params *params __free(kfree) =
4179 		kmalloc_obj(*params);
4180 	if (!params)
4181 		return -ENOMEM;
4182 
4183 	struct snd_pcm_hw_params_old *oparams __free(kfree) =
4184 		memdup_user(_oparams, sizeof(*oparams));
4185 	if (IS_ERR(oparams))
4186 		return PTR_ERR(oparams);
4187 
4188 	snd_pcm_hw_convert_from_old_params(params, oparams);
4189 	err = snd_pcm_hw_params(substream, params);
4190 	if (err < 0)
4191 		return err;
4192 
4193 	snd_pcm_hw_convert_to_old_params(oparams, params);
4194 	if (copy_to_user(_oparams, oparams, sizeof(*oparams)))
4195 		return -EFAULT;
4196 	return 0;
4197 }
4198 #endif /* CONFIG_SND_SUPPORT_OLD_API */
4199 
4200 #ifndef CONFIG_MMU
4201 static unsigned long snd_pcm_get_unmapped_area(struct file *file,
4202 					       unsigned long addr,
4203 					       unsigned long len,
4204 					       unsigned long pgoff,
4205 					       unsigned long flags)
4206 {
4207 	struct snd_pcm_file *pcm_file = file->private_data;
4208 	struct snd_pcm_substream *substream = pcm_file->substream;
4209 	struct snd_pcm_runtime *runtime = substream->runtime;
4210 	unsigned long offset = pgoff << PAGE_SHIFT;
4211 
4212 	switch (offset) {
4213 	case SNDRV_PCM_MMAP_OFFSET_STATUS_NEW:
4214 		return (unsigned long)runtime->status;
4215 	case SNDRV_PCM_MMAP_OFFSET_CONTROL_NEW:
4216 		return (unsigned long)runtime->control;
4217 	default:
4218 		return (unsigned long)runtime->dma_area + offset;
4219 	}
4220 }
4221 #else
4222 # define snd_pcm_get_unmapped_area NULL
4223 #endif
4224 
4225 /*
4226  *  Register section
4227  */
4228 
4229 const struct file_operations snd_pcm_f_ops[2] = {
4230 	{
4231 		.owner =		THIS_MODULE,
4232 		.write =		snd_pcm_write,
4233 		.write_iter =		snd_pcm_writev,
4234 		.open =			snd_pcm_playback_open,
4235 		.release =		snd_pcm_release,
4236 		.poll =			snd_pcm_poll,
4237 		.unlocked_ioctl =	snd_pcm_ioctl,
4238 		.compat_ioctl = 	snd_pcm_ioctl_compat,
4239 		.mmap =			snd_pcm_mmap,
4240 		.fasync =		snd_pcm_fasync,
4241 		.get_unmapped_area =	snd_pcm_get_unmapped_area,
4242 	},
4243 	{
4244 		.owner =		THIS_MODULE,
4245 		.read =			snd_pcm_read,
4246 		.read_iter =		snd_pcm_readv,
4247 		.open =			snd_pcm_capture_open,
4248 		.release =		snd_pcm_release,
4249 		.poll =			snd_pcm_poll,
4250 		.unlocked_ioctl =	snd_pcm_ioctl,
4251 		.compat_ioctl = 	snd_pcm_ioctl_compat,
4252 		.mmap =			snd_pcm_mmap,
4253 		.fasync =		snd_pcm_fasync,
4254 		.get_unmapped_area =	snd_pcm_get_unmapped_area,
4255 	}
4256 };
4257