Skip to contentSkip to conversation

ALSA: virtio: Fix request lifetime and error recovery

PATCH Superseded Joonho Lee 2 participants 13 messages Oct 13

Subsystems (3)

v2 of 33 Superseded Latest is v33 →

lore
Share & tools
lore

Joonho Lee

author
#0 lore raw

v2 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 v1, following the Sashiko AI review:
- Patch 1 propagates enqueue failures through ACK. Indirect PCM state is committed only on success; a failed transfer stops the stream and returns -EPIPE rather than allowing an out-of-sync retry.
- Patch 2 is unchanged.
- Patch 3 detaches unused descriptors on all queues after reset and balances PCM cancellation and control-message references.
- Patch 4 supports NOMMU with an owned, zeroed buffer instead of rejecting an ordinary kmalloc-backed ALSA buffer. Capture copies are bounded and disabled once the stream stops.
- Patch 5 separates CPU metadata from DMA storage and aligns each DMA region to dma_get_cache_alignment(). Control-send cleanup also uses explicit, balanced locking instead of mixing scoped guards and gotos.

Validation of the final source:
- Source-extracted ASan/UBSan regressions on macOS arm64 and Linux arm64, including expected failures on the v1 ACK and NOMMU implementations.
- ARM64 W=1 module builds at all five patch steps, plus an ARM32 CONFIG_MMU=n driver object build of the final source.
- QEMU ARM64 KASAN tests with delayed PCM completion past hw_free, delayed PCM_INFO completion after timeout, and reset with pending control requests. Each case includes a subsequent recovery operation.

The QEMU tests use a synthetic audio backend; they do not validate a host microphone. NOMMU coverage is a compile and source-extracted test, not a booted NOMMU guest. Cache-alignment checks are not a physical non-coherent DMA hardware test.

Reproducer source and instructions, pinned to the tested revision:
https://github.com/whatisyourname0/virtio-snd-reproducer/tree/ef97b69baea51d952ddd7c329a1894150f41849e

The reproducer currently obtains the same final driver source by applying the archived v1 patches plus review-v2.diff. Its full kernel/QEMU rebuild recipe has not been rerun end to end; the reported runtime tests used rebuilt candidate modules with the existing matching KASAN kernel image.

Based on sound.git for-next commit
8d70e364e866bdfca81eee24d0688fac9472cfb9.

AI assistance was used for code changes, test harnesses, review, and patch text. The Sashiko findings were checked against the driver and reproduced where applicable before incorporating the fixes. Assisted-by trailers are included in the patches.

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 | 305 +++++++++++++++++++++++++++-------
 sound/virtio/virtio_ctl_msg.h |  28 +++-
 sound/virtio/virtio_kctl.c    | 104 ++++++------
 sound/virtio/virtio_pcm.h     |  13 ++
 sound/virtio/virtio_pcm_msg.c | 295 +++++++++++++++++++++++++++++---
 sound/virtio/virtio_pcm_ops.c | 147 +++++++++++++---
 8 files changed, 780 insertions(+), 158 deletions(-)

base-commit: 8d70e364e866bdfca81eee24d0688fac9472cfb9

Signature · 1 line
2.54.0 (Apple Git-157)
author
#1 lore raw

PATCH v2 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.

Fixes fe981e67568c ("ALSA: virtio: use ack callback")
Assisted-by LLM

---
Changes in v2:
- Propagate send errors through ACK, retain indirect state only on success, and stop the stream before an out-of-sync retry.

 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
index 72103f606716..5371f4985fd0 100644
@@ -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)
#2 lore raw

Re: [PATCH v2 1/5] ALSA: virtio: Propagate PCM send failures through ACK

Sashiko 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 LLM

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
author
#3 lore raw

PATCH v2 2/5 ALSA: virtio: Recover PCM state after a failed start

In reply to Joonho Lee

Capture trigger queues I/O messages before sending PCM_START. If allocation of the START control message fails, trigger returns an error with capture I/O messages potentially pending, but without marking the stream stopped or arming sync_stop. If sending START fails, trigger also leaves transfers enabled. ALSA does not run the action undo callback after this trigger failure, so the normal STOP path cannot be relied on to drain those requests. Retrying START can then submit the same capture messages again.

