Linux USB
 help / color / mirror / Atom feed
* [PATCH v4 0/2] usb: dwc2: gadget: descriptor DMA fixes for BNA, found on Sophgo SG2002
@ 2026-12-05 13:02 Vadim Yuzifovich
  2026-12-05 13:02 ` [PATCH v4 1/2] usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA Vadim Yuzifovich
  2026-12-05 13:02 ` [PATCH v4 2/2] usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN " Vadim Yuzifovich
  0 siblings, 2 replies; 5+ messages in thread
From: Vadim Yuzifovich @ 2026-12-05 13:02 UTC (permalink / raw)
  To: Thinh.Nguyen, gregkh
  Cc: linux-usb, linux-kernel, chenyou910331, inochiama, sophgo

These are patches 1 and 2 of the three offered in [1], on top of
usb-next. Chen-Yu asked for them as a series and has tested v2 on a
Milk-V Duo 256M, see his reply in [3]. Patch 3 of v3 is left out of v4,
see below.

We run a Sophgo SG2002 (T-Head C906, DWC_otg 4.20a) as a peripheral with
g_dma and g_dma_desc both on, as a composite gadget: mass storage, HID,
ACM and UAC1. Descriptor DMA works there, but only with these changes.
In mainline, dwc2_set_cv1800_params() turns gadget DMA off on these
SoCs, so none of this runs there as it is; see the end of this letter
for how to try it.

Patch 1: an isochronous OUT endpoint that takes a BNA is never restarted,
and the BNA interrupt then repeats until the host resets the port.

Patch 2: a bulk or interrupt IN endpoint that takes a BNA is only logged
at debug level. It stays disabled with its request current, and the
function waits until the host times out.

Patch 3 of v3 made descriptors visible to the core before the endpoint
is enabled: on this SoC the core fetched a descriptor before the CPU's
stores to it had reached DRAM, which is why bulk endpoints took BNAs at
all. It is a CV18XX/SG200X workaround, and mainline cannot reach it
while dwc2_set_cv1800_params() turns gadget DMA off. It will come back
with a patch that enables gadget DMA on these SoCs, after I have asked
the RISC-V side about the C906 fence behaviour that looks like its root
cause. Testers on an SG2002 still need it to avoid bulk BNAs under load;
it is v3 patch 3 [5].

Thinh, patch 1 is built on what I saw this core do, not on what it is
specified to do: after a BNA on an isochronous OUT endpoint it holds
the packet, shows the endpoint as disabled, and delivers the packet to
descriptor 0 as soon as that is host ready, enabled or not; and it does
not survive a Rx FIFO flush with OUT traffic going on. If the databook
describes the recovery differently, please say so. The same for patch
2: in about 40000 BNAs on bulk endpoints in the v1 and v2 tests the
endpoint was disabled already when the BNA was handled, and no
endpoint-disabled interrupt followed. v4 restarts from the BNA handler
then. When the endpoint still reads enabled, it sets SNAK and EPDIS
and restarts from the endpoint-disabled interrupt that brings. If it
should always go that way, I will do it so.

Patch 2 has a Fixes tag but no Cc: stable, since it is built on patch 1
and would not apply without it.

Testing by Chen-Yu on v2, on a Duo 256M with 7.4-rc3, a composite of
ECM, mass storage and UAC1, and a console line every 2 s as the
interrupt hold: without the series the UAC1 stream wedged in 3 of 4
runs; with patches 1 and 2, or all three, no run wedged. Patches 2 and
3 were not exercised there, since no bulk BNA happened without the
series either. v4 has not been run there; Chen-Yu, a run of v4 would be
welcome.

Testing here, on the SG2002 with v4 applied to our 7.4-rc5 tree, with
v3 patch 3, counters and two test hooks: one holds interrupts off for a
given time, the other holds back the requests the function queues on
the isochronous OUT endpoint and gives them back one at a time or all
together. A tone is played into the UAC1 gadget, eight requests of 1 ms
are queued, and the host sends TEST UNIT READY to the mass storage
function and GET_STATUS on EP0 in a loop throughout.
- 50 rounds of holding back every request for 20 ms, then 50 rounds of
  giving them back one at a time: 250 stops with nothing queued, each
  drained (one packet each time, 23 us at most), and 250 restarts.
- 200 interrupt holds of 3 to 40 ms, 1.6 s apart: 304 restarts, in each
  of which the core had taken descriptor 0 for the held packet; BNAs
  latched before a restart were seen and ignored afterwards; no BNA was
  seen with the endpoint enabled at any other time.
- 5 holds of 3 s with nothing queued: the stream stopped and resumed.
- During these, 82609 TEST UNIT READY commands and 48676 control
  requests, none failed; the slowest took 45 ms and 40 ms. Without the
  NAK and drain in patch 1, one 3 s hold made a TEST UNIT READY take
  3 s and two control requests time out.
- 450 holds of 3 s with nothing queued during which the host closed the
  stream, so that the endpoint was disabled while stopped, at 0.2 to
  4.2 s into the hold; the stream was opened again after each.
- A USB reset from the host, three times, and an unbind and bind of the
  gadget on the board, each while the endpoint was stopped: the gadget
  enumerated again and the stream ran.
- SET_FEATURE(ENDPOINT_HALT) and CLEAR_FEATURE on the mass storage bulk
  IN endpoint, three times: the endpoint reported halted and then not,
  and the mass storage function answered afterwards.
- With a test hook that skips the drain of a stopping endpoint, so that
  it still held its packets, an unbind and bind of the gadget on the
  board during a hold, 15 times: the drain in dwc2_hsotg_ep_disable()
  took the packets each time, the gadget enumerated again, and TEST
  UNIT READY, control requests and the stream worked right after. The
  OUT endpoints disabled before it timed out waiting for the global OUT
  NAK, which the held packets keep from taking effect (100 us each,
  with a warning). The previous revision of v4 left those packets held
  in that test, and every core reset after it then timed out waiting
  for the AHB master to go idle, until a reboot.
The stream ran at about 1009 completions a second after each part, and
there was no port reset. The holds, the USB resets and 5 of the unbinds
with packets held ran on v4 as posted. The stream closes and the halt
test ran on earlier revisions of v4, which differed in the paths that
an endpoint disable takes; 40 of the stream closes were run on the
revision before this one, which differs from it only in the review
fixes listed last below.

Once, in a test of an earlier revision of v4, a counter of
isochronous OUT XferCompl interrupts went up by about 6.7 million in
about 10 s, right as the host closed the stream at the end of a hold,
and then stopped by itself; the board stayed responsive and nothing was
logged. It did not happen again in 516 more tries of that test, 490
of them on later revisions and 450 of those with every XferCompl that
finds no completed descriptor traced; none were run on v4 as posted.
I do not know its cause; the test hook that holds the requests back,
which f_uac1 may free while the hook still has them, is a suspect, but
that is not shown.

Patch 2 was not exercised by v4 on the board: the bulk BNAs only came
with a 1080p60 encode loading the DRAM, which was not running, and the
v3 patch 3 that the board runs closes the window they came through. Its
v3 results are below. Since v3 it restarts IN endpoints only, restarts
a scatter-gather request only from its start, disables an endpoint
that still reads enabled and restarts it from the endpoint-disabled
interrupt, skips the TxFIFO flush of a restarted endpoint on a later
endpoint-disabled interrupt, warns about a BNA that leaves the endpoint
stopped, and gives up after three restarts; none of those changes has
been exercised.

Patches 2 and 3 in v3, under the load described in v3 patch 3 (TEST
UNIT READY as fast as the host can, a 1080p60 H.264 encode running),
with the read-back of patch 3 switched off: 402000 commands in 120 s
(3347 a second), 14452 BNAs on the bulk endpoints, 12269 of them
restarted by patch 2, no port reset. The warning is rate limited; the
30 that were logged as not restarted were all on the bulk OUT endpoint,
came together with XferCompl, and the descriptor read DMA done. With
the read-back on: 546000 commands in 180 s, no BNA and no reset.

Not tested, or known and left as they are:
- a BNA restart with more than 256 requests queued. As before the
  series, requests beyond the 256 descriptors are not put in the chain
  when it is started.
- a BNA in the middle of a bulk chain of several descriptors, or of a
  scatter-gather chain. We only hit the BNA on a chain of one
  descriptor.
- a bulk OUT BNA: patch 2 leaves those alone, as before the series.
- a drain that hits its bound or times out: every drain here took one
  packet and finished.
- the core may take descriptor 0 between the last poll of a wait and
  the store that marks it host busy again, or while a request queued in
  the window before a BNA is put on it; one packet, or its status, is
  lost then. Closing that needs the core to say whether it holds a
  packet, which I have not found.
- isochronous IN, full speed, an interval above 1. Isochronous IN
  behaves as before the series.
- any other core version or SoC, and SMP: the SG2002 has one core. The
  disable count in patch 1 is for SMP and could not be exercised here.

To try it on a CV18XX/SG200X board, gadget DMA has to be allowed, since
dwc2_set_cv1800_params() turns it off, and v3 patch 3 [5] applied:

  --- a/drivers/usb/dwc2/params.c
  +++ b/drivers/usb/dwc2/params.c
  @@ static void dwc2_set_cv1800_params(struct dwc2_hsotg *hsotg)
   	p->host_dma = false;
  -	p->g_dma = false;
  -	p->g_dma_desc = false;
   	p->speed = DWC2_SPEED_PARAM_HIGH;

"usb: dwc2: Disable gadget descriptor DMA for Sophgo CV18XX/SG200X",
now in usb-next, only silences the probe warning while g_dma is off and
does not conflict with this series. Whether DMA should become the
default on these SoCs is a separate question, and host DMA was not
tested.

An AI coding assistant (Claude) was used in the debugging sessions and
in drafting the code and the changelogs. The measurements were made on
real hardware, and I have reviewed the patches.

Changes in v4. The first three answer the four findings of the Sashiko
review of v3 [4], the rest come from reviews of v4 before sending it,
two of them local Sashiko runs, and from the tests above:
- Patch 1: dwc2_hsotg_ep_queue() no longer restarts a stopped endpoint;
  it only unmasks it, and the BNA or OUTTKNEPDIS that follows restarts
  it from the interrupt handler. So no request completes inside
  usb_ep_queue(), and the endpoint is not unmasked before the held
  packet has been given back.
- Patch 1: mark a descriptor of an OUT endpoint host busy again when its
  request is given back, so that the completion loop cannot take a
  descriptor left as DMA done from the last lap of the ring.
- Patch 1: stop if the endpoint was disabled while the lock was dropped
  for a giveback. v4 uses a count that dwc2_hsotg_ep_disable() bumps
  rather than USBACTEP, so that an endpoint disabled and enabled again
  meanwhile is seen too.
- Patch 1: ignore a BNA seen with the endpoint enabled only right after
  a restart, until the next interrupt of the endpoint without a BNA.
  Any other such BNA resets the state as before the series and leaves
  the restart to the endpoint-disabled or OUT token interrupt.
- Patch 1: wait for a held packet only on the first start after a BNA,
  not on every stream start.
- Patch 1: NAK an endpoint that is stopped with no request queued, and
  write the packets it holds to a scratch buffer until the core takes
  no more; dwc2_hsotg_ep_disable() does the same for an endpoint left
  that way. Before, they stayed at the head of the Rx FIFO, and EP0 and
  bulk OUT stalled until the function queued a request again. The drain
  waits 200 us at most with interrupts off; what is left is drained on
  the next BNA. A descriptor the core took for a dropped packet but has
  not written is not reused for a request until it has.
- Patch 1: dwc2_hsotg_epint() stops after a handler that dropped the
  lock if the endpoint was disabled meanwhile, instead of acting on the
  interrupts it read before.
- Patch 1: an OUT token interrupt that finds the chain taken for running
  but the endpoint disabled restarts it as after a BNA.
- Patch 1: write descriptor status words with one store. Host ready is
  0, so a status built up in place could read host ready too early.
- Patch 1: leave isochronous IN as it was: its BNA is handled where and
  how it was, the endpoint-disabled handler keeps its per-frame
  completion for it, and its descriptors are not written back.
- Patch 2: restart IN endpoints only, and a scatter-gather request only
  from its start. A bulk OUT endpoint may hold an acknowledged packet as
  the isochronous one does, and a restart could race with its write.
- Patch 2: restart a request at most three times between completions.
  Warn about an actual restart and about a BNA that leaves the endpoint
  stopped with its request current; other BNAs stay at debug level.
- Patch 2: do not flush the TxFIFO of a restarted endpoint on an
  endpoint-disabled interrupt latched for its BNA and not handled yet;
  a halted or stalled endpoint is always flushed. Fixes tag added.
- Patch 1: the drain in dwc2_hsotg_ep_disable() may wait up to 2 ms
  rather than 200 us, since no BNA comes to drain on once the endpoint
  is gone, and warns if packets are left. A Rx FIFO flush would not
  release them, see patch 1.
- Patch 1: forget the BNA state, including a descriptor 0 left with the
  core by a drain that timed out, in dwc2_hsotg_ep_disable() and
  dwc2_hsotg_ep_enable(), and bump the disable count in
  dwc2_hsotg_disconnect() too.
- Patch 1: the endpoint-disabled handler leaves an endpoint the BNA
  handler has just stopped alone, so the waits with interrupts off are
  not repeated in one interrupt: about 310 us at most.
- Patch 1: a drain that times out, or finds descriptor 0 still with the
  core, leaves the stopped endpoint unmasked, so that the BNA of the
  next held packet drains on; at most four times in a row.
- Patch 2: the TxFIFO flush mark is cleared only by the
  endpoint-disabled handler and the reset paths, not by an XferCompl or
  the start of the next request in the same interrupt.
- Patch 2: a BNA seen with the endpoint still enabled sets SNAK and
  EPDIS, so that the endpoint-disabled interrupt the restart waits for
  is sure to come.
- Patch 3 left out, see above. Chen-Yu's Tested-by on it goes with it.
- Rebased on usb-next.
- Patch 1 is long; if you prefer it split (the Rx FIFO flush removal,
  the endpoint-disabled change, the restart and held packet, the NAK and
  drain, the disable count, the single-store status writes, the stop at
  the wrap of next_desc), I will split it, and the same for cutting the
  changelog of patch 2 down.

Changes in v3 [4]. The first, second, fourth and fifth are from the
Sashiko review of v2 [3], the rest from my own review and tests:
- Patch 1: stop filling the isochronous chain when next_desc wraps to
  0. In v2 more than 256 queued requests overwrote descriptor 0, which
  is kept host busy at that point.
- Patch 1: a request queued from a completion while the endpoint is
  stopped after a BNA no longer makes descriptor 0 host ready before
  the chain is built again.
- Patch 2: restart only while the first descriptor of the chain is
  still host ready, so that a BNA further down a chain of several
  descriptors does not transfer the start of it twice.
- Patch 1: for an OUT endpoint the BNA handler gives no request back.
  The held packet lands in the request at the head of the queue, so v2
  completed that one empty and put the packet into the next.
- Patch 1: an OUT endpoint left with no request after a BNA, because
  none was queued or the held packet took the last one, is restarted
  by dwc2_hsotg_ep_queue() when a request arrives. In v2 it stayed
  disabled until a later BNA, or for good once the held packet had
  been taken.
- Patch 1: if the held packet has not landed within 100 us, warn and
  leave descriptor 0 to the core instead of building the chain over it.
- Patch 1: mask the endpoint's interrupts while it is stopped with no
  request queued. The core raises BNA as fast as the handler clears it
  while it holds the packet: 1.8 million interrupts in about a second
  without the mask, and the host reset the port.
- Patch 1: clear the stopped mark before a restart, so that a request
  queued from the held packet's completion cannot start a second
  restart inside the first.
- Patch 1: give back descriptors that completed before a BNA or an
  endpoint disable while the chain still ran, and clear the stopped
  state in dwc2_hsotg_ep_disable() before the requests are killed.
- Patch 3: say in the changelog that a descriptor appended to a running
  isochronous chain is not read back.

