From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.43 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796462070; b=tcaP9WWDYsaAJQgvsQmiOKKJZ3vPjJRanA+xpyT9pOY9tMh/psMNozZj9xBvyZDNVllW S+inLpTKOwa+ClYD/EWUKVSTZ4GOI46t+Ybs5vDp4V62rF9xK7zDcAQnbNygEr/DYEFQw 6v1pxT1J8h9XXyvnAMo1PxNDNtt5FEkgrfFNA7ABbRB2dH3P24LKKKWFQO82rkL61ElqW UiLp1faKJG4xQpmCs7FZ9+4colE57A2ZY1XCkpta9T1iWG48/BCX4foj0gR1L0IA/yP+L Yd/dfAniPjKiclVxj+noilaXtnw9nGvyK9Hfu7eecctdad9M8fW/0x2ULYRpuArWzhA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796462070; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Gm-Message-State:X-Gm-Gg:X-Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:MIME-Version:Content-Transfer-Encoding; bh=Z2L12//NUb2/VZojkHufEO09NpBuKgJFctGU7W2C8Q8=; b=fpK2MFuDi7s+jTDHS78rhOyY55Gl5FMn1m9xk6UV6iCpyp9VHnyab3Z3Z7mB8SjBtCrP DZlkYTXy2tMNvXRZde6u3Jdjx8dOmqMoy4CUeRgxQurRPbgg599bt5beO0lX/ocnhnQAz ARLEyXAitZP9FRgUkv9OK6n4pxONWALrhBzMoDE1oTCswqecrtPkcrMMy05qdt85J/HFR zDgAHRO2JsnJSFvr+99pIjNCl5JQI2ob0d9xoW1pXAzD8oFuNBrA74XHy7Y+wecAES26G /Llp5/r6BkndS1vrkDzQFZd4ukkoyB01TBE4FZRpBPNoVbdu/V2sHotI50gHEL0st7w== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=Pe+YOCVn; arc=none smtp.remote-ip=74.125.82.43 Received: from mail-dl1-f43.google.com (mail-dl1-f43.google.com [74.125.82.43]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9E7B9606A322 for ; Sat, 5 Dec 2026 09:14:29 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 9E7B9606A322 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key, unprotected) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=Pe+YOCVn Received: by mail-dl1-f43.google.com with SMTP id a92af1059eb24-1b5d5f3d5b8so1817261c88.0 for ; Sat, 05 Dec 2026 01:14:29 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796462069; x=1797066869; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to:content-type; bh=Z2L12//NUb2/VZojkHufEO09NpBuKgJFctGU7W2C8Q8=; b=Pe+YOCVn/sHQRmlVGYFW0FTuVuH1AxBlbex65cAxnm76f/I4taMSKSS6u72s2wZoi9 3RolN7CxaiLMwjYvdA6xeSU3xKeT09Khs5bQbx8vqOjITr1C0+mzIHZK9fpGtlJszo9Q hcoWOVzaxygQ4Gj7UPYrT8JQZK9K8IqdwowSUQNA0XIKxF9IDe9mOtgsftu3U8lDnjFA JrXYVD/fBzBc9scYv1GX83qkuz0zJsom6/fEyOmOcQ6p2inKqYSz46I/YWG9ghT3Frg5 3fUsRiBXGn0hTfd8huNWpHY+5pv2/hEfWVNZf79sGSKzJeWWEyLlWpGzC8e6VjydOLq5 MAWw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796462069; x=1797066869; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=Z2L12//NUb2/VZojkHufEO09NpBuKgJFctGU7W2C8Q8=; b=HSFrWQnmDf7MDz0+cD59GGmP8KH65czUJ+uZbcqtSQ/tWMp2kDCj3xfK93soJleUnd 8K/9T4sIRgPr61JZjy5Uv+AtZU7i2scT9kWjCC2OoV8tw+qQr+TeGIfVDaHy6KFKG316 bl5pm9XBETUC+RFrECUG/X5nylFKuXrYahqlKEC0/3t4tSE48nnLn2+XAJ6gsWiIFty0 Uyc2/NQFyF3mZoSIKXQiopSDSUc5V+LSaZI4A2Be2LEvSv6dGNtQAK1yWIZfL8VXpD0d /ePTDq0+BOGvSnH/aRnQENg25CFIRBrDQildgn3TMJW0U+9gZBPUGvz4boETvdvqQCzt D6bA== X-Gm-Message-State: APuU4Z+nMMDVe6p7MyUspaiFDnMMkxONAkizym2iu834yGOTiSt9IVaO Kw8v20bVH6Xwiqcl9b5tqKqITPHeZuDm+rLMS3yOK2ql6Rt1wnQJhkPm X-Gm-Gg: AZFdTZfbGpF01uH5lwvZB99j4fvZPSMezxF/deLjcexLJtLQPXSk8R9PJo+XNsBNLo9 +G+Kgo3INKw3j5hPXqkcgCgZIquF/9k7CSvoeAglUY7BMUDBrETWEBiLUW+wzKa0D6zEeqmt/jy NErBTO093letExVFr9u8Nxx5ze6KtYhVx/2fbHnV9zx7ZVMJdSxYGGstQPwfULdZ39A/Am42Uah v6UEZ5IcTsj1dSndrhnVYhwtiGSM3k4zhTDycyn/+QtWZZ1tuPcaFOuTzdtMlRHFqHw8x57kaOo wwal6SgvMrmE5GO2QB4X8WDljQPz//Xy8iKvc29zf7Q1MBe8yqE8bwsZFUcyWDBDksz9aH2vxKD SciL8MKchpxhtEc/mdGqy0JjcU9Dyl3fwjJAMJ0h1/F3Hk7cVCk8zt/Ty2gWcgT5ufRMIFIvZn4 4TQq9nr7pbRFDoPfJcRk4qf3xEpkFAqDsjw9VYwOoMUN+tv4RoM0OuEgQhqNn+dgToNTKFWK8Ju jyIp+q2OEQZA/b4JsFHDPu2YtpCZDbwRK4Pbq5lieHx1b8aHIN8P5t7ougvMRswzHxiQB79nPjc CqRLgE/bT/u9Mp5n2JjfrgGqs+mqZ3Ilp35MhA8u156NYN/wmpzEd70oPa+vCd94u/qduLo+YtO Ro/rN X-Received: by 2002:a05:701b:220b:b0:1b5:c45e:5e70 with SMTP id a92af1059eb24-1b5d712b89emr3435862c88.22.1796462068266; Sat, 05 Dec 2026 01:14:28 -0800 (PST) Received: from smalls.localdomain (ip-198-145-71-161.az.bambroadband.net. [198.145.71.161]) by smtp.gmail.com with ESMTPSA id a92af1059eb24-1b5d642e254sm14914046c88.4.2026.12.05.01.14.27 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sat, 05 Dec 2026 01:14:27 -0800 (PST) From: Hunter Laux To: Thinh Nguyen , Greg Kroah-Hartman Cc: linux-usb@vger.kernel.org, Hunter Laux , stable@vger.kernel.org, Guenter Roeck , Doug Anderson Subject: [PATCH v2] usb: dwc2: hcd: Fix DMA overrun of short IN buffers Date: Sat, 5 Dec 2026 02:14:23 -0700 Message-ID: <20261205091423.1543329-1-hunterlaux@gmail.com> X-Mailer: git-send-email 2.43.0 X-Mailing-List: linux-usb@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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 Cc: Doug Anderson Signed-off-by: Hunter Laux --- 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