Disable transfers and mark the stream stopped after a failed start, and arm runtime->stop_operating so ALSA invokes sync_stop. Make sync_stop send RELEASE when the stream is stopped or has pending I/O, and keep the stream stopped when RELEASE or queue draining fails. Reject prepare, hw_params, and START retries until a later sync_stop resolves the outstanding state.

Always cancel elapsed-period work in sync_stop, even when no RELEASE is needed.

Fixes da76e9f3e43a ("ALSA: virtio: PCM substream operators")
Assisted-by LLM

---
Changes in v2:
- No code or commit-message changes.

 sound/virtio/virtio_pcm_ops.c | 63 +++++++++++++++++++++++++++++------
 1 file changed, 53 insertions(+), 10 deletions(-)
sound/virtio/virtio_pcm_ops.c +53 -10
index a40ea394bf17..fe8e0dc3eafc 100644
@@ -96,6 +96,15 @@ static const struct virtsnd_a2v_rate g_a2v_rate_map[] = {
 
 static int virtsnd_pcm_sync_stop(struct snd_pcm_substream *substream);
 
+static void virtsnd_pcm_start_failed(struct virtio_pcm_substream *vss)
+{
+	scoped_guard(spinlock_irqsave, &vss->lock) {
+		vss->xfer_enabled = false;
+		vss->stopped = true;
+	}
+	vss->substream->runtime->stop_operating = true;
+}
+
 /**
  * virtsnd_pcm_open() - Open the PCM substream.
  * @substream: Kernel ALSA substream.
@@ -115,7 +124,7 @@ static int virtsnd_pcm_open(struct snd_pcm_substream *substream)
 	snd_pcm_hw_constraint_integer(substream->runtime,
 				      SNDRV_PCM_HW_PARAM_PERIODS);
 
-	vss->stopped = !!virtsnd_pcm_msg_pending_num(vss);
+	vss->stopped |= !!virtsnd_pcm_msg_pending_num(vss);
 	vss->suspended = false;
 
 	/*
@@ -224,6 +233,12 @@ static int virtsnd_pcm_hw_params(struct snd_pcm_substream *substream,
 			vss->sid);
 		return -EBADFD;
 	}
+	if (vss->stopped) {
+		dev_err(&vdev->dev, "SID %u: stream release failed\n",
+			vss->sid);
+		substream->runtime->stop_operating = true;
+		return -EBADFD;
+	}
 
 	rc = virtsnd_pcm_dev_set_params(vss, params_buffer_bytes(hw_params),
 					params_period_bytes(hw_params),
@@ -274,6 +289,13 @@ static int virtsnd_pcm_prepare(struct snd_pcm_substream *substream)
 	struct virtio_device *vdev = vss->snd->vdev;
 	struct virtio_snd_msg *msg;
 
+	if (vss->stopped) {
+		dev_err(&vdev->dev, "SID %u: stream release failed\n",
+			vss->sid);
+		substream->runtime->stop_operating = true;
+		return -EBADFD;
+	}
+
 	if (!vss->suspended) {
 		if (virtsnd_pcm_msg_pending_num(vss)) {
 			dev_err(&vdev->dev, "SID %u: invalid I/O queue state\n",
@@ -338,23 +360,32 @@ static int virtsnd_pcm_trigger(struct snd_pcm_substream *substream, int command)
 
 		scoped_guard(spinlock_irqsave, &queue->lock) {
 			guard(spinlock)(&vss->lock);
+			if (vss->stopped) {
+				substream->runtime->stop_operating = true;
+				return -EBADFD;
+			}
 			if (vss->direction == SNDRV_PCM_STREAM_CAPTURE)
 				rc = virtsnd_pcm_msg_send(vss, 0, vss->buffer_bytes);
-			if (rc)
+			if (rc) {
+				vss->stopped = true;
+				substream->runtime->stop_operating = true;
 				return rc;
+			}
 			vss->xfer_enabled = true;
 		}
 
 		msg = virtsnd_pcm_ctl_msg_alloc(vss, VIRTIO_SND_R_PCM_START,
 						GFP_KERNEL);
 		if (!msg) {
-			guard(spinlock_irqsave)(&vss->lock);
-			vss->xfer_enabled = false;
-
+			virtsnd_pcm_start_failed(vss);
 			return -ENOMEM;
 		}
 
-		return virtsnd_ctl_msg_send_sync(snd, msg);
+		rc = virtsnd_ctl_msg_send_sync(snd, msg);
+		if (rc)
+			virtsnd_pcm_start_failed(vss);
+
+		return rc;
 	case SNDRV_PCM_TRIGGER_SUSPEND:
 		vss->suspended = true;
 		fallthrough;
@@ -393,21 +424,32 @@ static int virtsnd_pcm_sync_stop(struct snd_pcm_substream *substream)
 	struct virtio_snd *snd = vss->snd;
 	struct virtio_snd_msg *msg;
 	unsigned int js = msecs_to_jiffies(virtsnd_msg_timeout_ms);
+	bool need_release;
 	int rc;
 
+	scoped_guard(spinlock_irqsave, &vss->lock) {
+		vss->xfer_enabled = false;
+		need_release = vss->stopped || vss->msg_count;
+	}
 	cancel_work_sync(&vss->elapsed_period);
-
-	if (!vss->stopped)
+	if (!need_release)
 		return 0;
 
+	scoped_guard(spinlock_irqsave, &vss->lock)
+		vss->stopped = true;
+
 	msg = virtsnd_pcm_ctl_msg_alloc(vss, VIRTIO_SND_R_PCM_RELEASE,
 					GFP_KERNEL);
-	if (!msg)
+	if (!msg) {
+		substream->runtime->stop_operating = true;
 		return -ENOMEM;
+	}
 
 	rc = virtsnd_ctl_msg_send_sync(snd, msg);
-	if (rc)
+	if (rc) {
+		substream->runtime->stop_operating = true;
 		return rc;
+	}
 
 	/*
 	 * The spec states that upon receipt of the RELEASE command "the device
@@ -421,6 +463,7 @@ static int virtsnd_pcm_sync_stop(struct snd_pcm_substream *substream)
 	if (rc <= 0) {
 		dev_warn(&snd->vdev->dev, "SID %u: failed to flush I/O queue\n",
 			 vss->sid);
+		substream->runtime->stop_operating = true;
 
 		return !rc ? -ETIMEDOUT : rc;
 	}
Signature · 1 line
2.54.0 (Apple Git-157)
#4 lore raw

Re: [PATCH v2 2/5] ALSA: virtio: Recover PCM state after a failed start

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] sound: virtio: Data race on vss->stopped due to missing ALSA stream lock in prepare/hw_params --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] sound: virtio: Data race on vss->stopped due to missing ALSA stream lock in prepare/hw_params --

commit cf7b0007082a8c0e3a16320e4229781856250174
Author: Joonho Lee <[email protected]>
ALSA: virtio: Recover PCM state after a failed start

This commit modifies the capture trigger to disable transfers, mark the stream as stopped, and arm the stop operating flag if a PCM START fails. It also adds checks in the hw_params and prepare callbacks to reject retries if the stream is stopped, until a subsequent sync_stop resolves the state.

Quoted 4 lines
sound/virtio/virtio_pcm_ops.c +0 -0
index a40ea394bf174..fe8e0dc3eafca 100644

[ ... ]

sound/virtio/virtio_pcm_ops.c static int virtsnd_pcm_hw_params(struct snd_pcm_substream *substream, · line 236

Quoted 5 lines
sound/virtio/virtio_pcm_ops.c +1 -0
@@ -224,6 +233,12 @@ static int virtsnd_pcm_hw_params(struct snd_pcm_substream *substream,
 			vss->sid);
 		return -EBADFD;
 	}
+	if (vss->stopped) {

[Severity: Medium]
Is it safe to read vss->stopped locklessly here?

ALSA explicitly drops the stream lock (group->mutex) before invoking virtsnd_pcm_hw_params(), virtsnd_pcm_prepare(), and hw_free() (which calls virtsnd_pcm_sync_stop()).

Concurrently, ioctls like SNDRV_PCM_IOCTL_FORWARD (which invoke the ack callback) acquire group->mutex but not buffer_mutex.

This means virtsnd_pcm_pb_ack() can execute concurrently with virtsnd_pcm_hw_params() or virtsnd_pcm_prepare() on the same substream.

Since the ack path writes to vss->stopped under vss->lock, reading it here without vss->lock could result in a data race. A torn read or compiler reordering could result in an incorrect stream state being observed.

Quoted 7 lines
sound/virtio/virtio_pcm_ops.c +5 -0
+		dev_err(&vdev->dev, "SID %u: stream release failed\n",
+			vss->sid);
+		substream->runtime->stop_operating = true;
+		return -EBADFD;
+	}
 
 	rc = virtsnd_pcm_dev_set_params(vss, params_buffer_bytes(hw_params),

[ ... ]

sound/virtio/virtio_pcm_ops.c static int virtsnd_pcm_prepare(struct snd_pcm_substream *substream) · line 292

Quoted 5 lines
sound/virtio/virtio_pcm_ops.c +1 -0
@@ -274,6 +289,13 @@ static int virtsnd_pcm_prepare(struct snd_pcm_substream *substream)
 	struct virtio_device *vdev = vss->snd->vdev;
 	struct virtio_snd_msg *msg;
 
+	if (vss->stopped) {

[Severity: Medium]
Similarly, vss->stopped is read locklessly here in virtsnd_pcm_prepare(). Could this also race with concurrent ack callbacks for the same reason?

This problem wasn't introduced by this patch, but vss->stopped is also written locklessly at the end of virtsnd_pcm_sync_stop().

Since virtsnd_pcm_sync_stop() is called from hw_free where ALSA also drops group->mutex, could that lockless write also race with concurrent ack callbacks?

Quoted 8 lines
sound/virtio/virtio_pcm_ops.c +6 -0
+		dev_err(&vdev->dev, "SID %u: stream release failed\n",
+			vss->sid);
+		substream->runtime->stop_operating = true;
+		return -EBADFD;
+	}
+
 	if (!vss->suspended) {
 		if (virtsnd_pcm_msg_pending_num(vss)) {
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#5 lore raw

Re: [PATCH v2 2/5] ALSA: virtio: Recover PCM state after a failed start

Thanks for pointing this out. The ALSA stream lock does not cover these callbacks, so the stopped accesses need the driver's own lock.

In v3, all accesses to vss->stopped use vss->lock, including open, STOP, hw_params, prepare and the final clear in sync_stop. The RELEASE decision and stopped=true transition are in one critical section. Allocation, control-message waits and work cancellation remain outside the spinlock.

The regression catches the unlocked v2 accesses and passes 73 lifecycle checks with v3. This uses deterministic source instrumentation, not KCSAN.

The updated series is in the new [PATCH v3 0/5] thread.

v3 cover Message-ID: <[email protected]>

author
#6 lore raw

PATCH v2 3/5 ALSA: virtio: Retain queued messages through device reset

In reply to Joonho Lee

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.

Fixes 9d45e514da88 ("ALSA: virtio: handling control messages")
Assisted-by LLM

---
Changes in v2:
- Detach unused descriptors after reset on every queue, cancel PCM tokens, and use explicit balanced locking in control send.

 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
index 6f35276416fe..df7091b74a52 100644
@@ -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
index 3ceee4e416fc..bd065bd00d25 100644
@@ -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
index 7f4db044f28e..d917435409d0 100644
@@ -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
index 8837dfc12828..5787a300d0ee 100644
@@ -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
index 5371f4985fd0..762480363b86 100644
@@ -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)
#7 lore raw

Re: [PATCH v2 3/5] ALSA: virtio: Retain queued messages through device reset

Sashiko 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 LLM

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
author
#8 lore raw

PATCH v2 4/5 ALSA: virtio: Keep PCM DMA buffers alive through device ownership

In reply to Joonho Lee

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.

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 LLM

---
Changes in v2:
- Support NOMMU with an owned zeroed DMA buffer, copy only while the stream is active, and bound capture lengths by message capacity.

 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
index 5787a300d0ee..02547899743a 100644
@@ -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
index fe8e0dc3eafc..ac2f28686632 100644
@@ -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)
#9 lore raw

Re: [PATCH v2 4/5] ALSA: virtio: Keep PCM DMA buffers alive through device ownership

Sashiko 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 LLM

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
author
#10 lore raw

PATCH v2 5/5 ALSA: virtio: Keep control payloads alive through DMA completion

In reply to Joonho Lee

Control requests can expose caller-owned payloads to the device after a synchronous send times out. Allocate request and response headers and payloads with the reference-counted message, and place each scatterlist region on separate DMA cacheline boundaries.

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.

Fixes 9d45e514da88 ("ALSA: virtio: handling control messages")
Assisted-by LLM

---
Changes in v2:
- Separate CPU metadata from DMA storage and align each DMA region using dma_get_cache_alignment(), with overflow-checked sizing.

 sound/virtio/virtio_ctl_msg.c | 273 ++++++++++++++++++++++++++--------
 sound/virtio/virtio_ctl_msg.h |  24 ++-
 sound/virtio/virtio_kctl.c    | 104 +++++++------
 sound/virtio/virtio_pcm_msg.c |   2 +-
 4 files changed, 283 insertions(+), 120 deletions(-)
sound/virtio/virtio_ctl_msg.c +209 -64
index 7114bea4033a..84e2fb2562e4 100644
@@ -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: DMA cacheline alignment.
+ *
+ * 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,83 @@ 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;
+	alignment = cache_alignment;
+
+	/* Reserve prefix alignment slack before the first DMA region. */
+	dma_buffer_size = alignment;
+	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 = (u8 *)msg->dma_buffer + 1;
+	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 +251,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 +270,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 +280,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 +311,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 +436,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 +462,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
index d917435409d0..f867b9b9233d 100644
@@ -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
index b7f2334bb221..b54642a9521d 100644
@@ -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)
#11 lore raw

