[PATCH v2 0/3] usb: gadget: f_tcm: fix TPG lifetime and lock ordering

From: Slawomir Stepien

Date: Mon Nov 23 2026 - 09:25:40 EST


This series fixes three f_tcm bugs. All of them come from the gadget
and the target configfs trees being set up and torn down independently:

1. Disabling a TPG while a UDC is being assigned can deadlock on
dep_lock vs gi->lock.
2. Removing an enabled TPG while the gadget is bound frees the TPG
under the bound function (use-after-free).
3. fu->tpg is copied when the function is linked, so it is NULL if the
TPG is created later and stale after the TPG is recreated. Taking
tpg_instances_lock there also causes the syzbot lockdep report.

Patch 2 makes sure a TPG is never freed while a function is bound to
it. Patch 3 relies on that: fu->tpg is taken in tcm_bind() and cannot
change until tcm_unbind(), so it needs no extra locking or reference
counting.

Tested with dummy_hcd, KASAN and lockdep: linking the function before
the TPG exists, rmdir of an enabled and bound TPG, recreating the TPG
and rebinding, enable/disable racing with UDC writes, and the legacy
g_target. Without the respective patch these hit a NULL dereference, a
use-after-free and the deadlock.

Not addressed here: usbg_make_tpg() calls configfs_depend_item_unlocked()
under tpg_instances_lock, which gives a separate lockdep report
(su_mutex -> tpg_instances_lock -> configfs inode lock). It is already
there on v7.3 and is not changed by this series. Since it turns lockdep
off, I used a local hack (lockdep_off()/lockdep_on()) to avoid it
during testing.

AI assistance: patch 3 was first drafted with Gemini (gemini-4-argon,
gemini-3.8-flash) in the syzbot AI job linked from it. Patches 1 and 2
were written with Claude (claude-opus-5-5), which I also used to rework
patch 3, update the changelogs, draft this cover letter and run the
tests above (virtme-ng, dummy_hcd, KASAN, lockdep).

Changes in v2:
- Reorder: the dep_lock deadlock fix and the detach-on-drop fix come
first, and the tcm_bind() patch is last, so a TPG can no longer
change or go away under a bound function (Greg).
- Patch 3: drop the dep_lock around the opts->tpg writes (Greg), the
can_attach reset in usbg_drop_tpg() and the !opts->tpg check in
tcm_bind(). They were only needed because of the old order. Document
why opts->tpg cannot change while the function is bound.
- Patch 2: note that it relies on patch 1, and that patch 3 fixes the
remaining stale fu->tpg.

v1: https://lore.kernel.org/all/20261022134926.1125473-1-sst@xxxxxxxxx/

Slawomir Stepien (3):
usb: gadget: f_tcm: don't hold dep_lock across
unregister_gadget_item()
usb: gadget: f_tcm: detach gadget when dropping an enabled TPG
usb: gadget: f_tcm: take the TPG in tcm_bind() instead of tcm_alloc()

drivers/usb/gadget/function/f_tcm.c | 32 ++++++++++++++---------------
drivers/usb/gadget/function/u_tcm.h | 6 ++++++
2 files changed, 21 insertions(+), 17 deletions(-)


base-commit: c03c1a14507dfaf8b856c2608f9ac216021fc222
--
2.56.0