ALSA: core: Add device-managed page allocator helper

This is a preparation for allowing devres usages more widely in
various sound drivers.  As a first step, this patch adds a new
allocator function, snd_devm_alloc_pages(), to manage the allocated
pages via devres, so that the pages will be automagically released as
device unbinding.

Unlike the old snd_dma_alloc_pages(), the new function returns
directly the snd_dma_buffer pointer.  The caller needs NULL-check for
the allocation error appropriately.

Also, since a real device pointer is mandatory for devres,
SNDRV_DMA_TYPE_CONTINUOUS or SNDRV_DMA_TYPE_VMALLOC type can't be used
for this function.

Link: https://lore.kernel.org/r/20210715075941.23332-2-tiwai@suse.de
Signed-off-by: Takashi Iwai <tiwai@suse.de>
This commit is contained in:
Takashi Iwai 2021-07-15 09:58:23 +02:00
parent e6c0a0889b
commit 427ae2689d
2 changed files with 50 additions and 0 deletions

View File

@ -79,5 +79,9 @@ struct page *snd_sgbuf_get_page(struct snd_dma_buffer *dmab, size_t offset);
unsigned int snd_sgbuf_get_chunk_size(struct snd_dma_buffer *dmab,
unsigned int ofs, unsigned int size);
/* device-managed memory allocator */
struct snd_dma_buffer *snd_devm_alloc_pages(struct device *dev, int type,
size_t size);
#endif /* __SOUND_MEMALLOC_H */

View File

@ -127,6 +127,52 @@ void snd_dma_free_pages(struct snd_dma_buffer *dmab)
}
EXPORT_SYMBOL(snd_dma_free_pages);
/* called by devres */
static void __snd_release_pages(struct device *dev, void *res)
{
snd_dma_free_pages(res);
}
/**
* snd_devm_alloc_pages - allocate the buffer and manage with devres
* @dev: the device pointer
* @type: the DMA buffer type
* @size: the buffer size to allocate
*
* Allocate buffer pages depending on the given type and manage using devres.
* The pages will be released automatically at the device removal.
*
* Unlike snd_dma_alloc_pages(), this function requires the real device pointer,
* hence it can't work with SNDRV_DMA_TYPE_CONTINUOUS or
* SNDRV_DMA_TYPE_VMALLOC type.
*
* The function returns the snd_dma_buffer object at success, or NULL if failed.
*/
struct snd_dma_buffer *
snd_devm_alloc_pages(struct device *dev, int type, size_t size)
{
struct snd_dma_buffer *dmab;
int err;
if (WARN_ON(type == SNDRV_DMA_TYPE_CONTINUOUS ||
type == SNDRV_DMA_TYPE_VMALLOC))
return NULL;
dmab = devres_alloc(__snd_release_pages, sizeof(*dmab), GFP_KERNEL);
if (!dmab)
return NULL;
err = snd_dma_alloc_pages(type, dev, size, dmab);
if (err < 0) {
devres_free(dmab);
return NULL;
}
devres_add(dev, dmab);
return dmab;
}
EXPORT_SYMBOL_GPL(snd_devm_alloc_pages);
/**
* snd_dma_buffer_mmap - perform mmap of the given DMA buffer
* @dmab: buffer allocation information