Re: [PATCH v2 5/5] ALSA: virtio: Keep control payloads alive through DMA completion

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] mm: Unaligned memory access due to +1 offset with small DMA cacheline alignment --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] mm: Unaligned memory access due to +1 offset with small DMA cacheline alignment --

commit d7c4b679538e28af5e6c452343c3bd0ca83a7fd1
Author: Joonho Lee <[email protected]>

ALSA: virtio: Keep control payloads alive through DMA completion

Control requests can expose caller-owned payloads to the device after a synchronous send times out. Allocate request and response headers and payloads with the reference-counted message, and place each scatterlist region on separate DMA cacheline boundaries.

Quoted 3 lines
sound/virtio/virtio_ctl_msg.c +0 -0

[ ... ]

Quoted 1 line
sound/virtio/virtio_ctl_msg.c +0 -0
@@ -85,20 +161,83 @@ struct virtio_snd_msg *virtsnd_ctl_msg_alloc(size_t request_size,

[ ... ]

sound/virtio/virtio_ctl_msg.c void *virtsnd_ctl_msg_response(struct virtio_snd_msg *msg) · line 222

Quoted 13 lines
sound/virtio/virtio_ctl_msg.c +6 -3
 	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 = (u8 *)msg->dma_buffer + 1;

[Severity: High]
When dma_get_cache_alignment() returns 1 (as it typically does on cache-coherent architectures like x86), does this +1 offset force all subsequent scatterlist entries to be at an odd, unaligned memory address?

Since the alignment is 1, padding = address % alignment in virtsnd_ctl_msg_sg_init() will evaluate to 0, leaving the data address unaligned without any added padding.

Later, callers like virtsnd_kctl_get() cast this response data to struct virtio_snd_ctl_value and directly load 64-bit integers:

sound/virtio/virtio_kctl.c:virtsnd_kctl_get() {
    ...
    case VIRTIO_SND_CTL_TYPE_INTEGER64:
        for (i = 0; i < count; ++i)
            uvalue->value.integer64.value[i] =
                le64_to_cpu(kvalue->value.integer64[i]);
    ...
}

Can this lead to an unaligned memory access exception or a kernel panic when UBSAN is enabled on strict architectures?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author
#12 lore raw

Re: [PATCH v2 5/5] ALSA: virtio: Keep control payloads alive through DMA completion

Thanks, this is a real alignment bug. I reproduced UBSan failures for both the control header and the integer64 response payload with the v2 code.

In v3, the alignment is at least __alignof__(struct virtio_snd_ctl_value), in addition to dma_get_cache_alignment(), and the initial +1 offset is removed. Each subsequent region is aligned as well, including when a preceding region has an odd length.

The ASan/UBSan regression now checks typed header and 64-bit payload accesses with DMA alignments 1, 2, 4, 8, 32, 64 and 128; v3 passes.

The updated series is in the new [PATCH v3 0/5] thread.

v3 cover Message-ID: <[email protected]>