ALSA: virtio: serialize PCM recovery and capture accounting
Subsystems (4)
v23 cover ALSA: virtio: serialize PCM recovery and capture accounting
This series updates PCM error recovery, queue ownership and capture accounting in virtio-snd. It also provides opt-in staged capture for backends whose completion lengths need explicit compatibility handling. The capture compatibility parameters remain disabled by default.
The previous series is at
https://lore.kernel.org/linux-sound/[email protected]/T/.
The v23 changes address the v22 automated review and a separate existing linked-buffer locking problem. Linked prepare now commits member states and driver admission under the group and member PCM locks. Suspended or disconnected members keep their states, and a canceled successful driver prepare returns an error to its caller. Failed prepares notify only the attempted prefix and do not generate a stop-timer event.
A separate core patch closes every linked member's buffer-access gate and takes buffer mutexes in the stable group order. The caller-first ordering and caller-only access gate are already present in the upstream base; this patch is distinct from the prepare-completion API change.
The failed-start patch owns the direction-independent error latch. The later recovery code keeps native pause admission closed when a linked resume rollback fails in PAUSED. Paused ordinary capture preserves the accounting-error XRUN path. Staged capture rejects unaligned application pointer deltas before changing policy or counters. The DMA lifetime and staged-capture commit messages now describe their full source changes.
The order separates the ALSA core APIs and existing linked-buffer fix, ACK propagation and failed-start recovery, message and control lifetime, teardown waits, opt-in capture compatibility, work priority, and option documentation. Each patch is represented by an independently checked cumulative source stage.
Validation used ARM64 QEMU with KASAN and lockdep. The eleven changed cumulative stages, 04 through 14, built with W=1 without compiler warnings or errors. Applying all fourteen patches in order reproduces every cumulative source stage and the exact final candidate.
A test PCM driver passed fourteen core scenarios, including linked success and partial failure, atomic and nonatomic locks, suspend and disconnect cancellation, overlapping DROP, an active sibling buffer access, parallel group actions, and old-generation ACK retirement. The stop-timer change was checked by source review; this run did not attach a timer client to count timer notifications.
The instrumented virtio-snd tests passed definite START and STOP rejection, RUNNING pause restoration, failed linked resume rollback, deferred group XRUN, DROP, prepare, real playback and capture I/O, and reopen in RW and MMAP modes. Actual SYNC_PTR calls checked rejected ACK rollback and unaligned ACK policy preservation. The alignment and invalid-accounting inputs are synthetic test geometry. A separate stage-07 test verified four START failure/recovery cases and failed playback drain termination.
The pure final driver passed ordinary and staged RW and MMAP recording.
Each configuration included a seventy-second capture. RW checked three
reopen cycles; MMAP checked RESET and a reopened stream. All fourteen
captured segments matched SHA256 values generated independently on the host from recorded QEMU sequence epochs. No KASAN or lockdep diagnostics were reported by the passing runs.
Additional tests used the same candidate with strict KCSAN and lockdep. The runtime selftest and an isolated positive-control race confirmed instrumentation. Fourteen core cases passed at both default and higher sampling rates. Twenty-four driver control and accounting assertions passed. Ordinary and staged RW/MMAP captures matched all fourteen independent signal segments, including RESET and reopen.
The KCSAN campaign did report an ARM64 saved-PSTATE race outside ALSA:copy_thread() races with spectre_v4_enable_task_mitigation(). I built the pristine base with the identical config and ran the same fork workload with all sound modules unloaded. It reproduced the original pair; the ARM64 source and compiled objects are identical between the two kernels. The report remains recorded, so this is not a globally KCSAN-clean result. No ARM64 change is included in this series.
Physical tests on macOS VZ used Scarlett 2i2 input 1 at 48 kHz. Direct ALSA RW and MMAP each recorded seventy seconds, with signal statistics checked against a simultaneous host capture. Pause/RESET, the first open after killing a running recorder, and capture after VM restart passed. These tests enabled all five compatibility options. They do not establish bit-exact physical sample continuity or Docker Desktop microphone support.
Two test-tool problems were corrected before the final runs: asynchronous ACK snapshots could evict a control-error record, and truncating an old capture file after START stalled the test client beyond its PCM ring. The final MMAP test prepares RAM before START and writes output after closing PCM. Source, config and data-oracle acceptance stayed unchanged.
Synthetic alignment checks do not represent an actual sub-byte capture device. The stop-timer change remains source-reviewed without an attached timer client. One-shot command rejection exercises a definite error path; uncertain control timeouts can still require device reset or reprobe. Heavy-load TCG scheduling limits remain outside this qualification.
The staged path and its backend compatibility options need maintainer review before they can be recommended for a production deployment.
PATCH v23 1/14 ALSA: pcm: mark stop-threshold accesses for capture policy sampling
The staged virtio-snd capture path needs to sample stop_threshold from completion context to distinguish free-running capture from bounded capture. Software parameters can update this field while capture runs.
Mark the runtime stop-threshold assignments with WRITE_ONCE and the proc status read with READ_ONCE. This pairs the assignments with the driver's staged-capture policy sampling.
These annotations do not provide a transaction for the entire sw_params update. The driver serializes its cached policy and accounting with its own substream lock.
---sound/core/oss/pcm_oss.c | 2 +-
sound/core/pcm.c | 3 ++- sound/core/pcm_native.c | 5 +++-- 3 files changed, 6 insertions(+), 4 deletions(-)
sound/core/oss/pcm_oss.c +1 -1
@@ -2958,7 +2958,7 @@ runtime->oss.mmap_bytes);#endif /* In mmap mode we never stop */ - runtime->stop_threshold = runtime->boundary; +WRITE_ONCE (runtime->stop_threshold, runtime->boundary);return 0 ; }
sound/core/pcm.c +2 -1
@@ -422,7 +422,8 @@snd_iprintf (buffer,"period_step: %u\n" , runtime->period_step);snd_iprintf (buffer,"avail_min: %lu\n" , runtime->control->avail_min);snd_iprintf (buffer,"start_threshold: %lu\n" , runtime->start_threshold); -snd_iprintf (buffer,"stop_threshold: %lu\n" , runtime->stop_threshold); +snd_iprintf (buffer,"stop_threshold: %lu\n" , +READ_ONCE (runtime->stop_threshold));snd_iprintf (buffer,"silence_threshold: %lu\n" , runtime->silence_threshold);snd_iprintf (buffer,"silence_size: %lu\n" , runtime->silence_size);snd_iprintf (buffer,"boundary: %lu\n" , runtime->boundary);
sound/core/pcm_native.c +3 -2
@@ -871,7 +871,7 @@ runtime->period_step =1 ; runtime->control->avail_min = runtime->period_size; runtime->start_threshold =1 ; - runtime->stop_threshold = runtime->buffer_size; +WRITE_ONCE (runtime->stop_threshold, runtime->buffer_size); runtime->silence_threshold =0 ; runtime->silence_size =0 ; runtime->boundary = runtime->buffer_size;
@@ -1062,7 +1062,8 @@ runtime->period_step = params->period_step; runtime->control->avail_min = params->avail_min; runtime->start_threshold = params->start_threshold; - runtime->stop_threshold = params->stop_threshold; +/* Drivers may sample the stop policy from completion context. */ +WRITE_ONCE (runtime->stop_threshold, params->stop_threshold); runtime->silence_threshold = params->silence_threshold; runtime->silence_size = params->silence_size; params->boundary = runtime->boundary;
[email protected]
AI reviewRe: [PATCH v23 01/14] ALSA: pcm: mark stop-threshold accesses for capture policy sampling
Sashiko has reviewed this patch and found no issues.
Quoted 8 lines
The staged virtio-snd capture path needs to sample
stop_thresholdfrom completion context to distinguish free-running capture from bounded capture. Software parameters can update this field while capture runs.Mark the runtime stop-threshold assignments with
WRITE_ONCEand the proc status read withREAD_ONCE. This pairs the assignments with the driver's staged-capture policy sampling.
Quoted 6 lines
These annotations do not provide a transaction for the entire
sw_paramsupdate. The driver serializes its cached policy and accounting with its own substream lock.Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v23 2/14 ALSA: pcm: report partial progress under the stream lock
In reply to Joonho LeeStaged capture can make readable data available before a complete period has elapsed. Skipping notification leaves a blocked reader asleep, while using the period-interrupt path for this event can infer a false ring wrap when the notification is delayed.
Add snd_pcm_progress_under_stream_lock() to update the hardware pointer through the non-interrupt path and notify readers and fasync listeners. It runs under the caller's PCM stream lock and does not tick the PCM timer. The driver must release its pointer and trigger locks before calling it. Existing period notification callers keep their current behavior.
---include/sound/pcm.h | 1 +
sound/core/pcm_lib.c | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+)
include/sound/pcm.h +1 -0
@@ -1182,6 +1182,7 @@int snd_pcm_lib_ioctl (struct snd_pcm_substream *substream,unsigned int cmd,void *arg);void snd_pcm_period_elapsed_under_stream_lock (struct snd_pcm_substream *substream); +void snd_pcm_progress_under_stream_lock (struct snd_pcm_substream *substream);void snd_pcm_period_elapsed (struct snd_pcm_substream *substream); snd_pcm_sframes_t __snd_pcm_lib_xfer(struct snd_pcm_substream *substream, void *buf, bool interleaved,
sound/core/pcm_lib.c +19 -0
@@ -1919,6 +1919,25 @@EXPORT_SYMBOL (snd_pcm_period_elapsed_under_stream_lock);/** +* snd_pcm_progress_under_stream_lock - Report progress without a period IRQ +* @substream: PCM substream +* +* Context: PCM stream lock held, with no driver pointer or trigger locks held. +* Updates the pointer and wakes readers for partial-period transfers. Unlike +* a period notification, this does not imply an elapsed period or tick the PCM +* timer. The same pointer, trigger and timestamp callbacks may be invoked. +*/ +void snd_pcm_progress_under_stream_lock (struct snd_pcm_substream *substream) +{ +if (PCM_RUNTIME_CHECK (substream) || !snd_pcm_running (substream)) +return ; +snd_pcm_update_hw_ptr (substream); +snd_kill_fasync (substream->runtime->fasync,SIGIO ,POLL_IN ); +} +EXPORT_SYMBOL_GPL (snd_pcm_progress_under_stream_lock); + + +/** * snd_pcm_period_elapsed() - update the status of runtime for the next period by acquiring lock of * PCM substream. * @substream: the instance of PCM substream.
[email protected]
AI reviewRe: [PATCH v23 02/14] ALSA: pcm: report partial progress under the stream lock
Sashiko has reviewed this patch and found no issues.
Quoted 12 lines
Staged capture can make readable data available before a complete period has elapsed. Skipping notification leaves a blocked reader asleep, while using the period-interrupt path for this event can infer a false ring wrap when the notification is delayed.
Add
snd_pcm_progress_under_stream_lock()to update the hardware pointer through the non-interrupt path and notify readers and fasync listeners. It runs under the caller's PCM stream lock and does not tick the PCM timer. The driver must release its pointer and trigger locks before calling it. Existing period notification callers keep their current behavior.
Quoted 2 lines
Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v23 3/14 ALSA: pcm: add an optional reset operation under the stream lock
In reply to Joonho LeeA driver may need to synchronize private capture accounting with the common RESET pointer observation and the core's position rebase.
Add an optional reset operation called under the member's stream lock. Expose snd_pcm_lib_reset() so the callback can retain common pointer and time handling. On zero return the core completes that member's rebase before unlocking it. Drivers without the callback retain the ioctl path. The operation is also used after a successful prepare.
Zero permits the position rebase; it does not promise XRUN recovery. A negative return skips the core rebase, so a callback returning an error must leave coherent pointer state even after partial work.
Linked RESET and prepare stop at the first error without rollback. Earlier callback members may already have completed. Legacy members keep the existing post_action policy. Applications must recover the group after partial failure before relying on shared positions.
This adds an internal kernel operation and no userspace ioctl or layout. Out-of-tree modules using snd_pcm_ops need to be rebuilt.
Complete appl_ptr rebasing once in the callback path. A later linked member can sleep in prepare while the earlier member accepts SYNC_PTR; a subsequent unlocked post_prepare assignment would overwrite that acknowledgment. Keep explicit RESET playback silence processing and leave prepare-time filling to the normal START path, preserving samples written and rewound after prepare.
---include/sound/pcm.h | 21 +++++++++++++++++++++
sound/core/pcm_lib.c | 29 ++++++++++++++++++++++++----- sound/core/pcm_native.c | 45 ++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 85 insertions(+), 10 deletions(-)
include/sound/pcm.h +21 -0
@@ -77,6 +77,26 @@ unsigned long offset);int (*mmap)(struct snd_pcm_substream *substream,struct vm_area_struct *vma);int (*ack)(struct snd_pcm_substream *substream); +/* +* Optional RESET operation, also used after a successful prepare. +* Called with this substream's PCM lock held; atomic streams must not +* sleep. Do not reacquire the PCM lock through snd_pcm_lib_ioctl(). +* snd_pcm_lib_reset() provides the common pointer update under this +* lock. The core completes the position and appl_ptr rebase before +* unlocking a successful member. +* +* Return zero to let the core complete the position rebase. As with +* the legacy RESET ioctl, zero does not guarantee recovery from XRUN; +* callers must still handle the stream state and subsequent I/O errors. +* On a negative return the core does not finish the rebase, so the +* callback must leave coherent pointer state even after partial work. +* +* Linked RESET/prepare +* stops at the first error without rollback. Earlier callback members +* retain their completed reset; legacy members retain the existing +* post_action policy. An error does not guarantee unchanged state. +*/ +int (*reset)(struct snd_pcm_substream *substream); };/*
@@ -1179,6 +1199,7 @@ { substream->runtime->std_sync_id = true; } +int snd_pcm_lib_reset (struct snd_pcm_substream *substream);int snd_pcm_lib_ioctl (struct snd_pcm_substream *substream,unsigned int cmd,void *arg);void snd_pcm_period_elapsed_under_stream_lock (struct snd_pcm_substream *substream);
sound/core/pcm_lib.c +24 -5
@@ -1760,20 +1760,39 @@ }EXPORT_SYMBOL (snd_pcm_hw_params_bits); -static int snd_pcm_lib_ioctl_reset (struct snd_pcm_substream *substream, -void *arg) +/** +* snd_pcm_lib_reset - Reset the pointer while holding the PCM stream lock +* @substream: PCM substream +* +* Context: PCM stream lock held. The caller must not hold driver locks +* acquired by the pointer or XRUN callbacks. +* +* Update a running stream through the ordinary pointer path. Other states +* start at zero. Pointer errors keep the existing RESET return semantics; +* a zero return does not imply recovery from XRUN. +* This helper does not update appl_ptr or acquire the stream lock. +* +* Return: zero. +*/ +int snd_pcm_lib_reset (struct snd_pcm_substream *substream) {struct snd_pcm_runtime *runtime = substream->runtime; -guard (pcm_stream_lock_irqsave)(substream); -if (snd_pcm_running (substream) && -snd_pcm_update_hw_ptr (substream) >=0 ) +if (snd_pcm_running (substream) &&snd_pcm_update_hw_ptr (substream) >=0 ) runtime->status->hw_ptr %= runtime->buffer_size;else { runtime->status->hw_ptr =0 ; runtime->hw_ptr_wrap =0 ; }return 0 ; +} +EXPORT_SYMBOL (snd_pcm_lib_reset); + +static int snd_pcm_lib_ioctl_reset (struct snd_pcm_substream *substream, +void *arg) +{ +guard (pcm_stream_lock_irqsave)(substream); +return snd_pcm_lib_reset (substream); } static int snd_pcm_lib_ioctl_channel_info(struct snd_pcm_substream *substream,
sound/core/pcm_native.c +40 -5
75 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v23 03/14] ALSA: pcm: add an optional reset operation under the stream lock
Sashiko has reviewed this patch and found no issues.
Quoted 28 lines
A driver may need to synchronize private capture accounting with the common RESET pointer observation and the core's position rebase.
Add an optional reset operation called under the member's stream lock. Expose
snd_pcm_lib_reset()so the callback can retain common pointer and time handling. On zero return the core completes that member's rebase before unlocking it. Drivers without the callback retain the ioctl path. The operation is also used after a successful prepare.Zero permits the position rebase; it does not promise XRUN recovery. A negative return skips the core rebase, so a callback returning an error must leave coherent pointer state even after partial work.
Linked RESET and prepare stop at the first error without rollback. Earlier callback members may already have completed. Legacy members keep the existing
post_actionpolicy. Applications must recover the group after partial failure before relying on shared positions.This adds an internal kernel operation and no userspace ioctl or layout. Out-of-tree modules using
snd_pcm_opsneed to be rebuilt.Complete
appl_ptrrebasing once in the callback path. A later linked member can sleep in prepare while the earlier member acceptsSYNC_PTR; a subsequent unlockedpost_prepareassignment would overwrite that acknowledgment. Keep explicit RESET playback silence processing and leave prepare-time filling to the normal START path, preserving samples written and rewound after prepare.
Quoted 2 lines
Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
PATCH v23 4/14 ALSA: pcm: notify drivers after linked prepare completes
In reply to Joonho LeeA linked prepare can finish one member before another member's driver prepare or reset fails. Drivers that admit transfers after their own prepare callback can then accept an ACK while the group action is still incomplete.
Add an optional prepare_complete callback. After all sleeping prepare and reset actions have succeeded, take the group and member PCM locks, publish every PREPARED state, and notify opted-in drivers before releasing those locks. Keep the buffer locks and access gates held throughout the operation. A concurrent DROP observes the group before or after this commit point.
On a driver error, notify only the attempted prefix, including the failing member. Opted-in members in that prefix return to SETUP. Leave unreached members untouched. Preflight failures have no completion callback. Preserve SUSPENDED and DISCONNECTED states if finalization finds either in the affected group or prefix. Successful driver actions canceled by such a state return -ESTRPIPE or -EBADFD, respectively. A driver error keeps its original return value. DISCONNECTED takes precedence when a linked group contains both terminal states.
Do not generate a stop-timer event while closing prepare admission. Ordinary legacy drivers keep their existing successful preparation and pointer rebasing. The new callback runs with the group and member locks held and must neither sleep nor acquire another PCM stream lock.
---include/sound/pcm.h | 17 +++++
sound/core/pcm_native.c | 152 +++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 149 insertions(+), 20 deletions(-)
include/sound/pcm.h +17 -0
@@ -77,6 +77,23 @@ unsigned long offset);int (*mmap)(struct snd_pcm_substream *substream,struct vm_area_struct *vma);int (*ack)(struct snd_pcm_substream *substream); +/* +* Optional prepare completion notification. Called while the core holds +* all linked PCM stream locks, after prepare/reset actions succeed or stop +* at the first error. On success, the core publishes PREPARED for every +* member before calling this with true. If any member is DISCONNECTED or +* SUSPENDED, all states are preserved and opted-in members receive false. +* On failure, called with false for opted-in members whose action ran, +* including the failing member. Their state becomes SETUP unless any member +* in that prefix is DISCONNECTED or SUSPENDED; then all prefix states are +* preserved. Members not reached and pre-action failures receive no +* callback. Standalone RESET does not call this callback. It must not sleep +* or acquire another PCM stream lock. +* A terminal-state cancellation returns -EBADFD for DISCONNECTED or +* -ESTRPIPE for SUSPENDED. +*/ +void (*prepare_complete)(struct snd_pcm_substream *substream, +bool success);/* * Optional RESET operation, also used after a successful prepare. * Called with this substream's PCM lock held; atomic streams must not
sound/core/pcm_native.c +132 -20
217 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v23 04/14] ALSA: pcm: notify drivers after linked prepare completes
Sashiko has reviewed this patch and found no issues.
Quoted 21 lines
A linked prepare can finish one member before another member's driver prepare or reset fails. Drivers that admit transfers after their own prepare callback can then accept an ACK while the group action is still incomplete.
Add an optional
prepare_completecallback. After all sleeping prepare and reset actions have succeeded, take the group and member PCM locks, publish every PREPARED state, and notify opted-in drivers before releasing those locks. Keep the buffer locks and access gates held throughout the operation. A concurrent DROP observes the group before or after this commit point.On a driver error, notify only the attempted prefix, including the failing member. Opted-in members in that prefix return to SETUP. Leave unreached members untouched. Preflight failures have no completion callback. Preserve SUSPENDED and DISCONNECTED states if finalization finds either in the affected group or prefix. Successful driver actions canceled by such a state return
-ESTRPIPEor-EBADFD, respectively. A driver error keeps its original return value. DISCONNECTED takes precedence when a linked group contains both terminal states.
Quoted 7 lines
Do not generate a stop-timer event while closing prepare admission. Ordinary legacy drivers keep their existing successful preparation and pointer rebasing. The new callback runs with the group and member locks held and must neither sleep nor acquire another PCM stream lock.
Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
PATCH v23 5/14 ALSA: pcm: serialize linked buffer actions
In reply to Joonho LeeConcurrent non-atomic actions on different members of a linked PCM group currently lock their own buffer first, then the other members. That acquisition order can differ between callers. Sibling buffer mutexes also do not close their buffer-access admission counters.
Close buffer access for every member before taking any buffer mutex, and acquire those mutexes in the stable linked-list order while group membership is protected. Release every access gate on success and on failure, including when a member already has an active buffer access. The group action then uses the buffers already held by its caller.
The PCM stream and group locks are not held across sleeping driver prepare callbacks. Single-stream non-atomic actions keep their existing buffer-access locking path.
---sound/core/pcm_native.c | 71 +++++++++++++++++++++++++++++++++++++----------
1 file changed, 56 insertions(+), 15 deletions(-)
sound/core/pcm_native.c +56 -15
@@ -731,6 +731,44 @@ {mutex_unlock (&runtime->buffer_mutex);atomic_inc (&runtime->buffer_accessing); +} + +/* Gate all linked buffers before taking their mutexes in group-list order. */ +static int snd_pcm_group_buffer_access_lock (struct snd_pcm_substream *substream) +{ +struct snd_pcm_substream *s, *s1; +int depth =0 ; + +snd_pcm_group_for_each_entry (s, substream) { +if (!atomic_dec_unless_positive (&s->runtime->buffer_accessing)) { +snd_pcm_group_for_each_entry (s1, substream) { +if (s1 == s) +break ; +atomic_inc (&s1->runtime->buffer_accessing); + } +return -EBUSY ; + } + } + +snd_pcm_group_for_each_entry (s, substream) { +if (depth ==0 ) +mutex_lock (&s->runtime->buffer_mutex); +else +mutex_lock_nested (&s->runtime->buffer_mutex, depth); + depth++; + } + +return 0 ; +} + +static void snd_pcm_group_buffer_access_unlock (struct snd_pcm_substream *substream) +{ +struct snd_pcm_substream *s; + +list_for_each_entry_reverse (s, &substream->group->substreams, link_list) +mutex_unlock (&s->runtime->buffer_mutex); +snd_pcm_group_for_each_entry (s, substream) +atomic_inc (&s->runtime->buffer_accessing); }/* fill the PCM buffer with the current silence format; called from pcm_oss.c */
@@ -1317,9 +1355,9 @@ };/* -* this functions is core for handling of linked stream -* Note: the stream state might be changed also on failure -* Note2: call with calling stream lock + link lock +* Handle an action on all linked streams. +* When stream_lock is true, the caller holds the calling stream and group +* locks. Otherwise, the caller holds link_rwsem and every group buffer_mutex. */ static int snd_pcm_action_group(const struct action_ops *ops, struct snd_pcm_substream *substream,
@@ -1331,10 +1369,8 @@int res =0 , depth =1 ;snd_pcm_group_for_each_entry (s, substream) { -if (s != substream) { -if (!stream_lock) -mutex_lock_nested (&s->runtime->buffer_mutex, depth); -else if (s->pcm->nonatomic) +if (s != substream && stream_lock) { +if (s->pcm->nonatomic)mutex_lock_nested (&s->self_group.mutex, depth);else spin_lock_nested (&s->self_group.lock, depth);
@@ -1371,10 +1407,8 @@ _unlock:/* unlock streams */ snd_pcm_group_for_each_entry (s1, substream) { -if (s1 != substream) { -if (!stream_lock) -mutex_unlock (&s1->runtime->buffer_mutex); -else if (s1->pcm->nonatomic) +if (s1 != substream && stream_lock) { +if (s1->pcm->nonatomic)mutex_unlock (&s1->self_group.mutex);else spin_unlock (&s1->self_group.lock);
@@ -1512,18 +1546,25 @@struct snd_pcm_substream *substream, snd_pcm_state_t state) { + bool linked;int res;/* Guarantee the group members won't change during non-atomic action */ guard (rwsem_read)(&snd_pcm_link_rwsem); - res =snd_pcm_buffer_access_lock (substream->runtime); + linked =snd_pcm_stream_linked (substream); +if (linked) + res =snd_pcm_group_buffer_access_lock (substream); +else + res =snd_pcm_buffer_access_lock (substream->runtime);if (res <0 )return res; -if (snd_pcm_stream_linked (substream)) +if (linked) { res =snd_pcm_action_group (ops, substream, state, false); -else +snd_pcm_group_buffer_access_unlock (substream); + }else { res =snd_pcm_action_single (ops, substream, state, false); -snd_pcm_buffer_access_unlock (substream->runtime); +snd_pcm_buffer_access_unlock (substream->runtime); + }return res; }
[email protected]
AI reviewRe: [PATCH v23 05/14] ALSA: pcm: serialize linked buffer actions
Sashiko has reviewed this patch and found no issues.
Quoted 11 lines
Concurrent non-atomic actions on different members of a linked PCM group currently lock their own buffer first, then the other members. That acquisition order can differ between callers. Sibling buffer mutexes also do not close their buffer-access admission counters.
Close buffer access for every member before taking any buffer mutex, and acquire those mutexes in the stable linked-list order while group membership is protected. Release every access gate on success and on failure, including when a member already has an active buffer access. The group action then uses the buffers already held by its caller.
Quoted 8 lines
The PCM stream and group locks are not held across sleeping driver prepare callbacks. Single-stream non-atomic actions keep their existing buffer-access locking path.
Fixes 3c3201f8c7bb ("ALSA: pcm: Fix races among concurrent prepare and hw_params/hw_free calls")Fixes bc55cfd5718c ("ALSA: pcm: Fix potential AB/BA lock with buffer_mutex and mmap_lock")Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
PATCH v23 6/14 ALSA: virtio: propagate PCM send failures through ACK
In reply to Joonho LeeA failed queue submission can strand earlier messages from the same ACK. Restore the failed message length, notify any earlier queued messages, and propagate the failure through the indirect transfer callback. Commit its private cursor only after successful submission.
Keep ACK admission closed across the linked prepare action and publish the prepared state from the new prepare-completion callback. On failure, leave the stream unprepared and reopen admission only after the core reports completion.
Once the PCM core has moved a member to XRUN, return -EBADFD from a later ACK so it does not request a second linked-group XRUN. ACK during prepare remains rejected until the completion callback.
---sound/virtio/virtio_pcm.h | 6 +
sound/virtio/virtio_pcm_msg.c | 12 ++ sound/virtio/virtio_pcm_ops.c | 249 +++++++++++++++++++++++++++++++++++++---- 3 files changed, 241 insertions(+), 26 deletions(-)
sound/virtio/virtio_pcm.h +6 -0
@@ -33,6 +33,10 @@* @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. +* @prepared: True after device PREPARE and the core pointer reset succeed; +* protected by @lock. +* @preparing: ACK gate through teardown and prepare's core reset; +* 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.
@@ -56,6 +60,8 @@bool xfer_enabled;bool xfer_xrun;bool stopped; +bool prepared; +bool preparing;bool suspended;struct virtio_pcm_msg **msgs;unsigned int nmsgs;
sound/virtio/virtio_pcm_msg.c +12 -0
@@ -260,6 +260,18 @@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 +223 -26
381 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v23 06/14] ALSA: virtio: propagate PCM send failures through ACK
Sashiko has reviewed this patch and found no issues.
Quoted 10 lines
A failed queue submission can strand earlier messages from the same ACK. Restore the failed message length, notify any earlier queued messages, and propagate the failure through the indirect transfer callback. Commit its private cursor only after successful submission.
Keep ACK admission closed across the linked prepare action and publish the prepared state from the new prepare-completion callback. On failure, leave the stream unprepared and reopen admission only after the core reports completion.
Quoted 7 lines
Once the PCM core has moved a member to XRUN, return
-EBADFDfrom a later ACK so it does not request a second linked-group XRUN. ACK during prepare remains rejected until the completion callback.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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
PATCH v23 7/14 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.
Latch a transfer XRUN in both playback and capture, and schedule the existing period worker so a running or draining core stream sees the pointer error. This also retires a failed playback START during drain, where drain-init can already have advanced the core state to DRAINING.
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.
Record the RELEASE obligation after successful PREPARE and clear it as soon as RELEASE succeeds. If the subsequent RX wait fails, retry that wait without submitting RELEASE again.
---sound/virtio/virtio_pcm.h | 6 +-
sound/virtio/virtio_pcm_ops.c | 113 +++++++++++++++++++++++++++++++---------- 2 files changed, 89 insertions(+), 30 deletions(-)
sound/virtio/virtio_pcm.h +4 -2
@@ -26,13 +26,13 @@* @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. * @prepared: True after device PREPARE and the core pointer reset succeed; * protected by @lock. * @preparing: ACK gate through teardown and prepare's core reset;
@@ -62,6 +62,8 @@bool stopped;bool prepared;bool preparing; +/* Successful PREPARE still needs RELEASE; protected by lock. */ +bool release_required;bool suspended;struct virtio_pcm_msg **msgs;unsigned int nmsgs;
sound/virtio/virtio_pcm_ops.c +85 -28
189 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v23 07/14] ALSA: virtio: Recover PCM state after a failed start
Sashiko has reviewed this patch and found no issues.
Quoted 23 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.Latch a transfer XRUN in both playback and capture, and schedule the existing period worker so a running or draining core stream sees the pointer error. This also retires a failed playback START during drain, where drain-init can already have advanced the core state to DRAINING.
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.Always cancel elapsed-period work in
sync_stop, even when no RELEASE is needed.
Quoted 7 lines
Record the RELEASE obligation after successful PREPARE and clear it as soon as RELEASE succeeds. If the subsequent RX wait fails, retry that wait without submitting RELEASE again.
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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
PATCH v23 8/14 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.
Protect event callback admission with the event queue lock. Disabling events waits for an active dispatch, and later callbacks see a closed gate before ALSA objects are freed. Enable and pending-event draining share the same lock.
Reclaim pending event buffers after a failed probe without dispatching notifications into ALSA objects that have not been constructed. Record the queue's prior enabled state under its lock before closing admission.
Track successful virtqueue initialization so teardown and failed restore cleanup call del_vqs() only for an initialized queue set.
---sound/virtio/virtio_card.c | 110 ++++++++++++++++++++++++++++++++---------
sound/virtio/virtio_card.h | 6 ++ sound/virtio/virtio_ctl_msg.c | 64 +++++++++++++++++++++--- sound/virtio/virtio_ctl_msg.h | 4 + sound/virtio/virtio_pcm.h | 2 + sound/virtio/virtio_pcm_msg.c | 42 ++++++++++++++-- 6 files changed, 193 insertions(+), 35 deletions(-)
sound/virtio/virtio_card.c +86 -24
@@ -70,23 +70,13 @@ } } -/** -* virtsnd_event_notify_cb() - Dispatch all reported events from the event queue. -* @vqueue: Underlying event virtqueue. -* -* This callback function is called upon a vring interrupt request from the -* device. -* -* Context: Interrupt context. -*/ -static void virtsnd_event_notify_cb (struct virtqueue *vqueue) -{ -struct virtio_snd *snd = vqueue->vdev->priv; -struct virtio_snd_queue *queue =virtsnd_event_queue (snd); +static void virtsnd_event_drain_locked (struct virtio_snd *snd, +struct virtqueue *vqueue) +{struct virtio_snd_event *event;u32 length; -guard (spinlock_irqsave)(&queue->lock); +lockdep_assert_held (&virtsnd_event_queue (snd)->lock); do { virtqueue_disable_cb(vqueue); while ((event = virtqueue_get_buf(vqueue, &length))) {
@@ -94,6 +84,26 @@virtsnd_event_send (vqueue, event, true,GFP_ATOMIC ); } }while (!virtqueue_enable_cb (vqueue)); +} + +/** +* virtsnd_event_notify_cb() - Dispatch all reported events from the event queue. +* @vqueue: Underlying event virtqueue. +* +* This callback function is called upon a vring interrupt request from the +* device. +* +* Context: Interrupt context. +*/ +static void virtsnd_event_notify_cb (struct virtqueue *vqueue) +{ +struct virtio_snd *snd = vqueue->vdev->priv; +struct virtio_snd_queue *queue =virtsnd_event_queue (snd); + +guard (spinlock_irqsave)(&queue->lock); +if (queue->vqueue != vqueue || !snd->event_vq_enabled) +return ; +virtsnd_event_drain_locked (snd, vqueue); }/**
@@ -131,6 +141,7 @@for (i =0 ; i <VIRTIO_SND_VQ_MAX ; ++i) snd->queues[i].vqueue = vqs[i]; + snd->vqs_initialized = true;/* Allocate events and populate the event queue */ virtqueue_disable_cb (vqs[VIRTIO_SND_VQ_EVENT ]);
@@ -158,8 +169,12 @@ {struct virtio_snd_queue *queue =virtsnd_event_queue (snd); +guard (spinlock_irqsave)(&queue->lock); +if (!queue->vqueue) +return ; + snd->event_vq_enabled = true;if (!virtqueue_enable_cb (queue->vqueue)) -virtsnd_event_notify_cb (queue->vqueue); +virtsnd_event_drain_locked (snd, queue->vqueue); }/**
@@ -172,13 +187,19 @@ {struct virtio_snd_queue *queue =virtsnd_event_queue (snd);struct virtio_snd_event *event; +bool dispatch_events;u32 length; +guard (spinlock_irqsave)(&queue->lock); + dispatch_events = snd->event_vq_enabled; + snd->event_vq_enabled = false;if (queue->vqueue) { -guard (spinlock_irqsave)(&queue->lock);virtqueue_disable_cb (queue->vqueue); -while ((event =virtqueue_get_buf (queue->vqueue, &length))) -virtsnd_event_dispatch (snd, event); +while ((event =virtqueue_get_buf (queue->vqueue, &length))) { +/* Reclaim used buffers even when failed probe cannot dispatch. */ +if (dispatch_events) +virtsnd_event_dispatch (snd, event); + } } }
@@ -338,6 +359,43 @@ }/** +* 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); +if (i ==VIRTIO_SND_VQ_EVENT ) + snd->event_vq_enabled = false; +/* IRQ callbacks must never see a detached ring as live. */ + queue->vqueue =NULL ; +spin_unlock_irqrestore (&queue->lock, flags); + } + +if (snd->vqs_initialized) { + vdev->config->del_vqs (vdev); + snd->vqs_initialized = false; + } +} + +/** * virtsnd_remove() - Remove VirtIO and ALSA devices. * @vdev: VirtIO parent device. *
@@ -349,13 +407,14 @@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 +442,8 @@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);
@@ -408,10 +467,13 @@int rc; rc =virtsnd_find_vqs (snd); -if (rc) +if (rc) { +virtsnd_reset_vqs (snd);return rc; + }virtio_device_ready (vdev); +virtsnd_ctl_msg_enable (snd);virtsnd_enable_event_vq (snd);
sound/virtio/virtio_card.h +6 -0
@@ -45,8 +45,11 @@* struct virtio_snd - VirtIO sound card device. * @vdev: Underlying virtio device. * @queues: Virtqueue wrappers. +* @vqs_initialized: Virtqueues allocated by virtio_find_vqs(). * @card: ALSA sound card. * @ctl_msgs: Pending control request list. +* @ctl_msgs_blocked: Control requests are blocked during teardown or suspend. +* @event_vq_enabled: Event callbacks may dispatch, protected by the event queue lock. * @event_msgs: Device events. * @pcm_list: VirtIO PCM device list. * @jacks: VirtIO jacks.
@@ -62,8 +65,11 @@struct virtio_snd {struct virtio_device *vdev;struct virtio_snd_queue queues[VIRTIO_SND_VQ_MAX ]; +bool vqs_initialized;struct snd_card *card;struct list_head ctl_msgs; +bool ctl_msgs_blocked; +bool event_vq_enabled;struct virtio_snd_event *event_msgs;struct list_head pcm_list;struct virtio_jack *jacks;
sound/virtio/virtio_ctl_msg.c +57 -7
130 lines not on this page · raw message
sound/virtio/virtio_ctl_msg.h +4 -0
@@ -68,6 +68,10 @@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
@@ -128,6 +128,8 @@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 +38 -4
74 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v23 08/14] ALSA: virtio: Retain queued messages through device reset
Sashiko has reviewed this patch and found no issues.
Quoted 19 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.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.
Protect event callback admission with the event queue lock. Disabling events waits for an active dispatch, and later callbacks see a closed gate before ALSA objects are freed. Enable and pending-event draining share the same lock.
Reclaim pending event buffers after a failed probe without dispatching notifications into ALSA objects that have not been constructed. Record the queue's prior enabled state under its lock before closing admission.
Quoted 6 lines
Track successful virtqueue initialization so teardown and failed restore cleanup call
del_vqs()only for an initialized queue set.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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
PATCH v23 9/14 ALSA: virtio: bound PCM transfers and retain DMA buffers
In reply to Joonho LeeA successful ACK must describe bytes that fit both the PCM ring and the transport queue. Validate playback boundary wrap, frame alignment, conversion bounds, ring offsets, signed ready counters and the combined queued-byte budget before the indirect helper changes accounting. Validate ordinary capture acknowledgments against completed unread RX bytes and reject consumption before the first RX ring is submitted.
Retain references to vmalloc PCM pages until their message descriptors are retired, including when a timed-out teardown releases the runtime mapping. Non-MMU ordinary transfers use driver-owned bounce buffers. Release these allocations with the message generation that owns them.
Check period and buffer geometry when applying hardware parameters, reject out-of-range send offsets and lengths, and validate RX response status and payload lengths before advancing the capture position. Preserve completed capture tails during drain and report transfer failures through the existing ACK and pointer error paths.
---
sound/virtio/virtio_pcm.h | 13 ++ sound/virtio/virtio_pcm_msg.c | 303 +++++++++++++++++++++++++++++++++++------ sound/virtio/virtio_pcm_ops.c | 213 ++++++++++++++++++++++++++++- 3 files changed, 478 insertions(+), 51 deletions(-)
sound/virtio/virtio_pcm.h +13 -0
@@ -13,6 +13,7 @@struct virtio_pcm ;struct virtio_pcm_msg ; +struct page ;/** * struct virtio_pcm_substream - VirtIO PCM substream.
@@ -29,6 +30,7 @@* substream operators, including @stopped. * @buffer_bytes: Current buffer size in bytes. * @hw_ptr: Substream hardware pointer value in bytes [0 ... buffer_bytes). +* @capture_rx_seeded: Ordinary capture ring was queued since prepare. * @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
@@ -42,6 +44,10 @@* @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 {
@@ -57,6 +63,7 @@spinlock_t lock;size_t buffer_bytes;size_t hw_ptr; +bool capture_rx_seeded;bool xfer_enabled;bool xfer_xrun;bool stopped;
@@ -68,6 +75,12 @@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 +261 -42
417 lines not on this page · raw message
sound/virtio/virtio_pcm_ops.c +204 -9
260 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v23 09/14] ALSA: virtio: bound PCM transfers and retain DMA buffers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] ALSA: virtio: partial RX on stop latches XRUN in virtsnd_pcm_msg_complete() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] ALSA: virtio: partial RX on stop latches XRUN in virtsnd_pcm_msg_complete()
--
commit 8701e733a8297edcfeb307fc6817693d437f58dc
Author: Joonho Lee <[email protected]>
ALSA: virtio: bound PCM transfers and retain DMA buffers
This commit validates PCM buffer geometry, ACK transfer bounds, and RX completions while retaining backing DMA pages until virtqueue messages are freed.
Quoted 4 lines
sound/virtio/virtio_pcm_msg.c +0
-0
[ ... ]
Quoted 38 lines
sound/virtio/virtio_pcm_msg.c +15
-14@@ -356,42 +536,81 @@ static void virtsnd_pcm_msg_complete(struct virtio_pcm_msg *msg, size_t written_bytes) {struct virtio_pcm_substream *vss = msg->substream; +bool capture_invalid = false;/* -* hw_ptr always indicates the buffer position of the first I/O message -* in the virtqueue. Therefore, on each completion of an I/O message, -* the hw_ptr value is unconditionally advanced. +* Completed requests can return captured data after STOP while the PCM +* buffer remains prepared. Once preparation ends, completions only retire +* queue ownership. */ guard (spinlock)(&vss->lock); -/* -* If the capture substream returned an incorrect status, then just -* increase the hw_ptr by the message size. -*/ -if (vss->direction ==SNDRV_PCM_STREAM_PLAYBACK || - written_bytes <=sizeof (msg->status)) - vss->hw_ptr += msg->length; -else - vss->hw_ptr += written_bytes -sizeof (msg->status); +if (vss->direction ==SNDRV_PCM_STREAM_CAPTURE && + (!vss->prepared || vss->xfer_xrun || + (vss->stopped && written_bytes <=sizeof (msg->status)))) { + msg->length =0 ; + vss->msg_count--; +if (!vss->msg_count) +wake_up_all (&vss->msg_empty); +return ; + } -if (vss->hw_ptr >= vss->buffer_bytes) - vss->hw_ptr -= vss->buffer_bytes; +/* Only the next complete ring slice can extend captured data. */ + if (vss->direction == SNDRV_PCM_STREAM_CAPTURE &&
sound/virtio/virtio_pcm_msg.c static void virtsnd_pcm_msg_complete(struct virtio_pcm_msg *msg, · line 568
Quoted 10 lines
sound/virtio/virtio_pcm_msg.c +10
-0+ (msg->data_offset != vss->hw_ptr || + written_bytes < sizeof(msg->status) || + le32_to_cpu(msg->status.status) != VIRTIO_SND_S_OK || + written_bytes - sizeof(msg->status) != msg->length)) { +dev_err_ratelimited (&vss->snd->vdev->dev, +"SID %u: invalid capture position, status or length\n" , + vss->sid); + vss->xfer_xrun = true; + capture_invalid = true; + }
[Severity: Medium]
Does this latch vss->xfer_xrun when the device completes a partially filled RX buffer upon VIRTIO_SND_R_PCM_STOP?
Under the VirtIO Sound specification (section 5.14.6.8.2.1), the last RX buffer returned when a capture stream stops may contain fewer than period_bytes of PCM frames. During SNDRV_PCM_IOCTL_DRAIN, virtsnd_pcm_trigger(SNDRV_PCM_TRIGGER_STOP) sets vss->stopped = true and sends VIRTIO_SND_R_PCM_STOP while leaving the substream in SNDRV_PCM_STATE_DRAINING. A partial RX completion has written_bytes > sizeof(msg->status) and written_bytes - sizeof(msg->status) < msg->length, so it bypasses the early return and sets vss->xfer_xrun = true. That causes virtsnd_pcm_cp_ack() to fail with -EBADFD and virtsnd_pcm_cp_pointer() to report SNDRV_PCM_POS_XRUN, preventing userspace from draining full periods that had already completed before STOP.
Similarly, SNDRV_PCM_TRIGGER_PAUSE_PUSH sends VIRTIO_SND_R_PCM_STOP without setting vss->stopped, so any empty or partial in-flight RX buffer returned on pause also latches vss->xfer_xrun.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
PATCH v23 10/14 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.
Keep response values in a separately allocated aligned response buffer so INTEGER64 control accesses are aligned from this patch onward.
---sound/virtio/virtio_ctl_msg.c | 289 +++++++++++++++++++++++++++++++----------
sound/virtio/virtio_ctl_msg.h | 24 ++- sound/virtio/virtio_kctl.c | 121 +++++++++-------- sound/virtio/virtio_pcm_msg.c | 2 4 files changed, 300 insertions(+), 136 deletions(-)
sound/virtio/virtio_ctl_msg.c +218 -71
@@ -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_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); + } }/**
@@ -71,12 +86,73 @@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 @@* 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; - -if (!request_size || !response_size) +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 || request_size >UINT_MAX || + response_size >UINT_MAX || request_data_size >UINT_MAX || + response_data_size >UINT_MAX )return NULL ; - - msg =kzalloc (sizeof (*msg) + request_size + response_size, gfp); + 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), 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 @@* 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 @@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 @@ 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); - -list_add_tail (&msg->list, &snd->ctl_msgs); -if (notify) -virtqueue_notify (queue->vqueue); - } - } +if (msg->response_data_size) + psgs[nouts + nins++] = &msg->sg_response_data; + +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 @@* 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 @@ {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 @@ query->count =cpu_to_le32 (count); query->size =cpu_to_le32 (size); -sg_init_one (&sg, info, count * size); - -return virtsnd_ctl_msg_send (snd, msg,NULL , &sg, false); +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 rc; }/**
sound/virtio/virtio_ctl_msg.h +16 -8
@@ -21,20 +21,28 @@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 @@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_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 +65 -56
192 lines not on this page · raw message
sound/virtio/virtio_pcm_msg.c +1 -1
@@ -687,7 +687,7 @@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);
[email protected]
AI reviewRe: [PATCH v23 10/14] ALSA: virtio: Keep control payloads alive through DMA completion
Sashiko has reviewed this patch and found no issues.
Quoted 18 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 6 lines
Keep response values in a separately allocated aligned response buffer so INTEGER64 control accesses are aligned from this patch onward.
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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
PATCH v23 11/14 ALSA: virtio: wait through signals for PCM teardown
In reply to Joonho LeeA signal can end the interruptible wait while a STOP or RELEASE request is still pending. A later teardown may then submit another RELEASE before the first request completes.
Keep both waits non-interruptible and use the existing message timeout. Other control requests remain interruptible. Device reset still cancels the pending request and wakes the waiter.
Keep timeout and wait results in the types returned by the kernel wait APIs.
---sound/virtio/virtio_ctl_msg.c | 19 ++++++++++++++++---
sound/virtio/virtio_ctl_msg.h | 3 +++ sound/virtio/virtio_pcm_ops.c | 10 +++++----- 3 files changed, 24 insertions(+), 8 deletions(-)
sound/virtio/virtio_ctl_msg.c +16 -3
@@ -265,7 +265,7 @@ {struct virtio_device *vdev = snd->vdev;struct virtio_snd_queue *queue =virtsnd_control_queue (snd); -unsigned int js =msecs_to_jiffies (virtsnd_msg_timeout_ms); +unsigned long js =msecs_to_jiffies (virtsnd_msg_timeout_ms);struct virtio_snd_hdr *request =virtsnd_ctl_msg_request (msg);struct virtio_snd_hdr *response =virtsnd_ctl_msg_response (msg);unsigned int nouts =0 ;
@@ -273,7 +273,7 @@struct scatterlist *psgs[4 ];bool notify = false;unsigned long flags; -int rc; +long rc;virtsnd_ctl_msg_ref (msg);/* This reference stays with the queue until completion or teardown. */
@@ -314,7 +314,20 @@*/ virtsnd_ctl_msg_unref (msg); }else if (!nowait) { - rc =wait_for_completion_interruptible_timeout (&msg->notify, js); +/* +* Teardown must observe completion even with a pending signal. +* Otherwise a subsequent open can retry RELEASE while the device +* is still processing the previous teardown request. +*/ +switch (le32_to_cpu (request->code)) { +case VIRTIO_SND_R_PCM_STOP : +case VIRTIO_SND_R_PCM_RELEASE : + rc =wait_for_completion_timeout (&msg->notify, js); +break ; +default : + rc =wait_for_completion_interruptible_timeout (&msg->notify, js); +break ; + }if (!rc) { dev_err(&vdev->dev, "control message (0x%08x) timeout\n",
sound/virtio/virtio_ctl_msg.h +3 -0
@@ -47,6 +47,9 @@* 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 * error. +* PCM STOP and RELEASE wait through pending signals within this timeout. +* Other requests remain interruptible. Device reset cancels and wakes either +* kind of waiter. * * Context: Any context that permits to sleep. * Return: 0 on success, -errno on failure.
sound/virtio/virtio_pcm_ops.c +5 -5
@@ -20,11 +20,11 @@* (RELEASE command in the ops->sync_stop()) and the ops->hw_free() has been * called. * -* When the substream stops, the ops->sync_stop() waits until the device has -* completed all pending messages. This wait can be interrupted either by a -* 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. +* When the substream stops, ops->sync_stop() stops and releases the device +* as required, then waits for pending messages. A failed control request or +* timed-out flush can leave the device able to access messages after +* 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. *
[email protected]
AI reviewRe: [PATCH v23 11/14] ALSA: virtio: wait through signals for PCM teardown
Sashiko has reviewed this patch and found no issues.
Quoted 8 lines
A signal can end the interruptible wait while a STOP or RELEASE request is still pending. A later teardown may then submit another RELEASE before the first request completes.
Keep both waits non-interruptible and use the existing message timeout. Other control requests remain interruptible. Device reset still cancels the pending request and wakes the waiter.
Quoted 5 lines
Keep timeout and wait results in the types returned by the kernel wait APIs.
Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
PATCH v23 12/14 ALSA: virtio: add opt-in staged capture and recovery
In reply to Joonho LeeA fixed-size PCM descriptor does not describe every host capture completion. Add an opt-in request-owned capture path that copies actual completed bytes into the ALSA ring and accounts queued data separately from bytes observed and acknowledged by userspace.
Introduce read-only capture_staging, capture_packed_status, capture_allow_short, capture_allow_empty and capture_pause_restart parameters. They default to false. Packed trailers, short responses, bounded empty startup responses and release/prepare-based pause recovery are explicit compatibility options for the staged path.
Keep prepare, synchronous release and queue ownership serialized. Track the device generation so reset invalidates late control replies, retain PREPARE ownership until RELEASE succeeds, and stop admitting transfers when the device control state becomes uncertain.
Handle trigger failures in both playback and capture. Restore a failed native pause only while the core remains RUNNING; a failed linked resume rollback remains paused with transfer admission closed. Defer a paused XRUN until the core can complete the linked state transition.
Allocate the PCM request and status buffers separately, and release them with their I/O message after asynchronous descriptor ownership ends.
Provide separate RESET callbacks for playback, ordinary capture and staged capture. Rebase transport accounting with the core pointer update, preserve completions that arrive after pointer observation, and reject playback RESET while the transport still owns messages. Switch the VMALLOC PCM buffer to explicit hw_params/hw_free allocation so late transport ownership remains separate from the runtime mapping.
Reject unaligned ACK deltas before changing the capture policy or byte counters. Keep invalid alignment separate from accounting failures, including the deferred XRUN path for paused ordinary capture.
---sound/virtio/virtio_card.c | 58 +
sound/virtio/virtio_ctl_msg.c | 58 + sound/virtio/virtio_ctl_msg.h | 9 sound/virtio/virtio_pcm.c | 121 ++ sound/virtio/virtio_pcm.h | 144 +++ sound/virtio/virtio_pcm_msg.c | 511 +++++++++- sound/virtio/virtio_pcm_ops.c | 2063 ++++++++++++++++++++++++++++++++++++----- 7 files changed, 2613 insertions(+), 351 deletions(-)
sound/virtio/virtio_card.c +52 -6
@@ -369,6 +369,23 @@struct virtio_device *vdev = snd->vdev;unsigned int i; +for (i =0 ; snd->substreams && i < snd->nsubstreams; ++i) { +struct virtio_pcm_substream *vss = &snd->substreams[i]; +struct virtio_snd_queue *queue =virtsnd_pcm_queue (vss); + +guard (spinlock_irqsave)(&queue->lock); +guard (spinlock)(&vss->lock); + vss->reset_epoch++; + vss->resetting = true; + vss->prepared = false; + vss->preparing = false; + vss->device_running = false; + vss->release_required = false; + vss->control_uncertain = false; + vss->capture_reset_observing = false; + vss->xfer_enabled = false; + vss->suspended = true; + }virtio_reset_device (vdev);/* Deleting a virtqueue does not unmap its outstanding descriptors. */
@@ -388,7 +405,6 @@ queue->vqueue =NULL ;spin_unlock_irqrestore (&queue->lock, flags); } -if (snd->vqs_initialized) { vdev->config->del_vqs (vdev); snd->vqs_initialized = false;
@@ -396,6 +412,30 @@ }/** +* virtsnd_cancel_period_work() - Drain PCM work after control cleanup. +* @snd: VirtIO sound device. +* +* Must follow control message cleanup, which wakes work blocked on a PCM +* control request. +* +* Context: Any context that permits to sleep. +*/ +static void virtsnd_cancel_period_work (struct virtio_snd *snd) +{ +unsigned int i; + +for (i =0 ; snd->substreams && i < snd->nsubstreams; ++i) { +struct virtio_pcm_substream *vss = &snd->substreams[i]; + +cancel_work_sync (&vss->elapsed_period); +guard (spinlock_irqsave)(&vss->lock); + vss->stopped = false; + vss->xfer_xrun = false; + vss->pause_restart_state =VIRTSND_PCM_PAUSE_RESTART_NONE ; + } +} + +/** * virtsnd_remove() - Remove VirtIO and ALSA devices. * @vdev: VirtIO parent device. *
@@ -414,12 +454,13 @@virtsnd_ctl_msg_cancel_all (snd);virtsnd_reset_vqs (snd); +/* Wake PCM workers blocked on control replies before draining them. */ virtsnd_ctl_msg_cleanup (snd); +virtsnd_cancel_period_work (snd);for (i =0 ; snd->substreams && i < snd->nsubstreams; ++i) {struct virtio_pcm_substream *vss = &snd->substreams[i]; -cancel_work_sync (&vss->elapsed_period);virtsnd_pcm_msg_free (vss); }
@@ -437,16 +478,14 @@static int virtsnd_freeze (struct virtio_device *vdev) {struct virtio_snd *snd = vdev->priv; -unsigned int i;virtsnd_disable_event_vq (snd);virtsnd_ctl_msg_cancel_all (snd);virtsnd_reset_vqs (snd); +/* Wake PCM workers blocked on control replies before draining them. */ virtsnd_ctl_msg_cleanup (snd); - -for (i =0 ; i < snd->nsubstreams; ++i) -cancel_work_sync (&snd->substreams[i].elapsed_period); +virtsnd_cancel_period_work (snd);kfree (snd->event_msgs); snd->event_msgs =NULL ;
@@ -465,6 +504,7 @@ {struct virtio_snd *snd = vdev->priv;int rc; +unsigned int i; rc =virtsnd_find_vqs (snd);if (rc) {
@@ -475,6 +515,12 @@virtio_device_ready (vdev);virtsnd_ctl_msg_enable (snd); +for (i =0 ; i < snd->nsubstreams; ++i) { +struct virtio_pcm_substream *vss = &snd->substreams[i]; + +guard (spinlock_irqsave)(&vss->lock); + vss->resetting = false; + }virtsnd_enable_event_vq (snd);return 0 ;
sound/virtio/virtio_ctl_msg.c +53 -5
86 lines not on this page · raw message
sound/virtio/virtio_ctl_msg.h +8 -1
@@ -11,6 +11,13 @@struct virtio_snd ;struct virtio_snd_msg ; +struct virtio_pcm_substream ; + +void virtsnd_ctl_msg_bind_pcm (struct virtio_snd_msg *msg, +struct virtio_pcm_substream *vss,u64 epoch); +u64 virtsnd_ctl_msg_pcm_epoch (struct virtio_snd_msg *msg); + +bool virtsnd_ctl_msg_uncertain (struct virtio_snd_msg *msg,int rc);void virtsnd_ctl_msg_ref (struct virtio_snd_msg *msg);
@@ -47,7 +54,7 @@* 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 * error. -* PCM STOP and RELEASE wait through pending signals within this timeout. +* PCM state-changing requests wait through pending signals within this timeout. * Other requests remain interruptible. Device reset cancels and wakes either * kind of waiter. *
sound/virtio/virtio_pcm.c +117 -4
148 lines not on this page · raw message
sound/virtio/virtio_pcm.h +138 -6
212 lines not on this page · raw message
sound/virtio/virtio_pcm_msg.c +439 -72
663 lines not on this page · raw message
sound/virtio/virtio_pcm_ops.c +1806 -257
1,759 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Part of the diff is not shown here. View the raw message.
[email protected]
AI reviewRe: [PATCH v23 12/14] ALSA: virtio: add opt-in staged capture and recovery
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] ALSA: virtio: missed playback wakeup and wrap in virtsnd_pcm_trigger_inner() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] ALSA: virtio: missed playback wakeup and wrap in virtsnd_pcm_trigger_inner()
--
commit 1965297bcd244a03fcb4a5994d8a256a3575a92b
Author: Joonho Lee <[email protected]>
ALSA: virtio: add opt-in staged capture and recovery
This commit adds an opt-in request-owned staged capture path with compatibility options and updates PCM control serialization, pause/resume handling, and reset callbacks.
Quoted 4 lines
sound/virtio/virtio_pcm_msg.c +0
-0
[ ... ]
Quoted 1 line
sound/virtio/virtio_pcm_msg.c +0
-0@@ -536,78 +876,103 @@ static void virtsnd_pcm_msg_complete(struct virtio_pcm_msg *msg,
[ ... ]
Quoted 38 lines
sound/virtio/virtio_pcm_msg.c +21
-8+ vss->hw_ptr += completed_bytes; +if (vss->direction ==SNDRV_PCM_STREAM_CAPTURE ) { +/* A full unseen ring cannot be represented by the modulo pointer. */ +if (check_add_overflow (vss->capture_copied_total, + (u64 )completed_bytes, + &vss->capture_copied_total) || + vss->capture_copied_total < vss->capture_pointer_seen_total || + vss->capture_copied_total - vss->capture_pointer_seen_total >= + vss->buffer_bytes) + vss->xfer_xrun = true; + } +if (vss->hw_ptr >= vss->buffer_bytes) + vss->hw_ptr -= vss->buffer_bytes; + msg->length =0 ; + +/* Keep latched errors until prepare establishes a fresh epoch. */ vss->msg_count--; -if (vss->xfer_enabled) { -if (!capture_invalid) { -struct snd_pcm_runtime *runtime = vss->substream->runtime; +if (vss->xfer_enabled || + (vss->direction ==SNDRV_PCM_STREAM_CAPTURE && vss->xfer_xrun)) { +struct snd_pcm_runtime *runtime = vss->substream->runtime; - runtime->delay = -bytes_to_frames (runtime, -le32_to_cpu (msg->status.latency_bytes)); - } -schedule_work (&vss->elapsed_period); + runtime->delay =bytes_to_frames (runtime, latency_bytes); +virtsnd_pcm_schedule_period_elapsed (vss); }if (!vss->msg_count)wake_up_all (&vss->msg_empty); }
[ ... ]
Quoted 4 lines
sound/virtio/virtio_pcm_ops.c +0
-0
[ ... ]
Quoted 76 lines
sound/virtio/virtio_pcm_ops.c +48
-10+switch (command) { +case SNDRV_PCM_TRIGGER_START : +case SNDRV_PCM_TRIGGER_PAUSE_RELEASE : +scoped_guard (spinlock_irqsave, &vss->lock) + running = vss->device_running; +/* Preserve queued requests and unread RX data across native pause. */ + rc =virtsnd_pcm_start_queue (vss, epoch); +if (rc) { +virtsnd_pcm_trigger_failed (vss, epoch); +return rc; } + +if (running) { +if (vss->direction ==SNDRV_PCM_STREAM_CAPTURE ) +virtsnd_pcm_schedule_period_elapsed (vss); +return 0 ; + } + + msg =virtsnd_pcm_ctl_msg_alloc (vss,VIRTIO_SND_R_PCM_START , +GFP_KERNEL , epoch);if (!msg) { -virtsnd_pcm_start_failed (vss); +virtsnd_pcm_trigger_failed (vss, epoch);return -ENOMEM ; } - rc =virtsnd_ctl_msg_send_sync (snd, msg); -if (rc) -virtsnd_pcm_start_failed (vss); + rc =virtsnd_pcm_send_sync (vss, msg); +if (rc && rc != -ECANCELED ) +virtsnd_pcm_trigger_failed (vss, epoch); +if (!rc) { +guard (spinlock_irqsave)(&vss->lock); +if (vss->resetting || vss->reset_epoch != epoch) +return -ECANCELED ; + vss->device_running = true; + } +if (!rc && vss->direction ==SNDRV_PCM_STREAM_CAPTURE ) +virtsnd_pcm_schedule_period_elapsed (vss);return rc;case SNDRV_PCM_TRIGGER_SUSPEND : - vss->suspended = true; +scoped_guard (spinlock_irqsave, &vss->lock) + vss->suspended = true; fallthrough;case SNDRV_PCM_TRIGGER_STOP :case SNDRV_PCM_TRIGGER_PAUSE_PUSH : scoped_guard(spinlock_irqsave, &vss->lock) { +if (!vss->prepared) +return 0 ;if (command !=SNDRV_PCM_TRIGGER_PAUSE_PUSH ) vss->stopped = true; vss->xfer_enabled = false; +if (!vss->device_running) +return 0 ; } - msg =virtsnd_pcm_ctl_msg_alloc (vss,VIRTIO_SND_R_PCM_STOP , -GFP_KERNEL ); -if (!msg) -return -ENOMEM ; + rc =virtsnd_pcm_stop_device (vss, epoch); +if (rc && command !=SNDRV_PCM_PAUSE_PUSH ) { +guard (spinlock_irqsave)(&vss->lock); -return virtsnd_ctl_msg_send_sync (snd, msg); +if (vss->reset_epoch == epoch && !vss->resetting) { + vss->xfer_xrun = true; + substream->runtime->stop_operating = true; +if (vss->direction ==SNDRV_PCM_STREAM_CAPTURE ) +virtsnd_pcm_schedule_period_elapsed (vss); + } + } +if (rc && command ==SNDRV_PCM_TRIGGER_PAUSE_PUSH ) {
sound/virtio/virtio_pcm_ops.c
Quoted 10 lines
sound/virtio/virtio_pcm_ops.c +10
-0+if (substream->runtime->state !=SNDRV_PCM_STATE_RUNNING ) { +/* Failed resume rollback must leave a paused queue closed. */ +virtsnd_pcm_trigger_failed (vss, epoch); + }else if (virtsnd_pcm_start_queue (vss, epoch)) { +virtsnd_pcm_trigger_failed (vss, epoch); + }else if (vss->direction ==SNDRV_PCM_STREAM_CAPTURE ) { +virtsnd_pcm_schedule_period_elapsed (vss); + } + } +return rc;
[Severity: Medium]
Can pausing a playback stream stall playback when in-flight TX descriptors complete while vss->xfer_enabled is false?
SNDRV_PCM_TRIGGER_PAUSE_PUSH clears vss->xfer_enabled before virtsnd_pcm_stop_device() sends VIRTIO_SND_R_PCM_STOP. Any TX descriptors that complete in virtsnd_pcm_msg_complete() while vss->xfer_enabled is false advance vss->hw_ptr and decrement vss->msg_count without scheduling vss->elapsed_period, and any work already queued returns early in virtsnd_pcm_period_elapsed() while the substream is paused.
When playback resumes via SNDRV_PCM_TRIGGER_PAUSE_RELEASE (or recovers from a failed pause push while still running), virtsnd_pcm_trigger_inner() only schedules vss->elapsed_period for capture. If all queued TX descriptors completed while paused (vss->msg_count == 0), no further TX interrupt will arrive to run virtsnd_pcm_pb_pointer(), reclaim vss->pcm_indirect.hw_ready, or submit pending vss->pcm_indirect.sw_ready bytes.
In addition, virtsnd_pcm_msg_complete() only checks for a full-buffer unseen completion wrap on capture. Because virtsnd_pcm_playback_ack_validate() allows queuing a full buffer of TX descriptors, completing all of them before virtsnd_pcm_pb_pointer() runs wraps vss->hw_ptr modulo vss->buffer_bytes back to vss->pcm_indirect.hw_io, so snd_pcm_indirect_playback_pointer() observes zero progress and leaves vss->pcm_indirect.hw_ready stuck at vss->buffer_bytes.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
PATCH v23 13/14 ALSA: virtio: prioritize staged capture period work
In reply to Joonho LeeQueue staged capture period notifications on system_highpri_wq through the common scheduling helper. This allows capture notifications to make progress when ordinary workqueue workers are delayed by CPU contention. Playback and ordinary capture keep schedule_work().
This preserves the existing priority proposal without mixing RESET or lifecycle changes into it. It provides no hard real-time deadline and cannot prevent a userspace reader from overrunning its buffer.
---sound/virtio/virtio_pcm.h | 4 ++++
1 file changed, 4 insertions(+)
sound/virtio/virtio_pcm.h +4 -0
@@ -168,6 +168,10 @@static inline bool virtsnd_pcm_schedule_period_elapsed (struct virtio_pcm_substream *vss) { +if (vss->direction ==SNDRV_PCM_STREAM_CAPTURE && + vss->capture_staging) +return queue_work (system_highpri_wq, &vss->elapsed_period); +return schedule_work (&vss->elapsed_period); }
[email protected]
AI reviewRe: [PATCH v23 13/14] ALSA: virtio: prioritize staged capture period work
Sashiko has reviewed this patch and found no issues.
Quoted 11 lines
Queue staged capture period notifications on
system_highpri_wqthrough the common scheduling helper. This allows capture notifications to make progress when ordinary workqueue workers are delayed by CPU contention. Playback and ordinary capture keepschedule_work().This preserves the existing priority proposal without mixing RESET or lifecycle changes into it. It provides no hard real-time deadline and cannot prevent a userspace reader from overrunning its buffer.
Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
PATCH v23 14/14 docs: describe virtio-sound capture options
In reply to Joonho LeeDocument the five opt-in virtio_snd capture module parameters. State that capture_allow_empty, capture_allow_short, capture_packed_status and capture_pause_restart require capture_staging, and use the ALSA kernel parameter restriction tag for each entry.
---Documentation/admin-guide/kernel-parameters.txt | 29 +++++++++++++++++++++++
1 file changed, 29 insertions(+)
Documentation/admin-guide/kernel-parameters.txt +29 -0
@@ -8344,6 +8344,35 @@ Can be used multiple times for multiple devices. + virtio_snd.capture_allow_empty= [HW,ALSA] + Retry a bounded number of empty startup capture replies + when virtio_snd.capture_staging=1. + Format: <bool> + Default: false. Validate with the target device. + + virtio_snd.capture_allow_short= [HW,ALSA] + Accept non-empty, frame-aligned short capture replies + when virtio_snd.capture_staging=1. + Format: <bool> + Default: false. Validate with the target device. + + virtio_snd.capture_packed_status= [HW,ALSA] + Read status immediately after the returned capture data + when virtio_snd.capture_staging=1. + Format: <bool> + Default: false. Validate with the target device. + + virtio_snd.capture_pause_restart= [HW,ALSA] + Release and reprepare capture streams across pause when + virtio_snd.capture_staging=1. + Format: <bool> + Default: false. Validate with the target device. + + virtio_snd.capture_staging= [HW,ALSA] + Enable staged capture using request-owned buffers. + Format: <bool> + Default: false. Validate with the target device. + vga= [BOOT,X86-32] Select a particular video mode See Documentation/arch/x86/boot.rst and Documentation/admin-guide/svga.rst.
[email protected]
AI reviewRe: [PATCH v23 14/14] docs: describe virtio-sound capture options
Sashiko has reviewed this patch and found no issues.
Quoted 7 lines
Document the five opt-in
virtio_sndcapture module parameters. State thatcapture_allow_empty,capture_allow_short,capture_packed_statusandcapture_pause_restartrequirecapture_staging, and use the ALSA kernel parameter restriction tag for each entry.Assisted-by LLMSigned-off-by Joonho Lee <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14