Changes in v2 [3]:
- Patch 1: rewritten. v1 [2] was wrong, see my reply to it. Handle BNA
  before the endpoint-disabled, OUT token and NAK interrupts, ignore a
  BNA for an OUT endpoint that is enabled, keep descriptor 0 host busy
  until the chain is written, deal with the packet the core holds, do
  not flush the Rx FIFO. Fixes tag added.
- Patch 2: restart the request from req.actual instead of from its
  beginning.
- Patch 3: read the last descriptor back also when the isochronous
  chain is full, and read descriptor 0 of an isochronous chain back.

[1] the offer: https://lore.kernel.org/r/CAH_=YdDCDyFBn2k18w8Ck5jrmHHZme7TuAA71hSgcAa9ZPb38Q@mail.gmail.com
[2] v1: https://lore.kernel.org/r/20261115185335.782678-1-vadim@yuzi.co
[3] v2: https://lore.kernel.org/r/20261116070433.2813951-1-vadim@yuzi.co
[4] v3: https://lore.kernel.org/r/20261201142920.49830-1-vadim@yuzi.co
[5] v3 patch 3: https://lore.kernel.org/r/20261201142920.49830-4-vadim@yuzi.co

Vadim Yuzifovich (2):
  usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints
    after BNA
  usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN
    endpoints after BNA

 drivers/usb/dwc2/core.h   |  41 ++
 drivers/usb/dwc2/gadget.c | 845 ++++++++++++++++++++++++++++++++++++--
 2 files changed, 847 insertions(+), 39 deletions(-)


base-commit: 9357829ac604c28510b71b154cb6630af81226ff
-- 
2.56.1.windows.1


^ permalink raw reply	[flat|nested] 5+ messages in thread

* [PATCH v4 1/2] usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA
  2026-12-05 13:02 [PATCH v4 0/2] usb: dwc2: gadget: descriptor DMA fixes for BNA, found on Sophgo SG2002 Vadim Yuzifovich
