All of lore.kernel.org
 help / color / mirror / Atom feed
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] usb: dwc2: hcd: Fix DMA overrun of short IN buffers
Date: Sat,  5 Dec 2026 00:30:50 -0700	[thread overview]
Message-ID: <20261205073050.1510448-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. dwc2_map_urb_for_dma() bounces only
misaligned buffers, so an aligned IN buffer whose length is not a whole
number of packets 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 whose length is not a whole number of max-size
packets, through a buffer rounded up to whole packets. 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:
    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. This patch keeps the existing bounce scheme and its
    cache line alignment, which the RFT's review found MIPS needs.
    
    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 stored pointer: dwc2_alloc_dma_aligned_buffer() keeps the caller's
    transfer_buffer at PTR_ALIGN(buffer + length, dma_get_cache_alignment())
    and dwc2_free_dma_aligned_buffer() recomputes that offset, so both use
    dwc2_dma_buffer_len(). It takes the packet size from urb->ep, as
    usb_maxpacket() returns 0 for the URBs that usb_disable_endpoint() gives
    back (it clears udev->ep_in[] first), which would make the free path
    look in the wrong place. Rounding the length also moves that pointer out
    of the overrun's reach.
    
    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: dwc2 programs each frame on its own, at urb->dma plus
    the frame's offset, rounded up to whole packets, so a frame's overrun
    falls into the next frame's space, which that frame then overwrites.
    Rounding the whole buffer covers the last frame when the frame offsets
    are multiples of the packet size, as in uvcvideo (i * max payload). It
    does not when they are not: snd-usb-audio capture places frames at its
    current packet size, which can be below the endpoint's, and there the
    last frame can still reach past the rounded buffer. 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).
     - Before: red zone reports at every enumeration (above). After: none.
     - Write and verify stress with the Wi-Fi up, no data errors, no debug
       reports.
     - URB_NO_TRANSFER_DMA_MAP: 200 GET_DESCRIPTOR(DEVICE) reads (18 bytes,
       ep0 maxp 64) into a usb_alloc_coherent() buffer, compared with the
       cached descriptor: all 200 correct. An earlier version of this patch,
       which bounced such URBs, returned the bounce buffer's SLUB poison
       (6b 6b ...) instead of the descriptor in all 200. The coherent buffer
       still shows the overrun: bytes 18 and 19 written by the controller.
     - Endpoint teardown: a pending 100-byte bulk IN URB on the adapter's
       512-byte bulk endpoint (driver unbound), given back with -ESHUTDOWN
       by deauthorizing the device: urb->transfer_buffer is the caller's
       buffer again. The earlier version, which took the size from
       usb_maxpacket(), read the stored pointer at the wrong offset and
       handed back 0x6b6b6b6b (SLUB poison) as the caller's buffer.
    Also tested on a 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, with an RTL8153
    (r8152) on the port. 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 test shows the same 2-byte overrun as on the X2600, and both
    module tests pass with this patch. Throughput
    through the RTL8153 is unchanged (r8152's receive buffers are whole
    packets, so nothing is bounced): about 61-72 Mbit/s in, 137-138 Mbit/s
    out on these debug kernels, the receive spread being run-to-run noise,
    with the same CPU use on both kernels.
    Not tested: descriptor DMA mode, split transactions, isochronous IN.
    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
    on this setup, so it could not serve as that test.
    
    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 | 47 +++++++++++++++++++++++++++++++++++-------
 1 file changed, 39 insertions(+), 8 deletions(-)

