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