From: Hunter Laux <hunterlaux@gmail.com>
To: Thinh Nguyen <Thinh.Nguyen@synopsys.com>,
Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: linux-usb@vger.kernel.org, Hunter Laux <hunterlaux@gmail.com>,
stable@vger.kernel.org, Guenter Roeck <linux@roeck-us.net>,
Doug Anderson <dianders@chromium.org>
Subject: [PATCH v2] usb: dwc2: hcd: Fix DMA overrun of short IN buffers
Date: Sat, 5 Dec 2026 02:14:23 -0700 [thread overview]
Message-ID: <20261205091423.1543329-1-hunterlaux@gmail.com> (raw)
dwc2_hc_start_transfer() programs every IN transfer as a whole number
of max-size packets, and after a short packet the controller can write
past the bytes it received; isochronous frames are programmed one at a
time, at their offsets. dwc2_map_urb_for_dma() bounces only misaligned
buffers, so an aligned IN buffer too short for that is handed to the
controller as it is, and the memory after it can be overwritten.
With SLUB red zones this shows at every enumeration (64-byte ep0):
usb_get_device_descriptor()'s 18-byte buffer is written to byte 20, and
usb_get_configuration()'s 9-byte and usb_get_status()'s 2-byte buffers
to byte 32. Without red zones the extra bytes usually land in the unused
rest of the kmalloc slot.
Also bounce IN buffers that are too short, through a buffer that holds
whole packets, for isochronous URBs up to the end of the furthest frame.
Keep the bounce buffer's bookkeeping in front of the data instead of
behind it, where an overrun could reach it and where the free path had
to recompute the length: the data starts on a cache line of its own,
the bookkeeping sits in the line before. For isochronous IN, copy back
only what each frame received, so that gaps the caller cleared (usbfs
does) don't get the uninitialized bounce buffer's contents. Leave
URB_NO_TRANSFER_DMA_MAP URBs alone, as the controller DMAs to the
caller's transfer_dma; this change does not protect those buffers.
Link: https://lore.kernel.org/linux-usb/20200226210414.28133-2-linux@roeck-us.net/
Fixes: 7359d482eb4d ("staging: HCD files for the DWC2 driver")
Cc: stable@vger.kernel.org
Cc: Guenter Roeck <linux@roeck-us.net>
Cc: Doug Anderson <dianders@chromium.org>
Signed-off-by: Hunter Laux <hunterlaux@gmail.com>
---
Notes:
Changes in v2 (Sashiko's review of v1):
- Keep the bounce buffer's bookkeeping (the kmalloc() pointer and the
caller's transfer_buffer) in front of the data, in the cache line
before it, instead of behind the data. An isochronous overrun could
reach the pointer behind the data, and the free path had to
recompute the length to find it, which went wrong if ep0's
wMaxPacketSize changed in between (a device reset that corrects
bMaxPacketSize0 while a usbfs control URB is in flight).
- Size isochronous IN bounce buffers to the end of the furthest frame,
each frame rounded up to whole packets, as dwc2 programs the frames
one at a time at their offsets. v1 only rounded the total.
- For isochronous IN, copy back only each frame's received bytes, not
the whole buffer, so gaps the caller cleared (usbfs does) don't get
the uninitialized bounce buffer's contents.
- Link to v1: https://lore.kernel.org/linux-usb/20261205073050.1510448-1-hunterlaux@gmail.com/
How much of that was there before v1: the pointer behind the data, the
uninitialized bounce buffer and the whole-buffer isochronous copy-back
are all in the current code, but it bounces only misaligned buffers, so
they could only be reached through a misaligned isochronous IN buffer.
v1's wider bounce condition made them reachable with ordinary aligned
buffers: usbfs isochronous IN buffers would have been bounced, leaking
slab contents to userspace. The ep0 wMaxPacketSize case came with v1
itself, whose free path recomputed the length; the current code only
uses transfer_buffer_length there. v2 also closes the misaligned
variants: the bookkeeping in front protects misaligned isochronous
buffers too, and the per-frame copy-back applies to every bounced
isochronous IN URB.
How it was found: SLUB red zones (CONFIG_SLUB_DEBUG_ON) in a debug
build used to chase unrelated MMC corruption on the X2600. The overrun
reports showed up at every boot, during enumeration.
The analysis, the fix and the test module were developed with an AI
coding assistant (Claude); I reviewed them and ran the tests below on
the hardware.
Prior work (the Link: above): Guenter Roeck found the same overrun in
2020 while chasing receive corruption on Veyron Chromebooks and proposed
rounding the bounce buffer up to whole packets as part of a rework of
the alignment code. That RFT was not merged, and as it only changed the
bounce buffer, aligned short buffers would still have gone to the
controller directly.
Why in front: the end of the data is exactly where this overrun
writes. A pointer stored behind the data is overwritten by any overrun
longer than the length it was placed after (the isochronous case above,
or any future misjudgment of how far the controller writes), and the
free path then memcpy()s to that garbage address and hands it back as
urb->transfer_buffer. Finding it there also requires the free path to
recompute the length, a contract between alloc and free that breaks as
soon as an input changes in between (ep0's wMaxPacketSize). The
controller only writes forward from the data, so bookkeeping in front of
it cannot be reached, and the free path finds it at a fixed offset.
The bookkeeping in front of the data: 3bc04e28a030 kept it there, but
let the data start right after it, so it was not cache line aligned and
non-coherent MIPS corrupted it; 56406e017a88 and 4a4863bf2e79 then moved
the pointer behind the data, padded into a cache line of its own. v2
keeps both of those properties: the data starts on a cache line
boundary (PTR_ALIGN(.., dma_get_cache_alignment())), and the
bookkeeping ends right before it, in the previous line, which the
mapping of the data never touches.
How far the controller writes: the observed overruns stop at the next
4-byte (18 -> 20) or 32-byte (9, 2 -> 32) boundary, which looks like
word and AHB burst granularity rather than the whole packet. The buffer
is still rounded up to whole packets, the size the channel is
programmed with, as the only bound the driver can rely on.
The DMA mapping: usb_hcd_map_urb_for_dma() still maps only
transfer_buffer_length of the (now larger) bounce buffer, as before
this patch. Without swiotlb that is harmless: the bytes past the
mapping belong to the bounce buffer and are never copied back. With
swiotlb the overrun lands in swiotlb's buffer instead; for packet sizes
that divide its 2 KiB slots (every control and bulk endpoint, and
interrupt endpoints with power-of-two packets) it stays within the
slots of this mapping. This patch does not change that path.
Isochronous IN: a frame's overrun falls into the next frame's space,
which that frame then overwrites, and the buffer now reaches the end of
the furthest frame, so frame layouts that are not multiples of the
packet size (snd-usb-audio capture places frames at its current packet
size) are covered too. The high-bandwidth multiplier needs nothing
extra, as the channel's max_packet is usb_endpoint_maxp(), without it.
Testing: Ingenic X2600, DWC OTG core 3.00a (GSNPSID 0x4F54300A), host
mode, buffer DMA, 128-byte DMA alignment, dwc2's default AHB burst
setting (INCR). Letux 7.4-rc5 plus out-of-tree X2600 platform patches;
the patch applies to v7.4-rc5 as is. Debug kernel: SLUB_DEBUG_ON,
PROVE_LOCKING, DEBUG_ATOMIC_SLEEP, DEBUG_SG, DEBUG_LIST,
DEBUG_KMAP_LOCAL. Devices: a Genesys GL850G hub and a Realtek RTL8821CU
Wi-Fi adapter (rtw88, high speed, 512-byte bulk endpoints).
- Red zones: reports at every enumeration without the patch (above),
none with it.
- Write and verify stress for 25 minutes with the Wi-Fi up: no data
errors, no debug reports.
- An out-of-tree test module, 200 iterations each:
- bounce: GET_DESCRIPTOR(DEVICE) into an 18-byte kmalloc() buffer,
which is bounced: the data is correct and urb->transfer_buffer is
the caller's buffer again after every completion;
- URB_NO_TRANSFER_DMA_MAP: the same read into a usb_alloc_coherent()
buffer, which is not bounced: the data is correct (the buffer
still shows the overrun, bytes 18 and 19 written);
- teardown: a pending 100-byte bulk IN URB on the adapter's 512-byte
endpoint (driver unbound), given back with -ESHUTDOWN by
deauthorizing the device: urb->transfer_buffer is restored.
The last two fail on an earlier draft that bounced
URB_NO_TRANSFER_DMA_MAP URBs (the read returned SLUB poison) and
recomputed the stored pointer's offset from usb_maxpacket() (it
handed back 0x6b6b6b6b as the buffer).
Raspberry Pi 4 (BCM2711, arm64, the USB-C dwc2 port in host mode,
2 GB, swiotlb active for this controller's 1 GB DMA limit), v7.4-rc5
with the same debug options plus DMA_API_DEBUG, an RTL8153 (r8152) on
the port: the same module tests pass, no debug reports. Plain v7.4-rc5
shows no red zone reports there, presumably because the small
enumeration buffers are bounced through swiotlb, which then takes the
overrun (not traced); the coherent buffer shows the same 2-byte
overrun. RTL8153 throughput is unchanged within run-to-run variation:
r8152's receive buffers are whole packets, so nothing is bounced;
50-72 Mbit/s in and 124-138 Mbit/s out across runs on both kernels,
the unaffected OUT direction varying as much as IN.
Not tested: the isochronous changes (no isochronous device here),
descriptor DMA mode, split transactions. Not measured: the cost for
drivers whose IN buffers are not whole packets (cdc_ether's MTU-sized
receive buffers would be bounced on every packet); the RTL8153's CDC
ECM configuration did not pass traffic here.
Why not program the exact length instead: the core requires IN transfer
sizes in whole max-size packets (the comment in
dwc2_hc_start_transfer()), so the buffer has to be big enough.
Fixes: the overrun is reachable since the HCD import, 7359d482eb4d: it
handed URB buffers to the channel as they were and used its align
buffer only for misaligned ones, while the IN rounding came with the
core files just before it (56f5b1cff22a). The bounce code this patch
extends came with 3bc04e28a030 ("usb: dwc2: host: Get aligned DMA in a
more supported way"), v4.6, so stable trees before that need a
different fix.
drivers/usb/dwc2/hcd.c | 113 +++++++++++++++++++++++++++--------------
1 file changed, 76 insertions(+), 37 deletions(-)
diff --git a/drivers/usb/dwc2/hcd.c b/drivers/usb/dwc2/hcd.c
index 40ab50538334af..045ffdfb9de4b2 100644
--- a/drivers/usb/dwc2/hcd.c
+++ b/drivers/usb/dwc2/hcd.c
@@ -2452,69 +2452,108 @@ static int dwc2_alloc_split_dma_aligned_buf(struct dwc2_hsotg *hsotg,
#define DWC2_USB_DMA_ALIGN 4
+/* Kept just in front of the data of a bounce buffer */
+struct dwc2_dma_bounce {
+ void *kmalloc_ptr;
+ void *old_xfer_buffer;
+};
+
+/*
+ * IN transfers are programmed as a whole number of max-size packets (see
+ * dwc2_hc_start_transfer()), and after a short packet the controller can
+ * write past the bytes it received, up to that size. Isochronous frames are
+ * programmed one at a time, each at its own offset. Return how far the
+ * controller can write, which is what the DMA buffer has to hold.
+ */
+static size_t dwc2_dma_buffer_len(struct urb *urb)
+{
+ size_t len = urb->transfer_buffer_length;
+ unsigned int maxp;
+ int i;
+
+ if (!usb_urb_dir_in(urb))
+ return len;
+ maxp = usb_endpoint_maxp(&urb->ep->desc);
+ if (!maxp)
+ return len;
+ if (!usb_pipeisoc(urb->pipe))
+ return roundup(len, maxp);
+ for (i = 0; i < urb->number_of_packets; i++)
+ len = max_t(size_t, len, urb->iso_frame_desc[i].offset +
+ roundup(urb->iso_frame_desc[i].length, maxp));
+ return len;
+}
+
static void dwc2_free_dma_aligned_buffer(struct urb *urb)
{
- void *stored_xfer_buffer;
- size_t length;
+ struct dwc2_dma_bounce *b;
+ void *buf;
+ int i;
if (!(urb->transfer_flags & URB_ALIGNED_TEMP_BUFFER))
return;
- /* Restore urb->transfer_buffer from the end of the allocated area */
- memcpy(&stored_xfer_buffer,
- PTR_ALIGN(urb->transfer_buffer + urb->transfer_buffer_length,
- dma_get_cache_alignment()),
- sizeof(urb->transfer_buffer));
+ buf = urb->transfer_buffer;
+ b = buf - sizeof(*b);
if (usb_urb_dir_in(urb)) {
- if (usb_pipeisoc(urb->pipe))
- length = urb->transfer_buffer_length;
- else
- length = urb->actual_length;
-
- memcpy(stored_xfer_buffer, urb->transfer_buffer, length);
+ if (usb_pipeisoc(urb->pipe)) {
+ /* Only what was received: the gaps stay as they were */
+ for (i = 0; i < urb->number_of_packets; i++)
+ memcpy(b->old_xfer_buffer +
+ urb->iso_frame_desc[i].offset,
+ buf + urb->iso_frame_desc[i].offset,
+ min(urb->iso_frame_desc[i].actual_length,
+ urb->iso_frame_desc[i].length));
+ } else {
+ memcpy(b->old_xfer_buffer, buf, urb->actual_length);
+ }
}
- kfree(urb->transfer_buffer);
- urb->transfer_buffer = stored_xfer_buffer;
+ urb->transfer_buffer = b->old_xfer_buffer;
+ kfree(b->kmalloc_ptr);
urb->transfer_flags &= ~URB_ALIGNED_TEMP_BUFFER;
}
static int dwc2_alloc_dma_aligned_buffer(struct urb *urb, gfp_t mem_flags)
{
- void *kmalloc_ptr;
- size_t kmalloc_size;
+ struct dwc2_dma_bounce *b;
+ void *kmalloc_ptr, *buf;
+ size_t len;
+
+ /*
+ * The controller DMAs to urb->transfer_dma, so a buffer the caller
+ * mapped itself can't be bounced here
+ */
+ if (urb->num_sgs || urb->sg || urb->transfer_buffer_length == 0 ||
+ (urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
+ return 0;
- if (urb->num_sgs || urb->sg ||
- urb->transfer_buffer_length == 0 ||
+ /* Aligned and big enough for what the controller writes: use it */
+ len = dwc2_dma_buffer_len(urb);
+ if (len == urb->transfer_buffer_length &&
!((uintptr_t)urb->transfer_buffer & (DWC2_USB_DMA_ALIGN - 1)))
return 0;
/*
- * Allocate a buffer with enough padding for original transfer_buffer
- * pointer. This allocation is guaranteed to be aligned properly for
- * DMA
+ * The data starts on a cache line of its own, with the bookkeeping in
+ * front of it, in the previous line: nothing the controller writes
+ * shares a cache line with it, and the free path finds it without
+ * recomputing the length.
*/
- kmalloc_size = urb->transfer_buffer_length +
- (dma_get_cache_alignment() - 1) +
- sizeof(urb->transfer_buffer);
-
- kmalloc_ptr = kmalloc(kmalloc_size, mem_flags);
+ kmalloc_ptr = kmalloc(sizeof(*b) + dma_get_cache_alignment() - 1 + len,
+ mem_flags);
if (!kmalloc_ptr)
return -ENOMEM;
- /*
- * Position value of original urb->transfer_buffer pointer to the end
- * of allocation for later referencing
- */
- memcpy(PTR_ALIGN(kmalloc_ptr + urb->transfer_buffer_length,
- dma_get_cache_alignment()),
- &urb->transfer_buffer, sizeof(urb->transfer_buffer));
+ buf = PTR_ALIGN(kmalloc_ptr + sizeof(*b), dma_get_cache_alignment());
+ b = buf - sizeof(*b);
+ b->kmalloc_ptr = kmalloc_ptr;
+ b->old_xfer_buffer = urb->transfer_buffer;
if (usb_urb_dir_out(urb))
- memcpy(kmalloc_ptr, urb->transfer_buffer,
- urb->transfer_buffer_length);
- urb->transfer_buffer = kmalloc_ptr;
+ memcpy(buf, urb->transfer_buffer, urb->transfer_buffer_length);
+ urb->transfer_buffer = buf;
urb->transfer_flags |= URB_ALIGNED_TEMP_BUFFER;
base-commit: fe6ff8d5d675c01793b9f051d16055dd4aa75244
--
2.43.0
next reply other threads:[~2026-12-05 9:14 UTC|newest]
Thread overview: 2+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-05 9:14 Hunter Laux [this message]
2026-12-05 9:42 ` [PATCH v2] usb: dwc2: hcd: Fix DMA overrun of short IN buffers sashiko-bot
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261205091423.1543329-1-hunterlaux@gmail.com \
--to=hunterlaux@gmail.com \
--cc=Thinh.Nguyen@synopsys.com \
--cc=dianders@chromium.org \
--cc=gregkh@linuxfoundation.org \
--cc=linux-usb@vger.kernel.org \
--cc=linux@roeck-us.net \
--cc=stable@vger.kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox