xref: /linux/sound/core/init.c (revision f0780cfa6acf72576464dc3b40431db389f46ee8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Initialization routines
4  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
5  */
6 
7 #include <linux/init.h>
8 #include <linux/sched.h>
9 #include <linux/module.h>
10 #include <linux/device.h>
11 #include <linux/file.h>
12 #include <linux/slab.h>
13 #include <linux/time.h>
14 #include <linux/ctype.h>
15 #include <linux/pm.h>
16 #include <linux/debugfs.h>
17 #include <linux/completion.h>
18 #include <linux/interrupt.h>
19 
20 #include <sound/core.h>
21 #include <sound/control.h>
22 #include <sound/info.h>
23 
24 /* monitor files for graceful shutdown (hotplug) */
25 struct snd_monitor_file {
26 	struct file *file;
27 	const struct file_operations *disconnected_f_op;
28 	struct list_head shutdown_list;	/* still need to shutdown */
29 	struct list_head list;	/* link of monitor files */
30 };
31 
32 static DEFINE_SPINLOCK(shutdown_lock);
33 static LIST_HEAD(shutdown_files);
34 
35 static const struct file_operations snd_shutdown_f_ops;
36 
37 /* locked for registering/using */
38 static DECLARE_BITMAP(snd_cards_lock, SNDRV_CARDS);
39 static struct snd_card *snd_cards[SNDRV_CARDS];
40 
41 static DEFINE_MUTEX(snd_card_mutex);
42 
43 static char *slots[SNDRV_CARDS];
44 module_param_array(slots, charp, NULL, 0444);
45 MODULE_PARM_DESC(slots, "Module names assigned to the slots.");
46 
47 /* return non-zero if the given index is reserved for the given
48  * module via slots option
49  */
50 static int module_slot_match(struct module *module, int idx)
51 {
52 	int match = 1;
53 #ifdef CONFIG_MODULES
54 	const char *s1, *s2;
55 
56 	if (!module || !*module->name || !slots[idx])
57 		return 0;
58 
59 	s1 = module->name;
60 	s2 = slots[idx];
61 	if (*s2 == '!') {
62 		match = 0; /* negative match */
63 		s2++;
64 	}
65 	/* compare module name strings
66 	 * hyphens are handled as equivalent with underscore
67 	 */
68 	for (;;) {
69 		char c1 = *s1++;
70 		char c2 = *s2++;
71 		if (c1 == '-')
72 			c1 = '_';
73 		if (c2 == '-')
74 			c2 = '_';
75 		if (c1 != c2)
76 			return !match;
77 		if (!c1)
78 			break;
79 	}
80 #endif /* CONFIG_MODULES */
81 	return match;
82 }
83 
84 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
85 static DEFINE_MUTEX(mixer_oss_notify_mutex);
86 static int (*mixer_oss_notify_callback)(struct snd_card *card, int cmd);
87 
88 void snd_mixer_oss_notify(struct snd_card *card, int cmd)
89 {
90 	guard(mutex)(&mixer_oss_notify_mutex);
91 	if (mixer_oss_notify_callback)
92 		mixer_oss_notify_callback(card, cmd);
93 }
94 EXPORT_SYMBOL(snd_mixer_oss_notify);
95 
96 void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *, int))
97 {
98 	/* Wait for callbacks, including a final module_put(), to return. */
99 	guard(mutex)(&mixer_oss_notify_mutex);
100 	mixer_oss_notify_callback = callback;
101 }
102 EXPORT_SYMBOL(snd_mixer_oss_set_notify);
103 #endif
104 
105 static int check_empty_slot(struct module *module, int slot)
106 {
107 	return !slots[slot] || !*slots[slot];
108 }
109 
110 /* return an empty slot number (>= 0) found in the given bitmask @mask.
111  * @mask == -1 == 0xffffffff means: take any free slot up to 32
112  * when no slot is available, return the original @mask as is.
113  */
114 static int get_slot_from_bitmask(int mask, int (*check)(struct module *, int),
115 				 struct module *module)
116 {
117 	int slot;
118 
119 	for (slot = 0; slot < SNDRV_CARDS; slot++) {
120 		if (slot < 32 && !(mask & (1U << slot)))
121 			continue;
122 		if (!test_bit(slot, snd_cards_lock)) {
123 			if (check(module, slot))
124 				return slot; /* found */
125 		}
126 	}
127 	return mask; /* unchanged */
128 }
129 
130 /* the default release callback set in snd_device_alloc() */
131 static void default_release_alloc(struct device *dev)
132 {
133 	kfree(dev);
134 }
135 
136 /**
137  * snd_device_alloc - Allocate and initialize struct device for sound devices
138  * @dev_p: pointer to store the allocated device
139  * @card: card to assign, optional
140  *
141  * For releasing the allocated device, call put_device().
142  */
143 int snd_device_alloc(struct device **dev_p, struct snd_card *card)
144 {
145 	struct device *dev;
146 
147 	*dev_p = NULL;
148 	dev = kzalloc_obj(*dev);
149 	if (!dev)
150 		return -ENOMEM;
151 	device_initialize(dev);
152 	if (card)
153 		dev->parent = &card->card_dev;
154 	dev->class = &sound_class;
155 	dev->release = default_release_alloc;
156 	*dev_p = dev;
157 	return 0;
158 }
159 EXPORT_SYMBOL_GPL(snd_device_alloc);
160 
161 static int snd_card_init(struct snd_card *card, struct device *parent,
162 			 int idx, const char *xid, struct module *module,
163 			 size_t extra_size);
164 static int snd_card_do_free(struct snd_card *card);
165 static const struct attribute_group card_dev_attr_group;
166 
167 static void release_card_device(struct device *dev)
168 {
169 	snd_card_do_free(dev_to_snd_card(dev));
170 }
171 
172 /**
173  *  snd_card_new - create and initialize a soundcard structure
174  *  @parent: the parent device object
175  *  @idx: card index (address) [0 ... (SNDRV_CARDS-1)]
176  *  @xid: card identification (ASCII string)
177  *  @module: top level module for locking
178  *  @extra_size: allocate this extra size after the main soundcard structure
179  *  @card_ret: the pointer to store the created card instance
180  *
181  *  The function allocates snd_card instance via kzalloc with the given
182  *  space for the driver to use freely.  The allocated struct is stored
183  *  in the given card_ret pointer.
184  *
185  *  Return: Zero if successful or a negative error code.
186  */
187 int snd_card_new(struct device *parent, int idx, const char *xid,
188 		    struct module *module, int extra_size,
189 		    struct snd_card **card_ret)
190 {
191 	struct snd_card *card;
192 	int err;
193 
194 	if (snd_BUG_ON(!card_ret))
195 		return -EINVAL;
196 	*card_ret = NULL;
197 
198 	if (extra_size < 0)
199 		extra_size = 0;
200 	card = kzalloc_flex(*card, private_data_area, extra_size);
201 	if (!card)
202 		return -ENOMEM;
203 
204 	err = snd_card_init(card, parent, idx, xid, module, extra_size);
205 	if (err < 0)
206 		return err; /* card is freed by error handler */
207 
208 	*card_ret = card;
209 	return 0;
210 }
211 EXPORT_SYMBOL(snd_card_new);
212 
213 static void __snd_card_release(struct device *dev, void *data)
214 {
215 	snd_card_free(data);
216 }
217 
218 /**
219  * snd_devm_card_new - managed snd_card object creation
220  * @parent: the parent device object
221  * @idx: card index (address) [0 ... (SNDRV_CARDS-1)]
222  * @xid: card identification (ASCII string)
223  * @module: top level module for locking
224  * @extra_size: allocate this extra size after the main soundcard structure
225  * @card_ret: the pointer to store the created card instance
226  *
227  * This function works like snd_card_new() but manages the allocated resource
228  * via devres, i.e. you don't need to free explicitly.
229  *
230  * When a snd_card object is created with this function and registered via
231  * snd_card_register(), the very first devres action to call snd_card_free()
232  * is added automatically.  In that way, the resource disconnection is assured
233  * at first, then released in the expected order.
234  *
235  * Caveat: if an error happens at the probe before snd_card_register() is
236  * called and there have been other devres resources that are referred at the
237  * card-level destructor call, you'd still need to free the card manually;
238  * otherwise it may lead to UAF due to devres call orders.  Instead of a manual
239  * snd_card_free() call, you can use the automatic clean-up for the card
240  * pointer via __free(snd_card_free), too.  In this case, don't forget to do
241  * NULL-clear the card pointer before the successful return!
242  *
243  * Return: zero if successful, or a negative error code
244  */
245 int snd_devm_card_new(struct device *parent, int idx, const char *xid,
246 		      struct module *module, size_t extra_size,
247 		      struct snd_card **card_ret)
248 {
249 	struct snd_card *card;
250 	int err;
251 
252 	*card_ret = NULL;
253 	card = devres_alloc(__snd_card_release,
254 			    struct_size(card, private_data_area, extra_size),
255 			    GFP_KERNEL);
256 	if (!card)
257 		return -ENOMEM;
258 	card->managed = true;
259 	err = snd_card_init(card, parent, idx, xid, module, extra_size);
260 	if (err < 0) {
261 		devres_free(card); /* in managed mode, we need to free manually */
262 		return err;
263 	}
264 
265 	devres_add(parent, card);
266 	*card_ret = card;
267 	return 0;
268 }
269 EXPORT_SYMBOL_GPL(snd_devm_card_new);
270 
271 static int snd_card_init(struct snd_card *card, struct device *parent,
272 			 int idx, const char *xid, struct module *module,
273 			 size_t extra_size)
274 {
275 	int err;
276 
277 	if (extra_size > 0)
278 		card->private_data = card->private_data_area;
279 	if (xid)
280 		strscpy(card->id, xid, sizeof(card->id));
281 	err = 0;
282 	scoped_guard(mutex, &snd_card_mutex) {
283 		if (idx < 0) /* first check the matching module-name slot */
284 			idx = get_slot_from_bitmask(idx, module_slot_match, module);
285 		if (idx < 0) /* if not matched, assign an empty slot */
286 			idx = get_slot_from_bitmask(idx, check_empty_slot, module);
287 		if (idx < 0)
288 			err = -ENODEV;
289 		else if (idx < snd_ecards_limit) {
290 			if (test_bit(idx, snd_cards_lock))
291 				err = -EBUSY;	/* invalid */
292 		} else if (idx >= SNDRV_CARDS)
293 			err = -ENODEV;
294 		if (!err) {
295 			set_bit(idx, snd_cards_lock);		/* lock it */
296 			if (idx >= snd_ecards_limit)
297 				snd_ecards_limit = idx + 1; /* increase the limit */
298 		}
299 	}
300 	if (err < 0) {
301 		dev_err(parent, "cannot find the slot for index %d (range 0-%i), error: %d\n",
302 			idx, snd_ecards_limit - 1, err);
303 		if (!card->managed)
304 			kfree(card); /* manually free here, as no destructor called */
305 		return err;
306 	}
307 	card->dev = get_device(parent);
308 	card->number = idx;
309 	WARN_ON(IS_MODULE(CONFIG_SND) && !module);
310 	card->module = module;
311 	INIT_LIST_HEAD(&card->devices);
312 	init_rwsem(&card->controls_rwsem);
313 	rwlock_init(&card->controls_rwlock);
314 	INIT_LIST_HEAD(&card->controls);
315 	INIT_LIST_HEAD(&card->ctl_files);
316 #ifdef CONFIG_SND_CTL_FAST_LOOKUP
317 	xa_init(&card->ctl_numids);
318 	xa_init(&card->ctl_hash);
319 #endif
320 	spin_lock_init(&card->files_lock);
321 	INIT_LIST_HEAD(&card->files_list);
322 	mutex_init(&card->memory_mutex);
323 #ifdef CONFIG_PM
324 	init_waitqueue_head(&card->power_sleep);
325 	snd_refcount_init(&card->power_ref);
326 #endif
327 	init_waitqueue_head(&card->remove_sleep);
328 	card->sync_irq = -1;
329 
330 	device_initialize(&card->card_dev);
331 	card->card_dev.parent = parent;
332 	card->card_dev.class = &sound_class;
333 	card->card_dev.release = release_card_device;
334 	card->card_dev.groups = card->dev_groups;
335 	card->dev_groups[0] = &card_dev_attr_group;
336 	err = kobject_set_name(&card->card_dev.kobj, "card%d", idx);
337 	if (err < 0)
338 		goto __error;
339 
340 	snprintf(card->irq_descr, sizeof(card->irq_descr), "%s:%s",
341 		 dev_driver_string(card->dev), dev_name(&card->card_dev));
342 
343 	/* the control interface cannot be accessed from the user space until */
344 	/* snd_cards_bitmask and snd_cards are set with snd_card_register */
345 	err = snd_ctl_create(card);
346 	if (err < 0) {
347 		dev_err(parent, "unable to register control minors\n");
348 		goto __error;
349 	}
350 	err = snd_info_card_create(card);
351 	if (err < 0) {
352 		dev_err(parent, "unable to create card info\n");
353 		goto __error;
354 	}
355 
356 #ifdef CONFIG_SND_DEBUG
357 	card->debugfs_root = debugfs_create_dir(dev_name(&card->card_dev),
358 						sound_debugfs_root);
359 #endif
360 #ifdef CONFIG_SND_CTL_DEBUG
361 	card->value_buf = kmalloc_obj(*card->value_buf);
362 	if (!card->value_buf) {
363 		err = -ENOMEM;
364 		goto __error;
365 	}
366 #endif
367 	return 0;
368 
369       __error:
370 	snd_card_free(card);
371 	return err;
372 }
373 
374 /**
375  * snd_card_ref - Get the card object from the index
376  * @idx: the card index
377  *
378  * Returns a card object corresponding to the given index or NULL if not found.
379  * Release the object via snd_card_unref().
380  *
381  * Return: a card object or NULL
382  */
383 struct snd_card *snd_card_ref(int idx)
384 {
385 	struct snd_card *card;
386 
387 	guard(mutex)(&snd_card_mutex);
388 	card = snd_cards[idx];
389 	if (card)
390 		get_device(&card->card_dev);
391 	return card;
392 }
393 EXPORT_SYMBOL_GPL(snd_card_ref);
394 
395 /* return non-zero if a card is already locked */
396 int snd_card_locked(int card)
397 {
398 	guard(mutex)(&snd_card_mutex);
399 	return test_bit(card, snd_cards_lock);
400 }
401 
402 static loff_t snd_disconnect_llseek(struct file *file, loff_t offset, int orig)
403 {
404 	return -ENODEV;
405 }
406 
407 static ssize_t snd_disconnect_read(struct file *file, char __user *buf,
408 				   size_t count, loff_t *offset)
409 {
410 	return -ENODEV;
411 }
412 
413 static ssize_t snd_disconnect_write(struct file *file, const char __user *buf,
414 				    size_t count, loff_t *offset)
415 {
416 	return -ENODEV;
417 }
418 
419 static int snd_disconnect_release(struct inode *inode, struct file *file)
420 {
421 	struct snd_monitor_file *df = NULL, *_df;
422 
423 	scoped_guard(spinlock, &shutdown_lock) {
424 		list_for_each_entry(_df, &shutdown_files, shutdown_list) {
425 			if (_df->file == file) {
426 				df = _df;
427 				list_del_init(&df->shutdown_list);
428 				break;
429 			}
430 		}
431 	}
432 
433 	if (likely(df)) {
434 		if ((file->f_flags & FASYNC) && df->disconnected_f_op->fasync)
435 			df->disconnected_f_op->fasync(-1, file, 0);
436 		return df->disconnected_f_op->release(inode, file);
437 	}
438 
439 	panic("%s(%p, %p) failed!", __func__, inode, file);
440 }
441 
442 static __poll_t snd_disconnect_poll(struct file * file, poll_table * wait)
443 {
444 	return EPOLLERR | EPOLLNVAL;
445 }
446 
447 static long snd_disconnect_ioctl(struct file *file,
448 				 unsigned int cmd, unsigned long arg)
449 {
450 	return -ENODEV;
451 }
452 
453 static int snd_disconnect_mmap(struct file *file, struct vm_area_struct *vma)
454 {
455 	return -ENODEV;
456 }
457 
458 static int snd_disconnect_fasync(int fd, struct file *file, int on)
459 {
460 	return -ENODEV;
461 }
462 
463 static const struct file_operations snd_shutdown_f_ops = {
464 	.owner		=	THIS_MODULE,
465 	.llseek		=	snd_disconnect_llseek,
466 	.read		=	snd_disconnect_read,
467 	.write		=	snd_disconnect_write,
468 	.release	=	snd_disconnect_release,
469 	.poll		=	snd_disconnect_poll,
470 	.unlocked_ioctl	=	snd_disconnect_ioctl,
471 #ifdef CONFIG_COMPAT
472 	.compat_ioctl	=	snd_disconnect_ioctl,
473 #endif
474 	.mmap		=	snd_disconnect_mmap,
475 	.fasync		=	snd_disconnect_fasync
476 };
477 
478 /**
479  *  snd_card_disconnect - disconnect all APIs from the file-operations (user space)
480  *  @card: soundcard structure
481  *
482  *  Disconnects all APIs from the file-operations (user space).
483  *
484  *  Return: Zero, otherwise a negative error code.
485  *
486  *  Note: The current implementation replaces all active file->f_op with special
487  *        dummy file operations (they do nothing except release).
488  */
489 void snd_card_disconnect(struct snd_card *card)
490 {
491 	struct snd_monitor_file *mfile;
492 
493 	if (!card)
494 		return;
495 
496 	scoped_guard(spinlock, &card->files_lock) {
497 		if (card->shutdown)
498 			return;
499 		card->shutdown = 1;
500 
501 		/* replace file->f_op with special dummy operations */
502 		list_for_each_entry(mfile, &card->files_list, list) {
503 			/* it's critical part, use endless loop */
504 			/* we have no room to fail */
505 			mfile->disconnected_f_op = mfile->file->f_op;
506 
507 			scoped_guard(spinlock, &shutdown_lock)
508 				list_add(&mfile->shutdown_list, &shutdown_files);
509 
510 			mfile->file->f_op = &snd_shutdown_f_ops;
511 			fops_get(mfile->file->f_op);
512 		}
513 	}
514 
515 #ifdef CONFIG_PM
516 	/* wake up sleepers here before other callbacks for avoiding potential
517 	 * deadlocks with other locks (e.g. in kctls);
518 	 * then this notifies the shutdown and sleepers would abort immediately
519 	 */
520 	wake_up_all(&card->power_sleep);
521 #endif
522 
523 	/* notify all connected devices about disconnection */
524 	/* at this point, they cannot respond to any calls except release() */
525 
526 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
527 	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
528 #endif
529 
530 	/* notify all devices that we are disconnected */
531 	snd_device_disconnect_all(card);
532 
533 	if (card->sync_irq > 0)
534 		synchronize_irq(card->sync_irq);
535 
536 	snd_info_card_disconnect(card);
537 #ifdef CONFIG_SND_DEBUG
538 	debugfs_remove(card->debugfs_root);
539 	card->debugfs_root = NULL;
540 #endif
541 
542 	if (card->registered) {
543 		device_del(&card->card_dev);
544 		card->registered = false;
545 	}
546 
547 	/* disable fops (user space) operations for ALSA API */
548 	scoped_guard(mutex, &snd_card_mutex) {
549 		snd_cards[card->number] = NULL;
550 		clear_bit(card->number, snd_cards_lock);
551 	}
552 
553 	/* order card->shutdown store against power_ref read */
554 	smp_mb();
555 	snd_power_sync_ref(card);
556 }
557 EXPORT_SYMBOL(snd_card_disconnect);
558 
559 /**
560  * snd_card_disconnect_sync - disconnect card and wait until files get closed
561  * @card: card object to disconnect
562  *
563  * This calls snd_card_disconnect() for disconnecting all belonging components
564  * and waits until all pending files get closed.
565  * It assures that all accesses from user-space finished so that the driver
566  * can release its resources gracefully.
567  */
568 void snd_card_disconnect_sync(struct snd_card *card)
569 {
570 	snd_card_disconnect(card);
571 
572 	guard(spinlock_irq)(&card->files_lock);
573 	wait_event_lock_irq(card->remove_sleep,
574 			    list_empty(&card->files_list),
575 			    card->files_lock);
576 }
577 EXPORT_SYMBOL_GPL(snd_card_disconnect_sync);
578 
579 static int snd_card_do_free(struct snd_card *card)
580 {
581 	bool managed = card->managed;
582 
583 	card->releasing = true;
584 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
585 	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_FREE);
586 #endif
587 	snd_device_free_all(card);
588 	kfree(card->components);
589 	card->components = NULL;
590 	card->components_alloc_size = 0;
591 	if (card->private_free)
592 		card->private_free(card);
593 #ifdef CONFIG_SND_CTL_DEBUG
594 	kfree(card->value_buf);
595 #endif
596 	if (snd_info_card_free(card) < 0) {
597 		dev_warn(card->dev, "unable to free card info\n");
598 		/* Not fatal error */
599 	}
600 	put_device(card->dev);
601 	if (card->release_completion)
602 		complete(card->release_completion);
603 	if (!managed)
604 		kfree(card);
605 	return 0;
606 }
607 
608 /**
609  * snd_card_free_when_closed - Disconnect the card, free it later eventually
610  * @card: soundcard structure
611  *
612  * Unlike snd_card_free(), this function doesn't try to release the card
613  * resource immediately, but tries to disconnect at first.  When the card
614  * is still in use, the function returns before freeing the resources.
615  * The card resources will be freed when the refcount gets to zero.
616  *
617  * Return: zero if successful, or a negative error code
618  */
619 void snd_card_free_when_closed(struct snd_card *card)
620 {
621 	if (!card)
622 		return;
623 
624 	snd_card_disconnect(card);
625 	put_device(&card->card_dev);
626 	return;
627 }
628 EXPORT_SYMBOL(snd_card_free_when_closed);
629 
630 /**
631  * snd_card_free - frees given soundcard structure
632  * @card: soundcard structure
633  *
634  * This function releases the soundcard structure and the all assigned
635  * devices automatically.  That is, you don't have to release the devices
636  * by yourself.
637  *
638  * This function waits until the all resources are properly released.
639  *
640  * Return: Zero. Frees all associated devices and frees the control
641  * interface associated to given soundcard.
642  */
643 void snd_card_free(struct snd_card *card)
644 {
645 	DECLARE_COMPLETION_ONSTACK(released);
646 
647 	/* The call of snd_card_free() is allowed from various code paths;
648 	 * a manual call from the driver and the call via devres_free, and
649 	 * we need to avoid double-free. Moreover, the release via devres
650 	 * may call snd_card_free() twice due to its nature, we need to have
651 	 * the check here at the beginning.
652 	 */
653 	if (card->releasing)
654 		return;
655 
656 	card->release_completion = &released;
657 	snd_card_free_when_closed(card);
658 
659 	/* wait, until all devices are ready for the free operation */
660 	wait_for_completion(&released);
661 }
662 EXPORT_SYMBOL(snd_card_free);
663 
664 /* check, if the character is in the valid ASCII range */
665 static inline bool safe_ascii_char(char c)
666 {
667 	return isascii(c) && isalnum(c);
668 }
669 
670 /* retrieve the last word of shortname or longname */
671 static const char *retrieve_id_from_card_name(const char *name)
672 {
673 	const char *spos = name;
674 
675 	while (*name) {
676 		if (isspace(*name) && safe_ascii_char(name[1]))
677 			spos = name + 1;
678 		name++;
679 	}
680 	return spos;
681 }
682 
683 /* return true if the given id string doesn't conflict any other card ids */
684 static bool card_id_ok(struct snd_card *card, const char *id)
685 {
686 	int i;
687 	if (!snd_info_check_reserved_words(id))
688 		return false;
689 	for (i = 0; i < snd_ecards_limit; i++) {
690 		if (snd_cards[i] && snd_cards[i] != card &&
691 		    !strcmp(snd_cards[i]->id, id))
692 			return false;
693 	}
694 	return true;
695 }
696 
697 /* copy to card->id only with valid letters from nid */
698 static void copy_valid_id_string(struct snd_card *card, const char *src,
699 				 const char *nid)
700 {
701 	char *id = card->id;
702 
703 	while (*nid && !safe_ascii_char(*nid))
704 		nid++;
705 	if (isdigit(*nid))
706 		*id++ = isalpha(*src) ? *src : 'D';
707 	while (*nid && (size_t)(id - card->id) < sizeof(card->id) - 1) {
708 		if (safe_ascii_char(*nid))
709 			*id++ = *nid;
710 		nid++;
711 	}
712 	*id = 0;
713 }
714 
715 /* Set card->id from the given string
716  * If the string conflicts with other ids, add a suffix to make it unique.
717  */
718 static void snd_card_set_id_no_lock(struct snd_card *card, const char *src,
719 				    const char *nid)
720 {
721 	int len, loops;
722 	bool is_default = false;
723 	char *id;
724 
725 	copy_valid_id_string(card, src, nid);
726 	id = card->id;
727 
728  again:
729 	/* use "Default" for obviously invalid strings
730 	 * ("card" conflicts with proc directories)
731 	 */
732 	if (!*id || !strncmp(id, "card", 4)) {
733 		strscpy(card->id, "Default");
734 		is_default = true;
735 	}
736 
737 	len = strlen(id);
738 	for (loops = 0; loops < SNDRV_CARDS; loops++) {
739 		char sfxstr[5]; /* "_012" */
740 		int sfxlen, slen;
741 
742 		if (card_id_ok(card, id))
743 			return; /* OK */
744 
745 		/* Add _XYZ suffix */
746 		sfxlen = scnprintf(sfxstr, sizeof(sfxstr), "_%X", loops + 1);
747 		if (len + sfxlen >= sizeof(card->id))
748 			slen = sizeof(card->id) - sfxlen - 1;
749 		else
750 			slen = len;
751 		strscpy(id + slen, sfxstr, sizeof(card->id) - slen);
752 	}
753 	/* fallback to the default id */
754 	if (!is_default) {
755 		*id = 0;
756 		goto again;
757 	}
758 	/* last resort... */
759 	dev_err(card->dev, "unable to set card id (%s)\n", id);
760 	if (card->proc_root->name)
761 		strscpy(card->id, card->proc_root->name, sizeof(card->id));
762 }
763 
764 /**
765  *  snd_card_set_id - set card identification name
766  *  @card: soundcard structure
767  *  @nid: new identification string
768  *
769  *  This function sets the card identification and checks for name
770  *  collisions.
771  */
772 void snd_card_set_id(struct snd_card *card, const char *nid)
773 {
774 	/* check if user specified own card->id */
775 	if (card->id[0] != '\0')
776 		return;
777 	guard(mutex)(&snd_card_mutex);
778 	snd_card_set_id_no_lock(card, nid, nid);
779 }
780 EXPORT_SYMBOL(snd_card_set_id);
781 
782 static ssize_t id_show(struct device *dev,
783 		       struct device_attribute *attr, char *buf)
784 {
785 	struct snd_card *card = container_of(dev, struct snd_card, card_dev);
786 	return sysfs_emit(buf, "%s\n", card->id);
787 }
788 
789 static ssize_t id_store(struct device *dev, struct device_attribute *attr,
790 			const char *buf, size_t count)
791 {
792 	struct snd_card *card = container_of(dev, struct snd_card, card_dev);
793 	char buf1[sizeof(card->id)];
794 	size_t copy = count > sizeof(card->id) - 1 ?
795 					sizeof(card->id) - 1 : count;
796 	size_t idx;
797 	int c;
798 
799 	for (idx = 0; idx < copy; idx++) {
800 		c = buf[idx];
801 		if (!safe_ascii_char(c) && c != '_' && c != '-')
802 			return -EINVAL;
803 	}
804 	memcpy(buf1, buf, copy);
805 	buf1[copy] = '\0';
806 	guard(mutex)(&snd_card_mutex);
807 	if (!card_id_ok(NULL, buf1))
808 		return -EEXIST;
809 	strscpy(card->id, buf1);
810 	snd_info_card_id_change(card);
811 
812 	return count;
813 }
814 
815 static DEVICE_ATTR_RW(id);
816 
817 static ssize_t number_show(struct device *dev,
818 			   struct device_attribute *attr, char *buf)
819 {
820 	struct snd_card *card = container_of(dev, struct snd_card, card_dev);
821 	return sysfs_emit(buf, "%i\n", card->number);
822 }
823 
824 static DEVICE_ATTR_RO(number);
825 
826 static struct attribute *card_dev_attrs[] = {
827 	&dev_attr_id.attr,
828 	&dev_attr_number.attr,
829 	NULL
830 };
831 
832 static const struct attribute_group card_dev_attr_group = {
833 	.attrs	= card_dev_attrs,
834 };
835 
836 /**
837  * snd_card_add_dev_attr - Append a new sysfs attribute group to card
838  * @card: card instance
839  * @group: attribute group to append
840  *
841  * Return: zero if successful, or a negative error code
842  */
843 int snd_card_add_dev_attr(struct snd_card *card,
844 			  const struct attribute_group *group)
845 {
846 	int i;
847 
848 	/* loop for (arraysize-1) here to keep NULL at the last entry */
849 	for (i = 0; i < ARRAY_SIZE(card->dev_groups) - 1; i++) {
850 		if (!card->dev_groups[i]) {
851 			card->dev_groups[i] = group;
852 			return 0;
853 		}
854 	}
855 
856 	dev_err(card->dev, "Too many groups assigned\n");
857 	return -ENOSPC;
858 }
859 EXPORT_SYMBOL_GPL(snd_card_add_dev_attr);
860 
861 static void trigger_card_free(void *data)
862 {
863 	snd_card_free(data);
864 }
865 
866 /**
867  *  snd_card_register - register the soundcard
868  *  @card: soundcard structure
869  *
870  *  This function registers all the devices assigned to the soundcard.
871  *  Until calling this, the ALSA control interface is blocked from the
872  *  external accesses.  Thus, you should call this function at the end
873  *  of the initialization of the card.
874  *
875  *  Return: Zero otherwise a negative error code if the registration failed.
876  */
877 int snd_card_register(struct snd_card *card)
878 {
879 	int err;
880 
881 	if (snd_BUG_ON(!card))
882 		return -EINVAL;
883 
884 	if (!card->registered) {
885 		err = device_add(&card->card_dev);
886 		if (err < 0)
887 			return err;
888 		card->registered = true;
889 	} else {
890 		if (card->managed)
891 			devm_remove_action(card->dev, trigger_card_free, card);
892 	}
893 
894 	if (card->managed) {
895 		err = devm_add_action(card->dev, trigger_card_free, card);
896 		if (err < 0)
897 			return err;
898 	}
899 
900 	err = snd_device_register_all(card);
901 	if (err < 0)
902 		return err;
903 	scoped_guard(mutex, &snd_card_mutex) {
904 		if (snd_cards[card->number]) {
905 			/* already registered */
906 			return snd_info_card_register(card); /* register pending info */
907 		}
908 		if (*card->id) {
909 			/* make a unique id name from the given string */
910 			char tmpid[sizeof(card->id)];
911 
912 			memcpy(tmpid, card->id, sizeof(card->id));
913 			snd_card_set_id_no_lock(card, tmpid, tmpid);
914 		} else {
915 			/* create an id from either shortname or longname */
916 			const char *src;
917 
918 			src = *card->shortname ? card->shortname : card->longname;
919 			snd_card_set_id_no_lock(card, src,
920 						retrieve_id_from_card_name(src));
921 		}
922 		snd_cards[card->number] = card;
923 	}
924 	err = snd_info_card_register(card);
925 	if (err < 0)
926 		return err;
927 
928 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
929 	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER);
930 #endif
931 	return 0;
932 }
933 EXPORT_SYMBOL(snd_card_register);
934 
935 #ifdef CONFIG_SND_PROC_FS
936 static void snd_card_info_read(struct snd_info_entry *entry,
937 			       struct snd_info_buffer *buffer)
938 {
939 	int idx, count;
940 	struct snd_card *card;
941 
942 	for (idx = count = 0; idx < SNDRV_CARDS; idx++) {
943 		guard(mutex)(&snd_card_mutex);
944 		card = snd_cards[idx];
945 		if (card) {
946 			count++;
947 			snd_iprintf(buffer, "%2i [%-15s]: %s - %s\n",
948 					idx,
949 					card->id,
950 					card->driver,
951 					card->shortname);
952 			snd_iprintf(buffer, "                      %s\n",
953 					card->longname);
954 		}
955 	}
956 	if (!count)
957 		snd_iprintf(buffer, "--- no soundcards ---\n");
958 }
959 
960 #ifdef CONFIG_SND_OSSEMUL
961 void snd_card_info_read_oss(struct snd_info_buffer *buffer)
962 {
963 	int idx, count;
964 	struct snd_card *card;
965 
966 	for (idx = count = 0; idx < SNDRV_CARDS; idx++) {
967 		guard(mutex)(&snd_card_mutex);
968 		card = snd_cards[idx];
969 		if (card) {
970 			count++;
971 			snd_iprintf(buffer, "%s\n", card->longname);
972 		}
973 	}
974 	if (!count) {
975 		snd_iprintf(buffer, "--- no soundcards ---\n");
976 	}
977 }
978 
979 #endif
980 
981 #ifdef CONFIG_MODULES
982 static void snd_card_module_info_read(struct snd_info_entry *entry,
983 				      struct snd_info_buffer *buffer)
984 {
985 	int idx;
986 	struct snd_card *card;
987 
988 	for (idx = 0; idx < SNDRV_CARDS; idx++) {
989 		guard(mutex)(&snd_card_mutex);
990 		card = snd_cards[idx];
991 		if (card)
992 			snd_iprintf(buffer, "%2i %s\n",
993 				    idx, card->module->name);
994 	}
995 }
996 #endif
997 
998 int __init snd_card_info_init(void)
999 {
1000 	struct snd_info_entry *entry;
1001 
1002 	entry = snd_info_create_module_entry(THIS_MODULE, "cards", NULL);
1003 	if (! entry)
1004 		return -ENOMEM;
1005 	entry->c.text.read = snd_card_info_read;
1006 	if (snd_info_register(entry) < 0)
1007 		return -ENOMEM; /* freed in error path */
1008 
1009 #ifdef CONFIG_MODULES
1010 	entry = snd_info_create_module_entry(THIS_MODULE, "modules", NULL);
1011 	if (!entry)
1012 		return -ENOMEM;
1013 	entry->c.text.read = snd_card_module_info_read;
1014 	if (snd_info_register(entry) < 0)
1015 		return -ENOMEM; /* freed in error path */
1016 #endif
1017 
1018 	return 0;
1019 }
1020 #endif /* CONFIG_SND_PROC_FS */
1021 
1022 /**
1023  *  snd_component_add - add a component string
1024  *  @card: soundcard structure
1025  *  @component: the component id string
1026  *
1027  *  This function adds the component id string to the supported list.
1028  *  The component can be referred from the alsa-lib.
1029  *
1030  *  Return: Zero otherwise a negative error code.
1031  */
1032 
1033 int snd_component_add(struct snd_card *card, const char *component)
1034 {
1035 	char *ptr;
1036 	int len = strlen(component);
1037 	unsigned int cur_len, need_len;
1038 
1039 	guard(rwsem_write)(&snd_ioctl_rwsem);
1040 
1041 	if (card->components) {
1042 		ptr = strstr(card->components, component);
1043 		if (ptr) {
1044 			if (ptr[len] == '\0' || ptr[len] == ' ')	/* already there */
1045 				return 1;
1046 		}
1047 		cur_len = strlen(card->components) + 1;
1048 	} else {
1049 		cur_len = 0;
1050 	}
1051 
1052 	need_len = cur_len + len + 1;
1053 	if (need_len > 512) {
1054 		snd_BUG();
1055 		return -ENOMEM;
1056 	}
1057 
1058 	if (need_len > card->components_alloc_size) {
1059 		unsigned int new_alloc = roundup(need_len, 32);
1060 
1061 		ptr = krealloc(card->components, new_alloc, GFP_KERNEL);
1062 		if (!ptr)
1063 			return -ENOMEM;
1064 		if (!card->components)
1065 			ptr[0] = '\0';
1066 		card->components = ptr;
1067 		card->components_alloc_size = new_alloc;
1068 	}
1069 
1070 	if (card->components[0] != '\0')
1071 		strcat(card->components, " ");
1072 	strcat(card->components, component);
1073 	return 0;
1074 }
1075 EXPORT_SYMBOL(snd_component_add);
1076 
1077 /**
1078  *  snd_card_file_add - add the file to the file list of the card
1079  *  @card: soundcard structure
1080  *  @file: file pointer
1081  *
1082  *  This function adds the file to the file linked-list of the card.
1083  *  This linked-list is used to keep tracking the connection state,
1084  *  and to avoid the release of busy resources by hotplug.
1085  *
1086  *  Return: zero or a negative error code.
1087  */
1088 int snd_card_file_add(struct snd_card *card, struct file *file)
1089 {
1090 	struct snd_monitor_file *mfile;
1091 
1092 	mfile = kmalloc_obj(*mfile);
1093 	if (mfile == NULL)
1094 		return -ENOMEM;
1095 	mfile->file = file;
1096 	mfile->disconnected_f_op = NULL;
1097 	INIT_LIST_HEAD(&mfile->shutdown_list);
1098 	guard(spinlock)(&card->files_lock);
1099 	if (card->shutdown) {
1100 		kfree(mfile);
1101 		return -ENODEV;
1102 	}
1103 	list_add(&mfile->list, &card->files_list);
1104 	get_device(&card->card_dev);
1105 	return 0;
1106 }
1107 EXPORT_SYMBOL(snd_card_file_add);
1108 
1109 /**
1110  *  snd_card_file_remove - remove the file from the file list
1111  *  @card: soundcard structure
1112  *  @file: file pointer
1113  *
1114  *  This function removes the file formerly added to the card via
1115  *  snd_card_file_add() function.
1116  *  If all files are removed and snd_card_free_when_closed() was
1117  *  called beforehand, it processes the pending release of
1118  *  resources.
1119  *
1120  *  Return: Zero or a negative error code.
1121  */
1122 int snd_card_file_remove(struct snd_card *card, struct file *file)
1123 {
1124 	struct snd_monitor_file *mfile, *found = NULL;
1125 
1126 	scoped_guard(spinlock, &card->files_lock) {
1127 		list_for_each_entry(mfile, &card->files_list, list) {
1128 			if (mfile->file == file) {
1129 				list_del(&mfile->list);
1130 				scoped_guard(spinlock, &shutdown_lock)
1131 					list_del(&mfile->shutdown_list);
1132 				if (mfile->disconnected_f_op)
1133 					fops_put(mfile->disconnected_f_op);
1134 				found = mfile;
1135 				break;
1136 			}
1137 		}
1138 		if (list_empty(&card->files_list))
1139 			wake_up_all(&card->remove_sleep);
1140 	}
1141 	if (!found) {
1142 		dev_err(card->dev, "card file remove problem (%p)\n", file);
1143 		return -ENOENT;
1144 	}
1145 	kfree(found);
1146 	put_device(&card->card_dev);
1147 	return 0;
1148 }
1149 EXPORT_SYMBOL(snd_card_file_remove);
1150 
1151 #ifdef CONFIG_PM
1152 /**
1153  * snd_power_ref_and_wait - wait until the card gets powered up
1154  * @card: soundcard structure
1155  *
1156  * Take the power_ref reference count of the given card, and
1157  * wait until the card gets powered up to SNDRV_CTL_POWER_D0 state.
1158  * The refcount is down again while sleeping until power-up, hence this
1159  * function can be used for syncing the floating control ops accesses,
1160  * typically around calling control ops.
1161  *
1162  * The caller needs to pull down the refcount via snd_power_unref() later
1163  * when this function returns 0.
1164  *
1165  * Return: Zero if successful, or a negative error code.
1166  */
1167 int snd_power_ref_and_wait(struct snd_card *card)
1168 {
1169 	snd_power_ref(card);
1170 	/* order power_ref increment against card->shutdown read */
1171 	smp_mb__after_atomic();
1172 	if (snd_power_get_state(card) != SNDRV_CTL_POWER_D0) {
1173 		wait_event_cmd(card->power_sleep,
1174 			       card->shutdown ||
1175 			       snd_power_get_state(card) == SNDRV_CTL_POWER_D0,
1176 			       snd_power_unref(card), snd_power_ref(card));
1177 	}
1178 	if (card->shutdown) {
1179 		snd_power_unref(card);
1180 		return  -ENODEV;
1181 	}
1182 	return 0;
1183 }
1184 EXPORT_SYMBOL_GPL(snd_power_ref_and_wait);
1185 
1186 /**
1187  * snd_power_wait - wait until the card gets powered up (old form)
1188  * @card: soundcard structure
1189  *
1190  * Wait until the card gets powered up to SNDRV_CTL_POWER_D0 state.
1191  *
1192  * Return: Zero if successful, or a negative error code.
1193  */
1194 int snd_power_wait(struct snd_card *card)
1195 {
1196 	int ret;
1197 
1198 	ret = snd_power_ref_and_wait(card);
1199 	if (!ret)
1200 		snd_power_unref(card);
1201 	return ret;
1202 }
1203 EXPORT_SYMBOL(snd_power_wait);
1204 #endif /* CONFIG_PM */
1205