ALSA: virtio: Fix request lifetime and error recovery
Subsystems (3)
v3 cover ALSA: virtio: Fix request lifetime and error recovery
A failed PCM start or a timed-out request can leave virtio-snd messages owned by the device after the caller returns. Retrying can then reuse pending messages, and freeing ALSA or control buffers can leave their addresses in a virtqueue.
This series fixes enqueue-error recovery and keeps the memory referenced by outstanding requests alive until completion or device reset. Reset also detaches unused descriptors before deleting the queues, releasing their DMA mappings and cancelling PCM messages without reporting them as completed audio.
Changes since v2, following the Sashiko AI review:
- Patch 2 protects all stopped-state accesses with vss->lock, including hw_params, prepare, open, STOP and sync_stop completion. The RELEASE decision and stopped=true transition now share a critical section. Sleeping operations remain outside the spinlock.
- Patch 5 aligns every DMA region for both cache maintenance and typed CPU accesses, and removes the initial +1 offset. This handles coherent systems where dma_get_cache_alignment() returns 1, as well as odd region lengths that could otherwise misalign later payloads.
- Patches 1, 3 and 4 are unchanged.
Validation of the final v3 source:
- ARM64 W=1 module build and ARM32 CONFIG_MMU=n driver object build.
- Source-extracted ASan/UBSan PCM, control, reset, ACK and DMA lifetime regressions on macOS arm64. The v2 control allocator produces UBSan misalignment diagnostics; the v3 allocator passes typed header and request/response integer64 accesses with DMA alignments 1, 2, 4, 8, 32, 64 and 128.
- Deterministic stopped-state lock instrumentation catches unlocked v2 accesses and passes 73 lifecycle assertions for v3. It covers ACK failure, RELEASE failure/retry and ACK during RELEASE, and checks that blocking operations do not run with the spinlock held.
The stopped-state test instruments extracted source; it is not KCSAN or an actual threaded kernel race test. NOMMU was compiled, not booted. Physical non-coherent DMA hardware and host microphone behavior were not tested by these regressions. The QEMU ARM64 KASAN fault/recovery runs reported in v2 have not been rerun for these v3 changes.
Reproducer source and instructions:
https://github.com/whatisyourname0/virtio-snd-reproducer/tree/3ee5c7c1e864dae50a127b0a25cd122532daa6de
Based on sound.git for-next commit8d70e364e866bdfca81eee24d0688fac9472cfb9.
AI assistance was used for code changes, tests, review and patch text. Assisted-by trailers are included. Sashiko's findings were checked against the driver and covered by regressions before incorporating the fixes.
Previous series Message-ID:
<[email protected]>
Joonho Lee (5):
ALSA: virtio: Propagate PCM send failures through ACK
ALSA: virtio: Recover PCM state after a failed start
ALSA: virtio: Retain queued messages through device reset
ALSA: virtio: Keep PCM DMA buffers alive through device ownership
ALSA: virtio: Keep control payloads alive through DMA completion
sound/virtio/virtio_card.c | 44 ++++- sound/virtio/virtio_card.h | 2 + sound/virtio/virtio_ctl_msg.c | 307 +++++++++++++++++++++++++++------- sound/virtio/virtio_ctl_msg.h | 28 +++- sound/virtio/virtio_kctl.c | 104 ++++++------ sound/virtio/virtio_pcm.h | 17 +- sound/virtio/virtio_pcm_msg.c | 295 +++++++++++++++++++++++++++++--- sound/virtio/virtio_pcm_ops.c | 165 +++++++++++++++--- 8 files changed, 798 insertions(+), 164 deletions(-)
base-commit: 8d70e364e866bdfca81eee24d0688fac9472cfb9
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 1/5 ALSA: virtio: Propagate PCM send failures through ACK
virtsnd_pcm_msg_send() can fail while queueing a transfer. Restore the failed message's length and notify the device about earlier messages queued by the same call, so they do not remain stranded.
Propagate that failure through the indirect PCM transfer callback instead of discarding it. Commit the updated indirect state only after successful submission and stop further transfers when a send fails. Return an XRUN error to ALSA so the stream can recover.
Keep the polling feature path unchanged.
---
Changes in v3:
- No code or commit-message changes from v2.
sound/virtio/virtio_pcm_msg.c | 12 +++++ sound/virtio/virtio_pcm_ops.c | 82 +++++++++++++++++++++++++++++++---- 2 files changed, 85 insertions(+), 9 deletions(-)
sound/virtio/virtio_pcm_msg.c +12 -0
@@ -260,6 +260,18 @@ int virtsnd_pcm_msg_send(struct virtio_pcm_substream *vss, unsigned long offset,dev_err (&vdev->dev,"SID %u: failed to send I/O message\n" , vss->sid); + msg->length -= n; + +/* +* Do not leave earlier messages queued without notifying +* the device when a later message could not be added. +*/ +if (msg_count != vss->msg_count && + !(vss->features & + (1U <<VIRTIO_SND_PCM_F_MSG_POLLING )) && +virtqueue_kick_prepare (vqueue)) +virtqueue_notify (vqueue); +return rc; }
sound/virtio/virtio_pcm_ops.c +73 -9
109 lines not on this page · raw message
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 2/5 ALSA: virtio: Recover PCM state after a failed start
In reply to Joonho LeeCapture trigger queues I/O messages before PCM_START. If the START message cannot be allocated or sent, transfers may remain queued, and ALSA does not invoke the action undo callback for the failed trigger.
Mark the stream stopped and disable transfers for every failed START path. Arm runtime->stop_operating so sync_stop releases pending I/O and prevents prepare, hw_params, or START retries until release succeeds.
The stopped flag is shared with ACK callbacks that can run without the ALSA stream lock. Protect every stopped access with vss->lock. Read the pending message count under the same lock in open and hw_params. In sync_stop, decide whether RELEASE is needed and mark the stream stopped in one locked transition; leave it stopped when release or draining fails.
Always cancel elapsed-period work in sync_stop, even when no RELEASE is needed.
---
Changes in v3:
- Protect all stopped accesses with vss->lock. Keep the RELEASE decision and stopped transition in the same critical section.
sound/virtio/virtio_pcm.h | 4 +- sound/virtio/virtio_pcm_ops.c | 81 +++++++++++++++++++++++++++++------ 2 files changed, 69 insertions(+), 16 deletions(-)
sound/virtio/virtio_pcm.h +2 -2
@@ -26,13 +26,13 @@ struct virtio_pcm_msg;* @hw: Kernel ALSA substream hardware descriptor. * @elapsed_period: Kernel work to handle the elapsed period state. * @lock: Spinlock that protects fields shared by interrupt handlers and -* substream operators. +* substream operators, including @stopped. * @buffer_bytes: Current buffer size in bytes. * @hw_ptr: Substream hardware pointer value in bytes [0 ... buffer_bytes). * @xfer_enabled: Data transfer state (0 - off, 1 - on). * @xfer_xrun: Data underflow/overflow state (0 - no xrun, 1 - xrun). * @stopped: True if the substream is stopped and must be released on the device -* side. +* side; protected by @lock. * @suspended: True if the substream is suspended and must be reconfigured on * the device side at resume. * @msgs: Allocated I/O messages.
sound/virtio/virtio_pcm_ops.c +67 -14
162 lines not on this page · raw message
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 3/5 ALSA: virtio: Retain queued messages through device reset
In reply to Joonho LeeKeep the control queue available through snd_card_free() so close-time STOP and RELEASE commands can still be submitted. Block new control requests and mark pending messages canceled before reset, then release their queue references only after reset and queue deletion.
For PCM queues, detach each remaining virtqueue buffer after the device has stopped DMA and retire its message without reporting a normal completion. Detach all queues before deleting them so outstanding DMA mappings are unmapped and no token remains for a late device completion.
---
Changes in v3:
- No code or commit-message changes from v2.
sound/virtio/virtio_card.c | 44 ++++++++++++++++++++++--- sound/virtio/virtio_card.h | 2 ++ sound/virtio/virtio_ctl_msg.c | 62 +++++++++++++++++++++++++++++++---- sound/virtio/virtio_ctl_msg.h | 4 +++ sound/virtio/virtio_pcm.h | 2 ++ sound/virtio/virtio_pcm_msg.c | 29 ++++++++++++++++ 6 files changed, 131 insertions(+), 12 deletions(-)
sound/virtio/virtio_card.c +39 -5
@@ -337,6 +337,38 @@ static int virtsnd_probe(struct virtio_device *vdev)return rc; } +/** +* virtsnd_reset_vqs() - Stop device access and unmap outstanding buffers. +* @snd: VirtIO sound device. +* +* Context: Any context that permits to sleep. +*/ +static void virtsnd_reset_vqs (struct virtio_snd *snd) +{ +struct virtio_device *vdev = snd->vdev; +unsigned int i; + +virtio_reset_device (vdev); + +/* Deleting a virtqueue does not unmap its outstanding descriptors. */ +for (i =0 ; i <VIRTIO_SND_VQ_MAX ; ++i) { +struct virtio_snd_queue *queue = &snd->queues[i]; +unsigned long flags; +void *msg; + +spin_lock_irqsave (&queue->lock, flags); +if (queue->vqueue) +while ((msg =virtqueue_detach_unused_buf (queue->vqueue))) +if (i ==VIRTIO_SND_VQ_TX || i ==VIRTIO_SND_VQ_RX ) +virtsnd_pcm_msg_cancel (msg); +spin_unlock_irqrestore (&queue->lock, flags); + } + + vdev->config->del_vqs (vdev); +for (i =0 ; i <VIRTIO_SND_VQ_MAX ; ++i) + snd->queues[i].vqueue =NULL ; +} +/** * virtsnd_remove() - Remove VirtIO and ALSA devices. * @vdev: VirtIO parent device.
@@ -349,13 +381,14 @@ static void virtsnd_remove(struct virtio_device *vdev)unsigned int i;virtsnd_disable_event_vq (snd); -virtsnd_ctl_msg_cancel_all (snd);if (snd->card)snd_card_free (snd->card); -virtio_reset_device (vdev); - vdev->config->del_vqs (vdev); +virtsnd_ctl_msg_cancel_all (snd); + +virtsnd_reset_vqs (snd); +virtsnd_ctl_msg_cleanup (snd);for (i =0 ; snd->substreams && i < snd->nsubstreams; ++i) {struct virtio_pcm_substream *vss = &snd->substreams[i];
@@ -383,8 +416,8 @@ static int virtsnd_freeze(struct virtio_device *vdev)virtsnd_disable_event_vq (snd);virtsnd_ctl_msg_cancel_all (snd); -virtio_reset_device (vdev); - vdev->config->del_vqs (vdev); +virtsnd_reset_vqs (snd); +virtsnd_ctl_msg_cleanup (snd);for (i =0 ; i < snd->nsubstreams; ++i)cancel_work_sync (&snd->substreams[i].elapsed_period);
@@ -412,6 +445,7 @@ static int virtsnd_restore(struct virtio_device *vdev)return rc;virtio_device_ready (vdev); +virtsnd_ctl_msg_enable (snd);virtsnd_enable_event_vq (snd);
sound/virtio/virtio_card.h +2 -0
@@ -47,6 +47,7 @@ struct virtio_kctl {* @queues: Virtqueue wrappers. * @card: ALSA sound card. * @ctl_msgs: Pending control request list. +* @ctl_msgs_blocked: Control requests are blocked during teardown or suspend. * @event_msgs: Device events. * @pcm_list: VirtIO PCM device list. * @jacks: VirtIO jacks.
@@ -64,6 +65,7 @@ struct virtio_snd {struct virtio_snd_queue queues[VIRTIO_SND_VQ_MAX ];struct snd_card *card;struct list_head ctl_msgs; +bool ctl_msgs_blocked;struct virtio_snd_event *event_msgs;struct list_head pcm_list;struct virtio_jack *jacks;
sound/virtio/virtio_ctl_msg.c +55 -7
122 lines not on this page · raw message
sound/virtio/virtio_ctl_msg.h +4 -0
@@ -68,6 +68,10 @@ static inline int virtsnd_ctl_msg_send_async(struct virtio_snd *snd,void virtsnd_ctl_msg_cancel_all (struct virtio_snd *snd); +void virtsnd_ctl_msg_cleanup (struct virtio_snd *snd); + +void virtsnd_ctl_msg_enable (struct virtio_snd *snd); +void virtsnd_ctl_msg_complete (struct virtio_snd_msg *msg); int virtsnd_ctl_query_info(struct virtio_snd *snd, int command, int start_id,
sound/virtio/virtio_pcm.h +2 -0
@@ -120,6 +120,8 @@ void virtsnd_pcm_msg_free(struct virtio_pcm_substream *vss);void virtsnd_pcm_msg_reset (struct virtio_pcm_substream *vss); +void virtsnd_pcm_msg_cancel (struct virtio_pcm_msg *msg); +int virtsnd_pcm_msg_send (struct virtio_pcm_substream *vss,unsigned long offset,unsigned long bytes);
sound/virtio/virtio_pcm_msg.c +29 -0
@@ -307,6 +307,35 @@ unsigned int virtsnd_pcm_msg_pending_num(struct virtio_pcm_substream *vss)return vss->msg_count; } +/** +* virtsnd_pcm_msg_cancel() - Cancel a message detached during device reset. +* @msg: Message returned by virtqueue_detach_unused_buf(). +* +* Reset cancellation retires the queue token without treating it as a device +* completion. In particular, it does not advance the PCM hardware pointer or +* schedule period work. +* +* Context: Process context with the PCM queue lock held. +*/ +void virtsnd_pcm_msg_cancel (struct virtio_pcm_msg *msg) +{ +struct virtio_pcm_substream *vss = msg->substream; +bool wake; + + { +guard (spinlock)(&vss->lock); + msg->length =0 ; + vss->xfer_enabled = false; +if (WARN_ON_ONCE (!vss->msg_count)) +return ; + vss->msg_count--; + wake = !vss->msg_count; + } + +if (wake) +wake_up_all (&vss->msg_empty); +} +/** * virtsnd_pcm_msg_complete() - Complete an I/O message. * @msg: I/O message.
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 4/5 ALSA: virtio: Keep PCM DMA buffers alive through device ownership
In reply to Joonho LeeRetain references to the pages backing ALSA's vmalloc buffer until its queued I/O messages are freed. On NOMMU systems, use driver-owned memory for DMA and copy playback data before submission and capture data after completion, so ALSA buffer release cannot invalidate an active request.
Validate the PCM buffer and each period before building scatterlists. Clamp device-reported capture lengths to the message capacity before advancing the hardware pointer, preventing an oversized completion from accounting bytes beyond the buffer actually submitted.
---
Changes in v3:
- No code or commit-message changes from v2.
sound/virtio/virtio_pcm.h | 11 ++ sound/virtio/virtio_pcm_msg.c | 252 +++++++++++++++++++++++++++++++--- sound/virtio/virtio_pcm_ops.c | 2 + 3 files changed, 243 insertions(+), 22 deletions(-)
sound/virtio/virtio_pcm.h +11 -0
@@ -13,6 +13,7 @@struct virtio_pcm ;struct virtio_pcm_msg ; +struct page ;/** * struct virtio_pcm_substream - VirtIO PCM substream.
@@ -38,6 +39,10 @@ struct virtio_pcm_msg;* @msgs: Allocated I/O messages. * @nmsgs: Number of allocated I/O messages. * @msg_count: Number of pending I/O messages in the virtqueue. +* @dma_pages: Pages backing DMA messages, retained until messages are freed. +* @ndma_pages: Number of retained pages. +* @owned_dma_area: Driver-owned PCM buffer backing asynchronous messages. +* @owned_dma_bytes: Size of @owned_dma_area. * @msg_empty: Notify when msg_count is zero. */ struct virtio_pcm_substream {
@@ -60,6 +65,12 @@ struct virtio_pcm_substream {struct virtio_pcm_msg **msgs;unsigned int nmsgs;unsigned int msg_count; +struct page **dma_pages; +unsigned int ndma_pages; +#ifndef CONFIG_MMU +u8 *owned_dma_area; +size_t owned_dma_bytes; +#endif wait_queue_head_t msg_empty; };
sound/virtio/virtio_pcm_msg.c +230 -22
353 lines not on this page · raw message
sound/virtio/virtio_pcm_ops.c +2 -0
@@ -25,6 +25,8 @@* signal or due to a timeout. In this case, the device can still access * messages even after calling ops->hw_free(). It can also issue an interrupt, * and the interrupt handler will also try to access message structures. +* The messages retain references to the PCM buffer pages until they are +* freed, so late DMA does not target pages released by ALSA. * * Therefore, freeing of already allocated messages occurs: *
Signature · 1 line
2.54.0 (Apple Git-157)
PATCH v3 5/5 ALSA: virtio: Keep control payloads alive through DMA completion
In reply to Joonho LeeControl requests can expose caller-owned payloads to the device after a synchronous send times out. Keep request and response headers and payloads in the reference-counted message so caller cleanup cannot invalidate DMA.
Keep the queue reference until device completion or post-reset cleanup, even when the caller times out or is interrupted. Consume the caller's reference on every send path, and let response readers retain an extra reference through copyout. Check payload sizes and allocation arithmetic before building the scatterlists.
A control value payload is also read by the CPU as a typed structure. DMA cacheline alignment alone does not guarantee the structure's CPU alignment. Align regions to the greater of the DMA cacheline and control-value type alignment, and reserve prefix slack from the buffer base so typed accesses remain aligned while scatterlist regions stay on cacheline boundaries.
---
Changes in v3:
- Respect both DMA and CPU type alignment, remove the +1 offset, and retain alignment for every region, including odd-sized payloads.
sound/virtio/virtio_ctl_msg.c | 275 ++++++++++++++++++++++++++-------- sound/virtio/virtio_ctl_msg.h | 24 ++- sound/virtio/virtio_kctl.c | 104 +++++++------ sound/virtio/virtio_pcm_msg.c | 2 +- 4 files changed, 285 insertions(+), 120 deletions(-)
sound/virtio/virtio_ctl_msg.c +211 -64
@@ -3,7 +3,10 @@* virtio-snd: Virtio sound device * Copyright (C) 2021 OpenSynergy GmbH */ +#include <linux/dma-mapping.h> +#include <linux/limits.h> #include <linux/moduleparam.h> +#include <linux/overflow.h> #include <linux/virtio_config.h> #include "virtio_card.h"
@@ -11,7 +14,12 @@/** * struct virtio_snd_msg - Control message. * @sg_request: Scattergather list containing a device request (header). +* @sg_request_data: Scattergather list containing request data. * @sg_response: Scattergather list containing a device response (status). +* @sg_response_data: Scattergather list containing response data. +* @dma_buffer: Message-owned storage for all DMA-visible SG regions. +* @request_data_size: Size of the request data buffer. +* @response_data_size: Size of the response data buffer. * @list: Pending message list entry. * @notify: Request completed notification. * @ref_count: Reference count used to manage a message lifetime.
@@ -19,7 +27,12 @@*/ struct virtio_snd_msg {struct scatterlist sg_request; +struct scatterlist sg_request_data;struct scatterlist sg_response; +struct scatterlist sg_response_data; +void *dma_buffer; +size_t request_data_size; +size_t response_data_size;struct list_head list;struct completion notify;refcount_t ref_count;
@@ -47,8 +60,10 @@ void virtsnd_ctl_msg_ref(struct virtio_snd_msg *msg)*/ void virtsnd_ctl_msg_unref (struct virtio_snd_msg *msg) { -if (refcount_dec_and_test (&msg->ref_count)) +if (refcount_dec_and_test (&msg->ref_count)) { +kfree (msg->dma_buffer);kfree (msg); + } }/**
@@ -73,10 +88,71 @@ void *virtsnd_ctl_msg_response(struct virtio_snd_msg *msg)return sg_virt (&msg->sg_response); } +/** +* virtsnd_ctl_msg_request_data() - Get the request data buffer. +* @msg: Control message. +* +* Context: Any context. +*/ +void *virtsnd_ctl_msg_request_data (struct virtio_snd_msg *msg) +{ +return msg->request_data_size ?sg_virt (&msg->sg_request_data) :NULL ; +} + +/** +* virtsnd_ctl_msg_response_data() - Get the response data buffer. +* @msg: Control message. +* +* Context: Any context. +*/ +void *virtsnd_ctl_msg_response_data (struct virtio_snd_msg *msg) +{ +return msg->response_data_size ?sg_virt (&msg->sg_response_data) :NULL ; +} + +/** +* virtsnd_ctl_msg_sg_init() - Place one DMA region on cacheline boundaries. +* @sg: Scattergather entry for the region. +* @cursor: Current location in the message-owned DMA buffer. +* @size: Region length. +* @alignment: Alignment for DMA cachelines and typed CPU accesses. +* +* Context: Any context during message allocation. +* Return: 0 on success, -EOVERFLOW if the address cannot be represented. +*/ +static int virtsnd_ctl_msg_sg_init (struct scatterlist *sg,u8 **cursor, +size_t size,size_t alignment) +{ +uintptr_t address = (uintptr_t )*cursor; +uintptr_t end; +size_t padding; + + padding = address % alignment; +if (padding && +check_add_overflow (address, (uintptr_t )(alignment - padding), + &address)) +return -EOVERFLOW ; + +if (check_add_overflow (address, (uintptr_t )size, &end)) +return -EOVERFLOW ; + + padding = end % alignment; +if (padding && +check_add_overflow (end, (uintptr_t )(alignment - padding), &end)) +return -EOVERFLOW ; + +sg_init_one (sg, (void *)address, (unsigned int )size); + *cursor = (u8 *)end; + +return 0 ; +} +/** * virtsnd_ctl_msg_alloc() - Allocate and initialize a control message. * @request_size: Size of request header. * @response_size: Size of response header. +* @request_data_size: Size of request data buffer. +* @response_data_size: Size of response data buffer. * @gfp: Kernel flags for memory allocation. * * The message will be automatically freed when the ref_count value is 0.
@@ -85,20 +161,85 @@ void *virtsnd_ctl_msg_response(struct virtio_snd_msg *msg)* Return: Allocated message on success, NULL on failure. */ struct virtio_snd_msg *virtsnd_ctl_msg_alloc (size_t request_size, -size_t response_size,gfp_t gfp) +size_t response_size, +size_t request_data_size, +size_t response_data_size, +gfp_t gfp) {struct virtio_snd_msg *msg; +struct scatterlist *sgs[4 ]; +size_t sizes[4 ] = { + request_size, + response_size, + request_data_size, + response_data_size, + }; +size_t alignment; +size_t dma_buffer_size; +size_t aligned_size; +size_t padding; +u8 *data; +unsigned int i; +int cache_alignment; +int rc; -if (!request_size || !response_size) +if (!request_size || !response_size || request_size >UINT_MAX || + response_size >UINT_MAX || request_data_size >UINT_MAX || + response_data_size >UINT_MAX )return NULL ; + cache_alignment =dma_get_cache_alignment (); +if (cache_alignment <=0 ) +return NULL ; +/* DMA coherence does not remove the CPU's type alignment requirement. */ + alignment =max_t (size_t, cache_alignment, + __alignof__(struct virtio_snd_ctl_value )); + +/* Reserve prefix alignment slack before the first DMA region. */ + dma_buffer_size = alignment -1 ; +for (i =0 ; i <ARRAY_SIZE (sizes); ++i) { +if (!sizes[i]) +continue ; + + padding = sizes[i] % alignment; + aligned_size = sizes[i]; +if (padding && +check_add_overflow (aligned_size, alignment - padding, + &aligned_size)) +return NULL ; + +if (check_add_overflow (dma_buffer_size, aligned_size, + &dma_buffer_size)) +return NULL ; + } - msg =kzalloc (sizeof (*msg) + request_size + response_size, gfp); + msg =kzalloc (sizeof (*msg), gfp);if (!msg)return NULL ; -sg_init_one (&msg->sg_request, (u8 *)msg +sizeof (*msg), request_size); -sg_init_one (&msg->sg_response, (u8 *)msg +sizeof (*msg) + request_size, - response_size); + msg->dma_buffer =kzalloc (dma_buffer_size, gfp); +if (!msg->dma_buffer) { +kfree (msg); +return NULL ; + } + data = msg->dma_buffer; + sgs[0 ] = &msg->sg_request; + sgs[1 ] = &msg->sg_response; + sgs[2 ] = &msg->sg_request_data; + sgs[3 ] = &msg->sg_response_data; +for (i =0 ; i <ARRAY_SIZE (sizes); ++i) { +if (!sizes[i]) +continue ; + + rc =virtsnd_ctl_msg_sg_init (sgs[i], &data, sizes[i], alignment); +if (rc) { +kfree (msg->dma_buffer); +kfree (msg); +return NULL ; + } + } + + msg->request_data_size = request_data_size; + msg->response_data_size = response_data_size;INIT_LIST_HEAD (&msg->list);init_completion (&msg->notify);
@@ -112,17 +253,15 @@ struct virtio_snd_msg *virtsnd_ctl_msg_alloc(size_t request_size,* virtsnd_ctl_msg_send() - Send a control message. * @snd: VirtIO sound device. * @msg: Control message. -* @out_sgs: Additional sg-list to attach to the request header (may be NULL). -* @in_sgs: Additional sg-list to attach to the response header (may be NULL). * @nowait: Flag indicating whether to wait for completion. * * Context: Any context. Takes and releases the control queue spinlock. * May sleep if @nowait is false. +* Consumes the caller's reference on every return path. * Return: 0 on success, -errno on failure. */ int virtsnd_ctl_msg_send (struct virtio_snd *snd,struct virtio_snd_msg *msg, -struct scatterlist *out_sgs, -struct scatterlist *in_sgs,bool nowait) +bool nowait) {struct virtio_device *vdev = snd->vdev;struct virtio_snd_queue *queue =virtsnd_control_queue (snd);
@@ -133,6 +272,7 @@ int virtsnd_ctl_msg_send(struct virtio_snd *snd, struct virtio_snd_msg *msg,unsigned int nins =0 ;struct scatterlist *psgs[4 ];bool notify = false; +unsigned long flags;int rc;virtsnd_ctl_msg_ref (msg);
@@ -142,27 +282,27 @@ int virtsnd_ctl_msg_send(struct virtio_snd *snd, struct virtio_snd_msg *msg, response->code =cpu_to_le32 (VIRTIO_SND_S_IO_ERR ); psgs[nouts++] = &msg->sg_request; -if (out_sgs) - psgs[nouts++] = out_sgs; +if (msg->request_data_size) + psgs[nouts++] = &msg->sg_request_data; psgs[nouts + nins++] = &msg->sg_response; -if (in_sgs) - psgs[nouts + nins++] = in_sgs; - - scoped_guard(spinlock_irqsave, &queue->lock) { -if (snd->ctl_msgs_blocked) - rc = -ENODEV ; -else - rc =virtqueue_add_sgs (queue->vqueue, psgs, nouts, nins, - msg,GFP_ATOMIC ); -if (!rc) { - notify =virtqueue_kick_prepare (queue->vqueue); +if (msg->response_data_size) + psgs[nouts + nins++] = &msg->sg_response_data; -list_add_tail (&msg->list, &snd->ctl_msgs); -if (notify) -virtqueue_notify (queue->vqueue); - } +spin_lock_irqsave (&queue->lock, flags); +if (snd->ctl_msgs_blocked) + rc = -ENODEV ; +else + rc =virtqueue_add_sgs (queue->vqueue, psgs, nouts, nins, msg, +GFP_ATOMIC ); +if (!rc) { + notify =virtqueue_kick_prepare (queue->vqueue); + +list_add_tail (&msg->list, &snd->ctl_msgs); +if (notify) +virtqueue_notify (queue->vqueue); } +spin_unlock_irqrestore (&queue->lock, flags);if (rc) { dev_err(&vdev->dev, "failed to send control message (0x%08x)\n",
@@ -173,46 +313,36 @@ int virtsnd_ctl_msg_send(struct virtio_snd *snd, struct virtio_snd_msg *msg,* called, it is necessary to decrement the reference count. */ virtsnd_ctl_msg_unref (msg); - - goto on_exit; - } - -if (nowait) - goto on_exit; - - rc =wait_for_completion_interruptible_timeout (&msg->notify, js); -if (rc <=0 ) { + }else if (!nowait) { + rc =wait_for_completion_interruptible_timeout (&msg->notify, js);if (!rc) {dev_err (&vdev->dev,"control message (0x%08x) timeout\n" ,le32_to_cpu (request->code)); rc = -ETIMEDOUT ; + }else if (rc >0 ) { +if (READ_ONCE (msg->cancelled)) { + rc = -ENODEV ; + }else { +switch (le32_to_cpu (response->code)) { +case VIRTIO_SND_S_OK : + rc =0 ; +break ; +case VIRTIO_SND_S_NOT_SUPP : + rc = -EOPNOTSUPP ; +break ; +case VIRTIO_SND_S_IO_ERR : + rc = -EIO ; +break ; +default : + rc = -EINVAL ; +break ; + } + } } - - goto on_exit; - } - -if (READ_ONCE (msg->cancelled)) { - rc = -ENODEV ; - goto on_exit; - } - -switch (le32_to_cpu (response->code)) { -case VIRTIO_SND_S_OK : - rc =0 ; -break ; -case VIRTIO_SND_S_NOT_SUPP : - rc = -EOPNOTSUPP ; -break ; -case VIRTIO_SND_S_IO_ERR : - rc = -EIO ; -break ; -default : - rc = -EINVAL ; -break ; } -on_exit: +/* Drop the reference consumed by this send attempt. */ virtsnd_ctl_msg_unref (msg);return rc;
@@ -308,10 +438,23 @@ int virtsnd_ctl_query_info(struct virtio_snd *snd, int command, int start_id, {struct virtio_snd_msg *msg;struct virtio_snd_query_info *query; -struct scatterlist sg; +size_t info_size; +int rc; + +if (count <0 ) +return -EINVAL ; + +if (size >UINT_MAX || +check_mul_overflow ((size_t )count, size, &info_size) || + info_size >UINT_MAX ) +return -EOVERFLOW ; + +if (info_size && !info) +return -EINVAL ; msg =virtsnd_ctl_msg_alloc (sizeof (*query), -sizeof (struct virtio_snd_hdr ),GFP_KERNEL ); +sizeof (struct virtio_snd_hdr ),0 , info_size, +GFP_KERNEL );if (!msg)return -ENOMEM ;
@@ -321,9 +464,13 @@ int virtsnd_ctl_query_info(struct virtio_snd *snd, int command, int start_id, query->count =cpu_to_le32 (count); query->size =cpu_to_le32 (size); -sg_init_one (&sg, info, count * size); +virtsnd_ctl_msg_ref (msg); + rc =virtsnd_ctl_msg_send (snd, msg, false); +if (!rc && info_size) +memcpy (info,virtsnd_ctl_msg_response_data (msg), info_size); +virtsnd_ctl_msg_unref (msg); -return virtsnd_ctl_msg_send (snd, msg,NULL , &sg, false); +return rc; }/**
sound/virtio/virtio_ctl_msg.h +16 -8
@@ -21,20 +21,28 @@ void *virtsnd_ctl_msg_request(struct virtio_snd_msg *msg);void *virtsnd_ctl_msg_response (struct virtio_snd_msg *msg);struct virtio_snd_msg *virtsnd_ctl_msg_alloc (size_t request_size, -size_t response_size,gfp_t gfp); +size_t response_size, +size_t request_data_size, +size_t response_data_size, +gfp_t gfp); + +void *virtsnd_ctl_msg_request_data (struct virtio_snd_msg *msg); + +void *virtsnd_ctl_msg_response_data (struct virtio_snd_msg *msg);int virtsnd_ctl_msg_send (struct virtio_snd *snd,struct virtio_snd_msg *msg, -struct scatterlist *out_sgs, -struct scatterlist *in_sgs,bool nowait); +bool nowait);/** * virtsnd_ctl_msg_send_sync() - Simplified sending of synchronous message. * @snd: VirtIO sound device. * @msg: Control message. * -* After returning from this function, the message will be deleted. If message -* content is still needed, the caller must additionally to -* virtsnd_ctl_msg_ref/unref() it. +* This function consumes the caller's message reference on return. A message +* accepted by the control queue keeps its queue reference until completion or +* post-reset cleanup, including when this function returns on timeout or +* interruption. Callers that read the response after success must retain an +* additional reference through that access. * * The msg_timeout_ms module parameter defines the message completion timeout. * If the message is not completed within this time, the function will return an
@@ -49,7 +57,7 @@ int virtsnd_ctl_msg_send(struct virtio_snd *snd, struct virtio_snd_msg *msg,static inline int virtsnd_ctl_msg_send_sync (struct virtio_snd *snd,struct virtio_snd_msg *msg) { -return virtsnd_ctl_msg_send (snd, msg,NULL ,NULL , false); +return virtsnd_ctl_msg_send (snd, msg, false); }/**
@@ -63,7 +71,7 @@ static inline int virtsnd_ctl_msg_send_sync(struct virtio_snd *snd,static inline int virtsnd_ctl_msg_send_async (struct virtio_snd *snd,struct virtio_snd_msg *msg) { -return virtsnd_ctl_msg_send (snd, msg,NULL ,NULL , true); +return virtsnd_ctl_msg_send (snd, msg, true); }void virtsnd_ctl_msg_cancel_all (struct virtio_snd *snd);
sound/virtio/virtio_kctl.c +57 -47
173 lines not on this page · raw message
sound/virtio/virtio_pcm_msg.c +1 -1
@@ -671,7 +671,7 @@ virtsnd_pcm_ctl_msg_alloc(struct virtio_pcm_substream *vss,break ; } - msg =virtsnd_ctl_msg_alloc (request_size, response_size, gfp); + msg =virtsnd_ctl_msg_alloc (request_size, response_size,0 ,0 , gfp);if (msg) {struct virtio_snd_pcm_hdr *hdr =virtsnd_ctl_msg_request (msg);
Signature · 1 line
2.54.0 (Apple Git-157)
[email protected]
AI reviewRe: [PATCH v3 1/5] ALSA: virtio: Propagate PCM send failures through ACK
In reply to Joonho LeeSashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
virtsnd_pcm_msg_send()can fail while queueing a transfer. Restore the failed message's length and notify the device about earlier messages queued by the same call, so they do not remain stranded.Propagate that failure through the indirect PCM transfer callback instead of discarding it. Commit the updated indirect state only after successful submission and stop further transfers when a send fails. Return an XRUN error to ALSA so the stream can recover.
Quoted 5 lines
Keep the polling feature path unchanged.
Fixes fe981e67568c ("ALSA: virtio: use ack callback")Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [PATCH v3 2/5] ALSA: virtio: Recover PCM state after a failed start
In reply to Joonho LeeSashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines
Capture trigger queues I/O messages before
PCM_START. If the START message cannot be allocated or sent, transfers may remain queued, and ALSA does not invoke the action undo callback for the failed trigger.Mark the stream stopped and disable transfers for every failed START path. Arm
runtime->stop_operatingsosync_stopreleases pending I/O and prevents prepare,hw_params, or START retries until release succeeds.The stopped flag is shared with ACK callbacks that can run without the ALSA stream lock. Protect every stopped access with
vss->lock. Read the pending message count under the same lock in open andhw_params. Insync_stop, decide whether RELEASE is needed and mark the stream stopped in one locked transition; leave it stopped when release or draining fails.
Quoted 6 lines
Always cancel elapsed-period work in
sync_stop, even when no RELEASE is needed.Fixes da76e9f3e43a ("ALSA: virtio: PCM substream operators")Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH v3 3/5] ALSA: virtio: Retain queued messages through device reset
In reply to Joonho LeeSashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines
Keep the control queue available through
snd_card_free()so close-time STOP and RELEASE commands can still be submitted. Block new control requests and mark pending messages canceled before reset, then release their queue references only after reset and queue deletion.
Quoted 8 lines
For PCM queues, detach each remaining virtqueue buffer after the device has stopped DMA and retire its message without reporting a normal completion. Detach all queues before deleting them so outstanding DMA mappings are unmapped and no token remains for a late device completion.
Fixes 9d45e514da88 ("ALSA: virtio: handling control messages")Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
[email protected]
AI reviewRe: [PATCH v3 4/5] ALSA: virtio: Keep PCM DMA buffers alive through device ownership
In reply to Joonho LeeSashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines
Retain references to the pages backing ALSA's vmalloc buffer until its queued I/O messages are freed. On NOMMU systems, use driver-owned memory for DMA and copy playback data before submission and capture data after completion, so ALSA buffer release cannot invalidate an active request.
Quoted 8 lines
Validate the PCM buffer and each period before building scatterlists. Clamp device-reported capture lengths to the message capacity before advancing the hardware pointer, preventing an oversized completion from accounting bytes beyond the buffer actually submitted.
Fixes f40a28679e0b ("ALSA: virtio: handling control and I/O messages for the PCM device")Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
[email protected]
AI reviewRe: [PATCH v3 5/5] ALSA: virtio: Keep control payloads alive through DMA completion
In reply to Joonho LeeSashiko has reviewed this patch and found no issues. It looks great!
Quoted 16 lines
Control requests can expose caller-owned payloads to the device after a synchronous send times out. Keep request and response headers and payloads in the reference-counted message so caller cleanup cannot invalidate DMA.
Keep the queue reference until device completion or post-reset cleanup, even when the caller times out or is interrupted. Consume the caller's reference on every send path, and let response readers retain an extra reference through copyout. Check payload sizes and allocation arithmetic before building the scatterlists.
A control value payload is also read by the CPU as a typed structure. DMA cacheline alignment alone does not guarantee the structure's CPU alignment. Align regions to the greater of the DMA cacheline and control-value type alignment, and reserve prefix slack from the buffer base so typed accesses remain aligned while scatterlist regions stay on cacheline boundaries.
Quoted 3 lines
Fixes 9d45e514da88 ("ALSA: virtio: handling control messages")Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Quoted 54 lines · Joonho Lee
A failed PCM start or a timed-out request can leave virtio-snd messages owned by the device after the caller returns. Retrying can then reuse pending messages, and freeing ALSA or control buffers can leave their addresses in a virtqueue.
This series fixes enqueue-error recovery and keeps the memory referenced by outstanding requests alive until completion or device reset. Reset also detaches unused descriptors before deleting the queues, releasing their DMA mappings and cancelling PCM messages without reporting them as completed audio.
Changes since v2, following the Sashiko AI review:
- Patch 2 protects all stopped-state accesses withvss->lock, includinghw_params, prepare, open, STOP andsync_stopcompletion. The RELEASE decision and stopped=true transition now share a critical section. Sleeping operations remain outside the spinlock.
- Patch 5 aligns every DMA region for both cache maintenance and typed CPU accesses, and removes the initial +1 offset. This handles coherent systems wheredma_get_cache_alignment()returns 1, as well as odd region lengths that could otherwise misalign later payloads.
- Patches 1, 3 and 4 are unchanged.Validation of the final v3 source:
- ARM64 W=1 module build and ARM32CONFIG_MMU=ndriver object build.
- Source-extracted ASan/UBSan PCM, control, reset, ACK and DMA lifetime regressions on macOS arm64. The v2 control allocator produces UBSan misalignment diagnostics; the v3 allocator passes typed header and request/response integer64 accesses with DMA alignments 1, 2, 4, 8, 32, 64 and 128.
- Deterministic stopped-state lock instrumentation catches unlocked v2 accesses and passes 73 lifecycle assertions for v3. It covers ACK failure, RELEASE failure/retry and ACK during RELEASE, and checks that blocking operations do not run with the spinlock held.The stopped-state test instruments extracted source; it is not KCSAN or an actual threaded kernel race test. NOMMU was compiled, not booted. Physical non-coherent DMA hardware and host microphone behavior were not tested by these regressions. The QEMU ARM64 KASAN fault/recovery runs reported in v2 have not been rerun for these v3 changes.
Reproducer source and instructions:
https://github.com/whatisyourname0/virtio-snd-reproducer/tree/3ee5c7c1e864dae50a127b0a25cd122532daa6deBased on sound.git for-next commit
8d70e364e866bdfca81eee24d0688fac9472cfb9.AI assistance was used for code changes, tests, review and patch text. Assisted-by trailers are included. Sashiko's findings were checked against the driver and covered by regressions before incorporating the fixes.
Previous series Message-ID:
<[email protected]>
Quoted 6 lines
Joonho Lee (5):
ALSA: virtio: Propagate PCM send failures through ACK
ALSA: virtio: Recover PCM state after a failed start
ALSA: virtio: Retain queued messages through device reset
ALSA: virtio: Keep PCM DMA buffers alive through device ownership
ALSA: virtio: Keep control payloads alive through DMA completion
Through a quick glance, the patches look OK, but they are a bit too heavy changes at this very late stage for the next merge window. I can take those for 7.4-rc1 if the virtio maintainer gives an ack, but otherwise postponed for 7.5.
Or, if you have some more urgent fixes to address some known issues, please cook a smaller patch that can be more easily digested.
thanks,
Takashi