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