diff --git a/drivers/usb/dwc2/hcd.c b/drivers/usb/dwc2/hcd.c
index 40ab50538334af..ac12b3cc8d2130 100644
--- a/drivers/usb/dwc2/hcd.c
+++ b/drivers/usb/dwc2/hcd.c
@@ -2452,6 +2452,30 @@ static int dwc2_alloc_split_dma_aligned_buf(struct dwc2_hsotg *hsotg,
 
 #define DWC2_USB_DMA_ALIGN 4
 
+/*
+ * IN transfers are programmed as a whole number of max-size packets (see
+ * dwc2_hc_start_transfer()), and after a short packet the controller may
+ * write past the bytes it received, up to that size. The DMA buffer of an
+ * IN transfer is therefore a whole number of packets long.
+ *
+ * The size comes from urb->ep, not from usb_maxpacket(): the URBs of an
+ * endpoint being disabled are given back after usb_disable_endpoint() has
+ * cleared it in udev->ep_in[], and dwc2_free_dma_aligned_buffer() must get
+ * the same length as dwc2_alloc_dma_aligned_buffer() did.
+ */
+static size_t dwc2_dma_buffer_len(struct urb *urb)
+{
+	size_t len = urb->transfer_buffer_length;
+	unsigned int maxp;
+
+	if (usb_urb_dir_in(urb)) {
+		maxp = usb_endpoint_maxp(&urb->ep->desc);
+		if (maxp)
+			len = roundup(len, maxp);
+	}
+	return len;
+}
+
 static void dwc2_free_dma_aligned_buffer(struct urb *urb)
 {
 	void *stored_xfer_buffer;
@@ -2462,7 +2486,7 @@ static void dwc2_free_dma_aligned_buffer(struct urb *urb)
 
 	/* Restore urb->transfer_buffer from the end of the allocated area */
 	memcpy(&stored_xfer_buffer,
-	       PTR_ALIGN(urb->transfer_buffer + urb->transfer_buffer_length,
+	       PTR_ALIGN(urb->transfer_buffer + dwc2_dma_buffer_len(urb),
 			 dma_get_cache_alignment()),
 	       sizeof(urb->transfer_buffer));
 
@@ -2483,10 +2507,19 @@ static void dwc2_free_dma_aligned_buffer(struct urb *urb)
 static int dwc2_alloc_dma_aligned_buffer(struct urb *urb, gfp_t mem_flags)
 {
 	void *kmalloc_ptr;
-	size_t kmalloc_size;
+	size_t kmalloc_size, len;
 
-	if (urb->num_sgs || urb->sg ||
-	    urb->transfer_buffer_length == 0 ||
+	/*
+	 * 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;
+
+	/* Aligned and a whole number of packets long: the caller's buffer */
+	len = dwc2_dma_buffer_len(urb);
+	if (len == urb->transfer_buffer_length &&
 	    !((uintptr_t)urb->transfer_buffer & (DWC2_USB_DMA_ALIGN - 1)))
 		return 0;
 
@@ -2495,8 +2528,7 @@ static int dwc2_alloc_dma_aligned_buffer(struct urb *urb, gfp_t mem_flags)
 	 * pointer. This allocation is guaranteed to be aligned properly for
 	 * DMA
 	 */
-	kmalloc_size = urb->transfer_buffer_length +
-		(dma_get_cache_alignment() - 1) +
+	kmalloc_size = len + (dma_get_cache_alignment() - 1) +
 		sizeof(urb->transfer_buffer);
 
 	kmalloc_ptr = kmalloc(kmalloc_size, mem_flags);
@@ -2507,8 +2539,7 @@ static int dwc2_alloc_dma_aligned_buffer(struct urb *urb, gfp_t mem_flags)
 	 * 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()),
+	memcpy(PTR_ALIGN(kmalloc_ptr + len, dma_get_cache_alignment()),
 	       &urb->transfer_buffer, sizeof(urb->transfer_buffer));
 
 	if (usb_urb_dir_out(urb))

base-commit: fe6ff8d5d675c01793b9f051d16055dd4aa75244
-- 
2.43.0


             reply	other threads:[~2026-12-05  7:31 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-05  7:30 Hunter Laux [this message]
2026-12-05  7:56 ` [PATCH] 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=20261205073050.1510448-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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.