@ 2026-12-05 13:02 ` Vadim Yuzifovich
  2026-12-05 13:31   ` sashiko-bot
  2026-12-05 13:02 ` [PATCH v4 2/2] usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN " Vadim Yuzifovich
  1 sibling, 1 reply; 5+ messages in thread
From: Vadim Yuzifovich @ 2026-12-05 13:02 UTC (permalink / raw)
  To: Thinh.Nguyen, gregkh
  Cc: linux-usb, linux-kernel, chenyou910331, inochiama, sophgo

In descriptor DMA mode the core stops an isochronous endpoint when it
reaches a descriptor that is not ready (BNA), for example after an
interrupt latency longer than the queued requests cover.
dwc2_gadget_handle_isoc_bna() resets the endpoint and leaves the restart
to the next OUTTKNEPDIS. On a Sophgo SG2002 (DWC_otg 4.20a) that
interrupt does not come. The core keeps the OUT packet that met the BNA,
shows the endpoint as disabled, and tries the descriptor at the start of
the chain again and again, raising BNA each time, as fast as the handler
clears it.

With a UAC1 capture endpoint and eight requests queued, one 8 ms
interrupt latency (a line printed on the 115200 baud serial console)
caused one BNA. The endpoint stayed disabled and the BNA interrupt kept
the CPU busy until the host gave up and reset the port, which took the
other functions of the composite gadget down as well.

An endpoint-disabled interrupt after the BNA makes it worse:
dwc2_gadget_handle_ep_disabled() has an isochronous part written for
buffer DMA, which completes requests frame by frame and advances
target_frame up to the current frame. That moves target_frame off
TARGET_FRAME_INITIAL, and the OUT token handler then takes the chain for
running and never restarts it.

So restart an OUT endpoint from the BNA handler, and from the
endpoint-disabled handler when it finds the endpoint disabled with
requests queued, and do not run the buffer DMA completion for an
isochronous OUT endpoint in descriptor DMA mode. Isochronous IN
endpoints are left as they are; they keep restarting on the next NAK.

The restart has to deal with the packet the core holds. The core takes
the descriptor at the start of the chain the moment it is host ready,
before the endpoint is enabled, writes the packet to it and then stops:
a chain that is enabled after that takes one packet at most and raises
BNA on the next. Traced on the SG2002, a restart that just rebuilt the
chain and enabled the endpoint gave one BNA and one restart for every
packet from then on, about 2000 interrupts a second, with the audio
mostly intact; and since the chain is filled front to back, the core
took descriptor 0 while it still carried the L bit.

Therefore keep descriptor 0 host busy while the chain is filled, write
the chain address, and only then mark descriptor 0 host ready. If the
core takes it before the endpoint is enabled, wait for the packet to
land, give its request back, and build the chain once more: no packet is
waiting for that one, and it starts like the first chain of a stream. If
the packet has not landed after 100 us, warn and leave descriptor 0 to
the core: the chain is enabled as it is, the packet completes as its
first, and the BNA on the next descriptor restarts the endpoint again.
Rebuilding the chain over a descriptor the core is still writing would
lose the packet or its status. A stream that starts on its first OUT
token has no packet held and does not wait.

The BNA handler must not flush the Rx FIFO for this. The FIFO is shared
by all OUT endpoints and nothing stops the host: when an OUT token
arrived while the handler ran, the flush left the core with a FIFO it
never drained again. GINTSTS.RXFLVL stayed set, every isochronous OUT
packet was dropped with OUTTKNEPDIS and no XferCompl, and bulk OUT on
the mass storage function was NAKed until its host driver timed out and
reset the port, after which EP0 did not answer. That happened about once
in 100 BNAs here. The flush does not drop the packet that met the BNA
either; the core delivers it to the new chain all the same. So drop the
flush.

A BNA can also arrive in the same interrupt as the endpoint-disabled,
OUT token or NAK interrupt that starts a chain, and since the core keeps
raising it, one is latched just before the restart and seen after it.
Handle the BNA of an isochronous OUT endpoint before those interrupts,
and ignore a BNA that is seen with the endpoint enabled again after such
a restart, so that the BNA handler never gives back a request of a
running chain or resets the endpoint state under it. Such a BNA is seen
in the next interrupt of the endpoint, so the next one without a BNA
ends that. A BNA seen with the endpoint enabled at any other time, as a
core that clears EPENA only after raising BNA could give, resets the
endpoint state as before this patch and leaves the restart to the
endpoint-disabled or OUT token interrupt. An OUT token interrupt that
finds the chain taken for running but the endpoint disabled restarts it
as after a BNA, so that a BNA swallowed as one latched before a restart
cannot leave the endpoint dead either.

For an OUT endpoint the BNA handler gives no request back. The held
packet goes to descriptor 0 of the new chain, which belongs to the
request at the head of the queue; giving that request back first, as
dwc2 did, completed it empty and moved the packet to the next one. If no
request is queued at the BNA, or the held packet took the last one,
nothing can be started and no OUTTKNEPDIS follows, so mark the endpoint
stopped. IN endpoints keep giving the request back.

While it holds the packet, the core raises BNA again as fast as the
handler clears it. On the SG2002, with the function's requests held back
for 20 ms by a test hook, that was 1.8 million BNA interrupts in about a
second, and the work item that was to queue the next request did not run
before the host reset the port. So mask the endpoint's interrupts while
it is stopped this way, and unmask them in dwc2_hsotg_ep_queue() when a
request arrives. The BNA the core raises for the packet it holds, or the
OUTTKNEPDIS of the next OUT token, then restarts the endpoint from the
interrupt handler. A restart from the queue call itself would give back
the request of the held packet inside usb_ep_queue().

Masking does not release the packet the core holds. It stays at the head
of the Rx FIFO, which all OUT endpoints share, and the core takes no
other OUT packet from the FIFO until it has written that one somewhere.
A disabled isochronous OUT endpoint also goes on taking the packets the
host sends into the FIFO. On the SG2002, with the requests held back for
3 s, TEST UNIT READY to the mass storage function took 3 s and control
requests on EP0 timed out. So NAK the endpoint when it is stopped, which
makes the core drop the packets that arrive after that, and point
descriptor 0 at a scratch buffer of the endpoint, again and again, until
the core no longer takes it. The packets written there are dropped: no
request was there to take them. With the endpoint NAKed no packet is
added. The drain runs with interrupts off, so it stops after 200 us in
all; if packets are left then, the endpoint stays marked as after a BNA
and its interrupts are left unmasked, and the BNA the core raises for
the next packet it holds drains on. If the core has taken descriptor 0
for a packet but not written it within 100 us, the descriptor stays
with the core: it is not filled for a request, and the chain is not
started, until the core has written it, since the request would
otherwise be given back with the dropped packet. The endpoint is left
unmasked then too, so that the BNA of the packet after it drains on
once the descriptor is written; that is done at most four times in a
row, so that a descriptor the core never writes back cannot turn into a
BNA on every interrupt.
dwc2_hsotg_ep_disable() drains an endpoint still marked as after a BNA,
so that the host closing the stream does not leave packets in front of
EP0. Once the endpoint is gone no BNA comes to drain on, so that drain
may wait up to 2 ms, and a warning says if packets are left even then.
A Rx FIFO flush would not release them: it waits for the AHB master to
go idle, and the core's DMA stays busy while it holds a packet with no
descriptor to write it to. On the SG2002, with a test hook leaving the
packets held through an unbind of the gadget, every core reset after
that found GRSTCTL.AHBIDLE clear until a reboot. The restart clears the
NAK when it enables the endpoint. With that, TEST UNIT READY took at
most 46 ms during the holds and no control request failed. The scratch
buffer is allocated in dwc2_hsotg_ep_enable() before the descriptor
list, so that its failure does not reach the error path that frees a
list left from an earlier enable of the endpoint.

The waits for a held packet run with interrupts off. Each takes 10 us
when the core holds no packet and the time of one packet's DMA when it
does, at most 110 us. One runs on the first start after a BNA; the
drain of a stopped endpoint waits at most 200 us in all. One interrupt
waits at most about 310 us, when the held packet takes the last request
and the endpoint is stopped and drained right after: the
endpoint-disabled interrupt that can come with the BNA leaves an
endpoint that the BNA handler stopped alone. dwc2_hsotg_ep_disable()
may wait up to 2 ms for its drain. On the SG2002 the longest drain
measured took 25 us, for one packet. A core that does
not hold the packet pays 10 us on each start after a BNA and each stop.

The core may read the status word of a descriptor at any time while it
holds a packet, and host ready is 0. So the status words this patch
writes, and those dwc2_gadget_fill_isoc_desc() and the chain reset in
dwc2_gadget_start_isoc_ddma() write, are written with one store, not
built up in place.

A function driver may queue a request from the completion of another, as
f_uac1 does, and completions run while the endpoint is stopped: those of
packets that completed in the same interrupt as the BNA, and the one of
the held packet. If next_desc is 0 at that moment, the queue call fills
descriptor 0 and marks it host ready, and the core takes it for the held
packet before the chain is built. So in dwc2_hsotg_ep_queue() keep
descriptor 0 host busy while an OUT endpoint is disabled, reset the
endpoint state in the BNA handler before anything is given back, and
take the chain as not running while the request of the held packet is
given back, so that those requests only add to the queue.

With descriptor 0 host busy the fill function does not see a chain that
is full. Stop filling when next_desc has wrapped to 0; otherwise more
requests queued than the chain has descriptors would overwrite
descriptor 0 and the ones after it.

Before the state is reset, packets that completed before the BNA but
whose XferCompl was not seen yet are given back, so that the rebuilt
chain does not reuse their requests. That is done only while a chain
runs: after a reset compl_desc points at descriptors left over from the
last chain, which may still read DMA done. dwc2_hsotg_ep_disable()
clears the stopped mark and the target frame before it kills the
requests, so that one queued from those completions neither restarts the
endpoint nor goes into its chain. dwc2_hsotg_ep_disable() also bumps a
count in the endpoint. Code that dropped the lock for a giveback checks
it and stops if the endpoint was disabled meanwhile, and maybe enabled
again, instead of going on with the old chain or restarting the
endpoint. dwc2_hsotg_epint() checks it too after each handler that may
give a request back, so that it does not act on interrupts it read for
an endpoint that has been disabled since. dwc2_hsotg_disconnect() bumps
it as well before it kills the requests. dwc2_hsotg_ep_disable() and
dwc2_hsotg_ep_enable() also forget the BNA state of the endpoint,
including a descriptor 0 that a drain left with the core, which after a
reset may never read DMA done.

dwc2_gadget_complete_isoc_request_ddma() leaves a completed descriptor
marked DMA done and stops at the first descriptor that is not. Once the
ring has wrapped, every descriptor that has not been filled again reads
DMA done. That was harmless while every request queued from a completion
filled the next descriptor, but while the endpoint state is reset such a
request goes to the queue only, and the loop would take the stale
descriptor after the last real completion for that request, complete it,
and go on as long as the function queues another. So mark the descriptor
of an OUT endpoint host busy again when its request is given back.

Fixes: 729cac693eec ("usb: dwc2: Change ISOC DDMA flow")
Signed-off-by: Vadim Yuzifovich <vadim@yuzi.co>
---
 drivers/usb/dwc2/core.h   |  31 ++
 drivers/usb/dwc2/gadget.c | 696 ++++++++++++++++++++++++++++++++++++--
 2 files changed, 691 insertions(+), 36 deletions(-)

diff --git a/drivers/usb/dwc2/core.h b/drivers/usb/dwc2/core.h
index a25af51928fc..d7bed6c98ec2 100644
--- a/drivers/usb/dwc2/core.h
+++ b/drivers/usb/dwc2/core.h
@@ -106,6 +106,28 @@ struct dwc2_hsotg_req;
  * @last_load: The offset of data for the last start of request.
  * @size_loaded: The last loaded size for DxEPTSIZE for periodic IN
  * @target_frame: Targeted frame num to setup next ISOC transfer
+ * @isoc_out_stopped: Descriptor DMA isochronous OUT endpoint stopped after a
+ *                    BNA with no request left to restart it with. Its
+ *                    interrupts are masked, unless a drain left packets
+ *                    behind; a request queued unmasks them, and the next
+ *                    BNA or OUTTKNEPDIS restarts the endpoint.
+ * @isoc_out_bna: Descriptor DMA isochronous OUT endpoint stopped by a BNA and
+ *                not started since; the core may hold the packet that met
+ *                the BNA.
+ * @isoc_out_restarted: Descriptor DMA isochronous OUT endpoint enabled again
+ *                      after a BNA; a BNA latched before that is still to
+ *                      be seen.
+ * @isoc_out_drain_busy: Descriptor 0 of a descriptor DMA isochronous OUT
+ *                       endpoint was taken by the core for a packet to drop
+ *                       and has not been written back yet.
+ * @isoc_out_drain_tries: Times a stopped descriptor DMA isochronous OUT
+ *                        endpoint was left unmasked because its drain could
+ *                        not finish; see dwc2_gadget_isoc_out_drain_retry().
+ * @disable_count: Bumped by dwc2_hsotg_ep_disable(), to tell whether the
+ *                 endpoint was disabled while the lock was dropped.
+ * @isoc_out_drain: Buffer for a descriptor DMA isochronous OUT endpoint to
+ *                  take a packet into that no request is queued for.
+ * @isoc_out_drain_dma: The DMA address of @isoc_out_drain.
  * @frame_overrun: Indicates SOF number overrun in DSTS
  *
  * This is the driver's state for each registered endpoint, allowing it
@@ -145,6 +167,12 @@ struct dwc2_hsotg_ep {
 	unsigned int            isochronous:1;
 	unsigned int            send_zlp:1;
 	unsigned int            wedged:1;
+	unsigned int            isoc_out_stopped:1;
+	unsigned int            isoc_out_bna:1;
+	unsigned int            isoc_out_restarted:1;
+	unsigned int            isoc_out_drain_busy:1;
+	unsigned int            isoc_out_drain_tries:3;
+	unsigned int            disable_count;
 	unsigned int            target_frame;
 #define TARGET_FRAME_INITIAL   0xFFFFFFFF
 	bool			frame_overrun;
@@ -153,6 +181,9 @@ struct dwc2_hsotg_ep {
 	struct dwc2_dma_desc	*desc_list;
 	u8			desc_count;
 
+	void			*isoc_out_drain;
+	dma_addr_t		isoc_out_drain_dma;
+
 	unsigned int		next_desc;
 	unsigned int		compl_desc;
 
diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c
index 7ef704568e09..fdbc9677aef2 100644
--- a/drivers/usb/dwc2/gadget.c
+++ b/drivers/usb/dwc2/gadget.c
@@ -218,6 +218,53 @@ static void dwc2_hsotg_ctrl_epint(struct dwc2_hsotg *hsotg,
 	local_irq_restore(flags);
 }
 
+/*
+ * dwc2_gadget_isoc_out_stop - leave a descriptor DMA isochronous OUT endpoint
+ * stopped until a request is queued.
+ * @hs_ep: The endpoint, disabled after a BNA, with no request to restart it.
+ *
+ * While the core holds the packet that met the BNA it raises BNA again as
+ * fast as the handler clears it, which keeps the CPU from the function that
+ * would queue the next request. Mask the endpoint's interrupts until a
+ * request is queued, see dwc2_gadget_isoc_out_unstop().
+ *
+ * A disabled isochronous OUT endpoint still takes the packets the host sends
+ * into the Rx FIFO, which all OUT endpoints share, and in DMA mode nothing
+ * takes them out of it: control transfers on EP0 and bulk OUT transfers stall
+ * behind them. So NAK the endpoint as well, which makes the core drop its
+ * packets; the restart clears the NAK when it enables the endpoint.
+ */
+static void dwc2_gadget_isoc_out_stop(struct dwc2_hsotg_ep *hs_ep)
+{
+	struct dwc2_hsotg *hsotg = hs_ep->parent;
+	u32 epctl_reg = DOEPCTL(hs_ep->index);
+
+	hs_ep->isoc_out_stopped = 1;
+	dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, 0, 0);
+	dwc2_writel(hsotg, dwc2_readl(hsotg, epctl_reg) | DXEPCTL_SNAK,
+		    epctl_reg);
+}
+
+/*
+ * dwc2_gadget_isoc_out_unstop - let the interrupt handler restart a stopped
+ * descriptor DMA isochronous OUT endpoint.
+ * @hs_ep: The endpoint, stopped by dwc2_gadget_isoc_out_stop(), with a
+ * request queued.
+ *
+ * The endpoint is not restarted here: the restart gives back the request that
+ * receives the packet the core holds, and a request must not complete inside
+ * usb_ep_queue(). Unmasking is enough. The core raises BNA for the endpoint
+ * while it holds a packet and OUTTKNEPDIS for the next OUT token otherwise,
+ * and either handler builds the chain again from the queue.
+ */
+static void dwc2_gadget_isoc_out_unstop(struct dwc2_hsotg_ep *hs_ep)
+{
+	if (!hs_ep->isoc_out_stopped)
+		return;
+	hs_ep->isoc_out_stopped = 0;
+	dwc2_hsotg_ctrl_epint(hs_ep->parent, hs_ep->index, 0, 1);
+}
+
 /**
  * dwc2_hsotg_tx_fifo_count - return count of TX FIFOs in device mode
  *
@@ -900,6 +947,7 @@ static void dwc2_gadget_config_nonisoc_xfer_ddma(struct dwc2_hsotg_ep *hs_ep,
  * @hs_ep: The isochronous endpoint.
  * @dma_buff: usb requests dma buffer.
  * @len: usb request transfer length.
+ * @hold: leave the descriptor host busy; the caller marks it host ready.
  *
  * Fills next free descriptor with the data of the arrived usb request,
  * frame info, sets Last and IOC bits increments next_desc. If filled
@@ -907,12 +955,14 @@ static void dwc2_gadget_config_nonisoc_xfer_ddma(struct dwc2_hsotg_ep *hs_ep,
  * status.
  */
 static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep,
-				      dma_addr_t dma_buff, unsigned int len)
+				      dma_addr_t dma_buff, unsigned int len,
+				      bool hold)
 {
 	struct dwc2_dma_desc *desc;
 	struct dwc2_hsotg *hsotg = hs_ep->parent;
 	u32 index;
 	u32 mask = 0;
+	u32 sts;
 	u8 pid = 0;
 
 	dwc2_gadget_get_desc_params(hs_ep, &mask);
@@ -934,29 +984,31 @@ static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep,
 	dev_dbg(hsotg->dev, "%s: Filling ep %d, dir %s isoc desc # %d\n",
 		__func__, hs_ep->index, hs_ep->dir_in ? "in" : "out", index);
 
-	desc->status = 0;
-	desc->status |= (DEV_DMA_BUFF_STS_HBUSY	<< DEV_DMA_BUFF_STS_SHIFT);
-
 	desc->buf = dma_buff;
-	desc->status |= (DEV_DMA_L | DEV_DMA_IOC |
-			 ((len << DEV_DMA_NBYTES_SHIFT) & mask));
+	sts = DEV_DMA_L | DEV_DMA_IOC | ((len << DEV_DMA_NBYTES_SHIFT) & mask);
 
 	if (hs_ep->dir_in) {
 		if (len)
 			pid = DIV_ROUND_UP(len, hs_ep->ep.maxpacket);
 		else
 			pid = 1;
-		desc->status |= ((pid << DEV_DMA_ISOC_PID_SHIFT) &
-				 DEV_DMA_ISOC_PID_MASK) |
-				((len % hs_ep->ep.maxpacket) ?
-				 DEV_DMA_SHORT : 0) |
-				((hs_ep->target_frame <<
-				  DEV_DMA_ISOC_FRNUM_SHIFT) &
-				 DEV_DMA_ISOC_FRNUM_MASK);
+		sts |= ((pid << DEV_DMA_ISOC_PID_SHIFT) &
+			DEV_DMA_ISOC_PID_MASK) |
+		       ((len % hs_ep->ep.maxpacket) ? DEV_DMA_SHORT : 0) |
+		       ((hs_ep->target_frame << DEV_DMA_ISOC_FRNUM_SHIFT) &
+			DEV_DMA_ISOC_FRNUM_MASK);
 	}
 
-	desc->status &= ~DEV_DMA_BUFF_STS_MASK;
-	desc->status |= (DEV_DMA_BUFF_STS_HREADY << DEV_DMA_BUFF_STS_SHIFT);
+	/*
+	 * Write the status word once. The core may be polling the descriptor,
+	 * see dwc2_gadget_isoc_out_held_packet(), and the buffer status
+	 * "host ready" is 0: a status built up in place would read host ready
+	 * with the length or flags of a descriptor still being filled.
+	 */
+	sts |= (hold ? DEV_DMA_BUFF_STS_HBUSY :
+		       DEV_DMA_BUFF_STS_HREADY) << DEV_DMA_BUFF_STS_SHIFT;
+	dma_wmb();
+	WRITE_ONCE(desc->status, sts);
 
 	/* Increment frame number by interval for IN */
 	if (hs_ep->dir_in)
@@ -970,6 +1022,262 @@ static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep,
 	return 0;
 }
 
+static void dwc2_gadget_complete_isoc_request_ddma(struct dwc2_hsotg_ep *hs_ep);
+
+/*
+ * dwc2_gadget_isoc_out_wait_packet - wait for the core to write a packet it
+ * holds to descriptor 0, just marked host ready.
+ * @hs_ep: The isochronous OUT endpoint, not enabled.
+ * @waited: Incremented by the microseconds waited.
+ *
+ * The core takes the descriptor within a few bus cycles if it holds a
+ * packet, and the DMA of one packet of at most 1024 bytes takes
+ * microseconds. So this waits 10 us when no packet is held, and at most
+ * 110 us when one is.
+ *
+ * Return: 1 if the packet was written, 0 if the core did not take the
+ * descriptor, or -ETIMEDOUT if it took it but has not written it yet.
+ */
+static int dwc2_gadget_isoc_out_wait_packet(struct dwc2_hsotg_ep *hs_ep,
+					    unsigned int *waited)
+{
+	struct dwc2_dma_desc *desc = &hs_ep->desc_list[0];
+	int i;
+
+	for (i = 0; i < 10; i++) {
+		if (READ_ONCE(desc->status) >> DEV_DMA_BUFF_STS_SHIFT !=
+		    DEV_DMA_BUFF_STS_HREADY)
+			break;
+		udelay(1);
+	}
+	*waited += i;
+	if (i == 10)
+		return 0;
+
+	for (i = 0; i < 100; i++) {
+		if (READ_ONCE(desc->status) >> DEV_DMA_BUFF_STS_SHIFT ==
+		    DEV_DMA_BUFF_STS_DMADONE)
+			break;
+		udelay(1);
+	}
+	*waited += i;
+	if (i < 100)
+		return 1;
+
+	dev_warn_ratelimited(hs_ep->parent->dev,
+			     "%s: held packet not written in 100 us\n",
+			     hs_ep->ep.name);
+	return -ETIMEDOUT;
+}
+
+/*
+ * dwc2_gadget_isoc_out_held_packet - let the core finish an OUT packet it
+ * holds from before a BNA.
+ * @hs_ep: The isochronous OUT endpoint, its new chain written and descriptor 0
+ * just marked host ready, the endpoint not enabled yet.
+ *
+ * A packet that met a descriptor that was not ready stays with the core. The
+ * core raises BNA, shows the endpoint as disabled, and keeps trying the
+ * descriptor at the start of the chain. As soon as that one is host ready the
+ * core writes the packet to it, without the endpoint being enabled, and then
+ * stops: a chain enabled after that takes no further packet. So wait for the
+ * packet to land and give its request back. The caller then starts a new
+ * chain, which no packet is waiting for.
+ *
+ * If the packet has not landed within 100 us, the descriptor is left to the
+ * core: the caller enables the chain as it is, the packet completes as the
+ * first of it, and a BNA on the next descriptor restarts the endpoint again.
+ *
+ * Only called for the first start after a BNA; a stream that starts on its
+ * first OUT token has no packet held.
+ *
+ * Return: true if the core took descriptor 0 and wrote the packet to it.
+ */
+static bool dwc2_gadget_isoc_out_held_packet(struct dwc2_hsotg_ep *hs_ep)
+{
+	unsigned int count = hs_ep->disable_count;
+	unsigned int waited = 0;
+	u32 target_frame;
+
+	if (dwc2_gadget_isoc_out_wait_packet(hs_ep, &waited) <= 0)
+		return false;
+
+	/*
+	 * The completion may queue a request. Keep it out of this chain,
+	 * which the caller builds again: as long as target_frame is initial,
+	 * dwc2_hsotg_ep_queue() only adds the request to the queue.
+	 */
+	target_frame = hs_ep->target_frame;
+	hs_ep->target_frame = TARGET_FRAME_INITIAL;
+	dwc2_gadget_complete_isoc_request_ddma(hs_ep);
+	/* Unless dwc2_hsotg_ep_disable() ran meanwhile, see the caller. */
+	if (hs_ep->disable_count == count)
+		hs_ep->target_frame = target_frame;
+
+	return true;
+}
+
+#define DWC2_ISOC_OUT_DRAIN_SIZE	1024
+/* Time one drain may spend waiting for packets, with interrupts off. */
+#define DWC2_ISOC_OUT_DRAIN_US		200
+/* The same when the endpoint is disabled, and no BNA comes to drain on. */
+#define DWC2_ISOC_OUT_DRAIN_DISABLE_US	2000
+/* Times a drain that could not finish leaves the endpoint to the next BNA. */
+#define DWC2_ISOC_OUT_DRAIN_TRIES	4
+
+/*
+ * dwc2_gadget_isoc_out_drain_settled - see whether descriptor 0 is free again
+ * after a drain that timed out.
+ * @hs_ep: The isochronous OUT endpoint.
+ *
+ * When the core took descriptor 0 for a packet to drop but had not written it
+ * within the wait, it still owns the descriptor, which points at the scratch
+ * buffer. It must not be filled for a request before the core has written it:
+ * the request would be given back with the dropped packet.
+ *
+ * Return: true if descriptor 0 may be written.
+ */
+static bool dwc2_gadget_isoc_out_drain_settled(struct dwc2_hsotg_ep *hs_ep)
+{
+	struct dwc2_dma_desc *desc = &hs_ep->desc_list[0];
+
+	if (!hs_ep->isoc_out_drain_busy)
+		return true;
+	if (READ_ONCE(desc->status) >> DEV_DMA_BUFF_STS_SHIFT !=
+	    DEV_DMA_BUFF_STS_DMADONE)
+		return false;
+	WRITE_ONCE(desc->status,
+		   DEV_DMA_BUFF_STS_HBUSY << DEV_DMA_BUFF_STS_SHIFT);
+	hs_ep->isoc_out_drain_busy = 0;
+	hs_ep->isoc_out_drain_tries = 0;
+	return true;
+}
+
+/*
+ * dwc2_gadget_isoc_out_drain_retry - leave a stopped isochronous OUT endpoint
+ * whose drain could not finish open to the next BNA.
+ * @hs_ep: The isochronous OUT endpoint.
+ *
+ * Once the core has written descriptor 0, it raises BNA for the next packet it
+ * holds, and the handler drains on. A descriptor the core never writes back
+ * would turn that into a BNA on every interrupt, so the endpoint is left
+ * unmasked only DWC2_ISOC_OUT_DRAIN_TRIES times in a row; after that it stays
+ * masked until a request is queued or the endpoint is disabled.
+ */
+static void dwc2_gadget_isoc_out_drain_retry(struct dwc2_hsotg_ep *hs_ep)
+{
+	if (!hs_ep->isoc_out_stopped)
+		return;
+	if (hs_ep->isoc_out_drain_tries >= DWC2_ISOC_OUT_DRAIN_TRIES) {
+		dev_warn_ratelimited(hs_ep->parent->dev,
+				     "%s: descriptor 0 not written back, endpoint left stopped\n",
+				     hs_ep->ep.name);
+		return;
+	}
+	hs_ep->isoc_out_drain_tries++;
+	dwc2_hsotg_ctrl_epint(hs_ep->parent, hs_ep->index, 0, 1);
+}
+
+/*
+ * dwc2_gadget_isoc_out_drain - take the packets that a stopped isochronous
+ * OUT endpoint holds into a buffer of the driver's own.
+ * @hs_ep: The isochronous OUT endpoint, disabled after a BNA with no request
+ * to restart it with, and NAKed.
+ * @budget: The time in microseconds the drain may wait in all.
+ *
+ * The packet that met the BNA stays at the head of the Rx FIFO, which all OUT
+ * endpoints share, and so may the ones that arrived before the NAK took
+ * effect. Until the core has written them somewhere, no other OUT packet is
+ * taken from the FIFO: control transfers on EP0 and bulk OUT transfers stall
+ * until a request is queued on this endpoint, which a function that has
+ * stopped streaming may not do for a long time. So point descriptor 0 at a
+ * scratch buffer, let the core write a held packet there as it does for the
+ * request of one, see dwc2_gadget_isoc_out_held_packet(), and drop it, until
+ * the core takes the descriptor no more. No request was there to take them.
+ *
+ * This runs with interrupts off, so it stops waiting after @budget in all,
+ * DWC2_ISOC_OUT_DRAIN_US from the interrupt handler. If packets are left then,
+ * the endpoint stays
+ * marked as after a BNA, and for a stopped endpoint its interrupts are left
+ * unmasked: the core raises BNA again for the packet it holds, and the
+ * handler drains on. If the core took a descriptor but has not written it,
+ * the descriptor stays with the core, see
+ * dwc2_gadget_isoc_out_drain_settled(); the endpoint is left unmasked then
+ * too, so that the BNA of the packet after it drains on once it is written,
+ * see dwc2_gadget_isoc_out_drain_retry().
+ *
+ * Descriptor 0 is host busy again afterwards, so that the completion loop
+ * does not take a packet for a request queued later.
+ */
+static void dwc2_gadget_isoc_out_drain(struct dwc2_hsotg_ep *hs_ep,
+				       unsigned int budget)
+{
+	struct dwc2_hsotg *hsotg = hs_ep->parent;
+	struct dwc2_dma_desc *desc = &hs_ep->desc_list[0];
+	u32 len = min_t(u32, hs_ep->ep.maxpacket, DWC2_ISOC_OUT_DRAIN_SIZE);
+	u32 hbusy = DEV_DMA_BUFF_STS_HBUSY << DEV_DMA_BUFF_STS_SHIFT;
+	unsigned int waited = 0;
+	u32 mask = 0;
+	int ret;
+
+	if (!hs_ep->isoc_out_drain)
+		return;
+	if (!dwc2_gadget_isoc_out_drain_settled(hs_ep)) {
+		dwc2_gadget_isoc_out_drain_retry(hs_ep);
+		return;
+	}
+
+	dwc2_gadget_get_desc_params(hs_ep, &mask);
+	/* A packet may take 110 us: do not start one past the budget. */
+	while (waited + 110 <= budget) {
+		desc->buf = hs_ep->isoc_out_drain_dma;
+		WRITE_ONCE(desc->status, hbusy | DEV_DMA_L |
+			   ((len << DEV_DMA_NBYTES_SHIFT) & mask));
+		dwc2_writel(hsotg, hs_ep->desc_list_dma, DOEPDMA(hs_ep->index));
+		dma_wmb();
+		WRITE_ONCE(desc->status, (desc->status & ~DEV_DMA_BUFF_STS_MASK) |
+			   DEV_DMA_BUFF_STS_HREADY << DEV_DMA_BUFF_STS_SHIFT);
+
+		ret = dwc2_gadget_isoc_out_wait_packet(hs_ep, &waited);
+		if (ret < 0) {
+			hs_ep->isoc_out_drain_busy = 1;
+			dwc2_gadget_isoc_out_drain_retry(hs_ep);
+			return;
+		}
+		WRITE_ONCE(desc->status, hbusy);
+		if (!ret) {
+			hs_ep->isoc_out_bna = 0;
+			return;
+		}
+	}
+
+	if (hs_ep->isoc_out_stopped)
+		dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, 0, 1);
+}
+
+/*
+ * dwc2_gadget_bna_state_reset - forget the BNA state of an endpoint that goes
+ * away.
+ * @hs_ep: The endpoint.
+ *
+ * Descriptor 0 of an isochronous OUT endpoint that a drain left with the core
+ * is taken back as well: after the endpoint is disabled, or the core reset,
+ * it may never read DMA done, and dwc2_gadget_start_isoc_ddma() would wait
+ * for that for good. dwc2_hsotg_disconnect() leaves the state alone, so that
+ * dwc2_hsotg_ep_disable() still drains an endpoint that holds packets.
+ */
+static void dwc2_gadget_bna_state_reset(struct dwc2_hsotg_ep *hs_ep)
+{
+	hs_ep->isoc_out_stopped = 0;
+	hs_ep->isoc_out_bna = 0;
+	hs_ep->isoc_out_restarted = 0;
+	if (hs_ep->isoc_out_drain_busy && hs_ep->desc_list)
+		WRITE_ONCE(hs_ep->desc_list[0].status,
+			   DEV_DMA_BUFF_STS_HBUSY << DEV_DMA_BUFF_STS_SHIFT);
+	hs_ep->isoc_out_drain_busy = 0;
+	hs_ep->isoc_out_drain_tries = 0;
+}
+
 /*
  * dwc2_gadget_start_isoc_ddma - start isochronous transfer in DDMA
  * @hs_ep: The isochronous endpoint.
@@ -982,6 +1290,7 @@ static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep)
 	struct dwc2_hsotg *hsotg = hs_ep->parent;
 	struct dwc2_hsotg_req *hs_req, *treq;
 	int index = hs_ep->index;
+	bool again = false;
 	int ret;
 	int i;
 	u32 dma_reg;
@@ -989,20 +1298,45 @@ static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep)
 	u32 ctrl;
 	struct dwc2_dma_desc *desc;
 
+restart:
 	if (list_empty(&hs_ep->queue)) {
 		hs_ep->target_frame = TARGET_FRAME_INITIAL;
+		/*
+		 * The held packet took the last queued request. The endpoint
+		 * is stopped with nothing to restart it, as after a BNA with
+		 * an empty queue: let the next request queued restart it.
+		 */
+		if (again) {
+			dwc2_gadget_isoc_out_stop(hs_ep);
+			dwc2_gadget_isoc_out_drain(hs_ep, DWC2_ISOC_OUT_DRAIN_US);
+		}
 		dev_dbg(hsotg->dev, "%s: No requests in queue\n", __func__);
 		return;
 	}
 
+	/*
+	 * Descriptor 0 still belongs to the core after a drain that timed
+	 * out. Try again on a later OUT token or BNA interrupt.
+	 */
+	if (!hs_ep->dir_in && !dwc2_gadget_isoc_out_drain_settled(hs_ep)) {
+		hs_ep->target_frame = TARGET_FRAME_INITIAL;
+		return;
+	}
+
 	/* Initialize descriptor chain by Host Busy status */
 	for (i = 0; i < MAX_DMA_DESC_NUM_HS_ISOC; i++) {
 		desc = &hs_ep->desc_list[i];
-		desc->status = 0;
-		desc->status |= (DEV_DMA_BUFF_STS_HBUSY
-				    << DEV_DMA_BUFF_STS_SHIFT);
+		/* One store: a status of 0 would read host ready. */
+		WRITE_ONCE(desc->status,
+			   DEV_DMA_BUFF_STS_HBUSY << DEV_DMA_BUFF_STS_SHIFT);
 	}
 
+	/*
+	 * Descriptor 0 stays host busy until the rest of the chain is written
+	 * and the chain address is set. After a BNA the core may take it the
+	 * moment it is host ready, see dwc2_gadget_isoc_out_held_packet(), and
+	 * must not find it as the last of a chain that is still being built.
+	 */
 	hs_ep->next_desc = 0;
 	list_for_each_entry_safe(hs_req, treq, &hs_ep->queue, queue) {
 		dma_addr_t dma_addr = hs_req->req.dma;
@@ -1012,8 +1346,14 @@ static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep)
 			dma_addr = sg_dma_address(hs_req->req.sg);
 		}
 		ret = dwc2_gadget_fill_isoc_desc(hs_ep, dma_addr,
-						 hs_req->req.length);
-		if (ret)
+						 hs_req->req.length,
+						 !hs_ep->next_desc);
+		/*
+		 * Stop when the chain is full and next_desc has wrapped:
+		 * descriptor 0 is still host busy here, so the next call
+		 * would not see the chain as full and would fill it again.
+		 */
+		if (ret || !hs_ep->next_desc)
 			break;
 	}
 
@@ -1024,6 +1364,32 @@ static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep)
 	/* write descriptor chain address to control register */
 	dwc2_writel(hsotg, hs_ep->desc_list_dma, dma_reg);
 
+	desc = &hs_ep->desc_list[0];
+	dma_wmb();
+	WRITE_ONCE(desc->status, (desc->status & ~DEV_DMA_BUFF_STS_MASK) |
+		   DEV_DMA_BUFF_STS_HREADY << DEV_DMA_BUFF_STS_SHIFT);
+
+	if (!hs_ep->dir_in && hs_ep->isoc_out_bna && !again) {
+		unsigned int count = hs_ep->disable_count;
+
+		if (dwc2_gadget_isoc_out_held_packet(hs_ep)) {
+			/*
+			 * dwc2_hsotg_ep_disable() may have run while the lock
+			 * was dropped for the giveback, and the endpoint may
+			 * have been enabled again since.
+			 */
+			if (hs_ep->disable_count != count)
+				return;
+			again = true;
+			goto restart;
+		}
+	}
+
+	if (!hs_ep->dir_in) {
+		hs_ep->isoc_out_restarted = hs_ep->isoc_out_bna;
+		hs_ep->isoc_out_bna = 0;
+	}
+
 	ctrl = dwc2_readl(hsotg, depctl);
 	ctrl |= DXEPCTL_EPENA | DXEPCTL_CNAK;
 	dwc2_writel(hsotg, ctrl, depctl);
@@ -1485,13 +1851,31 @@ static int dwc2_hsotg_ep_queue(struct usb_ep *ep, struct usb_request *req,
 	if (using_desc_dma(hs) && hs_ep->isochronous) {
 		if (hs_ep->target_frame != TARGET_FRAME_INITIAL) {
 			dma_addr_t dma_addr = hs_req->req.dma;
+			bool hold;
 
 			if (hs_req->req.num_sgs) {
 				WARN_ON(hs_req->req.num_sgs > 1);
 				dma_addr = sg_dma_address(hs_req->req.sg);
 			}
+
+			/*
+			 * After a BNA the core retries descriptor 0 for the
+			 * packet it holds. Until the BNA handler has built
+			 * the chain again, a request queued from a completion
+			 * must not make that descriptor host ready, see
+			 * dwc2_gadget_isoc_out_held_packet().
+			 */
+			hold = !hs_ep->dir_in && !hs_ep->next_desc &&
+			       !(dwc2_readl(hs, DOEPCTL(hs_ep->index)) &
+				 DXEPCTL_EPENA);
 			dwc2_gadget_fill_isoc_desc(hs_ep, dma_addr,
-						   hs_req->req.length);
+						   hs_req->req.length, hold);
+		} else if (hs_ep->isoc_out_stopped) {
+			/*
+			 * A BNA stopped this OUT endpoint with nothing to
+			 * restart it with.
+			 */
+			dwc2_gadget_isoc_out_unstop(hs_ep);
 		}
 		return 0;
 	}
@@ -2214,6 +2598,7 @@ static void dwc2_gadget_complete_isoc_request_ddma(struct dwc2_hsotg_ep *hs_ep)
 	struct dwc2_hsotg *hsotg = hs_ep->parent;
 	struct dwc2_hsotg_req *hs_req;
 	struct usb_request *ureq;
+	unsigned int count = hs_ep->disable_count;
 	u32 desc_sts;
 	u32 mask;
 
@@ -2250,8 +2635,29 @@ static void dwc2_gadget_complete_isoc_request_ddma(struct dwc2_hsotg_ep *hs_ep)
 				DEV_DMA_ISOC_FRNUM_SHIFT;
 		}
 
+		/*
+		 * Mark the descriptor of an OUT endpoint host busy again.
+		 * Left as DMA done, it would be taken for a new completion
+		 * once the ring has wrapped and the loop reached it before
+		 * the descriptor was filled again: a request queued while the
+		 * endpoint is being restarted after a BNA goes to the queue
+		 * only.
+		 */
+		if (!hs_ep->dir_in)
+			WRITE_ONCE(hs_ep->desc_list[hs_ep->compl_desc].status,
+				   DEV_DMA_BUFF_STS_HBUSY <<
+				   DEV_DMA_BUFF_STS_SHIFT);
+
 		dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
 
+		/*
+		 * The lock was dropped for the giveback. If the endpoint was
+		 * disabled meanwhile, and maybe enabled again, the chain this
+		 * loop walks is gone.
+		 */
+		if (hs_ep->disable_count != count)
+			return;
+
 		hs_ep->compl_desc++;
 		if (hs_ep->compl_desc > (MAX_DMA_DESC_NUM_HS_ISOC - 1))
 			hs_ep->compl_desc = 0;
@@ -2260,25 +2666,128 @@ static void dwc2_gadget_complete_isoc_request_ddma(struct dwc2_hsotg_ep *hs_ep)
 }
 
 /*
- * dwc2_gadget_handle_isoc_bna - handle BNA interrupt for ISOC.
- * @hs_ep: The isochronous endpoint.
+ * dwc2_gadget_restart_isoc_out_ddma - build the chain of a disabled ISOC OUT
+ * endpoint again from its queue and enable it.
+ * @hs_ep: The isochronous OUT endpoint, in its initial state.
  *
- * If EP ISOC OUT then need to flush RX FIFO to remove source of BNA
- * interrupt. Reset target frame and next_desc to allow to start
- * ISOC's on NAK interrupt for IN direction or on OUTTKNEPDIS
- * interrupt for OUT direction.
+ * After a BNA the core keeps raising BNA for the endpoint, as fast as the
+ * handler clears it, and no OUTTKNEPDIS comes to restart the chain. So the
+ * chain is restarted here at once.
  */
-static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep)
+static void dwc2_gadget_restart_isoc_out_ddma(struct dwc2_hsotg_ep *hs_ep)
 {
 	struct dwc2_hsotg *hsotg = hs_ep->parent;
 
-	if (!hs_ep->dir_in)
-		dwc2_flush_rx_fifo(hsotg);
-	dwc2_hsotg_complete_request(hsotg, hs_ep, get_ep_head(hs_ep), 0);
+	if (list_empty(&hs_ep->queue) ||
+	    hs_ep->target_frame != TARGET_FRAME_INITIAL ||
+	    dwc2_readl(hsotg, DOEPCTL(hs_ep->index)) & DXEPCTL_EPENA)
+		return;
+
+	hs_ep->target_frame = dwc2_hsotg_read_frameno(hsotg);
+	dwc2_gadget_start_isoc_ddma(hs_ep);
+}
+
+/*
+ * dwc2_gadget_isoc_out_bna_reset - put a descriptor DMA isochronous OUT
+ * endpoint that the core stopped back in its initial state.
+ * @hs_ep: The isochronous OUT endpoint.
+ * @start: Build the chain again from the queue and enable it, or mark the
+ *         endpoint stopped if nothing is queued.
+ *
+ * The state is reset before anything is given back. A completion may queue a
+ * request, and that one must go to the queue only, not to a descriptor of the
+ * chain that has stopped: the core would take descriptor 0 for the packet it
+ * holds, see dwc2_gadget_isoc_out_held_packet().
+ *
+ * Packets that completed before the BNA but whose XferCompl was not yet seen
+ * are given back first, so that the new chain does not reuse their requests.
+ * That is done only while a chain runs: once the state has been reset,
+ * compl_desc no longer points into the chain the core used.
+ */
+static void dwc2_gadget_isoc_out_bna_reset(struct dwc2_hsotg_ep *hs_ep,
+					   bool start)
+{
+	unsigned int count = hs_ep->disable_count;
+	bool running = hs_ep->target_frame != TARGET_FRAME_INITIAL;
 
+	hs_ep->isoc_out_restarted = 0;
 	hs_ep->target_frame = TARGET_FRAME_INITIAL;
+	if (running) {
+		dwc2_gadget_complete_isoc_request_ddma(hs_ep);
+		/* Disabled while the lock was dropped for a giveback. */
+		if (hs_ep->disable_count != count)
+			return;
+	}
 	hs_ep->next_desc = 0;
 	hs_ep->compl_desc = 0;
+	hs_ep->isoc_out_bna = 1;
+
+	if (!start)
+		return;
+	if (list_empty(&hs_ep->queue)) {
+		dwc2_gadget_isoc_out_stop(hs_ep);
+		dwc2_gadget_isoc_out_drain(hs_ep, DWC2_ISOC_OUT_DRAIN_US);
+	} else {
+		dwc2_gadget_restart_isoc_out_ddma(hs_ep);
+	}
+}
+
+/*
+ * dwc2_gadget_handle_isoc_bna - handle BNA interrupt for ISOC.
+ * @hs_ep: The isochronous endpoint.
+ *
+ * Reset target frame and next_desc. For an IN endpoint, give back the request
+ * that met the BNA; the endpoint starts again on the next NAK interrupt.
+ *
+ * An OUT endpoint is restarted here, see dwc2_gadget_restart_isoc_out_ddma(),
+ * and no request is given back: the core holds the packet that met the BNA
+ * and writes it to descriptor 0 of the new chain, which belongs to the
+ * request at the head of the queue, see dwc2_gadget_isoc_out_held_packet().
+ * Giving that request back first would complete it empty, and the packet
+ * would land in the next one. With no request queued the endpoint stays
+ * stopped until one is, see dwc2_gadget_isoc_out_unstop().
+ *
+ * The Rx FIFO is not flushed for an OUT endpoint. It is shared by all OUT
+ * endpoints and the host goes on sending, so a flush here can hit a packet
+ * that is being received, after which the core no longer drains the FIFO.
+ * The packet that met the BNA is not dropped by a flush either: the core
+ * holds it and writes it to the first descriptor of the new chain.
+ */
+static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep)
+{
+	struct dwc2_hsotg *hsotg = hs_ep->parent;
+	bool start = true;
+
+	if (hs_ep->dir_in) {
+		dwc2_hsotg_complete_request(hsotg, hs_ep, get_ep_head(hs_ep),
+					    0);
+		hs_ep->target_frame = TARGET_FRAME_INITIAL;
+		hs_ep->next_desc = 0;
+		hs_ep->compl_desc = 0;
+		return;
+	}
+
+	/*
+	 * The core disables an OUT endpoint that raises BNA and goes on
+	 * raising BNA for it until it is enabled again. So a BNA can be
+	 * latched between the moment the interrupt handler clears DOEPINT and
+	 * the restart, and is then seen with the new chain running. Leave
+	 * that chain alone.
+	 *
+	 * A BNA seen with the endpoint enabled and no restart before it means
+	 * that the core has not cleared EPENA yet. Reset the state as for any
+	 * BNA, but leave the restart to the endpoint-disabled or OUT token
+	 * interrupt that follows once it has.
+	 */
+	if (dwc2_readl(hsotg, DOEPCTL(hs_ep->index)) & DXEPCTL_EPENA) {
+		if (hs_ep->isoc_out_restarted) {
+			hs_ep->isoc_out_restarted = 0;
+			return;
+		}
+		start = false;
+	}
+
+	dwc2_gadget_isoc_out_bna_reset(hs_ep, start);
 }
 
 /**
@@ -2902,6 +3411,27 @@ static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep)
 	if (!hs_ep->isochronous)
 		return;
 
+	/*
+	 * In descriptor DMA the requests of an OUT endpoint sit in the
+	 * descriptor chain rather than one per frame, so the frame by frame
+	 * completion below does not apply. The core disables an isochronous
+	 * OUT endpoint by itself when it meets a descriptor that was not
+	 * filled in time (BNA). Put such an endpoint back in its initial state
+	 * and build the chain again from the queue, as the BNA handler does.
+	 * The loop below would move target_frame off TARGET_FRAME_INITIAL,
+	 * which tells the OUT token handler that a chain runs: the endpoint
+	 * then stays disabled for good, and every request queued again goes
+	 * into a dead chain. If the BNA handler has restarted the endpoint
+	 * already, it is enabled and left alone; if it stopped it for lack of a
+	 * request, it is left stopped.
+	 */
+	if (using_desc_dma(hsotg) && !dir_in) {
+		if (!(dwc2_readl(hsotg, epctl_reg) & DXEPCTL_EPENA) &&
+		    !hs_ep->isoc_out_stopped)
+			dwc2_gadget_isoc_out_bna_reset(hs_ep, true);
+		return;
+	}
+
 	if (list_empty(&hs_ep->queue)) {
 		dev_dbg(hsotg->dev, "%s: complete_ep 0x%p, ep->queue empty!\n",
 			__func__, hs_ep);
@@ -2947,6 +3477,15 @@ static void dwc2_gadget_handle_out_token_ep_disabled(struct dwc2_hsotg_ep *ep)
 			/* Start first ISO Out */
 			ep->target_frame = hsotg->frame_number;
 			dwc2_gadget_start_isoc_ddma(ep);
+		} else if (!(dwc2_readl(hsotg, DOEPCTL(ep->index)) &
+			     DXEPCTL_EPENA)) {
+			/*
+			 * The chain is taken for running, but the endpoint
+			 * is disabled: the core stopped it on a BNA that was
+			 * not handled as one, for example one seen with the
+			 * endpoint still enabled. Restart it as after a BNA.
+			 */
+			dwc2_gadget_isoc_out_bna_reset(ep, true);
 		}
 		return;
 	}
@@ -3091,6 +3630,7 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
 	u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);
 	u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);
 	u32 epsiz_reg = dir_in ? DIEPTSIZ(idx) : DOEPTSIZ(idx);
+	unsigned int count;
 	u32 ints;
 
 	ints = dwc2_gadget_read_ep_interrupts(hsotg, idx, dir_in);
@@ -3107,6 +3647,13 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
 	dev_dbg(hsotg->dev, "%s: ep%d(%s) DxEPINT=0x%08x\n",
 		__func__, idx, dir_in ? "in" : "out", ints);
 
+	/*
+	 * The handlers below may drop the lock to give a request back. If the
+	 * endpoint was disabled meanwhile, the interrupts read above belong to
+	 * an endpoint that is gone.
+	 */
+	count = hs_ep->disable_count;
+
 	/* Don't process XferCompl interrupt if it is a setup packet */
 	if (idx == 0 && (ints & (DXEPINT_SETUP | DXEPINT_SETUP_RCVD)))
 		ints &= ~DXEPINT_XFERCOMPL;
@@ -3149,10 +3696,35 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
 			if (!hs_ep->isochronous || !(ints & DXEPINT_OUTTKNEPDIS))
 				dwc2_hsotg_handle_outdone(hsotg, idx);
 		}
+		if (hs_ep->disable_count != count)
+			return;
+	}
+
+	/*
+	 * Handle BNA of an isochronous OUT endpoint before the
+	 * endpoint-disabled and OUT token interrupts that can come with it.
+	 * Those handlers start a new chain in descriptor DMA mode, and the BNA
+	 * handler must not then reset the endpoint state under it.
+	 */
+	if ((ints & DXEPINT_BNAINTR) && hs_ep->isochronous && !dir_in) {
+		dev_dbg(hsotg->dev, "%s: BNA interrupt\n", __func__);
+		dwc2_gadget_handle_isoc_bna(hs_ep);
+		if (hs_ep->disable_count != count)
+			return;
+	} else if (hs_ep->isochronous && !dir_in) {
+		/*
+		 * A BNA latched before a restart is seen in the next interrupt
+		 * of the endpoint. This one has none, so any BNA from now on
+		 * is a new one.
+		 */
+		hs_ep->isoc_out_restarted = 0;
 	}
 
-	if (ints & DXEPINT_EPDISBLD)
+	if (ints & DXEPINT_EPDISBLD) {
 		dwc2_gadget_handle_ep_disabled(hs_ep);
+		if (hs_ep->disable_count != count)
+			return;
+	}
 
 	if (ints & DXEPINT_OUTTKNEPDIS)
 		dwc2_gadget_handle_out_token_ep_disabled(hs_ep);
@@ -3208,7 +3780,7 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
 	if (ints & DXEPINT_BACK2BACKSETUP)
 		dev_dbg(hsotg->dev, "%s: B2BSetup/INEPNakEff\n", __func__);
 
-	if (ints & DXEPINT_BNAINTR) {
+	if ((ints & DXEPINT_BNAINTR) && (!hs_ep->isochronous || dir_in)) {
 		dev_dbg(hsotg->dev, "%s: BNA interrupt\n", __func__);
 		if (hs_ep->isochronous)
 			dwc2_gadget_handle_isoc_bna(hs_ep);
@@ -3377,14 +3949,22 @@ void dwc2_hsotg_disconnect(struct dwc2_hsotg *hsotg)
 		dwc2_clear_bit(hsotg, GOTGCTL, GOTGCTL_DEVHNPEN);
 	}
 
-	/* all endpoints should be shutdown */
+	/*
+	 * all endpoints should be shutdown. Bump the disable count first, see
+	 * dwc2_hsotg_ep_disable(): a giveback that dropped the lock must not
+	 * go on with an endpoint of a gadget that goes away.
+	 */
 	for (ep = 0; ep < hsotg->num_of_eps; ep++) {
-		if (hsotg->eps_in[ep])
+		if (hsotg->eps_in[ep]) {
+			hsotg->eps_in[ep]->disable_count++;
 			kill_all_requests(hsotg, hsotg->eps_in[ep],
 					  -ESHUTDOWN);
-		if (hsotg->eps_out[ep])
+		}
+		if (hsotg->eps_out[ep]) {
+			hsotg->eps_out[ep]->disable_count++;
 			kill_all_requests(hsotg, hsotg->eps_out[ep],
 					  -ESHUTDOWN);
+		}
 	}
 
 	call_gadget(hsotg, disconnect);
@@ -4161,6 +4741,21 @@ static int dwc2_hsotg_ep_enable(struct usb_ep *ep,
 	else
 		desc_num = MAX_DMA_DESC_NUM_GENERIC;
 
+	/*
+	 * See dwc2_gadget_isoc_out_drain(). Allocated first: the error path
+	 * below frees a descriptor list it finds, which may be one from an
+	 * earlier enable of the endpoint.
+	 */
+	if (using_desc_dma(hsotg) && ep_type == USB_ENDPOINT_XFER_ISOC &&
+	    !dir_in && !hs_ep->isoc_out_drain) {
+		hs_ep->isoc_out_drain =
+			dmam_alloc_coherent(hsotg->dev, DWC2_ISOC_OUT_DRAIN_SIZE,
+					    &hs_ep->isoc_out_drain_dma,
+					    GFP_ATOMIC);
+		if (!hs_ep->isoc_out_drain)
+			return -ENOMEM;
+	}
+
 	/* Allocate DMA descriptor chain for non-ctrl endpoints */
 	if (using_desc_dma(hsotg) && !hs_ep->desc_list) {
 		hs_ep->desc_list = dmam_alloc_coherent(hsotg->dev,
@@ -4202,6 +4797,7 @@ static int dwc2_hsotg_ep_enable(struct usb_ep *ep,
 		hs_ep->target_frame = TARGET_FRAME_INITIAL;
 		hs_ep->next_desc = 0;
 		hs_ep->compl_desc = 0;
+		dwc2_gadget_bna_state_reset(hs_ep);
 		if (dir_in) {
 			hs_ep->periodic = 1;
 			mask = dwc2_readl(hsotg, DIEPMSK);
@@ -4348,6 +4944,25 @@ static int dwc2_hsotg_ep_disable(struct usb_ep *ep)
 
 	ctrl = dwc2_readl(hsotg, epctrl_reg);
 
+	/*
+	 * An isochronous OUT endpoint disabled by a BNA may still hold packets
+	 * at the head of the Rx FIFO, which EP0 shares, see
+	 * dwc2_gadget_isoc_out_drain(). Once the endpoint is gone no BNA comes
+	 * to drain on, so give the drain more time here. A Rx FIFO flush does
+	 * not help: the core holds the packet for a DMA write that waits for
+	 * a descriptor, and the flush waits for the AHB master to go idle.
+	 */
+	if (using_desc_dma(hsotg) && hs_ep->isochronous && !dir_in &&
+	    hs_ep->isoc_out_bna && !(ctrl & DXEPCTL_EPENA)) {
+		dwc2_writel(hsotg, ctrl | DXEPCTL_SNAK, epctrl_reg);
+		dwc2_gadget_isoc_out_drain(hs_ep,
+					   DWC2_ISOC_OUT_DRAIN_DISABLE_US);
+		if (hs_ep->isoc_out_bna)
+			dev_warn(hsotg->dev,
+				 "%s: packets left in the Rx FIFO at disable\n",
+				 hs_ep->ep.name);
+	}
+
 	if (ctrl & DXEPCTL_EPENA)
 		dwc2_hsotg_ep_stop_xfr(hsotg, hs_ep);
 
@@ -4361,6 +4976,15 @@ static int dwc2_hsotg_ep_disable(struct usb_ep *ep)
 	/* disable endpoint interrupts */
 	dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, hs_ep->dir_in, 0);
 
+	/*
+	 * A request queued from a completion below must not restart the
+	 * endpoint or go into its descriptor chain. The count tells a
+	 * giveback that dropped the lock that the endpoint went away.
+	 */
+	dwc2_gadget_bna_state_reset(hs_ep);
+	hs_ep->target_frame = TARGET_FRAME_INITIAL;
+	hs_ep->disable_count++;
+
 	/* terminate all requests with shutdown */
 	kill_all_requests(hsotg, hs_ep, -ESHUTDOWN);
 
-- 
2.56.1.windows.1


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* [PATCH v4 2/2] usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN endpoints after BNA
  2026-12-05 13:02 [PATCH v4 0/2] usb: dwc2: gadget: descriptor DMA fixes for BNA, found on Sophgo SG2002 Vadim Yuzifovich
  2026-12-05 13:02 ` [PATCH v4 1/2] usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA Vadim Yuzifovich
