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