usb: dwc2: gadget: descriptor DMA fixes for BNA, found on Sophgo SG2002
Subsystems (3)
v4 cover usb: dwc2: gadget: descriptor DMA fixes for BNA, found on Sophgo SG2002
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/[email protected]
[3] v2: https://lore.kernel.org/r/[email protected]
[4] v3: https://lore.kernel.org/r/[email protected]
[5] v3 patch 3: https://lore.kernel.org/r/[email protected]
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
Signature · 1 line
2.56.1.windows.1
PATCH v4 1/2 usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA
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.
--- drivers/usb/dwc2/core.h | 31 ++ drivers/usb/dwc2/gadget.c | 696 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 691 insertions(+), 36 deletions(-)
drivers/usb/dwc2/core.h +31 -0
@@ -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 0xFFFFFFFFbool 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;
drivers/usb/dwc2/gadget.c +660 -36
890 lines not on this page · raw message
Signature · 1 line
2.56.1.windows.1
[email protected]
AI reviewRe: [PATCH v4 1/2] usb: dwc2: gadget: restart descriptor DMA isochronous OUT endpoints after BNA
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…
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 <[email protected]>
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.
Quoted 8 lines
drivers/usb/dwc2/gadget.c +0
-0@@ -218,6 +218,53 @@ static void dwc2_hsotg_ctrl_epint(struct dwc2_hsotg *hsotg,local_irq_restore (flags); }
drivers/usb/dwc2/gadget.c static void dwc2_hsotg_ctrl_epint(struct dwc2_hsotg *hsotg, · line 230
Quoted 10 lines
drivers/usb/dwc2/gadget.c +10
-0+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.
[ ... ]
Quoted 21 lines
drivers/usb/dwc2/gadget.c +21
-0+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 );
drivers/usb/dwc2/gadget.c static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep, · line 1071
Quoted 10 lines
drivers/usb/dwc2/gadget.c +10
-0+ } + *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.
[ ... ]
Quoted 7 lines
drivers/usb/dwc2/gadget.c +7
-0+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 ;
drivers/usb/dwc2/gadget.c static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep, · line 1228
Quoted 10 lines
drivers/usb/dwc2/gadget.c +10
-0+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.
drivers/usb/dwc2/gadget.c static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep, · line 1239
Quoted 10 lines
drivers/usb/dwc2/gadget.c +10
-0+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.
drivers/usb/dwc2/gadget.c static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep, · line 1241
Quoted 1 line
drivers/usb/dwc2/gadget.c +1
-0+ 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.
[ ... ]
drivers/usb/dwc2/gadget.c static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep, · line 1256
Quoted 3 lines
drivers/usb/dwc2/gadget.c +3
-0+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.
[ ... ]
drivers/usb/dwc2/gadget.c static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep) · line 1324
Quoted 11 lines
static void
dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep){
[ ... ]drivers/usb/dwc2/gadget.c +8
-0+/* +* 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.
[ ... ]
drivers/usb/dwc2/gadget.c static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep) · line 1358
Quoted 13 lines
drivers/usb/dwc2/gadget.c +8
-2ret =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.
drivers/usb/dwc2/gadget.c static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep) · line 1370
Quoted 11 lines
drivers/usb/dwc2/gadget.c +4
-0hs_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.
Quoted 5 lines
drivers/usb/dwc2/gadget.c +5
-0+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)) { +/*
drivers/usb/dwc2/gadget.c static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep) · line 1386
Quoted 10 lines
drivers/usb/dwc2/gadget.c +10
-0+* 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.
[ ... ]
Quoted 6 lines
drivers/usb/dwc2/gadget.c +2
-0@@ -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 )) {
drivers/usb/dwc2/gadget.c static void dwc2_gadget_handle_out_token_ep_disabled(struct dwc2_hsotg_ep *ep) · line 3491
Quoted 10 lines
drivers/usb/dwc2/gadget.c +7
-0+/* +* 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.
[ ... ]
Quoted 12 lines
drivers/usb/dwc2/gadget.c +8
-0@@ -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. +*/
drivers/usb/dwc2/gadget.c static int dwc2_hsotg_ep_disable(struct usb_ep *ep) · line 4964
Quoted 10 lines
drivers/usb/dwc2/gadget.c +10
-0+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 CPU1dwc2_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 drainsThe 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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v4 2/2 usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN endpoints after BNA
In reply to Vadim YuzifovichIn 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 off_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.
--- drivers/usb/dwc2/core.h | 10 +++ drivers/usb/dwc2/gadget.c | 151 +++++++++++++++++++++++++++++++++++++- 2 files changed, 157 insertions(+), 4 deletions(-)
drivers/usb/dwc2/core.h +10 -0
@@ -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 0xFFFFFFFFbool frame_overrun;
drivers/usb/dwc2/gadget.c +147 -4
196 lines not on this page · raw message
Signature · 1 line
2.56.1.windows.1
[email protected]
AI reviewRe: [PATCH v4 2/2] usb: dwc2: gadget: restart descriptor DMA bulk and interrupt IN endpoints after BNA
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…
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 <[email protected]>
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.
Quoted 4 lines
drivers/usb/dwc2/gadget.c +0
-0
[ ... ]
Quoted 1 line
drivers/usb/dwc2/gadget.c +0
-0@@ -2790,6 +2798,111 @@ static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep)
[ ... ]
Quoted 18 lines
drivers/usb/dwc2/gadget.c +18
-0+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
drivers/usb/dwc2/gadget.c static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep) · line 2872
Quoted 10 lines
drivers/usb/dwc2/gadget.c +10
-0+* 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.
[ ... ]
drivers/usb/dwc2/gadget.c static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep) · line 2898
Quoted 6 lines
drivers/usb/dwc2/gadget.c +6
-0+/* +* 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.
drivers/usb/dwc2/gadget.c static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep) · line 2904
Quoted 6 lines
drivers/usb/dwc2/gadget.c +6
-0+ +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().
[ ... ]
drivers/usb/dwc2/gadget.c static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep) · line 3539
Quoted 12 lines
drivers/usb/dwc2/gadget.c +6
-0@@ -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 transferBecause 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.
[ ... ]
drivers/usb/dwc2/gadget.c static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx, · line 3812
Quoted 13 lines
drivers/usb/dwc2/gadget.c +8
-0@@ -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.
[ ... ]
Quoted 10 lines
drivers/usb/dwc2/gadget.c +2
-3@@ -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);
drivers/usb/dwc2/gadget.c static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx, · line 3930
Quoted 10 lines
drivers/usb/dwc2/gadget.c +8
-0} +/* +* 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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2