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