Re: [BUG] ALSA: core: pcm_memory: a possible data race in do_alloc_pages()

From: Takashi Iwai
Date: Mon Jun 26 2023 - 03:33:55 EST


On Mon, 26 Jun 2023 09:31:18 +0200,
Tuo Li wrote:
>
>
> Hello,
>
> Thank you for your reply!

FWIW, the simplest fix would be something like below, just extending
the mutex coverage. But it'll serialize the all calls, so it might
influence on the performance, while it's the safest way.


Takashi

--- a/sound/core/pcm_memory.c
+++ b/sound/core/pcm_memory.c
@@ -37,20 +37,22 @@ static int do_alloc_pages(struct snd_card *card, int type, struct device *dev,
enum dma_data_direction dir;
int err;

+ mutex_lock(&card->memory_mutex);
if (max_alloc_per_card &&
- card->total_pcm_alloc_bytes + size > max_alloc_per_card)
- return -ENOMEM;
+ card->total_pcm_alloc_bytes + size > max_alloc_per_card) {
+ err = -ENOMEM;
+ goto unlock;
+ }

if (str == SNDRV_PCM_STREAM_PLAYBACK)
dir = DMA_TO_DEVICE;
else
dir = DMA_FROM_DEVICE;
err = snd_dma_alloc_dir_pages(type, dev, dir, size, dmab);
- if (!err) {
- mutex_lock(&card->memory_mutex);
+ if (!err)
card->total_pcm_alloc_bytes += dmab->bytes;
- mutex_unlock(&card->memory_mutex);
- }
+ unlock:
+ mutex_unlock(&card->memory_mutex);
return err;
}