2f790a7b1e90421ef37150955115095d2b5a4579
[linux-2.6-block.git] / sound / core / control.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Routines for driver control interface
4  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
5  */
6
7 #include <linux/threads.h>
8 #include <linux/interrupt.h>
9 #include <linux/module.h>
10 #include <linux/moduleparam.h>
11 #include <linux/slab.h>
12 #include <linux/vmalloc.h>
13 #include <linux/time.h>
14 #include <linux/mm.h>
15 #include <linux/math64.h>
16 #include <linux/sched/signal.h>
17 #include <sound/core.h>
18 #include <sound/minors.h>
19 #include <sound/info.h>
20 #include <sound/control.h>
21
22 // Max allocation size for user controls.
23 static int max_user_ctl_alloc_size = 8 * 1024 * 1024;
24 module_param_named(max_user_ctl_alloc_size, max_user_ctl_alloc_size, int, 0444);
25 MODULE_PARM_DESC(max_user_ctl_alloc_size, "Max allocation size for user controls");
26
27 #define MAX_CONTROL_COUNT       1028
28
29 struct snd_kctl_ioctl {
30         struct list_head list;          /* list of all ioctls */
31         snd_kctl_ioctl_func_t fioctl;
32 };
33
34 static DECLARE_RWSEM(snd_ioctl_rwsem);
35 static DECLARE_RWSEM(snd_ctl_layer_rwsem);
36 static LIST_HEAD(snd_control_ioctls);
37 #ifdef CONFIG_COMPAT
38 static LIST_HEAD(snd_control_compat_ioctls);
39 #endif
40 static struct snd_ctl_layer_ops *snd_ctl_layer;
41
42 static int snd_ctl_remove_locked(struct snd_card *card,
43                                  struct snd_kcontrol *kcontrol);
44
45 static int snd_ctl_open(struct inode *inode, struct file *file)
46 {
47         struct snd_card *card;
48         struct snd_ctl_file *ctl;
49         int i, err;
50
51         err = stream_open(inode, file);
52         if (err < 0)
53                 return err;
54
55         card = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_CONTROL);
56         if (!card) {
57                 err = -ENODEV;
58                 goto __error1;
59         }
60         err = snd_card_file_add(card, file);
61         if (err < 0) {
62                 err = -ENODEV;
63                 goto __error1;
64         }
65         if (!try_module_get(card->module)) {
66                 err = -EFAULT;
67                 goto __error2;
68         }
69         ctl = kzalloc(sizeof(*ctl), GFP_KERNEL);
70         if (ctl == NULL) {
71                 err = -ENOMEM;
72                 goto __error;
73         }
74         INIT_LIST_HEAD(&ctl->events);
75         init_waitqueue_head(&ctl->change_sleep);
76         spin_lock_init(&ctl->read_lock);
77         ctl->card = card;
78         for (i = 0; i < SND_CTL_SUBDEV_ITEMS; i++)
79                 ctl->preferred_subdevice[i] = -1;
80         ctl->pid = get_pid(task_pid(current));
81         file->private_data = ctl;
82         scoped_guard(write_lock_irqsave, &card->controls_rwlock)
83                 list_add_tail(&ctl->list, &card->ctl_files);
84         snd_card_unref(card);
85         return 0;
86
87       __error:
88         module_put(card->module);
89       __error2:
90         snd_card_file_remove(card, file);
91       __error1:
92         if (card)
93                 snd_card_unref(card);
94         return err;
95 }
96
97 static void snd_ctl_empty_read_queue(struct snd_ctl_file * ctl)
98 {
99         struct snd_kctl_event *cread;
100
101         guard(spinlock_irqsave)(&ctl->read_lock);
102         while (!list_empty(&ctl->events)) {
103                 cread = snd_kctl_event(ctl->events.next);
104                 list_del(&cread->list);
105                 kfree(cread);
106         }
107 }
108
109 static int snd_ctl_release(struct inode *inode, struct file *file)
110 {
111         struct snd_card *card;
112         struct snd_ctl_file *ctl;
113         struct snd_kcontrol *control;
114         unsigned int idx;
115
116         ctl = file->private_data;
117         file->private_data = NULL;
118         card = ctl->card;
119
120         scoped_guard(write_lock_irqsave, &card->controls_rwlock)
121                 list_del(&ctl->list);
122
123         scoped_guard(rwsem_write, &card->controls_rwsem) {
124                 list_for_each_entry(control, &card->controls, list)
125                         for (idx = 0; idx < control->count; idx++)
126                                 if (control->vd[idx].owner == ctl)
127                                         control->vd[idx].owner = NULL;
128         }
129
130         snd_fasync_free(ctl->fasync);
131         snd_ctl_empty_read_queue(ctl);
132         put_pid(ctl->pid);
133         kfree(ctl);
134         module_put(card->module);
135         snd_card_file_remove(card, file);
136         return 0;
137 }
138
139 /**
140  * snd_ctl_notify - Send notification to user-space for a control change
141  * @card: the card to send notification
142  * @mask: the event mask, SNDRV_CTL_EVENT_*
143  * @id: the ctl element id to send notification
144  *
145  * This function adds an event record with the given id and mask, appends
146  * to the list and wakes up the user-space for notification.  This can be
147  * called in the atomic context.
148  */
149 void snd_ctl_notify(struct snd_card *card, unsigned int mask,
150                     struct snd_ctl_elem_id *id)
151 {
152         struct snd_ctl_file *ctl;
153         struct snd_kctl_event *ev;
154
155         if (snd_BUG_ON(!card || !id))
156                 return;
157         if (card->shutdown)
158                 return;
159
160         guard(read_lock_irqsave)(&card->controls_rwlock);
161 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
162         card->mixer_oss_change_count++;
163 #endif
164         list_for_each_entry(ctl, &card->ctl_files, list) {
165                 if (!ctl->subscribed)
166                         continue;
167                 scoped_guard(spinlock, &ctl->read_lock) {
168                         list_for_each_entry(ev, &ctl->events, list) {
169                                 if (ev->id.numid == id->numid) {
170                                         ev->mask |= mask;
171                                         goto _found;
172                                 }
173                         }
174                         ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
175                         if (ev) {
176                                 ev->id = *id;
177                                 ev->mask = mask;
178                                 list_add_tail(&ev->list, &ctl->events);
179                         } else {
180                                 dev_err(card->dev, "No memory available to allocate event\n");
181                         }
182 _found:
183                         wake_up(&ctl->change_sleep);
184                 }
185                 snd_kill_fasync(ctl->fasync, SIGIO, POLL_IN);
186         }
187 }
188 EXPORT_SYMBOL(snd_ctl_notify);
189
190 /**
191  * snd_ctl_notify_one - Send notification to user-space for a control change
192  * @card: the card to send notification
193  * @mask: the event mask, SNDRV_CTL_EVENT_*
194  * @kctl: the pointer with the control instance
195  * @ioff: the additional offset to the control index
196  *
197  * This function calls snd_ctl_notify() and does additional jobs
198  * like LED state changes.
199  */
200 void snd_ctl_notify_one(struct snd_card *card, unsigned int mask,
201                         struct snd_kcontrol *kctl, unsigned int ioff)
202 {
203         struct snd_ctl_elem_id id = kctl->id;
204         struct snd_ctl_layer_ops *lops;
205
206         id.index += ioff;
207         id.numid += ioff;
208         snd_ctl_notify(card, mask, &id);
209         guard(rwsem_read)(&snd_ctl_layer_rwsem);
210         for (lops = snd_ctl_layer; lops; lops = lops->next)
211                 lops->lnotify(card, mask, kctl, ioff);
212 }
213 EXPORT_SYMBOL(snd_ctl_notify_one);
214
215 /**
216  * snd_ctl_new - create a new control instance with some elements
217  * @kctl: the pointer to store new control instance
218  * @count: the number of elements in this control
219  * @access: the default access flags for elements in this control
220  * @file: given when locking these elements
221  *
222  * Allocates a memory object for a new control instance. The instance has
223  * elements as many as the given number (@count). Each element has given
224  * access permissions (@access). Each element is locked when @file is given.
225  *
226  * Return: 0 on success, error code on failure
227  */
228 static int snd_ctl_new(struct snd_kcontrol **kctl, unsigned int count,
229                        unsigned int access, struct snd_ctl_file *file)
230 {
231         unsigned int idx;
232
233         if (count == 0 || count > MAX_CONTROL_COUNT)
234                 return -EINVAL;
235
236         *kctl = kzalloc(struct_size(*kctl, vd, count), GFP_KERNEL);
237         if (!*kctl)
238                 return -ENOMEM;
239
240         (*kctl)->count = count;
241         for (idx = 0; idx < count; idx++) {
242                 (*kctl)->vd[idx].access = access;
243                 (*kctl)->vd[idx].owner = file;
244         }
245
246         return 0;
247 }
248
249 /**
250  * snd_ctl_new1 - create a control instance from the template
251  * @ncontrol: the initialization record
252  * @private_data: the private data to set
253  *
254  * Allocates a new struct snd_kcontrol instance and initialize from the given
255  * template.  When the access field of ncontrol is 0, it's assumed as
256  * READWRITE access. When the count field is 0, it's assumes as one.
257  *
258  * Return: The pointer of the newly generated instance, or %NULL on failure.
259  */
260 struct snd_kcontrol *snd_ctl_new1(const struct snd_kcontrol_new *ncontrol,
261                                   void *private_data)
262 {
263         struct snd_kcontrol *kctl;
264         unsigned int count;
265         unsigned int access;
266         int err;
267
268         if (snd_BUG_ON(!ncontrol || !ncontrol->info))
269                 return NULL;
270
271         count = ncontrol->count;
272         if (count == 0)
273                 count = 1;
274
275         access = ncontrol->access;
276         if (access == 0)
277                 access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
278         access &= (SNDRV_CTL_ELEM_ACCESS_READWRITE |
279                    SNDRV_CTL_ELEM_ACCESS_VOLATILE |
280                    SNDRV_CTL_ELEM_ACCESS_INACTIVE |
281                    SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE |
282                    SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND |
283                    SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK |
284                    SNDRV_CTL_ELEM_ACCESS_LED_MASK |
285                    SNDRV_CTL_ELEM_ACCESS_SKIP_CHECK);
286
287         err = snd_ctl_new(&kctl, count, access, NULL);
288         if (err < 0)
289                 return NULL;
290
291         /* The 'numid' member is decided when calling snd_ctl_add(). */
292         kctl->id.iface = ncontrol->iface;
293         kctl->id.device = ncontrol->device;
294         kctl->id.subdevice = ncontrol->subdevice;
295         if (ncontrol->name) {
296                 strscpy(kctl->id.name, ncontrol->name, sizeof(kctl->id.name));
297                 if (strcmp(ncontrol->name, kctl->id.name) != 0)
298                         pr_warn("ALSA: Control name '%s' truncated to '%s'\n",
299                                 ncontrol->name, kctl->id.name);
300         }
301         kctl->id.index = ncontrol->index;
302
303         kctl->info = ncontrol->info;
304         kctl->get = ncontrol->get;
305         kctl->put = ncontrol->put;
306         kctl->tlv.p = ncontrol->tlv.p;
307
308         kctl->private_value = ncontrol->private_value;
309         kctl->private_data = private_data;
310
311         return kctl;
312 }
313 EXPORT_SYMBOL(snd_ctl_new1);
314
315 /**
316  * snd_ctl_free_one - release the control instance
317  * @kcontrol: the control instance
318  *
319  * Releases the control instance created via snd_ctl_new()
320  * or snd_ctl_new1().
321  * Don't call this after the control was added to the card.
322  */
323 void snd_ctl_free_one(struct snd_kcontrol *kcontrol)
324 {
325         if (kcontrol) {
326                 if (kcontrol->private_free)
327                         kcontrol->private_free(kcontrol);
328                 kfree(kcontrol);
329         }
330 }
331 EXPORT_SYMBOL(snd_ctl_free_one);
332
333 static bool snd_ctl_remove_numid_conflict(struct snd_card *card,
334                                           unsigned int count)
335 {
336         struct snd_kcontrol *kctl;
337
338         /* Make sure that the ids assigned to the control do not wrap around */
339         if (card->last_numid >= UINT_MAX - count)
340                 card->last_numid = 0;
341
342         list_for_each_entry(kctl, &card->controls, list) {
343                 if (kctl->id.numid < card->last_numid + 1 + count &&
344                     kctl->id.numid + kctl->count > card->last_numid + 1) {
345                         card->last_numid = kctl->id.numid + kctl->count - 1;
346                         return true;
347                 }
348         }
349         return false;
350 }
351
352 static int snd_ctl_find_hole(struct snd_card *card, unsigned int count)
353 {
354         unsigned int iter = 100000;
355
356         while (snd_ctl_remove_numid_conflict(card, count)) {
357                 if (--iter == 0) {
358                         /* this situation is very unlikely */
359                         dev_err(card->dev, "unable to allocate new control numid\n");
360                         return -ENOMEM;
361                 }
362         }
363         return 0;
364 }
365
366 /* check whether the given id is contained in the given kctl */
367 static bool elem_id_matches(const struct snd_kcontrol *kctl,
368                             const struct snd_ctl_elem_id *id)
369 {
370         return kctl->id.iface == id->iface &&
371                 kctl->id.device == id->device &&
372                 kctl->id.subdevice == id->subdevice &&
373                 !strncmp(kctl->id.name, id->name, sizeof(kctl->id.name)) &&
374                 kctl->id.index <= id->index &&
375                 kctl->id.index + kctl->count > id->index;
376 }
377
378 #ifdef CONFIG_SND_CTL_FAST_LOOKUP
379 /* Compute a hash key for the corresponding ctl id
380  * It's for the name lookup, hence the numid is excluded.
381  * The hash key is bound in LONG_MAX to be used for Xarray key.
382  */
383 #define MULTIPLIER      37
384 static unsigned long get_ctl_id_hash(const struct snd_ctl_elem_id *id)
385 {
386         int i;
387         unsigned long h;
388
389         h = id->iface;
390         h = MULTIPLIER * h + id->device;
391         h = MULTIPLIER * h + id->subdevice;
392         for (i = 0; i < SNDRV_CTL_ELEM_ID_NAME_MAXLEN && id->name[i]; i++)
393                 h = MULTIPLIER * h + id->name[i];
394         h = MULTIPLIER * h + id->index;
395         h &= LONG_MAX;
396         return h;
397 }
398
399 /* add hash entries to numid and ctl xarray tables */
400 static void add_hash_entries(struct snd_card *card,
401                              struct snd_kcontrol *kcontrol)
402 {
403         struct snd_ctl_elem_id id = kcontrol->id;
404         int i;
405
406         xa_store_range(&card->ctl_numids, kcontrol->id.numid,
407                        kcontrol->id.numid + kcontrol->count - 1,
408                        kcontrol, GFP_KERNEL);
409
410         for (i = 0; i < kcontrol->count; i++) {
411                 id.index = kcontrol->id.index + i;
412                 if (xa_insert(&card->ctl_hash, get_ctl_id_hash(&id),
413                               kcontrol, GFP_KERNEL)) {
414                         /* skip hash for this entry, noting we had collision */
415                         card->ctl_hash_collision = true;
416                         dev_dbg(card->dev, "ctl_hash collision %d:%s:%d\n",
417                                 id.iface, id.name, id.index);
418                 }
419         }
420 }
421
422 /* remove hash entries that have been added */
423 static void remove_hash_entries(struct snd_card *card,
424                                 struct snd_kcontrol *kcontrol)
425 {
426         struct snd_ctl_elem_id id = kcontrol->id;
427         struct snd_kcontrol *matched;
428         unsigned long h;
429         int i;
430
431         for (i = 0; i < kcontrol->count; i++) {
432                 xa_erase(&card->ctl_numids, id.numid);
433                 h = get_ctl_id_hash(&id);
434                 matched = xa_load(&card->ctl_hash, h);
435                 if (matched && (matched == kcontrol ||
436                                 elem_id_matches(matched, &id)))
437                         xa_erase(&card->ctl_hash, h);
438                 id.index++;
439                 id.numid++;
440         }
441 }
442 #else /* CONFIG_SND_CTL_FAST_LOOKUP */
443 static inline void add_hash_entries(struct snd_card *card,
444                                     struct snd_kcontrol *kcontrol)
445 {
446 }
447 static inline void remove_hash_entries(struct snd_card *card,
448                                        struct snd_kcontrol *kcontrol)
449 {
450 }
451 #endif /* CONFIG_SND_CTL_FAST_LOOKUP */
452
453 enum snd_ctl_add_mode {
454         CTL_ADD_EXCLUSIVE, CTL_REPLACE, CTL_ADD_ON_REPLACE,
455 };
456
457 /* add/replace a new kcontrol object; call with card->controls_rwsem locked */
458 static int __snd_ctl_add_replace(struct snd_card *card,
459                                  struct snd_kcontrol *kcontrol,
460                                  enum snd_ctl_add_mode mode)
461 {
462         struct snd_ctl_elem_id id;
463         unsigned int idx;
464         struct snd_kcontrol *old;
465         int err;
466
467         lockdep_assert_held_write(&card->controls_rwsem);
468
469         id = kcontrol->id;
470         if (id.index > UINT_MAX - kcontrol->count)
471                 return -EINVAL;
472
473         old = snd_ctl_find_id(card, &id);
474         if (!old) {
475                 if (mode == CTL_REPLACE)
476                         return -EINVAL;
477         } else {
478                 if (mode == CTL_ADD_EXCLUSIVE) {
479                         dev_err(card->dev,
480                                 "control %i:%i:%i:%s:%i is already present\n",
481                                 id.iface, id.device, id.subdevice, id.name,
482                                 id.index);
483                         return -EBUSY;
484                 }
485
486                 err = snd_ctl_remove_locked(card, old);
487                 if (err < 0)
488                         return err;
489         }
490
491         if (snd_ctl_find_hole(card, kcontrol->count) < 0)
492                 return -ENOMEM;
493
494         scoped_guard(write_lock_irq, &card->controls_rwlock) {
495                 list_add_tail(&kcontrol->list, &card->controls);
496                 card->controls_count += kcontrol->count;
497                 kcontrol->id.numid = card->last_numid + 1;
498                 card->last_numid += kcontrol->count;
499         }
500
501         add_hash_entries(card, kcontrol);
502
503         for (idx = 0; idx < kcontrol->count; idx++)
504                 snd_ctl_notify_one(card, SNDRV_CTL_EVENT_MASK_ADD, kcontrol, idx);
505
506         return 0;
507 }
508
509 static int snd_ctl_add_replace(struct snd_card *card,
510                                struct snd_kcontrol *kcontrol,
511                                enum snd_ctl_add_mode mode)
512 {
513         int err = -EINVAL;
514
515         if (! kcontrol)
516                 return err;
517         if (snd_BUG_ON(!card || !kcontrol->info))
518                 goto error;
519
520         scoped_guard(rwsem_write, &card->controls_rwsem)
521                 err = __snd_ctl_add_replace(card, kcontrol, mode);
522
523         if (err < 0)
524                 goto error;
525         return 0;
526
527  error:
528         snd_ctl_free_one(kcontrol);
529         return err;
530 }
531
532 /**
533  * snd_ctl_add - add the control instance to the card
534  * @card: the card instance
535  * @kcontrol: the control instance to add
536  *
537  * Adds the control instance created via snd_ctl_new() or
538  * snd_ctl_new1() to the given card. Assigns also an unique
539  * numid used for fast search.
540  *
541  * It frees automatically the control which cannot be added.
542  *
543  * Return: Zero if successful, or a negative error code on failure.
544  *
545  */
546 int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol)
547 {
548         return snd_ctl_add_replace(card, kcontrol, CTL_ADD_EXCLUSIVE);
549 }
550 EXPORT_SYMBOL(snd_ctl_add);
551
552 /**
553  * snd_ctl_replace - replace the control instance of the card
554  * @card: the card instance
555  * @kcontrol: the control instance to replace
556  * @add_on_replace: add the control if not already added
557  *
558  * Replaces the given control.  If the given control does not exist
559  * and the add_on_replace flag is set, the control is added.  If the
560  * control exists, it is destroyed first.
561  *
562  * It frees automatically the control which cannot be added or replaced.
563  *
564  * Return: Zero if successful, or a negative error code on failure.
565  */
566 int snd_ctl_replace(struct snd_card *card, struct snd_kcontrol *kcontrol,
567                     bool add_on_replace)
568 {
569         return snd_ctl_add_replace(card, kcontrol,
570                                    add_on_replace ? CTL_ADD_ON_REPLACE : CTL_REPLACE);
571 }
572 EXPORT_SYMBOL(snd_ctl_replace);
573
574 static int __snd_ctl_remove(struct snd_card *card,
575                             struct snd_kcontrol *kcontrol,
576                             bool remove_hash)
577 {
578         unsigned int idx;
579
580         lockdep_assert_held_write(&card->controls_rwsem);
581
582         if (snd_BUG_ON(!card || !kcontrol))
583                 return -EINVAL;
584
585         if (remove_hash)
586                 remove_hash_entries(card, kcontrol);
587
588         scoped_guard(write_lock_irq, &card->controls_rwlock) {
589                 list_del(&kcontrol->list);
590                 card->controls_count -= kcontrol->count;
591         }
592
593         for (idx = 0; idx < kcontrol->count; idx++)
594                 snd_ctl_notify_one(card, SNDRV_CTL_EVENT_MASK_REMOVE, kcontrol, idx);
595         snd_ctl_free_one(kcontrol);
596         return 0;
597 }
598
599 static inline int snd_ctl_remove_locked(struct snd_card *card,
600                                         struct snd_kcontrol *kcontrol)
601 {
602         return __snd_ctl_remove(card, kcontrol, true);
603 }
604
605 /**
606  * snd_ctl_remove - remove the control from the card and release it
607  * @card: the card instance
608  * @kcontrol: the control instance to remove
609  *
610  * Removes the control from the card and then releases the instance.
611  * You don't need to call snd_ctl_free_one().
612  * Passing NULL to @kcontrol argument is allowed as noop.
613  *
614  * Return: 0 if successful, or a negative error code on failure.
615  *
616  * Note that this function takes card->controls_rwsem lock internally.
617  */
618 int snd_ctl_remove(struct snd_card *card, struct snd_kcontrol *kcontrol)
619 {
620         if (!kcontrol)
621                 return 0;
622         guard(rwsem_write)(&card->controls_rwsem);
623         return snd_ctl_remove_locked(card, kcontrol);
624 }
625 EXPORT_SYMBOL(snd_ctl_remove);
626
627 /**
628  * snd_ctl_remove_id - remove the control of the given id and release it
629  * @card: the card instance
630  * @id: the control id to remove
631  *
632  * Finds the control instance with the given id, removes it from the
633  * card list and releases it.
634  *
635  * Return: 0 if successful, or a negative error code on failure.
636  */
637 int snd_ctl_remove_id(struct snd_card *card, struct snd_ctl_elem_id *id)
638 {
639         struct snd_kcontrol *kctl;
640
641         guard(rwsem_write)(&card->controls_rwsem);
642         kctl = snd_ctl_find_id(card, id);
643         if (kctl == NULL)
644                 return -ENOENT;
645         return snd_ctl_remove_locked(card, kctl);
646 }
647 EXPORT_SYMBOL(snd_ctl_remove_id);
648
649 /**
650  * snd_ctl_remove_user_ctl - remove and release the unlocked user control
651  * @file: active control handle
652  * @id: the control id to remove
653  *
654  * Finds the control instance with the given id, removes it from the
655  * card list and releases it.
656  *
657  * Return: 0 if successful, or a negative error code on failure.
658  */
659 static int snd_ctl_remove_user_ctl(struct snd_ctl_file * file,
660                                    struct snd_ctl_elem_id *id)
661 {
662         struct snd_card *card = file->card;
663         struct snd_kcontrol *kctl;
664         int idx;
665
666         guard(rwsem_write)(&card->controls_rwsem);
667         kctl = snd_ctl_find_id(card, id);
668         if (kctl == NULL)
669                 return -ENOENT;
670         if (!(kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_USER))
671                 return -EINVAL;
672         for (idx = 0; idx < kctl->count; idx++)
673                 if (kctl->vd[idx].owner != NULL && kctl->vd[idx].owner != file)
674                         return -EBUSY;
675         return snd_ctl_remove_locked(card, kctl);
676 }
677
678 /**
679  * snd_ctl_activate_id - activate/inactivate the control of the given id
680  * @card: the card instance
681  * @id: the control id to activate/inactivate
682  * @active: non-zero to activate
683  *
684  * Finds the control instance with the given id, and activate or
685  * inactivate the control together with notification, if changed.
686  * The given ID data is filled with full information.
687  *
688  * Return: 0 if unchanged, 1 if changed, or a negative error code on failure.
689  */
690 int snd_ctl_activate_id(struct snd_card *card, struct snd_ctl_elem_id *id,
691                         int active)
692 {
693         struct snd_kcontrol *kctl;
694         struct snd_kcontrol_volatile *vd;
695         unsigned int index_offset;
696         int ret;
697
698         down_write(&card->controls_rwsem);
699         kctl = snd_ctl_find_id(card, id);
700         if (kctl == NULL) {
701                 ret = -ENOENT;
702                 goto unlock;
703         }
704         index_offset = snd_ctl_get_ioff(kctl, id);
705         vd = &kctl->vd[index_offset];
706         ret = 0;
707         if (active) {
708                 if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_INACTIVE))
709                         goto unlock;
710                 vd->access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
711         } else {
712                 if (vd->access & SNDRV_CTL_ELEM_ACCESS_INACTIVE)
713                         goto unlock;
714                 vd->access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
715         }
716         snd_ctl_build_ioff(id, kctl, index_offset);
717         downgrade_write(&card->controls_rwsem);
718         snd_ctl_notify_one(card, SNDRV_CTL_EVENT_MASK_INFO, kctl, index_offset);
719         up_read(&card->controls_rwsem);
720         return 1;
721
722  unlock:
723         up_write(&card->controls_rwsem);
724         return ret;
725 }
726 EXPORT_SYMBOL_GPL(snd_ctl_activate_id);
727
728 /**
729  * snd_ctl_rename_id - replace the id of a control on the card
730  * @card: the card instance
731  * @src_id: the old id
732  * @dst_id: the new id
733  *
734  * Finds the control with the old id from the card, and replaces the
735  * id with the new one.
736  *
737  * The function tries to keep the already assigned numid while replacing
738  * the rest.
739  *
740  * Note that this function should be used only in the card initialization
741  * phase.  Calling after the card instantiation may cause issues with
742  * user-space expecting persistent numids.
743  *
744  * Return: Zero if successful, or a negative error code on failure.
745  */
746 int snd_ctl_rename_id(struct snd_card *card, struct snd_ctl_elem_id *src_id,
747                       struct snd_ctl_elem_id *dst_id)
748 {
749         struct snd_kcontrol *kctl;
750         int saved_numid;
751
752         guard(rwsem_write)(&card->controls_rwsem);
753         kctl = snd_ctl_find_id(card, src_id);
754         if (kctl == NULL)
755                 return -ENOENT;
756         saved_numid = kctl->id.numid;
757         remove_hash_entries(card, kctl);
758         kctl->id = *dst_id;
759         kctl->id.numid = saved_numid;
760         add_hash_entries(card, kctl);
761         return 0;
762 }
763 EXPORT_SYMBOL(snd_ctl_rename_id);
764
765 /**
766  * snd_ctl_rename - rename the control on the card
767  * @card: the card instance
768  * @kctl: the control to rename
769  * @name: the new name
770  *
771  * Renames the specified control on the card to the new name.
772  *
773  * Note that this function takes card->controls_rwsem lock internally.
774  */
775 void snd_ctl_rename(struct snd_card *card, struct snd_kcontrol *kctl,
776                     const char *name)
777 {
778         guard(rwsem_write)(&card->controls_rwsem);
779         remove_hash_entries(card, kctl);
780
781         if (strscpy(kctl->id.name, name, sizeof(kctl->id.name)) < 0)
782                 pr_warn("ALSA: Renamed control new name '%s' truncated to '%s'\n",
783                         name, kctl->id.name);
784
785         add_hash_entries(card, kctl);
786 }
787 EXPORT_SYMBOL(snd_ctl_rename);
788
789 #ifndef CONFIG_SND_CTL_FAST_LOOKUP
790 static struct snd_kcontrol *
791 snd_ctl_find_numid_slow(struct snd_card *card, unsigned int numid)
792 {
793         struct snd_kcontrol *kctl;
794
795         guard(read_lock_irqsave)(&card->controls_rwlock);
796         list_for_each_entry(kctl, &card->controls, list) {
797                 if (kctl->id.numid <= numid && kctl->id.numid + kctl->count > numid)
798                         return kctl;
799         }
800         return NULL;
801 }
802 #endif /* !CONFIG_SND_CTL_FAST_LOOKUP */
803
804 /**
805  * snd_ctl_find_numid - find the control instance with the given number-id
806  * @card: the card instance
807  * @numid: the number-id to search
808  *
809  * Finds the control instance with the given number-id from the card.
810  *
811  * Return: The pointer of the instance if found, or %NULL if not.
812  *
813  * Note that this function takes card->controls_rwlock lock internally.
814  */
815 struct snd_kcontrol *snd_ctl_find_numid(struct snd_card *card,
816                                         unsigned int numid)
817 {
818         if (snd_BUG_ON(!card || !numid))
819                 return NULL;
820
821 #ifdef CONFIG_SND_CTL_FAST_LOOKUP
822         return xa_load(&card->ctl_numids, numid);
823 #else
824         return snd_ctl_find_numid_slow(card, numid);
825 #endif
826 }
827 EXPORT_SYMBOL(snd_ctl_find_numid);
828
829 /**
830  * snd_ctl_find_id - find the control instance with the given id
831  * @card: the card instance
832  * @id: the id to search
833  *
834  * Finds the control instance with the given id from the card.
835  *
836  * Return: The pointer of the instance if found, or %NULL if not.
837  *
838  * Note that this function takes card->controls_rwlock lock internally.
839  */
840 struct snd_kcontrol *snd_ctl_find_id(struct snd_card *card,
841                                      const struct snd_ctl_elem_id *id)
842 {
843         struct snd_kcontrol *kctl;
844
845         if (snd_BUG_ON(!card || !id))
846                 return NULL;
847
848         if (id->numid != 0)
849                 return snd_ctl_find_numid(card, id->numid);
850 #ifdef CONFIG_SND_CTL_FAST_LOOKUP
851         kctl = xa_load(&card->ctl_hash, get_ctl_id_hash(id));
852         if (kctl && elem_id_matches(kctl, id))
853                 return kctl;
854         if (!card->ctl_hash_collision)
855                 return NULL; /* we can rely on only hash table */
856 #endif
857         /* no matching in hash table - try all as the last resort */
858         guard(read_lock_irqsave)(&card->controls_rwlock);
859         list_for_each_entry(kctl, &card->controls, list)
860                 if (elem_id_matches(kctl, id))
861                         return kctl;
862
863         return NULL;
864 }
865 EXPORT_SYMBOL(snd_ctl_find_id);
866
867 static int snd_ctl_card_info(struct snd_card *card, struct snd_ctl_file * ctl,
868                              unsigned int cmd, void __user *arg)
869 {
870         struct snd_ctl_card_info *info __free(kfree) = NULL;
871
872         info = kzalloc(sizeof(*info), GFP_KERNEL);
873         if (! info)
874                 return -ENOMEM;
875         scoped_guard(rwsem_read, &snd_ioctl_rwsem) {
876                 info->card = card->number;
877                 strscpy(info->id, card->id, sizeof(info->id));
878                 strscpy(info->driver, card->driver, sizeof(info->driver));
879                 strscpy(info->name, card->shortname, sizeof(info->name));
880                 strscpy(info->longname, card->longname, sizeof(info->longname));
881                 strscpy(info->mixername, card->mixername, sizeof(info->mixername));
882                 strscpy(info->components, card->components, sizeof(info->components));
883         }
884         if (copy_to_user(arg, info, sizeof(struct snd_ctl_card_info)))
885                 return -EFAULT;
886         return 0;
887 }
888
889 static int snd_ctl_elem_list(struct snd_card *card,
890                              struct snd_ctl_elem_list *list)
891 {
892         struct snd_kcontrol *kctl;
893         struct snd_ctl_elem_id id;
894         unsigned int offset, space, jidx;
895
896         offset = list->offset;
897         space = list->space;
898
899         guard(rwsem_read)(&card->controls_rwsem);
900         list->count = card->controls_count;
901         list->used = 0;
902         if (!space)
903                 return 0;
904         list_for_each_entry(kctl, &card->controls, list) {
905                 if (offset >= kctl->count) {
906                         offset -= kctl->count;
907                         continue;
908                 }
909                 for (jidx = offset; jidx < kctl->count; jidx++) {
910                         snd_ctl_build_ioff(&id, kctl, jidx);
911                         if (copy_to_user(list->pids + list->used, &id, sizeof(id)))
912                                 return -EFAULT;
913                         list->used++;
914                         if (!--space)
915                                 return 0;
916                 }
917                 offset = 0;
918         }
919         return 0;
920 }
921
922 static int snd_ctl_elem_list_user(struct snd_card *card,
923                                   struct snd_ctl_elem_list __user *_list)
924 {
925         struct snd_ctl_elem_list list;
926         int err;
927
928         if (copy_from_user(&list, _list, sizeof(list)))
929                 return -EFAULT;
930         err = snd_ctl_elem_list(card, &list);
931         if (err)
932                 return err;
933         if (copy_to_user(_list, &list, sizeof(list)))
934                 return -EFAULT;
935
936         return 0;
937 }
938
939 /* Check whether the given kctl info is valid */
940 static int snd_ctl_check_elem_info(struct snd_card *card,
941                                    const struct snd_ctl_elem_info *info)
942 {
943         static const unsigned int max_value_counts[] = {
944                 [SNDRV_CTL_ELEM_TYPE_BOOLEAN]   = 128,
945                 [SNDRV_CTL_ELEM_TYPE_INTEGER]   = 128,
946                 [SNDRV_CTL_ELEM_TYPE_ENUMERATED] = 128,
947                 [SNDRV_CTL_ELEM_TYPE_BYTES]     = 512,
948                 [SNDRV_CTL_ELEM_TYPE_IEC958]    = 1,
949                 [SNDRV_CTL_ELEM_TYPE_INTEGER64] = 64,
950         };
951
952         if (info->type < SNDRV_CTL_ELEM_TYPE_BOOLEAN ||
953             info->type > SNDRV_CTL_ELEM_TYPE_INTEGER64) {
954                 if (card)
955                         dev_err(card->dev,
956                                 "control %i:%i:%i:%s:%i: invalid type %d\n",
957                                 info->id.iface, info->id.device,
958                                 info->id.subdevice, info->id.name,
959                                 info->id.index, info->type);
960                 return -EINVAL;
961         }
962         if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED &&
963             info->value.enumerated.items == 0) {
964                 if (card)
965                         dev_err(card->dev,
966                                 "control %i:%i:%i:%s:%i: zero enum items\n",
967                                 info->id.iface, info->id.device,
968                                 info->id.subdevice, info->id.name,
969                                 info->id.index);
970                 return -EINVAL;
971         }
972         if (info->count > max_value_counts[info->type]) {
973                 if (card)
974                         dev_err(card->dev,
975                                 "control %i:%i:%i:%s:%i: invalid count %d\n",
976                                 info->id.iface, info->id.device,
977                                 info->id.subdevice, info->id.name,
978                                 info->id.index, info->count);
979                 return -EINVAL;
980         }
981
982         return 0;
983 }
984
985 /* The capacity of struct snd_ctl_elem_value.value.*/
986 static const unsigned int value_sizes[] = {
987         [SNDRV_CTL_ELEM_TYPE_BOOLEAN]   = sizeof(long),
988         [SNDRV_CTL_ELEM_TYPE_INTEGER]   = sizeof(long),
989         [SNDRV_CTL_ELEM_TYPE_ENUMERATED] = sizeof(unsigned int),
990         [SNDRV_CTL_ELEM_TYPE_BYTES]     = sizeof(unsigned char),
991         [SNDRV_CTL_ELEM_TYPE_IEC958]    = sizeof(struct snd_aes_iec958),
992         [SNDRV_CTL_ELEM_TYPE_INTEGER64] = sizeof(long long),
993 };
994
995 /* fill the remaining snd_ctl_elem_value data with the given pattern */
996 static void fill_remaining_elem_value(struct snd_ctl_elem_value *control,
997                                       struct snd_ctl_elem_info *info,
998                                       u32 pattern)
999 {
1000         size_t offset = value_sizes[info->type] * info->count;
1001
1002         offset = DIV_ROUND_UP(offset, sizeof(u32));
1003         memset32((u32 *)control->value.bytes.data + offset, pattern,
1004                  sizeof(control->value) / sizeof(u32) - offset);
1005 }
1006
1007 /* check whether the given integer ctl value is valid */
1008 static int sanity_check_int_value(struct snd_card *card,
1009                                   const struct snd_ctl_elem_value *control,
1010                                   const struct snd_ctl_elem_info *info,
1011                                   int i, bool print_error)
1012 {
1013         long long lval, lmin, lmax, lstep;
1014         u64 rem;
1015
1016         switch (info->type) {
1017         default:
1018         case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
1019                 lval = control->value.integer.value[i];
1020                 lmin = 0;
1021                 lmax = 1;
1022                 lstep = 0;
1023                 break;
1024         case SNDRV_CTL_ELEM_TYPE_INTEGER:
1025                 lval = control->value.integer.value[i];
1026                 lmin = info->value.integer.min;
1027                 lmax = info->value.integer.max;
1028                 lstep = info->value.integer.step;
1029                 break;
1030         case SNDRV_CTL_ELEM_TYPE_INTEGER64:
1031                 lval = control->value.integer64.value[i];
1032                 lmin = info->value.integer64.min;
1033                 lmax = info->value.integer64.max;
1034                 lstep = info->value.integer64.step;
1035                 break;
1036         case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
1037                 lval = control->value.enumerated.item[i];
1038                 lmin = 0;
1039                 lmax = info->value.enumerated.items - 1;
1040                 lstep = 0;
1041                 break;
1042         }
1043
1044         if (lval < lmin || lval > lmax) {
1045                 if (print_error)
1046                         dev_err(card->dev,
1047                                 "control %i:%i:%i:%s:%i: value out of range %lld (%lld/%lld) at count %i\n",
1048                                 control->id.iface, control->id.device,
1049                                 control->id.subdevice, control->id.name,
1050                                 control->id.index, lval, lmin, lmax, i);
1051                 return -EINVAL;
1052         }
1053         if (lstep) {
1054                 div64_u64_rem(lval, lstep, &rem);
1055                 if (rem) {
1056                         if (print_error)
1057                                 dev_err(card->dev,
1058                                         "control %i:%i:%i:%s:%i: unaligned value %lld (step %lld) at count %i\n",
1059                                         control->id.iface, control->id.device,
1060                                         control->id.subdevice, control->id.name,
1061                                         control->id.index, lval, lstep, i);
1062                         return -EINVAL;
1063                 }
1064         }
1065
1066         return 0;
1067 }
1068
1069 /* check whether the all input values are valid for the given elem value */
1070 static int sanity_check_input_values(struct snd_card *card,
1071                                      const struct snd_ctl_elem_value *control,
1072                                      const struct snd_ctl_elem_info *info,
1073                                      bool print_error)
1074 {
1075         int i, ret;
1076
1077         switch (info->type) {
1078         case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
1079         case SNDRV_CTL_ELEM_TYPE_INTEGER:
1080         case SNDRV_CTL_ELEM_TYPE_INTEGER64:
1081         case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
1082                 for (i = 0; i < info->count; i++) {
1083                         ret = sanity_check_int_value(card, control, info, i,
1084                                                      print_error);
1085                         if (ret < 0)
1086                                 return ret;
1087                 }
1088                 break;
1089         default:
1090                 break;
1091         }
1092
1093         return 0;
1094 }
1095
1096 /* perform sanity checks to the given snd_ctl_elem_value object */
1097 static int sanity_check_elem_value(struct snd_card *card,
1098                                    const struct snd_ctl_elem_value *control,
1099                                    const struct snd_ctl_elem_info *info,
1100                                    u32 pattern)
1101 {
1102         size_t offset;
1103         int ret;
1104         u32 *p;
1105
1106         ret = sanity_check_input_values(card, control, info, true);
1107         if (ret < 0)
1108                 return ret;
1109
1110         /* check whether the remaining area kept untouched */
1111         offset = value_sizes[info->type] * info->count;
1112         offset = DIV_ROUND_UP(offset, sizeof(u32));
1113         p = (u32 *)control->value.bytes.data + offset;
1114         for (; offset < sizeof(control->value) / sizeof(u32); offset++, p++) {
1115                 if (*p != pattern) {
1116                         ret = -EINVAL;
1117                         break;
1118                 }
1119                 *p = 0; /* clear the checked area */
1120         }
1121
1122         return ret;
1123 }
1124
1125 static int __snd_ctl_elem_info(struct snd_card *card,
1126                                struct snd_kcontrol *kctl,
1127                                struct snd_ctl_elem_info *info,
1128                                struct snd_ctl_file *ctl)
1129 {
1130         struct snd_kcontrol_volatile *vd;
1131         unsigned int index_offset;
1132         int result;
1133
1134 #ifdef CONFIG_SND_DEBUG
1135         info->access = 0;
1136 #endif
1137         result = kctl->info(kctl, info);
1138         if (result >= 0) {
1139                 snd_BUG_ON(info->access);
1140                 index_offset = snd_ctl_get_ioff(kctl, &info->id);
1141                 vd = &kctl->vd[index_offset];
1142                 snd_ctl_build_ioff(&info->id, kctl, index_offset);
1143                 info->access = vd->access;
1144                 if (vd->owner) {
1145                         info->access |= SNDRV_CTL_ELEM_ACCESS_LOCK;
1146                         if (vd->owner == ctl)
1147                                 info->access |= SNDRV_CTL_ELEM_ACCESS_OWNER;
1148                         info->owner = pid_vnr(vd->owner->pid);
1149                 } else {
1150                         info->owner = -1;
1151                 }
1152                 if (!snd_ctl_skip_validation(info) &&
1153                     snd_ctl_check_elem_info(card, info) < 0)
1154                         result = -EINVAL;
1155         }
1156         return result;
1157 }
1158
1159 static int snd_ctl_elem_info(struct snd_ctl_file *ctl,
1160                              struct snd_ctl_elem_info *info)
1161 {
1162         struct snd_card *card = ctl->card;
1163         struct snd_kcontrol *kctl;
1164
1165         guard(rwsem_read)(&card->controls_rwsem);
1166         kctl = snd_ctl_find_id(card, &info->id);
1167         if (!kctl)
1168                 return -ENOENT;
1169         return __snd_ctl_elem_info(card, kctl, info, ctl);
1170 }
1171
1172 static int snd_ctl_elem_info_user(struct snd_ctl_file *ctl,
1173                                   struct snd_ctl_elem_info __user *_info)
1174 {
1175         struct snd_card *card = ctl->card;
1176         struct snd_ctl_elem_info info;
1177         int result;
1178
1179         if (copy_from_user(&info, _info, sizeof(info)))
1180                 return -EFAULT;
1181         result = snd_power_ref_and_wait(card);
1182         if (result)
1183                 return result;
1184         result = snd_ctl_elem_info(ctl, &info);
1185         snd_power_unref(card);
1186         if (result < 0)
1187                 return result;
1188         /* drop internal access flags */
1189         info.access &= ~(SNDRV_CTL_ELEM_ACCESS_SKIP_CHECK|
1190                          SNDRV_CTL_ELEM_ACCESS_LED_MASK);
1191         if (copy_to_user(_info, &info, sizeof(info)))
1192                 return -EFAULT;
1193         return result;
1194 }
1195
1196 static int snd_ctl_elem_read(struct snd_card *card,
1197                              struct snd_ctl_elem_value *control)
1198 {
1199         struct snd_kcontrol *kctl;
1200         struct snd_kcontrol_volatile *vd;
1201         unsigned int index_offset;
1202         struct snd_ctl_elem_info info;
1203         const u32 pattern = 0xdeadbeef;
1204         int ret;
1205
1206         guard(rwsem_read)(&card->controls_rwsem);
1207         kctl = snd_ctl_find_id(card, &control->id);
1208         if (!kctl)
1209                 return -ENOENT;
1210
1211         index_offset = snd_ctl_get_ioff(kctl, &control->id);
1212         vd = &kctl->vd[index_offset];
1213         if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_READ) || !kctl->get)
1214                 return -EPERM;
1215
1216         snd_ctl_build_ioff(&control->id, kctl, index_offset);
1217
1218 #ifdef CONFIG_SND_CTL_DEBUG
1219         /* info is needed only for validation */
1220         memset(&info, 0, sizeof(info));
1221         info.id = control->id;
1222         ret = __snd_ctl_elem_info(card, kctl, &info, NULL);
1223         if (ret < 0)
1224                 return ret;
1225 #endif
1226
1227         if (!snd_ctl_skip_validation(&info))
1228                 fill_remaining_elem_value(control, &info, pattern);
1229         ret = kctl->get(kctl, control);
1230         if (ret < 0)
1231                 return ret;
1232         if (!snd_ctl_skip_validation(&info) &&
1233             sanity_check_elem_value(card, control, &info, pattern) < 0) {
1234                 dev_err(card->dev,
1235                         "control %i:%i:%i:%s:%i: access overflow\n",
1236                         control->id.iface, control->id.device,
1237                         control->id.subdevice, control->id.name,
1238                         control->id.index);
1239                 return -EINVAL;
1240         }
1241         return 0;
1242 }
1243
1244 static int snd_ctl_elem_read_user(struct snd_card *card,
1245                                   struct snd_ctl_elem_value __user *_control)
1246 {
1247         struct snd_ctl_elem_value *control __free(kfree) = NULL;
1248         int result;
1249
1250         control = memdup_user(_control, sizeof(*control));
1251         if (IS_ERR(control))
1252                 return PTR_ERR(control);
1253
1254         result = snd_power_ref_and_wait(card);
1255         if (result)
1256                 return result;
1257         result = snd_ctl_elem_read(card, control);
1258         snd_power_unref(card);
1259         if (result < 0)
1260                 return result;
1261
1262         if (copy_to_user(_control, control, sizeof(*control)))
1263                 return -EFAULT;
1264         return result;
1265 }
1266
1267 static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
1268                               struct snd_ctl_elem_value *control)
1269 {
1270         struct snd_kcontrol *kctl;
1271         struct snd_kcontrol_volatile *vd;
1272         unsigned int index_offset;
1273         int result = 0;
1274
1275         down_write(&card->controls_rwsem);
1276         kctl = snd_ctl_find_id(card, &control->id);
1277         if (kctl == NULL) {
1278                 up_write(&card->controls_rwsem);
1279                 return -ENOENT;
1280         }
1281
1282         index_offset = snd_ctl_get_ioff(kctl, &control->id);
1283         vd = &kctl->vd[index_offset];
1284         if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) || kctl->put == NULL ||
1285             (file && vd->owner && vd->owner != file)) {
1286                 up_write(&card->controls_rwsem);
1287                 return -EPERM;
1288         }
1289
1290         snd_ctl_build_ioff(&control->id, kctl, index_offset);
1291         /* validate input values */
1292         if (IS_ENABLED(CONFIG_SND_CTL_INPUT_VALIDATION)) {
1293                 struct snd_ctl_elem_info info;
1294
1295                 memset(&info, 0, sizeof(info));
1296                 info.id = control->id;
1297                 result = __snd_ctl_elem_info(card, kctl, &info, NULL);
1298                 if (!result)
1299                         result = sanity_check_input_values(card, control, &info,
1300                                                            false);
1301         }
1302         if (!result)
1303                 result = kctl->put(kctl, control);
1304         if (result < 0) {
1305                 up_write(&card->controls_rwsem);
1306                 return result;
1307         }
1308
1309         if (result > 0) {
1310                 downgrade_write(&card->controls_rwsem);
1311                 snd_ctl_notify_one(card, SNDRV_CTL_EVENT_MASK_VALUE, kctl, index_offset);
1312                 up_read(&card->controls_rwsem);
1313         } else {
1314                 up_write(&card->controls_rwsem);
1315         }
1316
1317         return 0;
1318 }
1319
1320 static int snd_ctl_elem_write_user(struct snd_ctl_file *file,
1321                                    struct snd_ctl_elem_value __user *_control)
1322 {
1323         struct snd_ctl_elem_value *control __free(kfree) = NULL;
1324         struct snd_card *card;
1325         int result;
1326
1327         control = memdup_user(_control, sizeof(*control));
1328         if (IS_ERR(control))
1329                 return PTR_ERR(control);
1330
1331         card = file->card;
1332         result = snd_power_ref_and_wait(card);
1333         if (result < 0)
1334                 return result;
1335         result = snd_ctl_elem_write(card, file, control);
1336         snd_power_unref(card);
1337         if (result < 0)
1338                 return result;
1339
1340         if (copy_to_user(_control, control, sizeof(*control)))
1341                 return -EFAULT;
1342         return result;
1343 }
1344
1345 static int snd_ctl_elem_lock(struct snd_ctl_file *file,
1346                              struct snd_ctl_elem_id __user *_id)
1347 {
1348         struct snd_card *card = file->card;
1349         struct snd_ctl_elem_id id;
1350         struct snd_kcontrol *kctl;
1351         struct snd_kcontrol_volatile *vd;
1352
1353         if (copy_from_user(&id, _id, sizeof(id)))
1354                 return -EFAULT;
1355         guard(rwsem_write)(&card->controls_rwsem);
1356         kctl = snd_ctl_find_id(card, &id);
1357         if (!kctl)
1358                 return -ENOENT;
1359         vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
1360         if (vd->owner)
1361                 return -EBUSY;
1362         vd->owner = file;
1363         return 0;
1364 }
1365
1366 static int snd_ctl_elem_unlock(struct snd_ctl_file *file,
1367                                struct snd_ctl_elem_id __user *_id)
1368 {
1369         struct snd_card *card = file->card;
1370         struct snd_ctl_elem_id id;
1371         struct snd_kcontrol *kctl;
1372         struct snd_kcontrol_volatile *vd;
1373
1374         if (copy_from_user(&id, _id, sizeof(id)))
1375                 return -EFAULT;
1376         guard(rwsem_write)(&card->controls_rwsem);
1377         kctl = snd_ctl_find_id(card, &id);
1378         if (!kctl)
1379                 return -ENOENT;
1380         vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
1381         if (!vd->owner)
1382                 return -EINVAL;
1383         if (vd->owner != file)
1384                 return -EPERM;
1385         vd->owner = NULL;
1386         return 0;
1387 }
1388
1389 struct user_element {
1390         struct snd_ctl_elem_info info;
1391         struct snd_card *card;
1392         char *elem_data;                /* element data */
1393         unsigned long elem_data_size;   /* size of element data in bytes */
1394         void *tlv_data;                 /* TLV data */
1395         unsigned long tlv_data_size;    /* TLV data size */
1396         void *priv_data;                /* private data (like strings for enumerated type) */
1397 };
1398
1399 // check whether the addition (in bytes) of user ctl element may overflow the limit.
1400 static bool check_user_elem_overflow(struct snd_card *card, ssize_t add)
1401 {
1402         return (ssize_t)card->user_ctl_alloc_size + add > max_user_ctl_alloc_size;
1403 }
1404
1405 static int snd_ctl_elem_user_info(struct snd_kcontrol *kcontrol,
1406                                   struct snd_ctl_elem_info *uinfo)
1407 {
1408         struct user_element *ue = kcontrol->private_data;
1409         unsigned int offset;
1410
1411         offset = snd_ctl_get_ioff(kcontrol, &uinfo->id);
1412         *uinfo = ue->info;
1413         snd_ctl_build_ioff(&uinfo->id, kcontrol, offset);
1414
1415         return 0;
1416 }
1417
1418 static int snd_ctl_elem_user_enum_info(struct snd_kcontrol *kcontrol,
1419                                        struct snd_ctl_elem_info *uinfo)
1420 {
1421         struct user_element *ue = kcontrol->private_data;
1422         const char *names;
1423         unsigned int item;
1424         unsigned int offset;
1425
1426         item = uinfo->value.enumerated.item;
1427
1428         offset = snd_ctl_get_ioff(kcontrol, &uinfo->id);
1429         *uinfo = ue->info;
1430         snd_ctl_build_ioff(&uinfo->id, kcontrol, offset);
1431
1432         item = min(item, uinfo->value.enumerated.items - 1);
1433         uinfo->value.enumerated.item = item;
1434
1435         names = ue->priv_data;
1436         for (; item > 0; --item)
1437                 names += strlen(names) + 1;
1438         strcpy(uinfo->value.enumerated.name, names);
1439
1440         return 0;
1441 }
1442
1443 static int snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol,
1444                                  struct snd_ctl_elem_value *ucontrol)
1445 {
1446         struct user_element *ue = kcontrol->private_data;
1447         unsigned int size = ue->elem_data_size;
1448         char *src = ue->elem_data +
1449                         snd_ctl_get_ioff(kcontrol, &ucontrol->id) * size;
1450
1451         memcpy(&ucontrol->value, src, size);
1452         return 0;
1453 }
1454
1455 static int snd_ctl_elem_user_put(struct snd_kcontrol *kcontrol,
1456                                  struct snd_ctl_elem_value *ucontrol)
1457 {
1458         int err, change;
1459         struct user_element *ue = kcontrol->private_data;
1460         unsigned int size = ue->elem_data_size;
1461         char *dst = ue->elem_data +
1462                         snd_ctl_get_ioff(kcontrol, &ucontrol->id) * size;
1463
1464         err = sanity_check_input_values(ue->card, ucontrol, &ue->info, false);
1465         if (err < 0)
1466                 return err;
1467
1468         change = memcmp(&ucontrol->value, dst, size) != 0;
1469         if (change)
1470                 memcpy(dst, &ucontrol->value, size);
1471         return change;
1472 }
1473
1474 /* called in controls_rwsem write lock */
1475 static int replace_user_tlv(struct snd_kcontrol *kctl, unsigned int __user *buf,
1476                             unsigned int size)
1477 {
1478         struct user_element *ue = kctl->private_data;
1479         unsigned int *container;
1480         unsigned int mask = 0;
1481         int i;
1482         int change;
1483
1484         lockdep_assert_held_write(&ue->card->controls_rwsem);
1485
1486         if (size > 1024 * 128)  /* sane value */
1487                 return -EINVAL;
1488
1489         // does the TLV size change cause overflow?
1490         if (check_user_elem_overflow(ue->card, (ssize_t)(size - ue->tlv_data_size)))
1491                 return -ENOMEM;
1492
1493         container = vmemdup_user(buf, size);
1494         if (IS_ERR(container))
1495                 return PTR_ERR(container);
1496
1497         change = ue->tlv_data_size != size;
1498         if (!change)
1499                 change = memcmp(ue->tlv_data, container, size) != 0;
1500         if (!change) {
1501                 kvfree(container);
1502                 return 0;
1503         }
1504
1505         if (ue->tlv_data == NULL) {
1506                 /* Now TLV data is available. */
1507                 for (i = 0; i < kctl->count; ++i)
1508                         kctl->vd[i].access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ;
1509                 mask = SNDRV_CTL_EVENT_MASK_INFO;
1510         } else {
1511                 ue->card->user_ctl_alloc_size -= ue->tlv_data_size;
1512                 ue->tlv_data_size = 0;
1513                 kvfree(ue->tlv_data);
1514         }
1515
1516         ue->tlv_data = container;
1517         ue->tlv_data_size = size;
1518         // decremented at private_free.
1519         ue->card->user_ctl_alloc_size += size;
1520
1521         mask |= SNDRV_CTL_EVENT_MASK_TLV;
1522         for (i = 0; i < kctl->count; ++i)
1523                 snd_ctl_notify_one(ue->card, mask, kctl, i);
1524
1525         return change;
1526 }
1527
1528 static int read_user_tlv(struct snd_kcontrol *kctl, unsigned int __user *buf,
1529                          unsigned int size)
1530 {
1531         struct user_element *ue = kctl->private_data;
1532
1533         if (ue->tlv_data_size == 0 || ue->tlv_data == NULL)
1534                 return -ENXIO;
1535
1536         if (size < ue->tlv_data_size)
1537                 return -ENOSPC;
1538
1539         if (copy_to_user(buf, ue->tlv_data, ue->tlv_data_size))
1540                 return -EFAULT;
1541
1542         return 0;
1543 }
1544
1545 static int snd_ctl_elem_user_tlv(struct snd_kcontrol *kctl, int op_flag,
1546                                  unsigned int size, unsigned int __user *buf)
1547 {
1548         if (op_flag == SNDRV_CTL_TLV_OP_WRITE)
1549                 return replace_user_tlv(kctl, buf, size);
1550         else
1551                 return read_user_tlv(kctl, buf, size);
1552 }
1553
1554 /* called in controls_rwsem write lock */
1555 static int snd_ctl_elem_init_enum_names(struct user_element *ue)
1556 {
1557         char *names, *p;
1558         size_t buf_len, name_len;
1559         unsigned int i;
1560         const uintptr_t user_ptrval = ue->info.value.enumerated.names_ptr;
1561
1562         lockdep_assert_held_write(&ue->card->controls_rwsem);
1563
1564         buf_len = ue->info.value.enumerated.names_length;
1565         if (buf_len > 64 * 1024)
1566                 return -EINVAL;
1567
1568         if (check_user_elem_overflow(ue->card, buf_len))
1569                 return -ENOMEM;
1570         names = vmemdup_user((const void __user *)user_ptrval, buf_len);
1571         if (IS_ERR(names))
1572                 return PTR_ERR(names);
1573
1574         /* check that there are enough valid names */
1575         p = names;
1576         for (i = 0; i < ue->info.value.enumerated.items; ++i) {
1577                 name_len = strnlen(p, buf_len);
1578                 if (name_len == 0 || name_len >= 64 || name_len == buf_len) {
1579                         kvfree(names);
1580                         return -EINVAL;
1581                 }
1582                 p += name_len + 1;
1583                 buf_len -= name_len + 1;
1584         }
1585
1586         ue->priv_data = names;
1587         ue->info.value.enumerated.names_ptr = 0;
1588         // increment the allocation size; decremented again at private_free.
1589         ue->card->user_ctl_alloc_size += ue->info.value.enumerated.names_length;
1590
1591         return 0;
1592 }
1593
1594 static size_t compute_user_elem_size(size_t size, unsigned int count)
1595 {
1596         return sizeof(struct user_element) + size * count;
1597 }
1598
1599 static void snd_ctl_elem_user_free(struct snd_kcontrol *kcontrol)
1600 {
1601         struct user_element *ue = kcontrol->private_data;
1602
1603         // decrement the allocation size.
1604         ue->card->user_ctl_alloc_size -= compute_user_elem_size(ue->elem_data_size, kcontrol->count);
1605         ue->card->user_ctl_alloc_size -= ue->tlv_data_size;
1606         if (ue->priv_data)
1607                 ue->card->user_ctl_alloc_size -= ue->info.value.enumerated.names_length;
1608
1609         kvfree(ue->tlv_data);
1610         kvfree(ue->priv_data);
1611         kfree(ue);
1612 }
1613
1614 static int snd_ctl_elem_add(struct snd_ctl_file *file,
1615                             struct snd_ctl_elem_info *info, int replace)
1616 {
1617         struct snd_card *card = file->card;
1618         struct snd_kcontrol *kctl;
1619         unsigned int count;
1620         unsigned int access;
1621         long private_size;
1622         size_t alloc_size;
1623         struct user_element *ue;
1624         unsigned int offset;
1625         int err;
1626
1627         if (!*info->id.name)
1628                 return -EINVAL;
1629         if (strnlen(info->id.name, sizeof(info->id.name)) >= sizeof(info->id.name))
1630                 return -EINVAL;
1631
1632         /* Delete a control to replace them if needed. */
1633         if (replace) {
1634                 info->id.numid = 0;
1635                 err = snd_ctl_remove_user_ctl(file, &info->id);
1636                 if (err)
1637                         return err;
1638         }
1639
1640         /* Check the number of elements for this userspace control. */
1641         count = info->owner;
1642         if (count == 0)
1643                 count = 1;
1644
1645         /* Arrange access permissions if needed. */
1646         access = info->access;
1647         if (access == 0)
1648                 access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
1649         access &= (SNDRV_CTL_ELEM_ACCESS_READWRITE |
1650                    SNDRV_CTL_ELEM_ACCESS_INACTIVE |
1651                    SNDRV_CTL_ELEM_ACCESS_TLV_WRITE);
1652
1653         /* In initial state, nothing is available as TLV container. */
1654         if (access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE)
1655                 access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
1656         access |= SNDRV_CTL_ELEM_ACCESS_USER;
1657
1658         /*
1659          * Check information and calculate the size of data specific to
1660          * this userspace control.
1661          */
1662         /* pass NULL to card for suppressing error messages */
1663         err = snd_ctl_check_elem_info(NULL, info);
1664         if (err < 0)
1665                 return err;
1666         /* user-space control doesn't allow zero-size data */
1667         if (info->count < 1)
1668                 return -EINVAL;
1669         private_size = value_sizes[info->type] * info->count;
1670         alloc_size = compute_user_elem_size(private_size, count);
1671
1672         guard(rwsem_write)(&card->controls_rwsem);
1673         if (check_user_elem_overflow(card, alloc_size))
1674                 return -ENOMEM;
1675
1676         /*
1677          * Keep memory object for this userspace control. After passing this
1678          * code block, the instance should be freed by snd_ctl_free_one().
1679          *
1680          * Note that these elements in this control are locked.
1681          */
1682         err = snd_ctl_new(&kctl, count, access, file);
1683         if (err < 0)
1684                 return err;
1685         memcpy(&kctl->id, &info->id, sizeof(kctl->id));
1686         ue = kzalloc(alloc_size, GFP_KERNEL);
1687         if (!ue) {
1688                 kfree(kctl);
1689                 return -ENOMEM;
1690         }
1691         kctl->private_data = ue;
1692         kctl->private_free = snd_ctl_elem_user_free;
1693
1694         // increment the allocated size; decremented again at private_free.
1695         card->user_ctl_alloc_size += alloc_size;
1696
1697         /* Set private data for this userspace control. */
1698         ue->card = card;
1699         ue->info = *info;
1700         ue->info.access = 0;
1701         ue->elem_data = (char *)ue + sizeof(*ue);
1702         ue->elem_data_size = private_size;
1703         if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
1704                 err = snd_ctl_elem_init_enum_names(ue);
1705                 if (err < 0) {
1706                         snd_ctl_free_one(kctl);
1707                         return err;
1708                 }
1709         }
1710
1711         /* Set callback functions. */
1712         if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
1713                 kctl->info = snd_ctl_elem_user_enum_info;
1714         else
1715                 kctl->info = snd_ctl_elem_user_info;
1716         if (access & SNDRV_CTL_ELEM_ACCESS_READ)
1717                 kctl->get = snd_ctl_elem_user_get;
1718         if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
1719                 kctl->put = snd_ctl_elem_user_put;
1720         if (access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE)
1721                 kctl->tlv.c = snd_ctl_elem_user_tlv;
1722
1723         /* This function manage to free the instance on failure. */
1724         err = __snd_ctl_add_replace(card, kctl, CTL_ADD_EXCLUSIVE);
1725         if (err < 0) {
1726                 snd_ctl_free_one(kctl);
1727                 return err;
1728         }
1729         offset = snd_ctl_get_ioff(kctl, &info->id);
1730         snd_ctl_build_ioff(&info->id, kctl, offset);
1731         /*
1732          * Here we cannot fill any field for the number of elements added by
1733          * this operation because there're no specific fields. The usage of
1734          * 'owner' field for this purpose may cause any bugs to userspace
1735          * applications because the field originally means PID of a process
1736          * which locks the element.
1737          */
1738         return 0;
1739 }
1740
1741 static int snd_ctl_elem_add_user(struct snd_ctl_file *file,
1742                                  struct snd_ctl_elem_info __user *_info, int replace)
1743 {
1744         struct snd_ctl_elem_info info;
1745         int err;
1746
1747         if (copy_from_user(&info, _info, sizeof(info)))
1748                 return -EFAULT;
1749         err = snd_ctl_elem_add(file, &info, replace);
1750         if (err < 0)
1751                 return err;
1752         if (copy_to_user(_info, &info, sizeof(info))) {
1753                 snd_ctl_remove_user_ctl(file, &info.id);
1754                 return -EFAULT;
1755         }
1756
1757         return 0;
1758 }
1759
1760 static int snd_ctl_elem_remove(struct snd_ctl_file *file,
1761                                struct snd_ctl_elem_id __user *_id)
1762 {
1763         struct snd_ctl_elem_id id;
1764
1765         if (copy_from_user(&id, _id, sizeof(id)))
1766                 return -EFAULT;
1767         return snd_ctl_remove_user_ctl(file, &id);
1768 }
1769
1770 static int snd_ctl_subscribe_events(struct snd_ctl_file *file, int __user *ptr)
1771 {
1772         int subscribe;
1773         if (get_user(subscribe, ptr))
1774                 return -EFAULT;
1775         if (subscribe < 0) {
1776                 subscribe = file->subscribed;
1777                 if (put_user(subscribe, ptr))
1778                         return -EFAULT;
1779                 return 0;
1780         }
1781         if (subscribe) {
1782                 file->subscribed = 1;
1783                 return 0;
1784         } else if (file->subscribed) {
1785                 snd_ctl_empty_read_queue(file);
1786                 file->subscribed = 0;
1787         }
1788         return 0;
1789 }
1790
1791 static int call_tlv_handler(struct snd_ctl_file *file, int op_flag,
1792                             struct snd_kcontrol *kctl,
1793                             struct snd_ctl_elem_id *id,
1794                             unsigned int __user *buf, unsigned int size)
1795 {
1796         static const struct {
1797                 int op;
1798                 int perm;
1799         } pairs[] = {
1800                 {SNDRV_CTL_TLV_OP_READ,  SNDRV_CTL_ELEM_ACCESS_TLV_READ},
1801                 {SNDRV_CTL_TLV_OP_WRITE, SNDRV_CTL_ELEM_ACCESS_TLV_WRITE},
1802                 {SNDRV_CTL_TLV_OP_CMD,   SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND},
1803         };
1804         struct snd_kcontrol_volatile *vd = &kctl->vd[snd_ctl_get_ioff(kctl, id)];
1805         int i;
1806
1807         /* Check support of the request for this element. */
1808         for (i = 0; i < ARRAY_SIZE(pairs); ++i) {
1809                 if (op_flag == pairs[i].op && (vd->access & pairs[i].perm))
1810                         break;
1811         }
1812         if (i == ARRAY_SIZE(pairs))
1813                 return -ENXIO;
1814
1815         if (kctl->tlv.c == NULL)
1816                 return -ENXIO;
1817
1818         /* Write and command operations are not allowed for locked element. */
1819         if (op_flag != SNDRV_CTL_TLV_OP_READ &&
1820             vd->owner != NULL && vd->owner != file)
1821                 return -EPERM;
1822
1823         return kctl->tlv.c(kctl, op_flag, size, buf);
1824 }
1825
1826 static int read_tlv_buf(struct snd_kcontrol *kctl, struct snd_ctl_elem_id *id,
1827                         unsigned int __user *buf, unsigned int size)
1828 {
1829         struct snd_kcontrol_volatile *vd = &kctl->vd[snd_ctl_get_ioff(kctl, id)];
1830         unsigned int len;
1831
1832         if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ))
1833                 return -ENXIO;
1834
1835         if (kctl->tlv.p == NULL)
1836                 return -ENXIO;
1837
1838         len = sizeof(unsigned int) * 2 + kctl->tlv.p[1];
1839         if (size < len)
1840                 return -ENOMEM;
1841
1842         if (copy_to_user(buf, kctl->tlv.p, len))
1843                 return -EFAULT;
1844
1845         return 0;
1846 }
1847
1848 static int snd_ctl_tlv_ioctl(struct snd_ctl_file *file,
1849                              struct snd_ctl_tlv __user *buf,
1850                              int op_flag)
1851 {
1852         struct snd_ctl_tlv header;
1853         unsigned int __user *container;
1854         unsigned int container_size;
1855         struct snd_kcontrol *kctl;
1856         struct snd_ctl_elem_id id;
1857         struct snd_kcontrol_volatile *vd;
1858
1859         lockdep_assert_held(&file->card->controls_rwsem);
1860
1861         if (copy_from_user(&header, buf, sizeof(header)))
1862                 return -EFAULT;
1863
1864         /* In design of control core, numerical ID starts at 1. */
1865         if (header.numid == 0)
1866                 return -EINVAL;
1867
1868         /* At least, container should include type and length fields.  */
1869         if (header.length < sizeof(unsigned int) * 2)
1870                 return -EINVAL;
1871         container_size = header.length;
1872         container = buf->tlv;
1873
1874         kctl = snd_ctl_find_numid(file->card, header.numid);
1875         if (kctl == NULL)
1876                 return -ENOENT;
1877
1878         /* Calculate index of the element in this set. */
1879         id = kctl->id;
1880         snd_ctl_build_ioff(&id, kctl, header.numid - id.numid);
1881         vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
1882
1883         if (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
1884                 return call_tlv_handler(file, op_flag, kctl, &id, container,
1885                                         container_size);
1886         } else {
1887                 if (op_flag == SNDRV_CTL_TLV_OP_READ) {
1888                         return read_tlv_buf(kctl, &id, container,
1889                                             container_size);
1890                 }
1891         }
1892
1893         /* Not supported. */
1894         return -ENXIO;
1895 }
1896
1897 static long snd_ctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1898 {
1899         struct snd_ctl_file *ctl;
1900         struct snd_card *card;
1901         struct snd_kctl_ioctl *p;
1902         void __user *argp = (void __user *)arg;
1903         int __user *ip = argp;
1904         int err;
1905
1906         ctl = file->private_data;
1907         card = ctl->card;
1908         if (snd_BUG_ON(!card))
1909                 return -ENXIO;
1910         switch (cmd) {
1911         case SNDRV_CTL_IOCTL_PVERSION:
1912                 return put_user(SNDRV_CTL_VERSION, ip) ? -EFAULT : 0;
1913         case SNDRV_CTL_IOCTL_CARD_INFO:
1914                 return snd_ctl_card_info(card, ctl, cmd, argp);
1915         case SNDRV_CTL_IOCTL_ELEM_LIST:
1916                 return snd_ctl_elem_list_user(card, argp);
1917         case SNDRV_CTL_IOCTL_ELEM_INFO:
1918                 return snd_ctl_elem_info_user(ctl, argp);
1919         case SNDRV_CTL_IOCTL_ELEM_READ:
1920                 return snd_ctl_elem_read_user(card, argp);
1921         case SNDRV_CTL_IOCTL_ELEM_WRITE:
1922                 return snd_ctl_elem_write_user(ctl, argp);
1923         case SNDRV_CTL_IOCTL_ELEM_LOCK:
1924                 return snd_ctl_elem_lock(ctl, argp);
1925         case SNDRV_CTL_IOCTL_ELEM_UNLOCK:
1926                 return snd_ctl_elem_unlock(ctl, argp);
1927         case SNDRV_CTL_IOCTL_ELEM_ADD:
1928                 return snd_ctl_elem_add_user(ctl, argp, 0);
1929         case SNDRV_CTL_IOCTL_ELEM_REPLACE:
1930                 return snd_ctl_elem_add_user(ctl, argp, 1);
1931         case SNDRV_CTL_IOCTL_ELEM_REMOVE:
1932                 return snd_ctl_elem_remove(ctl, argp);
1933         case SNDRV_CTL_IOCTL_SUBSCRIBE_EVENTS:
1934                 return snd_ctl_subscribe_events(ctl, ip);
1935         case SNDRV_CTL_IOCTL_TLV_READ:
1936                 err = snd_power_ref_and_wait(card);
1937                 if (err < 0)
1938                         return err;
1939                 scoped_guard(rwsem_read, &card->controls_rwsem)
1940                         err = snd_ctl_tlv_ioctl(ctl, argp, SNDRV_CTL_TLV_OP_READ);
1941                 snd_power_unref(card);
1942                 return err;
1943         case SNDRV_CTL_IOCTL_TLV_WRITE:
1944                 err = snd_power_ref_and_wait(card);
1945                 if (err < 0)
1946                         return err;
1947                 scoped_guard(rwsem_write, &card->controls_rwsem)
1948                         err = snd_ctl_tlv_ioctl(ctl, argp, SNDRV_CTL_TLV_OP_WRITE);
1949                 snd_power_unref(card);
1950                 return err;
1951         case SNDRV_CTL_IOCTL_TLV_COMMAND:
1952                 err = snd_power_ref_and_wait(card);
1953                 if (err < 0)
1954                         return err;
1955                 scoped_guard(rwsem_write, &card->controls_rwsem)
1956                         err = snd_ctl_tlv_ioctl(ctl, argp, SNDRV_CTL_TLV_OP_CMD);
1957                 snd_power_unref(card);
1958                 return err;
1959         case SNDRV_CTL_IOCTL_POWER:
1960                 return -ENOPROTOOPT;
1961         case SNDRV_CTL_IOCTL_POWER_STATE:
1962                 return put_user(SNDRV_CTL_POWER_D0, ip) ? -EFAULT : 0;
1963         }
1964
1965         guard(rwsem_read)(&snd_ioctl_rwsem);
1966         list_for_each_entry(p, &snd_control_ioctls, list) {
1967                 err = p->fioctl(card, ctl, cmd, arg);
1968                 if (err != -ENOIOCTLCMD)
1969                         return err;
1970         }
1971         dev_dbg(card->dev, "unknown ioctl = 0x%x\n", cmd);
1972         return -ENOTTY;
1973 }
1974
1975 static ssize_t snd_ctl_read(struct file *file, char __user *buffer,
1976                             size_t count, loff_t * offset)
1977 {
1978         struct snd_ctl_file *ctl;
1979         int err = 0;
1980         ssize_t result = 0;
1981
1982         ctl = file->private_data;
1983         if (snd_BUG_ON(!ctl || !ctl->card))
1984                 return -ENXIO;
1985         if (!ctl->subscribed)
1986                 return -EBADFD;
1987         if (count < sizeof(struct snd_ctl_event))
1988                 return -EINVAL;
1989         spin_lock_irq(&ctl->read_lock);
1990         while (count >= sizeof(struct snd_ctl_event)) {
1991                 struct snd_ctl_event ev;
1992                 struct snd_kctl_event *kev;
1993                 while (list_empty(&ctl->events)) {
1994                         wait_queue_entry_t wait;
1995                         if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
1996                                 err = -EAGAIN;
1997                                 goto __end_lock;
1998                         }
1999                         init_waitqueue_entry(&wait, current);
2000                         add_wait_queue(&ctl->change_sleep, &wait);
2001                         set_current_state(TASK_INTERRUPTIBLE);
2002                         spin_unlock_irq(&ctl->read_lock);
2003                         schedule();
2004                         remove_wait_queue(&ctl->change_sleep, &wait);
2005                         if (ctl->card->shutdown)
2006                                 return -ENODEV;
2007                         if (signal_pending(current))
2008                                 return -ERESTARTSYS;
2009                         spin_lock_irq(&ctl->read_lock);
2010                 }
2011                 kev = snd_kctl_event(ctl->events.next);
2012                 ev.type = SNDRV_CTL_EVENT_ELEM;
2013                 ev.data.elem.mask = kev->mask;
2014                 ev.data.elem.id = kev->id;
2015                 list_del(&kev->list);
2016                 spin_unlock_irq(&ctl->read_lock);
2017                 kfree(kev);
2018                 if (copy_to_user(buffer, &ev, sizeof(struct snd_ctl_event))) {
2019                         err = -EFAULT;
2020                         goto __end;
2021                 }
2022                 spin_lock_irq(&ctl->read_lock);
2023                 buffer += sizeof(struct snd_ctl_event);
2024                 count -= sizeof(struct snd_ctl_event);
2025                 result += sizeof(struct snd_ctl_event);
2026         }
2027       __end_lock:
2028         spin_unlock_irq(&ctl->read_lock);
2029       __end:
2030         return result > 0 ? result : err;
2031 }
2032
2033 static __poll_t snd_ctl_poll(struct file *file, poll_table * wait)
2034 {
2035         __poll_t mask;
2036         struct snd_ctl_file *ctl;
2037
2038         ctl = file->private_data;
2039         if (!ctl->subscribed)
2040                 return 0;
2041         poll_wait(file, &ctl->change_sleep, wait);
2042
2043         mask = 0;
2044         if (!list_empty(&ctl->events))
2045                 mask |= EPOLLIN | EPOLLRDNORM;
2046
2047         return mask;
2048 }
2049
2050 /*
2051  * register the device-specific control-ioctls.
2052  * called from each device manager like pcm.c, hwdep.c, etc.
2053  */
2054 static int _snd_ctl_register_ioctl(snd_kctl_ioctl_func_t fcn, struct list_head *lists)
2055 {
2056         struct snd_kctl_ioctl *pn;
2057
2058         pn = kzalloc(sizeof(struct snd_kctl_ioctl), GFP_KERNEL);
2059         if (pn == NULL)
2060                 return -ENOMEM;
2061         pn->fioctl = fcn;
2062         guard(rwsem_write)(&snd_ioctl_rwsem);
2063         list_add_tail(&pn->list, lists);
2064         return 0;
2065 }
2066
2067 /**
2068  * snd_ctl_register_ioctl - register the device-specific control-ioctls
2069  * @fcn: ioctl callback function
2070  *
2071  * called from each device manager like pcm.c, hwdep.c, etc.
2072  *
2073  * Return: zero if successful, or a negative error code
2074  */
2075 int snd_ctl_register_ioctl(snd_kctl_ioctl_func_t fcn)
2076 {
2077         return _snd_ctl_register_ioctl(fcn, &snd_control_ioctls);
2078 }
2079 EXPORT_SYMBOL(snd_ctl_register_ioctl);
2080
2081 #ifdef CONFIG_COMPAT
2082 /**
2083  * snd_ctl_register_ioctl_compat - register the device-specific 32bit compat
2084  * control-ioctls
2085  * @fcn: ioctl callback function
2086  *
2087  * Return: zero if successful, or a negative error code
2088  */
2089 int snd_ctl_register_ioctl_compat(snd_kctl_ioctl_func_t fcn)
2090 {
2091         return _snd_ctl_register_ioctl(fcn, &snd_control_compat_ioctls);
2092 }
2093 EXPORT_SYMBOL(snd_ctl_register_ioctl_compat);
2094 #endif
2095
2096 /*
2097  * de-register the device-specific control-ioctls.
2098  */
2099 static int _snd_ctl_unregister_ioctl(snd_kctl_ioctl_func_t fcn,
2100                                      struct list_head *lists)
2101 {
2102         struct snd_kctl_ioctl *p;
2103
2104         if (snd_BUG_ON(!fcn))
2105                 return -EINVAL;
2106         guard(rwsem_write)(&snd_ioctl_rwsem);
2107         list_for_each_entry(p, lists, list) {
2108                 if (p->fioctl == fcn) {
2109                         list_del(&p->list);
2110                         kfree(p);
2111                         return 0;
2112                 }
2113         }
2114         snd_BUG();
2115         return -EINVAL;
2116 }
2117
2118 /**
2119  * snd_ctl_unregister_ioctl - de-register the device-specific control-ioctls
2120  * @fcn: ioctl callback function to unregister
2121  *
2122  * Return: zero if successful, or a negative error code
2123  */
2124 int snd_ctl_unregister_ioctl(snd_kctl_ioctl_func_t fcn)
2125 {
2126         return _snd_ctl_unregister_ioctl(fcn, &snd_control_ioctls);
2127 }
2128 EXPORT_SYMBOL(snd_ctl_unregister_ioctl);
2129
2130 #ifdef CONFIG_COMPAT
2131 /**
2132  * snd_ctl_unregister_ioctl_compat - de-register the device-specific compat
2133  * 32bit control-ioctls
2134  * @fcn: ioctl callback function to unregister
2135  *
2136  * Return: zero if successful, or a negative error code
2137  */
2138 int snd_ctl_unregister_ioctl_compat(snd_kctl_ioctl_func_t fcn)
2139 {
2140         return _snd_ctl_unregister_ioctl(fcn, &snd_control_compat_ioctls);
2141 }
2142 EXPORT_SYMBOL(snd_ctl_unregister_ioctl_compat);
2143 #endif
2144
2145 static int snd_ctl_fasync(int fd, struct file * file, int on)
2146 {
2147         struct snd_ctl_file *ctl;
2148
2149         ctl = file->private_data;
2150         return snd_fasync_helper(fd, file, on, &ctl->fasync);
2151 }
2152
2153 /* return the preferred subdevice number if already assigned;
2154  * otherwise return -1
2155  */
2156 int snd_ctl_get_preferred_subdevice(struct snd_card *card, int type)
2157 {
2158         struct snd_ctl_file *kctl;
2159         int subdevice = -1;
2160
2161         guard(read_lock_irqsave)(&card->controls_rwlock);
2162         list_for_each_entry(kctl, &card->ctl_files, list) {
2163                 if (kctl->pid == task_pid(current)) {
2164                         subdevice = kctl->preferred_subdevice[type];
2165                         if (subdevice != -1)
2166                                 break;
2167                 }
2168         }
2169         return subdevice;
2170 }
2171 EXPORT_SYMBOL_GPL(snd_ctl_get_preferred_subdevice);
2172
2173 /*
2174  * ioctl32 compat
2175  */
2176 #ifdef CONFIG_COMPAT
2177 #include "control_compat.c"
2178 #else
2179 #define snd_ctl_ioctl_compat    NULL
2180 #endif
2181
2182 /*
2183  * control layers (audio LED etc.)
2184  */
2185
2186 /**
2187  * snd_ctl_request_layer - request to use the layer
2188  * @module_name: Name of the kernel module (NULL == build-in)
2189  *
2190  * Return: zero if successful, or an error code when the module cannot be loaded
2191  */
2192 int snd_ctl_request_layer(const char *module_name)
2193 {
2194         struct snd_ctl_layer_ops *lops;
2195
2196         if (module_name == NULL)
2197                 return 0;
2198         scoped_guard(rwsem_read, &snd_ctl_layer_rwsem) {
2199                 for (lops = snd_ctl_layer; lops; lops = lops->next)
2200                         if (strcmp(lops->module_name, module_name) == 0)
2201                                 return 0;
2202         }
2203         return request_module(module_name);
2204 }
2205 EXPORT_SYMBOL_GPL(snd_ctl_request_layer);
2206
2207 /**
2208  * snd_ctl_register_layer - register new control layer
2209  * @lops: operation structure
2210  *
2211  * The new layer can track all control elements and do additional
2212  * operations on top (like audio LED handling).
2213  */
2214 void snd_ctl_register_layer(struct snd_ctl_layer_ops *lops)
2215 {
2216         struct snd_card *card;
2217         int card_number;
2218
2219         scoped_guard(rwsem_write, &snd_ctl_layer_rwsem) {
2220                 lops->next = snd_ctl_layer;
2221                 snd_ctl_layer = lops;
2222         }
2223         for (card_number = 0; card_number < SNDRV_CARDS; card_number++) {
2224                 card = snd_card_ref(card_number);
2225                 if (card) {
2226                         scoped_guard(rwsem_read, &card->controls_rwsem)
2227                                 lops->lregister(card);
2228                         snd_card_unref(card);
2229                 }
2230         }
2231 }
2232 EXPORT_SYMBOL_GPL(snd_ctl_register_layer);
2233
2234 /**
2235  * snd_ctl_disconnect_layer - disconnect control layer
2236  * @lops: operation structure
2237  *
2238  * It is expected that the information about tracked cards
2239  * is freed before this call (the disconnect callback is
2240  * not called here).
2241  */
2242 void snd_ctl_disconnect_layer(struct snd_ctl_layer_ops *lops)
2243 {
2244         struct snd_ctl_layer_ops *lops2, *prev_lops2;
2245
2246         guard(rwsem_write)(&snd_ctl_layer_rwsem);
2247         for (lops2 = snd_ctl_layer, prev_lops2 = NULL; lops2; lops2 = lops2->next) {
2248                 if (lops2 == lops) {
2249                         if (!prev_lops2)
2250                                 snd_ctl_layer = lops->next;
2251                         else
2252                                 prev_lops2->next = lops->next;
2253                         break;
2254                 }
2255                 prev_lops2 = lops2;
2256         }
2257 }
2258 EXPORT_SYMBOL_GPL(snd_ctl_disconnect_layer);
2259
2260 /*
2261  *  INIT PART
2262  */
2263
2264 static const struct file_operations snd_ctl_f_ops =
2265 {
2266         .owner =        THIS_MODULE,
2267         .read =         snd_ctl_read,
2268         .open =         snd_ctl_open,
2269         .release =      snd_ctl_release,
2270         .poll =         snd_ctl_poll,
2271         .unlocked_ioctl =       snd_ctl_ioctl,
2272         .compat_ioctl = snd_ctl_ioctl_compat,
2273         .fasync =       snd_ctl_fasync,
2274 };
2275
2276 /* call lops under rwsems; called from snd_ctl_dev_*() below() */
2277 #define call_snd_ctl_lops(_card, _op)                               \
2278         do {                                                        \
2279                 struct snd_ctl_layer_ops *lops;                     \
2280                 guard(rwsem_read)(&(_card)->controls_rwsem);        \
2281                 guard(rwsem_read)(&snd_ctl_layer_rwsem);            \
2282                 for (lops = snd_ctl_layer; lops; lops = lops->next) \
2283                         lops->_op(_card);                           \
2284         } while (0)
2285
2286 /*
2287  * registration of the control device
2288  */
2289 static int snd_ctl_dev_register(struct snd_device *device)
2290 {
2291         struct snd_card *card = device->device_data;
2292         int err;
2293
2294         err = snd_register_device(SNDRV_DEVICE_TYPE_CONTROL, card, -1,
2295                                   &snd_ctl_f_ops, card, card->ctl_dev);
2296         if (err < 0)
2297                 return err;
2298         call_snd_ctl_lops(card, lregister);
2299         return 0;
2300 }
2301
2302 /*
2303  * disconnection of the control device
2304  */
2305 static int snd_ctl_dev_disconnect(struct snd_device *device)
2306 {
2307         struct snd_card *card = device->device_data;
2308         struct snd_ctl_file *ctl;
2309
2310         scoped_guard(read_lock_irqsave, &card->controls_rwlock) {
2311                 list_for_each_entry(ctl, &card->ctl_files, list) {
2312                         wake_up(&ctl->change_sleep);
2313                         snd_kill_fasync(ctl->fasync, SIGIO, POLL_ERR);
2314                 }
2315         }
2316
2317         call_snd_ctl_lops(card, ldisconnect);
2318         return snd_unregister_device(card->ctl_dev);
2319 }
2320
2321 /*
2322  * free all controls
2323  */
2324 static int snd_ctl_dev_free(struct snd_device *device)
2325 {
2326         struct snd_card *card = device->device_data;
2327         struct snd_kcontrol *control;
2328
2329         scoped_guard(rwsem_write, &card->controls_rwsem) {
2330                 while (!list_empty(&card->controls)) {
2331                         control = snd_kcontrol(card->controls.next);
2332                         __snd_ctl_remove(card, control, false);
2333                 }
2334
2335 #ifdef CONFIG_SND_CTL_FAST_LOOKUP
2336                 xa_destroy(&card->ctl_numids);
2337                 xa_destroy(&card->ctl_hash);
2338 #endif
2339         }
2340         put_device(card->ctl_dev);
2341         return 0;
2342 }
2343
2344 /*
2345  * create control core:
2346  * called from init.c
2347  */
2348 int snd_ctl_create(struct snd_card *card)
2349 {
2350         static const struct snd_device_ops ops = {
2351                 .dev_free = snd_ctl_dev_free,
2352                 .dev_register = snd_ctl_dev_register,
2353                 .dev_disconnect = snd_ctl_dev_disconnect,
2354         };
2355         int err;
2356
2357         if (snd_BUG_ON(!card))
2358                 return -ENXIO;
2359         if (snd_BUG_ON(card->number < 0 || card->number >= SNDRV_CARDS))
2360                 return -ENXIO;
2361
2362         err = snd_device_alloc(&card->ctl_dev, card);
2363         if (err < 0)
2364                 return err;
2365         dev_set_name(card->ctl_dev, "controlC%d", card->number);
2366
2367         err = snd_device_new(card, SNDRV_DEV_CONTROL, card, &ops);
2368         if (err < 0)
2369                 put_device(card->ctl_dev);
2370         return err;
2371 }
2372
2373 /*
2374  * Frequently used control callbacks/helpers
2375  */
2376
2377 /**
2378  * snd_ctl_boolean_mono_info - Helper function for a standard boolean info
2379  * callback with a mono channel
2380  * @kcontrol: the kcontrol instance
2381  * @uinfo: info to store
2382  *
2383  * This is a function that can be used as info callback for a standard
2384  * boolean control with a single mono channel.
2385  *
2386  * Return: Zero (always successful)
2387  */
2388 int snd_ctl_boolean_mono_info(struct snd_kcontrol *kcontrol,
2389                               struct snd_ctl_elem_info *uinfo)
2390 {
2391         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2392         uinfo->count = 1;
2393         uinfo->value.integer.min = 0;
2394         uinfo->value.integer.max = 1;
2395         return 0;
2396 }
2397 EXPORT_SYMBOL(snd_ctl_boolean_mono_info);
2398
2399 /**
2400  * snd_ctl_boolean_stereo_info - Helper function for a standard boolean info
2401  * callback with stereo two channels
2402  * @kcontrol: the kcontrol instance
2403  * @uinfo: info to store
2404  *
2405  * This is a function that can be used as info callback for a standard
2406  * boolean control with stereo two channels.
2407  *
2408  * Return: Zero (always successful)
2409  */
2410 int snd_ctl_boolean_stereo_info(struct snd_kcontrol *kcontrol,
2411                                 struct snd_ctl_elem_info *uinfo)
2412 {
2413         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2414         uinfo->count = 2;
2415         uinfo->value.integer.min = 0;
2416         uinfo->value.integer.max = 1;
2417         return 0;
2418 }
2419 EXPORT_SYMBOL(snd_ctl_boolean_stereo_info);
2420
2421 /**
2422  * snd_ctl_enum_info - fills the info structure for an enumerated control
2423  * @info: the structure to be filled
2424  * @channels: the number of the control's channels; often one
2425  * @items: the number of control values; also the size of @names
2426  * @names: an array containing the names of all control values
2427  *
2428  * Sets all required fields in @info to their appropriate values.
2429  * If the control's accessibility is not the default (readable and writable),
2430  * the caller has to fill @info->access.
2431  *
2432  * Return: Zero (always successful)
2433  */
2434 int snd_ctl_enum_info(struct snd_ctl_elem_info *info, unsigned int channels,
2435                       unsigned int items, const char *const names[])
2436 {
2437         info->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
2438         info->count = channels;
2439         info->value.enumerated.items = items;
2440         if (!items)
2441                 return 0;
2442         if (info->value.enumerated.item >= items)
2443                 info->value.enumerated.item = items - 1;
2444         WARN(strlen(names[info->value.enumerated.item]) >= sizeof(info->value.enumerated.name),
2445              "ALSA: too long item name '%s'\n",
2446              names[info->value.enumerated.item]);
2447         strscpy(info->value.enumerated.name,
2448                 names[info->value.enumerated.item],
2449                 sizeof(info->value.enumerated.name));
2450         return 0;
2451 }
2452 EXPORT_SYMBOL(snd_ctl_enum_info);