@ 2026-12-05 13:02 ` Vadim Yuzifovich
  2026-12-05 13:31   ` sashiko-bot
  1 sibling, 1 reply; 5+ messages in thread
From: Vadim Yuzifovich @ 2026-12-05 13:02 UTC (permalink / raw)
  To: Thinh.Nguyen, gregkh
  Cc: linux-usb, linux-kernel, chenyou910331, inochiama, sophgo

In descriptor DMA mode the core raises BNA and disables an endpoint when
the descriptor it fetches is not marked host ready. For isochronous
endpoints dwc2 handles that; for bulk and interrupt endpoints it only
logs the interrupt at debug level. Nothing was transferred and no
XferCompl follows, so the request stays current, the requests queued
behind it never start, and the function driver waits for a completion
that never comes.

On a Sophgo SG2002 (DWC_otg 4.20a) with a video pipeline loading the
DRAM this happened every minute or two to the bulk IN endpoint of
f_mass_storage: debugfs showed the endpoint disabled with an 18-byte
REQUEST SENSE reply current and nothing done, the 13-byte CSW queued
behind it, and f_mass_storage asleep waiting for its buffer. The host's
command timed out after 30 s and it reset the port. Read in the BNA
handler, the descriptor is 0x0e000012: host ready, last, short,
interrupt on completion, 18 bytes. The chain is written completely
before the endpoint is enabled, so the core fetched the descriptor
before the CPU's stores to it reached memory. On this SoC that window can
be closed separately, by reading the descriptor back before the endpoint
is enabled, but a BNA on such an endpoint should not leave it dead on
any platform.

