xref: /linux-6.15/sound/core/control.c (revision 38ea4c3d)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Routines for driver control interface
4  *  Copyright (c) by Jaroslav Kysela <[email protected]>
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 	for (idx = 0; idx < count; idx++) {
241 		(*kctl)->vd[idx].access = access;
242 		(*kctl)->vd[idx].owner = file;
243 	}
244 	(*kctl)->count = count;
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 = snd_power_ref_and_wait(card);
1138 	if (!result)
1139 		result = kctl->info(kctl, info);
1140 	snd_power_unref(card);
1141 	if (result >= 0) {
1142 		snd_BUG_ON(info->access);
1143 		index_offset = snd_ctl_get_ioff(kctl, &info->id);
1144 		vd = &kctl->vd[index_offset];
1145 		snd_ctl_build_ioff(&info->id, kctl, index_offset);
1146 		info->access = vd->access;
1147 		if (vd->owner) {
1148 			info->access |= SNDRV_CTL_ELEM_ACCESS_LOCK;
1149 			if (vd->owner == ctl)
1150 				info->access |= SNDRV_CTL_ELEM_ACCESS_OWNER;
1151 			info->owner = pid_vnr(vd->owner->pid);
1152 		} else {
1153 			info->owner = -1;
1154 		}
1155 		if (!snd_ctl_skip_validation(info) &&
1156 		    snd_ctl_check_elem_info(card, info) < 0)
1157 			result = -EINVAL;
1158 	}
1159 	return result;
1160 }
1161 
1162 static int snd_ctl_elem_info(struct snd_ctl_file *ctl,
1163 			     struct snd_ctl_elem_info *info)
1164 {
1165 	struct snd_card *card = ctl->card;
1166 	struct snd_kcontrol *kctl;
1167 
1168 	guard(rwsem_read)(&card->controls_rwsem);
1169 	kctl = snd_ctl_find_id(card, &info->id);
1170 	if (!kctl)
1171 		return -ENOENT;
1172 	return __snd_ctl_elem_info(card, kctl, info, ctl);
1173 }
1174 
1175 static int snd_ctl_elem_info_user(struct snd_ctl_file *ctl,
1176 				  struct snd_ctl_elem_info __user *_info)
1177 {
1178 	struct snd_ctl_elem_info info;
1179 	int result;
1180 
1181 	if (copy_from_user(&info, _info, sizeof(info)))
1182 		return -EFAULT;
1183 	result = snd_ctl_elem_info(ctl, &info);
1184 	if (result < 0)
1185 		return result;
1186 	/* drop internal access flags */
1187 	info.access &= ~(SNDRV_CTL_ELEM_ACCESS_SKIP_CHECK|
1188 			 SNDRV_CTL_ELEM_ACCESS_LED_MASK);
1189 	if (copy_to_user(_info, &info, sizeof(info)))
1190 		return -EFAULT;
1191 	return result;
1192 }
1193 
1194 static int snd_ctl_elem_read(struct snd_card *card,
1195 			     struct snd_ctl_elem_value *control)
1196 {
1197 	struct snd_kcontrol *kctl;
1198 	struct snd_kcontrol_volatile *vd;
1199 	unsigned int index_offset;
1200 	struct snd_ctl_elem_info info;
1201 	const u32 pattern = 0xdeadbeef;
1202 	int ret;
1203 
1204 	guard(rwsem_read)(&card->controls_rwsem);
1205 	kctl = snd_ctl_find_id(card, &control->id);
1206 	if (!kctl)
1207 		return -ENOENT;
1208 
1209 	index_offset = snd_ctl_get_ioff(kctl, &control->id);
1210 	vd = &kctl->vd[index_offset];
1211 	if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_READ) || !kctl->get)
1212 		return -EPERM;
1213 
1214 	snd_ctl_build_ioff(&control->id, kctl, index_offset);
1215 
1216 #ifdef CONFIG_SND_CTL_DEBUG
1217 	/* info is needed only for validation */
1218 	memset(&info, 0, sizeof(info));
1219 	info.id = control->id;
1220 	ret = __snd_ctl_elem_info(card, kctl, &info, NULL);
1221 	if (ret < 0)
1222 		return ret;
1223 #endif
1224 
1225 	if (!snd_ctl_skip_validation(&info))
1226 		fill_remaining_elem_value(control, &info, pattern);
1227 	ret = snd_power_ref_and_wait(card);
1228 	if (!ret)
1229 		ret = kctl->get(kctl, control);
1230 	snd_power_unref(card);
1231 	if (ret < 0)
1232 		return ret;
1233 	if (!snd_ctl_skip_validation(&info) &&
1234 	    sanity_check_elem_value(card, control, &info, pattern) < 0) {
1235 		dev_err(card->dev,
1236 			"control %i:%i:%i:%s:%i: access overflow\n",
1237 			control->id.iface, control->id.device,
1238 			control->id.subdevice, control->id.name,
1239 			control->id.index);
1240 		return -EINVAL;
1241 	}
1242 	return 0;
1243 }
1244 
1245 static int snd_ctl_elem_read_user(struct snd_card *card,
1246 				  struct snd_ctl_elem_value __user *_control)
1247 {
1248 	struct snd_ctl_elem_value *control __free(kfree) = NULL;
1249 	int result;
1250 
1251 	control = memdup_user(_control, sizeof(*control));
1252 	if (IS_ERR(control))
1253 		return PTR_ERR(no_free_ptr(control));
1254 
1255 	result = snd_ctl_elem_read(card, control);
1256 	if (result < 0)
1257 		return result;
1258 
1259 	if (copy_to_user(_control, control, sizeof(*control)))
1260 		return -EFAULT;
1261 	return result;
1262 }
1263 
1264 static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
1265 			      struct snd_ctl_elem_value *control)
1266 {
1267 	struct snd_kcontrol *kctl;
1268 	struct snd_kcontrol_volatile *vd;
1269 	unsigned int index_offset;
1270 	int result;
1271 
1272 	down_write(&card->controls_rwsem);
1273 	kctl = snd_ctl_find_id(card, &control->id);
1274 	if (kctl == NULL) {
1275 		up_write(&card->controls_rwsem);
1276 		return -ENOENT;
1277 	}
1278 
1279 	index_offset = snd_ctl_get_ioff(kctl, &control->id);
1280 	vd = &kctl->vd[index_offset];
1281 	if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) || kctl->put == NULL ||
1282 	    (file && vd->owner && vd->owner != file)) {
1283 		up_write(&card->controls_rwsem);
1284 		return -EPERM;
1285 	}
1286 
1287 	snd_ctl_build_ioff(&control->id, kctl, index_offset);
1288 	result = snd_power_ref_and_wait(card);
1289 	/* validate input values */
1290 	if (IS_ENABLED(CONFIG_SND_CTL_INPUT_VALIDATION) && !result) {
1291 		struct snd_ctl_elem_info info;
1292 
1293 		memset(&info, 0, sizeof(info));
1294 		info.id = control->id;
1295 		result = __snd_ctl_elem_info(card, kctl, &info, NULL);
1296 		if (!result)
1297 			result = sanity_check_input_values(card, control, &info,
1298 							   false);
1299 	}
1300 	if (!result)
1301 		result = kctl->put(kctl, control);
1302 	snd_power_unref(card);
1303 	if (result < 0) {
1304 		up_write(&card->controls_rwsem);
1305 		return result;
1306 	}
1307 
1308 	if (result > 0) {
1309 		downgrade_write(&card->controls_rwsem);
1310 		snd_ctl_notify_one(card, SNDRV_CTL_EVENT_MASK_VALUE, kctl, index_offset);
1311 		up_read(&card->controls_rwsem);
1312 	} else {
1313 		up_write(&card->controls_rwsem);
1314 	}
1315 
1316 	return 0;
1317 }
1318 
1319 static int snd_ctl_elem_write_user(struct snd_ctl_file *file,
1320 				   struct snd_ctl_elem_value __user *_control)
1321 {
1322 	struct snd_ctl_elem_value *control __free(kfree) = NULL;
1323 	struct snd_card *card;
1324 	int result;
1325 
1326 	control = memdup_user(_control, sizeof(*control));
1327 	if (IS_ERR(control))
1328 		return PTR_ERR(no_free_ptr(control));
1329 
1330 	card = file->card;
1331 	result = snd_ctl_elem_write(card, file, control);
1332 	if (result < 0)
1333 		return result;
1334 
1335 	if (copy_to_user(_control, control, sizeof(*control)))
1336 		return -EFAULT;
1337 	return result;
1338 }
1339 
1340 static int snd_ctl_elem_lock(struct snd_ctl_file *file,
1341 			     struct snd_ctl_elem_id __user *_id)
1342 {
1343 	struct snd_card *card = file->card;
1344 	struct snd_ctl_elem_id id;
1345 	struct snd_kcontrol *kctl;
1346 	struct snd_kcontrol_volatile *vd;
1347 
1348 	if (copy_from_user(&id, _id, sizeof(id)))
1349 		return -EFAULT;
1350 	guard(rwsem_write)(&card->controls_rwsem);
1351 	kctl = snd_ctl_find_id(card, &id);
1352 	if (!kctl)
1353 		return -ENOENT;
1354 	vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
1355 	if (vd->owner)
1356 		return -EBUSY;
1357 	vd->owner = file;
1358 	return 0;
1359 }
1360 
1361 static int snd_ctl_elem_unlock(struct snd_ctl_file *file,
1362 			       struct snd_ctl_elem_id __user *_id)
1363 {
1364 	struct snd_card *card = file->card;
1365 	struct snd_ctl_elem_id id;
1366 	struct snd_kcontrol *kctl;
1367 	struct snd_kcontrol_volatile *vd;
1368 
1369 	if (copy_from_user(&id, _id, sizeof(id)))
1370 		return -EFAULT;
1371 	guard(rwsem_write)(&card->controls_rwsem);
1372 	kctl = snd_ctl_find_id(card, &id);
1373 	if (!kctl)
1374 		return -ENOENT;
1375 	vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
1376 	if (!vd->owner)
1377 		return -EINVAL;
1378 	if (vd->owner != file)
1379 		return -EPERM;
1380 	vd->owner = NULL;
1381 	return 0;
1382 }
1383 
1384 struct user_element {
1385 	struct snd_ctl_elem_info info;
1386 	struct snd_card *card;
1387 	char *elem_data;		/* element data */
1388 	unsigned long elem_data_size;	/* size of element data in bytes */
1389 	void *tlv_data;			/* TLV data */
1390 	unsigned long tlv_data_size;	/* TLV data size */
1391 	void *priv_data;		/* private data (like strings for enumerated type) */
1392 };
1393 
1394 // check whether the addition (in bytes) of user ctl element may overflow the limit.
1395 static bool check_user_elem_overflow(struct snd_card *card, ssize_t add)
1396 {
1397 	return (ssize_t)card->user_ctl_alloc_size + add > max_user_ctl_alloc_size;
1398 }
1399 
1400 static int snd_ctl_elem_user_info(struct snd_kcontrol *kcontrol,
1401 				  struct snd_ctl_elem_info *uinfo)
1402 {
1403 	struct user_element *ue = kcontrol->private_data;
1404 	unsigned int offset;
1405 
1406 	offset = snd_ctl_get_ioff(kcontrol, &uinfo->id);
1407 	*uinfo = ue->info;
1408 	snd_ctl_build_ioff(&uinfo->id, kcontrol, offset);
1409 
1410 	return 0;
1411 }
1412 
1413 static int snd_ctl_elem_user_enum_info(struct snd_kcontrol *kcontrol,
1414 				       struct snd_ctl_elem_info *uinfo)
1415 {
1416 	struct user_element *ue = kcontrol->private_data;
1417 	const char *names;
1418 	unsigned int item;
1419 	unsigned int offset;
1420 
1421 	item = uinfo->value.enumerated.item;
1422 
1423 	offset = snd_ctl_get_ioff(kcontrol, &uinfo->id);
1424 	*uinfo = ue->info;
1425 	snd_ctl_build_ioff(&uinfo->id, kcontrol, offset);
1426 
1427 	item = min(item, uinfo->value.enumerated.items - 1);
1428 	uinfo->value.enumerated.item = item;
1429 
1430 	names = ue->priv_data;
1431 	for (; item > 0; --item)
1432 		names += strlen(names) + 1;
1433 	strcpy(uinfo->value.enumerated.name, names);
1434 
1435 	return 0;
1436 }
1437 
1438 static int snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol,
1439 				 struct snd_ctl_elem_value *ucontrol)
1440 {
1441 	struct user_element *ue = kcontrol->private_data;
1442 	unsigned int size = ue->elem_data_size;
1443 	char *src = ue->elem_data +
1444 			snd_ctl_get_ioff(kcontrol, &ucontrol->id) * size;
1445 
1446 	memcpy(&ucontrol->value, src, size);
1447 	return 0;
1448 }
1449 
1450 static int snd_ctl_elem_user_put(struct snd_kcontrol *kcontrol,
1451 				 struct snd_ctl_elem_value *ucontrol)
1452 {
1453 	int err, change;
1454 	struct user_element *ue = kcontrol->private_data;
1455 	unsigned int size = ue->elem_data_size;
1456 	char *dst = ue->elem_data +
1457 			snd_ctl_get_ioff(kcontrol, &ucontrol->id) * size;
1458 
1459 	err = sanity_check_input_values(ue->card, ucontrol, &ue->info, false);
1460 	if (err < 0)
1461 		return err;
1462 
1463 	change = memcmp(&ucontrol->value, dst, size) != 0;
1464 	if (change)
1465 		memcpy(dst, &ucontrol->value, size);
1466 	return change;
1467 }
1468 
1469 /* called in controls_rwsem write lock */
1470 static int replace_user_tlv(struct snd_kcontrol *kctl, unsigned int __user *buf,
1471 			    unsigned int size)
1472 {
1473 	struct user_element *ue = kctl->private_data;
1474 	unsigned int *container;
1475 	unsigned int mask = 0;
1476 	int i;
1477 	int change;
1478 
1479 	lockdep_assert_held_write(&ue->card->controls_rwsem);
1480 
1481 	if (size > 1024 * 128)	/* sane value */
1482 		return -EINVAL;
1483 
1484 	// does the TLV size change cause overflow?
1485 	if (check_user_elem_overflow(ue->card, (ssize_t)(size - ue->tlv_data_size)))
1486 		return -ENOMEM;
1487 
1488 	container = vmemdup_user(buf, size);
1489 	if (IS_ERR(container))
1490 		return PTR_ERR(container);
1491 
1492 	change = ue->tlv_data_size != size;
1493 	if (!change)
1494 		change = memcmp(ue->tlv_data, container, size) != 0;
1495 	if (!change) {
1496 		kvfree(container);
1497 		return 0;
1498 	}
1499 
1500 	if (ue->tlv_data == NULL) {
1501 		/* Now TLV data is available. */
1502 		for (i = 0; i < kctl->count; ++i)
1503 			kctl->vd[i].access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ;
1504 		mask = SNDRV_CTL_EVENT_MASK_INFO;
1505 	} else {
1506 		ue->card->user_ctl_alloc_size -= ue->tlv_data_size;
1507 		ue->tlv_data_size = 0;
1508 		kvfree(ue->tlv_data);
1509 	}
1510 
1511 	ue->tlv_data = container;
1512 	ue->tlv_data_size = size;
1513 	// decremented at private_free.
1514 	ue->card->user_ctl_alloc_size += size;
1515 
1516 	mask |= SNDRV_CTL_EVENT_MASK_TLV;
1517 	for (i = 0; i < kctl->count; ++i)
1518 		snd_ctl_notify_one(ue->card, mask, kctl, i);
1519 
1520 	return change;
1521 }
1522 
1523 static int read_user_tlv(struct snd_kcontrol *kctl, unsigned int __user *buf,
1524 			 unsigned int size)
1525 {
1526 	struct user_element *ue = kctl->private_data;
1527 
1528 	if (ue->tlv_data_size == 0 || ue->tlv_data == NULL)
1529 		return -ENXIO;
1530 
1531 	if (size < ue->tlv_data_size)
1532 		return -ENOSPC;
1533 
1534 	if (copy_to_user(buf, ue->tlv_data, ue->tlv_data_size))
1535 		return -EFAULT;
1536 
1537 	return 0;
1538 }
1539 
1540 static int snd_ctl_elem_user_tlv(struct snd_kcontrol *kctl, int op_flag,
1541 				 unsigned int size, unsigned int __user *buf)
1542 {
1543 	if (op_flag == SNDRV_CTL_TLV_OP_WRITE)
1544 		return replace_user_tlv(kctl, buf, size);
1545 	else
1546 		return read_user_tlv(kctl, buf, size);
1547 }
1548 
1549 /* called in controls_rwsem write lock */
1550 static int snd_ctl_elem_init_enum_names(struct user_element *ue)
1551 {
1552 	char *names, *p;
1553 	size_t buf_len, name_len;
1554 	unsigned int i;
1555 	const uintptr_t user_ptrval = ue->info.value.enumerated.names_ptr;
1556 
1557 	lockdep_assert_held_write(&ue->card->controls_rwsem);
1558 
1559 	buf_len = ue->info.value.enumerated.names_length;
1560 	if (buf_len > 64 * 1024)
1561 		return -EINVAL;
1562 
1563 	if (check_user_elem_overflow(ue->card, buf_len))
1564 		return -ENOMEM;
1565 	names = vmemdup_user((const void __user *)user_ptrval, buf_len);
1566 	if (IS_ERR(names))
1567 		return PTR_ERR(names);
1568 
1569 	/* check that there are enough valid names */
1570 	p = names;
1571 	for (i = 0; i < ue->info.value.enumerated.items; ++i) {
1572 		name_len = strnlen(p, buf_len);
1573 		if (name_len == 0 || name_len >= 64 || name_len == buf_len) {
1574 			kvfree(names);
1575 			return -EINVAL;
1576 		}
1577 		p += name_len + 1;
1578 		buf_len -= name_len + 1;
1579 	}
1580 
1581 	ue->priv_data = names;
1582 	ue->info.value.enumerated.names_ptr = 0;
1583 	// increment the allocation size; decremented again at private_free.
1584 	ue->card->user_ctl_alloc_size += ue->info.value.enumerated.names_length;
1585 
1586 	return 0;
1587 }
1588 
1589 static size_t compute_user_elem_size(size_t size, unsigned int count)
1590 {
1591 	return sizeof(struct user_element) + size * count;
1592 }
1593 
1594 static void snd_ctl_elem_user_free(struct snd_kcontrol *kcontrol)
1595 {
1596 	struct user_element *ue = kcontrol->private_data;
1597 
1598 	// decrement the allocation size.
1599 	ue->card->user_ctl_alloc_size -= compute_user_elem_size(ue->elem_data_size, kcontrol->count);
1600 	ue->card->user_ctl_alloc_size -= ue->tlv_data_size;
1601 	if (ue->priv_data)
1602 		ue->card->user_ctl_alloc_size -= ue->info.value.enumerated.names_length;
1603 
1604 	kvfree(ue->tlv_data);
1605 	kvfree(ue->priv_data);
1606 	kfree(ue);
1607 }
1608 
1609 static int snd_ctl_elem_add(struct snd_ctl_file *file,
1610 			    struct snd_ctl_elem_info *info, int replace)
1611 {
1612 	struct snd_card *card = file->card;
1613 	struct snd_kcontrol *kctl;
1614 	unsigned int count;
1615 	unsigned int access;
1616 	long private_size;
1617 	size_t alloc_size;
1618 	struct user_element *ue;
1619 	unsigned int offset;
1620 	int err;
1621 
1622 	if (!*info->id.name)
1623 		return -EINVAL;
1624 	if (strnlen(info->id.name, sizeof(info->id.name)) >= sizeof(info->id.name))
1625 		return -EINVAL;
1626 
1627 	/* Delete a control to replace them if needed. */
1628 	if (replace) {
1629 		info->id.numid = 0;
1630 		err = snd_ctl_remove_user_ctl(file, &info->id);
1631 		if (err)
1632 			return err;
1633 	}
1634 
1635 	/* Check the number of elements for this userspace control. */
1636 	count = info->owner;
1637 	if (count == 0)
1638 		count = 1;
1639 
1640 	/* Arrange access permissions if needed. */
1641 	access = info->access;
1642 	if (access == 0)
1643 		access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
1644 	access &= (SNDRV_CTL_ELEM_ACCESS_READWRITE |
1645 		   SNDRV_CTL_ELEM_ACCESS_INACTIVE |
1646 		   SNDRV_CTL_ELEM_ACCESS_TLV_WRITE);
1647 
1648 	/* In initial state, nothing is available as TLV container. */
1649 	if (access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE)
1650 		access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
1651 	access |= SNDRV_CTL_ELEM_ACCESS_USER;
1652 
1653 	/*
1654 	 * Check information and calculate the size of data specific to
1655 	 * this userspace control.
1656 	 */
1657 	/* pass NULL to card for suppressing error messages */
1658 	err = snd_ctl_check_elem_info(NULL, info);
1659 	if (err < 0)
1660 		return err;
1661 	/* user-space control doesn't allow zero-size data */
1662 	if (info->count < 1)
1663 		return -EINVAL;
1664 	private_size = value_sizes[info->type] * info->count;
1665 	alloc_size = compute_user_elem_size(private_size, count);
1666 
1667 	guard(rwsem_write)(&card->controls_rwsem);
1668 	if (check_user_elem_overflow(card, alloc_size))
1669 		return -ENOMEM;
1670 
1671 	/*
1672 	 * Keep memory object for this userspace control. After passing this
1673 	 * code block, the instance should be freed by snd_ctl_free_one().
1674 	 *
1675 	 * Note that these elements in this control are locked.
1676 	 */
1677 	err = snd_ctl_new(&kctl, count, access, file);
1678 	if (err < 0)
1679 		return err;
1680 	memcpy(&kctl->id, &info->id, sizeof(kctl->id));
1681 	ue = kzalloc(alloc_size, GFP_KERNEL);
1682 	if (!ue) {
1683 		kfree(kctl);
1684 		return -ENOMEM;
1685 	}
1686 	kctl->private_data = ue;
1687 	kctl->private_free = snd_ctl_elem_user_free;
1688 
1689 	// increment the allocated size; decremented again at private_free.
1690 	card->user_ctl_alloc_size += alloc_size;
1691 
1692 	/* Set private data for this userspace control. */
1693 	ue->card = card;
1694 	ue->info = *info;
1695 	ue->info.access = 0;
1696 	ue->elem_data = (char *)ue + sizeof(*ue);
1697 	ue->elem_data_size = private_size;
1698 	if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
1699 		err = snd_ctl_elem_init_enum_names(ue);
1700 		if (err < 0) {
1701 			snd_ctl_free_one(kctl);
1702 			return err;
1703 		}
1704 	}
1705 
1706 	/* Set callback functions. */
1707 	if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
1708 		kctl->info = snd_ctl_elem_user_enum_info;
1709 	else
1710 		kctl->info = snd_ctl_elem_user_info;
1711 	if (access & SNDRV_CTL_ELEM_ACCESS_READ)
1712 		kctl->get = snd_ctl_elem_user_get;
1713 	if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
1714 		kctl->put = snd_ctl_elem_user_put;
1715 	if (access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE)
1716 		kctl->tlv.c = snd_ctl_elem_user_tlv;
1717 
1718 	/* This function manage to free the instance on failure. */
1719 	err = __snd_ctl_add_replace(card, kctl, CTL_ADD_EXCLUSIVE);
1720 	if (err < 0) {
1721 		snd_ctl_free_one(kctl);
1722 		return err;
1723 	}
1724 	offset = snd_ctl_get_ioff(kctl, &info->id);
1725 	snd_ctl_build_ioff(&info->id, kctl, offset);
1726 	/*
1727 	 * Here we cannot fill any field for the number of elements added by
1728 	 * this operation because there're no specific fields. The usage of
1729 	 * 'owner' field for this purpose may cause any bugs to userspace
1730 	 * applications because the field originally means PID of a process
1731 	 * which locks the element.
1732 	 */
1733 	return 0;
1734 }
1735 
1736 static int snd_ctl_elem_add_user(struct snd_ctl_file *file,
1737 				 struct snd_ctl_elem_info __user *_info, int replace)
1738 {
1739 	struct snd_ctl_elem_info info;
1740 	int err;
1741 
1742 	if (copy_from_user(&info, _info, sizeof(info)))
1743 		return -EFAULT;
1744 	err = snd_ctl_elem_add(file, &info, replace);
1745 	if (err < 0)
1746 		return err;
1747 	if (copy_to_user(_info, &info, sizeof(info))) {
1748 		snd_ctl_remove_user_ctl(file, &info.id);
1749 		return -EFAULT;
1750 	}
1751 
1752 	return 0;
1753 }
1754 
1755 static int snd_ctl_elem_remove(struct snd_ctl_file *file,
1756 			       struct snd_ctl_elem_id __user *_id)
1757 {
1758 	struct snd_ctl_elem_id id;
1759 
1760 	if (copy_from_user(&id, _id, sizeof(id)))
1761 		return -EFAULT;
1762 	return snd_ctl_remove_user_ctl(file, &id);
1763 }
1764 
1765 static int snd_ctl_subscribe_events(struct snd_ctl_file *file, int __user *ptr)
1766 {
1767 	int subscribe;
1768 	if (get_user(subscribe, ptr))
1769 		return -EFAULT;
1770 	if (subscribe < 0) {
1771 		subscribe = file->subscribed;
1772 		if (put_user(subscribe, ptr))
1773 			return -EFAULT;
1774 		return 0;
1775 	}
1776 	if (subscribe) {
1777 		file->subscribed = 1;
1778 		return 0;
1779 	} else if (file->subscribed) {
1780 		snd_ctl_empty_read_queue(file);
1781 		file->subscribed = 0;
1782 	}
1783 	return 0;
1784 }
1785 
1786 static int call_tlv_handler(struct snd_ctl_file *file, int op_flag,
1787 			    struct snd_kcontrol *kctl,
1788 			    struct snd_ctl_elem_id *id,
1789 			    unsigned int __user *buf, unsigned int size)
1790 {
1791 	static const struct {
1792 		int op;
1793 		int perm;
1794 	} pairs[] = {
1795 		{SNDRV_CTL_TLV_OP_READ,  SNDRV_CTL_ELEM_ACCESS_TLV_READ},
1796 		{SNDRV_CTL_TLV_OP_WRITE, SNDRV_CTL_ELEM_ACCESS_TLV_WRITE},
1797 		{SNDRV_CTL_TLV_OP_CMD,   SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND},
1798 	};
1799 	struct snd_kcontrol_volatile *vd = &kctl->vd[snd_ctl_get_ioff(kctl, id)];
1800 	int i, ret;
1801 
1802 	/* Check support of the request for this element. */
1803 	for (i = 0; i < ARRAY_SIZE(pairs); ++i) {
1804 		if (op_flag == pairs[i].op && (vd->access & pairs[i].perm))
1805 			break;
1806 	}
1807 	if (i == ARRAY_SIZE(pairs))
1808 		return -ENXIO;
1809 
1810 	if (kctl->tlv.c == NULL)
1811 		return -ENXIO;
1812 
1813 	/* Write and command operations are not allowed for locked element. */
1814 	if (op_flag != SNDRV_CTL_TLV_OP_READ &&
1815 	    vd->owner != NULL && vd->owner != file)
1816 		return -EPERM;
1817 
1818 	ret = snd_power_ref_and_wait(file->card);
1819 	if (!ret)
1820 		ret = kctl->tlv.c(kctl, op_flag, size, buf);
1821 	snd_power_unref(file->card);
1822 	return ret;
1823 }
1824 
1825 static int read_tlv_buf(struct snd_kcontrol *kctl, struct snd_ctl_elem_id *id,
1826 			unsigned int __user *buf, unsigned int size)
1827 {
1828 	struct snd_kcontrol_volatile *vd = &kctl->vd[snd_ctl_get_ioff(kctl, id)];
1829 	unsigned int len;
1830 
1831 	if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ))
1832 		return -ENXIO;
1833 
1834 	if (kctl->tlv.p == NULL)
1835 		return -ENXIO;
1836 
1837 	len = sizeof(unsigned int) * 2 + kctl->tlv.p[1];
1838 	if (size < len)
1839 		return -ENOMEM;
1840 
1841 	if (copy_to_user(buf, kctl->tlv.p, len))
1842 		return -EFAULT;
1843 
1844 	return 0;
1845 }
1846 
1847 static int snd_ctl_tlv_ioctl(struct snd_ctl_file *file,
1848 			     struct snd_ctl_tlv __user *buf,
1849                              int op_flag)
1850 {
1851 	struct snd_ctl_tlv header;
1852 	unsigned int __user *container;
1853 	unsigned int container_size;
1854 	struct snd_kcontrol *kctl;
1855 	struct snd_ctl_elem_id id;
1856 	struct snd_kcontrol_volatile *vd;
1857 
1858 	lockdep_assert_held(&file->card->controls_rwsem);
1859 
1860 	if (copy_from_user(&header, buf, sizeof(header)))
1861 		return -EFAULT;
1862 
1863 	/* In design of control core, numerical ID starts at 1. */
1864 	if (header.numid == 0)
1865 		return -EINVAL;
1866 
1867 	/* At least, container should include type and length fields.  */
1868 	if (header.length < sizeof(unsigned int) * 2)
1869 		return -EINVAL;
1870 	container_size = header.length;
1871 	container = buf->tlv;
1872 
1873 	kctl = snd_ctl_find_numid(file->card, header.numid);
1874 	if (kctl == NULL)
1875 		return -ENOENT;
1876 
1877 	/* Calculate index of the element in this set. */
1878 	id = kctl->id;
1879 	snd_ctl_build_ioff(&id, kctl, header.numid - id.numid);
1880 	vd = &kctl->vd[snd_ctl_get_ioff(kctl, &id)];
1881 
1882 	if (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
1883 		return call_tlv_handler(file, op_flag, kctl, &id, container,
1884 					container_size);
1885 	} else {
1886 		if (op_flag == SNDRV_CTL_TLV_OP_READ) {
1887 			return read_tlv_buf(kctl, &id, container,
1888 					    container_size);
1889 		}
1890 	}
1891 
1892 	/* Not supported. */
1893 	return -ENXIO;
1894 }
1895 
1896 static long snd_ctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1897 {
1898 	struct snd_ctl_file *ctl;
1899 	struct snd_card *card;
1900 	struct snd_kctl_ioctl *p;
1901 	void __user *argp = (void __user *)arg;
1902 	int __user *ip = argp;
1903 	int err;
1904 
1905 	ctl = file->private_data;
1906 	card = ctl->card;
1907 	if (snd_BUG_ON(!card))
1908 		return -ENXIO;
1909 	switch (cmd) {
1910 	case SNDRV_CTL_IOCTL_PVERSION:
1911 		return put_user(SNDRV_CTL_VERSION, ip) ? -EFAULT : 0;
1912 	case SNDRV_CTL_IOCTL_CARD_INFO:
1913 		return snd_ctl_card_info(card, ctl, cmd, argp);
1914 	case SNDRV_CTL_IOCTL_ELEM_LIST:
1915 		return snd_ctl_elem_list_user(card, argp);
1916 	case SNDRV_CTL_IOCTL_ELEM_INFO:
1917 		return snd_ctl_elem_info_user(ctl, argp);
1918 	case SNDRV_CTL_IOCTL_ELEM_READ:
1919 		return snd_ctl_elem_read_user(card, argp);
1920 	case SNDRV_CTL_IOCTL_ELEM_WRITE:
1921 		return snd_ctl_elem_write_user(ctl, argp);
1922 	case SNDRV_CTL_IOCTL_ELEM_LOCK:
1923 		return snd_ctl_elem_lock(ctl, argp);
1924 	case SNDRV_CTL_IOCTL_ELEM_UNLOCK:
1925 		return snd_ctl_elem_unlock(ctl, argp);
1926 	case SNDRV_CTL_IOCTL_ELEM_ADD:
1927 		return snd_ctl_elem_add_user(ctl, argp, 0);
1928 	case SNDRV_CTL_IOCTL_ELEM_REPLACE:
1929 		return snd_ctl_elem_add_user(ctl, argp, 1);
1930 	case SNDRV_CTL_IOCTL_ELEM_REMOVE:
1931 		return snd_ctl_elem_remove(ctl, argp);
1932 	case SNDRV_CTL_IOCTL_SUBSCRIBE_EVENTS:
1933 		return snd_ctl_subscribe_events(ctl, ip);
1934 	case SNDRV_CTL_IOCTL_TLV_READ:
1935 		scoped_guard(rwsem_read, &ctl->card->controls_rwsem)
1936 			err = snd_ctl_tlv_ioctl(ctl, argp, SNDRV_CTL_TLV_OP_READ);
1937 		return err;
1938 	case SNDRV_CTL_IOCTL_TLV_WRITE:
1939 		scoped_guard(rwsem_write, &ctl->card->controls_rwsem)
1940 			err = snd_ctl_tlv_ioctl(ctl, argp, SNDRV_CTL_TLV_OP_WRITE);
1941 		return err;
1942 	case SNDRV_CTL_IOCTL_TLV_COMMAND:
1943 		scoped_guard(rwsem_write, &ctl->card->controls_rwsem)
1944 			err = snd_ctl_tlv_ioctl(ctl, argp, SNDRV_CTL_TLV_OP_CMD);
1945 		return err;
1946 	case SNDRV_CTL_IOCTL_POWER:
1947 		return -ENOPROTOOPT;
1948 	case SNDRV_CTL_IOCTL_POWER_STATE:
1949 		return put_user(SNDRV_CTL_POWER_D0, ip) ? -EFAULT : 0;
1950 	}
1951 
1952 	guard(rwsem_read)(&snd_ioctl_rwsem);
1953 	list_for_each_entry(p, &snd_control_ioctls, list) {
1954 		err = p->fioctl(card, ctl, cmd, arg);
1955 		if (err != -ENOIOCTLCMD)
1956 			return err;
1957 	}
1958 	dev_dbg(card->dev, "unknown ioctl = 0x%x\n", cmd);
1959 	return -ENOTTY;
1960 }
1961 
1962 static ssize_t snd_ctl_read(struct file *file, char __user *buffer,
1963 			    size_t count, loff_t * offset)
1964 {
1965 	struct snd_ctl_file *ctl;
1966 	int err = 0;
1967 	ssize_t result = 0;
1968 
1969 	ctl = file->private_data;
1970 	if (snd_BUG_ON(!ctl || !ctl->card))
1971 		return -ENXIO;
1972 	if (!ctl->subscribed)
1973 		return -EBADFD;
1974 	if (count < sizeof(struct snd_ctl_event))
1975 		return -EINVAL;
1976 	spin_lock_irq(&ctl->read_lock);
1977 	while (count >= sizeof(struct snd_ctl_event)) {
1978 		struct snd_ctl_event ev;
1979 		struct snd_kctl_event *kev;
1980 		while (list_empty(&ctl->events)) {
1981 			wait_queue_entry_t wait;
1982 			if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
1983 				err = -EAGAIN;
1984 				goto __end_lock;
1985 			}
1986 			init_waitqueue_entry(&wait, current);
1987 			add_wait_queue(&ctl->change_sleep, &wait);
1988 			set_current_state(TASK_INTERRUPTIBLE);
1989 			spin_unlock_irq(&ctl->read_lock);
1990 			schedule();
1991 			remove_wait_queue(&ctl->change_sleep, &wait);
1992 			if (ctl->card->shutdown)
1993 				return -ENODEV;
1994 			if (signal_pending(current))
1995 				return -ERESTARTSYS;
1996 			spin_lock_irq(&ctl->read_lock);
1997 		}
1998 		kev = snd_kctl_event(ctl->events.next);
1999 		ev.type = SNDRV_CTL_EVENT_ELEM;
2000 		ev.data.elem.mask = kev->mask;
2001 		ev.data.elem.id = kev->id;
2002 		list_del(&kev->list);
2003 		spin_unlock_irq(&ctl->read_lock);
2004 		kfree(kev);
2005 		if (copy_to_user(buffer, &ev, sizeof(struct snd_ctl_event))) {
2006 			err = -EFAULT;
2007 			goto __end;
2008 		}
2009 		spin_lock_irq(&ctl->read_lock);
2010 		buffer += sizeof(struct snd_ctl_event);
2011 		count -= sizeof(struct snd_ctl_event);
2012 		result += sizeof(struct snd_ctl_event);
2013 	}
2014       __end_lock:
2015 	spin_unlock_irq(&ctl->read_lock);
2016       __end:
2017       	return result > 0 ? result : err;
2018 }
2019 
2020 static __poll_t snd_ctl_poll(struct file *file, poll_table * wait)
2021 {
2022 	__poll_t mask;
2023 	struct snd_ctl_file *ctl;
2024 
2025 	ctl = file->private_data;
2026 	if (!ctl->subscribed)
2027 		return 0;
2028 	poll_wait(file, &ctl->change_sleep, wait);
2029 
2030 	mask = 0;
2031 	if (!list_empty(&ctl->events))
2032 		mask |= EPOLLIN | EPOLLRDNORM;
2033 
2034 	return mask;
2035 }
2036 
2037 /*
2038  * register the device-specific control-ioctls.
2039  * called from each device manager like pcm.c, hwdep.c, etc.
2040  */
2041 static int _snd_ctl_register_ioctl(snd_kctl_ioctl_func_t fcn, struct list_head *lists)
2042 {
2043 	struct snd_kctl_ioctl *pn;
2044 
2045 	pn = kzalloc(sizeof(struct snd_kctl_ioctl), GFP_KERNEL);
2046 	if (pn == NULL)
2047 		return -ENOMEM;
2048 	pn->fioctl = fcn;
2049 	guard(rwsem_write)(&snd_ioctl_rwsem);
2050 	list_add_tail(&pn->list, lists);
2051 	return 0;
2052 }
2053 
2054 /**
2055  * snd_ctl_register_ioctl - register the device-specific control-ioctls
2056  * @fcn: ioctl callback function
2057  *
2058  * called from each device manager like pcm.c, hwdep.c, etc.
2059  *
2060  * Return: zero if successful, or a negative error code
2061  */
2062 int snd_ctl_register_ioctl(snd_kctl_ioctl_func_t fcn)
2063 {
2064 	return _snd_ctl_register_ioctl(fcn, &snd_control_ioctls);
2065 }
2066 EXPORT_SYMBOL(snd_ctl_register_ioctl);
2067 
2068 #ifdef CONFIG_COMPAT
2069 /**
2070  * snd_ctl_register_ioctl_compat - register the device-specific 32bit compat
2071  * control-ioctls
2072  * @fcn: ioctl callback function
2073  *
2074  * Return: zero if successful, or a negative error code
2075  */
2076 int snd_ctl_register_ioctl_compat(snd_kctl_ioctl_func_t fcn)
2077 {
2078 	return _snd_ctl_register_ioctl(fcn, &snd_control_compat_ioctls);
2079 }
2080 EXPORT_SYMBOL(snd_ctl_register_ioctl_compat);
2081 #endif
2082 
2083 /*
2084  * de-register the device-specific control-ioctls.
2085  */
2086 static int _snd_ctl_unregister_ioctl(snd_kctl_ioctl_func_t fcn,
2087 				     struct list_head *lists)
2088 {
2089 	struct snd_kctl_ioctl *p;
2090 
2091 	if (snd_BUG_ON(!fcn))
2092 		return -EINVAL;
2093 	guard(rwsem_write)(&snd_ioctl_rwsem);
2094 	list_for_each_entry(p, lists, list) {
2095 		if (p->fioctl == fcn) {
2096 			list_del(&p->list);
2097 			kfree(p);
2098 			return 0;
2099 		}
2100 	}
2101 	snd_BUG();
2102 	return -EINVAL;
2103 }
2104 
2105 /**
2106  * snd_ctl_unregister_ioctl - de-register the device-specific control-ioctls
2107  * @fcn: ioctl callback function to unregister
2108  *
2109  * Return: zero if successful, or a negative error code
2110  */
2111 int snd_ctl_unregister_ioctl(snd_kctl_ioctl_func_t fcn)
2112 {
2113 	return _snd_ctl_unregister_ioctl(fcn, &snd_control_ioctls);
2114 }
2115 EXPORT_SYMBOL(snd_ctl_unregister_ioctl);
2116 
2117 #ifdef CONFIG_COMPAT
2118 /**
2119  * snd_ctl_unregister_ioctl_compat - de-register the device-specific compat
2120  * 32bit control-ioctls
2121  * @fcn: ioctl callback function to unregister
2122  *
2123  * Return: zero if successful, or a negative error code
2124  */
2125 int snd_ctl_unregister_ioctl_compat(snd_kctl_ioctl_func_t fcn)
2126 {
2127 	return _snd_ctl_unregister_ioctl(fcn, &snd_control_compat_ioctls);
2128 }
2129 EXPORT_SYMBOL(snd_ctl_unregister_ioctl_compat);
2130 #endif
2131 
2132 static int snd_ctl_fasync(int fd, struct file * file, int on)
2133 {
2134 	struct snd_ctl_file *ctl;
2135 
2136 	ctl = file->private_data;
2137 	return snd_fasync_helper(fd, file, on, &ctl->fasync);
2138 }
2139 
2140 /* return the preferred subdevice number if already assigned;
2141  * otherwise return -1
2142  */
2143 int snd_ctl_get_preferred_subdevice(struct snd_card *card, int type)
2144 {
2145 	struct snd_ctl_file *kctl;
2146 	int subdevice = -1;
2147 
2148 	guard(read_lock_irqsave)(&card->controls_rwlock);
2149 	list_for_each_entry(kctl, &card->ctl_files, list) {
2150 		if (kctl->pid == task_pid(current)) {
2151 			subdevice = kctl->preferred_subdevice[type];
2152 			if (subdevice != -1)
2153 				break;
2154 		}
2155 	}
2156 	return subdevice;
2157 }
2158 EXPORT_SYMBOL_GPL(snd_ctl_get_preferred_subdevice);
2159 
2160 /*
2161  * ioctl32 compat
2162  */
2163 #ifdef CONFIG_COMPAT
2164 #include "control_compat.c"
2165 #else
2166 #define snd_ctl_ioctl_compat	NULL
2167 #endif
2168 
2169 /*
2170  * control layers (audio LED etc.)
2171  */
2172 
2173 /**
2174  * snd_ctl_request_layer - request to use the layer
2175  * @module_name: Name of the kernel module (NULL == build-in)
2176  *
2177  * Return: zero if successful, or an error code when the module cannot be loaded
2178  */
2179 int snd_ctl_request_layer(const char *module_name)
2180 {
2181 	struct snd_ctl_layer_ops *lops;
2182 
2183 	if (module_name == NULL)
2184 		return 0;
2185 	scoped_guard(rwsem_read, &snd_ctl_layer_rwsem) {
2186 		for (lops = snd_ctl_layer; lops; lops = lops->next)
2187 			if (strcmp(lops->module_name, module_name) == 0)
2188 				return 0;
2189 	}
2190 	return request_module(module_name);
2191 }
2192 EXPORT_SYMBOL_GPL(snd_ctl_request_layer);
2193 
2194 /**
2195  * snd_ctl_register_layer - register new control layer
2196  * @lops: operation structure
2197  *
2198  * The new layer can track all control elements and do additional
2199  * operations on top (like audio LED handling).
2200  */
2201 void snd_ctl_register_layer(struct snd_ctl_layer_ops *lops)
2202 {
2203 	struct snd_card *card;
2204 	int card_number;
2205 
2206 	scoped_guard(rwsem_write, &snd_ctl_layer_rwsem) {
2207 		lops->next = snd_ctl_layer;
2208 		snd_ctl_layer = lops;
2209 	}
2210 	for (card_number = 0; card_number < SNDRV_CARDS; card_number++) {
2211 		card = snd_card_ref(card_number);
2212 		if (card) {
2213 			scoped_guard(rwsem_read, &card->controls_rwsem)
2214 				lops->lregister(card);
2215 			snd_card_unref(card);
2216 		}
2217 	}
2218 }
2219 EXPORT_SYMBOL_GPL(snd_ctl_register_layer);
2220 
2221 /**
2222  * snd_ctl_disconnect_layer - disconnect control layer
2223  * @lops: operation structure
2224  *
2225  * It is expected that the information about tracked cards
2226  * is freed before this call (the disconnect callback is
2227  * not called here).
2228  */
2229 void snd_ctl_disconnect_layer(struct snd_ctl_layer_ops *lops)
2230 {
2231 	struct snd_ctl_layer_ops *lops2, *prev_lops2;
2232 
2233 	guard(rwsem_write)(&snd_ctl_layer_rwsem);
2234 	for (lops2 = snd_ctl_layer, prev_lops2 = NULL; lops2; lops2 = lops2->next) {
2235 		if (lops2 == lops) {
2236 			if (!prev_lops2)
2237 				snd_ctl_layer = lops->next;
2238 			else
2239 				prev_lops2->next = lops->next;
2240 			break;
2241 		}
2242 		prev_lops2 = lops2;
2243 	}
2244 }
2245 EXPORT_SYMBOL_GPL(snd_ctl_disconnect_layer);
2246 
2247 /*
2248  *  INIT PART
2249  */
2250 
2251 static const struct file_operations snd_ctl_f_ops =
2252 {
2253 	.owner =	THIS_MODULE,
2254 	.read =		snd_ctl_read,
2255 	.open =		snd_ctl_open,
2256 	.release =	snd_ctl_release,
2257 	.llseek =	no_llseek,
2258 	.poll =		snd_ctl_poll,
2259 	.unlocked_ioctl =	snd_ctl_ioctl,
2260 	.compat_ioctl =	snd_ctl_ioctl_compat,
2261 	.fasync =	snd_ctl_fasync,
2262 };
2263 
2264 /* call lops under rwsems; called from snd_ctl_dev_*() below() */
2265 #define call_snd_ctl_lops(_card, _op)				    \
2266 	do {							    \
2267 		struct snd_ctl_layer_ops *lops;			    \
2268 		guard(rwsem_read)(&(_card)->controls_rwsem);	    \
2269 		guard(rwsem_read)(&snd_ctl_layer_rwsem);	    \
2270 		for (lops = snd_ctl_layer; lops; lops = lops->next) \
2271 			lops->_op(_card);			    \
2272 	} while (0)
2273 
2274 /*
2275  * registration of the control device
2276  */
2277 static int snd_ctl_dev_register(struct snd_device *device)
2278 {
2279 	struct snd_card *card = device->device_data;
2280 	int err;
2281 
2282 	err = snd_register_device(SNDRV_DEVICE_TYPE_CONTROL, card, -1,
2283 				  &snd_ctl_f_ops, card, card->ctl_dev);
2284 	if (err < 0)
2285 		return err;
2286 	call_snd_ctl_lops(card, lregister);
2287 	return 0;
2288 }
2289 
2290 /*
2291  * disconnection of the control device
2292  */
2293 static int snd_ctl_dev_disconnect(struct snd_device *device)
2294 {
2295 	struct snd_card *card = device->device_data;
2296 	struct snd_ctl_file *ctl;
2297 
2298 	scoped_guard(read_lock_irqsave, &card->controls_rwlock) {
2299 		list_for_each_entry(ctl, &card->ctl_files, list) {
2300 			wake_up(&ctl->change_sleep);
2301 			snd_kill_fasync(ctl->fasync, SIGIO, POLL_ERR);
2302 		}
2303 	}
2304 
2305 	call_snd_ctl_lops(card, ldisconnect);
2306 	return snd_unregister_device(card->ctl_dev);
2307 }
2308 
2309 /*
2310  * free all controls
2311  */
2312 static int snd_ctl_dev_free(struct snd_device *device)
2313 {
2314 	struct snd_card *card = device->device_data;
2315 	struct snd_kcontrol *control;
2316 
2317 	scoped_guard(rwsem_write, &card->controls_rwsem) {
2318 		while (!list_empty(&card->controls)) {
2319 			control = snd_kcontrol(card->controls.next);
2320 			__snd_ctl_remove(card, control, false);
2321 		}
2322 
2323 #ifdef CONFIG_SND_CTL_FAST_LOOKUP
2324 		xa_destroy(&card->ctl_numids);
2325 		xa_destroy(&card->ctl_hash);
2326 #endif
2327 	}
2328 	put_device(card->ctl_dev);
2329 	return 0;
2330 }
2331 
2332 /*
2333  * create control core:
2334  * called from init.c
2335  */
2336 int snd_ctl_create(struct snd_card *card)
2337 {
2338 	static const struct snd_device_ops ops = {
2339 		.dev_free = snd_ctl_dev_free,
2340 		.dev_register =	snd_ctl_dev_register,
2341 		.dev_disconnect = snd_ctl_dev_disconnect,
2342 	};
2343 	int err;
2344 
2345 	if (snd_BUG_ON(!card))
2346 		return -ENXIO;
2347 	if (snd_BUG_ON(card->number < 0 || card->number >= SNDRV_CARDS))
2348 		return -ENXIO;
2349 
2350 	err = snd_device_alloc(&card->ctl_dev, card);
2351 	if (err < 0)
2352 		return err;
2353 	dev_set_name(card->ctl_dev, "controlC%d", card->number);
2354 
2355 	err = snd_device_new(card, SNDRV_DEV_CONTROL, card, &ops);
2356 	if (err < 0)
2357 		put_device(card->ctl_dev);
2358 	return err;
2359 }
2360 
2361 /*
2362  * Frequently used control callbacks/helpers
2363  */
2364 
2365 /**
2366  * snd_ctl_boolean_mono_info - Helper function for a standard boolean info
2367  * callback with a mono channel
2368  * @kcontrol: the kcontrol instance
2369  * @uinfo: info to store
2370  *
2371  * This is a function that can be used as info callback for a standard
2372  * boolean control with a single mono channel.
2373  *
2374  * Return: Zero (always successful)
2375  */
2376 int snd_ctl_boolean_mono_info(struct snd_kcontrol *kcontrol,
2377 			      struct snd_ctl_elem_info *uinfo)
2378 {
2379 	uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2380 	uinfo->count = 1;
2381 	uinfo->value.integer.min = 0;
2382 	uinfo->value.integer.max = 1;
2383 	return 0;
2384 }
2385 EXPORT_SYMBOL(snd_ctl_boolean_mono_info);
2386 
2387 /**
2388  * snd_ctl_boolean_stereo_info - Helper function for a standard boolean info
2389  * callback with stereo two channels
2390  * @kcontrol: the kcontrol instance
2391  * @uinfo: info to store
2392  *
2393  * This is a function that can be used as info callback for a standard
2394  * boolean control with stereo two channels.
2395  *
2396  * Return: Zero (always successful)
2397  */
2398 int snd_ctl_boolean_stereo_info(struct snd_kcontrol *kcontrol,
2399 				struct snd_ctl_elem_info *uinfo)
2400 {
2401 	uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2402 	uinfo->count = 2;
2403 	uinfo->value.integer.min = 0;
2404 	uinfo->value.integer.max = 1;
2405 	return 0;
2406 }
2407 EXPORT_SYMBOL(snd_ctl_boolean_stereo_info);
2408 
2409 /**
2410  * snd_ctl_enum_info - fills the info structure for an enumerated control
2411  * @info: the structure to be filled
2412  * @channels: the number of the control's channels; often one
2413  * @items: the number of control values; also the size of @names
2414  * @names: an array containing the names of all control values
2415  *
2416  * Sets all required fields in @info to their appropriate values.
2417  * If the control's accessibility is not the default (readable and writable),
2418  * the caller has to fill @info->access.
2419  *
2420  * Return: Zero (always successful)
2421  */
2422 int snd_ctl_enum_info(struct snd_ctl_elem_info *info, unsigned int channels,
2423 		      unsigned int items, const char *const names[])
2424 {
2425 	info->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
2426 	info->count = channels;
2427 	info->value.enumerated.items = items;
2428 	if (!items)
2429 		return 0;
2430 	if (info->value.enumerated.item >= items)
2431 		info->value.enumerated.item = items - 1;
2432 	WARN(strlen(names[info->value.enumerated.item]) >= sizeof(info->value.enumerated.name),
2433 	     "ALSA: too long item name '%s'\n",
2434 	     names[info->value.enumerated.item]);
2435 	strscpy(info->value.enumerated.name,
2436 		names[info->value.enumerated.item],
2437 		sizeof(info->value.enumerated.name));
2438 	return 0;
2439 }
2440 EXPORT_SYMBOL(snd_ctl_enum_info);
2441