net: macb: implement context swapping
Subsystems (5)
Théo Lebrun
maintainerv10 cover net: macb: implement context swapping
MACB has a pretty primitive approach to buffer management. They are all stored in struct macb *bp. On operations that require buffer realloc (set_ringparam & change_mtu at the moment), the only option is to close the interface, change our global state and re-open the interface.
Two issues:
- It doesn't fly on memory pressured systems; we free our precious buffers and don't manage to reallocate fully, meaning our machine just lost its network access.
- Anecdotally, it is pretty slow because it implies a full PHY reinit.
Instead, we shall:
- allocate a new context (including buffers) first
- if it fails, early return without any impact to the interface
- stop interface
- update global state (bp, netdev, etc)
- pass newly allocated buffer pointers to the hardware
- start interface
- free old context
This is what we implement here. Both .set_ringparam() and .ndo_change_mtu() are covered by this series. In the future, at least .set_channels() [0], XDP [1] and XSK [2] would benefit.
---
We now rebased onto the quiesce work that's made it to net-next. Also, I shortened the series by dropping one useless patch (took me a while to realise!) and one that has been posted separately [4]. A Sashiko review also lead to another separate patch sent [5].
I wonder if we can get those changes in before the next merge window? The idea being that we can restart iterating on XDP [1] & XSK [2] during the next kernel cycle, bringing those long awaited features into MACB.
Thanks,
Have a nice day,
Théo
[0]: https://lore.kernel.org/netdev/[email protected]/
[1]: https://lore.kernel.org/netdev/[email protected]/
[2]: https://lore.kernel.org/netdev/[email protected]/
[3]: https://lore.kernel.org/all/[email protected]/
[4]: https://lore.kernel.org/netdev/[email protected]/
[5]: https://lore.kernel.org/netdev/[email protected]/
---
Changes in v10:
- Rebase onto latest net-next/main (47a144672573), dropping first 7
patches applied by Jakub. It also means we reuse the quiesce work introduced by 4fcaed2cb1d8 ("net: macb: quiesce IRQs and drain BH on interface close").
- Drop wrong patch "read ISR inside bp->lock critical section".
- Patch "move printk() calls out of bp->lock critical section"
was sent separately as it is standalone.
https://lore.kernel.org/netdev/[email protected]/
- In commit "change caps helpers signatures", in macb_rx_pending(),
convert missed macb_is_gem() call from bp to bp->info. Restore bisectability.
- Writes to bp->ctx are now made with WRITE_ONCE() + wmb().
- macb_tx_restart() now early exits if context swap is ongoing, to avoid races. For that, we grow its existing bp->lock critical section.
- Link to v9: https://patch.msgid.link/[email protected]
Changes in v9:
- Drop unused netdev stack variable in macb_interrupt_misc().
- Rebase onto latest net-next/main (ac155a26750a), nothing to report.
- Link to v8: https://patch.msgid.link/[email protected]
Changes in v8:
- Avoid growing existing race condition window inbetween macb_tx_error_task() and macb_interrupt() by moving printks.
- On swap end, don't start tx queues if link-down.
- On swap end, wake tx queues instead of only starting them.
- Rebase onto latest net-next/main (a23b36233d41), nothing to report.
- Link to v7: https://patch.msgid.link/[email protected]
Changes in v7:
- queue->tx_{head,tail} got renamed: fixup queue->tx_ptr_lock field comment and netdev_dbg() call in macb_start_xmit().
- Ensure bp->configured_{rx,tx}_ring_size have correct values in the EMAC case so that get_ringparam doesn't lie.
- Refuse set_ringparam on EMAC, which is invalid (sizes are hardcoded).
- Fix whitespace issue in "change function signatures to take contexts".
- Fix rebase mistake: macb_tx_unmap() signature change moved from patch "change function signatures to take contexts" to "change caps helpers signatures".
- Patch "move printk() calls out of bp->lock critical section":
- Undrop netdev_vdbg() in macb_tx_error_task(); let's ignore the race for debug printk calls.
- Move netdev_err() from macb_interrupt_misc() into macb_interrupt()
so it can live outside the bp->lock critical section.
- Add details to commit message.
- Patch "use context swapping in .set_ringparam()":
- Re-schedule LPI after swap with delay=1s. Pick 1s so that if
link-up -> swap instantly, we still respect the IEEE spec. - Add bp->link_up set under bp->mac_cfg_lock. netif_carrier_ok() bit
is unsafe because not set inside a critical section we can enter.
- Drop mac_cfg_lock from macb_hresp_error_task(); made useless by
above.
- Move macb_halt_tx() out of bp->lock to avoid 14ms latency spike possibility. Safe to do so.
- Patch "use context swapping in .ndo_change_mtu()":
- Clarify commit message about EMAC.
- Rebase onto latest net-next/main (69963a0678a3), nothing to report.
- Link to v6: https://patch.msgid.link/[email protected]
Changes in v6:
- Non Sashiko based:
- Take 3x Reviewed-By: Nicolai.
- Silence checkpatch warnings in [02/15] about printk(..., __func__).
- Rebase to latest net-next/main (a5c6ae8de11e), nothing to report.
- Fix netconsole/netpoll deadlock coming from macb_tx_error_task()
calling printk() inside the bp->lock critical section.
- Move at91ether synchronize_irq() on close to protect more kfree().
- Clarify commit message for [11/15]: functions operating on the
interface have no risk of using the wrong interface.
- On swap end, only re-enable the interface if !netif_carrier_ok().
- macb_hresp_error_task() grabs bp->mac_cfg_lock as it toggles the
carrier state, to avoid race with context swap.
- On swap end, move netif_tx_start_all_queues() into bp->mac_cfg_lock.
- Link to v5: https://patch.msgid.link/[email protected]
Changes in v5:
- Fix build on [PATCH 02/15]; bp->dev got renamed to bp->netdev.
- Fix one word in commit message of [PATCH 07/15].
- Move bp->ctx->info assignment in at91ether_open() from [PATCH 12/15]
to [PATCH 09/15].
- In [PATCH 14/15], reset DQL (dynamic queue limits) after tx disable,
not before.
- Take 7 Reviewed-by: Nicolai (weirdly not all detected by b4).
- Rebase on latest net-next/main (89d8006259b8), nothing to report.
- Link to v4: https://patch.msgid.link/[email protected]
Changes in v4:
- Disable tx_error_task then disable NAPI because error task does a napi_disable() which deadlocks if NAPI is already disabled.
- Disable NAPI then disable tx_lpi_work, because NAPI might re-arm the latter.
- Last iteration did mask-irqs then disable-and-wait-for-bh then disable-hw. This is flawed because BH rearm IRQs once done. We don't
have a good way to signal to them they shouldn't do so (we don't want
to lock from NAPI context). So instead we add a bp->ctx_swap flag, shielded by bp->lock, to indicate to our IRQ handler to ignore IRQs
and self-disarm.
- at91ether_close(): synchronize_irq() before freeing context.
- macb_interrupt(): drop double ISR read (outside & inside bp->lock).
- Rebase on latest net-next/main (f6f3b36c15ed). macb_free() since
commit 27f575836cfe ("net: macb: drop in-flight Tx SKBs on close")
needs access to queue stats => add them to macb_info.
- Take trailers.
- I did NOT init ctx->rx_ring_size/tx_ring_size/rx_buffer_size from at91ether_open(), as recommended by the netdev LLM. They are not the first fields in MACB that are present in both instances and that are uninitialised in one case. AT91 is almost a different driver. [3]
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Use const struct macb_info *info instead of bare u32 caps as
helper arguments, for type safety.
- macb_interrupt(): the pre-lock readl(ISR) to detect spurious
interrupts is only done if CLEAR_ON_WRITE.
- Don't forget allocating context in at91ether_open().
- swap:
- Refuse swap for EMAC HW; it would crash because codepaths are so different.
- Grab new bp->mac_cfg_lock to serialise with phylink MAC callbacks.
We cannot rely on phydev->lock because it isn't present in the SFP
or fixed-link cases. We also want to avoid phylink_stop() which triggers a slow PHY retrain.
- swap start:
- We used to do disable-irqs-and-hw then drain-all-bh-features, but
then HW might be raced against. Instead we disable-irqs then drain-all-bh then disable-hw which means at disable-hw step no BH context can be active.
- Use macb_halt_tx() helper to properly stop HW.
- Disable BH features before netif_tx_disable() call to avoid queue wakeup races.
- Use macb_queue_isr_clear() helper instead of manual if-then-writel.
- swap end:
- Grab bp->lock for the hardware reinit sequence composed of DMACFG
and NCR writes.
- Drop now useless EMAC check (we refuse EMAC HW before swapping).
- nits:
- New patch to rename macb_{alloc,free}_consistent() which don't only allocate consistent buffers since a long time ago.
- Fix the start_xmit verbose netdev_vdbg() format string from %hu to %u because the queue index type changed.
- Strong commit reword from "unify struct macb * naming convention"
to "unify variable naming convention in at91ether functions" which
was underselling the changes.
- Rebase upon latest net-next/main (1c664ec4b9ea).
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Patch "add subset of struct macb to struct macb_context" was
messed up. It contained much more than what the name implied. Split
into three commits (I caused trouble by rebase reordering).
- Fix tieoff; V1 allocated it without initialisation.
- Fix NULL pointer dereference on context in mab_get_regs() and macb_get_ringparam() when interface is offline.
- Patch "unify device pointer naming convention":
- Fix build issue when CONFIG_NETCONSOLE=y.
- Rename struct net_device *dev to netdev in macb.h.
- Rename struct phy_device *phy to phydev in macb_main.c.
- On swap, call netdev_tx_reset_queue() to reset all DQL counters.
- At end of swap, add missing kfree(old_ctx).
- During HW disabling in swap, grab bp->lock to protect against IRQ handler.
- On swap, cancel the three BH features MACB has:
bp->hresp_err_bh_work, bp->tx_lpi_work and queue->tx_error_task.
- On swap, call macb_configure_dma() which writes buffer size to
hardware registers. This is important because the change_mtu codepath changes the buffer size.
- Rebase onto latest net-next/main (58dd34dbd5b0) & resolve conflicts.
- Link to v1: https://patch.msgid.link/[email protected]
To: Théo Lebrun <[email protected]>
To: Conor Dooley <[email protected]>
To: Andrew Lunn <[email protected]>
To: "David S. Miller" <[email protected]>
To: Eric Dumazet <[email protected]>
To: Jakub Kicinski <[email protected]>
To: Paolo Abeni <[email protected]>
To: Richard Cochran <[email protected]>
To: Russell King <[email protected]>
---
Théo Lebrun (8):
net: macb: introduce macb_context struct for buffer management
net: macb: avoid macb_init_rx_buffer_size() modifying state
net: macb: make struct macb subset reachable from macb_context struct
net: macb: change caps helpers signatures
net: macb: change function signatures to take contexts
net: macb: introduce macb_context_alloc() helper
net: macb: use context swapping in .set_ringparam()
net: macb: use context swapping in .ndo_change_mtu()
drivers/net/ethernet/cadence/macb.h | 115 ++- drivers/net/ethernet/cadence/macb_main.c | 1136 +++++++++++++++++++----------- drivers/net/ethernet/cadence/macb_ptp.c | 8 +- 3 files changed, 818 insertions(+), 441 deletions(-)
---
base-commit: 068b5854d6cf588826bd876172652e7c1469d4e6
change-id: 20260401-macb-context-bd0caf20414d
Best regards,
Signature · 1 line
Théo Lebrun <[email protected]>
Théo Lebrun
maintainerPATCH v10 1/8 net: macb: introduce macb_context struct for buffer management
Whenever an operation requires buffer realloc, we close the interface, update parameters and reopen. To improve reliability under memory pressure, we should rather alloc new buffers, reconfigure HW and free old buffers. This requires MACB to support having multiple "contexts" in parallel.
Introduce this concept by adding the macb_context struct, which owns all queue buffers and the parameters associated. We do not yet support multiple contexts in parallel, because all functions access bp->ctx (the currently active context) directly.
Steps:
- Introduce struct macb_context and its children struct macb_rxq and struct macb_txq. Context fields are stolen from struct macb and rxq/txq fields are from struct macb_queue.
Making it two separate structs per queue simplifies accesses: we grab a txq/rxq local variable and access fields like txq->head instead of queue->tx_head. It also anecdotally improves data locality.
- macb_init_dflt() / macb_get_ringparam() do not access bp->ctx->{rx,tx}_ring_size as they will/might run while interface is offline and ctx is NULL. Instead, introduce bp->configured_{rx,tx}_ring_size which get updated on user requests.
- macb_open() starts by allocating bp->ctx. It gets freed in the open error codepath or by macb_close().
- Guided by compile errors, update all codepaths. Most diff is changing queue->tx_* to txq->* and queue->rx_* to rxq->*, with a new local variable. Also rx_buffer_size / rx_ring_size / tx_ring_size move from bp to bp->ctx.
Introduce two helpers macb_txq|rxq() functions to convert macb_queue pointers.
- macb_get_regs() is tweaked to support being ran while interface is offline (and context is NULL). Use default values at zero and override them only if context is present.
- Protect our ctx freeing in at91ether code with a synchronize_irq() call.
--- drivers/net/ethernet/cadence/macb.h | 51 +++- drivers/net/ethernet/cadence/macb_main.c | 506 +++++++++++++++++++------------ 2 files changed, 344 insertions(+), 213 deletions(-)
drivers/net/ethernet/cadence/macb.h +35 -16
@@ -1267,23 +1267,12 @@ struct macb_queue {unsigned int ENST_ON_TIME ;unsigned int ENST_OFF_TIME ; -/* Lock to protect tx_head and tx_tail */ +/* Lock to protect ctx->txq[q].head and ctx->txq[q].tail */ spinlock_t tx_ptr_lock; -unsigned int tx_head, tx_tail; -struct macb_dma_desc *tx_ring; -struct macb_tx_skb *tx_skb; -dma_addr_t tx_ring_dma;struct work_struct tx_error_task;bool txubr_pending;struct napi_struct napi_tx; -dma_addr_t rx_ring_dma; -dma_addr_t rx_buffers_dma; -unsigned int rx_tail; -unsigned int rx_prepared_head; -struct macb_dma_desc *rx_ring; -struct sk_buff **rx_skbuff; -void *rx_buffers;struct napi_struct napi_rx;struct queue_stats stats; };
@@ -1298,6 +1287,32 @@ struct ethtool_rx_fs_list {unsigned int count; }; +struct macb_rxq { +struct macb_dma_desc *ring;/* MACB & GEM */ +dma_addr_t ring_dma;/* MACB & GEM */ +unsigned int tail;/* MACB & GEM */ +unsigned int prepared_head;/* GEM */ +struct sk_buff **skbuff;/* GEM */ +dma_addr_t buffers_dma;/* MACB */ +void *buffers;/* MACB */ +}; + +struct macb_txq { +unsigned int head; +unsigned int tail; +struct macb_dma_desc *ring; +dma_addr_t ring_dma; +struct macb_tx_skb *skb; +}; + +struct macb_context { +unsigned int rx_buffer_size; +unsigned int rx_ring_size; +unsigned int tx_ring_size; +struct macb_rxq rxq[MACB_MAX_QUEUES ]; +struct macb_txq txq[MACB_MAX_QUEUES ]; +}; +struct macb {void __iomem *regs;bool native_io;
@@ -1306,12 +1321,16 @@ struct macb {u32 (*macb_reg_readl)(struct macb *bp,int offset);void (*macb_reg_writel)(struct macb *bp,int offset,u32 value); +/* +* Context stores all its parameters. +* But we must remember them across closure. +*/ +unsigned int configured_rx_ring_size; +unsigned int configured_tx_ring_size; +struct macb_context *ctx; +struct macb_dma_desc *rx_ring_tieoff;dma_addr_t rx_ring_tieoff_dma; -size_t rx_buffer_size; - -unsigned int rx_ring_size; -unsigned int tx_ring_size;unsigned int num_queues;struct macb_queue queues[MACB_MAX_QUEUES ];
drivers/net/ethernet/cadence/macb_main.c +309 -197
1,211 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH net-next v10 1/8] net: macb: introduce macb_context struct for buffer management
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.
Critical: 0 · High: 0 · Medium: 1 (1) · Low: 2
If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).
- [Medium] The NAPI poll handlers read the context after napi_complete_done(), and nothing stops that context from being freed…
- [Low] The patch changes what ethtool -g reports on AT91 EMAC devices, and the commit message does not say so.
- [Low] On EMAC, at91ether_open() kzallocs bp->ctx and never sets ctx->rx_ring_size or ctx->tx_ring_size, so both stay 0.
Pre-existing issues:
- [Medium] macb_set_ringparam() calls macb_close(), updates configured_*_ring_size, and then calls macb_open(bp->netdev) without…
--
net: macb: introduce macb_context struct for buffer management
This commit moves the per-queue ring buffers and ring parameters out of struct macb and struct macb_queue into a new struct macb_context. The context is allocated in macb_open()/at91ether_open() and freed on close. User-requested ring sizes are now kept in bp->configured_{rx,tx}_ring_size so they persist while the interface is down.
Quoted 4 lines
drivers/net/ethernet/cadence/macb_main.c +0
-0
[ ... ]
drivers/net/ethernet/cadence/macb_main.c static void macb_tx_restart(struct macb_queue *queue) · line 2019
Quoted 11 lines
drivers/net/ethernet/cadence/macb_main.c +2
-1@@ -2011,15 +2011,16 @@ static void macb_tx_restart(struct macb_queue *queue)static bool macb_tx_complete_pending (struct macb_queue *queue) { +struct macb_txq *txq =macb_txq (queue);bool retval = false;unsigned long flags;spin_lock_irqsave (&queue->tx_ptr_lock, flags); -if (queue->tx_head != queue->tx_tail) { +if (txq->head != txq->tail) {
[Severity: Medium]
Can bp->ctx be freed while this is running?
macb_tx_poll() calls this after napi_complete_done() has already released NAPI ownership:
if (work_done < budget && napi_complete_done(napi, work_done)) {
queue_writel(queue, IER, MACB_BIT(TCOMP));
...
if (macb_tx_complete_pending(queue)) {napi_disable() waits only for ownership to be released. It does not wait for the poll function to return. Documentation/networking/napi.rst says:
napi_disable() and subsequent calls to the poll method only wait for the ownership of the instance to be released, not for the poll method to exit. This means that drivers should avoid accessing any data structures after calling napi_complete_done().
That seems to allow this interleaving:
CPU A CPU Bmacb_tx_poll()
napi_complete_done() == true
<delayed>
macb_close()
macb_quiesce_start()
napi_disable() /* returns */
...
macb_free(bp);
kfree(bp->ctx);
bp->ctx = NULL;
macb_tx_complete_pending()
macb_txq()
&bp->ctx->txq[q] /* NULL or freed */
txq->headBefore this patch, queue->tx_head and queue->tx_tail lived in bp->queues and were always valid. The freed ring was only touched when head != tail. Now txq points into the ctx, so an empty TX ring also hits the freed or NULL memory.
The RX side (macb_rx_poll()->macb_rx_pending()->macb_rxq()) already had a similar window on rx_ring before this patch. Now it is on the ctx itself.
This window also seems to remain at the end of the series. There, macb_close() and macb_context_swap_end() free the old ctx after napi_disable(), with no further synchronization.
Should the poll handlers avoid touching ctx after napi_complete_done()? Alternatively, should the ctx free wait for in-flight poll calls to return?
[ ... ]
drivers/net/ethernet/cadence/macb_main.c static int macb_set_ringparam(struct net_device *netdev, · line 3919
Quoted 11 lines
drivers/net/ethernet/cadence/macb_main.c +2
-2@@ -3822,8 +3912,8 @@ static int macb_set_ringparam(struct net_device *netdev,macb_close (bp->netdev); } - bp->rx_ring_size = new_rx_size; - bp->tx_ring_size = new_tx_size; + bp->configured_rx_ring_size = new_rx_size; + bp->configured_tx_ring_size = new_tx_size;if (reset)macb_open (bp->netdev);
[Severity: Medium]
This is a pre-existing issue, but the macb_open() return value is ignored here.
With this patch, every macb_open() error path ends with bp->ctx == NULL:
free_ctx:
kfree(bp->ctx);
bp->ctx = NULL;Meanwhile the netdev stays IFF_UP. A later dev_close()->macb_close() calls macb_quiesce_start()->napi_disable() on NAPI instances that were left disabled, and that hangs. The same hang could already happen before this patch when macb_alloc() failed on reopen. If that point were somehow passed, macb_free() would then dereference the NULL bp->ctx.
This patch adds one more way for this path to fail: the kzalloc_obj() of ctx.
The later commit "net: macb: use context swapping in .set_ringparam()" in this series seems to fix this. It allocates the new context first and returns the error with the interface untouched.
Should the macb_open() failure be handled here until then?
[ ... ]
drivers/net/ethernet/cadence/macb_main.c static int at91ether_open(struct net_device *netdev) · line 5276
Quoted 11 lines
drivers/net/ethernet/cadence/macb_main.c +7
-0@@ -5177,6 +5267,13 @@ static int at91ether_open(struct net_device *netdev)if (ret <0 )return ret; +WRITE_ONCE (bp->ctx,kzalloc_obj (*bp->ctx)); +wmb ();/* ensure IRQ enabled below read the new context */ +if (!bp->ctx) { + ret = -ENOMEM ; + goto pm_exit; + } +
[Severity: Low]
Unlike macb_open(), at91ether_open() never sets ctx->rx_ring_size or ctx->tx_ring_size. Both stay 0, while bp->configured_* holds 9/1.
Shared helpers still read these fields. For example, at91ether_start()->macb_rx_desc()->macb_rx_ring_wrap() does:
return index & (bp->ctx->rx_ring_size - 1);
With a size of 0 the mask is UINT_MAX, so indices pass through unchanged. This matches the pre-patch behaviour, where bp->rx_ring_size was also 0 on EMAC.
It only works because at91ether_start() bounds its loop with AT91ETHER_MAX_RX_DESCR and at91ether_rx() wraps rxq->tail by hand.
If the configured value were copied into ctx the way macb_open() does it, there would be a problem. AT91ETHER_MAX_RX_DESCR (9) is not a power of two, so the mask would be 8 and descriptors 1..7 would alias descriptor 0.
Is it intended that the EMAC ctx has ring sizes of 0 while configured_* reports 9/1?
[ ... ]
drivers/net/ethernet/cadence/macb_main.c static int macb_probe(struct platform_device *pdev) · line 6108
Quoted 9 lines
drivers/net/ethernet/cadence/macb_main.c +5
-0@@ -5998,6 +6101,15 @@ static int macb_probe(struct platform_device *pdev)/* setup capabilities */ macb_configure_caps (bp, macb_config); +if (bp->caps &MACB_CAPS_MACB_IS_EMAC ) { +/* The name is lying on EMAC: sizes aren't configurable. */ + bp->configured_rx_ring_size =AT91ETHER_MAX_RX_DESCR ; + bp->configured_tx_ring_size =1 ;/* tiny ring buffer */ + }else {
[Severity: Low]
This changes what ethtool -g reports on EMAC devices.
Before this patch, only macb_init_dflt() set bp->rx_ring_size and bp->tx_ring_size. EMAC goes through at91ether_init() instead, but it still installs macb_ethtool_ops. As a result, macb_get_ringparam() reported 0/0 on EMAC. With this hunk it reports 9/1.
The new values match the hardware: TX only ever uses rm9200_txq[0]. So this looks like a fix to the reporting.
However, the commit message describes configured_{rx,tx}_ring_size only as a way to keep the sizes across close. Could it also mention the user-visible ethtool -g change on EMAC?
Also, at91ether_open() does not copy configured_* into the ctx (see the comment above), so the reported values and the ctx disagree.
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261001-macb-context-v10-0-beb541bbb7df%40bootlin.com
Jakub Kicinski
maintainerRe: [PATCH net-next v10 1/8] net: macb: introduce macb_context struct for buffer management
Quoted 2 lines · On Sun, 04 Oct 2026 23:33:24 +0000 [email protected] wrote:
- [Medium] The NAPI poll handlers read the context after
napi_complete_done(), and nothing stops that context from being freed…
Looks legit at the surface. I was going to try to double check and then realized the series no longer applies :S
Signature · 1 line
pw-bot: cr
Théo Lebrun
maintainerRe: [PATCH net-next v10 1/8] net: macb: introduce macb_context struct for buffer management
Hello Jakub,
Quoted 6 lines · Jakub Kicinski
Quoted 2 lines · On Sun, 04 Oct 2026 23:33:24 +0000 [email protected] wrote:
- [Medium] The NAPI poll handlers read the context after
napi_complete_done(), and nothing stops that context from being freed…Looks legit at the surface. I was going to try to double check and then realized the series no longer applies :S
Yes that report was correct!
napi_disable() only waits for napi_complete_done() to be called, but our poll functions still dereference the rings after the napi_complete_done() call.
That's an issue for all drivers (quite a few are broken in that sense). I see two solutions:
- Avoid all dangerous reads in NAPI poll after napi_complete_done().
- Wait for full NAPI poll to be done using synchronize_net().
We cannot use the first solution in MACB as we must re-read rings after unmasking IRQs to check if we lost a wakeup signal, see commit 0bf476fc3624 ("net: macb: Fix lost RX packet wakeup race in NAPI receive"). So we'll take the second one.
This bug is unrelated to context swapping though; the upstream driver already has the same race condition. Sashiko rather funnily attributes it to our series; somehow the use-after-free got more serious.
I checked for precedent as I would have been surprised we were the first ones to land in that napi_disable() subtlety. See commit eb41a264a3a5 ("net/mlx5e: Fix race between DIM disable and net_dim()") which uses the synchronize_net() mechanism to prevent against the exact same race.
V11 has been sent already, see:
[PATCH net-next v11 1/9] net: macb: close race between NAPI polls & ndo_stop
https://lore.kernel.org/netdev/[email protected]/
Thanks,
--
Théo Lebrun, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
Théo Lebrun
maintainerPATCH v10 2/8 net: macb: avoid macb_init_rx_buffer_size() modifying state
In reply to Théo Lebrunmacb_init_rx_buffer_size() takes the macb private data struct and overrides its bp->ctx->rx_buffer_size. To make it usable with multiple contexts, make it return its value.
Also, move the bufsz computation into it. The value is only used if GEM, and for historical reason it currently lives in macb_open().
--- drivers/net/ethernet/cadence/macb_main.c | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-)
drivers/net/ethernet/cadence/macb_main.c +13 -13
@@ -2709,25 +2709,26 @@ static netdev_tx_t macb_start_xmit(struct sk_buff *skb,return ret; } -static void macb_init_rx_buffer_size (struct macb *bp,size_t size) +static unsigned int macb_rx_buffer_size (struct macb *bp,unsigned int mtu) { -if (!macb_is_gem (bp)) { - bp->ctx->rx_buffer_size =MACB_RX_BUFFER_SIZE ; - }else { - bp->ctx->rx_buffer_size =MIN (size,RX_BUFFER_MAX ); +unsigned int size; -if (bp->ctx->rx_buffer_size %RX_BUFFER_MULTIPLE ) { +if (!macb_is_gem (bp)) { + size =MACB_RX_BUFFER_SIZE ; + }else { + size = mtu +ETH_HLEN +ETH_FCS_LEN +NET_IP_ALIGN ; + size =MIN (size,RX_BUFFER_MAX ); + +if (size %RX_BUFFER_MULTIPLE ) {netdev_dbg (bp->netdev,"RX buffer must be multiple of %d bytes, expanding\n" ,RX_BUFFER_MULTIPLE ); - bp->ctx->rx_buffer_size = -roundup (bp->ctx->rx_buffer_size, -RX_BUFFER_MULTIPLE ); + size =roundup (size,RX_BUFFER_MULTIPLE ); } } -netdev_dbg (bp->netdev,"mtu [%u] rx_buffer_size [%u]\n" , - bp->netdev->mtu, bp->ctx->rx_buffer_size); +netdev_dbg (bp->netdev,"mtu [%u] rx_buffer_size [%u]\n" , mtu, size); +return size; }static void gem_free_rx_buffers (struct macb *bp)
@@ -3312,7 +3313,6 @@ static void macb_set_rx_mode(struct net_device *netdev)static int macb_open (struct net_device *netdev) { -size_t bufsz = netdev->mtu +ETH_HLEN +ETH_FCS_LEN +NET_IP_ALIGN ;struct macb *bp =netdev_priv (netdev);int err;
@@ -3330,7 +3330,7 @@ static int macb_open(struct net_device *netdev) }/* RX buffers initialization */ -macb_init_rx_buffer_size (bp, bufsz); + bp->ctx->rx_buffer_size =macb_rx_buffer_size (bp, netdev->mtu); bp->ctx->rx_ring_size = bp->configured_rx_ring_size; bp->ctx->tx_ring_size = bp->configured_tx_ring_size;
Signature · 1 line
2.55.0
Théo Lebrun
maintainerPATCH v10 3/8 net: macb: make `struct macb` subset reachable from macb_context struct
In reply to Théo LebrunFor parallel MACB context to start become a reality, many functions need to stop operating on bp->ctx (the currently active context) and instead work on a context they get passed. That context might be
(1) the new one that is getting allocated and initialised, or,
(2) the old one to be freed.
To reduce bug surface area, we will taint those functions to *only* take a context and no struct macb *bp. That way, no bug of using bp->ctx instead of ctx will ever occur.
For that, we need to embed a subset of struct macb information into each context so that all helpers can still do their jobs. That subset must be constant once probe is completed. Do this by taking a pointer to a subset of macb called struct macb_info.
That subset is accessible from context (ctx->info->caps) or from bp (bp->caps) using -fms-extensions option, thanks to commit c4781dc3d1cf ("Kbuild: enable -fms-extensions").
https://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html
Add the structure and assign ctx->info at alloc,
but nothing uses it yet.
--- drivers/net/ethernet/cadence/macb.h | 31 ++++++++++++++++++++++--------- drivers/net/ethernet/cadence/macb_main.c | 6 ++++++ 2 files changed, 28 insertions(+), 9 deletions(-)
drivers/net/ethernet/cadence/macb.h +22 -9
@@ -1287,6 +1287,17 @@ struct ethtool_rx_fs_list {unsigned int count; }; +struct macb_info { +struct platform_device *pdev; +struct net_device *netdev; +struct macb_or_gem_ops macbgem_ops; +unsigned int num_queues; +u32 caps; +int rx_bd_rd_prefetch; +int tx_bd_rd_prefetch; +struct queue_stats *queue_stats[MACB_MAX_QUEUES ]; +}; +struct macb_rxq {struct macb_dma_desc *ring;/* MACB & GEM */ dma_addr_t ring_dma;/* MACB & GEM */
@@ -1306,6 +1317,8 @@ struct macb_txq { };struct macb_context { +const struct macb_info *info; +unsigned int rx_buffer_size;unsigned int rx_ring_size;unsigned int tx_ring_size;
@@ -1321,6 +1334,15 @@ struct macb {u32 (*macb_reg_readl)(struct macb *bp,int offset);void (*macb_reg_writel)(struct macb *bp,int offset,u32 value); +/* +* Give direct access (bp->caps) and +* allow taking a pointer to it (&bp->info) for contexts. +*/ +union { +struct macb_info ; +struct macb_info info; + }; +/* * Context stores all its parameters. * But we must remember them across closure.
@@ -1332,17 +1354,14 @@ struct macb {struct macb_dma_desc *rx_ring_tieoff;dma_addr_t rx_ring_tieoff_dma; -unsigned int num_queues;struct macb_queue queues[MACB_MAX_QUEUES ];spinlock_t lock; -struct platform_device *pdev;struct clk *pclk;struct clk *hclk;struct clk *tx_clk;struct clk *rx_clk;struct clk *tsu_clk; -struct net_device *netdev;/* Protects hw_stats and ethtool_stats */ spinlock_t stats_lock;union {
@@ -1350,15 +1369,12 @@ struct macb {struct gem_stats gem; } hw_stats; -struct macb_or_gem_ops macbgem_ops; -struct mii_bus *mii_bus;struct phylink *phylink;struct phylink_config phylink_config;struct phylink_pcs phylink_usx_pcs;struct phylink_pcs phylink_sgmii_pcs; -u32 caps;unsigned int dma_burst_length;phy_interface_t phy_interface;
@@ -1406,9 +1422,6 @@ struct macb {*/ bool irq_quiesced; -int rx_bd_rd_prefetch; -int tx_bd_rd_prefetch; -u32 rx_intr_mask;struct macb_pm_data pm_data;
drivers/net/ethernet/cadence/macb_main.c +6 -0
@@ -3329,6 +3329,8 @@ static int macb_open(struct net_device *netdev) goto pm_exit; } + bp->ctx->info = &bp->info; +/* RX buffers initialization */ bp->ctx->rx_buffer_size =macb_rx_buffer_size (bp, netdev->mtu); bp->ctx->rx_ring_size = bp->configured_rx_ring_size;
@@ -5273,6 +5275,7 @@ static int at91ether_open(struct net_device *netdev) ret = -ENOMEM ; goto pm_exit; } + bp->ctx->info = &bp->info;/* Clear internal statistics */ ctl =macb_readl (bp,NCR );
@@ -5995,6 +5998,7 @@ static int macb_probe(struct platform_device *pdev)u32 wtrmrk_rst_val;void __iomem *mem;struct macb *bp; +unsigned int q;int num_queues;bool native_io;int err, val;
@@ -6040,6 +6044,8 @@ static int macb_probe(struct platform_device *pdev) bp->netdev = netdev; bp->regs = mem; bp->native_io = native_io; +for (q =0 ; q <MACB_MAX_QUEUES ; q++) + bp->info.queue_stats[q] = &bp->queues[q].stats;if (native_io) { bp->macb_reg_readl = hw_readl_native; bp->macb_reg_writel = hw_writel_native;
Signature · 1 line
2.55.0
Théo Lebrun
maintainerPATCH v10 4/8 net: macb: change caps helpers signatures
In reply to Théo LebrunFor parallel MACB context to start becoming a reality, many functions will soon not have access to struct macb *bp. Those will still have access to caps through ctx->info->caps.
Change all caps helpers signatures, from taking struct macb *bp to taking struct macb_info *info. Info is accessible in both bp and ctx and it ensures type safety (versus passing raw u32 caps).
Function list:
macb_is_gem()
gem_has_ptp()
macb_dma64()
macb_dma_ptp()
macb_dma_desc_get_size()
macb_set_addr()
macb_get_addr()
macb_64b_desc()
macb_tx_unmap()
Note: drop macb_64b_desc(bp, ...) parameter; it is unused and it must be dropped as macb_{set,get}_addr() call macb_64b_desc().
--- drivers/net/ethernet/cadence/macb.h | 21 ++-- drivers/net/ethernet/cadence/macb_main.c | 159 ++++++++++++++++--------------- drivers/net/ethernet/cadence/macb_ptp.c | 8 +- 3 files changed, 98 insertions(+), 90 deletions(-)
drivers/net/ethernet/cadence/macb.h +11 -10
@@ -834,7 +834,7 @@*/ #define macb_or_gem_writel (__bp, __reg, __value) \ ({ \ - if (macb_is_gem((__bp))) \ + if (macb_is_gem(&(__bp)->info)) \ gem_writel((__bp), __reg, __value); \ else \ macb_writel((__bp), __reg, __value); \
@@ -843,7 +843,7 @@#define macb_or_gem_readl (__bp, __reg) \ ({ \ u32 __v; \ - if (macb_is_gem((__bp))) \ + if (macb_is_gem(&(__bp)->info)) \ __v = gem_readl((__bp), __reg); \ else \ __v = macb_readl((__bp), __reg); \
@@ -1473,14 +1473,15 @@ static inline void gem_ptp_do_txstamp(struct macb *bp, struct sk_buff *skb, strustatic inline void gem_ptp_do_rxstamp (struct macb *bp,struct sk_buff *skb,struct macb_dma_desc *desc) { }#endif -static inline bool macb_is_gem (struct macb *bp) +static inline bool macb_is_gem (const struct macb_info *info) { -return !!(bp->caps &MACB_CAPS_MACB_IS_GEM ); +return !!(info->caps &MACB_CAPS_MACB_IS_GEM ); } -static inline bool gem_has_ptp (struct macb *bp) +static inline bool gem_has_ptp (const struct macb_info *info) { -return IS_ENABLED (CONFIG_MACB_USE_HWSTAMP ) && (bp->caps &MACB_CAPS_GEM_HAS_PTP ); +return IS_ENABLED (CONFIG_MACB_USE_HWSTAMP ) && + (info->caps &MACB_CAPS_GEM_HAS_PTP ); }/* ENST Helper functions */
@@ -1496,16 +1497,16 @@ static inline u64 enst_max_hw_interval(u32 speed_mbps) ENST_TIME_GRANULARITY_NS * 1000, (speed_mbps)); } -static inline bool macb_dma64 (struct macb *bp) +static inline bool macb_dma64 (const struct macb_info *info) {return IS_ENABLED (CONFIG_ARCH_DMA_ADDR_T_64BIT ) && - bp->caps &MACB_CAPS_DMA_64B ; + info->caps &MACB_CAPS_DMA_64B ; } -static inline bool macb_dma_ptp (struct macb *bp) +static inline bool macb_dma_ptp (const struct macb_info *info) {return IS_ENABLED (CONFIG_MACB_USE_HWSTAMP ) && - bp->caps &MACB_CAPS_DMA_PTP ; + info->caps &MACB_CAPS_DMA_PTP ; } static inline void macb_queue_isr_clear(struct macb *bp,
drivers/net/ethernet/cadence/macb_main.c +83 -76
562 lines not on this page · raw message
drivers/net/ethernet/cadence/macb_ptp.c +4 -4
@@ -28,10 +28,10 @@static struct macb_dma_desc_ptp *macb_ptp_desc (struct macb *bp,struct macb_dma_desc *desc) { -if (!macb_dma_ptp (bp)) +if (!macb_dma_ptp (&bp->info))return NULL ; -if (macb_dma64 (bp)) +if (macb_dma64 (&bp->info))return (struct macb_dma_desc_ptp *) ((u8 *)desc +sizeof (struct macb_dma_desc ) +sizeof (struct macb_dma_desc_64 ));
@@ -380,7 +380,7 @@ int gem_get_hwtst(struct net_device *netdev,struct macb *bp =netdev_priv (netdev); *tstamp_config = bp->tstamp_config; -if (!macb_dma_ptp (bp)) +if (!macb_dma_ptp (&bp->info))return -EOPNOTSUPP ;return 0 ;
@@ -399,7 +399,7 @@ int gem_set_hwtst(struct net_device *netdev,u32 ncr_bits =0 ;u32 regval; -if (!macb_dma_ptp (bp)) +if (!macb_dma_ptp (&bp->info))return -EOPNOTSUPP ;switch (tstamp_config->tx_type) {
Signature · 1 line
2.55.0
Théo Lebrun
maintainerPATCH v10 5/8 net: macb: change function signatures to take contexts
In reply to Théo LebrunFor parallel MACB context to start become a reality, many functions need to stop operating on bp->ctx (the currently active context) and instead work on a context they get passed. That context might be
(1) the new one that is getting allocated and initialised, or,
(2) the old one to be freed.
To reduce bug surface area, taint those functions to *only* take a context struct macb_context *ctx and no struct macb *bp. That way, no bug of using bp->ctx instead of ctx will ever occur.
We also convert functions that take a struct macb_queue *queue to instead take struct macb_context *ctx, unsigned int q, with q indexing ctx->txq[] and ctx->rxq[].
Full list:
macb_adj_dma_desc_idx()
macb_tx_ring_wrap()
macb_tx_desc()
macb_rx_ring_wrap()
macb_rx_desc()
macb_get_addr()
gem_rx_refill()
macb_init_rx_ring()
gem_free_rx_buffers()
macb_free_rx_buffers()
macb_tx_ring_size_per_queue()
macb_rx_ring_size_per_queue()
macb_free()
gem_alloc_rx_buffers()
macb_alloc_rx_buffers()
macb_alloc()
gem_init_rx_ring()
gem_init_rings()
macb_init_rings()
Note about gem_rx_refill(): it ends with a netdev_vdbg() that prints the queue pointer. Change to print the queue index because we do not have access to the queue anymore.
Note: functions that operate on the interface during its normal lifetime do not need to be converted and have no risk of using the wrong context. We do not allow concurrent swaps. When interface is alive, there can only be one context alive.
--- drivers/net/ethernet/cadence/macb.h | 7 +- drivers/net/ethernet/cadence/macb_main.c | 391 ++++++++++++++++--------------- 2 files changed, 210 insertions(+), 188 deletions(-)
drivers/net/ethernet/cadence/macb.h +4 -3
@@ -1193,11 +1193,12 @@ static const struct gem_statistic queue_statistics[] = {struct macb ;struct macb_queue ; +struct macb_context ;struct macb_or_gem_ops { -int (*mog_alloc_rx_buffers)(struct macb *bp); -void (*mog_free_rx_buffers)(struct macb *bp); -int (*mog_init_rings)(struct macb *bp); +int (*mog_alloc_rx_buffers)(struct macb_context *ctx); +void (*mog_free_rx_buffers)(struct macb_context *ctx); +int (*mog_init_rings)(struct macb_context *ctx);int (*mog_rx)(struct macb_queue *queue,struct napi_struct *napi,int budget); };
drivers/net/ethernet/cadence/macb_main.c +206 -185
991 lines not on this page · raw message
Signature · 1 line
2.55.0
Théo Lebrun
maintainerPATCH v10 6/8 net: macb: introduce macb_context_alloc() helper
In reply to Théo LebrunMove the context allocation sequence from inline macb_open() to its own helper function called macb_context_alloc(). All ops doing context swapping (set_ringparam, change_mtu, etc) will use this helper.
--- drivers/net/ethernet/cadence/macb_main.c | 68 +++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 22 deletions(-)
drivers/net/ethernet/cadence/macb_main.c +46 -22
@@ -2972,6 +2972,43 @@ static int macb_alloc(struct macb_context *ctx)return -ENOMEM ; } +static struct macb_context *macb_context_alloc (struct macb *bp, +unsigned int mtu, +unsigned int rx_ring_size, +unsigned int tx_ring_size) +{ +struct macb_context *ctx; +int err; + + ctx =kzalloc_obj (*ctx); +if (!ctx) +return ERR_PTR (-ENOMEM ); + + ctx->info = &bp->info; + ctx->rx_buffer_size =macb_rx_buffer_size (bp, mtu); + ctx->rx_ring_size = rx_ring_size; + ctx->tx_ring_size = tx_ring_size; + + err =macb_alloc (ctx); +if (err) { +netdev_err (bp->netdev, +"Unable to allocate DMA memory (error %d)\n" , err); + goto free_ctx; + } + + err = bp->macbgem_ops.mog_init_rings (ctx); +if (err) + goto free_rings; + +return ctx; + +free_rings: +macb_free (ctx); +free_ctx: +kfree (ctx); +return ERR_PTR (err); +} +static int gem_init_rx_ring (struct macb_context *ctx,unsigned int q) {struct macb_rxq *rxq = &ctx->rxq[q];
@@ -3342,6 +3379,7 @@ static void macb_set_rx_mode(struct net_device *netdev)static int macb_open (struct net_device *netdev) {struct macb *bp =netdev_priv (netdev); +struct macb_context *ctx;int err;netdev_dbg (bp->netdev,"open\n" );
@@ -3350,30 +3388,18 @@ static int macb_open(struct net_device *netdev)if (err <0 )return err; -WRITE_ONCE (bp->ctx,kzalloc_obj (*bp->ctx)); -wmb ();/* ensure IRQ enabled at quiesce end read the new context */ -if (!bp->ctx) { - err = -ENOMEM ; + ctx =macb_context_alloc (bp, netdev->mtu, + bp->configured_rx_ring_size, + bp->configured_tx_ring_size); +if (IS_ERR (ctx)) { + err =PTR_ERR (ctx); + bp->ctx =NULL ; goto pm_exit; } - bp->ctx->info = &bp->info; +WRITE_ONCE (bp->ctx, ctx); +wmb ();/* ensure IRQ enabled at quiesce end read the new context */ -/* RX buffers initialization */ - bp->ctx->rx_buffer_size =macb_rx_buffer_size (bp, netdev->mtu); - bp->ctx->rx_ring_size = bp->configured_rx_ring_size; - bp->ctx->tx_ring_size = bp->configured_tx_ring_size; - - err =macb_alloc (bp->ctx); -if (err) { -netdev_err (netdev,"Unable to allocate DMA memory (error %d)\n" , - err); - goto free_ctx; - } - - err = bp->macbgem_ops.mog_init_rings (bp->ctx); -if (err) - goto free_rings;macb_init_buffers (bp);macb_quiesce_end (bp);
@@ -3407,9 +3433,7 @@ static int macb_open(struct net_device *netdev)macb_quiesce_start (bp);macb_reset_hw (bp); -free_rings:macb_free (bp->ctx); -free_ctx:kfree (bp->ctx); bp->ctx =NULL ; pm_exit:
Signature · 1 line
2.55.0
Théo Lebrun
maintainerPATCH v10 7/8 net: macb: use context swapping in .set_ringparam()
In reply to Théo Lebrunethtool_ops.set_ringparam() is implemented using the primitive close / update ring size / reopen sequence. Under memory pressure this does not
fly: we free our buffers at close and cannot reallocate new ones at open. Also, it triggers a slow PHY reinit.
Instead, exploit the new context mechanism and improve our sequence to:
- allocate a new context (including buffers) first
- if it fails, early return without any impact to the interface
- stop interface
- update global state (bp, netdev, etc)
- pass buffer pointers to the hardware
- start interface
- free old context.
The HW disable sequence is inspired by macb_reset_hw() but avoids
(1) setting NCR bit CLRSTAT and (2) clearing register PBUFRXCUT.
The HW re-enable sequence is inspired by macb_mac_link_up(), skipping over register writes which would be redundant (because values have not changed).
The generic context swapping parts are isolated into helper functions macb_context_swap_start|end(), reusable by other operations (change_mtu, set_channels, etc).
Introduce a new locking primitive (mac_cfg_lock mutex) to serialise swap with phylink MAC callbacks. Avoid stopping phylink to avoid a slow PHY retrain. We cannot sync to phylink ops using phydev->lock because it is not available in the SFP case. We cannot check link state using netif_carrier_ok() because we could race with its changes; so we use a redundant bp->link_up boolean that is mac_cfg_lock protected.
AT91 EMAC is handled differently as their buffer management is separate and they don't do NAPI. They must never call swap_start/end(). Anyway they do not implement set_ringparam (-EOPNOTSUPP) so we are safe.
--- drivers/net/ethernet/cadence/macb.h | 7 +- drivers/net/ethernet/cadence/macb_main.c | 188 +++++++++++++++++++++++++++---- 2 files changed, 175 insertions(+), 20 deletions(-)
drivers/net/ethernet/cadence/macb.h +6 -1
@@ -1358,6 +1358,8 @@ struct macb {struct macb_queue queues[MACB_MAX_QUEUES ];spinlock_t lock; +/* Serializes context swap against phylink MAC callbacks. */ +struct mutex mac_cfg_lock;struct clk *pclk;struct clk *hclk;struct clk *tx_clk;
@@ -1419,10 +1421,13 @@ struct macb {u32 tx_lpi_timer;/* ISR must not drive NAPI & BH mechanisms. True when the interface -* is closed. Protected by bp->lock. +* is closed or during context-swap. Protected by bp->lock. */ bool irq_quiesced; +/* Redundant to netif_carrier_ok(), but set under bp->mac_cfg_lock. */ +bool link_up; +u32 rx_intr_mask;struct macb_pm_data pm_data;
drivers/net/ethernet/cadence/macb_main.c +169 -19
307 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH net-next v10 7/8] net: macb: use context swapping in .set_ringparam()
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 0 · Low: 0
If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).
- [High] Use-after-free in the new live context swap.
--
net: macb: use context swapping in .set_ringparam()
This patch reworks macb_set_ringparam(). It now allocates a new context before stopping the interface, swaps it in and then frees the old one, instead of doing a full close/open. The generic swap logic is split into macb_context_swap_start() and macb_context_swap_end(), and a new mac_cfg_lock mutex serialises the swap against the phylink MAC callbacks.
Quoted 4 lines
drivers/net/ethernet/cadence/macb_main.c +0
-0
[ ... ]
Quoted 14 lines
drivers/net/ethernet/cadence/macb_main.c +10
-0@@ -3217,6 +3255,112 @@ static void macb_configure_dma(struct macb *bp) } } +static void macb_context_swap_start (struct macb *bp) +{ +struct macb_queue *queue; +unsigned long flags; +unsigned int q; +u32 ctrl; + +mutex_lock (&bp->mac_cfg_lock); + +macb_quiesce_start (bp);
[ ... ]
Quoted 3 lines
drivers/net/ethernet/cadence/macb_main.c +3
-0+static void macb_context_swap_end (struct macb *bp, +struct macb_context *new_ctx) +{
[ ... ]
Quoted 4 lines
drivers/net/ethernet/cadence/macb_main.c +4
-0+ old_ctx = bp->ctx; +WRITE_ONCE (bp->ctx, new_ctx); +wmb ();/* ensure IRQ enabled below read the new context */ +macb_init_buffers (bp);
[ ... ]
drivers/net/ethernet/cadence/macb_main.c static void macb_configure_dma(struct macb *bp) · line 3362
Quoted 7 lines
drivers/net/ethernet/cadence/macb_main.c +7
-0+mutex_unlock (&bp->mac_cfg_lock); + +/* Free old context. */ + +macb_free (old_ctx); +kfree (old_ctx); +}
[Severity: High]
Can a NAPI poll still be reading old_ctx when it gets freed here?
The swap depends on macb_quiesce_start() calling napi_disable() to drain NAPI. However, napi_disable() only waits for NAPIF_STATE_SCHED and NAPIF_STATE_NPSVC to clear, and napi_complete_done() clears SCHED before the poll callback returns. Documentation/networking/napi.rst notes that napi_disable() only waits for the ownership of the instance to be released, not for the poll method to exit.
Both poll functions keep reading the context after napi_complete_done() succeeds. In macb_rx_poll():
if (work_done < budget && napi_complete_done(napi, work_done)) {
queue_writel(queue, IER, bp->rx_intr_mask);
...
if (macb_rx_pending(queue)) {and macb_rx_pending() does:
struct macb_context *ctx = queue->bp->ctx; struct macb_rxq *rxq = macb_rxq(queue); ... entry = macb_rx_ring_wrap(ctx, rxq->tail); desc = macb_rx_desc(ctx, q, entry); ... return (desc->addr & MACB_BIT(RX_USED)) != 0;
macb_tx_poll() does the same through macb_tx_complete_pending(). That function reads queue->bp->ctx and the TX ring under tx_ptr_lock. The swap and free path takes neither tx_ptr_lock nor any other lock or RCU grace period that these helpers respect.
This looks like a possible interleaving:
poll CPUmacb_rx_poll()
napi_complete_done() /* clears SCHED */
macb_rx_pending()
ctx = queue->bp->ctx; /* old ctx */
<delayed>ethtool CPUmacb_set_ringparam()
macb_context_swap_start()
macb_quiesce_start()
napi_disable() /* returns, SCHED already clear */
macb_context_swap_end()
WRITE_ONCE(bp->ctx, new_ctx);
...
macb_free(old_ctx); /* rings NULLed and dma_free_coherent()ed */
kfree(old_ctx);poll CPU
desc = macb_rx_desc(ctx, q, entry); /* freed memory */
Here the poll CPU would dereference the kfree()d context, a NULL ring pointer, or freed coherent DMA memory. The delay could come from threaded NAPI, softirq preemption on PREEMPT_RT, interrupts or vCPU preemption. This can be triggered with ethtool -G while traffic is flowing.
The new irq_quiesced check in macb_tx_restart() does not seem to cover this. That helper runs before napi_complete_done() and is already protected by NAPI ownership.
macb_close() uses the same napi_disable-then-free pattern. This patch adds a new free-while-running site that is reachable during normal operation. The later patch "net: macb: use context swapping in .ndo_change_mtu()" reuses these helpers without adding any extra synchronization.
Would a synchronize_net() (or an equivalent grace period) before macb_free(old_ctx) be enough to close this window? Alternatively, the post-completion helpers could be made to check for an ongoing swap.
[ ... ]
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261001-macb-context-v10-0-beb541bbb7df%40bootlin.com
Théo Lebrun
maintainerRe: [PATCH net-next v10 7/8] net: macb: use context swapping in .set_ringparam()
Hello netdev-bot+sashiko,
Quoted 133 lines · CEST,
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 0 · Low: 0
If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).
- [High] Use-after-free in the new live context swap.
--
net: macb: use context swapping in .set_ringparam()
This patch reworks
macb_set_ringparam(). It now allocates a new context before stopping the interface, swaps it in and then frees the old one, instead of doing a full close/open. The generic swap logic is split intomacb_context_swap_start()andmacb_context_swap_end(), and a newmac_cfg_lockmutex serialises the swap against the phylink MAC callbacks.Quoted 4 lines
drivers/net/ethernet/cadence/macb_main.c +0
-0[ ... ]
Quoted 14 lines
drivers/net/ethernet/cadence/macb_main.c +10
-0@@ -3217,6 +3255,112 @@ static void macb_configure_dma(struct macb *bp) } } +static void macb_context_swap_start (struct macb *bp) +{ +struct macb_queue *queue; +unsigned long flags; +unsigned int q; +u32 ctrl; + +mutex_lock (&bp->mac_cfg_lock); + +macb_quiesce_start (bp);[ ... ]
Quoted 3 lines
drivers/net/ethernet/cadence/macb_main.c +3
-0+static void macb_context_swap_end (struct macb *bp, +struct macb_context *new_ctx) +{[ ... ]
Quoted 4 lines
drivers/net/ethernet/cadence/macb_main.c +4
-0+ old_ctx = bp->ctx; +WRITE_ONCE (bp->ctx, new_ctx); +wmb ();/* ensure IRQ enabled below read the new context */ +macb_init_buffers (bp);[ ... ]
drivers/net/ethernet/cadence/macb_main.c
Quoted 7 lines
drivers/net/ethernet/cadence/macb_main.c +7
-0+mutex_unlock (&bp->mac_cfg_lock); + +/* Free old context. */ + +macb_free (old_ctx); +kfree (old_ctx); +}[Severity: High]
Can a NAPI poll still be readingold_ctxwhen it gets freed here?The swap depends on
macb_quiesce_start()callingnapi_disable()to drain NAPI. However,napi_disable()only waits forNAPIF_STATE_SCHEDandNAPIF_STATE_NPSVCto clear, andnapi_complete_done()clears SCHED before the poll callback returns.Documentation/networking/napi.rstnotes thatnapi_disable()only waits for the ownership of the instance to be released, not for the poll method to exit.Both poll functions keep reading the context after
napi_complete_done()succeeds. Inmacb_rx_poll():if (work_done < budget && napi_complete_done(napi, work_done)) { queue_writel(queue, IER, bp->rx_intr_mask); ... if (macb_rx_pending(queue)) {and
macb_rx_pending()does:struct macb_context *ctx = queue->bp->ctx; struct macb_rxq *rxq = macb_rxq(queue); ... entry = macb_rx_ring_wrap(ctx, rxq->tail); desc = macb_rx_desc(ctx, q, entry); ... return (desc->addr & MACB_BIT(RX_USED)) != 0;
macb_tx_poll()does the same throughmacb_tx_complete_pending(). That function readsqueue->bp->ctxand the TX ring undertx_ptr_lock. The swap and free path takes neithertx_ptr_locknor any other lock or RCU grace period that these helpers respect.This looks like a possible interleaving:
poll CPU
macb_rx_poll()
napi_complete_done()/* clears SCHED */
macb_rx_pending()ctx = queue->bp->ctx; /* old ctx */ <delayed>ethtool CPU
macb_set_ringparam()
macb_context_swap_start()
macb_quiesce_start()
napi_disable()/* returns, SCHED already clear */
macb_context_swap_end()WRITE_ONCE(bp->ctx, new_ctx); ... macb_free(old_ctx); /* rings NULLed and dma_free_coherent()ed */ kfree(old_ctx);poll CPU
desc =macb_rx_desc(ctx, q, entry); /* freed memory */Here the poll CPU would dereference the kfree()d context, a NULL ring pointer, or freed coherent DMA memory. The delay could come from threaded NAPI, softirq preemption on
PREEMPT_RT, interrupts or vCPU preemption. This can be triggered with ethtool -G while traffic is flowing.The new
irq_quiescedcheck inmacb_tx_restart()does not seem to cover this. That helper runs beforenapi_complete_done()and is already protected by NAPI ownership.
Quoted 8 lines
macb_close()uses the same napi_disable-then-free pattern. This patch adds a new free-while-running site that is reachable during normal operation. The later patch "net: macb: use context swapping in .ndo_change_mtu()" reuses these helpers without adding any extra synchronization.Would a
synchronize_net()(or an equivalent grace period) beforemacb_free(old_ctx)be enough to close this window? Alternatively, the post-completion helpers could be made to check for an ongoing swap.
Technically this is possible. To get it in practice, you would have to
- have no phylink attached
- be running a PREEMPT_RT kernel would help a lot
- be unlucky
I'm fixing it with the recommended synchronize_net(), after having checked that we are not the first ones. A few commits do justify the same bug for using synchronize_net().
Looked through the results from
⟩ git log -S synchronize_net net-next/main drivers/net/ethernet/
For example, here is the simplest precedent I could find:
commit eb41a264a3a576dc040ee37c3d9d6b7e2d9be968
Author: Carolina Jubran <[email protected]> Date: Thu Jul 10 16:53:43 2025 +0300
net/mlx5e: Fix race between DIM disable and net_dim()
There's a race between disabling DIM and NAPI callbacks using the dim pointer on the RQ or SQ.
If NAPI checks the DIM state bit and sees it still set, it assumes rq->dim or sq->dim is valid. But if DIM gets disabled right after that check, the pointer might already be set to NULL, leading to a NULL pointer dereference in net_dim().
Fix this by calling synchronize_net() before freeing the DIM context. This ensures all in-progress NAPI callbacks are finished before the pointer is cleared.
Kernel log:
BUG: kernel NULL pointer dereference, address: 0000000000000000 [...]
drivers/net/ethernet/mellanox/mlx5/core/en_dim.c +2 -2
@@ -113,7 +113,7 @@ int mlx5e_dim_rx_change(struct mlx5e_rq *rq, bool enable)__set_bit (MLX5E_RQ_STATE_DIM , &rq->state); }else {__clear_bit (MLX5E_RQ_STATE_DIM , &rq->state); - +synchronize_net ();mlx5e_dim_disable (rq->dim); rq->dim =NULL ; }
@@ -140,7 +140,7 @@ int mlx5e_dim_tx_change(struct mlx5e_txqsq *sq, bool enable)__set_bit (MLX5E_SQ_STATE_DIM , &sq->state); }else {__clear_bit (MLX5E_SQ_STATE_DIM , &sq->state); - +synchronize_net ();mlx5e_dim_disable (sq->dim); sq->dim =NULL ; }
Thanks,
--
Théo Lebrun, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
Théo Lebrun
maintainerPATCH v10 8/8 net: macb: use context swapping in .ndo_change_mtu()
In reply to Théo LebrunUse newly introduced context buffer management to implement .ndo_change_mtu() as a context swap: allocate new context -> reconfigure HW -> free old context.
This resists memory pressure well by failing without closing the interface and it is much faster by avoiding PHY reinit.
AT91 EMAC is handled differently as their buffer management is separate and they don't do NAPI. They cannot land in macb_change_mtu as they use a different ndo struct. We still defensively protect against it in code.
--- drivers/net/ethernet/cadence/macb_main.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-)
drivers/net/ethernet/cadence/macb_main.c +20 -2
@@ -3624,11 +3624,29 @@ static int macb_close(struct net_device *netdev)static int macb_change_mtu (struct net_device *netdev,int new_mtu) { -if (netif_running (netdev)) -return -EBUSY ; +struct macb *bp =netdev_priv (netdev); +bool running =netif_running (netdev); +struct macb_context *new_ctx; + +if (running) { +/* Context swapping is not supported for AT91. */ +if (bp->caps &MACB_CAPS_MACB_IS_EMAC ) +return -EBUSY ; + + new_ctx =macb_context_alloc (bp, new_mtu, + bp->configured_rx_ring_size, + bp->configured_tx_ring_size); +if (IS_ERR (new_ctx)) +return PTR_ERR (new_ctx); + +macb_context_swap_start (bp); + }WRITE_ONCE (netdev->mtu, new_mtu); +if (running) +macb_context_swap_end (bp, new_ctx); +return 0 ; }
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH net-next v10 8/8] net: macb: use context swapping in .ndo_change_mtu()
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 1 · Medium: 0 · Low: 0
If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).
- [High] A live MTU change can free the old context while a NAPI poll on another CPU is still reading it.
--
net: macb: use context swapping in .ndo_change_mtu()
This patch changes .ndo_change_mtu() so that it works on a running interface. It allocates a new context, quiesces and reconfigures the hardware, then frees the old context. Before this patch the call returned -EBUSY when the interface was up. AT91 EMAC still returns -EBUSY.
Quoted 10 lines
drivers/net/ethernet/cadence/macb_main.c +0
-2@@ -3624,11 +3624,29 @@ static int macb_close(struct net_device *netdev)static int macb_change_mtu (struct net_device *netdev,int new_mtu) { -if (netif_running (netdev)) -return -EBUSY ;
[ ... ]
drivers/net/ethernet/cadence/macb_main.c static int macb_close(struct net_device *netdev) · line 3648
Quoted 13 lines
drivers/net/ethernet/cadence/macb_main.c +10
-0+ new_ctx =macb_context_alloc (bp, new_mtu, + bp->configured_rx_ring_size, + bp->configured_tx_ring_size); +if (IS_ERR (new_ctx)) +return PTR_ERR (new_ctx); + +macb_context_swap_start (bp); + }WRITE_ONCE (netdev->mtu, new_mtu); +if (running) +macb_context_swap_end (bp, new_ctx);
[Severity: High]
Can a live MTU change free the old context while a NAPI poll on another CPU is still reading it?
Both poll functions keep using context memory after napi_complete_done(). In macb_rx_poll():
if (work_done < budget && napi_complete_done(napi, work_done)) {
queue_writel(queue, IER, bp->rx_intr_mask);
...
if (macb_rx_pending(queue)) {macb_rx_pending() then reads bp->ctx and rxq->tail/prepared_head, and dereferences a descriptor in the rx ring:
struct macb_context *ctx = queue->bp->ctx;
struct macb_rxq *rxq = macb_rxq(queue);
...
desc = macb_rx_desc(ctx, q, entry);
...
return (desc->addr & MACB_BIT(RX_USED)) != 0;macb_tx_poll() does the same thing. After napi_complete_done() it calls macb_tx_complete_pending(), which reads:
if (macb_tx_desc(ctx, q, txq->tail)->ctrl & MACB_BIT(TX_USED))
napi_complete_done() clears NAPIF_STATE_SCHED. napi_disable() only waits for the instance's ownership bits to clear, not for the poll callback to return. Documentation/networking/napi.rst says drivers should not touch data structures after napi_complete_done() for this reason.
One possible interleaving:
CPU A (softirq)macb_rx_poll()
napi_complete_done() /* SCHED cleared */
CPU Bmacb_change_mtu()
macb_context_swap_start()
macb_quiesce_start()
synchronize_irq() ...
napi_disable() /* returns immediately */
macb_context_swap_end()
WRITE_ONCE(bp->ctx, new_ctx);
...
macb_free(old_ctx); /* dma_free_coherent() of rings */
kfree(old_ctx);CPU A
macb_rx_pending()
reads the freed ctx and descriptor ring
As far as I can see, nothing on the swap path closes this window. There is no synchronize_net() or synchronize_rcu(), and no tx_ptr_lock or bp->lock handshake with the poll tail.
On non-coherent ARM/arm64 SoCs, coherent DMA memory is usually remapped and unmapped on free, so this read could fault in softirq context. The window is short on !PREEMPT_RT. It can be much longer under PREEMPT_RT, threaded NAPI, or vCPU preemption.
Before this patch, macb_change_mtu() never reached the swap path on a running interface. Any CAP_NET_ADMIN "ip link set mtu" while traffic is flowing now gets there.
The same window also seems to exist through .set_ringparam(), which an earlier patch in this series ("net: macb: use context swapping in .set_ringparam()") converted to context swapping. Would a grace period such as synchronize_net() before freeing old_ctx in macb_context_swap_end() fix both paths? So would making the poll tails avoid touching the context after napi_complete_done().
Quoted 3 lines
drivers/net/ethernet/cadence/macb_main.c +1
-0+return 0 ; }
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261001-macb-context-v10-0-beb541bbb7df%40bootlin.com