When a bulk or interrupt IN endpoint other than EP0 raises BNA, is
disabled and not halted, start its current request again, which fills
the descriptor anew. Start it from what has been transferred of it, the
way the next part of a request longer than one chain is started, so that
a BNA on a later part does not send the start of the buffer again. A
scatter-gather request is only started again from its beginning, since
its chain is always built from the first entry of the list. Report a
restart with a rate limited warning, since unlike on an isochronous
endpoint it is not expected. A BNA that leaves a request current on a
disabled endpoint and is not restarted is reported with a rate limited
warning as well, since the endpoint stays stopped until the request is
dequeued; any other BNA stays at debug level, as before.

If the endpoint still reads enabled when the BNA is handled, as on a
core that clears EPENA only after raising BNA, set SNAK and EPDIS, so
that an endpoint-disabled interrupt is sure to come, and restart from
that.

Restart a request at most three times between its start and an
XferCompl. A BNA that comes back after that points at something a
restart does not fix, such as a descriptor the core cannot read, and
restarting on would keep the CPU in the interrupt handler. Report it as
an error and leave the endpoint as before this patch.

Do this only while the first descriptor of the chain still reads host
ready. If the core has taken it, a part of the chain has been
transferred that req.actual does not include yet, and starting again
would transfer that part twice. Such a BNA is only reported, and so is a
BNA on an OUT endpoint: after a BNA an isochronous OUT endpoint holds
the packet it has acknowledged and writes it to the first descriptor as
soon as that is host ready (see "usb: dwc2: gadget: restart descriptor
DMA isochronous OUT endpoints after BNA"). If a bulk OUT
endpoint does the same, filling that descriptor anew would race with the
write and could lose the packet. All the BNAs seen here that a restart
recovered were on bulk IN.

In the BNAs seen here the endpoint was disabled already when the BNA was
handled, and no endpoint-disabled interrupt followed. As a precaution,
an endpoint-disabled interrupt that comes after the restart does not
flush the TxFIFO of the endpoint, which then holds the data of the
restarted request. The restart marks the endpoint for that only when an
endpoint-disabled interrupt for the BNA is latched and not handled yet.
Only the endpoint-disabled handler and the reset paths clear the mark,
not an XferCompl or the start of the next request in the same
interrupt, which would let the flush hit the request started after the
restarted one. The TxFIFO of a halted or stalled endpoint is always
flushed, so that a halt set and cleared by the host still gets the
flush.

BNA interrupts of IN endpoints are only enabled since commit
37981e00503f ("usb: dwc2: Enable BNA interrupt for IN endpoints"). The
commit in the Fixes tag is the one that started these endpoints in
descriptor DMA mode without handling a BNA.

Fixes: aa3e8bc81311 ("usb: dwc2: gadget: DDMA transfer start and complete")
Signed-off-by: Vadim Yuzifovich <vadim@yuzi.co>
---
 drivers/usb/dwc2/core.h   |  10 +++
 drivers/usb/dwc2/gadget.c | 151 +++++++++++++++++++++++++++++++++++++-
 2 files changed, 157 insertions(+), 4 deletions(-)

diff --git a/drivers/usb/dwc2/core.h b/drivers/usb/dwc2/core.h
index d7bed6c98ec2..9c35b6f76348 100644
--- a/drivers/usb/dwc2/core.h
+++ b/drivers/usb/dwc2/core.h
@@ -128,6 +128,13 @@ struct dwc2_hsotg_req;
  * @isoc_out_drain: Buffer for a descriptor DMA isochronous OUT endpoint to
  *                  take a packet into that no request is queued for.
  * @isoc_out_drain_dma: The DMA address of @isoc_out_drain.
+ * @bna_restarts: Restarts of the current request of a bulk or interrupt IN
+ *                endpoint after a BNA in descriptor DMA mode.
+ * @bna_pending: A BNA of a bulk or interrupt IN endpoint was seen with the
+ *               endpoint still enabled; it is restarted on the endpoint
+ *               disabled interrupt.
+ * @bna_restarted: A bulk or interrupt IN endpoint was restarted after a BNA;
+ *                 its TxFIFO holds the data of the restarted request.
  * @frame_overrun: Indicates SOF number overrun in DSTS
  *
  * This is the driver's state for each registered endpoint, allowing it
@@ -173,6 +180,9 @@ struct dwc2_hsotg_ep {
 	unsigned int            isoc_out_drain_busy:1;
 	unsigned int            isoc_out_drain_tries:3;
 	unsigned int            disable_count;
+	u8                      bna_restarts;
+	unsigned int            bna_pending:1;
+	unsigned int            bna_restarted:1;
 	unsigned int            target_frame;
 #define TARGET_FRAME_INITIAL   0xFFFFFFFF
 	bool			frame_overrun;
diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c
index fdbc9677aef2..bd2e4f397f3c 100644
--- a/drivers/usb/dwc2/gadget.c
+++ b/drivers/usb/dwc2/gadget.c
@@ -1276,6 +1276,8 @@ static void dwc2_gadget_bna_state_reset(struct dwc2_hsotg_ep *hs_ep)
 			   DEV_DMA_BUFF_STS_HBUSY << DEV_DMA_BUFF_STS_SHIFT);
 	hs_ep->isoc_out_drain_busy = 0;
 	hs_ep->isoc_out_drain_tries = 0;
+	hs_ep->bna_pending = 0;
+	hs_ep->bna_restarted = 0;
 }
 
 /*
@@ -1441,6 +1443,12 @@ static void dwc2_hsotg_start_req(struct dwc2_hsotg *hsotg,
 		}
 	}
 
+	/* See dwc2_gadget_handle_nonisoc_bna() */
+	if (!continuing) {
+		hs_ep->bna_restarts = 0;
+		hs_ep->bna_pending = 0;
+	}
+
 	dma_reg = dir_in ? DIEPDMA(index) : DOEPDMA(index);
 	epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
 	epsize_reg = dir_in ? DIEPTSIZ(index) : DOEPTSIZ(index);
