xref: /openbmc/linux/sound/core/pcm_memory.c (revision 21f9cb44)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Digital Audio (PCM) abstract layer
4  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
5  */
6 
7 #include <linux/io.h>
8 #include <linux/time.h>
9 #include <linux/init.h>
10 #include <linux/slab.h>
11 #include <linux/moduleparam.h>
12 #include <linux/vmalloc.h>
13 #include <linux/export.h>
14 #include <sound/core.h>
15 #include <sound/pcm.h>
16 #include <sound/info.h>
17 #include <sound/initval.h>
18 #include "pcm_local.h"
19 
20 static int preallocate_dma = 1;
21 module_param(preallocate_dma, int, 0444);
22 MODULE_PARM_DESC(preallocate_dma, "Preallocate DMA memory when the PCM devices are initialized.");
23 
24 static int maximum_substreams = 4;
25 module_param(maximum_substreams, int, 0444);
26 MODULE_PARM_DESC(maximum_substreams, "Maximum substreams with preallocated DMA memory.");
27 
28 static const size_t snd_minimum_buffer = 16384;
29 
30 static unsigned long max_alloc_per_card = 32UL * 1024UL * 1024UL;
31 module_param(max_alloc_per_card, ulong, 0644);
32 MODULE_PARM_DESC(max_alloc_per_card, "Max total allocation bytes per card.");
33 
34 static void __update_allocated_size(struct snd_card *card, ssize_t bytes)
35 {
36 	card->total_pcm_alloc_bytes += bytes;
37 }
38 
39 static void update_allocated_size(struct snd_card *card, ssize_t bytes)
40 {
41 	mutex_lock(&card->memory_mutex);
42 	__update_allocated_size(card, bytes);
43 	mutex_unlock(&card->memory_mutex);
44 }
45 
46 static void decrease_allocated_size(struct snd_card *card, size_t bytes)
47 {
48 	mutex_lock(&card->memory_mutex);
49 	WARN_ON(card->total_pcm_alloc_bytes < bytes);
50 	__update_allocated_size(card, -(ssize_t)bytes);
51 	mutex_unlock(&card->memory_mutex);
52 }
53 
54 static int do_alloc_pages(struct snd_card *card, int type, struct device *dev,
55 			  int str, size_t size, struct snd_dma_buffer *dmab)
56 {
57 	enum dma_data_direction dir;
58 	int err;
59 
60 	/* check and reserve the requested size */
61 	mutex_lock(&card->memory_mutex);
62 	if (max_alloc_per_card &&
63 	    card->total_pcm_alloc_bytes + size > max_alloc_per_card) {
64 		mutex_unlock(&card->memory_mutex);
65 		return -ENOMEM;
66 	}
67 	__update_allocated_size(card, size);
68 	mutex_unlock(&card->memory_mutex);
69 
70 	if (str == SNDRV_PCM_STREAM_PLAYBACK)
71 		dir = DMA_TO_DEVICE;
72 	else
73 		dir = DMA_FROM_DEVICE;
74 	err = snd_dma_alloc_dir_pages(type, dev, dir, size, dmab);
75 	if (!err) {
76 		/* the actual allocation size might be bigger than requested,
77 		 * and we need to correct the account
78 		 */
79 		if (dmab->bytes != size)
80 			update_allocated_size(card, dmab->bytes - size);
81 	} else {
82 		/* take back on allocation failure */
83 		decrease_allocated_size(card, size);
84 	}
85 	return err;
86 }
87 
88 static void do_free_pages(struct snd_card *card, struct snd_dma_buffer *dmab)
89 {
90 	if (!dmab->area)
91 		return;
92 	decrease_allocated_size(card, dmab->bytes);
93 	snd_dma_free_pages(dmab);
94 	dmab->area = NULL;
95 }
96 
97 /*
98  * try to allocate as the large pages as possible.
99  * stores the resultant memory size in *res_size.
100  *
101  * the minimum size is snd_minimum_buffer.  it should be power of 2.
102  */
103 static int preallocate_pcm_pages(struct snd_pcm_substream *substream,
104 				 size_t size, bool no_fallback)
105 {
106 	struct snd_dma_buffer *dmab = &substream->dma_buffer;
107 	struct snd_card *card = substream->pcm->card;
108 	size_t orig_size = size;
109 	int err;
110 
111 	do {
112 		err = do_alloc_pages(card, dmab->dev.type, dmab->dev.dev,
113 				     substream->stream, size, dmab);
114 		if (err != -ENOMEM)
115 			return err;
116 		if (no_fallback)
117 			break;
118 		size >>= 1;
119 	} while (size >= snd_minimum_buffer);
120 	dmab->bytes = 0; /* tell error */
121 	pr_warn("ALSA pcmC%dD%d%c,%d:%s: cannot preallocate for size %zu\n",
122 		substream->pcm->card->number, substream->pcm->device,
123 		substream->stream ? 'c' : 'p', substream->number,
124 		substream->pcm->name, orig_size);
125 	return -ENOMEM;
126 }
127 
128 /**
129  * snd_pcm_lib_preallocate_free - release the preallocated buffer of the specified substream.
130  * @substream: the pcm substream instance
131  *
132  * Releases the pre-allocated buffer of the given substream.
133  */
134 void snd_pcm_lib_preallocate_free(struct snd_pcm_substream *substream)
135 {
136 	do_free_pages(substream->pcm->card, &substream->dma_buffer);
137 }
138 
139 /**
140  * snd_pcm_lib_preallocate_free_for_all - release all pre-allocated buffers on the pcm
141  * @pcm: the pcm instance
142  *
143  * Releases all the pre-allocated buffers on the given pcm.
144  */
145 void snd_pcm_lib_preallocate_free_for_all(struct snd_pcm *pcm)
146 {
147 	struct snd_pcm_substream *substream;
148 	int stream;
149 
150 	for_each_pcm_substream(pcm, stream, substream)
151 		snd_pcm_lib_preallocate_free(substream);
152 }
153 EXPORT_SYMBOL(snd_pcm_lib_preallocate_free_for_all);
154 
155 #ifdef CONFIG_SND_VERBOSE_PROCFS
156 /*
157  * read callback for prealloc proc file
158  *
159  * prints the current allocated size in kB.
160  */
161 static void snd_pcm_lib_preallocate_proc_read(struct snd_info_entry *entry,
162 					      struct snd_info_buffer *buffer)
163 {
164 	struct snd_pcm_substream *substream = entry->private_data;
165 	snd_iprintf(buffer, "%lu\n", (unsigned long) substream->dma_buffer.bytes / 1024);
166 }
167 
168 /*
169  * read callback for prealloc_max proc file
170  *
171  * prints the maximum allowed size in kB.
172  */
173 static void snd_pcm_lib_preallocate_max_proc_read(struct snd_info_entry *entry,
174 						  struct snd_info_buffer *buffer)
175 {
176 	struct snd_pcm_substream *substream = entry->private_data;
177 	snd_iprintf(buffer, "%lu\n", (unsigned long) substream->dma_max / 1024);
178 }
179 
180 /*
181  * write callback for prealloc proc file
182  *
183  * accepts the preallocation size in kB.
184  */
185 static void snd_pcm_lib_preallocate_proc_write(struct snd_info_entry *entry,
186 					       struct snd_info_buffer *buffer)
187 {
188 	struct snd_pcm_substream *substream = entry->private_data;
189 	struct snd_card *card = substream->pcm->card;
190 	char line[64], str[64];
191 	size_t size;
192 	struct snd_dma_buffer new_dmab;
193 
194 	mutex_lock(&substream->pcm->open_mutex);
195 	if (substream->runtime) {
196 		buffer->error = -EBUSY;
197 		goto unlock;
198 	}
199 	if (!snd_info_get_line(buffer, line, sizeof(line))) {
200 		snd_info_get_str(str, line, sizeof(str));
201 		size = simple_strtoul(str, NULL, 10) * 1024;
202 		if ((size != 0 && size < 8192) || size > substream->dma_max) {
203 			buffer->error = -EINVAL;
204 			goto unlock;
205 		}
206 		if (substream->dma_buffer.bytes == size)
207 			goto unlock;
208 		memset(&new_dmab, 0, sizeof(new_dmab));
209 		new_dmab.dev = substream->dma_buffer.dev;
210 		if (size > 0) {
211 			if (do_alloc_pages(card,
212 					   substream->dma_buffer.dev.type,
213 					   substream->dma_buffer.dev.dev,
214 					   substream->stream,
215 					   size, &new_dmab) < 0) {
216 				buffer->error = -ENOMEM;
217 				pr_debug("ALSA pcmC%dD%d%c,%d:%s: cannot preallocate for size %zu\n",
218 					 substream->pcm->card->number, substream->pcm->device,
219 					 substream->stream ? 'c' : 'p', substream->number,
220 					 substream->pcm->name, size);
221 				goto unlock;
222 			}
223 			substream->buffer_bytes_max = size;
224 		} else {
225 			substream->buffer_bytes_max = UINT_MAX;
226 		}
227 		if (substream->dma_buffer.area)
228 			do_free_pages(card, &substream->dma_buffer);
229 		substream->dma_buffer = new_dmab;
230 	} else {
231 		buffer->error = -EINVAL;
232 	}
233  unlock:
234 	mutex_unlock(&substream->pcm->open_mutex);
235 }
236 
237 static inline void preallocate_info_init(struct snd_pcm_substream *substream)
238 {
239 	struct snd_info_entry *entry;
240 
241 	entry = snd_info_create_card_entry(substream->pcm->card, "prealloc",
242 					   substream->proc_root);
243 	if (entry) {
244 		snd_info_set_text_ops(entry, substream,
245 				      snd_pcm_lib_preallocate_proc_read);
246 		entry->c.text.write = snd_pcm_lib_preallocate_proc_write;
247 		entry->mode |= 0200;
248 	}
249 	entry = snd_info_create_card_entry(substream->pcm->card, "prealloc_max",
250 					   substream->proc_root);
251 	if (entry)
252 		snd_info_set_text_ops(entry, substream,
253 				      snd_pcm_lib_preallocate_max_proc_read);
254 }
255 
256 #else /* !CONFIG_SND_VERBOSE_PROCFS */
257 static inline void preallocate_info_init(struct snd_pcm_substream *substream)
258 {
259 }
260 #endif /* CONFIG_SND_VERBOSE_PROCFS */
261 
262 /*
263  * pre-allocate the buffer and create a proc file for the substream
264  */
265 static int preallocate_pages(struct snd_pcm_substream *substream,
266 			      int type, struct device *data,
267 			      size_t size, size_t max, bool managed)
268 {
269 	int err;
270 
271 	if (snd_BUG_ON(substream->dma_buffer.dev.type))
272 		return -EINVAL;
273 
274 	substream->dma_buffer.dev.type = type;
275 	substream->dma_buffer.dev.dev = data;
276 
277 	if (size > 0) {
278 		if (!max) {
279 			/* no fallback, only also inform -ENOMEM */
280 			err = preallocate_pcm_pages(substream, size, true);
281 			if (err < 0)
282 				return err;
283 		} else if (preallocate_dma &&
284 			   substream->number < maximum_substreams) {
285 			err = preallocate_pcm_pages(substream, size, false);
286 			if (err < 0 && err != -ENOMEM)
287 				return err;
288 		}
289 	}
290 
291 	if (substream->dma_buffer.bytes > 0)
292 		substream->buffer_bytes_max = substream->dma_buffer.bytes;
293 	substream->dma_max = max;
294 	if (max > 0)
295 		preallocate_info_init(substream);
296 	if (managed)
297 		substream->managed_buffer_alloc = 1;
298 	return 0;
299 }
300 
301 static int preallocate_pages_for_all(struct snd_pcm *pcm, int type,
302 				      void *data, size_t size, size_t max,
303 				      bool managed)
304 {
305 	struct snd_pcm_substream *substream;
306 	int stream, err;
307 
308 	for_each_pcm_substream(pcm, stream, substream) {
309 		err = preallocate_pages(substream, type, data, size, max, managed);
310 		if (err < 0)
311 			return err;
312 	}
313 	return 0;
314 }
315 
316 /**
317  * snd_pcm_lib_preallocate_pages - pre-allocation for the given DMA type
318  * @substream: the pcm substream instance
319  * @type: DMA type (SNDRV_DMA_TYPE_*)
320  * @data: DMA type dependent data
321  * @size: the requested pre-allocation size in bytes
322  * @max: the max. allowed pre-allocation size
323  *
324  * Do pre-allocation for the given DMA buffer type.
325  */
326 void snd_pcm_lib_preallocate_pages(struct snd_pcm_substream *substream,
327 				  int type, struct device *data,
328 				  size_t size, size_t max)
329 {
330 	preallocate_pages(substream, type, data, size, max, false);
331 }
332 EXPORT_SYMBOL(snd_pcm_lib_preallocate_pages);
333 
334 /**
335  * snd_pcm_lib_preallocate_pages_for_all - pre-allocation for continuous memory type (all substreams)
336  * @pcm: the pcm instance
337  * @type: DMA type (SNDRV_DMA_TYPE_*)
338  * @data: DMA type dependent data
339  * @size: the requested pre-allocation size in bytes
340  * @max: the max. allowed pre-allocation size
341  *
342  * Do pre-allocation to all substreams of the given pcm for the
343  * specified DMA type.
344  */
345 void snd_pcm_lib_preallocate_pages_for_all(struct snd_pcm *pcm,
346 					  int type, void *data,
347 					  size_t size, size_t max)
348 {
349 	preallocate_pages_for_all(pcm, type, data, size, max, false);
350 }
351 EXPORT_SYMBOL(snd_pcm_lib_preallocate_pages_for_all);
352 
353 /**
354  * snd_pcm_set_managed_buffer - set up buffer management for a substream
355  * @substream: the pcm substream instance
356  * @type: DMA type (SNDRV_DMA_TYPE_*)
357  * @data: DMA type dependent data
358  * @size: the requested pre-allocation size in bytes
359  * @max: the max. allowed pre-allocation size
360  *
361  * Do pre-allocation for the given DMA buffer type, and set the managed
362  * buffer allocation mode to the given substream.
363  * In this mode, PCM core will allocate a buffer automatically before PCM
364  * hw_params ops call, and release the buffer after PCM hw_free ops call
365  * as well, so that the driver doesn't need to invoke the allocation and
366  * the release explicitly in its callback.
367  * When a buffer is actually allocated before the PCM hw_params call, it
368  * turns on the runtime buffer_changed flag for drivers changing their h/w
369  * parameters accordingly.
370  *
371  * When @size is non-zero and @max is zero, this tries to allocate for only
372  * the exact buffer size without fallback, and may return -ENOMEM.
373  * Otherwise, the function tries to allocate smaller chunks if the allocation
374  * fails.  This is the behavior of snd_pcm_set_fixed_buffer().
375  *
376  * When both @size and @max are zero, the function only sets up the buffer
377  * for later dynamic allocations. It's used typically for buffers with
378  * SNDRV_DMA_TYPE_VMALLOC type.
379  *
380  * Upon successful buffer allocation and setup, the function returns 0.
381  *
382  * Return: zero if successful, or a negative error code
383  */
384 int snd_pcm_set_managed_buffer(struct snd_pcm_substream *substream, int type,
385 				struct device *data, size_t size, size_t max)
386 {
387 	return preallocate_pages(substream, type, data, size, max, true);
388 }
389 EXPORT_SYMBOL(snd_pcm_set_managed_buffer);
390 
391 /**
392  * snd_pcm_set_managed_buffer_all - set up buffer management for all substreams
393  *	for all substreams
394  * @pcm: the pcm instance
395  * @type: DMA type (SNDRV_DMA_TYPE_*)
396  * @data: DMA type dependent data
397  * @size: the requested pre-allocation size in bytes
398  * @max: the max. allowed pre-allocation size
399  *
400  * Do pre-allocation to all substreams of the given pcm for the specified DMA
401  * type and size, and set the managed_buffer_alloc flag to each substream.
402  *
403  * Return: zero if successful, or a negative error code
404  */
405 int snd_pcm_set_managed_buffer_all(struct snd_pcm *pcm, int type,
406 				   struct device *data,
407 				   size_t size, size_t max)
408 {
409 	return preallocate_pages_for_all(pcm, type, data, size, max, true);
410 }
411 EXPORT_SYMBOL(snd_pcm_set_managed_buffer_all);
412 
413 /**
414  * snd_pcm_lib_malloc_pages - allocate the DMA buffer
415  * @substream: the substream to allocate the DMA buffer to
416  * @size: the requested buffer size in bytes
417  *
418  * Allocates the DMA buffer on the BUS type given earlier to
419  * snd_pcm_lib_preallocate_xxx_pages().
420  *
421  * Return: 1 if the buffer is changed, 0 if not changed, or a negative
422  * code on failure.
423  */
424 int snd_pcm_lib_malloc_pages(struct snd_pcm_substream *substream, size_t size)
425 {
426 	struct snd_card *card;
427 	struct snd_pcm_runtime *runtime;
428 	struct snd_dma_buffer *dmab = NULL;
429 
430 	if (PCM_RUNTIME_CHECK(substream))
431 		return -EINVAL;
432 	if (snd_BUG_ON(substream->dma_buffer.dev.type ==
433 		       SNDRV_DMA_TYPE_UNKNOWN))
434 		return -EINVAL;
435 	runtime = substream->runtime;
436 	card = substream->pcm->card;
437 
438 	if (runtime->dma_buffer_p) {
439 		/* perphaps, we might free the large DMA memory region
440 		   to save some space here, but the actual solution
441 		   costs us less time */
442 		if (runtime->dma_buffer_p->bytes >= size) {
443 			runtime->dma_bytes = size;
444 			return 0;	/* ok, do not change */
445 		}
446 		snd_pcm_lib_free_pages(substream);
447 	}
448 	if (substream->dma_buffer.area != NULL &&
449 	    substream->dma_buffer.bytes >= size) {
450 		dmab = &substream->dma_buffer; /* use the pre-allocated buffer */
451 	} else {
452 		/* dma_max=0 means the fixed size preallocation */
453 		if (substream->dma_buffer.area && !substream->dma_max)
454 			return -ENOMEM;
455 		dmab = kzalloc(sizeof(*dmab), GFP_KERNEL);
456 		if (! dmab)
457 			return -ENOMEM;
458 		dmab->dev = substream->dma_buffer.dev;
459 		if (do_alloc_pages(card,
460 				   substream->dma_buffer.dev.type,
461 				   substream->dma_buffer.dev.dev,
462 				   substream->stream,
463 				   size, dmab) < 0) {
464 			kfree(dmab);
465 			pr_debug("ALSA pcmC%dD%d%c,%d:%s: cannot preallocate for size %zu\n",
466 				 substream->pcm->card->number, substream->pcm->device,
467 				 substream->stream ? 'c' : 'p', substream->number,
468 				 substream->pcm->name, size);
469 			return -ENOMEM;
470 		}
471 	}
472 	snd_pcm_set_runtime_buffer(substream, dmab);
473 	runtime->dma_bytes = size;
474 	return 1;			/* area was changed */
475 }
476 EXPORT_SYMBOL(snd_pcm_lib_malloc_pages);
477 
478 /**
479  * snd_pcm_lib_free_pages - release the allocated DMA buffer.
480  * @substream: the substream to release the DMA buffer
481  *
482  * Releases the DMA buffer allocated via snd_pcm_lib_malloc_pages().
483  *
484  * Return: Zero if successful, or a negative error code on failure.
485  */
486 int snd_pcm_lib_free_pages(struct snd_pcm_substream *substream)
487 {
488 	struct snd_pcm_runtime *runtime;
489 
490 	if (PCM_RUNTIME_CHECK(substream))
491 		return -EINVAL;
492 	runtime = substream->runtime;
493 	if (runtime->dma_area == NULL)
494 		return 0;
495 	if (runtime->dma_buffer_p != &substream->dma_buffer) {
496 		struct snd_card *card = substream->pcm->card;
497 
498 		/* it's a newly allocated buffer.  release it now. */
499 		do_free_pages(card, runtime->dma_buffer_p);
500 		kfree(runtime->dma_buffer_p);
501 	}
502 	snd_pcm_set_runtime_buffer(substream, NULL);
503 	return 0;
504 }
505 EXPORT_SYMBOL(snd_pcm_lib_free_pages);
506 
507 int _snd_pcm_lib_alloc_vmalloc_buffer(struct snd_pcm_substream *substream,
508 				      size_t size, gfp_t gfp_flags)
509 {
510 	struct snd_pcm_runtime *runtime;
511 
512 	if (PCM_RUNTIME_CHECK(substream))
513 		return -EINVAL;
514 	runtime = substream->runtime;
515 	if (runtime->dma_area) {
516 		if (runtime->dma_bytes >= size)
517 			return 0; /* already large enough */
518 		vfree(runtime->dma_area);
519 	}
520 	runtime->dma_area = __vmalloc(size, gfp_flags);
521 	if (!runtime->dma_area)
522 		return -ENOMEM;
523 	runtime->dma_bytes = size;
524 	return 1;
525 }
526 EXPORT_SYMBOL(_snd_pcm_lib_alloc_vmalloc_buffer);
527 
528 /**
529  * snd_pcm_lib_free_vmalloc_buffer - free vmalloc buffer
530  * @substream: the substream with a buffer allocated by
531  *	snd_pcm_lib_alloc_vmalloc_buffer()
532  *
533  * Return: Zero if successful, or a negative error code on failure.
534  */
535 int snd_pcm_lib_free_vmalloc_buffer(struct snd_pcm_substream *substream)
536 {
537 	struct snd_pcm_runtime *runtime;
538 
539 	if (PCM_RUNTIME_CHECK(substream))
540 		return -EINVAL;
541 	runtime = substream->runtime;
542 	vfree(runtime->dma_area);
543 	runtime->dma_area = NULL;
544 	return 0;
545 }
546 EXPORT_SYMBOL(snd_pcm_lib_free_vmalloc_buffer);
547 
548 /**
549  * snd_pcm_lib_get_vmalloc_page - map vmalloc buffer offset to page struct
550  * @substream: the substream with a buffer allocated by
551  *	snd_pcm_lib_alloc_vmalloc_buffer()
552  * @offset: offset in the buffer
553  *
554  * This function is to be used as the page callback in the PCM ops.
555  *
556  * Return: The page struct, or %NULL on failure.
557  */
558 struct page *snd_pcm_lib_get_vmalloc_page(struct snd_pcm_substream *substream,
559 					  unsigned long offset)
560 {
561 	return vmalloc_to_page(substream->runtime->dma_area + offset);
562 }
563 EXPORT_SYMBOL(snd_pcm_lib_get_vmalloc_page);
564