7.3.7-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 574/1005 kprobes: Fix double free and NULL deref in unregister_kretprobes()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 2053bac1d6e47b33fa2e570c87518395e64f7da0 upstream.
In unregister_kretprobes(), if __unregister_kprobe_top() returns an error (e.g., if the kretprobe was not registered or was already unregistered), rethook_free(rps[i]->rh) or rcu_assign_pointer(rps[i]->rph->rp, NULL) is still executed. For rethook-based kretprobes, calling rethook_free() on an already-freed rethook causes a double-free / list corruption in RCU. For legacy kretprobes, rps[i]->rph is NULL after previous cleanup, resulting in a NULL pointer dereference.
Skip rethook_free() and rph cleanup if __unregister_kprobe_top() fails, and clear rps[i]->rh after synchronize_rcu() has waited for in-flight pre_handler_kretprobe() invocations to complete.
--- kernel/kprobes.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/kprobes.c +6 -2
@@ -2370,8 +2370,10 @@ void unregister_kretprobes(struct kretprfor (i =0 ; i < num; i++) {guard (mutex)(&kprobe_mutex); -if (__unregister_kprobe_top (&rps[i]->kp) <0 ) +if (__unregister_kprobe_top (&rps[i]->kp) <0 ) { rps[i]->kp.addr =NULL ; +continue ; + }#ifdef CONFIG_KRETPROBE_ON_RETHOOK rethook_free (rps[i]->rh);#else
@@ -2383,7 +2385,9 @@ void unregister_kretprobes(struct kretprfor (i =0 ; i < num; i++) {if (rps[i]->kp.addr) {__unregister_kprobe_bottom (&rps[i]->kp); -#ifndef CONFIG_KRETPROBE_ON_RETHOOK +#ifdef CONFIG_KRETPROBE_ON_RETHOOK + rps[i]->rh =NULL ; +#else free_rp_inst (rps[i]);#endif }
Greg Kroah-Hartman
maintainerPATCH 575/1005 kprobes: Validate re-registration earlier in register_kretprobe()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit a553b499f22bf054964d4fd16d136f3d4f836c23 upstream.
register_kretprobe() only checked for re-registration if rp->kp.addr was specified, skipping the check when rp was registered with symbol_name and rp->kp.addr was NULL. In that scenario, register_kretprobe() proceeded to allocate a new rethook (or kretprobe holder), and when register_kprobe(&rp->kp) subsequently failed due to re-registration, the error path freed and NULL-ed rp->rh (or rp->rph) on the still-active kretprobe, leading to NULL pointer dereferences when the active probe was hit.
Resolve the target address via _kprobe_addr() up-front and check whether the probe is already registered at that address via check_kprobe_rereg_at() before allocating any resources, and drop the WARN_ON_ONCE() in the re-registration check now that re-registration is gracefully detected and rejected.
--- kernel/kprobes.c | 72 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 40 insertions(+), 32 deletions(-)
kernel/kprobes.c +40 -32
@@ -1558,52 +1558,61 @@ _kprobe_addr(kprobe_opcode_t *addr, consreturn addr; } -static kprobe_opcode_t *kprobe_addr (struct kprobe *p) -{ -bool on_func_entry; - -return _kprobe_addr (p->addr, p->symbol_name, p->offset, &on_func_entry); -} -/* * Check the 'p' is valid and return the aggregator kprobe * at the same address. */ -static struct kprobe *__get_valid_kprobe (struct kprobe *p) +static struct kprobe *__get_valid_kprobe_at (struct kprobe *p,kprobe_opcode_t *addr) { +struct hlist_head *head;struct kprobe *ap, *list_p;lockdep_assert_held (&kprobe_mutex); - ap =get_kprobe (p->addr); -if (unlikely (!ap)) +if (unlikely (!addr))return NULL ; -if (p == ap) -return ap; - -list_for_each_entry (list_p, &ap->list, list) -if (list_p == p) -/* kprobe p is a valid probe */ + head = &kprobe_table[hash_ptr (addr,KPROBE_HASH_BITS )]; +hlist_for_each_entry_rcu (ap, head, hlist, +lockdep_is_held (&kprobe_mutex)) { +if (ap == p) { + p->addr = addr;return ap; + } +if (ap->addr == addr &&kprobe_aggrprobe (ap)) { +list_for_each_entry (list_p, &ap->list, list) { +if (list_p == p) { + p->addr = addr; +return ap; + } + } + } + }return NULL ; } -/* -* Warn and return error if the kprobe is being re-registered since -* there must be a software bug. -*/ -static inline int warn_kprobe_rereg (struct kprobe *p) +static inline struct kprobe *__get_valid_kprobe (struct kprobe *p) +{ +return __get_valid_kprobe_at (p, p->addr); +} + +/* Return error if the kprobe is being re-registered */ +static inline int check_kprobe_rereg_at (struct kprobe *p,kprobe_opcode_t *addr) {guard (mutex)(&kprobe_mutex); -if (WARN_ON_ONCE (__get_valid_kprobe (p))) +if (__get_valid_kprobe_at (p, addr))return -EINVAL ;return 0 ; } +static inline int check_kprobe_rereg (struct kprobe *p) +{ +return check_kprobe_rereg_at (p, p->addr); +} +static int check_ftrace_location (struct kprobe *p) {unsigned long addr = (unsigned long )p->addr;
@@ -1734,7 +1743,7 @@ int register_kprobe(struct kprobe *p)return PTR_ERR (addr); p->addr = addr; - ret =warn_kprobe_rereg (p); + ret =check_kprobe_rereg (p);if (ret)return ret;
@@ -2270,20 +2279,19 @@ int register_kretprobe(struct kretprobeint ret;int i;void *addr; +bool on_func_entry; - ret =kprobe_on_func_entry (rp->kp.addr, rp->kp.symbol_name, rp->kp.offset); -if (ret) -return ret; + addr =_kprobe_addr (rp->kp.addr, rp->kp.symbol_name, rp->kp.offset, &on_func_entry); +if (IS_ERR (addr)) +return PTR_ERR (addr); + +if (!on_func_entry) +return -EINVAL ; -/* If only 'rp->kp.addr' is specified, check reregistering kprobes */ -if (rp->kp.addr &&warn_kprobe_rereg (&rp->kp)) +if (check_kprobe_rereg_at (&rp->kp, addr))return -EINVAL ;if (kretprobe_blacklist_size) { - addr =kprobe_addr (&rp->kp); -if (IS_ERR (addr)) -return PTR_ERR (addr); -for (i =0 ; kretprobe_blacklist[i].name !=NULL ; i++) {if (kretprobe_blacklist[i].addr == addr)return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 576/1005 mmc: jz4740: Remove the host before resetting the controller
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Olivier Louvignes <[email protected]>
commit 6b8b1e8827837bf4cf1f87219038fddae9e81b0b upstream.
jz4740_mmc_remove() masks every interrupt and resets the controller before mmc_remove_host(), which removes the card and lets the card's driver send its last commands. Those commands then run on a controller that was just reset, and can wait out the driver's 5 s request timeout.
With an SDIO card that cost 5 s on every unbind: on a HiBy R1 (Ingenic X1600, a BCM43430A1 driven by brcmfmac), the CMD52 that sdio_release_irq() sends from brcmfmac's remove waited 5.1 s. The command had finished (END_CMD_RES set in MSC_STAT), but MSC_IMASK read 0xffffffff although the request had unmasked END_CMD_RES. MSC_STAT can still show IS_RESETTING after jz4740_mmc_reset() returns, so the reset most likely completed after that write and undid it.
Remove the host first, then quiesce the controller, as other host drivers do. On the R1, unbinding the Wi-Fi's MSC now takes 0.65 s.
--- drivers/mmc/host/jz4740_mmc.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/mmc/host/jz4740_mmc.c +3 -2
@@ -1151,12 +1151,13 @@ static void jz4740_mmc_remove(struct pla {struct jz4740_mmc_host *host =platform_get_drvdata (pdev); +/* The card's driver may still send commands as it goes */ +mmc_remove_host (host->mmc); +timer_delete_sync (&host->timeout_timer);jz4740_mmc_set_irq_enabled (host,0xff , false);jz4740_mmc_reset (host); -mmc_remove_host (host->mmc); -free_irq (host->irq, host);if (host->use_dma)
Greg Kroah-Hartman
maintainerPATCH 577/1005 mmc: sdhci-brcmstb: dont log an error for missing BOOT registers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit cf4a8d8b82db7f8e88e6ef4f3020a72860a9c440 upstream.
The BOOT register range is optional: the probe function ignores a failure to map it and the suspend/resume code checks for NULL. It is mapped with devm_platform_get_and_ioremap_resource(), though, which calls dev_err_probe() when the resource does not exist. Every non-removable host without a third reg entry therefore logs an error at probe time and then works normally.
The binding only describes the "host" and "cfg" ranges, so this is the case for the in-tree users. On the Raspberry Pi 5 family (BCM2712), where the SDIO host of the Wi-Fi module is non-removable, each boot prints:
sdhci-brcmstb 1001100000.mmc: error -EINVAL: invalid resource (null)
Look the resource up with platform_get_resource() first and map it only when it is present. Hosts that do have the range are mapped by the same two calls as before.
--- drivers/mmc/host/sdhci-brcmstb.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-)
drivers/mmc/host/sdhci-brcmstb.c +8 -3
@@ -491,6 +491,7 @@ static int sdhci_brcmstb_probe(struct plstruct sdhci_brcmstb_priv *priv;u32 actual_clock_mhz;struct sdhci_host *host; +struct resource *boot_res;struct clk *clk;struct clk *base_clk =NULL ;int res;
@@ -534,9 +535,13 @@ static int sdhci_brcmstb_probe(struct pl/* map non-standard BOOT registers if present */ if (host->mmc->caps &MMC_CAP_NONREMOVABLE ) { - priv->boot_regs =devm_platform_get_and_ioremap_resource (pdev,2 ,NULL ); -if (IS_ERR (priv->boot_regs)) - priv->boot_regs =NULL ; + boot_res =platform_get_resource (pdev,IORESOURCE_MEM ,2 ); +if (boot_res) { + priv->boot_regs =devm_ioremap_resource (&pdev->dev, + boot_res); +if (IS_ERR (priv->boot_regs)) + priv->boot_regs =NULL ; + } }/*
Greg Kroah-Hartman
maintainerPATCH 578/1005 mmc: sunxi: fix clock and runtime PM leaks on probe failure
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anfernee Cao <[email protected]>
commit e35e360bd66898a977c296ab71fe4bae17ddceb7 upstream.
sunxi_mmc_resource_request() enables the bus, card, output and sample clocks before returning. Several failure paths later in sunxi_mmc_probe() leave them running:
- If devm_request_threaded_irq() fails, the clocks enabled by sunxi_mmc_enable() are never disabled.
- If dma_alloc_coherent(), mmc_of_parse() or sunxi_mmc_init_host() fails, probe only frees the DMA buffer and the mmc_host.
- If mmc_add_host() fails, runtime PM has already been enabled, but pm_runtime_disable() is never called.
Besides leaking the clocks, this leaves the clock enable counts unbalanced, so a reprobe (for example after -EPROBE_DEFER) calls clk_prepare_enable() on the same clocks again.
Disable the IRQ and the clocks in the probe error path, and disable runtime PM on the mmc_add_host() failure path. Also handle a failure of devm_request_threaded_irq() in sunxi_mmc_resource_request().
Tested with QEMU's orangepi-pc machine: with forced sunxi_mmc_init_host() and mmc_add_host() failures the MMC clocks stay disabled in clk_summary, and a normal probe with an emulated SD card still works.
This issue was found by manual code inspection.
--- drivers/mmc/host/sunxi-mmc.c | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-)
drivers/mmc/host/sunxi-mmc.c +18 -6
@@ -1354,8 +1354,13 @@ static int sunxi_mmc_resource_request(st goto error_disable_mmc; } -return devm_request_threaded_irq (&pdev->dev, host->irq, sunxi_mmc_irq, - sunxi_mmc_handle_manual_stop,0 ,"sunxi-mmc" , host); + ret =devm_request_threaded_irq (&pdev->dev, host->irq, sunxi_mmc_irq, + sunxi_mmc_handle_manual_stop,0 , +"sunxi-mmc" , host); +if (ret) + goto error_disable_mmc; + +return 0 ; error_disable_mmc:sunxi_mmc_disable (host);
@@ -1385,9 +1390,11 @@ static int sunxi_mmc_probe(struct platfo host->sg_cpu =dma_alloc_coherent (&pdev->dev,PAGE_SIZE , &host->sg_dma,GFP_KERNEL ); -if (!host->sg_cpu) -return dev_err_probe (&pdev->dev, -ENOMEM , -"Failed to allocate DMA descriptor mem\n" ); +if (!host->sg_cpu) { + ret =dev_err_probe (&pdev->dev, -ENOMEM , +"Failed to allocate DMA descriptor mem\n" ); + goto error_disable_mmc; + }if (host->cfg->ccu_has_timings_switch) {/*
@@ -1467,7 +1474,7 @@ static int sunxi_mmc_probe(struct platfo ret =mmc_add_host (mmc);if (ret) - goto error_free_dma; + goto error_disable_rpm; dev_info(&pdev->dev, "initialized, max. request size: %u KB%s\n", mmc->max_req_size >> 10,
@@ -1475,8 +1482,13 @@ static int sunxi_mmc_probe(struct platforeturn 0 ; +error_disable_rpm: +pm_runtime_disable (&pdev->dev); error_free_dma:dma_free_coherent (&pdev->dev,PAGE_SIZE , host->sg_cpu, host->sg_dma); +error_disable_mmc: +disable_irq (host->irq); +sunxi_mmc_disable (host);return ret; }
Greg Kroah-Hartman
maintainerPATCH 579/1005 mmc: mmci: fix DMA channel leak when mmc_add_host() fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anfernee Cao <[email protected]>
commit 2d8927fadbf95e2d2dfa95bcc73882d6e19c2ce4 upstream.
mmci_probe() calls mmci_dma_setup(), which acquires the RX and TX DMA channels via dma_request_chan(). These channels are not managed by devres, and are released only by mmci_dma_release().
If the following mmc_add_host() fails, probe jumps to the clk_disable label, which only disables the clock. As probe then fails, mmci_remove() is never called, so both DMA channels are leaked.
Release them by adding a dedicated unwind label, reached only after mmci_dma_setup().
This issue was found by manual code inspection.
--- drivers/mmc/host/mmci.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/mmc/host/mmci.c +3 -1
@@ -2477,11 +2477,13 @@ static int mmci_probe(struct amba_device ret =mmc_add_host (mmc);if (ret) - goto clk_disable; + goto dma_release;pm_runtime_put (&dev->dev);return 0 ; +dma_release: +mmci_dma_release (host); clk_disable:clk_disable_unprepare (host->clk);return ret;
Greg Kroah-Hartman
maintainerPATCH 580/1005 mmc: omap: synchronize clock timer before disabling fclk
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Runyu Xiao <[email protected]>
commit c931c51681e33b24bc8d65c6df35b70e1827daa2 upstream.
mmc_omap_select_slot() removes clk_timer with timer_delete() before switching slots and changing the functional clock state. timer_delete() only removes a pending timer and does not wait for a callback that is already running.
If mmc_omap_clk_timer() is already running, it can therefore call mmc_omap_fclk_enable() while the request or slot-switch path changes the same clock state. During host removal, the same window can overlap the final clock shutdown.
Use timer_delete_sync() so the callback has completed before slot switching or changing the functional clock state. Keep the timer restartable for normal request handling.
--- drivers/mmc/host/omap.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/mmc/host/omap.c +2 -2
@@ -214,7 +214,7 @@ static void mmc_omap_select_slot(struct host->mmc = slot->mmc;spin_unlock_irqrestore (&host->slot_lock, flags); no_claim: -timer_delete (&host->clk_timer); +timer_delete_sync (&host->clk_timer);if (host->current_slot != slot || !claimed)mmc_omap_fclk_offdelay (host->current_slot);
@@ -273,7 +273,7 @@ static void mmc_omap_release_slot(struct/* Keeps clock running for at least 8 cycles on valid freq */ mod_timer (&host->clk_timer, jiffies +HZ /10 ); else { -timer_delete (&host->clk_timer); +timer_delete_sync (&host->clk_timer);mmc_omap_fclk_offdelay (slot);mmc_omap_fclk_enable (host,0 ); }
Greg Kroah-Hartman
maintainerPATCH 581/1005 mmc: sdhci-esdhc-imx: map unsupported driver type to Type B
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Ray <[email protected]>
commit d35d93c2902592a84347a15deac4d67a323694c9 upstream.
Since commit 5a52c5701a67 ("mmc: core: Fix host controller programming for fixed driver type"), the eMMC driver strength is passed directly to mmc_set_driver_type(), which propagates the value through ios.drv_type all the way to sdhci_set_ios(). For value 4, SDHCI correctly warns:
mmc2: invalid driver type, default to driver type B
The host driver type has no effect on this controller: esdhc_writew_le() never programs the driver-type field of SDHCI_HOST_CONTROL2. Hook set_ios() and force drv_type to the always-valid Type B, so that SDHCI never sees an unsupported value.
Tested on i.MX8MP (usdhc3, eMMC in HS400) with fixed-emmc-driver-type = <4>: the warning is gone and the HS_TIMING register contains 0x43 as expected.
--- drivers/mmc/host/sdhci-esdhc-imx.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
drivers/mmc/host/sdhci-esdhc-imx.c +17 -0
@@ -1142,6 +1142,20 @@ static void esdhc_reset_tuning(struct sd } } +static void sdhci_esdhc_imx_set_ios (struct mmc_host *mmc,struct mmc_ios *ios) +{ +/* +* This controller has no driver-type control: esdhc_writew_le() +* discards the driver-type field when writing SDHCI_HOST_CONTROL2. +* The programmed value is therefore irrelevant, but SDHCI rejects +* non-SD values such as 4 (eMMC 40 ohm, from fixed-emmc-driver-type). +* Force an always-valid Type B. +*/ + ios->drv_type =MMC_SET_DRIVER_TYPE_B ; + +sdhci_set_ios (mmc, ios); +} +static void usdhc_init_card (struct mmc_host *mmc,struct mmc_card *card) {struct sdhci_host *host =mmc_priv (mmc);
@@ -1952,6 +1966,9 @@ static int sdhci_esdhc_imx_probe(struct host->max_timeout_count =0xF ; } +/* No SDHCI driver type control */ + host->mmc_host_ops.set_ios = sdhci_esdhc_imx_set_ios; +if (imx_data->socdata->flags &ESDHC_FLAG_MAN_TUNING ) sdhci_esdhc_ops.platform_execute_tuning = esdhc_executing_tuning;
Greg Kroah-Hartman
maintainerPATCH 582/1005 mmc: meson-gx: report busy from DAT0 alone
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Velkov <[email protected]>
commit 318fdb75f4dc9d18ae621b9fb25eb11160c95649 upstream.
meson_mmc_card_busy() reports busy only while DAT0..3 are all low. A busy card drives DAT0 low and leaves DAT1..3 to the pull-ups, and the callback is defined as "Check if the card is pulling dat[0] low". So a busy card is reported free, and the core, which prefers card_busy over CMD13 in mmc_busy_cb(), stops polling after CMD6 and erase at once. The controller hides this on R1b commands, where it waits for busy itself. Once max_busy_timeout is reported, the core sends the longer waits, the 120 s BKOPS and 240 s sanitize switches among them, as R1 and has only the polling left.
Look at DAT0 only, as sdhci_card_busy() does. The checks around the voltage switch in mmc_set_uhs_voltage() still hold: the card drives DAT0..3 low together after CMD11 and keeps them low together on failure.
--- drivers/mmc/host/meson-gx-mmc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/mmc/host/meson-gx-mmc.c +2 -2
@@ -1079,8 +1079,8 @@ static int meson_mmc_card_busy(struct mm regval =readl (host->regs +SD_EMMC_STATUS ); -/* We are only interrested in lines 0 to 3, so mask the other ones */ -return !(FIELD_GET (STATUS_DATI , regval) &0xf ); +/* The card signals busy on DAT0 alone. */ +return !(FIELD_GET (STATUS_DATI , regval) &BIT (0 )); }static int meson_mmc_voltage_switch (struct mmc_host *mmc,struct mmc_ios *ios)
Greg Kroah-Hartman
maintainerPATCH 583/1005 mmc: meson-gx: honour the busy timeout for R1b commands
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Velkov <[email protected]>
commit 7e3cc541aa5855bc36e6cbffa82efc2795955a10 upstream.
For a command without data the driver programs a fixed 1024 ms into the CMD_CFG timeout field, and for R1b the controller waits for the card to release busy within that time. The core sends erase and cache flush as R1b with busy timeouts of up to 60 s and 30 s, and the controller gives up after one second:
mmc_erase: erase error -110, status 0x0
mmc1: cache flush error -110
Program the timeout from cmd->busy_timeout, kept between 1024 ms, the fixed value until now, and 32768 ms, the most the field holds, and rounded up to a power of two. The clamp comes first: MMC_IOC_CMD passes cmd_timeout_ms from user space straight into busy_timeout, and roundup_pow_of_two() of a value above 2^31 does not fit in unsigned int. sdhci takes its command timeout from cmd->busy_timeout in the same way.
--- drivers/mmc/host/meson-gx-mmc.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-)
drivers/mmc/host/meson-gx-mmc.c +15 -1
@@ -214,6 +214,20 @@ static unsigned int meson_mmc_get_timeoureturn min (timeout,32768U );/* max. 2^15 ms */ } +/* For R1b the controller waits for busy to be released within this timeout. */ +static unsigned int meson_mmc_get_cmd_timeout_msecs (struct mmc_command *cmd) +{ +unsigned int timeout = cmd->busy_timeout; + +if (!timeout) +return SD_EMMC_CMD_TIMEOUT ; + + timeout = clamp_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT, +SD_EMMC_CMD_TIMEOUT_MAX ); + +return roundup_pow_of_two (timeout); +} +static struct mmc_command *meson_mmc_get_next_command (struct mmc_command *cmd) {if (cmd->opcode ==MMC_SET_BLOCK_COUNT && !cmd->error)
@@ -840,7 +854,7 @@ static void meson_mmc_start_cmd(struct m cmd_data = host->bounce_dma_addr &CMD_DATA_MASK ; }else { cmd_cfg |=FIELD_PREP (CMD_CFG_TIMEOUT_MASK , -ilog2 (SD_EMMC_CMD_TIMEOUT )); +ilog2 (meson_mmc_get_cmd_timeout_msecs (cmd))); }/* Last descriptor */
Greg Kroah-Hartman
maintainerPATCH 584/1005 mmc: meson-gx: report the longest busy wait the controller can do
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Velkov <[email protected]>
commit 18e9f7fb05ada68d491ff49165b9644f790e0e0c upstream.
The driver does not set max_busy_timeout, so the core takes the host for one that can wait for busy indefinitely and sends erase and cache flush as R1b with busy timeouts of up to 60 s and 30 s. The CMD_CFG timeout field holds at most 32768 ms, so the controller times out first.
Report 32768 ms as max_busy_timeout. The core then sizes discards to fit and, for a longer wait, sends R1 and polls for busy itself.
--- drivers/mmc/host/meson-gx-mmc.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/mmc/host/meson-gx-mmc.c +3 -0
@@ -1180,6 +1180,9 @@ static int meson_mmc_probe(struct platfo mmc->caps |=MMC_CAP_CMD23 ; +/* The longest busy wait the CMD_CFG timeout field can hold. */ + mmc->max_busy_timeout =SD_EMMC_CMD_TIMEOUT_MAX ; +if (mmc->caps &MMC_CAP_SDIO_IRQ ) mmc->caps2 |=MMC_CAP2_SDIO_IRQ_NOTHREAD ;
Greg Kroah-Hartman
maintainerPATCH 585/1005 mmc: meson-gx: name the limit of the CMD_CFG timeout field
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Velkov <[email protected]>
commit e1644210d15f7f8adbe6315199b4b73bead63a2c upstream.
The data timeout is capped at a literal 32768 ms with a comment next to it. Give the limit a name beside the other timeout constants.
--- drivers/mmc/host/meson-gx-mmc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/mmc/host/meson-gx-mmc.c +2 -1
@@ -125,6 +125,7 @@#define SD_EMMC_CFG_RESP_TIMEOUT 256/* in clock cycles */ #define SD_EMMC_CMD_TIMEOUT 1024/* in ms */ #define SD_EMMC_CMD_TIMEOUT_DATA 4096/* in ms */ +#define SD_EMMC_CMD_TIMEOUT_MAX 32768/* in ms, 2^15: limit of CMD_CFG_TIMEOUT_MASK */ #define SD_EMMC_CFG_CMD_GAP 16/* in clock cycles */ #define SD_EMMC_DESC_BUF_LEN PAGE_SIZE
@@ -211,7 +212,7 @@ static unsigned int meson_mmc_get_timeou timeout =roundup_pow_of_two (timeout); -return min (timeout,32768U );/* max. 2^15 ms */ + return min_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT_MAX); }/* For R1b the controller waits for busy to be released within this timeout. */
Greg Kroah-Hartman
maintainerPATCH 586/1005 memstick: core: dont clear dev->driver in memstick_device_remove()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joshua Mulloy <[email protected]>
commit 6f2b998a52746892968741cbf8fc226985cbf286 upstream.
memstick_device_remove() sets card->dev.driver to NULL after calling the driver's remove() callback. Since commit a995fe1a3aa7 ("rust: driver:
drop device private data post unbind"), device_unbind_cleanup() dereferences dev->driver after the bus remove() callback has returned, so this should result in a NULL pointer dereference whenever a MemoryStick card is removed or its driver is unbound.
The driver core clears dev->driver itself in device_unbind_cleanup(), so there is no need for the bus code to do it. Remove the assignment.
This was found by code inspection, with the help of an AI coding assistant, after hitting the same bug in the TI FlashMedia bus code (drivers/misc/tifm_core.c), which oopsed on SD card removal. It has only been compile-tested: no MemoryStick hardware was available.
--- drivers/memstick/core/memstick.c | 1 - 1 file changed, 1 deletion(-)
drivers/memstick/core/memstick.c +0 -1
@@ -100,7 +100,6 @@ static void memstick_device_remove(strucif (dev->driver && drv->remove) { drv->remove (card); - card->dev.driver =NULL ; }put_device (dev);
Greg Kroah-Hartman
maintainerPATCH 587/1005 errseq: dont let errseq_check_and_advance() hide later errors
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shashank Mohan Jain <[email protected]>
commit 94defd41d80f10bbe883c0c8d1b28d1665b6b153 upstream.
errseq_check_and_advance() reads the errseq_t, sets ERRSEQ_SEEN with a cmpxchg() and then advances *since to the value it computed, ignoring whether the cmpxchg() succeeded. When it fails because errseq_set() recorded a different error in the meantime, *since ends up holding a value that was never stored in the errseq_t.
errseq_set() only bumps the counter when ERRSEQ_SEEN is set. So as long as nobody has seen the new error, recording the original errno again recreates exactly the old value, and once another subscriber marks it seen, it is equal to the stale *since. The next check through that cursor then reports nothing, although -ENOSPC was recorded after the value that check reported, and -EIO was recorded again after it returned:
cursor f writeback cursor g
-------- --------- --------
set(-EIO)
check_and_advance(&f)
old = [c, EIO]
set(-ENOSPC)
-> [c, ENOSPC]
cmpxchg() fails
f = [c, EIO, SEEN]
returns -EIO
set(-EIO)
-> [c, EIO]
(no bump: unseen)
check_and_advance(&g)
-> [c, EIO, SEEN]
returns -EIO check_and_advance(&f)
[c, EIO, SEEN] == f
returns 0 <- -ENOSPC and the second -EIO are lost
For file->f_wb_err this means that fsync() on one descriptor can return 0 although writeback failed after the previous fsync() on that descriptor returned, when writeback errors race with fsync() on another descriptor of the same file. The same applies to syncfs() through sb->s_wb_err, which every file on the filesystem shares, and to the ext4 and jbd2 cursors on the block device mapping. The kernel-doc promises "Negative errno if one has been stored, or 0 if no new error has occurred".
Retry with the value found when the cmpxchg() fails, so that *since is only ever advanced to a value that was actually stored with ERRSEQ_SEEN set. Every later errseq_set() then has to bump the counter, and the error is reported. The retry loop terminates because each iteration needs a concurrent update, like the loop in errseq_set().
A TLA+ model of errseq_set() and errseq_check_and_advance(), checked with the TLC model checker, finds the lost error with the current code; with this change TLC checks that an error recorded after a check returned is always reported by the next check (exhaustively for two subscribers with three checks each, and one writer recording four errors or two writers recording two each). The KUnit race test added in the next patch misses the error in 1-6% of 2 million rounds on 4-CPU UML before this change (depending on host load), and in none after it.
--- lib/errseq.c | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-)
lib/errseq.c +18 -11
@@ -162,7 +162,8 @@ EXPORT_SYMBOL(errseq_check);* points to. If it does, then just return 0. * * If it doesn't, then the value has changed. Set the "seen" flag, and try to -* swap it into place as the new eseq value. Then, set that value as the new +* swap it into place as the new eseq value. If the swap fails because the +* value changed, retry with the new value. Then, set that value as the new * "since" value, and return whatever the error portion is set to. * * Note that no locking is provided here for concurrent updates to the "since"
@@ -184,24 +185,30 @@ int errseq_check_and_advance(errseq_t *e* to take the lock that protects the "since" value. */ old =READ_ONCE (*eseq); -if (old != *since) { +while (old != *since) {/* * Set the flag and try to swap it into place if it has * changed. * -* We don't care about the outcome of the swap here. If the -* swap doesn't occur, then it has either been updated by a -* writer who is altering the value in some way (updating -* counter or resetting the error), or another reader who is -* just setting the "seen" flag. Either outcome is OK, and we -* can advance "since" and return an error based on what we -* have. +* If the swap fails, a writer or another reader changed the +* value under us, so retry with the new value. "since" must +* only ever be set to a value that was stored with the SEEN +* flag: errseq_set() does not bump the counter while the +* flag is clear, so an unstored value could come back later +* and hide the errors that were recorded in the meantime. */ new = old |ERRSEQ_SEEN ; -if (new != old) -cmpxchg (eseq, old, new); +if (new != old) { +errseq_t cur =cmpxchg (eseq, old, new); + +if (cur != old) { + old = cur; +continue ; + } + } *since = new; err = -(new &ERRNO_MASK ); +break ; }return err; }
Greg Kroah-Hartman
maintainerPATCH 588/1005 backing-file: pass RWF_NOAPPEND to synchronous writes
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit afa735786a89bde4959db52f20e3579de54ec740 upstream.
pwritev2() with RWF_NOAPPEND ignores the offset and appends the data on an overlayfs or FUSE passthrough file that was opened with O_APPEND, and the call still returns success. The flag must make the write go to the given offset even though the file is in append mode. Any user who can write to the file is affected, with the default mount options.
overlayfs and FUSE passthrough forward the reads and writes on their files to a backing file on an underlying filesystem, through the helpers in fs/backing-file.c.
The flag works for the file that the user opened: kiocb_set_rw_flags() clears IOCB_APPEND in the write's kiocb. It also copies RWF_NOAPPEND into ki_flags, as it does with every RWF_ flag.
overlayfs and FUSE passthrough then pass the write on to the backing file. They opened it with the open flags of the user's file, so it is in append mode too.
For a synchronous write, do_backing_file_write_iter() calls vfs_iter_write(), which sets up a new kiocb for the backing file. That kiocb starts out with IOCB_APPEND set. vfs_iter_write() is only given the flags of the user's kiocb that are in BACKING_IOCB_MASK, and RWF_NOAPPEND is not one of them. So nothing clears IOCB_APPEND again, and the data goes to the end of the file while the call returns success.
An asynchronous write reuses the flags of the user's kiocb and is not affected.
Reproduced by calling pwritev2() with RWF_NOAPPEND at offset 0, on an overlayfs file and on a FUSE passthrough file opened with O_APPEND: the data was at the end of the file afterwards.
Fix this by adding RWF_NOAPPEND to BACKING_IOCB_MASK.
--- fs/backing-file.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
fs/backing-file.c +6 -1
@@ -115,8 +115,13 @@ struct backing_aio {static struct kmem_cache *backing_aio_cachep; +/* +* RWF_NOAPPEND stays set in ki_flags. Pass it on, because the backing file is +* in append mode as well and a new kiocb for it starts with IOCB_APPEND. +*/ #define BACKING_IOCB_MASK \ - (IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND) + (IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND | \ + (__force int) RWF_NOAPPEND)static rwf_t iocb_to_rw_flags (int flags) {
Greg Kroah-Hartman
maintainerPATCH 589/1005 pidfd: restrict task access ioctls to the callers pid namespace
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chen Linxuan <[email protected]>
commit ee8323fdc827c580425644db605a4be776cace57 upstream.
pidfds can cross pid namespace boundaries: a task may obtain one for a process outside of its own pid namespace hierarchy through SO_PASSPIDFD or SO_PEERPIDFD, via SCM_RIGHTS, or through file descriptor inheritance.
The namespace ioctls gate access with a ptrace check against the target's credentials only. That check does not account for the pid namespace relationship between the caller and the target, so a task inside a pid namespace can use a pidfd obtained across that boundary to acquire namespace file descriptors of a task outside of its hierarchy.
procfs exposes the equivalent information only for tasks visible in the reader's pid namespace, and PIDFD_GET_INFO already answers with -EREMOTE for targets outside the caller's hierarchy. Extend that policy to the namespace ioctls: fail with -EREMOTE unless the target is visible in the caller's active pid namespace. Callers in ancestor pid namespaces are unaffected.
Unlike PIDFD_GET_INFO, the visibility check is performed after the task lookup here, so reaped targets outside of the caller's pid namespace hierarchy answer -ESRCH instead of -EREMOTE.
--- fs/pidfs.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/pidfs.c +8 -0
@@ -591,6 +591,14 @@ static long pidfd_ioctl(struct file *filreturn -EINVAL ;/* +* Require the target to be visible in the caller's pid namespace +* for operations that grant access to its resources, mirroring +* procfs and PIDFD_GET_INFO. +*/ +if (!pid_in_current_pidns (pidfd_pid (file))) +return -EREMOTE ; + +/* * We're trying to open a file descriptor to the namespace so perform a * filesystem cred ptrace check. Hold @task's exec_update_lock for the * duration of the ptrace check and the namespace lookup so that the
Greg Kroah-Hartman
maintainerPATCH 590/1005 eventpoll: wake the next waiter when a woken waiter is killed
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mani Tofigh <[email protected]>
commit 9f4413e522faed76f4cf610098b2369eb3ba1f1c upstream.
Processes sharing an epoll instance can sleep forever while an event is ready. An event wakes only one waiter, which then wakes the next one in ep_done_scan() if events are still ready. Since commit c257a340ede0 ("fs, epoll: short circuit fetching events if thread has been killed"), ep_send_events() returns before the scan when the waiter has a fatal signal. If the woken waiter is killed before it runs, nobody wakes the next one:
Task A Task B Task C
epoll_wait(ep, -1) epoll_wait(ep, -1)
write(efd)
/* wakes A only */
kill(A, SIGKILL)
ep_send_events()
return -EINTR
/* skips ep_done_scan() */
/* still asleep */B then sleeps until another file on the instance becomes ready, if ever. This can hit eg a pre-fork server whose worker gets OOM killed. Commit 7fab29e35630 ("fs/epoll: restore waking from ep_done_scan()") fixed the same kind of hang when the wakeup in ep_done_scan() was removed.
Keep the early return so that a dying task still doesn't take events nobody will see, but wake the next waiter there if events are ready, as ep_done_scan() would have. With the fix, B gets the event.
This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it within about 2s.
--- fs/eventpoll.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
fs/eventpoll.c +9 -2
@@ -2144,10 +2144,17 @@ static int ep_send_events(struct eventpo/* * Always short-circuit for fatal signals to allow threads to make a * timely exit without the chance of finding more events available and -* fetching repeatedly. +* fetching repeatedly. The wakeup that got us here may have been the +* only one for the events on ->rdllist, so pass it on to the next +* waiter, as ep_done_scan() would have. */ -if (fatal_signal_pending (current)) +if (fatal_signal_pending (current)) { +spin_lock_irq (&ep->lock); +if (!list_empty (&ep->rdllist)) +wake_up (&ep->wq); +spin_unlock_irq (&ep->lock);return -EINTR ; + }init_poll_funcptr (&pt,NULL );
Greg Kroah-Hartman
maintainerPATCH 591/1005 aio: dont let exit_aio() return before complete() is done
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit ac4b449b39e605123c12ea10042cafc9b6f39603 upstream.
exit_aio() kills all contexts in one go and waits for them with a single on-stack struct ctx_rq_wait. The count starts at table->nr, each killed context drops one count in free_ioctx_reqs() and exit_aio() subtracts the empty slots afterwards. Whoever drops the last count either calls complete() or, if it is exit_aio(), skips the wait.
With a full table skipped is zero and atomic_sub_and_test(0, ...) only tells us whether the count already hit zero. free_ioctx_reqs() runs from the percpu_ref RCU callback, so if exit_aio() is off the CPU long enough the last callback can have done its atomic_dec_and_test() but not yet called complete():
free_ioctx_reqs() exit_aio()
atomic_dec_and_test() // 1 -> 0
atomic_sub_and_test(0) // true
kfree(table)
return
complete(&wait.comp)complete() then locks and writes a completion on a stack frame that is gone. So hold an extra count for exit_aio() itself. Then the last count is always dropped by exit_aio() after it waited, or by a callback while exit_aio() waits for it. An unprivileged user gets there with four io_setup() calls and an exit without io_destroy().
--- fs/aio.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/aio.c +2 -2
@@ -962,7 +962,7 @@ void exit_aio(struct mm_struct *mm)if (!table)return ; -atomic_set (&wait.count, table->nr); +atomic_set (&wait.count, table->nr +1 );init_completion (&wait.comp); skipped =0 ;
@@ -986,7 +986,7 @@ void exit_aio(struct mm_struct *mm)kill_ioctx (mm, ctx, &wait); } -if (!atomic_sub_and_test (skipped, &wait.count)) { +if (!atomic_sub_and_test (skipped +1 , &wait.count)) {/* Wait until all IO for the context are done. */ wait_for_completion (&wait.comp); }
Greg Kroah-Hartman
maintainerPATCH 592/1005 fs: fix the SEEK_CUR f_lock condition
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 1448959fe3d013ffdb8302d17e4a8fdad2d2da95 upstream.
Commit da06e3c51794 ("fs: don't needlessly acquire f_lock") wanted to skip f_lock for SEEK_CUR on files that already serialize f_pos through f_pos_lock, i.e. FMODE_ATOMIC_POS files and directories, and keep it for everything else. The condition it added does the opposite:file_seek_cur_needs_f_lock() returns false exactly for the files that never take f_pos_lock and true for the ones that do.
So since v6.15 a SEEK_CUR on a shared block device or on a character device that uses fixed_size_llseek() updates f_pos without any lock and two concurrent calls can lose an update, while regular files and directories pay for a spinlock they don't need.
Invert the condition.
--- fs/file.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
fs/file.c +7 -3
@@ -1237,14 +1237,18 @@ static inline bool file_needs_f_pos_lockbool file_seek_cur_needs_f_lock (struct file *file) { -if (!(file->f_mode &FMODE_ATOMIC_POS ) && !file->f_op->iterate_shared) -return false; -/* +* Files that go through f_pos_lock when they are shared, i.e. +* FMODE_ATOMIC_POS files and directories, don't need f_lock for a +* SEEK_CUR. Everything else does, since nothing else serializes +* the f_pos update. +* * Note that we are not guaranteed to be called after fdget_pos() on * this file obj, in which case the caller is expected to provide the * appropriate locking. */ +if ((file->f_mode &FMODE_ATOMIC_POS ) || file->f_op->iterate_shared) +return false;return true; }
Greg Kroah-Hartman
maintainerPATCH 593/1005 splice, net: avoid MSG_MORE when the bvec array fills
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
commit 8eaa35c6c29ae669949f4b5b0814c3d34c8ed658 upstream.
splice_to_socket() leaves tail at the last included pipe buffer when its 16-entry bvec array fills. If the requested length exceeds the available pipe data, pipe_occupancy() counts that buffer again and sets MSG_MORE even though the pipe is empty. Small TCP transfers can then be delayed until the cork timeout expires.
Advance tail before checking the array limit so the occupancy test counts only pipe buffers that have not been included in the send.
--- fs/splice.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/splice.c +1 -1
@@ -863,9 +863,9 @@ ssize_t splice_to_socket(struct pipe_inobvec_set_page (&bvec[bc++], buf->page, seg, buf->offset); remain -= seg; + tail++;if (remain ==0 || bc >=ARRAY_SIZE (bvec))break ; - tail++; }if (!bc)
Greg Kroah-Hartman
maintainerPATCH 594/1005 libfs: make i_rwsem the lock of the offset tree
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit e7d73cef9726bea49de97ae1fd76405df4050a75 upstream.
The offset tree of a directory is only changed with the directory's i_rwsem held exclusive and offset_readdir() walks it with i_rwsem held shared. But the maple tree doesn't know that. It is set up with its internal spinlock, which every mtree_*() helper takes, and readdir takes rcu_read_lock() around each lookup.
The next patch makes readdir keep one ma_state across dir_emit(), which can sleep. That is safe because no writer can run while readdir holds i_rwsem. But the maple tree only allows keeping a ma_state across a sleep if it is protected by the tree's lock. A reader that relies on rcu_read_lock() has to mas_pause() before it drops it, and that means a walk from the root for every entry again.
So tell the tree what protects it. Initialize it with MT_FLAGS_LOCK_EXTERN and the directory's i_rwsem as its lock and switch the writers from the mtree_*() helpers to the mas_*() api. They all run with i_rwsem held exclusive already. With lockdep enabled the maple tree now also checks that every writer holds i_rwsem exclusive.
Nothing can reach the offset tree anymore when the directory inode is destroyed. So clear the external lock with mt_on_stack() and destroy the tree with __mt_destroy() instead of taking i_rwsem in ->destroy_inode().
--- fs/libfs.c | 46 +++++++++++++++++++++++++++++----------------- include/linux/fs.h | 2 +- mm/shmem.c | 2 +- 3 files changed, 31 insertions(+), 19 deletions(-)
fs/libfs.c +29 -17
@@ -263,17 +263,18 @@ static long dentry2offset(struct dentryreturn (long )dentry->d_fsdata; } -static struct lock_class_key simple_offset_lock_class; -/** * simple_offset_init - initialize an offset_ctx * @octx: directory offset map to be initialized +* @dir: the directory @octx belongs to * +* The directory's i_rwsem is the lock of the offset map. Writers hold it +* exclusive, offset_readdir() holds it shared. */ -void simple_offset_init (struct offset_ctx *octx) +void simple_offset_init (struct offset_ctx *octx,struct inode *dir) { -mt_init_flags (&octx->mt,MT_FLAGS_ALLOC_RANGE ); -lockdep_set_class (&octx->mt.ma_lock, &simple_offset_lock_class); +mt_init_flags (&octx->mt,MT_FLAGS_ALLOC_RANGE |MT_FLAGS_LOCK_EXTERN ); +mt_set_external_lock (&octx->mt, &dir->i_rwsem); octx->next_offset =DIR_OFFSET_MIN ; }
@@ -296,12 +297,13 @@ int simple_offset_add(struct offset_ctxunsigned long offset;int ret; +MA_STATE (mas, &octx->mt,0 ,0 ); +if (dentry2offset (dentry) !=0 )return -EBUSY ; - ret =mtree_alloc_cyclic (&octx->mt, &offset, dentry,DIR_OFFSET_MIN , -DIR_OFFSET_MAX , &octx->next_offset, -GFP_KERNEL ); + ret =mas_alloc_cyclic (&mas, &offset, dentry,DIR_OFFSET_MIN , +DIR_OFFSET_MAX , &octx->next_offset,GFP_KERNEL );if (unlikely (ret <0 ))return ret == -EBUSY ? -ENOSPC : ret;
@@ -314,7 +316,9 @@ static int simple_offset_replace(struct {int ret; - ret =mtree_store (&octx->mt, offset, dentry,GFP_KERNEL ); +MA_STATE (mas, &octx->mt, offset, offset); + + ret =mas_store_gfp (&mas, dentry,GFP_KERNEL );if (ret)return ret;offset_set (dentry, offset);
@@ -329,13 +333,14 @@ static int simple_offset_replace(struct*/ void simple_offset_remove (struct offset_ctx *octx,struct dentry *dentry) { -long offset; +long offset =dentry2offset (dentry); + +MA_STATE (mas, &octx->mt, offset, offset); - offset =dentry2offset (dentry);if (offset ==0 )return ; -mtree_erase (&octx->mt, offset); +mas_erase (&mas);offset_set (dentry,0 ); }
@@ -393,16 +398,20 @@ int simple_offset_rename_exchange(structlong new_index =dentry2offset (new_dentry);int ret; +MA_STATE (old_mas, &old_ctx->mt, old_index, old_index); +MA_STATE (new_mas, &new_ctx->mt, new_index, new_index); +if (WARN_ON (!old_index || !new_index))return -EINVAL ; - ret =mtree_store (&new_ctx->mt, new_index, old_dentry,GFP_KERNEL ); + ret =mas_store_gfp (&new_mas, old_dentry,GFP_KERNEL );if (WARN_ON (ret))return ret; - ret =mtree_store (&old_ctx->mt, old_index, new_dentry,GFP_KERNEL ); + ret =mas_store_gfp (&old_mas, new_dentry,GFP_KERNEL );if (WARN_ON (ret)) { -mtree_store (&new_ctx->mt, new_index, new_dentry,GFP_KERNEL ); +mas_set (&new_mas, new_index); +mas_store_gfp (&new_mas, new_dentry,GFP_KERNEL );return ret; }
@@ -417,11 +426,14 @@ int simple_offset_rename_exchange(struct* @octx: directory offset ctx that is about to be destroyed * * During fs teardown (eg. umount), a directory's offset map might still -* contain entries. xa_destroy() cleans out anything that remains. +* contain entries. __mt_destroy() cleans out anything that remains. +* Nothing can reach the map of a directory that is being destroyed, so +* this runs without the directory's i_rwsem. */ void simple_offset_destroy (struct offset_ctx *octx) { -mtree_destroy (&octx->mt); +mt_on_stack (octx->mt); +__mt_destroy (&octx->mt); }/**
include/linux/fs.h +1 -1
@@ -3328,7 +3328,7 @@ struct offset_ctx {unsigned long next_offset; }; -void simple_offset_init (struct offset_ctx *octx); +void simple_offset_init (struct offset_ctx *octx,struct inode *dir);int simple_offset_add (struct offset_ctx *octx,struct dentry *dentry);void simple_offset_remove (struct offset_ctx *octx,struct dentry *dentry); void simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry,
mm/shmem.c +1 -1
@@ -3131,7 +3131,7 @@ static struct inode *__shmem_get_inode(s inode->i_size =2 *BOGO_DIRENT_SIZE ; inode->i_op = &shmem_dir_inode_operations; inode->i_fop = &simple_offset_dir_operations; -simple_offset_init (shmem_get_offset_ctx (inode)); +simple_offset_init (shmem_get_offset_ctx (inode), inode);break ;case S_IFLNK :/*
Greg Kroah-Hartman
maintainerPATCH 595/1005 mm/mmzone: read the zoneref slot once in zonelist_zone()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit 9c52ebe9c89d41c56fcb5d94efe9e539414175a9 upstream.
Memory hotplug rebuilds zonelists in place while allocations walk them, so a zoneref slot can change between two loads of it.
zonelist_zone() loads the slot with a plain access. The compiler may load it again later instead of keeping the zone it already read, so a caller can check one zone and then use another, or the NULL terminator.
Use READ_ONCE(). Callers that take a zone from a slot and keep using it, such as get_page_from_freelist() with ac->preferred_zoneref, need that single load.
--- include/linux/mmzone.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/mmzone.h +2 -1
@@ -1815,7 +1815,8 @@ extern struct zone *next_zone(struct zonstatic inline struct zone *zonelist_zone (struct zoneref *zoneref) { -return zoneref->zone; +/* Memory hotplug rewrites zonelists in place. */ +return READ_ONCE (zoneref->zone); }static inline int zonelist_zone_idx (const struct zoneref *zoneref)
Greg Kroah-Hartman
maintainerPATCH 596/1005 mm, page_alloc: pass zone pointer to trace_reclaim_retry_zone
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 6c48b3ab4ee435c41c3395d31e8ec3dbccc3478c upstream.
should_reclaim_retry() walks a zonelist and passes the zoneref pointer to the reclaim_retry_zone tracepoint, which loads the zone from the entry again to find the node.
Memory hotplug rebuilds the zonelists in place while allocations are under way. When a zone in front of the zoneref entry has become empty, the entries move up, and this one can be the end marker by the time the tracepoint looks at it. zonelist_node_idx() then dereferences a NULL zone. Short of that, the event can name another zone than the one its numbers belong to.
Pass the zone pointer instead of the zoneref pointer.
--- include/trace/events/oom.h | 8 ++++---- mm/page_alloc.c | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-)
include/trace/events/oom.h +4 -4
@@ -33,7 +33,7 @@ TRACE_EVENT(oom_score_adj_update, TRACE_EVENT(reclaim_retry_zone, - TP_PROTO(struct zoneref *zoneref, + TP_PROTO(struct zone *zone, int order, unsigned long reclaimable, unsigned long available,
@@ -41,7 +41,7 @@ TRACE_EVENT(reclaim_retry_zone,int no_progress_loops, bool wmark_check), -TP_ARGS (zoneref ,order ,reclaimable ,available ,min_wmark ,no_progress_loops ,wmark_check ), +TP_ARGS (zone ,order ,reclaimable ,available ,min_wmark ,no_progress_loops ,wmark_check ),TP_STRUCT__entry ( __field( int, node)
@@ -55,8 +55,8 @@ TRACE_EVENT(reclaim_retry_zone, ), TP_fast_assign( - __entry->node = zonelist_node_idx(zoneref); - __entry->zone_idx =zonelist_zone_idx (zoneref); + __entry->node = zone_to_nid(zone); + __entry->zone_idx =zone_idx (zone); __entry->order = order; __entry->reclaimable = reclaimable; __entry->available = available;
mm/page_alloc.c +1 -1
@@ -4693,7 +4693,7 @@ should_reclaim_retry(gfp_t gfp_mask, uns*/ wmark =__zone_watermark_ok (zone, order, min_wmark, ac->highest_zoneidx, alloc_flags, available); -trace_reclaim_retry_zone (z, order, reclaimable, +trace_reclaim_retry_zone (zone, order, reclaimable, available, min_wmark, *no_progress_loops, wmark);if (wmark) { ret = true;
Greg Kroah-Hartman
maintainerPATCH 597/1005 mm/page_alloc: retry alloc_contig_pages() when the zonelist is rebuilt
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit da0d7a895e9021dc2cffa90fb6fafd8b9379e544 upstream.
Onlining the first block of a zone rebuilds every zonelist in place, shifting the slots after the new zone. alloc_contig_frozen_pages_noprof() approves a slot by the caller's gfp and nodemask, then loads the zone from it:
CPU 0 CPU 1
alloc_contig_frozen_pages_noprof(GFP_HIGHUSER | __GFP_THISNODE)
slot 0 (NORMAL1) approved
online_pages()
build_all_zonelists()
[NORMAL1]
-> [MOVABLE1, NORMAL1]
zone = zonelist_zone(slot 0) /* MOVABLE1 */
alloc_contig_frozen_range(MOVABLE1 pfns)
A gigantic hugetlb page can then land in ZONE_MOVABLE, and a nodemask caller can get a range from another node. Gigantic pages are kept out of ZONE_MOVABLE since commit 79b63f12abcb ("mm, hugetlb: do not allocate non-migrateable gigantic pages from movable zones").
Check zonelist_update_seq before using each zone, and restart the walk if it changed, as the hugetlb pool walk does. Check again before escalating to the pass that may migrate hugetlb pages, so a pass a rebuild cut short is redone rather than escalated.
With kprobes holding the walk across the online, the base kernel put the 1G page in ZONE_MOVABLE in 3 of 3 runs, and this change put it in ZONE_NORMAL in 3 of 3. Direct GFP_KERNEL calls with nodemask {1} and {2} got a ZONE_MOVABLE range and a node 1 range on base, 3 of 3 each, and neither with this change.
--- mm/page_alloc.c | 9 +++++++++ 1 file changed, 9 insertions(+)
mm/page_alloc.c +9 -0
@@ -7583,6 +7583,7 @@ struct page *alloc_contig_frozen_pages_n gfp_t gfp_mask, int nid, nodemask_t *nodemask) { unsigned long ret, pfn, flags; +unsigned int zonelist_cookie;struct zonelist *zonelist;struct zone *zone;struct zoneref *z;
@@ -7591,8 +7592,13 @@ struct page *alloc_contig_frozen_pages_n retry: zonelist =node_zonelist (nid, gfp_mask); + zonelist_cookie =zonelist_iter_begin ();for_each_zone_zonelist_nodemask (zone, z, zonelist,gfp_zone (gfp_mask), nodemask) { +/* A rebuild may have shifted an ineligible zone into this slot. */ +if (unlikely (check_retry_zonelist (zonelist_cookie))) + goto retry; +spin_lock_irqsave (&zone->lock, flags); pfn =ALIGN (zone->zone_start_pfn, nr_pages);
@@ -7627,6 +7633,9 @@ retry:* second pass, we will try moving HugeTLB pages when those pages are * smaller than the requested contiguous region size. */ +/* Redo a pass that a rebuild cut short before escalating. */ +if (unlikely (check_retry_zonelist (zonelist_cookie))) + goto retry;if (skip_hugetlb && skipped_hugetlb) { skip_hugetlb = false; goto retry;
Greg Kroah-Hartman
maintainerPATCH 598/1005 mm: page_frag: refill the cache for large fragments
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit c028ecdf15131a2ab70d78a76657b81c00fa240d upstream.
A fragment which is larger than PAGE_SIZE can only be served from the 32K page of a page_frag_cache. If memory is low and the cache had to fall back to a single page, __page_frag_alloc_align() returns NULL and keeps that page.
Since the offset counts up, this check comes first and is made whenever the fragment does not fit behind nc->offset, no matter how big the page of the cache is. So the cache is never refilled on behalf of a large
fragment: with fragsz = 10000 the first three allocations succeed, the fourth one and all the following ones fail although memory is plentiful. nc->offset does not move either, so this lasts until smaller fragments have used up the rest of the page, which never happens if the cache has no other user.
The nfp driver allocates its receive buffers with napi_alloc_frag() and netdev_alloc_frag(). They are larger than a page with a jumbo MTU.
Only give up if the fragment does not fit into the page at all, which is what the comment describes. The fourth allocation in the scenario above with a 32k page will thus now proceed to refill the cache.
--- mm/page_frag_cache.c | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-)
mm/page_frag_cache.c +13 -8
@@ -119,15 +119,20 @@ refill: size =PAGE_SIZE <<encoded_page_decode_order (encoded_page); offset =__ALIGN_KERNEL_MASK (nc->offset, ~align_mask);if (unlikely (offset + fragsz > size)) { -if (unlikely (fragsz >PAGE_SIZE )) { +if (unlikely (fragsz > size)) {/* -* The caller is trying to allocate a fragment -* with fragsz > PAGE_SIZE but the cache isn't big -* enough to satisfy the request, this may -* happen in low memory conditions. -* We don't release the cache page because -* it could make memory pressure worse -* so we simply return NULL here. +* The caller is trying to allocate a fragment that's +* larger than the whole cache page. +* +* Either fragsz is larger than PAGE_FRAG_CACHE_MAX_SIZE +* so this cannot ever succeed. +* +* Or the refill has fallen back to order-0 due to a low +* memory condition. Then we don't want to release the +* cache page to attempt a new large-size refill because +* it could make memory pressure worse. +* +* So in both cases we simply return NULL here. */ return NULL ; }
Greg Kroah-Hartman
maintainerPATCH 599/1005 mm/mempolicy: read the zoneref slot once in mempolicy_slab_node()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit 4cc1bcdf2e4ebcd319005ce2ea132489f6155139 upstream.
For a bind or preferred-many policy, mempolicy_slab_node() tests the first matching slot's zone for NULL, then reads the slot again to look up the zone's node. Offlining a zone's last block rebuilds the zonelists in place, so the second read can return the terminator:
CPU 0 CPU 1
mempolicy_slab_node()
zonelist_zone(slot 4)
= node 2 NORMAL
offline_pages()
build_all_zonelists()
slot 4 = NULL
zonelist_node_idx(slot 4)
zone_to_nid(NULL)
Current GCC merges the two reads, but nothing requires it. With mm/mempolicy.o built with -fno-inline -fno-ipa-sra, holding a bound task's slab_strict_numa allocation between the reads while a movable block earlier in the zonelist goes offline oopses every time:
BUG: kernel NULL pointer dereference, address: 0000000000000060 RIP: 0010:zone_to_nid+0x0/0x10 Call Trace: kmem_cache_alloc_noprof+0x294/0x610 do_getname+0x34/0x230
mempolicy_slab_node() and zonelist_node_idx() are tail calls here, so neither appears in the trace.
Read the slot once and use that zone.
--- mm/mempolicy.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
mm/mempolicy.c +3 -1
@@ -2159,6 +2159,7 @@ unsigned int mempolicy_slab_node(void)case MPOL_PREFERRED_MANY : {struct zoneref *z; +struct zone *zone;/* * Follow bind policy behavior and start allocation at the
@@ -2169,7 +2170,8 @@ unsigned int mempolicy_slab_node(void) zonelist = &NODE_DATA (node)->node_zonelists[ZONELIST_FALLBACK ]; z =first_zones_zonelist (zonelist, highest_zoneidx, &policy->nodes); -return zonelist_zone (z) ?zonelist_node_idx (z) : node; + zone =zonelist_zone (z); +return zone ?zone_to_nid (zone) : node; }case MPOL_LOCAL :return node;
Greg Kroah-Hartman
maintainerPATCH 600/1005 mm/mmzone: read each zoneref slot once when filtering by nodemask
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit e55119ab611a0e47595db7e1d2ac1e69f7a73ff0 upstream.
__next_zones_zonelist() tests a slot's zone for NULL, then reads the slot again to look up the zone's node. Offlining a zone's last block rebuilds the zonelists in place, so the second read can return the terminator:
CPU 0 CPU 1
__next_zones_zonelist(nodemask)
zonelist_zone(slot 1) = NORMAL
offline_pages()
build_all_zonelists()
[MOVABLE, NORMAL, NULL] -> [NORMAL, NULL]
zref_in_nodemask(slot 1)
zone_to_nid(NULL)
Current GCC and clang merge the two reads, but nothing requires it. With mm/mmzone.o built with -fno-inline -fno-ipa-sra, holding a nodemask allocation between the reads while the node's last movable block goes offline oopses every time:
BUG: kernel NULL pointer dereference, address: 0000000000000060 RIP: 0010:zone_to_nid+0x0/0x10 Call Trace: zref_in_nodemask+0x9/0x20 __next_zones_zonelist+0x23/0x70 prepare_alloc_pages.constprop.0+0x16c/0x190 __alloc_frozen_pages_noprof+0xaf/0x330
Read the slot once and test that zone. A NULL zone still ends the walk. To achieve that, rename zref_in_nodemask() to zone_in_nodemask() and pass a zone instead of zoneref pointer.
--- mm/mmzone.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
mm/mmzone.c +6 -5
@@ -43,13 +43,14 @@ struct zone *next_zone(struct zone *zonereturn zone; } -static inline int zref_in_nodemask (struct zoneref *zref, -const nodemask_t *nodes) +/* A NULL zone terminates the zonelist, so it ends the search. */ +static inline bool zone_in_nodemask (const struct zone *zone, +const nodemask_t *nodes) {#ifdef CONFIG_NUMA -return node_isset (zonelist_node_idx (zref), *nodes); +return !zone ||node_isset (zone_to_nid (zone), *nodes);#else -return 1 ; +return true;#endif /* CONFIG_NUMA */ }
@@ -67,7 +68,7 @@ struct zoneref *__next_zones_zonelist(st z++; else while (zonelist_zone_idx(z) > highest_zoneidx || - (zonelist_zone(z) && !zref_in_nodemask(z, nodes))) + !zone_in_nodemask(zonelist_zone(z), nodes)) z++;return z;
Greg Kroah-Hartman
maintainerPATCH 601/1005 mm/memory_hotplug: resize zones under their seqlock
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 58e81bb7de5aac8ec5e4aa21d401e7dafbd4058b upstream.
With CONFIG_DEBUG_VM the page allocator checks that a page which is freed, split or allocated lies within its zone. The check reads zone->zone_start_pfn and zone->spanned_pages under zone->span_seqlock, as memory hotplug can change the two at any time.
Commit 27cacaad16c5 ("mm,memory_hotplug: drop unneeded locking") removed the write side, since all resizing is serialized by the hotplug lock. That leaves the reader without protection. When memory below the start of a zone goes online, the start is lowered first and the size is raised afterwards. When the lowest memory of a zone goes offline, the size is reduced first. In between, the zone seems to end before its last pages. If one of them goes through the allocator at that moment, it is reported as being outside of the zone triggers VM_BUG_ON_PAGE().
Write the two fields in a write section of the seqlock. Interrupts are disabled as pages are freed from interrupts, too, and the reader would wait for the writer which it has interrupted.
--- mm/memory_hotplug.c | 44 ++++++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 16 deletions(-)
mm/memory_hotplug.c +28 -16
@@ -475,6 +475,22 @@ static unsigned long find_biggest_sectioreturn 0 ; } +/* +* The page allocator checks pages against the span of their zone while the +* zone is resized, see page_outside_zone_boundaries(). It must not see the +* new value of one field together with the old value of the other one. +*/ +static void zone_set_span (struct zone *zone,unsigned long start_pfn, +unsigned long spanned_pages) +{ +unsigned long flags; + +write_seqlock_irqsave (&zone->span_seqlock, flags); + zone->zone_start_pfn = start_pfn; + zone->spanned_pages = spanned_pages; +write_sequnlock_irqrestore (&zone->span_seqlock, flags); +} +static void shrink_zone_span (struct zone *zone,unsigned long start_pfn,unsigned long end_pfn) {
@@ -490,13 +506,10 @@ static void shrink_zone_span(struct zone*/ pfn =find_smallest_section_pfn (nid, zone, end_pfn,zone_end_pfn (zone)); -if (pfn) { - zone->spanned_pages =zone_end_pfn (zone) - pfn; - zone->zone_start_pfn = pfn; - }else { - zone->zone_start_pfn =0 ; - zone->spanned_pages =0 ; - } +if (pfn) +zone_set_span (zone, pfn,zone_end_pfn (zone) - pfn); +else +zone_set_span (zone,0 ,0 ); }else if (zone_end_pfn (zone) == end_pfn) {/* * If the section is biggest section in the zone, it need
@@ -507,11 +520,10 @@ static void shrink_zone_span(struct zone pfn =find_biggest_section_pfn (nid, zone, zone->zone_start_pfn, start_pfn);if (pfn) - zone->spanned_pages = pfn - zone->zone_start_pfn +1 ; -else { - zone->zone_start_pfn =0 ; - zone->spanned_pages =0 ; - } +zone_set_span (zone, zone->zone_start_pfn, + pfn - zone->zone_start_pfn +1 ); +else +zone_set_span (zone,0 ,0 ); } }
@@ -703,12 +715,12 @@ static void online_pages_range(unsignedstatic void __meminit resize_zone_range (struct zone *zone,unsigned long start_pfn,unsigned long nr_pages) { -unsigned long old_end_pfn =zone_end_pfn (zone); +unsigned long end_pfn =max (start_pfn + nr_pages,zone_end_pfn (zone)); -if (zone_is_empty (zone) || start_pfn < zone->zone_start_pfn) - zone->zone_start_pfn = start_pfn; +if (!zone_is_empty (zone) && start_pfn > zone->zone_start_pfn) + start_pfn = zone->zone_start_pfn; - zone->spanned_pages =max (start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn; +zone_set_span (zone, start_pfn, end_pfn - start_pfn); } static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
Greg Kroah-Hartman
maintainerPATCH 602/1005 mm: page_isolation: do not take slab pages for free
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 213268869301f747d19ca00a391757a6cf2d4fa8 upstream.
page_is_unmovable() regards a page with a reference count of zero as free or about to be freed. Since slab allocates frozen pages, they will be wrongly considered to be freed if order 0 (higher-order compound pages are caught earlier).
If such slabs are the only unmovable pages of a memory block, memory offlining now isolates the block, this can lead to offline_pages() looping without progress.
Thus detect the slab pages as removable to return -EBUSY, as would happen before commit 9aec2fb0fd5e ("slab: allocate frozen pages").
--- mm/memory_hotplug.c | 7 +++++++ mm/page_isolation.c | 7 +++++++ 2 files changed, 14 insertions(+)
mm/memory_hotplug.c +7 -0
@@ -1835,6 +1835,13 @@ static int scan_movable_pages(unsigned lif (PageOffline (page) &&page_count (page))return -EBUSY ; +/* +* A page that was allocated, but was not a slab page yet, when +* its pageblock was isolated. +*/ +if (PageSlab (page)) +return -EBUSY ; + folio =page_folio (page);if (!folio_test_hugetlb (folio))continue ;
mm/page_isolation.c +7 -0
@@ -75,6 +75,13 @@ bool page_is_unmovable(struct zone *zone }/* +* Slab pages are frozen: do not take their reference count of zero +* for that of a free page. +*/ +if (PageSlab (page)) +return true; + +/* * We can't use page_count without pin a page * because another CPU can free compound page. * This check already skips compound tails of THP
Greg Kroah-Hartman
maintainerPATCH 603/1005 mm/page_alloc: dont undo another isolation in alloc_contig_range
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit 7d9c29ed8feec8bfbe5e5f673ba2b5926da11375 upstream.
An alloc_contig_range() that overlaps a block going offline can leave the offline spinning until it gets a signal, holding the device hotplug lock. When isolation fails, alloc_contig_frozen_range() undoes it over the whole range, clearing the offline's MIGRATE_ISOLATE too:
CPU 1 (offline_pages) CPU 2 (alloc_contig_range)
start_isolate_page_range()
blocks are MIGRATE_ISOLATE
start_isolate_page_range()
-EBUSY on CPU 1's blocks
undo_isolate_page_range()
blocks are MIGRATE_MOVABLE
test_pages_isolated()
never succeeds again
start_isolate_page_range() fails only on a block someone else isolated, after undoing its own, so this undo only ever clears another caller's. Return directly, as before alloc_contig_range() went pageblock granular.
With offline_pages() parked after isolating a DIMM block and a 1G hugetlb allocation made over it, the offline on base still loops 30s later in 4 of 4 runs:
offline_pages+0x5b2/0x1570 memory_subsys_offline+0x17e/0x470 device_offline+0x250/0x340 state_store+0x88/0x110
With this patch the allocation still fails, and the offline completes in 3 of 3 runs.
--- mm/page_alloc.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
mm/page_alloc.c +5 -1
@@ -7377,9 +7377,13 @@ int alloc_contig_frozen_range_noprof(uns* put back to page allocator so that buddy can use them. */ +/* +* On failure this has undone its own isolation, and any other +* isolated blocks in the range belong to someone else, e.g. offline. +*/ ret =start_isolate_page_range (start, end, mode);if (ret) - goto done; +return ret;drain_all_pages (cc.zone);
Greg Kroah-Hartman
maintainerPATCH 604/1005 mm/page_alloc: reset can_retry_reserves when the slowpath restarts
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit b35ce030893929b3670de82bdac2713cb7b20d90 upstream.
Commit 2c4c3e29897d ("mm/page_alloc: simplify __alloc_pages_slowpath() flow") retries an allocation once with reserve_flags when the caller becomes eligible for reserves, guarded by can_retry_reserves.
A restart after a cpuset update or a zonelist rebuild retries with can_retry_reserves already set to false, so a caller that cannot reclaim (GFP_NOWAIT | __GFP_MEMALLOC), fails without trying reserves.
Reset can_retry_reserves on restart. Only a cpuset or zonelist change restarts the slowpath, so the retry still runs at most once per change.
With a kprobe helping to make the race deterministic, an allocation can be made to return NULL. With this patch the allocation will succeed.
--- mm/page_alloc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/page_alloc.c +2 -1
@@ -4806,7 +4806,7 @@ __alloc_pages_slowpath(gfp_t gfp_mask, uunsigned int zonelist_iter_cookie;int reserve_flags;bool compact_first = false; -bool can_retry_reserves = true; +bool can_retry_reserves;unsigned long alloc_start_time = jiffies;/*
@@ -4840,6 +4840,7 @@ restart: no_progress_loops =0 ; compact_result =COMPACT_SKIPPED ; compact_priority =DEF_COMPACT_PRIORITY ; + can_retry_reserves = true; cpuset_mems_cookie =read_mems_allowed_begin (); zonelist_iter_cookie =zonelist_iter_begin ();
Greg Kroah-Hartman
maintainerPATCH 605/1005 mm/page_alloc: keep the pagesets of an empty zone
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 7bfcf81b1cb469bc016fa8e07939c0924b9ff8db upstream.
When the last memory of a zone goes offline, zone_pcp_reset() frees zone->per_cpu_pageset and zone->per_cpu_zonestats. Nothing waits for those who found the zone populated and still use the two pointers. They take neither the memory hotplug lock nor any other lock which offline_pages() holds, and some of them can sleep:
CPU0 vmstat_update() CPU1 offline_pages()
refresh_cpu_vm_stats()
for_each_populated_zone(zone)
pcp = zone->per_cpu_pageset
cond_resched()
adjust_present_page_count()
zone_pcp_reset(zone)
free_percpu(zone->per_cpu_pageset)
decay_pcp_high(zone, pcp)
__this_cpu_write(pcp->expire, 0)The same goes for drain_all_pages(NULL), which takes pcp->lock, for zone_pcp_update(), show_free_areas() and the readers and writers of the zonestats. If the per-cpu memory has got a new owner in the meantime, it is corrupted.
The pagesets are only freed because setup_zone_pageset() would otherwise leak them when the zone gets memory again. Keep them instead and let setup_zone_pageset() and zone_pcp_init() use them again, like it is done with pgdat->per_cpu_nodestats. Their lists are empty, and their limits have been calculated for a zone without memory by the init_per_zone_wmark_min() of offline_pages(), which is what setup_zone_pageset() would come up with as well.
--- mm/page_alloc.c | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-)
mm/page_alloc.c +14 -6
@@ -6357,6 +6357,10 @@ void __meminit setup_zone_pageset(struct {int cpu; +/* The zone has been populated before, see zone_pcp_reset(). */ +if (zone->per_cpu_pageset != &boot_pageset) +return ; +/* Size may be 0 on !SMP && !NUMA */ if (sizeof (struct per_cpu_zonestat ) >0 ) zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
@@ -6449,6 +6453,10 @@ void __init setup_per_cpu_pageset(void)__meminit void zone_pcp_init (struct zone *zone) { +/* This initialization only needs to be done once */ +if (zone->per_cpu_pageset) +return ; +/* * per cpu subsystem is not up at this point. The following code * relies on the ability of the linker to provide the
@@ -7746,6 +7754,12 @@ void zone_pcp_enable(struct zone *zone)mutex_unlock (&pcp_batch_high_lock); } +/* +* The zone has become empty. Its pagesets and zonestats are not freed: nothing +* keeps somebody who found the zone populated, such as refresh_cpu_vm_stats() +* or drain_all_pages(), from still using them. They are used again when the +* zone gets memory again. +*/ void zone_pcp_reset (struct zone *zone) {int cpu;
@@ -7756,12 +7770,6 @@ void zone_pcp_reset(struct zone *zone) pzstats =per_cpu_ptr (zone->per_cpu_zonestats, cpu);drain_zonestat (zone, pzstats); } -free_percpu (zone->per_cpu_pageset); - zone->per_cpu_pageset = &boot_pageset; -if (zone->per_cpu_zonestats != &boot_zonestats) { -free_percpu (zone->per_cpu_zonestats); - zone->per_cpu_zonestats = &boot_zonestats; - } } }
Greg Kroah-Hartman
maintainerPATCH 606/1005 mm/page_alloc: detect zonelist rebuilds from memory hot-add
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit e5db040c3d09c5d85dda70f736d4d1a6714b741e upstream.
The zonelist_update_seq retry was limited to CONFIG_MEMORY_HOTREMOVE, presumably because only hot-remove takes zones out of a zonelist.
However, build_zonerefs_node() rewrites the zonelists in place, so onlining the first block of a zone shifts the entries that follow it in every zonelist containing that zone. This can cause a spurious allocation failure for a __GFP_THISNODE caller.
For a node with only ZONE_NORMAL, onlining its first ZONE_MOVABLE block rewrites the node's ZONELIST_NOFALLBACK list as:
[NORMAL, NULL] -> [MOVABLE, NULL] -> [MOVABLE, NORMAL, NULL]
A concurrent GFP_KERNEL | __GFP_THISNODE allocation can observe the intermediate list, skip ZONE_MOVABLE, and find no eligible zone. With CONFIG_MEMORY_HOTREMOVE=n, check_retry_zonelist() returns 0 and the allocation fails even though the node has free ZONE_NORMAL memory.
Gate the sequence checks on CONFIG_MEMORY_HOTPLUG, which covers every configuration that rebuilds zonelists after boot.
--- mm/page_alloc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
mm/page_alloc.c +2 -2
@@ -4427,7 +4427,7 @@ static DEFINE_SEQLOCK(zonelist_update_sestatic unsigned int zonelist_iter_begin (void ) { -if (IS_ENABLED (CONFIG_MEMORY_HOTREMOVE )) +if (IS_ENABLED (CONFIG_MEMORY_HOTPLUG ))return read_seqbegin (&zonelist_update_seq);return 0 ;
@@ -4435,7 +4435,7 @@ static unsigned int zonelist_iter_begin(static unsigned int check_retry_zonelist (unsigned int seq) { -if (IS_ENABLED (CONFIG_MEMORY_HOTREMOVE )) +if (IS_ENABLED (CONFIG_MEMORY_HOTPLUG ))return read_seqretry (&zonelist_update_seq, seq);return seq;
Greg Kroah-Hartman
maintainerPATCH 607/1005 mm/page_alloc: snapshot the preferred zone against shrink rebuilds
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price (Meta) <[email protected]>
commit b3e3a760eb68449e2794ef68ab212173d9c3e8c7 upstream.
get_page_from_freelist() and alloc_pages_bulk_noprof() reread ac->preferred_zoneref->zone at every use. Offlining a zone's last block rebuilds the zonelists in place, and the shrunk list's NULL terminator can land on the preferred slot mid-walk:
CPU 0 CPU 1
get_page_from_freelist(GFP_KERNEL | __GFP_THISNODE)
zone = NORMAL (slot 1)
offline_pages()
build_all_zonelists()
[MOVABLE, NORMAL, NULL] -> [NORMAL, NULL]
rmqueue(zonelist_zone(slot 1), zone)
zone_statistics(NULL, zone)
BUG: kernel NULL pointer dereference, address: 0000000000000060 RIP: 0010:get_page_from_freelist+0x6a5/0x15f0 Call Trace: __alloc_frozen_pages_noprof+0x125/0x330
Read the slot once. Zones are never freed, so a stale zone is safe, and a NULL slot fails the same way as walking off the end.
--- mm/page_alloc.c | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-)
mm/page_alloc.c +23 -8
@@ -3817,12 +3817,21 @@ get_page_from_freelist(gfp_t gfp_mask, u {struct zoneref *z;struct zone *zone; +struct zone *preferred_zone;struct pglist_data *last_pgdat =NULL ;bool last_pgdat_dirty_ok = false;bool no_fallback;bool skip_kswapd_nodes = nr_online_nodes >1 ;bool skipped_kswapd_nodes = false; +/* +* A concurrent zonelist rebuild can NULL or replace this slot. Zones +* are never freed, so reading it once keeps a usable zone. +*/ + preferred_zone =zonelist_zone (ac->preferred_zoneref); +if (!preferred_zone) +return NULL ; + retry:/* * Scan zonelist, looking for a zone with enough free.
@@ -3869,7 +3878,7 @@ retry: }if (no_fallback && !defrag_mode && nr_online_nodes >1 && - zone !=zonelist_zone (ac->preferred_zoneref)) { + zone != preferred_zone) {int local_nid;/*
@@ -3877,7 +3886,7 @@ retry:* fragmenting fallbacks. Locality is more important * than fragmentation avoidance. */ - local_nid =zonelist_node_idx (ac->preferred_zoneref); + local_nid =zone_to_nid (preferred_zone);if (zone_to_nid (zone) != local_nid) { alloc_flags &= ~ALLOC_NOFRAGMENT ; goto retry;
@@ -3939,7 +3948,7 @@ check_alloc_wmark: goto try_this_zone;if (!node_reclaim_enabled () || - !zone_allows_reclaim (zonelist_zone (ac->preferred_zoneref), zone)) + !zone_allows_reclaim (preferred_zone, zone))continue ;if (!node_reclaim (zone->zone_pgdat, gfp_mask, order))
@@ -3952,7 +3961,7 @@ check_alloc_wmark: } try_this_zone: - page =rmqueue (zonelist_zone (ac->preferred_zoneref), zone, order, + page =rmqueue (preferred_zone, zone, order, gfp_mask, alloc_flags, ac->migratetype);if (page) {prep_new_page (page, order, gfp_mask, alloc_flags);
@@ -5207,6 +5216,7 @@ unsigned long alloc_pages_bulk_noprof(gf {struct page *page;struct zone *zone; +struct zone *preferred_zone;struct zoneref *z;struct per_cpu_pages *pcp;struct list_head *pcp_list;
@@ -5254,6 +5264,11 @@ unsigned long alloc_pages_bulk_noprof(gfif (!prepare_alloc_pages (gfp,0 , preferred_nid, nodemask, &ac, &gfp, &alloc_flags)) goto out; +/* Read once; see get_page_from_freelist(). */ + preferred_zone =zonelist_zone (ac.preferred_zoneref); +if (!preferred_zone) + goto failed; +/* Find an allowed local zone that meets the low watermark. */ z = ac.preferred_zoneref; for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
@@ -5264,8 +5279,8 @@ unsigned long alloc_pages_bulk_noprof(gfcontinue ; } -if (nr_online_nodes >1 && zone !=zonelist_zone (ac.preferred_zoneref) && -zone_to_nid (zone) !=zonelist_node_idx (ac.preferred_zoneref)) { +if (nr_online_nodes >1 && zone != preferred_zone && +zone_to_nid (zone) !=zone_to_nid (preferred_zone)) { goto failed; }
@@ -5273,7 +5288,7 @@ unsigned long alloc_pages_bulk_noprof(gf retry_this_zone: mark =wmark_pages (zone, alloc_flags &ALLOC_WMARK_MASK ) + nr_pages - nr_populated;if (zone_watermark_fast (zone,0 , mark, -zonelist_zone_idx (ac.preferred_zoneref), +zone_idx (preferred_zone), alloc_flags, gfp)) {break ; }
@@ -5330,7 +5345,7 @@ retry_this_zone:pcp_spin_unlock (pcp);__count_zid_vm_events (PGALLOC ,zone_idx (zone), nr_account); -zone_statistics (zonelist_zone (ac.preferred_zoneref), zone, nr_account); +zone_statistics (preferred_zone, zone, nr_account); out:return nr_populated;
Greg Kroah-Hartman
maintainerPATCH 608/1005 mm/page_alloc: clear ->private of deferred free pages
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit aae6b83fe47ed8bff9195efbe1d191ec52e5436e upstream.
free_pages_nolock() and free_frozen_pages_nolock() put the page on zone->trylock_free_pages if they get neither the pcp lock nor zone->lock. add_page_to_zone_llist() keeps the order of the page in page->private. The next free_one_page() which does get zone->lock passes these pages to split_large_buddy() with ->private still set.
__free_one_page() writes ->private of the head of the resulting free page only. If the deferred page is merged with its lower buddy, it becomes a tail of that free page and keeps the order in ->private.
All other free pages which are not the head of a buddy have a ->private of zero, and since commit 819bfbd47e49 ("mm/page_alloc: remove set_page_private() in prep_compound_tail()") the allocator relies on it. When the stale page is allocated again as a tail of a larger page:
- prep_compound_tail() hits VM_WARN_ON_ONCE(tail->private);
- with the page checks enabled, __free_pages_prepare() reports "BUG: Bad page state", "nonzero private", and leaks the whole page;
- without them the value is seen by whoever uses that page next, e.g. as folio->private of a folio which is split off a large folio.
Only pages of an order above zero are affected. Those can be freed through _nolock() by the stack depot (order 2) and by SLUB (a new slab which cannot be added to the partial list by kmalloc_nolock()).
Clear ->private when the page is taken off the list.
--- mm/page_alloc.c | 2 ++ 1 file changed, 2 insertions(+)
mm/page_alloc.c +2 -0
@@ -1580,6 +1580,8 @@ static void free_one_page(struct zone *zllist_for_each_entry_safe (p, tmp, llnode, pcp_llist) {unsigned int p_order = p->private; +/* It may end up as a tail of the merged free page. */ + p->private =0 ;split_large_buddy (zone, p,page_to_pfn (p), p_order, fpi_flags);__count_vm_events (PGFREE ,1 << p_order); }
Greg Kroah-Hartman
maintainerPATCH 609/1005 mm/page_alloc: remove the zone_spans_pfn() check from get_pfnblock_bitmap_bitidx()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vlastimil Babka (SUSE) <[email protected]>
commit 2122887b04f3f2d76daa80055c2c273926032fa0 upstream.
Whenever the flags of a pageblock are read or written, a kernel with CONFIG_DEBUG_VM makes sure that the pfn lies within the zone of the page. Unlike bad_range(), that check reads zone->zone_start_pfn and zone->spanned_pages without zone->span_seqlock.
Memory hotplug changes the two fields one after the other. If the lower end of a zone moves, the zone seems to end before its last pages in between. A page of that part which is freed at that moment, on another CPU, ends in
page dumped because: VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn)) kernel BUG at mm/page_alloc.c:372! free_unref_folios+0x55e/0xed0 folios_put_refs+0x2b5/0x530
An attempt has been made [1] to fix this with the span seqlock check. But that can trigger all sorts of problems in restricted contexts, as noted by sashiko [2].
Since this is just a sanity debug check and anything with BUG_ON is frowned upon anyway, just remove it altogether.
--- mm/page_alloc.c | 1 - 1 file changed, 1 deletion(-)
mm/page_alloc.c +0 -1
@@ -370,7 +370,6 @@ get_pfnblock_bitmap_bitidx(const structBUILD_BUG_ON (NR_PAGEBLOCK_BITS !=4 );#endif BUILD_BUG_ON (__MIGRATE_TYPE_END >PAGEBLOCK_MIGRATETYPE_MASK ); -VM_BUG_ON_PAGE (!zone_spans_pfn (page_zone (page), pfn), page); bitmap =get_pageblock_bitmap (page, pfn); *bitidx =pfn_to_bitidx (page, pfn);
Greg Kroah-Hartman
maintainerPATCH 610/1005 ACPI: APEI: GHES: Fix severity check in ghes_log_hwerr()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Breno Leitao <[email protected]>
commit cf12faa1e76d43f97b1486aaec959b16baca498a upstream.
ghes_log_hwerr() is meant to count recoverable GHES errors in hwerror_data[], but it skips them and counts informational records instead. As a result, recoverable CPU, memory, CXL and vendor-specific errors reported through GHES never show up in a vmcore.
ghes_do_proc() passes ghes_log_hwerr() the record severity after ghes_severity() has converted it to a GHES_SEV_* value. ghes_log_hwerr() compares it against CPER_SEV_RECOVERABLE, which is 0 in the CPER enum and matches GHES_SEV_NO, so only informational records pass and GHES_SEV_RECOVERABLE ones return early.
Compare against GHES_SEV_RECOVERABLE instead.
Recoverable PCIe errors that ghes_handle_aer() hands to AER are also counted by pci_dev_aer_stats_incr(), so with the check fixed they are counted twice under HWERR_RECOV_PCI. That is not addressed here.
--- drivers/acpi/apei/ghes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/acpi/apei/ghes.c +1 -1
@@ -912,7 +912,7 @@ EXPORT_SYMBOL_NS_GPL(cxl_cper_kfifo_get,static void ghes_log_hwerr (int sev,guid_t *sec_type) { -if (sev !=CPER_SEV_RECOVERABLE ) +if (sev !=GHES_SEV_RECOVERABLE )return ; if (guid_equal(sec_type, &CPER_SEC_PROC_ARM) ||
Greg Kroah-Hartman
maintainerPATCH 611/1005 bootconfig: Trim unquoted values at end of file
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eduardo Mucelli Rezende Oliveira <[email protected]>
commit 381b391bfaa3f10d52da4740529804b0b6b8160d upstream.
__xbc_parse_value() trims an unquoted value when it encounters a delimiter, but leaves trailing whitespace intact when it reaches the end
of the input. Thus "key = value " has a different value depending on
whether the file ends with a newline. The extra whitespace also reaches the rendered kernel command line.
Trim unquoted values after the scan finishes, including at end of input. Skip trimming after a closing quote so intentional whitespace in quoted values remains unchanged. Add checks for scalars, arrays and quoted values without a final newline.
--- lib/bootconfig.c | 5 +++-- tools/bootconfig/test-bootconfig.sh | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-)
lib/bootconfig.c +3 -2
@@ -790,16 +790,17 @@ static int __init __xbc_parse_value(charreturn xbc_parse_error ("No value delimiter" , p);if (*p) p++; -break ; + goto skip_trim; }if (strchr (",;\n#}" , c)) { *p++ ='\0' ; - v =strim (v);break ; } }if (quotes)return xbc_parse_error ("No closing quotes" , p); + v =strim (v); +skip_trim:if (c =='#' ) { p =skip_comment (p); c ='\n' ;/* A comment must be treated as a newline */
tools/bootconfig/test-bootconfig.sh +18 -0
@@ -171,6 +171,24 @@ $BOOTCONF $INITRD > $OUTFILE xfail grep -q 'val[[:space:]]' $OUTFILE xpass grep -q 'val2[[:space:]]' $OUTFILE +echo "Remove unquoted trailing whitespace at end of file" +printf 'foo = val \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Remove trailing whitespace from the last array value at end of file" +printf 'foo = first, last \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "first", "last"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Keep quoted trailing whitespace at end of file" +printf 'foo = "val "' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val "\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + echo "Showing correct line:column of no closing brace" cat > $TEMPCONF << EOF foo {
Greg Kroah-Hartman
maintainerPATCH 612/1005 btrfs: fix bio counter and bioc leak when async checksumming fails
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mani Tofigh <[email protected]>
commit d27d0039bc1334be8a72c769e14c0b0c3efc317d upstream.
A single failed checksum allocation can make a later device replace hang forever. btrfs_submit_chunk() takes a dev-replace bio counter reference and a bioc before it hands a write to the checksum worker. If the checksum fails there (e.g., its allocation fails), run_one_async_done() ends the bio but drops neither. The counter then never gets back to zero and the next replace waits for it:
[ 8.369] BTRFS info (device ram0): dev_replace from /dev/ram0 (devid 1) to /dev/ram1 finished [41.534] INFO: task btrfscsum:80 blocked for more than 20 seconds. [41.534] btrfs_rm_dev_replace_blocked+0x135/0x180 [41.534] btrfs_dev_replace_finishing+0xefe/0x13b0
The worker is only used when CONFIG_BTRFS_EXPERIMENTAL is off and the checksum isn't a fast one, e.g., sha256. We hit it on a sha256 filesystem.
We put the bioc and drop the counter in that error branch. We also put the bioc on the synchronous error path and on the btrfs_split_bio() error path, which both only drop the counter. With the fix, the replace doesn't hang anymore.
This bug was identified and confirmed with the help of fault-injection testing on a deterministic hypervisor currently under development. Our C reproducer however hits it within about 35s.
--- fs/btrfs/bio.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/btrfs/bio.c +4 -0
@@ -634,6 +634,8 @@ static void run_one_async_done(struct bt/* If an error occurred we just want to clean up the bio and move on. */ if (bio->bi_status) { +btrfs_put_bioc (async->bioc); +btrfs_bio_counter_dec (async->bbio->inode->root->fs_info);btrfs_bio_end_io (async->bbio, bio->bi_status);return ; }
@@ -772,6 +774,7 @@ static bool btrfs_submit_chunk(struct bt split =btrfs_split_bio (fs_info, bbio, map_length);if (IS_ERR (split)) { status =errno_to_blk_status (PTR_ERR (split)); +btrfs_put_bioc (bioc);btrfs_bio_counter_dec (fs_info); goto end_bbio; }
@@ -832,6 +835,7 @@ done:return map_length == length; fail: +btrfs_put_bioc (bioc);btrfs_bio_counter_dec (fs_info);/* * We have split the original bbio, now we have to end both the current
Greg Kroah-Hartman
maintainerPATCH 613/1005 btrfs: reject refs=0 subvolume without DEAD in SUBVOL_SYNC_WAIT
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cheng Yongkang <[email protected]>
commit 9a58e56e70f610e29b53821e9c706600e529cca3 upstream.
btrfs_ioctl_subvol_sync() assumes that a cached root with zero references has BTRFS_ROOT_SUBVOL_DEAD set, and asserts that before waiting for the cleaner. Two states break the assumption:
- A corrupt ROOT_ITEM with zero references and a matching orphan item, on a writable filesystem.
- A failed subvolume deletion. btrfs_delete_subvolume() zeroes the root references, aborts the transaction, which forces the filesystem read-only, and then clears DEAD again. No on-disk metadata is corrupted in this case.
With CONFIG_BTRFS_ASSERT=y, both reach a BUG().
Change the ASSERT() into a proper rejection to avoid triggering a BUG().
--- fs/btrfs/ioctl.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
fs/btrfs/ioctl.c +6 -2
@@ -5173,8 +5173,12 @@ static int btrfs_ioctl_subvol_sync(strucreturn -ENOENT ; wait_for_deletion = true; -ASSERT (root_flags &BTRFS_ROOT_SUBVOL_DEAD ,"root_flags=0x%llx" , - root_flags); +if (unlikely (!(root_flags &BTRFS_ROOT_SUBVOL_DEAD ))) { +btrfs_err (fs_info, +"subvol %llu has refs 0 without DEAD flag" , + args.subvolid); +return -EUCLEAN ; + } sched_ret =schedule_timeout_interruptible (HZ );/* Early wake up or error. */ if (sched_ret !=0 )
Greg Kroah-Hartman
maintainerPATCH 614/1005 coda: honor the append state of each write
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit 87ea037a9166a5842356ce68e3585fc6e756603b upstream.
coda_open() adds O_APPEND to the container file's f_flags after it has been opened, without updating its cached f_iocb_flags. An O_APPEND write can therefore overwrite existing data instead of appending. For example, writing "Z" to a file containing "abc" produces "Zbc" rather than "abcZ".
Pass RWF_APPEND or RWF_NOAPPEND to vfs_iter_write() according to the incoming IOCB_APPEND state. This also honors changes made with F_SETFL and per-write append overrides instead of relying on the container's open-time flags.
--- fs/coda/file.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/coda/file.c +2 -1
@@ -71,6 +71,7 @@ coda_file_write_iter(struct kiocb *iocb,struct file *host_file = cfi->cfi_container;loff_t ki_pos = iocb->ki_pos;size_t count =iov_iter_count (to); +rwf_t flags = (iocb->ki_flags &IOCB_APPEND ) ?RWF_APPEND :RWF_NOAPPEND ;ssize_t ret; ret = venus_access_intent(coda_inode->i_sb, coda_i2f(coda_inode),
@@ -80,7 +81,7 @@ coda_file_write_iter(struct kiocb *iocb, goto finish_write;inode_lock (coda_inode); - ret =vfs_iter_write (cfi->cfi_container, to, &iocb->ki_pos,0 ); + ret =vfs_iter_write (cfi->cfi_container, to, &iocb->ki_pos, flags); coda_inode->i_size =file_inode (host_file)->i_size; coda_inode->i_blocks = (coda_inode->i_size +511 ) >>9 ;inode_set_mtime_to_ts (coda_inode,inode_set_ctime_current (coda_inode));
Greg Kroah-Hartman
maintainerPATCH 615/1005 entry: Complete syscall_enter_from_user_mode_work() to bool migration
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Florian Bezdeka <[email protected]>
commit efe191f1605a149b06eb0fe1ff975e7d3137c9bb upstream.
The return type of syscall_enter_from_user_mode_work() was changed to bool in the commit referenced below.
While doing so, one caller in syscall_enter_from_user_mode_randomize_stack() was overlooked and stayed at the previous type: long.
Update this caller accordingly.
--- include/linux/entry-common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/entry-common.h +1 -1
@@ -202,7 +202,7 @@ do { \ \instrumentation_begin (); \local_irq_enable (); \ -long _ret =syscall_enter_from_user_mode_work (regs, syscall); \ +bool _ret =syscall_enter_from_user_mode_work (regs, syscall); \instrumentation_end (); \ \ _ret; \
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 616/1005 entry: Fix return type of syscall_trace_enter()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Florian Bezdeka <[email protected]>
commit 75b1663222d7aa0b3c33cc3522a347757e6d1d26 upstream.
All return values of syscall_trace_enter() were migrated to bool in commit 71ff30013f19 ("entry: Make return type of syscall_trace_enter() bool"), but the function declaration has not been updated.
Fix that up now.
--- include/linux/entry-common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/entry-common.h +1 -1
@@ -62,7 +62,7 @@ void trace_syscall_enter(struct pt_regs *regs);void trace_syscall_exit (struct pt_regs *regs,long ret);void syscall_enter_audit (struct pt_regs *regs); -static __always_inline long syscall_trace_enter (struct pt_regs *regs,unsigned long work, +static __always_inline bool syscall_trace_enter(struct pt_regs *regs, unsigned long work,long syscall) {/*
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 617/1005 net: dst_metadata: fix memcmp overread in skb_metadata_dst_cmp
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jean-Paul Sergent <[email protected]>
commit 74a7db839308dd7d1c3f72dd1e3299784df3affb upstream.
Commit 3fcece12bc1b6 ("net: store port/representator id in metadata_dst") dropped the options_len equality check when converting skb_metadata_dst_cmp() to a type switch, so the memcmp length is taken from skb a alone. When skb b carries fewer options than a, the comparison reads past b's allocation.
Hit in practice with Cilium geneve GRO aggregation, comparing an skb carrying 12 bytes of tunnel options against one carrying none:
memcmp: detected buffer overflow: 108 byte read of buffer size 96
WARNING: CPU: 0 PID: 15 at lib/string_helpers.c:1036 __fortify_report __fortify_panic+0x9/0x10 skb_metadata_dst_cmp+0x11b/0x120 dev_gro_receive+0x303/0x620 gro_cell_poll+0x67/0xa0
Restore the check: unequal options_len means different metadata and no aggregation; the memcmp only runs when both sides carry the same options length.
--- include/net/dst_metadata.h | 2 ++ 1 file changed, 2 insertions(+)
include/net/dst_metadata.h +2 -0
@@ -116,6 +116,8 @@ static inline int skb_metadata_dst_cmp(creturn memcmp (&a->u.port_info, &b->u.port_info,sizeof (a->u.port_info));case METADATA_IP_TUNNEL : +if (a->u.tun_info.options_len != b->u.tun_info.options_len) +return 1 ;return memcmp (&a->u.tun_info, &b->u.tun_info,sizeof (a->u.tun_info) + a->u.tun_info.options_len);
Greg Kroah-Hartman
maintainerPATCH 618/1005 liveupdate: check for duplicate session before growing block set
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Aurich Zanettini Martins <[email protected]>
commit cc448e44f6e9fc83f1527f926f52ebfa5a3d1ce9 upstream.
luo_session_insert() grows the outgoing block set before checking for a duplicate session name. On -EEXIST the new block stays in the set.
If the session count is an exact multiple of the per-block capacity (51 with 4K pages), that block stays empty. It is serialized with count 0, which kho_block_set_restore() rejects in the next kernel:
luo: Block contains invalid entry count: 0
Kernel panic - not syncing: The incoming tree failed to initialize properly [-EINVAL], disabling live update
Check for the duplicate before growing the block set, as luo_preserve_file() does with the token.
--- kernel/liveupdate/luo_session.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-)
kernel/liveupdate/luo_session.c +11 -10
@@ -177,16 +177,6 @@ static int luo_session_insert(struct luoguard (rwsem_write)(&sh->rwsem);/* -* For outgoing we should make sure there is room in serialization array -* for new session. -*/ -if (sh == &luo_session_global.outgoing) { - err =kho_block_set_grow (&sh->block_set, sh->count +1 ); -if (err) -return err; - } - -/* * For small number of sessions this loop won't hurt performance * but if we ever start using a lot of sessions, this might * become a bottle neck during deserialization time, as it would
@@ -196,6 +186,17 @@ static int luo_session_insert(struct luoif (!strncmp (it->name, session->name,sizeof (it->name)))return -EEXIST ; } + +/* +* For outgoing we should make sure there is room in serialization array +* for new session. +*/ +if (sh == &luo_session_global.outgoing) { + err =kho_block_set_grow (&sh->block_set, sh->count +1 ); +if (err) +return err; + } +list_add_tail (&session->list, &sh->list); sh->count++;
Greg Kroah-Hartman
maintainerPATCH 619/1005 macsec: reject frames that decapsulate into runt Ethernet frames
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 1d5e2c57e9ffc134e14b3f837c8d7c53b508bd22 upstream.
When an SCI is unknown and the C bit is clear, macsec_handle_frame() removes the SecTAG and the default ICV without checking how much of the frame remains. A short frame can therefore become an skb shorter than ETH_HLEN. eth_type_trans() cannot pull its Ethernet header, and a second stacked MACsec device can copy stale skb headroom into a packet delivered to a packet socket.
The matched-SCI path has a related hole: macsec_validate_skb() accepts a short_length of one, so a frame that passes the existing length check can still become a 13-byte Ethernet frame.
Require enough bytes for the MACsec overhead and a complete Ethernet header before decapsulating an unknown-SCI frame. Apply the same bound in macsec_validate_skb(), using the selected SecY's ICV length, to cover the no-SA, synchronous-decrypt and asynchronous-decrypt delivery paths. Leave other unknown-SCI handling unchanged.
--- drivers/net/macsec.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/net/macsec.c +10 -5
@@ -407,8 +407,10 @@ static bool macsec_validate_skb(struct sint len = skb->len -2 *ETH_ALEN ;int extra_len =macsec_extra_len (!!(h->tci_an &MACSEC_TCI_SC )) + icv_len; -/* a) It comprises at least 17 octets */ -if (skb->len <=16 ) +/* a) It comprises at least 17 octets. The SecTAG and ICV must +* also leave a complete Ethernet header. +*/ +if (skb->len <ETH_HLEN + extra_len)return false;/* b) MACsec EtherType: already checked */
@@ -1330,9 +1332,12 @@ drop_direct: nosci:/* 10.6.1 if the SC is not found */ cbit = !!(hdr->tci_an &MACSEC_TCI_C ); -if (!cbit) -macsec_finalize_skb (skb,MACSEC_DEFAULT_ICV_LEN , -macsec_extra_len (macsec_skb_cb (skb)->has_sci)); +if (!cbit) { + len =macsec_extra_len (macsec_skb_cb (skb)->has_sci); +if (skb->len <ETH_HLEN + len +MACSEC_DEFAULT_ICV_LEN ) + goto drop_nosc; +macsec_finalize_skb (skb,MACSEC_DEFAULT_ICV_LEN , len); + }list_for_each_entry_rcu (macsec, &rxd->secys, secys) {struct sk_buff *nskb;
Greg Kroah-Hartman
maintainerPATCH 620/1005 mctp: accept MSG_CMSG_COMPAT in recvmsg
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Davidlohr Bueso <[email protected]>
commit 350e1d0d3b386fcc0cff2d37aa920fab4800bf72 upstream.
32-bit userspace running on a 64-bit kernel is unable to receive MCTP messages on an AF_MCTP socket, even though sending succeeds. There is nothing for MCTP to do with it beyond not rejecting it, as af_packet, af_key and can/isotp already do, for example.
--- net/mctp/af_mctp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/mctp/af_mctp.c +1 -1
@@ -292,7 +292,7 @@ static int mctp_recvmsg(struct socket *su8 type;int rc; -if (flags & ~(MSG_DONTWAIT |MSG_TRUNC |MSG_PEEK )) +if (flags & ~(MSG_DONTWAIT |MSG_TRUNC |MSG_PEEK |MSG_CMSG_COMPAT ))return -EOPNOTSUPP ; skb =skb_recv_datagram (sk, flags, &rc);
Greg Kroah-Hartman
maintainerPATCH 621/1005 net/mlx5e: Fix queue stats access to queues without stats
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Breno Leitao <[email protected]>
commit 9a24799e219b1699bb1c144248c8c500b9504db5 upstream.
I am seeing the following mlx5e crash in the Meta fleet:
pc : mlx5e_get_queue_stats_rx+0x4c/0xc8 Call trace: mlx5e_get_queue_stats_rx+0x4c/0xc8 (P) netdev_stat_queue_sum+0x78/0x480 netdev_nl_qstats_get_dump_one+0xf0/0x268 netdev_nl_qstats_get_dumpit+0x7c/0x1f8
When dumping device-wide qstats, the core calls the per-queue callbacks for every queue below real_num_{rx,tx}_queues, regardless of whether the netdev is up. Some of those queues have no stats behind them:
- RX stats live in priv->channel_stats[], which only has entries for channels that have been opened (stats_nch). real_num_rx_queues can be larger, for example after the channel count is raised while the netdev is down, or after opening the channels failed part way.
- TX stats are looked up in priv->txq2sq_stats[], which is NULL for SQs that were never activated and for HTB queues while the channels are closed.
In both cases the callback dereferences a NULL pointer. The dump needs no privileges, so any user can trigger it.
Return early for RX queues at or above stats_nch and for TX queues without SQ stats.
--- drivers/net/ethernet/mellanox/mlx5/core/en_main.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/net/ethernet/mellanox/mlx5/core/en_main.c +4 -1
@@ -5490,7 +5490,7 @@ static void mlx5e_get_queue_stats_rx(strstruct mlx5e_rq_stats *xskrq_stats;struct mlx5e_rq_stats *rq_stats; -if (mlx5e_is_uplink_rep (priv) || !mlx5e_stats_nch_read (priv)) +if (mlx5e_is_uplink_rep (priv) || i >=mlx5e_stats_nch_read (priv))return ; channel_stats = priv->channel_stats[i];
@@ -5522,6 +5522,9 @@ static void mlx5e_get_queue_stats_tx(str* inactive sqs. */ sq_stats = priv->txq2sq_stats[i]; +if (!sq_stats) +return ; + stats->packets = sq_stats->packets; stats->bytes = sq_stats->bytes;
Greg Kroah-Hartman
maintainerPATCH 622/1005 net/mlx5e: SHAMPO, Disable end padding when relaxed ordering is supported
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiabin Deng <[email protected]>
commit 68c183619f24982a635930697bf8e148f2d78f71 upstream.
When SHAMPO and relaxed ordering writes are enabled, aligned RQ end padding can corrupt received TCP data. Due to reordering, alignment padding written at the end of one packet can overwrite data from the next packet.
The current RQ end padding selection avoids alignment padding for LRO, but not for SHAMPO. Extend the condition to SHAMPO to prevent this corruption.
The issue was observed in a two-host test using a BlueField-3 NIC and an NVIDIA H20 GPU. In the original test with MTU 1500, 354 of 400 transfers contained corrupted data before the fix. After applying this change, all 400 transfers across eight message sizes from 32 KiB to 4 MiB, with 50 transfers per size, completed successfully, with no incorrect bytes or corrupted intervals.
--- drivers/net/ethernet/mellanox/mlx5/core/en/params.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en/params.c +3 -2
@@ -911,10 +911,11 @@ static void mlx5e_build_rx_cq_param(strustatic u8 rq_end_pad_mode (struct mlx5_core_dev *mdev,struct mlx5e_params *params) { -bool lro_en = params->packet_merge.type ==MLX5E_PACKET_MERGE_LRO ; +bool no_pad = params->packet_merge.type ==MLX5E_PACKET_MERGE_LRO || + params->packet_merge.type ==MLX5E_PACKET_MERGE_SHAMPO ;bool ro =MLX5_CAP_GEN (mdev, relaxed_ordering_write); -return ro && lro_en ? +return ro && no_pad ?MLX5_WQ_END_PAD_MODE_NONE :MLX5_WQ_END_PAD_MODE_ALIGN ; }
Greg Kroah-Hartman
maintainerPATCH 623/1005 net/rds: Do not unpin a page after a failed atomic pin
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 8d5ce4751fad9499ea408163af7f410f18a85782 upstream.
rds_cmsg_atomic() assumes that a non-NULL output from rds_pin_pages() represents a pin that it owns. However, pin_user_pages_fast() can roll back a fast-GUP pin after racing fork() and then fail in the slow path, for example after a concurrent mprotect(PROT_NONE). The output slot can still contain the already-unpinned page.
The common error path calls unpin_user_page() on that stale pointer. This can consume another subsystem's pin and allow the page to be freed while it is still in use. A local unprivileged reproducer triggers a KASAN use-after-free write through an io_uring registered buffer.
Clear page when rds_pin_pages() does not return one. The error path continues to release the page on errors after a successful pin, and successful requests retain their existing ownership and behavior. All four RDS atomic ancillary operations share this path.
The issue was found by an LLM.
--- net/rds/rdma.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
net/rds/rdma.c +4 -1
@@ -957,8 +957,11 @@ int rds_cmsg_atomic(struct rds_sock *rs, } ret =rds_pin_pages (args->local_addr,1 , &page,1 ); -if (ret !=1 ) +if (ret !=1 ) { +/* A failed pin can leave a stale page pointer. */ + page =NULL ; goto err; + } ret =0 ;sg_set_page (rm->atomic.op_sg, page,8 ,offset_in_page (args->local_addr));
Greg Kroah-Hartman
maintainerPATCH 624/1005 net/smc: fix lgr/lnk lifetime vs diag reader race
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mahanta Jambigi <[email protected]>
commit d7900fa51642fbc2a5a03354238e71050a7d391d upstream.
The diag dump walks the socket hash table under a read_lock and dereferences conn->lgr and conn->lnk. Several paths expose a window where a hashed socket has freed or partially freed conn/lgr/lnk state.
First, smc_conn_abort() calls smc_conn_free() during early handshake aborts while the socket is still hashed in SMC_INIT, synchronously freeing the lgr on the smc_lgr_cleanup_early() path without holding the hash write_lock. A concurrent diag reader can load a non-NULL conn->lgr and dereference it after the kfree. Skip the connection, link group and DMB attributes in __smc_diag_dump() for sockets in SMC_INIT or SMC_CLOSED or fallen back to TCP, and take diag_mode from an is_smcd flag cached at connection creation.
The state filter alone does not close the race. A connection aborted by a failed handshake can keep its alert token, because smc_conn_free() skips the unregister when smc_lgr_terminate_sched() has emptied lgr->list; close_work may also have been queued before the abort, as the CDC receive path is not excluded by the handshake's socket lock. smc_close_passive_work() would then move the hashed socket from SMC_INIT to SMC_APPCLOSEWAIT1 or SMC_PROCESSABORT, states the filter does not cover, and later run a passive-closing sock_put() that smc_connect_decline_fallback() dropped already. Return early from smc_close_passive_work() when the connection was freed; the check holds the socket lock that every smc_conn_free() caller holds as well, so a hashed socket with a freed connection stays in SMC_INIT or SMC_CLOSED until release.
This changes the sock_diag output for such sockets: the connection, link group and DMB attributes are omitted, which smcss does not read for sockets in these states, while SMC_DIAG_FALLBACK is still reported and an SMC-D socket in SMC_INIT or SMC_CLOSED still reports SMC_DIAG_MODE_SMCD from the cached flag. A fallback socket is a plain TCP socket with no SMC connection state to report; the stale conn fields left behind by smc_conn_abort() must not be read.
Second, in smc_conn_kill() on SMC-D with dmb_nocopy, smcd_buf_detach() NULLs and frees conn->sndbuf_desc while the socket is still hashed. A concurrent diag reader entering the CONNINFO block can dereference the freed descriptor. Unhash the socket right before smcd_buf_detach(). As a result, killed ACTIVE and APPCLOSEWAIT sockets that are still open are no longer visible to smcss on loopback-ism devices.
Third, in the terminal teardown branches of smc_close_active_abort() (PEERCLOSEWAIT and PROCESSABORT groups) and in smc_close_passive_work(), smc_conn_free() drops lgr and lnk references while the socket is still hashed. Unhash immediately before each smc_conn_free() call at those sites. Sockets killed in those close states are therefore unhashed, and their inuse accounting dropped, before close(), even if the fd is still open.
Fourth, use smp_load_acquire() / smp_store_release() on sk_state to order these checks on weakly ordered CPUs. A reader that observes SMC_ACTIVE is guaranteed to see the connection setup that preceded the store; a reader that observes SMC_CLOSED from smc_listen_out_err() skips the connection fields in any case, so that particular store is hardening kept for uniformity, not a required ordering.
Additionally, in __smc_diag_dump(), use the cached link->ibname instead of link->smcibdev->ibdev->name, avoiding a NULL pointer dereference or use-after-free of the IB device when __smcr_link_clear() zeroes the link during concurrent SMC-R link failover. The link data is still read without conns_lock or send_lock, so a dump racing a failover may transiently report zeroed or mixed link fields; this does not affect memory safety and the next dump reports the new link. Like the SMC netlink link dump and the tracepoints, the name is the one cached at link creation time.
--- net/smc/af_smc.c | 10 +++++----- net/smc/smc.h | 1 + net/smc/smc_close.c | 14 ++++++++++++++ net/smc/smc_core.c | 8 +++++++- net/smc/smc_diag.c | 12 ++++++++---- 5 files changed, 35 insertions(+), 10 deletions(-)
net/smc/af_smc.c +5 -5
@@ -976,7 +976,7 @@ static int smc_connect_fallback(struct ssmc_copy_sock_settings_to_clc (smc); smc->connect_nonblock =0 ;if (smc->sk.sk_state ==SMC_INIT ) - smc->sk.sk_state =SMC_ACTIVE ; +smp_store_release (&smc->sk.sk_state,SMC_ACTIVE );return 0 ; }
@@ -1381,7 +1381,7 @@ static int smc_connect_rdma(struct smc_ssmc_copy_sock_settings_to_clc (smc); smc->connect_nonblock =0 ;if (smc->sk.sk_state ==SMC_INIT ) - smc->sk.sk_state =SMC_ACTIVE ; +smp_store_release (&smc->sk.sk_state,SMC_ACTIVE );return 0 ; connect_abort:
@@ -1484,7 +1484,7 @@ static int smc_connect_ism(struct smc_sosmc_copy_sock_settings_to_clc (smc); smc->connect_nonblock =0 ;if (smc->sk.sk_state ==SMC_INIT ) - smc->sk.sk_state =SMC_ACTIVE ; +smp_store_release (&smc->sk.sk_state,SMC_ACTIVE );return 0 ; connect_abort:
@@ -1951,7 +1951,7 @@ static void smc_listen_out_connected(strstruct sock *newsmcsk = &new_smc->sk;if (newsmcsk->sk_state ==SMC_INIT ) - newsmcsk->sk_state =SMC_ACTIVE ; +smp_store_release (&newsmcsk->sk_state,SMC_ACTIVE );smc_listen_out (new_smc); }
@@ -1965,7 +1965,7 @@ static void smc_listen_out_err(struct smthis_cpu_inc (net->smc.smc_stats->srv_hshake_err_cnt);if (newsmcsk->sk_state ==SMC_INIT )sock_put (&new_smc->sk);/* passive closing */ - newsmcsk->sk_state =SMC_CLOSED ; +smp_store_release (&newsmcsk->sk_state,SMC_CLOSED );smc_listen_out (new_smc); }
net/smc/smc.h +1 -0
@@ -196,6 +196,7 @@ struct smc_connection {struct rb_node alert_node;struct smc_link_group *lgr;/* link group of connection */ struct smc_link *lnk;/* assigned SMC-R link */ +bool is_smcd;/* SMC-R or SMC-D connection */ u32 alert_token_local;/* unique conn. id */ u8 peer_rmbe_idx;/* from tcp handshake */ int peer_rmbe_size;/* size of peer rx buffer */
net/smc/smc_close.c +14 -0
@@ -154,6 +154,7 @@ void smc_close_active_abort(struct smc_sif (sk->sk_state !=SMC_PEERABORTWAIT )break ; sk->sk_state =SMC_CLOSED ; + sk->sk_prot->unhash (sk);smc_conn_free (&smc->conn); release_clcsock = true;sock_put (sk);/* passive closing */
@@ -165,6 +166,7 @@ void smc_close_active_abort(struct smc_sif (sk->sk_state !=SMC_PEERABORTWAIT )break ; sk->sk_state =SMC_CLOSED ; + sk->sk_prot->unhash (sk);smc_conn_free (&smc->conn); release_clcsock = true;break ;
@@ -367,6 +369,17 @@ static void smc_close_passive_work(struclock_sock (sk); old_state = sk->sk_state; +if (conn->freed) { +/* conn->freed is set under the socket lock, which is +* held here as well, so this cannot race with the free; the +* state machine and its postponed sock_put() are not owed +* anymore +*/ +release_sock (sk); +sock_put (sk);/* sock_hold done by schedulers of close_work */ +return ; + } + rxflags = &conn->local_rx_ctrl.conn_state_flags;if (rxflags->peer_conn_abort) {/* peer has not received all data */
@@ -433,6 +446,7 @@ wakeup: sk->sk_state_change (sk);if ((sk->sk_state ==SMC_CLOSED ) && (sock_flag (sk,SOCK_DEAD ) || !sk->sk_socket)) { + sk->sk_prot->unhash (sk);smc_conn_free (conn);if (smc->clcsock) release_clcsock = true;
net/smc/smc_core.c +7 -1
@@ -1530,8 +1530,10 @@ static void smc_conn_kill(struct smc_contasklet_kill (&conn->rx_tsklet); else tasklet_unlock_wait(&conn->rx_tsklet); -if (smc_ism_support_dmb_nocopy (conn->lgr->smcd)) +if (smc_ism_support_dmb_nocopy (conn->lgr->smcd)) { + smc->sk.sk_prot->unhash (&smc->sk);smcd_buf_detach (conn); + } }else {smc_cdc_wait_pend_tx_wr (conn); }
@@ -2051,6 +2053,10 @@ create: goto out; } } +/* cache the connection type: smc_diag reads it after +* smc_conn_free() dropped the link group reference +*/ + conn->is_smcd = conn->lgr->is_smcd;smc_lgr_hold (conn->lgr);/* lgr_put in smc_conn_free() */ if (!conn->lgr->is_smcd)smcr_link_hold (conn->lnk);/* link_put in smc_conn_free() */
net/smc/smc_diag.c +8 -4
@@ -87,10 +87,10 @@ static int __smc_diag_dump(struct sock * r =nlmsg_data (nlh);smc_diag_msg_common_fill (r, sk); - r->diag_state = sk->sk_state; + r->diag_state =smp_load_acquire (&sk->sk_state);if (smc->use_fallback) r->diag_mode =SMC_DIAG_MODE_FALLBACK_TCP ; -else if (smc_conn_lgr_valid (&smc->conn) && smc->conn.lgr->is_smcd) +else if (smc->conn.is_smcd) r->diag_mode =SMC_DIAG_MODE_SMCD ;else r->diag_mode =SMC_DIAG_MODE_SMCR ;
@@ -103,6 +103,10 @@ static int __smc_diag_dump(struct sock *if (nla_put (skb,SMC_DIAG_FALLBACK ,sizeof (fallback), &fallback) <0 ) goto errout; +if (r->diag_state ==SMC_INIT || r->diag_state ==SMC_CLOSED || + smc->use_fallback) + goto out; +if ((req->diag_ext & (1 << (SMC_DIAG_CONNINFO -1 ))) && smc->conn.alert_token_local) {struct smc_connection *conn = &smc->conn;
@@ -154,8 +158,7 @@ static int __smc_diag_dump(struct sock * .lnk[0].link_id = link->link_id, }; -memcpy (linfo.lnk[0 ].ibname, link->smcibdev->ibdev->name, -sizeof (link->smcibdev->ibdev->name)); +memcpy (linfo.lnk[0 ].ibname, link->ibname,sizeof (link->ibname));smc_gid_be16_convert (linfo.lnk[0 ].gid, link->gid);smc_gid_be16_convert (linfo.lnk[0 ].peer_gid, link->peer_gid);
@@ -185,6 +188,7 @@ static int __smc_diag_dump(struct sock * goto errout; } +out:nlmsg_end (skb, nlh);return 0 ;
Greg Kroah-Hartman
maintainerPATCH 625/1005 net/smc: fix link group ownership in handshake abort
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mahanta Jambigi <[email protected]>
commit e227b511582828c5a6513f70fc6a71211e5efbf0 upstream.
An aborted first-contact handshake can hang the handshake worker on the socket lock it already holds, reset the clcsock of a socket that has fallen back to TCP, or corrupt the alert-node lookup when the handshake retries with the same connection.
The abort leaves a connection registered in a link group that another context has already unlinked for termination: smc_conn_free() skips the unregister when lgr->list is empty, so the alert token and alert node stay in lgr->conns_all. If the handshake retries another device or SMC version, smc_conn_create() creates a second link group and smc_lgr_register_conn() inserts the same alert node into it: the token loop is skipped, rb_link_node() links a node that is still in the old tree into the new one, and a second sock_hold() is taken where only one sock_put() will follow. The old group's terminator then keeps returning that node from rb_first() and can kill a connection that now belongs to the new group.
smc_lgr_cleanup_early() also starts a second termination of the link group that is already being terminated, which takes lock_sock() on the socket the handshake worker holds; if the termination work wins the race instead, it later kills the freed connection and aborts the clcsock of a socket that has fallen back to TCP. Making the unregister unconditional also lets smc_conn_free() reach the delayed free work on a claimed link group, where the lockless freeing check can arm it after the owner has cancelled it.
Always unregister the connection, claim a link group for termination once under lgr_lock, keep the link group alive across the abort, and arm the delayed free work only under the same lock and cancel it synchronously before the teardown. Drop an already freed connection in smc_conn_kill() without running the connection and socket teardown.
--- net/smc/af_smc.c | 11 ++++--- net/smc/smc_core.c | 78 ++++++++++++++++++++++++++++++++++++++--------------- net/smc/smc_core.h | 6 ++-- 3 files changed, 65 insertions(+), 30 deletions(-)
net/smc/af_smc.c +6 -5
@@ -1009,14 +1009,15 @@ static void smc_conn_abort(struct smc_so {struct smc_connection *conn = &smc->conn;struct smc_link_group *lgr = conn->lgr; -bool lgr_valid = false; - -if (smc_conn_lgr_valid (conn)) - lgr_valid = true; +bool lgr_valid = local_first &&smc_conn_lgr_valid (conn); +if (lgr_valid) +smc_lgr_hold (lgr);/* lgr_put below */ smc_conn_free (conn); -if (local_first && lgr_valid) +if (lgr_valid) {smc_lgr_cleanup_early (lgr); +smc_lgr_put (lgr); + } }/* check if there is a rdma device available for this connection. */
net/smc/smc_core.c +56 -22
143 lines not on this page · raw message
net/smc/smc_core.h +3 -3
@@ -301,9 +301,9 @@ struct smc_link_group {struct delayed_work free_work;/* delayed freeing of an lgr */ struct work_struct terminate_work;/* abnormal lgr termination */ struct workqueue_struct *tx_wq;/* wq for conn. tx workers */ - u8 sync_err : 1; /* lgr no longer fits to peer */ - u8 terminating : 1;/* lgr is terminating */ - u8 freeing : 1; /* lgr is being freed */ +u8 sync_err;/* lgr no longer fits to peer */ +u8 terminating;/* lgr is terminating */ +u8 freeing;/* lgr is being freed */ refcount_t refcnt;/* lgr reference count */ bool is_smcd;/* SMC-R or SMC-D */
Greg Kroah-Hartman
maintainerPATCH 626/1005 net: bridge: use one headroom snapshot for ND replies
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jun Yang <[email protected]>
commit e573df093ef849bb7c763aed591cb6556b110671 upstream.
br_nd_send() calls LL_RESERVED_SPACE(dev) once to size the reply skb and again to reserve its headroom. When a port requiring more headroom is added to the bridge, br_add_if() can increase dev->needed_headroom between the two calls. The reserved headroom can then exceed the space accounted for by alloc_skb().
Take one headroom snapshot and use it for both the allocation size and skb_reserve().
--- net/bridge/br_arp_nd_proxy.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
net/bridge/br_arp_nd_proxy.c +4 -2
@@ -262,6 +262,7 @@ static void br_nd_send(struct net_bridgestruct sk_buff *reply;struct ipv6hdr *pip6;int na_olen =8 ;/* opt hdr + ETH_ALEN for target */ +int headroom;int ns_olen;u8 *daddr;bool dad;
@@ -271,7 +272,8 @@ static void br_nd_send(struct net_bridgeif (!dev)return ; - len =LL_RESERVED_SPACE (dev) +sizeof (struct ipv6hdr ) + + headroom =LL_RESERVED_SPACE (dev); + len = headroom +sizeof (struct ipv6hdr ) +sizeof (*na) + na_olen + dev->needed_tailroom; reply =alloc_skb (len,GFP_ATOMIC );
@@ -280,7 +282,7 @@ static void br_nd_send(struct net_bridge reply->protocol =htons (ETH_P_IPV6 ); reply->dev = dev; -skb_reserve (reply,LL_RESERVED_SPACE (dev)); +skb_reserve (reply, headroom);skb_push (reply,sizeof (struct ethhdr ));skb_set_mac_header (reply,0 );
Greg Kroah-Hartman
maintainerPATCH 627/1005 net: dsa: microchip: initialize the IRQ access mutex
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tapio Reijonen <[email protected]>
commit ba1dc196502f3435f4ae53ed6745caacf066f83e upstream.
ksz_switch_register() initializes dev_mutex, regmap_mutex, alu_mutex and vlan_mutex but not lock_irq, which the IRQ chip takes in its bus lock callbacks on every mask and unmask of a switch interrupt, and the PTP code takes the same way. The zeroed mutex happens to work on the uncontended fast path, but with CONFIG_DEBUG_MUTEXES the first lock, from the IRQ domain mapping during probe, warns:
DEBUG_LOCKS_WARN_ON(lock->magic != lock)
WARNING: kernel/locking/mutex.c:625 at __mutex_lock ... ksz_irq_domain_map irq_domain_associate_locked irq_create_mapping_affinity ksz_irq_common_setup ksz9477_setup dsa_register_switch ksz_spi_probe
and turns lock debugging off for the rest of the boot.
Initialize it with the other mutexes.
Triggered at every boot of a KSZ9897S over SPI on an i.MX6 SoloX board with CONFIG_DEBUG_MUTEXES, on v7.4-rc1 and earlier. With this patch the same board boots with lock debugging enabled and it stays enabled (debug_locks 1) through two hours of unrelated stress tests.
--- drivers/net/dsa/microchip/ksz_common.c | 1 + 1 file changed, 1 insertion(+)
drivers/net/dsa/microchip/ksz_common.c +1 -0
@@ -3928,6 +3928,7 @@ int ksz_switch_register(struct ksz_devicmutex_init (&dev->regmap_mutex);mutex_init (&dev->alu_mutex);mutex_init (&dev->vlan_mutex); +mutex_init (&dev->lock_irq); ret =ksz_switch_detect (dev);if (ret)
Greg Kroah-Hartman
maintainerPATCH 628/1005 net: leave O_NONBLOCK to the sendmsg and recvmsg syscalls
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jens Axboe <[email protected]>
commit bdc350ddbcbe4788158019d4d8e8e9345cb16235 upstream.
____sys_sendmsg() and ____sys_recvmsg() turn O_NONBLOCK on the socket into MSG_DONTWAIT. That is right for the system calls, but io_uring uses __sys_sendmsg_sock() and __sys_recvmsg_sock() for a blocking attempt from io-wq as well, after the non-blocking attempts with MSG_DONTWAIT have failed. On an O_NONBLOCK socket that attempt can't block either and the request completes with -EAGAIN, unlike IORING_OP_SEND and RECV, which call sock_sendmsg() and sock_recvmsg() directly and don't look at O_NONBLOCK at all.
Move the O_NONBLOCK handling to ___sys_sendmsg() and ___sys_recvmsg(), which the sendmsg, sendmmsg, recvmsg and recvmmsg system calls go through. The io_uring helpers then pass the flags the caller asked for.
--- net/socket.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
net/socket.c +6 -5
@@ -2695,8 +2695,6 @@ static int ____sys_sendmsg(struct socket flags &= ~MSG_INTERNAL_SENDMSG_FLAGS ; msg_sys->msg_flags = flags; -if (sock->file->f_flags &O_NONBLOCK ) - msg_sys->msg_flags |=MSG_DONTWAIT ;/* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision.
@@ -2760,6 +2758,9 @@ static int ___sys_sendmsg(struct socket msg_sys->msg_name = &address; +if (sock->file->f_flags &O_NONBLOCK ) + flags |=MSG_DONTWAIT ; + err =sendmsg_copy_msghdr (msg_sys, msg, flags, &iov);if (err <0 )return err;
@@ -2924,9 +2925,6 @@ static int ____sys_recvmsg(struct socket/* We assume all kernel code knows the size of sockaddr_storage */ msg_sys->msg_namelen =0 ; -if (sock->file->f_flags &O_NONBLOCK ) - flags |=MSG_DONTWAIT ; -if (unlikely (nosec)) err =sock_recvmsg_nosec (sock, msg_sys, flags);else
@@ -2968,6 +2966,9 @@ static int ___sys_recvmsg(struct socketstruct sockaddr __user *uaddr;ssize_t err; +if (sock->file->f_flags &O_NONBLOCK ) + flags |=MSG_DONTWAIT ; + err =recvmsg_copy_msghdr (msg_sys, msg, flags, &uaddr, &iov);if (err <0 )return err;
Greg Kroah-Hartman
maintainerPATCH 629/1005 net: mana: report RX checksum offload for IPv6
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hamza Mahfooz <[email protected]>
commit bbcd02741c4cfbf9e1c59b1906f21ef772bd15eb upstream.
The hardware validates TCP and UDP checksums for both IPv4 and IPv6 and reports the result in rx_tcp_csum_succeed and rx_udp_csum_succeed. However, mana_rx_skb() also requires rx_iphdr_csum_succeed before it sets CHECKSUM_UNNECESSARY. That bit is only set for IPv4 (since IPv6 has no header checksum), so IPv6 TCP and UDP traffic is always checksummed again in software.
So, only look at the L4 result. For IPv4 this makes no material difference since CHECKSUM_UNNECESSARY only covers the L4 checksum, and ip_rcv_core() always verifies the IPv4 header checksum in software.
Between two Azure Standard_E16s_v6 VMs (VF enabled), IPv6 TCP and UDP packets (including VXLAN over IPv6), now arrive with CHECKSUM_UNNECESSARY instead of CHECKSUM_NONE, so GRO no longer checksums them in software. Calls to __skb_gro_checksum_complete() on the receiver during an 8 second iperf3 run:
before after
TCP/IPv4, 12.2 Gbps 23 28 TCP/IPv6, 12.1 Gbps 8728419 25 UDP/IPv6, 1.5 Gbps 1071380 20 TCP/VXLAN/IPv6, 10.9 Gbps 7934373 18
--- drivers/net/ethernet/microsoft/mana/mana_en.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
drivers/net/ethernet/microsoft/mana/mana_en.c +3 -4
@@ -2148,10 +2148,9 @@ static void mana_rx_skb(void *buf_va, boskb_checksum_none_assert (skb);skb_record_rx_queue (skb, rxq_idx); -if ((ndev->features &NETIF_F_RXCSUM ) && cqe->rx_iphdr_csum_succeed) { -if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed) - skb->ip_summed =CHECKSUM_UNNECESSARY ; - } +if ((ndev->features &NETIF_F_RXCSUM ) && + (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed)) + skb->ip_summed =CHECKSUM_UNNECESSARY ;if (cqe->rx_hashtype !=0 && (ndev->features &NETIF_F_RXHASH )) {if (cqe->rx_hashtype &MANA_HASH_L4 )
Greg Kroah-Hartman
maintainerPATCH 630/1005 net: netns: fix INT_MAX nsid cleanup
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Gongyi <[email protected]>
commit dd6f1e7582f0f7f12c2d620cf50446aa987d7327 upstream.
A syzkaller reproducer assigning INT_MAX as a peer nsid triggers an idr_get_next() warning during netns cleanup. With panic_on_warn, this panics the kernel.
alloc_netid() also overflows reqid + 1 for this nsid. Use idr_alloc_u32() for requested IDs and idr_get_next_ul() for cleanup so the cursor can advance past INT_MAX.
QEMU/KVM reproduced the warning without kernel changes or fault injection. The same reproducer ran without warnings after this change. Kernel selftests were not run.
--- net/core/net_namespace.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-)
net/core/net_namespace.c +11 -6
@@ -270,14 +270,19 @@ static void ops_undo_single(struct pernet_operations *ops,/* should be called with nsid_lock held */ static int alloc_netid (struct net *net,struct net *peer,int reqid) { -int min =0 , max =0 ; +int ret; +u32 id;if (reqid >=0 ) { - min = reqid; - max = reqid +1 ; + id = reqid; + ret =idr_alloc_u32 (&net->netns_ids, peer, &id, id, +GFP_ATOMIC ); +if (ret) +return ret; +return id; } -return idr_alloc (&net->netns_ids, peer, min, max,GFP_ATOMIC ); +return idr_alloc (&net->netns_ids, peer,0 ,0 ,GFP_ATOMIC ); }/* This function is used by idr_for_each(). If net is equal to peer, the
@@ -639,10 +644,10 @@ static void unhash_nsid(struct net *last)* use for_each_net_rcu() or net_rwsem. */ for_each_net (tmp) { -int id =0 ; +unsigned long id =0 ;spin_lock (&tmp->nsid_lock); -while ((peer =idr_get_next (&tmp->netns_ids, &id))) { +while ((peer =idr_get_next_ul (&tmp->netns_ids, &id))) {int curr_id = id; id++;
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 631/1005 net: stmmac: ptp: fix support for PTP_EXTTS_REQUEST2 ioctl
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Clark <[email protected]>
commit b66fca408bf85bb40f48a689daac75421f5283f8 upstream.
Commit 7c571ac57d9d ("net: ptp: introduce .supported_extts_flags to ptp_clock_info") modified the PTP core to validate the supported flags of external timestamp requests, rather than relying on each driver to check them.
stmmac_enable() and dwmac1000_ptp_enable() ignore the flags, and neither stmmac_ptp_clock_ops nor dwmac1000_ptp_clock_ops was given any .supported_extts_flags. Since PTP_EXTTS_REQUEST2 always implies PTP_STRICT_FLAGS, the core now rejects every PTP_EXTTS_REQUEST2 for this driver with -EOPNOTSUPP, where before that commit the same requests succeeded. Only the PTP_EXTTS_REQUEST ioctl still works.
Tests on an NXP i.MX 8M Plus (FRDM-IMX8MPLUS, GMAC 5.10a) show that the auxiliary snapshot inputs timestamp just the rising edge. The reference manuals for the STM32MP13 (GMAC 4.20a) and the Cyclone V HPS (GMAC 3.70a, which uses dwmac1000_ptp_clock_ops) say the same.
Encode this in .supported_extts_flags. A PTP_EXTTS_REQUEST2 for the rising edge then succeeds, and one for the falling edge or for both edges fails with -EOPNOTSUPP.
--- drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +2 -0
@@ -277,6 +277,7 @@ const struct ptp_clock_info stmmac_ptp_c .n_per_out = 0, /* will be overwritten in stmmac_ptp_register */ .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, .gettimex64 = stmmac_get_timex,
@@ -294,6 +295,7 @@ const struct ptp_clock_info dwmac1000_pt .n_per_out = 0, .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, .gettimex64 = stmmac_get_timex,
Greg Kroah-Hartman
maintainerPATCH 632/1005 net: usb: lan78xx: let unregister_netdev() stop phylink
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: YuanZhe Liu <[email protected]>
commit 9280128245612b30ca4a238daa6a777b0f4e583e upstream.
lan78xx_disconnect() stops phylink before unregistering the net device. phylink_start() is only called from lan78xx_open(), so when the device is unplugged before the interface has been brought up, the attached PHY is still in PHY_READY and phy_stop() reports:
called from state READY
WARNING: drivers/net/phy/phy.c:1670 at phy_stop+0xad/0x380
The same warning is emitted after an ifup/ifdown cycle, where the PHY is already in PHY_HALTED.
unregister_netdev() already closes a running device, which calls lan78xx_stop() and phylink_stop() with dev->dev_mutex held and after the URBs have been terminated. Unregister first and disconnect the PHY afterwards, so the interface is stopped exactly once and only while it is running, and the net device can no longer be opened while its phylink instance has no PHY attached.
--- drivers/net/usb/lan78xx.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/usb/lan78xx.c +2 -3
@@ -4592,13 +4592,12 @@ static void lan78xx_disconnect(struct us net = dev->net; +unregister_netdev (net); +rtnl_lock (); -phylink_stop (dev->phylink);phylink_disconnect_phy (dev->phylink);rtnl_unlock (); -unregister_netdev (net); -timer_shutdown_sync (&dev->stat_monitor);set_bit (EVENT_DEV_DISCONNECT , &dev->flags);cancel_delayed_work_sync (&dev->wq);
Greg Kroah-Hartman
maintainerPATCH 633/1005 xprtrdma: serialize unmap_sync with xprt_disconnect
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Menninger <[email protected]>
commit 1fa415883c37b02ff17acdd7977ed591d3d389ee upstream.
frwr_unmap_sync() posts LOCAL_INV Work Requests to the QP and waits for the matching CQE. This can race with rpcrdma_xprt_disconnect():
1. frwr_unmap_sync() samples r_xprt->rx_ep
2. rpcrdma_xprt_disconnect() drains the QP
3. frwr_unmap_sync() posts LOCAL_INV WRs after the drain
4. No CQE arrives, so wait_for_completion() blocks indefinitely
The hung task appears in the rpciod workqueue:
Workqueue: rpciod rpc_async_schedule [sunrpc]
wait_for_completion()
frwr_unmap_sync()
xprt_rdma_free()
xprt_release()Serialize synchronous MR invalidation against QP teardown with rx_unmap_rwsem. frwr_unmap_sync() holds the read side while it builds and submits the LOCAL_INV chain. Disconnect holds the write side across QP drain and resource teardown. Drop the read side before waiting so disconnect can drain the submitted Work Requests and deliver their CQEs.
Disconnect can reset a request while frwr_unmap_sync() waits for the read side. Recheck rl_registered after acquiring the rwsem and return without posting if the request has already been reset.
Move the synchronous invalidation completion from the final MR to the request, whose lifetime covers xprt_rdma_free(). This allows disconnect to destroy MRs after draining the QP while frwr_unmap_sync() is still waiting. On a post failure, call rpcrdma_force_disconnect() before dropping the read side so the endpoint is not dereferenced after disconnect can run.
frwr_unmap_async() runs inline from Receive completion processing. rpcrdma_xprt_drain() drains the Receive Queue before the Send Queue, so asynchronous LOCAL_INV Work Requests are submitted before Send Queue drain. frwr_unmap_sync(), however, runs from xprt_rdma_free() after the transport send lock has been released, so it is not ordered against disconnect.
Tested on v7.4-rc1 under pNFS load with repeated data server restarts to provoke rapid QP disconnect/reconnect cycling. Without the fix, a hung task in frwr_unmap_sync() reproduced twice in six attempts. With the fix, no hang occurred across 200 cycles.
Also observed on v6.8 and v6.18.34.
--- net/sunrpc/xprtrdma/frwr_ops.c | 89 ++++++++++++++++++++++++---------------- net/sunrpc/xprtrdma/transport.c | 2 net/sunrpc/xprtrdma/verbs.c | 16 +++++-- net/sunrpc/xprtrdma/xprt_rdma.h | 10 ++++ 4 files changed, 78 insertions(+), 39 deletions(-)
net/sunrpc/xprtrdma/frwr_ops.c +55 -34
@@ -27,13 +27,17 @@/* Transport recovery * -* frwr_map and frwr_unmap_* cannot run at the same time the transport -* connect worker is running. The connect worker holds the transport -* send lock, just as ->send_request does. This prevents frwr_map and -* the connect worker from running concurrently. When a connection is -* closed, the Receive completion queue is drained before the allowing -* the connect worker to get control. This prevents frwr_unmap and the -* connect worker from running concurrently. +* frwr_map() is serialized with the connect worker by the transport +* send lock. +* +* frwr_unmap_async() runs from Receive completion processing. +* rpcrdma_xprt_drain() drains the Receive Queue before the Send Queue, +* so asynchronous LOCAL_INV Work Requests are submitted before Send +* Queue drain. +* +* frwr_unmap_sync() runs after the transport send lock is released. +* rx_unmap_rwsem orders its LOCAL_INV submission before disconnect +* drains the QP. * * When the underlying transport disconnects, MRs that are in flight * are flushed and are likely unusable. Thus all MRs are destroyed.
@@ -139,7 +143,6 @@ int frwr_mr_init(struct rpcrdma_xprt *r_ mr->mr_ibmr = frmr; mr->mr_device =NULL ;INIT_LIST_HEAD (&mr->mr_list); -init_completion (&mr->mr_linv_done);frwr_cid_init (ep, mr);sg_init_table (sg, depth);
@@ -539,40 +542,60 @@ static void frwr_wc_localinv(struct ib_c* @cq: completion queue * @wc: WCE for a completed LocalInv WR * -* Awaken anyone waiting for an MR to finish being fenced. +* Wake frwr_unmap_sync() after the final LOCAL_INV completion. */ static void frwr_wc_localinv_wake (struct ib_cq *cq,struct ib_wc *wc) {struct ib_cqe *cqe = wc->wr_cqe; struct rpcrdma_mr *mr = container_of(cqe, struct rpcrdma_mr, mr_cqe); +struct rpcrdma_req *req = mr->mr_req;/* WARNING: Only wr_cqe and status are reliable at this point */ trace_xprtrdma_wc_li_wake (wc, &mr->mr_cid);frwr_mr_done (wc, mr); -complete (&mr->mr_linv_done); +complete (&req->rl_linv_done);rpcrdma_flush_disconnect (cq->cq_context, wc); }/** -* frwr_unmap_sync - invalidate memory regions that were registered for @req +* frwr_unmap_sync - synchronously invalidate MRs registered for @req * @r_xprt: controlling transport instance -* @req: rpcrdma_req with a non-empty list of MRs to process +* @req: request whose registered MRs are to be invalidated +* +* If @req still owns registered MRs after synchronizing with transport +* disconnect, post a chain of LOCAL_INV Work Requests and wait for the +* final completion. On successful completion, this fences the mapped +* regions from remote access and preserves Send Queue flow control. +* +* A concurrent disconnect can reset @req while this function waits for +* the read side. In that case the MRs have already been released and no +* LOCAL_INV Work Requests are posted. * -* Sleeps until it is safe for the host CPU to access the previously mapped -* memory regions. This guarantees that registered MRs are properly fenced -* from the server before the RPC consumer accesses the data in them. It -* also ensures proper Send flow control: waking the next RPC waits until -* this RPC has relinquished all its Send Queue entries. +* Context: Process context. Takes and releases +* @r_xprt->rx_unmap_rwsem for read. May sleep. */ void frwr_unmap_sync (struct rpcrdma_xprt *r_xprt,struct rpcrdma_req *req) {struct ib_send_wr *first, **prev, *last; -struct rpcrdma_ep *ep = r_xprt->rx_ep;const struct ib_send_wr *bad_wr; +struct rpcrdma_ep *ep;struct rpcrdma_mr *mr;int rc; +/* serialize against rpcrdma_xprt_disconnect() */ +down_read (&r_xprt->rx_unmap_rwsem); + +/* +* Disconnect can reset this request while we wait for the read side. +* Recheck rl_registered in case rx_ep now refers to a new connection. +*/ + ep = r_xprt->rx_ep; +if (!ep ||list_empty (&req->rl_registered)) { +up_read (&r_xprt->rx_unmap_rwsem); +return ; + } +/* ORDER: Invalidate all of the MRs first * * Chain the LOCAL_INV Work Requests and post them with
@@ -599,37 +622,35 @@ void frwr_unmap_sync(struct rpcrdma_xprt prev = &last->next; }while ((mr =rpcrdma_mr_pop (&req->rl_registered))); - mr = container_of(last, struct rpcrdma_mr, mr_invwr); -/* Strong send queue ordering guarantees that when the * last WR in the chain completes, all WRs in the chain * are complete. */ last->wr_cqe->done = frwr_wc_localinv_wake; -reinit_completion (&mr->mr_linv_done); +reinit_completion (&req->rl_linv_done); -/* Transport disconnect drains the receive CQ before it -* replaces the QP. The RPC reply handler won't call us -* unless re_id->qp is a valid pointer. +/* +* The read side prevents disconnect from draining this QP until the +* LOCAL_INV chain has been submitted. */ bad_wr =NULL ; rc =ib_post_send (ep->re_id->qp, first, &bad_wr); +if (rc) { +/* On error, the MRs get destroyed once the QP has drained. */ +trace_xprtrdma_post_linv_err (req, rc); + +/* Force a connection loss to ensure complete recovery. +*/ +rpcrdma_force_disconnect (ep); + } +up_read (&r_xprt->rx_unmap_rwsem);/* The final LOCAL_INV WR in the chain is supposed to * do the wake. If it was never posted, the wake will * not happen, so don't wait in that case. */ if (bad_wr != first) -wait_for_completion (&mr->mr_linv_done); -if (!rc) -return ; - -/* On error, the MRs get destroyed once the QP has drained. */ -trace_xprtrdma_post_linv_err (req, rc); - -/* Force a connection loss to ensure complete recovery. -*/ -rpcrdma_force_disconnect (ep); +wait_for_completion (&req->rl_linv_done); }/**
net/sunrpc/xprtrdma/transport.c +2 -0
@@ -364,6 +364,8 @@ xprt_setup_rdma(struct xprt_create *argsINIT_DELAYED_WORK (&new_xprt->rx_connect_worker, xprt_rdma_connect_worker); +init_rwsem (&new_xprt->rx_unmap_rwsem); + xprt->max_payload =RPCRDMA_MAX_DATA_SEGS <<PAGE_SHIFT ;return xprt;
net/sunrpc/xprtrdma/verbs.c +12 -4
@@ -572,20 +572,24 @@ out:* rpcrdma_xprt_disconnect - Disconnect underlying transport * @r_xprt: controlling transport instance * -* Caller serializes. Either the transport send lock is held, -* or we're being called to destroy the transport. +* Context: Caller serializes. Either the transport send lock is held, +* or the transport is being destroyed. Takes and releases +* @r_xprt->rx_unmap_rwsem for write. May sleep. * * On return, @r_xprt is completely divested of all hardware * resources and prepared for the next ->connect operation. */ void rpcrdma_xprt_disconnect (struct rpcrdma_xprt *r_xprt) { -struct rpcrdma_ep *ep = r_xprt->rx_ep; +struct rpcrdma_ep *ep;struct rdma_cm_id *id;int rc; +down_write (&r_xprt->rx_unmap_rwsem); + + ep = r_xprt->rx_ep;if (!ep) -return ; + goto out_unlock;/* Prevent teardown-generated events from requesting another close. */ atomic_xchg (&ep->re_force_disconnect,1 );
@@ -604,6 +608,9 @@ void rpcrdma_xprt_disconnect(struct rpcrrdma_destroy_id (id); r_xprt->rx_ep =NULL ; + +out_unlock: +up_write (&r_xprt->rx_unmap_rwsem); }/* Fixed-size circular FIFO queue. This implementation is wait-free and
@@ -927,6 +934,7 @@ struct rpcrdma_req *rpcrdma_req_create(sINIT_LIST_HEAD (&req->rl_free_mrs);INIT_LIST_HEAD (&req->rl_registered); +init_completion (&req->rl_linv_done);spin_lock (&buffer->rb_lock);list_add (&req->rl_all, &buffer->rb_allreqs);spin_unlock (&buffer->rb_lock);
net/sunrpc/xprtrdma/xprt_rdma.h +9 -1
@@ -46,6 +46,7 @@#include <linux/spinlock.h> /* spinlock_t, etc */ #include <linux/atomic.h> /* atomic_t, etc */ #include <linux/kref.h> /* struct kref */ +#include <linux/rwsem.h> /* struct rw_semaphore */ #include <linux/workqueue.h> /* struct work_struct */ #include <linux/llist.h>
@@ -249,7 +250,6 @@ struct rpcrdma_mr {int mr_nents;enum dma_data_direction mr_dir;struct ib_cqe mr_cqe; -struct completion mr_linv_done;union {struct ib_reg_wr mr_regwr;struct ib_send_wr mr_invwr;
@@ -348,6 +348,7 @@ struct rpcrdma_req {struct list_head rl_free_mrs;struct list_head rl_registered; +struct completion rl_linv_done; }; static inline struct rpcrdma_req *
@@ -449,6 +450,13 @@ struct rpcrdma_xprt {struct delayed_work rx_connect_worker;struct rpc_timeout rx_timeout;struct rpcrdma_stats rx_stats; + +/* +* Orders frwr_unmap_sync()'s LOCAL_INV submission ahead of the +* QP drain. Disconnect holds the write side across the drain +* and resource teardown. +*/ +struct rw_semaphore rx_unmap_rwsem; };#define rpcx_to_rdmax (x) container_of(x, struct rpcrdma_xprt, rx_xprt)
Greg Kroah-Hartman
maintainerPATCH 634/1005 xsk: defer software checksum until the skb is complete
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rongzheng Wang <[email protected]>
commit f2eddafbfcc004098425fee7c5664adbe29152d7 upstream.
When XDP_UMEM_TX_SW_CSUM is used with multi-buffer TX, xsk_skb_metadata() calls skb_checksum_help() while only the first descriptor has been added to the skb. The checksum therefore covers just the first fragment, and skb_checksum_help() sets ip_summed to CHECKSUM_NONE, so the remaining fragments are never included in the checksum.
Move the software checksum calculation to the point where the last descriptor has been added to the skb.
On a checksum failure the packet is now dropped instead of being returned to the application for a retry. This path is not reachable with the existing metadata validation, but the behavior change is intentional.
--- net/xdp/xsk.c | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-)
net/xdp/xsk.c +15 -8
@@ -1011,14 +1011,6 @@ static int xsk_skb_metadata(struct sk_bu skb->csum_start = hr + csum_start; skb->csum_offset = csum_offset; skb->ip_summed =CHECKSUM_PARTIAL ; - -if (unlikely (pool->tx_sw_csum)) { -int err; - - err =skb_checksum_help (skb); -if (err) -return err; - } }if (flags &XDP_TXMD_FLAGS_LAUNCH_TIME )
@@ -1030,6 +1022,15 @@ static int xsk_skb_metadata(struct sk_bureturn 0 ; } +static int xsk_skb_sw_csum (struct sk_buff *skb,struct xsk_buff_pool *pool) +{ +if (unlikely (pool->tx_sw_csum && + skb->ip_summed ==CHECKSUM_PARTIAL )) +return skb_checksum_help (skb); + +return 0 ; +} +static struct sk_buff *xsk_build_skb_zerocopy (struct xdp_sock *xs,struct xdp_desc *desc) {
@@ -1277,6 +1278,12 @@ static int __xsk_generic_xmit(struct soccontinue ; } + err =xsk_skb_sw_csum (skb, xs->pool); +if (unlikely (err)) { +xsk_drop_skb (skb); + goto out; + } + err =__dev_direct_xmit (skb, xs->queue_id);if (err ==NETDEV_TX_BUSY ) {/* Tell user-space to retry the send */
Greg Kroah-Hartman
maintainerPATCH 635/1005 udf: dont allocate the inode block in udf_sync_inode_metadata()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 05ad4c91fe2852a19d04311883420ffefb02300d upstream.
udf_sync_inode_metadata() looks the block that holds the inode up with sb_getblk() which allocates a buffer for it if it isn't cached. But a block that isn't cached is neither dirty nor under writeback, so there's nothing to write or to wait for and the buffer just gets thrown away again.
That allocation is also something we can't afford once inode eviction calls ->sync_inode_metadata() from reclaim. So look the block up with sb_find_get_block_nonatomic() instead.
--- fs/udf/inode.c | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-)
fs/udf/inode.c +15 -16
@@ -1735,25 +1735,24 @@ void udf_update_extra_perms(struct inodeint udf_sync_inode_metadata (struct inode *inode,struct writeback_control *wbc) {struct buffer_head *bh; +unsigned long block;int err =0 ; - bh =sb_getblk (inode->i_sb, -udf_get_lb_pblock (inode->i_sb, - &UDF_I (inode)->i_location,0 )); -if (!bh) -return -EIO ; - -sync_dirty_buffer (bh); -if (buffer_write_io_error (bh)) { -udf_warn (inode->i_sb,"IO error syncing udf inode [%08llx]\n" , - inode->i_ino); - err = -EIO ; - goto out; + block =udf_get_lb_pblock (inode->i_sb, &UDF_I (inode)->i_location,0 ); +/* A block that isn't cached is neither dirty nor under writeback. */ + bh =sb_find_get_block_nonatomic (inode->i_sb, block); +if (bh) { +sync_dirty_buffer (bh); +if (buffer_write_io_error (bh)) { +udf_warn (inode->i_sb,"IO error syncing udf inode [%08llx]\n" , + inode->i_ino); + err = -EIO ; + } +brelse (bh); +if (err) +return err; } - err =mmb_sync (&UDF_I (inode)->i_metadata_bhs); -out: -brelse (bh); -return err; +return mmb_sync (&UDF_I (inode)->i_metadata_bhs); }static void udf_adjust_time (struct udf_inode_info *iinfo,struct timespec64 time)
Greg Kroah-Hartman
maintainerPATCH 636/1005 vdso: Add VDSO_UNALIGNED_PACKED config option
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Rogers <[email protected]>
commit 2727aca4439ee4b9085141a3babadc8de580397f upstream.
Commit a339671db64b ("vdso: Switch get/put_unaligned() from packed struct to memcpy()") switched __get_unaligned_t() and __put_unaligned_t() from using a __packed struct to __builtin_memcpy() to avoid strict aliasing undefined behavior.
On targets without efficient unaligned memory accesses (such as ARMv5), GCC may not inline __builtin_memcpy() into byte shifts and instead emit stack spills or much slower out-of-line memcpy() calls. Add CONFIG_VDSO_UNALIGNED_PACKED, defaulting to !HAVE_EFFICIENT_UNALIGNED_ACCESS, to use the __packed struct implementation on strict-alignment targets while keeping __builtin_memcpy() elsewhere and in tools/.
--- include/vdso/unaligned.h | 16 ++++++++++++++++ lib/vdso/Kconfig | 10 ++++++++++ 2 files changed, 26 insertions(+)
include/vdso/unaligned.h +16 -0
@@ -4,6 +4,20 @@#include <linux/compiler_types.h> +#ifdef CONFIG_VDSO_UNALIGNED_PACKED + +#define __get_unaligned_t (type, ptr) ({ \ + const struct { type x; } __packed * __get_pptr = (typeof(__get_pptr))(ptr); \ + __get_pptr->x; \ +}) + +#define __put_unaligned_t (type, val, ptr) do { \ + struct { type x; } __packed * __put_pptr = (typeof(__put_pptr))(ptr); \ + __put_pptr->x = (val); \ +} while (0) + +#else /* !CONFIG_VDSO_UNALIGNED_PACKED */ +/** * __get_unaligned_t - read an unaligned value from memory. * @type: the type to load from the pointer.
@@ -41,4 +55,6 @@ sizeof(__put_unaligned_val)); \ } while (0) +#endif /* CONFIG_VDSO_UNALIGNED_PACKED */ +#endif /* __VDSO_UNALIGNED_H */
lib/vdso/Kconfig +10 -0
@@ -23,3 +23,13 @@ config VDSO_GETRANDOM select VDSO_DATASTORE help Selected by architectures that support vDSO getrandom(). + +config VDSO_UNALIGNED_PACKED + bool + default !HAVE_EFFICIENT_UNALIGNED_ACCESS + help + Use packed structs rather than memcpy() in include/vdso/unaligned.h + for unaligned memory accesses. Enabled by default when the + architecture does not have efficient unaligned accesses, as GCC may + emit stack spills or out-of-line memcpy() calls instead of inlining + byte shifts.
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 637/1005 vsock/virtio: clear vqs[] to avoid a UAF on a failed PM restore
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jerome Mohm <[email protected]>
commit 2a24ba1694f14299fbde3fa107e5d56629f2f8b6 upstream.
virtio_vsock_vqs_del() frees the virtqueues but leaves vsock->vqs[] pointing at them. If virtio_vsock_restore() then fails, the driver stays bound with a dangling vqs[], and the next freeze or unbind passes a freed virtqueue to virtqueue_detach_unused_buf():
BUG: KASAN: slab-use-after-free in virtqueue_detach_unused_buf virtio_vsock_vqs_del (net/vmw_vsock/virtio_transport.c:785) virtio_vsock_remove Freed by task ...: vp_del_vqs virtio_vsock_freeze
Clear vqs[] after del_vqs() and when virtio_find_vqs() fails. Return early from virtio_vsock_vqs_del() when vqs[] is empty: the detach loops would pass NULL to virtqueue_detach_unused_buf(), and a second del_vqs() would free virtio-mmio's IRQ again, which only WARNs in free_irq() ("Trying to free already-free IRQ").
Found with the help of Anthropic's Claude and reproduced on virtio-pci and virtio-mmio by failing the restore with failslab, without other kernel changes; the virtio-mmio WARN was found by the netdev Sashiko review and reproduced with v1 of this patch. With this patch neither report appears on virtio-pci or virtio-mmio guests, and the vsock vmtest.sh single-VM tests pass. A find_vqs() failure after some virtqueues were set up was not exercised.
--- net/vmw_vsock/virtio_transport.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-)
net/vmw_vsock/virtio_transport.c +13 -3
@@ -714,8 +714,10 @@ static int virtio_vsock_vqs_init(structatomic_set (&vsock->queued_replies,0 ); ret =virtio_find_vqs (vdev,VSOCK_VQ_MAX , vsock->vqs, vqs_info,NULL ); -if (ret <0 ) +if (ret <0 ) { +memset (vsock->vqs,0 ,sizeof (vsock->vqs));return ret; + }virtio_vsock_update_guest_cid (vsock);
@@ -776,11 +778,19 @@ static void virtio_vsock_vqs_del(struct vsock->event_run = false;mutex_unlock (&vsock->event_lock); +virtio_vsock_skb_queue_purge (&vsock->send_pkt_queue); +/* Flush all device writes and interrupts, device will not use any * more buffers. */ virtio_reset_device (vdev); +/* After a failed restore no virtqueues are live, and a second +* del_vqs() would free virtio-mmio's IRQ again (a WARN in free_irq()). +*/ +if (!vsock->vqs[VSOCK_VQ_RX ]) +return ; +mutex_lock (&vsock->rx_lock);while ((skb =virtqueue_detach_unused_buf (vsock->vqs[VSOCK_VQ_RX ])))kfree_skb (skb);
@@ -791,10 +801,10 @@ static void virtio_vsock_vqs_del(structkfree_skb (skb);mutex_unlock (&vsock->tx_lock); -virtio_vsock_skb_queue_purge (&vsock->send_pkt_queue); -/* Delete virtqueues and flush outstanding callbacks if any */ vdev->config->del_vqs (vdev); + +memset (vsock->vqs,0 ,sizeof (vsock->vqs)); }static int virtio_vsock_probe (struct virtio_device *vdev)
Greg Kroah-Hartman
maintainerPATCH 638/1005 tsacct: Keep task begin times stable across suspend
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit c49b3c20a2d0b22700e2100a527e68e829ece7f0 upstream.
bacct_add_tsk() derives ac_btime and ac_btime64 by subtracting a CLOCK_MONOTONIC elapsed duration from CLOCK_REALTIME. MONOTONIC stops during suspend while REALTIME continues, so querying an existing task after resume moves its reported begin time forward by the time spent suspended.
Calculate the begin time from the wall-clock boot timestamp and the task's CLOCK_BOOTTIME start timestamp instead. This accounts for suspend and adds the nanoseconds before truncating to seconds. Keep ac_etime and ac_tgetime on CLOCK_MONOTONIC and retain the existing rebasing when the wall clock is adjusted.
The new begin time can be negative: setting CLOCK_REALTIME is bounded by CLOCK_MONOTONIC, which excludes suspend, rather than CLOCK_BOOTTIME. A permitted backward clock adjustment after suspend can therefore put the task's begin time before the epoch. Clamp ac_btime64 at zero too, instead of wrapping in the unsigned field, and retain its positive range.
--- kernel/tsacct.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
kernel/tsacct.c +6 -4
@@ -24,7 +24,7 @@ void bacct_add_tsk(struct user_namespaceconst struct cred *tcred;u64 utime, stime, utimescaled, stimescaled;u64 now_ns, delta; -time64_t btime; +struct timespec64 btime;BUILD_BUG_ON (TS_COMM_LEN <TASK_COMM_LEN );
@@ -39,9 +39,11 @@ void bacct_add_tsk(struct user_namespacedo_div (delta,NSEC_PER_USEC ); stats->ac_etime = delta;/* Convert to seconds for btime (note y2106 limit) */ - btime =ktime_get_real_seconds () -div_u64 (delta,USEC_PER_SEC ); - stats->ac_btime =clamp_t (time64_t, btime,0 ,U32_MAX ); - stats->ac_btime64 = btime; +getboottime64 (&btime); + btime =timespec64_add (btime,ns_to_timespec64 (tsk->start_boottime)); + stats->ac_btime =clamp_t (time64_t, btime.tv_sec,0 ,U32_MAX ); +/* Setting the clock back after suspend can make btime negative. */ + stats->ac_btime64 =max_t (time64_t, btime.tv_sec,0 );if (tsk->flags &PF_EXITING ) stats->ac_exitcode = tsk->exit_code;
Greg Kroah-Hartman
maintainerPATCH 639/1005 tls: only install push_pending_record for a TX context
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rishikesh Jethwani <[email protected]>
commit c47e766c5307c06a78304582b2b5b5ab01ee1358 upstream.
tls_set_sw_offload() assigns ctx->push_pending_record for both directions, but the hook is a TX-side dispatcher. On a socket whose TX side is HW offloaded, tls_set_device_offload() installs tls_device_push_pending_record(); any later TLS_RX setsockopt overwrites it with tls_sw_push_pending_record(), because tls_set_device_offload_rx() itself calls tls_set_sw_offload(sk, 0, NULL) for the software half of a successful HW RX offload, and so does the fallback when the RX offload is declined (NIC with TX-only offload, tls_dev_add() failure).
Quoted 1 line
From then on
tls_handle_open_record()(aTLS_SET_RECORD_TYPEcmsg after
a MSG_MORE send, or the close path with a pending writer) runs tls_sw_push_pending_record() against priv_ctx_tx, which is a struct tls_offload_context_tx, not a struct tls_sw_context_tx, and reads open_rec from inside the offload context. On x86_64 without lock debugging that field overlays sg_tx_data[2].dma_address, which is never set, so the push is silently skipped and the data buffered by the MSG_MORE send is later sent under the cmsg's record type, e.g. application data in a handshake or alert record. Enabling CONFIG_DEBUG_SPINLOCK, CONFIG_DEBUG_LOCK_ALLOC and CONFIG_LOCKDEP, but not CONFIG_LOCK_STAT, in the tested x86_64 configuration moves open_rec over sg_tx_data[5].page_link. Once populated, its page pointer and scatterlist flags are interpreted as a tls_rec pointer and dereferenced while reading msg_plaintext.sg.size.
Only set the hook when initialising the TX side.
Found by code review while developing TLS 1.3 HW offload rekey support.
Tested with HW TLS TX and RX offload on Mellanox ConnectX-6 Dx (Crypto Enabled): after setting TLS_RX, send() "AAAA" with MSG_MORE, then sendmsg() "BBBB" with a TLS_SET_RECORD_TYPE cmsg for a handshake record. Without this patch the peer receives a single handshake record "AAAABBBB"; with it, an application data record "AAAA" followed by a handshake record "BBBB".
--- net/tls/tls_sw.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/tls/tls_sw.c +2 -1
@@ -2630,7 +2630,8 @@ int tls_set_sw_offload(struct sock *sk, } } - ctx->push_pending_record = tls_sw_push_pending_record; +if (tx) + ctx->push_pending_record = tls_sw_push_pending_record;/* setkey is the last operation that could fail during a * rekey. if it succeeds, we can start modifying the
Greg Kroah-Hartman
maintainerPATCH 640/1005 tools/bootconfig: Close only opened braces in compact output
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eduardo Mucelli Rezende Oliveira <[email protected]>
commit 26fa92f351d4993428268afebf6c60c987477af5 upstream.
A key may have both a value and subkeys. When it has only one subkey, xbc_show_compact_tree() can print that subkey using dotted notation without opening a brace. During backtracking, however, it treats the value node followed by a subkey as evidence that a brace was opened.
For example, a.b=v, a.b.c=w and a.z=q are printed with the brace for a closed before z. Reading that output back changes a.z into the root key z, silently changing the configuration.
Check the key children when deciding whether to close a brace. Skip the value child, and account for a sole subkey that itself has both a value and subkeys, since that combination is not compacted. This follows the conditions used to open braces without keeping a depth-indexed array. Extend the mixed-value/subkey sample to cover the lost sibling.
--- tools/bootconfig/main.c | 29 ++++++++++++++++------ tools/bootconfig/samples/exp-good-mixed-kv1.bconf | 5 +++ tools/bootconfig/samples/good-mixed-kv1.bconf | 5 +++ 3 files changed, 32 insertions(+), 7 deletions(-)
tools/bootconfig/main.c +22 -7
@@ -39,6 +39,23 @@ static int xbc_show_value(struct xbc_nodreturn i; } +/* Match the conditions under which the compact formatter opens braces. */ +static bool xbc_node_needs_braces (struct xbc_node *node) +{ +struct xbc_node *child =xbc_node_get_child (node); + +if (child &&xbc_node_is_value (child)) + child =xbc_node_get_next (child); +if (!child) +return false; +if (child->next) +return true; + +/* A single subkey with both a value and subkeys is not compacted. */ + child =xbc_node_get_child (child); +return child &&xbc_node_is_value (child) && child->next; +} +static void xbc_show_compact_tree (void ) {struct xbc_node *node, *cnode =NULL , *vnode;
@@ -99,14 +116,12 @@ static void xbc_show_compact_tree(void) node =xbc_node_get_parent (node);if (!node)return ; -if (!xbc_node_get_child (node)->next) +if (!depth || !xbc_node_needs_braces (node))continue ; -if (depth) { - depth--; -for (i =0 ; i < depth; i++) -printf ("\t" ); -printf ("}\n" ); - } + depth--; +for (i =0 ; i < depth; i++) +printf ("\t" ); +printf ("}\n" ); } node =xbc_node_get_next (node); }
tools/bootconfig/samples/exp-good-mixed-kv1.bconf +5 -0
@@ -1,2 +1,7 @@ key = "value"; key.subkey = "another-value"; +a { + b = "v"; + b.c = "w"; + z = "q"; +}
tools/bootconfig/samples/good-mixed-kv1.bconf +5 -0
@@ -1,3 +1,8 @@ # value -> subkey pattern key = value key.subkey = another-value + +# A valued parent with one subkey must not close its enclosing brace. +a.b = v +a.b.c = w +a.z = q
Greg Kroah-Hartman
maintainerPATCH 641/1005 tcp: free saved_syn after an RCU grace period
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit 2b9fd1a0abf0c1c7200be7a33cfeeca1c68089b6 upstream.
tcp_reqsk_record_syn() allocates saved_syn separately from its request socket. bpf_sock_ops_get_syn() can load that pointer while processing a retransmitted SYN under RCU.
There are two ownership transfers which can let another CPU reclaim the allocation while such a reader is still using it.
First, tcp_move_syn() transfers req->saved_syn to a newly created child socket. The child can be closed and tcp_saved_syn_free() can reclaim the allocation before a reader of the old request finishes.
Second, inet_reqsk_clone() shallow-copies request_sock during request migration. After reqsk_migrate_reset() clears the old request pointer, the migrated clone owns it. However, a reader which already loaded the pointer from the old request can still be using it when the clone is released.
I found this through LLM-assisted concurrency fuzzing.
Mark the request-socket saved_syn pointer as RCU protected and use RCU accessors for its reads and updates. Keep the full-socket pointer plain because all of its accesses hold the socket lock. Embed an rcu_head in struct saved_syn and use kfree_rcu() in both teardown paths. This lets a request-side reader which loaded the object before an ownership transfer finish.
This follows commit e3f33b0a1d89 ("ipv4: free inet_opt and ireq_opt after an RCU grace period"), which fixed the same ownership-transfer pattern for IPv4 options.
The issue was confirmed with KASAN on v7.3-16007-g36aad21d50d1 using temporary kernel instrumentation to widen the reader and request-migration window. KASAN reported a slab-use-after-free read in bpf_sock_ops_get_syn(), with the allocation freed by __reqsk_free() from reqsk_timer_handler(). The same explicit migration test completed without a report with deferred reclamation. A patched kernel without the delay instrumentation also completed a successful migration and seven saved-SYN reads without a KASAN report.
--- include/linux/tcp.h | 6 +++--- include/net/request_sock.h | 3 ++- net/core/filter.c | 2 +- net/ipv4/inet_connection_sock.c | 6 +++--- net/ipv4/tcp_input.c | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-)
include/linux/tcp.h +3 -3
@@ -612,13 +612,13 @@ static inline void fastopen_queue_tune(sstatic inline void tcp_move_syn (struct tcp_sock *tp,struct request_sock *req) { - tp->saved_syn = req->saved_syn; - req->saved_syn =NULL ; + tp->saved_syn =unrcu_pointer (req->saved_syn); +RCU_INIT_POINTER (req->saved_syn,NULL ); }static inline void tcp_saved_syn_free (struct tcp_sock *tp) { -kfree (tp->saved_syn); +kfree_rcu (tp->saved_syn, rcu); tp->saved_syn =NULL ; }
include/net/request_sock.h +2 -1
@@ -39,6 +39,7 @@ struct request_sock_ops { };struct saved_syn { +struct rcu_head rcu;u32 mac_hdrlen;u32 network_hdrlen;u32 tcp_hdrlen;
@@ -68,7 +69,7 @@ struct request_sock {struct timer_list rsk_timer;const struct request_sock_ops *rsk_ops;struct sock *sk; -struct saved_syn *saved_syn; +struct saved_syn __rcu *saved_syn;u32 secid;u32 peer_secid;u32 timeout;
net/core/filter.c +1 -1
@@ -6188,7 +6188,7 @@ static int bpf_sock_ops_get_syn(struct b* not be available. It has to resort to * saved_syn (if it is saved). */ - saved_syn =inet_reqsk (sk)->saved_syn; + saved_syn =rcu_dereference (inet_reqsk (sk)->saved_syn); else saved_syn =tcp_sk (sk)->saved_syn;
net/ipv4/inet_connection_sock.c +3 -3
@@ -869,7 +869,7 @@ reqsk_alloc_noprof(const struct request_req_to_sk (req)->sk_prot = sk_listener->sk_prot;sk_node_init (&req_to_sk (req)->sk_node);sk_tx_queue_clear (req_to_sk (req)); - req->saved_syn =NULL ; +RCU_INIT_POINTER (req->saved_syn,NULL ); req->syncookie =0 ; req->num_timeout =0 ; req->num_retrans =0 ;
@@ -908,7 +908,7 @@ void __reqsk_free(struct request_sock *r req->rsk_ops->destructor (req);if (req->rsk_listener)sock_put (req->rsk_listener); -kfree (req->saved_syn); +kfree_rcu (unrcu_pointer (req->saved_syn), rcu);kmem_cache_free (req->rsk_ops->slab, req); }
@@ -979,7 +979,7 @@ static void reqsk_queue_migrated(structstatic void reqsk_migrate_reset (struct request_sock *req) { - req->saved_syn =NULL ; +RCU_INIT_POINTER (req->saved_syn,NULL );#if IS_ENABLED (CONFIG_IPV6 )inet_rsk (req)->ipv6_opt =NULL ;inet_rsk (req)->pktopts =NULL ;
net/ipv4/tcp_input.c +1 -1
@@ -7636,7 +7636,7 @@ static void tcp_reqsk_record_syn(const s saved_syn->network_hdrlen =skb_network_header_len (skb); saved_syn->tcp_hdrlen =tcp_hdrlen (skb);memcpy (saved_syn->data, base, len); - req->saved_syn = saved_syn; +RCU_INIT_POINTER (req->saved_syn, saved_syn); } } }
Greg Kroah-Hartman
maintainerPATCH 642/1005 tcp: do not coalesce segments after FIN
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyunwoo Kim <[email protected]>
commit 1c46780dec48893b8c25fd5e33a3127e8dc39dd4 upstream.
A FIN consumes a sequence number. If another FIN segment is coalesced into an skb that already carries FIN, end_seq advances to account for the additional FIN, but tcp_flags still contains only one FIN bit.
When the preceding gap is filled and tcp_ofo_queue() processes the coalesced skb, rcv_nxt advances to the skb's end_seq. When the receive path consumes all data in the skb, copied_seq advances by the data length and one sequence number for FIN. If three or more FIN segments have been coalesced into one skb, tcp_inq() can still return a positive value after the receive queue becomes empty and the SOCK_DONE adjustment is applied.
TCP_ZEROCOPY_RECEIVE is another consumer affected by this state. tcp_zerocopy_receive() takes its length from tcp_inq() and follows skb->next without checking for the end of the receive queue.
Software kTLS receive is one consumer affected by this state. When strp->copy_mode is false, tls_strp_msg_consume() calls the TCP helper tcp_read_done() to consume the current TLS record. In the reproducer, tcp_read_done() consumed the record data and one FIN before freeing the receive skb.
When kTLS looked for the next record, tcp_inq() reported at least TLS_HEADER_SIZE bytes even though the receive queue was empty. tcp_recv_skb() returned NULL, so tls_strp_load_anchor_with_queue() hit WARN_ON_ONCE() and returned without updating the anchor.
Since tcp_inq() had reported at least TLS_HEADER_SIZE, tls_strp_read_sock() proceeded to tls_strp_check_queue_ok(). skb_shinfo(strp->anchor)->frag_list still pointed to the freed receive skb. tls_strp_check_queue_ok() then read TCP_SKB_CB(first)->seq through the stale pointer, causing a use-after-free.
The reproducer followed this call path:
tls_rx_rec_done()
tls_strp_msg_consume()
tcp_read_done() // frees the receive skb
tls_strp_check_rcv()
tls_strp_read_sock()
tls_strp_load_anchor_with_queue() // returns after WARN_ON_ONCE()
tcp_recv_skb() == NULL
tls_strp_check_queue_ok()
TCP_SKB_CB(first)->seq // reads the freed receive skb
KASAN reported:
BUG: KASAN: slab-use-after-free in tls_strp_check_queue_ok.isra.0+0x5f/0x100 Read of size 4 at addr ffff888103169ca8 by task ktls-server/71 ... Call Trace: <TASK> ... tls_strp_check_queue_ok.isra.0+0x5f/0x100 tls_strp_check_rcv+0x2a9/0x400 ... tls_sw_recvmsg+0x3ce/0xa10 ... sock_recvmsg+0xea/0x100 __sys_recvfrom+0x142/0x1f0 ... __x64_sys_recvfrom+0x76/0x90 do_syscall_64+0xdd/0x4a0 entry_SYSCALL_64_after_hwframe+0x77/0x7f ... </TASK> ... Freed by task 71: ... napi_skb_cache_put+0x24/0xf0 skb_attempt_defer_free+0x183/0x3b0 tcp_read_done+0x2d4/0x340 tls_strp_msg_consume+0x45/0x80 tls_sw_recvmsg+0x3c4/0xa10 ...
In tcp_try_coalesce(), skip coalescing when the destination skb already carries FIN. tcp_add_backlog() calls skb_try_coalesce() directly instead of using this helper, so add the same check there. Since both paths check only the destination skb, a final segment carrying data and FIN can still be coalesced into an skb without FIN when the other coalescing checks pass.
--- net/ipv4/tcp_input.c | 4 ++++ net/ipv4/tcp_ipv4.c | 2 ++ 2 files changed, 6 insertions(+)
net/ipv4/tcp_input.c +4 -0
@@ -5263,6 +5263,10 @@ static bool tcp_try_coalesce(struct sockif (!tcp_skb_can_collapse_rx (to, from))return false; +/* Nothing follows a FIN. */ +if (unlikely (TCP_SKB_CB (to)->tcp_flags &TCPHDR_FIN )) +return false; +if (!skb_try_coalesce (to, from, fragstolen, &delta))return false;
net/ipv4/tcp_ipv4.c +2 -0
@@ -1957,6 +1957,8 @@ enum skb_drop_reason tcp_add_backlog(str ((TCP_SKB_CB (tail)->tcp_flags ^TCP_SKB_CB (skb)->tcp_flags) & (TCPHDR_ECE |TCPHDR_CWR |TCPHDR_AE )) || +/* Nothing follows a FIN, see tcp_try_coalesce() */ + (TCP_SKB_CB (tail)->tcp_flags &TCPHDR_FIN ) || !tcp_skb_can_collapse_rx (tail, skb) || thtail->doff != th->doff || memcmp(thtail + 1, th + 1, hdrlen - sizeof(*th)) ||
Greg Kroah-Hartman
maintainerPATCH 643/1005 tcp: fix authentication bypass via unsupported TCP auth options
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 7cc235fb1251fec1183e3158c60d2e504c2a8e8b upstream.
tcp_inbound_hash() parses both TCP-MD5 and TCP-AO options when at least one of the two features is enabled. With TCP_MD5SIG=y and TCP_AO=n, a packet carrying an AO option reaches the disabled tcp_inbound_ao_hash() stub. That stub returns success, so sockets configured to require MD5 authentication end up accepting unauthenticated data. A forged AO option skips the unsigned fast path, which is the only place where tcp_inbound_hash() can return SKB_DROP_REASON_TCP_MD5NOTFOUND.
The inverse configuration with TCP_MD5SIG=n and TCP_AO=y has the same problem for an MD5 option on AO sockets.
Note that TCP-AO depends on 64BIT: therefore, every 32-bit kernel with TCP_MD5SIG=y is in the vulnerable configuration.
Make the disabled stubs reject options for the unsupported authentication scheme. This matches the real helpers' behavior for sockets without keys. It also means that kernels with TCP_MD5SIG=n and TCP_AO=y now drop segments carrying an MD5 option on unkeyed sockets, as kernels configured with TCP_MD5SIG=y already do.
--- include/net/tcp_ao.h | 3 ++- net/ipv4/tcp.c | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-)
include/net/tcp_ao.h +2 -1
@@ -303,7 +303,8 @@ static inline enum skb_drop_reason tcp_i const struct request_sock *req, int l3index, const struct tcp_ao_hdr *aoh) { - return SKB_NOT_DROPPED_YET; +NET_INC_STATS (sock_net (sk ),LINUX_MIB_TCPAOKEYNOTFOUND ); +return SKB_DROP_REASON_TCP_AOUNEXPECTED ; } static inline struct tcp_ao_key *tcp_ao_do_lookup(const struct sock *sk,
net/ipv4/tcp.c +2 -1
@@ -4974,7 +4974,8 @@ tcp_inbound_md5_hash(const struct sock * const void *saddr, const void *daddr, int family, int l3index, const __u8 *hash_location) { - return SKB_NOT_DROPPED_YET; +NET_INC_STATS (sock_net (sk ),LINUX_MIB_TCPMD5UNEXPECTED ); +return SKB_DROP_REASON_TCP_MD5UNEXPECTED ; }#endif
Greg Kroah-Hartman
maintainerPATCH 644/1005 tcp: fix request_sock use-after-free during Fast Open accept()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyunwoo Kim <[email protected]>
commit 62754aad50d0b30938bd8ce30b43474ce502a2af upstream.
Commit e3d95ad7da4f ("inet: avoid fastopen lock for regular accept()") made inet_csk_accept() check tfo_listener before taking fastopenq.lock to avoid taking the lock for connections that did not use Fast Open.
reqsk_fastopen_remove() clears tfo_listener while holding fastopenq.lock, then reads req->sk. If inet_csk_accept() concurrently observes tfo_listener after it has been cleared, it skips fastopenq.lock and drops the last reference to the request_sock. This can free the request_sock while reqsk_fastopen_remove() is still using it.
If the freed memory is reused for a new request_sock with req->sk == NULL, the reset path in reqsk_fastopen_remove() can append the new request_sock to the original listener's list of requests that caused an RST. After the new request_sock is freed, the next append writes through the stale rskq_rst_tail into freed memory.
KASAN reported the following use-after-free when writing fastopenq->rskq_rst_tail->dl_next = req:
BUG: KASAN: slab-use-after-free in reqsk_fastopen_remove+0x142/0x210 Write of size 8 at addr ffff888108230688 by task swapper/5/0 ... Call Trace: <IRQ> ... reqsk_fastopen_remove+0x142/0x210 tcp_check_req+0x96f/0xdd0 ... tcp_rcv_state_process+0x19c/0x26b0 ... tcp_v4_do_rcv+0x16e/0x490 tcp_v4_rcv+0x14a0/0x1af0 ... ip_protocol_deliver_rcu+0x39/0x1e0 ip_local_deliver_finish+0x124/0x1e0 ip_local_deliver+0xfb/0x1e0 ... </IRQ>
To widen the race windows, mdelay(5) was added after newsk = req->sk, mdelay(20) after the if (req) reqsk_put(req) block, and mdelay(100) after tcp_rsk(req)->tfo_listener = false. The KASAN report above was reproduced with this kernel.
For the lockless check, use tcp_sk(newsk)->syn_fastopen_child instead of tfo_listener, which reqsk_fastopen_remove() clears.
syn_fastopen_child is a field of the Fast Open child TCP socket referenced by newsk, not of the request_sock. It is set before the child socket is added to the accept queue. The paths that call reqsk_fastopen_remove() in response to a remote ACK or RST do not clear this field.
inet_csk_accept() uses this field to take fastopenq.lock only for Fast Open child sockets and rechecks tfo_listener while holding the lock. Connections that did not use Fast Open continue to avoid the lock.
--- net/ipv4/inet_connection_sock.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv4/inet_connection_sock.c +1 -1
@@ -683,7 +683,7 @@ struct sock *inet_csk_accept(struct sock newsk = req->sk;if (sk->sk_protocol ==IPPROTO_TCP && -tcp_rsk (req)->tfo_listener) { +tcp_sk (newsk)->syn_fastopen_child) {spin_lock_bh (&queue->fastopenq.lock);if (tcp_rsk (req)->tfo_listener) {/* We are still waiting for the final ACK from 3WHS
Greg Kroah-Hartman
maintainerPATCH 645/1005 seg6: validate state in netfilter continuations
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zixuan Chai <[email protected]>
commit 549484dd3e80a721d51bd695f22a800d2e05bea1 upstream.
When nf_hooks_lwtunnel is enabled, End.DX4 sends decapsulated packets through NF_INET_PRE_ROUTING. If DNAT changes the inner destination, nf_nat_ipv4_pre_routing() drops skb_dst(), and the continuation then dereferences the missing dst's lwtstate. This causes a KASAN NULL pointer dereference and fatal exception panic.
End.DX6 has the same issue with IPv6 DNAT. In seg6_iptunnel, POST_ROUTING SNAT with an outbound XFRM policy can replace the dst before the continuation resumes.
Validate the current dst and expected lwtstate type in each NF_HOOK() continuation before calling the existing handler. Drop packets with missing or incompatible state while preserving direct no-hook paths. The helpers return bool because callers only need a validity check.
Testing shows that the End.DX4 DNAT reproducer triggers a KASAN NULL pointer dereference without this change and no longer does so with the fix. The SNAT+ESP/XFRM reproducer also completes without the reported fault. The in-tree End.DX4 netfilter forwarding selftest passes all four bidirectional checks with nf_hooks_lwtunnel disabled and enabled.
--- net/ipv6/seg6_iptunnel.c | 46 +++++++++++++++++++++++++++++++++++---- net/ipv6/seg6_local.c | 55 ++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 94 insertions(+), 7 deletions(-)
net/ipv6/seg6_iptunnel.c +42 -4
@@ -18,6 +18,7 @@#include <net/ip6_fib.h> #include <net/route.h> #include <net/seg6.h> +#include <net/dst_metadata.h> #include <linux/seg6.h> #include <linux/seg6_iptunnel.h> #include <net/addrconf.h>
@@ -60,6 +61,21 @@ static inline struct seg6_lwt *seg6_lwt_return (struct seg6_lwt *)lwt->data; } +static bool seg6_skb_has_lwtstate (struct sk_buff *skb) +{ +struct dst_entry *dst; + +if (unlikely (!skb_valid_dst (skb))) +return false; + + dst =skb_dst (skb); +if (unlikely (!dst->lwtstate || + dst->lwtstate->type !=LWTUNNEL_ENCAP_SEG6 )) +return false; + +return true; +} +static inline struct seg6_iptunnel_encap *seg6_encap_lwtunnel (struct lwtunnel_state *lwt) {
@@ -616,6 +632,17 @@ drop:return err; } +static int seg6_input_core_nf (struct net *net,struct sock *sk, +struct sk_buff *skb) +{ +if (unlikely (!seg6_skb_has_lwtstate (skb))) { +kfree_skb (skb); +return -EINVAL ; + } + +return seg6_input_core (net, sk, skb); +} +static int seg6_input_nf (struct sk_buff *skb) {struct net_device *dev =skb_dst_dev (skb);
@@ -624,10 +651,10 @@ static int seg6_input_nf(struct sk_buffswitch (skb->protocol) {case htons (ETH_P_IP ):return NF_HOOK (NFPROTO_IPV4 ,NF_INET_POST_ROUTING , net,NULL , - skb,NULL , dev, seg6_input_core); + skb,NULL , dev, seg6_input_core_nf);case htons (ETH_P_IPV6 ):return NF_HOOK (NFPROTO_IPV6 ,NF_INET_POST_ROUTING , net,NULL , - skb,NULL , dev, seg6_input_core); + skb,NULL , dev, seg6_input_core_nf); }return -EINVAL ;
@@ -720,6 +747,17 @@ drop:return err; } +static int seg6_output_core_nf (struct net *net,struct sock *sk, +struct sk_buff *skb) +{ +if (unlikely (!seg6_skb_has_lwtstate (skb))) { +kfree_skb (skb); +return -EINVAL ; + } + +return seg6_output_core (net, sk, skb); +} +static int seg6_output_nf (struct net *net,struct sock *sk,struct sk_buff *skb) {struct net_device *dev =skb_dst_dev (skb);
@@ -727,10 +765,10 @@ static int seg6_output_nf(struct net *neswitch (skb->protocol) {case htons (ETH_P_IP ):return NF_HOOK (NFPROTO_IPV4 ,NF_INET_POST_ROUTING , net, sk, skb, -NULL , dev, seg6_output_core); +NULL , dev, seg6_output_core_nf);case htons (ETH_P_IPV6 ):return NF_HOOK (NFPROTO_IPV6 ,NF_INET_POST_ROUTING , net, sk, skb, -NULL , dev, seg6_output_core); +NULL , dev, seg6_output_core_nf); }return -EINVAL ;
net/ipv6/seg6_local.c +52 -3
103 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 646/1005 mptcp: reject DATA_ACKs against a reversed send interval
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit d75e5cd72995ec2fa77ec77a593cea28e2490ff1 upstream.
ack_update_msk() samples snd_nxt before taking the data lock, but reads snd_una after taking it. Concurrent transmission and ACK processing can therefore leave the sampled upper bound behind snd_una. Active-open completion also exposes a reversed interval when it initializes snd_una to IDSN + 1 while the socket-owned state synchronization is deferred.
A peer-supplied 64-bit Data ACK half a sequence space away can pass both wraparound comparisons against such an interval. The resulting snd_una can make __mptcp_retrans() inflate a fragment's already_sent field. Later ACKs can then underflow data_len and cause out-of-bounds page fragments to be passed to TCP.
Read snd_nxt after acquiring the data lock and reject reversed intervals before checking the received Data ACK. This keeps the interval shorter than half the sequence space, so the existing upper-bound check cannot accept an advance beyond snd_nxt. Preserve the existing handling of old ACKs and keep the transmit fields under their existing socket locking.
--- net/mptcp/options.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
net/mptcp/options.c +8 -4
@@ -1122,9 +1122,9 @@ static void ack_update_msk(struct mptcp_struct sock *ssk, struct mptcp_options_received *mp_opt) { - u64 new_wnd_end, new_snd_una, snd_nxt = READ_ONCE(msk->snd_nxt); + u64 new_wnd_end, new_snd_una, old_snd_una;struct sock *sk = (struct sock *)msk; -u64 old_snd_una; +u64 snd_nxt;mptcp_data_lock (sk);
@@ -1133,10 +1133,14 @@ static void ack_update_msk(struct mptcp_* more dangerous than missing an ack */ old_snd_una = msk->snd_una; + snd_nxt =READ_ONCE (msk->snd_nxt); new_snd_una =mptcp_expand_seq (old_snd_una, mp_opt->data_ack, mp_opt->ack64); -/* ACK for data not even sent yet? Ignore.*/ -if (unlikely (after64 (new_snd_una, snd_nxt))) +/* The active-open state sync can defer the snd_nxt update. Do not +* accept an ACK against a reversed interval, or beyond snd_nxt. +*/ +if (unlikely (before64 (snd_nxt, old_snd_una) || +after64 (new_snd_una, snd_nxt))) new_snd_una = old_snd_una; new_wnd_end = new_snd_una +tcp_sk (ssk)->snd_wnd;
Greg Kroah-Hartman
maintainerPATCH 647/1005 ipv4: keep XFRM headers out of corked skb lengths
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 0f47fce51a98d3d9f439c16861d519a7b833a176 upstream.
__ip_append_data() allocates space for dst.header_len in the first skb, but includes that space in skb->len until __ip_make_skb() pulls it. Fragment accounting uses an MTU that already excludes the XFRM headers. As a result, the next skb can have a fraggap larger than its capped datalen, and skb_copy_and_csum_bits() can overwrite its shared info.
For example, five AH tunnel states can reserve 500 bytes while leaving an effective MTU of 348. With 40 bytes of IPv4 options, the second skb has room for 288 bytes of fragment data but receives a 500-byte gap copy. The overwritten shared info is subsequently consumed by the skb release paths.
Reserve the XFRM headers together with the link-layer headroom instead. This keeps skb->len, the gap-copy offsets and the trim lengths relative to the IPv4 packet throughout corking. The network and transport header addresses and the headroom available to XFRM at output are unchanged. Both paged and linear allocations, including subsequent corked appends, use the corrected accounting.
--- net/ipv4/ip_output.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
net/ipv4/ip_output.c +4 -4
@@ -1150,16 +1150,16 @@ alloc_new_skb:*/ skb->ip_summed = csummode; skb->csum =0 ; -skb_reserve (skb, hh_len); +skb_reserve (skb, hh_len + exthdrlen);/* * Find where to start putting bytes. */ - data =skb_put (skb, fraglen + exthdrlen - pagedlen); -skb_set_network_header (skb, exthdrlen); + data =skb_put (skb, fraglen - pagedlen); +skb_reset_network_header (skb); skb->transport_header = (skb->network_header + fragheaderlen); - data += fragheaderlen + exthdrlen; + data += fragheaderlen;if (fraggap) { skb->csum = skb_copy_and_csum_bits(
Greg Kroah-Hartman
maintainerPATCH 648/1005 ipv4: fib_trie: prevent speculative out-of-bounds child access
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daniël Trujillo <[email protected]>
commit fd3d73286662950656f54616d0b3fea29e2dc99a upstream.
fib_table_lookup() checks the child index against the bounds before passing it to get_child_rcu().
The index is derived from the lookup key, which in turn is derived from flp->daddr. A userspace process can therefore influence the index by triggering lookups for chosen destination IPv4 addresses.
If this bounds check is mispredicted as in-bounds, an out-of-bounds index can be transiently passed to get_child_rcu(). The value loaded beyond the child array is then treated as a node pointer. A later transient dereference of that pointer can cause a data-dependent cache footprint.
This was found during Spectre-v1 research. Leakage was demonstrated with instrumentation that delays branch resolution with a CLFLUSH before the mispredicted branch and makes the leaked location deterministic for reproducible measurement. In that setup, a userspace-controlled IPv4 lookup key was able to trigger a transient out-of-bounds child access. The transient use of the loaded value as a pointer caused a data-dependent cache footprint that was recoverable from userspace using Prime+Probe. A real-world attacker would likely need to delay branch resolution, which was not demonstrated end-to-end without the added CLFLUSH.
Sanitize the index with array_index_nospec() before accessing the child array. This removed the observed leakage in the described setup.
Apply the hardening before setting cindex in fib_table_lookup(), because cindex can later be used by the backtrace path to load another child pointer. fib_find_node() has the same pattern, with the checked index derived from a user-provided key in fib_table_insert() and fib_table_delete(). leaf_walk_rcu() has a similar checked cindex before get_child_rcu(), and the traversed state can be influenced by userspace actions. fib_find_node() runs under RTNL and leaf_walk_rcu() is not on the packet lookup hot path, so harden those analogous accesses in the same way. Also harden fib_trie_get_next(), where a mispredicted loop condition could transiently read one child past the array.
I see a slowdown of roughly 10% in a microbenchmark where we call fib_table_lookup() with 64 routes directly from inside the kernel. I observed no slowdown in a loopback UDP sendto() microbenchmark.
--- net/ipv4/fib_trie.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
net/ipv4/fib_trie.c +13 -1
@@ -61,6 +61,7 @@#include <linux/export.h> #include <linux/vmalloc.h> #include <linux/notifier.h> +#include <linux/nospec.h> #include <net/net_namespace.h> #include <net/inet_dscp.h> #include <net/ip.h>
@@ -961,6 +962,8 @@ static struct key_vector *fib_find_node(break ; } + index =array_index_nospec (index,1ul << n->bits); +/* keep searching until we find a perfect match leaf or NULL */ }while (IS_TNODE (n));
@@ -1466,6 +1469,8 @@ int fib_table_lookup(struct fib_table *tif (IS_LEAF (n)) goto found; + index =array_index_nospec (index,1ul << n->bits); +/* only record pn and cindex if we are going to be chopping * bits later. Otherwise we are just wasting cycles. */
@@ -1766,6 +1771,8 @@ static struct key_vector *leaf_walk_rcu(if (cindex >> pn->bits)break ; + cindex =array_index_nospec (cindex,1ul << pn->bits); +/* descend into the next child */ n =get_child_rcu (pn, cindex++);if (!n)
@@ -1787,6 +1794,8 @@ static struct key_vector *leaf_walk_rcu(continue ; } + cindex =array_index_nospec (cindex,1ul << pn->bits); +/* grab the next available node */ n =get_child_rcu (pn, cindex++);if (!n)
@@ -2431,7 +2440,10 @@ static struct key_vector *fib_trie_get_nwhile (!IS_TRIE (pn)) {while (cindex <child_length (pn)) { -struct key_vector *n =get_child_rcu (pn, cindex++); +struct key_vector *n; + + cindex =array_index_nospec (cindex,child_length (pn)); + n =get_child_rcu (pn, cindex++);if (!n)continue ;
Greg Kroah-Hartman
maintainerPATCH 649/1005 ipv6: fix cached route reuse for control messages
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xia Yan <[email protected]>
commit f778e80b3daf5033fb996f45c2b5d0ce1e82c0a7 upstream.
A connected IPv6 UDP or ping socket can reuse its cached route when an SO_MARK cmsg requests another mark. A packet can then bypass a prohibit rule instead of failing with EACCES.
ip6_sk_dst_lookup_flow() reads the cache even when connected is false. UDP clears connected after parsing IP or socket control messages. Ping always passes false.
Only read the cache when connected is true. Ordinary connected UDP sends keep using the cache. Ping sends do a fresh lookup.
Found during code review of IPv6 UDP route caching. On UML, the same connected-socket selftest fails four IPv6 cases before the fix and passes all 54 with it.
--- net/ipv6/ip6_output.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-)
net/ipv6/ip6_output.c +8 -5
@@ -1305,7 +1305,7 @@ EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);* @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup -* @connected: whether @sk is connected or not +* @connected: whether the flow can use and update the socket dst cache * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid.
@@ -1322,11 +1322,14 @@ struct dst_entry *ip6_sk_dst_lookup_flow const struct in6_addr *final_dst, bool connected) { -struct dst_entry *dst =sk_dst_check (sk,inet6_sk (sk)->dst_cookie); +struct dst_entry *dst; - dst =ip6_sk_dst_check (sk, dst, fl6); -if (dst) -return dst; +if (connected) { + dst =sk_dst_check (sk,inet6_sk (sk)->dst_cookie); + dst =ip6_sk_dst_check (sk, dst, fl6); +if (dst) +return dst; + } dst =ip6_dst_lookup_flow (sock_net (sk), sk, fl6, final_dst);if (connected && !IS_ERR (dst))
Greg Kroah-Hartman
maintainerPATCH 650/1005 ipv6: reject routes without an inet6_dev
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit 08a1eb7a634f665718ebe74e0960e242f597135e upstream.
ip6_route_output() and ip6_route_lookup() can return an error-free route whose rt6i_idev is NULL. Lowering an external nexthop device's MTU below IPV6_MIN_MTU tears down its inet6_dev, while fib6_ifdown() leaves routes using nexthop objects in the FIB.
An unprivileged user with CAP_NET_ADMIN in a private user and network namespace can construct this state. Consumers which treat a route without an error as usable can then dereference the NULL rt6i_idev. This was reproduced as a KASAN NULL pointer dereference in ip6_tnl_xmit().
An audit of IPv6 route and tunnel users found this unchecked ip6_dst_idev() dereference.
A similar missing inet6_dev check was fixed in commit 1b9b5323725e ("netfilter: ip6t_rpfilter: reject routes without inet6_dev"). However, the route construction path still marks routes without an inet6_dev as successful, leaving every consumer responsible for the same check.
Acquire the inet6_dev reference before initializing the destination. If a non-reject route has no inet6_dev, initialize it as RTN_UNREACHABLE instead of a successful route. Explicit reject routes keep their original type and error. This establishes that ordinary error-free IPv6 routes have an inet6_dev while retaining the existing defensive checks at callers.
The modified route object builds cleanly with W=1. A full x86_64 KASAN bzImage build completes; it reports two pre-existing kernel-doc warnings outside this change.
Tests:
- make W=1 net/ipv6/route.o
- full x86_64 KASAN bzImage build with W=1
- KASAN QEMU with an unprivileged user and network namespace: after lowering the MTU, the stale route returned No route to host, a normal route still resolved, and the collect_md trigger completed without KASAN, oops, or panic
- tools/testing/selftests/net/ip6_tunnel.sh in the same KASAN QEMU
--- net/ipv6/route.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
net/ipv6/route.c +7 -1
@@ -1165,6 +1165,12 @@ static void ip6_rt_init_dst(struct rt6_ireturn ; } +/* addrconf_ifdown() removed inet6_dev. The device can't do IPv6. */ +if (!rt->rt6i_idev) { +ip6_rt_init_dst_reject (rt,RTN_UNREACHABLE ); +return ; + } + rt->dst.error =0 ; rt->dst.output = ip6_output;
@@ -1200,10 +1206,10 @@ static void ip6_rt_copy_init(struct rt6_const struct net_device *dev = nh->fib_nh_dev;struct fib6_info *f6i = res->f6i; + rt->rt6i_idev = dev ?in6_dev_get (dev) :NULL ;ip6_rt_init_dst (rt, res); rt->rt6i_dst = f6i->fib6_dst; - rt->rt6i_idev = dev ?in6_dev_get (dev) :NULL ; rt->rt6i_flags = res->fib6_flags;if (nh->fib_nh_gw_family) { rt->rt6i_gateway = nh->fib_nh_gw6;
Greg Kroah-Hartman
maintainerPATCH 651/1005 ipvs: Defer application parent freeing until after RCU readers
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chengfeng Ye <[email protected]>
commit 1e0808008e44d736e57a897a51d14fa995099010 upstream.
unregister_ip_vs_app() removes each incarnation from its protocol list and uses call_rcu() to defer freeing it, but frees the parent application immediately. An RCU reader that already found an incarnation can still access the parent through inc->app in ip_vs_app_inc_get().
During FTP helper module unload, the following interleaving is possible:
CPU 0 (RCU reader) CPU 1 (module unload)
tcp_app_conn_bind()
find inc in protocol list
unregister_ip_vs_app()
ip_vs_app_inc_release(inc)
list_del_rcu(&inc->p_list)
call_rcu(&inc->rcu_head, ...)
kfree(a)
ip_vs_app_inc_get(inc)
try_module_get(inc->app->module)The helper module is already going away, so try_module_get() would fail, but evaluating its argument first reads the freed parent. The subsequent rcu_barrier() in pernet unregistration cannot protect this earlier free. KASAN reported:
BUG: KASAN: slab-use-after-free in ip_vs_app_inc_get+0x7c/0x90 Call Trace: ip_vs_app_inc_get+0x7c/0x90 tcp_app_conn_bind+0x1bc/0x290 ip_vs_conn_new+0x1915/0x20d0 ip_vs_schedule+0x697/0xea0 tcp_conn_schedule+0x489/0x820 ip_vs_in_hook+0x7bf/0x1f40 Allocated by task 88: kmemdup_noprof+0x20/0x50 register_ip_vs_app+0x12d/0x2c0 __ip_vs_ftp_init+0x56/0x160 [ip_vs_ftp] Freed by task 104: kfree+0x131/0x3c0 unregister_ip_vs_app+0x2f4/0x5b0 unregister_pernet_operations+0x232/0x490 unregister_pernet_subsys+0x1c/0x30 __do_sys_delete_module+0x346/0x510
Use kfree_rcu() with the existing rcu_head to keep the parent alive until these readers finish. Successful helper references already prevent normal module unload, and incarnation RCU callbacks do not access the parent.
--- net/netfilter/ipvs/ip_vs_app.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/netfilter/ipvs/ip_vs_app.c +1 -1
@@ -242,7 +242,7 @@ void unregister_ip_vs_app(struct netns_i }list_del (&a->a_list); -kfree (a); +kfree_rcu (a, rcu_head);/* decrease the module use count */ ip_vs_use_count_dec ();
Greg Kroah-Hartman
maintainerPATCH 652/1005 ipvs: fix protocol data lifetime during namespace teardown
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chengfeng Ye <[email protected]>
commit 832aa3e89e806bb2667fe4e656b705f4088b3c9d upstream.
IPVS frees its per-net protocol data before control cleanup cancels defense work and unregisters the sysctl table. A defense worker can load a protocol data pointer, then namespace cleanup can unlink and free that object before the worker dereferences pd->pp or pd->next. The worker's securetcp_lock does not serialize with protocol cleanup. A concurrent defense-mode sysctl write can reach the same timeout update path.
KASAN reported:
BUG: KASAN: slab-use-after-free in ip_vs_protocol_timeout_change Workqueue: events_long defense_work_handler Call Trace: ip_vs_protocol_timeout_change+0x1b4/0x1e0 update_defense_level+0x63e/0xd80 defense_work_handler+0x1e/0xc0 Allocated by task 125: ip_vs_protocol_net_init+0xda/0x2f0 __ip_vs_init+0x16b/0x240 setup_net+0xfc/0x310 Freed by task 12: ip_vs_protocol_net_cleanup+0x1d6/0x2e0 __ip_vs_cleanup_batch+0x7d/0x100 cleanup_net+0x38c/0x770
Run control cleanup before protocol cleanup so that defense work and active sysctl handlers have finished before their protocol data is freed. Initialize protocols before exposing the control interface, and unwind in reverse order, to enforce the same lifetime on initialization failure. Protocol initialization and exit do not depend on control state.
--- net/netfilter/ipvs/ip_vs_core.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
net/netfilter/ipvs/ip_vs_core.c +6 -6
@@ -2502,12 +2502,12 @@ static int __net_init __ip_vs_init(strucif (ip_vs_estimator_net_init (ipvs) <0 ) goto estimator_fail; -if (ip_vs_control_net_init (ipvs) <0 ) - goto control_fail; -if (ip_vs_protocol_net_init (ipvs) <0 ) goto protocol_fail; +if (ip_vs_control_net_init (ipvs) <0 ) + goto control_fail; +if (ip_vs_app_net_init (ipvs) <0 ) goto app_fail;
@@ -2527,10 +2527,10 @@ sync_fail: conn_fail:ip_vs_app_net_cleanup (ipvs); app_fail: -ip_vs_protocol_net_cleanup (ipvs); -protocol_fail:ip_vs_control_net_cleanup (ipvs); control_fail: +ip_vs_protocol_net_cleanup (ipvs); +protocol_fail:ip_vs_estimator_net_cleanup (ipvs); estimator_fail: net->ipvs =NULL ;
@@ -2547,8 +2547,8 @@ static void __net_exit __ip_vs_cleanup_b ipvs =net_ipvs (net);ip_vs_conn_net_cleanup (ipvs);ip_vs_app_net_cleanup (ipvs); -ip_vs_protocol_net_cleanup (ipvs);ip_vs_control_net_cleanup (ipvs); +ip_vs_protocol_net_cleanup (ipvs);ip_vs_estimator_net_cleanup (ipvs);IP_VS_DBG (2 ,"ipvs netns %d released\n" , ipvs->gen); net->ipvs =NULL ;
Greg Kroah-Hartman
maintainerPATCH 653/1005 gtp: free the skb after handling an echo response
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joas Antonio dos Santos <[email protected]>
commit f17b293d155f377e4cff582b8113991d2ad346d6 upstream.
gtp0_handle_echo_resp() and gtp1u_handle_echo_resp() return the result of genlmsg_multicast_netns() to gtp_encap_recv(). When the netlink notification is delivered that result is 0, and gtp_encap_recv() treats 0 as "the skb has been consumed":
switch (ret) {
case 1:
netdev_dbg(gtp->dev, "pass up to the process\n");
break;
case 0:
break;
case -1:
netdev_dbg(gtp->dev, "GTP packet has been dropped\n");
kfree_skb(skb);
ret = 0;
break;
}The echo response handlers only read from the skb and never free it or pass it on, so every echo response that is reported to a listener on the gtp multicast group leaks the skb. Echo responses are handled for any peer when the UDP sockets were created by the kernel, so a remote host can leak memory on the receiver by sending GTP echo responses while a process with CAP_NET_ADMIN is subscribed to the gtp multicast group, for example a daemon that monitors echo responses.
The error paths do not leak but have a related problem. -ENOMEM and the error from genlmsg_multicast_netns() (-ESRCH when nobody listens) are not -1, so they are returned unchanged to the UDP stack, which takes a negative value from encap_rcv() as a request to resubmit the packet to the protocol with that number.
Return -1 when the notification cannot be built, so that gtp_encap_recv() drops the skb, and consume the skb once the notification has been handed to netlink, whether or not anybody is listening.
Found by LLM-assisted source review, untested.
--- drivers/net/gtp.c | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-)
drivers/net/gtp.c +14 -8
@@ -560,16 +560,19 @@ static int gtp0_handle_echo_resp(struct msg =nlmsg_new (NLMSG_DEFAULT_SIZE ,GFP_ATOMIC );if (!msg) -return -ENOMEM ; +return -1 ; ret =gtp_genl_fill_echo (msg,0 ,0 ,0 ,GTP_CMD_ECHOREQ , echo);if (ret <0 ) {nlmsg_free (msg); -return ret; +return -1 ; } -return genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), - msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), + msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +consume_skb (skb); + +return 0 ; }static int gtp_proto_to_family (__u16 proto)
@@ -747,16 +750,19 @@ static int gtp1u_handle_echo_resp(struct msg =nlmsg_new (NLMSG_DEFAULT_SIZE ,GFP_ATOMIC );if (!msg) -return -ENOMEM ; +return -1 ; ret =gtp_genl_fill_echo (msg,0 ,0 ,0 ,GTP_CMD_ECHOREQ , echo);if (ret <0 ) {nlmsg_free (msg); -return ret; +return -1 ; } -return genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), - msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +genlmsg_multicast_netns (>p_genl_family,dev_net (gtp->dev), + msg,0 ,GTP_GENL_MCGRP ,GFP_ATOMIC ); +consume_skb (skb); + +return 0 ; }static int gtp_parse_exthdrs (struct sk_buff *skb,unsigned int *hdrlen)
Greg Kroah-Hartman
maintainerPATCH 654/1005 hv_netvsc: Stop PPI parsing on invalid metadata
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Erni Sri Satya Vennela <[email protected]>
commit 19a227903e65c7a9c179156485660a4e017575fe upstream.
rndis_get_ppi() uses continue when a per-packet information entry has an invalid size or offset, or cannot hold the requested metadata. However, the remaining length and entry pointer are only updated at the bottom of the loop. Each error path therefore retries the same invalid entry indefinitely, repeatedly logging the error and preventing receive processing from completing.
Return NULL on these validation failures instead of continuing. This terminates the lookup when malformed metadata is encountered while preserving the existing behavior for valid entries.
The issue was reported through an internal bug-tracking system and confirmed by manual code inspection. The pre-fix hang has not been reproduced locally.
--- drivers/net/hyperv/rndis_filter.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/net/hyperv/rndis_filter.c +3 -3
@@ -401,12 +401,12 @@ static inline void *rndis_get_ppi(struct/* Validate ppi_offset and ppi_size */ if (ppi->size > len) {netdev_err (ndev,"Invalid ppi size: %u\n" , ppi->size); -continue ; +return NULL ; }if (ppi->ppi_offset >= ppi->size) {netdev_err (ndev,"Invalid ppi_offset: %u\n" , ppi->ppi_offset); -continue ; +return NULL ; }if (ppi->type == type && ppi->internal == internal) {
@@ -414,7 +414,7 @@ static inline void *rndis_get_ppi(structif (ppi->size - ppi->ppi_offset < ppi_size) {netdev_err (ndev,"Invalid ppi: size %u ppi_offset %u\n" , ppi->size, ppi->ppi_offset); -continue ; +return NULL ; }return (void *)((ulong )ppi + ppi->ppi_offset); }
Greg Kroah-Hartman
maintainerPATCH 655/1005 hv_sock: Report no unread data before a channel is available
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 71b06766b7c49ed5f489b8bd104f82ff164d67a3 upstream.
The Hyper-V transport is assigned before the asynchronous VMBus channel offer completes. Its zero-initialized hvsock therefore has a NULL chan until hvs_open_connection() associates the channel with the socket.
SIOCINQ can query the assigned transport while the socket is connecting, or after connect() fails once the transport has been assigned. Unlike poll(), that path does not check stream_is_active() before calling the transport's stream_has_data callback. hvs_stream_has_data() then passes the NULL channel to hvs_channel_readable_payload(), and any user in the guest can trigger an oops:
BUG: kernel NULL pointer dereference, address: 0000000000000178 RIP: 0010:hvs_stream_has_data+0x23/0x120 Call Trace: <TASK> ? vsock_ioctl+0x74/0xf0 sock_do_ioctl+0x42/0xf0 sock_ioctl+0x27d/0x310 do_vfs_ioctl+0x700/0x810 __x64_sys_ioctl+0x7d/0xf0
Return zero unread bytes when no channel is available, before accessing the receive state or ring. Leave the existing channel-backed receive handling unchanged.
The oops was reproduced on an unmodified v7.4-rc1 kernel in a WSL2 guest with a small user-space program, available on request. With this patch, the program reports zero unread bytes and the kernel logs nothing. Other vsock_test cases were not run, as most of them need a host-side peer.
AI assistance was used to identify the issue and develop the fix.
--- net/vmw_vsock/hyperv_transport.c | 3 +++ 1 file changed, 3 insertions(+)
net/vmw_vsock/hyperv_transport.c +3 -0
@@ -697,6 +697,9 @@ static s64 hvs_stream_has_data(struct vsstruct hvsock *hvs = vsk->trans;s64 ret; +if (!hvs->chan) +return 0 ; +if (hvs->recv_data_len >0 )return hvs->recv_data_len;
Greg Kroah-Hartman
maintainerPATCH 656/1005 net: gro: avoid parsing headers from shared fragments
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 44818c9a826d766dc0e21179dc76f229334f1dda upstream.
When an skb has an empty linear head, skb_gro_reset_offset() can expose the first page fragment directly to GRO header parsers. For an SKBFL_SHARED_FRAG skb, those bytes may still be writable through a file mapping. Headers validated during receive can therefore differ from the headers later copied into the linear head and used during completion.
For example, changing an IPv6 destination-options length between the short and full header fetches in ipv6_gro_pull_exthdrs() can make ipv6_gro_complete() pass an out-of-bounds offset to udp6_gro_complete(). A userspace reproducer triggered a KASAN slab-out-of-bounds read there on an unmodified kernel as UID 1000. The same completion path can write the UDP checksum and length through the invalid offset. The packet has trusted TCP GSO metadata and spliced file data, so it reaches completion without an skb zerocopy destructor or a second GRO packet.
Disable the direct-fragment fast path for skbs with externally writable fragments. With an empty linear head, frag0_len remains zero, so skb_gro_header_slow() pulls each required header into the linear head before it is inspected. Subsequent pulls preserve the validated prefix. This covers both gro_receive_skb() and napi_gro_frags(), including other protocols using the same helpers. Linear headers and private fragments retain their existing fast paths.
Codex assisted with review of the supplied report, reproducer and draft fix, related-path analysis, and this changelog. The patched net/core/gro.o builds with W=1 using the supplied x86-64 configuration, allyesconfig and allmodconfig. The fix was checked by code-path analysis; the reproducer and kernel selftests have not been run on a booted patched kernel.
The issue was found by an LLM.
--- net/core/gro.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/core/gro.c +2 -1
@@ -414,7 +414,8 @@ static inline void skb_gro_reset_offset( headlen =skb_headlen (skb);NAPI_GRO_CB (skb)->frag0 = skb->data;NAPI_GRO_CB (skb)->frag0_len = headlen; -if (headlen) +/* Shared fragments must be pulled into the linear head before parsing. */ +if (headlen ||skb_has_shared_frag (skb))return ; pinfo =skb_shinfo (skb);
Greg Kroah-Hartman
maintainerPATCH 657/1005 net: gro: do not undo remote checksum offload on merged packets
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
commit c817ec1b06875b98460fbd19591be541bc3fa924 upstream.
skb_gro_flush_final_remcsum() calls skb_gro_remcsum_cleanup() to undo the checksum adjustment done by skb_gro_remcsum_process() when the packet was not consumed by GRO.
When the inner handler merged the packet (NAPI_GRO_CB(skb)->same_flow is set), grc->offset can no longer be trusted:
- skb_gro_receive() either gives the frags or the head of the skb to the held packet, or uses __skb_pull(skb, offset) before adding the skb to the frag_list of the held packet.
- skb_gro_receive_list() uses skb_pull(skb, skb_gro_offset(skb)).
grc->offset is relative to the original skb->data, so the 2-byte read-modify-write done by skb_gro_remcsum_cleanup() can land in the payload of a packet which now belongs to the GRO packet. pskb_may_pull() can also be called on this frag_list member.
With fraglist GRO, this can also be a use-after-free:pskb_may_pull(skb, skb_gro_offset(skb)) in skb_gro_receive_list() or udp_gro_receive_segment() releases the first page fragment if it only contains headers. NAPI_GRO_CB(skb)->frag0 and frag0_len are not updated, so skb_gro_remcsum_cleanup() takes the fast path and writes through frag0 into a page the skb no longer holds a reference on. The non merged case, where frag0 is used after this pull, is handled in the following patch.
For skbs merged by skb_gro_receive(), the cleanup can be skipped:
the skb is freed, or its headers are rebuilt from the head skb in skb_segment().
Fraglist members keep their own inner headers, as skb_segment_list() only copies the link-layer and tunnel headers from the head skb. Their checksum can not be right in all cases: a packet forwarded with its tunnel header needs the original value, while a VXLAN packet decapsulated locally needs the adjusted one, as vxlan_remcsum() only adjusts the head skb. Make skb_gro_receive_list() refuse packets with skb->remcsum_offload set, so that fraglist members never carry an adjusted checksum.
This affects VXLAN (VXLAN_F_REMCSUM_NOPARTIAL) and GUE (FOU_F_REMCSUM_NOPARTIAL).
This was found while fixing a report from Taesoo Kim and Cen Zhang, who used LLM assisted code analysis and provided reproducers.
--- include/net/gro.h | 8 +++++++- net/core/gro.c | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-)
include/net/gro.h +7 -1
@@ -351,7 +351,13 @@ static inline void skb_gro_remcsum_cleanvoid *ptr;size_t plen = grc->offset +sizeof (u16); -if (!grc->delta) +/* Once merged, grc->offset can not be trusted: the frags or head +* of this skb now belong to the GRO packet, or skb->data was pulled +* past the headers before adding it to a frag_list. +* skb_gro_receive_list() does not merge packets with an adjusted +* checksum, other merged packets do not use their headers anymore. +*/ +if (!grc->delta ||NAPI_GRO_CB (skb)->same_flow)return ; ptr =skb_gro_header (skb, plen, grc->offset);
net/core/gro.c +7 -0
@@ -238,6 +238,13 @@ int skb_gro_receive_list(struct sk_buff NAPI_GRO_CB(skb)->flush))return -E2BIG ; +/* Fraglist members keep their own headers. Their checksum can not +* be right both for a forwarded packet and for a decapsulated one, +* if remote checksum offload adjusted it. +*/ +if (unlikely (skb->remcsum_offload)) +return -EINVAL ; +if (!pskb_may_pull (skb,skb_gro_offset (skb))) {NAPI_GRO_CB (skb)->flush =1 ;return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 658/1005 net: gro: invalidate frag0 after a pull
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
commit 98d949a15ff9d3fffaa6983223178374aab92db6 upstream.
Since commit bd56a29c7a4e ("net: gro: change skb_gro_network_header()"), skb_gro_header_slow() no longer invalidates NAPI_GRO_CB(skb)->frag0 after pskb_may_pull(). skb_gro_may_pull() keeps comparing against the frag0_len value set in skb_gro_reset_offset(), assuming that after a slow pull, all later accesses are beyond frag0_len.
This is not true:
- udp4_gro_receive() and udp6_gro_receive() read the network header with skb_gro_network_header() after udp_gro_udphdr() pulled the UDP header.
- vxlan_gro_receive() calls skb_gro_remcsum_cleanup() at a lower offset after the inner handlers pulled their headers.
- skb_gro_remcsum_process() can pull beyond the inner Ethernet header before eth_gro_receive() reads it.
- napi_frags_skb() calls __skb_pull(skb, ETH_HLEN) after a slow pull, so frag0 still points to the Ethernet header.
If the pull consumed the first page fragment, __skb_pull_tail() released it. If the head had to grow, pskb_expand_head() freed the old one. These reads, and the 2-byte write in skb_gro_remcsum_cleanup(), then access memory the skb no longer holds a reference on.
esp4_gro_receive(), esp6_gro_receive(), skb_gro_receive_list() and udp_gro_receive_segment() also pull directly and never invalidated frag0.
Add skb_gro_frag0_invalidate(), which only clears frag0_len, and call it before each of these pulls. This is a single store in the slow path, and frag0 stays non NULL, so skb_gro_network_header() does not need a NULL test.
frag0 must be invalidated even if the pull fails: __pskb_pull_tail() can return NULL after pskb_expand_head() freed the old head, for instance if a frag_list member has to be cloned or pulled.
As frag0 is now invalidated before a pull that can fail, gro_try_pull_from_frag0() can see an skb whose linear part does not cover skb_gro_offset() while frag0 still points to the start of the packet, for instance after skb_gro_remcsum_cleanup() pulled a shorter length. Copying from frag0 would then corrupt the headers: only use frag0 while frag0_len is not zero, and use pskb_may_pull() otherwise. If this pull fails, for instance after a failed pskb_pull() in esp4_gro_receive(), do not hold the packet: later GRO lookups and gro_complete() handlers expect its headers in the linear part.
This was found by Taesoo Kim and Cen Zhang, using LLM assisted code analysis, and confirmed with reproducers.
--- include/net/gro.h | 10 ++++++++++ net/core/gro.c | 20 ++++++++++++++++---- net/ipv4/esp4_offload.c | 1 + net/ipv4/udp_offload.c | 1 + net/ipv6/esp6_offload.c | 1 + 5 files changed, 29 insertions(+), 4 deletions(-)
include/net/gro.h +10 -0
@@ -160,9 +160,19 @@ static inline bool skb_gro_may_pull(consreturn likely (hlen <=NAPI_GRO_CB (skb)->frag0_len); } +/* A pull can release the page fragment frag0 points to, or reallocate +* skb->head, even if it fails. Call this before the pull, to make sure later +* skb_gro_header() and skb_gro_network_header() calls no longer use frag0. +*/ +static inline void skb_gro_frag0_invalidate (struct sk_buff *skb) +{ +NAPI_GRO_CB (skb)->frag0_len =0 ; +} +static inline void *skb_gro_header_slow (struct sk_buff *skb,unsigned int hlen,unsigned int offset) { +skb_gro_frag0_invalidate (skb);if (!pskb_may_pull (skb, hlen))return NULL ;
net/core/gro.c +16 -4
@@ -245,6 +245,7 @@ int skb_gro_receive_list(struct sk_buffif (unlikely (skb->remcsum_offload))return -EINVAL ; +skb_gro_frag0_invalidate (skb);if (!pskb_may_pull (skb,skb_gro_offset (skb))) {NAPI_GRO_CB (skb)->flush =1 ;return -ENOMEM ;
@@ -459,12 +460,19 @@ static void gro_pull_from_frag0(struct s } } -static void gro_try_pull_from_frag0 (struct sk_buff *skb) +static bool gro_try_pull_from_frag0 (struct sk_buff *skb) {int grow =skb_gro_offset (skb) -skb_headlen (skb); -if (grow >0 ) +if (grow <=0 ) +return true; + +/* frag0 can only be used if no pull happened. */ +if (likely (NAPI_GRO_CB (skb)->frag0_len)) {gro_pull_from_frag0 (skb, grow); +return true; + } +return pskb_may_pull (skb,skb_gro_offset (skb)); }static void gro_flush_oldest (struct gro_node *gro,struct list_head *head)
@@ -566,13 +574,17 @@ found_ptype:if (NAPI_GRO_CB (skb)->flush) goto normal; +/* Must be called before setting NAPI_GRO_CB(skb)->{age|last}. +* A held packet must have its headers in the linear part. +*/ +if (unlikely (!gro_try_pull_from_frag0 (skb))) + goto normal; +if (unlikely (gro_list->count >=MAX_GRO_SKBS ))gro_flush_oldest (gro, &gro_list->list);else gro_list->count++; -/* Must be called before setting NAPI_GRO_CB(skb)->{age|last} */ -gro_try_pull_from_frag0 (skb);NAPI_GRO_CB (skb)->age = jiffies;NAPI_GRO_CB (skb)->last = skb;if (!skb_is_gso (skb))
net/ipv4/esp4_offload.c +1 -0
@@ -37,6 +37,7 @@ static struct sk_buff *esp4_gro_receive(__be32 seq;__be32 spi; +skb_gro_frag0_invalidate (skb);if (!pskb_pull (skb, offset))return NULL ;
net/ipv4/udp_offload.c +1 -0
@@ -748,6 +748,7 @@ static struct sk_buff *udp_gro_receive_s pp = p; }else {if (NAPI_GRO_CB (skb)->is_flist) { +skb_gro_frag0_invalidate (skb);if (!pskb_may_pull (skb,skb_gro_offset (skb))) {NAPI_GRO_CB (skb)->flush =1 ;return NULL ;
net/ipv6/esp6_offload.c +1 -0
@@ -64,6 +64,7 @@ static struct sk_buff *esp6_gro_receive(if (NAPI_GRO_CB (skb)->proto ==IPPROTO_UDP ) encap_type =UDP_ENCAP_ESPINUDP ; +skb_gro_frag0_invalidate (skb);if (!pskb_pull (skb, offset))return NULL ;
Greg Kroah-Hartman
maintainerPATCH 659/1005 netfilter: nf_dup: preserve guard across NFQUEUE reinjection
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zihan Xi <[email protected]>
commit 82052e5b5ec36504fe1b9c3c28a711a78fcacf37 upstream.
NFQUEUE can suspend traversal of a duplicated packet while the task-local duplication guard is set. The output call then returns and clears the guard before a later verdict resumes hook traversal.
Save the guard in the queue entry and restore it while reinjection continues hook traversal. Preserve and restore the verdict task's prior state, including nested synchronous reinjection.
--- include/net/netfilter/nf_queue.h | 1 + net/netfilter/nf_queue.c | 1 + net/netfilter/nfnetlink_queue.c | 17 ++++++++++++++--- 3 files changed, 16 insertions(+), 3 deletions(-)
include/net/netfilter/nf_queue.h +1 -0
@@ -23,6 +23,7 @@ struct nf_queue_entry {struct net_device *physout;#endif struct nf_hook_state state; +bool in_nf_duplicate;bool nf_ct_is_unconfirmed;u16 size;/* sizeof(entry) + saved route keys */
net/netfilter/nf_queue.c +1 -0
@@ -219,6 +219,7 @@ static int __nf_queue(struct sk_buff *sk *entry = (struct nf_queue_entry ) { .skb = skb, .skb_dev = skb->dev, + .in_nf_duplicate = current->in_nf_duplicate, .state = *state, .hook_index = index, .size =sizeof (*entry) + route_key_size,
net/netfilter/nfnetlink_queue.c +14 -3
@@ -44,6 +44,7 @@#include <net/sock.h> #include <net/tcp_states.h> #include <net/netfilter/nf_queue.h> +#include <net/net_debug.h> #include <net/netns/generic.h> #include <linux/atomic.h>
@@ -365,21 +366,30 @@ static void nf_reinject(struct nf_queue_const struct nf_hook_entry *hook_entry;const struct nf_hook_entries *hooks;struct sk_buff *skb = entry->skb; +bool old_in_nf_duplicate;const struct net *net;unsigned int i;int err;u8 pf; +DEBUG_NET_WARN_ONCE (current->in_nf_duplicate && + !entry->in_nf_duplicate, +"%s called with unexpected duplication guard" , + __func__); +local_bh_disable (); + old_in_nf_duplicate = current->in_nf_duplicate; + net = entry->state.net; pf = entry->state.pf; + current->in_nf_duplicate = entry->in_nf_duplicate; hooks =nf_hook_entries_head (net, pf, entry->state.hook); i = entry->hook_index;if (!hooks || i >= hooks->num_hook_entries) {kfree_skb_reason (skb,SKB_DROP_REASON_NETFILTER_DROP );nf_queue_entry_free (entry); -return ; + goto out; } hook_entry = &hooks->hooks[i];
@@ -402,9 +412,7 @@ next_hook:switch (verdict &NF_VERDICT_MASK ) {case NF_ACCEPT :case NF_STOP : -local_bh_disable (); entry->state.okfn (entry->state.net, entry->state.sk, skb); -local_bh_enable ();break ;case NF_QUEUE : err =nf_queue (skb, &entry->state, i, verdict);
@@ -418,6 +426,9 @@ next_hook: }nf_queue_entry_free (entry); +out: + current->in_nf_duplicate = old_in_nf_duplicate; +local_bh_enable (); }/* return true if the entry has an unconfirmed conntrack attached that isn't owned by us
Greg Kroah-Hartman
maintainerPATCH 660/1005 netfilter: xt_recent: do not call remove_proc_entry() under recent_lock
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft) <[email protected]>
commit 17c2e41736b62cfe444c64d67860b1fbc1e886ac upstream.
recent_proc_net_exit() removes the /proc/net/xt_recent/<name> entries of a dying network namespace while holding spin_lock_bh(&recent_lock). remove_proc_entry() may sleep: proc_entry_rundown() waits until every task that is still inside the entry's file operations has left. A reader of such an entry is counted in by proc_reg_read() before recent_seq_start() takes recent_lock. So if a read is in flight when the namespace is torn down, cleanup_net() sleeps in atomic context holding the spinlock that the reader is spinning on, and neither side can ever make progress.
An unprivileged user can trigger this from a user namespace by adding a rule with the "recent" match and reading its proc file while the namespace is being destroyed. As recent_lock is global, every later attempt to take it spins forever too: the spinning can spread to all CPUs, and network namespace teardown stops system-wide.
BUG: sleeping function called from invalid context at
kernel/sched/completion.c:116
#3: (recent_lock){+...}-{3:3}, at: recent_net_exit+0x2b/0x140
Workqueue: netns cleanup_net
Call Trace:
proc_entry_rundown+0x185/0x1b0
remove_proc_entry+0x21a/0x520
recent_net_exit+0x7f/0x140
cleanup_net+0x414/0x8f0
...
rcu: INFO: rcu_preempt self-detected stall on CPU
Call Trace:
queued_spin_lock_slowpath+0x313/0xc20
recent_seq_start+0x87/0x1b0
seq_read_iter+0x265/0x11e0
proc_reg_read+0x1ab/0x270Fix by taking recent_mutex instead of recent_lock. According to commit a0e889bb1bdc ("[NETFILTER]: recent match: fix "sleeping function called from invalid context""), recent_mutex is the lock to use here: it protects recent_net->tables and was introduced so that proc entries are created and removed without recent_lock held, because those calls may sleep. hashlimit_proc_net_exit() does the same for xt_hashlimit.
--- net/netfilter/xt_recent.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
net/netfilter/xt_recent.c +4 -3
@@ -649,14 +649,15 @@ static void __net_exit recent_proc_net_e/* recent_net_exit() is called before recent_mt_destroy(). Make sure * that the parent xt_recent proc entry is empty before trying to -* remove it. +* remove it. Use recent_mutex instead of recent_lock since +* remove_proc_entry() may sleep. */ -spin_lock_bh (&recent_lock); +mutex_lock (&recent_mutex);list_for_each_entry (t, &recent_net->tables, list)remove_proc_entry (t->name, recent_net->xt_recent); recent_net->xt_recent =NULL ; -spin_unlock_bh (&recent_lock); +mutex_unlock (&recent_mutex);remove_proc_entry ("xt_recent" , net->proc_net); }
Greg Kroah-Hartman
maintainerPATCH 661/1005 netfilter: flowtable: extend ct timeout of offloaded GRE flows
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michail Andreas Michalopoulos <[email protected]>
commit 46ecda278f6eedffb2898d41e3e56757c996a41f upstream.
Since commit 03428ca5cee9 ("netfilter: conntrack: rework offload nf_conn timeout extension logic"), the flowtable gc worker extends the timeout of an offloaded conntrack entry from nf_flow_table_extend_ct_timeout() once it falls below 5 minutes. That function only knows about TCP and UDP and hits WARN_ON_ONCE() for any other layer 4 protocol. However, GRE flows can be offloaded too, both via nft_flow_offload and act_ct, since commit 4e8d9584d154 ("netfilter: flowtable: Support GRE").
The timeout of an offloaded GRE entry drops below that threshold as soon as a packet of the flow still goes through conntrack. With ip6gre tunnels using the default encapsulation limit this is ordinary traffic:
the flowtable does not parse the Destination Options header in front of GRE, so every packet of the flow takes the classic forwarding path. It also happens for a packet with ttl <= 1, which the flowtable fast path passes up to the classic forwarding path. nf_conntrack_gre_packet() then refreshes ct->timeout to the GRE stream timeout (180 seconds by default), and the next gc run triggers, as reported by syzbot:
WARNING: net/netfilter/nf_flow_table_core.c:553 at nf_flow_table_extend_ct_timeout+0x1ee/0x2f0 Workqueue: events_power_efficient nf_flow_offload_work_gc Call Trace: nf_flow_offload_gc_step+0x545/0x7b0 nf_flow_table_iterate+0x13c/0x1f0 nf_flow_offload_work_gc+0x22/0x70 process_scheduled_works+0xc3d/0x1630 worker_thread+0xa47/0xfb0 kthread+0x38b/0x480
Besides the splat, which panics the machine with panic_on_warn, the default branch sets the new timeout to 1 jiffy, so the conntrack entry expires right away and the offloaded flow is torn down.
Handle GRE like UDP and extend the timeout to NF_CT_DAY. GRE conntrack has no protocol state to take into account, and NF_CT_DAY is also what flow_offload_add() already sets for every offloaded entry, GRE included. This also restores the behaviour from before commit 03428ca5cee9, when the conntrack gc worker extended offloaded entries of any protocol to NF_CT_DAY.
--- net/netfilter/nf_flow_table_core.c | 1 + 1 file changed, 1 insertion(+)
net/netfilter/nf_flow_table_core.c +1 -0
@@ -544,6 +544,7 @@ static void nf_flow_table_extend_ct_timeswitch (l4proto) {case IPPROTO_UDP : +case IPPROTO_GRE : new_timeout =NF_CT_DAY ;break ;case IPPROTO_TCP :
Greg Kroah-Hartman
maintainerPATCH 662/1005 netfs: preserve prepare_write errno on reissue
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Iván Ezequiel Rodriguez <[email protected]>
commit 62869ecb3aeca670b86058387e7533a33524b95b upstream.
prepare_write() may call netfs_prepare_write_failed() (FAILED + errno) before write_retry calls netfs_reissue_write(). Clearing subreq->error to 0 for a clean I/O reissue (82e8885bd763) then makes netfs_do_issue_write() terminate with 0. The collector copies front->error into stream->error and mapping_set_error(), which ignores 0, so writeback failure is silent.
Skip clearing error when NETFS_SREQ_FAILED is already set; do_issue_write() already terminates FAILED subrequests.
--- fs/netfs/write_issue.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/netfs/write_issue.c +3 -1
@@ -252,7 +252,9 @@ void netfs_reissue_write(struct netfs_ioiov_iter_truncate (&subreq->io_iter, size); subreq->retry_count++; - subreq->error =0 ; +/* Keep prepare_write() errno; do_issue_write() terminates FAILED. */ +if (!test_bit (NETFS_SREQ_FAILED , &subreq->flags)) + subreq->error =0 ;__clear_bit (NETFS_SREQ_MADE_PROGRESS , &subreq->flags);__set_bit (NETFS_SREQ_IN_PROGRESS , &subreq->flags);netfs_stat (&netfs_n_wh_retry_write_subreq);
Greg Kroah-Hartman
maintainerPATCH 663/1005 netfs: keep the prepare_read errno when abandoning read retries
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit d88a0c3a96fd6d7228d04532cecb23f23676aa2d upstream.
When ->prepare_read() fails while retrying a read, netfs_retry_read_subrequests() marks the subrequest failed and abandons the rest, which overwrites the error of every failed subrequest with -ENOMEM. The reader then gets -ENOMEM for e.g. a handle that couldn't be reopened (-EHOSTDOWN, -ENOENT), a credit wait interrupted by a signal (-ERESTARTSYS) or umount -f (-EIO). The first pass doesn't have this problem, as netfs_cancel_read() keeps the errno.
Record the errno of ->prepare_read() in the subrequest and keep the error of subrequests that already failed, using -ENOMEM only for those abandoned while still waiting for a retry.
--- fs/netfs/read_retry.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
fs/netfs/read_retry.c +12 -4
@@ -28,6 +28,7 @@ static void netfs_retry_read_subrequestsstruct netfs_io_subrequest *subreq;struct netfs_io_stream *stream = &rreq->io_streams[0 ];struct list_head *next; +int ret;_enter ("R=%x" , rreq->debug_id);
@@ -140,8 +141,11 @@ static void netfs_retry_read_subrequests/* Renegotiate max_len (rsize) */ stream->sreq_max_len = subreq->len; -if (rreq->netfs_ops->prepare_read && - rreq->netfs_ops->prepare_read (subreq) <0 ) { + ret =0 ; +if (rreq->netfs_ops->prepare_read) + ret = rreq->netfs_ops->prepare_read (subreq); +if (ret <0 ) { + subreq->error = ret;trace_netfs_sreq (subreq, netfs_sreq_trace_reprep_failed);__set_bit (NETFS_SREQ_FAILED , &subreq->flags); goto abandon;
@@ -222,7 +226,9 @@ static void netfs_retry_read_subrequests part =netfs_limit_iter (&source,0 , part, stream->sreq_max_segs);netfs_stat (&netfs_n_rh_download); -if (rreq->netfs_ops->prepare_read (subreq) <0 ) { + ret = rreq->netfs_ops->prepare_read (subreq); +if (ret <0 ) { + subreq->error = ret;trace_netfs_sreq (subreq, netfs_sreq_trace_reprep_failed);__set_bit (NETFS_SREQ_FAILED , &subreq->flags); goto abandon;
@@ -258,7 +264,9 @@ abandon:if (!test_bit (NETFS_SREQ_FAILED , &subreq->flags) && !test_bit (NETFS_SREQ_NEED_RETRY , &subreq->flags))continue ; - subreq->error = -ENOMEM ; +if (!subreq->error || + !test_bit (NETFS_SREQ_FAILED , &subreq->flags)) + subreq->error = -ENOMEM ;__set_bit (NETFS_SREQ_FAILED , &subreq->flags);__clear_bit (NETFS_SREQ_NEED_RETRY , &subreq->flags); }
Greg Kroah-Hartman
maintainerPATCH 664/1005 netfs: dont hang a read whose retry is abandoned
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit d1bb754ab9e775b0fbb2743d3df425c25a561114 upstream.
When ->prepare_read() fails while retrying a read, or a subrequest can't be allocated, netfs_retry_read_subrequests() marks the remaining subrequests failed without reissuing them. If none was reissued in that pass, nothing is in progress any more to wake the collector, which returned after the retry, so an offloaded read (readahead, async direct I/O) never completes and its folios stay locked.
Wake the collector after abandoning, so it collects the failed subrequests and completes the request.
--- fs/netfs/read_retry.c | 1 + 1 file changed, 1 insertion(+)
fs/netfs/read_retry.c +1 -0
@@ -270,6 +270,7 @@ abandon:__set_bit (NETFS_SREQ_FAILED , &subreq->flags);__clear_bit (NETFS_SREQ_NEED_RETRY , &subreq->flags); } +netfs_wake_collector (rreq); }/*
Greg Kroah-Hartman
maintainerPATCH 665/1005 net/sched: sch_teql: reject qdiscs from another network namespace
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 1ae84bdd736f8fab30180159996e1d193f8029ff upstream.
Reported by shaos <[email protected]> with a reproducer, which was reproduced and verified in our test environment.
The issue:
The teql master devices are created once in the initial network namespace and their Qdisc_ops are global. teql_qdisc_init() takes the teql_master embedded in the registered sch->ops and uses it without checking whether the new qdisc's device lives in the same network namespace as the master. A qdisc created in another netns can therefore attach to the init-net master and change its MTU and flags.
The Fix:
Reject a teql qdisc whose device is not in the master's network namespace with -EOPNOTSUPP and an extack message; same-netns teql still works.
Initialize the private skb queue before any validation so every constructor failure path, including qdisc_create_dflt(), which resets the qdisc before destroying it, sees an initialized empty queue.
Conditions to recreate the bug:CONFIG_NET_SCH_TEQL=y, CONFIG_DUMMY=y, CONFIG_USER_NS=y, CONFIG_NET_NS=y. As an unprivileged UID, unshare a user and network namespace, create a dummy device, set its MTU to 60000, and add a root teql0 qdisc:
unshare -Urn
ip link add dummy0 type dummy
ip link set dummy0 mtu 60000
tc qdisc add dev dummy0 root teql0
The init-net teql0 device changes from MTU 1500 to 60000. A pfifo control on the same device leaves the MTU unchanged, and a direct MTU change on init-net teql0 is denied. The namespace needs CAP_NET_ADMIN; no init-net privilege is required. With the fix the attach fails with "Operation not supported" and the init-net MTU stays 1500.
--- net/sched/sch_teql.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
net/sched/sch_teql.c +7 -2
@@ -198,6 +198,8 @@ static int teql_qdisc_init(struct Qdiscstruct Qdisc *first;unsigned long flags; +skb_queue_head_init (&q->q); +if (dev->hard_header_len > m->dev->hard_header_len)return -EINVAL ;
@@ -209,9 +211,12 @@ static int teql_qdisc_init(struct Qdiscreturn -EOPNOTSUPP ; } - q->m = m; +if (dev_net (dev) !=dev_net (m->dev)) { +NL_SET_ERR_MSG_MOD (extack,"teql master is in a different network namespace" ); +return -EOPNOTSUPP ; + } -skb_queue_head_init (&q->q); + q->m = m;raw_spin_lock_irqsave (&m->slaves_lock, flags); first =rcu_dereference_protected (m->slaves,lockdep_is_held (&m->slaves_lock));
Greg Kroah-Hartman
maintainerPATCH 666/1005 net/sched: act_ife: encode configured zero metadata values
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 7d02c07c738bf5c4b9a7d7ef498fbf465c446853 upstream.
Reported by shaos <[email protected]> with a reproducer for the 32-bit case, which was reproduced and verified in our test environment.
The issue:ife_check_meta_u32() and ife_check_meta_u16() both reserve eight bytes of metadata for a configured value even when that value is zero, but the matching encoder returns without calling ife_tlv_meta_encode(). The encoder therefore writes neither the TLV header nor its value, while the enclosing IFE length still includes the reserved bytes, exposing stale skb headroom contents to the peer.
The 32-bit helper has been present since the IFE action was introduced (v4.6); the 16-bit helper was added with the 16-bit metadata helpers used by the skbtcindex callback (v4.9). Both defects predate the oldest supported stable kernel (5.10), so they are fixed together in this patch. Each hunk keeps its own Fixes: tag for provenance.
The fix:
Encode any configured value, including zero; skip the TLV only when there is neither a configured nor a runtime value. The runtime fallback is unchanged.
A raw TCA_IFE_METALST netlink request is needed to express the configured zero: the IFE_META_SKBMARK attribute carries four zero payload bytes for the u32 helper, and IFE_META_TCINDEX two zero payload bytes for the 16-bit helper (not an absent or zero-length attribute). Stock tc cannot build these requests; "use mark 0x0" emits no mark attribute and "allow mark" emits a zero-length one.
Conditions to recreate the bug:CONFIG_NET_ACT_IFE=y, CONFIG_NET_IFE_SKBMARK=y, CONFIG_NET_IFE_SKBTCINDEX=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_INGRESS=y, CONFIG_USER_NS=y, CONFIG_NET_NS=y, CONFIG_VETH=y. In a fresh user and network namespace create a veth pair and attach clsact to the egress side. Install a matchall filter whose ife encode action carries a zero skb mark (or a zero tcindex) in TCA_IFE_METALST. Send a frame through the veth and inspect the IFE metadata in the received frame. The metadata region is eight bytes but holds neither a valid TLV header nor a value; it exposes prior headroom contents. Setting the value to a nonzero one does not trigger the leak. The namespace needs CAP_NET_ADMIN; no additional privilege is required. With the fix the zero TLVs are 0001000800000000 (u32) and 0005000600000000 (u16).
--- net/sched/act_ife.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
net/sched/act_ife.c +2 -4
@@ -50,8 +50,7 @@ int ife_encode_meta_u16(u16 metaval, voi edata = *(u16 *)mi->metaval; else if (metaval) edata = metaval; - -if (!edata)/* will not encode */ + else return 0; edata =htons (edata);
@@ -94,8 +93,7 @@ int ife_encode_meta_u32(u32 metaval, voi edata = *(u32 *)mi->metaval; else if (metaval) edata = metaval; - -if (!edata)/* will not encode */ + else return 0; edata =htonl (edata);
Greg Kroah-Hartman
maintainerPATCH 667/1005 net/sched: act_ife: require a full Ethernet header on egress
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 11dbce09083473249c3843ff31bf8d8fa01bdeef upstream.
This is a followup of commit 5b483f7791b0 ("net/sched: act_ife: Only operate on Ethernet frames") as reported by Sashiko.
The finding was raised by both Sashiko providers (nipa and gemini) while reviewing the parent patchset. shaos <[email protected]> independently reported the same undersized-egress path with a reproducer, which was reproduced and verified in our test environment.
The issue:
On egress tcf_ife_is_eth_skb() only checks the device type; it does not check that the skb carries a full Ethernet header. For an Ethernet or loopback device it returns true even when the skb has no Ethernet header. tcf_ife_encode() then calls ife_encode(), which copies ETH_HLEN bytes from skb->data. A short skb therefore reads past its linear data and the copied bytes, including stale kernel memory, are emitted in the outer Ethernet header.
The parent commit fixed the reported ingress mac_len case but left the egress path without a length check.
A total-length test is not sufficient: a non-GSO TUN skb can have a large total length while only a single byte sits in the linear area, so ife_encode() still reads past the linear header. Require instead that the Ethernet header the encoder copies is present in the linear part of the skb.
The Fix:
On egress require pskb_may_pull(skb, ETH_HLEN) before encoding, which ensures the Ethernet header is present in the linear data ife_encode() copies from; the ingress mac_len check is unchanged. A short egress skb is now dropped instead of being encoded.
Conditions to recreate the bug:CONFIG_NET_ACT_IFE=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_INGRESS=y, CONFIG_TUN=y, CONFIG_NET_ACT_MIRRED=y. In two user and network namespaces (a victim and an attacker), open a TUN device in IFF_TUN mode and attach clsact to it and to lo. Redirect ingress traffic from the TUN device to lo egress with mirred, and install an ife encode action on lo egress:
tc qdisc add dev <tun> clsact
tc qdisc add dev lo clsact
tc filter add dev <tun> ingress matchall action mirred egress \
redirect dev lo
tc filter add dev lo egress matchall action ife encode use mark 1 \
action ok
Send a TUN packet shorter than ETH_HLEN (a one-byte payload is enough) and receive the emitted frame on the other side. Without the fix the outer Ethernet header contains bytes copied past the short packet; with the fix the short skb is dropped. The attacker needs CAP_NET_ADMIN in its user namespace; no init-net privilege is required.
The same path is reachable when the total length is large but the Ethernet header is not linear: write a non-GSO virtio header with hdr_len=1 followed by an 8192-byte packet so that only one byte stays linear. Without the fix the copied header reads past the linear data; with the fix the header is pulled into the linear area before the copy.
--- net/sched/act_ife.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
net/sched/act_ife.c +5 -2
@@ -878,13 +878,16 @@ drop:* is an Ethernet header because the skb could've been redirected with mirred * from a non-Ethernet device. */ -static bool tcf_ife_is_eth_skb (const struct sk_buff *skb) +static bool tcf_ife_is_eth_skb (struct sk_buff *skb) {if (skb->dev->type !=ARPHRD_ETHER && skb->dev->type !=ARPHRD_LOOPBACK )return false; -return !skb_at_tc_ingress (skb) || skb->mac_len ==ETH_HLEN ; +if (skb_at_tc_ingress (skb)) +return skb->mac_len ==ETH_HLEN ; + +return pskb_may_pull (skb,ETH_HLEN ); } TC_INDIRECT_SCOPE int tcf_ife_act(struct sk_buff *skb,
Greg Kroah-Hartman
maintainerPATCH 668/1005 net: wait for in-flight device unregistrations before netns dismantle
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
commit c164a431a646983275d0076ff5b0e4c326fbc10b upstream.
A device can be unregistered by a context other than the cleanup_net() of its own netns, for instance a veth whose peer in another netns is deleted. If references on it are still held, it stays in netdev_wait_allrefs_any(), which rebroadcasts NETDEV_UNREGISTER every second.
Meanwhile its netns can be dismantled: default_device_exit_batch() only takes care of devices still listed in the netns, then pernet exit handlers free their state, and finally struct net is freed while the device still points to it.
The rebroadcasts then run notifiers against torn down pernet state, or freed memory. Three instances were reported so far:
- netdev_genl_netdevice_event(): net->genl_sock is NULL [1]
- nh_netdev_event(): net->nexthop.devhash is NULL [2]
- nf_tables netdevice notifiers: use-after-free of the nftables pernet storage [3]
but any notifier using dev_net(dev) is affected, as is netdev_wait_allrefs_any() itself (__rtnl_net_lock(dev_net(dev)) with CONFIG_DEBUG_NET_SMALL_RTNL=y).
This was prevented by rtnl_lock_unregistering() until I removed it in commit 8a4fc54b07d7 ("net: get rid of rtnl_lock_unregistering()"), considering only the loopback dependency, and missing the notifiers one.
Restore a per-netns counter of devices sitting in netdev_run_todo(), and make default_device_exit_batch() wait for it to reach zero, after it has unregistered all devices of the dying netns(es). At this point no new unregistration can be started for these netns.
Unlike the old barrier, this only waits for devices of the netns being dismantled and runs after their own devices are gone.
Tested on a KASAN kernel with a debug-only hack holding a reference on a veth device for 5 seconds after its unregistration: a nexthop on the veth in netns X, delete its peer from init_net, then delete X. Without this patch, the nexthop_flush_dev() null-ptr-deref from [2] triggers. With it, no splat; netns churn and dismantle of a netns whose own device is held still work.
[1] https://lore.kernel.org/netdev/[email protected]/
[2] https://lore.kernel.org/netdev/[email protected]/
[3] https://lore.kernel.org/netdev/[email protected]/
--- include/net/net_namespace.h | 1 + net/core/dev.c | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+)
include/net/net_namespace.h +1 -0
@@ -69,6 +69,7 @@ struct net {spinlock_t rules_mod_lock;unsigned int dev_base_seq;/* protected by rtnl_mutex */ +atomic_t dev_unreg_pending;/* devices in netdev_run_todo() */ u32 ifindex;spinlock_t nsid_lock;
net/core/dev.c +35 -0
@@ -11007,6 +11007,14 @@ atomic_t dev_unreg_count = ATOMIC_INIT(0static void net_set_todo (struct net_device *dev) {list_add_tail (&dev->todo_list, &net_todo_list); +atomic_inc (&dev_net (dev)->dev_unreg_pending); +} + +/* Paired with net_set_todo(). @net must not be used after this call. */ +static void net_unreg_done (struct net *net) +{ +if (atomic_dec_and_test (&net->dev_unreg_pending)) +wake_up (&netdev_unregistering_wq); } static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
@@ -11890,6 +11898,7 @@ void netdev_run_todo(void)if (unlikely (dev->reg_state !=NETREG_UNREGISTERING )) {netdev_WARN (dev,"run_todo but not unregistering\n" );list_del (&dev->todo_list); +net_unreg_done (dev_net (dev));continue ; }
@@ -11906,8 +11915,11 @@ void netdev_run_todo(void) cnt =0 ;while (!list_empty (&list)) { +struct net *net; + dev =netdev_wait_allrefs_any (&list);list_del (&dev->todo_list); + net =dev_net (dev);/* paranoia */ BUG_ON (netdev_refcnt_read (dev) !=1 );
@@ -11928,6 +11940,8 @@ void netdev_run_todo(void)/* Free network device */ kobject_put (&dev->dev.kobj); + +net_unreg_done (net); }if (cnt &&atomic_sub_and_test (cnt, &dev_unreg_count))wake_up (&netdev_unregistering_wq);
@@ -13372,6 +13386,17 @@ static void __net_exit default_device_ex } } +static bool __net_exit netns_dev_unreg_pending(const struct list_head *net_list) +{ +struct net *net; + +list_for_each_entry (net, net_list, exit_list) { +if (atomic_read (&net->dev_unreg_pending)) +return true; + } +return false; +} + static void __net_exit default_device_exit_batch(struct list_head *net_list) {/* At exit all network devices most be removed from a network
@@ -13413,6 +13438,16 @@ static void __net_exit default_device_exunregister_netdevice_many (&dev_kill_list);rtnl_unlock (); +/* Devices of these netns unregistered from another context +* (e.g. a veth whose peer was deleted) can still be waiting +* in netdev_run_todo() for their last references, while +* NETDEV_UNREGISTER is rebroadcast for them. Wait for them +* before pernet exit handlers tear down the state used by +* netdevice notifiers, and before the netns is freed. +* No new unregistration can start: all devices are unlisted. +*/ +wait_event (netdev_unregistering_wq, !netns_dev_unreg_pending (net_list)); +rtnl_net_flush_workqueue (); }
Greg Kroah-Hartman
maintainerPATCH 669/1005 minix: add minix_inode_block() helper
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 1037134824e9d5c8cc04eea5ec6a5eb3ef4312bb upstream.
Move the lookup of the block that holds an inode out of minix_V1_raw_inode() and minix_V2_raw_inode() into a helper. minix_sync_inode_metadata() is going to use it to find the block without reading it from disk.
No functional changes.
--- fs/minix/bitmap.c | 37 +++++++++++++++++++++++-------------- fs/minix/minix.h | 1 + 2 files changed, 24 insertions(+), 14 deletions(-)
fs/minix/bitmap.c +23 -14
@@ -103,21 +103,35 @@ unsigned long minix_count_free_blocks(st << sbi->s_log_zone_size); } -struct minix_inode * -minix_V1_raw_inode (struct super_block *sb,ino_t ino,struct buffer_head **bh) +/* Return the block that holds inode @ino or 0 if @ino is out of range. */ +int minix_inode_block (struct super_block *sb,ino_t ino) { -int block;struct minix_sb_info *sbi =minix_sb (sb); -struct minix_inode *p; +int inodes_per_block;if (!ino || ino > sbi->s_ninodes) {printk ("Bad inode number on dev %s: %ld is out of range\n" , sb->s_id, (long )ino); -return NULL ; +return 0 ; } +if (sbi->s_version ==MINIX_V1 ) + inodes_per_block =MINIX_INODES_PER_BLOCK ; +else + inodes_per_block = sb->s_blocksize /sizeof (struct minix2_inode ); +return 2 + sbi->s_imap_blocks + sbi->s_zmap_blocks + + (ino -1 ) / inodes_per_block; +} + +struct minix_inode * +minix_V1_raw_inode (struct super_block *sb,ino_t ino,struct buffer_head **bh) +{ +int block; +struct minix_inode *p; + + block =minix_inode_block (sb, ino); +if (!block) +return NULL ; ino--; - block =2 + sbi->s_imap_blocks + sbi->s_zmap_blocks + - ino /MINIX_INODES_PER_BLOCK ; *bh =sb_bread (sb, block);if (!*bh) {printk ("Unable to read inode block\n" );
@@ -131,19 +145,14 @@ struct minix2_inode * minix_V2_raw_inode(struct super_block *sb, ino_t ino, struct buffer_head **bh) { int block; -struct minix_sb_info *sbi =minix_sb (sb);struct minix2_inode *p;int minix2_inodes_per_block = sb->s_blocksize /sizeof (struct minix2_inode ); *bh =NULL ; -if (!ino || ino > sbi->s_ninodes) { -printk ("Bad inode number on dev %s: %ld is out of range\n" , - sb->s_id, (long )ino); + block =minix_inode_block (sb, ino); +if (!block)return NULL ; - } ino--; - block =2 + sbi->s_imap_blocks + sbi->s_zmap_blocks + - ino / minix2_inodes_per_block; *bh =sb_bread (sb, block);if (!*bh) {printk ("Unable to read inode block\n" );
fs/minix/minix.h +1 -0
@@ -47,6 +47,7 @@ void __minix_error_inode(struct inode *i unsigned int line, const char *fmt, ...);struct inode *minix_iget (struct super_block *,unsigned long ); +int minix_inode_block (struct super_block *sb,ino_t ino);struct minix_inode *minix_V1_raw_inode (struct super_block *,ino_t ,struct buffer_head **);struct minix2_inode *minix_V2_raw_inode (struct super_block *,ino_t ,struct buffer_head **);struct inode *minix_new_inode (const struct inode *,umode_t );
Greg Kroah-Hartman
maintainerPATCH 670/1005 minix: dont read the inode block in minix_sync_inode_metadata()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit ccb8bbf93985d89f60d904386e27aad60f34dbbf upstream.
minix_sync_inode_metadata() looks the inode block up with minix_V1_raw_inode() or minix_V2_raw_inode() which read it from disk if it isn't cached. But a block that isn't cached is neither dirty nor under writeback, so there's nothing to write or to wait for.
That read is also something we can't afford once inode eviction calls ->sync_inode_metadata() from reclaim. So look the block up with sb_find_get_block_nonatomic() instead.
--- fs/minix/inode.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
fs/minix/inode.c +8 -8
@@ -702,24 +702,24 @@ static int minix_sync_inode_metadata(struct inode *inode, {int err =0 ;struct buffer_head *bh; -void *raw_inode; +int block; -if (INODE_VERSION (inode) ==MINIX_V1 ) - raw_inode =minix_V1_raw_inode (inode->i_sb, inode->i_ino, &bh); -else - raw_inode =minix_V2_raw_inode (inode->i_sb, inode->i_ino, &bh); -if (!raw_inode) + block =minix_inode_block (inode->i_sb, inode->i_ino); +if (!block)return -EIO ; err =mmb_sync (&minix_i (inode)->i_metadata_bhs);if (err) - goto out; +return err; +/* A block that isn't cached is neither dirty nor under writeback. */ + bh =sb_find_get_block_nonatomic (inode->i_sb, block); +if (!bh) +return 0 ;sync_dirty_buffer (bh);if (buffer_write_io_error (bh)) {printk ("IO error syncing minix inode [%s:%08llx]\n" , inode->i_sb->s_id, inode->i_ino); err = -EIO ; } -out:brelse (bh);return err; }
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 671/1005 NFSv4: Prevent indefinite waits for out-of-order OPEN stateids
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Menninger <[email protected]>
commit 151d95a1e696979a7d54b23c96338754be2fcc1f upstream.
When processing an out-of-order OPEN stateid on an NFSv4.1 or later mount, nfs_set_open_stateid_locked() waits for stateid updates to be processed in order. A five-second timeout is intended to prevent indefinite waits when preceding updates never arrive.
However, each iteration calls schedule_timeout() with a fresh five-second timeout. An update to the shared open state can wake the caller without satisfying its ordering check. The remaining timeout is then discarded, and the next iteration starts another full wait.
Under sustained concurrent OPEN/CLOSE activity on the same open state, repeated wakeups can prevent the timeout from ever expiring. Some tasks can remain stuck in update_open_stateid() while others continue making progress.
Compute a single deadline on entry and pass only the remaining time to schedule_timeout(). Once the deadline expires, take the existing timeout path rather than starting another wait. This prevents wakeups from extending the wait indefinitely.
Observed on Linux 6.8.0 and reproduced on 7.3.0 with 96 concurrent O_RDWR|O_TRUNC open/close loops on one NFSv4.1/TCP file (nconnect=16). Ten workers made no progress for over 300 seconds while others ran. With the fix, all workers resumed after transient stalls.
--- fs/nfs/nfs4proc.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/nfs/nfs4proc.c +4 -1
@@ -1722,6 +1722,8 @@ static void nfs_set_open_stateid_locked( {DEFINE_WAIT (wait);int status =0 ; +unsigned long deadline = jiffies +5 *HZ ; +signed long remaining;for (;;) {if (nfs_stateid_is_sequential (state, stateid))
@@ -1756,7 +1758,8 @@ static void nfs_set_open_stateid_locked(if (!fatal_signal_pending (current) && !nfs_current_task_exiting ()) { -if (schedule_timeout (5 *HZ ) ==0 ) + remaining = (long )(deadline - jiffies); +if (remaining <=0 ||schedule_timeout (remaining) ==0 ) status = -EAGAIN ;else status =0 ;
Greg Kroah-Hartman
maintainerPATCH 672/1005 ntfs: check the file name against the key length of an index entry
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wahid Khan <[email protected]>
commit 5e7143476219eac7cab7bdd341db68dab1649737 upstream.
ntfs_index_entry_inconsistent() checks that the file name of a $FILE_NAME key fits in the index entry. It does not check that the name fits in the key, which is what key_length describes. Code that works on the key alone relies on that.
ntfs_readdir() copies key_length bytes of the key of the next entry to resume the enumeration, and later uses the copy to search the index. If file_name_length is larger than the key holds, the name comparison reads past the copy:
BUG: KASAN: slab-out-of-bounds in ntfs_file_compare_values+0x2d1/0x4b0 Read of size 2 at addr ffff88800a4ef2ce by task init/1 ntfs_file_compare_values ntfs_collate ntfs_ie_lookup ntfs_index_lookup ntfs_readdir iterate_dir Allocated by task 1: kmemdup_noprof ntfs_readdir The buggy address is located 0 bytes to the right of allocated 78-byte region
Two bytes of an image from mkntfs are enough: in an entry whose name has six characters (key_length 78), change file_name_length from 6 to 7, so the key claims 80 bytes. The entry itself is 96 bytes, so the existing check lets it pass. The next readdir of the directory reads the extra bytes.
Check the name against key_length, and check that the key is large enough to hold file_name_length in the first place.
--- fs/ntfs/index.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
fs/ntfs/index.c +5 -3
@@ -41,9 +41,11 @@ static int ntfs_index_entry_inconsistent }else {if (collation_rule ==COLLATION_FILE_NAME ) { - if ((offsetof(struct index_entry, key.file_name.file_name) + - ie->key.file_name.file_name_length * sizeof(__le16)) > - le16_to_cpu(ie->length)) { +if (le16_to_cpu (ie->key_length) < + offsetof(struct file_name_attr , file_name) || + (offsetof(struct file_name_attr , file_name) + + ie->key.file_name.file_name_length *sizeof (__le16)) > +le16_to_cpu (ie->key_length)) {ntfs_error (vol->sb,"File name overflow from index entry in inode %lld\n" , (long long )inum);
Greg Kroah-Hartman
maintainerPATCH 673/1005 ntfs: do not read an index block outside $INDEX_ALLOCATION
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wahid Khan <[email protected]>
commit 0ea30dd6eeabc09235d5c2cdb98ca4e0d593963f upstream.
A directory whose $INDEX_ROOT has a child node but whose $INDEX_ALLOCATION is missing or damaged gets an empty index inode from ntfs_read_locked_index_inode(): size 0 and not non-resident. ntfs_lookup_inode_by_name() still follows the child node and reads a folio from that inode while it holds the mft record lock of the directory.
Since the resident iomap read started to take base_ni->mrec_lock, that read waits for a lock the caller already holds:
INFO: task init:1 is blocked on a mutex likely owned by task init:1. __mutex_lock __ntfs_read_iomap_begin ntfs_read_iomap_next iomap_read_folio ntfs_read_folio ntfs_lookup_inode_by_name ntfs_lookup
The task never returns, and neither does anything else that needs the directory's mft record.
It takes one corrupted byte on an image from mkntfs: change the first byte of the type of the $INDEX_ALLOCATION attribute header of a directory with index blocks from 0xa0 to 0x00. The first lookup in that directory hangs.
Check that the index inode is non-resident and that the vcn lies inside it before every index block read, and fail with -EIO otherwise. This also rejects a negative vcn, which was only checked on later descents.
--- fs/ntfs/dir.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
fs/ntfs/dir.c +14 -0
@@ -308,6 +308,20 @@ found_it: ia_mapping = ia_vi->i_mapping; descend_into_child_node:/* +* The child node has to be inside $INDEX_ALLOCATION. A directory that +* lacks the attribute gets an empty index inode that is not +* non-resident, and reading a folio from it locks the mft record that +* is already locked here. +*/ +if (!NInoNonResident (NTFS_I (ia_vi)) || vcn <0 || + (u64 )vcn >= (u64 )i_size_read (ia_vi) >> dir_ni->itype.index.vcn_size_bits) { +ntfs_error (sb, +"Child node vcn %lld is outside $INDEX_ALLOCATION in directory inode 0x%llx." , + vcn, dir_ni->mft_no); + err = -EIO ; + goto err_out; + } +/* * Convert vcn to index into the index allocation attribute in units * of PAGE_SIZE and map the page cache page, reading it from * disk if necessary.
Greg Kroah-Hartman
maintainerPATCH 674/1005 ntfs: open the index allocation before reading or writing an index block
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wahid Khan <[email protected]>
commit bada7bbb11aaa6feba8904cf38ff833453f5b5d9 upstream.
ntfs_ib_write() and ntfs_ib_read() use icx->ia_ni without checking it. ntfs_ir_reparent() only opens the index allocation through ntfs_ia_add() when the root is a small index. For a root that is already marked as a large index it calls ntfs_ib_write() directly.
The lookup does not open the index allocation either when it ends in the root. If the last entry of the root has no child node, ia_ni is still NULL when the root has to be moved into an index block, and the write dereferences it:
Oops: general protection fault, KASAN: null-ptr-deref in range
[0x0000000000000128-0x000000000000012f]
RIP: 0010:ntfs_inode_attr_pwrite+0x52/0x1600
ntfs_ir_make_space
ntfs_ie_add
ntfs_index_add_filename
__ntfs_link
ntfs_link
vfs_linkA single byte of an image from mkntfs is enough. In a directory that has one empty index block, clear INDEX_ENTRY_NODE (flags 3 -> 2) of the last entry of the $INDEX_ROOT and link() a file into the directory.
Commit 9365c4a1357e ("ntfs: fix NULL dereference on index allocation open failure") covers the case where ntfs_ia_open() fails in the lookup. Here it was never tried. Open the index allocation on demand in both
helpers and fail with -EIO if that does not work.
ntfs_ia_open() also succeeds for a directory that has no $INDEX_ALLOCATION attribute. The inode it returns is then an empty resident stub that does not describe an index allocation, so reject that case too.
--- fs/ntfs/index.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+)
fs/ntfs/index.c +22 -0
@@ -99,12 +99,30 @@ static s64 ntfs_ib_pos_to_vcn(struct ntfreturn pos >> icx->vcn_size_bits; } +/* Open the index allocation inode if no earlier step of the operation did. */ +static int ntfs_icx_ia_ensure (struct ntfs_index_context *icx) +{ +if (!icx->ia_ni) { + icx->ia_ni =ntfs_ia_open (icx, icx->idx_ni); +if (!icx->ia_ni) +return -EIO ; + } +/* Without $INDEX_ALLOCATION the index inode is an empty resident stub. */ +if (!NInoNonResident (icx->ia_ni)) +return -EIO ; +return 0 ; +} +static int ntfs_ib_write (struct ntfs_index_context *icx,struct index_block *ib) {s64 ret, vcn =le64_to_cpu (ib->index_block_vcn);ntfs_debug ("vcn: %lld\n" , vcn); + ret =ntfs_icx_ia_ensure (icx); +if (ret) +return ret; + ret =pre_write_mst_fixup ((struct ntfs_record *)ib, icx->block_size);if (ret)return -EIO ;
@@ -770,6 +788,10 @@ static int ntfs_ib_read(struct ntfs_indentfs_debug ("vcn: %lld\n" , vcn); + ret =ntfs_icx_ia_ensure (icx); +if (ret) +return ret; + pos =ntfs_ib_vcn_to_pos (icx, vcn); ret =ntfs_inode_attr_pread (VFS_I (icx->ia_ni), pos, icx->block_size, (u8 *)dst);
Greg Kroah-Hartman
maintainerPATCH 675/1005 openvswitch: advance by the real header length in get_ipv6_ext_hdrs()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joas Antonio dos Santos <[email protected]>
commit dbce972650ed6348e3d3856e49308aa5603e02a7 upstream.
get_ipv6_ext_hdrs() walks the IPv6 extension header chain to fill key->ipv6.exthdrs, but advances to the next header with ipv6_optlen() whatever the current header is. That is only right for Hop-by-Hop, Destination Options and Routing headers:
- an Authentication Header is ((hdrlen + 2) << 2) bytes long (ipv6_authlen()), so with hdrlen = 4 the walk skips 40 bytes instead of 24 and reads the next "header" from the ICV and payload;
- a Fragment header is always 8 bytes, and the byte read as hdrlen is its Reserved field, which the sender controls and receivers ignore, so a non-zero value makes the walk skip up to 2048 bytes and miss the headers that follow;
- in a non-first fragment nothing after the Fragment header is a header at all, it is the middle of the fragmentable part, yet the walk keeps parsing it as an extension header chain.
In all cases the OFPIEH12_* bits stored in key->ipv6.exthdrs depend on bytes chosen by the sender rather than on the headers that are actually
present: payload bytes that look like another AH or a Hop-by-Hop header add OFPIEH12_UNREP/OFPIEH12_UNSEQ, and real headers after a Fragment header can go unreported. Flows that match on OVS_KEY_ATTR_IPV6_EXTHDRS then classify such packets wrongly. There is no memory safety issue, skb_header_pointer() bounds every read.
Advance by sizeof(struct frag_hdr) for Fragment headers and by ipv6_authlen() for AH, and stop at the Fragment header if its offset is non-zero, as ipv6_find_hdr() does.
--- net/openvswitch/flow.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-)
net/openvswitch/flow.c +18 -1
@@ -370,11 +370,28 @@ static void get_ipv6_ext_hdrs(struct sk_return ; } +if (next_type ==IPPROTO_FRAGMENT ) { +struct frag_hdr _fh, *fh; + + fh =skb_header_pointer (skb, start,sizeof (_fh), &_fh); +if (!fh) +break ; +/* Only the first fragment has the headers that follow. */ +if (fh->frag_off &htons (IP6_OFFSET )) +break ; + start +=sizeof (_fh); + next_type = fh->nexthdr; +continue ; + } + hp =skb_header_pointer (skb, start,sizeof (_hdr), &_hdr);if (!hp)break ; +if (next_type ==IPPROTO_AH ) + start +=ipv6_authlen (hp); +else + start +=ipv6_optlen (hp); next_type = hp->nexthdr; - start +=ipv6_optlen (hp); } }
Greg Kroah-Hartman
maintainerPATCH 676/1005 perf/core: Do not resurrect cpuctx->cgrp after last cgroup event exit
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Phat Dinh <[email protected]>
commit 59f1398140869432c7171b9a2a279ca315467c4e upstream.
perf_cgroup_switch() relies on:
/*
* cpuctx->cgrp is set when the first cgroup event enabled,
* and is cleared when the last cgroup event disabled. */
It computes the next task's cgroup, schedules out the CPU context and then assigns cpuctx->cgrp unconditionally:
ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
/*
* must not be done before ctxswout due
* to update_cgrp_time_from_cpuctx() in
* ctx_sched_out()
*/
cpuctx->cgrp = cgrp;However, ctx_sched_out() can disable events itself. If a cgroup event has a pending disable from perf_event_disable_inatomic() (e.g. its PERF_EVENT_IOC_REFRESH limit ran out) that the irq_work has not handled yet, event_sched_out() consumes it inline:
if (event->pending_disable) {
event->pending_disable = 0;
perf_cgroup_event_disable(event, ctx);
state = PERF_EVENT_STATE_OFF;
}If that was the last cgroup event, perf_cgroup_event_disable() clears cpuctx->cgrp:
if (--ctx->nr_cgroups)
return;
cpuctx->cgrp = NULL;and perf_cgroup_switch() then sets it again. cpuctx->cgrp is left non-NULL with ctx.nr_cgroups == 0, so the NULL check in perf_cgroup_switch() no longer catches it and the next switch trips:
WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
cpuctx->cgrp does not hold a reference on the cgroup. Once that cgroup is removed, the next ctx_sched_in() dereferences the stale pointer:
BUG: KASAN: slab-use-after-free in ctx_sched_in+0xb1f/0xfa0 Read of size 8 at addr ffff8881008972d0 by task swapper/3/0 Tainted: [W]=WARN Call Trace: <IRQ> ctx_sched_in+0xb1f/0xfa0 perf_event_sched_in+0x1a/0x70 ctx_resched+0x32b/0xac0 __perf_install_in_context+0x475/0xab0 remote_function+0x105/0x200 __flush_smp_call_function_queue+0x179/0x8d0 __sysvec_call_function_single+0x1b/0x1c0 sysvec_call_function_single+0x66/0x80 </IRQ> <TASK> asm_sysvec_call_function_single+0x1a/0x20
Only assign cpuctx->cgrp when cgroup events remain after the context has been scheduled out, so that it stays NULL as the invariant requires.
--- kernel/events/core.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/events/core.c +6 -1
@@ -1072,8 +1072,13 @@ static void perf_cgroup_switch(struct ta* must not be done before ctxswout due * to update_cgrp_time_from_cpuctx() in * ctx_sched_out() +* +* ctx_sched_out() can consume a pending disable and drop the last cgroup +* event, which clear the cpuctx->cgrp. Cgroup tracking follow active cgroup +* event, so do not resurrect it */ - cpuctx->cgrp = cgrp; +if (cpuctx->ctx.nr_cgroups) + cpuctx->cgrp = cgrp;/* * set cgrp before ctxsw in to allow * perf_cgroup_set_timestamp() in ctx_sched_in()
Greg Kroah-Hartman
maintainerPATCH 677/1005 perf/hw_breakpoint: Clear stop state in hw_breakpoint_add()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paolo Bertinetti <[email protected]>
commit 6bea5e29daf123a78ae58cb5926023f4705f396f upstream.
Since commit 18dbcbfabfff ("perf: Fix the POLL_HUP delivery breakage"), __perf_event_overflow() stops the event with pmu->stop() and disables it when the PERF_EVENT_IOC_REFRESH limit is reached. When userspace re-arms the event with PERF_EVENT_IOC_REFRESH, the event is enabled again and pmu->add() is called with PERF_EF_START.
hw_breakpoint_add() sets PERF_HES_STOPPED when PERF_EF_START is missing, but never clears it. The flag set by pmu->stop() stays, and perf_bp_event() drops every later hit, so a breakpoint re-armed this way delivers only its first overflow.
Set the state from PERF_EF_START on every add, as perf_swevent_add() does.
--- kernel/events/hw_breakpoint.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/events/hw_breakpoint.c +1 -2
@@ -968,8 +968,7 @@ static int hw_breakpoint_event_init(strustatic int hw_breakpoint_add (struct perf_event *bp,int flags) { -if (!(flags &PERF_EF_START )) - bp->hw.state =PERF_HES_STOPPED ; + bp->hw.state = (flags &PERF_EF_START ) ?0 :PERF_HES_STOPPED ;if (is_sampling_event (bp)) { bp->hw.last_period = bp->hw.sample_period;
Greg Kroah-Hartman
maintainerPATCH 678/1005 PM: runtime: Update last_busy in rpm_resume() for active devices
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rafael J. Wysocki <[email protected]>
commit 55b2b8af704f845e01fa2f31ee259b07641ce3a9 upstream.
Setting an autosuspend delay for a device can be expected to cause a runtime suspend of the device after calling, say, pm_runtime_put() to be deferred, so the time between the last successful attempt to resume the device and its subsequent suspend is at least equal to the autosuspend delay.
However, that expectation is only met after the device has been actually resumed in rpm_resume() by invoking its runtime resume callback. If the runtime PM status of the device is already "active" when rpm_resume() runs for it, the device's last_busy timestamp is not updated which may allow a subsequent pm_runtime_put() invocation (or similar) to suspend it right away.
This is arguably inconsistent and confusing, so make rpm_resume() also update the device's last_busy timestamp when it finds that the device is already "active" and it is about to return 1 early.
--- drivers/base/power/runtime.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/base/power/runtime.c +6 -0
@@ -822,6 +822,12 @@ static int rpm_resume(struct device *devpm_runtime_deactivate_timer (dev);if (dev->power.runtime_status ==RPM_ACTIVE ) { +/* +* The attempt to resume the device means that it is needed for +* something, so update its last_busy timestamp as in the case +* in which it actually resumes below. +*/ +pm_runtime_mark_last_busy (dev); retval =1 ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 679/1005 Revert "powercap: intel_rapl: Expose all package CPUs in PMU cpumask"
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dennis Chen <[email protected]>
commit a74c332aaf46270101b32a32311275d86953a2b5 upstream.
Commit 525e0064f3d8 ("powercap: intel_rapl: Expose all package CPUs in PMU cpumask") expanded cpumask to include all CPUs in the package. Since perf opens an event for every CPU in cpumask, the value returned for power/energy-pkg/ is roughly scaled by the number of CPUs.
On a single-socket 72-core DMR machine the reported value is roughly 72x higher than when perf is restricted to reading from a single CPU:
$ perf stat -e power/energy-pkg/ -- sleep 1 Performance counter stats for 'system wide':
8,052.48 Joules power/energy-pkg/
1.010483558 seconds time elapsed$ perf stat -C 5 -e power/energy-pkg/ -- sleep 1
Performance counter stats for 'CPU(s) 5':
112.15 Joules power/energy-pkg/
1.009685587 seconds time elapsedReverting this commit restores the expected behavior for perf.
--- drivers/powercap/intel_rapl_common.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/powercap/intel_rapl_common.c +10 -5
@@ -1139,21 +1139,23 @@ static struct rapl_pmu rapl_pmu;/* PMU helpers */ -static void set_pmu_cpumask (struct rapl_package *rp,cpumask_var_t mask) +static int get_pmu_cpu (struct rapl_package *rp) {int cpu;if (!rp->has_pmu) -return ; +return nr_cpu_ids;/* Only TPMI & MSR RAPL are supported for now */ if (rp->priv->type !=RAPL_IF_TPMI && rp->priv->type !=RAPL_IF_MSR ) -return ; +return nr_cpu_ids;/* TPMI/MSR RAPL uses any CPU in the package for PMU */ for_each_online_cpu (cpu)if (topology_physical_package_id (cpu) == rp->id) -cpumask_set_cpu (cpu, mask); +return cpu; + +return nr_cpu_ids; }static bool is_rp_pmu_cpu (struct rapl_package *rp,int cpu)
@@ -1435,6 +1437,7 @@ static ssize_t cpumask_show(struct device *dev, {struct rapl_package *rp;cpumask_var_t cpu_mask; +int cpu;int ret;if (!alloc_cpumask_var (&cpu_mask,GFP_KERNEL ))
@@ -1446,7 +1449,9 @@ static ssize_t cpumask_show(struct device *dev,/* Choose a cpu for each RAPL Package */ list_for_each_entry (rp, &rapl_packages, plist) { -set_pmu_cpumask (rp, cpu_mask); + cpu =get_pmu_cpu (rp); +if (cpu < nr_cpu_ids) +cpumask_set_cpu (cpu, cpu_mask); }cpus_read_unlock ();
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 680/1005 power: sequencing: pcie-m2: fix use-after-free in pwrseq_pcie_m2_vregs_enable()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit cd5f26ed96604b18e4235052525abe6b4ba505d6 upstream.
During device teardown or on the probe error path, a concurrent consumer access triggers a use-after-free in pwrseq_pcie_m2_vregs_enable() or pwrseq_pcie_m2_vregs_disable() due to a lifetime inversion between devm-managed device registration and manual resource cleanup.
The driver exposes the power sequencer using devm_pwrseq_device_register(), meaning the device remains fully registered and accessible on the pwrseq_bus until the driver core schedules devm_pwrseq_device_unregister() to run after pwrseq_pcie_m2_remove() returns. However, the driver performs manual resource teardown within pwrseq_pcie_m2_remove() and the pwrseq_pcie_m2_probe() error path, prematurely destroying the backing regulator array.
This creates a narrow vulnerability window where the globally visible power sequencer is backed by freed memory. If a concurrent consumer invokes pwrseq_enable() during this window, execution is routed to the sequencer callback and dereferences the destroyed ctx->regs array, resulting in a direct use-after-free and a kernel crash.
Schedule a devres action for freeing the memory used for the regulator array to ensure it runs *after* the pwrseq provider was unregistered.
--- drivers/power/sequencing/pwrseq-pcie-m2.c | 36 +++++++++++++++--------------- 1 file changed, 18 insertions(+), 18 deletions(-)
drivers/power/sequencing/pwrseq-pcie-m2.c +18 -18
@@ -492,6 +492,14 @@ err_remove_serdev:return ret; } +static void pwrseq_pcie_m2_free_regulators (void *data) +{ +struct pwrseq_pcie_m2_ctx *ctx = data; + +regulator_bulk_free (ctx->num_vregs, ctx->regs); +kfree (ctx->regs); +} +static int pwrseq_pcie_m2_probe (struct platform_device *pdev) {struct device *dev = &pdev->dev;
@@ -522,19 +530,19 @@ static int pwrseq_pcie_m2_probe(struct p ctx->num_vregs = ret; + ret =devm_add_action_or_reset (dev, pwrseq_pcie_m2_free_regulators, ctx); +if (ret) +return ret; + ctx->w_disable1_gpio =devm_gpiod_get_optional (dev,"w-disable1" ,GPIOD_OUT_HIGH ); -if (IS_ERR (ctx->w_disable1_gpio)) { - ret =dev_err_probe (dev,PTR_ERR (ctx->w_disable1_gpio), +if (IS_ERR (ctx->w_disable1_gpio)) +return dev_err_probe (dev,PTR_ERR (ctx->w_disable1_gpio),"Failed to get the W_DISABLE_1# GPIO\n" ); - goto err_free_regulators; - } ctx->w_disable2_gpio =devm_gpiod_get_optional (dev,"w-disable2" ,GPIOD_OUT_HIGH ); -if (IS_ERR (ctx->w_disable2_gpio)) { - ret =dev_err_probe (dev,PTR_ERR (ctx->w_disable2_gpio), +if (IS_ERR (ctx->w_disable2_gpio)) +return dev_err_probe (dev,PTR_ERR (ctx->w_disable2_gpio),"Failed to get the W_DISABLE_2# GPIO\n" ); - goto err_free_regulators; - } config.parent = dev; config.owner =THIS_MODULE ;
@@ -543,11 +551,9 @@ static int pwrseq_pcie_m2_probe(struct p config.targets = ctx->pdata->targets; ctx->pwrseq =devm_pwrseq_device_register (dev, &config); -if (IS_ERR (ctx->pwrseq)) { - ret =dev_err_probe (dev,PTR_ERR (ctx->pwrseq), +if (IS_ERR (ctx->pwrseq)) +return dev_err_probe (dev,PTR_ERR (ctx->pwrseq),"Failed to register the power sequencer\n" ); - goto err_free_regulators; - }mutex_init (&ctx->list_lock);INIT_LIST_HEAD (&ctx->pci_devices);
@@ -572,9 +578,6 @@ err_remove_serdev:pwrseq_pcie_m2_remove_serdev (ctx,NULL ); err_destroy_mutex:mutex_destroy (&ctx->list_lock); -err_free_regulators: -regulator_bulk_free (ctx->num_vregs, ctx->regs); -kfree (ctx->regs);return ret; }
@@ -586,9 +589,6 @@ static void pwrseq_pcie_m2_remove(structbus_unregister_notifier (&pci_bus_type, &ctx->nb);pwrseq_pcie_m2_remove_serdev (ctx,NULL );mutex_destroy (&ctx->list_lock); - -regulator_bulk_free (ctx->num_vregs, ctx->regs); -kfree (ctx->regs); }static const struct of_device_id pwrseq_pcie_m2_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 681/1005 power: sequencing: pcie-m2: fix serdev controller reference leak
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit b149b12f6a52997eded725ae5deae24620dbbbff upstream.
In pwrseq_pcie_m2_create_serdev_one(), if serdev_ctrl->serdev is NULL but pdev is already tracked in ctx->pci_devices, we return early from the loop and skip the serdev_controller_put(), leaking the reference.
Initialize ret to 0 and jump directly to the label that ensures the reference is released.
--- drivers/power/sequencing/pwrseq-pcie-m2.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-)
drivers/power/sequencing/pwrseq-pcie-m2.c +4 -6
@@ -270,7 +270,7 @@ static int pwrseq_pcie_m2_create_serdev_struct serdev_controller *serdev_ctrl;struct device *dev = ctx->dev;struct pwrseq_pci_dev *pci_dev; -int ret; +int ret =0 ; struct device_node *serdev_parent __free(device_node) =of_graph_get_remote_node (dev_of_node (ctx->dev),3 ,0 );
@@ -282,16 +282,14 @@ static int pwrseq_pcie_m2_create_serdev_return 0 ;/* Bail out if the device was already attached to this controller */ -if (serdev_ctrl->serdev) { -serdev_controller_put (serdev_ctrl); -return 0 ; - } +if (serdev_ctrl->serdev) + goto err_put_ctrl;/* Bail out if the serdev device was already created for the PCI dev */ scoped_guard(mutex, &ctx->list_lock) {list_for_each_entry (pci_dev, &ctx->pci_devices, list) {if (pci_dev->pdev == pdev) -return 0 ; + goto err_put_ctrl; } }
Greg Kroah-Hartman
maintainerPATCH 682/1005 ASoC: qcom: q6asm: Reset PCM positions when preparing a stream
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michael McAllister <[email protected]>
commit 54e89fab723d5a374972d3f5c3e0b89ae055bd18 upstream.
Preparing an existing PCM stream closes the DSP stream and remaps its buffers, but leaves queue_ptr, dsp_buf and hw_ptr at their previous positions. ALSA resets appl_ptr during prepare, so q6asm_dai_ack() can subtract a stale queue_ptr from the new appl_ptr and queue an incorrect number of periods.
On the Motorola Moto G10, playback works after opening the PCM device, but the first write after snd_pcm_drop() and snd_pcm_prepare() fails with -EBUSY and "Error queuing playback buffer -16".
Reset queue_ptr in prepare, and reset the DSP buffer index and hardware pointer when allocating the new buffer ring. This keeps the queued, submitted and completed positions aligned with the new PCM stream.
--- sound/soc/qcom/qdsp6/q6asm-dai.c | 3 +++ sound/soc/qcom/qdsp6/q6asm.c | 2 ++ 2 files changed, 5 insertions(+)
sound/soc/qcom/qdsp6/q6asm-dai.c +3 -0
@@ -243,6 +243,9 @@ static int q6asm_dai_prepare(struct snd_soc_component *component, prtd->state =Q6ASM_STREAM_STOPPED ; } +/* ALSA resets appl_ptr for every prepare, including xrun recovery. */ + prtd->queue_ptr =0 ; + ret = q6asm_map_memory_regions(substream->stream, prtd->audio_client, prtd->phys, (prtd->pcm_size / prtd->periods),
sound/soc/qcom/qdsp6/q6asm.c +2 -0
@@ -514,6 +514,8 @@ int q6asm_map_memory_regions(unsigned int dir, struct audio_client *ac, ac->port[dir].buf = buf; + ac->port[dir].dsp_buf =0 ; +atomic_set (&ac->port[dir].hw_ptr,0 ); buf[0 ].phys = phys; buf[0 ].size = period_sz;
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 683/1005 ASoC: SOF: ipc4-topology: Fix pin format leak in process widget setup
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baoli Zhang <[email protected]>
commit e5c09fe3f9c8d9da33b177ee432db15b6ab46884 upstream.
sof_ipc4_widget_setup_comp_process() allocates the input and output pin format arrays via sof_ipc4_get_audio_fmt(). When the following sof_ipc4_widget_setup_msg() fails, e.g. because the firmware does not provide a module matching the widget UUID, the error path jumps to the 'err' label, which frees the process struct and clears swidget->private but skips sof_ipc4_free_audio_fmt(). The arrays are then unreachable and are reported by kmemleak:
sof_ipc4_get_audio_fmt+0xc9/0x420 [snd_sof]
sof_ipc4_widget_setup_comp_process+0x8e/0x200 [snd_sof]
snd_sof_load_topology+0x71a/0x840 [snd_sof]
sof_pcm_probe+0x77/0x120 [snd_sof]
snd_soc_component_probe+0x21/0x60 [snd_soc_core]
...Jump to 'free_available_fmt' instead, as the other process widget error paths after sof_ipc4_get_audio_fmt() already do.
The other IPC4 widget setup functions (pga, mixer, src, asrc) free the audio formats in their common error label and are not affected.
--- sound/soc/sof/ipc4-topology.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/sof/ipc4-topology.c +1 -1
@@ -1310,7 +1310,7 @@ static int sof_ipc4_widget_setup_comp_pr ret =sof_ipc4_widget_setup_msg (swidget, &process->msg);if (ret) - goto err; + goto free_available_fmt;/* parse process init module payload config type from module info */ fw_module = swidget->module_info;
Greg Kroah-Hartman
maintainerPATCH 684/1005 Bluetooth: btusb: fix use-after-free in force_poll_sync
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: YuanZhe Liu <[email protected]>
commit 868c886f45f7c10dc888b94c6993352702a84d04 upstream.
The force_poll_sync debugfs file uses the driver's struct btusb_data as its private data. The file is created under hdev->debugfs and is removed only when the HCI device is released, while btusb_disconnect() frees btusb_data unconditionally. The HCI device can outlive the driver data, for example when an HCI socket still references it, so reading or writing the already opened file then dereferences freed memory:
BUG: KASAN: slab-use-after-free in force_poll_sync_read+0x129/0x140 Read of size 1 at addr ffff88800cfb7038 ... Freed by task ...: kfree btusb_disconnect
Remove the debugfs file before the private data is freed. debugfs_remove() waits for callers that are already inside the file operations, and any later access fails with -EIO instead of reaching the driver, so the force_poll_sync file can no longer dereference btusb_data after it is gone.
--- drivers/bluetooth/btusb_main.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/bluetooth/btusb_main.c +8 -2
@@ -1063,6 +1063,8 @@ struct btusb_data {int (*disconnect)(struct hci_dev *hdev);int oob_wake_irq;/* irq for out-of-band wake-on-bt */ + +struct dentry *force_poll_sync_dentry; };static void btusb_reset (struct hci_dev *hdev)
@@ -4557,8 +4559,9 @@ static int btusb_probe(struct usb_interfusb_set_intfdata (intf, data); -debugfs_create_file ("force_poll_sync" ,0644 , hdev->debugfs, data, - &force_poll_sync_fops); + data->force_poll_sync_dentry = +debugfs_create_file ("force_poll_sync" ,0644 , hdev->debugfs, + data, &force_poll_sync_fops);return 0 ;
@@ -4599,6 +4602,9 @@ static void btusb_disconnect(struct usb_if (!data)return ; +debugfs_remove (data->force_poll_sync_dentry); + data->force_poll_sync_dentry =NULL ; + hdev = data->hdev;usb_set_intfdata (data->intf,NULL );
Greg Kroah-Hartman
maintainerPATCH 685/1005 Bluetooth: hci_qca: fix use-after-free in ibs debugfs files
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: YuanZhe Liu <[email protected]>
commit eeca795cec6d9c6c193c2c1bd0cb26cde44f9fc3 upstream.
qca_debugfs_init() creates an "ibs" directory under hdev->debugfs and stores pointers to fields of struct qca_data in the debugfs files. qca_close() frees qca_data without removing that directory, while hdev->debugfs is only removed when the HCI device is released. The HCI device can outlive the driver data, for example when an HCI socket still references it, so reading or writing one of the ibs files then dereferences freed memory.
Store the directory dentry in struct qca_data and remove the directory with debugfs_remove_recursive() before qca_data is freed. debugfs_remove() waits for callers that are already inside the file operations, and any later access fails with -EIO instead of reaching the debugfs helpers. This covers the two writable files as well.
--- drivers/bluetooth/hci_qca.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/bluetooth/hci_qca.c +5 -0
@@ -161,6 +161,7 @@ struct qca_data {struct delayed_work ctrl_memdump_timeout;struct qca_memdump_info *qca_memdump;unsigned long flags; +struct dentry *debugfs_ibs_dir;struct completion drop_ev_comp;wait_queue_head_t suspend_wait_q;enum qca_memdump_states memdump_state;
@@ -665,6 +666,7 @@ static void qca_debugfs_init(struct hci_return ; ibs_dir =debugfs_create_dir ("ibs" , hdev->debugfs); + qca->debugfs_ibs_dir = ibs_dir;/* read only */ mode =0444 ;
@@ -744,6 +746,9 @@ static int qca_close(struct hci_uart *hu hu->priv =NULL ; +debugfs_remove_recursive (qca->debugfs_ibs_dir); + qca->debugfs_ibs_dir =NULL ; +kfree (qca);return 0 ;
Greg Kroah-Hartman
maintainerPATCH 686/1005 Bluetooth: L2CAP: Keep recvmsg from resuming a closed channel
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 1f2ac56137c51be0601e18a163d817e02a15913f upstream.
Reading buffered ERTM data after ACL link loss can clear local busy and send a supervisory frame after l2cap_conn_del() has destroyed the HCI channel, which oopses on a NULL pointer in hci_send_acl(). The socket still owns its L2CAP channel, so its lifetime does not protect the underlying HCI channel.
Require BT_CONNECTED before clearing local busy in recvmsg. The socket lock already held here serializes this check and send with teardown, which closes the socket before the HCI channel is destroyed. Continue to allow buffered data to be read after disconnection.
AI assistance was used.
--- net/bluetooth/l2cap_sock.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/bluetooth/l2cap_sock.c +2 -1
@@ -1332,7 +1332,8 @@ static int l2cap_sock_recvmsg(struct soc* available. This avoids resending large numbers of * frames. */ -if (test_bit (CONN_LOCAL_BUSY , &pi->chan->conn_state) && +if (sk->sk_state ==BT_CONNECTED && +test_bit (CONN_LOCAL_BUSY , &pi->chan->conn_state) &&atomic_read (&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >>1 )l2cap_chan_busy (pi->chan,0 );
Greg Kroah-Hartman
maintainerPATCH 687/1005 cgroup/cpuset: Correctly set isolated_cpus when switching partition state
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Waiman Long <[email protected]>
commit 56681bc448a80bb2473026b41c44c133766bc38d upstream.
When update_prstate() is called to switch the partition state from root to isolated or vice versa, the whole effective_xcpus is passed to isolated_cpus_update(). However, if there are child partitions present, some of the effective_xcpus are dedicated to those child partitions and their partition states will remain the same or get invalidated in the case of child root partition with isolated parent in the latter update_cpumasks_hier() call. In the latter case, their exclusive CPUs will be returned to their parent.
Therefore isolated_cpus may be set incorrectly with child partitions underneath. Fix that by excluding their exclusive CPUs in computing the correct cpumask of exclusive CPUs used by that partition alone.
Add new test cases into test_cpuset_prs.sh to test for such cases.
--- kernel/cgroup/cpuset.c | 30 ++++++++++++++++++---- tools/testing/selftests/cgroup/test_cpuset_prs.sh | 7 +++++ 2 files changed, 32 insertions(+), 5 deletions(-)
kernel/cgroup/cpuset.c +25 -5
@@ -3151,12 +3151,32 @@ static int update_prstate(struct cpuset cs->effective_xcpus, NULL)) err =PERR_HKEEPING ; else if (parent_prs == PRS_ISOLATED) - err =PERR_ISOPARENT ; + err =PERR_ISOPARENT ;/* old_prs should be isolated */ -if (!err) - isolcpus_updated = true; -else +if (err) { disable_partition = true; + }else { +struct cgroup_subsys_state *css; +struct cpuset *child; + +/* +* Need to scan child partitions, if present, and +* exclude their effective_xcpus from cs. In the case +* of switching to isolated partition with child root +* partitions, those child partitions will be +* invalidated in update_cpumasks_hier(). +*/ + isolcpus_updated = true; +cpumask_copy (tmpmask.new_cpus, cs->effective_xcpus); +rcu_read_lock (); +cpuset_for_each_child (child, css, cs) { +if (!is_partition_valid (child)) +continue ; +cpumask_andnot (tmpmask.new_cpus, tmpmask.new_cpus, + child->effective_xcpus); + } +rcu_read_unlock (); + } }else {/* * Switching back to member is always allowed even if it
@@ -3193,7 +3213,7 @@ out:if (!is_partition_valid (cs))reset_partition_data (cs);else if (isolcpus_updated) -isolated_cpus_update (old_prs, new_prs, cs->effective_xcpus); +isolated_cpus_update (old_prs, new_prs, tmpmask.new_cpus);spin_unlock_irq (&callback_lock);/* Force update if partition is disabled & update effective_xcpus */
tools/testing/selftests/cgroup/test_cpuset_prs.sh +7 -0
@@ -468,6 +468,13 @@ TEST_MATRIX=( " C1-4:P1 C3-4:P2 . . T:C4-6 . . . 0 A1:5-6|A2:4 A1:P1|A2:P2 4" " C1-4:P1 C1-2:P2 . . T:C4-6 . . . 0 A1:4-6|A2:4-6 A1:P1|A2:P-2 ." + # Switch PRS state (root <=> isolated) will properly update cpuset.cpus.isolated + # even if child partitions are present. + " C1-6:P1 C3-6:P1 C5-6:P2 . . P2 . . 0 A1:1-2|A2:3-4|A3:5-6 \ + A1:P1|A2:P2|A3:P2 3-6" + " C1-6:P1 C3-6:P2 C5-6:P2 . . P1 . . 0 A1:1-2|A2:3-4|A3:5-6 \ + A1:P1|A2:P1|A3:P2 5-6" + # # old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS # ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
Greg Kroah-Hartman
maintainerPATCH 688/1005 cgroup/cpuset: Dont revive invalid partition without active CPU on hotplug
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ridong Chen <[email protected]>
commit acec9637e03ca54bd3c3a0c1a6ad5c6dfa07c0df upstream.
When a CPU hotplug leaves no CPU outside of the partitions for the top cpuset, cpuset_handle_hotplug() clears subpartitions_cpus and gives all the active CPUs back to the top cpuset. cpuset_hotplug_update_tasks() then walks the hierarchy and invalidates the partitions, as subpartitions_cpus is empty.
However, an invalid partition visited in the same walk may be revived if its effective_xcpus is not empty. tasks_nocpu_error() doesn't catch it when its CPUs are all offline but it has no task. Its CPUs are put back into subpartitions_cpus, and the valid partitions visited after it are no longer invalidated, as subpartitions_cpus is not empty any more. The top cpuset is left with CPUs overlapping with these partitions.
It can be reproduced on a system with 8 CPUs:
# cd /sys/fs/cgroup # echo +cpuset > cgroup.subtree_control # mkdir A1 B1 # echo 1 > A1/cpuset.cpus # echo 1 > A1/cpuset.cpus.exclusive # echo 0,2-7 > B1/cpuset.cpus # echo root > B1/cpuset.cpus.partition # echo root > A1/cpuset.cpus.partition # cat A1/cpuset.cpus.partition root invalid (Parent unable to distribute cpu downstream) # echo 0 > /sys/devices/system/cpu/cpu1/online # cat A1/cpuset.cpus.partition B1/cpuset.cpus.partition root root # cat cpuset.cpus.effective 0,2-7
A1 can't take CPU 1, the last CPU of the root cgroup which has tasks. When CPU 1 is offlined, A1 is revived without any active CPU, and B1 stays valid while its CPUs are also in the effective CPUs of the root cgroup, which triggers
WARNING: kernel/cgroup/cpuset.c:919 at rebuild_sched_domains_locked
Only revive an invalid partition in hotplug if its effective_xcpus has an active CPU, the same as what is required to create a partition with tasks. With that, A1 and B1 are both invalidated in the above case.
--- kernel/cgroup/cpuset.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +2 -2
@@ -4179,10 +4179,10 @@ static void cpuset_hotplug_update_tasks( partcmd = partcmd_invalidate;/* * On the other hand, an invalid partition root may be transitioned -* back to a regular one with a non-empty effective xcpus. +* back to a regular one if its effective xcpus has an active CPU. */ else if (is_partition_valid(parent) && is_partition_invalid(cs) && - !cpumask_empty(cs->effective_xcpus)) + cpumask_intersects(cs->effective_xcpus, cpu_active_mask)) partcmd = partcmd_update;if (partcmd >=0 ) {
Greg Kroah-Hartman
maintainerPATCH 689/1005 cgroup/freezer: walk exiting tasks in the v1 freezer
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mani Tofigh <[email protected]>
commit 8ab6980c70076db5f8c0c66a5fac06472b254333 upstream.
An exiting task can stay frozen after its v1 freezer cgroup is thawed. Since commit a72f73c4dd9b ("cgroup: Don't expose dead tasks in cgroup") the css task walk hides an exiting task once its process has no live threads left. That count drops when another thread of the process exits, which can happen between the freeze and the thaw walk. A pid namespace init hits this easily since it waits freezably in zap_pid_ns_processes() after commit 81933038f5e2 ("pid_namespace: make zap_pid_ns_processes() freezable"):
Task A (pid ns init) Task B (A's thread) Task C
do_exit()
exit_signals()
do_exit()
zap_pid_ns_processes()
write FROZEN
/* A frozen */
/* live count 0 */
write THAWED
/* A skipped */A then stays frozen even after SIGKILL:
[ 10.775155] task:fz-init state:D stack:28152 pid:65 tgid:65 ppid:1 task_flags:0xc0004c flags:0x00080000 [ 10.775176] Call Trace: [ 10.775180] <TASK> [ 10.775188] __schedule+0x10f1/0x4760 [ 10.775252] schedule+0xd7/0x2c0 [ 10.775265] zap_pid_ns_processes+0x2c7/0x5f0 [ 10.775346] do_exit+0x1bf4/0x2560 [ 10.775403] __x64_sys_exit+0x3d/0x50 [ 10.775414] x64_sys_call+0x156c/0x1570 [ 10.775425] do_syscall_64+0xfb/0x590 [ 10.775450] entry_SYSCALL_64_after_hwframe+0x77/0x7f [ 10.775529] </TASK>
Use CSS_TASK_ITER_WITH_DEAD in the three v1 freezer walks so they all see the same tasks, as commit 60f21a264930 ("cgroup, sched_ext: Include exiting tasks in cgroup iter") did for sched_ext. With the fix, A is thawed and exits.
This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it within about 10s.
--- kernel/cgroup/legacy_freezer.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
kernel/cgroup/legacy_freezer.c +3 -3
@@ -265,7 +265,7 @@ static void update_if_frozen(struct cgrorcu_read_unlock ();/* are all tasks frozen? */ -css_task_iter_start (css,0 , &it); +css_task_iter_start (css,CSS_TASK_ITER_WITH_DEAD , &it);while ((task =css_task_iter_next (&it))) {if (freezing (task) && !frozen (task))
@@ -309,7 +309,7 @@ static void freeze_cgroup(struct freezerstruct css_task_iter it;struct task_struct *task; -css_task_iter_start (&freezer->css,0 , &it); +css_task_iter_start (&freezer->css,CSS_TASK_ITER_WITH_DEAD , &it);while ((task =css_task_iter_next (&it)))freeze_task (task);css_task_iter_end (&it);
@@ -320,7 +320,7 @@ static void unfreeze_cgroup(struct freezstruct css_task_iter it;struct task_struct *task; -css_task_iter_start (&freezer->css,0 , &it); +css_task_iter_start (&freezer->css,CSS_TASK_ITER_WITH_DEAD , &it);while ((task =css_task_iter_next (&it)))__thaw_task (task);css_task_iter_end (&it);
Greg Kroah-Hartman
maintainerPATCH 690/1005 cgroup/freezer: Fix exiting tasks left frozen forever after rmdir
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tejun Heo <[email protected]>
commit e1aed52b68a361f6fc047b24a37d9ec4d928a158 upstream.
Since 93618edf7538 ("cgroup: Defer css percpu_ref kill on rmdir until cgroup is depopulated"), rmdir succeeds once cgroup.procs is empty, but exiting tasks hidden from it can stay in the cgroup until their final context switch. If such a task is frozen in a v1 freezer cgroup, nothing is left to thaw it after rmdir: freezer.state is gone with the cgroup, and a THAWED write to an ancestor clears only CGROUP_FREEZING_PARENT.
8ab6980c7007 ("cgroup/freezer: walk exiting tasks in the v1 freezer") made the freezer walks include exiting tasks. A FROZEN write now also freezes a hidden task in a freezable sleep on its exit path. The fix depends on that commit, as the thaw reaches hidden tasks through the same walk.
Since 81933038f5e2 ("pid_namespace: make zap_pid_ns_processes() freezable"), an exiting pid namespace init sleeps that way until a parent outside the namespace reaps a zombie in it.
Thaw the cgroup from ->css_killed(), as a THAWED write to it would. A descendant removed earlier can still hold hidden tasks frozen through CGROUP_FREEZING_PARENT. The thaw reaches it too, as its css stays online until its tasks are gone.
rmdir removes freezer.state only after ->css_killed() returns, and a write to it takes no cgroup_mutex. A FROZEN write after the thaw would freeze the removed cgroup again, so refuse to freeze a dead cgroup.
Verified with a reproducer, including under a frozen parent, from an already removed child and with a racing FROZEN write.
--- kernel/cgroup/legacy_freezer.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+)
kernel/cgroup/legacy_freezer.c +34 -0
@@ -382,6 +382,24 @@ static void freezer_change_state(struct freezer *freezer, bool freeze)* CGROUP_FREEZING_PARENT. */ mutex_lock (&freezer_mutex); + +/* +* A dead cgroup must not be frozen. +* +* rmdir thaws the cgroup from freezer_css_killed(), but freezer.state +* stays writable until rmdir removes it a moment later. A FROZEN write +* in that gap would freeze the cgroup again, and nothing could thaw it +* after that. +* +* A freezer.state write doesn't take cgroup_mutex, but testing +* cgroup_is_dead() without it is safe. rmdir marks the cgroup dead +* before the thaw, so a write that takes freezer_mutex after the thaw +* sees it dead. One that takes it before the thaw may still see the +* cgroup alive, but the thaw then undoes its freeze. +*/ +if (freeze &&data_race (cgroup_is_dead (freezer->css.cgroup))) + goto out_unlock; +rcu_read_lock ();css_for_each_descendant_pre (pos, &freezer->css) {struct freezer *pos_f =css_freezer (pos);
@@ -403,10 +421,25 @@ static void freezer_change_state(struct freezer *freezer, bool freeze)css_put (pos); }rcu_read_unlock (); +out_unlock:mutex_unlock (&freezer_mutex);cpus_read_unlock (); } +/** +* freezer_css_killed - Thaw a freezer cgroup being removed +* @css: css being killed +* +* Exiting tasks hidden from cgroup.procs can still be in the cgroup when it is +* removed, and a frozen one has nothing left to thaw it once freezer.state is +* gone. Thaw the cgroup as a THAWED write to it would. A frozen ancestor keeps +* the tasks frozen through CGROUP_FREEZING_PARENT until the ancestor is thawed. +*/ +static void freezer_css_killed (struct cgroup_subsys_state *css) +{ +freezer_change_state (css_freezer (css), false); +} +static ssize_t freezer_write (struct kernfs_open_file *of,char *buf,size_t nbytes,loff_t off) {
@@ -466,6 +499,7 @@ static struct cftype files[] = {struct cgroup_subsys freezer_cgrp_subsys = { .css_alloc = freezer_css_alloc, .css_online = freezer_css_online, + .css_killed = freezer_css_killed, .css_offline = freezer_css_offline, .css_free = freezer_css_free, .attach = freezer_attach,
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 691/1005 cgroup: arm the notify timer only while the file exists
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mani Tofigh <[email protected]>
commit fffbdad76a57eed26cff1be19f4cbb407f0b6e7c upstream.
cgroup_rm_file() clears cfile->kn under cfile->lock and then deletes the notify timer. Since commit 4616120fca7f ("cgroup: add lockless fast-path checks to cgroup_file_notify()"), cgroup_file_notify() checks kn and arms the timer without that lock and can arm it right after it was deleted:
Task A (memcg charge) Task B (subtree_control write)
cgroup_file_notify()
READ_ONCE(cfile->kn) != NULL
cgroup_rm_file()
cfile->kn = NULL
timer_delete_sync()
timer_reduce(&cfile->notify_timer)
/* timer queued again */If the css is only hidden, showing it again runs timer_setup() on the still queued timer and corrupts the timer wheel:
[ 14.324093] ODEBUG: init active (active state 0) object: 0000000009e526fd object type: timer_list hint: cgroup_file_notify_timer+0x0/0x10 [ 14.324123] WARNING: lib/debugobjects.c:629 at debug_print_object+0x1a4/0x3b0, CPU#1: cgnotify/64 [ 14.329806] CPU: 1 UID: 0 PID: 64 Comm: cgnotify Tainted: G W 7.3.0-17087-gd865f2677c44 #1 PREEMPT [ 14.335109] RIP: 0010:debug_print_object+0x1ae/0x3b0 [ 14.354351] Call Trace: [ 14.354927] <TASK> [ 14.356650] __debug_object_init+0x203/0x3c0 [ 14.361799] timer_init_key+0x2c/0x240 [ 14.362682] cgroup_addrm_files+0x754/0xc40 [ 14.366744] css_populate_dir+0x12e/0x440 [ 14.368636] cgroup_apply_control_enable+0x2f3/0xb60 [ 14.371769] cgroup_subtree_control_write+0x740/0xc10 [ 14.376924] cgroup_file_write+0x19e/0x700 [ 14.381809] kernfs_fop_write_iter+0x337/0x510 [ 14.382818] vfs_write+0x545/0x1250 [ 14.386491] ksys_write+0xfa/0x200 [ 14.390144] do_syscall_64+0xfb/0x590 [ 14.390994] entry_SYSCALL_64_after_hwframe+0x77/0x7f
If the css is freed instead, the timer can fire on freed memory.
Arm the timer under cfile->lock after checking kn again and keep only the kn and timer_pending() checks outside the lock. With the fix, the timer stays idle once the file is removed.
This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it within a minute.
--- kernel/cgroup/cgroup.c | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-)
kernel/cgroup/cgroup.c +12 -10
@@ -4810,19 +4810,21 @@ void cgroup_file_notify(struct cgroup_fiif (!READ_ONCE (cfile->kn))return ; - last =READ_ONCE (cfile->notified_at); - next = last +CGROUP_FILE_NOTIFY_MIN_INTV ; -if (time_in_range (jiffies, last, next)) { -timer_reduce (&cfile->notify_timer, next); -if (timer_pending (&cfile->notify_timer)) -return ; - } +if (timer_pending (&cfile->notify_timer)) +return ;spin_lock_irqsave (&cfile->lock, flags);if (cfile->kn) { - kn = cfile->kn; -kernfs_get (kn); -WRITE_ONCE (cfile->notified_at, jiffies); + last = cfile->notified_at; + next = last +CGROUP_FILE_NOTIFY_MIN_INTV ; + +if (time_in_range (jiffies, last, next)) { +timer_reduce (&cfile->notify_timer, next); + }else { + kn = cfile->kn; +kernfs_get (kn); + cfile->notified_at = jiffies; + } }spin_unlock_irqrestore (&cfile->lock, flags);
Greg Kroah-Hartman
maintainerPATCH 692/1005 crypto: caam - reject overlong RSA CRT parameters
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 828c3b265b6df877dced3dde56ea41daa2e6181e upstream.
caam_read_rsa_crt() right-aligns dP, dQ, and qInv in buffers sized from the corresponding prime. rsa_parse_priv_key() only bounds these integers against n, so a malformed key can provide, for example, a two-byte dP with a one-byte p. dstlen - nbytes then underflows and memcpy() writes outside the allocation during set_priv_key(). KASAN reports a slab-out-of-bounds write in caam_read_rsa_crt().
Reject empty or overlong CRT parameters after stripping leading zeros. qInv is consumed by CAAM as a p-sized value, so size it from p rather than q to match the DMA mapping in set_rsa_priv_f3_pdb(). Let the top-level key cleanup handle partial form-3 allocations and return the specific error to the caller.
Also test nbytes before dereferencing it while stripping zeros, so an all-zero integer does not read one byte beyond its input.
--- drivers/crypto/caam/caampkc.c | 79 +++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 47 deletions(-)
drivers/crypto/caam/caampkc.c +32 -47
@@ -880,7 +880,7 @@ static void caam_rsa_free_key(struct caastatic void caam_rsa_drop_leading_zeros (const u8 **ptr,size_t *nbytes) { -while (!**ptr && *nbytes) { +while (*nbytes && !**ptr) { (*ptr)++; (*nbytes)--; }
@@ -896,22 +896,22 @@ static void caam_rsa_drop_leading_zeros(* @ptr : pointer to {dP, dQ, qInv} CRT member * @nbytes: length in bytes of {dP, dQ, qInv} CRT member * @dstlen: length in bytes of corresponding p or q prime factor +* @dst : pointer to the zero-padded output buffer */ -static u8 *caam_read_rsa_crt (const u8 *ptr,size_t nbytes,size_t dstlen) +static int caam_read_rsa_crt (const u8 *ptr,size_t nbytes,size_t dstlen, +u8 **dst) { -u8 *dst; -caam_rsa_drop_leading_zeros (&ptr, &nbytes); -if (!nbytes) -return NULL ; +if (!nbytes || nbytes > dstlen) +return -EINVAL ; - dst =kzalloc (dstlen,GFP_KERNEL ); -if (!dst) -return NULL ; + *dst =kzalloc (dstlen,GFP_KERNEL ); +if (!*dst) +return -ENOMEM ; -memcpy (dst + (dstlen - nbytes), ptr, nbytes); +memcpy (*dst + (dstlen - nbytes), ptr, nbytes); -return dst; +return 0 ; }/**
@@ -991,6 +991,7 @@ static int caam_rsa_set_priv_key_form(stsize_t p_sz = raw_key->p_sz;size_t q_sz = raw_key->q_sz;unsigned aligned_size; +int ret; rsa_key->p =caam_read_raw_data (raw_key->p, &p_sz);if (!rsa_key->p)
@@ -999,57 +1000,39 @@ static int caam_rsa_set_priv_key_form(st rsa_key->q =caam_read_raw_data (raw_key->q, &q_sz);if (!rsa_key->q) - goto free_p; +return -ENOMEM ; rsa_key->q_sz = q_sz; aligned_size =ALIGN (raw_key->p_sz,dma_get_cache_alignment ()); rsa_key->tmp1 =kzalloc (aligned_size,GFP_KERNEL );if (!rsa_key->tmp1) - goto free_q; +return -ENOMEM ; aligned_size =ALIGN (raw_key->q_sz,dma_get_cache_alignment ()); rsa_key->tmp2 =kzalloc (aligned_size,GFP_KERNEL );if (!rsa_key->tmp2) - goto free_tmp1; +return -ENOMEM ; rsa_key->priv_form =FORM2 ; - rsa_key->dp =caam_read_rsa_crt (raw_key->dp, raw_key->dp_sz, p_sz); -if (!rsa_key->dp) - goto free_tmp2; - - rsa_key->dq =caam_read_rsa_crt (raw_key->dq, raw_key->dq_sz, q_sz); -if (!rsa_key->dq) - goto free_dp; - - rsa_key->qinv =caam_read_rsa_crt (raw_key->qinv, raw_key->qinv_sz, - q_sz); -if (!rsa_key->qinv) - goto free_dq; + ret =caam_read_rsa_crt (raw_key->dp, raw_key->dp_sz, p_sz, + &rsa_key->dp); +if (ret) +return ret; + + ret =caam_read_rsa_crt (raw_key->dq, raw_key->dq_sz, q_sz, + &rsa_key->dq); +if (ret) +return ret; + + ret =caam_read_rsa_crt (raw_key->qinv, raw_key->qinv_sz, p_sz, + &rsa_key->qinv); +if (ret) +return ret; rsa_key->priv_form =FORM3 ;return 0 ; - -free_dq: -kfree_sensitive (rsa_key->dq); - rsa_key->dq =NULL ; -free_dp: -kfree_sensitive (rsa_key->dp); - rsa_key->dp =NULL ; -free_tmp2: -kfree_sensitive (rsa_key->tmp2); - rsa_key->tmp2 =NULL ; -free_tmp1: -kfree_sensitive (rsa_key->tmp1); - rsa_key->tmp1 =NULL ; -free_q: -kfree_sensitive (rsa_key->q); - rsa_key->q =NULL ; -free_p: -kfree_sensitive (rsa_key->p); - rsa_key->p =NULL ; -return -ENOMEM ; } static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key,
@@ -1067,6 +1050,8 @@ static int caam_rsa_set_priv_key(structif (ret)return ret; + ret = -ENOMEM ; +/* Copy key in DMA zone */ rsa_key->d =kmemdup (raw_key.d, raw_key.d_sz,GFP_KERNEL );if (!rsa_key->d)
@@ -1103,7 +1088,7 @@ static int caam_rsa_set_priv_key(struct err:caam_rsa_free_key (rsa_key); -return -ENOMEM ; +return ret; }static unsigned int caam_rsa_max_size (struct crypto_akcipher *tfm)
Greg Kroah-Hartman
maintainerPATCH 693/1005 crypto: essiv - fix use-after-free in AEAD path
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit e9ce64dce975a14700e835003847415e29918474 upstream.
The request that ESSIV submits to its wrapped AEAD transform may finish before crypto_aead_encrypt() or crypto_aead_decrypt() returns. In case this happens, essiv_aead_done() calls aead_request_complete() on the original ESSIV request, which can end up freeing the request before essiv_aead_crypt() resumes, creating a UAF:
BUG: KASAN: slab-use-after-free in essiv_aead_crypt+0x8e6/0x950 Read of size 8 at addr ffff888102af1360 by task init/66
Check the return status before dereferencing rctx after submitting that request. If the operation did not return -EINPROGRESS or -EBUSY, then the request cannot have been freed yet.
--- crypto/essiv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
crypto/essiv.c +1 -1
@@ -250,7 +250,7 @@ static int essiv_aead_crypt(struct aead_ err = enc ?crypto_aead_encrypt (subreq) :crypto_aead_decrypt (subreq); -if (rctx->assoc && err != -EINPROGRESS && err != -EBUSY ) +if (err != -EINPROGRESS && err != -EBUSY )kfree (rctx->assoc);return err; }
Greg Kroah-Hartman
maintainerPATCH 694/1005 dcache: let d_invalidate() wait for a d_set_mounted() in flight
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 20a6a9ec19e522ae85f87337886b3fb47efce5f3 upstream.
d_invalidate() and d_set_mounted() are supposed to exclude each other. Either the mount fails with -ENOENT because an ancestor of the mountpoint was unhashed or d_invalidate() finds the mountpoint and detaches the mount. d_invalidate() unhashes the dentry first and then searches the subtree with d_walk() which starts out lockless and only looks at the seqcount of rename_lock.
Since d_set_mounted() switched to read_seqlock_excl() nothing makes that walk wait or retry:
CPU0: mount on A/M CPU1: d_invalidate(A)
d_set_mounted(M)
read_seqlock_excl(&rename_lock)
A is hashed, go on
__d_drop(A)
shrink_dcache_parent(A)
d_walk(A, find_submount)
read_seqbegin(&rename_lock)
M is not a mountpoint
need_seqretry() == false
return
M->d_flags |= DCACHE_MOUNTED
return 0mount gets attached to M
The mount ends up below an unhashed dentry. It can't be reached anymore and pins the subtree until its parent mount or the mount namespace goes away. The window grows with the depth of the mountpoint. With a FUSE directory 3000 levels deep a bind mount racing with FUSE_NOTIFY_INVAL_ENTRY for the parent of the mountpoint survived in 151 of 200 attempts.
Before 5e317d23f6c6 the seqcount bump made the walk wait while d_set_mounted() ran and retry under the lock when one had run in the meantime. That was the right thing to wait for on the wrong counter:
every rename_lock reader paid for it, d_lookup(), d_path(), the ".." step of the RCU walk.
So give d_set_mounted() a seqlock of its own. It is the only writer and d_invalidate() is the only reader. After unhashing the dentry d_invalidate() runs an empty read_seqbegin()/read_seqretry() section on it. That spins while the count is odd, i.e. while a d_set_mounted() is between its ancestor check and its flag, and goes round once more if one started in the meantime. Nobody else retries anything. The ordering comes from the locks both already take:
- If that d_set_mounted() saw the dentry hashed its check ran under the dentry's d_lock before __d_drop() took it. So the count is odd by the time d_invalidate() reads it and d_invalidate() waits.
- Once the count is even again the flag has been set under the mountpoint's d_lock and the walk takes that lock to look at it.
A d_set_mounted() that starts after the unhash fails its ancestor check and never touches the flag. So the only flag the walk can pick up belongs to the one mount that saw the dentry hashed and is still in flight, and there is at most one of those because namespace_sem serializes mounts. Either it gets attached and detach_mounts() takes it off after waiting for namespace_sem or it fails later on and drops the flag again. In that case the walk goes round once more and finds nothing. The same goes for the mountpoint that attach_recursive_mnt() preallocates on the root of the tree it attaches. IOW, d_invalidate() does at most one extra round, which the removed-name trap (cf. [1]) relies on.
Note that on PREEMPT_RT read_seqbegin() takes the lock instead of spinning on a preempted d_set_mounted().
The cost is a seqlock around the ancestor walk for every new mountpoint and two loads of a cacheline that only d_set_mounted() writes for every d_invalidate() of a positive dentry. Walking the ancestors a second time after setting the flag would close the race as well but doubles the cost of d_set_mounted() with the depth of the mountpoint: about 1us at 64 levels and 75us at 4096 levels.
[1]: https://patch.msgid.link/[email protected]
--- fs/dcache.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-)
fs/dcache.c +15 -4
@@ -1589,21 +1589,25 @@ int path_has_submounts(const struct path }EXPORT_SYMBOL (path_has_submounts); +/* odd while d_set_mounted() runs, d_invalidate() waits on it */ +static __cacheline_aligned_in_smp DEFINE_SEQLOCK (d_set_mounted_lock ); +/* * Called by mount code to set a mountpoint and check if the mountpoint is * reachable (e.g. NFS can unhash a directory dentry and then the complete * subtree can become unreachable). * * Only one of d_invalidate() and d_set_mounted() must succeed. For -* this reason take rename_lock and d_lock on dentry and ancestors. -* Likewise for dont_mount() which marks a dentry that is being removed -* under d_lock. +* this reason take rename_lock, d_set_mounted_lock and d_lock on dentry +* and ancestors. Likewise for dont_mount() which marks a dentry that +* is being removed under d_lock. */ int d_set_mounted (struct dentry *dentry) {struct dentry *p;int ret = -ENOENT ;read_seqlock_excl (&rename_lock); +write_seqlock (&d_set_mounted_lock);for (p = dentry->d_parent; !IS_ROOT (p); p = p->d_parent) {/* Need exclusion wrt. d_invalidate() */ spin_lock (&p->d_lock);
@@ -1621,8 +1625,9 @@ int d_set_mounted(struct dentry *dentry) ret =0 ; } } -spin_unlock (&dentry->d_lock); +spin_unlock (&dentry->d_lock); out: +write_sequnlock (&d_set_mounted_lock);read_sequnlock_excl (&rename_lock);return ret; }
@@ -1875,6 +1880,7 @@ static enum d_walk_ret find_submount(voivoid d_invalidate (struct dentry *dentry) {bool had_submounts = false; +unsigned seq;spin_lock (&dentry->d_lock);if (d_unhashed (dentry)) {spin_unlock (&dentry->d_lock);
@@ -1887,6 +1893,11 @@ void d_invalidate(struct dentry *dentry)if (!dentry->d_inode)return ; +/* wait for a d_set_mounted() that saw us hashed to set its flag */ +do { + seq =read_seqbegin (&d_set_mounted_lock); + }while (read_seqretry (&d_set_mounted_lock, seq)); +shrink_dcache_parent (dentry);for (;;) {struct dentry *victim =NULL ;
Greg Kroah-Hartman
maintainerPATCH 695/1005 dcache: wait for a racing eviction of a secondary root
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 649918e04e0ead9bfc861aacdd2e5b39b5bdf869 upstream.
Commit e9895609cb7f ("wind ->s_roots via ->d_sib instead of ->d_hash") keeps a secondary root on ->s_roots until dentry_unlist() so that shrink_dcache_for_umount() can find one that another thread is evicting and wait for it. But do_one_tree() takes every root off the list before its dput() which breaks that:
thread A umount
dentry_kill(root), refcount is 0
lock_for_kill()
spin_trylock(->i_lock) fails
spin_unlock(->d_lock)
shrink_dcache_for_umount()
dget_dlock(root)
do_one_tree(root)
unlink_secondary_root(root)
spin_lock(->i_lock)
dput(root), refcount is 0
lock_for_kill()
trylock fails, waits
spin_lock(->d_lock)
refcount is 0 again, go on
lockref_mark_dead()
dentry_unlink_inode()
drops both locks
root is dead, give up
->s_roots is empty, done
evict_inodes()
"Busy inodes after unmount"
iput()Thread A evicts without pinning the superblock. namespace_unlock() does that for old mountpoints after dropping namespace_sem, and a secondary root goes with its last child.
So only take busy roots off the list. Leave the others to dentry_unlist() so that shrink_dcache_for_umount() finds them and waits for an eviction in progress. A root that becomes busy after the check is picked up again and taken off the list then.
--- fs/dcache.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
fs/dcache.c +7 -2
@@ -1816,8 +1816,13 @@ static void do_one_tree(struct dentry *dd_walk (dentry, dentry, umount_check);spin_lock (&dentry->d_lock);__d_drop (dentry); -/* A busy root survives the dput() below so don't leave it on ->s_roots. */ -if (unlikely (!hlist_unhashed (&dentry->d_sib))) +/* +* A busy root survives the dput() below so don't leave it on ->s_roots. +* An idle one stays until dentry_unlist() so that umount can wait for +* a racing eviction, see lock_for_kill(). +*/ +if (unlikely (dentry->d_lockref.count >1 && + !hlist_unhashed (&dentry->d_sib)))unlink_secondary_root (dentry);spin_unlock (&dentry->d_lock);dput (dentry);
Greg Kroah-Hartman
maintainerPATCH 696/1005 dcache: let umount find a disconnected ex-mountpoint
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 32e564e222b7ca3811b2acee404b73fcaf43f312 upstream.
When a mount goes away the reference to its mountpoint is dropped with dput_to_list() and namespace_unlock() evicts the dentry after dropping namespace_sem. Nothing pins the filesystem at that point so it can be unmounted at the same time. That's fine as long as shrink_dcache_for_umount() finds the dentry. It then either evicts it itself or waits for the eviction to finish.
But it can't find a disconnected root as those are neither in the tree nor on ->s_roots. And they can be mounted on:
fd = open_by_handle_at(mnt_fd, handle of a file with no dentry, O_PATH); tree = open_tree(AT_FDCWD, "/tmp/x", OPEN_TREE_CLONE); move_mount(tree, "", fd, "", MOVE_MOUNT_F_EMPTY_PATH |
MOVE_MOUNT_T_EMPTY_PATH);
close(fd);
thread A thread B
umount2("/proc/self/fd/<tree>", MNT_DETACH)
namespace_unlock()
up_write(&namespace_sem)
umount of the filesystem
shrink_dcache_for_umount() evict_inodes() "Busy inodes after unmount"
shrink_dentry_list()
dentry_kill()
iput() of an inode of a superblock that is gone
So put such a dentry on ->s_roots when it's put on the shrink list. From then on it's a secondary root like any other.
This needs the previous patch. Otherwise do_one_tree() takes the dentry off ->s_roots and umount doesn't wait for an eviction in progress.
The stable tag is narrower than the Fixes tag on purpose. Before commit e9895609cb7f ("wind ->s_roots via ->d_sib instead of ->d_hash") umount doesn't wait for a secondary root that is being evicted either.
--- fs/dcache.c | 16 ++++++++++++++-- include/linux/fs/super_types.h | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-)
fs/dcache.c +14 -2
@@ -45,7 +45,8 @@* dcache_hash_bucket lock protects: * - the dcache hash table * s_roots_lock protects: -* - the s_roots list (see __d_move()/dentry_unlist()/d_obtain_root()) +* - the s_roots list (see __d_move()/dentry_unlist()/d_obtain_root()/ +* dput_to_list()) * dentry->d_sb->s_dentry_lru_lock protects: * - the dcache lru lists and counters * d_lock protects:
@@ -1101,7 +1102,18 @@ void dput_to_list(struct dentry *dentry, {if (likely (fast_dput (dentry)))return ; -__move_to_shrink_list (dentry, list); +/* +* The list owner need not pin the superblock, so make a disconnected +* root a secondary one for shrink_dcache_for_umount() to find. +*/ +if (__move_to_shrink_list (dentry, list) && +unlikely (IS_ROOT (dentry) &&hlist_unhashed (&dentry->d_sib))) { +struct super_block *sb = dentry->d_sb; + +spin_lock (&sb->s_roots_lock); +hlist_add_head (&dentry->d_sib, &sb->s_roots); +spin_unlock (&sb->s_roots_lock); + }spin_unlock (&dentry->d_lock); }
include/linux/fs/super_types.h +1 -1
@@ -173,7 +173,7 @@ struct super_block {struct unicode_map *s_encoding;__u16 s_encoding_flags;#endif -struct hlist_head s_roots;/* alternate root dentries for NFS */ +struct hlist_head s_roots;/* alternate root dentries for NFS and ex-mountpoints */ spinlock_t s_roots_lock;struct mount *s_mounts;/* list of mounts; _not_ for fs use */ struct block_device *s_bdev;/* can go away once we use an accessor for @s_bdev_file */
Greg Kroah-Hartman
maintainerPATCH 697/1005 ext2: add ext2_inode_block() helper
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit 57a84ef0520b0d17e930ff15cbd13af687e6d233 upstream.
Move the lookup of the inode table block that holds an inode out of ext2_get_inode() into a helper. ext2_sync_inode_metadata() is going to use it to find the block without reading it from disk.
No functional changes.
--- fs/ext2/inode.c | 49 +++++++++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 18 deletions(-)
fs/ext2/inode.c +31 -18
@@ -1264,46 +1264,59 @@ static int ext2_setsize(struct inode *inreturn 0 ; } -static struct ext2_inode *ext2_get_inode (struct super_block *sb,ino_t ino, -struct buffer_head **p) +/* +* Find the inode table block that holds inode @ino and the offset of the +* inode in that block. +*/ +static int ext2_inode_block (struct super_block *sb,ino_t ino, +unsigned long *block,unsigned long *offset) { -struct buffer_head * bh;unsigned long block_group; -unsigned long block; -unsigned long offset;struct ext2_group_desc * gdp; - *p =NULL ;if ((ino !=EXT2_ROOT_INO && ino <EXT2_FIRST_INO (sb)) || - ino >le32_to_cpu (EXT2_SB (sb)->s_es->s_inodes_count)) - goto Einval; + ino >le32_to_cpu (EXT2_SB (sb)->s_es->s_inodes_count)) { +ext2_error (sb, __func__,"bad inode number: %lu" , + (unsigned long ) ino); +return -EINVAL ; + } block_group = (ino -1 ) /EXT2_INODES_PER_GROUP (sb); gdp =ext2_get_group_desc (sb, block_group,NULL );if (!gdp) - goto Egdp; +return -EIO ;/* * Figure out the offset within the block group inode table */ - offset = ((ino -1 ) %EXT2_INODES_PER_GROUP (sb)) *EXT2_INODE_SIZE (sb); - block =le32_to_cpu (gdp->bg_inode_table) + - (offset >>EXT2_BLOCK_SIZE_BITS (sb)); + *offset = ((ino -1 ) %EXT2_INODES_PER_GROUP (sb)) *EXT2_INODE_SIZE (sb); + *block =le32_to_cpu (gdp->bg_inode_table) + + (*offset >>EXT2_BLOCK_SIZE_BITS (sb)); + *offset &= (EXT2_BLOCK_SIZE (sb) -1 ); +return 0 ; +} + +static struct ext2_inode *ext2_get_inode (struct super_block *sb,ino_t ino, +struct buffer_head **p) +{ +struct buffer_head *bh; +unsigned long block; +unsigned long offset; +int err; + + *p =NULL ; + err =ext2_inode_block (sb, ino, &block, &offset); +if (err) +return ERR_PTR (err);if (!(bh =sb_bread (sb, block))) goto Eio; *p = bh; - offset &= (EXT2_BLOCK_SIZE (sb) -1 );return (struct ext2_inode *) (bh->b_data + offset); -Einval: -ext2_error (sb,"ext2_get_inode" ,"bad inode number: %lu" , - (unsigned long ) ino); -return ERR_PTR (-EINVAL ); Eio:ext2_error (sb,"ext2_get_inode" ,"unable to read inode block - inode=%lu, block=%lu" , (unsigned long ) ino, block); -Egdp:return ERR_PTR (-EIO ); }
Greg Kroah-Hartman
maintainerPATCH 698/1005 ext2: dont read the inode block in ext2_sync_inode_metadata()
In reply to Greg Kroah-Hartman7.3-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Brauner <[email protected]>
commit c2e595a57aba6aa166053776969f31cc510b3e71 upstream.
ext2_sync_inode_metadata() looks the inode block up with ext2_get_inode() which reads it from disk if it isn't cached. But a block that isn't cached is neither dirty nor under writeback, so there's nothing to write or to wait for.
That read is also something we can't afford once inode eviction calls ->sync_inode_metadata() from reclaim. So look the block up with sb_find_get_block_nonatomic() instead, the way fat_sync_inode_metadata() already does.
--- fs/ext2/inode.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
fs/ext2/inode.c +7 -5
@@ -1578,19 +1578,22 @@ int ext2_write_inode(struct inode *inodeint ext2_sync_inode_metadata (struct inode *inode,struct writeback_control *wbc) {struct buffer_head *bh; -struct ext2_inode *raw_inode =ext2_get_inode (inode->i_sb, inode->i_ino, - &bh); +unsigned long block, offset;int err =0 ; -if (IS_ERR (raw_inode)) +if (ext2_inode_block (inode->i_sb, inode->i_ino, &block, &offset))return -EIO ; err =mmb_sync (&EXT2_I (inode)->i_metadata_bhs);if (err) {ext2_error (inode->i_sb, __func__,"Error syncing inode metadata ino=%lu\n" , (unsigned long )inode->i_ino); - goto out; +return err; } +/* A block that isn't cached is neither dirty nor under writeback. */ + bh =sb_find_get_block_nonatomic (inode->i_sb, block); +if (!bh) +return 0 ;sync_dirty_buffer (bh);if (buffer_write_io_error (bh)) { ext2_error(inode->i_sb, __func__,
@@ -1598,7 +1601,6 @@ int ext2_sync_inode_metadata(struct inod (unsigned long)inode->i_ino); err = -EIO ; } -out:brelse (bh);return err; }