@@ -2790,6 +2798,111 @@ static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep)
 	dwc2_gadget_isoc_out_bna_reset(hs_ep, start);
 }
 
+#define DWC2_BNA_RESTARTS	3
+
+/*
+ * dwc2_gadget_handle_nonisoc_bna - handle BNA interrupt for bulk and
+ * interrupt endpoints in descriptor DMA mode.
+ * @hs_ep: The endpoint, not EP0 and not isochronous.
+ * @ints: The endpoint interrupts that came with the BNA, for the log.
+ *
+ * The core raises BNA and disables the endpoint when the descriptor it
+ * fetches is not marked host ready. The chain of a bulk or interrupt
+ * endpoint is complete before the endpoint is enabled, and afterwards the
+ * descriptor reads host ready, so the core read it before the CPU's writes
+ * to it reached memory. Nothing was transferred and no XferCompl
+ * follows: the request stays current, the ones queued behind it never
+ * start, and the function waits until the host gives up and resets the
+ * port. Start the request again from what has been transferred of it, as
+ * for the next part of a request longer than one chain; that fills the
+ * descriptor anew.
+ *
+ * This is done only while the first descriptor of the chain is still host
+ * ready. If the core has taken it, a part of the chain has been transferred
+ * that the request does not account for yet, and starting again would
+ * transfer that part twice. A scatter-gather request is only started again
+ * from its beginning: dwc2_gadget_config_nonisoc_xfer_ddma() builds its chain
+ * from the first entry of the list.
+ *
+ * It is done for IN endpoints only. An OUT endpoint that raised BNA may hold
+ * a packet it has acknowledged already and write it to the first descriptor
+ * as soon as that is host ready, as an isochronous OUT endpoint does, see
+ * dwc2_gadget_isoc_out_held_packet(). Filling the descriptor anew could then
+ * race with that write and lose the packet. A BNA on an OUT endpoint is only
+ * reported.
+ *
+ * A BNA seen while the endpoint is still enabled disables the endpoint, and
+ * the restart runs from the endpoint-disabled interrupt that this is sure to
+ * bring. A BNA that leaves a request
+ * current and is not restarted is reported as a warning: the endpoint stays
+ * stopped until the request is dequeued.
+ *
+ * A request is started again at most DWC2_BNA_RESTARTS times, counted from
+ * its start or its last XferCompl. A BNA that keeps coming back points at
+ * something a restart does not fix, and restarting on would keep the CPU in
+ * the interrupt handler.
+ */
+static void dwc2_gadget_handle_nonisoc_bna(struct dwc2_hsotg_ep *hs_ep,
+					   u32 ints)
+{
+	struct dwc2_hsotg *hsotg = hs_ep->parent;
+	struct dwc2_hsotg_req *hs_req = hs_ep->req;
+	u32 epctl_reg = hs_ep->dir_in ? DIEPCTL(hs_ep->index) :
+					DOEPCTL(hs_ep->index);
+	u32 epctl = dwc2_readl(hsotg, epctl_reg);
+	u32 status = hs_ep->desc_list ? READ_ONCE(hs_ep->desc_list[0].status) : 0;
+	/* A request is current, and nothing else will move the endpoint on. */
+	bool stuck = hs_req && !hs_ep->halted &&
+		     !(epctl & (DXEPCTL_EPENA | DXEPCTL_STALL));
+	bool restart = stuck && hs_ep->dir_in && hs_ep->desc_list &&
+		       (!hs_req->req.num_sgs || !hs_req->req.actual) &&
+		       status >> DEV_DMA_BUFF_STS_SHIFT == DEV_DMA_BUFF_STS_HREADY;
+
+	/*
+	 * Not disabled yet. Disable it, so that an endpoint-disabled
+	 * interrupt is sure to come, and restart from there, see
+	 * dwc2_gadget_handle_ep_disabled().
+	 */
+	if (hs_ep->dir_in && hs_req && !hs_ep->halted &&
+	    (epctl & DXEPCTL_EPENA)) {
+		hs_ep->bna_pending = 1;
+		dwc2_writel(hsotg, epctl | DXEPCTL_SNAK | DXEPCTL_EPDIS,
+			    epctl_reg);
+		return;
+	}
+
+	if (!restart) {
+		if (stuck)
+			dev_warn_ratelimited(hsotg->dev,
+					     "%s: BNA, DxEPINT %08x DxEPCTL %08x descriptor %08x, not restarted, endpoint stopped\n",
+					     hs_ep->name, ints, epctl, status);
+		else
+			dev_dbg(hsotg->dev,
+				"%s: BNA, DxEPINT %08x DxEPCTL %08x descriptor %08x\n",
+				hs_ep->name, ints, epctl, status);
+		return;
+	}
+
+	if (hs_ep->bna_restarts >= DWC2_BNA_RESTARTS) {
+		dev_err_ratelimited(hsotg->dev,
+				    "%s: BNA after %u restarts, descriptor %08x, not restarted\n",
+				    hs_ep->name, hs_ep->bna_restarts, status);
+		return;
+	}
+	hs_ep->bna_restarts++;
+	/*
+	 * An endpoint-disabled interrupt latched for this BNA and not handled
+	 * yet must not flush the data of the restarted request.
+	 */
+	hs_ep->bna_restarted = !(ints & DXEPINT_EPDISBLD) &&
+		(dwc2_readl(hsotg, DIEPINT(hs_ep->index)) & DXEPINT_EPDISBLD);
+
+	dev_warn_ratelimited(hsotg->dev,
+			     "%s: BNA, DxEPINT %08x DxEPCTL %08x descriptor %08x, request restarted\n",
+			     hs_ep->name, ints, epctl, status);
+	dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
+}
+
 /**
  * dwc2_hsotg_rx_data - receive data from the FIFO for an endpoint
  * @hsotg: The device state.
@@ -3392,7 +3505,15 @@ static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep)
 	if (dir_in) {
 		int epctl = dwc2_readl(hsotg, epctl_reg);
 
-		dwc2_hsotg_txfifo_flush(hsotg, hs_ep->fifo_index);
+		/*
+		 * A bulk or interrupt endpoint restarted after a BNA, see
+		 * dwc2_gadget_handle_nonisoc_bna(), has the data of the
+		 * restarted request in its TxFIFO already.
+		 */
+		if (!hs_ep->bna_restarted || hs_ep->halted ||
+		    (epctl & DXEPCTL_STALL))
+			dwc2_hsotg_txfifo_flush(hsotg, hs_ep->fifo_index);
+		hs_ep->bna_restarted = 0;
 
 		if ((epctl & DXEPCTL_STALL) && (epctl & DXEPCTL_EPTYPE_BULK)) {
 			int dctl = dwc2_readl(hsotg, DCTL);
@@ -3408,6 +3529,12 @@ static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep)
 		}
 	}
 
+	/* See dwc2_gadget_handle_nonisoc_bna() */
+	if (hs_ep->bna_pending) {
+		hs_ep->bna_pending = 0;
+		dwc2_gadget_handle_nonisoc_bna(hs_ep, DXEPINT_EPDISBLD);
+	}
+
 	if (!hs_ep->isochronous)
 		return;
 
@@ -3674,6 +3801,14 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
 			__func__, dwc2_readl(hsotg, epctl_reg),
 			dwc2_readl(hsotg, epsiz_reg));
 
