* [PATCH v3 0/3] usb: core: fix three use-after-free windows in the USB anchor protocol
@ 2026-11-27 13:28 Hongyu Xie
2026-11-27 13:28 ` [PATCH v3 1/3] usb: core: Fix use-after-free in anchor wakeup protocol Hongyu Xie
` (2 more replies)
0 siblings, 3 replies; 5+ messages in thread
From: Hongyu Xie @ 2026-11-27 13:28 UTC (permalink / raw)
To: Greg KH, Alan Stern
Cc: Oliver Neukum, oliver, Hans de Goede, linux-usb, linux-kernel
Anchors are usually embedded in driver-private structures, and
several anchor API returns -- a non-zero
usb_wait_anchor_empty_timeout(), usb_kill_anchored_urbs(),
usb_poison_anchored_urbs() and usb_scuttle_anchored_urbs() --
license the caller to free that memory. The wakeup protocol backing
this license has three windows in which a URB giveback or unanchor
still touches the anchor after the caller has been told it is
unused:
1. The waiter's condition check and the giveback's
suspend_wakeups decrement plus wake_up() were not serialized,
so the waiter could return while a giveback was still in
flight. Reported by syzbot repeatedly since 2019; patch 1
references the two reports this analysis is built on.
2. __usb_hcd_giveback_urb() captured urb->anchor at the top of
the function but incremented suspend_wakeups only after DMA
unmapping and the usbmon hooks. A concurrent unanchor could
empty the anchor with suspend_wakeups still zero, so the waiter
returned and freed the anchor underneath the pending increment.
No syzbot report is attributed to this interleaving; it was
found by extending the analysis of patch 1.
3. usb_unanchor_urb() and the giveback read urb->anchor and only
then acquire anchor->lock; between the two the anchor can
already have been freed. The gap is as old as
usb_unanchor_urb() itself and cannot be closed with a
reference count: the first dereference of the freshly read
pointer would have to be the increment itself.
Patch 1 completes the locking protocol for the waiter/wakeup side.
Patch 2 folds the giveback's pointer capture, the increment and the
unanchor into a single anchor->lock critical section. Patch 3
turns the wakeup protocol into a contention-gated RCU lifetime
protocol: lockless anchor readers register in a usbcore-private
per-URB counter (urb->anchor_readers) inside RCU read-side critical
sections, urb->anchor is published with rcu_assign_pointer(),
__usb_unanchor_urb() snapshots get_state_synchronize_rcu() onto the
anchor only when another reader is concurrently in flight on that
URB, and every teardown return that lets the caller free the anchor
calls cond_synchronize_rcu() only when an unelapsed contended grace
period is pending (touching nothing on the anchor after unlocking).
Contract notes for patch 3:
- usb_kill_anchored_urbs(), usb_poison_anchored_urbs() and
usb_scuttle_anchored_urbs() may sleep even on an empty anchor
(when draining an in-flight giveback pin or waiting for a
contended unanchor's grace period): the empty-anchor retry blocks
on the anchor's wait queue instead of busy-waiting.
usb_scuttle_anchored_urbs() is the only sleeping-context contract
change among the three (the others already slept transitively
through usb_kill_urb()/usb_poison_urb()), and all three carry a
might_sleep() at entry so an atomic-context caller is caught at
the call site with debugging configurations enabled. All in-tree
callers already sleep.
- Uncontended waits and drains on persistent or empty anchors pay
zero RCU grace periods, and usb_wait_anchor_empty_timeout()
preserves its remaining-jiffies return value on uncontended
waits. Only when two threads actually raced to unanchor a URB on
the anchor (and that grace period has not yet elapsed) does a
successful wait or drain wait in cond_synchronize_rcu(), in which
case usb_wait_anchor_empty_timeout() may overrun its timeout by
up to one grace period and clamps its non-zero return to at
least 1.
- The safe-to-free license is per caller: a caller that frees on
its own successful return must first wait for any other
in-flight teardown calls to return. The kerneldoc of all four
teardown returns states this proviso alongside the no-new-URBs
one.
Why the retry loop must not busy-wait: on !PREEMPT_RCU kernels
whose scheduler tick reports no quiescent state for a spinning
process context (the v6.6 stable tree, for one; the 7.3 base adds
process context only with CONFIG_PREEMPT_COUNT), a busy retry stalls
every grace period that still awaits that CPU's quiescent state for
as long as it spins, and under real-time scheduling it can starve
the very completion path it is waiting for.
The sleeping retry keeps the re-drain behavior of the busy loop it
replaces: usb_anchor_urb() wakes the anchor's wait queue (gated by
waitqueue_active() under anchor->lock, so the per-submission hot
path stays off the wakeup machinery when no drain is sleeping), and
the wait also ends -- without declaring the anchor unused -- when a
URB is anchored after the drain, so the drain restarts and tears
the late arrival down too.
No driver changes are needed: struct urb gains a usbcore-private
reader counter (anchor_readers), and struct usb_anchor records the
conditional grace-period state (need_rcu_gp and rcu_gp_seq).
checkpatch: 0 errors, 0 warnings for all three patches.
Signed-off-by: Hongyu Xie <xiehongyu1@kylinos.cn>
---
Changes in v3 (patch 3 only; patches 1 and 2 are unchanged):
- Gate the teardown RCU grace period on actual unanchor contention
(urb->anchor_readers + anchor->need_rcu_gp / anchor->rcu_gp_seq +
cond_synchronize_rcu()) instead of calling synchronize_rcu()
unconditionally on every successful wait and drain. Runtime I/O
paths that wait on or drain persistent or empty anchors without
unanchor races (such as zd1211rw register write batches, hiface
PCM stream stops, usbtmc reads and btusb traffic stops) now pay
zero grace periods, and usb_wait_anchor_empty_timeout() preserves
its remaining-jiffies return value on uncontended waits.
- Link to v2: https://lore.kernel.org/r/179577006613.23588.1120308700542393912@kylinos.cn
Changes in v2 (patches 2 and 3; patch 1 is unchanged; rebased onto
v7.4-rc3 in RESEND v2):
- Patch 2's usb_unanchor_urb_and_suspend_wakeups() race-loser
path unlocked each branch's locked anchor before clearing the
local anchor pointer to NULL.
- Replaced the kill/poison/scuttle empty-anchor busy-wait retry
with a sleepable wait_event() on anchor->wait that re-drains
late-anchored URBs via waitqueue_active()-gated wakeups in
usb_anchor_urb().
- Dropped teardown-side suspend_wakeups pins and updated kerneldoc
and Documentation/driver-api/usb/anchors.rst to document the
teardown lifetime contract and per-caller proviso.
Hongyu Xie (3):
usb: core: Fix use-after-free in anchor wakeup protocol
usb: core: Close anchor capture-to-increment race in URB giveback
usb: core: Close residual anchor read-to-lock window with RCU
Documentation/driver-api/usb/anchors.rst | 26 +-
drivers/usb/core/hcd.c | 10 +-
drivers/usb/core/urb.c | 490 ++++++++++++++++++++++++++++---
drivers/usb/core/usb.h | 1 +
include/linux/usb.h | 10 +-
5 files changed, 488 insertions(+), 49 deletions(-)
base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3
--
2.39.5
^ permalink raw reply [flat|nested] 5+ messages in thread
* [PATCH v3 1/3] usb: core: Fix use-after-free in anchor wakeup protocol
2026-11-27 13:28 [PATCH v3 0/3] usb: core: fix three use-after-free windows in the USB anchor protocol Hongyu Xie
@ 2026-11-27 13:28 ` Hongyu Xie
2026-11-27 13:57 ` Greg KH
2026-11-27 13:28 ` [PATCH v3 2/3] usb: core: Close anchor capture-to-increment race in URB giveback Hongyu Xie
2026-11-27 13:29 ` [PATCH v3 3/3] usb: core: Close residual anchor read-to-lock window with RCU Hongyu Xie
2 siblings, 1 reply; 5+ messages in thread
From: Hongyu Xie @ 2026-11-27 13:28 UTC (permalink / raw)
To: Greg KH, Alan Stern
Cc: Oliver Neukum, oliver, Hans de Goede, linux-usb, linux-kernel
usb_wait_anchor_empty_timeout() and the anchor cleanup helpers
promise that once they return successfully (non-zero, for
usb_wait_anchor_empty_timeout()), no URB giveback is in flight for
the anchor any more, so the driver may free the memory holding it
(xpad, for example, embeds irq_out_anchor in its private structure
and kfrees it in xpad_disconnect()).
Two windows break this promise: the waiter can observe "anchor
list empty and suspend_wakeups == 0" while a giveback is still
about to access anchor->wait.
1. usb_anchor_resume_wakeups() decrements suspend_wakeups -- which
makes the wait condition true -- and only then calls
wake_up(&anchor->wait), with nothing in between serializing the
two. A waiter returns, the driver frees the anchor, and the
late wake_up() touches the freed wait queue head.
2. __usb_unanchor_urb() wakes waiters while holding anchor->lock,
but usb_wait_anchor_empty_timeout() evaluated the same condition
without the lock, so it could observe the emptied urb_list in
the middle of that critical section and return before the
wake_up() and the spin_unlock() had run. Reading the two
condition fields locklessly could likewise observe a stale
suspend_wakeups value after the giveback's unanchor on weakly
ordered systems.
Complete the locking protocol that commit fbc299437c06 ("usb:
core: Solve race condition in anchor cleanup functions")
established for the kill/poison/scuttle helpers:
usb_wait_anchor_empty_timeout() now evaluates the condition under
anchor->lock (a self-locking wrapper around the lockless check),
and usb_anchor_resume_wakeups() performs the suspend_wakeups
decrement, the wakeup check and the wake_up() within a single
anchor->lock critical section.
With the decrement and the wake_up() atomic with respect to the
locked condition check, a waiter can only observe the condition
true after every giveback that has incremented suspend_wakeups has
stopped accessing the anchor: the guarantee that the wakeup is
delayed until the completion handler has run now extends to the
anchor memory itself.
syzbot has reported this race repeatedly since 2019, most
recently as:
BUG: KASAN: slab-use-after-free in register_lock_class+0x8d1/0x980 kernel/locking/lockdep.c:1333
[...]
__wake_up_common_lock+0x25/0x1e0 kernel/sched/wait.c:105
__usb_hcd_giveback_urb+0x3ac/0x530 drivers/usb/core/hcd.c:1653
Freed by task 7828:
[...]
kfree+0x14a/0x380 mm/slub.c:4390
xpad_disconnect+0x359/0x490 drivers/input/joystick/xpad.c:2194
and:
BUG: KASAN: use-after-free in register_lock_class+0xe6a/0x1120 kernel/locking/lockdep.c:1336
[...]
__wake_up_common_lock+0xb4/0x130 kernel/sched/wait.c:136
usb_anchor_resume_wakeups drivers/usb/core/urb.c:958 [inline]
usb_anchor_resume_wakeups+0xbe/0xe0 drivers/usb/core/urb.c:951
__usb_hcd_giveback_urb+0x2df/0x5c0 drivers/usb/core/hcd.c:1674
Freed by task 3889:
[...]
kfree+0x173/0x390 mm/slab.c:3786
xpad_disconnect+0x1cb/0x530 drivers/input/joystick/xpad.c:1905
Both reports lack a reproducer; the analysis was verified
by walking the two stacks against the code, not at runtime. All
in-tree callers of usb_wait_anchor_empty_timeout() (and every
driver which frees an anchor after the anchor cleanup helpers) are
equally affected; xpad is merely the one syzbot found.
Fixes: 6ec4147e7bdb ("usb-anchor: Delay usb_wait_anchor_empty_timeout wake up till completion is done")
Fixes: 51a2f077c44e ("USB: introduce usb_anchor")
Reported-by: syzbot+7f5e98b052c766f47f68@syzkaller.appspotmail.com
Closes: https://lore.kernel.org/r/00000000000090170a0614431f47@google.com
Reported-by: syzbot+59d3714b44d79d02f944@syzkaller.appspotmail.com
Closes: https://lore.kernel.org/r/00000000000038435e05e9f94cd4@google.com
Cc: stable@vger.kernel.org
Cc: Alan Stern <stern@rowland.harvard.edu>
Cc: Oliver Neukum <oliver@neukum.org>
Cc: Hans de Goede <hansg@kernel.org>
Signed-off-by: Hongyu Xie <xiehongyu1@kylinos.cn>
---
drivers/usb/core/urb.c | 51 +++++++++++++++++++++++++++++++++++++-----
1 file changed, 45 insertions(+), 6 deletions(-)
diff --git a/drivers/usb/core/urb.c b/drivers/usb/core/urb.c
index ae0d61b5081f..bb1778d9e9db 100644
--- a/drivers/usb/core/urb.c
+++ b/drivers/usb/core/urb.c
@@ -139,19 +139,39 @@ void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor)
}
EXPORT_SYMBOL_GPL(usb_anchor_urb);
-static int usb_anchor_check_wakeup(struct usb_anchor *anchor)
+/* Callers must hold anchor->lock */
+static int __usb_anchor_check_wakeup(struct usb_anchor *anchor)
{
return atomic_read(&anchor->suspend_wakeups) == 0 &&
list_empty(&anchor->urb_list);
}
+/*
+ * Same check as __usb_anchor_check_wakeup(), but takes anchor->lock. It is
+ * meant for waiters which do not hold the lock: the critical section
+ * serializes with the URB giveback path, so once the check succeeds no
+ * giveback that has incremented suspend_wakeups will touch the anchor
+ * anymore and the caller may free the memory holding the anchor.
+ */
+static int usb_anchor_check_wakeup(struct usb_anchor *anchor)
+{
+ unsigned long flags;
+ int wakeup;
+
+ spin_lock_irqsave(&anchor->lock, flags);
+ wakeup = __usb_anchor_check_wakeup(anchor);
+ spin_unlock_irqrestore(&anchor->lock, flags);
+
+ return wakeup;
+}
+
/* Callers must hold anchor->lock */
static void __usb_unanchor_urb(struct urb *urb, struct usb_anchor *anchor)
{
urb->anchor = NULL;
list_del(&urb->anchor_list);
usb_put_urb(urb);
- if (usb_anchor_check_wakeup(anchor))
+ if (__usb_anchor_check_wakeup(anchor))
wake_up(&anchor->wait);
}
@@ -835,7 +855,7 @@ void usb_kill_anchored_urbs(struct usb_anchor *anchor)
usb_put_urb(victim);
spin_lock_irq(&anchor->lock);
}
- surely_empty = usb_anchor_check_wakeup(anchor);
+ surely_empty = __usb_anchor_check_wakeup(anchor);
spin_unlock_irq(&anchor->lock);
cpu_relax();
@@ -874,7 +894,7 @@ void usb_poison_anchored_urbs(struct usb_anchor *anchor)
usb_put_urb(victim);
spin_lock_irq(&anchor->lock);
}
- surely_empty = usb_anchor_check_wakeup(anchor);
+ surely_empty = __usb_anchor_check_wakeup(anchor);
spin_unlock_irq(&anchor->lock);
cpu_relax();
@@ -927,12 +947,23 @@ EXPORT_SYMBOL_GPL(usb_anchor_suspend_wakeups);
*/
void usb_anchor_resume_wakeups(struct usb_anchor *anchor)
{
+ unsigned long flags;
+
if (!anchor)
return;
+ /*
+ * The decrement, the wakeup check and the wake_up() must happen
+ * under anchor->lock: usb_wait_anchor_empty_timeout() waiters
+ * evaluate the same condition under the lock and may free the
+ * anchor once they observe it true, so this function must not
+ * touch anchor->wait after that.
+ */
+ spin_lock_irqsave(&anchor->lock, flags);
atomic_dec(&anchor->suspend_wakeups);
- if (usb_anchor_check_wakeup(anchor))
+ if (__usb_anchor_check_wakeup(anchor))
wake_up(&anchor->wait);
+ spin_unlock_irqrestore(&anchor->lock, flags);
}
EXPORT_SYMBOL_GPL(usb_anchor_resume_wakeups);
@@ -949,6 +980,14 @@ EXPORT_SYMBOL_GPL(usb_anchor_resume_wakeups);
int usb_wait_anchor_empty_timeout(struct usb_anchor *anchor,
unsigned int timeout)
{
+ /*
+ * The condition must be evaluated under anchor->lock: when this
+ * function returns non-zero, every URB giveback that has incremented
+ * suspend_wakeups has finished with the anchor, so the caller may
+ * free the anchor, which is typically embedded in the driver's
+ * private structure. A zero return (timeout) means a giveback may
+ * still be in flight and gives no such guarantee.
+ */
return wait_event_timeout(anchor->wait,
usb_anchor_check_wakeup(anchor),
msecs_to_jiffies(timeout));
@@ -1005,7 +1044,7 @@ void usb_scuttle_anchored_urbs(struct usb_anchor *anchor)
struct urb, anchor_list);
__usb_unanchor_urb(victim, anchor);
}
- surely_empty = usb_anchor_check_wakeup(anchor);
+ surely_empty = __usb_anchor_check_wakeup(anchor);
spin_unlock_irqrestore(&anchor->lock, flags);
cpu_relax();
base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3
--
2.39.5 (Apple Git-154)
^ permalink raw reply [flat|nested] 5+ messages in thread
* [PATCH v3 2/3] usb: core: Close anchor capture-to-increment race in URB giveback
2026-11-27 13:28 [PATCH v3 0/3] usb: core: fix three use-after-free windows in the USB anchor protocol Hongyu Xie
2026-11-27 13:28 ` [PATCH v3 1/3] usb: core: Fix use-after-free in anchor wakeup protocol Hongyu Xie
@ 2026-11-27 13:28 ` Hongyu Xie
2026-11-27 13:29 ` [PATCH v3 3/3] usb: core: Close residual anchor read-to-lock window with RCU Hongyu Xie
2 siblings, 0 replies; 5+ messages in thread
From: Hongyu Xie @ 2026-11-27 13:28 UTC (permalink / raw)
To: Greg KH, Alan Stern
Cc: Oliver Neukum, oliver, Hans de Goede, linux-usb, linux-kernel
__usb_hcd_giveback_urb() captures urb->anchor into a local
variable at the top of the function, but increments the anchor's
suspend_wakeups counter only after unmapping the URB for DMA and
running the usbmon hooks. Nothing pins the anchor during that
window. If the URB is concurrently unanchored by another thread --
a driver calling usb_unanchor_urb() on its own in-flight URB, or
usb_get_from_anchor() or usb_scuttle_anchored_urbs() taking it --
the anchor list can become empty while suspend_wakeups is still
zero. A usb_wait_anchor_empty_timeout() waiter then observes the
condition true, returns, and the driver frees the anchor (anchors
are typically embedded in driver-private structures); the giveback's
atomic_inc() on the captured pointer, and the later decrement and
wake_up() in usb_anchor_resume_wakeups(), operate on freed memory.
The previous fix ("usb: core: Fix use-after-free in anchor wakeup
protocol") made both the waiter's condition check and the wakeup
side hold anchor->lock, but its guarantee was deliberately scoped
to givebacks that had already incremented suspend_wakeups: the
capture-to-increment gap remained open.
Fold the pointer capture, the increment and the unanchor into a
single anchor->lock critical section which re-verifies that
urb->anchor still names the captured anchor, so a giveback that
lost the race to a concurrent unanchor performs no anchor work at
all. From the verified increment onward, a non-zero
suspend_wakeups keeps waiters from freeing the anchor until
usb_anchor_resume_wakeups() has finished with it.
What remains open is the few instructions between reading
urb->anchor and acquiring anchor->lock inside the new helper: a
concurrent unanchor plus waiter return plus anchor free would all
have to fit into that gap for the lock acquisition itself to touch
freed memory. This is the same residual exposure
usb_unanchor_urb() has had since usb_anchor was introduced; closing
it entirely would require a lifetime protocol change (reference
count or RCU) for anchors, which is out of scope for a bugfix.
No syzbot report has been attributed to this interleaving; it was
found by extending the analysis of the previous fix.
Fixes: 6ec4147e7bdb ("usb-anchor: Delay usb_wait_anchor_empty_timeout wake up till completion is done")
Cc: stable@vger.kernel.org
Cc: Alan Stern <stern@rowland.harvard.edu>
Cc: Oliver Neukum <oliver@neukum.org>
Cc: Hans de Goede <hansg@kernel.org>
Signed-off-by: Hongyu Xie <xiehongyu1@kylinos.cn>
---
drivers/usb/core/hcd.c | 10 ++++++---
drivers/usb/core/urb.c | 48 ++++++++++++++++++++++++++++++++++++++++++
drivers/usb/core/usb.h | 1 +
3 files changed, 56 insertions(+), 3 deletions(-)
diff --git a/drivers/usb/core/hcd.c b/drivers/usb/core/hcd.c
index 8e8a5f59b319..f221425fec0a 100644
--- a/drivers/usb/core/hcd.c
+++ b/drivers/usb/core/hcd.c
@@ -1630,7 +1630,7 @@ int usb_hcd_unlink_urb (struct urb *urb, int status)
static void __usb_hcd_giveback_urb(struct urb *urb)
{
struct usb_hcd *hcd = bus_to_hcd(urb->dev->bus);
- struct usb_anchor *anchor = urb->anchor;
+ struct usb_anchor *anchor;
int status = urb->unlinked;
urb->hcpriv = NULL;
@@ -1641,8 +1641,12 @@ static void __usb_hcd_giveback_urb(struct urb *urb)
unmap_urb_for_dma(hcd, urb);
usbmon_urb_complete(&hcd->self, urb, status);
- usb_anchor_suspend_wakeups(anchor);
- usb_unanchor_urb(urb);
+ /*
+ * Capturing the anchor, suspending its wakeups and unanchoring
+ * must be atomic with each other; see
+ * usb_unanchor_urb_and_suspend_wakeups().
+ */
+ anchor = usb_unanchor_urb_and_suspend_wakeups(urb);
if (likely(status == 0))
usb_led_activity(USB_LED_EVENT_HOST);
diff --git a/drivers/usb/core/urb.c b/drivers/usb/core/urb.c
index bb1778d9e9db..174dc42c95c1 100644
--- a/drivers/usb/core/urb.c
+++ b/drivers/usb/core/urb.c
@@ -14,6 +14,8 @@
#include <linux/usb/hcd.h>
#include <linux/scatterlist.h>
+#include "usb.h"
+
#define to_urb(d) container_of(d, struct urb, kref)
@@ -205,6 +207,52 @@ void usb_unanchor_urb(struct urb *urb)
}
EXPORT_SYMBOL_GPL(usb_unanchor_urb);
+/*
+ * usb_unanchor_urb_and_suspend_wakeups - atomically unanchor @urb and
+ * increment the suspend_wakeups counter of its anchor.
+ * @urb: the URB to unanchor
+ *
+ * Used by the URB giveback path, which must capture urb->anchor and
+ * increment anchor->suspend_wakeups atomically with the removal of
+ * @urb from anchor->urb_list. Otherwise a concurrent unanchor of
+ * @urb (a driver calling usb_unanchor_urb() on its own in-flight URB,
+ * or usb_get_from_anchor() or usb_scuttle_anchored_urbs() taking it)
+ * can leave the anchor with an empty urb_list while suspend_wakeups
+ * is still zero, so a usb_wait_anchor_empty_timeout() waiter observes
+ * the wait condition true, returns, and the driver may free the
+ * anchor before the giveback gets to touch it.
+ *
+ * The verification of urb->anchor under anchor->lock makes this safe
+ * against racing re-anchoring, because "urb->anchor == anchor" and
+ * "@urb is on anchor->urb_list" are changed together only while
+ * holding anchor->lock.
+ *
+ * Return: the anchor, which the caller must later pass to
+ * usb_anchor_resume_wakeups(), or NULL if @urb is not anchored
+ * anymore (a concurrent unanchor won the race).
+ */
+struct usb_anchor *usb_unanchor_urb_and_suspend_wakeups(struct urb *urb)
+{
+ struct usb_anchor *anchor;
+ unsigned long flags;
+
+ anchor = urb->anchor;
+ if (!anchor)
+ return NULL;
+
+ spin_lock_irqsave(&anchor->lock, flags);
+ if (likely(anchor == urb->anchor)) {
+ atomic_inc(&anchor->suspend_wakeups);
+ __usb_unanchor_urb(urb, anchor);
+ spin_unlock_irqrestore(&anchor->lock, flags);
+ } else {
+ spin_unlock_irqrestore(&anchor->lock, flags);
+ anchor = NULL;
+ }
+
+ return anchor;
+}
+
/*-------------------------------------------------------------------*/
static const int pipetypes[4] = {
diff --git a/drivers/usb/core/usb.h b/drivers/usb/core/usb.h
index a9b37aeb515b..362bfda497cc 100644
--- a/drivers/usb/core/usb.h
+++ b/drivers/usb/core/usb.h
@@ -20,6 +20,7 @@ extern int usb_create_ep_devs(struct device *parent,
struct usb_host_endpoint *endpoint,
struct usb_device *udev);
extern void usb_remove_ep_devs(struct usb_host_endpoint *endpoint);
+extern struct usb_anchor *usb_unanchor_urb_and_suspend_wakeups(struct urb *urb);
extern void usb_enable_endpoint(struct usb_device *dev,
struct usb_host_endpoint *ep, bool reset_toggle);
--
2.39.5 (Apple Git-154)
^ permalink raw reply [flat|nested] 5+ messages in thread
* [PATCH v3 3/3] usb: core: Close residual anchor read-to-lock window with RCU
2026-11-27 13:28 [PATCH v3 0/3] usb: core: fix three use-after-free windows in the USB anchor protocol Hongyu Xie
2026-11-27 13:28 ` [PATCH v3 1/3] usb: core: Fix use-after-free in anchor wakeup protocol Hongyu Xie
2026-11-27 13:28 ` [PATCH v3 2/3] usb: core: Close anchor capture-to-increment race in URB giveback Hongyu Xie
@ 2026-11-27 13:29 ` Hongyu Xie
2 siblings, 0 replies; 5+ messages in thread
From: Hongyu Xie @ 2026-11-27 13:29 UTC (permalink / raw)
To: Greg KH, Alan Stern
Cc: Oliver Neukum, oliver, Hans de Goede, linux-usb, linux-kernel
usb_unanchor_urb() and the URB giveback read urb->anchor and only
then acquire anchor->lock. Between the read and the lock
acquisition the anchor can already have been freed: a concurrent
unanchor of the last URB empties the anchor, a
usb_wait_anchor_empty_timeout() waiter observes the condition true,
returns, and the driver frees the memory holding the anchor; the
spin_lock() then touches freed memory. This gap is as old as
usb_unanchor_urb() itself and was deliberately left open by the
capture-to-increment fix, whose guarantee is scoped to givebacks
that have already incremented suspend_wakeups.
A plain reference count cannot close it: the first dereference of
the freshly read anchor pointer would have to be the refcount
increment itself, so the pin would be taken on memory that may
already have been freed. Protecting the pointer read requires
deferred reclamation, and because anchors are embedded in
driver-private structures and freed with plain kfree() right after
a successful wait, the deferral has to live on the side usbcore
controls: the return of the wait.
However, waiting for an unconditional synchronize_rcu() on every
successful wait or drain would penalize runtime I/O paths that wait
on persistent or empty anchors without freeing them (such as
zd1211rw register write batches, ALSA stream stops or btusb traffic
stops), even though an uncontended unanchor already releases
anchor->lock before any waiter can observe the anchor empty. A
grace period is only needed when a second thread actually raced on
urb->anchor and may still be inside the read-to-lock gap after
__usb_unanchor_urb() cleared urb->anchor.
Convert the anchor wakeup protocol into a contention-gated RCU
lifetime protocol:
- Lockless unanchor readers (usb_unanchor_urb() and
usb_unanchor_urb_and_suspend_wakeups()) register in
urb->anchor_readers inside RCU read-side critical sections
(ordered by smp_mb__after_atomic()) before dereferencing
urb->anchor, and urb->anchor is published with
rcu_assign_pointer(). Unanchored URBs take an early
rcu_access_pointer() exit without touching the counter.
- Under anchor->lock, __usb_unanchor_urb() clears urb->anchor,
orders the clear against reading the remaining urb->anchor_readers
count (dropping the caller's own reader count before
usb_put_urb()), and only when another reader is still in flight
snapshots get_state_synchronize_rcu() into anchor->rcu_gp_seq and
sets anchor->need_rcu_gp.
- Every function whose return lets the caller free the anchor --
usb_wait_anchor_empty_timeout() on a non-zero return,
usb_kill_anchored_urbs(), usb_poison_anchored_urbs() and
usb_scuttle_anchored_urbs() -- inspects anchor->need_rcu_gp under
anchor->lock when observing the anchor unused, retiring the flag
in place via poll_state_synchronize_rcu() if that grace period has
already elapsed, and otherwise waits with cond_synchronize_rcu()
after dropping the lock while touching nothing on the anchor
afterwards. Uncontended waits and drains pay zero grace periods.
Provided the caller stops anchoring new URBs, any losing reader
from a contended unanchor has released anchor->lock before the
caller may free the anchor, and readers starting after the clear
find urb->anchor == NULL and never touch the anchor at all. The
license is per caller: another teardown call may still be sleeping
on the anchor's wait queue, so a caller that frees on its own
success must first let other in-flight teardown calls return. And
as with any wait on the anchor, these calls must not be made from
the completion callback of a URB on the same anchor.
The empty-anchor retry of kill/poison/scuttle waits on the anchor's
wait queue instead of busy-waiting. On !PREEMPT_RCU kernels whose
scheduler tick reports no quiescent state for a spinning process
context, a busy retry keeps this CPU from reporting a quiescent
state and stalls every grace period that still awaits this CPU's
quiescent state -- a concurrent teardown's grace-period exit
included -- and under real-time scheduling it can starve the very
completion path it is waiting for. The retry keeps the re-drain
behavior of the busy loop it replaces: usb_anchor_urb() wakes the
anchor's wait queue (gated by waitqueue_active() under anchor->lock),
and the wait also ends -- without declaring the anchor unused --
when a URB is anchored after the drain, so the loop restarts and
tears the late arrival down too.
usb_wait_anchor_empty_timeout() keeps its documented contract and
remaining-jiffies return value on uncontended waits; when a
contended-unanchor grace period is pending, a successful wait --
including one with a zero timeout -- waits with
cond_synchronize_rcu(), may overrun the caller's timeout by up to
one grace period, and clamps its non-zero return to at least 1.
usb_kill_anchored_urbs(), usb_poison_anchored_urbs() and
usb_scuttle_anchored_urbs() must be called from a context that can
sleep (all in-tree callers already do) and carry might_sleep() at
entry so atomic-context callers are caught even when no grace period
is needed. No driver changes are required: struct urb gains a
usbcore-private reader counter (anchor_readers), and struct
usb_anchor records the conditional grace-period state (need_rcu_gp
and rcu_gp_seq). Documentation/driver-api/usb/anchors.rst is
updated to match.
Fixes: 51a2f077c44e ("USB: introduce usb_anchor")
Cc: stable@vger.kernel.org
Cc: Alan Stern <stern@rowland.harvard.edu>
Cc: Oliver Neukum <oliver@neukum.org>
Cc: Hans de Goede <hansg@kernel.org>
Signed-off-by: Hongyu Xie <xiehongyu1@kylinos.cn>
---
Changes in v3:
- Gate the RCU grace period on actual unanchor contention via
urb->anchor_readers + anchor->need_rcu_gp / get_state_synchronize_rcu()
+ cond_synchronize_rcu() instead of calling synchronize_rcu()
unconditionally on every successful wait and drain, eliminating
grace-period stalls on uncontended persistent or empty anchors (such
as zd1211rw register write batches, hiface stream stops, usbtmc reads
and btusb traffic stops) while preserving remaining-jiffies returns on
uncontended usb_wait_anchor_empty_timeout() calls.
- Link to v2: https://lore.kernel.org/r/179577006613.23588.1120308700542393912@kylinos.cn
Documentation/driver-api/usb/anchors.rst | 26 +-
drivers/usb/core/urb.c | 439 ++++++++++++++++++++---
include/linux/usb.h | 10 +-
3 files changed, 411 insertions(+), 64 deletions(-)
diff --git a/Documentation/driver-api/usb/anchors.rst b/Documentation/driver-api/usb/anchors.rst
index 5a93d171e76c..68b6d966e38a 100644
--- a/Documentation/driver-api/usb/anchors.rst
+++ b/Documentation/driver-api/usb/anchors.rst
@@ -22,8 +22,16 @@ initialise the data structure.
Deallocation
============
-Once it has no more URBs associated with it, the anchor can be
-freed with normal memory management operations.
+Once it has no more URBs associated with it, and one of
+usb_wait_anchor_empty_timeout(), usb_kill_anchored_urbs(),
+usb_poison_anchored_urbs() or usb_scuttle_anchored_urbs() has returned
+successfully, the anchor can be freed with normal memory management
+operations. When a concurrent unanchor raced on one of the anchor's
+URBs, the successful return drains any lockless reader that may still
+hold the anchor pointer by waiting for an RCU grace period. This holds
+only for the caller's own teardown: the caller must have stopped
+anchoring new URBs, and must not free the anchor while another call on
+it is still in flight.
Association and disassociation of URBs with anchors
===================================================
@@ -48,14 +56,22 @@ This way no data can be reordered.
:c:func:`usb_scuttle_anchored_urbs`
-----------------------------------
-All URBs of an anchor are unanchored en masse.
+All URBs of an anchor are unanchored en masse. This function may
+sleep while draining in-flight givebacks or waiting for a contended
+unanchor's RCU grace period.
:c:func:`usb_wait_anchor_empty_timeout`
---------------------------------------
This function waits for all URBs associated with an anchor to finish
-or a timeout, whichever comes first. Its return value will tell you
-whether the timeout was reached.
+or a timeout, whichever comes first. Its return value will tell you
+whether the timeout was reached (0 on timeout, remaining jiffies or 1
+if the anchor drained). If a concurrent unanchor raced on the anchor,
+a successful wait -- even with a zero timeout -- waits for the
+corresponding RCU grace period before returning, so it may overrun the
+caller's timeout by up to one grace period; uncontended waits pay no
+grace period; this is what makes it safe for the caller to free the
+anchor on a non-zero return.
:c:func:`usb_anchor_empty`
--------------------------
diff --git a/drivers/usb/core/urb.c b/drivers/usb/core/urb.c
index 174dc42c95c1..b1085fc02e40 100644
--- a/drivers/usb/core/urb.c
+++ b/drivers/usb/core/urb.c
@@ -9,6 +9,7 @@
#include <linux/slab.h>
#include <linux/log2.h>
#include <linux/kmsan.h>
+#include <linux/rcupdate.h>
#include <linux/usb.h>
#include <linux/wait.h>
#include <linux/usb/hcd.h>
@@ -132,11 +133,34 @@ void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor)
spin_lock_irqsave(&anchor->lock, flags);
usb_get_urb(urb);
list_add_tail(&urb->anchor_list, &anchor->urb_list);
- urb->anchor = anchor;
+ rcu_assign_pointer(urb->anchor, anchor);
if (unlikely(anchor->poisoned))
atomic_inc(&urb->reject);
+ /*
+ * Wake a teardown drain sleeping on this anchor: the late URB
+ * makes the drain's wait condition true again, so the wait
+ * ends with the anchor not unused and the drain restarts to
+ * take care of the late arrival. The waitqueue_active()
+ * gate keeps the common no-drain submission off the wakeup
+ * path; it cannot lose this wakeup, because a drain that
+ * enqueues only after this critical section re-checks the
+ * list under anchor->lock and restarts on its own (see
+ * usb_anchor_teardown_progress()).
+ *
+ * The gate deviates from the two usages wait.h sanctions for
+ * waitqueue_active() (the waitqueue lock, or an explicit
+ * smp_mb()): here it is evaluated inside the same
+ * anchor->lock critical section as the list_add_tail() above,
+ * and the drains evaluate their wait condition under that
+ * lock too, so the store and the gate load cannot be
+ * reordered apart. Hoisting the gate out of the lock would
+ * silently lose wakeups.
+ */
+ if (waitqueue_active(&anchor->wait))
+ wake_up(&anchor->wait);
+
spin_unlock_irqrestore(&anchor->lock, flags);
}
EXPORT_SYMBOL_GPL(usb_anchor_urb);
@@ -149,28 +173,130 @@ static int __usb_anchor_check_wakeup(struct usb_anchor *anchor)
}
/*
- * Same check as __usb_anchor_check_wakeup(), but takes anchor->lock. It is
- * meant for waiters which do not hold the lock: the critical section
- * serializes with the URB giveback path, so once the check succeeds no
- * giveback that has incremented suspend_wakeups will touch the anchor
- * anymore and the caller may free the memory holding the anchor.
+ * Called under anchor->lock right after __usb_anchor_check_wakeup()
+ * observes @anchor unused. Only an anchor that experienced a contended
+ * unanchor (a second reader in flight on urb->anchor when
+ * __usb_unanchor_urb() cleared it) needs an RCU grace period before the
+ * caller may free @anchor: an uncontended unanchor releases anchor->lock
+ * before any waiter can observe @anchor unused and never touches @anchor
+ * afterwards. Retire need_rcu_gp in place once the recorded grace
+ * period has elapsed so persistent anchors pay nothing thereafter and
+ * never carry a stale cookie across gp_seq wraparound.
+ */
+static bool __usb_anchor_prepare_rcu_gp(struct usb_anchor *anchor,
+ unsigned long *gp_seq)
+{
+ if (likely(!anchor->need_rcu_gp))
+ return false;
+
+ if (poll_state_synchronize_rcu(anchor->rcu_gp_seq)) {
+ anchor->need_rcu_gp = 0;
+ return false;
+ }
+
+ *gp_seq = anchor->rcu_gp_seq;
+ return true;
+}
+
+/*
+ * Same check as __usb_anchor_check_wakeup(), but takes anchor->lock and
+ * snapshots any pending contended-unanchor grace-period cookie in the
+ * same critical section. The check alone does not make freeing safe:
+ * when @need_gp is set, the caller must wait with
+ * cond_synchronize_rcu(@gp_seq) after dropping the lock, and must not
+ * anchor new URBs concurrently; see usb_wait_anchor_empty_timeout() for
+ * the full contract.
*/
-static int usb_anchor_check_wakeup(struct usb_anchor *anchor)
+static int usb_anchor_check_wakeup(struct usb_anchor *anchor,
+ bool *need_gp, unsigned long *gp_seq)
{
unsigned long flags;
int wakeup;
spin_lock_irqsave(&anchor->lock, flags);
wakeup = __usb_anchor_check_wakeup(anchor);
+ if (wakeup)
+ *need_gp = __usb_anchor_prepare_rcu_gp(anchor, gp_seq);
spin_unlock_irqrestore(&anchor->lock, flags);
return wakeup;
}
+/*
+ * Wait-condition helper for the teardown drain loops: the wait ends
+ * either with the anchor observed unused under anchor->lock (*unused
+ * is set, *need_gp and *gp_seq are captured, and the caller takes the
+ * conditional grace-period exit), or -- without that observation --
+ * when a URB was anchored after the drain, so the caller returns to
+ * the top of its loop and drains the late arrival. usb_anchor_urb()
+ * wakes the anchor's wait queue for the second case, and the lockless
+ * list read is only a fast path: a stale non-empty entry merely
+ * restarts the drain, and a stale empty one is caught by the locked
+ * re-check below, so neither direction can lose the restart.
+ */
+static bool usb_anchor_teardown_progress(struct usb_anchor *anchor,
+ bool *unused, bool *need_gp,
+ unsigned long *gp_seq)
+{
+ unsigned long flags;
+ bool ret;
+
+ if (!list_empty_careful(&anchor->urb_list)) {
+ *unused = false;
+ return true;
+ }
+
+ spin_lock_irqsave(&anchor->lock, flags);
+ if (!list_empty(&anchor->urb_list)) {
+ /* A late URB landed: restart the drain for it. */
+ *unused = false;
+ ret = true;
+ } else {
+ *unused = __usb_anchor_check_wakeup(anchor);
+ if (*unused)
+ *need_gp = __usb_anchor_prepare_rcu_gp(anchor, gp_seq);
+ ret = *unused;
+ }
+ spin_unlock_irqrestore(&anchor->lock, flags);
+
+ return ret;
+}
+
/* Callers must hold anchor->lock */
-static void __usb_unanchor_urb(struct urb *urb, struct usb_anchor *anchor)
+static void __usb_unanchor_urb(struct urb *urb, struct usb_anchor *anchor,
+ bool from_reader)
{
- urb->anchor = NULL;
+ int remaining;
+
+ rcu_assign_pointer(urb->anchor, NULL);
+ if (from_reader) {
+ /*
+ * atomic_dec_return() implies full barriers on both
+ * sides, pairing with smp_mb__after_atomic() after
+ * atomic_inc(&urb->anchor_readers) on reader entry:
+ * either a racing reader sees urb->anchor == NULL and
+ * never touches @anchor, or @remaining > 0 observes
+ * that reader (which only decrements after acquiring
+ * anchor->lock). Drop our own reader count before
+ * usb_put_urb() in case @anchor held the last @urb ref.
+ */
+ remaining = atomic_dec_return(&urb->anchor_readers);
+ } else {
+ /*
+ * Same store-to-load full barrier for unanchorers that
+ * already hold anchor->lock without entering through
+ * the lockless reader path (usb_get_from_anchor() and
+ * usb_scuttle_anchored_urbs()).
+ */
+ smp_mb();
+ remaining = atomic_read(&urb->anchor_readers);
+ }
+
+ if (unlikely(remaining > 0)) {
+ anchor->rcu_gp_seq = get_state_synchronize_rcu();
+ anchor->need_rcu_gp = 1;
+ }
+
list_del(&urb->anchor_list);
usb_put_urb(urb);
if (__usb_anchor_check_wakeup(anchor))
@@ -191,19 +317,43 @@ void usb_unanchor_urb(struct urb *urb)
if (!urb)
return;
- anchor = urb->anchor;
- if (!anchor)
+ if (!rcu_access_pointer(urb->anchor))
return;
- spin_lock_irqsave(&anchor->lock, flags);
/*
- * At this point, we could be competing with another thread which
- * has the same intention. To protect the urb from being unanchored
- * twice, only the winner of the race gets the job.
+ * The anchor pointer is read locklessly: a concurrent unanchor
+ * can empty the anchor and let a waiter return and free it
+ * before this thread manages to acquire anchor->lock. Register
+ * in urb->anchor_readers inside an RCU read-side critical
+ * section before dereferencing urb->anchor: if we win the
+ * unanchor under anchor->lock with no other reader in flight,
+ * no grace period is needed; if another thread unanchors @urb
+ * first while we are in the read-to-lock gap, __usb_unanchor_urb()
+ * sees our reader count and arms a conditional grace-period wait
+ * on @anchor so its memory stays alive until we release
+ * anchor->lock and rcu_read_unlock().
*/
- if (likely(anchor == urb->anchor))
- __usb_unanchor_urb(urb, anchor);
- spin_unlock_irqrestore(&anchor->lock, flags);
+ rcu_read_lock();
+ atomic_inc(&urb->anchor_readers);
+ /* Pairs with __usb_unanchor_urb(): order inc before urb->anchor load. */
+ smp_mb__after_atomic();
+ anchor = rcu_dereference(urb->anchor);
+ if (anchor) {
+ spin_lock_irqsave(&anchor->lock, flags);
+ /*
+ * At this point, we could be competing with another thread
+ * which has the same intention. To protect the urb from being
+ * unanchored twice, only the winner of the race gets the job.
+ */
+ if (likely(anchor == rcu_dereference(urb->anchor)))
+ __usb_unanchor_urb(urb, anchor, true);
+ else
+ atomic_dec(&urb->anchor_readers);
+ spin_unlock_irqrestore(&anchor->lock, flags);
+ } else {
+ atomic_dec(&urb->anchor_readers);
+ }
+ rcu_read_unlock();
}
EXPORT_SYMBOL_GPL(usb_unanchor_urb);
@@ -227,6 +377,13 @@ EXPORT_SYMBOL_GPL(usb_unanchor_urb);
* "@urb is on anchor->urb_list" are changed together only while
* holding anchor->lock.
*
+ * Like usb_unanchor_urb(), the initial urb->anchor read registers in
+ * urb->anchor_readers inside an RCU read-side critical section so a
+ * concurrent unanchor that wins the race arms a conditional grace
+ * period on @anchor before @anchor can be freed. Anchoring new URBs
+ * concurrently would re-publish urb->anchor and is outside that
+ * teardown contract.
+ *
* Return: the anchor, which the caller must later pass to
* usb_anchor_resume_wakeups(), or NULL if @urb is not anchored
* anymore (a concurrent unanchor won the race).
@@ -236,19 +393,29 @@ struct usb_anchor *usb_unanchor_urb_and_suspend_wakeups(struct urb *urb)
struct usb_anchor *anchor;
unsigned long flags;
- anchor = urb->anchor;
- if (!anchor)
+ if (!rcu_access_pointer(urb->anchor))
return NULL;
- spin_lock_irqsave(&anchor->lock, flags);
- if (likely(anchor == urb->anchor)) {
- atomic_inc(&anchor->suspend_wakeups);
- __usb_unanchor_urb(urb, anchor);
- spin_unlock_irqrestore(&anchor->lock, flags);
+ rcu_read_lock();
+ atomic_inc(&urb->anchor_readers);
+ /* Pairs with __usb_unanchor_urb(): order inc before urb->anchor load. */
+ smp_mb__after_atomic();
+ anchor = rcu_dereference(urb->anchor);
+ if (anchor) {
+ spin_lock_irqsave(&anchor->lock, flags);
+ if (likely(anchor == rcu_dereference(urb->anchor))) {
+ atomic_inc(&anchor->suspend_wakeups);
+ __usb_unanchor_urb(urb, anchor, true);
+ spin_unlock_irqrestore(&anchor->lock, flags);
+ } else {
+ atomic_dec(&urb->anchor_readers);
+ spin_unlock_irqrestore(&anchor->lock, flags);
+ anchor = NULL;
+ }
} else {
- spin_unlock_irqrestore(&anchor->lock, flags);
- anchor = NULL;
+ atomic_dec(&urb->anchor_readers);
}
+ rcu_read_unlock();
return anchor;
}
@@ -882,15 +1049,31 @@ EXPORT_SYMBOL_GPL(usb_block_urb);
* with guarantee that no completer callbacks will take place from the
* anchor after this function returns.
*
+ * It is safe to free the anchor (or the structure embedding it) once
+ * this function returns, provided that no new URBs are anchored to it
+ * concurrently and no other teardown call (a kill, poison, scuttle or
+ * wait on the same anchor) is still in flight: such a call may be
+ * sleeping on the anchor's wait queue, which lives in the memory to
+ * be freed. This function may sleep.
+ *
+ * This function must not be called from the completion callback of a
+ * URB on @anchor: the callback runs while the giveback still holds
+ * the anchor's suspend_wakeups pin, so the drain would wait for
+ * itself.
+ *
* This routine should not be called by a driver after its disconnect
* method has returned.
*/
void usb_kill_anchored_urbs(struct usb_anchor *anchor)
{
+ unsigned long gp_seq = 0;
+ bool need_gp = false;
struct urb *victim;
- int surely_empty;
+ bool unused;
+
+ might_sleep();
- do {
+ for (;;) {
spin_lock_irq(&anchor->lock);
while (!list_empty(&anchor->urb_list)) {
victim = list_entry(anchor->urb_list.prev,
@@ -903,11 +1086,50 @@ void usb_kill_anchored_urbs(struct usb_anchor *anchor)
usb_put_urb(victim);
spin_lock_irq(&anchor->lock);
}
- surely_empty = __usb_anchor_check_wakeup(anchor);
+
+ if (__usb_anchor_check_wakeup(anchor)) {
+ need_gp = __usb_anchor_prepare_rcu_gp(anchor, &gp_seq);
+ spin_unlock_irq(&anchor->lock);
+ /*
+ * If a contended unanchor left a lockless reader
+ * between reading urb->anchor and acquiring
+ * anchor->lock, wait until that grace period has
+ * elapsed before returning; uncontended drains pay
+ * no grace period. Nothing in this path may touch
+ * @anchor after unlocking above.
+ */
+ if (unlikely(need_gp))
+ cond_synchronize_rcu(gp_seq);
+ return;
+ }
spin_unlock_irq(&anchor->lock);
- cpu_relax();
- } while (!surely_empty);
+ /*
+ * The anchor is empty but a giveback still holds a
+ * suspend_wakeups pin. Busy-waiting for it would
+ * keep this CPU from reporting a quiescent state on
+ * !PREEMPT_RCU kernels whose scheduler tick reports
+ * none for a spinning process context, stalling every
+ * grace period that still awaits this CPU's quiescent
+ * state -- a concurrent teardown's grace-period exit
+ * included -- and under real-time scheduling it can
+ * starve the very completion path it is waiting for.
+ * Wait for the wakeup protocol to signal the state
+ * change and take the same conditional grace-period
+ * exit as above. The wait also ends without an unused
+ * observation when a URB is anchored after the drain,
+ * so the loop restarts and kills it, like the busy
+ * loop this replaced did.
+ */
+ wait_event(anchor->wait,
+ usb_anchor_teardown_progress(anchor, &unused,
+ &need_gp, &gp_seq));
+ if (unused) {
+ if (unlikely(need_gp))
+ cond_synchronize_rcu(gp_seq);
+ return;
+ }
+ }
}
EXPORT_SYMBOL_GPL(usb_kill_anchored_urbs);
@@ -920,15 +1142,28 @@ EXPORT_SYMBOL_GPL(usb_kill_anchored_urbs);
* from the back of the queue. Newly added URBs will also be
* poisoned
*
+ * Like usb_kill_anchored_urbs(), it is safe to free the anchor once
+ * this function returns, provided that no new URBs are anchored to it
+ * concurrently and no other teardown call on the same anchor is still
+ * in flight. This function may sleep.
+ *
+ * Like usb_kill_anchored_urbs(), it must not be called from the
+ * completion callback of a URB on @anchor: the drain would wait for
+ * the pin its own giveback holds.
+ *
* This routine should not be called by a driver after its disconnect
* method has returned.
*/
void usb_poison_anchored_urbs(struct usb_anchor *anchor)
{
+ unsigned long gp_seq = 0;
+ bool need_gp = false;
struct urb *victim;
- int surely_empty;
+ bool unused;
+
+ might_sleep();
- do {
+ for (;;) {
spin_lock_irq(&anchor->lock);
anchor->poisoned = 1;
while (!list_empty(&anchor->urb_list)) {
@@ -942,11 +1177,27 @@ void usb_poison_anchored_urbs(struct usb_anchor *anchor)
usb_put_urb(victim);
spin_lock_irq(&anchor->lock);
}
- surely_empty = __usb_anchor_check_wakeup(anchor);
+
+ if (__usb_anchor_check_wakeup(anchor)) {
+ need_gp = __usb_anchor_prepare_rcu_gp(anchor, &gp_seq);
+ spin_unlock_irq(&anchor->lock);
+ /* Same conditional lifetime exit as usb_kill_anchored_urbs(). */
+ if (unlikely(need_gp))
+ cond_synchronize_rcu(gp_seq);
+ return;
+ }
spin_unlock_irq(&anchor->lock);
- cpu_relax();
- } while (!surely_empty);
+ /* Same sleepable retry as usb_kill_anchored_urbs(). */
+ wait_event(anchor->wait,
+ usb_anchor_teardown_progress(anchor, &unused,
+ &need_gp, &gp_seq));
+ if (unused) {
+ if (unlikely(need_gp))
+ cond_synchronize_rcu(gp_seq);
+ return;
+ }
+ }
}
EXPORT_SYMBOL_GPL(usb_poison_anchored_urbs);
@@ -976,8 +1227,15 @@ EXPORT_SYMBOL_GPL(usb_unpoison_anchored_urbs);
* @anchor: the anchor you want to suspend wakeups on
*
* Call this to stop the last urb being unanchored from waking up any
- * usb_wait_anchor_empty_timeout waiters. This is used in the hcd urb give-
- * back path to delay waking up until after the completion handler has run.
+ * usb_wait_anchor_empty_timeout waiters. The hcd urb give-back path,
+ * which delays waking up until after the completion handler has run,
+ * uses usb_unanchor_urb_and_suspend_wakeups() for that nowadays; this
+ * export remains for external users pairing it with
+ * usb_anchor_resume_wakeups().
+ *
+ * Note that a manually held pin also holds up anchor teardown: a
+ * kill, poison, scuttle or wait call on the same anchor will not
+ * return while the pin is outstanding.
*/
void usb_anchor_suspend_wakeups(struct usb_anchor *anchor)
{
@@ -1016,29 +1274,60 @@ void usb_anchor_resume_wakeups(struct usb_anchor *anchor)
EXPORT_SYMBOL_GPL(usb_anchor_resume_wakeups);
/**
- * usb_wait_anchor_empty_timeout - wait for an anchor to be unused
+ * usb_wait_anchor_empty_timeout - wait for an anchor to become unused
* @anchor: the anchor you want to become unused
* @timeout: how long you are willing to wait in milliseconds
*
* Call this is you want to be sure all an anchor's
* URBs have finished
*
- * Return: Non-zero if the anchor became unused. Zero on timeout.
+ * A non-zero return also makes it safe to free the anchor (or the
+ * structure embedding it), provided that no new URBs are anchored to
+ * it concurrently and no other teardown call on the same anchor is
+ * still in flight (it may be sleeping on the anchor's wait queue).
+ * This function may sleep; if a concurrent unanchor raced on @anchor,
+ * a successful wait -- even with a zero timeout -- waits for the
+ * corresponding RCU grace period before returning, whereas uncontended
+ * waits pay no grace period. It must not be called from the completion
+ * callback of a URB on @anchor: the wait cannot end before the giveback
+ * releases its suspend_wakeups pin, which happens only after the
+ * callback returns.
+ *
+ * Return: Non-zero (remaining jiffies, or 1 if none remain) if the
+ * anchor became unused. Zero on timeout.
*/
int usb_wait_anchor_empty_timeout(struct usb_anchor *anchor,
unsigned int timeout)
{
+ unsigned long deadline = jiffies + msecs_to_jiffies(timeout);
+ unsigned long gp_seq = 0;
+ bool need_gp = false;
+ long ret;
+
/*
- * The condition must be evaluated under anchor->lock: when this
- * function returns non-zero, every URB giveback that has incremented
- * suspend_wakeups has finished with the anchor, so the caller may
- * free the anchor, which is typically embedded in the driver's
- * private structure. A zero return (timeout) means a giveback may
- * still be in flight and gives no such guarantee.
+ * The condition is evaluated under anchor->lock. When this
+ * function returns non-zero, every URB giveback that has
+ * incremented suspend_wakeups has finished with the anchor and
+ * any lockless reader left in flight by a contended unanchor is
+ * flushed by cond_synchronize_rcu() below, so the caller may
+ * free the anchor -- provided that no new URBs are anchored
+ * concurrently -- which is typically embedded in the driver's
+ * private structure. A zero return (timeout) means a giveback
+ * may still be in flight and gives no such guarantee.
*/
- return wait_event_timeout(anchor->wait,
- usb_anchor_check_wakeup(anchor),
- msecs_to_jiffies(timeout));
+ ret = wait_event_timeout(anchor->wait,
+ usb_anchor_check_wakeup(anchor, &need_gp,
+ &gp_seq),
+ msecs_to_jiffies(timeout));
+ if (!ret)
+ return 0;
+
+ if (unlikely(need_gp)) {
+ cond_synchronize_rcu(gp_seq);
+ ret = max_t(long, (long)(deadline - jiffies), 1);
+ }
+
+ return min_t(long, ret, INT_MAX);
}
EXPORT_SYMBOL_GPL(usb_wait_anchor_empty_timeout);
@@ -1049,6 +1338,11 @@ EXPORT_SYMBOL_GPL(usb_wait_anchor_empty_timeout);
* This will take the oldest urb from an anchor, unanchor and return it with
* a reference held.
*
+ * A %NULL return does not mean the anchor is quiescent: a URB giveback
+ * may still be between its suspend_wakeups increment and its wakeup
+ * resume. Call usb_wait_anchor_empty_timeout() and check for a
+ * non-zero return before freeing the anchor.
+ *
* Return: The oldest urb from @anchor, or %NULL if @anchor has no
* urbs associated with it.
*/
@@ -1062,7 +1356,7 @@ struct urb *usb_get_from_anchor(struct usb_anchor *anchor)
victim = list_entry(anchor->urb_list.next, struct urb,
anchor_list);
usb_get_urb(victim);
- __usb_unanchor_urb(victim, anchor);
+ __usb_unanchor_urb(victim, anchor, false);
} else {
victim = NULL;
}
@@ -1078,25 +1372,54 @@ EXPORT_SYMBOL_GPL(usb_get_from_anchor);
* @anchor: the anchor whose urbs you want to unanchor
*
* use this to get rid of all an anchor's urbs
+ *
+ * Like usb_kill_anchored_urbs(), it is safe to free the anchor once
+ * this function returns, provided that no new URBs are anchored to it
+ * concurrently and no other teardown call on the same anchor is still
+ * in flight. This function may sleep.
+ *
+ * Like usb_kill_anchored_urbs(), it must not be called from the
+ * completion callback of a URB on @anchor: the drain would wait for
+ * the pin its own giveback holds.
*/
void usb_scuttle_anchored_urbs(struct usb_anchor *anchor)
{
+ unsigned long gp_seq = 0;
+ bool need_gp = false;
struct urb *victim;
unsigned long flags;
- int surely_empty;
+ bool unused;
+
+ might_sleep();
- do {
+ for (;;) {
spin_lock_irqsave(&anchor->lock, flags);
while (!list_empty(&anchor->urb_list)) {
victim = list_entry(anchor->urb_list.prev,
struct urb, anchor_list);
- __usb_unanchor_urb(victim, anchor);
+ __usb_unanchor_urb(victim, anchor, false);
+ }
+
+ if (__usb_anchor_check_wakeup(anchor)) {
+ need_gp = __usb_anchor_prepare_rcu_gp(anchor, &gp_seq);
+ spin_unlock_irqrestore(&anchor->lock, flags);
+ /* Same conditional lifetime exit as usb_kill_anchored_urbs(). */
+ if (unlikely(need_gp))
+ cond_synchronize_rcu(gp_seq);
+ return;
}
- surely_empty = __usb_anchor_check_wakeup(anchor);
spin_unlock_irqrestore(&anchor->lock, flags);
- cpu_relax();
- } while (!surely_empty);
+ /* Same sleepable retry as usb_kill_anchored_urbs(). */
+ wait_event(anchor->wait,
+ usb_anchor_teardown_progress(anchor, &unused,
+ &need_gp, &gp_seq));
+ if (unused) {
+ if (unlikely(need_gp))
+ cond_synchronize_rcu(gp_seq);
+ return;
+ }
+ }
}
EXPORT_SYMBOL_GPL(usb_scuttle_anchored_urbs);
@@ -1105,6 +1428,8 @@ EXPORT_SYMBOL_GPL(usb_scuttle_anchored_urbs);
* usb_anchor_empty - is an anchor empty
* @anchor: the anchor you want to query
*
+ * This is an unsynchronized peek; it gives no lifetime guarantee.
+ *
* Return: 1 if the anchor has no urbs associated with it.
*/
int usb_anchor_empty(struct usb_anchor *anchor)
diff --git a/include/linux/usb.h b/include/linux/usb.h
index 825f03b29067..c84a0791f199 100644
--- a/include/linux/usb.h
+++ b/include/linux/usb.h
@@ -1431,6 +1431,8 @@ struct usb_anchor {
spinlock_t lock;
atomic_t suspend_wakeups;
unsigned int poisoned:1;
+ unsigned int need_rcu_gp:1;
+ unsigned long rcu_gp_seq;
};
static inline void init_usb_anchor(struct usb_anchor *anchor)
@@ -1447,7 +1449,10 @@ typedef void (*usb_complete_t)(struct urb *);
* struct urb - USB Request Block
* @urb_list: For use by current owner of the URB.
* @anchor_list: membership in the list of an anchor
- * @anchor: to anchor URBs to a common mooring
+ * @anchor: to anchor URBs to a common mooring; usbcore publishes it
+ * with rcu_assign_pointer() and consumes it under
+ * rcu_read_lock() with rcu_dereference(), see
+ * drivers/usb/core/urb.c for the anchor lifetime protocol
* @ep: Points to the endpoint's data structure. Will eventually
* replace @pipe.
* @pipe: Holds endpoint number, direction, type, and more.
@@ -1642,12 +1647,13 @@ struct urb {
void *hcpriv; /* private data for host controller */
atomic_t use_count; /* concurrent submissions counter */
atomic_t reject; /* submissions will fail */
+ atomic_t anchor_readers; /* lockless urb->anchor readers */
/* public: documented fields in the urb that can be used by drivers */
struct list_head urb_list; /* list head for use by the urb's
* current owner */
struct list_head anchor_list; /* the URB may be anchored */
- struct usb_anchor *anchor;
+ struct usb_anchor __rcu *anchor;
struct usb_device *dev; /* (in) pointer to associated device */
struct usb_host_endpoint *ep; /* (internal) pointer to endpoint */
unsigned int pipe; /* (in) pipe information */
--
2.39.5 (Apple Git-154)
^ permalink raw reply [flat|nested] 5+ messages in thread
* Re: [PATCH v3 1/3] usb: core: Fix use-after-free in anchor wakeup protocol
2026-11-27 13:28 ` [PATCH v3 1/3] usb: core: Fix use-after-free in anchor wakeup protocol Hongyu Xie
@ 2026-11-27 13:57 ` Greg KH
0 siblings, 0 replies; 5+ messages in thread
From: Greg KH @ 2026-11-27 13:57 UTC (permalink / raw)
To: Hongyu Xie
Cc: Alan Stern, Oliver Neukum, oliver, Hans de Goede, linux-usb,
linux-kernel
On Fri, Nov 27, 2026 at 09:28:51PM +0800, Hongyu Xie wrote:
> usb_wait_anchor_empty_timeout() and the anchor cleanup helpers
> promise that once they return successfully (non-zero, for
> usb_wait_anchor_empty_timeout()), no URB giveback is in flight for
> the anchor any more, so the driver may free the memory holding it
> (xpad, for example, embeds irq_out_anchor in its private structure
> and kfrees it in xpad_disconnect()).
>
> Two windows break this promise: the waiter can observe "anchor
> list empty and suspend_wakeups == 0" while a giveback is still
> about to access anchor->wait.
>
> 1. usb_anchor_resume_wakeups() decrements suspend_wakeups -- which
> makes the wait condition true -- and only then calls
> wake_up(&anchor->wait), with nothing in between serializing the
> two. A waiter returns, the driver frees the anchor, and the
> late wake_up() touches the freed wait queue head.
>
> 2. __usb_unanchor_urb() wakes waiters while holding anchor->lock,
> but usb_wait_anchor_empty_timeout() evaluated the same condition
> without the lock, so it could observe the emptied urb_list in
> the middle of that critical section and return before the
> wake_up() and the spin_unlock() had run. Reading the two
> condition fields locklessly could likewise observe a stale
> suspend_wakeups value after the giveback's unanchor on weakly
> ordered systems.
>
> Complete the locking protocol that commit fbc299437c06 ("usb:
> core: Solve race condition in anchor cleanup functions")
> established for the kill/poison/scuttle helpers:
> usb_wait_anchor_empty_timeout() now evaluates the condition under
> anchor->lock (a self-locking wrapper around the lockless check),
> and usb_anchor_resume_wakeups() performs the suspend_wakeups
> decrement, the wakeup check and the wake_up() within a single
> anchor->lock critical section.
>
> With the decrement and the wake_up() atomic with respect to the
> locked condition check, a waiter can only observe the condition
> true after every giveback that has incremented suspend_wakeups has
> stopped accessing the anchor: the guarantee that the wakeup is
> delayed until the completion handler has run now extends to the
> anchor memory itself.
>
> syzbot has reported this race repeatedly since 2019, most
> recently as:
>
> BUG: KASAN: slab-use-after-free in register_lock_class+0x8d1/0x980 kernel/locking/lockdep.c:1333
> [...]
> __wake_up_common_lock+0x25/0x1e0 kernel/sched/wait.c:105
> __usb_hcd_giveback_urb+0x3ac/0x530 drivers/usb/core/hcd.c:1653
>
> Freed by task 7828:
> [...]
> kfree+0x14a/0x380 mm/slub.c:4390
> xpad_disconnect+0x359/0x490 drivers/input/joystick/xpad.c:2194
>
> and:
>
> BUG: KASAN: use-after-free in register_lock_class+0xe6a/0x1120 kernel/locking/lockdep.c:1336
> [...]
> __wake_up_common_lock+0xb4/0x130 kernel/sched/wait.c:136
> usb_anchor_resume_wakeups drivers/usb/core/urb.c:958 [inline]
> usb_anchor_resume_wakeups+0xbe/0xe0 drivers/usb/core/urb.c:951
> __usb_hcd_giveback_urb+0x2df/0x5c0 drivers/usb/core/hcd.c:1674
>
> Freed by task 3889:
> [...]
> kfree+0x173/0x390 mm/slab.c:3786
> xpad_disconnect+0x1cb/0x530 drivers/input/joystick/xpad.c:1905
>
> Both reports lack a reproducer; the analysis was verified
> by walking the two stacks against the code, not at runtime. All
> in-tree callers of usb_wait_anchor_empty_timeout() (and every
> driver which frees an anchor after the anchor cleanup helpers) are
> equally affected; xpad is merely the one syzbot found.
>
> Fixes: 6ec4147e7bdb ("usb-anchor: Delay usb_wait_anchor_empty_timeout wake up till completion is done")
> Fixes: 51a2f077c44e ("USB: introduce usb_anchor")
> Reported-by: syzbot+7f5e98b052c766f47f68@syzkaller.appspotmail.com
> Closes: https://lore.kernel.org/r/00000000000090170a0614431f47@google.com
> Reported-by: syzbot+59d3714b44d79d02f944@syzkaller.appspotmail.com
> Closes: https://lore.kernel.org/r/00000000000038435e05e9f94cd4@google.com
> Cc: stable@vger.kernel.org
> Cc: Alan Stern <stern@rowland.harvard.edu>
> Cc: Oliver Neukum <oliver@neukum.org>
> Cc: Hans de Goede <hansg@kernel.org>
> Signed-off-by: Hongyu Xie <xiehongyu1@kylinos.cn>
> ---
> drivers/usb/core/urb.c | 51 +++++++++++++++++++++++++++++++++++++-----
> 1 file changed, 45 insertions(+), 6 deletions(-)
>
> diff --git a/drivers/usb/core/urb.c b/drivers/usb/core/urb.c
> index ae0d61b5081f..bb1778d9e9db 100644
> --- a/drivers/usb/core/urb.c
> +++ b/drivers/usb/core/urb.c
> @@ -139,19 +139,39 @@ void usb_anchor_urb(struct urb *urb, struct usb_anchor *anchor)
> }
> EXPORT_SYMBOL_GPL(usb_anchor_urb);
>
> -static int usb_anchor_check_wakeup(struct usb_anchor *anchor)
> +/* Callers must hold anchor->lock */
> +static int __usb_anchor_check_wakeup(struct usb_anchor *anchor)
Mark this so the tools catch it when that lock is not held.
> {
> return atomic_read(&anchor->suspend_wakeups) == 0 &&
> list_empty(&anchor->urb_list);
> }
>
> +/*
> + * Same check as __usb_anchor_check_wakeup(), but takes anchor->lock. It is
> + * meant for waiters which do not hold the lock: the critical section
> + * serializes with the URB giveback path, so once the check succeeds no
> + * giveback that has incremented suspend_wakeups will touch the anchor
> + * anymore and the caller may free the memory holding the anchor.
> + */
> +static int usb_anchor_check_wakeup(struct usb_anchor *anchor)
> +{
> + unsigned long flags;
> + int wakeup;
> +
> + spin_lock_irqsave(&anchor->lock, flags);
> + wakeup = __usb_anchor_check_wakeup(anchor);
> + spin_unlock_irqrestore(&anchor->lock, flags);
guard()?
> +
> + return wakeup;
> +}
> +
> /* Callers must hold anchor->lock */
> static void __usb_unanchor_urb(struct urb *urb, struct usb_anchor *anchor)
> {
> urb->anchor = NULL;
> list_del(&urb->anchor_list);
> usb_put_urb(urb);
> - if (usb_anchor_check_wakeup(anchor))
> + if (__usb_anchor_check_wakeup(anchor))
> wake_up(&anchor->wait);
> }
>
> @@ -835,7 +855,7 @@ void usb_kill_anchored_urbs(struct usb_anchor *anchor)
> usb_put_urb(victim);
> spin_lock_irq(&anchor->lock);
> }
> - surely_empty = usb_anchor_check_wakeup(anchor);
> + surely_empty = __usb_anchor_check_wakeup(anchor);
>
> spin_unlock_irq(&anchor->lock);
> cpu_relax();
> @@ -874,7 +894,7 @@ void usb_poison_anchored_urbs(struct usb_anchor *anchor)
> usb_put_urb(victim);
> spin_lock_irq(&anchor->lock);
> }
> - surely_empty = usb_anchor_check_wakeup(anchor);
> + surely_empty = __usb_anchor_check_wakeup(anchor);
>
> spin_unlock_irq(&anchor->lock);
> cpu_relax();
> @@ -927,12 +947,23 @@ EXPORT_SYMBOL_GPL(usb_anchor_suspend_wakeups);
> */
> void usb_anchor_resume_wakeups(struct usb_anchor *anchor)
> {
> + unsigned long flags;
> +
> if (!anchor)
> return;
>
> + /*
> + * The decrement, the wakeup check and the wake_up() must happen
> + * under anchor->lock: usb_wait_anchor_empty_timeout() waiters
> + * evaluate the same condition under the lock and may free the
> + * anchor once they observe it true, so this function must not
> + * touch anchor->wait after that.
> + */
> + spin_lock_irqsave(&anchor->lock, flags);
guard()?
And please reduce the llm-generated comments and changelog spam, it's
not helpful. It can, and should, be much smaller. Delete all of the
changelogs and write them on your own please.
thanks,
greg k-h
^ permalink raw reply [flat|nested] 5+ messages in thread
end of thread, other threads:[~2026-11-27 13:56 UTC | newest]
Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-27 13:28 [PATCH v3 0/3] usb: core: fix three use-after-free windows in the USB anchor protocol Hongyu Xie
2026-11-27 13:28 ` [PATCH v3 1/3] usb: core: Fix use-after-free in anchor wakeup protocol Hongyu Xie
2026-11-27 13:57 ` Greg KH
2026-11-27 13:28 ` [PATCH v3 2/3] usb: core: Close anchor capture-to-increment race in URB giveback Hongyu Xie
2026-11-27 13:29 ` [PATCH v3 3/3] usb: core: Close residual anchor read-to-lock window with RCU Hongyu Xie
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®