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