+		/*
+		 * See dwc2_gadget_handle_nonisoc_bna(). bna_restarted is left
+		 * to the endpoint-disabled handler below, which may still have
+		 * an interrupt of the BNA to handle.
+		 */
+		hs_ep->bna_restarts = 0;
+		hs_ep->bna_pending = 0;
+
 		/* In DDMA handle isochronous requests separately */
 		if (using_desc_dma(hsotg) && hs_ep->isochronous) {
 			dwc2_gadget_complete_isoc_request_ddma(hs_ep);
@@ -3780,12 +3915,20 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
 	if (ints & DXEPINT_BACK2BACKSETUP)
 		dev_dbg(hsotg->dev, "%s: B2BSetup/INEPNakEff\n", __func__);
 
-	if ((ints & DXEPINT_BNAINTR) && (!hs_ep->isochronous || dir_in)) {
+	if ((ints & DXEPINT_BNAINTR) && hs_ep->isochronous && dir_in) {
 		dev_dbg(hsotg->dev, "%s: BNA interrupt\n", __func__);
-		if (hs_ep->isochronous)
-			dwc2_gadget_handle_isoc_bna(hs_ep);
+		dwc2_gadget_handle_isoc_bna(hs_ep);
 	}
 
+	/*
+	 * A bulk or interrupt endpoint is restarted here, after the
+	 * endpoint-disabled handler above has flushed the TxFIFO of an IN
+	 * endpoint.
+	 */
+	if ((ints & DXEPINT_BNAINTR) && !hs_ep->isochronous &&
+	    using_desc_dma(hsotg) && idx)
+		dwc2_gadget_handle_nonisoc_bna(hs_ep, ints);
+
 	if (dir_in && !hs_ep->isochronous) {
 		/* not sure if this is important, but we'll clear it anyway */
 		if (ints & DXEPINT_INTKNTXFEMP) {
-- 
2.56.1.windows.1


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* Re: [PATCH v4 1/2] usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA
  2026-12-05 13:02 ` [PATCH v4 1/2] usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA Vadim Yuzifovich
@ 2026-12-05 13:31   ` sashiko-bot
  0 siblings, 0 replies; 5+ messages in thread
From: sashiko-bot @ 2026-12-05 13:31 UTC (permalink / raw)
  To: Vadim Yuzifovich; +Cc: linux-usb

Thank you for your contribution! Sashiko AI review found 12 potential
issues to consider:
- [High] usb: dwc2: unbounded BNA IRQ storm when queuing with
  isoc_out_drain_busy
- [High] usb: dwc2: ep_disable() skips Rx FIFO drain before isoc_out_bna
  is set
- [Medium] usb: dwc2: dwc2_gadget_isoc_out_drain() ignores budget when
  desc 0 busy
- [Medium] usb: dwc2: drain budget exit leaves stopped isoc OUT endpoint
  unmasked
- [Medium] usb: dwc2: missing EPENA check in
  dwc2_gadget_handle_out_token_ep_disabled()
- [Medium] usb: dwc2: dwc2_gadget_start_isoc_ddma() marks desc 1..N-1
  ready before DOEPDMA
- [Medium] usb: dwc2: dma_wmb() does not flush posted DOEPDMA write
  before HREADY/udelay
- [Medium] usb: dwc2: dwc2_gadget_start_isoc_ddma() exposes desc 1..N-1
  before restart
- [Medium] usb: dwc2: missing write barrier before polling desc->status
  after HREADY
- [Medium] usb: dwc2: gadget: race between DXEPCTL_SNAK and in-flight
  ISOC OUT drain
- [Medium] usb: dwc2: dwc2_gadget_isoc_out_drain() budget ignores fast
  DMA completions
- [Low] usb: dwc2: trailing udelay(1) in
  dwc2_gadget_isoc_out_wait_packet()
--

commit 80d6fd01c9d63259ec27d838061a3b843634e06e
Author: Vadim Yuzifovich <vadim@yuzi.co>

usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA

This commit restarts descriptor DMA isochronous OUT endpoints directly from
the BNA and endpoint-disabled handlers instead of flushing the Rx FIFO,
waits for any held packet to land on descriptor 0, and drains held packets
into a scratch buffer when no requests are queued or when the endpoint is
disabled.

> diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c
> index 7ef704568e090..fdbc9677aef29 100644
> --- a/drivers/usb/dwc2/gadget.c
> +++ b/drivers/usb/dwc2/gadget.c
> @@ -218,6 +218,53 @@ static void dwc2_hsotg_ctrl_epint(struct dwc2_hsotg *hsotg,
>  	local_irq_restore(flags);
>  }
>  
> +static void dwc2_gadget_isoc_out_stop(struct dwc2_hsotg_ep *hs_ep)
> +{
> +	struct dwc2_hsotg *hsotg = hs_ep->parent;
> +	u32 epctl_reg = DOEPCTL(hs_ep->index);
> +
> +	hs_ep->isoc_out_stopped = 1;
> +	dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, 0, 0);
> +	dwc2_writel(hsotg, dwc2_readl(hsotg, epctl_reg) | DXEPCTL_SNAK,
> +		    epctl_reg);
> +}

[Severity: Medium]
Can setting DXEPCTL_SNAK without waiting for an in-flight OUT packet to
finish arriving leave a late packet stuck in the Rx FIFO?

Unlike dwc2_hsotg_ep_stop_xfr(), both dwc2_gadget_isoc_out_stop() and
dwc2_hsotg_ep_disable() only write DXEPCTL_SNAK and immediately call
dwc2_gadget_isoc_out_drain().  Setting SNAK rejects future OUT tokens, but
a packet already on the wire (up to ~17 us at High-Speed or ~682 us at
Full-Speed) does not become visible in the Rx FIFO until EOP.

If the 10 us probe in dwc2_gadget_isoc_out_drain() finishes first, it
clears isoc_out_bna and returns with the endpoint masked.  The late packet
then sits stuck at the head of the shared Rx FIFO, stalling EP0 and other
OUT endpoints, and dwc2_hsotg_ep_disable() will skip draining it because
isoc_out_bna is already 0.  Asserting DCTL_SGOUTNAK and waiting for
GINTSTS_GOUTNAKEFF before draining would ensure any in-flight packet has
landed first.

[ ... ]

> +static int dwc2_gadget_isoc_out_wait_packet(struct dwc2_hsotg_ep *hs_ep,
> +					    unsigned int *waited)
> +{
> +	struct dwc2_dma_desc *desc = &hs_ep->desc_list[0];
> +	int i;
> +
> +	for (i = 0; i < 10; i++) {
> +		if (READ_ONCE(desc->status) >> DEV_DMA_BUFF_STS_SHIFT !=
> +		    DEV_DMA_BUFF_STS_HREADY)
> +			break;
> +		udelay(1);
> +	}
> +	*waited += i;
> +	if (i == 10)
> +		return 0;
> +
> +	for (i = 0; i < 100; i++) {
> +		if (READ_ONCE(desc->status) >> DEV_DMA_BUFF_STS_SHIFT ==
> +		    DEV_DMA_BUFF_STS_DMADONE)
> +			break;
> +		udelay(1);
> +	}
> +	*waited += i;
> +	if (i < 100)
> +		return 1;
> +
> +	dev_warn_ratelimited(hs_ep->parent->dev,
> +			     "%s: held packet not written in 100 us\n",
> +			     hs_ep->ep.name);
> +	return -ETIMEDOUT;
> +}

[Severity: Low]
Should both polling loops re-check desc->status after the final udelay(1)?

On the last iteration each loop sleeps 1 us without checking whether
desc->status changed during that microsecond.  In the first loop, if the
core claims descriptor 0 during that trailing delay, returning 0 causes
dwc2_gadget_isoc_out_drain() to overwrite desc->status with HBUSY and clear
isoc_out_bna while DMA owns it; in the second loop, a packet completing in
the 100th microsecond is misreported as -ETIMEDOUT.  Using
read_poll_timeout_atomic() or checking desc->status once more after each
loop avoids the unchecked window.

[ ... ]

> +static void dwc2_gadget_isoc_out_drain(struct dwc2_hsotg_ep *hs_ep,
> +				       unsigned int budget)
> +{
> +	struct dwc2_hsotg *hsotg = hs_ep->parent;
> +	struct dwc2_dma_desc *desc = &hs_ep->desc_list[0];
> +	u32 len = min_t(u32, hs_ep->ep.maxpacket, DWC2_ISOC_OUT_DRAIN_SIZE);
> +	u32 hbusy = DEV_DMA_BUFF_STS_HBUSY << DEV_DMA_BUFF_STS_SHIFT;
> +	unsigned int waited = 0;
> +	u32 mask = 0;
> +	int ret;
> +
> +	if (!hs_ep->isoc_out_drain)
> +		return;
> +	if (!dwc2_gadget_isoc_out_drain_settled(hs_ep)) {
> +		dwc2_gadget_isoc_out_drain_retry(hs_ep);
> +		return;
> +	}

[Severity: Medium]
Does dwc2_gadget_isoc_out_drain() abandon the caller's budget too early
when descriptor 0 is already busy or a packet times out?

dwc2_gadget_isoc_out_drain_settled() does a single non-waiting read of
desc->status, so if isoc_out_drain_busy is already set,
dwc2_gadget_isoc_out_drain() returns after 0 us even when
dwc2_hsotg_ep_disable() passes the 2000 us DWC2_ISOC_OUT_DRAIN_DISABLE_US
budget.  A single 100 us timeout from dwc2_gadget_isoc_out_wait_packet()
below also returns immediately without using the remaining disable budget.

During dwc2_hsotg_ep_disable(), dwc2_gadget_isoc_out_drain_retry() then
needlessly unmasks DAINTMSK right before disable masks it again, and
dwc2_gadget_bna_state_reset() overwrites desc_list[0].status with HBUSY
while hardware DMA may still own descriptor 0 and packets remain stuck in
the Rx FIFO.

> +	dwc2_gadget_get_desc_params(hs_ep, &mask);
> +	/* A packet may take 110 us: do not start one past the budget. */
> +	while (waited + 110 <= budget) {
> +		desc->buf = hs_ep->isoc_out_drain_dma;
> +		WRITE_ONCE(desc->status, hbusy | DEV_DMA_L |
> +			   ((len << DEV_DMA_NBYTES_SHIFT) & mask));
> +		dwc2_writel(hsotg, hs_ep->desc_list_dma, DOEPDMA(hs_ep->index));
> +		dma_wmb();
> +		WRITE_ONCE(desc->status, (desc->status & ~DEV_DMA_BUFF_STS_MASK) |
> +			   DEV_DMA_BUFF_STS_HREADY << DEV_DMA_BUFF_STS_SHIFT);

[Severity: Medium]
Is dma_wmb() sufficient to flush the posted write to DOEPDMA before
descriptor 0 is marked HREADY and the 10 us wait begins?

dma_wmb() provides no ordering guarantees for MMIO writes (for example on
arm64, arm, or PCI/x86), and writeX() is not ordered before a subsequent
udelay() loop.  The same pattern appears in dwc2_gadget_start_isoc_ddma().

If the posted DOEPDMA write has not reached the controller before the 10 us
poll runs, the core will not claim descriptor 0 in time, causing
dwc2_gadget_isoc_out_drain() to clear isoc_out_bna with a packet still
stuck in the Rx FIFO, or dwc2_gadget_start_isoc_ddma() to enable the chain
with a held packet pending.  Reading back DOEPDMA with dwc2_readl() before
marking descriptor 0 HREADY flushes the posted write.

> +		ret = dwc2_gadget_isoc_out_wait_packet(hs_ep, &waited);

[Severity: Medium]
Can fast DMA completions allow dwc2_gadget_isoc_out_drain() to spin past
its 200 us hardirq budget?

dwc2_gadget_isoc_out_wait_packet() only adds its udelay(1) loop counts to
*waited, so any packet that completes before the first udelay(1) adds 0 us,
ignoring coherent descriptor accesses, MMIO writes, and barriers.  With a
default 2048-DWORD Rx FIFO able to buffer hundreds of short or zero-length
packets, draining a backlog of fast-completing packets can spin with
hsotg->lock held and interrupts disabled into the millisecond range.
Bounding the loop with a ktime_get() deadline would enforce the intended
budget.

[ ... ]

> +	if (hs_ep->isoc_out_stopped)
> +		dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, 0, 1);
> +}

[Severity: Medium]
Can unmasking the stopped endpoint on budget exit leave it permanently
unmasked if the last held packet was just drained?

If draining the last held packet takes more than 90 us, the loop exits with
waited + 110 > budget without seeing ret == 0, leaving isoc_out_bna set and
unmasking DAINTMSK without any retry cap.  Because no held packet remains,
the core raises OUTTKNEPDIS on every subsequent host ISOC OUT token instead
of BNA.

dwc2_gadget_handle_out_token_ep_disabled() then calls
dwc2_gadget_start_isoc_ddma(), which sees an empty queue with again == false
and returns without re-masking DAINTMSK or clearing isoc_out_bna, leaving
the endpoint taking continuous OUTTKNEPDIS hardirqs until a request is
queued or the endpoint is disabled.

[ ... ]

>  static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep)
>  {
> [ ... ]
> +	/*
> +	 * Descriptor 0 still belongs to the core after a drain that timed
> +	 * out. Try again on a later OUT token or BNA interrupt.
> +	 */
> +	if (!hs_ep->dir_in && !dwc2_gadget_isoc_out_drain_settled(hs_ep)) {
> +		hs_ep->target_frame = TARGET_FRAME_INITIAL;
> +		return;
> +	}

[Severity: High]
Can queuing a request while isoc_out_drain_busy is set trigger an unbounded
BNA interrupt storm?

When a drain times out and exhausts DWC2_ISOC_OUT_DRAIN_TRIES, the endpoint
is left stopped with interrupts masked.  If the function driver later
queues a request, dwc2_hsotg_ep_queue() calls dwc2_gadget_isoc_out_unstop(),
which clears isoc_out_stopped and unmasks DAINTMSK even though
isoc_out_drain_busy is still set.

On the next BNA, dwc2_gadget_isoc_out_bna_reset() sees a non-empty queue
and calls dwc2_gadget_restart_isoc_out_ddma() ->
dwc2_gadget_start_isoc_ddma(), which hits this early return without
re-masking interrupts or checking isoc_out_drain_tries.  Because the
endpoint stays disabled and unmasked while the core holds a packet, BNA
fires as fast as dwc2_hsotg_epint() clears DOEPINT, starving the CPU and
bypassing the DWC2_ISOC_OUT_DRAIN_TRIES safeguard.

[ ... ]

>  		ret = dwc2_gadget_fill_isoc_desc(hs_ep, dma_addr,
> -						 hs_req->req.length);
> -		if (ret)
> +						 hs_req->req.length,
> +						 !hs_ep->next_desc);
> +		/*
> +		 * Stop when the chain is full and next_desc has wrapped:
> +		 * descriptor 0 is still host busy here, so the next call
> +		 * would not see the chain as full and would fill it again.
> +		 */
> +		if (ret || !hs_ep->next_desc)
>  			break;
>  	}

[Severity: Medium]
Can marking descriptors 1..N-1 host ready before resetting DOEPDMA let the
core claim a descriptor other than descriptor 0 for the held packet?

Only descriptor 0 is held HBUSY in this loop; descriptors 1..N-1 are marked
HREADY before DOEPDMA is written with hs_ep->desc_list_dma.  If a prior BNA
stopped at descriptor k >= 1 (for instance after the 100 us held-packet
timeout fallback where descriptor 0 has L cleared, or during the window in
dwc2_gadget_fill_isoc_desc() between clearing L on descriptor k - 1 and
marking descriptor k HREADY), the polling DMA engine can claim descriptor k
while the next iteration clears DEV_DMA_L on it via a non-atomic
read-modify-write.

The held packet then lands in request k instead of request 0, races with
the L-bit clear, and is missed when dwc2_gadget_isoc_out_held_packet()
polls descriptor 0.  Writing and flushing DOEPDMA after the HBUSY
initialization loop and before filling descriptors 1..N-1 avoids this
window.

>  	hs_ep->compl_desc = 0;
>  	depctl = hs_ep->dir_in ? DIEPCTL(index) : DOEPCTL(index);
>  	dma_reg = hs_ep->dir_in ? DIEPDMA(index) : DOEPDMA(index);
>  
>  	/* write descriptor chain address to control register */
>  	dwc2_writel(hsotg, hs_ep->desc_list_dma, dma_reg);
>  
> +	desc = &hs_ep->desc_list[0];
> +	dma_wmb();
> +	WRITE_ONCE(desc->status, (desc->status & ~DEV_DMA_BUFF_STS_MASK) |
> +		   DEV_DMA_BUFF_STS_HREADY << DEV_DMA_BUFF_STS_SHIFT);

[Severity: Medium]
Is a write barrier needed after marking descriptor 0 HREADY before polling
desc->status in dwc2_gadget_isoc_out_wait_packet()?

Both here and in dwc2_gadget_isoc_out_drain(), dma_wmb() precedes the
HREADY store to coherent DMA memory, but no wmb()/mb() or MMIO write
follows it before the 10 us udelay(1) polling loop.  On platforms with
write-combining coherent DMA memory or outer cache store buffers (such as
ARMv7 with PL310, arm64, RISC-V, or MIPS), the HREADY store can remain
buffered while the CPU polls.

If dwc2_gadget_isoc_out_wait_packet() falsely returns 0 as a result,
dwc2_gadget_start_isoc_ddma() enables the chain with a held packet pending
(reintroducing per-packet BNAs), and dwc2_gadget_isoc_out_drain() clears
isoc_out_bna while packets remain stuck in the Rx FIFO.

> +	if (!hs_ep->dir_in && hs_ep->isoc_out_bna && !again) {
> +		unsigned int count = hs_ep->disable_count;
> +
> +		if (dwc2_gadget_isoc_out_held_packet(hs_ep)) {
> +			/*
> +			 * dwc2_hsotg_ep_disable() may have run while the lock
> +			 * was dropped for the giveback, and the endpoint may
> +			 * have been enabled again since.
> +			 */
> +			if (hs_ep->disable_count != count)
> +				return;
> +			again = true;
> +			goto restart;
> +		}
> +	}

[Severity: Medium]
Can exposing descriptors 1..N-1 as HREADY with L cleared on descriptor 0
corrupt the chain when goto restart wipes all descriptors?

With at least two queued requests and multiple packets buffered in the Rx
FIFO (which a disabled ISOC OUT endpoint keeps accepting until NAKed),
filling descriptor 1 clears DEV_DMA_L on descriptor 0 and marks descriptor
1 HREADY.  While dwc2_gadget_isoc_out_held_packet() drops hsotg->lock to
give back request 0, the core can advance into descriptor 1 for a second
buffered packet.  dwc2_gadget_complete_isoc_request_ddma() stops as soon as
descriptor 1 is DMABUSY (or not yet DMADONE), and goto restart then
unconditionally overwrites all descriptors with HBUSY and refills them.

A subsequent DMA writeback to descriptor 1 can clobber the newly refilled
descriptor status or silently drop the second packet.  Even on a core that
stops after descriptor 0, the !again guard handles only one held packet,
leaving a second buffered packet to trigger BNA as soon as EPENA is set.

[ ... ]

> @@ -2947,6 +3477,15 @@ static void dwc2_gadget_handle_out_token_ep_disabled(struct dwc2_hsotg_ep *ep)
>  			/* Start first ISO Out */
>  			ep->target_frame = hsotg->frame_number;
>  			dwc2_gadget_start_isoc_ddma(ep);
> +		} else if (!(dwc2_readl(hsotg, DOEPCTL(ep->index)) &
> +			     DXEPCTL_EPENA)) {
> +			/*
> +			 * The chain is taken for running, but the endpoint
> +			 * is disabled: the core stopped it on a BNA that was
> +			 * not handled as one, for example one seen with the
> +			 * endpoint still enabled. Restart it as after a BNA.
> +			 */
> +			dwc2_gadget_isoc_out_bna_reset(ep, true);
>  		}
>  		return;
>  	}

[Severity: Medium]
Should the TARGET_FRAME_INITIAL branch also verify that DXEPCTL_EPENA is
clear before calling dwc2_gadget_start_isoc_ddma()?

When dwc2_gadget_handle_isoc_bna() sees a BNA with EPENA still set and
isoc_out_restarted clear, it resets target_frame to TARGET_FRAME_INITIAL
with start = false to defer restarting until EPENA clears.  If
DXEPINT_OUTTKNEPDIS was latched in the same interrupt word,
dwc2_gadget_handle_out_token_ep_disabled() runs immediately afterward and
calls dwc2_gadget_start_isoc_ddma() without checking EPENA, overwriting
desc_list with HBUSY and reprogramming DOEPDMA while the endpoint is still
enabled in hardware.

[ ... ]

> @@ -4348,6 +4944,25 @@ static int dwc2_hsotg_ep_disable(struct usb_ep *ep)
>  
>  	ctrl = dwc2_readl(hsotg, epctrl_reg);
>  
> +	/*
> +	 * An isochronous OUT endpoint disabled by a BNA may still hold packets
> +	 * at the head of the Rx FIFO, which EP0 shares, see
> +	 * dwc2_gadget_isoc_out_drain(). Once the endpoint is gone no BNA comes
> +	 * to drain on, so give the drain more time here. A Rx FIFO flush does
> +	 * not help: the core holds the packet for a DMA write that waits for
> +	 * a descriptor, and the flush waits for the AHB master to go idle.
> +	 */
> +	if (using_desc_dma(hsotg) && hs_ep->isochronous && !dir_in &&
> +	    hs_ep->isoc_out_bna && !(ctrl & DXEPCTL_EPENA)) {
> +		dwc2_writel(hsotg, ctrl | DXEPCTL_SNAK, epctrl_reg);
> +		dwc2_gadget_isoc_out_drain(hs_ep,
> +					   DWC2_ISOC_OUT_DRAIN_DISABLE_US);
> +		if (hs_ep->isoc_out_bna)
> +			dev_warn(hsotg->dev,
> +				 "%s: packets left in the Rx FIFO at disable\n",
> +				 hs_ep->ep.name);
> +	}

[Severity: High]
Can dwc2_hsotg_ep_disable() skip draining held packets from the Rx FIFO
when a BNA happens concurrently before hs_ep->isoc_out_bna is set?

dwc2_gadget_isoc_out_bna_reset() calls
dwc2_gadget_complete_isoc_request_ddma() before setting
hs_ep->isoc_out_bna = 1, dropping hsotg->lock for the giveback:

CPU0                                CPU1
dwc2_hsotg_epint()
  clear DOEPINT (including BNAINTR)
  dwc2_gadget_isoc_out_bna_reset()
    dwc2_gadget_complete_isoc_request_ddma()
      spin_unlock(&hsotg->lock)
                                    dwc2_hsotg_ep_disable()
                                      isoc_out_bna == 0 <-- skips drain
                                      disable_count++
      spin_lock(&hsotg->lock)
    if (disable_count != count)
      return;  <-- never sets isoc_out_bna or drains

The same gap occurs if dwc2_hsotg_ep_disable() runs during an XferCompl
giveback when XferCompl and BNAINTR arrive in the same interrupt, or before
dwc2_hsotg_epint() runs at all (for example when GINTSTS_USBRST calls
dwc2_hsotg_core_init_disconnected() -> dwc2_hsotg_ep_disable() before
GINTSTS_OEPINT is serviced).  Undrained packets then stay at the head of
the shared Rx FIFO after disable, stalling EP0 and other OUT endpoints and
leaving GRSTCTL.AHBIDLE clear so subsequent core resets fail until reboot.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261205130225.341741-1-vadim@yuzi.co?part=1

^ permalink raw reply	[flat|nested] 5+ messages in thread

* Re: [PATCH v4 2/2] usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN endpoints after BNA
  2026-12-05 13:02 ` [PATCH v4 2/2] usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN " Vadim Yuzifovich
@ 2026-12-05 13:31   ` sashiko-bot
  0 siblings, 0 replies; 5+ messages in thread
From: sashiko-bot @ 2026-12-05 13:31 UTC (permalink / raw)
  To: Vadim Yuzifovich; +Cc: linux-usb

Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [Medium] usb: dwc2: stale BNAINTR in dwc2_hsotg_epint() aborts
  restarted IN transfer
- [Medium] usb: dwc2: dwc2_gadget_handle_nonisoc_bna() disables
  ineligible IN endpoint
- [Medium] usb: dwc2: stale bna_pending aborts restarted IN transfer on
  next EPDISBLD
- [Medium] usb: dwc2: broken bna_restarted tracking causes wrong TxFIFO
  flush behavior
- [Medium] usb: dwc2: latched EPDISBLD and stale bna_restarted break
  ep_stop_xfr()
- [Medium] usb: dwc2: dwc2_gadget_handle_nonisoc_bna() skips IN EP NAK
  handshake
- [Medium] usb: dwc2: XferCompl clears bna_pending before EPDISBLD
  flushes next TxFIFO
--

commit 41dd4823735d8cbadd17712a8c5f5ad25bf69eda
Author: Vadim Yuzifovich <vadim@yuzi.co>

usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN endpoints after BNA

This commit adds BNA interrupt recovery for non-EP0 bulk and interrupt IN
endpoints in descriptor DMA mode, restarting the current request when the
endpoint is disabled and the first descriptor is still host ready.

> diff --git a/drivers/usb/dwc2/gadget.c b/drivers/usb/dwc2/gadget.c
> index fdbc9677aef29..bd2e4f397f3c2 100644
> --- a/drivers/usb/dwc2/gadget.c
> +++ b/drivers/usb/dwc2/gadget.c

[ ... ]

> @@ -2790,6 +2798,111 @@ static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep)

[ ... ]

> +static void dwc2_gadget_handle_nonisoc_bna(struct dwc2_hsotg_ep *hs_ep,
> +					   u32 ints)
> +{
> +	struct dwc2_hsotg *hsotg = hs_ep->parent;
> +	struct dwc2_hsotg_req *hs_req = hs_ep->req;
> +	u32 epctl_reg = hs_ep->dir_in ? DIEPCTL(hs_ep->index) :
> +					DOEPCTL(hs_ep->index);
> +	u32 epctl = dwc2_readl(hsotg, epctl_reg);
> +	u32 status = hs_ep->desc_list ? READ_ONCE(hs_ep->desc_list[0].status) : 0;
> +	/* A request is current, and nothing else will move the endpoint on. */
> +	bool stuck = hs_req && !hs_ep->halted &&
> +		     !(epctl & (DXEPCTL_EPENA | DXEPCTL_STALL));
> +	bool restart = stuck && hs_ep->dir_in && hs_ep->desc_list &&
> +		       (!hs_req->req.num_sgs || !hs_req->req.actual) &&
> +		       status >> DEV_DMA_BUFF_STS_SHIFT == DEV_DMA_BUFF_STS_HREADY;
> +
> +	/*
> +	 * Not disabled yet. Disable it, so that an endpoint-disabled
> +	 * interrupt is sure to come, and restart from there, see
> +	 * dwc2_gadget_handle_ep_disabled().
> +	 */
> +	if (hs_ep->dir_in && hs_req && !hs_ep->halted &&
> +	    (epctl & DXEPCTL_EPENA)) {
> +		hs_ep->bna_pending = 1;
> +		dwc2_writel(hsotg, epctl | DXEPCTL_SNAK | DXEPCTL_EPDIS,
> +			    epctl_reg);
> +		return;
> +	}

[Severity: Medium]
Can this disable an active IN endpoint that is not eligible for a restart?

This branch writes DXEPCTL_SNAK | DXEPCTL_EPDIS before checking DXEPCTL_STALL,
desc_list, scatter-gather req.actual, descriptor 0 HREADY status, or the
DWC2_BNA_RESTARTS limit.  If DMA has already taken descriptor 0 or the
restart cap has been reached, dwc2_gadget_handle_ep_disabled() flushes the
TxFIFO and the subsequent dwc2_gadget_handle_nonisoc_bna() refuses to restart,
leaving the endpoint stopped (or bypassing DWC2_BNA_RESTARTS if EPENA still
reads set).

[Severity: Medium]
Is it safe to write DXEPCTL_SNAK | DXEPCTL_EPDIS directly without the IN
endpoint NAK-effective handshake?

In dwc2_hsotg_ep_stop_xfr(), disabling a non-stalled IN endpoint first waits
for DXEPINT_INEPNAKEFF (for dedicated TxFIFOs or periodic IN) or asserts
DCTL_SGNPINNAK and waits for GINTSTS_GINNAKEFF (for shared-FIFO bulk IN)
before setting DXEPCTL_EPDIS.  Skipping that handshake risks disrupting an
in-flight IN transfer.

In shared-FIFO mode (which dwc2_check_params() permits with g_dma_desc),
dwc2_gadget_handle_ep_disabled() then flushes shared TxFIFO 0 with
bna_restarted == 0 while other non-periodic IN endpoints such as EP0 IN were
never quiesced via DCTL_SGNPINNAK.

[ ... ]

> +	/*
> +	 * An endpoint-disabled interrupt latched for this BNA and not handled
> +	 * yet must not flush the data of the restarted request.
> +	 */
> +	hs_ep->bna_restarted = !(ints & DXEPINT_EPDISBLD) &&
> +		(dwc2_readl(hsotg, DIEPINT(hs_ep->index)) & DXEPINT_EPDISBLD);

[Severity: Medium]
Does the !(ints & DXEPINT_EPDISBLD) check drop a newly latched
DXEPINT_EPDISBLD on consecutive BNAs?

dwc2_hsotg_epint() clears all bits in ints from DIEPINT at entry, so any
DXEPINT_EPDISBLD read here is a newly latched, unhandled interrupt.  If BNA #1
left EPDISBLD pending and the restarted request immediately hits BNA #2 so
that ints carries both DXEPINT_EPDISBLD and DXEPINT_BNAINTR, !(ints &
DXEPINT_EPDISBLD) forces bna_restarted to 0 despite BNA #2's new EPDISBLD,
causing the next dwc2_gadget_handle_ep_disabled() to flush the restarted
request's TxFIFO.

Separately, dwc2_hsotg_ep_sethalt() never clears bna_restarted or bna_pending,
so if a halt is set and cleared before EPDISBLD is serviced, both halted and
DXEPCTL_STALL are 0 in dwc2_gadget_handle_ep_disabled() and a stale
bna_restarted skips the TxFIFO flush.  Clearing an already-latched
DXEPINT_EPDISBLD before restarting would avoid carrying bna_restarted across
interrupts altogether.

> +
> +	dev_warn_ratelimited(hsotg->dev,
> +			     "%s: BNA, DxEPINT %08x DxEPCTL %08x descriptor %08x, request restarted\n",
> +			     hs_ep->name, ints, epctl, status);
> +	dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
> +}

[Severity: Medium]
Does leaving DXEPINT_EPDISBLD latched in DIEPINT while re-enabling the
endpoint break dwc2_hsotg_ep_stop_xfr()?

If dwc2_hsotg_ep_dequeue() or dwc2_hsotg_ep_disable() runs before the pending
EPDISBLD interrupt is serviced, dwc2_hsotg_ep_stop_xfr() writes DXEPCTL_EPDIS
and polls DXEPINT_EPDISBLD, which immediately matches the stale BNA bit before
hardware finishes disabling the endpoint.  It then flushes the TxFIFO and
dwc2_hsotg_complete_request() unmaps the DMA buffer while DMA may still be
active.

dwc2_hsotg_ep_stop_xfr() also clears DXEPINT_EPDISBLD directly without
clearing bna_restarted or bna_pending, so bna_restarted stays 1 across future
requests and causes a later unrelated EPDISBLD in
dwc2_gadget_handle_ep_disabled() to skip dwc2_hsotg_txfifo_flush().

[ ... ]

> @@ -3408,6 +3529,12 @@ static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep)
>  		}
>  	}
>  
> +	/* See dwc2_gadget_handle_nonisoc_bna() */
> +	if (hs_ep->bna_pending) {
> +		hs_ep->bna_pending = 0;
> +		dwc2_gadget_handle_nonisoc_bna(hs_ep, DXEPINT_EPDISBLD);
> +	}
> +
>  	if (!hs_ep->isochronous)
>  		return;

[Severity: Medium]
Can a stale bna_pending survive a BNA restart and abort the restarted transfer
on the subsequent EPDISBLD interrupt?

IRQ 1: BNA with EPENA set
  dwc2_gadget_handle_nonisoc_bna()
    bna_pending = 1
    write DXEPCTL_SNAK | DXEPCTL_EPDIS

IRQ 2: BNAINTR read (EPDISBLD not latched yet)
  (hardware clears EPENA and latches EPDISBLD before DIEPCTL read)
  dwc2_gadget_handle_nonisoc_bna()
    EPENA is clear; bna_pending left at 1
    bna_restarted = 1
    dwc2_hsotg_start_req(..., true)   /* continuing=true keeps bna_pending */

IRQ 3: EPDISBLD
  dwc2_gadget_handle_ep_disabled()
    bna_restarted = 0                 /* skips TxFIFO flush */
    bna_pending == 1 -> dwc2_gadget_handle_nonisoc_bna()
      sees EPENA set -> writes SNAK | EPDIS  <-- aborts restarted transfer

Because dwc2_hsotg_start_req() only clears bna_pending when !continuing,
clearing bna_pending when dwc2_gadget_handle_nonisoc_bna() sees EPENA clear
would prevent IRQ 3 from aborting the restarted request.

[ ... ]

> @@ -3674,6 +3801,14 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
>  			__func__, dwc2_readl(hsotg, epctl_reg),
>  			dwc2_readl(hsotg, epsiz_reg));
>  
> +		/*
> +		 * See dwc2_gadget_handle_nonisoc_bna(). bna_restarted is left
> +		 * to the endpoint-disabled handler below, which may still have
> +		 * an interrupt of the BNA to handle.
> +		 */
> +		hs_ep->bna_restarts = 0;
> +		hs_ep->bna_pending = 0;
> +
>  		/* In DDMA handle isochronous requests separately */

[Severity: Medium]
If XferCompl arrives while bna_pending is 1, does clearing bna_pending here
allow the pending EPDISBLD to flush the next request's TxFIFO?

When dwc2_gadget_handle_nonisoc_bna() writes DXEPCTL_SNAK | DXEPCTL_EPDIS with
bna_pending = 1, bna_restarted stays 0.  If the in-flight transfer completes
before SNAK takes effect (for instance after a stale BNAINTR survived an
ep_disable()/ep_enable() cycle and hit a newly queued request),
DXEPINT_XFERCOMPL clears bna_pending and dwc2_hsotg_complete_in() starts the
next request with data in the TxFIFO.

When the pending DXEPINT_EPDISBLD then reaches
dwc2_gadget_handle_ep_disabled() in the same or next interrupt, bna_restarted
is 0, so it calls dwc2_hsotg_txfifo_flush() on the newly started request,
corrupting its data or hanging the endpoint.

[ ... ]

> @@ -3780,12 +3915,20 @@ static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
>  	if (ints & DXEPINT_BACK2BACKSETUP)
>  		dev_dbg(hsotg->dev, "%s: B2BSetup/INEPNakEff\n", __func__);
>  
> -	if ((ints & DXEPINT_BNAINTR) && (!hs_ep->isochronous || dir_in)) {
> +	if ((ints & DXEPINT_BNAINTR) && hs_ep->isochronous && dir_in) {
>  		dev_dbg(hsotg->dev, "%s: BNA interrupt\n", __func__);
> -		if (hs_ep->isochronous)
> -			dwc2_gadget_handle_isoc_bna(hs_ep);
> +		dwc2_gadget_handle_isoc_bna(hs_ep);
>  	}
>  
> +	/*
> +	 * A bulk or interrupt endpoint is restarted here, after the
> +	 * endpoint-disabled handler above has flushed the TxFIFO of an IN
> +	 * endpoint.
> +	 */
> +	if ((ints & DXEPINT_BNAINTR) && !hs_ep->isochronous &&
> +	    using_desc_dma(hsotg) && idx)
> +		dwc2_gadget_handle_nonisoc_bna(hs_ep, ints);

[Severity: Medium]
Can a stale DXEPINT_BNAINTR bit in ints abort a transfer that was just started
earlier in dwc2_hsotg_epint()?

ints is read once at the top of dwc2_hsotg_epint().  If DXEPINT_BNAINTR is set
alongside DXEPINT_EPDISBLD (with bna_pending set) or DXEPINT_XFERCOMPL, those
earlier branches already restart or start a transfer with DIEPCTL.EPENA set.

Falling through to dwc2_gadget_handle_nonisoc_bna() then sees DXEPCTL_EPENA
set from that fresh transfer and writes DXEPCTL_SNAK | DXEPCTL_EPDIS to abort
it; if DMA has already moved descriptor 0 off HREADY before the disable
completes, the subsequent EPDISBLD flushes the TxFIFO and refuses to restart,
leaving the endpoint stopped.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261205130225.341741-1-vadim@yuzi.co?part=2

^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2026-12-05 13:31 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-05 13:02 [PATCH v4 0/2] usb: dwc2: gadget: descriptor DMA fixes for BNA, found on Sophgo SG2002 Vadim Yuzifovich
2026-12-05 13:02 ` [PATCH v4 1/2] usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA Vadim Yuzifovich
2026-12-05 13:31   ` sashiko-bot
2026-12-05 13:02 ` [PATCH v4 2/2] usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN " Vadim Yuzifovich
2026-12-05 13:31   ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox